text:
import React from "react";
import PropTypes from "prop-types";
import injectSheet from "react-jss";

import Footnote from "./Footnote";

const styles = theme => ({
  footer: {
    color: theme.main.colors.footer,
    padding: `1.5rem 1.5rem  calc(${theme.bars.sizes.actionsBar}px + 1.5rem) 1.5rem`,
    "& p": {
      margin: 0
    },
    [`@media (min-width: ${theme.mediaQueryTresholds.M}px)`]: {
      padding: `2rem 2.5rem  calc(${theme.bars.sizes.actionsBar}px + 2rem) 2.5rem`
    },
    [`@media (min-width: ${theme.mediaQueryTresholds.L}px)`]: {
      padding: `2rem 3rem 2rem 3rem`
    }
  }
});

const Footer = props => {
  const { classes, footnote } = props;
  const { html } = footnote;

  return (
    <footer className={classes.footer}>
      <Footnote content={html} />
    </footer>
  );
};

Footer.propTypes = {
  classes: PropTypes.object.isRequired,
  footnote: PropTypes.object.isRequired
};

export default injectSheet(styles)(Footer);


text:
const KEY_SEPARATOR = '-';

class MultiDecorator {
  constructor(decorators) {
    this.decorators = decorators;
  }

  /**
   * Return list of decoration IDs per character
   *
   * @param {ContentBlock} block
   * @return {List<String>}
   */
  getDecorations(block, contentState) {
    const decorations = new Array(block.getText().length).fill(null);
    this.decorators.forEach((decorator, i) => {
      const subDecorations = decorator.getDecorations(block, contentState);

      subDecorations.forEach((key, offset) => {
        if (!key) {
          return;
        }

        decorations[offset] = i + KEY_SEPARATOR + key;
      });
    });

    return decorations;
  }

  /**
   * Return component to render a decoration
   *
   * @param {String} key
   * @return {Function}
   */
  getComponentForKey(key) {
    const decorator = this.getDecoratorForKey(key);
    return decorator.getComponentForKey(MultiDecorator.getInnerKey(key));
  }

  /**
   * Return props to render a decoration
   *
   * @param {String} key
   * @return {Object}
   */
  getPropsForKey(key) {
    const decorator = this.getDecoratorForKey(key);
    return decorator.getPropsForKey(MultiDecorator.getInnerKey(key));
  }

  /**
   * Return a decorator for a specific key
   *
   * @param {String} key
   * @return {Decorator}
   */
  getDecoratorForKey(key) {
    const parts = key.split(KEY_SEPARATOR);
    const index = Number(parts[0]);

    return this.decorators[index];
  }

  /**
   * Return inner key for a decorator
   *
   * @param {String} key
   * @return {String}
   */
  static getInnerKey(key) {
    const parts = key.split(KEY_SEPARATOR);
    return parts.slice(1).join(KEY_SEPARATOR);
  }
}

export default MultiDecorator;

redpajama_set_name: RedPajamaGithub


text:
package com.browseengine.bobo.sort;

import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Scorer;

public class MultiDocIdComparator extends DocComparator {
  private final DocComparator[] _comparators;

  public MultiDocIdComparator(DocComparator[] comparators) {
    _comparators = comparators;
  }

  @Override
  public int compare(ScoreDoc doc1, ScoreDoc doc2) {
    for (int i = 0; i < _comparators.length; ++i) {
      int v = _comparators[i].compare(doc1, doc2);
      if (v != 0) return v;
    }
    return 0;
  }

  @Override
  public MultiDocIdComparator setScorer(Scorer scorer) {
    for (DocComparator comparator : _comparators) {
      comparator.setScorer(scorer);
    }
    return this;
  }

  @Override
  public Comparable<?> value(ScoreDoc doc) {
    return new MultiDocIdComparable(doc, _comparators);
  }

  @SuppressWarnings("rawtypes")
  public static class MultiDocIdComparable implements Comparable {
    private final ScoreDoc _doc;
    private final DocComparator[] _comparators;

    public MultiDocIdComparable(ScoreDoc doc, DocComparator[] comparators) {
      _doc = doc;
      _comparators = comparators;
    }

    @SuppressWarnings("unchecked")
    @Override
    public int compareTo(Object o) {
      MultiDocIdComparable other = (MultiDocIdComparable) o;
      Comparable c1, c2;
      for (int i = 0; i < _comparators.length; ++i) {
        c1 = _comparators[i].value(_doc);
        c2 = other._comparators[i].value(other._doc);
        int v = c1.compareTo(c2);
        if (v != 0) {
          return v;
        }
      }
      return 0;
    }
  }
}


text:
class QTableWidget;
class QLineEdit;
class QPushButton;
class QTimer;

namespace qt
{
class DrawWidget;

class SearchPanel : public QWidget
{
  DrawWidget * m_pDrawWidget;
  QTableWidget * m_pTable;
  QLineEdit * m_pEditor;
  QPushButton * m_pClearButton;
  QTimer * m_pAnimationTimer;

  QPixmap m_busyIcon;

  std::vector<search::Result> m_results;

  search::EverywhereSearchParams m_params;
  uint64_t m_timestamp;

  ThreadChecker m_threadChecker;

  Q_OBJECT

public:
  SearchPanel(DrawWidget * drawWidget, QWidget * parent);

private:
  virtual void hideEvent(QHideEvent *);

  void ClearResults();

private slots:
  void OnSearchPanelItemClicked(int row, int column);
  void OnSearchTextChanged(QString const &);
  void OnSearchResults(uint64_t timestamp, search::Results const & results);

  void OnAnimationTimer();
  void OnClearButton();

  bool TryChangeRouterCmd(QString const & str);
  bool Try3dModeCmd(QString const & str);
  bool TryDisplacementModeCmd(QString const & str);
  bool TryTrafficSimplifiedColorsCmd(QString const & str);
};
}  // namespace qt


text:
require 'java_buildpack/component'

module JavaBuildpack
  module Component

    # An abstraction around the +JAVA_HOME+ path and +VERSION+ used by the droplet.  This implementation is mutable and
    # should be passed to any component that is a jre.
    #
    # A new instance of this type should be created once for the application.
    class MutableJavaHome

      # @!attribute [rw] root
      # @return [String] the root of the droplet's +JAVA_HOME+
      attr_accessor :root

      # @!attribute [rw] version
      # @return [Array] the major, minor, micro and qualifier of the droplet's +VERSION+
      attr_accessor :version

    end

  end
end


text:
package cn.bmob.imdemo.bean;

/**
 * Created by Administrator on 2017/3/20.
 */
public class Msg {
    public static final int TYPE_RECEIVE = 0;
    public static final int TYPE_SEND = 1;
    private String contant;
    private User who;
    private int type;

    public Msg(String contant, int type, User who) {
        this.contant = contant;
        this.who = who;
        this.type = type;
    }
    public User getWho(){return who;}
    public String getContant(){
        return contant;
    }
    public int getType(){
        return type;
    }

    public void setContant(String contant) {
        this.contant = contant;
    }
}


text:
import com.datastax.driver.core.Cluster
import com.datastax.driver.core.SocketOptions
import com.twitter.zipkin.builder.Scribe
import com.twitter.zipkin.cassandra
import com.twitter.zipkin.collector.builder.CollectorServiceBuilder
import com.twitter.zipkin.storage.Store
import org.twitter.zipkin.storage.cassandra.ZipkinRetryPolicy

val contactPoints: Array[String] = sys.env.get("CASSANDRA_CONTACT_POINTS").getOrElse("localhost")
  .split(",")

val cluster = Cluster.builder()
  .addContactPoints(contactPoints:_*)
  .withSocketOptions(new SocketOptions().setConnectTimeoutMillis(10000).setReadTimeoutMillis(20000))
  .withRetryPolicy(ZipkinRetryPolicy.INSTANCE)
  .build()

val storeBuilder = Store.Builder(new cassandra.SpanStoreBuilder(cluster))

CollectorServiceBuilder(Scribe.Interface(categories = Set("zipkin")))
  .writeTo(storeBuilder)


text:
namespace atf {
namespace utils {

// ------------------------------------------------------------------------
// The "auto_array" class.
// ------------------------------------------------------------------------

template< class T >
struct auto_array_ref {
    T* m_ptr;

    explicit auto_array_ref(T*);
};

template< class T >
auto_array_ref< T >::auto_array_ref(T* ptr) :
    m_ptr(ptr)
{
}

template< class T >
class auto_array {
    T* m_ptr;

public:
    auto_array(T* = NULL) throw();
    auto_array(auto_array< T >&) throw();
    auto_array(auto_array_ref< T >) throw();
    ~auto_array(void) throw();

    T* get(void) throw();
    const T* get(void) const throw();
    T* release(void) throw();
    void reset(T* = NULL) throw();

    auto_array< T >& operator=(auto_array< T >&) throw();
    auto_array< T >& operator=(auto_array_ref< T >) throw();

    T& operator[](int) throw();
    operator auto_array_ref< T >(void) throw();
};

template< class T >
auto_array< T >::auto_array(T* ptr)
    throw() :
    m_ptr(ptr)
{
}

template< class T >
auto_array< T >::auto_array(auto_array< T >& ptr)
    throw() :
    m_ptr(ptr.release())
{
}

template< class T >
auto_array< T >::auto_array(auto_array_ref< T > ref)
    throw() :
    m_ptr(ref.m_ptr)
{
}

template< class T >
auto_array< T >::~auto_array(void)
    throw()
{
    if (m_ptr != NULL)
        delete [] m_ptr;
}

template< class T >
T*
auto_array< T >::get(void)
    throw()
{
    return m_ptr;
}

template< class T >
const T*
auto_array< T >::get(void)
    const throw()
{
    return m_ptr;
}

template< class T >
T*
auto_array< T >::release(void)
    throw()
{
    T* ptr = m_ptr;
    m_ptr = NULL;
    return ptr;
}

template< class T >
void
auto_array< T >::reset(T* ptr)
    throw()
{
    if (m_ptr != NULL)
        delete [] m_ptr;
    m_ptr = ptr;
}

template< class T >
auto_array< T >&
auto_array< T >::operator=(auto_array< T >& ptr)
    throw()
{
    reset(ptr.release());
    return *this;
}

template< class T >
auto_array< T >&
auto_array< T >::operator=(auto_array_ref< T > ref)
    throw()
{
    if (m_ptr != ref.m_ptr) {
        delete [] m_ptr;
        m_ptr = ref.m_ptr;
    }
    return *this;
}

template< class T >
T&
auto_array< T >::operator[](int pos)
    throw()
{
    return m_ptr[pos];
}

template< class T >
auto_array< T >::operator auto_array_ref< T >(void)
    throw()
{
    return auto_array_ref< T >(release());
}

// ------------------------------------------------------------------------
// The "noncopyable" class.
// ------------------------------------------------------------------------

class noncopyable {
    // The class cannot be empty; otherwise we get ABI-stability warnings
    // during the build, which will break it due to strict checking.
    int m_noncopyable_dummy;

    noncopyable(const noncopyable& nc);
    noncopyable& operator=(const noncopyable& nc);

protected:
    // Explicitly needed to provide some non-private functions.  Otherwise
    // we also get some warnings during the build.
    noncopyable(void) {}
    ~noncopyable(void) {}
};

} // namespace utils
} // namespace atf

#endif // !defined(_ATF_CXX_UTILS_HPP_)


text:
layout: post
permalink: /javascript-ucfirst-function
title: "Implementing ucfirst in JavaScript"
category: "One-Liner"
tags: capitalize javascript jquery ucfirst
---
### What is ucfirst()?

`ucfirst` is a function which exists natively in [PHP](http://php.net/manual/en/function.ucfirst.php) and other languages. It is used to capitalize the first character of a string. Unfortunately, it is not included in the JavaScript language by default.

That's alright, because it is not that difficult to emulate!

## Function: ucfirst

The `ucfirst` function will retrieve the character at position 0 in a string an apply the uppercase function to it. It will then apply a lowercase function and concatenate the remainder of the string to the uppercase first character.

With JavaScript, it is very simple as you can see below:

    function ucfirst(string){
        return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
    }

## Usage

    // Create example string variable
    var example_str = "this is an example string!";

    // Lets view the output
    console.log( ucfirst( example_str ) );

    // Returns:
    // This is an example string!


text:
===========
libxmlquery
===========

C library to parse and query xml using css selectors, built for low
memory footprint and portability.

This software is released under the `MIT license
<http://github.com/nullable/libxmlquery/blob/master/LICENSE>`_.

Both the software and its documentation are in a *pre alpha* stage,
please use with caution.


text:
class ContactResource < JSONAPI::Resource
  include JSONAPI::Resources::Filterer
end


text:
using System;
using Pomelo.EntityFrameworkCore.MySql.Tests;

namespace Pomelo.EntityFrameworkCore.MySql.IntegrationTests.Commands
{
    public class ConnectionStringCommand : IConnectionStringCommand
    {
        public void Run()
        {
            Console.Write(AppConfig.ConnectionString);
        }
    }
}


text:
package org.hibernate.envers.test.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.envers.Audited;

/**
 * @author Adam Warski (adam at warski dot org)
 */
@Entity
public class StrIntTestEntity {
    @Id
    @GeneratedValue
    private Integer id;

    @Audited
    private String str1;

    @Audited
    @Column(name = "NUM_VAL")
    private Integer number;

    public StrIntTestEntity() {
    }

    public StrIntTestEntity(String str1, Integer number, Integer id) {
        this.id = id;
        this.str1 = str1;
        this.number = number;
    }

    public StrIntTestEntity(String str1, Integer number) {
        this.str1 = str1;
        this.number = number;
    }

    public Integer getId() {
        return id;
    }

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

    public String getStr1() {
        return str1;
    }

    public void setStr1(String str1) {
        this.str1 = str1;
    }

    public Integer getNumber() {
        return number;
    }

    public void setNumber(Integer number) {
        this.number = number;
    }

    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof StrIntTestEntity)) return false;

        StrIntTestEntity that = (StrIntTestEntity) o;

        if (id != null ? !id.equals(that.id) : that.id != null) return false;
        if (number != null ? !number.equals(that.number) : that.number != null) return false;
        if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false;

        return true;
    }

    public int hashCode() {
        int result;
        result = (id != null ? id.hashCode() : 0);
        result = 31 * result + (str1 != null ? str1.hashCode() : 0);
        result = 31 * result + (number != null ? number.hashCode() : 0);
        return result;
    }

    public String toString() {
        return "SITE(id = " + id + ", str1 = " + str1 + ", number = " + number + ")";
    }
}


text:
using Microsoft.ApplicationInsights;
using NLog;
using System.Collections.Generic;
using System.Web.Http.ExceptionHandling;
using SFA.DAS.Logging;

namespace SFA.DAS.EAS.Account.Api.ExceptionLoggers
{
    public class ErrorLogger : ExceptionLogger
    {
        private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

        public override void Log(ExceptionLoggerContext context)
        {
            var properties = new Dictionary<string, object>
            {
                ["HttpMethod"] = context.Request.Method,
                ["IsAuthenticated"] = context.RequestContext.Principal?.Identity?.IsAuthenticated ?? false,
                ["Url"] = context.Request.RequestUri.PathAndQuery,
                ["UrlReferrer"] = context.Request.Headers.Referrer?.PathAndQuery
            };

            var message = context.Exception.GetMessage();
            var telemetryClient = new TelemetryClient();

            Logger.Error(context.Exception, message, properties);
            telemetryClient.TrackException(context.Exception);
        }
    }
}


text:
using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Bson.Serialization.Options;
using MongoDB.Bson.Serialization.Serializers;
using Platform.Domain;

namespace WhoWhat.Core.Configuration
{
    internal class MongoDbConfigurator
    {
        internal void RegisterMongoDbConventions()
        {
            var appConventions = new ConventionPack
            {
                new IgnoreExtraElementsConvention(true),
                new EnumRepresentationConvention(BsonType.String),
                new NamedIdMemberConvention("Id"),
            };

            BsonClassMap.RegisterClassMap<EventMetadata>();
            ConventionRegistry.Register("Core", appConventions, type => true);

            BsonSerializer.RegisterSerializer(typeof(DateTime), new DateTimeSerializer(new DateTimeSerializationOptions(DateTimeKind.Utc)));
            BsonSerializer.RegisterSerializer(typeof(DateTime?), new NullableSerializer<DateTime>());
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Sxta.GenericProtocol.Encoding
{
	public class ByteEncoding
	{
		 public static readonly EndianTypes Endian = (BitConverter.IsLittleEndian ? EndianTypes.LittleEndian : EndianTypes.BigEndian);

        /// <summary>
        /// Encodes the specified parameterValue, returning the result as a byte array.
        /// </summary>
        /// <param name="parameterValue">the parameterValue to Encode
        /// </param>
        /// <returns>
        /// a byte array containing the encoded parameterValue
        /// An array of bytes with length 1.
        /// </returns>
        public static byte[] Encode(byte val)
        {
            return new byte[] { val };
        }
        public static void Encode(Stream buffer, byte val)
        {
            buffer.WriteByte(val);
        }

        /// <summary>
        /// Decodes and returns the parameterValue stored in the specified bufferStream.
        /// </summary>
        /// <param name="bufferStream">the bufferStream containing the encoded parameterValue
        /// </param>
        /// <returns> the decoded parameterValue
        /// </returns>
        /// <exception cref="System.IO.IOException"> if the parameterValue could not be decoded
        /// </exception>
        public static byte Decode(byte[] buffer)
        {
            if (buffer == null)
                throw new Exception();
            if (buffer.Length < sizeof(byte))
                throw new Exception();
            return buffer[0];
        }
        public static byte Decode(byte[] buffer, int startPos)
        {
            if (buffer == null)
                throw new Exception();
            if (buffer.Length < startPos + sizeof(byte))
                throw new Exception();
            return buffer[startPos];
        }
        public static byte Decode(Stream buffer)
        {
            if (buffer == null)
                throw new ArgumentException("Buffer is null");
            return (byte)buffer.ReadByte();
        }

        public static int ByteSize
        {
            get { return sizeof(byte); }
        }

	}

	public class ByteEncodingLE : ByteEncoding
	{
	}

	public class ByteEncodingBE : ByteEncoding
	{
	}
}


text:
'use strict';
var S = {
	log: (typeof console !== 'undefined' && console.log ) || function(){},
	toInt:function(arg){ return parseInt(arg,10); },

    /* IS */

    isString: function(varName){ return typeof varName === 'string'; },
    isObject: function(varName){ return typeof varName === 'object'; },
    isFunction: function(varName){ return typeof varName === 'function'; },
    isNumber: function(varName){ return typeof varName === 'number'; },
    isArray: Array.isArray,

    /* utils */

    iterator: function(iterable) {
        if (Array.isArray(iterable)) {
            return S.array.iterator(iterable);
        }
        var iterator = iterable.iterator();
        if (S.isFunction(iterator.hasNext)) {
            return iterator;
        }

        var nextValue, hasNext=true;
        var next = function(){
            try {
                nextValue = iterator.next();
            } catch(StopIteration) {
                hasNext = false;
                nextValue = undefined;
            }
        };
        next();
        return Object.freeze({
            hasNext: function(){
                return hasNext;
            },
            next: function(){
                var currentValue = nextValue;
                next();
                return currentValue;
            }
        });
    },

    asyncWhile: function(nextCallback, forEachCallback, endCallback) {
        (function _while(err) {
            if (err) {
                return endCallback(err);
            }
            nextCallback(function(next) {
                if (next) {
                    forEachCallback(next, _while);
                } else {
                    endCallback();
                }
            });
        })();
    },

	/* IS */

    /* HTML */
    escape: function(html) {
        return String(html)
            .replace(/&(?!\w+;)/g, '&')
            .replace(/</g, '<')
            .replace(/>/g, '>')
            .replace(/"/g, '"');
    },
    escapeUrl: function(html) {
        return html.replace(/&/g,'&');
    },

    regexpEscape: function(s) {
        return s.replace( /([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1" );
    }
};
//S.Class=S.extClass(Object);

'filter find findIndex forEach join map reduce reduceRight some'.split(' ').forEach(function(methodName) {
    S[methodName] = function(arrayOrObject) {
        var args = Array.prototype.slice.call(arguments, 1);
        var method = arrayOrObject[methodName];
        if (!method) {
            method = S.object[methodName];
            args.unshift(arrayOrObject);
        }
        return method.apply(null, args);
    };
});

/**
 * Create a new object library
 * @param {Function} fn
 * @return {Object}
 */
S.newLibrary = function(fn) {
    var lib = {};
    Object.defineProperty(lib, 'defineProperties', { value: S.defineProperties.bind(null, lib) });
    if (fn) {
        fn(lib);
    }
    return lib;
};

/**
 * Freeze a library
 * @param {Object} lib
 * @return {Object}
 */
S.freezeLibrary = function(lib) {
    Object.freeze(lib);
    return lib;
};

/**
 * Create a new class
 * @param {function} fn
 * @return {function}
 */
S.newClass = function(fn) {
    return S.extendClass(Object, fn);
};

S.extendThis = function(fn) {
    return S.extendClass(this, fn);
};

S.extendClass = function(parent, fn) {
    // The constructor function for the new subclass is either defined by you
    // (the "constructor" property in your `extend` definition), or defaulted
    // by us to simply call the parent's constructor.
    var child = function() {
        this.construct.apply(this, arguments);
    };
    /*
        in constructor when mixins :
        if (mixins) {
            mixins.forEach(function(mixin){
                mixin.call(this);
            }.bind(this));
        }
    */

    // Set the prototype chain to inherit from `parent`, without calling `parent`'s constructor function.
    // + Set a convenience property in case the parent's prototype is needed later.
    child.prototype = Object.create(child.super_ = parent.prototype);
    if (!child.prototype.construct) {
        child.prototype.construct = function() {
            if (child.super_.construct) {
                child.super_.construct.apply(this, arguments);
            }
        };
    }
    Object.defineProperty(child, 'superConstruct', { value: function() {
        return child.super_.construct.apply(this, arguments);
    } });
    Object.defineProperty(child.prototype, 'self', { value: child });
    Object.defineProperty(child, 'extend', { configurable: true, value: S.extendThis });
    Object.defineProperty(child, 'extendPrototype', { value: S.extendPrototype.bind(null, child) });
    Object.defineProperty(child, 'defineProperties', { value: S.defineProperties.bind(null, child) });
    Object.defineProperty(child, 'defineProperty', { value: S.defineProperty.bind(null, child) });

    if (fn) {
        if (S.isObject(fn)) {
            child.extendPrototype(fn);
        } else {
            fn(child, parent);
        }
    }

    // Add mixins
    /*
    if (mixins) {
        mixins.forEach(function(mixin){
            S.mixin(child, mixin);
        }.bind(this));
    }*/

    return child;
};

S.defineProperty = function(targetObject, property, value, writable, configurable) {
    Object.defineProperty(targetObject, property, { value: value, writable: !!writable, configurable: !!configurable });
};

S.defineProperties = function(targetObject, properties, writable, configurable) {
    if (properties) {
        writable = !!writable;
        configurable = !!configurable;
        for (var k in properties) {
            if (k === 'writable') {
                S.defineProperties(targetObject, properties[k], true);
            } else if (k === 'configurable') {
                S.defineProperties(targetObject, properties[k], false, true);
            } else {
                Object.defineProperty(targetObject, k,{ value: properties[k], writable: writable, configurable: configurable });
            }
        }
    }
    return targetObject;
};

S.extendPrototype = function(targetClass, methods, writable) {
    S.defineProperties(targetClass.prototype, methods, writable);
    return targetClass;
};

module.exports = S;

S.array = require('./array.js');
S.object = require('./object.js')
S.string = require('./string/string.js');
S.date = require('./date.js');


text:
motionstream
============

Multiplayer Motion Data Streams


text:
package task.application.com.colette.ui.appsearch;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.SparseArray;
import android.view.ViewGroup;

/**
 * Created by sHIVAM on 7/23/2017.
 */

public abstract class CustomFragmentStatePagerAdapter<T extends Fragment>
        extends FragmentStatePagerAdapter {

    private SparseArray<T> registeredFragments = new SparseArray<T>();

    public CustomFragmentStatePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        T fragment = (T) super.instantiateItem(container, position);
        registeredFragments.put(position, fragment);
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        registeredFragments.remove(position);
        super.destroyItem(container, position, object);
    }

    public T getRegisteredFragment(int position) {
        return registeredFragments.get(position);
    }

}


text:
package com.jlfex.hermes.repository;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import com.jlfex.hermes.model.Product;
import com.jlfex.hermes.model.ProductOverdue;

/**
 * 产品逾期信息仓库
 */
@Repository
public interface ProductOverdueRepository extends JpaRepository<ProductOverdue, String>, JpaSpecificationExecutor<ProductOverdue> {

	/**
	 * 通过产品获取逾期列表
	 * @param product
	 * @return
	 */
	public List<ProductOverdue> findByProduct(Product product);

}


text:
package aecor.data

import aecor.Has
final case class EntityEvent[K, A](entityKey: K, sequenceNr: Long, payload: A) {
  def map[B](f: A => B): EntityEvent[K, B] = copy(payload = f(payload))
}

object EntityEvent {
  implicit def aecorHasInstanceForKey[X, K, A](implicit K: Has[K, X]): Has[EntityEvent[K, A], X] =
    Has.instance[EntityEvent[K, A]](x => K.get(x.entityKey))
  implicit def aecorHasInstanceForValue[X, K, A](implicit A: Has[A, X]): Has[EntityEvent[K, A], X] =
    Has.instance[EntityEvent[K, A]](x => A.get(x.payload))
}


text:
package org.commcare.interfaces;

import android.os.Bundle;

public interface BasePresenterContract {
    void saveInstanceState(Bundle out);

    void loadSaveInstanceState(Bundle savedInstanceState);

    void onActivityDestroy();

    void start();
}


text:
package com.zedeff.vendingma.services;

import android.support.annotation.Nullable;

import com.zedeff.vendingma.models.PurchaseResult;
import com.zedeff.vendingma.models.Item;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

public class VendingMachineImpl implements VendingMachine {

    private Map<Item, Integer> stock = new HashMap<>();

    @Override
    public void addStock(Item item, int amount) {
        if (stock.containsKey(item)) {
            amount += stock.get(item);
        }
        stock.put(item, amount);
    }

    @Override
    public Map<Item, Integer> getStockLevels() {
        return stock;
    }

    @Override
    public PurchaseResult purchase(Item item, BigDecimal amount) {
        if (!stock.containsKey(item) || stock.get(item) < 1) {
            return new PurchaseResult(false, "Item is not available", amount);
        }
        if (item.getPrice().compareTo(amount) > 0) {
            return new PurchaseResult(false, "Not enough money, keep those coins coming!", BigDecimal.ZERO);
        }

        stock.put(item, stock.get(item) - 1);

        return new PurchaseResult(true, null, amount.subtract(item.getPrice()).setScale(2, RoundingMode.HALF_UP));
    }

    @Override
    @Nullable
    public Item getItemForName(String itemName) {
        for (Item i : stock.keySet()) {
            if (i.getName().equals(itemName)) {
                return i;
            }
        }
        return null;
    }
}


text:
package com.google.gerrit.server.account;

import java.io.IOException;
import java.util.Arrays;

import org.apache.http.HttpStatus;

import com.google.common.base.MoreObjects;
import com.google.gerrit.extensions.common.AccountInfo;
import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.extensions.restapi.ResourceConflictException;
import com.google.gerrit.extensions.restapi.Response;
import com.google.gerrit.extensions.restapi.TopLevelResource;
import com.google.gerrit.extensions.restapi.UnprocessableEntityException;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Account.Id;
import com.google.gerrit.reviewdb.client.AccountExternalId;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.account.CreateAccount.Factory;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;

public class AccountImporter {
  private final Factory createAccountFactory;
  private final Provider<ReviewDb> schema;

  @Inject
  public AccountImporter(final CreateAccount.Factory createAccountFactory,
      final Provider<ReviewDb> schema) {
    this.createAccountFactory = createAccountFactory;
    this.schema = schema;
  }

  public Account.Id importAccount(String login, String name, String email)
      throws IOException, BadRequestException, ResourceConflictException,
      UnprocessableEntityException, OrmException {
    ReviewDb db = schema.get();
    CreateAccount createAccount = createAccountFactory.create(login);
    CreateAccount.Input accountInput = new CreateAccount.Input();
    accountInput.email = email;
    accountInput.username = login;
    accountInput.name = MoreObjects.firstNonNull(name, login);
    Response<AccountInfo> accountResponse =
        (Response<AccountInfo>) createAccount.apply(TopLevelResource.INSTANCE,
            accountInput);
    if (accountResponse.statusCode() == HttpStatus.SC_CREATED) {
      Id accountId = new Account.Id(accountResponse.value()._accountId);
      db.accountExternalIds().insert(
          Arrays
              .asList(new AccountExternalId(accountId,
                  new AccountExternalId.Key(AccountExternalId.SCHEME_GERRIT,
                      login))));
      return accountId;
    } else {
      throw new IOException("Cannot import GitHub account " + login
          + ": HTTP Status " + accountResponse.statusCode());
    }
  }
}


text:
package org.ajgl.graphics.shaders;

import org.ajgl.graphics.UtilAnnotations.GlShaderFunction;
import org.lwjgl.opengl.GL20;

/**
 * This class is designed to represent a shader program in OpenGL.
 *
 * @author Tyler Bucher
 * @see GlShaderFunction
 */
@GlShaderFunction
public class ShaderProgram {

    /**
     * The shader program id.
     */
    public final int id;

    /**
     * Creates a new {@link GL20#glCreateProgram() Shader Program} object.
     */
    public ShaderProgram() {
        id = GL20.glCreateProgram();
    }

    /**
     * @param shader the {@link Shader} to be attached to the {@link ShaderProgram}.
     */
    public void attachShader(Shader shader) {
        GL20.glAttachShader(id, shader.id);
    }

    /**
     * @param shader the {@link Shader} to be detached from the {@link ShaderProgram}.
     */
    public void detachShader(Shader shader) {
        GL20.glDetachShader(id, shader.id);
    }

    /**
     * Links the {@link GL20#glLinkProgram shader program}.
     */
    public void link() {
        GL20.glLinkProgram(id);
    }

    /**
     * Validates the {@link GL20#glValidateProgram shader program}.
     */
    public void validate() {
        GL20.glValidateProgram(id);
    }

    /**
     * @return true if the shader program was compiled false otherwise.
     */
    public boolean verify() {
        int status = GL20.glGetProgrami(id, GL20.GL_LINK_STATUS);

        return status != 0;
    }

    /**
     * Deletes an OpenGL shader program.
     */
    public void deleteProgram() {
        GL20.glDeleteProgram(id);
    }

    @Override
    public void finalize() {
        GL20.glDeleteProgram(id);
    }
}


text:
  <load-edit title="{$ ctrl.title $}"
             model="ctrl.spec"
             max-bytes="{$ 16 * 1024 $}"
             key="spec"
             rows=8 required="true"
             on-textarea-change="ctrl.onSpecChange(textContent)">
  </load-edit>


text:
<?php
namespace Lawoole\Contracts\Server;

use IteratorAggregate;
use Lawoole\Contracts\Support\EventDispatcher;

interface Server extends EventDispatcher, IteratorAggregate
{
    /**
     * Set the server options.
     *
     * @param array $options
     */
    public function setOptions(array $options = []);

    /**
     * Add a listening defined in the given server socket.
     *
     * @param \Lawoole\Contracts\Server\ServerSocket $serverSocket
     */
    public function listen(ServerSocket $serverSocket);

    /**
     * Add a child process managed by the server.
     *
     * @param \Lawoole\Contracts\Server\Process $process
     */
    public function fork(Process $process);

    /**
     * Return whether the server is running.
     *
     * @return bool
     */
    public function isRunning();

    /**
     * Start the server.
     *
     * @return bool
     */
    public function start();

    /**
     * Shutdown the server.
     *
     * @return bool
     */
    public function shutdown();

    /**
     * Reload all workers.
     *
     * @param bool $onlyTask
     *
     * @return bool
     */
    public function reload($onlyTask = false);

    /**
     * Retrieve an iterator for all connections connected to the server.
     *
     * @return \Traversable
     */
    public function getIterator();
}


text:
from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
from osmtm.utils import load_local_settings

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
from osmtm import models
target_metadata = models.Base.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.

def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    url = config.get_main_option("sqlalchemy.url")
    context.configure(url=url, target_metadata=target_metadata)

    with context.begin_transaction():
        context.run_migrations()

def run_migrations_online():
    """Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """

    settings = config.get_section(config.config_ini_section)
    load_local_settings(settings)
    engine = engine_from_config(
        settings,
        prefix='sqlalchemy.',
        poolclass=pool.NullPool
    )

    connection = engine.connect()
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        compare_type=True
    )

    try:
        with context.begin_transaction():
            context.run_migrations()
    finally:
        connection.close()

if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()


text:
<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android"
            class="com.bkromhout.minerva.ui.transitions.CircularReveal"
            android:interpolator="@android:interpolator/linear_out_slow_in"
            android:duration="500">
    <targets>
        <target android:targetId="@id/coordinator"/>
    </targets>
</transition>


text:
namespace ccl.Framework.Commands.Context
{
    /// <summary>
    /// Contains information about configured services, commands and additional parameters supplied during execution.
    /// </summary>
    public interface ICommandContext
    {
    }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.03.27 at 03:31:18 PM GMT
//

package org.apache.wss4j.binding.wsu10;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;

/**
 * This object contains factory methods for each
 * Java content interface and Java element interface
 * generated in the org.apache.wss4j.binding.wsu10 package.
 *
An ObjectFactory allows you to programatically
 * construct new instances of the Java representation
 * for XML content. The Java representation of XML
 * content can consist of schema derived interfaces
 * and classes representing the binding of schema
 * type definitions, element declarations and model
 * groups.  Factory methods for each of these are
 * provided in this class.
 *
 */
@XmlRegistry
public class ObjectFactory {

    private static final String WSU_NS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
    private static final QName _Expires_QNAME = new QName(WSU_NS, "Expires");
    private static final QName _Created_QNAME = new QName(WSU_NS, "Created");
    private static final QName _Timestamp_QNAME = new QName(WSU_NS, "Timestamp");

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.apache.wss4j.binding.wsu10
     *
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link AttributedDateTime }
     *
     */
    public AttributedDateTime createAttributedDateTime() {
        return new AttributedDateTime();
    }

    /**
     * Create an instance of {@link TimestampType }
     *
     */
    public TimestampType createTimestampType() {
        return new TimestampType();
    }

    /**
     * Create an instance of {@link AttributedURI }
     *
     */
    public AttributedURI createAttributedURI() {
        return new AttributedURI();
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link AttributedDateTime }{@code >}}
     *
     */
    @XmlElementDecl(namespace = WSU_NS, name = "Expires")
    public JAXBElement<AttributedDateTime> createExpires(AttributedDateTime value) {
        return new JAXBElement<AttributedDateTime>(_Expires_QNAME, AttributedDateTime.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link AttributedDateTime }{@code >}}
     *
     */
    @XmlElementDecl(namespace = WSU_NS, name = "Created")
    public JAXBElement<AttributedDateTime> createCreated(AttributedDateTime value) {
        return new JAXBElement<AttributedDateTime>(_Created_QNAME, AttributedDateTime.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link TimestampType }{@code >}}
     *
     */
    @XmlElementDecl(namespace = WSU_NS, name = "Timestamp")
    public JAXBElement<TimestampType> createTimestamp(TimestampType value) {
        return new JAXBElement<TimestampType>(_Timestamp_QNAME, TimestampType.class, null, value);
    }

}


text:
using UnityEngine;
using System.Collections;

public class PlayLevelButton : MonoBehaviour
{
	// Public vars
	public float TimeDelay = 0.5f;

	// Private vars
	private Vector3 originalScale;
	private bool pressed = false;
	private float timer = 0.0f;

	// Use this for initialization
	void Start()
	{
		originalScale = transform.localScale;
	}

	// Update is called once per frame
	void Update()
	{
		transform.localScale = Vector3.Lerp(transform.localScale, originalScale, 5.0f * Time.deltaTime);

		// Load the level once the button is back to it's original size.
		if (pressed)
		{
			timer -= Time.deltaTime;
			if (timer < 0)
			{
				gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");
				Camera.mainCamera.GetComponent<GUILayer>().enabled = false;
				LevelSelectGUI.worldToShow = LevelSelectGUI.currentWorld;
				LevelSelectGUI.levelToShow = LevelSelectGUI.currentLevel.number;
				LevelSelectGUI.LoadSelectedLevel();
				pressed = false;
			}
		}
	}

	void OnMouseDown()
	{
		// If the highscores menu is open, then we can't be pressed.
		if (!HighScoresGUI.enable)
		{
			LevelSelectGUI.canSpin = false;

			GameObject highscoresbutton = GameObject.Find("Highscores");
			if (highscoresbutton != null)
				highscoresbutton.active = false;
			GameObject rButton = GameObject.Find("ReturnButton");
			if (rButton != null)
				rButton.active = false;
			transform.localScale *= 1.1f;
			pressed = true;
			timer = TimeDelay;
		}
	}
}


text:
<?php

namespace SellerLabs\Nucleus\Control;

/**
 * Class Nothing
 *
 * @author Eduardo Trujillo <ed@sellerlabs.com>
 * @package SellerLabs\Nucleus\Control
 */
class Nothing extends Maybe
{
    protected $value = null;

    /**
     * @inheritdoc
     */
    public function isJust()
    {
        return false;
    }

    /**
     * @inheritdoc
     */
    public function isNothing()
    {
        return true;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

     Copyright 2014-2016 CyberVision, Inc.

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.

-->

<resources>

    <style name="FullScreenAppTheme" parent="Theme.AppCompat.AppTheme">
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowActionBarOverlay">true</item>
        <item name="android:windowActionModeOverlay">true</item>
    </style>

    <style name="FullScreenDeviceTheme" parent="DeviceTheme">
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowActionBarOverlay">true</item>
        <item name="android:windowActionModeOverlay">true</item>
    </style>

    <style name="Widget.Holo" parent="@android:style/Widget.Holo">
    </style>

    <style name="Widget.Holo.SeekBar" parent="@android:style/Widget.Holo.SeekBar">
    </style>

    <style name="Widget.Holo.Light.SeekBar" parent="@android:style/Widget.Holo.Light.SeekBar">
    </style>

</resources>


text:
package org.sakaiproject.tool.assessment.ui.model.delivery;

import java.util.Date;

import org.sakaiproject.tool.assessment.facade.PublishedAssessmentFacade;

/**
 *
Title:

 *
Description:

 *
Copyright: Copyright (c) 2004

 *
Company:

 * @author not attributable
 * @version 1.0
 */

public class TimedAssessmentGradingModel
{
  private Long assessmentGradingId;
  private int timeLimit; // in seconds
  private int timeLeft; // in seconds
  private Date beginDate;
  private Date expirationDate;
  private Date bufferedExpirationDate;
  private Date localBeginDate;
  private Date localExpirationDate;
  private boolean submittedForGrade=false;
  private String timerId;
  private PublishedAssessmentFacade publishedAssessment;

  /* 30 sec, this is to allow JScript clock to catch up before server submit the
   * assessment for grade
   */
  private int latencyBuffer=30;

  /* timedAG is removed from timedAssessmentQueue immediately if the submission for
   * grade is initiated by user OR the AutoSubmit script in the web page. If user exit
   * application unexpectedly (e.g.closing browser), server will do the submission
   * when time is up and also clean up the timedAG in queue. So we add a transactionBuffer
   * here before server clean up
   */
  private int transactionBuffer=30; // 30 sec

  public TimedAssessmentGradingModel() {
  }

  public TimedAssessmentGradingModel(Long assessmentGradingId,
      int timeLimit, int timeLeft,
      Date beginDate, Date localBeginDate,
      boolean submittedForGrade, String timerId, PublishedAssessmentFacade publishedAssessment){
    this.assessmentGradingId = assessmentGradingId;
    this.timeLimit = timeLimit;
    this.timeLeft = timeLeft;
    this.beginDate = beginDate;
    this.expirationDate = new Date(beginDate.getTime() + timeLeft*1000L);
    this.bufferedExpirationDate = new Date(beginDate.getTime() + timeLeft*1000L + latencyBuffer*1000);
    this.submittedForGrade = submittedForGrade;
    this.localBeginDate = localBeginDate;
    this.localExpirationDate = new Date(localBeginDate.getTime() + timeLeft*1000L);
    this.timerId = timerId;
    this.publishedAssessment = publishedAssessment;
  }

  public TimedAssessmentGradingModel(Long assessmentGradingId,
      int timeLimit, int timeLeft,
      int latencyBuffer, int transactionBuffer,
      Date beginDate, Date localBeginDate,
      boolean submittedForGrade, String timerId, PublishedAssessmentFacade publishedAssessment){
    this.assessmentGradingId = assessmentGradingId;
    this.timeLimit = timeLimit;
    this.timeLeft = timeLeft;
    this.latencyBuffer = latencyBuffer;
    this.transactionBuffer = transactionBuffer;
    this.beginDate = beginDate;
    this.expirationDate = new Date(beginDate.getTime() + timeLeft*1000L);
    this.bufferedExpirationDate = new Date(beginDate.getTime() + timeLeft*1000L + latencyBuffer*1000);
    this.submittedForGrade = submittedForGrade;
    this.localBeginDate = localBeginDate;
    this.localExpirationDate = new Date(localBeginDate.getTime() + timeLeft*1000L);
    this.timerId = timerId;
    this.publishedAssessment = publishedAssessment;
  }

  public Long getAssessmentGradingId() {
    return assessmentGradingId;
  }

  public void setAssessmentGradingId(Long assessmentGradingId) {
    this.assessmentGradingId = assessmentGradingId;
  }

  public int getTimeLimit() {
    return timeLimit;
  }

  public void setTimeLimit(int timeLimit) {
    this.timeLimit = timeLimit;
  }

  public int getTimeLeft() {
    return timeLeft;
  }

  public void setTimeLeft(int timeLeft) {
    this.timeLeft = timeLeft;
  }

  public int getLatencyBuffer() {
    return latencyBuffer;
  }

  public void setLatencyBuffer(int latencyBuffer) {
    this.latencyBuffer = latencyBuffer;
  }

  public int getTransactionBuffer() {
    return transactionBuffer;
  }

  public void setTransactionBuffer(int transactionBuffer) {
    this.transactionBuffer = transactionBuffer;
  }

  public Date getBeginDate() {
    return beginDate;
  }

  public void setBeginDate(Date beginDate) {
    this.beginDate = beginDate;
  }

  public Date getExpirationDate() {
    return expirationDate;
  }

  public void setExpirationDate(Date expirationDate) {
    this.expirationDate = expirationDate;
  }

  public Date getBufferedExpirationDate() {
    return bufferedExpirationDate;
  }

  public void setBufferedExpirationDate(Date bufferedExpirationDate) {
    this.bufferedExpirationDate = bufferedExpirationDate;
  }

  public Date getLocalBeginDate() {
    return localBeginDate;
  }

  public void setLocalBeginDate(Date localBeginDate) {
    this.localBeginDate = localBeginDate;
  }

  public Date getLocalExpirationDate() {
    return localExpirationDate;
  }

  public void setLocalExpirationDate(Date localExpirationDate) {
    this.localExpirationDate = localExpirationDate;
  }

  public boolean getSubmittedForGrade() {
    return submittedForGrade;
  }

  public void setSubmittedForGrade(boolean submittedForGrade) {
    this.submittedForGrade = submittedForGrade;
  }

  public String getTimerId(){
    return timerId;
  }

  public void setTimerId(String timerId) {
    this.timerId = timerId;
  }

  public PublishedAssessmentFacade getPublishedAssessment(){
	  return publishedAssessment;
  }

  public void setPublishedAssessment(PublishedAssessmentFacade publishedAssessment) {
	  this.publishedAssessment = publishedAssessment;
  }
}


text:
using Aspose.Email.Mail;
using Aspose.Email.Outlook;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Email for .NET API reference
when the project is build. Please check https://Docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.Email for .NET API from http://www.aspose.com/downloads,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
*/

namespace Aspose.Email.Examples.CSharp.Email.Outlook
{
    class CreatingMSGFilesWithRTFBody
    {
        public static void Run()
        {
            string dataDir = RunExamples.GetDataDir_Outlook();

            // ExStart:CreatingMSGFilesWithRTFBody
            // Create an instance of the MailMessage class
            MailMessage mailMsg = new MailMessage();

            // Set from, to, subject and body properties
            mailMsg.From = "from@domain.com";
            mailMsg.To = "to@domain.com";
            mailMsg.Subject = "subject";
            mailMsg.HtmlBody = "
rtf example

creating an outlook message (msg) file using Aspose.Email.
";

            MapiMessage outlookMsg = MapiMessage.FromMailMessage(mailMsg);
            outlookMsg.Save(dataDir + "CreatingMSGFilesWithRTFBody_out.msg");
            // ExEnd:CreatingMSGFilesWithRTFBody
        }
    }
}


text:
namespace system_logs {

// Reads the file at |path| into |contents| and returns true on success and
// false on error. For security reasons a |path| containing path traversal
// components ('..') is treated as a read error and |contents| is not changed.
// When the file exceeds |max_size| function returns true with the last
// |max_size| bytes from the file.
bool ReadEndOfFile(const base::FilePath& path,
                   std::string* contents,
                   size_t max_size);

// Exposes the utility methods only for unittests.
#if defined(UNIT_TEST)
std::string ReadUserLogFile(const base::FilePath& log_file_path);
std::string ReadUserLogFilePattern(const base::FilePath& log_file_path_pattern);
#endif  // defined(UNIT_TEST)

// Gathers log data from Debug Daemon.
class DebugDaemonLogSource : public SystemLogsSource {
 public:
  explicit DebugDaemonLogSource(bool scrub);

  DebugDaemonLogSource(const DebugDaemonLogSource&) = delete;
  DebugDaemonLogSource& operator=(const DebugDaemonLogSource&) = delete;

  ~DebugDaemonLogSource() override;

  // SystemLogsSource override:
  // Fetches logs from the daemon over dbus. After the fetch is complete, the
  // results will be forwarded to the request supplied to the constructor and
  // this instance will free itself.
  void Fetch(SysLogsSourceCallback callback) override;

 private:
  typedef std::map<std::string, std::string> KeyValueMap;

  // Callbacks for the dbus calls to debugd.
  void OnGetRoutes(bool is_ipv6,
                   absl::optional<std::vector<std::string>> routes);
  void OnGetOneLog(std::string key, absl::optional<std::string> status);
  void OnGetLogs(const base::TimeTicks get_start_time,
                 bool succeeded,
                 const KeyValueMap& logs);

  // Reads the logged-in users' log files that have to be read by Chrome as
  // debugd has no access to them. The contents of these logs are appended to
  // |response_|. This is called at the end when all debugd logs are collected
  // so that we can see any debugd related errors surface in feedback reports.
  void GetLoggedInUsersLogFiles();

  void OnGetUserLogFiles(bool succeeded,
                         const KeyValueMap& logs);

  // Merge the responses from ReadUserLogFiles into the main response dict and
  // invoke the callback_.Run method with the assumption that all other logs
  // have already been collected.
  void MergeUserLogFilesResponse(std::unique_ptr<SystemLogsResponse> response);

  // When all the requests are completed, send one last request to collect the
  // user logs and complete the collection by invoking the callback's Run
  // method.
  void RequestCompleted();

  std::unique_ptr<SystemLogsResponse> response_;
  SysLogsSourceCallback callback_;
  int num_pending_requests_;
  bool scrub_;
  base::WeakPtrFactory<DebugDaemonLogSource> weak_ptr_factory_{this};
};

}  // namespace system_logs

#endif  // CHROME_BROWSER_ASH_SYSTEM_LOGS_DEBUG_DAEMON_LOG_SOURCE_H_


text:
import React from 'react';

import strings from '../../strings';
import BuildTitle from './build-title';

export default React.createClass({
  displayName: 'ErrorBuildDetails',

  propTypes: {
    build: React.PropTypes.object.isRequired,
  },

  render: function() {
    const {build} = this.props;
    return (

        <BuildTitle project={build.project} branch={build.branch} buildNumber={build.build_number} size={2}/>

{strings('BUILD_ERRORED')}

{build.result.tasks}

    );
  },
});


text:
import * as Actions from './actions';
import * as ActionTypes from './action-types';
import {DASHBOARD_SAVE_SUCCESS_STATUS, DASHBOARD_SAVE_STARTED_STATUS, DASHBOARD_SAVE_ERROR_STATUS} from 'dashboard-app/config/status'
const initialState = {
  dashboardId: '',
  dashboardName: '',
  dashboardInEditMode: false,
  status: {},
  loader: false
};
export default (state = initialState, action) => {
  switch (action.type) {
    case ActionTypes.DASHBOARD_SAVE_STARTED:
      return Object.assign({}, state, {
        status: DASHBOARD_SAVE_STARTED_STATUS,
        loader: true
      })
    case ActionTypes.DASHBOARD_SAVE_COMPLETED:
      return Object.assign({}, state, {
        status: DASHBOARD_SAVE_SUCCESS_STATUS,
        loader: false
      })
    case ActionTypes.DASHBOARD_SAVE_REJECTED:
      return Object.assign({}, state, {
        status: DASHBOARD_SAVE_SUCCESS_STATUS,
        loader: false
      })
    case ActionTypes.UPDATE_DASHBOARD_MODEL:
      return Object.assign({}, state, {
        dashboardId: action.payload.dashboardId,
        dashboardName: action.payload.dashboardName,
        dashboardInEditMode: action.payload.dashboardInEditMode,
        status: {},
        loader: false
      })
    case ActionTypes.DASHBOARD_REMOVE_STARTED:
      return Object.assign({}, state)
    case ActionTypes.DASHBOARD_REMOVE_COMPLETED:
      return Object.assign({}, state)
    case ActionTypes.DASHBOARD_REMOVE_REJECTED:
      return Object.assign({}, state)
    default:
      return state
  }
};


text:
layout: post
date: 2018-02-28
title: "Vera Wang Evelyn"
category: Vera Wang
tags: [Vera Wang]
---
### Vera Wang Evelyn
Just **$349.99**
###

Buy it: [https://www.readybrides.com/en/vera-wang/4118-vera-wang-evelyn.html](https://www.readybrides.com/en/vera-wang/4118-vera-wang-evelyn.html)


text:
package azkaban.project;

import azkaban.project.validator.ValidationReport;
import azkaban.project.validator.ValidationStatus;
import azkaban.spi.Dependency;
import azkaban.spi.DependencyFile;
import azkaban.spi.FileValidationStatus;
import azkaban.test.executions.ThinArchiveTestUtils;
import azkaban.utils.DependencyTransferException;
import azkaban.utils.DependencyTransferManager;
import azkaban.utils.ValidatorUtils;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.stubbing.Answer;
import org.skyscreamer.jsonassert.JSONAssert;

import static azkaban.test.executions.ThinArchiveTestUtils.*;
import static azkaban.utils.ThinArchiveUtils.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

public class ArchiveUnthinnerTest {
  @Rule
  public final TemporaryFolder TEMP_DIR = new TemporaryFolder();

  public static final String VALIDATION_KEY = "somerandomhash";
  public static final String DEPENDENCY_DOWNLOAD_BASE_URI = "https://example.com/deps/";

  private final Project project = new Project(107, "Test_Project");
  private File projectFolder;
  private File startupDependenciesFile;

  private Dependency depA;
  private Dependency depB;
  private File depAInArtifactory;
  private File depBInArtifactory;
  private File startupDepsInProject;
  private File depAInProject;
  private File depBInProject;

  private Set<Dependency> depSetAB;
  private Set<Dependency> depSetA;
  private Set<Dependency> depSetB;

  private ArchiveUnthinner archiveUnthinner;
  private ValidatorUtils validatorUtils;
  private JdbcDependencyManager jdbcDependencyManager;
  private DependencyTransferManager dependencyTransferManager;

  private Map<String, ValidationReport> defaultBaseReport;

  @Before
  public void setUp() throws Exception {
    this.validatorUtils = mock(ValidatorUtils.class);
    this.jdbcDependencyManager = mock(JdbcDependencyManager.class);
    this.dependencyTransferManager = mock(DependencyTransferManager.class);
    doReturn(true).when(this.dependencyTransferManager).isEnabled();

    this.archiveUnthinner = new ArchiveUnthinner(this.validatorUtils,
        this.jdbcDependencyManager, this.dependencyTransferManager);

    // Create test project directory
    // ../
    // ../lib/some-snapshot.jar
    // ../app-meta/startup-dependencies.json
    projectFolder = TEMP_DIR.newFolder("testproj");
    startupDependenciesFile = getStartupDependenciesFile(this.projectFolder);
    ThinArchiveTestUtils.makeSampleThinProjectDirAB(projectFolder);

    // Setup sample dependencies
    depA = ThinArchiveTestUtils.getDepA();
    depB = ThinArchiveTestUtils.getDepB();
    depAInArtifactory = TEMP_DIR.newFile(depA.getFileName());
    depBInArtifactory = TEMP_DIR.newFile(depB.getFileName());
    FileUtils.writeStringToFile(depAInArtifactory, ThinArchiveTestUtils.getDepAContent());
    FileUtils.writeStringToFile(depBInArtifactory, ThinArchiveTestUtils.getDepBContent());

    // Get objects for commonly referenced files in tests
    startupDepsInProject = getStartupDependenciesFile(projectFolder);
    depAInProject = new File(projectFolder, depA.getDestination() + File.separator + depA.getFileName());
    depBInProject = new File(projectFolder, depB.getDestination() + File.separator + depB.getFileName());

    // Get commonly used sets
    depSetA = ThinArchiveTestUtils.getDepSetA();
    depSetB = ThinArchiveTestUtils.getDepSetB();
    depSetAB = ThinArchiveTestUtils.getDepSetAB();

    // When downloadDependency() is called, write the content to the file as if it was downloaded
    // NOTE: This is only set up to work for depA and depB right now!!!
    doAnswer(invocation -> {
      ((Set<DependencyFile>) invocation.getArguments()[0]).forEach(destDep -> {
        String contentToWrite = destDep.equals(depA) ?
            ThinArchiveTestUtils.getDepAContent() :
            ThinArchiveTestUtils.getDepBContent();

        try {
          FileUtils.writeStringToFile(destDep.getFile(), contentToWrite);
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      });
      return null;
    }).when(this.dependencyTransferManager).downloadAllDependencies(any(Set.class));

    // When the unthinner attempts to get a validationKey for the project, return our sample one.
    when(this.validatorUtils.getCacheKey(eq(this.project), eq(this.projectFolder), any()))
        .thenReturn(VALIDATION_KEY);

    // Set up a default report map with a single empty report (the cached report)
    defaultBaseReport = new HashMap<>();
    defaultBaseReport.put(ArchiveUnthinner.CACHED_VALIDATOR_REPORT_NAME, new ValidationReport());
  }

  private Map<String, ValidationReport> runUnthinner() {
    return this.archiveUnthinner.validateThinProject(this.project, this.projectFolder,
        startupDependenciesFile, null);
  }

  @Test(expected = ProjectManagerException.class)
  public void testDisabled() {
    // Ensure that if the DependencyTransferManager is disabled, ArchiveUnthinner is also.
    DependencyTransferManager disabledTransferManager = mock(DependencyTransferManager.class);
    doReturn(false).when(disabledTransferManager).isEnabled();

    ArchiveUnthinner disabledUnthinner = new ArchiveUnthinner(this.validatorUtils,
        this.jdbcDependencyManager, disabledTransferManager);

    // Try to validate a project (this should fail!)
    disabledUnthinner.validateThinProject(this.project, this.projectFolder,
        startupDependenciesFile, null);
  }

  @Test
  public void testAllNew() throws Exception {
    // Indicate that the both dependencies are NEW, forcing them to be downloaded
    Map<Dependency, FileValidationStatus> sampleValidationStatuses = new HashMap();
    sampleValidationStatuses.put(depA, FileValidationStatus.NEW);
    sampleValidationStatuses.put(depB, FileValidationStatus.NEW);
    when(this.jdbcDependencyManager.getValidationStatuses(any(), eq(VALIDATION_KEY)))
        .thenReturn(sampleValidationStatuses);

    // When the unthinner attempts to validate the project, return an empty map (indicating that
    // no validators are loaded - and no validation modifications have been made)
    when(this.validatorUtils.validateProject(eq(this.project), eq(this.projectFolder), any()))
        .thenReturn(new HashMap<>());

    // Run the ArchiveUnthinner!
    Map<String, ValidationReport> result = runUnthinner();

    // Verify that ValidationReport is as expected (empty)
    assertEquals(result, defaultBaseReport);

    // Verify that both dependencies were added to DB as VALID
    Map<Dependency, FileValidationStatus> expectedStatuses = new HashMap();
    expectedStatuses.put(depA, FileValidationStatus.VALID);
    expectedStatuses.put(depB, FileValidationStatus.VALID);
    verify(this.jdbcDependencyManager).updateValidationStatuses(expectedStatuses, VALIDATION_KEY);

    // Verify that dependencies were removed from project /lib folder and only original snapshot jar remains
    assertEquals(1, new File(projectFolder, depA.getDestination()).listFiles().length);

    // Verify that the startup-dependencies.json file is NOT modified
    String finalJSON = FileUtils.readFileToString(startupDependenciesFile);
    JSONAssert.assertEquals(ThinArchiveTestUtils.getRawJSONDepsAB(), finalJSON, false);
  }

  @Test
  public void testAllNewUnrelatedModifyRemove() throws Exception {
    // Indicate that the both dependencies are NEW, forcing them to be downloaded
    Map<Dependency, FileValidationStatus> sampleValidationStatuses = new HashMap();
    sampleValidationStatuses.put(depA, FileValidationStatus.NEW);
    sampleValidationStatuses.put(depB, FileValidationStatus.NEW);
    when(this.jdbcDependencyManager.getValidationStatuses(any(), eq(VALIDATION_KEY)))
        .thenReturn(sampleValidationStatuses);

    // When the unthinner attempts to validate the project, return a report that indicates
    // the validator modified a non-dependency file and removed a non-dependency file
    File randomFileToRemove = new File(this.projectFolder, "imnotreal.txt");
    File randomFileToModify = new File(this.projectFolder, "lib/imnotreal.jar");
    Set<File> removedFiles = new HashSet();
    removedFiles.add(randomFileToRemove);
    Set<File> modifiedFiles = new HashSet();
    modifiedFiles.add(randomFileToModify);
    ValidationReport sampleReport = new ValidationReport();
    sampleReport.addRemovedFiles(removedFiles);
    sampleReport.addModifiedFiles(modifiedFiles);

    Map<String, ValidationReport> allReports = new HashMap<>();
    allReports.put("sample", sampleReport);
    when(this.validatorUtils.validateProject(eq(this.project), eq(this.projectFolder), any()))
        .thenReturn(allReports);

    // Run the ArchiveUnthinner!
    Map<String, ValidationReport> result = runUnthinner();

    // Verify that ValidationReport is as expected (has one empty cached report)
    defaultBaseReport.put("sample", sampleReport);
    assertEquals(result, defaultBaseReport);

    // Verify that both dependencies were added to DB as VALID
    Map<Dependency, FileValidationStatus> expectedStatuses = new HashMap();
    expectedStatuses.put(depA, FileValidationStatus.VALID);
    expectedStatuses.put(depB, FileValidationStatus.VALID);
    verify(this.jdbcDependencyManager).updateValidationStatuses(expectedStatuses, VALIDATION_KEY);

    // Verify that dependencies were removed from project /lib folder and only original snapshot jar remains
    assertEquals(1, new File(projectFolder, depA.getDestination()).listFiles().length);

    // Verify that the startup-dependencies.json file is NOT modified
    String finalJSON = FileUtils.readFileToString(startupDependenciesFile);
    JSONAssert.assertEquals(ThinArchiveTestUtils.getRawJSONDepsAB(), finalJSON, false);
  }

  @Test
  public void testCachedValid() throws Exception {
    // Indicate that the depA is cached VALID, but depB is NEW (forcing depB to be downloaded)
    Map<Dependency, FileValidationStatus> sampleValidationStatuses = new HashMap();
    sampleValidationStatuses.put(depA, FileValidationStatus.VALID);
    sampleValidationStatuses.put(depB, FileValidationStatus.NEW);
    when(this.jdbcDependencyManager.getValidationStatuses(any(), eq(VALIDATION_KEY)))
        .thenReturn(sampleValidationStatuses);

    // When the unthinner attempts to validate the project, return an empty map (indicating that
    // no validators are loaded - and no validation modifications have been made)
    when(this.validatorUtils.validateProject(eq(this.project), eq(this.projectFolder), any()))
        .thenReturn(new HashMap<>());

    // Run the ArchiveUnthinner!
    Map<String, ValidationReport> result = runUnthinner();

    // Verify that ValidationReport is as expected (has one empty cached report)
    assertEquals(result, defaultBaseReport);

    // Verify that ONLY depB was added to DB as VALID
    Map<Dependency, FileValidationStatus> expectedStatuses = new HashMap();
    expectedStatuses.put(depB, FileValidationStatus.VALID);
    verify(this.jdbcDependencyManager).updateValidationStatuses(expectedStatuses, VALIDATION_KEY);

    // Verify that no dependencies were added to project /lib folder and only original snapshot jar remains
    assertEquals(1, new File(projectFolder, depA.getDestination()).listFiles().length);

    // Verify that the startup-dependencies.json file is NOT modified
    String finalJSON = FileUtils.readFileToString(startupDependenciesFile);
    JSONAssert.assertEquals(ThinArchiveTestUtils.getRawJSONDepsAB(), finalJSON, false);
  }

  @Test
  public void testCachedRemoved() throws Exception {
    // Indicate that depA is cached REMOVED, but depB is NEW (forcing depB to be downloaded)
    Map<Dependency, FileValidationStatus> sampleValidationStatuses = new HashMap();
    sampleValidationStatuses.put(depA, FileValidationStatus.REMOVED);
    sampleValidationStatuses.put(depB, FileValidationStatus.NEW);
    when(this.jdbcDependencyManager.getValidationStatuses(any(), eq(VALIDATION_KEY)))
        .thenReturn(sampleValidationStatuses);

    // When the unthinner attempts to validate the project, return an empty map (indicating that
    // no validators are loaded - and no validation modifications have been made)
    when(this.validatorUtils.validateProject(eq(this.project), eq(this.projectFolder), any()))
        .thenReturn(new HashMap<>());

    // Run the ArchiveUnthinner!
    Map<String, ValidationReport> result = runUnthinner();

    // Verify that ValidationReport indicates the correct modified file (startup dependencies json)
    // and one warning for the cached removed file
    Set<File> modifiedFiles = new HashSet();
    modifiedFiles.add(startupDepsInProject);
    assertEquals(1, result.get(ArchiveUnthinner.CACHED_VALIDATOR_REPORT_NAME).getWarningMsgs().size());
    assertEquals(modifiedFiles, result.get(ArchiveUnthinner.CACHED_VALIDATOR_REPORT_NAME).getModifiedFiles());

    // Verify that ONLY depB was added to DB as VALID
    Map<Dependency, FileValidationStatus> expectedStatuses = new HashMap();
    expectedStatuses.put(depB, FileValidationStatus.VALID);
    verify(this.jdbcDependencyManager).updateValidationStatuses(expectedStatuses, VALIDATION_KEY);

    // Verify that no dependencies were added to project /lib folder and only original snapshot jar remains
    assertEquals(1, new File(projectFolder, depA.getDestination()).listFiles().length);

    // Verify that the startup-dependencies.json file now contains ONLY depB
    String finalJSON = FileUtils.readFileToString(startupDependenciesFile);
    JSONAssert.assertEquals(ThinArchiveTestUtils.getRawJSONDepB(), finalJSON, false);
  }

  @Test
  public void testValidatorDeleteFile() throws Exception {
    // Indicate that the both dependencies are NEW, forcing them to be downloaded
    Map<Dependency, FileValidationStatus> sampleValidationStatuses = new HashMap();
    sampleValidationStatuses.put(depA, FileValidationStatus.NEW);
    sampleValidationStatuses.put(depB, FileValidationStatus.NEW);
    when(this.jdbcDependencyManager.getValidationStatuses(any(), eq(VALIDATION_KEY)))
        .thenReturn(sampleValidationStatuses);

    // When the unthinner attempts to validate the project, return a report indicating that the depA jar
    // was removed.
    Set<File> removedFiles = new HashSet();
    removedFiles.add(depAInProject);

    doAnswer((Answer<Map>) invocation -> {
      depAInProject.delete();

      ValidationReport sampleReport = new ValidationReport();
      sampleReport.addRemovedFiles(removedFiles);

      Map<String, ValidationReport> allReports = new HashMap<>();
      allReports.put("sample", sampleReport);

      return allReports;
    }).when(this.validatorUtils).validateProject(eq(this.project), eq(this.projectFolder), any());

    // Run the ArchiveUnthinner!
    Map<String, ValidationReport> result = runUnthinner();

    // Verify that ValidationReport indicates the correct removed file (an no modified files).
    assertEquals(removedFiles, result.get("sample").getRemovedFiles());
    assertEquals(0, result.get("sample").getModifiedFiles().size());

    // Verify that depA was added to DB as REMOVED and depB was added as VALID
    Map<Dependency, FileValidationStatus> expectedStatuses = new HashMap();
    expectedStatuses.put(depA, FileValidationStatus.REMOVED);
    expectedStatuses.put(depB, FileValidationStatus.VALID);
    verify(this.jdbcDependencyManager).updateValidationStatuses(expectedStatuses, VALIDATION_KEY);

    // Verify that no dependencies were added to project /lib folder and only original snapshot jar remains
    assertEquals(1, new File(projectFolder, depA.getDestination()).listFiles().length);

    // Verify that the startup-dependencies.json file now contains ONLY depB
    String finalJSON = FileUtils.readFileToString(startupDependenciesFile);
    JSONAssert.assertEquals(ThinArchiveTestUtils.getRawJSONDepB(), finalJSON, false);
  }

  @Test
  public void testValidatorModifyFile() throws Exception {
    // Indicate that the both dependencies are NEW, forcing them to be downloaded
    Map<Dependency, FileValidationStatus> sampleValidationStatuses = new HashMap();
    sampleValidationStatuses.put(depA, FileValidationStatus.NEW);
    sampleValidationStatuses.put(depB, FileValidationStatus.NEW);
    when(this.jdbcDependencyManager.getValidationStatuses(any(), eq(VALIDATION_KEY)))
        .thenReturn(sampleValidationStatuses);

    // When the unthinner attempts to validate the project, return a report indicating that the depA jar
    // was modified.
    Set<File> modifiedFiles = new HashSet();
    modifiedFiles.add(depAInProject);

    doAnswer((Answer<Map>) invocation -> {
      ValidationReport sampleReport = new ValidationReport();
      sampleReport.addModifiedFiles(modifiedFiles);

      Map<String, ValidationReport> allReports = new HashMap<>();
      allReports.put("sample", sampleReport);

      return allReports;
    }).when(this.validatorUtils).validateProject(eq(this.project), eq(this.projectFolder), any());

    // Run the ArchiveUnthinner!
    Map<String, ValidationReport> result = runUnthinner();

    // Verify that ValidationReport indicates the correct modified file (and no removed files).
    assertEquals(modifiedFiles, result.get("sample").getModifiedFiles());
    assertEquals(0, result.get("sample").getRemovedFiles().size());

    // Verify that ONLY depB was added to DB as VALID
    Map<Dependency, FileValidationStatus> expectedStatuses = new HashMap();
    expectedStatuses.put(depB, FileValidationStatus.VALID);
    verify(this.jdbcDependencyManager).updateValidationStatuses(expectedStatuses, VALIDATION_KEY);

    // Verify that depA remains in the projectFolder (total of two jars)
    assertEquals(2, new File(projectFolder, depA.getDestination()).listFiles().length);
    assertTrue(depAInProject.exists());

    // Verify that the startup-dependencies.json file now contains ONLY depB
    String finalJSON = FileUtils.readFileToString(startupDependenciesFile);
    JSONAssert.assertEquals(ThinArchiveTestUtils.getRawJSONDepB(), finalJSON, false);
  }

  @Test(expected = ProjectManagerException.class)
  public void testErrorDownload() throws Exception {
    // Indicate that the both dependencies are NEW, forcing them to be downloaded
    Map<Dependency, FileValidationStatus> sampleValidationStatuses = new HashMap();
    sampleValidationStatuses.put(depA, FileValidationStatus.NEW);
    sampleValidationStatuses.put(depB, FileValidationStatus.NEW);
    when(this.jdbcDependencyManager.getValidationStatuses(any(), eq(VALIDATION_KEY)))
        .thenReturn(sampleValidationStatuses);

    // Remove the default mock for download handling
    reset(this.dependencyTransferManager);

    // When we attempt to download the dependencies, throw an error
    doThrow(new DependencyTransferException())
        .when(this.dependencyTransferManager).downloadAllDependencies(depSetEq(depSetAB));

    // Run the ArchiveUnthinner!
    runUnthinner();
  }

  @Test
  public void testReportWithError() throws Exception {
    // Indicate that the both dependencies are NEW, forcing them to be downloaded
    Map<Dependency, FileValidationStatus> sampleValidationStatuses = new HashMap();
    sampleValidationStatuses.put(depA, FileValidationStatus.NEW);
    sampleValidationStatuses.put(depB, FileValidationStatus.NEW);
    when(this.jdbcDependencyManager.getValidationStatuses(any(), eq(VALIDATION_KEY)))
        .thenReturn(sampleValidationStatuses);

    // When the unthinner attempts to validate the project, return a report with ValidationStatus.ERROR
    doAnswer((Answer<Map>) invocation -> {
      String someErrorMsg = "Big problem!";
      Set<String> errMsgs = new HashSet();
      errMsgs.add(someErrorMsg);

      ValidationReport sampleReport = new ValidationReport();
      sampleReport.addErrorMsgs(errMsgs);

      Map<String, ValidationReport> allReports = new HashMap<>();
      allReports.put("sample", sampleReport);

      return allReports;
    }).when(this.validatorUtils).validateProject(eq(this.project), eq(this.projectFolder), any());

    // Run the ArchiveUnthinner!
    Map<String, ValidationReport> result = runUnthinner();

    // Verify that ValidationReport has an ERROR status.
    assertEquals(ValidationStatus.ERROR, result.get("sample").getStatus());

    // Verify that nothing was updated in DB
    verify(this.jdbcDependencyManager, never()).updateValidationStatuses(any(), any());
  }
}


text:
<?php

namespace Colibri\Core;

/**
 * Class ORMEvents
 * @package Colibri\Core
 */
final class ORMEvents
{

    /**
     * Event occurs before repository execute search query
     */
    const beforeFindExecute = 'beforeFindExecute';

    /**
     * Event occurs after repository execute search query
     */
    const afterFindExecute = 'afterFindExecute';

    /**
     * Event occurs before repository trying to persist entity
     */
    const beforePersist = 'beforePersist';

    /**
     * Event occurs when repository successfully persist entity
     */
    const afterPersist = 'afterPersist';

    /**
     * Event occurs before repository trying to delete entity
     */
    const beforeRemove = 'beforeRemove';

    /**
     * Event occurs before repository trying to delete entity
     */
    const afterRemove = 'afterRemove';

    /**
     * Event occurs after metadata for entity was loaded.
     * Called one time because then its cached
     */
    const onMetadataLoad = 'onMetadataLoad';

    /**
     * Event occurs after new entity was created and hydrated
     */
    const onEntityLoad = 'onEntityLoad';

}


text:
/* $Id$ $Revision$ */
/* vim:set shiftwidth=4 ts=8: */

/*************************************************************************
 * Copyright (c) 2011 AT&T Intellectual Property
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors: See CVS logs. Details at http://www.graphviz.org/
 *************************************************************************/

#ifndef VISIBILITY_H
#define VISIBILITY_H

#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
#include "vispath.h"
#include "pathutil.h"

#ifdef __cplusplus
extern "C" {
#endif

    typedef COORD **array2;

#define	OBSCURED	0.0
#define EQ(p,q)		((p.x == q.x) && (p.y == q.y))
#define NEQ(p,q)	(!EQ(p,q))
#define NIL(p)		((p)0)
#define	CW			0
#define	CCW			1

    struct vconfig_s {
	int Npoly;
	int N;			/* number of points in walk of barriers */
	Ppoint_t *P;		/* barrier points */
	int *start;
	int *next;
	int *prev;

	/* this is computed from the above */
	array2 vis;
    };
#ifdef WIN32
#ifndef PATHPLAN_EXPORTS
#define extern __declspec(dllimport)
#endif
#endif
/*end visual studio*/

	extern COORD *ptVis(vconfig_t *, int, Ppoint_t);
    extern int directVis(Ppoint_t, int, Ppoint_t, int, vconfig_t *);
    extern void visibility(vconfig_t *);
    extern int *makePath(Ppoint_t p, int pp, COORD * pvis,
			 Ppoint_t q, int qp, COORD * qvis,
			 vconfig_t * conf);

#undef extern

#ifdef __cplusplus
}
#endif
#endif


text:
include(CGAL_Macros)

if ( NOT CGAL_TAUCS_FOUND )

  #
  # Find out TAUCS name for the current platform.
  # This code is a translation of TAUCS "configure" script.
  #

  # The first task is to figure out CMAKE_SYSTEM_NAME
  # (on unix this is uname -s, for windows it is Windows).
  #message("DEBUG: CMAKE_SYSTEM_NAME = ${CMAKE_SYSTEM_NAME}")
  #message("DEBUG: CMAKE_SYSTEM_PROCESSOR = ${CMAKE_SYSTEM_PROCESSOR}")
  set( CGAL_TAUCS_PLATFORM "${CMAKE_SYSTEM_NAME}" )

  # Convert to lower case
  STRING(TOLOWER "${CGAL_TAUCS_PLATFORM}" CGAL_TAUCS_PLATFORM)

  # Sometimes uname returns a value that is
  # inconsistent with the way CGAL_TAUCS_PLATFORM is set. For example, on
  # Solaris, CGAL_TAUCS_PLATFORM=solaris but uname returns SunOS.
  if ( ${CGAL_TAUCS_PLATFORM} STREQUAL "sunos" )
    set( CGAL_TAUCS_PLATFORM "solaris" )
  endif()
  if ( ${CGAL_TAUCS_PLATFORM} STREQUAL "windows" )
    set( CGAL_TAUCS_PLATFORM "win32" )
  endif()

  # LS 2007: added "darwin_intel" for Intel Macs.
  # "darwin" = original Darwin platform = PowerPC architecture.
  if ( ${CGAL_TAUCS_PLATFORM} STREQUAL "darwin" )
    # CMAKE_SYSTEM_PROCESSOR=uname -p
    if ( ${CMAKE_SYSTEM_PROCESSOR} STREQUAL "i386" )
      set( CGAL_TAUCS_PLATFORM "darwin_intel" )
    endif()
  endif()

  # LS 2007: append "64" if 64 bits processor (tested on Linux only)

  if ( ${CGAL_TAUCS_PLATFORM} STREQUAL "linux" )
    # CMAKE_SYSTEM_PROCESSOR=uname -p
    if ( ${CMAKE_SYSTEM_PROCESSOR} MATCHES ".*64.*" )
      set( CGAL_TAUCS_PLATFORM "${CGAL_TAUCS_PLATFORM}64" )
    endif()
  endif()

  #message("DEBUG: CGAL_TAUCS_PLATFORM = ${CGAL_TAUCS_PLATFORM}")

  #
  # Search for TAUCS folder.
  #

  #message("DEBUG: CGAL_SOURCE_DIRECTORY = ${CGAL_SOURCE_DIRECTORY}")

  # VC++ uses auto-link, thus we search for a folder containing the output of
  # build_taucs_win32_for_CGAL.bat/build_taucs_win64_for_CGAL.bat,
  # ie TAUCS libraries compiled for all Windows runtimes.
  if ( MSVC )

    # Check $CGAL_TAUCS_DIR environment variable
    fetch_env_var(CGAL_TAUCS_DIR)
    #message("DEBUG: CGAL_TAUCS_DIR = ${CGAL_TAUCS_DIR}")
    if (NOT "${CGAL_TAUCS_DIR}" STREQUAL "" AND EXISTS ${CGAL_TAUCS_DIR})

      set( CGAL_TAUCS_INCLUDE_DIR   "${CGAL_TAUCS_DIR}/include")
      set( CGAL_TAUCS_LIBRARIES_DIR "${CGAL_TAUCS_DIR}/lib"    )
      set( CGAL_TAUCS_FOUND TRUE )

    # Else, search for TAUCS in CGAL "auxiliary" folder
    elseif ( EXISTS "${CGAL_SOURCE_DIRECTORY}/auxiliary/taucs" )

      set( CGAL_TAUCS_INCLUDE_DIR   "${CGAL_SOURCE_DIRECTORY}/auxiliary/taucs/include")
      set( CGAL_TAUCS_LIBRARIES_DIR "${CGAL_SOURCE_DIRECTORY}/auxiliary/taucs/lib"    )
      set( CGAL_TAUCS_FOUND TRUE )

    endif()

  # On Unix, search for TAUCS "taucs_full" folder
  else ( MSVC )

    # Check $CGAL_TAUCS_DIR environment variable
    fetch_env_var(CGAL_TAUCS_DIR)
    #message("DEBUG: CGAL_TAUCS_DIR = ${CGAL_TAUCS_DIR}")
    if (NOT "${CGAL_TAUCS_DIR}" STREQUAL "" AND EXISTS ${CGAL_TAUCS_DIR})

        set( CGAL_TAUCS_INCLUDE_DIR   "${CGAL_TAUCS_DIR}/build/${CGAL_TAUCS_PLATFORM}"
                                      "${CGAL_TAUCS_DIR}/src" )
        set( CGAL_TAUCS_LIBRARIES_DIR "${CGAL_TAUCS_DIR}/external/lib/${CGAL_TAUCS_PLATFORM}"
                                      "${CGAL_TAUCS_DIR}/lib/${CGAL_TAUCS_PLATFORM}" )
        set( CGAL_TAUCS_FOUND TRUE )

    endif()

  endif ( MSVC )

  # Add variables to cache
  set( CGAL_TAUCS_DIR   "${CGAL_TAUCS_DIR}"
                        CACHE PATH "Directory containing BLAS, LAPACK and TAUCS" )

  #message("DEBUG: CGAL_TAUCS_INCLUDE_DIR = ${CGAL_TAUCS_INCLUDE_DIR}")
  #message("DEBUG: CGAL_TAUCS_LIBRARIES_DIR = ${CGAL_TAUCS_LIBRARIES_DIR}")
  #message("DEBUG: CGAL_TAUCS_FOUND = ${CGAL_TAUCS_FOUND}")

endif ( NOT CGAL_TAUCS_FOUND )


text:
find_package(Proton 0.5)

set (amqp_default ${amqp_force})
set (maximum_version 0.7)
if (Proton_FOUND)
    if (Proton_VERSION GREATER ${maximum_version})
        message(WARNING "Qpid proton ${Proton_VERSION} is not a tested version and might not be compatible, ${maximum_version} is highest tested; build may not work")
    endif (Proton_VERSION GREATER ${maximum_version})
    message(STATUS "Qpid proton found, amqp 1.0 support enabled")
    set (amqp_default ON)
    #remove when 0.5 no longer supported
    if (NOT Proton_VERSION EQUAL 0.5)
        set (HAVE_PROTON_TRACER 1)
    endif (NOT Proton_VERSION EQUAL 0.5)
else ()
    message(STATUS "Qpid proton not found, amqp 1.0 support not enabled")
endif ()

option(BUILD_AMQP "Build with support for AMQP 1.0" ${amqp_default})
if (BUILD_AMQP)

    if (NOT Proton_FOUND)
      message(FATAL_ERROR "Qpid proton not found, required for amqp 1.0 support")
    endif ()

    set (amqp_SOURCES
         qpid/broker/amqp/Authorise.h
         qpid/broker/amqp/Authorise.cpp
         qpid/broker/amqp/BrokerContext.h
         qpid/broker/amqp/BrokerContext.cpp
         qpid/broker/amqp/Connection.h
         qpid/broker/amqp/Connection.cpp
         qpid/broker/amqp/DataReader.h
         qpid/broker/amqp/DataReader.cpp
         qpid/broker/amqp/Domain.h
         qpid/broker/amqp/Domain.cpp
         qpid/broker/amqp/Exception.h
         qpid/broker/amqp/Exception.cpp
         qpid/broker/amqp/Filter.h
         qpid/broker/amqp/Filter.cpp
         qpid/broker/amqp/Header.h
         qpid/broker/amqp/Header.cpp
         qpid/broker/amqp/Incoming.h
         qpid/broker/amqp/Incoming.cpp
         qpid/broker/amqp/Interconnect.h
         qpid/broker/amqp/Interconnect.cpp
         qpid/broker/amqp/Interconnects.h
         qpid/broker/amqp/Interconnects.cpp
         qpid/broker/amqp/ManagedConnection.h
         qpid/broker/amqp/ManagedConnection.cpp
         qpid/broker/amqp/ManagedSession.h
         qpid/broker/amqp/ManagedSession.cpp
         qpid/broker/amqp/ManagedIncomingLink.h
         qpid/broker/amqp/ManagedIncomingLink.cpp
         qpid/broker/amqp/ManagedOutgoingLink.h
         qpid/broker/amqp/ManagedOutgoingLink.cpp
         qpid/broker/amqp/Message.h
         qpid/broker/amqp/Message.cpp
         qpid/broker/amqp/NodePolicy.h
         qpid/broker/amqp/NodePolicy.cpp
         qpid/broker/amqp/NodeProperties.h
         qpid/broker/amqp/NodeProperties.cpp
         qpid/broker/amqp/Outgoing.h
         qpid/broker/amqp/Outgoing.cpp
         qpid/broker/amqp/ProtocolPlugin.cpp
         qpid/broker/amqp/Relay.h
         qpid/broker/amqp/Relay.cpp
         qpid/broker/amqp/Sasl.h
         qpid/broker/amqp/Sasl.cpp
         qpid/broker/amqp/SaslClient.h
         qpid/broker/amqp/SaslClient.cpp
         qpid/broker/amqp/Session.h
         qpid/broker/amqp/Session.cpp
         qpid/broker/amqp/Topic.h
         qpid/broker/amqp/Topic.cpp
         qpid/broker/amqp/Translation.h
         qpid/broker/amqp/Translation.cpp
        )

    include_directories(${Proton_INCLUDE_DIRS})

    add_library (amqp MODULE ${amqp_SOURCES})
    target_link_libraries (amqp qpidtypes qpidbroker qpidcommon ${Proton_LIBRARIES} ${Boost_PROGRAM_OPTIONS_LIBRARY})
    set_target_properties (amqp PROPERTIES
                           PREFIX ""
                           LINK_FLAGS "${CATCH_UNDEFINED}"
                           COMPILE_DEFINITIONS _IN_QPID_BROKER)

    install (TARGETS amqp
             DESTINATION ${QPIDD_MODULE_DIR}
             COMPONENT ${QPID_COMPONENT_BROKER})

    set (amqpc_SOURCES
         qpid/messaging/amqp/AddressHelper.h
         qpid/messaging/amqp/AddressHelper.cpp
         qpid/messaging/amqp/ConnectionContext.h
         qpid/messaging/amqp/ConnectionContext.cpp
         qpid/messaging/amqp/ConnectionHandle.h
         qpid/messaging/amqp/ConnectionHandle.cpp
         qpid/messaging/amqp/DriverImpl.h
         qpid/messaging/amqp/DriverImpl.cpp
         qpid/messaging/amqp/ReceiverContext.h
         qpid/messaging/amqp/ReceiverContext.cpp
         qpid/messaging/amqp/ReceiverHandle.h
         qpid/messaging/amqp/ReceiverHandle.cpp
         qpid/messaging/amqp/Sasl.h
         qpid/messaging/amqp/Sasl.cpp
         qpid/messaging/amqp/SenderContext.h
         qpid/messaging/amqp/SenderContext.cpp
         qpid/messaging/amqp/SenderHandle.h
         qpid/messaging/amqp/SenderHandle.cpp
         qpid/messaging/amqp/SessionContext.h
         qpid/messaging/amqp/SessionContext.cpp
         qpid/messaging/amqp/SessionHandle.h
         qpid/messaging/amqp/SessionHandle.cpp
         qpid/messaging/amqp/TcpTransport.h
         qpid/messaging/amqp/TcpTransport.cpp
        )

    if (WIN32)
        list (APPEND amqp_SOURCES qpid/messaging/amqp/windows/SslTransport.cpp)
        list (APPEND amqpc_SOURCES qpid/messaging/amqp/windows/SslTransport.cpp)
    endif (WIN32)
else (BUILD_AMQP)
    # ensure that qpid build ignores proton
    UNSET( amqpc_SOURCES )
    UNSET( PROTON_LIBRARIES )
endif (BUILD_AMQP)


text:
random.c
-----------

@random.c
```c
#include "Python.h"
#ifdef MS_WINDOWS
#include <windows.h>
#else
#include <fcntl.h>
#endif
#ifdef Py_DEBUG
int _Py_HashSecret_Initialized = 0;
#else
static int _Py_HashSecret_Initialized = 0;
#endif
#ifdef MS_WINDOWS
typedef BOOL (WINAPI *CRYPTACQUIRECONTEXTA)(HCRYPTPROV *phProv,\
              LPCSTR pszContainer, LPCSTR pszProvider, DWORD dwProvType,\
              DWORD dwFlags );
typedef BOOL (WINAPI *CRYPTGENRANDOM)(HCRYPTPROV hProv, DWORD dwLen,\
              BYTE *pbBuffer );
static CRYPTGENRANDOM pCryptGenRandom = NULL;
```

>system will release it when the process terminates.

```c
static HCRYPTPROV hCryptProv = 0;
static int
win32_urandom_init(int raise)
{
    HINSTANCE hAdvAPI32 = NULL;
    CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL;
```

Obtain handle to the DLL containing CryptoAPI. This should not fail.

```c
    hAdvAPI32 = GetModuleHandle("advapi32.dll");
    if(hAdvAPI32 == NULL)
        goto error;
```

>versions of Win95.

```c
    pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress(
                               hAdvAPI32, "CryptAcquireContextA");
    if (pCryptAcquireContext == NULL)
        goto error;
    pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress(hAdvAPI32,
                                                     "CryptGenRandom");
    if (pCryptGenRandom == NULL)
        goto error;
```

Acquire context

```c
    if (! pCryptAcquireContext(&hCryptProv, NULL, NULL,
                               PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
        goto error;
    return 0;
error:
    if (raise)
        PyErr_SetFromWindowsErr(0);
    else
        Py_FatalError("Failed to initialize Windows random API (CryptoGen)");
    return -1;
}
```

>API. Return 0 on success, or -1 on error.

```c
static int
win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise)
{
    Py_ssize_t chunk;
    if (hCryptProv == 0)
    {
        if (win32_urandom_init(raise) == -1)
            return -1;
    }
    while (size > 0)
    {
        chunk = size > INT_MAX ? INT_MAX : size;
        if (!pCryptGenRandom(hCryptProv, chunk, buffer))
        {
```

CryptGenRandom() failed

```c
            if (raise)
                PyErr_SetFromWindowsErr(0);
            else
                Py_FatalError("Failed to initialized the randomized hash "
                        "secret using CryptoGen)");
            return -1;
        }
        buffer += chunk;
        size -= chunk;
    }
    return 0;
}
#endif /* MS_WINDOWS */
#ifdef __VMS
```

Use openssl random routine

```c
#include <openssl/rand.h>
static int
vms_urandom(unsigned char *buffer, Py_ssize_t size, int raise)
{
    if (RAND_pseudo_bytes(buffer, size) < 0) {
        if (raise) {
            PyErr_Format(PyExc_ValueError,
                         "RAND_pseudo_bytes");
        } else {
            Py_FatalError("Failed to initialize the randomized hash "
                          "secret using RAND_pseudo_bytes");
        }
        return -1;
    }
    return 0;
}
#endif /* __VMS */
#if !defined(MS_WINDOWS) && !defined(__VMS)
static struct {
    int fd;
    dev_t st_dev;
    ino_t st_ino;
} urandom_cache = { -1 };
```

>Call Py_FatalError() on error.

```c
static void
dev_urandom_noraise(unsigned char *buffer, Py_ssize_t size)
{
    int fd;
    Py_ssize_t n;
    assert (0 < size);
    fd = open("/dev/urandom", O_RDONLY);
    if (fd < 0)
        Py_FatalError("Failed to open /dev/urandom");
    while (0 < size)
    {
        do {
            n = read(fd, buffer, (size_t)size);
        } while (n < 0 && errno == EINTR);
        if (n <= 0)
        {
```

stop on error or if read(size) returned 0

```c
            Py_FatalError("Failed to read bytes from /dev/urandom");
            break;
        }
        buffer += n;
        size -= (Py_ssize_t)n;
    }
    close(fd);
}
```

>Return 0 on success, raise an exception and return -1 on error.

```c
static int
dev_urandom_python(char *buffer, Py_ssize_t size)
{
    int fd;
    Py_ssize_t n;
    struct stat st;
    if (size <= 0)
        return 0;
    if (urandom_cache.fd >= 0) {
```

Does the fd point to the same thing as before? (issue #21207)

```c
        if (fstat(urandom_cache.fd, &st)
            || st.st_dev != urandom_cache.st_dev
            || st.st_ino != urandom_cache.st_ino) {
```

since it probably points to something important for some
>third-party code).

```c
            urandom_cache.fd = -1;
        }
    }
    if (urandom_cache.fd >= 0)
        fd = urandom_cache.fd;
    else {
        Py_BEGIN_ALLOW_THREADS
        fd = open("/dev/urandom", O_RDONLY);
        Py_END_ALLOW_THREADS
        if (fd < 0)
        {
            if (errno == ENOENT || errno == ENXIO ||
                errno == ENODEV || errno == EACCES)
                PyErr_SetString(PyExc_NotImplementedError,
                                "/dev/urandom (or equivalent) not found");
            else
                PyErr_SetFromErrno(PyExc_OSError);
            return -1;
        }
        if (urandom_cache.fd >= 0) {
```

>not holding the GIL, keep it.

```c
            close(fd);
            fd = urandom_cache.fd;
        }
        else {
            if (fstat(fd, &st)) {
                PyErr_SetFromErrno(PyExc_OSError);
                close(fd);
                return -1;
            }
            else {
                urandom_cache.fd = fd;
                urandom_cache.st_dev = st.st_dev;
                urandom_cache.st_ino = st.st_ino;
            }
        }
    }
    Py_BEGIN_ALLOW_THREADS
    do {
        do {
            n = read(fd, buffer, (size_t)size);
        } while (n < 0 && errno == EINTR);
        if (n <= 0)
            break;
        buffer += n;
        size -= (Py_ssize_t)n;
    } while (0 < size);
    Py_END_ALLOW_THREADS
    if (n <= 0)
    {
```

stop on error or if read(size) returned 0

```c
        if (n < 0)
            PyErr_SetFromErrno(PyExc_OSError);
        else
            PyErr_Format(PyExc_RuntimeError,
                         "Failed to read %zi bytes from /dev/urandom",
                         size);
        return -1;
    }
    return 0;
}
static void
dev_urandom_close(void)
{
    if (urandom_cache.fd >= 0) {
        close(urandom_cache.fd);
        urandom_cache.fd = -1;
    }
}
#endif /* !defined(MS_WINDOWS) && !defined(__VMS) */
```

generator (LCG):
x(n+1) = (x(n) * 214013 + 2531011) % 2^32
>Use bits 23..16 of x(n) to generate a byte.

```c
static void
lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)
{
    size_t index;
    unsigned int x;
    x = x0;
    for (index=0; index < size; index++) {
        x *= 214013;
        x += 2531011;
```

modulo 2 ^ (8 * sizeof(int))

```c
        buffer[index] = (x >> 16) & 0xff;
    }
}
```

number generator (RNG). It is suitable for for most cryptographic purposes
except long living private keys for asymmetric encryption.
>Return 0 on success, raise an exception and return -1 on error.

```c
int
_PyOS_URandom(void *buffer, Py_ssize_t size)
{
    if (size < 0) {
        PyErr_Format(PyExc_ValueError,
                     "negative argument not allowed");
        return -1;
    }
    if (size == 0)
        return 0;
#ifdef MS_WINDOWS
    return win32_urandom((unsigned char *)buffer, size, 1);
#else
# ifdef __VMS
    return vms_urandom((unsigned char *)buffer, size, 1);
# else
    return dev_urandom_python((char*)buffer, size);
# endif
#endif
}
void
_PyRandom_Init(void)
{
    char *env;
    void *secret = &_Py_HashSecret;
    Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);
    if (_Py_HashSecret_Initialized)
        return;
    _Py_HashSecret_Initialized = 1;
```

By default, hash randomization is disabled, and only
enabled if PYTHONHASHSEED is set to non-empty or if
"-R" is provided at the command line:

```c
    if (!Py_HashRandomizationFlag) {
```

Disable the randomized hash:

```c
        memset(secret, 0, secret_size);
        return;
    }
```

Hash randomization is enabled.  Generate a per-process secret,
using PYTHONHASHSEED if provided.

```c
    env = Py_GETENV("PYTHONHASHSEED");
    if (env && *env != '\0' && strcmp(env, "random") != 0) {
        char *endptr = env;
        unsigned long seed;
        seed = strtoul(env, &endptr, 10);
        if (*endptr != '\0'
            || seed > 4294967295UL
            || (errno == ERANGE && seed == ULONG_MAX))
        {
            Py_FatalError("PYTHONHASHSEED must be \"random\" or an integer "
                          "in range [0; 4294967295]");
        }
        if (seed == 0) {
```

disable the randomized hash

```c
            memset(secret, 0, secret_size);
        }
        else {
            lcg_urandom(seed, (unsigned char*)secret, secret_size);
        }
    }
    else {
#ifdef MS_WINDOWS
        (void)win32_urandom((unsigned char *)secret, secret_size, 0);
#else /* #ifdef MS_WINDOWS */
# ifdef __VMS
        vms_urandom((unsigned char *)secret, secret_size, 0);
# else
        dev_urandom_noraise((unsigned char*)secret, secret_size);
# endif
#endif
    }
}
void
_PyRandom_Fini(void)
{
#ifdef MS_WINDOWS
    if (hCryptProv) {
        CryptReleaseContext(hCryptProv, 0);
        hCryptProv = 0;
    }
#else
    dev_urandom_close();
#endif
}
```
___