text:
from google.protobuf import text_format, json_format
from past.builtins import basestring

from recipe_engine.util import sentinel

# TODO(crbug.com/1147793): remove it after py3 migration is done.
def _msg_to_json_no_trailing_space(*args, **kwargs):
  jsonpb = json_format.MessageToJson(*args, **kwargs)
  return '\n'.join(l.rstrip() for l in jsonpb.splitlines())

BINARY = sentinel(
    'BINARY', ext='pb',
    enc=(lambda _self, msg, **extra: msg.SerializeToString(**extra)),
    enc_default_extra={
      'deterministic': True,
    },
    dec=(lambda _self, data, msg, **_extra: msg.ParseFromString(data)),
    dec_default_extra={})

TEXTPB = sentinel(
    'TEXTPB', ext='tpb',
    enc=staticmethod(text_format.MessageToString),
    enc_default_extra={},
    dec=staticmethod(text_format.Parse),
    dec_default_extra={})

JSONPB = sentinel(
    'JSONPB',
    ext='json',
    enc=staticmethod(_msg_to_json_no_trailing_space),
    enc_default_extra={
        'preserving_proto_field_name': True,
        'sort_keys': True,
        'indent': 2,
    },
    dec=staticmethod(json_format.Parse),
    dec_default_extra={'ignore_unknown_fields': True})

ALL_ENCODINGS = (BINARY, JSONPB, TEXTPB)
ENC_MAP = {str(enc): enc for enc in ALL_ENCODINGS}

def resolve(codec):
  """Resolves a codec to JSONPB, BINARY or TEXTPB.

  `codec` may be a string of the codec name, or the codec itself.

  Returns a codec.
  Raises a ValueError if the codec cannot be found.
  """
  if isinstance(codec, basestring):
    codec = ENC_MAP.get(codec, codec)
  if codec not in ALL_ENCODINGS: # pragma: no cover
    raise ValueError('Must specify a valid codec, got %r' % (codec,))
  return codec

def do_enc(codec, proto_msg, **extra_args):
  """Does a proto encoding operation.

  Args:
    * codec (JSONPB|BINARY|TEXTPB|str) - One of the codec
      sentinels, or its name.
    * proto_msg (message.Message) - A protobuf message to encode.
    * extra_args (dict|None) - any extra arguments for the encoder.

  Returns string of the encoded proto_msg.
  """
  codec = resolve(codec)

  extras = codec.enc_default_extra.copy()
  extras.update(extra_args)
  return codec.enc(proto_msg, **extras)

def do_dec(data, msg_class, codec, **extra_args):
  """Does a proto decoding operation.

  Args:
    * data (basestring) - The data to parse.
    * codec (JSONPB|BINARY|TEXTPB|str) - One of the codec
      sentinels, or its name.
    * proto_msg (message.Message) - A protobuf message to encode.
    * extra_args (dict|None) - any extra arguments for the encoder.

  Returns string of the encoded proto_msg.
  """
  codec = resolve(codec)

  extras = codec.dec_default_extra.copy()
  extras.update(extra_args)
  ret = msg_class()
  codec.dec(data, ret, **extras)
  return ret


text:
using System;
using System.CodeDom.Compiler;
using System.Xml.Serialization;

namespace MusicXMLUtils.Structure
{
    [GeneratedCode("xsd", "4.0.30319.18020")]
    [Serializable]
    [XmlType(TypeName = "bar-style")]
    public enum BarStyle
    {
        [XmlEnum("regular")]
        Regular,

        [XmlEnum("dotted")]
        Dotted,

        [XmlEnum("dashed")]
        Dashed,

        [XmlEnum("heavy")]
        Heavy,

        [XmlEnum("light-light")]
        LightLight,

        [XmlEnum("light-heavy")]
        LightHeavy,

        [XmlEnum("heavy-light")]
        HeavyLight,

        [XmlEnum("heavy-heavy")]
        HeavyHeavy,

        [XmlEnum("tick")]
        Tick,

        [XmlEnum("short")]
        Short,

        [XmlEnum("none")]
        None,
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="org.opencv"
      android:versionCode="243"
      android:versionName="2.4.3">

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="17" />

</manifest>


text:
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.7.6.1">
  <compounddef id="structboost_1_1geometry_1_1resolve__variant_1_1equals_3_01boost_1_1variant_3_01_b_o_o_s_t___v_a_898c9f85f328c171fd2118f1aeb433eb" kind="struct" prot="public">
    <compoundname>boost::geometry::resolve_variant::equals< boost::variant< BOOST_VARIANT_ENUM_PARAMS(T)>, Geometry2 ></compoundname>
    <includes local="no">equals.hpp</includes>
    <innerclass refid="structboost_1_1geometry_1_1resolve__variant_1_1equals_3_01boost_1_1variant_3_01_b_o_o_s_t___v_a_ceb97ec767f077ac27159bc3bff61db2" prot="public">boost::geometry::resolve_variant::equals< boost::variant< BOOST_VARIANT_ENUM_PARAMS(T)>, Geometry2 >::visitor</innerclass>
    <templateparamlist>
      <param>
        <type>BOOST_VARIANT_ENUM_PARAMS(typename T)</type>
      </param>
      <param>
        <type>typename Geometry2</type>
      </param>
    </templateparamlist>
      <sectiondef kind="public-static-func">
      <memberdef kind="function" id="structboost_1_1geometry_1_1resolve__variant_1_1equals_3_01boost_1_1variant_3_01_b_o_o_s_t___v_a_898c9f85f328c171fd2118f1aeb433eb_1a6ec8c8afb958f10f8bbeaf8190dfd9e4" prot="public" static="yes" const="no" explicit="no" inline="yes" virt="non-virtual">
        <type>bool</type>
        <definition>static bool boost::geometry::resolve_variant::equals< boost::variant< BOOST_VARIANT_ENUM_PARAMS(T)>, Geometry2 >::apply</definition>
        <argsstring>(boost::variant< BOOST_VARIANT_ENUM_PARAMS(T)> const &geometry1, Geometry2 const &geometry2)</argsstring>
        <name>apply</name>
        <param>
          <type>boost::variant< BOOST_VARIANT_ENUM_PARAMS(T)> const &</type>
          <declname>geometry1</declname>
        </param>
        <param>
          <type>Geometry2 const &</type>
          <declname>geometry2</declname>
        </param>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="/home/travis/build/boostorg/boost/boost/geometry/algorithms/equals.hpp" line="374" bodyfile="/home/travis/build/boostorg/boost/boost/geometry/algorithms/equals.hpp" bodystart="370" bodyend="376"/>
      </memberdef>
      </sectiondef>
    <briefdescription>
    </briefdescription>
    <detaileddescription>
    </detaileddescription>
    <location file="/home/travis/build/boostorg/boost/boost/geometry/algorithms/equals.hpp" line="352" bodyfile="/home/travis/build/boostorg/boost/boost/geometry/algorithms/equals.hpp" bodystart="351" bodyend="377"/>
    <listofallmembers>
      <member refid="structboost_1_1geometry_1_1resolve__variant_1_1equals_3_01boost_1_1variant_3_01_b_o_o_s_t___v_a_898c9f85f328c171fd2118f1aeb433eb_1a6ec8c8afb958f10f8bbeaf8190dfd9e4" prot="public" virt="non-virtual"><scope>boost::geometry::resolve_variant::equals< boost::variant< BOOST_VARIANT_ENUM_PARAMS(T)>, Geometry2 ></scope><name>apply</name></member>
    </listofallmembers>
  </compounddef>
</doxygen>


text:
@interface SyntaxHighlight ()
@property (nonatomic) BOOL isAlive;
@property (nonatomic) BOOL matchesDone;
@property SyntaxMatchStore* matchStore;
@property SyntaxMatchStore* overlapStore;
@property SyntaxMatchStore* renderTimeOverlapStore;
@end

@implementation SyntaxHighlight
@synthesize factory = _factory;
@synthesize delegate = _delegate;

- (id)initWithFile:(id<File>)file andDelegate:(id<CodeViewControllerDelegate>)delegate
{
    self = [super init];
    if (self) {
        _delegate = delegate;
        _currentFile = file;
        _overlays = [Constants syntaxOverlays];
        _bundle = [TMBundleSyntaxParser plistForExt:[file extension]];

        _syntaxPatterns = [[SyntaxPatterns alloc] initWithBundlePatterns:[_bundle objectForKey:@"patterns"] Repository:[_bundle objectForKey:@"repository"]];
        //NSLog(@"%@",_syntaxPatterns);
        _isAlive = YES;
        _matchesDone = NO;

        if ([[file contents] isKindOfClass:[NSString class]]) {
            _content = (NSString*)[file contents];
            _splitContent = [_content componentsSeparatedByString:@"\n"];
        }
        _overlapStore = [[SyntaxMatchStore alloc] init];
        _renderTimeOverlapStore = [[SyntaxMatchStore alloc] init];
        //reset ranges

    }
    return self;
}

- (NSArray*)capturableScopes:(NSString*)name
{
    NSArray *splitScopes = [name componentsSeparatedByString:@"."];
    NSString *accum = nil;
    NSMutableArray *scopes = [NSMutableArray array];

    for (NSString*  s in splitScopes) {
        if (!accum) {
            accum = s;
        } else {
            accum = [accum stringByAppendingFormat:@".%@",s];
        }
        [scopes addObject:accum];
    }
    return scopes;
}

- (void)applyStylesTo:(ArcAttributedString*)output
           withRanges:(SyntaxMatchStore*)pairs
            withTheme:(NSDictionary*)theme
{
    if (pairs) {
        for (NSString* scope in pairs.scopes) {
            //NSLog(@"%@",pairs.scopes);
            NSArray* ranges = [pairs rangesForScope:scope];
            NSArray* capturableScopes = [pairs capturableScopesForScope:scope];
            if (!capturableScopes) {
                capturableScopes = [self capturableScopes:scope];
            }
            if ([_overlays containsObject:capturableScopes[0]] && [pairs isEqual:_matchStore]) {
                [_renderTimeOverlapStore addParserResult:[[SyntaxParserResult alloc] initWithScope:scope Ranges:ranges CPS:capturableScopes]];
                continue;
            }
//            if ([[capturableScopes objectAtIndex:0] isEqualToString:@"meta"]) {
//                NSLog(@"arrgh");
//            }

            NSDictionary* styleScopes = [theme objectForKey:@"scopes"];
            //NSLog(@"%@",capturableScopes);
           // NSLog(@"%@",styleScopes);
            UIColor* fg = nil;
            for (NSString* ascope in capturableScopes) {
                NSDictionary* style = [styleScopes objectForKey:ascope];
                if (style) {
                    fg = [style objectForKey:@"foreground"];
                }
            }
            if (fg) {
                for (NSValue *v in ranges) {

                    NSRange range = [Utils rangeFromValue:v];
                    [output setForegroundColor:fg
                                       OnRange:range
                                    ForSetting:SYNTAX_KEY];
                }
            }

        }
    }

}

- (void)updateView:(ArcAttributedString*)output
         withTheme:(NSDictionary*)theme
{
    if (self.delegate) {
        [self.delegate mergeAndRenderWith:output
                                  forFile:_currentFile
                                WithStyle:[theme objectForKey:@"global"]
                                  AndTree:_foldTree];
    }
}

- (void)applyForeground:(ArcAttributedString*)output withTheme:(NSDictionary*)theme
{
    NSDictionary* global = [theme objectForKey:@"global"];
    UIColor* foreground = [global objectForKey:@"foreground"];
    if (foreground) {
        [output setForegroundColor:foreground OnRange:NSMakeRange(0, _content.length) ForSetting:SYNTAX_KEY];
    }
}

- (void)applyStylesTo:(ArcAttributedString*)output
            withTheme:(NSDictionary*)theme
{
    [output removeAttributesForSettingKey:SYNTAX_KEY];
    [self applyForeground:output withTheme:theme];
    [self applyStylesTo:output withRanges:_matchStore withTheme:theme];
    [self applyStylesTo:output withRanges:_overlapStore withTheme:theme];

}

- (void)setupFoldTree {
    NSString* foldStart = [_bundle objectForKey:@"foldingStartMarker"];
    NSString* foldEnd = [_bundle objectForKey:@"foldingStopMarker"];

    if (foldStart && foldEnd) {
        _foldTree = [CodeFolding foldTreeForContent:_content
                                          foldStart:foldStart
                                            foldEnd:foldEnd
                                         skipRanges:[NSArray array]
                                           delegate:self];
    }
}
- (void)execOn:(NSDictionary*)options
{
    _isAlive = YES;
    ArcAttributedString *output = [options objectForKey:@"attributedString"];
    _finalOutput = output;
    NSDictionary* theme = [options objectForKey:@"theme"];

    // "Greedy parser"
    _matchStore = [_syntaxPatterns parseResultsForContent:_content Range:NSMakeRange(0, _content.length)];

    // remove the previous attributes
    [output removeAttributesForSettingKey:SYNTAX_KEY];

    // apply results
    [self applyForeground:output withTheme:theme];
    [self applyStylesTo:output withRanges:_matchStore withTheme:theme];

    // render the overlaps
    [self applyStylesTo:output withRanges:_renderTimeOverlapStore withTheme:theme];

    // setup the fold tree.
    [self setupFoldTree];

    // update the view
    [self updateView:output withTheme:theme];
    //NSLog(@"view updated!");

    // "Forward Parse"
    _overlapStore = [_syntaxPatterns forwardParseForContent:_content Range:NSMakeRange(0, _content.length)];
    //NSLog(@"%@",_overlapStore);

    // remove duplicate scopes from matchStore
    [_matchStore removeDuplicateScopesWith:_overlapStore];

    // again
    [_renderTimeOverlapStore removeDuplicateScopesWith:_overlapStore];

    // remove everything again
    [output removeAttributesForSettingKey:SYNTAX_KEY];

    // apply results again.
    [self applyForeground:output withTheme:theme];
    [self applyStylesTo:output withRanges:_matchStore withTheme:theme];
    //[self applyStylesTo:output withRanges:_renderTimeOverlapStore withTheme:theme];
    [self applyStylesTo:output withRanges:_overlapStore withTheme:theme];
    [self updateView:output withTheme:theme];
     //NSLog(@"view updated!");
}

- (void)renderOn:(NSDictionary *)options {
     NSDictionary* theme = [options objectForKey:@"theme"];
    ArcAttributedString *output = [options objectForKey:@"attributedString"];
    [self applyStylesTo:output withTheme:theme];
     [self updateView:output withTheme:theme];
}
- (void)kill
{
    _isAlive = NO;
    _matchesDone = NO;
}

//- (void)testFoldsOnFoldRanges:(NSArray*)fR
//                   foldStarts:(NSArray*)fS
//                     foldEnds:(NSArray*)fE
//{
//
//    for (NSValue*v in fR) {
//        NSRange r;
//        [v getValue:&r];
//        [self styleOnRange:r fcolor:[UIColor yellowColor] output:_finalOutput];
//    }
//    //NSLog(@"_foldStarts: %@",_foldStarts);
//    for (NSValue* v in fS) {
//        NSRange r;
//        [v getValue:&r];
//        [self styleOnRange:r fcolor:[UIColor redColor] output:_finalOutput];
//    }
//
//    //NSLog(@"_foldEnds: %@",_foldEnds);
//    for (NSValue*v in fE) {
//        NSRange r;
//        [v getValue:&r];
//        [self styleOnRange:r fcolor:[UIColor greenColor] output:_finalOutput];
//    }
//
//}

@end


text:
/*
 * CCModuleGeneratorTest.java
 * JUnit based test
 *
 * Created on November 20, 2005, 9:48 PM
 *
 * 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.
 *
 */

package com.rometools.modules.cc.io;

import java.io.File;

import junit.framework.Test;
import junit.framework.TestSuite;

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

import com.rometools.modules.AbstractTestCase;
import com.rometools.modules.cc.CreativeCommons;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.SyndFeedOutput;

public class CCModuleGeneratorTest extends AbstractTestCase {

    private static final Logger LOG = LoggerFactory.getLogger(CCModuleGeneratorTest.class);

    public CCModuleGeneratorTest(final String testName) {
        super(testName);
    }

    public static Test suite() {
        final TestSuite suite = new TestSuite(CCModuleGeneratorTest.class);

        return suite;
    }

    public void testGenerate() throws Exception {
        LOG.debug("testGenerate");
        final SyndFeedInput input = new SyndFeedInput();
        final SyndFeedOutput output = new SyndFeedOutput();
        final File testDir = new File(super.getTestFile("xml"));
        final File[] testFiles = testDir.listFiles();
        for (int h = 0; h < testFiles.length; h++) {
            if (!testFiles[h].getName().endsWith(".xml")) {
                continue;
            }
            LOG.debug(testFiles[h].getName());
            final SyndFeed feed = input.build(testFiles[h]);
            // if( !feed.getFeedType().equals("rss_1.0"))
            {
                feed.setFeedType("rss_2.0");
                if (feed.getDescription() == null) {
                    feed.setDescription("test file");
                }
                output.output(feed, new File("target/" + testFiles[h].getName()));
                final SyndFeed feed2 = input.build(new File("target/" + testFiles[h].getName()));
                for (int i = 0; i < feed.getEntries().size(); i++) {
                    // FIXME
                    // final SyndEntry entry = feed.getEntries().get(i);
                    final SyndEntry entry2 = feed2.getEntries().get(i);
                    // / FIXME
                    // final CreativeCommons base = (CreativeCommons)
                    // entry.getModule(CreativeCommons.URI);
                    final CreativeCommons base2 = (CreativeCommons) entry2.getModule(CreativeCommons.URI);
                    LOG.debug("{}", base2);
                    // FIXME
                    // if( base != null)
                    // this.assertEquals( testFiles[h].getName(), base.getLicenses(),
                    // base2.getLicenses() );
                }
            }
        }

    }

}


text:
<?php
/**
 * Classe GestionnaireEntiteResultats
 *
 * Permet de gérer les résultats des requêtes du gestionnaire d'entités
 *
 * @author  Panpan76
 * @version 1.0
 */
class GestionnaireEntiteResultats{

  private $resultats;

  public function __construct($resultats = array()){
    $this->resultats = $resultats;
  }

  public function aleatoire(){
    shuffle($this->resultats);
    return $this;
  }

  public function getOne($id = 0){
    if(!isset($this->resultats[$id])){
      return null;
    }
    return $this->resultats[$id];
  }

  public function getAll(){
    return $this->resultats;
  }
}

?>


text:
#### A library that simulates array responses for sensors with arbitrary geometry and directional characteristics.

---
>
>    Archontis Politis, 2015
>
>    Department of Signal Processing and Acoustics, Aalto University, Finland
>
>    archontis.politis@aalto.fi
>
---

This Matlab/Octave library was developed during my doctoral research in the [Communication Acoustics Research Group] (http://spa.aalto.fi/en/research/research_groups/communication_acoustics/), Aalto University, Finland. If you would like to reference the code, you can refer to my dissertation published [here](https://aaltodoc.aalto.fi/handle/123456789/22499):

    Archontis Politis, Microphone array processing for parametric spatial audio techniques, 2016
    Doctoral Dissertation, Department of Signal Processing and Acoustics, Aalto University, Finland

## Description

This is a collection of MATLAB routines for simulation of array responses of

a) directional sensors and,

b) sensors mounted on, or at a distance from, a rigid spherical/cylindrical
scatterer.

The computation of their frequency and impulse responses is
based on the theoretical expansion of a scalar incident plane wave field to
a series of wavenumber-dependent Bessel-family functions and
direction-dependent Fourier or Legendre functions.

A function for arbitrary open arrays of directional microphones is included
not based on the expansion but directly on the steering vector formula of
inter-sensor delays and sensor gains for directional patterns
(e.g. arrays of cardioid microphones).

Most of the functionality of the library is displayed at [http://research.spa.aalto.fi/projects/arraysim-lib/arraysim.html],
or in the included script TEST_ARRAY_SIMULATOR.m

For more information on the expansions, you can have a look on

    Earl G. Williams, "Fourier Acoustics: Sound Radiation and Nearfield
    Acoustical Holography", Academic Press, 1999

    Heinz Teutsch, "Modal Array Signal Processing: Principles and
    Applications of Acoustic Wavefield Decomposition", Springer, 2007

and for example on
[http://en.wikipedia.org/wiki/Plane_wave_expansion] and
[http://en.wikipedia.org/wiki/Jacobi-Anger_expansion]

For any questions, comments, corrections, or general feedback, please
contact archontis.politis@aalto.fi

---

For more details on using functions, check their help output in Matlab.

### List of MATLAB files:

* sph_besselj.m     :   Various spherical Bessel-family functions and their
* sph_bessely.m     :   derivatives, for the computation of the radial
* sph_function.m    :   terms of the expansions (modal weights)
* sph_hankel1.m
* sph_hankel2.m
* dbesselj.m
* dbessely.m
* dhankel1.m
* dhankel2.m
* dsph_besselj.m
* dsph_bessely.m
* dsph_function.m
* dsph_hankel1.m
* dsph_hankel2.m

* simulateCylArray.m : Simulate cylindrical open arrays or arrays of sensors mounted on a rigid cylinder
* simulateSphArray.m : Simulate spherical open arrays or arrays of sensors mounted on a rigid sphere
* cylModalCoeffs.m : Compute the radial (modal) weights for a cylindrical scatterer
* sphModalCoeffs.m : Compute the radial (modal) weights for a spherical scatterer

* sphericalScatterer.m : Compute the response for a measurement point at an arbitrary distance from a rigid spherical scatterer
* cylindricalScatterer.m : Compute the response for a measurement point at an arbitrary distance from a rigid cylindrical scatterer

* getArrayResponse.m' :  Simulate open arrays of arbitrary directional microphones with axisymmetric responses


text:
package de.fu_berlin.cdv.chasingpictures;

import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import de.fu_berlin.cdv.chasingpictures.api.Picture;

/**
 * @author Simon Kalt
 */
public class PictureDownloader extends AsyncTask<Picture, PictureDownloader.Progress, Void> {
    private static final String TAG = "PictureDownloader";
    private static final int BUFFER_SIZE = 1024 * 100; // 100 KB
    private final File targetDirectory;
    private boolean cancelOnError = false;

    /**
     * Creates a new downloader, that tries to download all given
     * pictures, even if one download fails.
     *
     * @param targetDirectory Directory in the file system the pictures should be saved to.
     */
    public PictureDownloader(File targetDirectory) {
        this(targetDirectory, false);
    }

    /**
     * Creates a new downloader.
     *
     * @param targetDirectory Directory in the file system the pictures should be saved to.
     * @param cancelOnError Whether or not the downloader should stop downloading after an exception.
     */
    public PictureDownloader(File targetDirectory, boolean cancelOnError) {
        this.targetDirectory = targetDirectory;
        this.cancelOnError = cancelOnError;
    }

    @Override
    protected Void doInBackground(Picture... params) {
        int count = 0;

        for (Picture picture : params) {
            final Progress progress = new Progress(count, null);

            if (isCancelled())
                return null;

            try {
                String fileName = picture.getId() + "_" + picture.getUpdatedAt().getTime();
                File destinationFile = new File(targetDirectory, fileName);

                picture.setCachedFile(destinationFile);

                // If file already exists, (and isn't empty) skip the download.
                if (!(destinationFile.exists() && destinationFile.length() > 0)) {
                    URL url = picture.getASCIIUrl();
                    downloadUrlToFile(url, destinationFile);
                }
            } catch (IOException e) {
                Log.e(TAG, Log.getStackTraceString(e));
                picture.setCachedFile(null);
                progress.setException(e);
            }

            publishProgress(progress);
            count++;
        }
        return null;
    }

    @Override
    protected final void onProgressUpdate(Progress... values) {
        if (values.length > 0) {
            Progress progress = values[0];
            if (progress != null) {
                handleProgressUpdate(progress);
                handleException(progress.getException());
            }
        }
    }

    /**
     * Handle progress updates.
     *
     * @param progress The current progress, guaranteed to not be {@code null}
     */
    protected void handleProgressUpdate(@NonNull Progress progress) {

    }

    /**
     * If an exception occurred and {@link #cancelOnError} is set to true,
     * the downloading process will be stopped.
     *

     * Derived classes should call through to the super class's implementation of this method.
     * @param exception An exception, or {@code null} if none occurred
     */
    protected void handleException(@Nullable Throwable exception) {
        if (exception != null) {
            Log.e(TAG, "Exception during download.", exception);

            if (cancelOnError)
                cancel(true);
        }
    }

    private void downloadUrlToFile(URL url, File destinationFile) throws IOException {
        String location;
        HttpURLConnection urlConnection;

        // Follow redirects
        while (true) {
            urlConnection = ((HttpURLConnection) url.openConnection());

            /*
            urlConnection.setConnectTimeout(15000);
            urlConnection.setReadTimeout(15000);
            urlConnection.setInstanceFollowRedirects(false);
             */

            switch (urlConnection.getResponseCode()) {
                case HttpURLConnection.HTTP_MOVED_PERM:
                case HttpURLConnection.HTTP_MOVED_TEMP:
                    location = urlConnection.getHeaderField("Location");
                    url = new URL(url, location);  // Deal with relative URLs
                    continue;
            }

            break;
        }

        int contentLength = urlConnection.getContentLength();

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        FileOutputStream fos = new FileOutputStream(destinationFile);
        byte[] buffer;

        if (contentLength > 0) {
            buffer = new byte[contentLength];
        } else {
            buffer = new byte[BUFFER_SIZE];
        }

        try {
            int result;
            do {
                result = in.read(buffer);
                if (result > 0)
                    fos.write(buffer, 0, result);
            } while (result > 0);
        } finally {
            in.close();
            fos.close();
        }
    }

    /**
     * Class indicating the progress of downloading.
     * If an exception happened, it can be retrieved using {@link #getException()}.
     */
    public static class Progress {
        private final int state;
        @Nullable
        private Throwable exception;

        public Progress(int state) {
            this.state = state;
        }

        public Progress(int state, @Nullable Throwable exception) {
            this.state = state;
            this.exception = exception;
        }

        public int getState() {
            return state;
        }

        @Deprecated
        public int getCurrent() {
            return state;
        }

        /**
         * Returns the exception published with this progress update.
         *
         * @return A {@link Throwable} describing the error, or {@code null} if no exception occurred.
         */
        @Nullable
        public Throwable getException() {
            return exception;
        }

        public void setException(@Nullable Throwable exception) {
            this.exception = exception;
        }
    }
}


text:
package sorcer.core.monitoring;

import org.rioproject.event.RemoteServiceEvent;
import sorcer.core.analytics.MethodAnalytics;

/**
 * @author Dennis Reedy
 */
public class MonitorEvent extends RemoteServiceEvent {
    static final long serialVersionUID = 1L;
    private final String identifier;
    private final String owner;
    private final Monitor.Status status;
    private final MethodAnalytics analytics;

    public MonitorEvent(Object source, String identifier, String owner, Monitor.Status status, MethodAnalytics analytics) {
        super(source);
        this.identifier = identifier;
        this.status = status;
        this.owner = owner;
        this.analytics = analytics;
    }

    public String getIdentifier() {
        return identifier;
    }

    public String getOwner() {
        return owner;
    }

    public Monitor.Status getStatus() {
        return status;
    }

    public MethodAnalytics getAnalytics() {
        return analytics;
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AbsyntaxExcelAddIn.Core.Converters;
using Excel = Microsoft.Office.Interop.Excel;

namespace AbsyntaxExcelAddIn.Core
{
    /// <summary>
    /// Encapsulates all details necessary to invoke an Absyntax project.
    /// </summary>
    /// <remarks>
    /// This class also acts a UI view-model for list items in the project configuration dialogue.
    /// </remarks>
    public sealed class ProjectInvocationRule : NotifyPropertyChangedBase, IProjectInvocationRule
    {
        static ProjectInvocationRule()
        {
            var orderings = Enum.GetValues(typeof(RangeOrdering)).Cast<RangeOrdering>();
            var roc = new RangeOrderingConverter();
            s_availableRangeOrderingNames = orderings.Select(o => (string)roc.Convert(o, null, null, null));

            var timeUnits = Enum.GetValues(typeof(TimeUnit)).Cast<TimeUnit>();
            var tuc = new TimeUnitConverter();
            s_availableTimeUnitNames = timeUnits.Select(o => (string)tuc.Convert(o, null, null, null));
        }

        private static readonly IEnumerable<string> s_availableRangeOrderingNames;

        private static readonly IEnumerable<string> s_availableTimeUnitNames;

        private ProjectInvocationRule()
        { }

        /// <summary>
        /// Initialises a new ProjectInvocationRule using persisted field values.
        /// </summary>
        /// <param name="wsProvider">An IWorksheetProvider implementation.</param>
        /// <param name="nrProvider">An INamedRangeProvider implementation.</param>
        /// <param name="reader">An IDataReader capable of supplying the requisite field values on demand.</param>
        /// <exception cref="System.ArgumentNullException">Either the IWorksheetProvider or the INamedRangeProvider
        /// is null.</exception>
        /// <exception cref="System.NullReferenceException">The IDataReader is null.</exception>
        public ProjectInvocationRule(IWorksheetProvider wsProvider, INamedRangeProvider nrProvider, IDataReader reader)
        {
            SetProviders(wsProvider, nrProvider);
            Id = reader.Read<int>();
            UsesInput = reader.Read<bool>();
            InputSheetKey = reader.Read<string>();
            InputCellRange = reader.Read<string>();
            InputRangeOrder = reader.Read<RangeOrdering>();
            TimeLimit = reader.Read<int>();
            Unit = reader.Read<TimeUnit>();
            UsesOutput = reader.Read<bool>();
            OutputSheetKey = reader.Read<string>();
            OutputCellRange = reader.Read<string>();
            OutputRangeOrder = reader.Read<RangeOrdering>();
            ProjectPath = reader.Read<string>();
            ReloadProjectBeforeExecuting = reader.Read<bool>();
            Enabled = reader.Read<bool>();
            LastExecutionResult = reader.Read<ExecutionResult>();
            UpdateInputSheetRangeNames();
            UpdateOutputSheetRangeNames();
        }

        /// <summary>
        /// Initialises a new, empty ProjectInvocationRule instance.
        /// </summary>
        /// <param name="wsProvider">An IWorksheetProvider implementation.</param>
        /// <param name="nrProvider">An INamedRangeProvider implementation.</param>
        /// <param name="id">A number that identifies the ProjectInvocationRule in a set of such rules.</param>
        /// <exception cref="System.ArgumentNullException">Either the IWorksheetProvider or the INamedRangeProvider
        /// is null.</exception>
        public ProjectInvocationRule(IWorksheetProvider wsProvider, INamedRangeProvider nrProvider, int id)
        {
            SetProviders(wsProvider, nrProvider);
            Id = id;
            m_inputSheetKey = m_outputSheetKey = GetFirstSheetKey();
            UpdateInputSheetRangeNames();
            UpdateOutputSheetRangeNames();
        }

        /// <summary>
        /// Sets this ProjectInvocationRule's IWorksheetProvider and INamedRangeProvider references, throwing an
        /// ArgumentNullException if either is null.
        /// </summary>
        private void SetProviders(IWorksheetProvider wsProvider, INamedRangeProvider nrProvider)
        {
            if (wsProvider == null) {
                throw new ArgumentNullException("wsProvider");
            }
            if (nrProvider == null) {
                throw new ArgumentNullException("nrProvider");
            }
            m_wsProvider = wsProvider;
            m_nrProvider = nrProvider;
        }

        /// <summary>
        /// Gets the key of the first worksheet returned by the encapsulated IWorksheetProvider.
        /// </summary>
        private string GetFirstSheetKey()
        {
            Excel.Worksheet worksheet = GetFirstSheet();
            return GetSheetKey(worksheet);
        }

        /// <summary>
        /// An IWorksheetProvider implementation responsible for supplying the available worksheets on
        /// demand.
        /// </summary>
        private IWorksheetProvider m_wsProvider;

        /// <summary>
        /// An INamedRangeProvider implementation responsible for providing services in respect of Excel
        /// range names.
        /// </summary>
        private INamedRangeProvider m_nrProvider;

        private int m_id;

        /// <summary>
        /// Gets a number that identifies this ProjectInvocationRule in a set of such rules.
        /// </summary>
        public int Id
        {
            get { return m_id; }
            internal set { m_id = value; }
        }

        private bool m_isSelected;

        /// <summary>
        /// Gets or sets a value indicating whether this ProjectInvocationRule is selected in a list of
        /// such items.
        /// </summary>
        public bool IsSelected
        {
            get { return m_isSelected; }
            set { SetProperty(ref m_isSelected, value, () => IsSelected); }
        }

        public bool m_reloadProjectBeforeExecuting;

        /// <summary>
        /// Gets or sets a value indicating whether the represented Absyntax project should be reloaded
        /// prior to each invocation.
        /// </summary>
        /// <remarks>
        /// For performance reasons it is advantageous to leave a project loaded in memory between
        /// invocations because project-loading is a relatively slow process.  However, once a project
        /// is loaded then any changes made to the source project file can only be realised if the project
        /// is reloaded.  Setting this property to true is particularly useful if you are in the process
        /// of making changes to a project at the same time as using it with this add-in.
        /// </remarks>
        public bool ReloadProjectBeforeExecuting
        {
            get { return m_reloadProjectBeforeExecuting; }
            set { SetProperty(ref m_reloadProjectBeforeExecuting, value, () => ReloadProjectBeforeExecuting); }
        }

        private bool m_enabled = true;

        /// <summary>
        /// Gets or sets a value indicating whether this ProjectInvocationRule is enabled.
        /// </summary>
        /// <remarks>
        /// Disabled rules are not invoked.
        /// </remarks>
        public bool Enabled
        {
            get { return m_enabled; }
            set { SetProperty(ref m_enabled, value, () => Enabled); }
        }

        private bool m_usesInput;

        /// <summary>
        /// Gets or sets a value indicating whether data will be obtained from a worksheet and passed to
        /// the represented Absyntax project before each invocation.
        /// </summary>
        /// <remarks>
        /// Some Absyntax projects may have an entry-point that requires data, others may not.  Users are
        /// reasonably expected to know these details.
        /// </remarks>
        public bool UsesInput
        {
            get { return m_usesInput; }
            set {
                if (SetProperty(ref m_usesInput, value, () => UsesInput)) {
                    UpdateValidityInternal();
                }
            }
        }

        private string m_inputSheetKey;

        /// <summary>
        /// Gets the unique key of the worksheet that will be used to provide input data to the represented
        /// Absyntax project when UsesInput is set to true.
        /// </summary>
        public string InputSheetKey
        {
            get { return m_inputSheetKey; }
            private set { m_inputSheetKey = value; }
        }

        /// <summary>
        /// Gets or sets the name of the worksheet that will be used to provide input data to the represented
        /// Absyntax project when UsesInput is set to true.
        /// </summary>
        public string InputSheetName
        {
            get { return GetSheetName(m_inputSheetKey); }
            set {
                Excel.Worksheet ws = GetSheetByName(value);
                m_inputSheetKey = GetSheetKey(ws);
                EnsureCompatibleCellRange(m_inputSheetKey, InputCellRange, () => InputCellRange = String.Empty);
                OnPropertyChanged(() => InputSheetName);
                UpdateValidityInternal();
            }
        }

        /// <summary>
        /// Ensures that a cell range is compatible with a currently selected sheet name.
        /// </summary>
        private void EnsureCompatibleCellRange(string sheetKey, string cellRange, Action action)
        {
            Excel.Worksheet ws = m_nrProvider.IdentifyWorksheet(cellRange);
            if (ws == null) return;
            string otherKey = GetSheetKey(ws);
            if (sheetKey != otherKey) {
                action();
            }
        }

        /// <summary>
        /// Updates the list of available input sheet range names for the currently selected input worksheet
        /// name.
        /// </summary>
        private void UpdateInputSheetRangeNames()
        {
            string[] rangeNames = m_nrProvider.GetRangeNames();
            InputSheetRangeNames = rangeNames;
        }

        private string m_inputCellRange = "A1:B2";

        /// <summary>
        /// Gets or sets a notation defining a range of cells that will be used to obtain input data to be
        /// passed to the represented Absyntax project before each invocation when UsesInput is set to true.
        /// </summary>
        /// <remarks>
        /// This property supports range names.  Because a named range may consist of multiple areas, this
        /// means that it is possible to read input data from non-contiguous cells.  In such cases, data is
        /// read from areas in the order they are defined within the named range.
        /// </remarks>
        public string InputCellRange
        {
            get { return m_inputCellRange; }
            set {
                if (SetProperty(ref m_inputCellRange, value, () => InputCellRange)) {
                    EnsureCompatibleInputSheet();
                    UpdateValidityInternal();
                }
            }
        }

        private RangeOrdering m_inputRangeOrder;

        /// <summary>
        /// Gets or sets a value that determines the order in which the input data range of cell values are to
        /// be offered to the represented Absyntax project before each invocation when UsesInput is set to true.
        /// </summary>
        public RangeOrdering InputRangeOrder
        {
            get { return m_inputRangeOrder; }
            set { SetProperty(ref m_inputRangeOrder, value, () => InputRangeOrder); }
        }

        private bool m_usesOutput;

        /// <summary>
        /// Gets or sets a value indicating whether any data output by the represented Absyntax project will
        /// be written to a worksheet after each invocation.
        /// </summary>
        /// <remarks>
        /// Some Absyntax projects may have an exit-point that passes data, others may not.  Users are at
        /// liberty to ignore a project's output data if they want to.
        /// </remarks>
        public bool UsesOutput
        {
            get { return m_usesOutput; }
            set {
                if (SetProperty(ref m_usesOutput, value, () => UsesOutput)) {
                    UpdateValidityInternal();
                }
            }
        }

        private string m_outputSheetKey;

        /// <summary>
        /// Gets the unique key of the worksheet that will be used to write output data received from the
        /// represented Absyntax project when UsesOutput is set to true.
        /// </summary>
        public string OutputSheetKey
        {
            get { return m_outputSheetKey; }
            private set { m_outputSheetKey = value; }
        }

        /// <summary>
        /// Gets or sets the name of the worksheet that will be used to write output data received from the
        /// represented Absyntax project when UsesOutput is set to true.
        /// </summary>
        public string OutputSheetName
        {
            get { return GetSheetName(m_outputSheetKey); }
            set {
                Excel.Worksheet ws = GetSheetByName(value);
                m_outputSheetKey = GetSheetKey(ws);
                EnsureCompatibleCellRange(m_outputSheetKey, OutputCellRange, () => OutputCellRange = String.Empty);
                OnPropertyChanged(() => OutputSheetName);
                UpdateValidityInternal();
            }
        }

        private string m_outputCellRange = "C1";

        /// <summary>
        /// Gets or sets a notation defining a range of cells that will be used to write data received from
        /// the represented Absyntax project after each invocation when UsesOutput is set to true.
        /// </summary>
        /// <remarks>
        /// Note that a project's output is not confined to the specified range.  For example, if the range
        /// defines an area of two columns and five rows (i.e. ten cells) and the project outputs an array of
        /// 11 values, all 11 values will be written.  This is achieved by extending the range in a direction
        /// determined by the value of the OutputRangeOrder property.
        /// <para />
        /// In fact, the output cell range needs only to be defined in terms of 1 x n columns or n x 1 rows.
        /// For example, an output range defined as "C6:G6" with an output range ordering equal to
        /// RangeOrdering.ByRow will result in the first five output values being written to cells C6 through
        /// G6, the next five being written to cells C7 through G7 and so on.  Similarly, an output range
        /// defined as "C6:C10" with an output range ordering equal to RangeOrdering.ByColumn will result in
        /// the first five output values being written to cells C6 through C10, the next five being written to
        /// cells D6 through D10 and so on.
        /// <para />
        /// This property also supports range names.  Because a named range may consist of multiple areas, this
        /// means that it is possible to write output data to non-contiguous cells.  In such cases, data is
        /// written to areas in the order they are defined within the named range.  Only the last area may be
        /// extended as described above.  All other areas are filled up in turn.
        /// </remarks>
        public string OutputCellRange
        {
            get { return m_outputCellRange; }
            set {
                if (SetProperty(ref m_outputCellRange, value, () => OutputCellRange)) {
                    EnsureCompatibleOutputSheet();
                    UpdateValidityInternal();
                }
            }
        }

        /// <summary>
        /// Updates the list of available output sheet range names for the currently selected output worksheet
        /// name.
        /// </summary>
        private void UpdateOutputSheetRangeNames()
        {
            string[] rangeNames = m_nrProvider.GetRangeNames();
            OutputSheetRangeNames = rangeNames;
        }

        private RangeOrdering m_outputRangeOrder;

        /// <summary>
        /// Gets or sets a value that determines the order in which cells are to be written using output data
        /// received from the represented Absyntax project are to be written after each invocation when
        /// UsesOutput is set to true.
        /// </summary>
        public RangeOrdering OutputRangeOrder
        {
            get { return m_outputRangeOrder; }
            set { SetProperty(ref m_outputRangeOrder, value, () => OutputRangeOrder); }
        }

        private int m_timeLimit = 10;

        /// <summary>
        /// Gets or sets a value which, when combined with the Unit property value, determines the amount of
        /// time that Absyntax will allow for a project invocation to complete before terminating an
        /// invocation.
        /// </summary>
        public int TimeLimit
        {
            get { return m_timeLimit; }
            set {
                if (value > 0) {
                    m_timeLimit = value;
                }
                OnPropertyChanged(() => TimeLimit);
            }
        }

        private TimeUnit m_timeUnit;

        /// <summary>
        /// Gets or sets a value which, when combined with the TimeLimit property value, determines the amount
        /// of time that Absyntax will allow for a project invocation to complete before terminating an
        /// invocation.
        /// </summary>
        public TimeUnit Unit
        {
            get { return m_timeUnit; }
            set { SetProperty(ref m_timeUnit, value, () => Unit); }
        }

        private string m_projectPath;

        /// <summary>
        /// Gets or sets the full path of the file containing the serialised form of the Absyntax project to
        /// be invoked.
        /// </summary>
        public string ProjectPath
        {
            get { return m_projectPath; }
            set {
                if (SetProperty(ref m_projectPath, value, () => ProjectPath)) {
                    UpdateValidityInternal();
                }
            }
        }

        /// <summary>
        /// Returns the first available worksheet.
        /// </summary>
        private Excel.Worksheet GetFirstSheet()
        {
            return m_wsProvider.GetWorksheets().FirstOrDefault();
        }

        /// <summary>
        /// Returns the worksheet whose name matches the supplied value.
        /// </summary>
        private Excel.Worksheet GetSheetByName(string name)
        {
            return m_wsProvider.GetWorksheets().FirstOrDefault(w => w.Name == name);
        }

        /// <summary>
        /// Returns the worksheet whose unique key matches the supplied value.
        /// </summary>
        private Excel.Worksheet GetSheetByKey(string key)
        {
            var wi = new WorksheetIdentifier();
            return wi.GetWorksheet(m_wsProvider, key);
        }

        /// <summary>
        /// Returns the name of the worksheet whose unique key is supplied.
        /// </summary>
        private string GetSheetName(string key)
        {
            Excel.Worksheet ws = GetSheetByKey(key);
            return ws == null ? null : ws.Name;
        }

        /// <summary>
        /// Returns the unique key of the supplied worksheet.  If the worksheet does not have one then one is
        /// created and assigned.
        /// </summary>
        private string GetSheetKey(Excel.Worksheet worksheet)
        {
            return worksheet == null ? null : new WorksheetIdentifier().GetKey(worksheet);
        }

        /// <summary>
        /// Gets a collection of the names of the available worksheets.
        /// </summary>
        public IEnumerable<string> AvailableSheetNames
        {
            get { return m_wsProvider.GetWorksheets().Select(w => w.Name); }
        }

        /// <summary>
        /// Gets a collection of the available range names for the currently selected input worksheet name.
        /// </summary>
        public IEnumerable<string> InputSheetRangeNames { get; private set; }

        /// <summary>
        /// Gets a collection of the available range names for the currently selected output worksheet name.
        /// </summary>
        public IEnumerable<string> OutputSheetRangeNames { get; private set; }

        /// <summary>
        /// Gets a collection of the names of the range-ordering options.
        /// </summary>
        public IEnumerable<string> AvailableRangeOrderingNames
        {
            get { return s_availableRangeOrderingNames; }
        }

        /// <summary>
        /// Gets a collection of the names of the time units.
        /// </summary>
        public IEnumerable<string> AvailableTimeUnits
        {
            get { return s_availableTimeUnitNames; }
        }

        /// <summary>
        /// Updates the IsValid property value based on the state of this ProjectInvocationRule.
        /// </summary>
        private void UpdateValidityInternal()
        {
            UpdateValidity(false);
        }

        /// <summary>
        /// Ensures that selected input and output sheets are compatible with their respective named cell
        /// ranges and updates the IsValid property value based on the state of this ProjectInvocationRule.
        /// </summary>
        public void UpdateValidity()
        {
            UpdateValidity(true);
        }

        /// <summary>
        /// Ensures that selected input and output sheets are compatible with their respective named cell
        /// ranges and updates the IsValid property value based on the state of this ProjectInvocationRule.
        /// </summary>
        /// <param name="ensureCompatibleSheets">Determines whether operations should be performed to ensure
        /// that the input and output sheet names are compatible with the current input and output cell ranges.</param>
        private void UpdateValidity(bool ensureCompatibleSheets)
        {
            if (ensureCompatibleSheets) {
                EnsureCompatibleInputSheet();
                EnsureCompatibleOutputSheet();
            }
            IsValid = DetermineValidity();
        }

        /// <summary>
        /// Ensures that the selected input sheet is compatible with the input cell range.
        /// </summary>
        /// <remarks>
        /// If the input cell range references a range name, this method ensures that the selected input
        /// sheet name corresponds with the name of the worksheet that is referenced by said name.  Excel
        /// allows the user to change the areas of a named range.
        /// </remarks>
        private void EnsureCompatibleInputSheet()
        {
            EnsureCompatibleSheet(InputCellRange, ws => InputSheetName = ws.Name);
        }

        /// <summary>
        /// Ensures that the selected output sheet is compatible with the output cell range.
        /// </summary>
        /// <remarks>
        /// If the output cell range references a range name, this method ensures that the selected output
        /// sheet name corresponds with the name of the worksheet that is referenced by said name.  Excel
        /// allows the user to change the areas of a named range.
        /// </remarks>
        private void EnsureCompatibleOutputSheet()
        {
            EnsureCompatibleSheet(OutputCellRange, ws => OutputSheetName = ws.Name);
        }

        /// <summary>
        /// Invokes an Action if a range name cannot be associated with an existing worksheet.
        /// </summary>
        private void EnsureCompatibleSheet(string cellRange, Action<Excel.Worksheet> action)
        {
            Excel.Worksheet ws = m_nrProvider.IdentifyWorksheet(cellRange);
            if (ws != null) {
                action(ws);
            }
        }

        /// <summary>
        /// Returns a value indicating whether this ProjectInvocationRule is in a valid state.
        /// </summary>
        private bool DetermineValidity()
        {
            if (UsesInput) {
                Excel.Worksheet ws = GetSheetByKey(m_inputSheetKey);
                if (ws == null) {
                    return false;
                }
                var v = new CellRangeValidator(InputCellRange, m_nrProvider);
                if (!v.IsValid) {
                    return false;
                }
            }
            if (UsesOutput) {
                Excel.Worksheet ws = GetSheetByKey(m_outputSheetKey);
                if (ws == null) {
                    return false;
                }
                var v = new CellRangeValidator(OutputCellRange, m_nrProvider);
                if (!v.IsValid) {
                    return false;
                }
            }
            if (!PathIsValid(ProjectPath)) {
                return false;
            }
            return true;
        }

        /// <summary>
        /// Determines whether a file path represents an existing file.
        /// </summary>
        private bool PathIsValid(string path)
        {
            if (path == null) return false;
            try {
                var fi = new FileInfo(path);
                return fi.Exists;
            }
            catch { }
            return false;
        }

        private bool m_isValid;

        /// <summary>
        /// Gets a value indicating whether this ProjectInvocationRule is in a state that permits it to be
        /// invoked.
        /// </summary>
        public bool IsValid
        {
            get { return m_isValid; }
            private set { SetProperty(ref m_isValid, value, () => IsValid); }
        }

        private ExecutionResult m_lastExecutionResult;

        /// <summary>
        /// Gets this ProjectInvocationRule's last execution result.
        /// </summary>
        public ExecutionResult LastExecutionResult
        {
            get { return m_lastExecutionResult; }
            internal set { SetProperty(ref m_lastExecutionResult, value, () => LastExecutionResult); }
        }

        /// <summary>
        /// Gets a value indicating whether this rule is in a state that allows the Absyntax project it
        /// represents to be executed.
        /// </summary>
        public bool CanExecute
        {
            get { return IsValid && Enabled; }
        }

        /// <summary>
        /// Reads a collection of values from cells in the input range of the selected input data worksheet,
        /// sequenced in accordance with the input range ordering value.
        /// </summary>
        /// <returns>A collection of cell values.</returns>
        /// <exception cref="System.InvalidOperationException">Either the UsesInput property value is
        /// false or this ProjectInvocationRule is not in a valid state.</exception>
        public IEnumerable<object> ReadInputData()
        {
            if (!UsesInput || !IsValid) {
                throw new InvalidOperationException();
            }
            var v = new CellRangeValidator(InputCellRange, m_nrProvider);
            Excel.Worksheet ws = GetSheetByKey(m_inputSheetKey);
            Excel.Range r = v.GetRange(ws);
            return Helper.GetRangeValues(r, InputRangeOrder);
        }

        /// <summary>
        /// Attempts to write an object to a range of cells defined by the various output-related state values
        /// of this ProjectInvocationRule.
        /// </summary>
        /// <remarks>
        /// If the object is enumerable, its enumerated values are written.
        /// </remarks>
        /// <exception cref="System.InvalidOperationException">The UsesOutput property value is false.</exception>
        public void WriteOutputData(object data)
        {
            if (!UsesOutput) {
                throw new InvalidOperationException();
            }
            var v = new CellRangeValidator(OutputCellRange, m_nrProvider);
            Excel.Worksheet ws = GetSheetByKey(m_outputSheetKey);
            Excel.Range r = v.GetRange(ws);
            IEnumerable e = data as IEnumerable;
            if (e == null || e is string) {
                ws.Cells[r.Row, r.Column] = data;
            }
            else {
                Helper.SetRangeValues(e.Cast<object>(), r, OutputRangeOrder);
            }
        }

        /// <summary>
        /// Clones this ProjectInvocationRule.
        /// </summary>
        /// <returns>A new ProjectInvocationRule instance representing a clone of this ProjectInvocationRule.</returns>
        public ProjectInvocationRule Clone()
        {
            var rule = new ProjectInvocationRule() {
                m_wsProvider = this.m_wsProvider,
                m_nrProvider = this.m_nrProvider,
                m_id = this.m_id,
                m_usesInput = this.m_usesInput,
                m_inputSheetKey = this.m_inputSheetKey,
                m_inputCellRange = this.m_inputCellRange,
                m_inputRangeOrder = this.m_inputRangeOrder,
                m_timeLimit = this.m_timeLimit,
                m_timeUnit = this.m_timeUnit,
                m_usesOutput = this.m_usesOutput,
                m_outputSheetKey = this.m_outputSheetKey,
                m_outputCellRange = this.m_outputCellRange,
                m_outputRangeOrder = this.m_outputRangeOrder,
                m_projectPath = this.m_projectPath,
                m_reloadProjectBeforeExecuting = this.m_reloadProjectBeforeExecuting,
                m_enabled = this.m_enabled,
                m_lastExecutionResult = this.m_lastExecutionResult
            };
            rule.UpdateInputSheetRangeNames();
            rule.UpdateOutputSheetRangeNames();
            rule.UpdateValidity(true);
            return rule;
        }

        /// <summary>
        /// Serialises this ProjectInvocationRule.
        /// </summary>
        /// <param name="writer">An IDataWriter to which field values are written.</param>
        public void Write(IDataWriter writer)
        {
            writer.Write(Id);
            writer.Write(UsesInput);
            writer.Write(InputSheetKey);
            writer.Write(InputCellRange);
            writer.Write(InputRangeOrder.ToString());
            writer.Write(TimeLimit);
            writer.Write(Unit.ToString());
            writer.Write(UsesOutput);
            writer.Write(OutputSheetKey);
            writer.Write(OutputCellRange);
            writer.Write(OutputRangeOrder.ToString());
            writer.Write(ProjectPath);
            writer.Write(ReloadProjectBeforeExecuting);
            writer.Write(Enabled);
            writer.Write(LastExecutionResult.ToString());
        }
    }
}


text:
package ch.pantas.billsplitter.ui;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.inject.Inject;

import java.util.List;

import ch.pantas.billsplitter.dataaccess.UserStore;
import ch.pantas.billsplitter.model.User;
import ch.pantas.billsplitter.remote.SimpleBluetoothClient;
import ch.pantas.billsplitter.services.ActivityStarter;
import ch.pantas.billsplitter.services.ExportService;
import ch.pantas.billsplitter.services.ImportService;
import ch.pantas.billsplitter.services.LoginService;
import ch.pantas.billsplitter.services.SharedPreferenceService;
import ch.pantas.billsplitter.services.UserService;
import ch.pantas.billsplitter.services.datatransfer.EventDto;
import ch.pantas.billsplitter.services.datatransfer.EventDtoBuilder;
import ch.pantas.billsplitter.services.datatransfer.EventDtoOperator;
import ch.pantas.billsplitter.services.datatransfer.ParticipantDto;
import ch.pantas.billsplitter.ui.adapter.BeamParticipantAdapter;
import ch.pantas.splitty.R;
import roboguice.inject.InjectView;

import static android.nfc.NfcAdapter.ACTION_NDEF_DISCOVERED;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
import static ch.pantas.billsplitter.remote.SimpleBluetoothServer.BluetoothListener;
import static ch.pantas.billsplitter.services.datatransfer.EventDtoBuilder.convertToJson;
import static com.google.inject.internal.util.$Preconditions.checkNotNull;
import static com.google.inject.internal.util.$Preconditions.checkState;
import static roboguice.RoboGuice.getInjector;

public class BeamEventReceiver extends BeamBaseActivity implements BluetoothListener {
    @InjectView(R.id.participant_list)
    private ListView participantsList;

    @InjectView(R.id.user_selection_container)
    private LinearLayout userSelectionContainer;

    @InjectView(R.id.join_as_new_user)
    private CheckBox joinCheckBox;

    @Inject
    private UserService userService;

    @Inject
    private UserStore userStore;

    @Inject
    private SharedPreferenceService sharedPreferenceService;

    @Inject
    private LoginService loginService;

    @Inject
    private ActivityStarter activityStarter;

    @Inject
    private ImportService importService;

    @Inject
    private ExportService exportService;

    private SimpleBluetoothClient bluetoothClient;

    private String deviceAddress;

    private EventDtoOperator eventDto;
    private BeamParticipantAdapter adapter;

    @Override
    protected int getContentView() {
        return R.layout.beam_event_receiver;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(R.string.beam_event);
        getWindow().addFlags(FLAG_KEEP_SCREEN_ON);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            setUpForBeam();
        }
    }

    @Override
    protected void startBeaming(NfcAdapter nfcAdapter, BluetoothAdapter bluetoothAdapter) {
        deviceAddress = extractMessage(getIntent());
        startBluetoothClient(bluetoothAdapter);
        setUpWaitingScreen();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (bluetoothClient != null) {
            bluetoothClient.cancel();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.beam_event_receiver, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        boolean visible = getSelectedUser() != null && userSelectionContainer.getVisibility() == VISIBLE;
        menu.findItem(R.id.action_import).setVisible(visible);

        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (R.id.action_import == item.getItemId()) {
            User selectedUser = getSelectedUser();
            checkNotNull(selectedUser);
            handleDto(selectedUser);

            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setUpUserSelectionScreen(List<ParticipantDto> unconfirmedParticipants) {
        checkState(canShowList() || canShowCheckbox());

        hideMessageAndIndicator();
        userSelectionContainer.setVisibility(VISIBLE);

        if (canShowList()) {
            adapter = getInjector(this).getInstance(BeamParticipantAdapter.class);
            adapter.setParticipants(unconfirmedParticipants);

            // preselect Uer with my name
            User me = userService.getMe();
            if (me != null) {
                boolean success = adapter.selectParticipantByName(me.getName());
                joinCheckBox.setChecked(!success);
            }

            participantsList.setAdapter(adapter);
            participantsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    ParticipantDto participantDto = (ParticipantDto) adapterView.getItemAtPosition(i);
                    boolean success = adapter.select(participantDto.getUser());
                    joinCheckBox.setChecked(!success);
                    participantsList.invalidateViews();
                    invalidateOptionsMenu();
                }
            });

        }

        joinCheckBox.setVisibility(GONE);
        if (canShowCheckbox()) {
            joinCheckBox.setVisibility(VISIBLE);
            joinCheckBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (joinCheckBox.isChecked()) {
                        disableList();
                    } else {
                        enableList();
                    }

                    invalidateOptionsMenu();
                }
            });
            joinCheckBox.setChecked(adapter == null || adapter.getSelected() == null);
        }

        invalidateOptionsMenu();
    }

    private void handleDto(User selectedUser) {
        User me = userService.getMe();
        if (me == null) {
            me = selectedUser;
            loginService.login(me);
        } else {
            eventDto.replaceUser(selectedUser, me);
        }

        eventDto.confirmParticipant(me);

        importService.importEvent(eventDto);
        sharedPreferenceService.storeActiveEventId(eventDto.getEvent().getId());

        EventDto newEventDto = exportService.exportEvent(eventDto.getEvent().getId());
        bluetoothClient.postMessage(convertToJson(newEventDto));

        // TODO: Server should send ACK before we show success screen
        userSelectionContainer.setVisibility(GONE);
        invalidateOptionsMenu();
        setUpSuccessScreen();
    }

    private User getSelectedUser() {
        if (canShowCheckbox() && joinCheckBox.isChecked()) {
            return userService.getMe();
        } else if (canShowList() && adapter != null) {
            return adapter.getSelected();
        }

        return null;
    }

    private void startBluetoothClient(BluetoothAdapter bluetoothAdapter) {
        bluetoothClient = getInjector(this).getInstance(SimpleBluetoothClient.class).init(bluetoothAdapter, deviceAddress, this);
        bluetoothClient.start();
    }

    private String extractMessage(Intent intent) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                NfcAdapter.EXTRA_NDEF_MESSAGES);

        NdefMessage msg = (NdefMessage) rawMsgs[0];

        // record 0 contains the MIME type, record 1 is the AAR, if present
        return new String(msg.getRecords()[0].getPayload());
    }

    private void disableList() {
        if (adapter == null) return;

        adapter.disable();
        participantsList.setEnabled(false);
        participantsList.invalidateViews();
    }

    private void enableList() {
        if (adapter == null) return;

        adapter.enable();
        participantsList.setEnabled(true);
        participantsList.invalidateViews();
    }

    @Override
    public void onMessageReceived(String message) {
        eventDto = new EventDtoOperator(EventDtoBuilder.createFromJson(message));

        User me = userService.getMe();

        if (eventDto.hasParticipant(me)) {
            handleDto(me);
            return;
        }

        if (!canShowList() && !canShowCheckbox()) {
            setUpErrorScreen(R.string.can_not_join_group);
            return;
        }

        setUpUserSelectionScreen(eventDto.getUnconfirmedParticipants());
    }

    private boolean canShowList() {
        if (eventDto == null) return false;

        return !eventDto.getUnconfirmedParticipants().isEmpty();
    }

    private boolean canShowCheckbox() {
        User me = userService.getMe();
        return me != null;
    }

    @Override
    public void onConnected() {

    }

    @Override
    public void onCommunicationError(Exception e) {
        setUpCommunicationErrorScreen();
    }
}


text:
namespace Raccoom.Xml.DemoWPF.Properties
{
    public partial class Settings : System.Configuration.ApplicationSettingsBase
    {
        private static Settings m_Value;

        private static object m_SyncObject = new object();

        public static Settings Value
        {
            get
            {
                if ((Settings.m_Value == null))
                {
                    System.Threading.Monitor.Enter(Settings.m_SyncObject);
                    if ((Settings.m_Value == null))
                    {
                        try
                        {
                            Settings.m_Value = new Settings();
                        }
                        finally
                        {
                            System.Threading.Monitor.Exit(Settings.m_SyncObject);
                        }
                    }
                }
                return Settings.m_Value;
            }
        }
    }
}


text:
import middy from '@middy/core'

declare const urlEncodePathParser: middy.Middleware<any, any, any>;

export default urlEncodePathParser


text:
namespace Serviceable.Objects.Stateful
{
    public interface IStatefulContext<out TState, TContextType>
        where TState : struct
        where TContextType : Context<TContextType>
    {
        TState State { get; }
    }
}


text:
package org.apache.activemq.openwire.v4;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import org.apache.activemq.openwire.*;
import org.apache.activemq.command.*;

/**
 * Test case for the OpenWire marshalling for PartialCommand
 *
 *
 * NOTE!: This file is auto generated - do not modify!
 * if you need to make a change, please see the modify the groovy scripts in the
 * under src/gram/script and then use maven openwire:generate to regenerate
 * this file.
 */
public class PartialCommandTest extends DataFileGeneratorTestSupport {

   public static PartialCommandTest SINGLETON = new PartialCommandTest();

   public Object createObject() throws Exception {
      PartialCommand info = new PartialCommand();
      populateObject(info);
      return info;
   }

   protected void populateObject(Object object) throws Exception {
      super.populateObject(object);
      PartialCommand info = (PartialCommand) object;

      info.setCommandId(1);
      info.setData("Data:1".getBytes());
   }
}


text:
package net.scalytica.symbiotic.pages

import japgolly.scalajs.react._
import japgolly.scalajs.react.extra.router.RouterCtl
import japgolly.scalajs.react.vdom.prefix_<^._
import net.scalytica.symbiotic.components.authentication.{
  LoginForm,
  RegistrationForm
}
import net.scalytica.symbiotic.css.{FontAwesome, LoginStyle}
import net.scalytica.symbiotic.logger.log
import net.scalytica.symbiotic.models.party.User
import net.scalytica.symbiotic.routing.SymbioticRouter
import net.scalytica.symbiotic.routing.SymbioticRouter._

import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
import scalacss.ScalaCssReact._

object LoginPage {

  case class Props(ctl: RouterCtl[View])

  case class State(ctl: RouterCtl[View], register: Boolean = false)

  class Backend($ : BackendScope[Props, State]) {

    def socialAuth(provider: String): Callback =
      $.state.map { s =>
        Callback
          .future(
            User.authenticate(provider).map { success =>
              if (success) s.ctl.set(SymbioticRouter.Home)
              else {
                log.error(s"Unable to authenticate with $provider")
                Callback.alert(
                  s"There was an error trying to authenticate with $provider"
                )
              }
            }
          )
          .runNow()
      }
  }

  val component = ReactComponentB[Props]("LoginPage")
    .initialState_P(p => State(ctl = p.ctl))
    .backend(new Backend(_))
    .render { $ =>
      <.div(
        LoginStyle.loginWrapper,
        <.div(
          LoginStyle.cardWrapper,
          if (! $.state.register) {
            LoginForm($.props.ctl)
          } else {
            RegistrationForm($.props.ctl)
          },
          <.div(
            LoginStyle.signupCard,
            <.div(
              ^.float.left,
              <.a(
                LoginStyle.btnGoogle,
                ^.href := s"$ServerBaseURI/authenticate/google",
                <.i(FontAwesome.google)
              ),
              <.span("\u00a0\u00a0"),
              <.a(
                LoginStyle.btnTwitter,
                ^.onClick --> Callback
                  .alert("not yet implemented"), //s"$ServerBaseURI/authenticate/github",
                <.i(FontAwesome.twitter)
              ),
              <.span("\u00a0\u00a0"),
              <.a(
                LoginStyle.btnGithub,
                ^.href := s"$ServerBaseURI/authenticate/github",
                <.i(FontAwesome.github)
              )
            ),
            <.div(
              ^.float.right,
              <.a(
                LoginStyle.btnRegister,
                ^.onClick --> $.modState(
                  st => st.copy(register = !st.register)
                ),
                if ($.state.register)
                  <.span(
                    <.i(LoginStyle.toRegister),
                    "\u00a0Login"
                  )
                else
                  <.span(
                    "Register\u00a0",
                    <.i(LoginStyle.toLogin)
                  )
              )
            )
          )
        )
      )
    }
    .build

  def apply(props: Props) = component(props)

  def apply(ctl: RouterCtl[View]) =
    component(Props(ctl = ctl))
}


text:
package org.gradle.external.javadoc.internal;

import org.jmock.Expectations;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

public class BooleanJavadocOptionFileOptionTest {
    private final JUnit4Mockery context = new JUnit4Mockery();
    private JavadocOptionFileWriterContext writerContextMock;
    private final String optionName = "testOption";
    private BooleanJavadocOptionFileOption booleanOption;

    @Before
    public void setUp() {
        context.setImposteriser(ClassImposteriser.INSTANCE);
        writerContextMock = context.mock(JavadocOptionFileWriterContext.class);

        booleanOption = new BooleanJavadocOptionFileOption(optionName, null);
    }

    @Test
    public void testWriteNullValue() throws IOException {
        booleanOption.write(writerContextMock);
    }

    @Test
    public void testWriteFalseValue() throws IOException {
        booleanOption.setValue(false);

        booleanOption.write(writerContextMock);
    }

    @Test
    public void testWriteTrueValue() throws IOException {
        booleanOption.setValue(true);

        context.checking(new Expectations() {{
            oneOf(writerContextMock).writeOption(optionName);
        }});

        booleanOption.write(writerContextMock);
    }
}


text:
ApplicationConfig
=================

.. php:namespace:: DreamCommerce\Resource
.. php:class:: ApplicationConfig

Check: :doc:`../resource`.

constants
*********

``CONFIG_BLOG_COMMENTS_ENABLE``
    Enable blog comments
``CONFIG_BLOG_COMMENTS_FOR_USERS``
    Only registered users are allowed to post blog comments
``CONFIG_BLOG_COMMENTS_MODERATION``
    Is blog comments moderation enabled - boolean
``CONFIG_BLOG_DOWNLOAD_FOR_USERS``
    Allow to download blog attached files - boolean
``CONFIG_BLOG_ITEMS_PER_PAGE``
    Blog items per page count
``CONFIG_COMMENT_ENABLE``
    Enable product comments - boolean
``CONFIG_COMMENT_FOR_USERS``
    Only registered users are allowed to post comments - boolean
``CONFIG_COMMENT_MODERATION``
    Is comments moderation enabled - boolean
``CONFIG_DEFAULT_CURRENCY_ID``
    Default currency identifier - integer
``CONFIG_DEFAULT_CURRENCY_NAME``
    Default currency name - ISO 4217 ("PLN") - string
``CONFIG_DEFAULT_LANGUAGE_ID``
    Default shop language identifier - integer
``CONFIG_DEFAULT_LANGUAGE_NAME``
    Default shop language name - language_REGION format (eg. "pl_PL") - string
``CONFIG_DIGITAL_PRODUCT_LINK_EXPIRATION_TIME``
    Product link expiration time (days) - integer
``CONFIG_DIGITAL_PRODUCT_NUMBER_OF_DOWNLOADS``
    Maximum downloads number per user - integer
``CONFIG_DIGITAL_PRODUCT_UNLOCKING_STATUS_ID``
    Status identifier which sends email with files - integer
``CONFIG_LOCALE_DEFAULT_WEIGHT``
    Shop weight unit:

    - KILOGRAM
    - GRAM
    - LBS
``CONFIG_LOYALTY_ENABLE``
    Is loyalty program enabled - boolean
``CONFIG_PRODUCT_DEFAULTS_ACTIVE``
    Is product active in default - boolean
``CONFIG_PRODUCT_DEFAULTS_AVAILABILITY_ID``
    Default availability identifier - integer
``CONFIG_PRODUCT_DEFAULTS_CODE``
    Default product code generating method, available values:

    - 1 - no method
    - 2 - following ID
    - 3 - random
``CONFIG_PRODUCT_DEFAULTS_DELIVERY_ID``
    Default product delivery identifier - integer
``CONFIG_PRODUCT_DEFAULTS_ORDER``
    Default ordering factor value - integer
``CONFIG_PRODUCT_DEFAULTS_STOCK``
    Default stock value - integer
``CONFIG_PRODUCT_DEFAULTS_TAX_ID``
    Default tax value identifier - integer
``CONFIG_PRODUCT_DEFAULTS_UNIT_ID``
    Default measurement unit identifier - integer
``CONFIG_PRODUCT_DEFAULTS_WARN_LEVEL``
    Default stock value warning level - integer
``CONFIG_PRODUCT_DEFAULTS_WEIGHT``
    Default product weight - float
``CONFIG_PRODUCT_NOTIFIES_ENABLE``
    Notify on product availabilities - boolean
``CONFIG_PRODUCT_SEARCH_ALL_TOKENS``
    Only for product name search - require exact phrase
``CONFIG_PRODUCT_SEARCH_CODE``
    Only for product details search - include product code
``CONFIG_PRODUCT_SEARCH_DESCRIPTION``
    Only for product details search - include product description - boolean
``CONFIG_PRODUCT_SEARCH_SHORT_DESCRIPTION``
    Only for product details search - include product short description
``CONFIG_PRODUCT_SEARCH_TYPE``
    Product search mode:

    - 1 - only in product name
    - 2 - in product name and other details
``CONFIG_REGISTRATION_CONFIRM``
    Require registration confirmation - boolean
``CONFIG_REGISTRATION_ENABLE``
    Enable user registration - boolean
``CONFIG_REGISTRATION_LOGIN_TO_SEE_PRICE``
    Only signed in users see price - boolean
``CONFIG_REGISTRATION_REQUIRE_ADDRESS``
    New users address requirements:

    - 0 - only email address and password
    - 1 - full address details
``CONFIG_SHIPPING_ADD_PAYMENT_COST_TO_FREE_SHIPPING``
    Force payment price addition even if free shipping is present - boolean
``CONFIG_SHIPPING_VOLUMETRIC_WEIGHT_ENABLE``
    Enable volumetric weight - boolean
``CONFIG_SHOPPING_ALLOW_OVERSELLING``
    Allow to sell more products than stock value - boolean
``CONFIG_SHOPPING_ALLOW_PRODUCT_DIFFERENT_CURRENCY``
    Allow to set currency per product - boolean
``CONFIG_SHOPPING_ALLOW_TO_BU_NOT_REG``
    Allow buying without registration - boolean
``CONFIG_SHOPPING_BASKET_ADDING``
    Actions performed upon product adding, available values:

    - 1 - refresh page and do not redirect to the basket
    - 2 - refresh page and perform redirection to the basket
    - 3 - do not refresh page, show confirmation message
``CONFIG_SHOPPING_BESTSELLER_ALGORITHM``
    Bestseller calculation algorithm:

    - 1 - most orders count
    - 2 - most orders amount
``CONFIG_SHOPPING_BESTSELLER_DAYS``
    Only for automatic mode - days count when product is marked as bestseller, available values:

    - 7 - last 7 days
    - 30 - last 30 days
    - 90 - last 90 days
    - 0 - lifetime
``CONFIG_SHOPPING_BESTSELLER_MODE``
    Marking as "bestseller" mode:

    - 0 - manual
    - 1 - automatic, based on users orders
``CONFIG_SHOPPING_CONFIRM_ORDER``
    Require order confirmation - boolean
``CONFIG_SHOPPING_MIN_ORDER_VALUE``
    Minimal order value - float
``CONFIG_SHOPPING_MIN_PROD_QUANTITY``
    Minimal product quantity - float
``CONFIG_SHOPPING_NEWPRODUCTS_DAYS``
    Automatic mode - number of days after product creation it will be marked as "new" - integer
``CONFIG_SHOPPING_NEWPRODUCTS_MODE``
    Products marking as "new" mode, available values:

    - 0 - manual
    - 1 - automatic, based on product creation date
``CONFIG_SHOPPING_OFF``
    Disable shopping - boolean
``CONFIG_SHOPPING_ORDER_VIA_TOKEN``
    Share order via link - boolean
``CONFIG_SHOPPING_PARCEL_CREATE_STATUS_ID``
    Order status after parcel is created - integer|null
``CONFIG_SHOPPING_PARCEL_SEND_STATUS_ID``
    Order status after parcel is sent - integer|null
``CONFIG_SHOPPING_PRICE_COMPARISON_FIELD``
    Field which products are identified by - for price comparison websites, available values:

    - code - product code
    - additional_isbn - ISBN code
    - additional_kgo - KGO price
    - additional_bloz7 - BLOZ7 code
    - additional_bloz12 - BLOZ12 code
``CONFIG_SHOPPING_PRICE_LEVELS``
    Defined price levels (1-3) - integer
``CONFIG_SHOPPING_PRODUCTS_ALLOW_ZERO``
    Allow to buy zero-priced products - boolean
``CONFIG_SHOPPING_SAVE_BASKET``
    Save basket contents - boolean
``CONFIG_SHOPPING_SHIPPING_EXTRA_STEP``
    Show shipping and payment, available values:

    - 0 - show in basket
    - 1 - show as separated step
``CONFIG_SHOPPING_UPDATE_STOCK_ON_BUY``
    Update stock values on buy - boolean
``CONFIG_SHOP_ADDRESS_1``
    Shop address line 1 - string
``CONFIG_SHOP_ADDRESS_2``
    Shop address line 2 - string
``CONFIG_SHOP_CITY``
    Shop city - string
``CONFIG_SHOP_COMPANY_NAME``
    Company name - string
``CONFIG_SHOP_COUNTRY``
    Shop country code - string
``CONFIG_SHOP_EMAIL``
    Shop mail e-mail address - string
``CONFIG_SHOP_FULL_ADDRESS``
    Shop full address - string
``CONFIG_SHOP_NAME``
    Full shop name - string
``CONFIG_SHOP_OFF``
    Is shop disabled - boolean
``CONFIG_SHOP_PHONE``
    Shop phone number - string
``CONFIG_SHOP_PROVINCE``
    Shop province - string
``CONFIG_SHOP_REGON``
    Company identification number - integer
``CONFIG_SHOP_TAX_ID``
    Tax identifier - integer
``CONFIG_SHOP_TRADE``
    Shop trade - string
``CONFIG_SHOP_TRADE_CODE``
    Shop trade code, available values:

    - children
    - books_and_multimedia
    - clothes
    - computers
    - delicatessen
    - gifts_and_accessories
    - health_and_beauty
    - hobby
    - home_and_garden
    - automotive
    - consumer_electronics
    - sport_and_travel
    - other
``CONFIG_SHOP_URL``
    Shop URL - string
``CONFIG_SHOP_ZIP_CODE``
    Shop postcode - string


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.AppPlatform.Models
{
    /// <summary> Required inbound or outbound traffic for Azure Spring Cloud instance. </summary>
    public partial class RequiredTraffic
    {
        /// <summary> Initializes a new instance of RequiredTraffic. </summary>
        internal RequiredTraffic()
        {
            IPs = new ChangeTrackingList<string>();
            Fqdns = new ChangeTrackingList<string>();
        }

        /// <summary> Initializes a new instance of RequiredTraffic. </summary>
        /// <param name="protocol"> The protocol of required traffic. </param>
        /// <param name="port"> The port of required traffic. </param>
        /// <param name="ips"> The ip list of required traffic. </param>
        /// <param name="fqdns"> The FQDN list of required traffic. </param>
        /// <param name="direction"> The direction of required traffic. </param>
        internal RequiredTraffic(string protocol, int? port, IReadOnlyList<string> ips, IReadOnlyList<string> fqdns, TrafficDirection? direction)
        {
            Protocol = protocol;
            Port = port;
            IPs = ips;
            Fqdns = fqdns;
            Direction = direction;
        }

        /// <summary> The protocol of required traffic. </summary>
        public string Protocol { get; }
        /// <summary> The port of required traffic. </summary>
        public int? Port { get; }
        /// <summary> The ip list of required traffic. </summary>
        public IReadOnlyList<string> IPs { get; }
        /// <summary> The FQDN list of required traffic. </summary>
        public IReadOnlyList<string> Fqdns { get; }
        /// <summary> The direction of required traffic. </summary>
        public TrafficDirection? Direction { get; }
    }
}


text:
package org.elasticsearch.xpack.core.ssl;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.env.Environment;
import org.elasticsearch.xpack.core.ssl.cert.CertificateInfo;

import javax.net.ssl.X509ExtendedTrustManager;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.security.AccessControlException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;

/**
 * Trust configuration that is backed by a {@link java.security.KeyStore}
 */
class StoreTrustConfig extends TrustConfig {

    private static final String TRUSTSTORE_FILE = "truststore";

    final String trustStorePath;
    final String trustStoreType;
    final SecureString trustStorePassword;
    final String trustStoreAlgorithm;

    /**
     * Create a new configuration based on the provided parameters
     *
     * @param trustStorePath      the path to the truststore
     * @param trustStorePassword  the password for the truststore
     * @param trustStoreAlgorithm the algorithm to use for reading the truststore
     */
    StoreTrustConfig(String trustStorePath, String trustStoreType, SecureString trustStorePassword, String trustStoreAlgorithm) {
        this.trustStorePath = trustStorePath;
        this.trustStoreType = trustStoreType;
        // since we support reloading the truststore, we must store the passphrase in memory for the life of the node, so we
        // clone the password and never close it during our uses below
        this.trustStorePassword = Objects.requireNonNull(trustStorePassword, "truststore password must be specified").clone();
        this.trustStoreAlgorithm = trustStoreAlgorithm;
    }

    @Override
    X509ExtendedTrustManager createTrustManager(@Nullable Environment environment) {
        final Path storePath = CertParsingUtils.resolvePath(trustStorePath, environment);
        try {
            KeyStore trustStore = getStore(storePath, trustStoreType, trustStorePassword);
            return CertParsingUtils.trustManager(trustStore, trustStoreAlgorithm);
        } catch (FileNotFoundException | NoSuchFileException e) {
            throw missingTrustConfigFile(e, TRUSTSTORE_FILE, storePath);
        } catch (AccessDeniedException  e) {
            throw unreadableTrustConfigFile(e, TRUSTSTORE_FILE, storePath);
        } catch (AccessControlException e) {
            throw blockedTrustConfigFile(e, environment, TRUSTSTORE_FILE, List.of(storePath));
        } catch (Exception e) {
            throw new ElasticsearchException("failed to initialize SSL TrustManager", e);
        }
    }

    @Override
    Collection<CertificateInfo> certificates(Environment environment) throws GeneralSecurityException, IOException {
        final KeyStore trustStore = getStore(environment, trustStorePath, trustStoreType, trustStorePassword);
        final List<CertificateInfo> certificates = new ArrayList<>();
        final Enumeration<String> aliases = trustStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            final Certificate certificate = trustStore.getCertificate(alias);
            if (certificate instanceof X509Certificate) {
                final boolean hasKey = trustStore.isKeyEntry(alias);
                certificates.add(new CertificateInfo(trustStorePath, trustStoreType, alias, hasKey, (X509Certificate) certificate));
            }
        }
        return certificates;
    }

    @Override
    List<Path> filesToMonitor(@Nullable Environment environment) {
        if (trustStorePath == null) {
            return Collections.emptyList();
        }
        return Collections.singletonList(CertParsingUtils.resolvePath(trustStorePath, environment));
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        StoreTrustConfig that = (StoreTrustConfig) o;
        return Objects.equals(trustStorePath, that.trustStorePath)
            && Objects.equals(trustStoreType, that.trustStoreType)
            && Objects.equals(trustStorePassword, that.trustStorePassword)
            && Objects.equals(trustStoreAlgorithm, that.trustStoreAlgorithm);
    }

    @Override
    public int hashCode() {
        return Objects.hash(trustStorePath, trustStoreType, trustStorePassword, trustStoreAlgorithm);
    }

    @Override
    public String toString() {
        return "trustStorePath=[" + trustStorePath +
                "], trustStoreAlgorithm=[" + trustStoreAlgorithm +
                "]";
    }
}


text:
describe 'Project requires' do
  it 'alphabetizes cop requires' do
    source   = SpecHelper::ROOT.join('lib', 'rubocop-rspec.rb').read
    requires = source.split("\n").grep(%r{rubocop/cop})

    expect(requires.join("\n")).to eql(requires.sort.join("\n"))
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<sbml xmlns="http://www.sbml.org/sbml/level2/version4" level="2" version="4">
  <model>
    <listOfCompartments>
      <compartment id="compartment" size="1" constant="false"/>
    </listOfCompartments>
    <listOfSpecies>
      <species id="S1" compartment="compartment" initialAmount="1"/>
    </listOfSpecies>
    <listOfEvents>
      <event id="e">
        <trigger>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <piecewise>
              <piece>
                <apply>
                  <plus/>
                  <cn type="integer"> 2 </cn>
                  <cn type="integer"> 1 </cn>
                </apply>
                <true/>
              </piece>
              <otherwise>
                <cn> 0.05 </cn>
              </otherwise>
            </piecewise>
          </math>
        </trigger>
        <listOfEventAssignments>
          <eventAssignment variable="compartment"/>
        </listOfEventAssignments>
      </event>
    </listOfEvents>
  </model>
</sbml>


text:
import java.util.Arrays;

import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * Use in conjunction with TopicListener to test the performance of ActiveMQ
 * Topics.
 */
public class TopicPublisher implements MessageListener {

    private static final char[] DATA = "abcdefghijklmnopqrstuvwxyz".toCharArray();

    private final Object mutex = new Object();
    private Connection connection;
    private Session session;
    private MessageProducer publisher;
    private Topic topic;
    private Topic control;

    private String url = "tcp://localhost:61616";
    private int size = 256;
    private int subscribers = 1;
    private int remaining;
    private int messages = 10000;
    private long delay;
    private int batch = 2000;

    private byte[] payload;

    public static void main(String[] argv) throws Exception {
        TopicPublisher p = new TopicPublisher();
        String[] unknown = CommandLineSupport.setOptions(p, argv);
        if (unknown.length > 0) {
            System.out.println("Unknown options: " + Arrays.toString(unknown));
            System.exit(-1);
        }
        p.run();
    }

    private void run() throws Exception {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);
        connection = factory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        topic = session.createTopic("topictest.messages");
        control = session.createTopic("topictest.control");

        publisher = session.createProducer(topic);
        publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        payload = new byte[size];
        for (int i = 0; i < size; i++) {
            payload[i] = (byte)DATA[i % DATA.length];
        }

        session.createConsumer(control).setMessageListener(this);
        connection.start();

        long[] times = new long[batch];
        for (int i = 0; i < batch; i++) {
            if (i > 0) {
                Thread.sleep(delay * 1000);
            }
            times[i] = batch(messages);
            System.out.println("Batch " + (i + 1) + " of " + batch + " completed in " + times[i] + " ms.");
        }

        long min = min(times);
        long max = max(times);
        System.out.println("min: " + min + ", max: " + max + " avg: " + avg(times, min, max));

        // request shutdown
        publisher.send(session.createTextMessage("SHUTDOWN"));

        connection.stop();
        connection.close();
    }

    private long batch(int msgCount) throws Exception {
        long start = System.currentTimeMillis();
        remaining = subscribers;
        publish();
        waitForCompletion();
        return System.currentTimeMillis() - start;
    }

    private void publish() throws Exception {

        // send events
        BytesMessage msg = session.createBytesMessage();
        msg.writeBytes(payload);
        for (int i = 0; i < messages; i++) {
            publisher.send(msg);
            if ((i + 1) % 1000 == 0) {
                System.out.println("Sent " + (i + 1) + " messages");
            }
        }

        // request report
        publisher.send(session.createTextMessage("REPORT"));
    }

    private void waitForCompletion() throws Exception {
        System.out.println("Waiting for completion...");
        synchronized (mutex) {
            while (remaining > 0) {
                mutex.wait();
            }
        }
    }

    public void onMessage(Message message) {
        synchronized (mutex) {
            System.out.println("Received report " + getReport(message) + " " + --remaining + " remaining");
            if (remaining == 0) {
                mutex.notify();
            }
        }
    }

    Object getReport(Message m) {
        try {
            return ((TextMessage)m).getText();
        } catch (JMSException e) {
            e.printStackTrace(System.out);
            return e.toString();
        }
    }

    static long min(long[] times) {
        long min = times.length > 0 ? times[0] : 0;
        for (int i = 0; i < times.length; i++) {
            min = Math.min(min, times[i]);
        }
        return min;
    }

    static long max(long[] times) {
        long max = times.length > 0 ? times[0] : 0;
        for (int i = 0; i < times.length; i++) {
            max = Math.max(max, times[i]);
        }
        return max;
    }

    static long avg(long[] times, long min, long max) {
        long sum = 0;
        for (int i = 0; i < times.length; i++) {
            sum += times[i];
        }
        sum -= min;
        sum -= max;
        return sum / times.length - 2;
    }

    public void setBatch(int batch) {
        this.batch = batch;
    }

    public void setDelay(long delay) {
        this.delay = delay;
    }

    public void setMessages(int messages) {
        this.messages = messages;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public void setSubscribers(int subscribers) {
        this.subscribers = subscribers;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}


text:
'use strict';

module.exports = function IpDeniedError(message, extra) {
  Error.captureStackTrace(this, this.constructor);
  this.name = this.constructor.name;
  this.message = message || 'The requesting IP was denied';
  this.extra = extra;
};

require('util').inherits(module.exports, Error);
//# sourceMappingURL=deniedError.js.map


text:
<!DOCTYPE html><html><head><meta charset="utf-8" />
<meta http-equiv="refresh" content="0;url=/place/jersey/companies/" />
</head></html>