text:
package com.websudos.phantom.base

import org.scalatest.{FlatSpec, Matchers}
import com.websudos.phantom.dsl._

trait Test {
  private[this] lazy val _name: String = {
    val packagePath = getClass.getName.split("\\.")
    val fullName = packagePath(packagePath.length - 1)

    val index = fullName.indexOf("$$anonfun")

    if (index != -1) {
      val str = fullName.substring(index + 9, fullName.length)
      str.replaceAll("[(\\$\\d+\\$)]", "")
    } else {
      fullName.replaceAll("[(\\$\\d+\\$)]", "")
    }
  }

  def name: String = _name
}

case class CustomRecord(name: String, mp: Map[String, String])

trait TestTableNames extends CassandraTable[TestTableNames, CustomRecord] {
  object record extends StringColumn(this) with PartitionKey[String]
  object sampleLongTextColumnDefinition extends MapColumn[TestTableNames, CustomRecord, String, String](this)

  override def fromRow(r: Row): CustomRecord = {
    CustomRecord(record(r), sampleLongTextColumnDefinition(r))
  }
}

object TestTableNames extends TestTableNames

object Test extends PrimitiveColumn[TestTableNames, CustomRecord, String](TestTableNames)

trait TestNames extends TestTableNames

class Parent extends TestNames
class Parent2 extends Parent

class ClassNameExtraction extends FlatSpec with Matchers {

  it should "correctly name objects inside record classes " in {
    TestTableNames.record.name shouldEqual "record"
  }

  it should "correctly extract long object name definitions in nested record classes" in {
    TestTableNames.sampleLongTextColumnDefinition.name shouldEqual "sampleLongTextColumnDefinition"
  }

  it should "correctly name Cassandra Tables" in {
    TestTableNames.tableName shouldEqual "TestTableNames"
  }

  it should "correctly extract the object name " in {
    Test.name shouldEqual "Test"
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace yiiunit\data\ar;

/**
 * Class OrderItem
 *
 * @property integer $order_id
 * @property integer $item_id
 * @property integer $quantity
 * @property string $subtotal
 */
class OrderItem extends ActiveRecord
{
	public static function tableName()
	{
		return 'tbl_order_item';
	}

	public function getOrder()
	{
		return $this->hasOne(Order::className(), ['id' => 'order_id']);
	}

	public function getItem()
	{
		return $this->hasOne(Item::className(), ['id' => 'item_id']);
	}
}


text:
<?php
namespace TYPO3\Flow\Tests\Functional\Mvc\Fixtures\Controller;

use TYPO3\Flow\Annotations as Flow;
use TYPO3\Flow\Mvc\Controller\ActionController;
use TYPO3\Flow\Property\TypeConverter\DateTimeConverter;
use TYPO3\Flow\Property\TypeConverter\PersistentObjectConverter;
use TYPO3\Flow\Tests\Functional\Persistence\Fixtures\TestEntity;

/**
 * A TestEntity controller fixture
 */
class EntityController extends ActionController
{
    /**
     * @Flow\Inject
     * @var \TYPO3\Flow\Tests\Functional\Persistence\Fixtures\TestEntityRepository
     */
    protected $testEntityRepository;

    /**
     * @param \TYPO3\Flow\Tests\Functional\Persistence\Fixtures\TestEntity $entity
     * @return string
     */
    public function showAction(TestEntity $entity)
    {
        return $entity->getName();
    }

    /**
     * @return void
     */
    protected function initializeUpdateAction()
    {
        $propertyMappingConfiguration = $this->arguments->getArgument('entity')->getPropertyMappingConfiguration();
        $propertyMappingConfiguration
            ->allowAllProperties()
            ->setTypeConverterOption(PersistentObjectConverter::class, PersistentObjectConverter::CONFIGURATION_MODIFICATION_ALLOWED, true);
        $propertyMappingConfiguration
            ->forProperty('subEntities.*')
            ->allowAllProperties()
            ->setTypeConverterOption(PersistentObjectConverter::class, PersistentObjectConverter::CONFIGURATION_MODIFICATION_ALLOWED, true);
        $propertyMappingConfiguration
            ->forProperty('subEntities.*.date')
            ->setTypeConverterOption(DateTimeConverter::class, DateTimeConverter::CONFIGURATION_DATE_FORMAT, 'd.m.Y');
    }

    /**
     * @param TestEntity $entity
     * @return string
     */
    public function updateAction(TestEntity $entity)
    {
        $this->testEntityRepository->update($entity);
        return sprintf('Entity "%s" updated', $entity->getName());
    }

    /**
     * @return string
     */
    protected function getFlattenedValidationErrorMessage()
    {
        $message = 'An error occurred while trying to call ' . get_class($this) . '->' . $this->actionMethodName . '().' . PHP_EOL;
        foreach ($this->arguments->getValidationResults()->getFlattenedErrors() as $propertyPath => $errors) {
            foreach ($errors as $error) {
                $message .= 'Error for ' . $propertyPath . ':  ' . $error->render() . PHP_EOL;
            }
        }

        return $message;
    }
}


text:
<?php

namespace Helmut\Forms\Providers;

use Illuminate\Support\ServiceProvider;

class Laravel extends ServiceProvider {

    /**
     * Register form bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            'Helmut\Forms\Request',
            'Helmut\Forms\Requests\Laravel'
        );
    }

}


text:
<?php

class Google_Service_CloudVideoIntelligence_GoogleCloudVideointelligenceV1beta2WordInfo extends Google_Model
{
  public $confidence;
  public $endTime;
  public $speakerTag;
  public $startTime;
  public $word;

  public function setConfidence($confidence)
  {
    $this->confidence = $confidence;
  }
  public function getConfidence()
  {
    return $this->confidence;
  }
  public function setEndTime($endTime)
  {
    $this->endTime = $endTime;
  }
  public function getEndTime()
  {
    return $this->endTime;
  }
  public function setSpeakerTag($speakerTag)
  {
    $this->speakerTag = $speakerTag;
  }
  public function getSpeakerTag()
  {
    return $this->speakerTag;
  }
  public function setStartTime($startTime)
  {
    $this->startTime = $startTime;
  }
  public function getStartTime()
  {
    return $this->startTime;
  }
  public function setWord($word)
  {
    $this->word = $word;
  }
  public function getWord()
  {
    return $this->word;
  }
}


text:
class Foo {
  bar: number
  #baz: bool
}

function callMeMaybe(foo: ?Foo) {
  return foo?.
}


text:
{% macro sanger_button(variant) %}
  {% if variant.sanger_ordered %}
    {% if variant.validation in ['True positive', 'False positive']%}

Sanger: {{ variant.validation }}

    {% else %}
      <button class="btn btn-light" data-bs-toggle="modal" data-bs-target="#cancelSangerModal">
        Sanger pending...
      </button>
    {% endif %}
  {% else %}
    <button class="btn btn-light" data-bs-toggle="modal" data-bs-target="#sangerModal">
      Sanger
    </button>
  {% endif %}
{% endmacro %}

{% macro sanger_form(institute, case, variant, current_user) %}

      Case {{ case.display_name }}

        {{ variant.display_name }}

      HGNC symbols:
      {{ variant.hgnc_symbols|join(', ') }}

      Gene panels:
      {{ variant.panels|join(', ') }}

Amino acid changes

    {% for gene in variant.genes %}
        {% for transcript in gene.transcripts %}
          {% if "refseq_identifiers" in transcript or transcript.is_canonical %}
              {% if transcript.protein_sequence_name%}

                  [{{ transcript.refseq_identifiers|join(", ") }}] ({{ transcript.transcript_id }}):
                  {{ (transcript.protein_sequence_name or '')|url_decode }}

              {% endif %}
            {% endif %}
          {% endfor %}
    {% endfor %}

GT call

    {% for individual in variant.samples %}

        {{ individual.display_name }}: {{ individual.genotype_call }}

    {% endfor %}

      Ordered by:
      {{ current_user.name }}

Comment: <input type="text" size=45 name="verification_comment">

{% endmacro %}

{% macro modal_sanger(institute, case, variant, current_user) %}
  <form action="{{ url_for('variant.verify', institute_id=institute._id,
                           case_name=case.display_name, variant_id=variant._id, order=True) }}"
        method="POST">

Order Sanger sequencing

            <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
              ×
            </button>

            {{ sanger_form(institute, case, variant, current_user) }}

            <button class="btn btn-danger" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Send sanger order request</button>

  </form>
{% endmacro %}

{% macro modal_cancel_sanger(institute, case, variant, current_user) %}
  <form action="{{ url_for('variant.verify', institute_id=institute._id,
                           case_name=case.display_name, variant_id=variant._id, order=False) }}"
        method="POST">

            <button class="close" data-bs-dismiss="modal">×</button>

Cancel Sanger sequencing

            {{ sanger_form(institute, case, variant, current_user) }}

            <button class="btn btn-default" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Send sanger cancellation request</button>

  </form>
{% endmacro %}


text:
package db

// This file contains definition for structs in database schema

// Module is struct of Module table in db schema.
type Module struct {
	OrgName string // OrgName column refers to name of organization's name holding this Module.
	Name    string // Namme column refers to name of this Module.
	Version string // Version column refers to version of this Module.
	Summary string // Version column refers to summary of this Module.
	Data    string // Data column refers to json format string of this Module in YANG schema.
}

// FeatureBundle is struct of FeatureBundle table in db schema.
type FeatureBundle struct {
	OrgName string // OrgName column refers to name of organization's name holding this FeatureBundle.
	Name    string // Namme column refers to name of this FeatureBundle.
	Version string // Version column refers to version of this FeatureBundle.
	Data    string // Data column refers to json format string of this FeatureBundle in YANG schema.
}


text:
package org.apache.kafka.streams.processor.internals;

import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.processor.AbstractNotifyingBatchingRestoreCallback;
import org.apache.kafka.streams.processor.BatchingStateRestoreCallback;
import org.apache.kafka.streams.processor.StateRestoreCallback;
import org.apache.kafka.streams.processor.StateRestoreListener;

import java.util.Collection;

public class CompositeRestoreListener implements BatchingStateRestoreCallback, StateRestoreListener {

    public static final NoOpStateRestoreListener NO_OP_STATE_RESTORE_LISTENER = new NoOpStateRestoreListener();
    private final BatchingStateRestoreCallback internalBatchingRestoreCallback;
    private final StateRestoreListener storeRestoreListener;
    private StateRestoreListener globalRestoreListener = NO_OP_STATE_RESTORE_LISTENER;

    CompositeRestoreListener(final StateRestoreCallback stateRestoreCallback) {

        if (stateRestoreCallback instanceof StateRestoreListener) {
            storeRestoreListener = (StateRestoreListener) stateRestoreCallback;
        } else {
            storeRestoreListener = NO_OP_STATE_RESTORE_LISTENER;
        }

        internalBatchingRestoreCallback = getBatchingRestoreCallback(stateRestoreCallback);
    }

    @Override
    public void onRestoreStart(final TopicPartition topicPartition,
                               final String storeName,
                               final long startingOffset,
                               final long endingOffset) {
        globalRestoreListener.onRestoreStart(topicPartition, storeName, startingOffset, endingOffset);
        storeRestoreListener.onRestoreStart(topicPartition, storeName, startingOffset, endingOffset);
    }

    @Override
    public void onBatchRestored(final TopicPartition topicPartition,
                                final String storeName,
                                final long batchEndOffset,
                                final long numRestored) {
        globalRestoreListener.onBatchRestored(topicPartition, storeName, batchEndOffset, numRestored);
        storeRestoreListener.onBatchRestored(topicPartition, storeName, batchEndOffset, numRestored);
    }

    @Override
    public void onRestoreEnd(final TopicPartition topicPartition,
                             final String storeName,
                             final long totalRestored) {
        globalRestoreListener.onRestoreEnd(topicPartition, storeName, totalRestored);
        storeRestoreListener.onRestoreEnd(topicPartition, storeName, totalRestored);

    }

    @Override
    public void restoreAll(final Collection<KeyValue<byte[], byte[]>> records) {
        internalBatchingRestoreCallback.restoreAll(records);
    }

    void setGlobalRestoreListener(final StateRestoreListener globalRestoreListener) {
        if (globalRestoreListener != null) {
            this.globalRestoreListener = globalRestoreListener;
        }
    }

    @Override
    public void restore(final byte[] key,
                        final byte[] value) {
        throw new UnsupportedOperationException("Single restore functionality shouldn't be called directly but "
                                                + "through the delegated StateRestoreCallback instance");
    }

    private BatchingStateRestoreCallback getBatchingRestoreCallback(StateRestoreCallback restoreCallback) {
        if (restoreCallback instanceof  BatchingStateRestoreCallback) {
            return (BatchingStateRestoreCallback) restoreCallback;
        }

        return new WrappedBatchingStateRestoreCallback(restoreCallback);
    }

    private static final class NoOpStateRestoreListener extends AbstractNotifyingBatchingRestoreCallback {

        @Override
        public void restoreAll(final Collection<KeyValue<byte[], byte[]>> records) {

        }
    }
}


text:
//
//  Config.m
//  Master
//
//  Created by Kjuly on 1/18/13.
//  Copyright (c) 2013 Kjuly. All rights reserved.
//

#import "Config.h"

/*
 * Device UID
 */
// If APPLY_SECRET_DEVICE_UID_KEY if on,
//   define a key for the Device UID in the keychain
//   e.g. "your_secret_device_identifier"
#ifdef APPLY_SECRET_DEVICE_UID_KEY
NSString * const kDeviceUIDKey = @"<your_secret_device_identifier>";
#endif

/*
 * Server
 */
// e.g. http://123.123.123.123:8080
NSString * const kServerAPIRoot = @"";

/*
 *pragma mark - OAuth Configuration
 */
// Client Identifier to match C/S,
//   any string value is okay, but alpha is better
//   e.g. "iPokeMonClientIdentifier"
NSString * const kOAuthClientIdentifier = @"";
//
// Google
// Client ID for Google's Authentication
//   e.g. "123456789012.apps.googleusercontent.com"
NSString * const kOAuthGoogleClientID = @"<id>.apps.googleusercontent.com";
//
// Client Secret for Google's Authentication
//   e.g. "O0vXxXPUR7xXxYKz7xX6SLQ"
NSString * const kOAuthGoogleClientSecret = @"";
//
// Item name to be stored in keychain for Google OpenID
// Any string value is okay, but alpha is better
//   e.g. "PMOAuth2_Google"
NSString * const kOAuthGoogleKeychainItemName = @"";
//
// Scope for Google+ API,
NSString * const kOAuthGoogleScope = @"https://www.googleapis.com/auth/plus.me";

/*
 * In-App Purchase Configuration
 */
// Tiers
NSString * const kIAPCurrencyTier1 = @"<your_identifier>.coin.tier1";
NSString * const kIAPCurrencyTier2 = @"<your_identifier>.coin.tier2";
NSString * const kIAPCurrencyTier3 = @"<your_identifier>.coin.tier3";

#pragma mark - LIB

/*
 * KYUnlockCodeManager
 */
// If |kKYUnlockCodeManagerUniqueCodeDefined| is defined
// Define a unique code for KYUnlockCodeManager
//   e.g. "abcdef"
#ifdef kKYUnlockCodeManagerUniqueCodeDefined
NSString * const kKYUnlockCodeManagerUniqueCode = @"abcdef";
#endif

@implementation Config

@end


text:
from cradmin_legacy import crapp
from cradmin_legacy.viewhelpers.detail import DetailRoleView

from devilry.apps.core import models as coremodels
from devilry.apps.core.models import Assignment, Candidate, AssignmentGroup
from devilry.apps.core.models import Examiner
from devilry.apps.core.models import RelatedExaminer
from devilry.apps.core.models import RelatedStudent
from devilry.devilry_account.models import SubjectPermissionGroup
from devilry.devilry_admin.views.assignment.anonymizationmode import AssignmentAnonymizationmodeUpdateView
from devilry.devilry_admin.views.assignment.deadline_handling import AssignmentDeadlineHandlingUpdateView
from devilry.devilry_admin.views.assignment.gradingconfiguration import AssignmentGradingConfigurationUpdateView
from devilry.devilry_admin.views.assignment.long_and_shortname import AssignmentLongAndShortNameUpdateView
from devilry.devilry_admin.views.assignment.projectgroups import AssignmentProjectGroupUpdateView
from devilry.devilry_admin.views.assignment.examiner_selfassign import AssignmentExaminerSelfAssignUpdateView
from .first_deadline import AssignmentFirstDeadlineUpdateView
from .publishing_time import AssignmentPublishingTimeUpdateView, PublishNowRedirectView

class Overview(DetailRoleView):
    model = coremodels.Assignment
    template_name = 'devilry_admin/assignment/overview.django.html'

    def get_candidates_count(self):
        return coremodels.Candidate.objects\
            .filter(assignment_group__parentnode=self.assignment)\
            .count()

    def get_distinct_examiners_count(self):
        """
        Get distinct examiners otherwise the same relatedexaminer assigned to multiple groups
        would be shown as multiple examiners.
        """
        return Examiner.objects\
            .filter(assignmentgroup__parentnode=self.assignment)\
            .distinct('relatedexaminer__user').count()

    def get_assignmentgroups_count(self):
        return self.assignment.assignmentgroups.count()

    def get_related_students_count(self):
        return RelatedStudent.objects\
            .filter(period=self.assignment.period, active=True)\
            .distinct('user').count()

    def get_related_examiners_count(self):
        return RelatedExaminer.objects\
            .filter(period=self.assignment.period, active=True)\
            .distinct('user').count()

    @property
    def assignment(self):
        if not hasattr(self, '_assignment'):
            queryset = Assignment.objects\
                .filter(id=self.request.cradmin_role.id)\
                .prefetch_point_to_grade_map()
            self._assignment = queryset.get()
        return self._assignment

    def get_user_is_subjectadmin_or_higher(self):
        return SubjectPermissionGroup.objects\
            .get_devilryrole_for_user_on_subject(
                user=self.request.user, subject=self.assignment.parentnode.parentnode) is not None

    def get_assignment_groups_without_any_examiners(self):
        return AssignmentGroup.objects.filter(parentnode=self.request.cradmin_role, examiners__isnull=True)

    def get_context_data(self, **kwargs):
        context = super(Overview, self).get_context_data(**kwargs)
        context['assignmentgroups_count'] = self.get_assignmentgroups_count()
        context['candidates_count'] = self.get_candidates_count()
        context['examiners_count'] = self.get_distinct_examiners_count()
        context['assignment'] = self.assignment
        context['relatedstudents_count'] = self.get_related_students_count()
        context['relatedexaminers_count'] = self.get_related_examiners_count()
        context['user_is_subjectadmin_or_higher'] = self.get_user_is_subjectadmin_or_higher()
        context['students_without_examiners_exists'] = self.get_assignment_groups_without_any_examiners().exists()
        return context

class App(crapp.App):
    appurls = [
        crapp.Url(r'^$',
                  Overview.as_view(),
                  name=crapp.INDEXVIEW_NAME),
        crapp.Url(r'^update_assignment_short_and_long_name/(?P<pk>\d+)$',
                  AssignmentLongAndShortNameUpdateView.as_view(),
                  name="update_assignment_short_and_long_name"),

        crapp.Url(r'^update_publishing_time/(?P<pk>\d+)$',
                  AssignmentPublishingTimeUpdateView.as_view(),
                  name="update_publishing_time"),

        crapp.Url(r'^publish_assignment_now/(?P<pk>\d+)$',
                  PublishNowRedirectView.as_view(),
                  name="publish_assignment_now"),

        crapp.Url(r'^update_first_deadline/(?P<pk>\d+)$',
                  AssignmentFirstDeadlineUpdateView.as_view(),
                  name="update_first_deadline"),

        crapp.Url(r'^update_gradingconfiguration/(?P<pk>\d+)$',
                  AssignmentGradingConfigurationUpdateView.as_view(),
                  name="update_gradingconfiguration"),

        crapp.Url(r'^update_projectgroup_settings/(?P<pk>\d+)$',
                  AssignmentProjectGroupUpdateView.as_view(),
                  name="update_projectgroup_settings"),

        crapp.Url(r'^update_anonymizationmode/(?P<pk>\d+)$',
                  AssignmentAnonymizationmodeUpdateView.as_view(),
                  name="update_anonymizationmode"),

        crapp.Url(r'^update_deadlinehandling/(?P<pk>\d+)',
                  AssignmentDeadlineHandlingUpdateView.as_view(),
                  name='update_deadline_handling'),
        crapp.Url(f'^update_examiner_selfassign_settings/(?P<pk>\d+)',
                AssignmentExaminerSelfAssignUpdateView.as_view(),
                name='update_examiner_selfassign_settings')
    ]


text:
import { getBidIdParameter } from '../src/utils.js';
import {BANNER} from '../src/mediaTypes.js';
import {registerBidder} from '../src/adapters/bidderFactory.js';

export const spec = {
  code: 'lockerdome',
  supportedMediaTypes: [BANNER],
  isBidRequestValid: function(bid) {
    return !!bid.params.adUnitId;
  },
  buildRequests: function(bidRequests, bidderRequest) {
    let schain;

    const adUnitBidRequests = bidRequests.map(function (bid) {
      if (bid.schain) schain = schain || bid.schain;
      return {
        requestId: bid.bidId,
        adUnitCode: bid.adUnitCode,
        adUnitId: getBidIdParameter('adUnitId', bid.params),
        sizes: bid.mediaTypes && bid.mediaTypes.banner && bid.mediaTypes.banner.sizes
      };
    });

    const payload = {
      bidRequests: adUnitBidRequests,
      // TODO: are these the right refererInfo values?
      url: encodeURIComponent(bidderRequest?.refererInfo?.canonicalUrl || ''),
      referrer: encodeURIComponent(bidderRequest?.refererInfo?.topmostLocation || '')
    };
    if (schain) {
      payload.schain = schain;
    }
    if (bidderRequest) {
      if (bidderRequest.gdprConsent) {
        payload.gdpr = {
          applies: bidderRequest.gdprConsent.gdprApplies,
          consent: bidderRequest.gdprConsent.consentString
        };
      }
      if (bidderRequest.uspConsent) {
        payload.us_privacy = {
          consent: bidderRequest.uspConsent
        }
      }
    }

    const payloadString = JSON.stringify(payload);
    return {
      method: 'POST',
      url: 'https://lockerdome.com/ladbid/prebid',
      data: payloadString
    };
  },
  interpretResponse: function(serverResponse, bidRequest) {
    if (!serverResponse || !serverResponse.body || !serverResponse.body.bids) {
      return [];
    }
    return serverResponse.body.bids.map(function(bid) {
      return {
        requestId: bid.requestId,
        cpm: bid.cpm,
        width: bid.width,
        height: bid.height,
        creativeId: bid.creativeId,
        currency: bid.currency,
        netRevenue: bid.netRevenue,
        ad: bid.ad,
        ttl: bid.ttl,
        meta: {
          advertiserDomains: bid.adomain && Array.isArray(bid.adomain) ? bid.adomain : []
        }
      };
    });
  },
};
registerBidder(spec);


text:
<?php

namespace Google\Service\CloudMachineLearningEngine;

class GoogleCloudMlV1CancelJobRequest extends \Google\Model
{
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudMlV1CancelJobRequest::class, 'Google_Service_CloudMachineLearningEngine_GoogleCloudMlV1CancelJobRequest');


text:
package com.facebook.buck.rust;

import com.facebook.buck.config.BuckConfig;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.cxx.toolchain.linker.DefaultLinkerProvider;
import com.facebook.buck.cxx.toolchain.linker.LinkerProvider;
import com.facebook.buck.io.ExecutableFinder;
import com.facebook.buck.rules.ConstantToolProvider;
import com.facebook.buck.rules.HashedFileTool;
import com.facebook.buck.rules.ToolProvider;
import com.facebook.buck.rules.tool.config.ToolConfig;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;

public class RustBuckConfig {
  private static final String SECTION = "rust";
  private static final Path DEFAULT_RUSTC_COMPILER = Paths.get("rustc");
  private static final String RUSTC_FLAGS = "rustc_flags";
  private static final String RUSTC_BINARY_FLAGS = "rustc_binary_flags";
  private static final String RUSTC_LIBRARY_FLAGS = "rustc_library_flags";
  private static final String RUSTC_CHECK_FLAGS = "rustc_check_flags";
  private static final String RUSTC_TEST_FLAGS = "rustc_test_flags";
  private static final String UNFLAVORED_BINARIES = "unflavored_binaries";
  private static final String REMAP_SRC_PATHS = "remap_src_paths";
  private static final String FORCE_RLIB = "force_rlib";

  enum RemapSrcPaths {
    NO, // no path remapping
    UNSTABLE, // remap using unstable command-line option
    YES, // remap using stable command-line option
    ;

    public void addRemapOption(Builder<String> cmd, String cwd, String basedir) {
      switch (this) {
        case NO:
          break;
        case UNSTABLE:
          cmd.add("-Zremap-path-prefix-from=" + basedir);
          cmd.add("-Zremap-path-prefix-to=");
          cmd.add("-Zremap-path-prefix-from=" + cwd);
          cmd.add("-Zremap-path-prefix-to=./");
          break;
        case YES:
          cmd.add("--remap-path-prefix", basedir + "=");
          cmd.add("--remap-path-prefix", cwd + "=./");
          break;
        default:
          throw new RuntimeException("addRemapOption() not implemented for " + this);
      }
    }
  }

  private final BuckConfig delegate;

  public RustBuckConfig(BuckConfig delegate) {
    this.delegate = delegate;
  }

  ToolProvider getRustCompiler() {
    return delegate
        .getView(ToolConfig.class)
        .getToolProvider(SECTION, "compiler")
        .orElseGet(
            () -> {
              HashedFileTool tool =
                  new HashedFileTool(
                      delegate.getPathSourcePath(
                          new ExecutableFinder()
                              .getExecutable(DEFAULT_RUSTC_COMPILER, delegate.getEnvironment())));
              return new ConstantToolProvider(tool);
            });
  }

  /**
   * Get common set of rustc flags. These are used for all rules that invoke rustc.
   *
   * @return List of rustc option flags.
   */
  private ImmutableList<String> getRustCompilerFlags() {
    return delegate.getListWithoutComments(SECTION, RUSTC_FLAGS, ' ');
  }

  /**
   * Get rustc flags for rust_library() rules.
   *
   * @return List of rustc_library_flags, as well as common rustc_flags.
   */
  ImmutableList<String> getRustLibraryFlags() {
    ImmutableList.Builder<String> builder = ImmutableList.builder();

    builder.addAll(getRustCompilerFlags());
    builder.addAll(delegate.getListWithoutComments(SECTION, RUSTC_LIBRARY_FLAGS, ' '));

    return builder.build();
  }

  /**
   * Get rustc flags for rust_binary() rules.
   *
   * @return List of rustc_binary_flags, as well as common rustc_flags.
   */
  ImmutableList<String> getRustBinaryFlags() {
    ImmutableList.Builder<String> builder = ImmutableList.builder();

    builder.addAll(getRustCompilerFlags());
    builder.addAll(delegate.getListWithoutComments(SECTION, RUSTC_BINARY_FLAGS, ' '));

    return builder.build();
  }

  /**
   * Get rustc flags for rust_test() rules.
   *
   * @return List of rustc_test_flags, as well as common rustc_flags.
   */
  ImmutableList<String> getRustTestFlags() {
    ImmutableList.Builder<String> builder = ImmutableList.builder();

    builder.addAll(getRustCompilerFlags());
    builder.addAll(delegate.getListWithoutComments(SECTION, RUSTC_TEST_FLAGS, ' '));

    return builder.build();
  }

  /**
   * Get rustc flags for #check flavored builds. Caller must also include rule-dependent flags and
   * common flags.
   *
   * @return List of rustc_check_flags.
   */
  ImmutableList<String> getRustCheckFlags() {
    ImmutableList.Builder<String> builder = ImmutableList.builder();

    builder.addAll(delegate.getListWithoutComments(SECTION, RUSTC_CHECK_FLAGS, ' '));

    return builder.build();
  }

  Optional<ToolProvider> getLinker() {
    return delegate.getView(ToolConfig.class).getToolProvider(SECTION, "linker");
  }

  LinkerProvider getLinkerProvider(CxxPlatform cxxPlatform, LinkerProvider.Type defaultType) {
    LinkerProvider.Type type =
        delegate.getEnum(SECTION, "linker_platform", LinkerProvider.Type.class).orElse(defaultType);

    return getLinker()
        .map(tp -> (LinkerProvider) new DefaultLinkerProvider(type, tp))
        .orElseGet(cxxPlatform::getLd);
  }

  // Get args for linker. Always return rust.linker_args if provided, and also include cxx.ldflags
  // if we're using the Cxx platform linker.
  ImmutableList<String> getLinkerArgs(CxxPlatform cxxPlatform) {
    ImmutableList.Builder<String> linkargs = ImmutableList.builder();

    linkargs.addAll(delegate.getListWithoutComments(SECTION, "linker_args"));

    if (!delegate.getPath(SECTION, "linker").isPresent()) {
      linkargs.addAll(cxxPlatform.getLdflags());
    }

    return linkargs.build();
  }

  /**
   * Get unflavored_binaries option. This controls whether executables have the build flavor in
   * their path. This is useful for making the path more deterministic (though really external tools
   * should be asking what the path is).
   *
   * @return Boolean of whether to use unflavored paths.
   */
  boolean getUnflavoredBinaries() {
    return delegate.getBoolean(SECTION, UNFLAVORED_BINARIES).orElse(false);
  }

  /**
   * Get source path remapping option. This controls whether we ask rustc to remap source paths in
   * all output (ie, compiler messages, file!() macros, debug info, etc).
   *
   * @return Remapping mode
   */
  RemapSrcPaths getRemapSrcPaths() {
    return delegate.getEnum(SECTION, REMAP_SRC_PATHS, RemapSrcPaths.class).orElse(RemapSrcPaths.NO);
  }

  /**
   * Get "force_rlib" config. When set, always use rlib (static) libraries, even for otherwise
   * shared targets.
   *
   * @return force_rlib flag
   */
  boolean getForceRlib() {
    return delegate.getBooleanValue(SECTION, FORCE_RLIB, false);
  }
}


text:
var selfSignup;
import {Page, NavController, Loading} from 'ionic-angular';
import {CodeCheckPage} from '../signup/codeCheck';
import {UserData} from '../../providers/user-data';

@Page({
  templateUrl: 'build/pages/signup/signup.html'
})
export class SignupPage {
  static get parameters() {
    return [[NavController], [UserData]];
  }

  constructor(nav, userData) {
    this.nav = nav;
    this.userData = userData;

    this.signup = {};
    this.submitted = false;
    this.rpass=true;
    selfSignup = this;
  }

  onSignup(form) {
      this.submitted = true;

      console.log(form);

      if (form.valid) {
          if (this.signup.password == this.signup.password2) {
              selfSignup = this;
              this.verifySignupAjax();
          } else {
              this.rpass = false;
          }
          //this.nav.push(CodeCheckPage);
      }
  }
  verifySignupAjax() {
      var xhttp = new XMLHttpRequest();
      let loading = Loading.create({
          content: "Aspetta un attimo..."
        });
      this.nav.present(loading);

      xhttp.onreadystatechange =  () => {
          if (xhttp.readyState == 4 && xhttp.status == 200) {
              console.log(xhttp.responseText);
              var xmlResponse = xhttp.responseXML;
              var reply = xmlResponse.getElementsByTagName("response")[0].childNodes[0].nodeValue;
              var code = xmlResponse.getElementsByTagName("key")[0].childNodes[0].nodeValue;
              console.log(reply + code);
              if (reply == "signup ok") {
                  loading.dismiss();
                  selfSignup.nav.push(CodeCheckPage, {"username" : selfSignup.signup.username,
                                                      "password" : selfSignup.signup.password,
                                                      "email" : selfSignup.signup.email,
                                                      "code" : code});
              } else {
                  //$scope.error = "Signup error";
              }
          }
      };
      xhttp.open("POST", "http://giacomovallorani.altervista.org/vallasciapp/verifyUser.php", true);
      xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhttp.send("username=" + selfSignup.signup.username + "&password=" + selfSignup.signup.password + "&email=" + selfSignup.signup.email);
  }

}


text:
require 'ipaddress'
require_relative 'config'

module Cloudstrap
  class Network
    def initialize(network = '10.0.0.0')
      @network = IPAddress(network).tap { |n| n.prefix = config.network_bits.to_i }
      self
    end

    attr_reader :network

    def subnets
      @subnets ||= network.subnet config.subnet_bits.to_i
    end

    def public
      @public ||= subnets.each_with_index.select { |_subnet, index| index.even? }.map(&:first)
    end

    def private
      @private ||= subnets.each_with_index.select { |_subnet, index| index.odd? }.map(&:first)
    end

    def public_layout(*zones)
      zones
        .zip(public.take(zones.size))
        .map { |zone, subnet| [zone, "#{subnet}/#{subnet.prefix}"] }
        .to_h
    end

    def private_layout(*zones)
      zones
        .zip(private.take(zones.size))
        .map { |zone, subnet| [zone, "#{subnet}/#{subnet.prefix}"] }
        .to_h
    end

    def layout(*zones)
      {
        public: public_layout(*zones),
        private: private_layout(*zones)
      }
    end

    private

    def config
      @config ||= Config.new
    end
  end
end


text:
{-# Language EmptyDataDecls    #-}

module Uri where

import FFI
import Prelude

-- | Creation and conversion

-- Choose to make Uri an opaque data type. If the accessors on the
-- jsUri objects were properties and not functions we could have
-- defined Uri as a record instead.
data Uri

-- To make Google Closure play nice we use [] instead of . for accessing properties.
currentUri :: Fay String
currentUri = ffi "window['location']['href']"

-- This assumes that Uri is defined globally, which it is by default.
newUri :: String -> Uri
newUri = ffi "new window['Uri'](%1)"

toString :: Uri -> String
toString = ffi "%1['toString']()"

-- If we ever want to pass a Uri back to JS we need to make sure we keep persistance internally.
clone :: Uri -> Uri
clone = ffi "%1['clone']()"

-- | Getters

-- All getters (except query! But lets be consistent) may return null if the value isn't set so we use
-- Language.FFI.Nullable here which converts null -> Null and String -> Nullable String.
-- Nullable is distinguished from Maybe to not break haskell compatibility.
-- If we want to decode null into Nullable (Nullable a) there is no way of
-- knowing if Null or Nullable Null is correct. This problem does not exist when
-- working with Maybe values in client server communication.
protocol :: Uri -> Nullable String
protocol = ffi "%1['protocol']()"

userInfo :: Uri -> Nullable String
userInfo = ffi "%1['userInfo']()"

host :: Uri -> Nullable String
host = ffi "%1['host']()"

port :: Uri -> Nullable String
port = ffi "%1['port']()"

path :: Uri -> Nullable String
path = ffi "%1['path']()"

query :: Uri -> Nullable String
query = ffi "%1['query']()"

anchor :: Uri -> Nullable String
anchor = ffi "%1['anchor']()"

-- | Other getters

queryParamValue :: String -> Uri -> String
queryParamValue = ffi "%2['getQueryParamValue'](%1)"

queryParamValues :: String -> Uri -> [String]
queryParamValues = ffi "%2['getQueryParamValues'](%1)"

-- | Setters

-- We could use Nullable here to combine the with* and remove* functions
-- but usage would be more verbose that way.

-- JsUri has clone() conveniently defined so we use it to get
-- persistence, otherwise our types would be `-> Fay Uri` which is of
-- course worse.

withProtocol :: String -> Uri -> Uri
withProtocol = ffi "%2['clone']()['setProtocol'](%1)"

withUserInfo :: String -> Uri -> Uri
withUserInfo = ffi "%2['clone']()['setUserInfo'](%1)"

withHost :: String -> Uri -> Uri
withHost = ffi "%2['clone']()['setHost'](%1)"

withPort :: String -> Uri -> Uri
withPort = ffi "%2['clone']()['setPort'](%1)"

withPath :: String -> Uri -> Uri
withPath = ffi "%2['clone']()['setPath'](%1)"

withQuery :: String -> Uri -> Uri
withQuery = ffi "%2['clone']()['setQuery'](%1)"

withAnchor :: String -> Uri -> Uri
withAnchor = ffi "%2['clone']()['setAnchor'](%1)"

-- | Removals

removeProtocol :: Uri -> Uri
removeProtocol = ffi "%1['clone']()['setProtocol'](null)"

removeUserInfo :: Uri -> Uri
removeUserInfo = ffi "%1['clone']()['setUserInfo'](null)"

removeHost :: Uri -> Uri
removeHost = ffi "%1['clone']()['setHost'](null)"

removePort :: Uri -> Uri
removePort = ffi "%1['clone']()['setPort'](null)"

removePath :: Uri -> Uri
removePath = ffi "%1['clone']()['setPath'](null)"

removeQuery :: Uri -> Uri
removeQuery = ffi "%1['clone']()['setQuery'](null)"

removeAnchor :: Uri -> Uri
removeAnchor = ffi "%1['clone']()['setAnchor'](null)"

-- | Other setters

addQueryParam :: String -> String -> Uri -> Uri
addQueryParam = ffi "%3['clone']()['addQueryParam'](%1,%2)"

replaceQueryParam :: String -> String -> Uri -> Uri
replaceQueryParam = ffi "%3['clone']()['replaceQueryParam'](%1,%2)"

-- The order of the arguments differ from the jsUri api, it is now
-- key -> oldValue -> newValue -> Uri -> Uri
replaceQueryParamValue :: String -> String -> String -> Uri -> Uri
replaceQueryParamValue = ffi "%4['clone']()['replaceQueryParam'](%1, %3, %2)"

deleteQueryParam :: String -> Uri -> Uri
deleteQueryParam = ffi "%2['clone']()['deleteQueryParam'](%1)"

deleteQueryParamValue :: String -> String -> Uri -> Uri
deleteQueryParamValue = ffi "%3['clone']()['deleteQueryParam'](%1,%2)"


text:
__Description__: If there is a `attachTo: <number>` key/value pair in the `option` object within a `state` object that is not on the root level and in `component` then the `state` will be attached to the index of the specified number in which `0` represents the root in the following fashion `<selector number index>:<state>` and `<selector number index>:not(:<state>)`

__Notes__

+ `0` represents the root


text:
/**
 * Created by lifetea on 2016/12/16.
 * email: 494886251@qq.com
 * github: https://github.com/lifetea
 */

//lazy load
const lazyLoading = (name, index = false) => () => System.import(`../view/${name}${index ? '/index' : ''}.vue`)

//布局

const routes = [
    { path: '', component: lazyLoading('Layout'),
        children: [

        ]
    },
    {
        path: '/login',
        name:'login',
        component: lazyLoading('Login')
    },
];

export default routes;


text: Copyright (c) 2016 Catenology All Rights Reserved.


text:
 // Design Basic Game Solo Challenge

// This is a solo challenge

// Your mission description:
// Overall mission: Take care of a kitty.
// Goals: After [tbd] turns, the kitty has a sufficient happines level
// Characters: Cat(variable name)
// Objects: cat(happiness), bowl(water,food), litterBox(poop)
// Functions:
//    pet = increase happiness
//    fillFood = increase food to 100% full
//    fillWater = increase water to 100% full
//    cleanLitter = decrease poop to 0%
//    turnEnd = decrease happiness, food, and water; increase poop
//    play = ask for user input, perform appropriate function, turnEnd

// Pseudocode

/*

PART ONE - story and action (new cat)
story: Go to animal shelter, pick out a cat.
action: set a variable catName equal to the user input when asked
  for the name of the new cat.
story:Worker will visit house in 5 days to see if the cat is a good fit.

PART TWO- setup (set up objects and related variables)
set up the following things with associated variables
cat =
  cat's name is equal to catName from Part One
  cat's happiness starts at 50%
bowl =
  food starts at 100%
  water starts at 100%
litterBox =
  poop starts at 0%

set up the following code blocks
code block pet does
  increase happiness by 10%
code block fillFood does
  increase food to 110% full
code block fillWater does
  increase water to 110% full
code block cleanLitter does
  decrease poop to 0%
code block turnEnd does
  decrease happiness, food, and water; increase poop
code block play does (for the number of turns decided)
  ask for user input
  perform appropriate function
  shows current information
  run turnEnd code block

PART THREE- (win?)
function win?
 if joy + food + water + (100-poop) > 300
     return true

function finish
 if win? = true
    story: Yay this is a good match, have fun with your kitty
 else
    story: Hey, this kitty doesn't look very happy. I think we should take them back. Come back when you're ready to try again.
*/

// Initial Code

// PART ONE - story and action (new cat)
console.log("Welcome to the local animal shelter! We have the perfect cat for you! What would you like to name them?")
var catName = prompt("What would you like to name your cat?")
console.log("Awesome. Hopefully you and " + catName + "get along well. We'll be by in a bit to make sure everything is going well!")

var Cat = {
    name: catName,
    joy: 50,
}
var Bowl = {
    food: 100,
    water: 100,
}
var LitterBox = {
    poop: 0,
}
function pet() {
    Cat.joy += 20;
}
function fillFood() {
    Bowl.food = 110;
}
function fillWater() {
    Bowl.water = 110;
}
function cleanLitter() {
    LitterBox.poop = -10;
}
function turnEnd() {
    Cat.joy -= 10;
    Bowl.food -= 10;
    Bowl.water -= 10;
    LitterBox.poop += 10;
}
function win() {
    if (Cat.joy + Bowl.food + Bowl.water + (100-LitterBox.poop) > 250){
        console.log("Wow, this cat seems happy! I suppose that they should stay with you! I hope you enjoy each other's company, because they're a healthy kitty and will be with you for a long time.");
        console.log("YOU WIN");
    }
    else {
        console.log("This cat doesn't seem very happy! I think I should take it back to the shelter. Feel free to try again later.");
        console.log("YOU LOSE");
    }
}
function play() {
    for (var turns = 1; turns < 25; turns++) {
        console.log("Begin Turn " + turns);
        console.log(Cat,Bowl,LitterBox)
        console.log("What would you like to do? (please type 'pet', 'feed', 'give water', 'clean litter'.)(type exit to force quit)");
        var userInput = prompt("What would you like to do? (please type 'pet', 'feed', 'give water', 'clean litter'.)");
        if(userInput === "pet" ){
            pet();
        }
        else if(userInput === "feed" ){
            fillFood();
        }
        else if(userInput === "give water" ){
            fillWater();
        }
        else if(userInput === "clean litter" ){
            cleanLitter();
        }
        else if(userInput === "exit"){
            console.log("Goodbye!")
            break;
        }
        else {
            console.log("That is not a valid input. You have forfeited this turn.");
        }
        turnEnd();
    }
    win()
}

// Refactored Code

//objects and functions
var Cat = {
    name: catName,
    joy: 50,
}
var Bowl = {
    food: 100,
    water: 100,
}
var LitterBox = {
    poop: 0,
}
function pet() {
    Cat.joy += 20;
}
function fillFood() {
    Bowl.food = 110;
}
function fillWater() {
    Bowl.water = 110;
}
function cleanLitter() {
    LitterBox.poop = -10;
}
function turnEnd() {
    Cat.joy -= 10;
    Bowl.food -= 10;
    Bowl.water -= 10;
    LitterBox.poop += 10;
}
function gameStart() {
    console.log("Welcome to the local animal shelter! We have the perfect cat for you! What would you like to name them?")
    var catName = prompt("What would you like to name your cat?")
    console.log("Awesome. Hopefully you and " + catName + "get along well. We'll be by in a bit to make sure everything is going well!")
}
function win() {
    if (Cat.joy + Bowl.food + Bowl.water + (100-LitterBox.poop) > 250){
        console.log("Wow, this cat seems happy! I suppose that they should stay with you! I hope you enjoy each other's company, because they're a healthy kitty and will be with you for a long time.");
        console.log("YOU WIN");
    }
    else {
        console.log("This cat doesn't seem very happy! I think I should take it back to the shelter. Feel free to try again later.");
        console.log("YOU LOSE");
    }
}
function play() {
    gameStart()
    for (var turns = 1; turns < 25; turns++) {
        alert("Begin Turn " + turns);
        alert("Happiness level is at " + Cat.joy + "%. Use 'pet' to raise. Food bowl is " + Bowl.food)
        var userInput = prompt("What would you like to do? (please type 'pet', 'feed', 'give water', 'clean litter'.)");
        if(userInput === "pet" ){
            pet();
        }
        else if(userInput === "feed" ){
            fillFood();
        }
        else if(userInput === "give water" ){
            fillWater();
        }
        else if(userInput === "clean litter" ){
            cleanLitter();
        }
        else if(userInput === "exit"){
            console.log("Goodbye!")
            break;
        }
        else {
            console.log("That is not a valid input. You have forfeited this turn.");
        }
        turnEnd();
    }
    win()
}

//Game Play

play()

// Reflection
//
//What was the most difficult part of this challenge?
        // I think the most difficult part of this challenge was just deciding to do it!
        // I had a lot of trouble coming up with ideas.
// What did you learn about creating objects and functions that interact with one another?
        // You have to keep track of what is doing what to what. So for example, all of the stats
        //  in my game have a decay value. YOu have to be able to use another function to
        // show the final count. Petting the cat has a decay of 10 joy a turn, so to increase
        // joy by ten instead, I have to have theh act of petting return +20, to also interact
        // with the -10 at turn end.
// Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
        // My initial solution was pretty neat. It's really just simple math adjustments and function clals. So I didn't find anything exciting.
// How can you access and manipulate properties of objects?
        // you can use functions that add to or replace values. for numeric values, you can use mathmatics on them.
        // To access them, you reference them as Object.property or Object[property]

//
//


text:
require 'spec_helper'

module  HardCiter
  describe BibTexLibrary do
    let(:valid_bibtex_path) { File.expand_path('../../../examples/example_bib.bib', __FILE__) }
    let(:bibtex_library) { BibTexLibrary.new(valid_bibtex_path) }

    subject { bibtex }

    describe 'initialization' do
      describe 'with a valid path to a bib file' do
        it 'should initalize its bibtex to a BibTeX::Bibliography object' do
          library = BibTexLibrary.new(valid_bibtex_path)
          library.bibtex.should be_kind_of(BibTeX::Bibliography)
        end
      end
    end

    describe 'getting an entry'  do
      before do
        bibtex_library.bibtex = BibTeX.parse <<-END
        @book{pickaxe,
          address = {Raleigh, North Carolina},
          author = {Thomas, Dave and Fowler, Chad and Hunt, Andy},
          publisher = {The Pragmatic Bookshelf},
          series = {The Facets of Ruby},
          title = {Programming Ruby 1.9: The Pragmatic Programmer's Guide},
          year = {2009}
        }
        END
      end

      context 'entry exists in BibTexLibrary' do
        describe 'using the hash brackets' do
          it 'should return a BibTex::Entry' do
            bibtex_library['pickaxe'].should be_kind_of(BibTeX::Entry)
          end
        end

        describe "using the get_entry method" do
          it 'should return a BibTex::Entry' do
            bibtex_library['pickaxe'].should be_kind_of(BibTeX::Entry)
          end
        end
      end

      context 'entry does not exist in the BibTex library' do
        describe 'using the hash brackets' do
          it { bibtex_library.get_entry('not-valid').should be_nil }
        end
      end
    end

    describe '#load_from_file' do
      context 'with a blank library and a valid path' do
        before { @blank_library = BibTexLibrary.new() }
        it 'should load a valid Bibtex::Bibliography into its bibtex' do
          @blank_library.load_from_file(valid_bibtex_path)
          @blank_library.bibtex.should be_kind_of(BibTeX::Bibliography)
        end
      end
    end
  end
end


text:
import {
  issuable1,
  issuable2,
  issuable3,
  issuable4,
  issuable5,
} from 'jest/vue_shared/components/issue/related_issuable_mock_data';
import RelatedIssuesStore from '~/related_issues/stores/related_issues_store';

describe('RelatedIssuesStore', () => {
  let store;

  beforeEach(() => {
    store = new RelatedIssuesStore();
  });

  describe('setRelatedIssues', () => {
    it('defaults to empty array', () => {
      expect(store.state.relatedIssues).toEqual([]);
    });

    it('sets issues', () => {
      const relatedIssues = [issuable1];
      store.setRelatedIssues(relatedIssues);

      expect(store.state.relatedIssues).toEqual(relatedIssues);
    });
  });

  describe('addRelatedIssues', () => {
    it('adds related issues', () => {
      store.state.relatedIssues = [issuable1];
      store.addRelatedIssues([issuable2, issuable3]);

      expect(store.state.relatedIssues).toEqual([issuable1, issuable2, issuable3]);
    });
  });

  describe('removeRelatedIssue', () => {
    it('removes issue', () => {
      store.state.relatedIssues = [issuable1];

      store.removeRelatedIssue(issuable1);

      expect(store.state.relatedIssues).toEqual([]);
    });

    it('removes issue with multiple in store', () => {
      store.state.relatedIssues = [issuable1, issuable2];

      store.removeRelatedIssue(issuable1);

      expect(store.state.relatedIssues).toEqual([issuable2]);
    });
  });

  describe('updateIssueOrder', () => {
    it('updates issue order', () => {
      store.state.relatedIssues = [issuable1, issuable2, issuable3, issuable4, issuable5];

      expect(store.state.relatedIssues[3].id).toBe(issuable4.id);
      store.updateIssueOrder(3, 0);

      expect(store.state.relatedIssues[0].id).toBe(issuable4.id);
    });
  });

  describe('setPendingReferences', () => {
    it('defaults to empty array', () => {
      expect(store.state.pendingReferences).toEqual([]);
    });

    it('sets pending references', () => {
      const relatedIssues = [issuable1.reference];
      store.setPendingReferences(relatedIssues);

      expect(store.state.pendingReferences).toEqual(relatedIssues);
    });
  });

  describe('addPendingReferences', () => {
    it('adds a reference', () => {
      store.state.pendingReferences = [issuable1.reference];
      store.addPendingReferences([issuable2.reference, issuable3.reference]);

      expect(store.state.pendingReferences).toEqual([
        issuable1.reference,
        issuable2.reference,
        issuable3.reference,
      ]);
    });
  });

  describe('removePendingRelatedIssue', () => {
    it('removes issue', () => {
      store.state.pendingReferences = [issuable1.reference];

      store.removePendingRelatedIssue(0);

      expect(store.state.pendingReferences).toEqual([]);
    });

    it('removes issue with multiple in store', () => {
      store.state.pendingReferences = [issuable1.reference, issuable2.reference];

      store.removePendingRelatedIssue(0);

      expect(store.state.pendingReferences).toEqual([issuable2.reference]);
    });
  });
});


text:
layout: post
title:  "Sqitch and Sqitchers"
author: Luca Ferrari
tags:
- sqitch
- planet-postgresql-org
- itpug
permalink: /:year/:month/:day/:title.html
---
Sqitch has nothing particular to do with PostgreSQL, except it does support our beloved database!

# Sqitch and Sqitchers

Long story short: **if you are not using [`sqitch`](https://sqitch.org/) you should give it a look**.

[`sqitch`](https://sqitch.org/) does not ties itself to *only* PostgreSQL, but it does support a lot of relational engines. However, if you want to know how to start using Sqitch over PostgreSQL go read the excellent [Introduction to Sqitch on PostgreSQL](https://github.com/sqitchers/sqitch/blob/master/lib/sqitchtutorial.pod).

I've already written about [`sqitch` in the past (in italian)](https://fluca1978.github.io/2014/12/20/calendario-dellavvento-itpug-20-dicembre.html).

[`sqitch`](https://sqitch.org/) is a great tool to manage database changes, mainly schema changes. The idea is to provide a `git`-like interface to manage *changes*, a *change* is made by three scripts appropriately written for the backend database:
- a *deploy* script (what to do);
- a *revert* script (how to undo);
- a *test* script (how to check the deploy succeeded).

### Introducing *sqitchers*.

[Around a month ago](https://justatheory.com/2018/05/sqitchers/), the `sqitch` creator, David E. Wheeler, created a GitHub Organization named [`sqitchers`](https://github.com/sqitchers) that now holds all the Sqitch related stuff including, obviously, the codebase for the project. At the same time, the Sqitch steering committee grown, and this is a good thing since this project quickly became an handy tool for database management.

In conclusion, `sqitch` is growing and getting more free every day. If you are curious about project history and explaination by its own creator David E. Wheeler, [I suggest you listening to this (old) FLOSS Weekly podcast](https://justatheory.com/2014/09/sqitch-on-floss-weekly/).


text:
<?php

namespace Org\Schema;

/**
 * Class Thing.
 * The most generic type of item.
 * @author      AppBels <app.bels@gmail.com>
 * @name        Thing
 * @namespace   Org\Schema
 * @package     Org\Schema
 * @see         https://schema.org/Thing
 * Date:        25/02/2017
 */
class Thing
{

	/**
	 * Context for json+ld
	 * @const
	 * @var		string
	 */
	const CONTEXT = "http://schema.org";

	/**
	 * Used to uniquely identify things that are being described in the document with IRIs or blank node identifiers.
	 * This keyword is described in section 5.3 Node Identifiers.
	 * Property used for json-ld.
	 * @access	public
	 * @see		https://www.w3.org/TR/json-ld/
	 * @var		string
	 */
	public $id;

    /**
     * An additional type for the item, typically used for adding more specific types from external
     * vocabularies in microdata syntax.
     * This is a relationship between something and a class that the thing is in.
     * In RDFa syntax, it is better to use the native RDFa syntax - the 'typeof' attribute - for multiple types.
     * Schema.org tools may have only weaker understanding of extra types, in particular those defined externally.
     * @access  public
     * @var     string
     */
    public $additionalType;

    /**
     * An alias for the item.
     * @access  public
     * @var     string
     */
    public $alternateName;

    /**
     * A description of the item.
     * @access  public
     * @var     string
     */
    public $description;

    /**
     * A sub property of description.
     * A short description of the item used to disambiguate from other, similar items.
     * Information from other properties (in particular, name) may be necessary for the description to be useful
     * for disambiguation.
     * @access  public
     * @var     string
     */
    public $disambiguatingDescription;

	/**
	 * The identifier property represents any kind of identifier for any kind of Thing,
	 * such as ISBNs, GTIN codes, UUIDs etc.
	 * Schema.org provides dedicated properties for representing many of these, either as
	 * textual strings or as URL (URI) links.
	 * See background notes for more details.
	 * @access	public
	 * @var		string|\Org\Schema\Thing\Intangible\StructuredValue\PropertyValue
	 */
    public $identifier;

    /**
     * An image of the item. This can be a URL or a fully described ImageObject.
     * @access  public
     * @var     string|\Org\Schema\Thing\CreativeWork\MediaObject\ImageObject
     */
    public $image;

    /**
     * Indicates a page (or other CreativeWork) for which this thing is the main entity being described.
     * See background notes for details.
     * Inverse property: mainEntity.
     * @access  public
     * @var     string|\Org\Schema\Thing\CreativeWork
     */
    public $mainEntityOfPage;

    /**
     * The name of the item.
     * @access  public
     * @var     string
     */
    public $name;

    /**
     * Indicates a potential Action, which describes an idealized action in which this thing would play an 'object' role.
     * @access  public
     * @var     \Org\Schema\Thing\Action
     */
    public $potentialAction;

    /**
     * URL of a reference Web page that unambiguously indicates the item's identity.
     * E.g. the URL of the item's Wikipedia page, Freebase page, or official website.
     * @access  public
     * @var     string
     */
    public $sameAs;

    /**
     * URL of the item.
     * @access  public
     * @var     string
     */
    public $url;

    /**
     * Thing constructor.
     * @access  public
     */
    public function __construct ()
    {

    }

	/**
	 * Thing toString.
	 * @access  public
	 *
	 * @return  string
	 */
    public function __toString ()
    {
	    return $this->toJson();
    }

	/**
     * Thing destructor
     * @access  public
     */
    public function __destruct ()
    {

    }

	/**
	 * Create json-ld schema.
	 * @final
	 * @access  public
	 * @param	int		$options	json options
	 *
	 * @return  string
	 */
    public final function toJson ($options = JSON_UNESCAPED_SLASHES)
    {
		$properties = get_object_vars($this);
		unset($properties['id']);
		$rs = array();
		foreach ($properties as $property => $value){
			if (!isset($this->{$property}) || empty($this->{$property})){
				continue;
			}

			if (is_object($value) && $value instanceof \Org\Schema\Thing){
				$rs[$property] = json_decode($value->toJson($options), true);
				unset($rs[$property]['@context']);
			}else if (is_array($value)){
				$props = array_values($value);
				$prop = array();
				$l = count($props);
				for ($i = 0; $i < $l; $i++){
					if (is_object($props[$i]) && $props[$i] instanceof \Org\Schema\Thing){
						$item = json_decode($props[$i]->toJson($options), true);
						unset($item['@context']);
						$prop[] = $item;
						unset($item);
					}else {
						$prop[] = $props[$i];
					}
				}
				$rs[$property] = $prop;
			}else {
				$rs[$property] = $value;
			}
		}

		if (!empty($this->id)){
			$rs['@id'] = $this->id;
		}

		if (!empty($rs)){
			$rs['@type'] = substr(static::class, (strrpos(static::class, "\\") + 1));
    		$rs['@context'] = self::CONTEXT;
		}

    	return json_encode($rs, $options);
    }

	/**
	 * Create html schema.
	 * @final
	 * @access  public
	 * @param 	string	$property	Parent property.
	 *
	 * @return  string
	 */
    public final function toHtml ($property = '')
    {
		$properties = get_object_vars($this);
		unset($properties['id']);
		$type = substr(static::class, (strrpos(static::class, "\\") + 1));
    	$html = "<div itemscope itemtype=\"" . self::CONTEXT ."/{$type}\"";

    	if (!empty($property)){
    		$html .= " itemprop=\"" . $property . "\"";
		}

		$html .= ">";

    	foreach ($properties as $prop => $value){
    		if (!isset($value) || empty($value)){
    			continue;
			}

			if ($value instanceof \Org\Schema\Thing){
    			$html .= $value->toHtml($prop);
			}else if (is_array($value)){
				$elems = array_values($value);
				$len = count($elems);
				for ($i = 0; $i < $len; $i++){
					if (empty($elems[$i])){
						continue;
					}

					if ($elems[$i] instanceof \Org\Schema\Thing){
						$html .= $elems[$i]->toHtml($prop);
					}else if (is_scalar($elems[$i])){
						$html .= (filter_var($elems[$i], FILTER_VALIDATE_URL)) ? "<link itemprop=\"" . $prop . "\" href=\"" . $elems[$i] . "\" />" : "<meta itemprop=\"" . $prop . "\" content=\"" . $elems[$i] . "\" />";
					}
				}
			}else if (is_scalar($value)){
				$html .= (filter_var($value, FILTER_VALIDATE_URL)) ? "<link itemprop=\"" . $prop . "\" href=\"" . $value . "\" />" : "<meta itemprop=\"" . $prop . "\" content=\"" . $value . "\" />";
			}
		}

		$html .= "</div>";

		return $html;
    }

	/**
	 * Create an object array of the set values.
	 * @final
	 * @access	public
	 *
	 * @return 	array
	 */
    public final function toArray ()
	{
		$properties = get_object_vars($this);
		unset($properties['id']);
		$rs = array();
		foreach ($properties as $property => $value){
			if (!isset($this->{$property}) || empty($this->{$property})){
				continue;
			}

			if (is_object($value) && $value instanceof \Org\Schema\Thing){
				$rs[$property] = $value->toArray();
			}else if (is_array($value)){
				$props = array_values($value);
				$prop = array();
				$l = count($props);
				for ($i = 0; $i < $l; $i++){
					if (is_object($props[$i]) && $props[$i] instanceof \Org\Schema\Thing){
						$prop[] = $props[$i]->toArray();
					}else {
						$prop[] = $props[$i];
					}
				}
				$rs[$property] = $prop;
			}else {
				$rs[$property] = $value;
			}
		}

		return $rs;
	}

}

?>


text:
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="style.css" rel="stylesheet" type="text/css">

L'ATELIER HEXAGONAL

                contact.bertrandlacourt@atelier.fr

                www.bertrandlacourt.com

Bertrand Lacourt

Ébéniste - Arcueil

Ebéniste depuis vingt ans dans l'ébénisterie d'agencement, Bertrand Lacourt
              a fait, il y a quelques années, un retour à la source : il est retourné
              en forêt, à l'arbre. Il est aussi remonté dans le temps, celui de son enfance
              au bord de la forêt de Fontainebleau, et celui, ancestral, du façonnage
              traditionnel du bois, pour aujourd'hui fabriquer des objets taillés dans
              de simples troncs d'arbre, sans aucun assemblage. En un mot, des monoxyles.

Dans l'atelier de Bertrand, vous ne trouverez pas d'équipement d'ébéniste
              mais des outils adaptés aux techniques primitives de la taille directe.
              Un vrai travail de sculpteur qui permet de créer des meubles par enlèvement
              de matière.

Bertrand a choisi de travailler les arbres de Bourgogne qu'il taille sur
              place, à la tronçonneuse, pour ébaucher les formes des meubles. Les pièces
              ainsi débitées sont ensuite ramenées dans son atelier d'Arcueil pour être
              séchées puis retravaillées.

Bertrand est l'un des seuls à pratiquer cette technique de la taille directe
              pour créer du mobilier au design contemporain et minimaliste en France.
              Le veinage du bois, la manière de le sculpter font que chaque pièce de
              sa collection est unique. Du mobilier intemporel qu'il peut reproduire
              et adapter à la demande pour du sur-mesure.

Créations

Ci-dessous, quelques une de ses créations monoxyles.

Crédits photographique : Pierre-Jérôme Duval

Artisans

Créations

Portraits

Réseaux sociaux

Newsletter

              <form role="form">

                    <input type="email" class="form-control" placeholder="Email">

                      S'abonner

              </form>

© 2016. Nom du site. Tous droits réservés. Contact : hello@domaine.fr


text:
<?php
namespace Desmond\functions\docs;
use Desmond\functions\Doc;

class Let implements Doc
{
    public function id()
    {
        return 'let';
    }

    public function synopsis()
    {
        return 'Creates a localized environment/scope containing a group of symbols/values.
Those symbols will not have value outside of the let block.';
    }

    public function usage()
    {
        return '(let <Hash> <Mixed>)';
    }

    public function examples()
    {
        return [
            '(let {x 1, y 2} (+ x y))'
        ];
    }
}


text:
module Frontend
  class StatisticsAnnouncementProvider
    def self.search(search_params = {})
      results = Whitehall.statistics_announcement_search_client.advanced_search(prepare_search_params(search_params))
      CollectionPage.new(build_collection(results['results']), total: results['total'], page: search_params[:page], per_page: search_params[:per_page])
    end

  private
    def self.build_collection(release_announcement_hashes)
      Array(release_announcement_hashes).map { | release_announcement_hash | build_from_rummager_hash(release_announcement_hash) }
    end

    def self.build_from_rummager_hash(rummager_hash)
      Frontend::StatisticsAnnouncement.new({
        slug: rummager_hash['slug'],
        title: rummager_hash['title'],
        summary: rummager_hash['description'],
        document_type: rummager_hash['display_type'],
        release_date: rummager_hash['release_timestamp'],
        display_date: rummager_hash['metadata']['display_date'],
        release_date_confirmed: rummager_hash['metadata']['confirmed'],
        release_date_change_note: rummager_hash['metadata']['change_note'],
        previous_display_date: rummager_hash['metadata']['previous_display_date'],
        organisations: build_organisations(rummager_hash['organisations']),
        topics: build_topics(rummager_hash['topics']),
        state: rummager_hash['statistics_announcement_state'],
        cancellation_reason: rummager_hash['metadata']['cancellation_reason'],
        cancellation_date: rummager_hash['metadata']['cancelled_at'],
      })
    end

    def self.build_organisations(org_slugs)
      Organisation.where(slug: org_slugs)
    end

    def self.build_topics(topic_slugs)
      Topic.where(slug: topic_slugs)
    end

    def self.prepare_search_params(params)
      params = params.dup

      params[:release_timestamp] = {
        from: (params.delete(:from_date) || Date.today).try(:iso8601),
        to: params.delete(:to_date).try(:iso8601)
      }.delete_if {|k, v| v.blank? }

      params[:page] = params[:page].to_s
      params[:per_page] = params[:per_page].to_s

      params[:format] = "statistics_announcement"
      params[:order] = {release_timestamp: "asc"}

      params
    end
  end
end


text:
from __future__ import unicode_literals
import codecs
import datetime
import glob
import hashlib
import os

Image = None
try:
    import Image as _Image
    import ExifTags
    Image = _Image
except ImportError:
    try:
        from PIL import Image, ExifTags  # NOQA
    except ImportError:
        pass

from nikola.plugin_categories import Task
from nikola import utils

class Galleries(Task):
    """Copy theme assets into output."""

    name = str("render_galleries")
    dates = {}

    def gen_tasks(self):
        """Render image galleries."""

        kw = {
            'thumbnail_size': self.site.config['THUMBNAIL_SIZE'],
            'max_image_size': self.site.config['MAX_IMAGE_SIZE'],
            'output_folder': self.site.config['OUTPUT_FOLDER'],
            'cache_folder': self.site.config['CACHE_FOLDER'],
            'default_lang': self.site.config['DEFAULT_LANG'],
            'blog_description': self.site.config['BLOG_DESCRIPTION'],
            'use_filename_as_title': self.site.config['USE_FILENAME_AS_TITLE'],
            'gallery_path': self.site.config['GALLERY_PATH']
        }

        # FIXME: lots of work is done even when images don't change,
        # which should be moved into the task.

        template_name = "gallery.tmpl"

        gallery_list = []
        for root, dirs, files in os.walk(kw['gallery_path']):
            gallery_list.append(root)
        if not gallery_list:
            yield {
                'basename': str('render_galleries'),
                'actions': [],
            }
            return

        # gallery_path is "gallery/name"
        for gallery_path in gallery_list:
            # gallery_name is "name"
            splitted = gallery_path.split(os.sep)[1:]
            if not splitted:
                gallery_name = ''
            else:
                gallery_name = os.path.join(*splitted)
            # output_gallery is "output/GALLERY_PATH/name"
            output_gallery = os.path.dirname(os.path.join(
                kw["output_folder"], self.site.path("gallery", gallery_name,
                                                    None)))
            output_name = os.path.join(output_gallery, self.site.config['INDEX_FILE'])
            if not os.path.isdir(output_gallery):
                yield {
                    'basename': str('render_galleries'),
                    'name': output_gallery,
                    'actions': [(os.makedirs, (output_gallery,))],
                    'targets': [output_gallery],
                    'clean': True,
                    'uptodate': [utils.config_changed(kw)],
                }
            # image_list contains "gallery/name/image_name.jpg"
            image_list = glob.glob(gallery_path + "/*jpg") +\
                glob.glob(gallery_path + "/*JPG") +\
                glob.glob(gallery_path + "/*PNG") +\
                glob.glob(gallery_path + "/*png")

            # Filter ignore images
            try:
                def add_gallery_path(index):
                    return "{0}/{1}".format(gallery_path, index)

                exclude_path = os.path.join(gallery_path, "exclude.meta")
                try:
                    f = open(exclude_path, 'r')
                    excluded_image_name_list = f.read().split()
                except IOError:
                    excluded_image_name_list = []

                excluded_image_list = list(map(add_gallery_path,
                                               excluded_image_name_list))
                image_set = set(image_list) - set(excluded_image_list)
                image_list = list(image_set)
            except IOError:
                pass

            # List of sub-galleries
            folder_list = [x.split(os.sep)[-2] for x in
                           glob.glob(os.path.join(gallery_path, '*') + os.sep)]

            crumbs = utils.get_crumbs(gallery_path)

            image_list = [x for x in image_list if "thumbnail" not in x]
            # Sort by date
            image_list.sort(key=lambda a: self.image_date(a))
            image_name_list = [os.path.basename(x) for x in image_list]
            thumbs = []
            # Do thumbnails and copy originals
            for img, img_name in list(zip(image_list, image_name_list)):
                # img is "galleries/name/image_name.jpg"
                # img_name is "image_name.jpg"
                # fname, ext are "image_name", ".jpg"
                fname, ext = os.path.splitext(img_name)
                # thumb_path is
                # "output/GALLERY_PATH/name/image_name.thumbnail.jpg"
                thumb_path = os.path.join(output_gallery,
                                          ".thumbnail".join([fname, ext]))
                # thumb_path is "output/GALLERY_PATH/name/image_name.jpg"
                orig_dest_path = os.path.join(output_gallery, img_name)
                thumbs.append(os.path.basename(thumb_path))
                yield {
                    'basename': str('render_galleries'),
                    'name': thumb_path,
                    'file_dep': [img],
                    'targets': [thumb_path],
                    'actions': [
                        (self.resize_image,
                            (img, thumb_path, kw['thumbnail_size']))
                    ],
                    'clean': True,
                    'uptodate': [utils.config_changed(kw)],
                }
                yield {
                    'basename': str('render_galleries'),
                    'name': orig_dest_path,
                    'file_dep': [img],
                    'targets': [orig_dest_path],
                    'actions': [
                        (self.resize_image,
                            (img, orig_dest_path, kw['max_image_size']))
                    ],
                    'clean': True,
                    'uptodate': [utils.config_changed(kw)],
                }

            # Remove excluded images
            if excluded_image_name_list:
                for img, img_name in zip(excluded_image_list,
                                         excluded_image_name_list):
                    # img_name is "image_name.jpg"
                    # fname, ext are "image_name", ".jpg"
                    fname, ext = os.path.splitext(img_name)
                    excluded_thumb_dest_path = os.path.join(
                        output_gallery, ".thumbnail".join([fname, ext]))
                    excluded_dest_path = os.path.join(output_gallery, img_name)
                    yield {
                        'basename': str('render_galleries_clean'),
                        'name': excluded_thumb_dest_path,
                        'file_dep': [exclude_path],
                        #'targets': [excluded_thumb_dest_path],
                        'actions': [
                            (utils.remove_file, (excluded_thumb_dest_path,))
                        ],
                        'clean': True,
                        'uptodate': [utils.config_changed(kw)],
                    }
                    yield {
                        'basename': str('render_galleries_clean'),
                        'name': excluded_dest_path,
                        'file_dep': [exclude_path],
                        #'targets': [excluded_dest_path],
                        'actions': [
                            (utils.remove_file, (excluded_dest_path,))
                        ],
                        'clean': True,
                        'uptodate': [utils.config_changed(kw)],
                    }

            context = {}
            context["lang"] = kw["default_lang"]
            context["title"] = os.path.basename(gallery_path)
            context["description"] = kw["blog_description"]
            if kw['use_filename_as_title']:
                img_titles = ['id="{0}" alt="{1}" title="{2}"'.format(
                    fn[:-4], fn[:-4], utils.unslugify(fn[:-4])) for fn
                    in image_name_list]
            else:
                img_titles = [''] * len(image_name_list)
            context["images"] = list(zip(image_name_list, thumbs, img_titles))
            context["folders"] = folder_list
            context["crumbs"] = crumbs
            context["permalink"] = self.site.link(
                "gallery", gallery_name, None)
            context["enable_comments"] = (
                self.site.config["COMMENTS_IN_GALLERIES"])

            # Use galleries/name/index.txt to generate a blurb for
            # the gallery, if it exists
            index_path = os.path.join(gallery_path, "index.txt")
            cache_dir = os.path.join(kw["cache_folder"], 'galleries')
            if not os.path.isdir(cache_dir):
                os.makedirs(cache_dir)
            index_dst_path = os.path.join(
                cache_dir,
                str(hashlib.sha224(index_path.encode('utf-8')).hexdigest() +
                    '.html'))
            if os.path.exists(index_path):
                compile_html = self.site.get_compiler(index_path).compile_html
                yield {
                    'basename': str('render_galleries'),
                    'name': index_dst_path,
                    'file_dep': [index_path],
                    'targets': [index_dst_path],
                    'actions': [(compile_html, [index_path, index_dst_path])],
                    'clean': True,
                    'uptodate': [utils.config_changed(kw)],
                }

            file_dep = self.site.template_system.template_deps(
                template_name) + image_list

            def render_gallery(output_name, context, index_dst_path):
                if os.path.exists(index_dst_path):
                    with codecs.open(index_dst_path, "rb", "utf8") as fd:
                        context['text'] = fd.read()
                    file_dep.append(index_dst_path)
                else:
                    context['text'] = ''
                self.site.render_template(template_name, output_name, context)

            yield {
                'basename': str('render_galleries'),
                'name': output_name,
                'file_dep': file_dep,
                'targets': [output_name],
                'actions': [(render_gallery, (output_name, context,
                                              index_dst_path))],
                'clean': True,
                'uptodate': [utils.config_changed({
                    1: kw,
                    2: self.site.config['GLOBAL_CONTEXT'],
                    3: self.site.config["COMMENTS_IN_GALLERIES"],
                })],
            }

    def resize_image(self, src, dst, max_size):
        """Make a copy of the image in the requested size."""
        if not Image:
            utils.copy_file(src, dst)
            return
        im = Image.open(src)
        w, h = im.size
        if w > max_size or h > max_size:
            size = max_size, max_size
            try:
                exif = im._getexif()
            except Exception:
                exif = None
            if exif is not None:
                for tag, value in list(exif.items()):
                    decoded = ExifTags.TAGS.get(tag, tag)

                    if decoded == 'Orientation':
                        if value == 3:
                            im = im.rotate(180)
                        elif value == 6:
                            im = im.rotate(270)
                        elif value == 8:
                            im = im.rotate(90)

                        break

            try:
                im.thumbnail(size, Image.ANTIALIAS)
            except Exception:
                # TODO: inform the user, but do not fail
                pass
            else:
                im.save(dst)

        else:
            utils.copy_file(src, dst)

    def image_date(self, src):
        """Try to figure out the date of the image."""
        if src not in self.dates:
            try:
                im = Image.open(src)
                exif = im._getexif()
            except Exception:
                exif = None
            if exif is not None:
                for tag, value in list(exif.items()):
                    decoded = ExifTags.TAGS.get(tag, tag)
                    if decoded == 'DateTimeOriginal':
                        try:
                            self.dates[src] = datetime.datetime.strptime(
                                value, r'%Y:%m:%d %H:%M:%S')
                            break
                        except ValueError:  # Invalid EXIF date.
                            pass
        if src not in self.dates:
            self.dates[src] = datetime.datetime.fromtimestamp(
                os.stat(src).st_mtime)
        return self.dates[src]


text:
'use strict';

const common = require('./components/common');
const logger = require('./components/logger');
const server = require('./components/server');
const db = require('./components/db');
module.exports = Object.assign({}, common, logger, server, db);


text:
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.0.xsd">
    <changeSet id="change_176" author="luke">
        <comment>Config variable management</comment>
        <sqlFile path="db/scripts/script_176_locations_municipalities.sql" splitStatements="false"/>
        <rollback>
            <sqlFile path="db/scripts/script_176_rollback.sql"/>
        </rollback>
    </changeSet>
</databaseChangeLog>


text:
- switch to new api url

## 0.0.7

- add balance api (retrieve)

## 0.0.1

- Initial version, created by Stagehand


text:
require "core/editors/level_editor/level_editor"

function init()
	Device.enable_resource_autoload(true)
	LevelEditor:init()
end

function update(dt)
	LevelEditor:update(dt)
end

function render(dt)
	LevelEditor:render(dt)
end

function shutdown()
	LevelEditor:shutdown()
end


text:
package org.jtheque.films.view.impl.models.able;

import org.jtheque.core.managers.view.able.components.IModel;

import java.util.Collection;

/**
 * @author Baptiste Wicht
 */
public interface IAutoImportFilm extends IModel {
    /**
     * Return the results of the search.
     *
     * @return A list of the results of the search.
     */
    Collection<String> getTitles();

    /**
     * Set the results of the search.
     *
     * @param titles The results to set.
     */
    void setTitles(Collection<String> titles);
}


text:
//-----------------------------------------------------------------------
// <copyright file="ReplicatorPruningSpec.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using Akka.Actor;
using Akka.Cluster;
using Akka.Cluster.TestKit;
using Akka.Configuration;
using Akka.Remote.TestKit;
using Akka.TestKit;
using Akka.Util.Internal;
using FluentAssertions;

namespace Akka.DistributedData.Tests.MultiNode
{
    public class ReplicatorPruningSpec : MultiNodeClusterSpec
    {
        public static readonly RoleName First = new RoleName("first");
        public static readonly RoleName Second = new RoleName("second");
        public static readonly RoleName Third = new RoleName("third");

        private readonly Cluster.Cluster _cluster;
        private readonly TimeSpan _maxPruningDissemination = TimeSpan.FromSeconds(3);
        private readonly IActorRef _replicator;
        private readonly TimeSpan _timeout;

        private readonly GCounterKey KeyA = new GCounterKey("A");
        private readonly ORSetKey<string> KeyB = new ORSetKey<string>("B");
        private readonly PNCounterDictionaryKey<string> KeyC = new PNCounterDictionaryKey<string>("C");

        public ReplicatorPruningSpec() : this(new ReplicatorPruningSpecConfig()) { }

        protected ReplicatorPruningSpec(ReplicatorPruningSpecConfig config) : base(config, typeof(ReplicatorPruningSpec))
        {
            _cluster = Akka.Cluster.Cluster.Get(Sys);
            _timeout = Dilated(TimeSpan.FromSeconds(3));
            _replicator = Sys.ActorOf(Replicator.Props(ReplicatorSettings.Create(Sys)
                .WithGossipInterval(TimeSpan.FromSeconds(1))
                .WithPruning(pruningInterval: TimeSpan.FromSeconds(1), maxPruningDissemination: _maxPruningDissemination)),
                "replicator");
        }

        [MultiNodeFact(Skip="FIXME")]
        public void Test()
        {
            Pruning_of_CRDT_should_move_data_from_removed_node();
        }

        private void Pruning_of_CRDT_should_move_data_from_removed_node()
        {
            Join(First, First);
            Join(Second, First);
            Join(Third, First);

            Within(TimeSpan.FromSeconds(5), () =>
            {
                AwaitAssert(() =>
                {
                    _replicator.Tell(Dsl.GetReplicaCount);
                    ExpectMsg(new ReplicaCount(3));
                });
            });

            // we need the UniqueAddress
            var memberProbe = CreateTestProbe();
            _cluster.Subscribe(memberProbe.Ref, ClusterEvent.SubscriptionInitialStateMode.InitialStateAsEvents, typeof(ClusterEvent.MemberUp));
            var thirdUniqueAddress = memberProbe.FishForMessage(msg =>
                msg is ClusterEvent.MemberUp && ((ClusterEvent.MemberUp)msg).Member.Address == Node(Third).Address)
                .AsInstanceOf<ClusterEvent.MemberUp>().Member.UniqueAddress;

            _replicator.Tell(Dsl.Update(KeyA, GCounter.Empty, new WriteAll(_timeout), x => x.Increment(_cluster, 3)));
            ExpectMsg(new UpdateSuccess(KeyA, null));

            _replicator.Tell(Dsl.Update(KeyB, ORSet<string>.Empty, new WriteAll(_timeout), x => x
                .Add(_cluster, "a")
                .Add(_cluster, "b")
                .Add(_cluster, "c")));
            ExpectMsg(new UpdateSuccess(KeyB, null));

            _replicator.Tell(Dsl.Update(KeyC, PNCounterDictionary<string>.Empty, new WriteAll(_timeout), x => x
                .Increment(_cluster, "x")
                .Increment(_cluster, "y")));
            ExpectMsg(new UpdateSuccess(KeyC, null));

            EnterBarrier("udpates-done");

            _replicator.Tell(Dsl.Get(KeyA, ReadLocal.Instance));
            var oldCounter = ExpectMsg<GetSuccess>().Get(KeyA);
            oldCounter.Value.Should().Be(9);

            _replicator.Tell(Dsl.Get(KeyB, ReadLocal.Instance));
            var oldSet = ExpectMsg<GetSuccess>().Get(KeyB);
            oldSet.Elements.Should().BeEquivalentTo(new[] { "c", "b", "a" });

            _replicator.Tell(Dsl.Get(KeyC, ReadLocal.Instance));
            var oldMap = ExpectMsg<GetSuccess>().Get(KeyC);
            oldMap["x"].Should().Be(3);
            oldMap["y"].Should().Be(3);

            EnterBarrier("get-old");

            RunOn(() => _cluster.Leave(Node(Third).Address), First);

            RunOn(() =>
            {
                Within(TimeSpan.FromSeconds(15), () => AwaitAssert(() =>
                {
                    _replicator.Tell(Dsl.GetReplicaCount);
                    ExpectMsg(new ReplicaCount(2));
                }));
            }, First, Second);

            EnterBarrier("third-removed");

            RunOn(() =>
            {
                Within(TimeSpan.FromSeconds(15), () =>
                {
                    AwaitAssert(() =>
                    {
                        _replicator.Tell(Dsl.Get(KeyA, ReadLocal.Instance));
                        var counter = ExpectMsg<GetSuccess>(msg => Equals(msg.Key, KeyA)).Get(KeyA);
                        counter.Value.ShouldBe(9UL);
                        counter.NeedPruningFrom(thirdUniqueAddress).Should().BeFalse($"{counter} shouldn't need prunning from {thirdUniqueAddress}");
                    });
                });

                Within(TimeSpan.FromSeconds(5), () =>
                {
                    AwaitAssert(() =>
                    {
                        _replicator.Tell(Dsl.Get(KeyB, ReadLocal.Instance));
                        var set = ExpectMsg<GetSuccess>(msg => Equals(msg.Key, KeyB)).Get(KeyB);
                        set.Elements.Should().BeEquivalentTo(new[] { "c", "b", "a" });
                        set.NeedPruningFrom(thirdUniqueAddress).Should().BeFalse($"{set} shouldn't need pruning from {thirdUniqueAddress}");
                    });
                });

                Within(TimeSpan.FromSeconds(5), () =>
                {
                    AwaitAssert(() =>
                    {
                        _replicator.Tell(Dsl.Get(KeyC, ReadLocal.Instance));
                        var map = ExpectMsg<GetSuccess>(msg => Equals(msg.Key, KeyC)).Get(KeyC);
                        map["x"].Should().Be(3);
                        map["y"].Should().Be(3);
                        map.NeedPruningFrom(thirdUniqueAddress).Should().BeFalse($"{map} shouldn't need pruning from {thirdUniqueAddress}");
                    });
                });
            }, First, Second);

            EnterBarrier("pruning-done");

            RunOn(() => UpdateAfterPruning(expectedValue: 10), First);
            EnterBarrier("update-first-after-pruning");

            RunOn(() => UpdateAfterPruning(expectedValue: 11), Second);
            EnterBarrier("update-second-after-pruning");

            // after pruning performed and maxDissemination it is tombstoned
            // and we should still not be able to update with data from removed node
            ExpectNoMsg(_maxPruningDissemination.Add(TimeSpan.FromSeconds(3)));

            RunOn(() => UpdateAfterPruning(expectedValue: 12), First);
            EnterBarrier("update-first-after-tombstone");

            RunOn(() => UpdateAfterPruning(expectedValue: 13), Second);
            EnterBarrier("update-second-after-tombstone");

            EnterBarrier("after-1");
        }

        protected override int InitialParticipantsValueFactory => Roles.Count;

        /// <summary>
        /// On one of the nodes the data has been updated by the pruning, client can update anyway
        /// </summary>
        private void UpdateAfterPruning(ulong expectedValue)
        {
            _replicator.Tell(Dsl.Update(KeyA, GCounter.Empty, new WriteAll(_timeout), x => x.Increment(_cluster, 1)));
            ExpectMsg<UpdateSuccess>(msg =>
            {
                _replicator.Tell(Dsl.Get(KeyA, ReadLocal.Instance));
                var retrieved = ExpectMsg<GetSuccess>().Get(KeyA);
                retrieved.Value.Should().Be(expectedValue);
            });
        }

        private void Join(RoleName from, RoleName to)
        {
            RunOn(() => _cluster.Join(Node(to).Address), from);
            EnterBarrier(from.Name + "-joined");
        }
    }

    public class ReplicatorPruningSpecConfig : MultiNodeConfig
    {
        public RoleName First { get; }
        public RoleName Second { get; }
        public RoleName Third { get; }
        public ReplicatorPruningSpecConfig()
        {
            First = Role("first");
            Second = Role("second");
            Third = Role("third");

            CommonConfig = ConfigurationFactory.ParseString(@"
                akka.loglevel = INFO
                akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster""
                akka.log-dead-letters-during-shutdown = off")
                .WithFallback(DistributedData.DefaultConfig());
        }
    }
}


text:
/**
 * @file   server.h
 * @brief  server node apis
 */
#pragma once
#include <memory>
#include "ps/base.h"
#include "ps/blob.h"
#include "proto/task.pb.h"
#include "kv/kv_store_sparse.h"
#include "kv/kv_store_sparse_st.h"
// #include "kv/kv_store_cuckoo.h"
namespace ps {

/**
 * @brief An example of the user-defined value for \ref OnlineServer
 *
 * The constructor function is called when the according key does not
 * exist. This class must be copyable and assignable (movable), which are only
 * called once with the constructor function, e.g. ``std::unordered_map::insert(IVal<Val>())``. It
 * also must implement the following three functions \ref Load, \ref Save and
 * \ref Empty
 */
template <typename Val>
struct IVal {

  /// \brief value
  Val w = 0;

  /// \brief Load from disk
  inline void Load(dmlc::Stream *fi) { fi->Read(&w, sizeof(Val)); }

  /// \brief Save to disk
  inline void Save(dmlc::Stream *fo) const { fo->Write(&w, sizeof(Val)); }

  /// \brief Return true if this value can be skipped from saving to disk
  inline bool Empty() const { return w == 0; }
};

/**
 * \brief An example of user-defined handle for \ref OnlineServer
 *
 * Assume OnlineServer stores the KV pairs in `map<Key, Val> store_`. It
 * processes a push request with \a keys and \a vals as following
 *
 * \code
 * handle_.Start(true, ...);
 * for (k : keys) handle_.Push(k, vals[k], store_[k]);
 * handle_.Finish();
 * \endcode
 *
 * A server node processes one request (either push or pull) at a time, the
 * above codes can be almost treated as a transaction. But the middle for loop
 * may run in parallel with the number of threads specified in \ref
 * OnlineServer.
 *
 * The procedure for a pull request is similar.
 *
 * \code
 * handle_.Start(true, ...);
 * for (k : keys) {
 *   handle_.Pull(k, store_[k], v);
 *   vals.push_back(v);
 * }
 * handle_.Finish();
 * // send back vals
 * \endcode
 *
 * \a v consists of a `SyncVal` pointer `v.data` with length `v.size =
 * pull_val_len`. One can reuse this buffer is if the actually value length for
 * sending is not larger than `v.size` (change `v.size` if less than). One can
 * also modify `v.data`, the system will `memcpy` it to it's internal
 * buffer. A sample usage:
 *
 * \code
 * struct MyVal { std::vector<Val> w; }
 * void Pull(Key recv_key, MyVal& my_val, ps::Blob<Val>& send_val) {
 *   send_val.data = my_val.w.data();
 *   send_val.size = my_val.w.size();
 * }
 * \endcode
 */
template <typename SyncV>
class IOnlineHandle {
 public:
  IOnlineHandle() { }
  virtual ~IOnlineHandle() { }

  /**
   * \brief Start to handle a request from a worker
   *
   * @param push true if this is a push request
   * @param timestamp the timestamp of this request
   * @param cmd the cmd specified in \ref SyncOpts
   * @param msg the received message
   */
  inline void Start(bool push, int timestamp, int cmd, void* msg) { }

  /**
   * \brief The request has been handled
   */
  inline void Finish() { }

  /**
   * \brief Handle a push request from a worker node
   *
   * @param recv_key the key received from a worker node
   * @param recv_vals the corresponding values received from the worker node
   * @param my_vals the corresponding local stored value
   */
  inline void Push(
      Key recv_key, Blob<const SyncV> recv_val, IVal<SyncV>& my_val) {
    for (const SyncV& v : recv_val) my_val.w += v;
  }

  /**
   * \brief Handle a pull requests from a worker node
   *
   * @param recv_key the key received from a worker node
   * @param my_vals the corresponding local value
   * @param sent_vals the corresponding values will send to the worker node
   */
  inline void Pull(
      Key recv_key, const IVal<SyncV>& my_val, Blob<SyncV>& send_val) {
    for (SyncV& v : send_val) v = my_val.w;
  }

  /** \brief Load from disk */
  inline void Load(dmlc::Stream *fi) { }

  /** \brief Save to disk */
  inline void Save(dmlc::Stream *fo) const { }
};

/**
 * \brief The online key-value store for server nodes
 *
 * A server node maintains KV pairs in a particular key range, and responses the
 * push and pull requests from worker nodes. It allows user-defined value type
 * and handle.
 *
 * @tparam SyncV the value type used for synchronization, which should be
 * primitive types such as int, float. It should by the same as the value type
 * defined in \ref ps::KVWorker
 * @tparam Val the value type stored in server, which could be a
 * user-defined type, see \ref IVal for more details
 * @tparam Handle User-defined handle for processing push and pull request from
 * workers, see \ref IOnlineHandle for more details
 */
template <typename SyncV,
          typename Val = IVal<SyncV>,
          typename Handle = IOnlineHandle<SyncV> >
class OnlineServer {
 public:
  /**
   * \brief Creates a KV store.
   *
   * @param handle the user-defined handle
   * @param pull_val_len the hint of the length of value pulled from server for each
   * key.
   * @param num_threads the number of threads can be used to process a worker
   * request
   * @param id the unique identity. It should match the according id of \ref
   * KVWorker
   */
  OnlineServer(const Handle& handle = Handle(),
               int pull_val_len = 1,
               int num_threads = 1,
               int id = NextID()) {
    if (num_threads == 1) {
      server_ = new KVStoreSparseST<Key, Val, SyncV, Handle>(
          id, handle, pull_val_len);
    } else {
      server_ = new KVStoreSparse<Key, Val, SyncV, Handle>(
          id, handle, pull_val_len, num_threads);
    }
    // server_ = new KVStoreCuckoo<Key, Val, SyncV, Handle>(
    //     id, handle, pull_val_len, num_threads);
    Postoffice::instance().manager().TransferCustomer(CHECK_NOTNULL(server_));
  }

  ~OnlineServer() { }

  /// \brief Returns the pointer of the actual KV store
  KVStore* server() { return server_; }

 private:
  KVStore* server_ = NULL;
};

}  // namespace ps

/**
 * \brief The main function for a server node
 *
 * All flags and their arguments (e.g. -logtostderr 1) has been parsed and
 * removed from argc and argv, but commandline arguments are remained such as
 * data=my_data.txt
 */
int CreateServerNode(int argc, char *argv[]);