text:
<?php
/**
 * Sqlite-specific updater.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Deployment
 */

/**
 * Class for handling updates to Sqlite databases.
 *
 * @ingroup Deployment
 * @since 1.17
 */
class SqliteUpdater extends DatabaseUpdater {

	protected function getCoreUpdateList() {
		return array(
			// 1.14
			array( 'addField', 'site_stats', 'ss_active_users', 'patch-ss_active_users.sql' ),
			array( 'doActiveUsersInit' ),
			array( 'addField', 'ipblocks', 'ipb_allow_usertalk', 'patch-ipb_allow_usertalk.sql' ),
			array( 'sqliteInitialIndexes' ),

			// 1.15
			array( 'addTable', 'change_tag', 'patch-change_tag.sql' ),
			array( 'addTable', 'tag_summary', 'patch-tag_summary.sql' ),
			array( 'addTable', 'valid_tag', 'patch-valid_tag.sql' ),

			// 1.16
			array( 'addTable', 'user_properties', 'patch-user_properties.sql' ),
			array( 'addTable', 'log_search', 'patch-log_search.sql' ),
			array( 'addField', 'logging', 'log_user_text', 'patch-log_user_text.sql' ),
			# listed separately from the previous update because 1.16 was released without this update
			array( 'doLogUsertextPopulation' ),
			array( 'doLogSearchPopulation' ),
			array( 'addTable', 'l10n_cache', 'patch-l10n_cache.sql' ),
			array( 'addIndex', 'log_search', 'ls_field_val', 'patch-log_search-rename-index.sql' ),
			array( 'addIndex', 'change_tag', 'change_tag_rc_tag', 'patch-change_tag-indexes.sql' ),
			array( 'addField', 'redirect', 'rd_interwiki', 'patch-rd_interwiki.sql' ),
			array( 'doUpdateTranscacheField' ),
			array( 'sqliteSetupSearchindex' ),

			// 1.17
			array( 'addTable', 'iwlinks', 'patch-iwlinks.sql' ),
			array( 'addIndex', 'iwlinks', 'iwl_prefix_title_from', 'patch-rename-iwl_prefix.sql' ),
			array( 'addField', 'updatelog', 'ul_value', 'patch-ul_value.sql' ),
			array( 'addField', 'interwiki', 'iw_api', 'patch-iw_api_and_wikiid.sql' ),
			array( 'dropIndex', 'iwlinks', 'iwl_prefix', 'patch-kill-iwl_prefix.sql' ),
			array( 'addField', 'categorylinks', 'cl_collation', 'patch-categorylinks-better-collation.sql' ),
			array( 'doCollationUpdate' ),
			array( 'addTable', 'msg_resource', 'patch-msg_resource.sql' ),
			array( 'addTable', 'module_deps', 'patch-module_deps.sql' ),
			array( 'dropIndex', 'archive', 'ar_page_revid', 'patch-archive_kill_ar_page_revid.sql' ),
			array( 'addIndex', 'archive', 'ar_revid', 'patch-archive_ar_revid.sql' ),

			// 1.18
			array( 'addIndex', 'user', 'user_email', 'patch-user_email_index.sql' ),
			array( 'addTable', 'uploadstash', 'patch-uploadstash.sql' ),
			array( 'addTable', 'user_former_groups', 'patch-user_former_groups.sql' ),

			// 1.19
			array( 'addIndex', 'logging', 'type_action', 'patch-logging-type-action-index.sql' ),
			array( 'doMigrateUserOptions' ),
			array( 'dropField', 'user', 'user_options', 'patch-drop-user_options.sql' ),
			array( 'addField', 'revision', 'rev_sha1', 'patch-rev_sha1.sql' ),
			array( 'addField', 'archive', 'ar_sha1', 'patch-ar_sha1.sql' ),
			array( 'addIndex', 'page', 'page_redirect_namespace_len',
				'patch-page_redirect_namespace_len.sql' ),
			array( 'addField', 'uploadstash', 'us_chunk_inx', 'patch-uploadstash_chunk.sql' ),
			array( 'addfield', 'job', 'job_timestamp', 'patch-jobs-add-timestamp.sql' ),

			// 1.20
			array( 'addIndex', 'revision', 'page_user_timestamp', 'patch-revision-user-page-index.sql' ),
			array( 'addField', 'ipblocks', 'ipb_parent_block_id', 'patch-ipb-parent-block-id.sql' ),
			array( 'addIndex', 'ipblocks', 'ipb_parent_block_id', 'patch-ipb-parent-block-id-index.sql' ),
			array( 'dropField', 'category', 'cat_hidden', 'patch-cat_hidden.sql' ),

			// 1.21
			array( 'addField', 'revision', 'rev_content_format', 'patch-revision-rev_content_format.sql' ),
			array( 'addField', 'revision', 'rev_content_model', 'patch-revision-rev_content_model.sql' ),
			array( 'addField', 'archive', 'ar_content_format', 'patch-archive-ar_content_format.sql' ),
			array( 'addField', 'archive', 'ar_content_model', 'patch-archive-ar_content_model.sql' ),
			array( 'addField', 'page', 'page_content_model', 'patch-page-page_content_model.sql' ),
			array( 'dropField', 'site_stats', 'ss_admins', 'patch-drop-ss_admins.sql' ),
			array( 'dropField', 'recentchanges', 'rc_moved_to_title', 'patch-rc_moved.sql' ),
			array( 'addTable', 'sites', 'patch-sites.sql' ),
			array( 'addField', 'filearchive', 'fa_sha1', 'patch-fa_sha1.sql' ),
			array( 'addField', 'job', 'job_token', 'patch-job_token.sql' ),
			array( 'addField', 'job', 'job_attempts', 'patch-job_attempts.sql' ),
			array( 'doEnableProfiling' ),
			array( 'addField', 'uploadstash', 'us_props', 'patch-uploadstash-us_props.sql' ),
			array( 'modifyField', 'user_groups', 'ug_group', 'patch-ug_group-length-increase-255.sql' ),
			array( 'modifyField', 'user_former_groups', 'ufg_group',
				'patch-ufg_group-length-increase-255.sql' ),
			array( 'addIndex', 'page_props', 'pp_propname_page',
				'patch-page_props-propname-page-index.sql' ),
			array( 'addIndex', 'image', 'img_media_mime', 'patch-img_media_mime-index.sql' ),
			array( 'addIndex', 'iwlinks', 'iwl_prefix_from_title', 'patch-iwlinks-from-title-index.sql' ),
			array( 'addField', 'archive', 'ar_id', 'patch-archive-ar_id.sql' ),
			array( 'addField', 'externallinks', 'el_id', 'patch-externallinks-el_id.sql' ),
		);
	}

	protected function sqliteInitialIndexes() {
		// initial-indexes.sql fails if the indexes are already present,
		// so we perform a quick check if our database is newer.
		if ( $this->updateRowExists( 'initial_indexes' ) ||
			$this->db->indexExists( 'user', 'user_name', __METHOD__ )
		) {
			$this->output( "...have initial indexes\n" );

			return;
		}
		$this->applyPatch( 'initial-indexes.sql', false, "Adding initial indexes" );
	}

	protected function sqliteSetupSearchindex() {
		$module = DatabaseSqlite::getFulltextSearchModule();
		$fts3tTable = $this->updateRowExists( 'fts3' );
		if ( $fts3tTable && !$module ) {
			$this->applyPatch(
				'searchindex-no-fts.sql',
				false,
				'PHP is missing FTS3 support, downgrading tables'
			);
		} elseif ( !$fts3tTable && $module == 'FTS3' ) {
			$this->applyPatch( 'searchindex-fts3.sql', false, "Adding FTS3 search capabilities" );
		} else {
			$this->output( "...fulltext search table appears to be in order.\n" );
		}
	}

	protected function doEnableProfiling() {
		global $wgProfileToDatabase;
		if ( $wgProfileToDatabase === true && !$this->db->tableExists( 'profiling', __METHOD__ ) ) {
			$this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
		}
	}
}


text:
			<?php get_sidebar('javascript'); ?>

.plugin()

More info coming soon.

					<?php /*

.component()

Returns a cached instance of the jQuery object at the dom-ready state.

The $ symbol in jQuery-based JavaScript development is typically read as a cached instance of the global jQuery object. If all variables are wrapped in a manner so as to not pollute the global namespace, however, the dollar-sign variable will not be accessible. <?php echo SITENAME; ?> caches the jQuery object to be able to globally read it's properties and executes it's functions without instatiatng a new instance each time.

Markup

;(function(clique) {
    var $ = clique.$;
    // Any jQuery functions can now be executed using the `$` symbol
    // without fear of polluting the global namespace
    ...
})(Clique);

Example

;(function(clique) {
    var $ = clique.$;

    // Begin jQuery object manipulation
    $('#my-element').animate({
        'margin-top' : 30
    });
})(Clique);

					*/ ?>
				<?php get_microdata('author'); ?>

redpajama_set_name: RedPajamaGithub


text:
#ifndef SQLPP_UNION_FLAGS_H
#define SQLPP_UNION_FLAGS_H

#include <sqlpp11/type_traits.h>
#include <sqlpp11/detail/type_set.h>
#include <sqlpp11/interpret_tuple.h>
#include <tuple>

namespace sqlpp
{
  // standard select flags
  struct union_all_t
  {
    using _traits = make_traits<no_value_t, tag::is_union_flag>;
    using _nodes = detail::type_vector<>;
  };

  template <typename Context>
  struct serializer_t<Context, union_all_t>
  {
    using _serialize_check = consistent_t;

    static Context& _(const union_all_t&, Context& context)
    {
      context << "ALL";
      return context;
    }
  };

  struct union_distinct_t
  {
    using _traits = make_traits<no_value_t, tag::is_union_flag>;
    using _nodes = detail::type_vector<>;
  };

  template <typename Context>
  struct serializer_t<Context, union_distinct_t>
  {
    using _serialize_check = consistent_t;

    static Context& _(const union_distinct_t&, Context& context)
    {
      return context;
    }
  };
}

#endif


text:
{% extends "base.html" %}
{% load i18n %}
{% block title %}{% trans "Password Modification" %}{% endblock %}

{% block extra_style %}
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/bootstrap.popover.min.css" />
{% endblock %}

{% block main_content %}

{% trans "Password Modification" %}

    <form action="" method="post" class="con">{% csrf_token %}
        {% if force_passwd_change %}

 {% trans "Please update your password before continue." %}

        {% endif %}
    {% trans "Current Password" %}

    {{ form.old_password }}
     {{ form.old_password.errors }}
    {% trans "New Password" %}

    {{ form.new_password1 }}
    {{ form.new_password1.errors }}

    {% trans "Confirm Password" %}

    {{ form.new_password2 }}
    {{ form.new_password2.errors }}

    <input type="submit" value="{% trans "Submit" %}" class="submit" />
  </form>

{% endblock %}

{% block extra_script %}

{% endblock %}


text:
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Text;
using Simple.Data.Extensions;

namespace Simple.Data.Commands
{
    using System.Collections;

    internal class UpdateCommand : ICommand
    {
        public bool IsCommandFor(string method)
        {
            return method.Equals("update", StringComparison.InvariantCultureIgnoreCase);
        }

        public object Execute(DataStrategy dataStrategy, DynamicTable table, InvokeMemberBinder binder, object[] args)
        {
            if (args.Length == 0 || args.Length > 2) throw new ArgumentException("Incorrect number of arguments to Update method.");

            if (args.Length == 1)
            {
                return UpdateUsingKeys(dataStrategy, table, args);
            }

            return UpdateUsingOriginalValues(dataStrategy, table, args);
        }

        private static object UpdateUsingOriginalValues(DataStrategy dataStrategy, DynamicTable table, object[] args)
        {
            var newValues = ObjectToDictionary(args[0]);
            var newValuesList = newValues as IList<IDictionary<string, object>>;
            if (newValuesList != null)
            {
                var originalValuesList = ObjectToDictionary(args[1]) as IList<IDictionary<string, object>>;
                if (originalValuesList == null) throw new InvalidOperationException("Parameter type mismatch; both parameters to Update should be same type.");
                return dataStrategy.Run.UpdateMany(table.GetQualifiedName(), newValuesList, originalValuesList);
            }

            var newValuesDict = newValues as IDictionary<string, object>;
            var originalValuesDict = ObjectToDictionary(args[1]) as IDictionary<string, object>;
            if (originalValuesDict == null) throw new InvalidOperationException("Parameter type mismatch; both parameters to Update should be same type.");
            return dataStrategy.Run.Update(table.GetQualifiedName(), newValuesDict, originalValuesDict);
        }

        private static object UpdateUsingKeys(DataStrategy dataStrategy, DynamicTable table, object[] args)
        {
            var record = ObjectToDictionary(args[0]);
            var list = record as IList<IDictionary<string, object>>;
            if (list != null) return dataStrategy.Run.UpdateMany(table.GetQualifiedName(), list);

            var dict = record as IDictionary<string, object>;
            if (dict == null) throw new InvalidOperationException("Could not resolve data from passed object.");
            var key = dataStrategy.GetAdapter().GetKey(table.GetQualifiedName(), dict);
            dict = dict.Where(kvp => key.All(keyKvp => keyKvp.Key.Homogenize() != kvp.Key.Homogenize())).ToDictionary();
            var criteria = ExpressionHelper.CriteriaDictionaryToExpression(table.GetQualifiedName(), key);
            return dataStrategy.Run.Update(table.GetQualifiedName(), dict, criteria);
        }

        internal static object ObjectToDictionary(object obj)
        {
            var dynamicRecord = obj as SimpleRecord;
            if (dynamicRecord != null)
            {
                return new Dictionary<string, object>(dynamicRecord, HomogenizedEqualityComparer.DefaultInstance);
            }

            var dictionary = obj as IDictionary<string, object>;
            if (dictionary != null)
            {
                return dictionary;
            }

            var list = obj as IEnumerable;
            if (list != null)
            {
                var originals = list.Cast<object>().ToList();
                var dictionaries = originals.Select(o => ObjectToDictionary(o) as IDictionary<string,object>).Where(o => o != null && o.Count > 0).ToList();
                if (originals.Count == dictionaries.Count)
                    return dictionaries;
            }

            return obj.ObjectToDictionary();
        }
    }
}


text:
set -e

. script/functions

DOCKER_IMAGE="dius/pact-broker"
gem_version=$(gem_version_from_gemfile_lock)
existing_tags=$(wget -q https://registry.hub.docker.com/v1/repositories/${DOCKER_IMAGE}/tags -O - | jq -r .[].name | sed 's/-[0-9]$/.1/g')
existing_release_numbers_for_current_gem_version=$(echo "$existing_tags" | grep "${gem_version}\." | sed 's/'${gem_version}'\.//g' | grep -E "^[0-9]+$" | cat)

if [ -n "${existing_release_numbers_for_current_gem_version}" ]; then
  last_release_number=$(printf "0\n${existing_release_numbers_for_current_gem_version}" | sort -g | tail -1)
  next_release_number=$(( $last_release_number + 1 ))
else
  next_release_number=0
fi

tag="${gem_version}.${next_release_number}"
echo $tag


text:
using Elastic.Clients.Elasticsearch.Fluent;
using Elastic.Clients.Elasticsearch.Serialization;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text.Json;
using System.Text.Json.Serialization;

#nullable restore
namespace Elastic.Clients.Elasticsearch.Aggregations;
public sealed partial class TermsPartition
{
	[JsonInclude]
	[JsonPropertyName("num_partitions")]
	public long NumPartitions { get; set; }

	[JsonInclude]
	[JsonPropertyName("partition")]
	public long Partition { get; set; }
}

public sealed partial class TermsPartitionDescriptor : SerializableDescriptor<TermsPartitionDescriptor>
{
	internal TermsPartitionDescriptor(Action<TermsPartitionDescriptor> configure) => configure.Invoke(this);
	public TermsPartitionDescriptor() : base()
	{
	}

	private long NumPartitionsValue { get; set; }

	private long PartitionValue { get; set; }

	public TermsPartitionDescriptor NumPartitions(long numPartitions)
	{
		NumPartitionsValue = numPartitions;
		return Self;
	}

	public TermsPartitionDescriptor Partition(long partition)
	{
		PartitionValue = partition;
		return Self;
	}

	protected override void Serialize(Utf8JsonWriter writer, JsonSerializerOptions options, IElasticsearchClientSettings settings)
	{
		writer.WriteStartObject();
		writer.WritePropertyName("num_partitions");
		writer.WriteNumberValue(NumPartitionsValue);
		writer.WritePropertyName("partition");
		writer.WriteNumberValue(PartitionValue);
		writer.WriteEndObject();
	}
}


text:
package org.apache.ignite.internal.processors.cache.distributed;

import java.util.ArrayList;
import java.util.Collection;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteState;
import org.apache.ignite.Ignition;
import org.apache.ignite.cache.CacheMemoryMode;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.affinity.Affinity;
import org.apache.ignite.cache.eviction.fifo.FifoEvictionPolicy;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.configuration.NearCacheConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.processors.cache.GridCacheAbstractSelfTest;

import static org.apache.ignite.cache.CacheMode.PARTITIONED;

/**
 *
 */
public class IgniteCacheNearOffheapGetSelfTest extends GridCacheAbstractSelfTest {
    /** {@inheritDoc} */
    @Override protected int gridCount() {
        return 4;
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        super.beforeTestsStarted();

        if (nearEnabled())
            grid(gridCount() - 1).getOrCreateCache(new CacheConfiguration(), nearConfiguration());
    }

    /** {@inheritDoc} */
    @SuppressWarnings("unchecked")
    @Override protected NearCacheConfiguration nearConfiguration() {
        NearCacheConfiguration nearCfg = super.nearConfiguration();

        nearCfg.setNearEvictionPolicy(new FifoEvictionPolicy(100));

        return nearCfg;
    }

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

        if (getTestIgniteInstanceName(gridCount() - 1).equals(igniteInstanceName)) {
            cfg.setClientMode(true);

            cfg.setCacheConfiguration();
        }

        return cfg;
    }

    /** {@inheritDoc} */
    @SuppressWarnings("unchecked")
    @Override protected CacheConfiguration cacheConfiguration(String igniteInstanceName) throws Exception {
        CacheConfiguration cfg = super.cacheConfiguration(igniteInstanceName);

        cfg.setBackups(1);
        cfg.setMemoryMode(CacheMemoryMode.OFFHEAP_TIERED);

        return cfg;
    }

    /** {@inheritDoc} */
    @Override protected CacheMode cacheMode() {
        return PARTITIONED;
    }

    @Override
    protected long getTestTimeout() {
        return Long.MAX_VALUE;
    }

    /**
     * @throws Exception If failed.
     */
    public void testGetFromNear() throws Exception {

        IgniteCache<Object, Object> nearOnly = ignite(gridCount() - 1).cache(null);

        // Start extra node.
        IgniteEx ignite = startGrid(gridCount());

        try {
            final int keyCnt = 30;

            for (int i = 0; i < keyCnt; i++)
                ignite(0).cache(null).put(i, i);

            for (int i = 0; i < keyCnt; i++)
                assertEquals(i, nearOnly.get(i));

            Collection<Integer> invalidatedKeys = new ArrayList<>();

            Affinity<Object> cacheAff = ignite.affinity(null);

            // Going to stop the last node.
            for (int i = 0; i < keyCnt; i++) {
                if (cacheAff.mapKeyToNode(i).equals(ignite.localNode()))
                    invalidatedKeys.add(i);
            }

            stopGrid(gridCount());

            for (Integer key : invalidatedKeys)
                assertEquals(key, nearOnly.get(key));
        }
        finally {
            if (Ignition.state(getTestIgniteInstanceName(gridCount())) == IgniteState.STARTED)
                stopGrid(gridCount());
        }
    }
}


text:
package vision;

import interfaces.Fermable;
import interfaces.Lancable;

import java.awt.Component;

import divers.Outil;

public class Redessinement implements Runnable, Lancable, Fermable {
	private static final int TEMPS = 40;
	private final Component repaint;
	private final int delai;
	private boolean run;

	public Redessinement(Component repaint) {
		this(repaint, TEMPS);
	}

	public Redessinement(Component repaint, int delai) {
		this.repaint = repaint;
		this.delai = delai;
	}

	@Override
	public void run() {
		run = true;
		while(run) {
			Outil.wait(delai);
			repaint.repaint();
		}
	}

	@Override
	public boolean fermer() {
		if(!run)
			return false;
		run = false;
		return true;
	}

	@Override
	public boolean lancer() {
		if(run)
			return false;
		new Thread(this).start();
		return true;
	}

}


text:
package org.asteriskjava.manager.event;

/**
 * A dial event is triggered whenever a phone attempts to dial someone.
 *

 * This event is implemented in apps/app_dial.c.
 *

 * Available since Asterisk 1.2.
 *
 * @author Asteria Solutions Group, Inc. http://www.asteriasgi.com/
 * @version $Id$
 * @since 0.2
 */
public class DialEvent extends ManagerEvent
{
    /**
     * Serializable version identifier.
     */
    private static final long serialVersionUID = 1L;

    public static final String SUBEVENT_BEGIN = "Begin";
    public static final String SUBEVENT_END = "End";

    public static final String DIALSTATUS_CHANUNAVAIL = "CHANUNAVAIL";
    public static final String DIALSTATUS_CONGESTION = "CONGESTION";
    public static final String DIALSTATUS_NOANSWER = "NOANSWER";
    public static final String DIALSTATUS_BUSY = "BUSY";
    public static final String DIALSTATUS_ANSWER = "ANSWER";
    public static final String DIALSTATUS_CANCEL = "CANCEL";
    public static final String DIALSTATUS_DONTCALL = "DONTCALL";
    public static final String DIALSTATUS_TORTURE = "TORTURE";
    public static final String DIALSTATUS_INVALIDARGS = "INVALIDARGS";

    private String subEvent = SUBEVENT_BEGIN;

    /**
     * The name of the source channel.
     */
    private String channel;

    /**
     * The name of the destination channel.
     */
    private String destination;

    /**
     * Destination channel state
     */
    private Integer destChannelState;
    private String destChannelStateDesc;

    private String destContext;

    private Integer destPriority;

    private String destExten;

    private String destConnectedLineName;
    private String destConnectedLineNum;

    private String destCallerIdName;
    private String destCallerIdNum;

    /**
     * The new Caller*ID.
     */
    private String callerIdNum;

    /**
     * The new Caller*ID Name.
     */
    private String callerIdName;

    /**
     * The unique id of the source channel.
     */
    private String uniqueId;

    /**
     * The unique id of the destination channel.
     */
    private String destUniqueId;

    private String dialString;
    private String dialStatus;

    public DialEvent(Object source)
    {
        super(source);
    }

    /**
     * Enro 2015-03 Workaround to build legacy DialEvent (unsupported in
     * Asterisk 13) from new DialBeginEvent Asterisk 13.
     */
    public DialEvent(DialBeginEvent dialBeginEvent)
    {
        this(dialBeginEvent.getSource());
        setDateReceived(dialBeginEvent.getDateReceived());
        setTimestamp(dialBeginEvent.getTimestamp());
        setPrivilege(dialBeginEvent.getPrivilege());
        setCallerId(dialBeginEvent.getCallerIdNum());
        setCallerIdName(dialBeginEvent.getCallerIdName());
        setSrc(dialBeginEvent.getChannel());
        setUniqueId(dialBeginEvent.getSrcUniqueId());
        setDestUniqueId(dialBeginEvent.getDestUniqueId());
        setDestination(dialBeginEvent.getDestChannel());
        setDialStatus(dialBeginEvent.getDialStatus());
    }

    /**
     * Since Asterisk 1.6 the begin and the end of a dial command generate a
     * Dial event. The subEvent property returns whether the dial started
     * execution ("Begin") or completed ("End"). As Asterisk prior to 1.6 only
     * sends one event per Dial command this always returns "Begin" for Asterisk
     * prior to 1.6.

     * For an "End" sub event only the properies channel, unqiue id and dial
     * status are available, for a "Begin" sub event all properties are
     * available except for the dial status.
     *
     * @return "Begin" or "End" for Asterisk since 1.6, "Begin" for Asterisk
     *         prior to 1.6.
     * @since 1.0.0
     */
    public String getSubEvent()
    {
        return subEvent;
    }

    public void setSubEvent(String subEvent)
    {
        this.subEvent = subEvent;
    }

    /**
     * Returns the name of the source channel.
     *
     * @return the name of the source channel.
     * @since 1.0.0
     */
    public String getChannel()
    {
        return channel;
    }

    /**
     * Returns the name of the source channel.
     *
     * @param channel the name of the source channel.
     * @since 1.0.0
     */
    public void setChannel(String channel)
    {
        this.channel = channel;
    }

    /**
     * Returns the name of the source channel.
     *
     * @return the name of the source channel.
     * @deprecated as of 1.0.0, use {@link #getChannel()} instead.
     */
    @Deprecated
    public String getSrc()
    {
        return channel;
    }

    /**
     * Sets the name of the source channel.
     *

     * Asterisk versions up to 1.4 use the "Source" property instead of
     * "Channel".
     *
     * @param src the name of the source channel.
     */
    public void setSrc(String src)
    {
        this.channel = src;
    }

    /**
     * Returns the name of the destination channel.
     *
     * @return the name of the destination channel.
     */
    public String getDestination()
    {
        return destination;
    }

    public String getDestChannel()
    {
        return getDestination();
    }

    /**
     * Sets the name of the destination channel.
     *
     * @param destination the name of the destination channel.
     */
    public void setDestination(String destination)
    {
        this.destination = destination;
    }

    public void setDestChannel(String destination)
    {
        setDestination(destination);
    }

    /**
     * Returns the Caller*ID.
     *
     * @return the Caller*ID or "<unknown>" if none has been set.
     * @deprecated as of 1.0.0, use {@link #getCallerIdNum()} instead.
     */
    @Deprecated
    public String getCallerId()
    {
        return callerIdNum;
    }

    /**
     * Sets the caller*ID.
     *
     * @param callerId the caller*ID.
     */
    public void setCallerId(String callerId)
    {
        this.callerIdNum = callerId;
    }

    /**
     * Returns the unique ID of the source channel.
     *
     * @return the unique ID of the source channel.
     * @since 1.0.0
     */
    public String getUniqueId()
    {
        return uniqueId;
    }

    /**
     * Sets the unique ID of the source channel.
     *
     * @param srcUniqueId the unique ID of the source channel.
     * @since 1.0.0
     */
    public void setUniqueId(String srcUniqueId)
    {
        this.uniqueId = srcUniqueId;
    }

    /**
     * Returns the unique ID of the source channel.
     *
     * @return the unique ID of the source channel.
     * @deprecated as of 1.0.0, use {@link #getUniqueId()} instead.
     */
    @Deprecated
    public String getSrcUniqueId()
    {
        return uniqueId;
    }

    /**
     * Sets the unique ID of the source channel.
     *

     * Asterisk versions up to 1.4 use the "SrcUniqueId" property instead of
     * "UniqueId".
     *
     * @param srcUniqueId the unique ID of the source channel.
     */
    public void setSrcUniqueId(String srcUniqueId)
    {
        this.uniqueId = srcUniqueId;
    }

    /**
     * Returns the unique ID of the destination channel.
     *
     * @return the unique ID of the destination channel.
     */
    public String getDestUniqueId()
    {
        return destUniqueId;
    }

    /**
     * Sets the unique ID of the destination channel.
     *
     * @param destUniqueId the unique ID of the destination channel.
     */
    public void setDestUniqueId(String destUniqueId)
    {
        this.destUniqueId = destUniqueId;
    }

    /**
     * Returns the dial string passed to the Dial application.
     *

     * Available since Asterisk 1.6.
     *
     * @return the dial string passed to the Dial application.
     * @since 1.0.0
     */
    public String getDialString()
    {
        return dialString;
    }

    /**
     * Sets the dial string passed to the Dial application.
     *
     * @param dialString the dial string passed to the Dial application.
     * @since 1.0.0
     */
    public void setDialString(String dialString)
    {
        this.dialString = dialString;
    }

    /**
     * For end subevents this returns whether the completion status of the dial
     * application.

     * Possible values are:
     *

     *
CHANUNAVAIL

     *
CONGESTION

     *
NOANSWER

     *
BUSY

     *
ANSWER

     *
CANCEL

     *
DONTCALL

     *
TORTURE

     *
INVALIDARGS

     *

     * It corresponds the the DIALSTATUS variable used in the dialplan.
     *

     * Available since Asterisk 1.6.
     *
     * @return the completion status of the dial application.
     * @since 1.0.0
     */
    public String getDialStatus()
    {
        return dialStatus;
    }

    public void setDialStatus(String dialStatus)
    {
        this.dialStatus = dialStatus;
    }

    @Override
    public String toString()
    {
        StringBuilder builder = new StringBuilder();
        builder.append("DialEvent [subEvent=");
        builder.append(subEvent);
        builder.append(", channel=");
        builder.append(channel);
        builder.append(", destination=");
        builder.append(destination);
        builder.append(", callerIdNum=");
        builder.append(callerIdNum);
        builder.append(", callerIdName=");
        builder.append(callerIdName);
        builder.append(", uniqueId=");
        builder.append(uniqueId);
        builder.append(", destUniqueId=");
        builder.append(destUniqueId);
        builder.append(", dialString=");
        builder.append(dialString);
        builder.append(", dialStatus=");
        builder.append(dialStatus);
        builder.append(", connectedLineNum=");
        builder.append(connectedLineNum);
        builder.append(", connectedLineName=");
        builder.append(connectedLineName);
        builder.append("]");
        return builder.toString();
    }

    public Integer getDestChannelState()
    {
        return destChannelState;
    }

    public void setDestChannelState(Integer destChannelState)
    {
        this.destChannelState = destChannelState;
    }

    public String getDestContext()
    {
        return destContext;
    }

    public void setDestContext(String destContext)
    {
        this.destContext = destContext;
    }

    public Integer getDestPriority()
    {
        return destPriority;
    }

    public void setDestPriority(Integer destPriority)
    {
        this.destPriority = destPriority;
    }

    public String getDestChannelStateDesc()
    {
        return destChannelStateDesc;
    }

    public void setDestChannelStateDesc(String destChannelStateDesc)
    {
        this.destChannelStateDesc = destChannelStateDesc;
    }

    public String getDestExten()
    {
        return destExten;
    }

    public void setDestExten(String destExten)
    {
        this.destExten = destExten;
    }

    public String getDestConnectedLineName()
    {
        return destConnectedLineName;
    }

    public void setDestConnectedLineName(String destConnectedLineName)
    {
        this.destConnectedLineName = destConnectedLineName;
    }

    public String getDestConnectedLineNum()
    {
        return destConnectedLineNum;
    }

    public void setDestConnectedLineNum(String destConnectedLineNum)
    {
        this.destConnectedLineNum = destConnectedLineNum;
    }

    public String getDestCallerIdName()
    {
        return destCallerIdName;
    }

    public void setDestCallerIdName(String destCallerIdName)
    {
        this.destCallerIdName = destCallerIdName;
    }

    public String getDestCallerIdNum()
    {
        return destCallerIdNum;
    }

    public void setDestCallerIdNum(String destCallerIdNum)
    {
        this.destCallerIdNum = destCallerIdNum;
    }
}


text:
class EmailThresholdResponseJob < ActiveJob::Base
  include EmailAllPetitionSignatories

  self.email_delivery_job_class = DeliverThresholdResponseEmailJob
  self.timestamp_name = 'government_response'
end


text:
module Acme
  class UploadFile < Grape::API
    format :json

    desc 'Upload an image.'
    post 'avatar' do
      {
        filename: params[:image_file][:filename],
        size: params[:image_file][:tempfile].size
      }
    end

    desc 'Upload and download a file of any format.'
    post 'download' do
      filename = params[:file][:filename]
      content_type MIME::Types.type_for(filename)[0].to_s
      env['api.format'] = :binary
      header 'Content-Disposition', "attachment; filename*=UTF-8''#{URI.escape(filename)}"
      params[:file][:tempfile].read
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
       default-autowire="byName">

    <tx:annotation-driven/>

    <!--加载配置文件-->
    <bean id="propertyConfigurer" class="com.jeeplus.common.configuration.EncryptPropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc-web.properties</value>
                <value>classpath:email.properties</value>
            </list>
        </property>
    </bean>

    <!--数据源配置-->
    <bean id="webDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.className}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>
        <property name="maxWait" value="${jdbc.maxWait}"/>
        <property name="proxyFilters">
            <list>
                <ref bean="statFilter"/>
                <ref bean="wallFilter"/>
            </list>
        </property>
    </bean>

    <bean id="statFilter" class="com.alibaba.druid.filter.stat.StatFilter">
        <property name="slowSqlMillis" value="1000"/>
        <property name="logSlowSql" value="true"/>
        <property name="mergeSql" value="true"/>
    </bean>

    <bean id="wallFilter" class="com.alibaba.druid.wall.WallFilter">
        <property name="dbType" value="mysql"/>
        <property name="config" ref="wallConfig"/>
    </bean>

    <bean id="wallConfig" class="com.alibaba.druid.wall.WallConfig">
        <property name="multiStatementAllow" value="true"/>
    </bean>

    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="webDataSource"/>
        <property name="mapperLocations" value="classpath:com/jeeplus/web/mapper/*.xml"/>
        <property name="typeAliasesPackage" value="com.jeeplus.web.entities"/>
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
    </bean>

    <bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"/>
        <property name="basePackage" value="com.jeeplus.web.mapper"/>
    </bean>

</beans>


text:
/**
 * SECTION:gstphysmemoryallocator
 * @title: GstPhysMemoryAllocator
 * @short_description: Interface for allocators that pass around physical memory addresses
 * @see_also: #GstMemory
 *
 * Since: 1.14
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "gstphysmemory.h"

G_DEFINE_INTERFACE (GstPhysMemoryAllocator, gst_phys_memory_allocator,
    GST_TYPE_ALLOCATOR);

static void
gst_phys_memory_allocator_default_init (GstPhysMemoryAllocatorInterface * iface)
{
}

/**
 * gst_is_phys_memory:
 * @mem: a #GstMemory
 *
 * Returns: whether the memory at @mem is backed by physical memory
 *
 * Since: 1.14
 */
gboolean
gst_is_phys_memory (GstMemory * mem)
{
  return mem != NULL && mem->allocator != NULL
      && g_type_is_a (G_OBJECT_TYPE (mem->allocator),
      GST_TYPE_PHYS_MEMORY_ALLOCATOR);
}

/**
 * gst_phys_memory_get_phys_addr:
 * @mem: a #GstMemory
 *
 * Returns: Physical memory address that is backing @mem, or 0 if none
 *
 * Since: 1.14
 */
guintptr
gst_phys_memory_get_phys_addr (GstMemory * mem)
{
  GstPhysMemoryAllocatorInterface *iface;

  g_return_val_if_fail (gst_is_phys_memory (mem), 0);

  iface = GST_PHYS_MEMORY_ALLOCATOR_GET_INTERFACE (mem->allocator);
  g_return_val_if_fail (iface->get_phys_addr != NULL, 0);

  return iface->get_phys_addr ((GstPhysMemoryAllocator *) mem->allocator, mem);
}


text:
package com.itranswarp.recurring.price.processor.recurring;

import com.itranswarp.recurring.common.exception.APIArgumentException;
import com.itranswarp.recurring.common.exception.APIException;
import com.itranswarp.recurring.common.util.JsonUtil;
import com.itranswarp.recurring.price.PriceInputItem;
import com.itranswarp.recurring.price.processor.PriceProcessor;
import com.itranswarp.recurring.price.processor.recurring.flatfee.RecurringFlatFeeData;
import org.apache.commons.lang3.StringUtils;

import javax.inject.Named;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;

/**
 * Created by changsure on 15/9/6.
 */
@Named
public class RecurringProcessor {

    protected void checkData(RecurringData priceData) {

        if (null == priceData.getPrice()) {
            throw new APIArgumentException("priceData-price", "billingData's price can not be null.");
        }

        if (StringUtils.isBlank(priceData.getPriceBase())) {
            throw new APIArgumentException("priceData-priceBase", "priceData's price base not right.");
        }

    }

    protected Double calculate(RecurringData priceData,LocalDate startDate,LocalDate endDate,Boolean isFullMonth) {

        this.checkData(priceData);

        BigDecimal result = BigDecimal.valueOf(0);
        if (StringUtils.equalsIgnoreCase("MONTH", priceData.getPriceBase())) {
            BigDecimal dayOfMonth = priceData.getDayOfMonth()==null?BigDecimal.valueOf(30):BigDecimal.valueOf(priceData.getDayOfMonth());
            Period period = Period.between(startDate, endDate.plusDays(1));
            BigDecimal monthGap = BigDecimal.valueOf(period.getYears() * 12 + period.getMonths());
            BigDecimal dayGap = BigDecimal.valueOf(period.getDays());

            if(isFullMonth!=null && isFullMonth){
                if(period.getDays()>0 &&period.getDays()<5){
                    dayGap = BigDecimal.valueOf(0);
                }else if(period.getDays()>25){
                    dayGap = BigDecimal.valueOf(0);
                    monthGap = monthGap.add(BigDecimal.valueOf(1));
                }
            }

            result = monthGap.multiply(BigDecimal.valueOf(priceData.getPrice())).add(dayGap.multiply(BigDecimal.valueOf(priceData.getPrice())).divide(dayOfMonth,2,RoundingMode.HALF_UP));
        } else if (StringUtils.equalsIgnoreCase("YEAR", priceData.getPriceBase())) {
            BigDecimal dayOfYear = priceData.getDayOfYear()==null?BigDecimal.valueOf(365):BigDecimal.valueOf(priceData.getDayOfYear());
            Period period = Period.between(startDate,endDate.plusDays(1));
            BigDecimal yearGap = BigDecimal.valueOf(period.getYears());
            BigDecimal monthGap = BigDecimal.valueOf(period.getMonths());
            BigDecimal dayGap = BigDecimal.valueOf(period.getDays());

            if(isFullMonth!=null && isFullMonth){
                if(period.getDays()>0 &&period.getDays()<5){
                    dayGap = BigDecimal.valueOf(0);
                }else if(period.getDays()>25){
                    dayGap = BigDecimal.valueOf(0);
                    monthGap = monthGap.add(BigDecimal.valueOf(1));
                }
            }

            BigDecimal yearResult = yearGap.multiply(BigDecimal.valueOf(priceData.getPrice()));
            BigDecimal monthResult = monthGap.multiply(BigDecimal.valueOf(priceData.getPrice())).divide(BigDecimal.valueOf(12),2,RoundingMode.HALF_UP);
            BigDecimal dayResult = dayGap.multiply(BigDecimal.valueOf(priceData.getPrice())).divide(dayOfYear, 2, RoundingMode.HALF_UP);
            result = yearResult.add(monthResult).add(dayResult);
        } else if (StringUtils.equalsIgnoreCase("DAY", priceData.getPriceBase())) {
            long dayGap = ChronoUnit.DAYS.between(startDate, endDate.plusDays(1));
            result = BigDecimal.valueOf(dayGap).multiply((BigDecimal.valueOf(priceData.getPrice())));
        } else if (StringUtils.equalsIgnoreCase("WEEK", priceData.getPriceBase())) {
            long dayGap = ChronoUnit.DAYS.between(startDate, endDate.plusDays(1));
            result = BigDecimal.valueOf(dayGap).multiply(BigDecimal.valueOf(priceData.getPrice())).divide(BigDecimal.valueOf(7), 3, RoundingMode.HALF_UP);
        }

        return result.setScale(2,RoundingMode.HALF_UP).doubleValue();
    }
}


text:
<?php
namespace Zanson\SMParser\Traits\Song;

use Zanson\SMParser\SMException;

trait TimeSignatures
{
    public $TimeSignatures = [];

    /**
     * @return string
     */
    public function getTimeSignatures() {
        return implode(',', $this->TimeSignatures);
    }

    /**
     * @param $TimsSignatures
     *
     * @return $this
     * @throws SMException
     */
    public function setTimeSignaturesFromString($TimsSignatures) {
        if (!is_string($TimsSignatures)) {
            throw new SMException("TimsSignatures must be a string");
        }
        $TimsSignatures = explode(',', $TimsSignatures);
        foreach ($TimsSignatures as $b) {
            $this->TimeSignatures[] = trim($b);
        }

        return $this;
    }
}


text:
<#
    .SYNOPSIS
        Powershell Script to Install Updates
    .DESCRIPTION
        Uses the Windows Update API to search, filter, and install updates.
    .PARAMETER Restart
        Whether to reboot the machine if one is required after installation.
    .PARAMETER List
        Only list the updates that are available for download/install.
    .PARAMETER UpdateCategories
        Comma separated list of update categories that you want to install.
    .PARAMETER KB
        Specify a single or comma separate list of KB's to install
    .EXAMPLE
            Install-Updates.ps1 -Restart True -UpdateCategories Definition, Critical, Security
            Install-Updates.ps1 -Restart True -KB KB2345678, KB3107780
    .Notes
        Author: Daniel Shepherd
        email: <daniels@mindpointgroup.com>
        website: http://www.mindpointgroup.com/

        Version History
        0.1  6/2/2014
            - Initial Release
#>
[CmdletBinding()]
param(
$Path = (Get-Location),
[switch]$Restart = $False,
[Bool]$List = $False,
[ValidateSet("Critical", "Definition", "Application", "FeaturePacks", "Security", "ServicePacks", "Tools", "UpdateRollups", "Updates", "All")]
[String]$UpdateCategories = "all",
[String]$KB = "*"

)

$CurrentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
    if (($CurrentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) -eq $false) {
        $ArgList = "-noprofile -noexit -file `"{0}`" -Path `"$Path`""
        If ($Reboot) {$ArgList = $ArgList + " -Reboot"}
        If ($List) {$ArgumentList = $ArgumentList + " -List"}
        If ($UpdateCategories) {$ArgumentList = $ArgumentList + " -UpdateCategories $UpdateCategories"}
        If ($KB) {$ArgumentList = $ArgumentList + " -KB $KB"}
        Start-Process powershell.exe -Verb RunAs -ArgumentList ($ArgList -f ($myinvocation.MyCommand.Definition))
        Break
    }
#Echo "Restart =" $Restart
#Echo "List =" $List
#Echo "UpdateCats =" $UpdateCategories
#Echo "KB =" $KB

$categories = @{"critical" = "E6CF1350-C01B-414D-A61F-263D14D133B4";
                "definition" = "E0789628-CE08-4437-BE74-2495B842F43B";
                "application" = "5C9376AB-8CE6-464A-B136-22113DD69801";
                "featurepacks" = "B54E7D24-7ADD-428F-8B75-90A396FA584F";
                "security" = "0FA1201D-4330-4FA8-8AE9-B877473B6441";
                "servicepacks" = "68C5B0A3-D1A6-4553-AE49-01D3A7827828";
                "tools" = "B4832BD8-E735-4761-8DAF-37F882276DAB";
                "updaterollups" = "28BC880E-0592-4CBF-8F95-C79B17911D5F";
                "updates" = "CD5FFD1E-E932-4E3A-BF74-18BF0B1BBD83"}
$updateCatIDs = @()
$availableUpdates = @()
$kbIDs = @()
$searchFilter = "IsInstalled=0 and IsHidden=0"

# Creating Update Session object
$muSession = New-Object -ComObject "Microsoft.Update.Session"

#Processing category types
#Loop through passed in categories and build arrary
foreach($cat in $UpdateCategories.split(",").Trim(" ")) {
    $cat = $cat.ToLower()
    If ($cat -eq "all") {
        $updateCatIDs = "*"
        Break
    }
    Else {
        $updateCatIDs += $categories.Item($cat)
    }
}

#Processing List of KBs
#Loop through passed in KBs and build array
foreach($id in ($KB.split(",").Trim(" "))) {
    $id = $id.ToLower()
    If (($id -eq "*") -or ($id -eq "all")) {
        $kbIDs = "*"
        Break
    }
    Else {
        $kbIDs += $id.Trim("kb")
    }
}

# Search for updates
$muSearch = $muSession.CreateUpdateSearcher()

If ($kbIDs -ne "*") {
    $muSearchResults = $muSearch.Search($searchFilter).Updates

    foreach($update in $muSearchResults) {
        If ($kbIDs -contains $update.KBArticleIDs) {
            $availableUpdates += $update
        }
    }
}
ElseIf ($updateCatIDs -eq "*") {
    #Just get all the updates that are available for install
    Write-Host "Should do this"
    $availableUpdates = $muSearch.Search($searchFilter).Updates
}
Else {
    $searchFilter = ""
    foreach($catID in $updateCatIDs) {
        $searchFilter += "(IsInstalled=0 and IsHidden=0 and CategoryIDs contains '"+$catID+"')"
    }

    $availableUpdates = $muSearch.Search($searchFilter).Updates
}

Write-Host $availableUpdates.Count
# Check if we have any updates
If ($availableUpdates.Count -eq 0) {
    Write-Host "No updates: nothing changed"
    Exit 0
}
# Accept Eula for silent install and add to update Collection
$updateCollection = New-Object -ComObject "Microsoft.Update.UpdateColl"

foreach ($update in $availableUpdates) {
    #Write-Host "Adding update -" $update
    If ($update.EulaAccepted -eq 0) {
        $update.AcceptEula()
    }

    $updateCollection.Add($update)
}

# Download updates
$muDownloader = $muSession.CreateUpdateDownloader()
$muDownloader.Updates = $updateCollection

try {
    $muDownloader.Download()
}
catch {
    Write-Host "FAILED!! on Download"
    Exit 1
}

# Install downloaded updates
$installCollection = New-Object -ComObject "Microsoft.Update.UpdateColl"

foreach ($update in $availableUpdates) {
    If ($update.IsDownloaded) {
    #Write-Host "Adding downloaded update - " $update
        $installCollection.Add($update)
    }
}

# Check if we have any updates at this stage
If ($installCollection.Count -eq 0) {
    Write-Host "FAILED!! nothing in download collection"
    Exit 1
}

$muInstaller = $muSession.CreateUpdateInstaller()
$muInstaller.Updates = $installCollection

try {
    $muInstallResults = $muInstaller.Install()
}
catch {
    Write-Host "FAILED!! on Install"
    Exit 1
}

# Reboot if needed
If ($muInstallResults.RebootRequired -and $Restart) {
    Restart-Computer -Force
}


text:
package dk.brics.jwig.analysis.jaive.feedback;

import soot.SootMethod;
import dk.brics.jwig.analysis.Parameter;

public class PossiblyMissingFilterParameter extends AbstractFeedback {

    public PossiblyMissingFilterParameter(Parameter p, SootMethod caller) {
        message = "The parameter \""
                + p.getName()
                + "\" in the method"
                + p.getHost().getSignature()
                + " is required. But it might not be present when the filter is invoked from "
                + caller.getSignature() + " as it isn't marked as required.";
        type = FeedbackType.WARNING;
    }
}


text:
<search-facet result="result" query="query" title="Persons and Companies"
              facet="entities" filter="entities.id">
</search-facet>

<div ng-repeat="facet in facets track by facet.field">
  <search-facet result="result" query="query" expandable="true"
                title="{{facet.label}}" facet="{{facet.field}}">
  </search-facet>
</div>


text:
package syntaxtree;
import visitor.Visitor;
import visitor.TypeVisitor;
import irgeneration.IRGenVisitor;

public class IdentifierType extends Type {
  public String s;

  public IdentifierType(String as) {
    super(as, 0,0);
    s=as;
  }

  public IdentifierType(String as, int line, int col) {
    super(as, line, col);
    s=as;
  }

  public void accept(Visitor v) {
    v.visit(this);
  }

  public Type accept(TypeVisitor v) {
    return v.visit(this);
  }

}


text:
'use strict';

// MODULES //

var dnanvariancetk = require( '@stdlib/stats/base/dnanvariancetk' );
var sqrt = require( '@stdlib/math/base/special/sqrt' );

// MAIN //

/**
* Computes the standard deviation of a double-precision floating-point strided array ignoring `NaN` values and using a one-pass textbook algorithm.
*
* @param {PositiveInteger} N - number of indexed elements
* @param {number} correction - degrees of freedom adjustment
* @param {Float64Array} x - input array
* @param {integer} stride - stride length
* @returns {number} standard deviation
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 1.0, -2.0, NaN, 2.0 ] );
* var N = x.length;
*
* var v = dnanstdevtk( N, 1, x, 1 );
* // returns ~2.0817
*/
function dnanstdevtk( N, correction, x, stride ) {
	return sqrt( dnanvariancetk( N, correction, x, stride ) );
}

// EXPORTS //

module.exports = dnanstdevtk;


text:
<?php

namespace Prokki\Warlight2BotTemplate\Game;

use Prokki\TheaigamesBotEngine\Game\RoundBasedEnvironment;

class Environment extends RoundBasedEnvironment
{
	/**
	 * @var Player
	 */
	protected $_player = null;

	/**
	 * @var Map
	 */
	protected $_map = null;

	/**
	 * Environment constructor.
	 *
	 * @inheritdoc
	 */
	public function __construct($max_rounds = 0)
	{
		$this->_player = EnvironmentFactory::Get()->newPlayer();
		$this->_map    = EnvironmentFactory::Get()->newMap();

		parent::__construct();
	}

	/**
	 * @return Player
	 */
	public function getPlayer()
	{
		return $this->_player;
	}

	/**
	 * @return Map
	 */
	public function getMap()
	{
		return $this->_map;
	}

	/**
	 * Overrides... to reference updated map of old round as initial map of new round.
	 *
	 * @inheritdoc
	 */
	public function addRound()
	{
		// call parent method
		/** @var Round $new_round */
		$new_round = parent::addRound();

		$this->_map = clone $this->_map;

		// reference map of old round as initial map of new round
		return $new_round->setInitialMap($this->_map);
	}
}


text:
package com.intellij.openapi.progress.util;

import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.ui.GraphicsConfig;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.Gray;
import com.intellij.ui.JBColor;
import com.intellij.util.NotNullProducer;
import com.intellij.util.ui.GraphicsUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;

/**
 * @author Eugene Belyaev
 */
public class ColorProgressBar extends JComponent {
  private static final Dimension PREFERRED_SIZE = new Dimension(146, 17);

  public static final Color GREEN = new JBColor(() -> {
    UISettings settings = UISettings.getInstance();
    return settings == null || null == settings.COLOR_BLINDNESS
           ? new JBColor(new Color(0x6cad74), new Color(0x4a8c53))
           : new JBColor(new Color(0x6ca69c), new Color(0x639990));
  });
  public static final Color RED = new JBColor(() -> {
    UISettings settings = UISettings.getInstance();
    return settings == null || null == settings.COLOR_BLINDNESS
           ? new JBColor(new Color(0xd67b76), new Color(0xe55757))
           : new JBColor(new Color(0xcc7447), new Color(0xcc7447));
  });
  public static final Color RED_TEXT = new JBColor(new Color(0xb81708), new Color(0xdb5c5c));
  public static final Color BLUE = new JBColor(new Color(1, 68, 208), JBColor.blue);
  public static final Color YELLOW = new JBColor(new Color(0xa67a21), new Color(0x91703a));
  private static final Color SHADOW1 = new JBColor(Gray._190, UIUtil.getBorderColor()) ;
  private static final Color SHADOW2 = Gray._105;

  private static final int BRICK_WIDTH = 6;
  private static final int BRICK_SPACE = 1;

  private static final int INDETERMINATE_BRICKS_DRAW = 5;
  private static final double INDETERMINATE_INC_OFFSET = 0.02;

  private double myFraction = 0.0;
  private Color myColor = BLUE;

  private double myIndeterminateInc = INDETERMINATE_INC_OFFSET;
  private boolean myIndeterminate = false;

  public boolean isIndeterminate() {
    return myIndeterminate;
  }

  public void setIndeterminate(boolean indeterminate) {
    this.myIndeterminate = indeterminate;
  }

  public ColorProgressBar() {
    updateUI();
  }

  public void setColor(Color color) {
    myColor = color;
    if (isDisplayable()) repaint();
  }

  public double getFraction() {
    return myFraction;
  }

  public void setFraction(double fraction) {
    if (Double.isNaN(fraction)) {
      fraction = 1.0;
    }

    if (myIndeterminate) {
      if (myFraction >= 1.0) {
        myIndeterminateInc = -INDETERMINATE_INC_OFFSET;
      }
      else if (myFraction <= 0) {
        myIndeterminateInc = INDETERMINATE_INC_OFFSET;
      }

      final boolean changed = myFraction == 0 || getBricksToDraw(myFraction) != getBricksToDraw(myFraction + myIndeterminateInc);
      myFraction += myIndeterminateInc;

      if (changed) {
        repaint();
      }
    }
    else {
      boolean changed = myFraction == 0 || getBricksToDraw(myFraction) != getBricksToDraw(fraction);
      myFraction = fraction;
      if (changed) {
        repaint();
      }
    }
  }

  private int getBricksToDraw(double fraction) {
    int bricksTotal = (getWidth() - 8) / (BRICK_WIDTH + BRICK_SPACE);
    return (int)(bricksTotal * fraction) + 1;
  }

  protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    final GraphicsConfig config = GraphicsUtil.setupAAPainting(g);
    Graphics2D g2 = (Graphics2D)g;
    if (myFraction > 1) {
      myFraction = 1;
    }

    Dimension size = getSize();

    g2.setPaint(UIUtil.getListBackground());
    Rectangle2D rect = new Rectangle2D.Double(2, 2, size.width - 4, size.height - 4);
    g2.fill(rect);

    g2.setPaint(new JBColor(SHADOW1, UIUtil.getBorderColor()));
    rect.setRect(1, 1, size.width - 2, size.height - 2);
    g2.drawRoundRect(1, 1, size.width - 2, size.height - 2, 5, 5);
    g2.setPaint(SHADOW2);
    g2.drawRoundRect(0, 0, size.width - 2, size.height - 2, 5, 5);

    int y_center = size.height / 2;
    int y_steps = size.height / 2 - 3;
    int alpha_step = y_steps > 0 ? (255 - 70) / y_steps : 255 - 70;
    int x_offset = 4;

    g.setClip(4, 3, size.width - 8, size.height - 6);

    int bricksToDraw = myFraction == 0 ? 0 : getBricksToDraw(myFraction);

    if (myIndeterminate) {

      int startFrom = bricksToDraw < INDETERMINATE_BRICKS_DRAW ? 0 : bricksToDraw - INDETERMINATE_BRICKS_DRAW;
      int endTo = bricksToDraw + INDETERMINATE_BRICKS_DRAW < getBricksToDraw(1) ? bricksToDraw + INDETERMINATE_BRICKS_DRAW  : getBricksToDraw(1);

      for (int i = startFrom; i <= endTo; i++) {
        g2.setPaint(myColor);

        int startXOffset = x_offset + (BRICK_WIDTH + BRICK_SPACE) * i;
        UIUtil.drawLine(g2, startXOffset, y_center, startXOffset + BRICK_WIDTH - 1, y_center);

        for (int j = 0; j < y_steps; j++) {
          Color color = ColorUtil.toAlpha(myColor, 255 - alpha_step * (j + 1));
          g2.setPaint(color);
          UIUtil.drawLine(g2, startXOffset, y_center - 1 - j, startXOffset + BRICK_WIDTH - 1, y_center - 1 - j);

          if (!(y_center % 2 != 0 && j == y_steps - 1)) {
            UIUtil.drawLine(g2, startXOffset, y_center + 1 + j, startXOffset + BRICK_WIDTH - 1, y_center + 1 + j);
          }
        }
        g2.setColor(
          ColorUtil.toAlpha(myColor, 255 - alpha_step * (y_steps / 2 + 1)));
        g2.drawRect(startXOffset, y_center - y_steps, BRICK_WIDTH - 1, size.height - 7);
      }

    } else {
      for (int i = 0; i < bricksToDraw; i++) {
        g2.setPaint(myColor);
        UIUtil.drawLine(g2, x_offset, y_center, x_offset + BRICK_WIDTH - 1, y_center);
        for (int j = 0; j < y_steps; j++) {
          Color color = ColorUtil.toAlpha(myColor, 255 - alpha_step * (j + 1));
          g2.setPaint(color);
          UIUtil.drawLine(g2, x_offset, y_center - 1 - j, x_offset + BRICK_WIDTH - 1, y_center - 1 - j);
          if (!(y_center % 2 != 0 && j == y_steps - 1)) {
            UIUtil.drawLine(g2, x_offset, y_center + 1 + j, x_offset + BRICK_WIDTH - 1, y_center + 1 + j);
          }
        }
        g2.setColor(
          ColorUtil.toAlpha(myColor, 255 - alpha_step * (y_steps / 2 + 1)));
        g2.drawRect(x_offset, y_center - y_steps, BRICK_WIDTH - 1, size.height - 7);
        x_offset += BRICK_WIDTH + BRICK_SPACE;
      }
    }

    config.restore();
  }

  public Dimension getPreferredSize() {
    return PREFERRED_SIZE;
  }

  public Dimension getMaximumSize() {
    Dimension dimension = getPreferredSize();
    dimension.width = Short.MAX_VALUE;
    return dimension;
  }

  public Dimension getMinimumSize() {
    Dimension dimension = getPreferredSize();
    dimension.width = 13;
    return dimension;
  }

  public Color getColor() {
    return myColor;
  }

  @SuppressWarnings({"HardCodedStringLiteral"})
  public static void main(String[] args) {
    JFrame frame = new JFrame("ColorProgressBar Test");
    frame.addWindowListener(
      new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          System.exit(0);
        }
      }
    );
    frame.setSize(800, 600);
    frame.setLocation(0, 0);
    Container contentPane = frame.getContentPane();
    contentPane.setLayout(new BorderLayout());
    final ColorProgressBar colorProgressBar = new ColorProgressBar();
    colorProgressBar.setFraction(0.5);
    colorProgressBar.setIndeterminate(true);
    contentPane.add(colorProgressBar, BorderLayout.NORTH);
    frame.setVisible(true);
    JButton b = new JButton ("X");
    b.addActionListener(new ActionListener () {
      public void actionPerformed(ActionEvent e) {
         colorProgressBar.setFraction(1);
      }
    });
    contentPane.add(b, BorderLayout.SOUTH);
  }
}


text:
package com.github.rhacoal.skylink.plug;

/**
 *
 * @author Rhacoal
 */
public interface PluginEntity {

    public PluginLocation getLocation();

    public void teleport(PluginLocation loc);

    public double getHealth();

}


text:
<?php

final class PhabricatorFilesManagementCycleWorkflow
  extends PhabricatorFilesManagementWorkflow {

  protected function didConstruct() {
    $this
      ->setName('cycle')
      ->setSynopsis(
        pht('Cycle master key for encrypted files.'))
      ->setArguments(
        array(
          array(
            'name' => 'key',
            'param' => 'keyname',
            'help' => pht('Select a specific storage key to cycle to.'),
          ),
          array(
            'name' => 'all',
            'help' => pht('Change encoding for all files.'),
          ),
          array(
            'name' => 'names',
            'wildcard' => true,
          ),
        ));
  }

  public function execute(PhutilArgumentParser $args) {
    $iterator = $this->buildIterator($args);
    if (!$iterator) {
      throw new PhutilArgumentUsageException(
        pht(
          'Either specify a list of files to cycle, or use --all to cycle '.
          'all files.'));
    }

    $format_map = PhabricatorFileStorageFormat::getAllFormats();
    $engines = PhabricatorFileStorageEngine::loadAllEngines();

    $key_name = $args->getArg('key');

    $failed = array();
    foreach ($iterator as $file) {
      $monogram = $file->getMonogram();

      $engine_key = $file->getStorageEngine();
      $engine = idx($engines, $engine_key);

      if (!$engine) {
        echo tsprintf(
          "%s\n",
          pht(
            '%s: Uses unknown storage engine "%s".',
            $monogram,
            $engine_key));
        $failed[] = $file;
        continue;
      }

      if ($engine->isChunkEngine()) {
        echo tsprintf(
          "%s\n",
          pht(
            '%s: Stored as chunks, declining to cycle directly.',
            $monogram));
        continue;
      }

      $format_key = $file->getStorageFormat();
      if (empty($format_map[$format_key])) {
        echo tsprintf(
          "%s\n",
          pht(
            '%s: Uses unknown storage format "%s".',
            $monogram,
            $format_key));
        $failed[] = $file;
        continue;
      }

      $format = clone $format_map[$format_key];
      $format->setFile($file);

      if (!$format->canCycleMasterKey()) {
        echo tsprintf(
          "%s\n",
          pht(
            '%s: Storage format ("%s") does not support key cycling.',
            $monogram,
            $format->getStorageFormatName()));
        continue;
      }

      echo tsprintf(
        "%s\n",
        pht(
          '%s: Cycling master key.',
          $monogram));

      try {
        if ($key_name) {
          $format->selectMasterKey($key_name);
        }

        $file->cycleMasterStorageKey($format);

        echo tsprintf(
          "%s\n",
          pht('Done.'));
      } catch (Exception $ex) {
        echo tsprintf(
          "%B\n",
          pht('Failed! %s', (string)$ex));
        $failed[] = $file;
      }
    }

    if ($failed) {
      $monograms = mpull($failed, 'getMonogram');

      echo tsprintf(
        "%s\n",
        pht('Failures: %s.', implode(', ', $monograms)));

      return 1;
    }

    return 0;
  }

}


text:
#include "../types.h"

extern char *Scrapt;
extern Atom propriete;
extern Atom type;
extern char *pixmapPath;
extern X11base *x11base;
extern int nbobj;
extern struct XObj *tabxobj[100];
extern int x_fd;

/* Constante pour les type de message envoie entre objets */
/* <0 valeur reserve pour les messages internes */
/* >0 message envoie par l'utilisateur */
#define SingleClic -1
#define DoubleClic -2

#ifdef I18N
void DrawString(Display * dpy, GC gc, Window win, XFontSet fontset, int x, int y, char *str,
#else
void DrawString(Display * dpy, GC gc, Window win, int x, int y, char *str,
#endif
		int strl, unsigned long ForeC, unsigned long HiC,
		unsigned long BackC, int WithRelief);

char *GetMenuTitle(char *str, int id);

void DrawPMenu(struct XObj *xobj, Window WinPop, int h, int StrtOpt);

void SelectMenu(struct XObj *xobj, Window WinPop, int hOpt, int newvalue, int Show);

int CountOption(char *str);

void DrawIconStr(int offset, struct XObj *xobj, int DoRedraw);

void DrawReliefRect(int x, int y, int width, int height, struct XObj *xobj,
   unsigned int LiC, unsigned int ShadC, unsigned int ForeC, int RectIn);

int GetAscFont(XFontStruct * xfont);

int InsertText(struct XObj *xobj, char *str, int SizeStr);

char *GetText(struct XObj *xobj, int End);

void SelectOneTextField(struct XObj *xobj);

void DrawArrowN(struct XObj *xobj, int x, int y, int Press);

void DrawArrowS(struct XObj *xobj, int x, int y, int Press);

void DrawArrowE(struct XObj *xobj, int x, int y, int Press);

void DrawArrowW(struct XObj *xobj, int x, int y, int Press);

int PtInRect(XPoint pt, XRectangle rect);

void Wait(int t);

int IsItDoubleClic(struct XObj *xobj);


text:
import _ from 'lodash';

import { PICK_HERO, UNPICK_HERO, CHANGE_TURN } from '../actions/index';
import { sides } from '../data/data.js';

var default_state = {
    turn: sides[0],
    pick: ""
}

sides.map((side) => default_state[side] = []);

function createPickHeroState(state, action) {
    var pick_hero = action.payload;
    var turn = state.turn;

    var hero_exist = false;
    for (var i = 0; i < sides.length; i++) {
        if (_.find(state[sides[i]], (o) => o == pick_hero)) {
            hero_exist = true;
            break;
        }
    }

    var new_state = _.clone(state);
    new_state.pick = pick_hero;

    if (!hero_exist && state[turn].length < 5) {
        new_state[turn] = [...state[turn], pick_hero];
    }

    return new_state;
}

function createUnpickHeroState(state, action) {
    var unpick_hero = action.payload;
    var turn = state.turn;

    var new_state = _.clone(state);
    new_state[turn] = new_state[turn].filter(item => item != unpick_hero);

    return new_state;
}

export default function (state = default_state, action) {
    switch (action.type) {
        case PICK_HERO:
            return createPickHeroState(state, action);
        case UNPICK_HERO:
            return createUnpickHeroState(state, action);
        case CHANGE_TURN:
            var new_state = _.clone(state);
            new_state.turn = action.payload;
            return new_state;
    }

    return state;
}


text:
<?php

namespace Market\SymfonyBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Market\SymfonyBundle\Entity\Addresses;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('MarketSymfonyBundle:Default:index.html.twig', array('name' => $name));
    }

    public function newAction(Request $request)
    {
    	$address = new Addresses();

        if(!isset($_POST['form']['name'])){
        	$address->setName('Write a blog post');
        	$address->setDescription('Write a blog description');
    	}

        $form = $this->createFormBuilder($address)
            ->add('name', 'text')
            ->add('description', 'text')
            ->add('save', 'submit')
            ->add('saveAndAdd', 'submit')
            ->getForm();
        if(isset($_POST['form']['name'])){
        	$address->setName($_POST['form']['name']);
        	$address->setDescription($_POST['form']['description']);

        	$em = $this->getDoctrine()->getManager();

        	//$em->persist($address);
			//$em->flush();
        }

        $form->handleRequest($request);

        if ($form->isValid()) {

        	$nextAction = $form->get('saveAndAdd')->isClicked()
        	//var_dump($nextAction);exit();
            ? 'You have pressed the "saveAndAdd" button!'
            : '"Save" button has been pressed!';var_dump($nextAction);exit();

        return $this->render('MarketSymfonyBundle:Default:index.html.twig', array('name' => 'Task succeeded!'));exit();
    }

        return $this->render('MarketSymfonyBundle:Default:new.html.twig', array(
            'form' => $form->createView(),
        ));
    }
}


text:
@implementation NSBundle (HUPicker)

+ (instancetype)hu_bundle {
    static NSBundle *bundle = nil;
    if (bundle == nil) {
        NSBundle *podBundle = [NSBundle bundleForClass:[HUImagePickerViewController class]];

        bundle = [NSBundle bundleWithPath:[podBundle pathForResource:@"HUPhotoPicker" ofType:@"bundle"]];
    }
    return bundle;
}

+ (UIImage *)hu_imageNamed:(NSString *)name {
    return [UIImage imageNamed:name inBundle:[self hu_bundle] compatibleWithTraitCollection:nil];
}

@end


text:
package user

import (
	"github.com/Unknwon/com"

	api "github.com/gogits/go-gogs-client"

	"github.com/gogits/gogs/models"
	"github.com/gogits/gogs/modules/middleware"
)

// https://github.com/gogits/go-gogs-client/wiki/Users#search-users
func Search(ctx *middleware.Context) {
	opt := models.SearchOption{
		Keyword: ctx.Query("q"),
		Limit:   com.StrTo(ctx.Query("limit")).MustInt(),
	}
	if opt.Limit == 0 {
		opt.Limit = 10
	}

	us, err := models.SearchUserByName(opt)
	if err != nil {
		ctx.JSON(500, map[string]interface{}{
			"ok":    false,
			"error": err.Error(),
		})
		return
	}

	results := make([]*api.User, len(us))
	for i := range us {
		results[i] = &api.User{
			ID:        us[i].Id,
			UserName:  us[i].Name,
			AvatarUrl: us[i].AvatarLink(),
			FullName:  us[i].FullName,
		}
		if ctx.IsSigned {
			results[i].Email = us[i].Email
		}
	}

	ctx.JSON(200, map[string]interface{}{
		"ok":   true,
		"data": results,
	})
}

// https://github.com/gogits/go-gogs-client/wiki/Users#get-a-single-user
func GetInfo(ctx *middleware.Context) {
	u, err := models.GetUserByName(ctx.Params(":username"))
	if err != nil {
		if models.IsErrUserNotExist(err) {
			ctx.Error(404)
		} else {
			ctx.APIError(500, "GetUserByName", err)
		}
		return
	}

	// Hide user e-mail when API caller isn't signed in.
	if !ctx.IsSigned {
		u.Email = ""
	}
	ctx.JSON(200, &api.User{u.Id, u.Name, u.FullName, u.Email, u.AvatarLink()})
}


text:
"""Batch sim comparison module.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import functools
import importlib

from makani.analysis.util.simdata_analysis import risk
import numpy as np
from scipy import stats
from scipy.spatial.distance import euclidean

CSV_DELIMITER = ';'

def get_score_comparison(prior_score, post_score, score_thr=0.999,
                         p_val_thr=0.05):
  """Compare two scores.

  Args:
    prior_score: VariableData object with the prior score.
    post_score: VariableData object with the posterior score.
    score_thr: Score threshold at which to evaluate the probabilities.
    p_val_thr: P-value threshold.

  Returns:
    Dictionary with the comparison result.
  """
  ks, p_val = stats.ks_2samp(prior_score.data, post_score.data)
  test_result = p_val < p_val_thr

  # Get prob above threshold
  prior_prob = prior_score.prob_above(score_thr).mean
  post_prob = post_score.prob_above(score_thr).mean

  # Risk evaluation.
  # Severity takes values in 1..5 (5 levels, see risk.py).
  # Here sometimes the severity takes a value of 0 to indicate no
  # severity at all, going against the standard. The idea is that if
  # a score has no severity, then it should not be a score.
  # We translate a severity of 0 into the standard lowest severity
  # level of 1.
  prior_severity = prior_score.variable_info['severity']
  if prior_severity == 0:
    prior_severity = 1
  post_severity = post_score.variable_info['severity']
  if post_severity == 0:
    post_severity = 1
  prior_risk_rank = risk.evaluate_risk(prior_prob, prior_severity)['rank']
  post_risk_rank = risk.evaluate_risk(post_prob, post_severity)['rank']

  # Append data
  return {'prior_table_idx': prior_score.table_info['index'],
          'post_table_idx': post_score.table_info['index'],
          'prior_score_idx': prior_score.variable_info['index'],
          'post_score_idx': post_score.variable_info['index'],
          'prior_score': prior_score.variable_info['name'],
          'post_score': post_score.variable_info['name'],
          'prior_table': prior_score.table_info['title'],
          'post_table': post_score.table_info['title'],
          'ks': ks,
          'p_val': p_val,
          'test_result': test_result,
          'prior_prob': prior_prob,
          'post_prob': post_prob,
          'delta_prob': post_prob - prior_prob,
          'prior_severity': prior_score.variable_info['severity'],
          'post_severity': post_score.variable_info['severity'],
          'prior_risk_rank': prior_risk_rank,
          'post_risk_rank': post_risk_rank,
          'delta_rank': post_risk_rank - prior_risk_rank}

def get_simdata_comparison(prior_simdata, post_simdata, table, score_thr=0.999,
                           p_val_thr=0.05):
  """Compares all scores in a table.

  Args:
    prior_simdata: SimData object with the prior data.
    post_simdata: SimData object with the posterior data.
    table: Table from which to evaluate the scores.
    score_thr: Score threshold at which to evaluate the probabilities.
    p_val_thr: P-value threshold.

  Returns:
    List of scores that are statistically different, based on the P-value.
  """
  table_dict = post_simdata.get_table_info(table, exact=True)
  if table_dict is None:
    return []

  table = table_dict['title']
  prior_score_dict = prior_simdata.get_all_score_data(table, exact=True)
  post_score_dict = post_simdata.get_all_score_data(table, exact=True)

  this_table_list = []
  for score in prior_simdata.get_score_list():
    if post_simdata.find_score(score, exact=True) is None:
      continue

    prior_score = prior_score_dict[score]
    post_score = post_score_dict[score]
    comparison = get_score_comparison(prior_score, post_score,
                                      score_thr=score_thr, p_val_thr=p_val_thr)
    if comparison['test_result']:
      # Append data
      this_table_list.append(comparison)

  return this_table_list

def compare_simulation_data(prior_simdata, post_simdata, output_file,
                            score_thr=0.999, p_val_thr=0.05,
                            use_concurrency=False, ncores=None):
  """Compares the data in two SimData objects and outputs data in CSV format.

  For concurrent evaluation this function relies in the library 'pathos':
  https://github.com/uqfoundation/pathos

  Args:
      prior_simdata: SimData object with prior (before) data.
      post_simdata: SimData object with post (after) data.
      output_file: Name of the CSV file where to output the data.
      score_thr: Float indicating the score threshold for probability
          commputation.
      p_val_thr: P-value threshold for Kolmogorov-Smirnov test (defaults to 5%).
      use_concurrency: Boolean indicating whether to use concurrency to
          speed up the computation.
      ncores: Integer with the number of cores to use for concurrent
          computation. If None, the number of cores is 80% of the
          available cores.
  """
  if use_concurrency:
    try:
      pathos = importlib.import_module('pathos.multiprocessing')
    except ImportError:
      print('Pathos library not installed. Get it here:')
      print('  https://github.com/uqfoundation/pathos.')
      use_concurrency = False

  if use_concurrency:
    cpucount = pathos.cpu_count()
    if ncores is None:
      ncpus = int(np.floor(cpucount*0.8))
    else:
      if not (ncores >= 1 and ncores <= cpucount):
        print('ncores must be between 1 and {0}.'.format(cpucount))
        return
      ncpus = int(ncores)

    print('Using {0} cores (out of {1}).'.format(ncpus, cpucount))
    pool = pathos.ProcessingPool(ncpus)
    try:
      pool.restart()  # Need to restart if the pool is still active.
    except AssertionError:
      pass

  else:
    print('Running without concurrency.')
    ncpus = 1

  ntables = prior_simdata.num_tables
  tablelist = prior_simdata.get_table_list()

  print('Comparing simulations...')
  result_list = []
  report_target = 0.1

  if ncpus > 1:
    # imap() returns data ordered.
    for table_comp in pool.imap(functools.partial(get_simdata_comparison,
                                                  prior_simdata,
                                                  post_simdata,
                                                  score_thr=score_thr,
                                                  p_val_thr=p_val_thr),
                                tablelist):
      result_list.append(table_comp)
      if len(result_list)/ntables > report_target:
        print('  {0:.0f}% completed.'.format(100.*report_target))
        report_target += 0.1

      pool.close()
      pool.join()
      pool.terminate()

  else:
    for table in tablelist:
      result_list.append(get_simdata_comparison(prior_simdata,
                                                post_simdata,
                                                table,
                                                score_thr,
                                                p_val_thr))
      if len(result_list)/ntables > report_target:
        print('  {0:.0f}% completed.'.format(100.*report_target))
        report_target += 0.1

  print('...done.')

    # Go over results and save to CSV
  columns_to_save = ['prior_score',
                     'prior_prob',
                     'post_prob',
                     'delta_prob',
                     'ks',
                     'p_val',
                     'prior_severity',
                     'post_severity',
                     'prior_risk_rank',
                     'post_risk_rank',
                     'delta_rank']

  print('Writing file {0}...'.format(output_file))
  with open(output_file, 'w') as fp:
    for ntable, table in enumerate(tablelist):
      score_comp_list = result_list[ntable]

      fp.write('Table #{0}: {1}\n\n'.format(ntable, table))
      if not score_comp_list:
        continue
      for col in columns_to_save:
        fp.write(CSV_DELIMITER + '{0}'.format(col))
      fp.write('\n')

      for score_comp in score_comp_list:
        for col in columns_to_save:
          fp.write(CSV_DELIMITER + '{0}'.format(score_comp[col]))
        fp.write('\n')
      fp.write('\n')
  print('...done.')

def find_closest_sample(simdata, table, datapoint, dist=None, weights=None,
                        **dist_kws):
  """Finds the closest sample in simdata to a datapoint.

  Args:
      simdata: SimData object.
      table: Table from which to evaluate the scores.
      datapoint: Dictionary with scores as keys, and score values as entries.
      dist: Distance function to use from scipy.spatial.distance. If None, the
          Euclidean distance is used.
      weights: Array of weights to be used in distance computation.
      **dist_kws: Additional keyword arguments for the distance function.

  Returns:
      Dictionary with information identifying the sample closest to datapont.
      Keywords:
          min_dist: Minimum distance.
          min_dist_idx: Index of the sample with the minimum distance.
          min_dist_job_id: Job_id of the sample with the minimum distance.
          min_dist_file: File containing the sample with the minimum distance.
  """
  if dist is None:
    dist = euclidean

  # Build the datapoint
  score_indexes = []
  datapoint_array = []
  weights_array = np.array([])
  for i, score_name in enumerate(datapoint):
    if (simdata.find_score(score_name, exact=False, verbose=True) is None or
        np.isnan(datapoint[score_name])):
      print('Skipping score {0}'.format(score_name))
      continue
    score_indexes.append(simdata.get_score_info(score_name,
                                                verbose=False)['index'])
    datapoint_array.append(datapoint[score_name])
    if weights is not None:
      weights_array = np.append(weights_array, weights[i])

  datapoint_array = np.array(datapoint_array)

  # Get the all distances to the datapoint
  table_df = simdata.get_all_table_data(table)
  crash_col = 'score_{0}'.format(simdata.get_score_info(
      'Crash indicator')['index'])
  all_scores = table_df.drop(['job_id', 'folder', crash_col],
                             axis=1).as_matrix()
  dist_store = np.array([])
  for sample in all_scores:
    sample_reduced = sample[score_indexes]
    non_nan_idxs = np.argwhere(~np.isnan(sample_reduced))
    if weights_array.size > 0:
      weights_filtered = weights_array[non_nan_idxs]
    else:
      weights_filtered = None

    distance = dist(sample_reduced[non_nan_idxs],
                    datapoint_array[non_nan_idxs],
                    w=weights_filtered,
                    **dist_kws)
    dist_store = np.append(dist_store, distance)

  # Populate output dictionary
  min_dist = np.min(dist_store)
  min_dist_idx = np.argmin(dist_store)
  min_dist_job_id = table_df.iloc[min_dist_idx]['job_id']
  min_dist_folder = table_df.iloc[min_dist_idx]['folder']

  return {'min_dist': min_dist,
          'min_dist_idx': min_dist_idx,
          'min_dist_job_id': min_dist_job_id,
          'min_dist_folder': min_dist_folder}