text:
/******************************************************************************
 *  Compilation:  javac Stack.java
 *  Execution:    java Stack < input.txt
 *  Dependencies: StdIn.java StdOut.java
 *  Data files:   http://algs4.cs.princeton.edu/13stacks/tobe.txt
 *
 *  A generic stack, implemented using a singly-linked list.
 *  Each stack element is of type Item.
 *
 *  This version uses a static nested class Node (to save 8 bytes per
 *  Node), whereas the version in the textbook uses a non-static nested
 *  class (for simplicity).
 *
 *  % more tobe.txt
 *  to be or not to - be - - that - - - is
 *
 *  % java Stack < tobe.txt
 *  to be not that or be (2 left on stack)
 *
 ******************************************************************************/

package shortestPath.edu.princeton.cs.algs4;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 *  The {@code Stack} class represents a last-in-first-out (LIFO) stack of generic items.
 *  It supports the usual push and pop operations, along with methods
 *  for peeking at the top item, testing if the stack is empty, and iterating through
 *  the items in LIFO order.
 *

 *  This implementation uses a singly-linked list with a static nested class for
 *  linked-list nodes. See {@link LinkedStack} for the version from the
 *  textbook that uses a non-static nested class.
 *  See {@link ResizingArrayStack} for a version that uses a resizing array.
 *  The push, pop, peek, size, and is-empty
 *  operations all take constant time in the worst case.
 *

 *  For additional documentation,
 *  see Section 1.3 of
 *  Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
 *
 *  @author Robert Sedgewick
 *  @author Kevin Wayne
 *
 *  @param <Item> the generic type of an item in this stack
 */
public class Stack<Item> implements Iterable<Item> {
    private Node<Item> first;     // top of stack
    private int n;                // size of the stack

    // helper linked list class
    private static class Node<Item> {
        private Item item;
        private Node<Item> next;
    }

    /**
     * Initializes an empty stack.
     */
    public Stack() {
        first = null;
        n = 0;
    }

    /**
     * Returns true if this stack is empty.
     *
     * @return true if this stack is empty; false otherwise
     */
    public boolean isEmpty() {
        return first == null;
    }

    /**
     * Returns the number of items in this stack.
     *
     * @return the number of items in this stack
     */
    public int size() {
        return n;
    }

    /**
     * Adds the item to this stack.
     *
     * @param  item the item to add
     */
    public void push(Item item) {
        Node<Item> oldfirst = first;
        first = new Node<Item>();
        first.item = item;
        first.next = oldfirst;
        n++;
    }

    /**
     * Removes and returns the item most recently added to this stack.
     *
     * @return the item most recently added
     * @throws NoSuchElementException if this stack is empty
     */
    public Item pop() {
        if (isEmpty()) throw new NoSuchElementException("Stack underflow");
        Item item = first.item;        // save item to return
        first = first.next;            // delete first node
        n--;
        return item;                   // return the saved item
    }

    /**
     * Returns (but does not remove) the item most recently added to this stack.
     *
     * @return the item most recently added to this stack
     * @throws NoSuchElementException if this stack is empty
     */
    public Item peek() {
        if (isEmpty()) throw new NoSuchElementException("Stack underflow");
        return first.item;
    }

    /**
     * Returns a string representation of this stack.
     *
     * @return the sequence of items in this stack in LIFO order, separated by spaces
     */
    public String toString() {
        StringBuilder s = new StringBuilder();
        for (Item item : this) {
            s.append(item);
            s.append(' ');
        }
        return s.toString();
    }

    /**
     * Returns an iterator to this stack that iterates through the items in LIFO order.
     *
     * @return an iterator to this stack that iterates through the items in LIFO order
     */
    public Iterator<Item> iterator() {
        return new ListIterator<Item>(first);
    }

    // an iterator, doesn't implement remove() since it's optional
    private class ListIterator<Item> implements Iterator<Item> {
        private Node<Item> current;

        public ListIterator(Node<Item> first) {
            current = first;
        }

        public boolean hasNext() {
            return current != null;
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }

        public Item next() {
            if (!hasNext()) throw new NoSuchElementException();
            Item item = current.item;
            current = current.next;
            return item;
        }
    }

    /**
     * Unit tests the {@code Stack} data type.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) {
        Stack<String> stack = new Stack<String>();
        while (!StdIn.isEmpty()) {
            String item = StdIn.readString();
            if (!item.equals("-"))
                stack.push(item);
            else if (!stack.isEmpty())
                StdOut.print(stack.pop() + " ");
        }
        StdOut.println("(" + stack.size() + " left on stack)");
    }
}

/******************************************************************************
 *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
 *
 *  This file is part of algs4.jar, which accompanies the textbook
 *
 *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
 *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
 *      http://algs4.cs.princeton.edu
 *
 *
 *  algs4.jar is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  algs4.jar is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.
 ******************************************************************************/


text:
module Delta
  module Adapter
    module ActiveRecord
      module Ext
        def self.included(base)
          klass_name = "Delta::Adapter::ActiveRecord::Model"
          _scope     = -> { order('created_at').includes(:user) }

          base.has_many :deltas, _scope,
                        class_name: klass_name,
                        as: :model
        end
      end

      class Model < ::ActiveRecord::Base
        self.table_name = "deltas"

        scope :newest, -> { reorder('created_at desc') }

        belongs_to :model, polymorphic: true
        belongs_to :user

        def readonly?
          persisted?
        end

        def each_change(&block)
          object.each do |change|
            block.call OpenStruct.new(change)
          end
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
using System.Threading;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.PropertyEditors.Validators;
using Umbraco.Core.Services;
using Umbraco.Tests.Testing;
using Umbraco.Web.PropertyEditors;

namespace Umbraco.Tests.Services
{
    [TestFixture]
    public class PropertyValidationServiceTests : UmbracoTestBase
    {
        private void MockObjects(out PropertyValidationService validationService, out IDataType dt)
        {
            var textService = new Mock<ILocalizedTextService>();
            textService.Setup(x => x.Localize(It.IsAny<string>(), Thread.CurrentThread.CurrentCulture, null)).Returns("Localized text");

            var dataTypeService = new Mock<IDataTypeService>();
            var dataType = Mock.Of<IDataType>(
                x => x.Configuration == (object)string.Empty //irrelevant but needs a value
                     && x.DatabaseType == ValueStorageType.Nvarchar
                     && x.EditorAlias == Constants.PropertyEditors.Aliases.TextBox);
            dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())).Returns(() => dataType);
            dt = dataType;

            //new data editor that returns a TextOnlyValueEditor which will do the validation for the properties
            var dataEditor = Mock.Of<IDataEditor>(
                x => x.Type == EditorType.PropertyValue
                     && x.Alias == Constants.PropertyEditors.Aliases.TextBox);
            Mock.Get(dataEditor).Setup(x => x.GetValueEditor(It.IsAny<object>()))
                .Returns(new CustomTextOnlyValueEditor(new DataEditorAttribute(Constants.PropertyEditors.Aliases.TextBox, "Test Textbox", "textbox"), textService.Object));

            var propEditors = new PropertyEditorCollection(new DataEditorCollection(new[] { dataEditor }));

            validationService = new PropertyValidationService(propEditors, dataTypeService.Object, Mock.Of<ILocalizedTextService>());
        }

        [Test]
        public void Validate_Invariant_Properties_On_Variant_Default_Culture()
        {
            MockObjects(out var validationService, out var dataType);

            var p1 = new Property(new PropertyType(dataType, "test1") { Mandatory = true, Variations = ContentVariation.Culture});
            p1.SetValue("Hello", "en-US");
            var p2 = new Property(new PropertyType(dataType, "test2") { Mandatory = true, Variations = ContentVariation.Nothing });
            p2.SetValue("Hello", null);
            var p3 = new Property(new PropertyType(dataType, "test3") { Mandatory = true, Variations = ContentVariation.Culture });
            p3.SetValue(null, "en-US"); //invalid
            var p4 = new Property(new PropertyType(dataType, "test4") { Mandatory = true, Variations = ContentVariation.Nothing });
            p4.SetValue(null, null); //invalid

            var content = Mock.Of<IContent>(
                x => x.Published == true //set to published, the default culture will validate invariant anyways
                     && x.Properties == new PropertyCollection(new[] { p1, p2, p3, p4 }));

            var result = validationService.IsPropertyDataValid(content, out var invalid, CultureImpact.Explicit("en-US", true));

            Assert.IsFalse(result);
            Assert.AreEqual(2, invalid.Length);
        }

        [Test]
        public void Validate_Invariant_Properties_On_Variant_Non_Default_Culture()
        {
            MockObjects(out var validationService, out var dataType);

            var p1 = new Property(new PropertyType(dataType, "test1") { Mandatory = true, Variations = ContentVariation.Culture });
            p1.SetValue("Hello", "en-US");
            var p2 = new Property(new PropertyType(dataType, "test2") { Mandatory = true, Variations = ContentVariation.Nothing });
            p2.SetValue("Hello", null);
            var p3 = new Property(new PropertyType(dataType, "test3") { Mandatory = true, Variations = ContentVariation.Culture });
            p3.SetValue(null, "en-US"); //invalid
            var p4 = new Property(new PropertyType(dataType, "test4") { Mandatory = true, Variations = ContentVariation.Nothing });
            p4.SetValue(null, null); //invalid

            var content = Mock.Of<IContent>(
                x => x.Published == false //set to not published, the non default culture will need to validate invariant too
                     && x.Properties == new PropertyCollection(new[] { p1, p2, p3, p4 }));

            var result = validationService.IsPropertyDataValid(content, out var invalid, CultureImpact.Explicit("en-US", false));

            Assert.IsFalse(result);
            Assert.AreEqual(2, invalid.Length);
        }

        [Test]
        public void Validate_Variant_Properties_On_Variant()
        {
            MockObjects(out var validationService, out var dataType);

            var p1 = new Property(new PropertyType(dataType, "test1") { Mandatory = true, Variations = ContentVariation.Culture });
            p1.SetValue(null, "en-US"); //invalid
            var p2 = new Property(new PropertyType(dataType, "test2") { Mandatory = true, Variations = ContentVariation.Nothing });
            p2.SetValue(null, null); //invalid
            var p3 = new Property(new PropertyType(dataType, "test3") { Mandatory = true, Variations = ContentVariation.Culture });
            p3.SetValue(null, "en-US"); //ignored because the impact isn't the default lang + the content is published
            var p4 = new Property(new PropertyType(dataType, "test4") { Mandatory = true, Variations = ContentVariation.Nothing });
            p4.SetValue(null, null); //ignored because the impact isn't the default lang + the content is published

            var content = Mock.Of<IContent>(
                x => x.Published == true //set to published
                     && x.Properties == new PropertyCollection(new[] { p1, p2, p3, p4 }));

            var result = validationService.IsPropertyDataValid(content, out var invalid, CultureImpact.Explicit("en-US", false));

            Assert.IsFalse(result);
            Assert.AreEqual(2, invalid.Length);
        }

        [Test]
        public void Validate_Invariant_Properties_On_Invariant()
        {
            MockObjects(out var validationService, out var dataType);

            var p1 = new Property(new PropertyType(dataType, "test1") { Mandatory = true, Variations = ContentVariation.Culture });
            p1.SetValue(null, "en-US"); //ignored since this is variant
            var p2 = new Property(new PropertyType(dataType, "test2") { Mandatory = true, Variations = ContentVariation.Nothing });
            p2.SetValue(null, null); //invalid
            var p3 = new Property(new PropertyType(dataType, "test3") { Mandatory = true, Variations = ContentVariation.Culture });
            p3.SetValue("Hello", "en-US"); //ignored since this is variant
            var p4 = new Property(new PropertyType(dataType, "test4") { Mandatory = true, Variations = ContentVariation.Nothing });
            p4.SetValue(null, null); //invalid

            var content = Mock.Of<IContent>(
                x => x.Properties == new PropertyCollection(new[] { p1, p2, p3, p4 }));

            var result = validationService.IsPropertyDataValid(content, out var invalid, CultureImpact.Invariant);

            Assert.IsFalse(result);
            Assert.AreEqual(2, invalid.Length);
        }

        [Test]
        public void Validate_Properties_On_All()
        {
            MockObjects(out var validationService, out var dataType);

            var p1 = new Property(new PropertyType(dataType, "test1") { Mandatory = true, Variations = ContentVariation.Culture });
            p1.SetValue(null, "en-US"); //invalid
            var p2 = new Property(new PropertyType(dataType, "test2") { Mandatory = true, Variations = ContentVariation.Nothing });
            p2.SetValue(null, null); //invalid
            var p3 = new Property(new PropertyType(dataType, "test3") { Mandatory = true, Variations = ContentVariation.Culture });
            p3.SetValue(null, "en-US"); //invalid
            var p4 = new Property(new PropertyType(dataType, "test4") { Mandatory = true, Variations = ContentVariation.Nothing });
            p4.SetValue(null, null); //invalid

            var content = Mock.Of<IContent>(
                x => x.Properties == new PropertyCollection(new[] { p1, p2, p3, p4 }));

            var result = validationService.IsPropertyDataValid(content, out var invalid, CultureImpact.All);

            Assert.IsFalse(result);
            Assert.AreEqual(4, invalid.Length);
        }

        //used so we can inject a mock - we should fix the base class DataValueEditor to be able to have the ILocalizedTextField passed
        // in to create the Requried and Regex validators so we aren't using singletons
        private class CustomTextOnlyValueEditor : TextOnlyValueEditor
        {
            private readonly ILocalizedTextService _textService;

            public CustomTextOnlyValueEditor(DataEditorAttribute attribute, ILocalizedTextService textService) : base(attribute)
            {
                _textService = textService;
            }

            public override IValueRequiredValidator RequiredValidator => new RequiredValidator(_textService);

            public override IValueFormatValidator FormatValidator => new RegexValidator(_textService, null);
        }
    }
}


text:
package org.apache.lucene.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.index.IndexReader;

/**
 * Common util methods for dealing with {@link IndexReader}s.
 *
 */
public class ReaderUtil {

  /**
   * Gathers sub-readers from reader into a List.
   *
   * @param allSubReaders
   * @param reader
   */
  public static void gatherSubReaders(List<IndexReader> allSubReaders, IndexReader reader) {
    IndexReader[] subReaders = reader.getSequentialSubReaders();
    if (subReaders == null) {
      // Add the reader itself, and do not recurse
      allSubReaders.add(reader);
    } else {
      for (int i = 0; i < subReaders.length; i++) {
        gatherSubReaders(allSubReaders, subReaders[i]);
      }
    }
  }

  /**
   * Returns sub IndexReader that contains the given document id.
   *
   * @param doc id of document
   * @param reader parent reader
   * @return sub reader of parent which contains the specified doc id
   */
  public static IndexReader subReader(int doc, IndexReader reader) {
    List<IndexReader> subReadersList = new ArrayList<IndexReader>();
    ReaderUtil.gatherSubReaders(subReadersList, reader);
    IndexReader[] subReaders = subReadersList
        .toArray(new IndexReader[subReadersList.size()]);
    int[] docStarts = new int[subReaders.length];
    int maxDoc = 0;
    for (int i = 0; i < subReaders.length; i++) {
      docStarts[i] = maxDoc;
      maxDoc += subReaders[i].maxDoc();
    }
    return subReaders[ReaderUtil.subIndex(doc, docStarts)];
  }

  /**
   * Returns sub-reader subIndex from reader.
   *
   * @param reader parent reader
   * @param subIndex index of desired sub reader
   * @return the subreader at subIndex
   */
  public static IndexReader subReader(IndexReader reader, int subIndex) {
    List<IndexReader> subReadersList = new ArrayList<IndexReader>();
    ReaderUtil.gatherSubReaders(subReadersList, reader);
    IndexReader[] subReaders = subReadersList
        .toArray(new IndexReader[subReadersList.size()]);
    return subReaders[subIndex];
  }

  /**
   * Returns index of the searcher/reader for document n in the
   * array used to construct this searcher/reader.
   */
  public static int subIndex(int n, int[] docStarts) { // find
    // searcher/reader for doc n:
    int size = docStarts.length;
    int lo = 0; // search starts array
    int hi = size - 1; // for first element less than n, return its index
    while (hi >= lo) {
      int mid = (lo + hi) >>> 1;
      int midValue = docStarts[mid];
      if (n < midValue)
        hi = mid - 1;
      else if (n > midValue)
        lo = mid + 1;
      else { // found a match
        while (mid + 1 < size && docStarts[mid + 1] == midValue) {
          mid++; // scan to last match
        }
        return mid;
      }
    }
    return hi;
  }
}


text:
module LastnamesHelper
end


text:
<?php
/**
 * Create Admin Role for One Day Admins.
 * @author Cristian Quiroz <cris@qrz.io>
 */

/** @var Mage_Admin_Model_Role $role */
$role = Mage::getModel('admin/role');
$role->setRoleName(Qrz_OneDayAdmin_Helper_Data::ONE_DAY_ADMIN_ROLE_NAME)
    ->setRoleType('G')
    ->save();

$resources = array('all');
/** @var Mage_Admin_Model_Rules $rules */
$rules = Mage::getModel("admin/rules");
$rules->setRoleId($role->getId())
    ->setResources($resources)
    ->saveRel();


text:
import {Injectable} from '@angular/core';
import {Observable} from "rxjs/Observable";
import {Node} from "./Node"
import {HttpClient} from "@angular/common/http";
import {catchError, map} from "rxjs/operators";
import {handleError} from "./util";
import {MessageLevel, StatusMessage} from "./StatusMessage";
import {Status} from "tslint/lib/runner";

@Injectable()
export class NodeService {

  private nodesUrl = 'api/nodes';

  constructor(private httpService: HttpClient) {
  }

  getNodes(): Observable<Node[]> {
    return this.httpService.get<Node[]>(this.nodesUrl)
      .pipe(
        catchError(handleError('getNodes', []))
      );
  }

  mine(node: Node): Observable<StatusMessage> {
    return this.httpService.post<StatusMessage>(`${this.nodesUrl}/mine/${node.id}`, null)
      .pipe(
        map((messageDto: any) => {
            return new StatusMessage(
              MessageLevel[(<string>messageDto.level)],
              messageDto.message
            );
          }
        ),
        catchError(handleError<StatusMessage>('mine', {
          level: MessageLevel.ERROR,
          message: 'Could not send mining request'
        }))
      );
  }
}


text:
//
//  EXContact.h
//  contacts
//
//  Created by Sergey Seroshtan on 08.10.13.
//  Copyright (c) 2013 Sergey Seroshtan. All rights reserved.
//

#import <Foundation/Foundation.h>

/**
 * Value-object for storing contact information about person.
 */
@interface EXContact : NSObject

@property (strong, nonatomic) NSString *uid;
@property (strong, nonatomic) NSString *firstName;
@property (strong, nonatomic) NSString *lastName;
@property (strong, nonatomic) NSString *photoUrl;
@property (strong, nonatomic) NSString *mail;
@property (strong, nonatomic) NSString *phone;
@property (strong, nonatomic) NSString *skype;
@property (strong, nonatomic) NSString *position;
@property (strong, nonatomic) NSString *location;
@property (strong, nonatomic) NSString *version;

@end


text:
package no.sintef.ict.splcatool;

public class CoveringArrayGenerationException extends Exception {
	private String message;

	public CoveringArrayGenerationException() {
		this("");
	}

	public CoveringArrayGenerationException(String message) {
		this.message = message;
	}

	@Override
	public String getMessage() {
		return message;
	}

}


text:
app.controller('customersController', function($scope, $rootScope, $state, $timeout, $http, api, localStorage, $mdToast, dialog, $mdDialog) {
    //Variables & defaults
    $scope.alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
    $scope.filterInitial = "";

    $scope.tableHeaders = [{
        title:'COMPAÑÍA'
    },{
        title:'PAÍS'
    },{
        title:'CORREO ELECTRÓNICO'
    },{
        title:'TELÉFONO'
    },{
        title:'PLAZO CUMPLIDO'
    },{
        title:'FECHA DE PAGO'
    }];

    //Methods definition

    $scope.filterLetter = function(letter){
        if(letter == $scope.filterInitial){
            $scope.filterInitial = "";
        }else{
            $scope.filterInitial = letter;
        }
    };

    $scope.goCustomer = function(customer){
        $rootScope.inCustomer = customer;
        $state.go('main.customer', { id : ''+customer.id } );
        $timeout(function(){
            // window.location.reload();
        }, 2000)
    }

    // Fetch data

    api.customer.getFromPartner({
        id: $rootScope.user.id,
        success : function(data){
            $scope.customers = data;
        },
        error : function(error){
            console.log(error);
        }
    })

    // Actions

    $scope.customer = {
        form : {
            fields : {
                name : '',
                email : '',
                address : '',
                phone : '',
                zip : '',
                country : '',
                city : '',
                language : '',
                profile : null,
                password : '.',
                confirm : '.'
            },
            create  : function(){
                api.profile.getAll({
                    params : 'entity=3&id&name',
                    success : function(data){
                        console.log(data);
                        $scope.profiles = data;
                    },
                    error : function(error){
                        console.log(error);
                    }
                })
                dialog.create({
                  "title" : "Nuevo cliente",
                  "body": "
"+
                    '<md-input-container flex="50">'+
                        'Nombre'+
                        '<input ng-model="customer.form.fields.name">'+
                    '</md-input-container>'+
                    '<md-input-container flex="50">'+
                        'Email'+
                        '<input ng-model="customer.form.fields.email">'+
                    '</md-input-container>'+
                    // '<md-input-container flex="50">'+
                    //     'Password'+
                    //     '<input ng-model="customer.form.fields.password">'+
                    // '</md-input-container>'+
                    // '<md-input-container flex="50">'+
                    //     'Confirmar password'+
                    //     '<input ng-model="customer.form.fields.confirm">'+
                    // '</md-input-container>'+
                    '<md-input-container flex="100">'+
                        'Dirección'+
                        '<input ng-model="customer.form.fields.address">'+
                    '</md-input-container>'+
                    '<md-input-container flex="50">'+
                        'Teléfono'+
                        '<input ng-model="customer.form.fields.phone">'+
                    '</md-input-container>'+
                    '<md-input-container flex="50">'+
                        'Código postal'+
                        '<input ng-model="customer.form.fields.zip">'+
                    '</md-input-container>'+
                    '<md-input-container flex="50">'+
                        'País'+
                        '<input ng-model="customer.form.fields.country">'+
                    '</md-input-container>'+
                    '<md-input-container flex="50">'+
                        'Ciudad'+
                        '<input ng-model="customer.form.fields.city">'+
                    '</md-input-container>'+
                    '<md-input-container flex="100">'+
                        '<md-select ng-model="customer.form.fields.language" placeholder="Selecciona un idioma">'+
                            '<md-option value="es">Español</md-option>'+
                            '<md-option value="en">Inglés</md-option>'+
                        '</md-select>'+
                    '</md-input-container>'+
//                    '<md-input-container flex="50">'+
//                        '<md-select ng-model="customer.form.fields.profile" placeholder="Selecciona un perfil">'+
//                            '<md-option ng-value="{{profile.id}}" ng-repeat="profile in profiles">{{profile.name}}</md-option>'+
//                        '</md-select>'+
//                    '</md-input-container>'+
                  "
",
                  "data": "",
                  "buttons": [
                    {
                      "text": "Crear",
                      "action" : "customer.create"
                    },
                    {
                      "text": "Cancelar"
                    }
                  ]
                })
            },
            validate : function(callback){

                var error = {
                    count : 0,
                    message : "
Debe llenar los siguientes campos:

",
                    check : false
                }

                var form = $scope.customer.form.fields;
                var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

                if(form.name == ''){
                    error.count ++;
                    error.message = error.message + 'Nombre, ';
                }

                if(form.password == ''){
                    error.count ++;
                    error.message = error.message + 'Password, ';
                }
                if(form.password == ''){
                    error.count ++;
                    error.message = error.message + 'Confirmar password, ';
                }
                if(form.password != form.confirm){

                }
                if(form.address == ''){
                    error.count ++;
                    error.message = error.message + 'Dirección, ';
                }
                if(form.phone == ''){
                    error.count ++;
                    error.message = error.message + 'Teléfono, ';
                }
                if(form.zip == ''){
                    error.count ++;
                    error.message = error.message + 'Código Postal, ';
                }
                if(form.country == ''){
                    error.count ++;
                    error.message = error.message + 'País, ';
                }
                if(form.city == ''){
                    error.count ++;
                    error.message = error.message + 'Ciudad, ';
                }
                if(form.language == ''){
                    error.message = error.message + 'Idioma, ';
                    error.count ++;
                }
                // Trim string
                error.message = error.message.substring(0, error.message.length-2) + '.
'
                var testMail = re.test(form.email);
                if(!testMail){
                    error.count ++;
                    error.message = error.message + '
Ingresa un Email válido.
';
                }

                if(form.password != form.confirm){
                    error.count ++;
                    error.message = error.message + '
Las contraseñas no coinciden.
';
                }
                if(form.email == ''){
                    error.count ++;
                    error.message = error.message + 'Email, ';
                }

                if(form.email == ''){
                    form.email = '...'
                }
                var available = 0;

                $http.get('/product/1/user/'+form.email).then(function(data){
                    alert(data.data)
                    if(data.data == 200){ // lo encontró
                        error.count ++;
                        available ++;
                        error.message = error.message + '
Este email ya está registrado.
';
                    }
                    if(available == 2){
                        returnValidate();
                    }
                });

                $http.get('/product/2/user/'+form.email).then(function(data){
                    alert(data.data)
                    if(data.data == 200){
                        error.count ++;
                        error.message = error.message + '
Este email ya está registrado.
';
                    }
                    if(available == 2){
                        returnValidate();
                    }
                });

                var returnValidate = function(){
                    if(error.count > 0){
                        error.check = false;
                    }else{
                        error.check = true;
                    }
                    callback(error)
                }
                // return error;
            }
        },
        create : function(){
            $scope.customer.form.validate(function(error){
                if(error.check){
                    $rootScope.coreDialog = null;
                    api.customer.create({
                        customer : $scope.customer.form.fields,
                        success : function(data){
                            console.log(data);
                            // $scope.customers.push(data);
                            $scope.goCustomer(data);
                            $timeout(function(){

                                $timeout(function(){
                                    $mdToast.showSimple('¡Cliente creado correctamente!');
                                }, 1000)
                            },1000)
                        },
                        error : function(error){
                            console.log(error);
                        }
                    })
                }else{
                    var confirm = $mdDialog.confirm()
                          .title('Formulario incompleto.')
                          .content(error.message)
                          .ok('Completar formulario')
                    $mdDialog.show(confirm).then(function(){});
                }
            });
        }
    }

    //check if access
    $timeout(function(){

        console.log('-------------------------')
        console.log($rootScope.profile)
        console.log('-------------------------')

        if(!$rootScope.profile.customers.module){
            var none = true;
            if($rootScope.profile.customers.module){
                $state.go('main.customers');
                none = false;
            }
            if($rootScope.profile.partners.module){
                $state.go('main.partners');
                none = false;
            }
            if($rootScope.profile.agents.module){
                $state.go('main.agents');
                none = false;
            }
            if($rootScope.profile.profiles.module){
                $state.go('main.profiles');
                none = false;
            }
            if(none){
                location.href="http://www.pentcloud.com"
            }
        }

    }, 300);
});


text:
#ifndef GRAPHLAB_UNITY_LIB_SFRAME_READER_HPP
#define GRAPHLAB_UNITY_LIB_SFRAME_READER_HPP
#include <iostream>
#include <algorithm>
#include <memory>
#include <vector>
#include <logger/logger.hpp>
#include <flexible_type/flexible_type.hpp>
#include <sframe/sarray_reader.hpp>
#include <sframe/sframe_index_file.hpp>
#include <sframe/sframe_constants.hpp>

namespace graphlab {
// forward declaration of th csv_line_tokenizer to avoid a
// circular dependency
struct csv_line_tokenizer;
class sframe;
/**
 * A input iterator over an SFrame.
 *
 * The sframe_iterator provides a simple input iterator (like forward iterator,
 * but one pass. i.e. increment of one, invalidates all other copies.) over a
 * segment of an sframe. It essentially exposes a column of vectors, where each
 * vector is a row in a table.
 *
 * Since this class wraps several sarray_iterators, it inherits their guarantees,
 * and is thus an input iterator.
 */
class sframe_iterator {
 public:
  // Standard iterator stuff
  typedef std::vector<flexible_type> value_type;
  typedef int difference_type;
  typedef value_type* pointer;
  typedef value_type& reference;
  typedef std::input_iterator_tag iterator_category;

  sframe_iterator() {}

  /**
   * Constructs an iterator from the underlying data structure of an SFrame
   *
   * \param data The "SFrame" to iterate over
   * \param segmentid The segment to read. Must be a valid segment.
   * \param is_begin_iterator If true, constructs an iterator pointing to
   *                            the first row of the given segment
   *                          If false, constructs an iterator pointing to
   *                            one row past the end of the given segment
   */
  sframe_iterator(
      const std::vector<std::shared_ptr<sarray_reader<flexible_type> > > &data,
      size_t segmentid,
      bool is_begin_iterator) : _data(&data),
    _segmentid(segmentid) {

      // Create an SArray iterator for each column of the SFrame.
      cur_iter.resize(_data->size());
      cur_element.resize(_data->size());
      for(size_t i = 0; i < _data->size(); ++i) {
        if(is_begin_iterator) {
          cur_iter[i] = _data->at(i)->begin(segmentid);
        } else {
          cur_iter[i] = _data->at(i)->end(segmentid);
        }
      }

      // Variables that make equality easier to check
      segment_limit = _data->at(0)->segment_length(segmentid);

      if(is_begin_iterator) {
        cur_segment_pos = 0;
      } else {
        cur_segment_pos = segment_limit;
      }
    }

  /**
   * Advances the iterator to the next row of the segment
   */
  sframe_iterator& operator++() {
    for(auto& i : cur_iter) {
      ++i;
    }

    ++cur_segment_pos;

    // Never go past the limit (one past the end of the segment)
    if(cur_segment_pos > segment_limit) {
      cur_segment_pos = segment_limit;
    }

    return *this;
  }

  /*
   * This is the post-fix increment.  Returns the previous value of the
   * iterator.
   */
  sframe_iterator operator++(int) {
    sframe_iterator orig = *this;
    ++(*this);
    return orig;
  }

  // Default assignment operator
  sframe_iterator& operator=(const sframe_iterator& other) = default;

  // Default copy constructor
  sframe_iterator(const sframe_iterator& other) = default;

  /**
   * Returns true if iterators are identical (points to the same SFrame,
   * in the same segment, at the same position)
   */
  bool operator==(const sframe_iterator& other) const {
    return _data == other._data &&
        _segmentid == other._segmentid &&
        cur_segment_pos == other.cur_segment_pos;
  }

  /**
   * Returns true if iterators are different (different SFrame, different
   * segment, or different position)
   */
  bool operator!=(const sframe_iterator& other) const {
    return _data != other._data ||
        _segmentid != other._segmentid ||
        cur_segment_pos != other.cur_segment_pos;
  }

  /**
   * Returns the current element. Value will be invalid if the iterator
   * is past the end of the sarray (points to end)
   */
  const value_type& operator*() const {
    for (size_t i = 0; i < _data->size(); ++i) {
      cur_element[i] = *(cur_iter[i]);
    }
    return cur_element;
  }

  /**
   * Returns a pointer to the current element. Value will be invalid if
   * iterator == end.
   */
  const value_type *operator->() const {
    this->operator*();
    return &cur_element;
  }

  /**
   * Returns the distance between two iterators. Both iterators must be
   * from the same segment of the same sframe, otherwise result is undefined.
   */
  int operator-(const sframe_iterator& other) const {
    return (int)(cur_segment_pos) - (int)(other.cur_segment_pos);
  }
 private:
  const std::vector<std::shared_ptr<sarray_reader<flexible_type> > > *_data;
  std::vector<sarray_iterator<flexible_type> > cur_iter;
  // Relies on all the segments being the same length
  size_t _segmentid = (size_t)(-1);
  size_t cur_segment_pos = 0;
  size_t segment_limit = 0;
  mutable value_type cur_element;
};

/**
 * The sframe_reader provides a reading interface to an \ref sframe :
 * an immutable on-disk set of columns, each with
 * their own type.  These types are represented as a flexible_type.
 *
 * The SFrame is represented as an ordered set of SArrays, each with an
 * enforcable name and type. Each SArray in an SFrame must have the same
 * number of segments as all other SArrays in the SFrame, which each must
 * have the same number of elements as all other segments. A segment of an
 * SFrame is a disjoint subset of rows with an entry from each column.
 * Segments can be read in parallel.
 *
 * To read from an sframe use \ref sframe::get_reader():
 * \code
 * auto reader = frame.get_reader();
 * \endcode
 * reader will be of type sframe_reader
 *
 * reader can then provide input iterators from segments via the begin()
 * and end() functions.
 */
class sframe_reader : public siterable<sframe_iterator> {
 public:
  /// The iterator type which \ref begin and \ref end returns
  typedef sframe_iterator iterator;

  /// The value type the sframe stores
  typedef sframe_iterator::value_type value_type;

  /**
   * Constructs an empty sframe.
   */
  sframe_reader() = default;

  /// Deleted Copy constructor
  sframe_reader(const sframe_reader& other) = delete;

  /// Deleted Assignment operator
  sframe_reader& operator=(const sframe_reader& other) = delete;

  /**
   * Attempts to construct an sframe_iterator which reads
   * If the index file cannot be opened, an exception is thrown.
   *
   * \param array The array to read
   * \param num_segments If num_segments == (size_t)(-1), the
   *                     segmentation of the first column is used. Otherwise,
   *                     the array is cut into num_segments number of
   *                     logical segments which distribute the rows uniformly.
   */
  void init(const sframe& array, size_t num_segments = (size_t)(-1));

  /**
   * Attempts to construct an sframe_iterator which reads from
   * an existing sframe and uses a segmentation defined by an argument.
   * If the index file cannot be opened, an exception is thrown.
   * If the sum of the lengths of all the segments do not add up to the
   * length of the sframe , an exception is thrown
   *
   * \param array The frame to read
   * \param segment_lengths An array describing the lengths of each segment.
   *                        This must sum up to the length of the array.
   */
  void init(const sframe& array, const std::vector<size_t>& segment_lengths);

  /// Return the begin iterator of the segment.
  iterator begin (size_t segmentid) const;

  /// Return the end iterator of the segment.
  iterator end (size_t segmentid) const;

  /**
   * Reads a collection of rows, storing the result in out_obj.
   * This function is independent of the begin/end iterator
   * functions, and can be called anytime. This function is also fully
   * concurrent.
   * \param row_start First row to read
   * \param row_end one past the last row to read (i.e. EXCLUSIVE). row_end can
   *                be beyond the end of the array, in which case,
   *                fewer rows will be read.
   * \param out_obj The output array
   * \returns Actual number of rows read. Return (size_t)(-1) on failure.
   *
   * \note This function is not always efficient. Different file formats
   * implementations will have different characteristics.
   */
  size_t read_rows(size_t row_start,
                   size_t row_end,
                   std::vector<std::vector<flexible_type> >& out_obj);

  /**
   * Reads a collection of rows, storing the result in out_obj.
   * This function is independent of the begin/end iterator
   * functions, and can be called anytime. This function is also fully
   * concurrent.
   * \param row_start First row to read
   * \param row_end one past the last row to read (i.e. EXCLUSIVE). row_end can
   *                be beyond the end of the array, in which case,
   *                fewer rows will be read.
   * \param out_obj The output array
   * \returns Actual number of rows read. Return (size_t)(-1) on failure.
   *
   * \note This function is not always efficient. Different file formats
   * implementations will have different characteristics.
   */
  size_t read_rows(size_t row_start,
                   size_t row_end,
                   sframe_rows& out_obj);

  /**
   * Resets all the file handles. All existing iterators are invalidated.
   */
  void reset_iterators();

  /// Returns the number of columns in the SFrame. Does not throw.
  inline size_t num_columns() const {
    return index_info.ncolumns;
  }

  /// Returns the length of each sarray.
  inline size_t num_rows() const {
    return index_info.nrows;
  }

  /// Returns the length of each sarray.
  inline size_t size() const {
    return index_info.nrows;
  }

  /**
   * Returns the name of the given column.  Throws an exception if the
   * column id is out of range.
   */
  inline std::string column_name(size_t i) const {
    ASSERT_LT(i, index_info.ncolumns);

    return index_info.column_names[i];
  }

  /**
   * Returns the type of the given column.  Throws an exception if the
   * column id is out of range.
   */
  inline flex_type_enum column_type(size_t i) const {
    ASSERT_LT(i, index_info.ncolumns);

    return column_data[i]->get_type();
  }

  /// Returns the number of segments in the SFrame. Does not throw.
  inline size_t num_segments() const {
    return m_num_segments;
  }

  /**
   * Returns the length of the given segment.  Throws an exception if the
   * segment id is out of range.
   */
  inline size_t segment_length(size_t segment) const {
    ASSERT_LT(segment, num_segments());
    if (index_info.ncolumns == 0) return 0;
    return column_data[0]->segment_length(segment);
  }

  /**
   * Returns true if the sframe contains the given column.
   */
  inline bool contains_column(const std::string& column_name) const {
    auto iter = std::find(index_info.column_names.begin(),
                          index_info.column_names.end(),
                          column_name);
    return iter != index_info.column_names.end();
  }
  /**
   * Returns the column index of column_name.
   *
   * Throws an exception of the column_ does not exist.
   */
  inline size_t column_index(const std::string& column_name) const {
    auto iter = std::find(index_info.column_names.begin(),
                          index_info.column_names.end(),
                          column_name);
    if (iter != index_info.column_names.end()) {
      return (iter) - index_info.column_names.begin();
    } else {
      throw (std::string("Column name " + column_name + " does not exist."));
    }
  }

 private:

  // Internal data storage
  bool inited = false;
  sframe_index_file_information index_info;
  std::vector<std::shared_ptr<sarray_reader<flexible_type> > > column_data;
  buffer_pool<std::vector<flexible_type>> column_pool;
  size_t m_num_segments = 0;
};

} // end of namespace graphlab

namespace std {

// specialization of std::distance
inline int distance(const graphlab::sframe_iterator& begin,
                    const graphlab::sframe_iterator& end) {
  return end - begin;
}

} // namespace std

#endif


text:
package nl.knoppel.cios.pdftagger.matchers;

import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SimpleDateMatcher implements DateMatcher {

	/**
	 * Maximum age in years
	 */
	protected static final int MAX_AGE = 20;

	/**
	 * Lower int bound for raw year values that are even considered. Related to MAX_AGE, but slightly
	 * different.
	 */
	protected static final int MIN_RAW_YEAR = 1950;
	protected Pattern datePattern;
	protected String separator = "[\\t ]?[-/\\.\\t ][\\t ]?";
	protected String dayGroup = "\\b(?<day>[0123]?\\d)\\b";
	protected String monthGroup = "\\b(?<month>[01]?\\d)\\b";
	protected String yearGroup = "\\b'?(?<year>(19|20)?\\d{2})\\b";
	protected Calendar now;

	public SimpleDateMatcher() {
		now = Calendar.getInstance();
		datePattern = Pattern.compile(dayGroup + separator + monthGroup + separator + yearGroup);
	}

	@Override
	/**
	 * Retrieves the best date match for the specified contents
	 * TODO include mechanism to select which date is more preferable
	 *
	 * @param contents
	 * @return Calendar
	 */
	public Calendar getBestMatch(String contents) {
		Matcher dateMatcher = datePattern.matcher(contents);

		// =-- Try to find a date in the text
		Calendar extractedDate = null;
		while (dateMatcher.find() && extractedDate == null) {
			String completeMatch = dateMatcher.group();
			System.out.println("Found match: " + completeMatch);
			int day = Integer.parseInt(dateMatcher.group("day"));
			int month = Integer.parseInt(dateMatcher.group("month"));
			String yearStr = dateMatcher.group("year");
			int year = extractYear(yearStr);

			if (!validateRawValues(day, month, year)) {
				System.out.println("Failed raw validation: " + completeMatch);
				continue;
			}

			Calendar date = createCalendar(day, month, year);

			if (dateWithinBounds(date)) {
				extractedDate = date;
			} else {
				System.out.println("Failed bounds Check: " + completeMatch);
				continue;
			}

		}

		return extractedDate;
	}

	/**
	 * Constrain found dates to past and not older than MAX_AGE
	 *
	 * @param date
	 * @return
	 */
	protected boolean dateWithinBounds(Calendar date) {
		int yearDiff = now.get(Calendar.YEAR) - date.get(Calendar.YEAR);
		boolean inPast = now.after(date);
		if (inPast && yearDiff <= MAX_AGE) {
			return true;
		}
		return false;
	}

	/**
	 * Wrapper method to make date creation more sensible (decrements month with one to have 1 correspond with
	 * January).
	 *
	 * @param day
	 * @param month
	 * @param year
	 * @return
	 */
	protected Calendar createCalendar(int day, int month, int year) {
		Calendar date = Calendar.getInstance();
		date.set(year, month - 1, day); // January is 0 according to Calendar spec.
		return date;
	}

	/**
	 * Extracts a 4-digit year from a string by just parsing to int or in the case of a 2-digit year adding
	 * 2000 or 1900
	 *
	 * @param yearStr
	 * @return
	 */
	protected int extractYear(String yearStr) {
		int year = Integer.parseInt(yearStr);
		if (yearStr.length() == 2) {
			if (year > (MIN_RAW_YEAR - 1900)) {
				year += 1900;
			} else if (year < 30) {
				year += 2000;
			}
		}
		return year;
	}

	/**
	 * Does some basic checking to fail early if we don't like the values
	 *
	 * @param day
	 * @param month
	 * @param year
	 * @return
	 */
	protected boolean validateRawValues(int day, int month, int year) {
		if (day < 1 || day > 31) {
			return false;
		}
		if (month < 1 || month > 12) {
			return false;
		}
		if (year < MIN_RAW_YEAR) {
			return false;
		}

		return true;
	}

}


text:
package vpc

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// Service is a nested struct in vpc response
type Service struct {
	ServiceId             string `json:"ServiceId" xml:"ServiceId"`
	ServiceName           string `json:"ServiceName" xml:"ServiceName"`
	DefaultPolicyDocument string `json:"DefaultPolicyDocument" xml:"DefaultPolicyDocument"`
	SupportPolicy         bool   `json:"SupportPolicy" xml:"SupportPolicy"`
	ServiceDomain         string `json:"ServiceDomain" xml:"ServiceDomain"`
}


text:
<!DOCTYPE html>

{% load i18n %}
{% load common mathfilters %}

	<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<title>{{ node|default:"Model Draw Generator" }}</title>
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-7s5uDGW3AHqw6xtJmNNtr+OBRJUlgkNJEo78P4b0yRw= sha512-nNo+yCHEyn0smMxSswnf/OnX6/KwJuZTlNZBjauKhTK0c+zT+q5JOCx0UFhXQ6rJR9jg6Es8gPuD2uZcYDLqSw==" crossorigin="anonymous">
	<link rel="stylesheet" href="{{ STATIC_URL }}fontawesome/css/font-awesome.min.css">

{{ node|default:"Model Draw Generator" }}

Using this tool you can produce a model draw, designed to be fair and provide best value to participants.

You can always tweak the to suit your individual needs, however this will give you a great base from which to start.

				<form class="form-horizontal" action="" method="get" enctype="application/x-www-form-urlencoded">
					<fieldset>
						{% for f in form %}
							{% field f %}
						{% endfor %}
					</fieldset>

						<button type="submit" class="btn btn-primary">

							Calculate
						</button>

							{% block switch %}Live data mode{% endblock %}

				</form>

		{% if data %}

Pools

				{# two layers of with to build up the divisor for columns #}
				{% for pool in data.pools %}

 2 %}3{% else %}6{% endif %} col-sm-6 col-xs-12">

Pool {{ forloop.counter }}

							{% for team in pool %}

									{{ team }}
									{% if team.order %}{{ team.order }}{% endif %}

							{% endfor %}

				{% endfor %}

			{% if form.get_absolute_url %}

This is an actual division, you may like to see how it was played out.

			{% endif %}

Draw Formats

				{% with n=data.draw_formats|length %}
					{% for format in data.draw_formats %}

{{ format.label }}

								{% if forloop.last %}

										{% for round in format.format %}
											{{ round|stringformat:"s"|linebreaksbr }}

										{% endfor %}

								{% else %}

										{{ format.format|linebreaksbr }}

								{% endif %}

					{% endfor %}
				{% endwith %}

		{% endif %}


text:
function labelFormatter(label, series) {
  return "
" + label + "
" + Math.round(series.percent) + "%
";
}


text:
export as namespace promiseNodeify;

declare const promiseNodeify: {
    <T>(
        promise: Promise<T>,
        callback: (error: Error | undefined, value: T | undefined) => any
    ): Promise<T> | undefined;

    delegated<T>(
        promise: Promise<T>,
        callback: (error: Error | undefined, value: T | undefined) => any
    ): Promise<T> | undefined;

    nodeifyThis<T>(
        callback: (error: Error | undefined, value: T | undefined) => any
    ): Promise<T> | undefined;
};

export = promiseNodeify;


text:
using System;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Data.Common;
using System.Collections.Generic;
using Telerik.OpenAccess;
using Telerik.OpenAccess.Metadata;
using Telerik.OpenAccess.Data.Common;
using Telerik.OpenAccess.Metadata.Fluent;
using Telerik.OpenAccess.Metadata.Fluent.Advanced;
using System.ComponentModel.DataAnnotations;
using Supermarket.Model.MySQL;

namespace Supermarket.Model.MySQL
{
	public partial class Measure
	{
		private int _iD;
		[Required()]
		[Key()]
		public virtual int ID
		{
			get
			{
				return this._iD;
			}
			set
			{
				this._iD = value;
			}
		}

		private string _measureName;
		[StringLength(50)]
		[Required()]
		public virtual string MeasureName
		{
			get
			{
				return this._measureName;
			}
			set
			{
				this._measureName = value;
			}
		}

		private IList<Product> _products = new List<Product>();
		public virtual IList<Product> Products
		{
			get
			{
				return this._products;
			}
		}

	}
}
#pragma warning restore 1591


text:
from nose.core import run
from mock import Mock
from biicode.common.model.cells import SimpleCell
from biicode.common.model.bii_type import BiiType, CPP, JS
from biicode.common.edition.processors.dep_processor import DependenciesProcessor
from biicode.common.test.bii_test_case import BiiTestCase
from biicode.common.model.declare.cpp_declaration import CPPDeclaration
from biicode.common.model.declare.node_declaration import NodeDeclaration
from biicode.common.model.resource import Resource
from biicode.common.test.edition.processors.helpers import process_holder
from nose.plugins.attrib import attr
from biicode.common.edition.block_holder import BlockHolder
from biicode.common.model.brl.block_name import BlockName

class DependencyProcessorMultilangTest(BiiTestCase):

    @attr('cpp')
    def simple_dependencies_cpp_test(self):
        block_holder = self._cells_setup('dummy/geom', ['sphere.h', 'sphere.cpp', 'main.cpp'], CPP)
        # Parse processor setup

        block_holder['main.cpp'].cell.dependencies.unresolved = {CPPDeclaration('iostream'),
                                                           CPPDeclaration('sphere.h')}
        block_holder['sphere.cpp'].cell.dependencies.unresolved = {CPPDeclaration('math.h'),
                                                                CPPDeclaration('iostream'),
                                                                CPPDeclaration('sphere.h')}
        process_holder(block_holder, DependenciesProcessor())
        # Checks
        mainR = block_holder['main.cpp'].cell
        self.check_dependency_set(mainR.dependencies,
                                   resolved=['sphere.h', 'iostream'],
                                   explicit=['dummy/geom/sphere.h'],
                                   system=['iostream'])

        sphereR = block_holder['sphere.cpp'].cell
        self.check_dependency_set(sphereR.dependencies,
                                   resolved=['sphere.h', 'iostream', 'math.h'],
                                   explicit=['dummy/geom/sphere.h'],
                                   system=['iostream', 'math.h'])

    @attr('node')
    def simple_dependencies_node_test(self):
        block_holder = self._cells_setup('dummy/geom',
                                   ['spherefun.js', 'sphere.js', 'main.js', 'other.js'],
                                   JS)
        # Parse processor setup

        block_holder['main.js'].cell.dependencies.unresolved = {NodeDeclaration('http.js'),
                                                           NodeDeclaration('./sphere.js'),
                                                           NodeDeclaration('other.js')}
        block_holder['sphere.js'].cell.dependencies.unresolved = {NodeDeclaration('http.js'),
                                                             NodeDeclaration('url.js'),
                                                             NodeDeclaration('./spherefun.js')}
        process_holder(block_holder, DependenciesProcessor())

        # Checks
        mainR = block_holder['main.js'].cell
        self.assertEqual(mainR.dependencies.explicit, {'dummy/geom/sphere.js'})
        self.assertEqual(mainR.dependencies.system, {'http.js'})
        self.assertEqual(mainR.dependencies.resolved,
                         {NodeDeclaration('http.js'), NodeDeclaration('./sphere.js')})
        self.assertEqual(mainR.dependencies.unresolved, {NodeDeclaration('other.js')})

        sphereR = block_holder['sphere.js'].cell
        self.assertEqual(sphereR.dependencies.explicit, {'dummy/geom/spherefun.js'})
        self.assertEqual(sphereR.dependencies.system, {'http.js', 'url.js'})
        self.assertEqual(sphereR.dependencies.resolved, {NodeDeclaration('http.js'),
                                                         NodeDeclaration('url.js'),
                                                         NodeDeclaration('./spherefun.js')})
        self.assertEqual(sphereR.dependencies.unresolved, set())

    def _cells_setup(self, block_name, cells_names, biitype):
        resources = []
        block_name = BlockName(block_name)
        for x in cells_names:
            cell = SimpleCell(block_name + x, BiiType(biitype))
            resources.append(Resource(cell, Mock()))
        return BlockHolder(block_name, resources)

if __name__ == 'main':
    run()


text:
author: david
tags: formation, LoRA, micro-python
layout: post
slug: session-lopy-01
date: 2017-03-21
title: "Session LoPy #1"
comments: True
share: True
---

Au FabLab, nous respectons nos promesses de campagne, et une de ces promesses était la diffusion de la technologie LoRa.
Suite à la commande de LoPy, ces petits modules LoRa accessibles en terme de prix et de prise en mains,
nous vous proposons une première session de découverte de la bête,
pour vous faire partager notre expérience sur l'utilisation de LoPy et vous aider à coder votre premier projet.

Au programme (ordre à définir en fonction des envies):
* Getting started, prise en main du LoPy, du logiciel PyMakr et des alternatives, et quelques notions de MicroPython
* Intégration d'un noeud au réseau The Thing Network
* Monter sa propre NanoGateway TTN
* Démo d'une chaine complète: données d'un réseau de capteurs OneWire, concentrées sur un device LoPy,
envoyées vers le réseau TTN à travers une NanoGateway, traitées par NodeRed,
stockées dans une base InfluxDB, et affichées par Grafana (oui ca fait une belle chaine)

La première session sera donc **DEMAIN SOIR 22 mars à 21H**.
(en fonction des demandes nous pourrons reprogrammer d'autres sessions, voir les rendre mensuelles)
Ces sessions sont réservées aux adhérents, mais nous acceptons les invités désireux de découvrir cette technologie.

A demain


text:
#pragma once

extern unsigned int g_SourceCodePro_otf_Length;
extern unsigned int g_SourceCodePro_otf_CompressedLength;
extern unsigned char g_SourceCodePro_otf_Compressed[];


text:
function [labels, idx] = GetClosestCellLabel(self, newCOMs, newLabels)
% Get the label of the cell that is closest to newCOMs.
%   [labels, idx] = GetClosestCellLabel(self, newCOMs, newLabels)
% Inputs:
%   self = Frame object.
%   newCOMs = Nx2 array of cells COMs.
%   newLabels = (optional) Nx1 array of cells labeles.
% Outputs:
%   labeles = output labeles.
%   idx = labeles locations in array.
    if(isempty(self.centers) || isempty(newCOMs))
        labels = [];
        idx = [];
    else
        if (nargin > 2)
            idx = knnsearch(newCOMs, self.centers);
            labels = newLabels(idx);
        else
            idx = knnsearch(self.centers,newCOMs);
            labels = self.labels(idx);
        end
    end
end


text:
//Write a program that reads 3 integer numbers from the console and prints their sum.

using System;

class Sum3Numbers
{
    static void Main()
    {
        int firstNum;
        int secondNum;
        int thirdNum;
        bool isValid;
        do
        {
            Console.WriteLine("Please input the first integer number:");
            isValid = Int32.TryParse(Console.ReadLine(), out firstNum);
        }
        while(!isValid);
        do
        {
            Console.WriteLine("Please input the second integer number:");
            isValid = Int32.TryParse(Console.ReadLine(), out secondNum);
        }
        while(!isValid);
        do
        {
            Console.WriteLine("Please input the third integer number:");
            isValid = Int32.TryParse(Console.ReadLine(), out thirdNum);
        }
        while (!isValid);
        Console.WriteLine("The sum of the three numbers is: {0}", firstNum + secondNum + thirdNum);
    }
}


text:
#ifndef ALEXA_CLIENT_SDK_AVSCOMMON_SDKINTERFACES_TEST_AVSCOMMON_SDKINTERFACES_MOCKDIRECTIVEHANDLERRESULT_H_
#define ALEXA_CLIENT_SDK_AVSCOMMON_SDKINTERFACES_TEST_AVSCOMMON_SDKINTERFACES_MOCKDIRECTIVEHANDLERRESULT_H_

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include "AVSCommon/SDKInterfaces/DirectiveHandlerResultInterface.h"

namespace alexaClientSDK {
namespace avsCommon {
namespace sdkInterfaces {
namespace test {

/// Mock @c DirectiveHandlerResultInterface implementation.
class MockDirectiveHandlerResult : public DirectiveHandlerResultInterface {
public:
    MOCK_METHOD0(setCompleted, void());
    MOCK_METHOD1(setFailed, void(const std::string& description));
};

}  // namespace test
}  // namespace sdkInterfaces
}  // namespace avsCommon
}  // namespace alexaClientSDK

#endif  // ALEXA_CLIENT_SDK_AVSCOMMON_SDKINTERFACES_TEST_AVSCOMMON_SDKINTERFACES_MOCKDIRECTIVEHANDLERRESULT_H_


text:
package com.example.client;

import java.util.UUID;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Note {

	final UUID id;
	final String title;

	@JsonCreator
	public Note(@JsonProperty("id") UUID id, @JsonProperty("title") String title) {
		this.id = id;
		this.title = title;
	}

	public UUID getId() {
		return id;
	}

	public String getTitle() {
		return title;
	}
}


text:
package org.mtransit.android.ui.view.map;

import android.graphics.Bitmap;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresPermission;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;

import java.util.List;

// based on Maciej Górski's Android Maps Extensions library (Apache License, Version 2.0)
@SuppressWarnings("unused")
public interface ExtendedGoogleMap {

	int MAP_TYPE_HYBRID = com.google.android.gms.maps.GoogleMap.MAP_TYPE_HYBRID;
	int MAP_TYPE_NONE = com.google.android.gms.maps.GoogleMap.MAP_TYPE_NONE;
	int MAP_TYPE_NORMAL = com.google.android.gms.maps.GoogleMap.MAP_TYPE_NORMAL;
	int MAP_TYPE_SATELLITE = com.google.android.gms.maps.GoogleMap.MAP_TYPE_SATELLITE;
	int MAP_TYPE_TERRAIN = com.google.android.gms.maps.GoogleMap.MAP_TYPE_TERRAIN;

	@Deprecated
	Circle addCircle(CircleOptions circleOptions);

	GroundOverlay addGroundOverlay(GroundOverlayOptions groundOverlayOptions);

	@NonNull
	IMarker addMarker(@NonNull ExtendedMarkerOptions markerOptions);

	Polygon addPolygon(PolygonOptions polygonOptions);

	Polyline addPolyline(PolylineOptions polylineOptions);

	TileOverlay addTileOverlay(TileOverlayOptions tileOverlayOptions);

	void animateCamera(CameraUpdate cameraUpdate, CancelableCallback cancelableCallback);

	void animateCamera(CameraUpdate cameraUpdate, int time, CancelableCallback cancelableCallback);

	void animateCamera(@NonNull CameraUpdate cameraUpdate);

	void clear();

	CameraPosition getCameraPosition();

	List<IMarker> getDisplayedMarkers();

	int getMapType();

	List<Circle> getCircles();

	List<GroundOverlay> getGroundOverlays();

	List<IMarker> getMarkers();

	IMarker getMarkerShowingInfoWindow();

	List<Polygon> getPolygons();

	List<Polyline> getPolylines();

	List<TileOverlay> getTileOverlays();

	float getMaxZoomLevel();

	float getMinZoomLevel();

	float getMinZoomLevelNotClustered(IMarker marker);

	Projection getProjection();

	UiSettings getUiSettings();

	boolean isBuildingsEnabled();

	boolean isIndoorEnabled();

	boolean isMyLocationEnabled();

	boolean isTrafficEnabled();

	void moveCamera(@NonNull CameraUpdate cameraUpdate);

	void setBuildingsEnabled(boolean buildingsEnabled);

	void setClustering(ClusteringSettings clusteringSettings);

	boolean setIndoorEnabled(boolean indoorEnabled);

	void setInfoWindowAdapter(InfoWindowAdapter infoWindowAdapter);

	void setLocationSource(LocationSource locationSource);

	void setMapType(int mapType);

	void setMapStyle(@Nullable MapStyleOptions mapStyleOptions);

	@RequiresPermission(
			anyOf = {"android.permission.ACCESS_COARSE_LOCATION", "android.permission.ACCESS_FINE_LOCATION"}
	)
	void setMyLocationEnabled(boolean myLocationEnabled);

	void setOnCameraChangeListener(OnCameraChangeListener onCameraChangeListener);

	void setOnInfoWindowClickListener(OnInfoWindowClickListener onInfoWindowClickListener);

	void setOnMapClickListener(OnMapClickListener onMapClickListener);

	void setOnMapLoadedCallback(OnMapLoadedCallback onMapLoadedCallback);

	void setOnMapLongClickListener(OnMapLongClickListener onMapLongClickListener);

	void setOnMarkerClickListener(OnMarkerClickListener onMarkerClickListener);

	void setOnMarkerDragListener(OnMarkerDragListener onMarkerDragListener);

	void setOnMyLocationButtonClickListener(OnMyLocationButtonClickListener listener);

	void setPadding(int left, int top, int right, int bottom);

	void setTrafficEnabled(boolean trafficEnabled);

	void snapshot(SnapshotReadyCallback callback);

	void snapshot(SnapshotReadyCallback callback, Bitmap bitmap);

	void stopAnimation();

	interface CancelableCallback extends com.google.android.gms.maps.GoogleMap.CancelableCallback {

		@Override
		void onCancel();

		@Override
		void onFinish();
	}

	interface InfoWindowAdapter {

		View getInfoContents(IMarker marker);

		View getInfoWindow(IMarker marker);
	}

	// FIXME
	@SuppressWarnings("deprecation")
	interface OnCameraChangeListener extends com.google.android.gms.maps.GoogleMap.OnCameraChangeListener {

		@Override
		void onCameraChange(@NonNull CameraPosition cameraPosition);
	}

	interface OnInfoWindowClickListener {

		void onInfoWindowClick(IMarker marker);
	}

	interface OnMapClickListener extends com.google.android.gms.maps.GoogleMap.OnMapClickListener {

		@Override
		void onMapClick(@NonNull LatLng position);
	}

	interface OnMapLoadedCallback extends com.google.android.gms.maps.GoogleMap.OnMapLoadedCallback {

		@Override
		void onMapLoaded();
	}

	interface OnMapLongClickListener extends com.google.android.gms.maps.GoogleMap.OnMapLongClickListener {

		@Override
		void onMapLongClick(@NonNull LatLng position);
	}

	interface OnMarkerClickListener {

		boolean onMarkerClick(IMarker marker);
	}

	interface OnMarkerDragListener {

		void onMarkerDragStart(IMarker marker);

		void onMarkerDrag(IMarker marker);

		void onMarkerDragEnd(IMarker marker);
	}

	interface OnMyLocationButtonClickListener extends com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener {

		@Override
		boolean onMyLocationButtonClick();
	}

	interface SnapshotReadyCallback extends com.google.android.gms.maps.GoogleMap.SnapshotReadyCallback {

		@Override
		void onSnapshotReady(@Nullable Bitmap snapshot);
	}
}


text:
package org.apache.geode.launchers;

import static java.nio.file.Files.copy;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.apache.geode.internal.lang.SystemUtils.isWindows;
import static org.apache.geode.test.awaitility.GeodeAwaitility.await;
import static org.apache.geode.test.awaitility.GeodeAwaitility.getTimeout;
import static org.apache.geode.test.util.ResourceUtils.createFileFromResource;
import static org.apache.geode.test.util.ResourceUtils.getResource;
import static org.assertj.core.api.Assertions.assertThat;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import org.apache.geode.internal.AvailablePortHelper;
import org.apache.geode.test.assertj.LogFileAssert;
import org.apache.geode.test.junit.rules.RequiresGeodeHome;

public class ServerLauncherWithCustomLogConfigAcceptanceTest {

  private static final String CONFIG_FILE_NAME =
      "ServerLauncherWithCustomLogConfigAcceptanceTest.xml";
  private static final String SERVER_NAME = "the-server";

  private int serverPort;
  private Path configFile;
  private Process server;
  private Path geodeDependencies;
  private Path stdoutFile;
  private Path serverLogFile;
  private Path javaBin;

  @Rule
  public RequiresGeodeHome requiresGeodeHome = new RequiresGeodeHome();
  @Rule
  public TemporaryFolder temporaryFolder = new TemporaryFolder();

  @Before
  public void setUpJava() {
    String javaHome = System.getProperty("java.home");
    assertThat(javaHome)
        .as("java.home is not null")
        .isNotNull();

    String java = isWindows() ? "java.exe" : "java";
    javaBin = Paths.get(javaHome, "bin", java);
    assertThat(javaBin)
        .as("JAVA_HOME/bin/" + java + " exists")
        .exists();
  }

  @Before
  public void setUpGeodeDependencies() {
    Path geodeHome = requiresGeodeHome.getGeodeHome().toPath();
    geodeDependencies = geodeHome.resolve("lib/geode-dependencies.jar");

    assertThat(geodeDependencies)
        .as("GEODE_HOME/lib/geode-dependencies.jar exists")
        .exists();
  }

  @Before
  public void setUpLogConfigFile() {
    configFile = createFileFromResource(getResource(CONFIG_FILE_NAME), temporaryFolder.getRoot(),
        CONFIG_FILE_NAME)
            .toPath();
  }

  @Before
  public void setUpOutputFiles() {
    stdoutFile = temporaryFolder.getRoot().toPath().resolve("stdout.txt");
    serverLogFile = temporaryFolder.getRoot().toPath().resolve(SERVER_NAME + ".log");
  }

  @Before
  public void setUpRandomPorts() {
    serverPort = AvailablePortHelper.getRandomAvailableTCPPort();
  }

  @After
  public void stopServer() throws Exception {
    if (server != null) {
      server.destroyForcibly().waitFor(getTimeout().toMillis(), MILLISECONDS);
    }
  }

  @Test
  public void serverLauncherUsesSpecifiedConfigFile() throws Exception {
    ProcessBuilder processBuilder = new ProcessBuilder()
        .redirectErrorStream(true)
        .redirectOutput(stdoutFile.toFile())
        .directory(temporaryFolder.getRoot())
        .command(javaBin.toFile().getAbsolutePath(),
            "-Djava.awt.headless=true",
            "-Dlog4j.configurationFile=" + configFile.toAbsolutePath(),
            "-cp", geodeDependencies.toFile().getAbsolutePath(),
            "org.apache.geode.distributed.ServerLauncher", "start", SERVER_NAME,
            "--server-port", String.valueOf(serverPort));

    System.out.println("Environment: " + System.getenv());
    System.out.println("Launching command: " + processBuilder.command());

    server = processBuilder
        .start();

    assertThat(server.isAlive()).isTrue();

    await().untilAsserted(() -> {
      assertThat(serverLogFile)
          .as(serverLogFile.toFile().getAbsolutePath())
          .doesNotExist();

      LogFileAssert.assertThat(stdoutFile.toFile())
          .as(stdoutFile.toFile().getAbsolutePath())
          .exists()
          .contains("Server " + SERVER_NAME + " startup completed in ")
          .doesNotContain("java.lang.IllegalStateException: No factory method found for class");
    });
  }

  @Test
  public void serverLauncherUsesConfigFileInClasspath() throws Exception {
    copy(configFile, temporaryFolder.getRoot().toPath().resolve("log4j2.xml"));

    String classpath = temporaryFolder.getRoot().getAbsolutePath() + File.pathSeparator +
        geodeDependencies.toFile().getAbsolutePath();

    ProcessBuilder processBuilder = new ProcessBuilder()
        .redirectErrorStream(true)
        .redirectOutput(stdoutFile.toFile())
        .directory(temporaryFolder.getRoot())
        .command(javaBin.toFile().getAbsolutePath(),
            "-Djava.awt.headless=true",
            "-cp", classpath,
            "org.apache.geode.distributed.ServerLauncher", "start", SERVER_NAME,
            "--server-port", String.valueOf(serverPort));

    System.out.println("Environment: " + System.getenv());
    System.out.println("Launching command: " + processBuilder.command());

    server = processBuilder
        .start();

    assertThat(server.isAlive()).isTrue();

    await().untilAsserted(() -> {
      assertThat(serverLogFile)
          .as(serverLogFile.toFile().getAbsolutePath())
          .doesNotExist();

      LogFileAssert.assertThat(stdoutFile.toFile())
          .as(stdoutFile.toFile().getAbsolutePath())
          .exists()
          .contains("Server " + SERVER_NAME + " startup completed in ")
          .doesNotContain("java.lang.IllegalStateException: No factory method found for class");
    });
  }
}


text:
package javax.print.attribute.standard;

import java.io.Serial;

import javax.print.attribute.Attribute;
import javax.print.attribute.EnumSyntax;

/**
 * Class {@code ReferenceUriSchemesSupported} is a printing attribute class an
 * enumeration, that indicates a "URI scheme," such as "http:" or "ftp:", that a
 * printer can use to retrieve print data stored at a {@code URI} location. If a
 * printer supports doc flavors with a print data representation class of
 * {@code "java.net.URL"}, the printer uses instances of class
 * {@code ReferenceUriSchemesSupported} to advertise the {@code URI} schemes it
 * can accept. The acceptable {@code URI} schemes are included as service
 * attributes in the lookup service; this lets clients search the for printers
 * that can get print data using a certain {@code URI} scheme. The acceptable
 * {@code URI} schemes can also be queried using the capability methods in
 * interface {@code PrintService}. However, {@code ReferenceUriSchemesSupported}
 * attributes are used solely for determining acceptable {@code URI} schemes,
 * they are never included in a doc's, print request's, print job's, or print
 * service's attribute set.
 *

 * The Internet Assigned Numbers Authority maintains the
 * official list of
 * URI schemes.
 *

 * Class {@code ReferenceUriSchemesSupported} defines enumeration values for
 * widely used {@code URI} schemes. A printer that supports additional
 * {@code URI} schemes can define them in a subclass of class
 * {@code ReferenceUriSchemesSupported}.
 *

 * IPP Compatibility: The category name returned by {@code getName()} is
 * the IPP attribute name. The enumeration's integer value is the IPP enum
 * value. The {@code toString()} method returns the IPP string representation of
 * the attribute value.
 *
 * @author Alan Kaminsky
 */
public class ReferenceUriSchemesSupported
    extends EnumSyntax implements Attribute {

    /**
     * Use serialVersionUID from JDK 1.4 for interoperability.
     */
    @Serial
    private static final long serialVersionUID = -8989076942813442805L;

    /**
     * File Transfer Protocol (FTP).
     */
    public static final ReferenceUriSchemesSupported FTP =
        new ReferenceUriSchemesSupported(0);

    /**
     * HyperText Transfer Protocol (HTTP).
     */
    public static final ReferenceUriSchemesSupported HTTP = new ReferenceUriSchemesSupported(1);

    /**
     * Secure HyperText Transfer Protocol (HTTPS).
     */
    public static final ReferenceUriSchemesSupported HTTPS = new ReferenceUriSchemesSupported(2);

    /**
     * Gopher Protocol.
     */
    public static final ReferenceUriSchemesSupported GOPHER = new ReferenceUriSchemesSupported(3);

    /**
     * USENET news.
     */
    public static final ReferenceUriSchemesSupported NEWS = new ReferenceUriSchemesSupported(4);

    /**
     * USENET news using Network News Transfer Protocol (NNTP).
     */
    public static final ReferenceUriSchemesSupported NNTP = new ReferenceUriSchemesSupported(5);

    /**
     * Wide Area Information Server (WAIS) protocol.
     */
    public static final ReferenceUriSchemesSupported WAIS = new ReferenceUriSchemesSupported(6);

    /**
     * Host-specific file names.
     */
    public static final ReferenceUriSchemesSupported FILE = new ReferenceUriSchemesSupported(7);

    /**
     * Construct a new reference {@code URI} scheme enumeration value with the
     * given integer value.
     *
     * @param  value Integer value
     */
    protected ReferenceUriSchemesSupported(int value) {
        super (value);
    }

    /**
     * The string table for class {@code ReferenceUriSchemesSupported}.
     */
    private static final String[] myStringTable = {
        "ftp",
        "http",
        "https",
        "gopher",
        "news",
        "nntp",
        "wais",
        "file",
    };

    /**
     * The enumeration value table for class
     * {@code ReferenceUriSchemesSupported}.
     */
    private static final ReferenceUriSchemesSupported[] myEnumValueTable = {
        FTP,
        HTTP,
        HTTPS,
        GOPHER,
        NEWS,
        NNTP,
        WAIS,
        FILE,
    };

    /**
     * Returns the string table for class {@code ReferenceUriSchemesSupported}.
     */
    protected String[] getStringTable() {
        return myStringTable.clone();
    }

    /**
     * Returns the enumeration value table for class
     * {@code ReferenceUriSchemesSupported}.
     */
    protected EnumSyntax[] getEnumValueTable() {
        return (EnumSyntax[])myEnumValueTable.clone();
    }

    /**
     * Get the printing attribute class which is to be used as the "category"
     * for this printing attribute value.
     *

     * For class {@code ReferenceUriSchemesSupported} and any vendor-defined
     * subclasses, the category is class {@code ReferenceUriSchemesSupported}
     * itself.
     *
     * @return printing attribute class (category), an instance of class
     *         {@link Class java.lang.Class}
     */
    public final Class<? extends Attribute> getCategory() {
        return ReferenceUriSchemesSupported.class;
    }

    /**
     * Get the name of the category of which this attribute value is an
     * instance.
     *

     * For class {@code ReferenceUriSchemesSupported} and any vendor-defined
     * subclasses, the category name is
     * {@code "reference-uri-schemes-supported"}.
     *
     * @return attribute category name
     */
    public final String getName() {
        return "reference-uri-schemes-supported";
    }
}


text:
<?php
namespace CoderOrders\V1\Rest\Products;

class ProductsResourceFactory
{
    public function __invoke($services)
    {
        $usersRepository = $services->get('CoderOrders\\V1\\Rest\\Users\\UsersRepository');
        return new ProductsResource($services->get('CoderOrders\\V1\\Rest\\Products\\ProductsRepository'), $usersRepository);
    }
}


text:
#ifndef MUMBLE_MUMBLE_THEMEINFO_H_
#define MUMBLE_MUMBLE_THEMEINFO_H_

#include <QtCore/QString>
#include <QtCore/QFileInfo>
#include <QtCore/QMap>
#include <QMetaType>
#ifndef Q_MOC_RUN
#include <boost/optional.hpp>
#endif

class QSettings;
class QDir;

class ThemeInfo;
typedef QMap<QString, ThemeInfo> ThemeMap;

/// Description of a Mumble theme with multiple styles
class ThemeInfo {
public:
	/// A specific style of a Mumble theme
	///
	/// Multiple styles can for example be used to differentiate light/dark
	/// variants of a theme.
	///
	/// A single style can refer to multiple run-time platform specific qss
	/// theme files.
	class StyleInfo {
	public:
		/// Name of the theme containing this style
		QString themeName;
		/// Name for the style
		QString name;

		/// @return Returns platform specific qss or defaultQss if none available
		QFileInfo getPlatformQss() const;

		/// Default QSS file for the style
		QFileInfo defaultQss;
		/// Platform specific QSS files available
		QMap<QString, QFileInfo> qssFiles;
	};

	typedef QMap<QString, StyleInfo> StylesMap;

	/// Takes stock of all mumble themes in the given folders.
	///
	/// If a theme with the same name is available in multiple directories
	/// only the last occurance will be returned.
	///
	/// @param themesDirectories List of directories to search for theme directories.
	/// @return Map of theme name to Theme
	static ThemeMap scanDirectories(const QVector<QDir> &themesDirectories);

	/// Takes stock of all mumble themes in the given folder
	///
	/// Uses loadThemeInfoFromDirectory on each directory in the folder
	/// to find themes. Themes with the same names will override each other.
	///
	/// @param themesDirectory Directory to scan for theme directories
	/// @return Map of theme name to Theme
	static ThemeMap scanDirectory(const QDir &themesDirectory);

	/// Loads the theme description from a given directory
	///
	/// @param themeDirectory
	/// @return Theme if description was correctly loaded. boost::none if not.
	static boost::optional<ThemeInfo> load(const QDir &themeDirectory);

	/// @return Style with given name or default
	StyleInfo getStyle(QString name) const;

	/// Ideally unique theme name. A theme with identical name can override.
	QString name;
	/// Style name to style mapping.
	StylesMap styles;
	/// Default style
	QString defaultStyle;
};

Q_DECLARE_METATYPE(ThemeInfo);
Q_DECLARE_METATYPE(ThemeInfo::StyleInfo);

#endif // MUMBLE_MUMBLE_THEMEINFO_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/blocks_context_browse"
        android:showAsAction="never"
        android:title="@string/action_browse"/>

</menu>


text:
package com.ocs.dynamo.dao.impl;

import com.ocs.dynamo.domain.CascadeEntity;
import com.querydsl.core.types.dsl.EntityPathBase;
import org.springframework.stereotype.Repository;

@Repository("cascadeEntityDao")
public class CascadeEntityDaoImpl extends BaseDaoImpl<Integer, CascadeEntity> implements CascadeEntityDao {

    @Override
    public Class<CascadeEntity> getEntityClass() {
        return CascadeEntity.class;
    }

    @Override
    protected EntityPathBase<CascadeEntity> getDslRoot() {
        return null;
    }

}


text:
Color Code is an Android App developed by [Gianpaolo Macario](https://gmacario.github.io/)
as final project for the [Android Study Jam](http://android-studyjam.eventbrite.it/) organized by [GDG Torino](https://www.facebook.com/gdgtorino) in March 2016.

![Color Code Logo](images/capture-20160415-1910.png)

Getting started
===============

Download [Android Studio](http://developer.android.com/sdk/index.html) 2.0 for Windows.

Install Android Studio on your laptop.

Start Android Studio, then **Check out project from Version Control** > **Git**

> Clone Repository
>
> * Git Repository URL: `https://github.com/gmacario/colorcode`
> * Parent Directory: `C:\Users\gmacario\AndroidStudioProjects`
> * Directory Name: `colorcode`

then click **Clone**.

Inside Android Studio: **Build** > **Make Project**

Inside Android Studio: **Run** > **Run 'app'**

Select Deployment target (choose Emulator `Nexus 5 API 23 x86`), then click **OK**.

The Idea
========

The "[Color Code](https://github.com/gmacario/colorcode)" project is an educational Android app which provides five ways to learn how to read and memorize color code of resistors.

### The Target User

A young student who is attempting at learning electrical engineering, or just recognizing the different resistors of his brand new [Arduino Starter Kit](http://www.arduino.cc/en/Main/ArduinoStarterKit).

Persona: Filippo (my younger kid).

### Information needed by the target user

Quick way for learning (and remembering) how to convert color stripes painted on a resistor to actual value of resistance (incl. tolerance).

Maybe use a game to help memorizing.

### The Functions

1. Select colors, print the resistance value and tolerance
2. Type resistance, display color stripes
3. Select decade and tolerance, print nominal resistance ranges
4. Game: Find the wrong color
5. Game: Fill in the missing color

The Design of the App
=====================

See [App Design (PDF)](colorcode-design-20160413-1656.pdf).

Known issues and limitations
============================

1. The App does not do anything really useful right now
1. Only Emulated target is supported. You may try running the app on your mobile phone connected via ADB, Your Mileage May Vary

Contributing to Color Code
==========================

[Pull Requests](https://github.com/gmacario/colorcode/pulls) are welcome!

Licensing
=========

Copyright 2016, [Gianpaolo Macario](https://gmacario.github.io/).

Color Code is licensed under the Apache License, Version 2.0. See
[LICENSE](https://github.com/gmacario/colorcode/blob/master/LICENSE) for the full
license text.

<!-- EOF -->


text:
package in.twizmwaz.cardinal.module.modules.doubleKillPatch;

import in.twizmwaz.cardinal.match.Match;
import in.twizmwaz.cardinal.module.BuilderData;
import in.twizmwaz.cardinal.module.ModuleBuilder;
import in.twizmwaz.cardinal.module.ModuleCollection;
import in.twizmwaz.cardinal.module.ModuleLoadTime;

@BuilderData(load = ModuleLoadTime.LATEST)
public class DoubleKillPatchBuilder implements ModuleBuilder {

    @Override
    public ModuleCollection load(Match match) {
        ModuleCollection results = new ModuleCollection();
        results.add(new DoubleKillPatch());
        return results;
    }

}


text:
// Define Libraries to Import
import React from 'react';
import { Link } from 'react-router';
import sanitizeHtml from 'sanitize-html';
import FileManager from '../../core/FileManager';

/**
 * @class WelcomePage
 * @description Initial page after loading the application,
 * responsible for retrieving all stored files and displaying to user.
 * @description Passes contents of word document to other pages.
 * */
class WelcomePage extends React.Component {
  static propTypes = {};

  /** CONSTRUCTOR
   *  - Create File Manager Instances
   *  - Initialize State as empty notes array
   *
   * @param props
   */
  constructor(props) {
    super(props);
    this.fileManager = new FileManager();
    this.state = { notes: [] };

    // Define Function that Updates Notes array
    this.updateNotes = () =>
      this.fileManager.getNotes()
        .then(({ notes, categories }) => {
          this.setState({ notes, categories });
          console.log(this.state);
          return this.state;
        }).catch((err) => {
          console.warn('Unable to retrieve notes', err);
          setTimeout(this.updateNotes, 1500);
        });
    // Define Function that deletes the given notes
    this.deleteNote = (folder, name) => {
      this.fileManager.deleteNote(folder, name)
        .then(this.updateNotes)
        .catch((err) => console.warn('Unable to delete note', err));
    };
  }

  /** Creates Folder and Updates Notes
   *
   */
  componentDidMount() {
    this.fileManager
      .createFolder()
      .then(this.updateNotes)
      .catch(console.error);
  }

  render() {
    const { notes, categories } = this.state;
    return (

Research Journal Writing Tool

                  <Link className="button is-primary" to="/home" >
                    Create Document</Link>

                {notes.map((note) => (
                  <article className="media note" key={`${note.fileName}${note.type}`} >

                          {note.date} {' | '}
                          {note.location}
                          {' | '}
                          {note.type}
                          {' '}

 100)
                                ? `${sanitizeHtml(note.body.slice(0, 100).replace(/<p>|<\/p>/g, ''))} ...`
                                : `${sanitizeHtml(note.body.replace(/<p>|<\/p>/g, ''))}`
                            }}
                          />

                            <Link
                              className="button is-info is-small"
                              to={{ pathname: '/home', state: { note, categories } }}
                            >

                              Open
                            </Link>

                             this.deleteNote(note.type, note.fileName)}
                            >

                              Delete

                ))
                }

    );
  }
}

export default WelcomePage;


text:
/*jslint indent:2*/
/*global require:true, console:true, process:true, setInterval:true*/

(function () {
  'use strict';

  process.env.DEBUG = '*';

  var diehard = require('../');

  setInterval(function () {
    console.log('Both cleanup handlers will be called!');
  }, 250);

  // synchronous handlers
  diehard.register(function () {
    console.log('cleanup #1');
  });

  // async handlers
  diehard.register(function (done) {
    console.log('cleanup #2');
    process.nextTick(done);
  });

  diehard.listen();

  setTimeout(function () {
    process.kill(process.pid, 'SIGINT');
  }, 1000);

}());


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.att.m2x.android.sharedPreferences</title>
<meta name="date" content="2017-03-06">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.att.m2x.android.sharedPreferences

Class Summary

Class
Description

APISharedPreferences

ATT M2X Shared Preference

Skip navigation links

Overview

Package

Class

Use

Tree

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes