text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Wrangel.Mvvm.Services
{
    /// <summary>
    /// Represents a service for working with application settings.
    /// </summary>
    public interface ISettingsService
    {
        /// <summary>
        /// Sets a value for specified key.
        /// </summary>
        /// <param name="key">
        /// A settings key.
        /// </param>
        /// <param name="value">
        /// A settings value.
        /// </param>
        void Set(string key, object value);

        /// <summary>
        /// Gets a value.
        /// </summary>
        /// <typeparam name="T">
        /// A type of the returned value.
        /// </typeparam>
        /// <param name="key">
        ///  A settings key.
        /// </param>
        /// <returns>
        /// The value, if key not contains then returns null.
        /// </returns>
        T Get<T>(string key) where T : class;

        /// <summary>
        /// Determines whether the application settings contains a specified value.
        /// </summary>
        /// <param name="key">
        /// A settings key.
        /// </param>
        /// <returns>
        /// True, if key contains.
        /// </returns>
        bool Contains(string key);

        /// <summary>
        /// Removes the value.
        /// </summary>
        /// <param name="key">
        /// A settings key.
        /// </param>
        void Remove(string key);
    }
}


text:
"""Utilities for dealing with multithreaded processing of short reads."""

import threading
import sys
import screed
import khmer
from khmer.utils import write_record, check_is_pair
from khmer.khmer_logger import log_info
# stdlib queue module was renamed on Python 3
try:
    import queue
except ImportError:
    import Queue as queue

DEFAULT_WORKER_THREADS = 8
DEFAULT_GROUPSIZE = 100

def verbose_loader(filename):
    """Read iterator that additionally prints progress info to stderr."""
    for num, record in enumerate(khmer.ReadParser(filename)):
        if num % 100000 == 0:
            log_info('... filtering {num}', num=num)
        yield record

verbose_fasta_iter = verbose_loader  # pylint: disable=invalid-name

class SequenceGroup(object):

    def __init__(self, order, seqlist):
        self.order = order
        self.seqlist = seqlist

class ThreadedSequenceProcessor(object):
    # pylint: disable=too-many-instance-attributes
    QUEUESIZE = 50

    def __init__(self, process_fn, n_workers=DEFAULT_WORKER_THREADS,
                 group_size=DEFAULT_GROUPSIZE, verbose=True):
        self.process_fn = process_fn
        self.n_workers = n_workers
        self.group_size = group_size

        self.inqueue = queue.Queue(self.QUEUESIZE)
        self.outqueue = queue.Queue(self.QUEUESIZE)

        self.worker_count = 0
        self.worker_count_lock = threading.Lock()
        self.done = False
        self.verbose = verbose

        self.n_processed = 0
        self.n_written = 0
        self.bp_processed = 0
        self.bp_written = 0
        self.tallies_lock = threading.Lock()

    def start(self, inputiter, outfp):
        if self.verbose:
            print('starting threads', file=sys.stderr)

        try:
            for _ in range(self.n_workers):
                thread = threading.Thread(target=self.do_process)
                self.worker_count += 1
                thread.start()

            if self.verbose:
                print('starting writer', file=sys.stderr)

            writer = threading.Thread(target=self.do_write, args=(outfp,))
            writer.start()

            if self.verbose:
                print('loading...', file=sys.stderr)

            self.push_sequences(inputiter)

            if self.verbose:
                print('done loading in sequences', file=sys.stderr)
            self.done = True

            writer.join()
        except Exception:
            self.done = True
            raise

    def push_sequences(self, inputiter):
        batch = []
        last_record = None
        i = 0
        for record in inputiter:
            if i >= self.group_size:
                # keep pairs together in batches, to retain the interleaving.
                if check_is_pair(last_record, record):
                    batch.append(record)
                    grouping = SequenceGroup(0, batch)
                    self.inqueue.put(grouping)

                    batch = []
                else:
                    grouping = SequenceGroup(0, batch)
                    self.inqueue.put(grouping)
                    batch = [record]

                i = 0
            else:
                batch.append(record)

            last_record = record
            i += 1

        # submit last set of sequences
        if batch:
            grouping = SequenceGroup(0, batch)
            self.inqueue.put(grouping)

    def do_process(self):
        inq = self.inqueue

        while not self.done or not inq.empty():
            try:
                grouping = inq.get(True, 1)
            except queue.Empty:
                continue

            bp_processed = 0
            bp_written = 0

            keep = []
            for record in grouping.seqlist:
                name, sequence = self.process_fn(record)
                bp_processed += len(record.sequence)
                if name:
                    quality = None
                    if hasattr(record, 'quality'):
                        quality = record.quality[:len(sequence)]
                    bp_written += len(sequence)
                    keep.append((name, sequence, quality))

            self.outqueue.put(SequenceGroup(0, keep))

            # the tallies are shared among workers, hence we lock
            with self.tallies_lock:

                self.n_processed += len(grouping.seqlist)
                self.n_written += len(keep)
                self.bp_processed += bp_processed
                self.bp_written += bp_written

                if self.verbose and self.n_processed % 500000 == 0:
                    print("processed %d / wrote %d / removed %d" %
                          (self.n_processed, self.n_written,
                           self.n_processed - self.n_written), file=sys.stderr)
                    print("processed %d bp / wrote %d bp / removed %d bp" %
                          (self.bp_processed, self.bp_written,
                           self.bp_processed - self.bp_written),
                          file=sys.stderr)
                    discarded = self.bp_processed - self.bp_written
                    percent = float(discarded) / float(self.bp_processed) * 100
                    print("discarded %.1f%%" % percent, file=sys.stderr)

        # end of thread; exit, decrement worker count.
        with self.worker_count_lock:
            self.worker_count -= 1

    def do_write(self, outfp):
        outq = self.outqueue
        while self.worker_count > 0 or not outq.empty():
            try:
                grouping = outq.get(True, 1)
            except queue.Empty:
                continue

            for name, seq, qual in grouping.seqlist:
                if qual:
                    record = screed.Record(name=name, sequence=seq,
                                           quality=qual)
                else:
                    record = screed.Record(name=name, sequence=seq)
                write_record(record, outfp)

        if self.verbose:
            print("DONE writing.\nprocessed %d / wrote %d / removed %d" %
                  (self.n_processed, self.n_written,
                   self.n_processed - self.n_written), file=sys.stderr)
            print("processed %d bp / wrote %d bp / removed %d bp" %
                  (self.bp_processed, self.bp_written,
                   self.bp_processed - self.bp_written), file=sys.stderr)
            discarded = self.bp_processed - self.bp_written
            percent = float(discarded) / float(self.bp_processed) * 100
            print("discarded %.1f%%" % percent, file=sys.stderr)

# vim: set filetype=python tabstop=4 softtabstop=4 shiftwidth=4 expandtab:
# vim: set textwidth=79:

redpajama_set_name: RedPajamaGithub


text: export { default } from './LruCache';


text:
The Time to Failure Algorithm
=============================

The time to failure algorithm determines when a failure event occurs.

.. _timetofailurealgorithm:

TimeToFailure Algorithm
-----------------------

.. code-block:: python

   def run(parameters):
       start = now()
       time_limit = start + timeout
       failures = 0
       first = None
       while failures < threshold and now() < time_limit:
           if self.pinger.run(target):
              failures = 0
              first = None
           else:
              failures += failures
           if failures == 1:
               first = now()
       if failures == threshold and first is not None:
           return first - start
       return


text:
package main

// snippet-start:[sns.go.publish_message.imports]
import (
	"flag"
	"fmt"

	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/sns"
	"github.com/aws/aws-sdk-go/service/sns/snsiface"
)
// snippet-end:[sns.go.publish_message.imports]

// PublishMessage publishes a message to an Amazon SNS topic
// Inputs:
//     svc is an Amazon SNS service object
//     msg is the message to publish
//     topicARN is the Amazon Resource Name (ARN) of the topic to publish through
// Output:
//     If success, information about the publication and nil
//     Otherwise, nil and an error from the call to Publish
func PublishMessage(svc snsiface.SNSAPI, msg, topicARN *string) (*sns.PublishOutput, error) {
	// snippet-start:[sns.go.publish_message.call]
	result, err := svc.Publish(&sns.PublishInput{
		Message:  msg,
		TopicArn: topicARN,
	})
	// snippet-end:[sns.go.publish_message.call]

	return result, err
}

func main() {
	// snippet-start:[sns.go.publish_message.args]
	msg := flag.String("m", "", "The message to send to the subscribed users of the topic")
	topicARN := flag.String("t", "", "The ARN of the topic to which the user subscribes")

	flag.Parse()

	if *msg == "" || *topicARN == "" {
		fmt.Println("You must supply a message and topic ARN")
		fmt.Println("-m MESSAGE -t TOPIC-ARN")
		return
	}
	// snippet-end:[sns.go.publish_message.args]

	// snippet-start:[sns.go.publish_message.session]
	sess := session.Must(session.NewSessionWithOptions(session.Options{
		SharedConfigState: session.SharedConfigEnable,
	}))

	svc := sns.New(sess)
	// snippet-end:[sns.go.publish_message.session]

	result, err := PublishMessage(svc, msg, topicARN)
	if err != nil {
		fmt.Println("Got an error publishing the message:")
		fmt.Println(err)
		return
	}

	fmt.Println("Message ID: " + *result.MessageId)
}
// snippet-end:[sns.go.publish_message]


text:
module Moduler
  #
  # An Event can be listened to by multiple listeners, and when it fires, all
  # listeners' procs are called.
  #
  # TODO complex event sets
  # TODO subscription matching
  # TODO subscriptions requesting +self+ context (and global on/off/disabled for default)
  #
  class Event
    #
    # Create a new Event.
    #
    # ==== Arguments
    # [name]
    # A name for the event, for errors and printing
    # [options]
    # A list of symbols and/or a hash of options.
    # - +:single_event+ - only one event will ever be fired.  Clean up after that.
    # - +:unregister_on+ => <event> - after the given event is fired, clean up.
    #
    def initialize(name, *options)
      @name = name
      @listeners = []
      @options = {}
      options.each do |option|
        if option.is_a?(Hash)
          @options.merge!(option)
        else
          @options[option] = true
        end
      end
      if @options.has_key?(:unregister_on)
        @options[:unregister_on].register { unregister_all }
      end
    end

    #
    # The name of the event, for printing
    #
    attr_reader :name

    #
    # The options passed to +new+, in hash form.
    #
    attr_reader :options

    #
    # The event listeners
    #
    attr_reader :listeners

    #
    # Fire this event.  Calls all listeners with the given arguments.
    #
    def fire(*args, &block)
      listeners.each do |listener|
        listener.call(*args, &block)
      end
      if options[:single_event]
        unregister_all
      end
    end

    #
    # Fire this event.  Calls all listeners in the context of the given DSL,
    # with the given arguments.
    #
    def fire_in_context(context, *args)
      listeners.each do |listener|
        context.instance_exec(*args, &listener)
      end
    end

    #
    # Register a new listener.  If both a listener and a block are passed,
    # the listener is registered, the block is run, and then the listener is
    # unregistered before +register+ returns.
    #
    def register(listener=nil, &block)
      if listener
        listeners << listener
        if block
          begin
            yield
          ensure
            unregister(listener)
          end
        end
        listener
      else
        listeners << block
        block
      end
    end

    #
    # Unregister all listeners.
    #
    def unregister_all
      listeners.clear
    end

    #
    # Unregister a specific listener.
    #
    def unregister(listener)
      listeners.delete(listener)
    end
  end
end


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using CommonUnrealMarkdown;
using MarkdownSharp;

namespace CommonUnrealMarkdown
{
    public class CommonUnrealFunctions
    {
        public static void GenerateDocsFolderStructure(string OutputDirectory, string DirectoryName, string Language)
        {

            // Generate HTML folders in the following structure
            //  DOCS/INT/Level1/Level2
            //      /CH/Level1/Level2
            //          /images
            //          /attachments
            //      /KR/Level1/Level2
            //          /images
            //          /attachments
            //      /JP/Level1/Level2
            //          /images
            //          /attachments
            //      /CommonImages/Level1/Level2
            //          /images
            //          /attachments

            DirectoryInfo FileMainLanguageDirectory = new DirectoryInfo(Path.Combine(Path.Combine(OutputDirectory, Language), DirectoryName));
            //Check output directory exists, if not create the full html structure for this language
            if (!FileMainLanguageDirectory.Exists)
            {
                FileMainLanguageDirectory.Create();
            }
        }

        class OutputPathEqualityComparer : IEqualityComparer<ImageConversion>
        {
            public bool Equals(ImageConversion x, ImageConversion y)
            {
                return x.OutImageName.Equals(y.OutImageName);
            }

            public int GetHashCode(ImageConversion obj)
            {
                return obj.OutImageName.GetHashCode();
            }
        }

        public static void CopyDocumentsImagesAndAttachments(string fileName, Logger log, string outputDirectory, string language, string fileOutputDirectory, IEnumerable<ImageConversion> imageDetails, IEnumerable<AttachmentConversionDetail> attachmentDetails)
        {
            GenerateDocsFolderStructure(outputDirectory, fileOutputDirectory, language);

            //attachment file check and copy to html folder
            foreach (var attachmentDetail in attachmentDetails)
            {
                try
                {
                    var attachmentInFolderFileName = attachmentDetail.InAttachName;
                    var attachmentOutFolderFileName = attachmentDetail.OutAttachName;

                    //Check out folder exists we may be working with a relative path to another directory
                    var attachmentOutFolder = new DirectoryInfo(attachmentOutFolderFileName).Parent;
                    if (!attachmentOutFolder.Exists)
                    {
                        attachmentOutFolder.Create();
                    }

                    var attachmentOutFolderFile = new FileInfo(attachmentOutFolderFileName);

                    if (attachmentOutFolderFile.Exists && FileEquals(attachmentInFolderFileName, attachmentOutFolderFileName))
                    {
                        continue;
                    }

                    SetFileAttributeForReplace(attachmentOutFolderFile);
                    File.Copy(attachmentInFolderFileName, attachmentOutFolderFileName, true);
                }
                catch (FileNotFoundException)
                {
                    log.Error(
                        MarkdownSharp.Language.Message(
                            "CheckingAttachmentsToSeeIfThereHasBeenAnUpdateThereWasAnError",
                            attachmentDetail.InAttachName));
                }
            }

            //image file check and copy to html folder

            // Create unique list on output path as it get overwritten anyway.
            imageDetails = imageDetails.Select(e => e).Distinct(new OutputPathEqualityComparer()).ToList();

            foreach (var imageDetail in imageDetails)
            {
                var imageInFolderFileName = imageDetail.InImageName;
                var imageOutFolderFileName = imageDetail.OutImageName;

                //Check out folder exists we may be working with a relative path to another directory
                var imageOutFolder = new DirectoryInfo(imageOutFolderFileName).Parent;
                if (!imageOutFolder.Exists)
                {
                    imageOutFolder.Create();
                }

                if (!File.Exists(imageInFolderFileName))
                {
                    Console.Write("\n");
                    log.Warn(
                        Language.Message(
                            "MissingImageFileDetectedPleaseLocate", Path.GetFileName(fileName), imageInFolderFileName));
                }
                else
                {
                    //Copy image across if not same
                    try
                    {
                        var imageOut = imageDetail.WebImage();

                        //Check compressed stream with existing file if different overwrite html/image folders image.
                        var imageOutFolderFile = new FileInfo(imageOutFolderFileName);

                        if (!imageOutFolderFile.Exists || !ByteEquals(imageOut, File.ReadAllBytes(imageOutFolderFileName)))
                        {
                            SetFileAttributeForReplace(imageOutFolderFile);

                            File.WriteAllBytes(imageOutFolderFileName, imageOut);
                        }

                    }
                    catch (FileNotFoundException)
                    {
                        log.Error(
                            MarkdownSharp.Language.Message(
                                "ErrorDuringCheckingImagesToSeeIfThereHasBeenAnUpdate", imageDetail.InImageName));
                    }
                    catch (IOException)
                    {
                        log.Warn(
                            MarkdownSharp.Language.Message(
                                "FileCouldNotBeMovedAlreadyBeingMovedByAnotherProcess", imageDetail.InImageName));
                    }
                }
            }
        }

        /// <summary>
        /// Compare two bytearray, return true if both streams are equivalent, otherwise false.
        /// </summary>
        /// <param name="ByteArray1"></param>
        /// <param name="ByteArray2"></param>
        /// <returns></returns>
        public static bool ByteEquals(byte[] ByteArray1, byte[] ByteArray2)
        {
            if (ByteArray1 == ByteArray2) return true;
            if (ByteArray1 == null || ByteArray2 == null) return false;
            if (ByteArray1.Length != ByteArray2.Length) return false;
            for (int i = 0; i < ByteArray2.Length; i++)
            {
                if (ByteArray1[i] != ByteArray2[i]) return false;
            }
            return true;
        }

        /// <summary>
        /// Compare two files, return true if both are equivalent, otherwise false.
        /// </summary>
        /// <param name="FileName1"></param>
        /// <param name="FileName2"></param>
        /// <returns></returns>
        public static bool FileEquals(string FileName1, string FileName2)
        {
            int File1Byte = 0;
            int File2Byte = 0;

            using (FileStream Stream1 = new FileStream(FileName1, FileMode.Open, FileAccess.Read, FileShare.Read))
            using (FileStream Stream2 = new FileStream(FileName2, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                if (Stream1.Length != Stream2.Length) return false;

                do
                {
                    File1Byte = Stream1.ReadByte();
                    File2Byte = Stream2.ReadByte();

                } while (File1Byte == File2Byte && File1Byte != -1);
            }

            return ((File1Byte - File2Byte) == 0);
        }

        /// <summary>
        /// If a file exists set it's attributes so that it can be edited.
        /// </summary>
        /// <param name="FileToChange">A file info object which will be set</param>
        /// <param name="ByteArray2"></param>
        /// <returns></returns>
        public static void SetFileAttributeForReplace(FileInfo FileToChange)
        {
            if (FileToChange.Exists)
            {
                FileToChange.Attributes = FileAttributes.Normal;
            }
        }

        /// <summary>
        /// Copy files from OutputDirectory/Include/ForlderTypeName to SourceDirectory/Include/FolderTypeName
        /// </summary>
        private static bool CopyDirectory(string OutputDirectory, string SourceDirectory, string FolderTypeName, Logger log)
        {
            DirectoryInfo SourceDirectoryInfo = new DirectoryInfo(Path.Combine(Path.Combine(SourceDirectory, "Include"), FolderTypeName));
            if (!SourceDirectoryInfo.Exists)
            {
                log.Error(Language.Message("DirectoryCouldNotBeFound", SourceDirectoryInfo.FullName));
                return false;
            }

            DirectoryInfo OutputDirectoryInfo = new DirectoryInfo(Path.Combine(Path.Combine(OutputDirectory, "Include"), FolderTypeName));
            if (!OutputDirectoryInfo.Exists)
            {
                OutputDirectoryInfo.Create();
            }

            foreach (FileInfo FileToCopy in SourceDirectoryInfo.GetFiles())
            {
                FileInfo OutFile = new FileInfo(Path.Combine(OutputDirectoryInfo.FullName, FileToCopy.Name));

                if (!OutFile.Exists || FileToCopy.LastWriteTimeUtc != OutFile.LastWriteTimeUtc)
                {
                    try
                    {
                        SetFileAttributeForReplace(OutFile);

                        FileToCopy.CopyTo(OutFile.FullName, true);
                    }
                    //These exception has occurred when spaming the markdownmode publish flag options.  Unlikely to occur in proper use, just raise warning.
                    catch (IOException)
                    {
                        log.Warn(Language.Message("FileCouldNotBeCopiedAlreadyBeingCopiedByAnotherProcess", OutFile.FullName));
                    }
                    catch (UnauthorizedAccessException)
                    {
                        log.Warn(Language.Message("FileCouldNotBeCopiedAlreadyBeingCopiedByAnotherProcess", OutFile.FullName));
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// On successful file conversion create directory structure
        /// </summary>
        /// <returns></returns>
        public static bool CreateCommonDirectories(string OutputDirectory, string SourceDirectory, Logger log)
        {

            DirectoryInfo OutputDirectoryInfo = new DirectoryInfo(OutputDirectory);
            if (!OutputDirectoryInfo.Exists)
            {
                //Try to create it
                try
                {
                    OutputDirectoryInfo.Create();
                }
                catch (IOException e)
                {
                    log.Error(Language.Message("DocumentOutputDirCouldNotBeCreated", e.GetType().Name, OutputDirectory));
                    return false;
                }
            }

            //Check CSS folders exists in source include directory
            if (!CopyDirectory(OutputDirectory, SourceDirectory, "CSS", log))
            {
                return false;
            }

            //Check Images folders exists in source include directory
            if (!CopyDirectory(OutputDirectory, SourceDirectory, "Images", log))
            {
                return false;
            }

            //Check Javascript folders exists in source include directory
            if (!CopyDirectory(OutputDirectory, SourceDirectory, "Javascript", log))
            {
                return false;
            }

            return true;
        }
    }
}


text:
 * eb597ef - Add Requests http adapter
 * 3a5232d - Add Symfony3 support
 * bc4c186 - Add caching support
 * b6e4bdf - [Socket] Fix https connection

### 0.8.0 (2015-08-12)

 * 2d8061b - Add guzzle 6 support
 * 26d6b7b - Add mock http adapter
 * 1cd6ee4 - [GuzzleHttp] Catch an exception that is able to provide a request
 * 6ac4d3b - [Travis] Add Symfony 2.7 to stable + Add Symfony 2.8.*@dev as unstable
 * 4f35c0e - Replace phly/http by zendframework/zend-diactoros
 * fbc3c4d - [Message][Stream] Remove guzzle streams
 * 9de52ee - Rewind stream before setting it on the response
 * 9a29e09 - Rely on PHP built in server instead of Nginx or Apache
 * e6ef972 - [Travis] Add PHP 7
 * 1e609b9 - [CakePHP] Drop 2.x support in favor of 3.x
 * 19a0e44 - [Headers] Automatically add content-type when there are datas
 * 005efb0 - Add PECL http adapter support
 * 789326e - [Event] Fix redirect subscriber which throws an exception
 * 2d245b6 - Rely on PSR response interface for trait typehint closure
 * 458a9e2 - [Decorator] Make decorator calls explicit
 * 9d126f8 - Upgrade phly/http library
 * 79e75ea - Makes event subscribers immutable + rename events

### 0.7.1 (2015-04-13)

 * f996f8e - [Travis] Use minimum PHP version for lowest deps
 * 0ae6275 - Fix RedirectSubscriber
 * 1e174e7 - Fixed dependency to non existing branch

### 0.7.0 (2015-03-08)

 * 5e844f6 - Move event dispatcher into a decorator
 * d49ad91 - Rely on 'phly/http' for PSR-7 implementation

### 0.6.0 (2015-02-10)

 * cd7e18b - [HttpAdapterFactory] Added a guess and capable methods
 * 21055c2 - Add parallel requests support
 * c0fcdfd - Add base url support
 * 77173c4 - Make http_buil_query independant of arg_separator.output ini setting
 * bbcf51a - Introduce Version
 * 1b15d7b - [Event] Make timer subscriber stateless
 * f16767a - Set request/response on exception before passing it to exception listeners
 * 613132a - [Test] Reintroduce send internal request tests
 * 7eb424b - Rename AbstractHttpAdapter::doSend to doSendInternalRequest
 * b91f40f - Remove AbstractHttpAdapter::createResponse and rely on MessageFactory::createResponse instead
 * a260489 - [Travis] Move Symfony 2.6.*@dev to 2.6.*
 * 605d943 - Remove HttpAdapterInterface::sendInternalRequest method
 * 4c33b6c - [Travis] Update config
 * 90c58a3 - Add .gitattributes
 * dfe5877 - Add CakePHP http adapter
 * dc3fa00 - Add ReactPHP http adapter
 * 5145b12 - Introduce http adapter factory
 * c918dbf - [Composer] Rely on autoload-dev
 * a88709c - [Test] Rename debug file to ivory-http-adapter.log
 * d00e1f7 - [Test] Add Apache 2.4 compatibility
 * e4f6efb - Add Symfony2 stopwatch support
 * cc3f5f2 - [Event][Retry] Fix verify for limited retry strategy
 * 6e10883 - [Encapsulation] Move everything from protected to private (except for entry point)

### 0.5.0 (2014-11-05)

 * 4523e62 - [Message] Update according to PSR HTTP message 0.5.0 BC breaks
 * 4e0e387 - [Composer] Refine dependency
 * 198b6f4 - Add Guzzle 5 support
 * a2940f6 - [Exception] Add related request/response if available

### 0.4.0 (2014-10-26)

 * 75e5f69 - [Message] Update according to PSR HTTP message 0.4.0 BC breaks

### 0.3.0 (2014-10-26)

 * 65ad8ba - [Message] Update according to PSR HTTP message 0.3.0 BC breaks

### 0.2.0 (2014-10-26)

 * 4cbd0b5 - [Message] Update according to PSR HTTP message 0.2.0 BC breaks

### 0.1.2 (2014-10-25)

 * 6527485 - [Stream] Fix some returns + PHPDoc

### 0.1.1 (2014-10-25)

 * 51ac68c - [Test] Remove http adapter file after execution
 * 9c1382a - [Stream] Fix string stream
 * 8478738 - [StringStream] Fix boolean return
 * 50871fe - [Test] Lock share file
 * 9a77280 - [Curl] Reduce timeout code duplication
 * ceddaf2 - [Composer] Refine dependencies
 * 704188f - Normalize timeout handling
 * 6238854 - Typehint PSR request + CS Fixes + Refine Guzzle4 dependency

### 0.1.0 (2014-10-03)


text:
from tools.link import *
from online.models import *
from home.models import *
import time
def pingall():
    computes = Compute.objects.all()
    for compute in computes:
        if(ping_ip(compute.ip)):
            Compute.objects.filter(ip = compute.ip).update(state = "开机")
            try:
               activecompute = Compute.objects.get(ip = compute.ip)
            except:
                print 'err'
            else:

                if (activecompute.activetime!=None):
                    activetime = int(activecompute.activetime)+1
                    Compute.objects.filter(ip = compute.ip).update(activetime = str(activetime))
                else:
                    Compute.objects.filter(ip = compute.ip).update(activetime = '0')
        else:
            Compute.objects.filter(ip = compute.ip).update(state = "关机")
            try:
                idletcompute = Compute.objects.get(ip = compute.ip)
            except:
                print "err"
            else:
                if (idletcompute.idletime!=None):
                    idletime = int(idletcompute.idletime)+1

                    Compute.objects.filter(ip = compute.ip).update(idletime = str(idletime))
                else:
                    Compute.objects.filter(ip = compute.ip).update(idletime = '0')
    return 1
def runpingall():
    while True:
       pingall()
       time.sleep(10)
if __name__ == "__main__":
    runpingall()


text:
package org.cru.godtools.api.packages.utils;

import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by ryancarlson on 8/1/14.
 */
@Qualifier
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.TYPE, ElementType.FIELD})
public @interface ProvidesImages
{

}


text:
import { connect } from 'react-redux';
import * as bookActions from '../actions/booksActions';
import { getBookFormState } from '../reducers/bookFormReducer';
import BookTitleInput from '../components/BookTitleInput';

function mapStateToProps(state) {
  return {
    text: getBookFormState(state).bookTitle,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    onChange(event) {
      dispatch(bookActions.titleChange(event.target.value));
    },
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(BookTitleInput);


text:
package confighistory

import (
	"fmt"

	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric/common/flogging"
	"github.com/hyperledger/fabric/core/ledger"
	"github.com/hyperledger/fabric/core/ledger/ledgerconfig"
	"github.com/hyperledger/fabric/protos/common"
	"github.com/hyperledger/fabric/protos/ledger/rwset/kvrwset"
	"github.com/pkg/errors"
)

var logger = flogging.MustGetLogger("confighistory")

const (
	collectionConfigNamespace = "lscc" // lscc namespace was introduced in version 1.2 and we continue to use this in order to be compatible with existing data
)

// Mgr should be registered as a state listener. The state listener builds the history and retriver helps in querying the history
type Mgr interface {
	ledger.StateListener
	GetRetriever(ledgerID string, ledgerInfoRetriever LedgerInfoRetriever) ledger.ConfigHistoryRetriever
	Close()
}

type mgr struct {
	ccInfoProvider ledger.DeployedChaincodeInfoProvider
	dbProvider     *dbProvider
}

// NewMgr constructs an instance that implements interface `Mgr`
func NewMgr(ccInfoProvider ledger.DeployedChaincodeInfoProvider) Mgr {
	return newMgr(ccInfoProvider, dbPath())
}

func newMgr(ccInfoProvider ledger.DeployedChaincodeInfoProvider, dbPath string) Mgr {
	return &mgr{ccInfoProvider, newDBProvider(dbPath)}
}

// InterestedInNamespaces implements function from the interface ledger.StateListener
func (m *mgr) InterestedInNamespaces() []string {
	return m.ccInfoProvider.Namespaces()
}

// StateCommitDone implements function from the interface ledger.StateListener
func (m *mgr) StateCommitDone(ledgerID string) {
	// Noop
}

// HandleStateUpdates implements function from the interface ledger.StateListener
// In this implementation, the latest collection config package is retrieved via
// ledger.DeployedChaincodeInfoProvider and is persisted as a separate entry in a separate db.
// The composite key for the entry is a tuple of <blockNum, namespace, key>
func (m *mgr) HandleStateUpdates(trigger *ledger.StateUpdateTrigger) error {
	updatedCCs, err := m.ccInfoProvider.UpdatedChaincodes(convertToKVWrites(trigger.StateUpdates))
	if err != nil {
		return err
	}
	if len(updatedCCs) == 0 {
		logger.Errorf("Config history manager is expected to recieve events only if at least one chaincode is updated stateUpdates = %#v",
			trigger.StateUpdates)
		return nil
	}
	updatedCollConfigs := map[string]*common.CollectionConfigPackage{}
	for _, cc := range updatedCCs {
		ccInfo, err := m.ccInfoProvider.ChaincodeInfo(cc.Name, trigger.PostCommitQueryExecutor)
		if err != nil {
			return err
		}
		if ccInfo.CollectionConfigPkg == nil {
			continue
		}
		updatedCollConfigs[ccInfo.Name] = ccInfo.CollectionConfigPkg
	}
	if len(updatedCollConfigs) == 0 {
		return nil
	}
	batch, err := prepareDBBatch(updatedCollConfigs, trigger.CommittingBlockNum)
	if err != nil {
		return err
	}
	dbHandle := m.dbProvider.getDB(trigger.LedgerID)
	return dbHandle.writeBatch(batch, true)
}

// GetRetriever returns an implementation of `ledger.ConfigHistoryRetriever` for the given ledger id.
func (m *mgr) GetRetriever(ledgerID string, ledgerInfoRetriever LedgerInfoRetriever) ledger.ConfigHistoryRetriever {
	return &retriever{dbHandle: m.dbProvider.getDB(ledgerID), ledgerInfoRetriever: ledgerInfoRetriever}
}

// Close implements the function in the interface 'Mgr'
func (m *mgr) Close() {
	m.dbProvider.Close()
}

type retriever struct {
	ledgerInfoRetriever LedgerInfoRetriever
	dbHandle            *db
}

// MostRecentCollectionConfigBelow implements function from the interface ledger.ConfigHistoryRetriever
func (r *retriever) MostRecentCollectionConfigBelow(blockNum uint64, chaincodeName string) (*ledger.CollectionConfigInfo, error) {
	compositeKV, err := r.dbHandle.mostRecentEntryBelow(blockNum, collectionConfigNamespace, constructCollectionConfigKey(chaincodeName))
	if err != nil || compositeKV == nil {
		return nil, err
	}
	return compositeKVToCollectionConfig(compositeKV)
}

// CollectionConfigAt implements function from the interface ledger.ConfigHistoryRetriever
func (r *retriever) CollectionConfigAt(blockNum uint64, chaincodeName string) (*ledger.CollectionConfigInfo, error) {
	info, err := r.ledgerInfoRetriever.GetBlockchainInfo()
	if err != nil {
		return nil, err
	}
	maxCommittedBlockNum := info.Height - 1
	if maxCommittedBlockNum < blockNum {
		return nil, &ledger.ErrCollectionConfigNotYetAvailable{MaxBlockNumCommitted: maxCommittedBlockNum,
			Msg: fmt.Sprintf("The maximum block number committed [%d] is less than the requested block number [%d]", maxCommittedBlockNum, blockNum)}
	}

	compositeKV, err := r.dbHandle.entryAt(blockNum, collectionConfigNamespace, constructCollectionConfigKey(chaincodeName))
	if err != nil || compositeKV == nil {
		return nil, err
	}
	return compositeKVToCollectionConfig(compositeKV)
}

func prepareDBBatch(chaincodeCollConfigs map[string]*common.CollectionConfigPackage, committingBlockNum uint64) (*batch, error) {
	batch := newBatch()
	for ccName, collConfig := range chaincodeCollConfigs {
		key := constructCollectionConfigKey(ccName)
		var configBytes []byte
		var err error
		if configBytes, err = proto.Marshal(collConfig); err != nil {
			return nil, errors.WithStack(err)
		}
		batch.add(collectionConfigNamespace, key, committingBlockNum, configBytes)
	}
	return batch, nil
}

func compositeKVToCollectionConfig(compositeKV *compositeKV) (*ledger.CollectionConfigInfo, error) {
	conf := &common.CollectionConfigPackage{}
	if err := proto.Unmarshal(compositeKV.value, conf); err != nil {
		return nil, errors.Wrap(err, "error unmarshalling compositeKV to collection config")
	}
	return &ledger.CollectionConfigInfo{CollectionConfig: conf, CommittingBlockNum: compositeKV.blockNum}, nil
}

func constructCollectionConfigKey(chaincodeName string) string {
	return chaincodeName + "~collection" // collection config key as in version 1.2 and we continue to use this in order to be compatible with existing data
}

func dbPath() string {
	return ledgerconfig.GetConfigHistoryPath()
}

func convertToKVWrites(stateUpdates ledger.StateUpdates) map[string][]*kvrwset.KVWrite {
	m := map[string][]*kvrwset.KVWrite{}
	for ns, updates := range stateUpdates {
		m[ns] = updates.([]*kvrwset.KVWrite)
	}
	return m
}

// LedgerInfoRetriever retrieves the relevant info from ledger
type LedgerInfoRetriever interface {
	GetBlockchainInfo() (*common.BlockchainInfo, error)
}


text:
local format=string.format
local tostring=tostring
local tonumber=tonumber
local sqrt=math.sqrt
local pairs=pairs

-- wireshark API globals
local Pref = Pref
local Proto = Proto
local ProtoField = ProtoField
local DissectorTable = DissectorTable
local ByteArray = ByteArray
local PI_MALFORMED = PI_MALFORMED
local PI_ERROR = PI_ERROR

-- zmq protocol example
-- declare our protocol
local zmtp_proto = Proto("zmtp", "ZMTP", "ZeroMQ Message Transport Protocol")

-- setup protocol fields.

vs_stype = {
    [0] = "pair",
    [1] = "publish",
    [2] = "subscribe",
    [3] = "request",
    [4] = "reply",
    [5] = "dealer",
    [6] = "router",
    [7] = "pull",
    [8] = "push"
}

zmtp_proto.fields = {}
local fds = zmtp_proto.fields
fds.greeting = ProtoField.new("Signature", "zmtp.greeting", ftypes.BYTES)
fds.version = ProtoField.new("ZMTP Version", "zmtp.greeting.version", ftypes.UINT16, nil, base.HEX)
fds.version_major = ProtoField.new("ZMTP Major Version", "zmtp.greeting.version.major", ftypes.UINT8, nil, base.DEC)

fds.version_minor = ProtoField.new("ZMTP Minor Version", "zmtp.greeting.version.minor", ftypes.UINT8, nil, base.DEC)
fds.mechanism = ProtoField.new("ZMTP Security Mechanism", "zmtp.greeting.mechanism", ftypes.STRINGZ)
fds.as_server = ProtoField.new("Is a ZMTP Server", "zmtp.greeting.as_server", ftypes.BOOLEAN)

fds.stype = ProtoField.new("Socket type", "zmtp.stype", ftypes.UINT8, vs_stype, base.HEX)

fds.frame = ProtoField.new("Frame", "zmtp.frame", ftypes.BYTES)
fds.flags = ProtoField.new("Flags", "zmtp.frame.flags", ftypes.UINT8, nil, base.HEX, "0xFF")
fds.flags_more = ProtoField.new("Has More", "zmtp.frame.flags.more", ftypes.UINT8, {[1]="Yes",[0]="No"}, base.DEC, "0x01")
fds.flags_long = ProtoField.new("64-bit Length", "zmtp.frame.flags.64bit", ftypes.UINT8, {[1]="Yes",[0]="No"}, base.DEC, "0x02")
fds.flags_cmd = ProtoField.new("Is Command", "zmtp.frame.flags.command", ftypes.UINT8, {[1]="Yes",[0]="No"}, base.DEC, "0x04")
fds.length = ProtoField.new("Payload Length", "zmtp.frame.length", ftypes.UINT64, nil, base.DEC)
fds.protocol = ProtoField.new("Protocol", "zmtp.frame.protocol", ftypes.STRING, nil, base.NONE, 0, "Set protocol in Preferences → ZMTP")
fds.command_name = ProtoField.new("Command Name", "zmtp.command.name", ftypes.STRING)
fds.cmd_unknown_data = ProtoField.new("Unknown Command", "zmtp.command.unknown", ftypes.BYTES)
fds.cmd_ready = ProtoField.new("READY Command", "zmtp.command.ready", ftypes.BYTES)
fds.cmd_ready_curvezmq_nonce = ProtoField.new("CurveZMQ Server Nonce", "zmtp.command.ready.curvezmq.nonce", ftypes.BYTES)
fds.cmd_ready_curvezmq_box = ProtoField.new("CurveZMQ Box (metadata)", "zmtp.command.ready.curvezmq.box", ftypes.BYTES)
fds.cmd_initiate = ProtoField.new("INITIATE Command", "zmtp.command.initiate", ftypes.BYTES)
fds.cmd_initiate_curvezmq_cookie = ProtoField.new("CurveZMQ Server Cookie", "zmtp.command.initiate.curvezmq.cookie", ftypes.BYTES)
fds.cmd_initiate_curvezmq_nonce = ProtoField.new("CurveZMQ Client Nonce", "zmtp.command.initiate.curvezmq.nonce", ftypes.BYTES)
fds.cmd_initiate_curvezmq_box = ProtoField.new("CurveZMQ Box (client permanent public key, vouch, metadata)", "zmtp.command.initiate.curvezmq.box", ftypes.BYTES)
fds.cmd_metadata_key = ProtoField.new("Metadata Key", "zmtp.command.metadata.key", ftypes.STRING)
fds.cmd_metadata_value = ProtoField.new("Metadata Value", "zmtp.command.metadata.value", ftypes.STRING)
fds.cmd_hello = ProtoField.new("HELLO Command", "zmtp.command.hello", ftypes.BYTES)
fds.cmd_hello_username = ProtoField.new("Username", "zmtp.command.hello.username", ftypes.STRING)
fds.cmd_hello_password = ProtoField.new("Password", "zmtp.command.hello.password", ftypes.STRING)
fds.cmd_hello_curvezmq_version = ProtoField.new("CurveZMQ Version", "zmtp.command.hello.curvezmq.version", ftypes.UINT16, nil, base.HEX)
fds.cmd_hello_curvezmq_version_major = ProtoField.new("CurveZMQ Major", "zmtp.command.hello.curvezmq.version.major", ftypes.UINT8, nil, base.DEC)
fds.cmd_hello_curvezmq_version_minor = ProtoField.new("CurveZMQ Minor", "zmtp.command.hello.curvezmq.version.minor", ftypes.UINT8, nil, base.DEC)
fds.cmd_hello_curvezmq_padding = ProtoField.new("CurveZMQ Padding", "zmtp.command.hello.curvezmq.padding", ftypes.BYTES)
fds.cmd_hello_curvezmq_pubkey = ProtoField.new("CurveZMQ Transient Public Key", "zmtp.command.hello.curvezmq.pubkey", ftypes.BYTES)
fds.cmd_hello_curvezmq_nonce = ProtoField.new("CurveZMQ Nonce", "zmtp.command.hello.curvezmq.nonce", ftypes.BYTES)
fds.cmd_hello_curvezmq_signature = ProtoField.new("CurveZMQ Signature", "zmtp.command.hello.curvezmq.Signature", ftypes.BYTES)
fds.cmd_welcome = ProtoField.new("WELCOME Command", "zmtp.command.welcome", ftypes.BYTES)
fds.cmd_welcome_curvezmq_nonce = ProtoField.new("CurveZMQ Server Nonce", "zmtp.command.welcome.curvezmq.nonce", ftypes.BYTES)
fds.cmd_welcome_curvezmq_box = ProtoField.new("CurveZMQ Box (server public transient key, server cookie)", "zmtp.command.welcome.curvezmq.box", ftypes.BYTES)
fds.message = ProtoField.new("Encrypted MESSAGE", "zmtp.message", ftypes.BYTES)
fds.message_curvezmq_nonce = ProtoField.new("CurveZMQ Message Nonce", "zmtp.message.curvezmq.nonce", ftypes.BYTES)
fds.message_curvezmq_box = ProtoField.new("CurveZMQ Message Box (flags, payload)", "zmtp.message.curvezmq.box", ftypes.BYTES)
fds.cmd_error = ProtoField.new("ERROR Command", "zmtp.command.error", ftypes.BYTES)
fds.cmd_error_reason = ProtoField.new("ERROR Reason", "zmtp.command.error.reason", ftypes.STRING)
fds.cmd_ping = ProtoField.new("PING Command", "zmtp.command.ping", ftypes.BYTES)
fds.cmd_ping_ttl = ProtoField.new("Time To Live (deciseconds)", "zmtp.command.ping.ttl", ftypes.UINT16)
fds.cmd_ping_context = ProtoField.new("Context", "zmtp.command.ping.context", ftypes.STRING)
fds.cmd_pong = ProtoField.new("PONG Command", "zmtp.command.pong", ftypes.BYTES)
fds.cmd_pong_context = ProtoField.new("Context", "zmtp.command.pong.context", ftypes.STRING)

local tcp_stream_id = Field.new("tcp.stream")
local subdissectors = DissectorTable.new("zmtp.protocol", "ZMTP", ftypes.UINT16)

local stream_mechanisms = {}

local function zmq_dissect_frame(buffer, pinfo, frame_tree, tap, toplevel_tree, stream_id)
        local flags_rang = buffer(0, 1)
        local flags = flags_rang:uint()

        if flags == 0xff then
                -- greeting
                frame_tree:add(fds.greeting, buffer(0, 10))
                frame_tree:set_text(format("Greeting"))

                local version_tree = frame_tree:add(fds.version, buffer(10, 2))
                local version_major_rang = buffer(10, 1)
                version_major = version_major_rang:uint()
                if version_major >= 2 then
                    version_tree:add(fds.version_major, version_major_rang)
                    local version_minor_rang = buffer(11, 1)
                    version_tree:add(fds.version_minor, version_minor_rang)
                    local mechanism_rang = buffer(12, 20)
                    frame_tree:add(fds.mechanism, mechanism_rang)
                    local as_server_rang = buffer(32, 1)
                    frame_tree:add(fds.as_server, as_server_rang)

                    tap.mechanism = mechanism_rang:stringz()
                    stream_mechanisms[stream_id] = tap.mechanism

                    if tap.mechanism == "NULL" then
                        return format("Greeting (ZMTP %d.%d, %s Mechanism)",
                                      version_major_rang:uint(),
                                      version_minor_rang:uint(),
                                      mechanism_rang:string())
                    else
                        local role
                        if as_server_rang:uint() == 1 then role = "Server" else role = "Client" end
                        return format("Greeting (ZMTP %d.%d, %s Mechanism, %s)",
                                      version_major_rang:uint(),
                                      version_minor_rang:uint(),
                                      mechanism_rang:string(), role)
                    end
                else
                    version_tree:add(fds.version_major, version_major_rang)
                    local type_rang = buffer(11, 1)
                    frame_tree:add(fds.stype, type_rang)
                    return format("Greeting (ZMTP %d), %s",
                                      version_major_rang:uint(),
                                      vs_stype[type_rang:uint()])
                end
        end

        local flags_tree = frame_tree:add(fds.flags, buffer(0, 1))
        flags_tree:add(fds.flags_more, buffer(0, 1))
        flags_tree:add(fds.flags_long, buffer(0, 1))
        flags_tree:add(fds.flags_cmd, buffer(0, 1))

        local flag_more = (bit.band(flags, 0x01) ~= 0)
        local flag_long = (bit.band(flags, 0x02) ~= 0)
        local flag_cmd  = (bit.band(flags, 0x04) ~= 0)

        local len_rang
        local body_offset
        local body_len
        if flag_long then -- LONG
                len_rang = buffer(1, 8)
                -- not before wireshark 1.11; http://wiki.wireshark.org/LuaAPI/Int64
                -- body_len = len_rang:uint64():tonumber()
                body_len = tonumber(tostring(len_rang:uint64()))
                body_offset = 9
        else
                len_rang = buffer(1, 1)
                body_len = len_rang:uint()
                body_offset = 2
        end
        frame_tree:add(fds.length, len_rang)

        local flags_desc = {}
        if flag_more then table.insert(flags_desc, "More") end
        if flag_cmd  then table.insert(flags_desc, "Command") end

        if #flags_desc > 0 then
                flags_tree:append_text(format(" (%s)", table.concat(flags_desc, ", ")))
        end

        tap.body_bytes = tap.body_bytes + body_len

        local has_more = ""
        if flag_more then
                has_more = " [Has More]"
        end

        local mechanism = stream_mechanisms[stream_id]
        local body_rang = buffer(body_offset, body_len)
        if flag_cmd then
                tap.commands = tap.commands + 1

                local cmd_name_len = body_rang:range(0, 1):uint()
                local cmd_name_rang = body_rang:range(1, cmd_name_len)
                local cmd_name = cmd_name_rang:string()
                frame_tree:add(fds.command_name, cmd_name_rang)

                local cmd_data_rang
                if body_rang:len() > 1 + cmd_name_len then
                        cmd_data_rang = body_rang:range(1 + cmd_name_len)
                end

                local function parse_metadata(cmd_tree)
                        local metadata = {}
                        local md_offset = 0
                        while md_offset < cmd_data_rang:len() do
                                local key_len = cmd_data_rang:range(md_offset, 1):uint()
                                local key_rang = cmd_data_rang:range(md_offset + 1, key_len)
                                cmd_tree:add(fds.cmd_metadata_key, key_rang)
                                md_offset = md_offset + 1 + key_len

                                local value_len = cmd_data_rang:range(md_offset, 4):uint()
                                if value_len > 0 then
                                        local value_rang = cmd_data_rang:range(md_offset + 4, value_len)
                                        cmd_tree:add(fds.cmd_metadata_value, value_rang)
                                        md_offset = md_offset + 4 + value_len

                                        table.insert(metadata, format("%s: %s",
                                                        key_rang:string(), value_rang:string()))
                                else
                                        md_offset = md_offset + 4

                                        table.insert(metadata, format("%s: (empty)",
                                                        key_rang:string()))
                                end
                        end

                        return table.concat(metadata, ", ")
                end

                if cmd_name == "READY" and mechanism ~= "CURVE" then
                        local ready_tree = frame_tree:add(fds.cmd_ready, cmd_data_rang)
                        frame_tree:set_text(format("Command READY%s: %s",
                                            has_more, parse_metadata(ready_tree)))
                elseif cmd_name == "READY" and mechanism == "CURVE" then
                        local ready_tree = frame_tree:add(fds.cmd_ready, cmd_data_rang)
                        ready_tree:add(fds.cmd_ready_curvezmq_nonce,
                                         cmd_data_rang:range(0, 8))
                        ready_tree:add(fds.cmd_ready_curvezmq_box,
                                         cmd_data_rang:range(8, cmd_data_rang:len() - 8))
                        frame_tree:set_text(format("Command READY"))
                elseif cmd_name == "HELLO" and mechanism == "PLAIN" then
                        local hello_tree = frame_tree:add(fds.cmd_hello, cmd_data_rang)

                        local username_len = cmd_data_rang:range(0, 1):uint()
                        local username_rang
                        if username_len > 0 then
                                username_rang = cmd_data_rang:range(1, username_len)
                        end

                        local password_len = cmd_data_rang:range(1 + username_len, 1):uint()
                        local password_rang
                        if password_len > 0 then
                                password_rang = cmd_data_rang:range(1 + username_len + 1, password_len)
                        end

                        local username
                        if username_rang then
                                username = username_rang:string()
                                hello_tree:add(fds.cmd_hello_username, username_rang)
                        else
                                username = "(empty)"
                        end

                        local password
                        if password_rang then
                                password = password_rang:string()
                                hello_tree:add(fds.cmd_hello_password, password_rang)
                        else
                                password = "(empty)"
                        end

                        frame_tree:set_text(format("Command HELLO%s: Username: %s, Password: %s",
                                            has_more, username, password))
                elseif cmd_name == "HELLO" and mechanism == "CURVE" then
                        local hello_tree = frame_tree:add(fds.cmd_hello, cmd_data_rang)

                        local ver_major = cmd_data_rang:range(0, 1)
                        local ver_minor = cmd_data_rang:range(1, 1)
                        local version_tree = hello_tree:add(fds.cmd_hello_curvezmq_version,
                                                            cmd_data_rang:range(0, 2))
                        version_tree:add(fds.cmd_hello_curvezmq_version_major, ver_major)
                        version_tree:add(fds.cmd_hello_curvezmq_version_minor, ver_minor)

                        if ver_major:uint() == 1 and ver_minor:uint() == 0 then
                                local padding_rang = cmd_data_rang:range(2, 72)
                                local padding_tree = hello_tree:add(fds.cmd_hello_curvezmq_padding, padding_rang)
                                if padding_rang:string() ~= string.rep("\0", 72) then
                                        padding_tree:add_expert_info(PI_PROTOCOL, PI_ERROR,
                                                                     "Non-zero padding")
                                end

                                hello_tree:add(fds.cmd_hello_curvezmq_pubkey,
                                               cmd_data_rang:range(74, 32))
                                hello_tree:add(fds.cmd_hello_curvezmq_nonce,
                                               cmd_data_rang:range(106, 8))
                                hello_tree:add(fds.cmd_hello_curvezmq_signature,
                                               cmd_data_rang:range(114, 80))
                        else
                                version_tree:add_expert_info(PI_UNDECODED, PI_ERROR,
                                                             "Unsupported CurveZMQ version")
                        end

                        frame_tree:set_text(format("Command HELLO%s: CurveZMQ %d.%d",
                                            has_more, ver_major:uint(), ver_minor:uint()))
                elseif cmd_name == "WELCOME" and mechanism == "CURVE" then
                        local welcome_tree = frame_tree:add(fds.cmd_welcome, cmd_data_rang)

                        welcome_tree:add(fds.cmd_welcome_curvezmq_nonce,
                                         cmd_data_rang:range(0, 16))
                        welcome_tree:add(fds.cmd_welcome_curvezmq_box,
                                         cmd_data_rang:range(16, 144))

                        frame_tree:set_text(format("Command WELCOME"))
                elseif cmd_name == "INITIATE" and mechanism == "PLAIN" then
                        local initiate_tree = frame_tree:add(fds.cmd_initiate, cmd_data_rang)
                        frame_tree:set_text(format("Command INITIATE%s: %s",
                                            has_more, parse_metadata(initiate_tree)))
                elseif cmd_name == "INITIATE" and mechanism == "CURVE" then
                        local initiate_tree = frame_tree:add(fds.cmd_initiate, cmd_data_rang)

                        initiate_tree:add(fds.cmd_initiate_curvezmq_cookie,
                                         cmd_data_rang:range(0, 96))
                        initiate_tree:add(fds.cmd_initiate_curvezmq_nonce,
                                         cmd_data_rang:range(96, 8))
                        initiate_tree:add(fds.cmd_initiate_curvezmq_box,
                                         cmd_data_rang:range(104, cmd_data_rang:len() - 104))

                        frame_tree:set_text(format("Command INITIATE"))
                elseif cmd_name == "ERROR" then
                        local error_tree = frame_tree:add(fds.cmd_error, cmd_data_rang)

                        local reason_len = cmd_data_rang:range(0, 1):uint()
                        local reason_rang = cmd_data_rang:range(1, reason_len)
                        error_tree:add(fds.cmd_error_reason, reason_rang)

                        frame_tree:set_text(format("Command ERROR%s: %s",
                                            has_more, reason_rang:string()))
                elseif cmd_name == "PING" then
                        local ping_tree = frame_tree:add(fds.cmd_ping, cmd_data_rang)
                        local ping_ttl = cmd_data_rang:range(0, 2)
                        local ttl_tree = ping_tree:add(fds.cmd_ping_ttl,
                                                       cmd_data_rang:range(0, 2))
                        if cmd_data_rang:len() - 2 > 0 then
                                local ping_context = cmd_data_rang:range(2, cmd_data_rang:len() - 2)
                                local ttl_tree = ping_tree:add(fds.cmd_ping_context,
                                                           ping_context)
                                frame_tree:set_text(format("Command PING%s: TTL: %d Context: %s",
                                                has_more, ping_ttl:uint(), ping_context))
                        else
                                frame_tree:set_text(format("Command PING%s: TTL: %d",
                                                has_more, ping_ttl:uint()))
                        end
                elseif cmd_name == "PONG" then
                        if cmd_data_rang then
                                local pong_tree = frame_tree:add(fds.cmd_pong, cmd_data_rang)
                                    local pong_context = cmd_data_rang:range(0, cmd_data_rang:len())
                                    local context_tree = pong_tree:add(fds.cmd_pong_context,
                                                               pong_context)
                                    frame_tree:set_text(format("Command PONG%s: Context: %s",
                                                    has_more, pong_context))
                        end
                else
                        if cmd_data_rang then
                                frame_tree:add(fds.cmd_unknown_data, cmd_data_rang)
                                frame_tree:set_text(format("Command %s%s: %s",
                                                    cmd_name, has_more, tostring(cmd_data_rang)))
                        else
                                frame_tree:set_text(format("Command %s%s",
                                                    cmd_name, has_more))
                        end
                end

                return format("Command (%s)", cmd_name)
        else
                tap.messages = tap.messages + 1

                if mechanism == "CURVE" and body_len >= 33 then
                        local cmd_name_len = body_rang:range(0, 1):uint()
                        if cmd_name_len == 7 then
                                local cmd_name_rang = body_rang:range(1, cmd_name_len)
                                local cmd_name = cmd_name_rang:string()
                                frame_tree:add(fds.command_name, cmd_name_rang)

                                local cmd_data_rang
                                if body_rang:len() > 1 + cmd_name_len then
                                        cmd_data_rang = body_rang:range(1 + cmd_name_len)
                                end
                                if cmd_name == "MESSAGE" then
                                        local message_tree = frame_tree:add(fds.message, cmd_data_rang)

                                        message_tree:add(fds.message_curvezmq_nonce,
                                                         cmd_data_rang:range(0, 8))
                                        message_tree:add(fds.message_curvezmq_box,
                                                         cmd_data_rang:range(8, cmd_data_rang:len() - 8))

                                        frame_tree:set_text(format("MESSAGE"))
                                end
                        end
                elseif body_len > 0 then
                        -- get right subdissectors if existing from src or dst port
                        local port = pinfo.src_port

                        local cur_dissector = subdissectors:get_dissector(port)
                        if (cur_dissector == nil) then
                            port = pinfo.dst_port

                            cur_dissector = subdissectors:get_dissector(port)
                        end

                        frame_tree:set_text(format("Data%s, Length: %u", has_more,
                                                   body_len, tostring(body_rang)))
                        if (cur_dissector) then
                            --frame_tree:add(fds.protocol, cur_dissector:__tostring()):set_generated()
                            subdissectors:try(port, body_rang:tvb(), pinfo, toplevel_tree)
                            return nil
                        else
                            return "Data"
                        end

                else
                        frame_tree:set_text(format("Empty%s", has_more))
                        return "Empty"
                end
        end
end

local DESEGMENT_ONE_MORE_SEGMENT = 0x0fffffff
local DESEGMENT_UNTIL_FIN        = 0x0ffffffe

-- packet dissector
function zmtp_proto.dissector(tvb, pinfo, tree)
        local offset = 0
        local rang
        local zmq_frames
        local tap  = {}
        local desc = {}

        tap.mechanism = ""
        tap.frames = 0
        tap.commands = 0
        tap.messages = 0
        tap.body_bytes = 0

        pinfo.cols.info:clear()
        subdissector_found = false

        local function ensure_length(len)
                if offset + len > tvb:len() then
                        pinfo.desegment_offset = offset
                        pinfo.desegment_len    = DESEGMENT_ONE_MORE_SEGMENT
                        return false
                else
                        return true
                end
        end

        -- print(format("zmtp_proto.dissector: offset:%d len:%d reported_len:%d", offset, tvb:len(), tvb:reported_len()), tvb(offset, 5))
        local stream_id = tcp_stream_id().value

        while offset < tvb:len() do
                if not ensure_length(1) then break end

                -- decode flags
                rang = tvb(offset, 1)
                local flags = rang:uint()
                if flags == 0xff then
                        -- greeting
                        if not ensure_length(12) then break end
                        local version_major_rang = tvb(offset + 10, 1)
                        local version_major = version_major_rang:uint()
                        if version_major >= 2 then
                            if not ensure_length(64) then break end
                            pdu_len = 64
                        else
                            pdu_len = 12
                        end
                elseif (bit.band(flags, 0x02) ~= 0) then
                        -- long frame
                        if not ensure_length(9) then break end
                        rang = tvb(offset + 1, 8)
                        -- not before wireshark 1.11; http://wiki.wireshark.org/LuaAPI/Int64
                        -- frame_len = rang:uint64():tonumber()
                        frame_len = tonumber(tostring(rang:uint64()))
                        pdu_len = frame_len + 9
                else
                        -- short frame
                        if not ensure_length(2) then break end
                        rang = tvb(offset + 1, 1)
                        frame_len = rang:uint()
                        pdu_len = frame_len + 2
                end

                local truncated = false
                -- check if we need more bytes to dissect this frame.
                if offset + pdu_len > tvb:len() then
                        if tvb:len() == tvb:reported_len() then
                                pinfo.desegment_offset = offset
                                pinfo.desegment_len    = offset + pdu_len - tvb:len()
                                -- print(format("zmtp_proto.dissector: desegment offset:%d len:%d", pinfo.desegment_offset, pinfo.desegment_len))
                                break
                        else
                                -- already tried to dissect, but the desegmenter failed
                                pdu_len = tvb:len() - offset
                                truncated = true
                        end
                end

                if not zmq_frames then
                        zmq_frames = tree:add(zmtp_proto, tvb())
                end

                if (bit.band(flags, 0xf8) ~= 0) and flags ~= 0xff then
                        zmq_frames:add_expert_info(PI_REASSEMBLE, PI_ERROR, "Framing error")
                        return
                end

                -- dissect zmq frame
                rang = tvb(offset, pdu_len)
                local frame_tree = zmq_frames:add(fds.frame, rang)
                if truncated then
                        frame_tree:add_expert_info(PI_REASSEMBLE, PI_ERROR, "Message truncated")
                end
                local frame_desc = zmq_dissect_frame(rang:tvb(), pinfo, frame_tree, tap, tree, stream_id)
                -- zmq_dissect_frame returns nil when it passed the payload to a subdissector,
                -- and a string describing the packet otherwise.
                if frame_desc then
                    table.insert(desc, frame_desc)
                else
                    subdissector_found = true
                end
                tap.frames = tap.frames + 1

                -- step to next frame.
                local offset_before = offset
                offset = offset + pdu_len
                if offset < offset_before then break end
        end

        if zmq_frames then
                zmq_frames:set_text(format("ZeroMQ Message Transport Protocol, Frames: %u", tap.frames))
        end

        if tap.messages > 0 then
                table.insert(desc, format("Data Frames: %u", tap.messages))
        end

        -- Info column (only if subdissector did not fill it)
        if not subdissector_found then
            pinfo.cols.protocol = "ZMTP"
            pinfo.cols.info:prepend(table.concat(desc, "; "))
            --pinfo.tap_data = tap
        end

        return
end

-- Register ZMTP for "decode as
DissectorTable.get("tcp.port"):add_for_decode_as(zmtp_proto)


text:
<?xml version="1.0" encoding="UTF-8"?>
<qnx>
    <initialWindow>
        <systemChrome>none</systemChrome>
        <transparent>false</transparent>
    </initialWindow>
    <icon>
        <image>icon_image.png</image>
    </icon>
    <permission>access_internet</permission>
    <platformVersion>1.0.0.0</platformVersion>
</qnx>


text:
package cluster

type Clusternodegroupcsvserverbinding struct {
	Name    string `json:"name,omitempty"`
	Vserver string `json:"vserver,omitempty"`
}


text:
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    ">
	<import resource="classpath:springmvc-resteasy.xml" />

	<context:component-scan base-package="com.dell.dsg" />

	<util:properties id="adapterProps" location="classpath:adapter.properties" />

	<context:annotation-config />

</beans>


text:
//  Copyright © 2019 650 Industries. All rights reserved.

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface ABI43_0_0EXUpdatesAsset : NSObject

/**
 * properties determined by asset source
 */
@property (nullable, nonatomic, strong) NSString *key;
@property (nonatomic, strong) NSString *type;
@property (nullable, nonatomic, strong) NSURL *url;
@property (nullable, nonatomic, strong) NSDictionary *metadata;
@property (nullable, nonatomic, strong) NSString *mainBundleDir; // used for embedded assets
@property (nullable, nonatomic, strong) NSString *mainBundleFilename; // used for embedded assets
@property (nonatomic, assign) BOOL isLaunchAsset;

/**
 * properties determined at runtime by updates implementation
 */
@property (nullable, nonatomic, strong) NSDate *downloadTime;
@property (nullable, nonatomic, strong) NSString *filename;
@property (nullable, nonatomic, strong) NSString *contentHash;
@property (nullable, nonatomic, strong) NSDictionary *headers;

/**
 * properties determined by updates database
 */
@property (nonatomic, assign) NSUInteger assetId;

- (instancetype)initWithKey:(nullable NSString *)key type:(NSString *)type;

@end

NS_ASSUME_NONNULL_END


text:
package com.facebook.buck.event.listener.stats.cache;

import com.facebook.buck.artifact_cache.ArtifactCacheEvent;
import com.facebook.buck.artifact_cache.HttpArtifactCacheEvent;
import com.facebook.buck.artifact_cache.HttpArtifactCacheEvent.Scheduled;
import com.facebook.buck.core.build.event.BuildEvent;
import com.facebook.buck.core.build.event.BuildRuleEvent;
import com.facebook.buck.core.util.immutables.BuckStyleValue;
import com.facebook.buck.event.listener.stats.cache.CacheRateStatsKeeper.CacheRateStatsUpdateEvent;
import com.google.common.eventbus.Subscribe;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nullable;

/** Tracks network related events and maintains stats about uploads/downloads/cache rate/etc. */
public class NetworkStatsTracker {

  /** The listener gets callbacks for interesting events. */
  public interface Listener {
    void onUploadsFinished();
  }

  /** Stats about remote artifact uploads. */
  @BuckStyleValue
  public interface RemoteArtifactUploadStats {
    int getStarted();

    int getFailed();

    int getUploaded();

    int getScheduled();

    long getTotalBytes();
  }

  private final AtomicInteger remoteArtifactUploadsScheduledCount = new AtomicInteger(0);
  private final AtomicInteger remoteArtifactUploadsStartedCount = new AtomicInteger(0);
  private final AtomicInteger remoteArtifactUploadedCount = new AtomicInteger(0);
  private final AtomicLong remoteArtifactTotalBytesUploaded = new AtomicLong(0);
  private final AtomicInteger remoteArtifactUploadFailedCount = new AtomicInteger(0);

  @Nullable private volatile HttpArtifactCacheEvent.Shutdown httpShutdownEvent;

  // TODO(cjhopman): CacheRateStatsKeeper is a bit odd here, it's actually interested in dir cache
  // and buck-out cache hits and just rules finished in general.
  private final CacheRateStatsKeeper cacheRateStatsKeeper;
  private final NetworkStatsKeeper networkStatsKeeper;

  private final ConcurrentLinkedQueue<Listener> listeners;

  public NetworkStatsTracker() {
    this.cacheRateStatsKeeper = new CacheRateStatsKeeper();
    this.networkStatsKeeper = new NetworkStatsKeeper();
    this.listeners = new ConcurrentLinkedQueue<>();
  }

  public void registerListener(Listener listener) {
    listeners.add(listener);
  }

  /** Get the current upload stats. */
  public RemoteArtifactUploadStats getRemoteArtifactUploadStats() {
    return ImmutableRemoteArtifactUploadStats.of(
        remoteArtifactUploadsStartedCount.get(),
        remoteArtifactUploadFailedCount.get(),
        remoteArtifactUploadedCount.get(),
        remoteArtifactUploadsScheduledCount.get(),
        remoteArtifactTotalBytesUploaded.get());
  }

  public boolean haveUploadsStarted() {
    return remoteArtifactUploadsScheduledCount.get() > 0;
  }

  public boolean haveUploadsFinished() {
    return httpShutdownEvent != null;
  }

  /** Get the current cache rate stats. */
  public CacheRateStatsUpdateEvent getCacheRateStats() {
    return cacheRateStatsKeeper.getStats();
  }

  /** Get the current download stats. */
  public NetworkStatsKeeper.RemoteDownloadStats getRemoteDownloadStats() {
    return networkStatsKeeper.getRemoteDownloadStats();
  }

  @Subscribe
  private void buildRuleFinished(BuildRuleEvent.Finished finished) {
    cacheRateStatsKeeper.buildRuleFinished(finished);
  }

  @Subscribe
  private void onHttpArtifactCacheScheduledEvent(Scheduled event) {
    if (event.getOperation() == ArtifactCacheEvent.Operation.STORE) {
      remoteArtifactUploadsScheduledCount.incrementAndGet();
    }
  }

  @Subscribe
  private void onHttpArtifactCacheStartedEvent(HttpArtifactCacheEvent.Started event) {
    if (event.getOperation() == ArtifactCacheEvent.Operation.STORE) {
      remoteArtifactUploadsStartedCount.incrementAndGet();
    }
  }

  @Subscribe
  private void onHttpArtifactCacheFinishedEvent(HttpArtifactCacheEvent.Finished event) {
    switch (event.getOperation()) {
      case MULTI_FETCH:
      case FETCH:
        if (event.getCacheResult().map(res -> res.getType().isSuccess()).orElse(false)) {
          // TODO(cjhopman): Does this count two-level artifacts as two things?
          // TODO(cjhopman): I think we should rename this artifacts->something. I think that
          // "artifacts" is generally understood to mean "files" and we upload archives of many
          // files. Maybe we could just use "archives" but that might be confusing, too.
          networkStatsKeeper.incrementRemoteDownloadedArtifactsCount();
          event
              .getCacheResult()
              .get()
              .artifactSizeBytes()
              .ifPresent(networkStatsKeeper::addRemoteDownloadedArtifactsBytes);
        }
        break;
      case STORE:
        if (event.getStoreData().wasStoreSuccessful().orElse(false)) {
          remoteArtifactUploadedCount.incrementAndGet();
          event
              .getStoreData()
              .getArtifactSizeBytes()
              .ifPresent(remoteArtifactTotalBytesUploaded::addAndGet);
        } else {
          remoteArtifactUploadFailedCount.incrementAndGet();
        }
        break;
      case MULTI_CONTAINS:
        break;
    }
  }

  @Subscribe
  private void onHttpArtifactCacheShutdownEvent(HttpArtifactCacheEvent.Shutdown event) {
    httpShutdownEvent = event;
    if (haveUploadsStarted()) {
      listeners.forEach(Listener::onUploadsFinished);
    }
  }

  @Subscribe
  private void ruleCountCalculated(BuildEvent.RuleCountCalculated calculated) {
    cacheRateStatsKeeper.ruleCountCalculated(calculated);
  }

  @Subscribe
  private void ruleCountUpdated(BuildEvent.UnskippedRuleCountUpdated updated) {
    cacheRateStatsKeeper.ruleCountUpdated(updated);
  }
}


text:
package org.datanucleus.tests;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import org.datanucleus.samples.jtsgeometry.SampleGeometryCollection;
import org.datanucleus.samples.jtsgeometry.SampleLineString;
import org.datanucleus.samples.jtsgeometry.SamplePoint;
import org.datanucleus.samples.jtsgeometry.SamplePolygon;
import org.datanucleus.util.StringUtils;

import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.geom.PrecisionModel;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;

/**
 * Series of tests for MySQL "MBR" spatial extensions to JTS.
 *
 * @version $Revision: 1.3 $
 */
public class JtsGeometryMySQLTest extends JDOPersistenceTestCase
{
    private static final WKTReader wktReader = new WKTReader(new GeometryFactory(new PrecisionModel(), 4326));

    public JtsGeometryMySQLTest(String name)
    {
        super(name);
    }

    protected void setUp() throws Exception
    {
        super.setUp();
        if (runTestsForDatastore())
        {
            PersistenceManager pm = pmf.getPersistenceManager();
            Transaction tx = pm.currentTransaction();
            try
            {
                tx.begin();
                pm.newQuery(SamplePoint.class).deletePersistentAll();
                pm.newQuery(SampleLineString.class).deletePersistentAll();
                pm.newQuery(SamplePolygon.class).deletePersistentAll();
                pm.newQuery(SampleGeometryCollection.class).deletePersistentAll();
            }
            finally
            {
                tx.commit();
            }
            Connection sqlConn = null;
            try
            {
                tx.begin();
                sqlConn = (Connection) pm.getDataStoreConnection();
                String connUrl = pmf.getConnectionURL().toLowerCase();
                String fileName = "sample_jts_postgis.sql";
                if (connUrl.contains("mysql") || connUrl.contains("mariadb"))
                {
                    fileName = "sample_jts_mysql.sql";
                }
                File file = new File(PgGeometryMySQLTest.class.getResource("/org/datanucleus/samples/data/" + fileName).toURI());
                String s = "";
                InputStream is = new FileInputStream(file);
                int c;
                while ((c = is.read()) != -1)
                {
                    s += (char) c;
                }
                String ss[] = StringUtils.split(s, ";");
                for (int i = 0; i < ss.length; i++)
                {
                    sqlConn.createStatement().execute(ss[i]);
                }
                is.close();
            }
            finally
            {
                sqlConn.close();
                tx.commit();
            }
        }
    }

    protected void tearDown() throws Exception
    {
        if (runTestsForDatastore())
        {
            clean(SamplePoint.class);
            clean(SampleLineString.class);
            clean(SamplePolygon.class);
            clean(SampleGeometryCollection.class);
        }
        super.tearDown();
   }

    boolean runTestsForDatastore()
    {
        return (rdbmsVendorID.equalsIgnoreCase("mysql"));
    }

    public void testMbrEqual() throws SQLException, ParseException
    {
        if (!runTestsForDatastore())
        {
            return;
        }

        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx = pm.currentTransaction();
        try
        {
            tx.begin();
            Polygon polygon = (Polygon) wktReader.read("POLYGON((25 25,75 25,75 75,25 75,25 25),(45 45,55 45,55 55,45 55,45 45))");
            Query query = pm.newQuery(SamplePolygon.class, "geom != null && MySQL.mbrEqual(geom, :polygon)");
            List list = (List) query.execute(polygon);
            assertEquals("Wrong number of geometries which are equal to a given polygon returned", 1, list.size());
            assertTrue("Polygon 1 should be in the list of geometries which are equal to a given polygon", list
                    .contains(getSamplePolygon(1)));
        }
        finally
        {
            tx.commit();
        }
    }

    public void testMbrDisjoint() throws SQLException, ParseException
    {
        if (!runTestsForDatastore())
        {
            return;
        }

        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx = pm.currentTransaction();
        try
        {
            tx.begin();
            Polygon polygon = (Polygon) wktReader.read("POLYGON((10 10,40 10,40 40,10 40,10 10))");
            Query query = pm.newQuery(SamplePolygon.class, "geom != null && MySQL.mbrDisjoint(geom, :polygon)");
            List list = (List) query.execute(polygon);
            assertEquals("Wrong number of geometries which are disjoint from a given polygon returned", 1, list.size());
            assertTrue("Polygon 2 should be in the list of geometries which are disjoint from a given polygon", list
                    .contains(getSamplePolygon(2)));
        }
        finally
        {
            tx.commit();
        }
    }

    public void testMbrIntersects() throws SQLException, ParseException
    {
        if (!runTestsForDatastore())
        {
            return;
        }

        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx = pm.currentTransaction();
        try
        {
            tx.begin();
            Polygon polygon = (Polygon) wktReader.read("POLYGON((10 10,40 10,40 40,10 40,10 10))");
            Query query = pm.newQuery(SamplePolygon.class, "geom != null && MySQL.mbrIntersects(geom, :polygon)");
            List list = (List) query.execute(polygon);
            assertEquals("Wrong number of geometries which intersect with a given polygon returned", 1, list.size());
            assertTrue("Polygon 1 should be in the list of geometries which intersect with a given polygon", list
                    .contains(getSamplePolygon(1)));
        }
        finally
        {
            tx.commit();
        }
    }

    public void testMbrTouches() throws SQLException, ParseException
    {
        if (!runTestsForDatastore())
        {
            return;
        }

        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx = pm.currentTransaction();
        try
        {
            tx.begin();
            Point point = (Point) wktReader.read("POINT(75 75)");
            Query query = pm.newQuery(SamplePolygon.class, "geom != null && MySQL.mbrTouches(:point, geom)");
            List list = (List) query.execute(point);
            assertEquals("Wrong number of geometries which are touched by a given point returned", 2, list.size());
            assertTrue("Polygon 1 should be in the list of geometries which are touched by a given point", list
                    .contains(getSamplePolygon(1)));
            assertTrue("Polygon 2 should be in the list of geometries which are touched by a given point", list
                    .contains(getSamplePolygon(2)));
        }
        finally
        {
            tx.commit();
        }
    }

    public void testMbrWithin() throws SQLException, ParseException
    {
        if (!runTestsForDatastore())
        {
            return;
        }

        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx = pm.currentTransaction();
        try
        {
            tx.begin();
            Point point = (Point) wktReader.read("POINT(30 30)");
            Query query = pm.newQuery(SamplePolygon.class, "geom != null && MySQL.mbrWithin(:point, geom)");
            List list = (List) query.execute(point);
            assertEquals("Wrong number of geometries where a given point is within returned", 1, list.size());
            assertTrue("Polygon 1 should be in the list of geometries where a given point is within", list.contains(getSamplePolygon(1)));
        }
        finally
        {
            tx.commit();
        }
    }

    public void testMbrContains() throws SQLException, ParseException
    {
        if (!runTestsForDatastore())
        {
            return;
        }

        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx = pm.currentTransaction();
        try
        {
            tx.begin();
            Point point = (Point) wktReader.read("POINT(30 30)");
            Query query = pm.newQuery(SamplePolygon.class, "geom != null && MySQL.mbrContains(geom, :point)");
            List list = (List) query.execute(point);
            assertEquals("Wrong number of geometries which contain a given point returned", 1, list.size());
            assertTrue("Polygon 1 should be in the list of geometries which contain a given point", list.contains(getSamplePolygon(1)));
        }
        finally
        {
            tx.commit();
        }
    }

    public void testMbrOverlaps() throws SQLException, ParseException
    {
        if (!runTestsForDatastore())
        {
            return;
        }

        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx = pm.currentTransaction();
        try
        {
            tx.begin();
            Polygon polygon = (Polygon) wktReader.read("POLYGON((10 10,50 10,50 50,10 50,10 10))");
            Query query = pm.newQuery(SamplePolygon.class, "geom != null && MySQL.mbrOverlaps(geom, :polygon)");
            List list = (List) query.execute(polygon);
            assertEquals("Wrong number of geometries which overlap a given linestring returned", 1, list.size());
            assertTrue("LineString 1 should be in the list of geometries which overlap a given linestring", list
                    .contains(getSamplePolygon(1)));
        }
        finally
        {
            tx.commit();
        }
    }

    private SamplePolygon getSamplePolygon(int num) throws SQLException, ParseException
    {
        switch (num)
        {
            case 0 :
                return new SamplePolygon(3000, "Polygon 0", null);
            case 1 :
                return new SamplePolygon(3001, "Polygon 1", (Polygon) wktReader.read(
                        "POLYGON((25 25,75 25,75 75,25 75,25 25),(45 45,55 45,55 55,45 55,45 45))"));
            case 2 :
                return new SamplePolygon(3002, "Polygon 2", (Polygon) wktReader.read("POLYGON((75 75,100 75,100 100,75 75))"));
        }
        return null;
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('person', '0050_auto_20160710_0431'),
    ]

    operations = [
        migrations.AlterField(
            model_name='patient',
            name='picture',
            field=models.ImageField(default='media/photos/no-img.jpg', upload_to='media/photos/'),
        ),
    ]


text:
'use strict';

/*
 * A simple wrapper module over storage modules which allows to switch between storage
 * implementation using a config option.
 */

module.exports = (options) => {
    options.conf.backend = options.conf.backend || 'cassandra';
    options.log = options.logger.log.bind(options.logger);

    if (options.conf.backend !== 'cassandra' &&
            options.conf.backend !== 'sqlite') {
        throw new Error(`Unsupported backend version specified: ${options.conf.backend}`);
    }

    return require(`restbase-mod-table-${options.conf.backend}`)(options);
};


text:
'use strict';

var express = require('express');
var https = require('https');
var openBrowser = require('react-dev-utils/openBrowser');
var jQueryExtend = require('extend');
var cookieParser = require('cookie-parser');
var log = require('chip')();
var defaultOptions = require('../lib/defaults/options-defaults');
var options = require('./options');
var getCertificate = require('../lib/Utils');

var app = express();
var server;
options = jQueryExtend(defaultOptions, options);

var logFunc = function () {
	if (process.env.NODE_ENV !== 'test') {
		log.info('server started at port ' + options.tunnel.port);
		if (options.open) {
			openBrowser('http://localhost:' + options.tunnel.port);
		}
	}
};

app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

function setHeaders(res) {
	res.setHeader('Test', "test");
	res.setHeader('Content-Type', options.contentType);
	res.setHeader('Access-Control-Expose-Headers', options.accessControlExposeHeaders);
	res.setHeader('Access-Control-Allow-Origin', options.accessControlAllowOrigin);
	res.setHeader('Access-Control-Allow-Methods', options.accessControlAllowMethods);
	res.setHeader('Access-Control-Allow-Headers', options.accessControlAllowHeaders);
	res.setHeader('Access-Control-Allow-Credentials', options.accessControlAllowCredentials);
}

app.get('/rest/v1/products', (req, res) => {
	setHeaders(res);
	var response = { tunnelResponse: { success: true, headers: req.headers } };
	res.send(JSON.stringify(response, null, 2));
	res.end();
});
app.post('/rest/v1/products/:productCode', (req, res) => {
	setHeaders(res);
	var body = jQueryExtend(req.body, {
		productCode: req.params.productCode,
		query: req.query
	});
	res.cookie('cookieName', 'my-cookie', { maxAge: 900000, httpOnly: true });
	res.send(JSON.stringify(body, null, 2));
	res.end();
});

if (options.tunnel.privateKey && options.tunnel.certificate) {
	server = https.createServer({
		key: getCertificate(options.tunnel.privateKey),
		cert: getCertificate(options.tunnel.certificate),
	}, app).listen(options.tunnel.port, logFunc);
} else {
	server = app.listen(options.tunnel.port, logFunc);
}


text:
<!-- Database information for various PHP scripts requiring MSSQL auth -->
<?php
$server="HOSTNAME:1433";
$username="USERNAME";
$password="PASSWORD";
$database="DBNAME";
?>


text:
//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
//
// Use of this sample source code is subject to the terms of the Microsoft
// license agreement under which you licensed this sample source code. If
// you did not accept the terms of the license agreement, you are not
// authorized to use this sample source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the LICENSE.RTF on your install media or the root of your tools installation.
// THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
/*
 *
 *  PARTITON.H [sic]
 *
 *  This defines the partition structures found on the first sector of every hard drive
 */

#ifndef INCLUDE_PARTITON
#define INCLUDE_PARTITON 1

#pragma pack(1)

// PARTITION defines

// Part_BootInd

#define PART_BOOTABLE           0x80    // bootable partition
#define PART_ACTIVE             PART_BOOTABLE
#define BOOT_IND_ACTIVE         PART_BOOTABLE
#define PART_NON_BOOTABLE       0       // non-bootable partition
#define BOOT_IND_INACTIVE       PART_NON_BOOTABLE

// Part_FileSystem

#define PART_UNKNOWN            0
#define PART_DOS2_FAT           0x01    // legit DOS partition
#define PART_DOS3_FAT           0x04    // legit DOS partition
#define PART_EXTENDED           0x05    // legit DOS partition
#define PART_DOS4_FAT           0x06    // legit DOS partition
#define PART_DOS32              0x0B    // legit DOS partition (FAT32)
#define PART_DOS32X13           0x0C    // Same as 0x0B only "use LBA"
#define PART_DOSX13             0x0E    // Same as 0x06 only "use LBA"
#define PART_DOSX13X            0x0F    // Same as 0x05 only "use LBA"

#ifdef LEGACY

// Legacy definitions for Part_FileSystem

#define PRIMARY                 0x00
#define NEC_98_INVALID          0x00
#define DOS12                   PART_DOS2_FAT   /* MS-DOS 12-bit FAT */
#define XENIX1                  0x02
#define XENIX2                  0x03
#define DOS16                   PART_DOS3_FAT   /* MS-DOS original 16-bit FAT */
#define EXTENDED                PART_EXTENDED   /* extended partition */
#define LOGICAL                 PART_EXTENDED
#define DOSNEW                  PART_DOS4_FAT   /* MS-DOS 16-bit FAT > 32Meg partition */
#define HPFS                    0x07            /* Also used by NTFS OFS and other IFS file systems */
#define PARTID_IFS              HPFS
#define COMMODOREid             0x08
#define BM_PART                 0x0A            /* OS/2 Boot Manager (BM) partition */
#define DOS32                   PART_DOS32      /* MS-DOS (32bit FAT) */
#define DOS32X13                PART_DOS32X13   /* MS-DOS (32bit FAT EXTENDED) */
#define DOSX32                  DOS32X13
#define DOSX13                  PART_DOSX13     /* Ext INT 13 drive comment out this line to turn off X13 sup. */
#define DOS1024                 DOSX13
#define DOSX13X                 PART_DOSX13X    /* EXTENDED partition XI13 */
#define DOSX1024                DOSX13X

#define NEC_98_DOS16            0x11            /* NEC MS-DOS (16bit FAT) */

#ifdef RESERVED_PARTITIONS
#define BM_FAT12_PART           0x11            /* OS/2 Boot Manager (BM) partition */
#define L_EDGEid                0x11
#define BM_FAT16_PART           0x14            /* OS/2 Boot Manager (BM) partition */
#define ASTid                   0x14
#define BM_NEW_PART             0x16            /* OS/2 Boot Manager (BM) partition */
#define BM_HPFS_PART            0x17            /* OS/2 Boot Manager (BM) partition */
#endif

#define NEC_98_DOSNEW           0x21            /* NEC MS-DOS (large partition) */

#ifdef RESERVED_PARTITIONS
#define OTHR3DPARTYI            0x23
#define NECid                   0x24
#define OTHR3DPARTYK            0x26
#define OTHR3DPARTYL            0x31
#define OTHR3DPARTYM            0x33
#define OTHR3DPARTYN            0x34
#define OTHR3DPARTYO            0x36
#define IBM_PPC_PREP        0x41        /* IBM PowerPC prep partition */
#define VERITASVXVM1        0x42        /* Veritas Volume Manager 1 partition */
#define VERITASVXVM2        0x43        /* Veritas Volume Manager 2 partition */
#define DM_DRIVERid1            0x50
#define DM_DRIVERid2            0x51
#define ATNTid                  0x56
#define OTHR3DPARTY1            0x61
#define OTHR3DPARTY2            0x63
#define NOVELL                  0x64
#define OTHR3DPARTY4            0x66
#define OTHR3DPARTY5            0x71
#define OTHR3DPARTY6            0x73
#define OTHR3DPARTY7            0x74
#define PCIX                    0x75
#define OTHR3DPARTY8            0x76
#define PLAN9                   0x9B            /* Bell Labs (Dennis Richie!!!) */
#define OTHR3DPARTYP            0xA1
#define OTHR3DPARTYQ            0xA3
#define OTHR3DPARTYR            0xA4
#define OTHR3DPARTYS            0xA6
#define OTHR3DPARTYT            0xB1
#define OTHR3DPARTYU            0xB3
#define OTHR3DPARTYV            0xB4
#define OTHR3DPARTYW            0xB6
#define PP_FAT12_PART           0xC1            /* DR-DOS Password Protected */
#define PP_FAT16_PART           0xC4            /* DR-DOS Password Protected */
#define PP_EXT_PART             0xC5            /* DR-DOS Password Protected */
#define PP_NEW_PART             0xC6            /* DR-DOS Password Protected */
#define CPM                     0xDB
#define OTHR3DPARTY9            0xE1
#define OTHR3DPARTYA            0xE3
#define OTHR3DPARTYB            0xE4
#define TANDYid                 0xE5
#define OTHR3DPARTYC            0xE6
#define OTHR3DPARTYD            0xF1
#define UNISYSid                0xF2
#define OTHR3DPARTYE            0xF3
#define OTHR3DPARTYF            0xF4
#define OTHR3DPARTYG            0xF6
#define INVALID                 0xFF            /* invalid or not used */
#endif  // RESERVED_PARTITIONS

#endif  // LEGACY

/*
 *  The following symbol defines the offset of 6 bytes in the MBR used by IOS.
 *  The DWORD at MBR_IOS_OFFSET+2 is used IFF the WORD at MBR_IOS_OFFSET is 0.
 */
#define MBR_IOS_OFFSET          0x00DA
#define MBR_IOS_RESVDSZBYTES    6

// PARTENTRY struc

// The First & Last numbers below are INCLUDED in the part of the disk
// in this partition.  Head & Track are 0-based, Sector is 1-based.

typedef struct _PARTENTRY {
        BYTE            Part_BootInd;           // If 80h means this is boot partition
        BYTE            Part_FirstHead;         // Partition starting head based 0
        BYTE            Part_FirstSector;       // Partition starting sector based 1
        BYTE            Part_FirstTrack;        // Partition starting track based 0
        BYTE            Part_FileSystem;        // Partition type signature field
        BYTE            Part_LastHead;          // Partition ending head based 0
        BYTE            Part_LastSector;        // Partition ending sector based 1
        BYTE            Part_LastTrack;         // Partition ending track based 0
        DWORD           Part_StartSector;       // Physical starting sector based 0
        DWORD           Part_TotalSectors;      // Total physical sectors in partition
} PARTENTRY;
typedef PARTENTRY UNALIGNED *PPARTENTRY;

/*
 *  Following define is the offset of the PARTTABLE structure in the Master Boot Record (MBR)
 */
#define VOLBOOT_ORG             0x7C00          // where MBR is loaded (0:7C00h) on Intel PC systems

#define MAX_PARTTABLE_ENTRIES   4
#define SIZE_PARTTABLE_ENTRIES  16

#define BOOTSECTRAILSIGH        0xAA55

#define SECTORALIGN             64

#define PARTTABLE_OFFSET        (DEFAULT_SECTOR_SIZE - 2 - (SIZE_PARTTABLE_ENTRIES * MAX_PARTTABLE_ENTRIES))

typedef struct _PARTTABLE {
        PARTENTRY       PartEntry[MAX_PARTTABLE_ENTRIES];
} PARTTABLE;
typedef PARTTABLE UNALIGNED *PPARTTABLE;

#pragma pack()

#endif // INCLUDE_PARTITON


text:
'use strict';

const path = require('path');
const clone = require('clone-deep');
const relative = require('relative');
const red = require('ansi-red');
const bold = require('ansi-bold');

/**
 * Asynchronously get the resolved path to "main" file for
 * the given module.
 *
 * ```js
 * resolve('micromatch', function(err, fp) {
 *   //=> 'node_modules/micromatch/index.js'
 * });
 * ```
 *
 * @param  {String} `name` The name of the module to resolve.
 * @param  {Function} `next` Callback function
 * @return {String} File path to the module
 */

function resolve(name, next) {
  try {
    next(null, resolveSync(name));
  } catch (err) {
    next(err);
  }
}

/**
 * Synchronously get the resolved path to "main" file for
 * the given module.
 *
 * ```js
 * var fp = resolve.sync('micromatch');
 * //=> 'node_modules/micromatch/index.js'
 * ```
 *
 * @param  {String} `name` The name of the module to resolve.
 * @param  {Function} `next` Callback function
 * @return {String} File path to the module
 */

function resolveSync(name) {
  const base = path.resolve(process.cwd(), 'node_modules', name);
  const pkg = tryResolve(path.join(base, 'package.json'));

  const res = clone(pkg);
  res.main = relative(path.join(base, pkg && pkg.main));
  return res;
}

/**
 * Try to require a file, fail silently if unsuccesful
 *
 * @param  {String} `fp`
 * @return {String} Resolved filepath
 */

function tryResolve(fp) {
  if (typeof fp === 'undefined') {
    throw new Error('helpers-resolve: tryResolve() requires a string.');
  }
  try {
    return require(path.resolve(fp));
  } catch (err) {
    console.error(red('helper-resolve cannot find'), bold(fp), err);
  }
  return {};
};

/**
 * Expose `resolve` helper
 */

module.exports = resolve;

/**
 * Expose `resolve.sync` helper
 */

module.exports.sync = resolveSync;