text:
package com.micronautics.aws

import com.amazonaws.auth.AWSCredentials
import com.amazonaws.services.cloudfront.{AmazonCloudFront, AmazonCloudFrontClientBuilder}
import com.amazonaws.services.cloudfront.model._
import com.micronautics.cache.{Memoizer, Memoizer0, Memoizer2}
import java.util.concurrent.atomic.AtomicBoolean
import scala.jdk.CollectionConverters._
import scala.collection.mutable
import scala.util.{Failure, Success, Try}

object CloudFront {
  val oneMinute: Long = 1L * 60L * 1000L

  def apply: CloudFront = new CloudFront
}

class CloudFront extends CFImplicits with S3Implicits {
  import CloudFront._
  import com.amazonaws.services.s3.model.Bucket

  implicit val cf: CloudFront = this
  implicit val cfClient: AmazonCloudFront = AmazonCloudFrontClientBuilder.standard.build

  val cacheIsDirty = new AtomicBoolean(false)

  protected val _distributions: Memoizer0[List[DistributionSummary]] =
    Memoizer(cfClient.listDistributions(new ListDistributionsRequest).getDistributionList.getItems.asScala.toList)

  val distributions: List[DistributionSummary] = _distributions.apply

  protected val _bucketNamesWithDistributions: Memoizer0[List[String]] =
    Memoizer(
      for {
        distribution <- distributions
        item         <- distribution.getOrigins.getItems.asScala // value: s"S3-$lcBucketName"
      } yield item.getId.substring(3)
    )

  /** @return List of bucket names that have CloudFront distributions for this AWS account */
  // id.getDomainName value: s"$lcBucketName.s3.amazonaws.com"
  val bucketNamesWithDistributions: List[String] =
    _bucketNamesWithDistributions.apply

  protected val _bucketsWithDistributions: Memoizer[S3, List[Bucket]] = Memoizer( s3 =>
    for {
      bucketName <- bucketNamesWithDistributions
      bucket     <- s3.findByName(bucketName).toList
    } yield bucket
  )

  def bucketsWithDistributions(implicit s3: S3): List[Bucket] =
    _bucketsWithDistributions(s3)

  /** @return List of CloudFront distributions for the specified bucket */
  protected val _distributionsFor: Memoizer2[Bucket, S3, List[DistributionSummary]] =
    Memoizer { (bucket, s3) =>
      val (_, bucketOriginId) = RichBucket(bucket)(s3).safeNames
      val distributionSummaries: List[DistributionSummary] = distributions.filter { distribution =>
        val origins: mutable.Seq[Origin] = distribution.getOrigins.getItems.asScala
        origins.exists(_.getId == bucketOriginId)
      }
      distributionSummaries
    }

  def distributionsFor(bucket: Bucket)
                      (implicit s3: S3): List[DistributionSummary] =
    _distributionsFor.apply(bucket, s3)

  def clearCaches(): Unit = {
    _bucketNamesWithDistributions.clear()
    _bucketsWithDistributions.clear()
    _distributions.clear()
    _distributionsFor.clear()
    cacheIsDirty.set(false)
  }

  /** Enable/disable all distributions for the given bucketName
    * @return list of UpdateDistributionResult for distributions that were enabled */
  def enableAllDistributions(bucket: Bucket, newStatus: Boolean=true)
                            (implicit s3: S3): List[UpdateDistributionResult] = {
    val distributions: List[DistributionSummary] = distributionsFor(bucket)
    distributions.flatMap { implicit distributionSummary =>
      val configResult: GetDistributionConfigResult = distributionSummary.configResult
      if (!configResult.getDistributionConfig.getEnabled) {
        configResult.getDistributionConfig.setEnabled(newStatus)
        val distributionETag = configResult.getETag // Is this in the proper sequence?
        val updateRequest = new UpdateDistributionRequest(configResult.getDistributionConfig, distributionSummary.getId, distributionETag)
        val result = cfClient.updateDistribution(updateRequest)
        cacheIsDirty.set(true)
        Some(result)
      } else None
    }
  }

  /** Enable/disable the most recently created distribution for the given bucketName
    * @return Some(UpdateDistributionResult) if distributions was enabled, else None */
  def enableLastDistribution(bucket: Bucket, newStatus: Boolean=true)
                            (implicit s3: S3): Option[UpdateDistributionResult] = {
    val distributions: Seq[DistributionSummary] = distributionsFor(bucket)
    distributions.lastOption.flatMap { implicit distributionSummary =>
      val configResult: GetDistributionConfigResult = distributionSummary.configResult
      if (!configResult.getDistributionConfig.getEnabled) {
        configResult.getDistributionConfig.setEnabled(newStatus)
        val distributionETag = configResult.getETag // Is this in the proper sequence?
        val updateRequest = new UpdateDistributionRequest(configResult.getDistributionConfig, distributionSummary.getId, distributionETag)
        val result = cfClient.updateDistribution(updateRequest)
        cacheIsDirty.set(true)
        Some(result)
      } else None
    }
  }

  /** Invalidate asset in all bucket distributions where it is present.
    * @param assetPath The path of the objects to invalidate, relative to the distribution and must begin with a slash (/).
    *                  If the path is a directory, all assets within in are invalidated
    * @return number of asset invalidations */
  def invalidate(bucket: Bucket, assetPath: String)
                (implicit s3: S3): Int =
    invalidateMany(bucket, List(assetPath))

  /** Invalidate asset in all bucket distributions where it is present.
    * @param assetPaths The path of the objects to invalidate, relative to the distribution and must begin with a slash (/).
    *                   If the path is a directory, all assets within in are invalidated
    * @return number of asset invalidations
    * @see http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/cloudfront/model/InvalidationBatch.html#InvalidationBatch(com.amazonaws.services.cloudfront.model.Paths,%20java.lang.String) */
  def invalidateMany(bucket: Bucket, assetPaths: List[String])(implicit s3: S3): Int = {
    val foundAssets: List[String] = assetPaths.filter(bucket.oneObjectData(_).isDefined)
    val foundPaths: Paths = new Paths().withItems(foundAssets.asJava).withQuantity(foundAssets.size)
    val counts: List[Int] = distributionsFor(bucket) map { distributionSummary =>
      import com.amazonaws.services.cloudfront.model.CreateInvalidationRequest
      val invalidationBatch = new InvalidationBatch(foundPaths, uuid)
      // distributionSummary.getId returns distribution.getId
      cfClient.createInvalidation(new CreateInvalidationRequest().withDistributionId(distributionSummary.getId).withInvalidationBatch(invalidationBatch))
      1
    }
    val sum = counts.sum
    if (sum>0) cacheIsDirty.set(true)
    sum
  }

  /** Remove the most recently created distribution for the given bucketName.
    * Can take 15 minutes to an hour to return. */
  def removeDistribution(bucket: Bucket)
                        (implicit s3: S3): Boolean =
    distributionsFor(bucket).lastOption.exists { implicit distSummary =>
      val distConfigResult = cfClient.getDistributionConfig(new GetDistributionConfigRequest().withId(distSummary.getId))
      val result = distSummary.originItems.map { removeOrigin(distSummary, distConfigResult, _) }.forall { _.isSuccess }
      if (result) cacheIsDirty.set(true)
      result
    }

  def removeOrigin(distSummary: DistributionSummary, distConfigResult: GetDistributionConfigResult, origin: Origin): Try[Boolean] = {
    val domainName: String = origin.getDomainName
    val distributionETag: String = distConfigResult.getETag
    val config: DistributionConfig = distConfigResult.getDistributionConfig
    // The explanation of how to find the eTag is wrong in the docs: http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/DeleteDistribution.html
    // I think the correct explanation is that the eTag from the most recent GET or PUT operation is what is actually required
    val eTag = if (distConfigResult.getDistributionConfig.getEnabled) {
      Logger.debug(s"Disabling distribution of $domainName with id $$distributionId and ETag $distributionETag")
      config.setEnabled(false)
      Logger.debug(s"Distribution config after disabling=${ jsonPrettyPrint(config) }")
      val updateRequest = new UpdateDistributionRequest(config, distSummary.getId, distributionETag)
      val updateResult: UpdateDistributionResult = cfClient.updateDistribution(updateRequest)
      val updateETag = updateResult.getETag
      Logger.debug(s"Update result ETag = $updateETag; enabled=${ distSummary.enabled }; status=${ distSummary.status }")
      var i = 1
      while (distSummary.status == "InProgress") {
        Thread.sleep(oneMinute) // TODO don't tie up a thread like this
        Logger.debug(s"  $i: Distribution enabled=${ distSummary.enabled }; status=InProgress")
        i = i + 1
      }
      updateETag
    } else {
      Logger.debug(s"Distribution of $domainName with id ${ distSummary.getId } and ETag $distributionETag was already disabled.")
      distributionETag
    }
    // Fails with: Distribution of scalacoursesdemo.s3.amazonaws.com with id E1ALVO6LY3X3XE and ETag E21ZQTZDDOETEA:
    // The distribution you are trying to delete has not been disabled.
    try {
      Logger.debug(s"Deleting distribution of $domainName with id ${ distSummary.getId } and ETag $eTag.")
      distSummary.delete(eTag)
      cacheIsDirty.set(true)
      Success(true)
    } catch {
      case nsde: NoSuchDistributionException =>
        Failure(nsde.prefixMsg(s"Distribution of $domainName with id ${ distSummary.getId } and ETag $distributionETag does not exist"))

      case e: Exception =>
        Failure(e.prefixMsg(s"Distribution of $domainName with id ${ distSummary.getId } and ETag $distributionETag: ${e.getMessage}"))
    }
  }

  def tryConfig(id: String): Try[DistributionConfig] = findDistributionById(id).map(_.getDistributionConfig)

  def findDistributionById(id: String): Try[Distribution] = try {
    Success(cfClient.getDistribution(new GetDistributionRequest().withId(id)).getDistribution)
  } catch {
    case nsde: NoSuchDistributionException =>
      Failure(nsde.prefixMsg(s"Distribution with id $id does not exist"))

    case e: Exception =>
      Failure(e.prefixMsg(s"Distribution of with id $id: ${ e.getMessage }"))
  }
}

trait CFImplicits {
  import com.amazonaws.services.s3.model.Bucket

  object RichDistribution {
    var minimumCacheTime: Long = 60 * 60 // one hour

    /** Create a new distribution for the given S3 bucket */
    def apply(
       bucket: Bucket,
       priceClass: PriceClass=PriceClass.PriceClass_All,
       minimumCacheTime: Long=minimumCacheTime
     )(implicit
       awsCredentials: AWSCredentials,
       cfClient: AmazonCloudFront,
       s3: S3
    ): Distribution = {
      val (lcBucketName, bucketOriginId) = bucket.safeNames
      val aliases = new Aliases().withQuantity(0)
      val allowedMethods = new AllowedMethods().withItems(Method.GET, Method.HEAD).withQuantity(2)
      val cacheBehaviors = new CacheBehaviors().withQuantity(0)
      val cookiePreference = new CookiePreference().withForward(ItemSelection.All)
      val loggingConfig = new LoggingConfig()
        .withEnabled(false).withIncludeCookies(false)
        .withPrefix("").withBucket("")
      val s3OriginConfig = new S3OriginConfig().withOriginAccessIdentity("")
      val trustedSigners = new TrustedSigners().withEnabled(false).withQuantity(0)
      val forwardedValues = new ForwardedValues()
        .withCookies(cookiePreference)
        .withQueryString(false)
      val defaultCacheBehavior = new DefaultCacheBehavior()
        .withAllowedMethods(allowedMethods)
        .withForwardedValues(forwardedValues)
        .withMinTTL(minimumCacheTime)
        .withTargetOriginId(bucketOriginId)
        .withTrustedSigners(trustedSigners)
        .withViewerProtocolPolicy(ViewerProtocolPolicy.AllowAll)
      val origin = new Origin()
        .withDomainName(s"$lcBucketName.s3.amazonaws.com")
        .withS3OriginConfig(s3OriginConfig)
        .withId(bucketOriginId)
      val items = List(origin).asJava
      val origins = new Origins().withItems(items).withQuantity(items.size)
      val distributionConfig = new DistributionConfig()
        .withAliases(aliases)
        .withCacheBehaviors(cacheBehaviors)
        .withCallerReference(System.nanoTime.toString)
        .withComment("")
        .withDefaultCacheBehavior(defaultCacheBehavior)
        .withDefaultRootObject("index.html")
        .withEnabled(true)
        .withLogging(loggingConfig)
        .withOrigins(origins)
        .withPriceClass(priceClass)
      val cdr = new CreateDistributionRequest().withDistributionConfig(distributionConfig)
      Logger.debug(s"cdr=${jsonPrettyPrint(cdr)}")
      try {
        val result: CreateDistributionResult = cfClient.createDistribution(cdr)
        result.getDistribution
      } catch {
        case nsoe: NoSuchOriginException =>
          throw new Exception(s"Origin with domain name '${ origin.getDomainName }' and id '${ origin.getId }' does not exist", nsoe)
      }
    }
  }

  implicit class RichDistributionSummary(distributionSummary: DistributionSummary)
                                        (implicit cfClient: AmazonCloudFront) {
    def config: DistributionConfig = configResult.getDistributionConfig

    def configResult: GetDistributionConfigResult = {
      val getDistributionConfigRequest = new GetDistributionConfigRequest().withId(distributionSummary.getId)
      cfClient.getDistributionConfig(getDistributionConfigRequest)
    }

    def enabled: Boolean = {
      Logger.debug("Getting enabled from distributionSummary")
      distributionSummary.getEnabled
    }

    def delete(eTag: String): Unit = {
      Logger.debug(s"Deleting distribution with id ${ distributionSummary.getId }")
      val deleteDistributionRequest = new DeleteDistributionRequest().withId(distributionSummary.getId).withIfMatch(eTag)
      Logger.debug(s"deleteDistributionRequest=${ jsonPrettyPrint(deleteDistributionRequest) }")
      cfClient.deleteDistribution(deleteDistributionRequest)
      ()
    }

    def eTag: String = configResult.getETag

    def originItems: List[Origin] = config.getOrigins.getItems.asScala.toList

    def removeOrigin(distConfigResult: GetDistributionConfigResult, origin: Origin)(implicit cf: CloudFront): Try[Boolean] =
      cf.removeOrigin(distributionSummary, distConfigResult, origin)

    def status: String = {
      Logger.debug(s"Getting status from distributionSummary with id ${ distributionSummary.getId }")
      distributionSummary.getStatus
    }
  }
}


text:
Doubles
=======

**Doubles** is a Python package that provides test doubles for use in automated tests.

It provides functionality for stubbing, mocking, and verification of test doubles against the real objects they double. In contrast to the Mock package, it provides a clear, expressive syntax and better safety guarantees to prevent API drift and to improve confidence in tests using doubles. It comes with drop-in support for test suites run by Pytest, Nose, or standard unittest.

.. toctree::
   :maxdepth: 2

   installation
   Integration with test frameworks <integration>
   Differences from Mock <mock>
   terminology
   usage
   api
   faq
   changelog

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

redpajama_set_name: RedPajamaGithub


text:
@class DBMultiPointCurvChartView;

@protocol DBMultiPointCurvDataSource <NSObject>
-(NSArray *)dataSourceOfcurvChartView:(DBMultiPointCurvChartView *)curvChartView ;

@end
@interface DBMultiPointCurvChartView : UIView
@property (nonatomic,weak) id<DBMultiPointCurvDataSource> dataSource;
@property (nonatomic) NSArray *points;
@property (nonatomic) float prevDegree;
@end


text:
#ifndef CVIMAGEWIDGET_H
#define CVIMAGEWIDGET_H

#include <QWidget>
#include <QImage>
#include <QPainter>
#include <opencv2/opencv.hpp>

class CVImageWidget : public QWidget
{
    Q_OBJECT
public:
    explicit CVImageWidget(QWidget *parent = 0) : QWidget(parent) {
        setMouseTracking(true);
    }

    QSize sizeHint() const { return _qimage.size(); }
    QSize minimumSizeHint() const { return _qimage.size(); }

    public slots:

        void showImage(const cv::Mat& image) {

            // Convert the image to the RGB888 format
            switch (image.type()) {
            case CV_8UC1:
                cvtColor(image, _tmp, CV_GRAY2RGB);
                break;
            case CV_8UC3:
                cvtColor(image, _tmp, CV_BGR2RGB);
                break;
            }

            // QImage needs the data to be stored continuously in memory
            assert(_tmp.isContinuous());
            // Assign OpenCV's image buffer to the QImage. Note that the bytesPerLine parameter
            // (http://qt-project.org/doc/qt-4.8/qimage.html#QImage-6) is 3*width because each pixel
            // has three bytes.
            _qimage = QImage(_tmp.data, _tmp.cols, _tmp.rows, _tmp.cols*3, QImage::Format_RGB888);

            this->setFixedSize(image.cols, image.rows);

            repaint();
        }

protected:
    void paintEvent(QPaintEvent* /*event*/) {
        // Display the image
        QPainter painter(this);
        painter.drawImage(QPoint(0,0), _qimage);
        painter.end();
    }
    void mousePressEvent(QMouseEvent* event);

    QImage _qimage;
    cv::Mat _tmp;

};

#endif // CVIMAGEWIDGET_H


text: package flash2


text:
'use strict';

import angular from 'angular';

/* @ngInject */
function HeaderController($scope, $window, $interval, iScrollService,
                          coreLayoutService) {
    $scope.iScrollState = iScrollService.state;
    $scope.toggleIScroll = iScrollService.toggle;

    $scope.toggleDrawer = coreLayoutService.toggleDrawer;

    $scope.demos = [
        {
            state: 'demos.staticList',
            name: 'Static List'
        },
        {
            state: 'demos.ngRepeatList',
            name: 'ngRepeat List'
        },
        {
            state: 'demos.multiColumnDynamic',
            name: 'Multi-column'
        }
    ];

    const promise = $interval(function _checkBrowserSync() {
        $scope.browserSync = !!$window.___browserSync___;
    }, 250);

    $scope.$on('$destroy', function _cleanUp() {
        $interval.cancel(promise);
    });
}

export default angular.module('myApp.header.HeaderController', [])
    .controller('HeaderController', HeaderController)
    .name;


text:
import { Injectable } from '@angular/core';
import { Store, Action } from '@ngrx/store';
import { Effect, Actions, toPayload } from '@ngrx/effects';
import { Observable } from 'rxjs';

import { AuthService } from '../_lib/vegerun';

import { AppState } from '../store';

import {
    AuthState, AuthActions, AUTH_ACTION_NAMES,
    LoginPayload, LoginStartedPayload, LoginCompletedPayload, LoginFailedPayload
} from '../features/auth';

@Injectable()
export class AuthEffects {

    constructor(
        private store: Store<AppState>,
        private authActions: AuthActions,
        private authService: AuthService,
        private actions$: Actions
    ) { }

    @Effect() loginEffect = this.actions$
        .ofType(AUTH_ACTION_NAMES.LOGIN)
        .map<LoginPayload>(toPayload)
        .map(payload => this.authActions.loginStarted(payload.email, payload.password));

    @Effect() loginStartedEffect = this.actions$
        .ofType(AUTH_ACTION_NAMES.LOGIN_STARTED)
        .map<LoginStartedPayload>(toPayload)
        .switchMap(payload => this.authService
            .login(payload.email, payload.password)
            .map(res => this.authActions.loginCompleted(res, payload.email))
            .catch(err => Observable.of(this.authActions.loginFailed(err, payload.email))));

    @Effect({ dispatch: false }) logoutEffect = this.actions$
        .ofType(AUTH_ACTION_NAMES.LOGOUT)
        .do(() => {
            window.location.href = '';
        });
}


text:
        Pitas

            <input type="checkbox">

            {{pita.price | currency:"$"}}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>slickgrid-colfix-plugin example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../bower_components/slickgrid/slick.grid.css" type="text/css" />
    <link rel="stylesheet" href="../bower_components/slickgrid/css/smoothness/jquery-ui-1.8.16.custom.css" type="text/css" />
    <link rel="stylesheet" href="../bower_components/slickgrid/examples/examples.css" type="text/css" />


text:
import * as assert from 'assert';
import * as http2 from 'http2';
import { range } from 'lodash';
import { Metadata, MetadataObject, MetadataValue } from '../src/metadata';

class TestMetadata extends Metadata {
  getInternalRepresentation() {
    return this.internalRepr;
  }

  static fromHttp2Headers(headers: http2.IncomingHttpHeaders): TestMetadata {
    const result = Metadata.fromHttp2Headers(headers) as TestMetadata;
    result.getInternalRepresentation =
      TestMetadata.prototype.getInternalRepresentation;
    return result;
  }
}

const validKeyChars = '0123456789abcdefghijklmnopqrstuvwxyz_-.';
const validNonBinValueChars = range(0x20, 0x7f)
  .map(code => String.fromCharCode(code))
  .join('');

describe('Metadata', () => {
  let metadata: TestMetadata;

  beforeEach(() => {
    metadata = new TestMetadata();
  });

  describe('set', () => {
    it('Only accepts string values for non "-bin" keys', () => {
      assert.throws(() => {
        metadata.set('key', Buffer.from('value'));
      });
      assert.doesNotThrow(() => {
        metadata.set('key', 'value');
      });
    });

    it('Only accepts Buffer values for "-bin" keys', () => {
      assert.throws(() => {
        metadata.set('key-bin', 'value');
      });
      assert.doesNotThrow(() => {
        metadata.set('key-bin', Buffer.from('value'));
      });
    });

    it('Rejects invalid keys', () => {
      assert.doesNotThrow(() => {
        metadata.set(validKeyChars, 'value');
      });
      assert.throws(() => {
        metadata.set('key$', 'value');
      }, /Error: Metadata key "key\$" contains illegal characters/);
      assert.throws(() => {
        metadata.set('', 'value');
      });
    });

    it('Rejects values with non-ASCII characters', () => {
      assert.doesNotThrow(() => {
        metadata.set('key', validNonBinValueChars);
      });
      assert.throws(() => {
        metadata.set('key', 'résumé');
      });
    });

    it('Saves values that can be retrieved', () => {
      metadata.set('key', 'value');
      assert.deepStrictEqual(metadata.get('key'), ['value']);
    });

    it('Overwrites previous values', () => {
      metadata.set('key', 'value1');
      metadata.set('key', 'value2');
      assert.deepStrictEqual(metadata.get('key'), ['value2']);
    });

    it('Normalizes keys', () => {
      metadata.set('Key', 'value1');
      assert.deepStrictEqual(metadata.get('key'), ['value1']);
      metadata.set('KEY', 'value2');
      assert.deepStrictEqual(metadata.get('key'), ['value2']);
    });
  });

  describe('add', () => {
    it('Only accepts string values for non "-bin" keys', () => {
      assert.throws(() => {
        metadata.add('key', Buffer.from('value'));
      });
      assert.doesNotThrow(() => {
        metadata.add('key', 'value');
      });
    });

    it('Only accepts Buffer values for "-bin" keys', () => {
      assert.throws(() => {
        metadata.add('key-bin', 'value');
      });
      assert.doesNotThrow(() => {
        metadata.add('key-bin', Buffer.from('value'));
      });
    });

    it('Rejects invalid keys', () => {
      assert.throws(() => {
        metadata.add('key$', 'value');
      });
      assert.throws(() => {
        metadata.add('', 'value');
      });
    });

    it('Saves values that can be retrieved', () => {
      metadata.add('key', 'value');
      assert.deepStrictEqual(metadata.get('key'), ['value']);
    });

    it('Combines with previous values', () => {
      metadata.add('key', 'value1');
      metadata.add('key', 'value2');
      assert.deepStrictEqual(metadata.get('key'), ['value1', 'value2']);
    });

    it('Normalizes keys', () => {
      metadata.add('Key', 'value1');
      assert.deepStrictEqual(metadata.get('key'), ['value1']);
      metadata.add('KEY', 'value2');
      assert.deepStrictEqual(metadata.get('key'), ['value1', 'value2']);
    });
  });

  describe('remove', () => {
    it('clears values from a key', () => {
      metadata.add('key', 'value');
      metadata.remove('key');
      assert.deepStrictEqual(metadata.get('key'), []);
    });

    it('Normalizes keys', () => {
      metadata.add('key', 'value');
      metadata.remove('KEY');
      assert.deepStrictEqual(metadata.get('key'), []);
    });
  });

  describe('get', () => {
    beforeEach(() => {
      metadata.add('key', 'value1');
      metadata.add('key', 'value2');
      metadata.add('key-bin', Buffer.from('value'));
    });

    it('gets all values associated with a key', () => {
      assert.deepStrictEqual(metadata.get('key'), ['value1', 'value2']);
    });

    it('Normalizes keys', () => {
      assert.deepStrictEqual(metadata.get('KEY'), ['value1', 'value2']);
    });

    it('returns an empty list for non-existent keys', () => {
      assert.deepStrictEqual(metadata.get('non-existent-key'), []);
    });

    it('returns Buffers for "-bin" keys', () => {
      assert.ok(metadata.get('key-bin')[0] instanceof Buffer);
    });
  });

  describe('getMap', () => {
    it('gets a map of keys to values', () => {
      metadata.add('key1', 'value1');
      metadata.add('Key2', 'value2');
      metadata.add('KEY3', 'value3a');
      metadata.add('KEY3', 'value3b');
      assert.deepStrictEqual(metadata.getMap(), {
        key1: 'value1',
        key2: 'value2',
        key3: 'value3a',
      });
    });
  });

  describe('clone', () => {
    it('retains values from the original', () => {
      metadata.add('key', 'value');
      const copy = metadata.clone();
      assert.deepStrictEqual(copy.get('key'), ['value']);
    });

    it('Does not see newly added values', () => {
      metadata.add('key', 'value1');
      const copy = metadata.clone();
      metadata.add('key', 'value2');
      assert.deepStrictEqual(copy.get('key'), ['value1']);
    });

    it('Does not add new values to the original', () => {
      metadata.add('key', 'value1');
      const copy = metadata.clone();
      copy.add('key', 'value2');
      assert.deepStrictEqual(metadata.get('key'), ['value1']);
    });

    it('Copy cannot modify binary values in the original', () => {
      const buf = Buffer.from('value-bin');
      metadata.add('key-bin', buf);
      const copy = metadata.clone();
      const copyBuf = copy.get('key-bin')[0] as Buffer;
      assert.deepStrictEqual(copyBuf, buf);
      copyBuf.fill(0);
      assert.notDeepStrictEqual(copyBuf, buf);
    });
  });

  describe('merge', () => {
    it('appends values from a given metadata object', () => {
      metadata.add('key1', 'value1');
      metadata.add('Key2', 'value2a');
      metadata.add('KEY3', 'value3a');
      metadata.add('key4', 'value4');
      const metadata2 = new TestMetadata();
      metadata2.add('KEY1', 'value1');
      metadata2.add('key2', 'value2b');
      metadata2.add('key3', 'value3b');
      metadata2.add('key5', 'value5a');
      metadata2.add('key5', 'value5b');
      const metadata2IR = metadata2.getInternalRepresentation();
      metadata.merge(metadata2);
      // Ensure metadata2 didn't change
      assert.deepStrictEqual(
        metadata2.getInternalRepresentation(),
        metadata2IR
      );
      assert.deepStrictEqual(metadata.get('key1'), ['value1', 'value1']);
      assert.deepStrictEqual(metadata.get('key2'), ['value2a', 'value2b']);
      assert.deepStrictEqual(metadata.get('key3'), ['value3a', 'value3b']);
      assert.deepStrictEqual(metadata.get('key4'), ['value4']);
      assert.deepStrictEqual(metadata.get('key5'), ['value5a', 'value5b']);
    });
  });

  describe('toHttp2Headers', () => {
    it('creates an OutgoingHttpHeaders object with expected values', () => {
      metadata.add('key1', 'value1');
      metadata.add('Key2', 'value2');
      metadata.add('KEY3', 'value3a');
      metadata.add('key3', 'value3b');
      metadata.add('key-bin', Buffer.from(range(0, 16)));
      metadata.add('key-bin', Buffer.from(range(16, 32)));
      metadata.add('key-bin', Buffer.from(range(0, 32)));
      const headers = metadata.toHttp2Headers();
      assert.deepStrictEqual(headers, {
        key1: ['value1'],
        key2: ['value2'],
        key3: ['value3a', 'value3b'],
        'key-bin': [
          'AAECAwQFBgcICQoLDA0ODw==',
          'EBESExQVFhcYGRobHB0eHw==',
          'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=',
        ],
      });
    });

    it('creates an empty header object from empty Metadata', () => {
      assert.deepStrictEqual(metadata.toHttp2Headers(), {});
    });
  });

  describe('fromHttp2Headers', () => {
    it('creates a Metadata object with expected values', () => {
      const headers = {
        key1: 'value1',
        key2: ['value2'],
        key3: ['value3a', 'value3b'],
        key4: ['part1, part2'],
        'key-bin': [
          'AAECAwQFBgcICQoLDA0ODw==',
          'EBESExQVFhcYGRobHB0eHw==',
          'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=',
        ],
      };
      const metadataFromHeaders = TestMetadata.fromHttp2Headers(headers);
      const internalRepr = metadataFromHeaders.getInternalRepresentation();
      const expected: MetadataObject = new Map<string, MetadataValue[]>([
        ['key1', ['value1']],
        ['key2', ['value2']],
        ['key3', ['value3a', 'value3b']],
        ['key4', ['part1, part2']],
        [
          'key-bin',
          [
            Buffer.from(range(0, 16)),
            Buffer.from(range(16, 32)),
            Buffer.from(range(0, 32)),
          ],
        ],
      ]);
      assert.deepStrictEqual(internalRepr, expected);
    });

    it('creates an empty Metadata object from empty headers', () => {
      const metadataFromHeaders = TestMetadata.fromHttp2Headers({});
      const internalRepr = metadataFromHeaders.getInternalRepresentation();
      assert.deepStrictEqual(internalRepr, new Map<string, MetadataValue[]>());
    });
  });
});


text:
namespace Tellurium.VisualAssertions.Screenshots.Service
{
    public class ContinousIntegration
    {
        public ContinousIntegration(string branchName, string commitHash, string commitTitle)
        {
            BranchName = branchName;
            CommitHash = commitHash;
            CommitTitle = commitTitle;
        }

        public string BranchName { get; }
        public string CommitTitle { get; }
        public string CommitHash { get; }
    }
}


text:
function b() {
    console.log('Called b!');
}

b();

console.log(a);

var a = 'Hello World!';

console.log(a);

/*The second stage of the execution context it excution. With all the variables in memery, the JS engine goes through your code line by line and interprets it. */


text:
using System.Text;

namespace Generic.Basic.FileSystem.Csv
{
    public class CsvCfg
    {
        /// <summary>
        /// Gets or sets the delimiter used to separate fields.  Default is ',';
        /// </summary>
        public virtual string Delimiter { get; set; }

        /// <summary>
        ///  Gets or sets the encoding used when counting bytes. Default UTF8
        /// </summary>
        public virtual Encoding Encoding { get; set; }

        /// <summary>
        /// Gets or sets a value indicating if blank lines should be ignored when reading.
        /// True to ignore, otherwise false. Default is true.
        /// </summary>
        public virtual bool IgnoreBlankLines { get; set; }

        public CsvCfg()
        {
            Delimiter = ",";
            Encoding = Encoding.UTF8;
            IgnoreBlankLines = true;

        }

    }
}


text:
<?php

declare(strict_types=1);

namespace BrianFaust\Exceptions\Runtime\Http;

use BrianFaust\Exceptions\Standards\RuntimeException;

class VariantAlsoNegotiatesException extends RuntimeException
{
    public function __construct(?string $message, ?string $errorCode = 'ERR-VARIANT-ALSO-NEGOTIATES')
    {
        parent::__construct($message, $errorCode, 506);
    }
}


text:
require 'job/tube'
require 'util/file'
require 'util/event'
require 'util/logging'
require 'monitor'

#
# suesue_dev@yahoo.co.jp
#
module SS
module Job

	class Bundle < SS::Event::Listener
		include SS::Logging::Loggable

		#@tubes
		#@started

		def initialize
			@lock = Monitor.new
			@cond = @lock.new_cond
			@tubes = []
			@running_tubes = []
			@started = false
		end

		# @override SS::Event::Listener
		def listen( event )
			return if event.nil?
			debug "#listen: event [ #{event.category}/#{event.type} ] arrived from #{event.source}"
			tube = event.source
			@lock.synchronize do
				case event.type
				when :done then
					@tubes.delete tube
					@cond.broadcast
				when :errored then
					@tubes.delete tube
					@cond.broadcast
				end
			end
		end

		def create_tube( path )
			file = SS::Utilities::File.new( path )
			tube = Tube.new( file )
			add_tube tube
		end

		def add_tube( tube )
			tube.add_listener self

			@lock.synchronize do
				if @started and tube.configured? then
					start_tube tube
					@running_tubes << tube
				else
					@tubes << tube
				end
			end

			tube
		end

		def find_tube_by_name( name )
			each do |tube|
				if tube == name then
					if block_given? then
						yield tube
						return nil
					else
						return tube
					end
				end
			end
			nil
		end

		def configure_tubes( config )
			raise if config.nil?
			@lock.synchronize do
				@tubes.each do |tube|
					tube.configure config
				end
			end
		end

		def start
			flag = nil
			@lock.synchronize do
				raise if @started
				flag = true
				@started = flag
				tubes = @tubes
				@tubes = []
				tubes.each do |tube|
					next unless tube.enabled?
					start_tube tube
					@running_tubes << tube
				end
			end
			flag
		end

		def start_tube( tube )
			raise if tube.nil?
			debug "#start_tube: starting Tube[ #{tube.name} ]"
			tube.start
			info "Tube[ #{tube.name} ] started @ #{tube.config[:preprocess_dir].absolute_path}"
		end

		def stop
			@lock.synchronize do
				#return nil unless @started
				running_tubes = @running_tubes
				@running_tubes = []
				running_tubes.each do |tube|
					tube.stop
				end
			end
		end

		def started?
			@lock.synchronize do
				return @started
			end
		end

		def wait_for_all
			trace "#wait_for_all: entered"
			@lock.synchronize do
				@cond.wait_until do
					@running_tubes.empty?
				end
			end
			trace "#wait_for_all: exiting"
		end

		def each
			return nil unless block_given?
			@lock.synchronize do
				#return nil unless @started
				@tubes.each do |tube|
					yield tube
				end
			end
			return self
		end

		def duplicated?( path )
			check_directory( path ) > 1
		end

		def existed?( path )
			check_directory( path ) > 0
		end

		def check_directory( path )
			dir = SS::Utilities::File.new( path )
			count = 0
			@lock.synchronize do
				@tubes.each do |tube|
					count.succ if tube.target_directory == dir
				end
			end
			count
		end

		def check_name( name )
			count = 0
			@lock.synchronize do
				@tubes.each do |tube|
					count.succ if tube.name == name
				end
			end
			count
		end

	end

end
end


text:
Type.registerNamespace("Strings");
Strings.OfficeOM = function()
{
};
Strings.OfficeOM.registerClass("Strings.OfficeOM");
Strings.OfficeOM.L_InvalidNamedItemForBindingType = "A megadott kötési típus nem kompatibilis a megadott névvel ellátott elemmel.";
Strings.OfficeOM.L_EventHandlerNotExist = "A megadott eseménytípus nem támogatott ezen az objektumon.";
Strings.OfficeOM.L_UnknownBindingType = "A kötési típus nem támogatott.";
Strings.OfficeOM.L_InvalidNode = "Érvénytelen csomópont";
Strings.OfficeOM.L_NotImplemented = "A(z) {0} függvény nincs implementálva.";
Strings.OfficeOM.L_NoCapability = "Nincs megfelelő engedélye a művelet végrehajtására.";
Strings.OfficeOM.L_SettingsCannotSave = "Nem sikerült menteni a beállításokat.";
Strings.OfficeOM.L_InvalidBinding = "Érvénytelen kötés";
Strings.OfficeOM.L_BindingCreationError = "Kötés-létrehozási hiba";
Strings.OfficeOM.L_SelectionNotSupportCoercionType = "A jelenlegi kijelölés nem kompatibilis a megadott típuskonverzióval.";
Strings.OfficeOM.L_InvalidBindingError = "Hiba: érvénytelen kötés";
Strings.OfficeOM.L_InvalidGetStartRowColumn = "A kezdő sorként vagy kezdő oszlopként megadott érték érvénytelen.";
Strings.OfficeOM.L_CannotWriteToSelection = "A jelenlegi kijelölés nem írható.";
Strings.OfficeOM.L_IndexOutOfRange = "Az index kívül esik az engedélyezett tartományon.";
Strings.OfficeOM.L_SettingsStaleError = "Hiba: elavult beállítások";
Strings.OfficeOM.L_ReadSettingsError = "Beállításolvasási hiba";
Strings.OfficeOM.L_CoercionTypeNotSupported = "A megadott típuskonverzió nem támogatott.";
Strings.OfficeOM.L_AppNotExistInitializeNotCalled = "A(z) {0} alkalmazás nem létezik. A Microsoft.Office.WebExtension.initialize(reason) elem hívása nem történik meg.";
Strings.OfficeOM.L_OverwriteWorksheetData = "A beállítási művelet nem sikerült, mert a megadott adatobjektum felülírná vagy eltolná az adatokat.";
Strings.OfficeOM.L_UnsupportedEnumeration = "Nem támogatott számbavétel";
Strings.OfficeOM.L_InvalidParameters = "A(z) {0} függvénynek érvénytelen paraméterei vannak.";
Strings.OfficeOM.L_DataNotMatchCoercionType = "A megadott adatobjektum típusa nem kompatibilis a jelenlegi kijelöléssel.";
Strings.OfficeOM.L_UnsupportedEnumerationMessage = "A számbavétel nem támogatott az aktuális gazdaalkalmazásban.";
Strings.OfficeOM.L_InvalidCoercion = "Érvénytelen típuskonverzió";
Strings.OfficeOM.L_NotSupportedEventType = "A megadott eseménytípus ({0}) nem támogatott.";
Strings.OfficeOM.L_UnsupportedDataObject = "A megadott adatobjektum típusa nem támogatott.";
Strings.OfficeOM.L_GetDataIsTooLarge = "A kért adatkészlet túl nagy.";
Strings.OfficeOM.L_AppNameNotExist = "A(z) {0} alkalmazásneve nem létezik.";
Strings.OfficeOM.L_AddBindingFromPromptDefaultText = "Válasszon a lehetőségek közül.";
Strings.OfficeOM.L_MultipleNamedItemFound = "Több azonos nevű objektum található.";
Strings.OfficeOM.L_DataNotMatchBindingType = "A megadott adatobjektum nem kompatibilis a kötéstípussal.";
Strings.OfficeOM.L_NotSupportedBindingType = "A megadott kötéstípus ({0}) nem támogatott.";
Strings.OfficeOM.L_InitializeNotReady = "Az Office.js fájl betöltése még nem fejeződött be. Próbálkozzon újra később, vagy ellenőrizze, hogy hozzáadta-e az inicializálási kódot az Office.initialize függvényhez.";
Strings.OfficeOM.L_ShuttingDown = "A művelet nem sikerült, mert a kiszolgálón lévő adatok nem naprakészek.";
Strings.OfficeOM.L_OperationNotSupported = "A művelet nem támogatott.";
Strings.OfficeOM.L_DocumentReadOnly = "A kért művelet nem engedélyezett a jelenlegi dokumentummódban.";
Strings.OfficeOM.L_NamedItemNotFound = "A névvel ellátott elem nem létezik.";
Strings.OfficeOM.L_InvalidApiCallInContext = "Érvénytelen API-hívás az aktuális környezetben.";
Strings.OfficeOM.L_SetDataIsTooLarge = "A megadott adatobjektum túl nagy.";
Strings.OfficeOM.L_DataWriteError = "Adatírási hiba";
Strings.OfficeOM.L_InvalidBindingOperation = "Érvénytelen kötési művelet";
Strings.OfficeOM.L_FunctionCallFailed = "A(z) {0} függvény hívása sikertelen, hibakód: {1}.";
Strings.OfficeOM.L_DataNotMatchBindingSize = "A megadott adatobjektum nem egyezik a jelenlegi kijelölés méretével.";
Strings.OfficeOM.L_SaveSettingsError = "Beállításmentési hiba";
Strings.OfficeOM.L_InvalidSetStartRowColumn = "A kezdő sorként vagy kezdő oszlopként megadott érték érvénytelen.";
Strings.OfficeOM.L_InvalidFormat = "Hiba: érvénytelen formátum";
Strings.OfficeOM.L_BindingNotExist = "A megadott kötés nem létezik.";
Strings.OfficeOM.L_EventHandlerAdditionFailed = "Nem sikerült hozzáadni az eseménykezelőt.";
Strings.OfficeOM.L_SettingNameNotExist = "A megadott beállításnév nem létezik.";
Strings.OfficeOM.L_InvalidAPICall = "Érvénytelen API-hívás";
Strings.OfficeOM.L_EventRegistrationError = "Eseményregisztrációs hiba";
Strings.OfficeOM.L_NonUniformPartialSetNotSupported = "Koordinátaparaméterek nem használhatók a Táblázat fajtájú típuskonverzióhoz, ha a táblázat egyesített cellákat tartalmaz.";
Strings.OfficeOM.L_RedundantCallbackSpecification = "A visszahívás nem adható meg az argumentumlistában és a választható objektumban is.";
Strings.OfficeOM.L_CustomXmlError = "Egyéni XML-hiba.";
Strings.OfficeOM.L_SettingsAreStale = "Nem sikerült menteni a beállításokat, mert nem naprakészek.";
Strings.OfficeOM.L_TooManyOptionalFunction = "több választható függvény van a paraméterlistában";
Strings.OfficeOM.L_MissingRequiredArguments = "hiányzik néhány kötelező argumentum";
Strings.OfficeOM.L_NonUniformPartialGetNotSupported = "Koordinátaparaméterek nem használhatók a Táblázat fajtájú típuskonverzióhoz, ha a táblázat egyesített cellákat tartalmaz.";
Strings.OfficeOM.L_HostError = "Állomáshiba";
Strings.OfficeOM.L_InvalidSelectionForBindingType = "A jelenlegi kijelöléssel és a megadott kötéstípussal nem hozható létre kötés.";
Strings.OfficeOM.L_TooManyOptionalObjects = "több választható objektum van a paraméterlistában";
Strings.OfficeOM.L_EventHandlerRemovalFailed = "Nem sikerült eltávolítani az eseménykezelőt.";
Strings.OfficeOM.L_BindingToMultipleSelection = "A nem összefüggő kijelölések használata nem támogatott.";
Strings.OfficeOM.L_DataReadError = "Adatolvasási hiba";
Strings.OfficeOM.L_InternalErrorDescription = "Belső hiba történt.";
Strings.OfficeOM.L_InvalidDataFormat = "A megadott adatobjektum formátuma érvénytelen.";
Strings.OfficeOM.L_DataStale = "Az adatok nem naprakészek";
Strings.OfficeOM.L_GetSelectionNotSupported = "A jelenlegi kijelölés nem támogatott.";
Strings.OfficeOM.L_PermissionDenied = "Engedély megtagadva";
Strings.OfficeOM.L_InvalidDataObject = "Érvénytelen adatobjektum";
Strings.OfficeOM.L_SelectionCannotBound = "A jelenlegi kijelöléshez nem lehet kötni.";
Strings.OfficeOM.L_BadSelectorString = "A választónak átadott karakterlánc helytelenül van formázva vagy nem támogatott.";
Strings.OfficeOM.L_InvalidGetRowColumnCounts = "A sorok vagy oszlopok számának megadott értéke érvénytelen.";
Strings.OfficeOM.L_OsfControlTypeNotSupported = "Az OsfControl típus nem támogatott.";
Strings.OfficeOM.L_DataNotMatchSelection = "A megadott adatobjektum nem kompatibilis a jelenlegi kijelölés alakjával vagy méreteivel.";
Strings.OfficeOM.L_InternalError = "Belső hiba";
Strings.OfficeOM.L_NotSupported = "A(z) {0} függvény nem támogatott.";
Strings.OfficeOM.L_CustomXmlNodeNotFound = "A megadott csomópont nem található.";
Strings.OfficeOM.L_CoercionTypeNotMatchBinding = "A megadott típuskonverzió nem kompatibilis ezzel a kötéstípussal.";
Strings.OfficeOM.L_TooManyArguments = "túl sok argumentum";
Strings.OfficeOM.L_OperationNotSupportedOnThisBindingType = "Ezen a kötéstípuson nem támogatott a művelet.";
Strings.OfficeOM.L_InValidOptionalArgument = "érvénytelen választható argumentum";
Strings.OfficeOM.L_FileTypeNotSupported = "A megadott fájltípus nem támogatott.";
Strings.OfficeOM.L_CallbackNotAFunction = "A visszahívás típusa csak függvény lehet, de ehelyett {0} típusú volt."


text:
layout: default
title: ICESDP'18 - Symposium
meta: Organize a symposium under the umbrella of the conference!
keyword: environmental sustainability, environmental development, environmental protection, environmental sustainability conference, environmental development conference, environmental protection conference, civil engineering conference, climate change conference, global warming conference, environmental risk management conference, health and environmental conference, waste management conference, environmental conference, civil engineering, climate change, global warming, environmental risk management, health and environmental, waste management, environmental
---

Workshop

We are proud to present A/Prof. Hany El Naggar and A/Prof. Mohamed Shahin as the presenters of our workshop for the 3rd World Congress on Civil, Structural, and Environmental Engineering (CSEE'18).

Workshop Presenters

        A/Prof.
Hany El Naggar,

        Dalhousie University, Canada

        Congress Chair

        A/Prof.
Mohamed Shahin,

        Curtin University, Australia

        Congress Co-Chair

Workshop Objectives

    This intensive Workshop will provide you with the needed theory and practical background required to confidently utilize modern analysis software to achieve practical solutions to challenging geotechnical problems. The workshop includes two modelling modules: Finite Elements and Artificial Intelligence.

    View Workshop Flyer

Registration for the workshop will be separate from the main conference. Workshop attendees will receive a certificate of participation. For registration, please visit: here.

If you have any questions, please do not hesitate to contact us at info@icesdp.com.

Symposium

The 3rd International Conference on Environmental Sustainability, Development, and Protection (ICESDP'18) invites you to propose a symposium.

The proposed symposium, if accepted, will be co-located with and under the umbrella of the conference.

Proposals by prospective chairs should be submitted to info@icesdp.com and will be evaluated by the Organizing and Scientific Committees. Upon approval, the Organizing Committee will disseminate the news through the conference website and call for papers. To obtain a high attendance, we kindly ask that the prospective chairs also publicize the event and personally contact researchers who they think will be interested to contribute. The minimum number of registered presenters for the event to take place is 7. Should attendance reach this minimum requirement, registration fees for the Chair will be waived.

If you have any questions, please do not hesitate to contact us at info@icesdp.com.


text:
/*
 * This code was generated by
 * ___ _ _ _ _ _    _ ____    ____ ____ _    ____ ____ _  _ ____ ____ ____ ___ __   __
 *  |  | | | | |    | |  | __ |  | |__| | __ | __ |___ |\ | |___ |__/ |__|  | |  | |__/
 *  |  |_|_| | |___ | |__|    |__| |  | |    |__] |___ | \| |___ |  \ |  |  | |__| |  \
 *
 * Twilio - Api
 * This is the public Twilio REST API.
 *
 * NOTE: This class is auto generated by OpenAPI Generator.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

package openapi

// ApiV2010UserDefinedMessageSubscription struct for ApiV2010UserDefinedMessageSubscription
type ApiV2010UserDefinedMessageSubscription struct {
	// Account SID.
	AccountSid *string `json:"account_sid,omitempty"`
	// Call SID.
	CallSid *string `json:"call_sid,omitempty"`
	// User Defined Message Subscription SID.
	Sid *string `json:"sid,omitempty"`
	// The date this User Defined Message Subscription was created.
	DateCreated *string `json:"date_created,omitempty"`
	// The URI of the User Defined Message Subscription Resource, relative to `https://api.twilio.com`.
	Uri *string `json:"uri,omitempty"`
}


text:
package org.finos.waltz.model.aggregate_overlay_diagram.overlay;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.immutables.value.Value;

@Value.Immutable
@JsonSerialize(as = ImmutableCountWidgetDatum.class)
public abstract class CountWidgetDatum implements CellExternalIdProvider {

    public abstract int currentStateCount();
    public abstract int targetStateCount();

}


text:
const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
    name: String,
    description: String,
    pictureURL: String,
    price: Number,
    ordPrice: Number,
    quantity: Number,
    startdate: { type: Date, default: '2000-10-10T08:00' },
    enddate: { type: Date, default: '2000-10-10T09:00' },
    restaurantId: { type: mongoose.Schema.Types.ObjectId, ref: 'Restaurant' }

}, { timestamps: true });

const Product = mongoose.model('Product', productSchema);

// Getter
productSchema.path('price').get(function(num) {
  return parseFloat(Math.round(num) / 100).toFixed(2);
});

// Setter
productSchema.path('price').set(function(num) {
  return num * 100;
});

// Getter
productSchema.path('ordPrice').get(function(num) {
  if (num) {
    return parseFloat(Math.round(num) / 100).toFixed(2);
  }
  return null;
});

// Setter
productSchema.path('ordPrice').set(function(num) {
  if (num) {
    return num * 100;
  }
  return null;
});

/**
 *  Notify admin middleware
 */
productSchema.pre('save', function(next) {
    const product = this;
    if (product.isModified('startdate')) {

      // Notify admin here.
      var Restaurant = require('./Restaurant');
      Restaurant.findById(product.restaurantId, (err, restaurant) => {
        var subject, message;
        subject = 'Ny/Uppdaterad produkt från ' + ((restaurant) ? restaurant.name : 'okänd');
        message = 'Produkten ('
                + product.name
                + ') har blivit satt till publicering den '
                + getLocalISOString(product.startdate).slice(0, 16).replace('T', ' ')
                + ' till '
                + getLocalISOString(product.enddate).slice(0, 16).replace('T', ' ')
        var adminNotify = require('../tools/adminNotify');
        adminNotify.sendEmail(subject, message);
      })
    }
    next();
});

function getLocalISOString(date) {
    var tzoffset = (new Date()).getTimezoneOffset() * 60000;
    return localISOTime = (new Date(date - tzoffset)).toISOString().slice(0,-1);
}

module.exports = Product;


text:
package javax.transaction.xa;

import java.io.Serializable;

/**
 * An XAException is an exception thrown by a Resource Manager to inform the
 * Transaction Manager of an error which has occurred in relation to a
 * transaction branch. In addition to the usual exception message, an
 * XAException carries an errorCode value which provides information about the
 * error, as defined by the series of integer values defined by the XAException
 * class.
 */
public class XAException extends Exception implements Serializable {

    private static final long serialVersionUID = -8249683284832867751L;

    /**
     * Code which contains the inclusive lower bound of the rollback error codes
     */
    public static final int XA_RBBASE = 100;

    /**
     * Code which means that the rollback occurred for an unspecified reason
     */
    public static final int XA_RBROLLBACK = 100;

    /**
     * Code which means that rollback was caused by a communication failure
     */
    public static final int XA_RBCOMMFAIL = 101;

    /**
     * Code which means that a failure occurred because a deadlock was detected
     */
    public static final int XA_RBDEADLOCK = 102;

    /**
     * Code which means that a condition was detected than implies a violation
     * of the integrity of the resource
     */
    public static final int XA_RBINTEGRITY = 103;

    /**
     * Code which means that the Resource Manager rolled back the transaction
     * branch for a reason not separately listed
     */
    public static final int XA_RBOTHER = 104;

    /**
     * Code which means that a protocol error occurred in the Resource Manager
     */
    public static final int XA_RBPROTO = 105;

    /**
     * Code which means that a transaction branch took too long
     */
    public static final int XA_RBTIMEOUT = 106;

    /**
     * Code which means that the caller may retry the transaction branch
     */
    public static final int XA_RBTRANSIENT = 107;

    /**
     * Code which contains the inclusive upper bound of the rollback error codes
     */
    public static final int XA_RBEND = 107;

    /**
     * Code which means that resumption must occur where the suspension occurred
     */
    public static final int XA_NOMIGRATE = 9;

    /**
     * Code which means that the transaction branch may have been heuristically
     * completed
     */
    public static final int XA_HEURHAZ = 8;

    /**
     * Code which means that the transaction branch has been heuristically
     * committed
     */
    public static final int XA_HEURCOM = 7;

    /**
     * Code which means that the transaction branch has been heuristically
     * rolled back
     */
    public static final int XA_HEURRB = 6;

    /**
     * Code which means that the transaction branch has been heuristically
     * committed and rolled back
     */
    public static final int XA_HEURMIX = 5;

    /**
     * Code which means that the method returned with no effect and can be
     * reissued
     */
    public static final int XA_RETRY = 4;

    /**
     * Code which means that the transaction branch was read only and has been
     * committed
     */
    public static final int XA_RDONLY = 3;

    /**
     * Code which means that there is already an asynchronous operation
     * outstanding
     */
    public static final int XAER_ASYNC = -2;

    /**
     * Code which means that a Resource Manager error has occurred for the
     * transaction branch
     */
    public static final int XAER_RMERR = -3;

    /**
     * Code which means that the XID is not valid
     */
    public static final int XAER_NOTA = -4;

    /**
     * Code which means that invalid arguments were supplied
     */
    public static final int XAER_INVAL = -5;

    /**
     * Code which means that the method was invoked in an improper context
     */
    public static final int XAER_PROTO = -6;

    /**
     * Code which means that the Resource Manager is unavailable
     */
    public static final int XAER_RMFAIL = -7;

    /**
     * Code which means that the XID already exists
     */
    public static final int XAER_DUPID = -8;

    /**
     * Work is being done by the Resource Manager outside the boundaries of a
     * global transaction.
     */
    public static final int XAER_OUTSIDE = -9;

    /**
     * The errorCode which details the error that has occurred
     */
    public int errorCode;

    /**
     * Creates an XAException with no message or error code
     */
    public XAException() {
        super();
    }

    /**
     * Creates an XAException with a supplied message and no error code
     *
     * @param theMessage
     *            a String containing the exception message
     */
    public XAException(String theMessage) {
        super(theMessage);
    }

    /**
     * Creates an XAException with a specified error code but no message
     *
     * @param errorCode
     *            an integer containing one of the XAException errorCode values
     */
    public XAException(int errorCode) {
        super();
        this.errorCode = errorCode;
    }
}


text:
class WordAction < Cramp::Action
    def start
        pa = params
        word = pa[:word]
        word_id = pa[:word_id]
        ap pa
        data = {}
        if !word_id.nil?
            data = get_by_id word_id
        elsif !word.nil? and !word.empty?
            data = get_by_word word
        end
        render data.to_json
        finish
    end

  def get_by_id(word_id)
      get_detail word_id: word_id
  end
  def get_by_word(word)
      get_detail content: word
  end
  def get_detail (where)
      data = {}
      wordinfos = Wordlist.where where
      wordinfo = wordinfos.first
      if !wordinfo.nil?
          data["word_id"] = wordinfo.word_id
          data["content"] = wordinfo.content
          uns = Unknownword.where word_id: wordinfo.word_id
          un = uns.first
          if !un.nil?
              data["familiarity"] = un.familiarity
          end
      end
      data
  end
end


text:
package com.socklabs.elasticservices.activemq;

import com.google.common.base.Optional;
import com.socklabs.elasticservices.core.misc.Ref;
import com.socklabs.elasticservices.core.transport.TransportClient;
import com.socklabs.elasticservices.core.transport.TransportClientFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.ConnectionFactory;

/**
 * Created by nick.gerakines on 1/9/14.
 */
public class ActiveMqTransportClientFactory implements TransportClientFactory {

	private static final Logger LOGGER = LoggerFactory.getLogger(ActiveMqTransportClientFactory.class);

	private final ConnectionFactory connectionFactory;

	public ActiveMqTransportClientFactory(final ConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
	}

	@Override
	public Optional<TransportClient> get(Ref ref) {
		LOGGER.debug("Transport client requested for ref {}.", ref.toString());
		if ("activemq".equals(ref.getId())) {
			try {
				final ActiveMqTransportClient transportClient = new ActiveMqTransportClient(ref, connectionFactory);
				transportClient.init();
				return Optional.<TransportClient>of(transportClient);
			} catch (final Exception e) {
				LOGGER.error("Could not create connection for ActiveMq transport.", e);
			}
		}
		return Optional.absent();
	}

}


text:
PersOA is used to match the personality details given on this site (http://rpg.ashami.com/) which provides an interesting way to isolate parts of a person's personality in a character. Thus this would make it easier to try to roleplay a character outside your comfort zone, since you could put together a few of the details, which would expand to fill out the whole sheet over time.

The app is made with a REST API to allow other apps to show and edit personalities. This is made mostly for use with WebDnD, though it does have an admin interface (Django's) so you can edit things there.

### Build Status

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

[![Requirements Status](https://requires.io/github/Saevon/PersOA/requirements.svg?branch=master)](https://requires.io/github/Saevon/PersOA/requirements/?branch=master)


text:
package com.niti.android.fotobesa.provider;

/**
 * Created by jpardogo on 22/02/2014.
 */
public enum FragmentTags {
    LIST_BUDDIES("ListBuddiesFragment"),
    CUSTOMIZE("CustomizeFragment");

    private String text;

    private FragmentTags(String text) {
        this.text = text;
    }

    @Override
    public String toString() {
        return text;
    }
}


text:
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------

<#
.SYNOPSIS
Get security auto provisioning settings on a subscription
#>
function Get-AzureRmSecurityAutoProvisioningSetting-SubscriptionScope
{
    $autoProvisioningSettings = Get-AzureRmSecurityAutoProvisioningSetting
	Validate-AutoProvisioningSettings $autoProvisioningSettings
}

<#
.SYNOPSIS
Get a security auto provisioning setting
#>
function Get-AzureRmSecurityAutoProvisioningSetting-SubscriptionLevelResource
{
    $autoProvisioningSettings = Get-AzureRmSecurityAutoProvisioningSetting -Name "default"
	Validate-AutoProvisioningSettings $autoProvisioningSettings
}

<#
.SYNOPSIS
Get security auto provisioning setting by a resource ID
#>
function Get-AzureRmSecurityAutoProvisioningSetting-ResourceId
{
	$autoProvisioningSetting = Get-AzureRmSecurityAutoProvisioningSetting | Select -First 1

    $fetchedAutoProvisioningSetting = Get-AzureRmSecurityAutoProvisioningSetting -ResourceId $autoProvisioningSetting.Id
	Validate-AutoProvisioningSetting $autoProvisioningSetting
}

<#
.SYNOPSIS
Set security auto provisioning setting
#>
function Set-AzureRmSecurityAutoProvisioningSetting-SubscriptionLevelResource
{
    Set-AzureRmSecurityAutoProvisioningSetting -Name "default" -EnableAutoProvision
}

<#
.SYNOPSIS
Set security auto provisioning setting by resource ID
#>
function Set-AzureRmSecurityAutoProvisioningSetting-ResourceId
{
	$autoProvisioningSetting = Get-AzureRmSecurityAutoProvisioningSetting | Select -First 1
    Set-AzureRmSecurityAutoProvisioningSetting -ResourceId $autoProvisioningSetting.Id -EnableAutoProvision
}

<#
.SYNOPSIS
Validates a list of security autoProvisioningSettings
#>
function Validate-AutoProvisioningSettings
{
	param($autoProvisioningSettings)

    Assert-True { $autoProvisioningSettings.Count -gt 0 }

	Foreach($autoProvisioningSetting in $autoProvisioningSettings)
	{
		Validate-AutoProvisioningSetting $autoProvisioningSetting
	}
}

<#
.SYNOPSIS
Validates a single autoProvisioningSetting
#>
function Validate-AutoProvisioningSetting
{
	param($autoProvisioningSetting)

	Assert-NotNull $autoProvisioningSetting
}


text:
#import "UIKit-Structs.h"
#import <UIKit/UILabel.h>

@interface UITextLabel : UILabel {
}
-(CGSize)ellipsizedTextSize;
-(void)setColor:(id)color;
-(id)color;
-(void)setHighlightedColor:(id)color;
-(id)highlightedColor;
-(void)setCentersHorizontally:(BOOL)horizontally;
-(BOOL)centersHorizontally;
-(void)setWrapsText:(BOOL)text;
-(BOOL)wrapsText;
-(void)setTextAutoresizesToFit:(BOOL)fit;
-(BOOL)textAutoresizesToFit;
-(void)setMinFontSize:(float)size;
-(float)minFontSize;
-(void)setAlignment:(int)alignment;
-(int)alignment;
-(void)setEllipsisStyle:(int)style;
-(int)ellipsisStyle;
-(void)drawRect:(CGRect)rect;
-(void)drawTextInRect:(CGRect)rect;
-(void)drawContentsInRect:(CGRect)rect;
@end


text:
package edu.isi.karma.controller.command.worksheet;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import edu.isi.karma.controller.command.CommandException;
import edu.isi.karma.controller.command.CommandType;
import edu.isi.karma.controller.command.WorksheetSelectionCommand;
import edu.isi.karma.controller.command.selection.SuperSelection;
import edu.isi.karma.controller.update.AddColumnUpdate;
import edu.isi.karma.controller.update.ErrorUpdate;
import edu.isi.karma.controller.update.UpdateContainer;
import edu.isi.karma.controller.update.WorksheetUpdateFactory;
import edu.isi.karma.rep.HNode;
import edu.isi.karma.rep.HNode.HNodeType;
import edu.isi.karma.rep.HNodePath;
import edu.isi.karma.rep.HTable;
import edu.isi.karma.rep.Node;
import edu.isi.karma.rep.Node.NodeStatus;
import edu.isi.karma.rep.RepFactory;
import edu.isi.karma.rep.Worksheet;
import edu.isi.karma.rep.Workspace;
import edu.isi.karma.util.Util;
import edu.isi.karma.webserver.KarmaException;

/**
 * Adds a new column to the table with hTableId.
 * hTableId may be empty if a hNodeId is provided.
 * If hNodeId is provided, adds the new column after hNodeId.
 * If no hNodeId is provided adds the new column as the first column in the table hTableId.
 * Returns the hNodeId of the newly created column.
 */
public class AddColumnCommand extends WorksheetSelectionCommand {
	//if null add column at beginning of table
	private final String hNodeId;
	//add column to this table
	private String hTableId;
	private final String newColumnName;
	private final String defaultValue;
	private String newColumnAbsoluteName;

	//the id of the new column that was created
	//needed for undo
	private String newHNodeId;

	private static Logger logger = LoggerFactory
	.getLogger(AddColumnCommand.class);

	protected AddColumnCommand(String id, String model, String worksheetId,
			String hTableId, String hNodeId, String newColumnName,
			String defaultValue, String selectionId) {
		super(id, model, worksheetId, selectionId);
		this.hNodeId = hNodeId;
		this.hTableId = hTableId;
		this.newColumnName=newColumnName;
		this.defaultValue = defaultValue;
		this.newColumnAbsoluteName = newColumnName;
		addTag(CommandTag.Transformation);
	}

	@Override
	public String getCommandName() {
		return AddColumnCommand.class.getSimpleName();
	}

	@Override
	public String getTitle() {
		return "Add New Column";
	}

	@Override
	public String getDescription() {
		if (newColumnAbsoluteName != null)
			return newColumnAbsoluteName;
		else
			return "";
	}

	@Override
	public CommandType getCommandType() {
		return CommandType.undoable;
	}

	@Override
	public UpdateContainer doIt(Workspace workspace) throws CommandException {
		inputColumns.clear();
		outputColumns.clear();
		Worksheet worksheet = workspace.getWorksheet(
				worksheetId);

		try{
			if(hTableId==null || hTableId.isEmpty()){
				//get table id based on the hNodeId
				if(hNodeId==null)
					throw new KarmaException("TableId and NodeId are empty. Can't add column.");
				hTableId = workspace.getFactory().getHNode(hNodeId).getHTableId();
			}
			HTable hTable = workspace.getFactory().getHTable(hTableId);
			if(hTable == null)
			{
				logger.error("No HTable for id "+ hTableId);
				throw new KarmaException("No HTable for id "+ hTableId );
			}
			if (null != hTable.getHNodeFromColumnName(newColumnName)) {
				logger.error("Add column failed to create " + newColumnName
						+ " because it already exists!");
				return new UpdateContainer(new ErrorUpdate(
						"Add column failed to create " + newColumnName
								+ " because it already exists!"));
			}
			//add new column to this table
			//add column after the column with hNodeId
			HNode ndid = hTable.addNewHNodeAfter(hNodeId, HNodeType.Transformation, workspace.getFactory(), newColumnName, worksheet,true);
			if(ndid == null)
			{
				logger.error("Unable to add new HNode!");
				throw new KarmaException("Unable to add new HNode!");
			}
			//add as first column in the table if hNodeId is null
			//HNode ndid = currentTable.addNewHNodeAfter(null, vWorkspace.getRepFactory(), newColumnName, worksheet,true);

			//save the new hNodeId for undo
			newHNodeId = ndid.getId();

			// Populate the column with default value if default value is present
			if (this.defaultValue != null && !this.defaultValue.equals("")) {
				populateRowsWithDefaultValues(worksheet, workspace.getFactory());
			}

			//create container and return hNodeId of newly created column
			UpdateContainer c =  new UpdateContainer(new AddColumnUpdate(newHNodeId, worksheetId));

			c.append(WorksheetUpdateFactory.createRegenerateWorksheetUpdates(worksheetId, getSuperSelection(worksheet), workspace.getContextId()));
			c.append(computeAlignmentAndSemanticTypesAndCreateUpdates(workspace));
			outputColumns.add(newHNodeId);
			newColumnAbsoluteName = ndid.getAbsoluteColumnName(workspace.getFactory());
			return c;
		} catch (Exception e) {
			logger.error("Error in AddColumnCommand" + e.toString());
			Util.logException(logger, e);
			return new UpdateContainer(new ErrorUpdate(e.getMessage()));
		}
	}

	private void populateRowsWithDefaultValues(Worksheet worksheet, RepFactory factory) {
		SuperSelection selection = getSuperSelection(worksheet);
		HNodePath selectedPath = null;
		List<HNodePath> columnPaths = worksheet.getHeaders().getAllPaths();
		for (HNodePath path : columnPaths) {
			if (path.getLeaf().getId().equals(newHNodeId)) {
				selectedPath = path;
			}
		}
		Collection<Node> nodes = new ArrayList<>(Math.max(1000, worksheet.getDataTable().getNumRows()));
		worksheet.getDataTable().collectNodes(selectedPath, nodes, selection);
		for (Node node : nodes) {
			node.setValue(this.defaultValue, NodeStatus.original, factory);
		}
	}

	@Override
	public UpdateContainer undoIt(Workspace workspace) {
		Worksheet worksheet = workspace.getWorksheet(worksheetId);

		HTable currentTable = workspace.getFactory().getHTable(hTableId);
		//remove the new column
		currentTable.removeHNode(newHNodeId, worksheet);

		return WorksheetUpdateFactory.createRegenerateWorksheetUpdates(worksheetId, getSuperSelection(worksheet), workspace.getContextId());
	}

	public String getNewHNodeId() {
		return newHNodeId;
	}
}


text:
    Site Name Here

  <menu class="site-menu">

      <menuitem class="site-menu-icon icon-reorder" label="Expand page menu">Sections</menuitem>

  </menu>


text:
export enum Keys {
  Escape = 27
}

export enum MouseButtons {
  Left = 0,
  Right = 2
}

export function isLeftButtonClicked(e: MouseEvent): boolean {
  return e.button === MouseButtons.Left;
}

export function isRightButtonClicked(e: MouseEvent): boolean {
  return e.button === MouseButtons.Right;
}

export function isEscapePressed(e: KeyboardEvent): boolean {
  return e.keyCode === Keys.Escape;
}


text:
declare const __JSWorks_models__: any[];

/**
 * Декоратор модели
 * @param target
 * @param name
 * @constructor
 */
export function JSWorksModelUpdateMethod(target: any, name: string) {
    let className = target.name;

    if (target.constructor && target.constructor.name) {
        className = target.constructor.name;
    }

    __JSWorks_models__[className] = __JSWorks_models__[className] || {};
    __JSWorks_models__[className].updateMethod = name;
}


text:
using System;
using System.ComponentModel;
using System.Linq;

namespace Bytes2you.Validation
{
    public interface IArgument<T>
    {
        [EditorBrowsable(EditorBrowsableState.Never)]
        string Name { get; }

        [EditorBrowsable(EditorBrowsableState.Never)]
        T Value { get; }
    }
}


text:
$(document).ready(function() {

  $('.referrer').val(document.referrer);

});


text:
<template name="visitorNavigation">

{{_ "Navigation_History"}}

				{{#if loadingNavigation}}
					{{_ "Loading..."}}
				{{else}}

							{{#each pageVisited}}

{{pageTitle}}

							{{/each}}

				{{/if}}

</template>


text:
namespace _02.Utils
{
    using System;

    internal static class UtilsTest
    {
        internal static void Main()
        {
            try
            {
                var substr = ArrayUtils.Subsequence("Hello!".ToCharArray(), 2, 3);
                Console.WriteLine(substr);

                var subarr = ArrayUtils.Subsequence(new int[] { -1, 3, 2, 1 }, 0, 2);
                Console.WriteLine(string.Join(" ", subarr));

                var allarr = ArrayUtils.Subsequence(new int[] { -1, 3, 2, 1 }, 0, 4);
                Console.WriteLine(string.Join(" ", allarr));

                var emptyarr = ArrayUtils.Subsequence(new int[] { -1, 3, 2, 1 }, 0, 0);
                Console.WriteLine(string.Join(" ", emptyarr));

                Console.WriteLine(StringUtils.ExtractEnding("I love C#", 2));
                Console.WriteLine(StringUtils.ExtractEnding("Nakov", 4));
                Console.WriteLine(StringUtils.ExtractEnding("beer", 4));

                // Console.WriteLine(StringUtils.ExtractEnding("Hi", 100));
                int n = 23;
                Console.WriteLine("{0} is {1}prime.", n, MathUtils.IsPrime(n) ? string.Empty : "not ");
                n = 33;
                Console.WriteLine("{0} is {1}prime.", n, MathUtils.IsPrime(n) ? string.Empty : "not ");
            }
            catch (ArithmeticException are)
            {
                Console.WriteLine(are.Message);
            }
            catch (IndexOutOfRangeException iore)
            {
                Console.WriteLine(iore.Message);
            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine(ane.Message);
            }
            catch (ArgumentException ae)
            {
                Console.WriteLine(ae.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}


text:
package com.bdc.ociney.fragment;

import android.app.ActivityOptions;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.bdc.ociney.R;
import com.bdc.ociney.activity.StarActivity;
import com.bdc.ociney.adapter.ObjectAdapter;
import com.bdc.ociney.fragment.core.BetterFragment;
import com.bdc.ociney.modele.Person.PersonFull;
import com.bdc.ociney.modele.Person.PersonSmall;
import com.bdc.ociney.task.LoadStarsFavorisTask;
import com.bdc.ociney.task.LoadStarsTask;
import com.bdc.ociney.task.SearchStarsTask;
import com.bdc.ociney.view.CellStar;

import java.text.Normalizer;
import java.util.ArrayList;
import java.util.List;

public class ListStarFragment extends BetterFragment implements AdapterView.OnItemClickListener, LoadStarsFavorisTask.LoadStarsFavorisTaskCallBack, ObjectAdapter.ObjectAdapterLoadMore, LoadStarsTask.LoadStarTaskCallBack, SearchStarsTask.SearchStarsTaskCallBack {

    public static final String PERSONS = "persons";
    public static final String FAVORIS = "favoris";
    public static final String FAVORIS_STRINGS = "favoris_string";

    List<PersonFull> persons = new ArrayList<PersonFull>();
    ObjectAdapter<PersonFull> adapter;
    AbsListView list;

    AsyncTask task = null;
    String texteRecherche = "";
    boolean recherche = false;
    boolean vide = false;
    boolean favoris = false;

    int page = 1;

    public static ListStarFragment newInstance(List<PersonFull> stars) {
        ListStarFragment fragment = new ListStarFragment();
        Bundle args = new Bundle();
        Gson gSon = new Gson();
        args.putString(PERSONS, gSon.toJson(stars));
        fragment.setArguments(args);

        return fragment;
    }

    public static ListStarFragment newInstance(List<String> stars, boolean b) { //favoris
        ListStarFragment fragment = new ListStarFragment();
        Bundle args = new Bundle();
        Gson gSon = new Gson();
        args.putBoolean(FAVORIS, true);
        args.putString(FAVORIS_STRINGS, gSon.toJson(stars));
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_list_star,
                container, false);

        setFragmentView(view);

        Bundle bundle = getArguments();
        if (bundle != null) {
            if (bundle.containsKey(FAVORIS)) {
                favoris = true;
                Gson gSon = new Gson();

                List<String> starsFavoris = gSon.fromJson(bundle.getString(FAVORIS_STRINGS), new TypeToken<List<String>>() {
                }.getType());
                if (starsFavoris.size() > 0) {
                    super.tournerRoulette(true);
                    new LoadStarsFavorisTask(this).execute(starsFavoris);
                } else
                    afficherVide(true);
            } else if (bundle.containsKey(PERSONS)) {
                Gson gSon = new Gson();
                persons = gSon.fromJson(bundle.getString(PERSONS), new TypeToken<List<PersonFull>>() {
                }.getType());
            }
        }

        charger();
        remplir();
        ajouterListeners();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    protected void charger() {
        list = (AbsListView) findViewById(R.id.list);
        if (!favoris)
            new LoadStarsTask(this).execute();
    }

    @Override
    protected void remplir() {

        adapter = new ObjectAdapter<PersonFull>(getActivity(), persons, R.layout.cell_star, CellStar.class);
        list.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        if (!favoris)
            adapter.listener = this;

    }

    @Override
    protected void ajouterListeners() {
        list.setOnItemClickListener(this);
    }

    public void onClick(View v) {

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        PersonFull person = (PersonFull) adapter.getItem(i);

        Intent intent = new Intent(getActivity(), StarActivity.class);
        intent.putExtra(StarFragment.PERSON, (new Gson()).toJson(person));

        Bundle b = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            b = ActivityOptions.makeScaleUpAnimation(view, 0, 0, view.getWidth(), view.getHeight()).toBundle();

            getActivity().startActivity(intent, b);
        } else {
            getActivity().startActivity(intent);
            getActivity().overridePendingTransition(0, 0);
        }
    }

    public void refreshAdapter(List<PersonFull> p) {
        this.persons.addAll(p);
        adapter.notifyDataSetChanged();
        //adapter.preloadView();
    }

    @Override
    public void loadMore() {
        page++;
        if (recherche && !vide)
            task = new SearchStarsTask(this).execute(texteRecherche, page);
        else
            new LoadStarsTask(this).execute(page);
    }

    @Override
    public void onLoadStarTaskCallBack(List<PersonFull> stars) {
        if (stars.size() == 0) //si plus de resultats, on enleve le loadmore
            adapter.listener = null;

        refreshAdapter(stars);
    }

    @Override
    public void search(String text) {
        if (task == null && text != null && !text.isEmpty()) {
            texteRecherche = Normalizer.normalize(text, Normalizer.Form.NFD)
                    .replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
            if (task == null && text != null && !text.isEmpty()) {
                if (!recherche) {
                    persons.clear();
                    adapter.notifyDataSetChanged();
                }
                task = new SearchStarsTask(this).execute(texteRecherche);
                recherche = true;
            }
        }
    }

    @Override
    public void onSearchStarsTaskCallBack(List<PersonSmall> ps) {

        if (persons.isEmpty() && this.persons.isEmpty()) {
            afficherVide(true);
            vide = true;
            adapter.listener = null;
        }
        else
            afficherVide(false);

        if (ps.isEmpty()) {
            vide = true;
            adapter.listener = null;
        }

        task = null;
        try {
            refreshAdapter(PersonFull.transformListFull(ps));
        } catch (Exception e) {
            adapter.listener = null;
        }
    }

    @Override
    public void onLoadStarFavorisTaskCallBack(List<PersonFull> stars) {

        if (stars.isEmpty() && this.persons.isEmpty())
            afficherVide(true);
        else
            afficherVide(false);

        super.tournerRoulette(false);
        persons.addAll(stars);
        adapter.notifyDataSetChanged();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion="8.0">
  <DefaultLanguage xmlns="" code="en-US" />
  <App xmlns="" ProductID="{8d25d7a0-be47-4abf-9897-d330e0e48825}" Title="OpenWARExample" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal" Author="OpenWARExample author" Description="Sample description" Publisher="OpenWARExample" PublisherID="{fe3b0c3f-d513-427a-ae84-5aa7d1147286}">
    <IconPath IsRelative="true" IsResource="false">Assets\ApplicationIcon.png</IconPath>
    <Capabilities>
      <Capability Name="ID_CAP_NETWORKING" />
      <Capability Name="ID_CAP_MEDIALIB_AUDIO" />
      <Capability Name="ID_CAP_MEDIALIB_PLAYBACK" />
      <Capability Name="ID_CAP_SENSORS" />
      <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />
      <Capability Name="ID_CAP_ISV_CAMERA" />
    </Capabilities>
    <Tasks>
      <DefaultTask Name="_default" NavigationPage="MainPage.xaml" />
    </Tasks>
    <Tokens>
      <PrimaryToken TokenID="OpenWARExampleToken" TaskName="_default">
        <TemplateFlip>
          <SmallImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileSmall.png</SmallImageURI>
          <Count>0</Count>
          <BackgroundImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileMedium.png</BackgroundImageURI>
          <Title>OpenWARExample</Title>
          <BackContent>
          </BackContent>
          <BackBackgroundImageURI>
          </BackBackgroundImageURI>
          <BackTitle>
          </BackTitle>
          <DeviceLockImageURI>
          </DeviceLockImageURI>
          <HasLarge>
          </HasLarge>
        </TemplateFlip>
      </PrimaryToken>
    </Tokens>
    <ScreenResolutions>
      <ScreenResolution Name="ID_RESOLUTION_WVGA" />
      <ScreenResolution Name="ID_RESOLUTION_WXGA" />
      <ScreenResolution Name="ID_RESOLUTION_HD720P" />
    </ScreenResolutions>
    <Requirements>
      <Requirement Name="ID_REQ_REARCAMERA" />
    </Requirements>
  </App>
</Deployment>


text:
@implementation SharingManager_MailObject_Attachment

@synthesize data;
@synthesize filename, mimeType;

- (id)initWithData:(NSData *)_data mimeType:(NSString *)_mimeType filename:(NSString *)_filename {
	self = [super init];
	if (self) {
		@try { data = [[NSData alloc] initWithData:_data]; }				@catch (NSException *exception) { data = [[NSData alloc] init]; }
		@try { mimeType = [[NSString alloc] initWithString:_mimeType]; }	@catch (NSException *exception) { mimeType = [[NSString alloc] init]; }
		@try { filename = [[NSString alloc] initWithString:_filename]; }	@catch (NSException *exception) { filename = [[NSString alloc] init]; }
	}
	return self;
}
- (void)dealloc {
	[data release];
	[mimeType release];
	[filename release];
	[super dealloc];
}

@end


text:
import os
import sys
import re
import argparse
import platform

def parse_args():
        parser = argparse.ArgumentParser(description='Creates sample_metadata.conf file based on hla typing result files.')
        parser.add_argument('-dir','--fastq_dir', help='Folder where the results are located.', required=False, action="store", dest="fdir", default=os.curdir)
        parser.add_argument('-o', '--output', help='Output file name (optional, default value is sample_metadata.conf).', required=False, action="store", dest="output_file", default="sample_metadata.conf")
        parser.add_argument('-c', '--centerCode', help='Center code',  required=False, action="store", dest="ccode", default="")
        parser.add_argument('-id', '--testid', help='Test id (optional).',  required=False, action="store", dest="test_id", default="")
        parser.add_argument('-hmlIdExt', '--hmlIdextension', help='HML id extension code (optional). Unique document identifier.',  required=False, action="store", dest="hmlid", default="")
        parser.add_argument('-uri', '--fileUrl', help='Url for R1 input file.',  required=False, action="store", dest="uri", default="")
        parser.add_argument('-s', '--source', help='Test id source (optional).',  required=False, action="store", dest="test_id_source", default="")
        parser.add_argument('-form', '--format', help='File format (default fastq).',  required=False, action="store", dest="format", default="FASTQ")
        parser.add_argument('-p', '--paired', help='Read file pairing (paired=true or paired=false), default value is true.',  required=False, action="store", dest="paired", default="true")
        parser.add_argument('-pool', '--pooled', help='Read file pooling (pooled=true or pooled=false), default value is true.',  required=False, action="store", dest="pooled", default="true")
        parser.add_argument('-avail', '--availabilty', help='Availabilty of read files (default value is private).',  required=False, action="store", dest="avail", default="private")
        parser.add_argument('-adTrim', '--adapterTrimmed', help='Sample is adapter trimmed (default value is true).',  required=False, action="store", dest="adapt", default="true")
        parser.add_argument('-qualTrim', '--qualityTrimmed', help='Sample is primer trimmed (default value is true).',  required=False, action="store", dest="qual", default="true")
        args = parser.parse_args()
        return args

def check_platform():
#Checks os to get an idea about path formats that will likely be used
    print 'Checking OS...'
    os=platform.system()
    print "\tDetected OS: " + os
    if os is 'Windows':
        delim= "\\\\"
    elif os is 'Linux':
        delim = '/'
    else:
        delim = "/"
    print "\tThe following delimiter will be used between the read file url and the filename: " + delim
    return delim

#Gets list of htr files using filenames in current or specified folder
def get_sample_list(fdir):
#Get list of htr files
    file_list = os.listdir(fdir)

    read_list = []
    for f in file_list:
        if re.search('.*htr', f):
            read_list.append(f)
    if not read_list:
        print "Please specify a folder containing result files using the \"-dir\" flag! If a folder was specified, check permissions!"
        print "Expected filename format: ID.S([0-9].*_L001_R1_001.*htr"
        print "Example filename mathching the expected format: BC-5_S32_L001_R1_001_2015-11-19_12-32-57.htr"
        sys.exit()
    else:
        return read_list

def get_id(sample):
    print "HTR filename is: " + sample
    s = re.search('.S([0-9].*_L001_R1_001.*htr)', sample)
    print "Extracting sample ID..."
    if not s:
        print "Filename did not match expected pattern!"
        sys.exit()
    else:
        sample_id = sample[0:s.start()]
        print "The following ID was extracted: " + sample_id
        return sample_id

def write_json(read_list,output_file,test_id,ccode,test_id_source,hmlid,uri,format,paired,pooled,avail,adapt,qual,delim):
#Get current time

# Creates JSON formatted file using the previously filtered lines.
        conf = open(output_file,'w')
        conf.write("hla {\n\texport {\n\t\thml {\n\t\t\tsamples = [")
        for sample in read_list:
            sample_id=get_id(sample)
            filename=sample
            conf.write("\n\t\t\t\t {")
#The .htr extension must be removed from the filenames, otherwise Twin won't fill out the id and centerCode fields.
            filename_reformatted = re.sub('.htr', '', filename)
            fastq_base = re.sub(r'_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}', '', filename_reformatted)
            conf.write('\n\t\t\t\t\tfilename = "%s"'% (filename_reformatted))
            conf.write('\n\t\t\t\t\tid = "%s"' % (sample_id))
            conf.write('\n\t\t\t\t\tcenterCode = "%s"' % (ccode))
            if test_id != "":
                conf.write('\n\t\t\t\t\ttestId = "%s"' % (test_id))
            else:
                conf.write('\n\t\t\t\t\ttestId= ""')
            if hmlid != "":
                conf.write('\n\t\t\t\t\thmlIdExtension = "%s-%s"' % ("hml-1.0.1",hmlid))
            else:
                conf.write('\n\t\t\t\t\thmlIdExtension = "hml-1.0.1"')
            if test_id_source != "":
                conf.write('\n\t\t\t\t\ttestIdSource = "%s"' % (test_id_source))
            else:
                conf.write('\n\t\t\t\t\ttestIdSource = ""')
            if uri != "":
                conf.write('\n\t\t\t\t\turi = "%s%s%s.fastq.gz"' % (uri,delim,fastq_base))
            else:
                conf.write('\n\t\t\t\t\turi = ""')
            if format != "FASTQ":
                conf.write('\n\t\t\t\t\tformat = "%s"' % (format))
            else:
                conf.write('\n\t\t\t\t\tformat = "FASTQ"')
            if paired != "true":
                conf.write('\n\t\t\t\t\tpaired = "%s"' % (paired))
            else:
                conf.write('\n\t\t\t\t\tpaired = "true"')
            if paired != "true":
                conf.write('\n\t\t\t\t\tpooled = "%s"' % (pooled))
            else:
                conf.write('\n\t\t\t\t\tpooled = "true"')
            if avail != "private":
                conf.write('\n\t\t\t\t\tavailability = "%s"' % (avail))
            else:
                conf.write('\n\t\t\t\t\tavailability = "private"')
            if adapt != "true":
                conf.write('\n\t\t\t\t\tadapterTrimmed = "%s"' % (adapt))
            else:
                conf.write('\n\t\t\t\t\tadapterTrimmed = "true"')
            if qual != "true":
                conf.write('\n\t\t\t\t\tqualityTrimmed = "%s"' % (qual))
            else:
                conf.write('\n\t\t\t\t\tqualityTrimmed = "true"')
            conf.write("\n\t\t\t\t },")
        conf.write("\n\t\t\t\t]\n\t\t\t}\n\t\t}\n}")
        return conf

def main():
        args = parse_args()
        delim = check_platform()
        filelist=get_sample_list(args.fdir)
        files = write_json(filelist,args.output_file,args.test_id,args.ccode,args.test_id_source,args.hmlid,args.uri,args.format,args.paired,args.pooled,args.avail,args.adapt,args.qual,delim)
        if os.path.isfile(args.output_file):
            print "Config file successfully created."

if __name__ == "__main__":
    sys.exit(main())


text:
// g2o - General Graph Optimization
// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#ifndef G2O_ROBOT_LASER_H
#define G2O_ROBOT_LASER_H

#include "raw_laser.h"
#include "g2o_types_data_api.h"
#include "g2o/core/hyper_graph_action.h"

namespace g2o {

  /**
   * \brief laser measurement obtained by a robot
   *
   * A laser measurement obtained by a robot. The measurement is equipped with a pose of the robot at which
   * the measurement was taken. The read/write function correspond to the CARMEN logfile format.
   */
  class G2O_TYPES_DATA_API RobotLaser : public RawLaser
  {
    public:
      EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
      RobotLaser();
      ~RobotLaser();

      virtual bool write(std::ostream& os) const;
      virtual bool read(std::istream& is);

      SE2 laserPose() const { return _odomPose * _laserParams.laserPose;}
      const SE2& odomPose() const { return _odomPose;}
      void setOdomPose(const SE2& odomPose);

    protected:
      SE2 _odomPose;
      //! velocities and safety distances of the robot.
      double _laserTv, _laserRv, _forwardSafetyDist, _sideSaftyDist, _turnAxis;
  };

#ifdef G2O_HAVE_OPENGL
  class G2O_TYPES_DATA_API RobotLaserDrawAction: public DrawAction{
  public:
    RobotLaserDrawAction();
    virtual HyperGraphElementAction* operator()(HyperGraph::HyperGraphElement* element,
            HyperGraphElementAction::Parameters* params_ );
  protected:
    virtual bool refreshPropertyPtrs(HyperGraphElementAction::Parameters* params_);
    IntProperty* _beamsDownsampling;
    FloatProperty* _pointSize;
    FloatProperty* _maxRange;
  };
#endif

}

#endif


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Tariff Calc | Web Site</title>
        <meta name="description" content="web application">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="./dist/main.css">


text:
namespace JustOrderIt.Web.Areas.Public.ViewModels.Comments
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using AutoMapper;
    using Data.Models;
    using Data.Models.Catalog;
    using Infrastructure.Mapping;

    public class CommentCacheViewModel : BasePublicViewModel<int>, IMapFrom<Comment>, IHaveCustomMappings
    {
        public string Content { get; set; }

        public string UserId { get; set; }

        public string UserName { get; set; }

        public int ProductId { get; set; }

        public void CreateMappings(IMapperConfigurationExpression configuration)
        {
            configuration.CreateMap<Comment, CommentCacheViewModel>()
                .ForMember(dest => dest.UserName, opt => opt.MapFrom(src => src.User.UserName));
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using Engine.Interfaces;
using Interop.Bindings;
using Interop.Exceptions.OpenGL;

namespace Engine {
    public class DemoRenderer : IRenderer {
        private IEnumerable<Geometry> _triangles;
        private IntPtr _window;

        public DemoRenderer(IntPtr window) {
            _window = window;
        }

        public void Cleanup() {
            foreach(var triangle in _triangles) {
                triangle.Cleanup();
            }
        }

        public void DrawScene() {
            // red, green, and blue values range from 0 (0) - 255 (1)
            OpenGL.ClearColor(1/255.0f, 113/255.0f, 187/255.0f, 1.0f);
            OpenGL.Clear(OpenGL.GL_COLOR_BUFFER_BIT);

            foreach(var triangle in _triangles) {
                triangle.Draw();
            }

            GLFW.SwapBuffers(_window);
        }

        public void SetupGeometry(IEnumerable<Geometry> geometry) {
            _triangles = geometry;
        }
    }
}


text:
package com.hazelcast.client.impl.protocol.task.map;

import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.codec.MapRemoveCodec;
import com.hazelcast.instance.Node;
import com.hazelcast.map.impl.MapContainer;
import com.hazelcast.map.impl.MapService;
import com.hazelcast.map.impl.operation.MapOperation;
import com.hazelcast.map.impl.operation.MapOperationProvider;
import com.hazelcast.nio.Connection;
import com.hazelcast.security.permission.ActionConstants;
import com.hazelcast.security.permission.MapPermission;
import com.hazelcast.spi.Operation;

import java.security.Permission;

public class MapRemoveMessageTask
        extends AbstractMapPartitionMessageTask<MapRemoveCodec.RequestParameters> {

    protected transient long startTimeNanos;

    public MapRemoveMessageTask(ClientMessage clientMessage, Node node, Connection connection) {
        super(clientMessage, node, connection);
    }

    @Override
    protected void beforeProcess() {
        startTimeNanos = System.nanoTime();
    }

    @Override
    protected void beforeResponse() {
        final long latencyNanos = System.nanoTime() - startTimeNanos;
        final MapService mapService = getService(MapService.SERVICE_NAME);
        MapContainer mapContainer = mapService.getMapServiceContext().getMapContainer(parameters.name);
        if (mapContainer.getMapConfig().isStatisticsEnabled()) {
            mapService.getMapServiceContext().getLocalMapStatsProvider().getLocalMapStatsImpl(parameters.name)
                    .incrementRemoveLatencyNanos(latencyNanos);
        }
    }

    @Override
    protected Operation prepareOperation() {
        MapOperationProvider operationProvider = getMapOperationProvider(parameters.name);
        MapOperation op = operationProvider.createRemoveOperation(parameters.name, parameters.key, false);
        op.setThreadId(parameters.threadId);
        return op;
    }

    @Override
    protected MapRemoveCodec.RequestParameters decodeClientMessage(ClientMessage clientMessage) {
        return MapRemoveCodec.decodeRequest(clientMessage);
    }

    @Override
    protected ClientMessage encodeResponse(Object response) {
        return MapRemoveCodec.encodeResponse(serializationService.toData(response));
    }

    @Override
    public String getServiceName() {
        return MapService.SERVICE_NAME;
    }

    public Permission getRequiredPermission() {
        return new MapPermission(parameters.name, ActionConstants.ACTION_REMOVE);
    }

    @Override
    public String getDistributedObjectName() {
        return parameters.name;
    }

    @Override
    public String getMethodName() {
        return "remove";
    }

    @Override
    public Object[] getParameters() {
        return new Object[]{parameters.key};
    }
}


text:
@class AVAssetExportSession, NSArray;

@interface KSIpodAudioDataProvider : KSAudioDataProvider
{
    _Bool _isReady;
    AVAssetExportSession *_exportSession;
    NSArray *_fileTypes;
}

@property(retain, nonatomic) NSArray *fileTypes; // @synthesize fileTypes=_fileTypes;
- (void).cxx_destruct;
- (void)exportdidComplete;
- (id)mimeType;
- (id)audioFileTypes;
- (_Bool)isReady;
- (_Bool)prepareAudioData;
- (void)close:(_Bool)arg1;
- (void)dealloc;
- (id)initWithSongInfo:(id)arg1 queue:(id)arg2 context:(void *)arg3;

@end