text:
<?php

declare(strict_types=1);

namespace Contentful\Delivery\Mapper;

use Contentful\Delivery\Resource\ContentType as ResourceClass;
use Contentful\Delivery\Resource\ContentType\Field as ResourceContentTypeField;
use Contentful\Delivery\SystemProperties\ContentType as SystemProperties;

/**
 * ContentType class.
 *
 * This class is responsible for converting raw API data into a PHP object
 * of class Contentful\Delivery\Resource\ContentType.
 */
class ContentType extends BaseMapper
{
    /**
     * {@inheritdoc}
     */
    public function map($resource, array $data): ResourceClass
    {
        $fields = [];
        foreach ($data['fields'] as $field) {
            $field = $this->mapField($field);
            $fields[$field->getId()] = $field;
        }

        /** @var ResourceClass $contentType */
        $contentType = $this->hydrator->hydrate($resource ?: ResourceClass::class, [
            'sys' => $this->createSystemProperties(SystemProperties::class, $data),
            'name' => $data['name'],
            'displayField' => $data['displayField'] ?? null,
            'description' => $data['description'] ?? null,
            'fields' => $fields,
        ]);

        return $contentType;
    }

    protected function mapField(array $data): ResourceContentTypeField
    {
        /** @var ResourceContentTypeField $field */
        $field = $this->hydrator->hydrate(ResourceContentTypeField::class, [
            'id' => $data['id'],
            'name' => $data['name'],
            'type' => $data['type'],
            'linkType' => $data['linkType'] ?? null,
            'itemsType' => isset($data['items']) && isset($data['items']['type']) ? $data['items']['type'] : null,
            'itemsLinkType' => isset($data['items']) && isset($data['items']['linkType']) ? $data['items']['linkType'] : null,
            'required' => $data['required'] ?? false,
            'localized' => $data['localized'] ?? false,
            'disabled' => $data['disabled'] ?? false,
        ]);

        return $field;
    }
}


text:
// Code generated by ""fitask" -type=Droplet"; DO NOT EDIT

package dotasks

import (
	"encoding/json"

	"k8s.io/kops/upup/pkg/fi"
)

// Droplet

// JSON marshalling boilerplate
type realDroplet Droplet

// UnmarshalJSON implements conversion to JSON, supporting an alternate specification of the object as a string
func (o *Droplet) UnmarshalJSON(data []byte) error {
	var jsonName string
	if err := json.Unmarshal(data, &jsonName); err == nil {
		o.Name = &jsonName
		return nil
	}

	var r realDroplet
	if err := json.Unmarshal(data, &r); err != nil {
		return err
	}
	*o = Droplet(r)
	return nil
}

var _ fi.HasLifecycle = &Droplet{}

// GetLifecycle returns the Lifecycle of the object, implementing fi.HasLifecycle
func (o *Droplet) GetLifecycle() *fi.Lifecycle {
	return o.Lifecycle
}

// SetLifecycle sets the Lifecycle of the object, implementing fi.SetLifecycle
func (o *Droplet) SetLifecycle(lifecycle fi.Lifecycle) {
	o.Lifecycle = &lifecycle
}

var _ fi.HasName = &Droplet{}

// GetName returns the Name of the object, implementing fi.HasName
func (o *Droplet) GetName() *string {
	return o.Name
}

// SetName sets the Name of the object, implementing fi.SetName
func (o *Droplet) SetName(name string) {
	o.Name = &name
}

// String is the stringer function for the task, producing readable output using fi.TaskAsString
func (o *Droplet) String() string {
	return fi.TaskAsString(o)
}

redpajama_set_name: RedPajamaGithub


text:
[![License](https://poser.pugx.org/LaravelCollective/html/license.svg)](https://packagist.org/packages/laravelcollective/html)

It is fork of popular Laravel Collective for Laravel five.

Some examples:
```php
{!! Bootstrap::open(array('url' => 'foo/bar', 'formType' => 'horizontal')) !!}
{!! Bootstrap::text('test',null,array('label' => 'Laravel')) !!}
{!! Bootstrap::number('test1',null,array('label' => 'Laravel')) !!}
{!! Bootstrap::password('test1',array('label' => 'Laravel')) !!}
{!! Bootstrap::checkbox('name', 'value') !!}
{!! Bootstrap::checkboxes('namea', array('value1' => 'Test1','value2' => 'Test2'), array('value1','value2'), array('label' => 'Leopard')) !!}
{!! Bootstrap::radios('namea', array('value1' => 'Test1','value2' => 'Test2'), 'value2', array('label' => 'Leopard')) !!}
{!! Bootstrap::select('animal', array('Cats' => array('leopard' => 'Leopard'),'Dogs' => array('spaniel' => 'Spaniel') )) !!}
{!! Bootstrap::select('animal', array('leopard' => 'Leopard','spaniel' => 'Spaniel' )) !!}
{!! Bootstrap::textarea("test") !!}
{!! Bootstrap::submit("Test") !!}
{!! Bootstrap::button("Test", array('pattern' => 'primary', 'disabled' => 'disabled')) !!}
{!! Bootstrap::close() !!}
```
Later I will add detailed comments and documentation.
If you want to contribute, welcome ;-)

Official documentation for Forms & Html for The Laravel Framework can be found at the [LaravelCollective](http://laravelcollective.com) website.


text:
angular.module('myApp').controller('Contribute/GlaasCtrl', function($scope, $routeParams, $location, Restangular, QuestionAssistant) {
    'use strict';

    $scope.questionnaireQueryParams = {permission: 'update', surveyType: 'glaas'};

    // If a questionnaire is specified in URL, load its data
    if ($routeParams.id) {
        $scope.isLoading = true;
        Restangular.one('questionnaire', $routeParams.id).all('question').getList({perPage: 1000, fields: 'type,filter,answers,isCompulsory,choices,parts,isMultiple,isFinal,chapter,description'}).then(function(questions) {
            $scope.questions = questions;
            $scope.isLoading = false;
        });
    }

    $scope.navigation = []; // used in next + previous buttons
    $scope.hierarchicQuestions = []; // used in hierarchic menu
    $scope.currentIndex = 0;
    $scope.currentQuestion = 0;
    $scope.index = {}; // indexed answers
    $scope.score = {};

    $scope.$watch(function() {
        return $location.url();
    }, function() {
        $scope.returnUrl = $location.search().returnUrl;
        $scope.currentUrl = encodeURIComponent($location.url());
    });

    $scope.$watch('questionnaire', function() {
        $scope.initializeQuestionnaire();
    });

    $scope.$watch('questions', function() {
        $scope.initializeQuestionnaire();
    });

    $scope.$watch('currentIndex', function(newIndex, old) {
        if (newIndex !== old) {
            $scope.refreshQuestion();
        }
    });

    var questionnaire2 = null;
    $scope.initializeQuestionnaire = function() {
        if ($scope.questionnaire && $scope.questions && $scope.questions.length > 0) {

            var questionnaire2 = _.cloneDeep($scope.questionnaire);

            // Load questionnaire permissions
            Restangular.one('questionnaire', $routeParams.id).get({fields: 'permissions'}).then(function(questionnaire) {
                $scope.questionnaire.permissions = questionnaire.permissions;
                questionnaire2.permissions = $scope.questionnaire.permissions;
            });

            questionnaire2.level = -1;
            questionnaire2.index = -1;
            questionnaire2.statusCode = 4;

            $scope.questions[0].active = true;

            angular.forEach($scope.questions, function(question, index) {

                // assign key to each question -> navigation menu bar uses it to avoid loops
                question.index = index;

                // prepare navigation
                question.hasFinalParentChapters = $scope.hasFinalParentChapters(index);
                if (question && question.type && !question.hasFinalParentChapters) {
                    question.navIndex = $scope.navigation.length;
                    $scope.navigation.push(question);
                }

                // restangularize answers
                angular.forEach(question.answers, function(answer) {
                    answer = Restangular.restangularizeElement(null, answer, 'answer');
                });
            });

            // preparing hierarchic questions : used for nav and for validation form
            $scope.hierarchicQuestions = $scope.getChildren(questionnaire2, $scope.questions);
            questionnaire2.children = $scope.hierarchicQuestions;
            QuestionAssistant.updateQuestion(questionnaire2, $scope.index, true);
            $scope.refreshQuestion();
        }
    };

    $scope.markQuestionnaireAs = function(newStatus) {
        if (questionnaire2.statusCode == 2 || questionnaire2.statusCode == 3) {
            if (newStatus === 'completed' && questionnaire2.status === 'new' || newStatus === 'validated' && questionnaire2.permissions.validate && questionnaire2.status === 'completed') {
                questionnaire2.status = newStatus;

                // -> cyclic structure error -> remove children
                var children = questionnaire2.children;
                delete questionnaire2.children;

                questionnaire2.put().then(function(questionnaire) {
                    questionnaire2.status = questionnaire.status;
                    questionnaire2.children = children;
                });

            }
        }
    };

    /**
     *
     * @param question that may contain children
     * @param list a flat array with list of all questions
     * @returns {Array} a list of children
     */
    $scope.getChildren = function(question, list) {
        var elements = [];
        if (list && list.length > 0) {
            for (var index = question.index + 1; index < list.length; index++) {
                var testedQuestion = list[index];

                // si même profondeur ou inférieure, inutile de poursuivre, c'est la fin du chapitre
                if (testedQuestion.level <= question.level) {
                    return elements;
                }
                // si profondeur plus grande de 1 = enfant
                if (testedQuestion.level == question.level + 1) {
                    testedQuestion.parent = question;
                    elements.push(testedQuestion);
                }

                if (testedQuestion.level >= question.level + 1) {
                    testedQuestion.children = $scope.getChildren(testedQuestion, list);
                }
            }

            return elements;
        }
    };

    $scope.goToPrintMode = function() {
        var i = 0;
        for (i; i < $scope.navigation.length; i++) {
            if ($scope.navigation[i].level === 0 && ($scope.navigation[i].activeParent || $scope.navigation[i].active)) {
                $scope.navigation[i].isFinal = true;
                if (i == $scope.currentIndex) {
                    $scope.refreshQuestion();
                } else {
                    $scope.currentIndex = $scope.navigation[i].navIndex;
                }
                break;
            }
        }
        setTimeout(function() {
            window.print();
            $scope.navigation[i].isFinal = false;
            $scope.refreshQuestion();
        }, 1500);
    };

    $scope.refreshQuestion = function() {
        var i;
        $scope.currentQuestion = $scope.navigation[$scope.currentIndex];
        // if question is chapter, retrieve all the subquestions that are contained in the chapter for display.
        if ($scope.currentQuestion.isFinal) {
            var children = [];
            for (i = $scope.currentQuestion.index + 1; i < $scope.questions.length; ++i) {
                var testedQuestion = $scope.questions[i];
                if (testedQuestion.level > $scope.currentQuestion.level) {
                    children.push(testedQuestion);
                } else {
                    break;
                }
            }
            $scope.currentQuestionChildren = children;

            // if question is not a chapter, there is no subquestions
        } else {
            $scope.currentQuestionChildren = [];
        }

        // retrieve all parent chapter to display name and description
        $scope.parentChapters = [];
        var firstChapterPerLevel = $scope.getListOfFirstChapterPerLevel($scope.currentQuestion.index, $scope.questions);
        for (var q in firstChapterPerLevel) {
            $scope.parentChapters.push($scope.questions[firstChapterPerLevel[q]]);
        }

        // Update nav (active and active_parent class)
        for (var id in $scope.navigation) {
            var question = $scope.navigation[id];
            question.active = false;
            question.activeParent = false;
        }

        firstChapterPerLevel = $scope.getListOfFirstChapterPerLevel($scope.currentIndex, $scope.navigation);
        for (i = 0; i < firstChapterPerLevel.length; i++) {
            $scope.navigation[firstChapterPerLevel[i]].activeParent = true;
        }
        $scope.currentQuestion.active = true;
    };

    /**
     *  Navigation
     *  */
    $scope.goToNext = function() {
        if ($scope.currentIndex < $scope.navigation.length - 1) {
            $scope.currentIndex = $scope.currentIndex + 1;
        }
    };

    $scope.goToPrevious = function() {
        if ($scope.currentIndex > 0) {
            $scope.currentIndex = $scope.currentIndex - 1;
        }
    };

    $scope.goTo = function(wantedIndex) {
        if (Number(wantedIndex) >= 0) {
            $scope.currentIndex = wantedIndex;
        }
    };

    $scope.getListOfFirstChapterPerLevel = function(startIndex, questions) {
        var askedQuestion = questions[startIndex];
        var firstChapterPerLevel = [];
        for (var j = startIndex; j >= 0; j--) { // go rewind until first question or first zero leveled question
            var testedQuestion = questions[j];
            if (testedQuestion.type === 'Chapter' && testedQuestion.level < askedQuestion.level && !firstChapterPerLevel[testedQuestion.level]) {
                firstChapterPerLevel[testedQuestion.level] = j; // sets the first chapter encontered each level
            }
            if (testedQuestion.level === 0) {
                break;
            }
        }
        return firstChapterPerLevel;
    };

    $scope.hasFinalParentChapters = function(index) {
        var listOfParentChapters = $scope.getListOfFirstChapterPerLevel(index, $scope.questions);
        for (var i in listOfParentChapters) {
            if ($scope.questions[listOfParentChapters[i]].isFinal) {
                return true;
            }
        }
        return false;
    };

    /* Redirect functions */
    var redirect = function() {
        $location.url($location.search().returnUrl);
    };

    $scope.cancel = function() {
        redirect();
    };

});


text:
from easycolor.style import wrap as _w
from easycolor.style import make_style, RESET

# wrap text, appends a style-reset
print(_w('yellow on red', fg='yellow', bg='red'))
print('normal text')

# NOTE: for complex formatting use the parser module

# define some styles
black_on_white = make_style(fg='black', bg='white')
# we have to reset the background here
red_bold = make_style(fg='red', bg='reset', opt='bold')
# An options reset is only possible with a total reset
# we can however negate an option to remove it('!option').
green_bold_underline = make_style(fg='green', opt=('!bold', 'underline'))

print(black_on_white + 'Black on white' + red_bold + 'Red bold' +
      green_bold_underline + 'Green not bold underline' + RESET)

# everything was reset
print('normal text')


text:
package org.foxbpm.engine.impl.task;

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

import org.foxbpm.engine.expression.Expression;
import org.foxbpm.engine.impl.bpmn.behavior.UserTaskBehavior;
import org.foxbpm.engine.impl.util.ExceptionUtil;
import org.foxbpm.engine.task.CommandParamType;
import org.foxbpm.engine.task.TaskCommand;
import org.foxbpm.kernel.runtime.FlowNodeExecutionContext;

public class TaskCommandImpl implements Serializable, TaskCommand {

	/**
	 *
	 */
	private static final long serialVersionUID = -3240434310337515303L;

	protected String id;

	protected String name;

	protected Expression expression;

	protected Expression expressionParam;

	protected String taskCommandType;

	protected UserTaskBehavior userTask;

	protected String taskCommandDefType;

	protected List<CommandParam> commandParams = new ArrayList<CommandParam>();

	public List<CommandParam> getCommandParamsByType(CommandParamType commandParamType) {
		List<CommandParam> commandParamsType = new ArrayList<CommandParam>();
		for (CommandParam commandParam : commandParams) {
			if (commandParam.getBizType() == commandParamType) {
				commandParamsType.add(commandParam);
			}
		}
		return commandParamsType;
	}

	public CommandParam getCommandParam(String paramKey) {
		for (CommandParam commandParam : commandParams) {
			if (commandParam.getKey().equals(paramKey)) {
				return commandParam;
			}
		}
		return null;
	}

	public List<CommandParam> getCommandParams() {
		return commandParams;
	}

	public void setCommandParams(List<CommandParam> commandParams) {
		this.commandParams = commandParams;
	}

	public String getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public Expression getExpression() {
		return expression;
	}

	public Object getExpressionValue(FlowNodeExecutionContext executionContext) {

		if (expression != null) {
			try{
				return expression.getValue(executionContext);
			}catch(Exception ex){
				throw ExceptionUtil.getException("10304003",ex);
			}

		}
		return null;
	}

	public Expression getExpressionParam() {
		return expressionParam;
	}

	public String getTaskCommandType() {
		return taskCommandType;
	}

	public UserTaskBehavior getUserTask() {
		return userTask;
	}

	public String getTaskCommandDefType() {
		return taskCommandDefType;
	}

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

	public void setName(String name) {
		this.name = name;
	}

	public void setExpression(Expression expression) {
		this.expression = expression;
	}

	public void setExpressionParam(Expression expressionParam) {
		this.expressionParam = expressionParam;
	}

	public void setTaskCommandType(String taskCommandType) {
		this.taskCommandType = taskCommandType;
	}

	public void setUserTask(UserTaskBehavior userTask) {
		this.userTask = userTask;
	}

	public void setTaskCommandDefType(String taskCommandDefType) {
		this.taskCommandDefType = taskCommandDefType;
	}

	public Map<String, Object> getPersistentState() {
		Map<String, Object> persistentState = new HashMap<String, Object>();
		persistentState.put("id", this.id);
		persistentState.put("name", getName());
		persistentState.put("type", this.taskCommandType);

		if (this.userTask != null) {
			persistentState.put("nodeId", this.userTask.getId());
			persistentState.put("nodeName", this.userTask.getName());
		}

		return persistentState;
	}

}


text:
package org.docksidestage.hangar.dbflute.dtomapper.bs;

import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;

import org.dbflute.Entity;
import org.dbflute.optional.OptionalEntity;
import org.dbflute.dbmeta.DBMeta;
import org.dbflute.dbmeta.InstanceKeyEntity;
import org.dbflute.dbmeta.dtomap.DtoMapper;
import org.dbflute.dbmeta.dtomap.InstanceKeyDto;
import org.dbflute.helper.beans.DfBeanDesc;
import org.dbflute.helper.beans.DfPropertyDesc;
import org.dbflute.helper.beans.factory.DfBeanDescFactory;
import org.dbflute.jdbc.Classification;
import org.docksidestage.hangar.dbflute.allcommon.CDef;
import org.docksidestage.hangar.dbflute.exentity.*;
import org.docksidestage.hangar.simpleflute.dto.*;
import org.docksidestage.hangar.dbflute.dtomapper.*;

/**
 * The DTO mapper of (サービスランク)SERVICE_RANK as TABLE.

 * 会員のサービスレベルを表現するランク。(ゴールドとかプラチナとか)
 *

 * [primary-key]
 *     SERVICE_RANK_CODE
 *
 * [column]
 *     SERVICE_RANK_CODE, SERVICE_RANK_NAME, SERVICE_POINT_INCIDENCE, NEW_ACCEPTABLE_FLG, DESCRIPTION, DISPLAY_ORDER
 *
 * [sequence]
 *
 *
 * [identity]
 *
 *
 * [version-no]
 *
 *
 * [foreign-table]
 *
 *
 * [referrer-table]
 *     MEMBER_SERVICE
 *
 * [foreign-property]
 *
 *
 * [referrer-property]
 *     memberServiceList
 *

 * @author DBFlute(AutoGenerator)
 */
public abstract class BsServiceRankDtoMapper implements DtoMapper<ServiceRank, ServiceRankDto>, Serializable {

    // ===================================================================================
    //                                                                          Definition
    //                                                                          ==========
    /** The serial version UID for object serialization. (Default) */
    private static final long serialVersionUID = 1L;

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    protected final Map<Entity, Object> _relationDtoMap;
    protected final Map<Object, Entity> _relationEntityMap;
    protected boolean _exceptCommonColumn;
    protected boolean _reverseReference; // default: one-way reference
    protected boolean _instanceCache = true; // default: cached
    protected boolean _suppressMemberServiceList;

    // ===================================================================================
    //                                                                         Constructor
    //                                                                         ===========
    public BsServiceRankDtoMapper() {
        _relationDtoMap = new HashMap<Entity, Object>();
        _relationEntityMap = new HashMap<Object, Entity>();
    }

    public BsServiceRankDtoMapper(Map<Entity, Object> relationDtoMap, Map<Object, Entity> relationEntityMap) {
        _relationDtoMap = relationDtoMap;
        _relationEntityMap = relationEntityMap;
    }

    // ===================================================================================
    //                                                                             Mapping
    //                                                                             =======
    // -----------------------------------------------------
    //                                                to DTO
    //                                                ------
    /**
     * {@inheritDoc}
     */
    public ServiceRankDto mappingToDto(ServiceRank entity) {
        if (entity == null) {
            return null;
        }
        boolean instanceCache = _instanceCache;
        Entity localKey = createInstanceKeyEntity(entity);
        Object cachedLocalDto = instanceCache ? _relationDtoMap.get(localKey) : null;
        if (cachedLocalDto != null) {
            return (ServiceRankDto)cachedLocalDto;
        }
        boolean exceptCommonColumn = isExceptCommonColumn();
        ServiceRankDto dto = new ServiceRankDto();
        dto.setServiceRankCode(entity.getServiceRankCode());
        dto.setServiceRankName(entity.getServiceRankName());
        dto.setServicePointIncidence(entity.getServicePointIncidence());
        dto.setNewAcceptableFlg(entity.getNewAcceptableFlg());
        dto.setDescription(entity.getDescription());
        dto.setDisplayOrder(entity.getDisplayOrder());
        reflectDerivedProperty(entity, dto, true);
        if (instanceCache && entity.hasPrimaryKeyValue()) { // caches only a DTO that has a primary key value
            _relationDtoMap.put(localKey, dto);
        }
        boolean reverseReference = isReverseReference();
        if (!_suppressMemberServiceList && !entity.getMemberServiceList().isEmpty()) {
            MemberServiceDtoMapper mapper = new MemberServiceDtoMapper(_relationDtoMap, _relationEntityMap);
            mapper.setExceptCommonColumn(exceptCommonColumn);
            mapper.setReverseReference(reverseReference);
            if (!instanceCache) { mapper.disableInstanceCache(); }
            mapper.suppressServiceRank();
            List<MemberServiceDto> relationDtoList = mapper.mappingToDtoList(entity.getMemberServiceList());
            dto.setMemberServiceList(relationDtoList);
            if (reverseReference) {
                for (MemberServiceDto relationDto : relationDtoList) {
                    relationDto.setServiceRank(dto);
                }
            }
        };
        return dto;
    }

    /**
     * {@inheritDoc}
     */
    public List<ServiceRankDto> mappingToDtoList(List<ServiceRank> entityList) {
        if (entityList == null) {
            throw new IllegalArgumentException("The argument 'entityList' should not be null.");
        }
        List<ServiceRankDto> dtoList = new ArrayList<ServiceRankDto>();
        for (ServiceRank entity : entityList) {
            ServiceRankDto dto = mappingToDto(entity);
            if (dto != null) {
                dtoList.add(dto);
            } else {
                if (isAcceptNullElementOnList()) {
                    dtoList.add(null);
                }
            }
        }
        return dtoList;
    }

    // -----------------------------------------------------
    //                                             to Entity
    //                                             ---------
    /**
     * {@inheritDoc}
     */
    public ServiceRank mappingToEntity(ServiceRankDto dto) {
        if (dto == null) {
            return null;
        }
        boolean instanceCache = _instanceCache;
        Object localKey = createInstanceKeyDto(dto, dto.instanceHash());
        Entity cachedLocalEntity = instanceCache ? _relationEntityMap.get(localKey) : null;
        if (cachedLocalEntity != null) {
            return (ServiceRank)cachedLocalEntity;
        }
        boolean exceptCommonColumn = isExceptCommonColumn();
        ServiceRank entity = new ServiceRank();
        if (needsMapping(dto, dto.getServiceRankCode(), "serviceRankCode")) {
            entity.setServiceRankCodeAsServiceRank(CDef.ServiceRank.codeOf(dto.getServiceRankCode()));
        }
        if (needsMapping(dto, dto.getServiceRankName(), "serviceRankName")) {
            entity.setServiceRankName(dto.getServiceRankName());
        }
        if (needsMapping(dto, dto.getServicePointIncidence(), "servicePointIncidence")) {
            entity.setServicePointIncidence(dto.getServicePointIncidence());
        }
        if (needsMapping(dto, dto.getNewAcceptableFlg(), "newAcceptableFlg")) {
            entity.setNewAcceptableFlgAsFlg(CDef.Flg.codeOf(dto.getNewAcceptableFlg()));
        }
        if (needsMapping(dto, dto.getDescription(), "description")) {
            entity.setDescription(dto.getDescription());
        }
        if (needsMapping(dto, dto.getDisplayOrder(), "displayOrder")) {
            entity.setDisplayOrder(dto.getDisplayOrder());
        }
        reflectDerivedProperty(entity, dto, false);
        if (instanceCache && entity.hasPrimaryKeyValue()) { // caches only an entity that has a primary key value
            _relationEntityMap.put(localKey, entity);
        }
        boolean reverseReference = isReverseReference();
        if (!_suppressMemberServiceList && !dto.getMemberServiceList().isEmpty()) {
            MemberServiceDtoMapper mapper = new MemberServiceDtoMapper(_relationDtoMap, _relationEntityMap);
            mapper.setExceptCommonColumn(exceptCommonColumn);
            mapper.setReverseReference(reverseReference);
            if (!instanceCache) { mapper.disableInstanceCache(); }
            mapper.suppressServiceRank();
            List<MemberService> relationEntityList = mapper.mappingToEntityList(dto.getMemberServiceList());
            entity.setMemberServiceList(relationEntityList);
            if (reverseReference) {
                for (MemberService relationEntity : relationEntityList) {
                    relationEntity.setServiceRank(OptionalEntity.of(entity));
                }
            }
        };
        return entity;
    }

    /**
     * Does the property need to be mapped to an entity?

     * If modified info of DTO has at least one property, only modified properties are mapped.
     * And if no property is modified, all properties are mapped (but the other option exists).
     * @param dto The instance of DTO. (NotNull)
     * @param value The value of DTO's property. (NotNull)
     * @param propName The property name of DTO. (NotNull)
     * @return The determination, true or false.
     */
    protected boolean needsMapping(ServiceRankDto dto, Object value, String propName) {
        Set<String> modifiedProperties = dto.mymodifiedProperties();
        if (modifiedProperties.isEmpty()) {
            return isMappingToEntityContainsNull() || value != null;
        }
        return modifiedProperties.contains(propName);
    }

    /**
     * Does the mapping to an entity contain null values? (when no property is modified)

     * Default is true that means a setter is called if the value is null.
     * But this method is valid only when no property is modified.
     * @return The determination, true or false.
     */
    protected boolean isMappingToEntityContainsNull() { // for extension
        return true; // as default
    }

    /**
     * {@inheritDoc}
     */
    public List<ServiceRank> mappingToEntityList(List<ServiceRankDto> dtoList) {
        if (dtoList == null) {
            throw new IllegalArgumentException("The argument 'dtoList' should not be null.");
        }
        List<ServiceRank> entityList = new ArrayList<ServiceRank>();
        for (ServiceRankDto dto : dtoList) {
            ServiceRank entity = mappingToEntity(dto);
            if (entity != null) {
                entityList.add(entity);
            } else {
                if (isAcceptNullElementOnList()) {
                    entityList.add(null);
                }
            }
        }
        return entityList;
    }

    protected boolean isAcceptNullElementOnList() {
        return true; // as default
    }

    // -----------------------------------------------------
    //                                          Instance Key
    //                                          ------------
    protected Object createInstanceKeyDto(final Object dto, final int instanceHash) {
        return new InstanceKeyDto(dto, instanceHash);
    }

    protected InstanceKeyEntity createInstanceKeyEntity(Entity entity) {
        return new InstanceKeyEntity(entity);
    }

    public void disableInstanceCache() { // internal option
        _instanceCache = false;
    }

    // -----------------------------------------------------
    //                                      Derived Property
    //                                      ----------------
    protected void reflectDerivedProperty(Entity entity, Object dto, boolean toDto) {
        DfBeanDesc entityDesc = DfBeanDescFactory.getBeanDesc(entity.getClass());
        DfBeanDesc dtoDesc = DfBeanDescFactory.getBeanDesc(dto.getClass());
        DBMeta dbmeta = entity.asDBMeta();
        for (String propertyName : entityDesc.getProppertyNameList()) {
            if (isOutOfDerivedPropertyName(entity, dto, toDto, dbmeta, entityDesc, dtoDesc, propertyName)) {
                continue;
            }
            DfPropertyDesc entityProp = entityDesc.getPropertyDesc(propertyName);
            Class<?> propertyType = entityProp.getPropertyType();
            if (isOutOfDerivedPropertyType(entity, dto, toDto, propertyName, propertyType)) {
                continue;
            }
            if (entityProp.isReadable() && entityProp.isWritable()) {
                DfPropertyDesc dtoProp = dtoDesc.getPropertyDesc(propertyName);
                if (dtoProp.isReadable() && dtoProp.isWritable()) {
                    if (toDto) {
                        dtoProp.setValue(dto, entityProp.getValue(entity));
                    } else {
                        entityProp.setValue(entity, dtoProp.getValue(dto));
                    }
                }
            }
        }
    }

    protected boolean isOutOfDerivedPropertyName(Entity entity, Object dto, boolean toDto
                                               , DBMeta dbmeta, DfBeanDesc entityDesc, DfBeanDesc dtoDesc
                                               , String propertyName) {
        return dbmeta.hasColumn(propertyName)
                    || dbmeta.hasForeign(propertyName) || dbmeta.hasReferrer(propertyName)
                    || !dtoDesc.hasPropertyDesc(propertyName);
    }

    protected boolean isOutOfDerivedPropertyType(Entity entity, Object dto, boolean toDto
                                               , String propertyName, Class<?> propertyType) {
        return List.class.isAssignableFrom(propertyType)
                || Entity.class.isAssignableFrom(propertyType)
                || Classification.class.isAssignableFrom(propertyType);
    }

    // ===================================================================================
    //                                                                   Suppress Relation
    //                                                                   =================
    // (basically) to suppress infinity loop
    public void suppressMemberServiceList() {
        _suppressMemberServiceList = true;
    }
    protected void doSuppressAll() { // internal
        suppressMemberServiceList();
    }
    protected void doSuppressClear() { // internal
        _suppressMemberServiceList = false;
    }

    // ===================================================================================
    //                                                                      Mapping Option
    //                                                                      ==============
    /**
     * {@inheritDoc}
     */
    public void setBaseOnlyMapping(boolean baseOnlyMapping) {
        if (baseOnlyMapping) {
            doSuppressAll();
        } else {
            doSuppressClear();
        }
    }

    protected boolean isExceptCommonColumn() {
        return _exceptCommonColumn;
    }

    /**
     * {@inheritDoc}
     */
    public void setExceptCommonColumn(boolean exceptCommonColumn) {
        _exceptCommonColumn = exceptCommonColumn;
    }

    protected boolean isReverseReference() {
        return _reverseReference;
    }

    /**
     * {@inheritDoc}
     */
    public void setReverseReference(boolean reverseReference) {
        _reverseReference = reverseReference;
    }

    // -----------------------------------------------------
    //                                           Easy-to-Use
    //                                           -----------
    /**
     * Enable base-only mapping that means the mapping ignores all references.
     * @return this. (NotNull)
     */
    public ServiceRankDtoMapper baseOnlyMapping() {
        setBaseOnlyMapping(true);
        return (ServiceRankDtoMapper)this;
    }

    /**
     * Enable except common column that means the mapping excepts common column.
     * @return this. (NotNull)
     */
    public ServiceRankDtoMapper exceptCommonColumn() {
        setExceptCommonColumn(true);
        return (ServiceRankDtoMapper)this;
    }

    /**
     * Enable reverse reference that means the mapping contains reverse references.
     * @return this. (NotNull)
     */
    public ServiceRankDtoMapper reverseReference() {
        setReverseReference(true);
        return (ServiceRankDtoMapper)this;
    }
}


text:
[![Build Status](https://travis-ci.org/ericfabreu/WearFlashcards.svg?branch=master)](https://travis-ci.org/ericfabreu/WearFlashcards)

Flashcards for Android Wear (available on the [Play Store](https://play.google.com/store/apps/details?id=com.ericfabreu.wearflashcards))

## Requirements
* Java JDK 1.8+
* Android SDK 26+
* Android Studio

## Acknowledgements
* In-app icons from Google's [material design guidelines](https://design.google.com/icons/) / CC BY 4.0
* Vertical View Pager from [Brett's answer](http://stackoverflow.com/a/22797619/3522216) / CC BY-SA 3.0

## License
* [MIT](https://github.com/ericfabreu/WearFlashcards/blob/master/LICENSE)


text:
@ECHO OFF
rake %*
IF %ERRORLEVEL%==9009 GOTO:rake_failed
GOTO:EOF

:rake_failed type Ruby_Not_Installed.txt
GOTO :EOF


text:
add_external_project_or_use_system(boost
  BUILD_IN_SOURCE 1
  CONFIGURE_COMMAND
    <SOURCE_DIR>/bootstrap.sh --prefix=<INSTALL_DIR>
                              --with-libraries=date_time,thread,regex,system,program_options,filesystem,iostreams
  BUILD_COMMAND <SOURCE_DIR>/bjam address-model=64 threading=multi
  INSTALL_COMMAND <SOURCE_DIR>/bjam  address-model=64 threading=multi --prefix=<INSTALL_DIR> install
)


text:
<?php namespace Peakfijn\GetSomeRest\Http;

use Peakfijn\GetSomeRest\Http\Response;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;

class Pagination {

	/**
	 * The total amount of objects.
	 *
	 * @var int
	 */
	protected $count  = 0;

	/**
	 * The maximum amount of objects within the response.
	 *
	 * @var int
	 */
	protected $limit  = 0;

	/**
	 * The amount of objects skipped.
	 *
	 * @var int
	 */
	protected $offset = 0;

	/**
	 * Create a new Pagination object that describes the "Pagination" info.
	 * Such as count and the current offset.
	 *
	 * @param int $count
	 * @param int $limit
	 * @param int $offset
	 */
	public function __construct( $count = 0, $limit = 0, $offset = 0 )
	{
		$this->count  = $count;
		$this->limit  = $limit;
		$this->offset = $offset;
	}

	/**
	 * Get the total amount of objects.
	 *
	 * @return int
	 */
	public function getCount()
	{
		return $this->count;
	}

	/**
	 * Get the maximum amount of objects within the response.
	 *
	 * @return int
	 */
	public function getLimit()
	{
		return $this->limit;
	}

	/**
	 * Get the amount of objects skipped.
	 *
	 * @return int
	 */
	public function getOffset()
	{
		return $this->offset;
	}

	/**
	 * Create a response WITH pagination data!
	 *
	 * @param  mixed $data
	 * @param  mixed $count
	 * @param  mixed $limit
	 * @param  mixed $offset
	 * @return \Peakfijn\GetSomeRest\Http\Response
	 */
	public static function make( $data, $count = 0, $limit = 0, $offset = 0 )
	{
		return static::makeFromResponse(new Response($data), $count, $limit, $offset);
	}

	/**
	 * Create a response WITH pagination data from an existing response
	 *
	 * @param  \Symfony\Component\HttpFoundation\Response $response
	 * @param  mixed $count
	 * @param  mixed $limit
	 * @param  mixed $offset
	 * @return \Peakfijn\GetSomeRest\Http\Response
	 */
	public static function makeFromResponse( SymfonyResponse $response, $count = 0, $limit = 0, $offset = 0 )
	{
		$response = Response::makeFromExisting($response);
		$response->setPagination(new static($count, $limit, $offset));

		return $response;
	}

}


text:
@interface VTDUpcomingDisplayData()
@property (nonatomic, copy) NSArray*    sections;
@end

@implementation VTDUpcomingDisplayData

+ (instancetype)upcomingDisplayDataWithSections:(NSArray *)sections
{
    VTDUpcomingDisplayData* data = [[VTDUpcomingDisplayData alloc] init];

    data.sections = sections;

    return data;
}

- (BOOL)isEqualToUpcomingDisplayData:(VTDUpcomingDisplayData *)data
{
    if (!data)
    {
        return NO;
    }

    BOOL hasEqualSections = [self.sections isEqualToArray:data.sections];

    return hasEqualSections;
}

- (BOOL)isEqual:(id)object
{
    if (self == object)
    {
        return YES;
    }

    if (![object isKindOfClass:[VTDUpcomingDisplayData class]])
    {
        return NO;
    }

    return [self isEqualToUpcomingDisplayData:object];
}

- (NSUInteger)hash
{
    return [self.sections hash];
}

@end


text:
//
//  RFCycleBaseView.m
//  RFCycleView
//
//  Created by DuRofei on 16/9/23.
//  Copyright © 2016年 DuRofei. All rights reserved.
//

#import "RFCycleBaseView.h"

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
//#import <AFNetworking/AFNetworking.h>
//#import "UIImageView+WebCache.h"
//#import "SDWebImageManager.h"
#import "FirstViewController.h"
@interface RFCycleBaseView ()<UIScrollViewDelegate>

//scrollView
@property (nonatomic, strong) UIScrollView    *imgScrollView;
//pageControl
@property (nonatomic, strong) UIPageControl   *imgPageControl;
//ImageViewArray
@property (nonatomic, strong) NSMutableArray  *imgViewArray;
//存放图片的array
@property (nonatomic, strong) NSMutableArray  *imgArray;
//当前展示的图片下标
@property (nonatomic, assign) NSInteger        index;
//timer
@property (nonatomic, strong) NSTimer         *imgTimer;
//点击回调 block
@property (nonatomic, copy)   void(^tapBlock)(RFCycleViewModel *model);
//参数传过来的url
@property (nonatomic, strong) NSString        *urlString;
//请求下来的轮播图片数组
@property (nonatomic, strong) UIButton        *closeButton;
//轮播图时间间隔
@property (nonatomic, assign) NSTimeInterval   interval;
//数据源数组
@property (nonatomic, strong) NSMutableArray *cycleViewArray;
//缓存的数据源数组
@property (nonatomic, strong) NSMutableArray *CachesCycleViewArray;
//数据源模型
@property (nonatomic, strong) RFCycleViewModel *model;
//图片url数组
@property (nonatomic, strong) NSMutableArray *imgUrlArray;
//存储图片名的数组
@property (nonatomic, strong) NSMutableArray *imgNameArray;
//判断轮播图内容是否已经更新
@property (nonatomic, assign) BOOL isUpdate;
@end

@implementation RFCycleBaseView

//判断某个数据是否已经更新

- (void)analysisCachesData{
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *fileDir = [cachesPath stringByAppendingPathComponent:@"cycleFile.txt"];
    NSData *data = [NSData dataWithContentsOfFile:fileDir];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSArray *dataArray = dic[@"data"];
    RFCycleViewModel *model = [[RFCycleViewModel alloc]init];
    for (NSDictionary *imageUrlDic in dataArray) {
        [model setValuesForKeysWithDictionary:imageUrlDic];
        [self.cycleViewArray addObject:model];
    }
}

//- (void)requestCycleImageData{
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [manager GET:_urlString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//        NSLog(@"显示当前进程");
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//        NSArray *dataArray = dic[@"data"];
//        RFCycleViewModel *model = [[RFCycleViewModel alloc]init];
//        for (NSDictionary *imageUrlDic in dataArray) {
//            NSString *cid = imageUrlDic[@"cid"];
//            if (cid == model.cid) {
//                self.isUpdate = NO;
//            }else{
//                self.isUpdate = YES;
//                [model setValuesForKeysWithDictionary:imageUrlDic];
//                [self.cycleViewArray addObject:model];
//            }
//        }
//        NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
//        NSString *fileDir = [cachesPath stringByAppendingPathComponent:@"cycleFile.txt"];
//        NSFileManager *manager = [[NSFileManager alloc]init];
//        [manager createFileAtPath:fileDir contents:responseObject attributes:nil];
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [self analysisCachesData];
//    }];
//}

@end


text:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

###############################################################################
# Copyright (c) 2010,2011 Vadim Shlyakhov
#
#  Permission is hereby granted, free of charge, to any person obtaining a
#  copy of this software and associated documentation files (the "Software"),
#  to deal in the Software without restriction, including without limitation
#  the rights to use, copy, modify, merge, publish, distribute, sublicense,
#  and/or sell copies of the Software, and to permit persons to whom the
#  Software is furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included
#  in all copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
#  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
#  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
#  DEALINGS IN THE SOFTWARE.
###############################################################################

import sys
import os
import os.path
import glob
import shutil
import logging
import optparse

from tiler_functions import *

ext_map=(
    ('\x89PNG\x0D\x0A\x1A\x0A','.png'),
    ('GIF89a','.gif'),
    ('GIF87a','.gif'),
    ('\xFF\xD8\xFF\xE0','.jpg'),
    )

def ext_from_buffer(buf):
    for magic,ext in ext_map:
        if buf.startswith(magic):
            return ext
    raise Exception('Cannot determing image type in a buffer')

def ext_from_file(path):
    with file(path, "r") as f:
        buf = f.read(512)
        return ext_from_buffer(buf)

class Tile(object):
    def __init__(self,coord):
        self._coord=coord

    def coord(self):
        return self._coord

class FileTile(Tile):
    def __init__(self,coord,path):
        super(FileTile, self).__init__(coord)
        self.path=path

    def data(self):
        return open(self.path,'rb').read()

    def get_ext(self):
        return os.path.splitext(self.path)[1]

    def copy2file(self,dst_path,tile_ext=None,link=False):
        # dest_path is w/o extension!
        if not tile_ext:
            tile_ext=self.get_ext()
        dst=dst_path+tile_ext
        if link and os.name == 'posix':
            dst_dir=os.path.split(dst)[0]
            src=os.path.relpath(self.path,dst_dir)
            os.symlink(src,dst)
        else:
            shutil.copy(self.path,dst)

class FileTileNoExt(FileTile):
    def get_ext(self):
        return ext_from_file(self.path)

class PixBufTile(Tile):
    def __init__(self,coord,pixbuf,key):
        super(PixBufTile, self).__init__(coord)
        self.pixbuf=pixbuf
        self.path=repr(key) # only for debugging

    def data(self):
        return self.pixbuf

    def get_ext(self):
        ext=ext_from_buffer(self.pixbuf)
        return ext

    def copy2file(self,dest_path,tile_ext=None,link=False):
        # dest_path is w/o extension!
        if not tile_ext:
            tile_ext=self.get_ext()
        open(dest_path+tile_ext,'wb').write(self.pixbuf)

class TileSet(object):
    def __init__(self,root,options=None,write=False):
        ld(root)
        self.root=root
        self.write=write
        self.options=options
        self.pyramid=None

        if not self.write:
            assert os.path.exists(root), "No file or directory found: %s" % root
        else:
            if not self.options.append and os.path.exists(self.root):
                if os.path.isdir(self.root):
                    shutil.rmtree(self.root,ignore_errors=True)
                else:
                    os.remove(self.root)
            if self.options.region:
                from gdal_tiler import Pyramid
                self.pyramid=Pyramid.profile_class('zxy')()
                self.pyramid.load_region(self.options.region)
                self.pyramid.set_zoom_range(self.options.zoom)

        self.child_init()

    def child_init(self):
        pass

    def __del__(self):
        ld(self.count)

    def load_from(self,src_tiles):
        ld((src_tiles.root, self.root))
        list(map(self.process_tile,src_tiles))

    def process_tile(self, tile):
        if self.pyramid and not self.pyramid.belongs_to(tile.coord()):
            return
        self.store_tile(tile)

    count=0
    tick_rate=100
    def counter(self):
        self.count+=1
        if self.count % self.tick_rate == 0:
            pf('.',end='')
            return True
        else:
            return False

# TileSet

class TileDir(TileSet):
    forced_ext = None
    tile_class = FileTile

    def child_init(self):
        if self.write:
            try:
                os.makedirs(self.root)
            except os.error: pass

    def __iter__(self):
        for f in glob.iglob(os.path.join(self.root,self.dir_pattern)):
            self.counter()
            yield self.tile_class(self.path2coord(f),f)

    def path2coord(self,tile_path):
        raise Exception("Unimplemented!")

    def coord2path(self,z,x,y):
        raise Exception("Unimplemented!")

    def store_tile(self, tile):
        # dest_path is w/o extension!
        dest_path=os.path.join(self.root,self.coord2path(*tile.coord()))
        ld('%s -> %s' % (tile.path,dest_path))
        try:
            os.makedirs(os.path.split(dest_path)[0])
        except os.error: pass
        tile.copy2file(dest_path,self.forced_ext,self.options.link)
        self.counter()
# TileDir

class TMStiles(TileDir): # see TileMap Diagram at http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification
    'TMS tiles'
    format,ext,input,output='tms','.tms',True,True
    dir_pattern='[0-9]*/*/*.*'

    def path2coord(self,tile_path):
        z,x,y=list(map(int,path2list(tile_path)[-4:-1]))
        return (z,x,2**z-y-1)

    def coord2path(self,z,x,y):
        return '%d/%d/%d' % (z,x,2**z-y-1)

class ZXYtiles(TileDir): # http://code.google.com/apis/maps/documentation/javascript/v2/overlays.html#Google_Maps_Coordinates
    'Popular ZXY aka XYZ format (Google Maps, OSM, mappero-compatible)'
    format,ext,input,output='zxy','.zxy',True,True
    dir_pattern='[0-9]*/*/*.*'

    def path2coord(self,tile_path):
        return list(map(int,path2list(tile_path)[-4:-1]))

    def coord2path(self,z,x,y):
        return '%d/%d/%d' % (z,x,y)

class MapNav(TileDir): # http://mapnav.spb.ru/site/e107_plugins/forum/forum_viewtopic.php?29047.post
    'MapNav (Global Mapper - compatible)'
    format,ext,input,output='mapnav','.mapnav',True,True
    dir_pattern='Z[0-9]*/*/*.pic'
    forced_ext = '.pic'
    tile_class = FileTileNoExt

    def path2coord(self,tile_path):
        z,y,x=path2list(tile_path)[-4:-1]
        return list(map(int,(z[1:],x,y)))

    def coord2path(self,z,x,y):
        return 'Z%d/%d/%d' % (z,y,x)

class SASPlanet(TileDir): # http://sasgis.ru/forum/viewtopic.php?f=2&t=24
    'SASPlanet cache'
    format,ext,input,output='sasplanet','.sasplanet',True,True
    dir_pattern='z[0-9]*/*/x[0-9]*/*/y[0-9]*.*'

    def path2coord(self,tile_path):
        z,dx,x,dy,y=path2list(tile_path)[-6:-1]
        z,x,y=list(map(int,(z[1:],x[1:],y[1:])))
        return (z-1,x,y)

    def coord2path(self,z,x,y):
        return 'z%d/%d/x%d/%d/y%d' % (z+1, x//1024, x, y//1024, y)

class SASGoogle(TileDir):
    'SASPlanet google maps cache'
    format,ext,input,output='sasgoogle','.sasgoogle',True,True
    dir_pattern='z[0-9]*/*/*.*'

    def path2coord(self,tile_path):
        z,y,x=path2list(tile_path)[-4:-1]
        return list(map(int,(z[1:],x,y)))

    def coord2path(self,z,x,y):
        return 'z%d/%d/%d' % (z,x,y)

class MapperSQLite(TileSet):
    'maemo-mapper SQLite cache'
    format,ext,input,output='sqlite','.db',True,True
    max_zoom=20

    def child_init(self):
        import sqlite3

        self.db=sqlite3.connect(self.root)
        self.dbc = self.db.cursor()
        if self.write:
            try:
                self.dbc.execute ('''
                    create table maps (
                        zoom integer,
                        tilex integer,
                        tiley integer,
                        pixbuf blob,
                        primary key (zoom, tilex, tiley));
                    ''')
            except:
                pass

    def __del__(self):
        self.db.commit()
        self.db.close()
        TileSet.__del__(self)

    def __iter__(self):
        self.dbc.execute('select * from maps')
        for z,x,y,pixbuf in self.dbc:
            self.counter()
            yield PixBufTile((self.max_zoom+1-z,x,y),str(pixbuf),(z,x,y))

    def store_tile(self, tile):
        z,x,y=tile.coord()
        # convert to maemo-mapper coords
        z=self.max_zoom+1-z
        ld('%s -> SQLite %d,%d,%d' % (tile.path, z, x, y))
        self.dbc.execute('insert or replace into maps (zoom,tilex,tiley,pixbuf) values (?,?,?,?);',
            (z,x,y,buffer(tile.data())))
        self.counter()
# MapperSQLite

class MapperGDBM(TileSet): # due to GDBM weirdness on ARM this only works if run on the tablet itself
    'maemo-mapper GDBM cache (works only on Nokia tablet)'
    format,ext,input,output='gdbm','.gdbm',True,True
    max_zoom=20

    def child_init(self):
        import platform
        assert platform.machine().startswith('arm'), 'This convertion works only on a Nokia tablet'
        import dbm.gnu
        import struct

        self.pack=struct.pack
        self.unpack=struct.unpack
        print(self.root)
        self.db=dbm.gnu.open(self.root, 'cf' if write else 'r')

    def __del__(self):
        self.db.sync()
        self.db.close()
        TileSet.__del__(self)

    def __iter__(self):
        key=self.db.firstkey()
        while key:
            z,x,y=self.unpack('>III',key)
            self.counter()
            yield PixBufTile((self.max_zoom+1-z,x,y),self.db[key],(z,x,y))
            key=self.db.nextkey(key)

    def store_tile(self, tile):
        z,x,y=tile.coord()
        # convert to maemo-mapper coords
        z=self.max_zoom+1-z
        ld('%s -> GDBM %d,%d,%d' % (tile.path, z, x, y))
        key=self.pack('>III',z,x,y)
        self.db[key]=tile.data()
        self.counter()
# MapperGDBM

tile_formats=(
    TMStiles,
    MapperSQLite,
    MapperGDBM,
    ZXYtiles,
    MapNav,
    SASPlanet,
    SASGoogle,
    )

def list_formats():
    for cl in tile_formats:
        print('%10s\t%s%s\t%s' % (
            cl.format,
            'r' if cl.input else ' ',
            'w' if cl.output else ' ',
            cl.__doc__
            ))

def tiles_convert(src_lst,options):
    for in_class in tile_formats:
        if in_class.input and options.in_fmt == in_class.format:
            break
    else:
        raise Exception("Invalid input format: %s" % options.in_fmt)
    for out_class in tile_formats:
        if out_class.output and options.out_fmt == out_class.format:
            break
    else:
        raise Exception("Invalid output format: %s" % options.out_fmt)

    for src in src_lst:
        dest=os.path.join(options.dst_dir,os.path.splitext(src)[0]+out_class.ext)
        pf('%s -> %s ' % (src,dest),end='')
        out_class(dest,options,write=True).load_from(in_class(src))
        pf('')

if __name__=='__main__':
    parser = optparse.OptionParser(
        usage="usage: %prog  <source> [<target>]",
        version=version,
        description="copies map tiles from one structure to another")
    parser.add_option("--from", dest="in_fmt", default='zxy',
        help='input tiles format (default: zxy)')
    parser.add_option("--to", dest="out_fmt", default='sqlite',
        help='output tiles format (default: sqlite)')
    parser.add_option("--formats", action="store_true", dest="list_formats",
        help='list available formats')
    parser.add_option("-a", "--append", action="store_true", dest="append",
        help="don't delete destination, append to it")
    parser.add_option("-t", "--dest-dir", default='.', dest="dst_dir",
        help='destination directory (default: current)')
    parser.add_option("-l", "--link", action="store_true", dest="link",
        help='make links to source tiles instead of copying if possible')
    parser.add_option("--region", default=None, metavar="DATASOURCE",
        help='region to process (OGR shape)')
    parser.add_option("-z", "--zoom", default=None,metavar="ZOOM_LIST",
        help='list of zoom ranges to process')
    parser.add_option("-d", "--debug", action="store_true", dest="debug")
    parser.add_option("-q", "--quiet", action="store_true", dest="quiet")

    (options, args) = parser.parse_args()
    logging.basicConfig(level=logging.DEBUG if options.debug else
        (logging.ERROR if options.quiet else logging.INFO))
    ld(options)

    if options.list_formats:
        list_formats()
        sys.exit(0)

    src_lst=args

    tiles_convert(src_lst,options)


text:
namespace gView.Framework.UI.Dialogs
{
    partial class ExplorerDialog
    {
        /// <summary>
        /// Erforderliche Designervariable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Verwendete Ressourcen bereinigen.
        /// </summary>
        /// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Vom Windows Form-Designer generierter Code

        /// <summary>
        /// Erforderliche Methode für die Designerunterstützung.
        /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ExplorerDialog));
            this.btnOK = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            this.explorerDialogControl1 = new gView.Framework.UI.Controls.ExplorerDialogControl();
            this.SuspendLayout();
            //
            // btnOK
            //
            this.btnOK.AccessibleDescription = null;
            this.btnOK.AccessibleName = null;
            resources.ApplyResources(this.btnOK, "btnOK");
            this.btnOK.BackgroundImage = null;
            this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.btnOK.Font = null;
            this.btnOK.Name = "btnOK";
            this.btnOK.UseVisualStyleBackColor = true;
            //
            // btnCancel
            //
            this.btnCancel.AccessibleDescription = null;
            this.btnCancel.AccessibleName = null;
            resources.ApplyResources(this.btnCancel, "btnCancel");
            this.btnCancel.BackgroundImage = null;
            this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.btnCancel.Font = null;
            this.btnCancel.Name = "btnCancel";
            this.btnCancel.UseVisualStyleBackColor = true;
            //
            // explorerDialogControl1
            //
            this.explorerDialogControl1.AccessibleDescription = null;
            this.explorerDialogControl1.AccessibleName = null;
            resources.ApplyResources(this.explorerDialogControl1, "explorerDialogControl1");
            this.explorerDialogControl1.BackgroundImage = null;
            this.explorerDialogControl1.Filters = null;
            this.explorerDialogControl1.Font = null;
            this.explorerDialogControl1.IsOpenDialog = true;
            this.explorerDialogControl1.MultiSelection = true;
            this.explorerDialogControl1.Name = "explorerDialogControl1";
            //
            // ExplorerDialog
            //
            this.AccessibleDescription = null;
            this.AccessibleName = null;
            resources.ApplyResources(this, "$this");
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackgroundImage = null;
            this.Controls.Add(this.btnOK);
            this.Controls.Add(this.btnCancel);
            this.Controls.Add(this.explorerDialogControl1);
            this.Font = null;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Icon = null;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "ExplorerDialog";
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.ResumeLayout(false);

        }

        #endregion

        private gView.Framework.UI.Controls.ExplorerDialogControl explorerDialogControl1;
        private System.Windows.Forms.Button btnCancel;
        private System.Windows.Forms.Button btnOK;
    }
}


text:
layout: post
title: For Friday, 22
modified:
categories: blog
excerpt:
tags: []
image:
  feature:
  teaser:
  thumb:
date: 2016-04-20T16:58:44-04:00
---

Hi everyone! For Friday, I'd like you to harmonize a melody containing accented non-chord tones. You can find the melody [here](https://www.dropbox.com/s/fr9c4litdut5s18/Accented%20NCT%20harmonization%201.pdf?dl=0). Due Friday.


text:
module Et1
  module Test
    module JsonObjects
      module V2
        # Represents the JSON attributes for an array of claimants
        class ClaimantsJsonObject < Base

          def has_valid_json_for_models?(example_claimants, errors: [], indent: 1)
            example_claimants.each_with_index do |claimant, idx|
              ClaimantJsonObject.new(json[idx]).has_valid_json_for_model?(claimant)
            end
            errors.empty?
          end
        end
      end
    end
  end
end


text:
#ifndef MAIN_H
#define MAIN_H

__syscall void dump_my_ptables(void);

#include <syscalls/main.h>

#endif


text:
require 'test_helper'

class PendencyTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
package io.github.devbhuwan.microservices.nutshell.order.usecases;

import io.github.devbhuwan.microservices.nutshell.order.commands.ImmutableOrderCommand;
import io.github.devbhuwan.microservices.nutshell.order.contracts.OrderCommandService;
import io.github.devbhuwan.microservices.nutshell.order.domain.Order;
import io.github.devbhuwan.microservices.nutshell.order.domain.OrderState;
import lombok.Setter;

/**
 * @author Bhuwan Upadhyay
 * @date 2017/05/19
 */
public class CreateNewOrderUseCase {

    @Setter
    private OrderCommandService orderCommandService;

    public void createNewOrder(Order order) {
        order.setState(OrderState.CREATED.name());
        orderCommandService.add(ImmutableOrderCommand
                .builder()
                .order(order).build());
    }
}


text:
package ch.ralscha.extdirectspring.provider;

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

import ch.ralscha.extdirectspring.annotation.ExtDirectMethod;

@ExtDirectMethod
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface SimpleEdsMethod {
	// nothing here
}


text:
namespace search
{
// GeometryCache -----------------------------------------------------------------------------------
GeometryCache::GeometryCache(size_t maxNumEntries, base::Cancellable const & cancellable)
  : m_maxNumEntries(maxNumEntries), m_cancellable(cancellable)
{
  CHECK_GREATER(m_maxNumEntries, 0, ());
}

void GeometryCache::InitEntry(MwmContext const & context, m2::RectD const & rect, int scale,
                              Entry & entry)
{
  Retrieval retrieval(context, m_cancellable);

  entry.m_rect = rect;
  entry.m_cbv = retrieval.RetrieveGeometryFeatures(rect, scale);
  entry.m_scale = scale;
}

// PivotRectsCache ---------------------------------------------------------------------------------
PivotRectsCache::PivotRectsCache(size_t maxNumEntries, base::Cancellable const & cancellable,
                                 double maxRadiusMeters)
  : GeometryCache(maxNumEntries, cancellable), m_maxRadiusMeters(maxRadiusMeters)
{
}

CBV PivotRectsCache::Get(MwmContext const & context, m2::RectD const & rect, int scale)
{
  auto p = FindOrCreateEntry(
      context.GetId(), [&rect, &scale](Entry const & entry)
      {
        return scale == entry.m_scale &&
               (entry.m_rect.IsRectInside(rect) || IsEqualMercator(rect, entry.m_rect, kMwmPointAccuracy));
      });
  auto & entry = p.first;
  if (p.second)
  {
    m2::RectD normRect = mercator::RectByCenterXYAndSizeInMeters(rect.Center(), m_maxRadiusMeters);
    if (!normRect.IsRectInside(rect))
      normRect = rect;
    InitEntry(context, normRect, scale, entry);
  }
  return entry.m_cbv;
}

// LocalityRectsCache ------------------------------------------------------------------------------
LocalityRectsCache::LocalityRectsCache(size_t maxNumEntries,
                                       base::Cancellable const & cancellable)
  : GeometryCache(maxNumEntries, cancellable)
{
}

CBV LocalityRectsCache::Get(MwmContext const & context, m2::RectD const & rect, int scale)
{
  auto p = FindOrCreateEntry(context.GetId(), [&rect, &scale](Entry const & entry)
                             {
                               return scale == entry.m_scale &&
                                      IsEqualMercator(rect, entry.m_rect, kMwmPointAccuracy);
                             });
  auto & entry = p.first;
  if (p.second)
    InitEntry(context, rect, scale, entry);
  return entry.m_cbv;
}
}  // namespace search


text:
var firebase = require('firebase');
var root = "https://refuge.firebaseio.com/";

var urls = {
    root : root,
    water : root + "water/",
    food : root + "food/",
    shelter : root + "shelter/",
    volunteers : root + "volunteers/",
    data : root+"data/"
};

var utils = {
    urls : urls,
};

module.exports=utils;


text:
#import "RCTNavItemManager.h"

#import "RCTConvert.h"
#import "RCTNavItem.h"

@implementation RCTNavItemManager

RCT_EXPORT_MODULE()

- (UIView *)view
{
  return [RCTNavItem new];
}

RCT_EXPORT_VIEW_PROPERTY(navigationBarHidden, BOOL)
RCT_EXPORT_VIEW_PROPERTY(navigationBarTransparent, BOOL)

RCT_EXPORT_VIEW_PROPERTY(shadowHidden, BOOL)
RCT_EXPORT_VIEW_PROPERTY(tintColor, UIColor)
RCT_EXPORT_VIEW_PROPERTY(barTintColor, UIColor)
RCT_EXPORT_VIEW_PROPERTY(translucent, BOOL)

RCT_EXPORT_VIEW_PROPERTY(title, NSString)
RCT_EXPORT_VIEW_PROPERTY(titleTextColor, UIColor)
RCT_EXPORT_VIEW_PROPERTY(titleIcon, UIImage)

RCT_EXPORT_VIEW_PROPERTY(backButtonIcon, UIImage)
RCT_EXPORT_VIEW_PROPERTY(backButtonTitle, NSString)

RCT_EXPORT_VIEW_PROPERTY(leftButtonTitle, NSString)
RCT_EXPORT_VIEW_PROPERTY(leftButtonIcon, UIImage)

RCT_EXPORT_VIEW_PROPERTY(rightButtonIcon, UIImage)
RCT_EXPORT_VIEW_PROPERTY(rightButtonTitle, NSString)

RCT_EXPORT_VIEW_PROPERTY(onNavLeftButtonTap, RCTBubblingEventBlock)
RCT_EXPORT_VIEW_PROPERTY(onNavRightButtonTap, RCTBubblingEventBlock)

@end


text:
/*  ======

    Layout - bloc-link.css
    -------------------
    part of AMORCE starter kit
        https://github.com/Sacripant/amorce
    -------------------

    Extend a link to cover full parent block

====== */

.block-link {
    position: relative;
}

.a__block-link:before {
    content: "";
    display: block;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

.block-link a:not(.a__block-link){
    position: relative;
    z-index: 2;
}


text:
<?php

/**
 * This file is a part of the bluemvc-core package.
 *
 * Read more at https://bluemvc.com/
 */

declare(strict_types=1);

namespace BlueMvc\Core;

use BlueMvc\Core\Exceptions\InvalidViewFileException;
use BlueMvc\Core\Exceptions\MissingViewRendererException;
use BlueMvc\Core\Exceptions\ViewFileNotFoundException;
use BlueMvc\Core\Interfaces\ApplicationInterface;
use BlueMvc\Core\Interfaces\Collections\ViewItemCollectionInterface;
use BlueMvc\Core\Interfaces\RequestInterface;
use BlueMvc\Core\Interfaces\ResponseInterface;
use BlueMvc\Core\Interfaces\ViewInterface;
use DataTypes\System\FilePath;

/**
 * Class representing a view.
 *
 * @since 1.0.0
 */
class View implements ViewInterface
{
    /**
     * Constructs the view.
     *
     * @since 1.0.0
     *
     * @param mixed|null  $model The model.
     * @param string|null $file  The file.
     *
     * @throws InvalidViewFileException If the file is invalid.
     */
    public function __construct(mixed $model = null, ?string $file = null)
    {
        if ($file !== null && preg_match('/[^a-zA-Z0-9._-]/', $file, $matches)) {
            throw new InvalidViewFileException('View file "' . $file . '" contains invalid character "' . $matches[0] . '".');
        }

        $this->model = $model;
        $this->file = $file;
    }

    /**
     * Returns the file.
     *
     * @since 1.0.0
     *
     * @return string|null The file.
     */
    public function getFile(): ?string
    {
        return $this->file;
    }

    /**
     * Returns the model.
     *
     * @since 1.0.0
     *
     * @return mixed The model.
     */
    public function getModel(): mixed
    {
        return $this->model;
    }

    /**
     * Updates the response.
     *
     * @since 1.0.0
     *
     * @param ApplicationInterface        $application The application.
     * @param RequestInterface            $request     The request.
     * @param ResponseInterface           $response    The response.
     * @param string                      $viewPath    The relative path to the view.
     * @param string                      $action      The action.
     * @param ViewItemCollectionInterface $viewItems   The view items.
     *
     * @throws MissingViewRendererException If no view renderer was added to the application.
     * @throws ViewFileNotFoundException    If a suitable view file could not be found.
     */
    public function updateResponse(ApplicationInterface $application, RequestInterface $request, ResponseInterface $response, string $viewPath, string $action, ViewItemCollectionInterface $viewItems): void
    {
        $viewRenderers = $application->getViewRenderers();
        if (count($viewRenderers) === 0) {
            throw new MissingViewRendererException('No view renderer was added to application.');
        }

        $viewPathsToCheck = $application->getViewPaths();

        // Try the view renderers until a match is found.
        $testedViewFiles = [];

        foreach ($viewRenderers as $viewRenderer) {
            foreach ($viewPathsToCheck as $viewPathToCheck) {
                $viewFile = FilePath::parse($viewPath . DIRECTORY_SEPARATOR . ($this->getFile() ?: $action) . '.' . $viewRenderer->getViewFileExtension());
                $fullViewFile = $viewPathToCheck->withFilePath($viewFile);

                if (file_exists($fullViewFile->__toString())) {
                    $response->setContent($viewRenderer->renderView($application, $request, $viewFile, $this->getModel(), $viewItems));

                    return;
                }

                $testedViewFiles[] = '"' . $fullViewFile->__toString() . '"';
            }
        }

        throw new ViewFileNotFoundException('Could not find view file ' . implode(' or ', $testedViewFiles));
    }

    /**
     * @var mixed The model.
     */
    private mixed $model;

    /**
     * @var string|null The file.
     */
    private ?string $file;
}


text:
  Azerailles est
       un village
       situé dans le département de Meurthe-et-Moselle en Lorraine. On dénombrait 833 habitants en 2008.

À Azerailles, le prix moyen à la vente d'un appartement se situe à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 015 € du m². À la location la valorisation moyenne se situe à 0 € du m² mensuel.

La commune propose quelques  équipements sportifs, elle dispose, entre autres, de un terrain de tennis, un terrain de sport et un équipement de roller/skate.

Si vous pensez emmenager à Azerailles, vous pourrez facilement trouver une maison à acheter.

Le parc de logements, à Azerailles, était réparti en 2011 en 67 appartements et 337 maisons soit
 un marché plutôt équilibré.

À coté de Azerailles sont positionnées géographiquement les villes de
Vathiménil localisée à 5 km, 306 habitants,
Gélacourt localisée à 2 km, 157 habitants,
Vaxainville localisée à 5 km, 81 habitants,
Baccarat à 5 km, 4 671 habitants,
Hablainville localisée à 4 km, 199 habitants,
Buriville localisée à 5 km, 62 habitants,
 entre autres. De plus, Azerailles est située à seulement 29 km de Saint-Dié-des-Vosges.


text:
from __future__ import division, print_function, unicode_literals
__doc__ = """
Creates a new tab with one glyph of each right group. Useful for checking the constency of right kerning groups.
"""

thisFont = Glyphs.font # frontmost font
thisFontMaster = thisFont.selectedFontMaster # active master
listOfSelectedLayers = thisFont.selectedLayers # active layers of selected glyphs

groupDict = {}

for thisGlyph in thisFont.glyphs:
	glyphName = thisGlyph.name
	rGroup = thisGlyph.rightKerningGroup
	if rGroup in groupDict.keys():
		groupDict[rGroup].append(glyphName)
	else:
		groupDict[rGroup] = [glyphName]

tabString = ""

for thisRightGroup in groupDict.keys():
	tabString += "/%s/space\n" % "/".join(groupDict[thisRightGroup])

# opens new Edit tab:
from PyObjCTools.AppHelper import callAfter
callAfter(Glyphs.currentDocument.windowController().addTabWithString_, tabString)


text:
<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Celebrate Creation</title>
    <link rel="stylesheet" href="/quickforms/css/quickforms/quickforms.css"/>

    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/custom.css"/>

Celebrate Creation

            Subscribe
            Unsubscribe

                      About

© 2014 Celebrate Creation

		Privacy Policy

                    ×

Privacy Policy

Celebrate Creation :is a not for profit, community

                    created resource for pregnant Aboriginal women. This page

                    provides you with information on our policies regarding the

                    collection and use of personal information we receive from

                    users of the site.

We will use your personal information only for

                    improving the site. By using the site, you agree to the

                    collection and use of information in accordance with this

                    policy.

Subscription Service In order to provide weekly

                    pregnancy updates, we collect your email address and

                    pregnancy due date in order to contact you.

Data Collection Like many site operators, we

                    collect information that your browser sends whenever you

                    visit our site.

This data may include information such as your

                    computer's Internet Protocol (IP) address, browser type,

                    the pages of our site that you visit, the time and date of

                    your visit, the time spent on these pages and other

                    statistics.

                    Protection Of Your Data We use industry standard physical,

                    technical and administrative security measures and

                    safeguards to protect the confidentiality and security of

                    your personal information.

However, since the Internet is not a 100% secure

                    environment, we cannot guarantee, ensure, or warrant the

                    security of any information you transmit to us.

There is no guarantee that information may not be

                    accessed, disclosed, altered or destroyed by breach of any

                    of our physical, technical or managerial

                    safeguards.

Complete Agreement Except as expressly provided in

                    a particular "legal notice" on the site, these Terms of Use

                    & Privacy Policy constitute the entire agreement between

                    you and us with respect to the use of the site and

                    content.

                    Contact

                    Celebrate Creation

                    75 Laurier Ave E, University of Ottawa

                    Ottawa, Canada K1N 6N5

                    E-mail: autoreplypregapp@gmail.com

                    © Copyright 2016 Celebrate Creation. All rights
                    reserved.


text:
import re

star_re = re.compile('(?<!\*)\*{1}(?!\*)')
fname_star_re = re.compile('\*\.([^/\.]+)$')

cache = dict()

def prepare(pattern):
    """Factory method for glob expression classes. This method should be used instead of the constructor, because it
    implements basic caching."""

    if pattern in cache:
        return cache[pattern]
    else:
        gb = GlobMatch(pattern)
        cache[pattern] = gb
        return gb

class GlobMatch:

    def __init__(self, pattern):
        m = fname_star_re.match(pattern)
        if m:
            p = '.*\.{}'.format(m.group(1))
        else:
            p = star_re.sub('[^\/]*', pattern)
            p = p.replace('.', '\.').replace('**', '.*').replace('?', '.')
            if p.find('/') < 0 or p.find('\\') < 0:
                p = '.*{}.*'.format(p)

        self.r = re.compile('^' + p + '$')
        self.p = p
        self.pattern = pattern

    def __str__(self):
        return self.pattern

    def __hash__(self):
        return hash(self.pattern)

    def __cmp__(self, other):
        if self.pattern < other.pattern:
            return -1
        elif self.pattern > other.pattern:
            return 1
        else:
            return 0

    def __eq__(self, other):
        return self.pattern == other.pattern

    def match(self, name):
        return self.r.match(name) != None


text:
require 'smartsheet/client'
require 'smartsheet/error'


text:
@extends('layouts.app')

@section('title')
Login - {{ env('APP_NAME', 'Keybeaker') }}
@endsection

@section('content')

Login

                    <form class="form-horizontal" role="form" method="POST" action="{{ url('/login') }}">
                        {{ csrf_field() }}

                            Public Key

                                <input id="key" type="text" class="form-control" name="key" maxlength="44" value="{{ isset($oldkey) ? $oldkey : '' }}" required{{ (!isset($sigerror)) ? ' autofocus' : '' }}>

                                @if (isset($keyerror))

                                        {{ $keyerror }}

                                @endif

                            Sign this message

                                {{ $nonce }}

                            Signature

                                <input id="signature" type="text" class="form-control" name="signature" maxlength="88" autocomplete="off" required {{ (isset($sigerror)) ? ' autofocus' : '' }}>

                                @if (isset($sigerror))

                                        {{ $sigerror }}

                                @endif

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

                    </form>

@endsection


text:
[![CI Status](http://img.shields.io/travis/biohazardlover/LNVTabBarController.svg?style=flat)](https://travis-ci.org/biohazardlover/LNVTabBarController)
[![Version](https://img.shields.io/cocoapods/v/LNVTabBarController.svg?style=flat)](http://cocoapods.org/pods/LNVTabBarController)
[![License](https://img.shields.io/cocoapods/l/LNVTabBarController.svg?style=flat)](http://cocoapods.org/pods/LNVTabBarController)
[![Platform](https://img.shields.io/cocoapods/p/LNVTabBarController.svg?style=flat)](http://cocoapods.org/pods/LNVTabBarController)

## Example

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

LNVTabBarController is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "LNVTabBarController"
```

## Author

biohazardlover, leon@leonandvane.date

## License

LNVTabBarController is available under the MIT license. See the LICENSE file for more info.


text:
package org.spongepowered.api.data.type;

import org.spongepowered.api.ResourceKey;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.registry.DefaultedRegistryReference;
import org.spongepowered.api.registry.Registry;
import org.spongepowered.api.registry.RegistryKey;
import org.spongepowered.api.registry.RegistryScope;
import org.spongepowered.api.registry.RegistryScopes;
import org.spongepowered.api.registry.RegistryTypes;

/**
 * An enumeration of vanilla {@link HandType}s.
 */
@SuppressWarnings("unused")
@RegistryScopes(scopes = RegistryScope.GAME)
public final class HandTypes {

    // @formatter:off

    // SORTFIELDS:ON

    /**
     * The hand used for main interactions such as using tools, and placing
     * blocks.
     */
    public static final DefaultedRegistryReference<HandType> MAIN_HAND = HandTypes.key(ResourceKey.sponge("main_hand"));

    /**
     * The hand used for secondary actions, such as a shield.
     */
    public static final DefaultedRegistryReference<HandType> OFF_HAND = HandTypes.key(ResourceKey.sponge("off_hand"));

    // SORTFIELDS:OFF

    // @formatter:on

    private HandTypes() {
    }

    public static Registry<HandType> registry() {
        return Sponge.game().registry(RegistryTypes.HAND_TYPE);
    }

    private static DefaultedRegistryReference<HandType> key(final ResourceKey location) {
        return RegistryKey.of(RegistryTypes.HAND_TYPE, location).asDefaultedReference(Sponge::game);
    }
}


text:
<?php

// Exit if accessed directly
if( !defined( 'ABSPATH' ) ) {
	exit;
}

get_header(); ?>
<?php global  $wpdb;
$user_id = get_current_user_id();
  $qry = "SELECT identifier FROM `wp_2_wslusersprofiles` WHERE user_id = '$user_id' && provider = 'Google' && identifier IS NOT NULL";
  $avalidgoogleid = $wpdb->get_results( $qry );

foreach ( $avalidgoogleid as $avalidgoogleid )
{
        $gid = $avalidgoogleid ->identifier;
                if ($gid < 100000) { echo "not a doap google account"; } else { echo " ".$gid.""; }
}
?>

<?php if (current_user_can( 'manage_options' ))  { } else { include('/var/www/html/lpmu/wp-content/themes/noticias' . '/lptv-page-wing-ads.php'); } ?>
<?php //include('/var/www/html/lpmu/wp-content/themes/noticias' . '/lptv-page-wing-ads.php'); ?>

<?php if (current_user_can( 'manage_options' ))  { echo '

doap.com

'; } else { include('/var/www/html/lpmu/wp-content/themes/noticias' . '/banner-ad-widget-270x90.php'); } ?>

<?php if (current_user_can( 'manage_options' ))  { echo '

DevOps and Platforms

'; } else { include('/var/www/html/lpmu/wp-content/themes/noticias' . '/banner-ad-widget.php'); } ?>

<?php //get_sidebar(); ?>
<?php get_footer('lptv'); ?>


text:
package io.crnk.cdi.internal;

import javax.enterprise.context.ApplicationScoped;
import javax.transaction.Transactional;
import java.util.concurrent.Callable;

@Transactional // does not seem to work on method-level
@ApplicationScoped
public class CdiTransactionRunnerImpl {

	public <T> T doInTransaction(Callable<T> callable) {
		try {
			return callable.call();
		} catch (RuntimeException e) {
			throw e;
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
	}
}


text:
using UnityEngine;
using System.Collections;

public class TeleportTile : GroundTile
{
	public TeleportTile OtherEnd;
	public Color color;
	private float time;
	private bool fadingOut;
	private Color fadeColor;
	// Use this for initialization
	void Start ()
	{
		GetComponent<MeshRenderer> ().material.color = color;
		time = 0f;
		fadingOut = false;
		fadeColor = Color.Lerp (color, Color.white, 0.5f);
	}

	// Update is called once per frame
	void Update ()
	{
		MeshRenderer mr = GetComponent<MeshRenderer> ();
		time += Time.deltaTime;
		if (fadingOut) {
			mr.material.color = Color.Lerp (color, fadeColor, time);
		} else {
			mr.material.color = Color.Lerp (fadeColor, color, time);
		}
		if(time > 1f) {
			time = 0f;
			fadingOut = !fadingOut;
			//fadeColor = GetComponent<MeshRenderer>().material.color;
		}
	}
}


text:
package refex

import (
	"strings"
)

type codeMatcher interface {
	match(code string, pattern pattern) ([]*match, error)
}

type codeMatcherImpl struct {
	code    string
	matches []*match
}

func (m *codeMatcherImpl) match(code string, pattern pattern) ([]*match, error) {
	err := m.find(code, pattern)
	if err != nil {
		return nil, err
	}

	err = m.buildParts()
	if err != nil {
		return nil, err
	}

	return m.matches, nil
}

func (m *codeMatcherImpl) find(code string, pattern pattern) error {
	m.code = code

	regexp, err := pattern.regexp()
	if err != nil {
		return err
	}

	regexMatches := regexp.FindAllStringIndex(code, -1)
	if regexMatches == nil {
		// not an error but still nothing more to do
		return nil
	}

	m.matches = make([]*match, len(regexMatches))
	for index, regexMatch := range regexMatches {
		startPos := regexMatch[0]
		endPos := regexMatch[1]

		endPos -= m.adjustForDoubleBrackets(code, startPos, endPos)
		endPos -= m.adjustForGreedy(code, startPos, endPos)

		m.matches[index] = &match{
			startPos: startPos,
			endPos:   endPos,
			pattern:  regexp.String(),
		}
	}

	return nil
}

// Adjust for cases where the params contain `()` or `(something)`
func (m *codeMatcherImpl) adjustForDoubleBrackets(code string, startPos int, endPos int) int {
	adjustment := 0

	codeMatch := code[startPos:endPos]
	if leftBrackets := strings.Count(codeMatch, "("); leftBrackets > 0 {
		lastRightBracket := strings.LastIndex(codeMatch, ")")
		if lastRightBracket > 0 {
			adjustment = (len(codeMatch) - lastRightBracket - 1)
		}
	}

	return adjustment
}

// Adjust for cases where Greedy matching matches too many closing brackets
func (m *codeMatcherImpl) adjustForGreedy(code string, startPos int, endPos int) int {
	adjustment := 0

	codeMatch := code[startPos:endPos]
	leftBrackets := strings.Count(codeMatch, "(")
	rightBrackets := strings.Count(codeMatch, ")")

	if rightBrackets > leftBrackets {
		lastRightBracket := strings.LastIndex(codeMatch, ")")
		if lastRightBracket > 0 {
			adjustment = (len(codeMatch) - lastRightBracket)
		}
	}

	return adjustment
}

func (m *codeMatcherImpl) buildParts() error {
	if len(m.matches) == 0 {
		// not an error but still nothing more to do
		return nil
	}

	lastPos := 0
	for _, match := range m.matches {
		match.parts = []*part{}

		before := m.code[lastPos:match.startPos]
		code := m.code[match.startPos:match.endPos]

		patternChunks := strings.Split(match.pattern, wildcard)

		for index, chunkRaw := range patternChunks {
			chunk := m.extractCodeFromPattern(chunkRaw)
			before += chunk
			if index == 0 {
				match.parts = append(match.parts, &part{code: before})
			}

			code = strings.TrimPrefix(code, chunk)

			nextIndex := index + 1
			if nextIndex > (len(patternChunks) - 1) {
				continue
			}

			after := m.extractCodeFromPattern(patternChunks[nextIndex])

			// grab the first occurrence or the last depending where we are in the pattern
			var loc int
			if nextIndex == (len(patternChunks) - 1) {
				loc = strings.LastIndex(code, after)
			} else {
				loc = strings.Index(code, after)
			}

			thisFragment := code[:loc]

			match.parts = append(match.parts, &part{
				code:  thisFragment,
				isArg: true,
				index: (index + 1),
			})
			match.parts = append(match.parts, &part{code: after})

			code = code[loc:]
		}

		lastPos = match.endPos
	}

	return nil
}

func (m *codeMatcherImpl) extractCodeFromPattern(chunk string) string {
	chunk = strings.TrimPrefix(chunk, patternPrefix)
	chunk = strings.TrimSuffix(chunk, patternSuffix)

	for _, thisChar := range specialChars {
		chunk = strings.Replace(chunk, `\`+thisChar, thisChar, -1)
	}
	return chunk
}


text:
#include "android-base/file.h"

#include <gtest/gtest.h>

#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

#include <string>

#include "android-base/test_utils.h"

TEST(file, ReadFileToString_ENOENT) {
  std::string s("hello");
  errno = 0;
  ASSERT_FALSE(android::base::ReadFileToString("/proc/does-not-exist", &s));
  EXPECT_EQ(ENOENT, errno);
  EXPECT_EQ("", s);  // s was cleared.
}

TEST(file, ReadFileToString_WriteStringToFile) {
  TemporaryFile tf;
  ASSERT_TRUE(tf.fd != -1);
  ASSERT_TRUE(android::base::WriteStringToFile("abc", tf.path))
    << strerror(errno);
  std::string s;
  ASSERT_TRUE(android::base::ReadFileToString(tf.path, &s))
    << strerror(errno);
  EXPECT_EQ("abc", s);
}

// WriteStringToFile2 is explicitly for setting Unix permissions, which make no
// sense on Windows.
#if !defined(_WIN32)
TEST(file, WriteStringToFile2) {
  TemporaryFile tf;
  ASSERT_TRUE(tf.fd != -1);
  ASSERT_TRUE(android::base::WriteStringToFile("abc", tf.path, 0660,
                                               getuid(), getgid()))
      << strerror(errno);
  struct stat sb;
  ASSERT_EQ(0, stat(tf.path, &sb));
  ASSERT_EQ(0660U, static_cast<unsigned int>(sb.st_mode & ~S_IFMT));
  ASSERT_EQ(getuid(), sb.st_uid);
  ASSERT_EQ(getgid(), sb.st_gid);
  std::string s;
  ASSERT_TRUE(android::base::ReadFileToString(tf.path, &s))
    << strerror(errno);
  EXPECT_EQ("abc", s);
}
#endif

TEST(file, WriteStringToFd) {
  TemporaryFile tf;
  ASSERT_TRUE(tf.fd != -1);
  ASSERT_TRUE(android::base::WriteStringToFd("abc", tf.fd));

  ASSERT_EQ(0, lseek(tf.fd, 0, SEEK_SET)) << strerror(errno);

  std::string s;
  ASSERT_TRUE(android::base::ReadFdToString(tf.fd, &s)) << strerror(errno);
  EXPECT_EQ("abc", s);
}

TEST(file, WriteFully) {
  TemporaryFile tf;
  ASSERT_TRUE(tf.fd != -1);
  ASSERT_TRUE(android::base::WriteFully(tf.fd, "abc", 3));

  ASSERT_EQ(0, lseek(tf.fd, 0, SEEK_SET)) << strerror(errno);

  std::string s;
  s.resize(3);
  ASSERT_TRUE(android::base::ReadFully(tf.fd, &s[0], s.size()))
    << strerror(errno);
  EXPECT_EQ("abc", s);

  ASSERT_EQ(0, lseek(tf.fd, 0, SEEK_SET)) << strerror(errno);

  s.resize(1024);
  ASSERT_FALSE(android::base::ReadFully(tf.fd, &s[0], s.size()));
}

TEST(file, RemoveFileIfExist) {
  TemporaryFile tf;
  ASSERT_TRUE(tf.fd != -1);
  close(tf.fd);
  tf.fd = -1;
  std::string err;
  ASSERT_TRUE(android::base::RemoveFileIfExists(tf.path, &err)) << err;
  ASSERT_TRUE(android::base::RemoveFileIfExists(tf.path));
  TemporaryDir td;
  ASSERT_FALSE(android::base::RemoveFileIfExists(td.path));
  ASSERT_FALSE(android::base::RemoveFileIfExists(td.path, &err));
  ASSERT_EQ("is not a regular or symbol link file", err);
}


text:
@interface SBStatusViewController : UITableViewController {
    SBStatus *status;
    UILabel *textLabel;
    UILabel *replyLabel;
    NSMutableArray *actions;
	NSString *url;
}

- (id)initWithStatus:(SBStatus *)_status;
- (void)changeFavorited:(BOOL)favorited;

@end


text:
package org.gradle.performance.measure;

import java.math.BigDecimal;

public class Duration {
    public static final Units<Duration> MILLI_SECONDS = Units.base(Duration.class, "ms");
    public static final Units<Duration> SECONDS = MILLI_SECONDS.times(1000, "s");
    public static final Units<Duration> MINUTES = SECONDS.times(60, "m");
    public static final Units<Duration> HOURS = MINUTES.times(60, "h");

    public static Amount<Duration> millis(long millis) {
        return Amount.valueOf(millis, MILLI_SECONDS);
    }

    public static Amount<Duration> millis(BigDecimal millis) {
        return Amount.valueOf(millis, MILLI_SECONDS);
    }

    public static Amount<Duration> seconds(BigDecimal seconds) {
        return Amount.valueOf(seconds, SECONDS);
    }

    public static Amount<Duration> minutes(BigDecimal minutes) {
        return Amount.valueOf(minutes, MINUTES);
    }

    public static Amount<Duration> hours(BigDecimal hours) {
        return Amount.valueOf(hours, HOURS);
    }
}


text:
<!DOCTYPE html>

	<title>QUnit Tests</title>
	<link rel="stylesheet" href="qunit/qunit.css" media="screen">

QUnit Test Suite

test markup


text:
using System;
using Xamarin.Forms;

namespace atlas.samples.helloworld.Shared.Views.Pages
{
    public partial class NextTabPage : ContentPage
    {
        public NextTabPage()
        {
            InitializeComponent();
            Label.Text = Guid.NewGuid().ToString();
        }
    }
}