text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2015 Couchbase, 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.
 */
#pragma once

#include <relaxed_atomic.h>

#include <memcached/engine_error.h>

#include <cstdint>
#include <mutex>
#include <vector>

/**
 * Stats stored per-thread.
 */
struct thread_stats {
    thread_stats() {
        reset();
    }

    void reset() {
        cmd_get = 0;
        get_hits = 0;
        get_misses = 0;
        cmd_set = 0;
        delete_hits = 0;
        cas_hits = 0;
        cas_badval = 0;
        delete_misses = 0;
        incr_misses = 0;
        decr_misses = 0;
        incr_hits = 0;
        decr_hits = 0;
        cas_misses = 0;
        bytes_written = 0;
        bytes_read = 0;
        cmd_flush = 0;
        conn_yields = 0;
        auth_cmds = 0;
        auth_errors = 0;
        cmd_subdoc_lookup = 0;
        cmd_subdoc_mutation = 0;
        cmd_lock = 0;
        lock_errors = 0;

        bytes_subdoc_lookup_total = 0;
        bytes_subdoc_lookup_extracted = 0;
        bytes_subdoc_mutation_total = 0;
        bytes_subdoc_mutation_inserted = 0;

        iovused_high_watermark = 0;
        msgused_high_watermark = 0;
    }

    thread_stats & operator += (const thread_stats &other) {
        cmd_get += other.cmd_get;
        get_misses += other.get_misses;
        cmd_set += other.cmd_set;
        get_hits += other.get_hits;
        delete_hits += other.delete_hits;
        cas_hits += other.cas_hits;
        cas_badval += other.cas_badval;
        delete_misses += other.delete_misses;
        decr_misses += other.decr_misses;
        incr_misses += other.incr_misses;
        decr_hits += other.decr_hits;
        incr_hits += other.incr_hits;
        cas_misses += other.cas_misses;
        bytes_read += other.bytes_read;
        bytes_written += other.bytes_written;
        cmd_flush += other.cmd_flush;
        conn_yields += other.conn_yields;
        auth_cmds += other.auth_cmds;
        auth_errors += other.auth_errors;
        cmd_subdoc_lookup += other.cmd_subdoc_lookup;
        cmd_subdoc_mutation += other.cmd_subdoc_mutation;

        cmd_lock += other.cmd_lock;
        lock_errors += other.lock_errors;

        bytes_subdoc_lookup_total += other.bytes_subdoc_lookup_total;
        bytes_subdoc_lookup_extracted += other.bytes_subdoc_lookup_extracted;
        bytes_subdoc_mutation_total += other.bytes_subdoc_mutation_total;
        bytes_subdoc_mutation_inserted += other.bytes_subdoc_mutation_inserted;

        iovused_high_watermark.setIfGreater(other.iovused_high_watermark);
        msgused_high_watermark.setIfGreater(other.msgused_high_watermark);

        return *this;
    }

    void aggregate(const std::vector<thread_stats>& thread_stats) {
        for (auto& ii : thread_stats) {
            *this += ii;
        }
    }

    cb::RelaxedAtomic<uint64_t> cmd_get;
    cb::RelaxedAtomic<uint64_t> get_hits;
    cb::RelaxedAtomic<uint64_t> get_misses;
    cb::RelaxedAtomic<uint64_t> cmd_set;
    cb::RelaxedAtomic<uint64_t> delete_hits;
    cb::RelaxedAtomic<uint64_t> cas_hits;
    cb::RelaxedAtomic<uint64_t> cas_badval;
    cb::RelaxedAtomic<uint64_t> delete_misses;
    cb::RelaxedAtomic<uint64_t> incr_misses;
    cb::RelaxedAtomic<uint64_t> decr_misses;
    cb::RelaxedAtomic<uint64_t> incr_hits;
    cb::RelaxedAtomic<uint64_t> decr_hits;
    cb::RelaxedAtomic<uint64_t> cas_misses;
    cb::RelaxedAtomic<uint64_t> bytes_read;
    cb::RelaxedAtomic<uint64_t> bytes_written;
    cb::RelaxedAtomic<uint64_t> cmd_flush;
    cb::RelaxedAtomic<uint64_t>
            conn_yields; /* # of yields for connections (-R option)*/
    cb::RelaxedAtomic<uint64_t> auth_cmds;
    cb::RelaxedAtomic<uint64_t> auth_errors;
    /* # of subdoc lookup commands (GET/EXISTS/MULTI_LOOKUP) */
    cb::RelaxedAtomic<uint64_t> cmd_subdoc_lookup;
    /* # of subdoc mutation commands */
    cb::RelaxedAtomic<uint64_t> cmd_subdoc_mutation;

    /** # of lock commands */
    cb::RelaxedAtomic<uint64_t> cmd_lock;

    /** # of times an operation failed due to accessing a locked item */
    cb::RelaxedAtomic<uint64_t> lock_errors;

    /* # of bytes in the complete document which subdoc lookups searched
       within. Compare with 'bytes_subdoc_lookup_extracted' */
    cb::RelaxedAtomic<uint64_t> bytes_subdoc_lookup_total;
    /* # of bytes extracted during a subdoc lookup operation and sent back to
      the client. */
    cb::RelaxedAtomic<uint64_t> bytes_subdoc_lookup_extracted;

    /* # of bytes in the complete document which subdoc mutations updated.
       Compare with 'bytes_subdoc_mutation_inserted' */
    cb::RelaxedAtomic<uint64_t> bytes_subdoc_mutation_total;
    /* # of bytes inserted during a subdoc mutation operation (which were
       received from the client). */
    cb::RelaxedAtomic<uint64_t> bytes_subdoc_mutation_inserted;

    /* Highest value iovsize has got to */
    cb::RelaxedAtomic<int> iovused_high_watermark;
    /* High value Connection->msgused has got to */
    cb::RelaxedAtomic<int> msgused_high_watermark;
};

/**
 * Global stats.
 */
struct stats {
    /** The current number of connections to the server */
    std::atomic<unsigned int> curr_conns;

    size_t getCurrConnections() const {
        return curr_conns.load(std::memory_order::memory_order_consume);
    }

    /// The number of system connections
    std::atomic<unsigned int> system_conns;

    size_t getSystemConnections() const {
        return system_conns.load(std::memory_order::memory_order_consume);
    }

    size_t getUserConnections() const {
        return getCurrConnections() - getSystemConnections();
    }

    /** The total number of connections to the server since start (or reset) */
    cb::RelaxedAtomic<unsigned int> total_conns;

    /** The current number of allocated connection objects */
    cb::RelaxedAtomic<unsigned int> conn_structs;

    /** The number of times I reject a client */
    cb::RelaxedAtomic<uint64_t> rejected_conns;
};

extern stats stats;

class Connection;
struct thread_stats* get_thread_stats(Connection* c);

class StatCollector;
class Bucket;
ENGINE_ERROR_CODE server_stats(StatCollector& collector, const Bucket& bucket);

/*
 *  Macros for managing statistics inside memcached
 */

/* The item must always be called "it" */
#define SLAB_GUTS(conn, thread_stats, slab_op, thread_op) \
    thread_stats->slab_op++;

#define THREAD_GUTS(conn, thread_stats, slab_op, thread_op) \
    thread_stats->thread_op++;

#define THREAD_GUTS2(conn, thread_stats, slab_op, thread_op) \
    thread_stats->slab_op++; \
    thread_stats->thread_op++;

#define SLAB_THREAD_GUTS(conn, thread_stats, slab_op, thread_op) \
    SLAB_GUTS(conn, thread_stats, slab_op, thread_op) \
    THREAD_GUTS(conn, thread_stats, slab_op, thread_op)

#define STATS_INCR1(GUTS, conn, slab_op, thread_op) { \
    struct thread_stats *thread_stats = get_thread_stats(conn); \
    GUTS(conn, thread_stats, slab_op, thread_op); \
}

#define STATS_INCR(conn, op) \
    STATS_INCR1(THREAD_GUTS, conn, op, op)

#define SLAB_INCR(conn, op) \
    STATS_INCR1(SLAB_GUTS, conn, op, op)

#define STATS_TWO(conn, slab_op, thread_op) \
    STATS_INCR1(THREAD_GUTS2, conn, slab_op, thread_op)

#define SLAB_TWO(conn, slab_op, thread_op) \
    STATS_INCR1(SLAB_THREAD_GUTS, conn, slab_op, thread_op)

#define STATS_HIT(conn, op) \
    SLAB_TWO(conn, op##_hits, cmd_##op)

#define STATS_MISS(conn, op) \
    STATS_TWO(conn, op##_misses, cmd_##op)

/*
 * Set the statistic to the maximum of the current value, and the specified
 * value.
 */
#define STATS_MAX(conn, op, value) get_thread_stats(conn)->op.setIfGreater(value);

extern std::mutex stats_mutex;
extern char reset_stats_time[80];

class Cookie;
void stats_reset(Cookie& cookie);


text:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace MyFirstMvcApp.Data
{
    public class BlogPosts
    {
        public int Id { get; set; }

        public IdentityUser User { get; set; }

        public string UserId { get; set; }
    }

    public class ApplicationDbContext : IdentityDbContext
    {
        public DbSet<BlogPosts> Posts { get; set; }
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.androidpn.demoapp;

import org.androidpn.client.NotificationService;
import org.androidpn.client.ServiceManager;
import org.androidpn.client.XmppManager;
import org.jivesoftware.smack.packet.Message;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

/**
 * This is an androidpn client demo application.
 *
 * @author Sehwan Noh (devnoh@gmail.com)
 */
public class DemoAppActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d("DemoAppActivity", "onCreate()...");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Settings
        Button okButton = (Button) findViewById(R.id.btn_settings);
        okButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
//                ServiceManager.viewNotificationSettings(DemoAppActivity.this);
            	XmppManager xmppManager = ServiceManager.getXmppManager();
            	if(xmppManager!=null)
            	{
            		xmppManager.submitSendTask();
            	}
            }
        });

        // Start the service
        ServiceManager serviceManager = new ServiceManager(this);
        serviceManager.setNotificationIcon(R.drawable.notification);
        serviceManager.startService();
    }

}


text:
using System;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using Metrics.Core;
using Metrics.Logging;

namespace Metrics.PerfCounters
{
    internal static class PerformanceCounters
    {
        private static readonly ILog log = LogProvider.GetCurrentClassLogger();

        private const string TotalInstance = "_Total";
        private const string GlobalInstance = "_Global_";

        private const string Exceptions = ".NET CLR Exceptions";
        private const string Memory = ".NET CLR Memory";
        private const string LocksAndThreads = ".NET CLR LocksAndThreads";
        private const string Networking = ".NET CLR Networking 4.0.0.0";

        internal static void RegisterSystemCounters(MetricsContext context)
        {
            context.Register("Available RAM", Unit.MegaBytes, "Memory", "Available MBytes", tags: "memory");
            context.Register("Free System Page Table Entries", Unit.Custom("entries"), "Memory", "Free System Page Table Entries", tags: "memory");
            context.Register("Pages Input/sec", Unit.Custom("pages/s"), "Memory", "Pages Input/sec", tags: "memory");
            context.Register("Pages/sec", Unit.Custom("pages/s"), "Memory", "Pages/sec", tags: "memory");
            context.Register("Pool Nonpaged MBytes", Unit.MegaBytes, "Memory", "Pool Nonpaged Bytes", derivate: v => v / (1024 * 1024.0), tags: "memory");
            context.Register("Pool Paged MBytes", Unit.MegaBytes, "Memory", "Pool Paged Bytes", derivate: v => v / (1024 * 1024.0), tags: "memory");

            context.Register("CPU Usage", Unit.Custom("%"), "Processor", "% Processor Time", TotalInstance, tags: "cpu");
            context.Register("Interrupts / sec", Unit.Custom("interrupts/s"), "Processor", "Interrupts/sec", TotalInstance, tags: "cpu");
            context.Register("% Interrupt time", Unit.Custom("%"), "Processor", "% Interrupt Time", TotalInstance, tags: "cpu");
            context.Register("% User Timer", Unit.Custom("%"), "Processor", "% User Time", TotalInstance, tags: "cpu");
            context.Register("% Privileged Timer", Unit.Custom("%"), "Processor", "% Privileged Time", TotalInstance, tags: "cpu");
            context.Register("% DPC Time", Unit.Custom("%"), "Processor", "% DPC Time", TotalInstance, tags: "cpu");

            context.Register("Logical Disk Avg. sec/Read", Unit.Custom("ms"), "LogicalDisk", "Avg. Disk sec/Read", TotalInstance, v => v * 1024.0, tags: "disk");
            context.Register("Logical Disk Avg. sec/Write", Unit.Custom("ms"), "LogicalDisk", "Avg. Disk sec/Write", TotalInstance, v => v * 1024.0, tags: "disk");
            context.Register("Logical Disk Transfers/sec", Unit.Custom("Transfers"), "LogicalDisk", "Disk Transfers/sec", TotalInstance, tags: "disk");
            context.Register("Logical Disk Writes/sec", Unit.Custom("kb/s"), "LogicalDisk", "Disk Reads/sec", TotalInstance, f => f / 1024.0, tags: "disk");
            context.Register("Logical Disk Reads/sec", Unit.Custom("kb/s"), "LogicalDisk", "Disk Writes/sec", TotalInstance, f => f / 1024.0, tags: "disk");

            context.Register("Physical Disk Avg. sec/Read", Unit.Custom("ms"), "PhysicalDisk", "Avg. Disk sec/Read", TotalInstance, v => v * 1024.0, tags: "disk");
            context.Register("Physical Disk Avg. sec/Write", Unit.Custom("ms"), "PhysicalDisk", "Avg. Disk sec/Write", TotalInstance, v => v * 1024.0, tags: "disk");
            context.Register("Physical Disk Transfers/sec", Unit.Custom("Transfers"), "PhysicalDisk", "Disk Transfers/sec", TotalInstance, tags: "disk");
            context.Register("Physical Disk Writes/sec", Unit.Custom("kb/s"), "PhysicalDisk", "Disk Reads/sec", TotalInstance, f => f / 1024.0, tags: "disk");
            context.Register("Physical Disk Reads/sec", Unit.Custom("kb/s"), "PhysicalDisk", "Disk Writes/sec", TotalInstance, f => f / 1024.0, tags: "disk");
        }

        internal static void RegisterAppCounters(MetricsContext context)
        {
            var app = Process.GetCurrentProcess().ProcessName;

            context.Register("Process CPU Usage", Unit.Percent, "Process", "% Processor Time", app, derivate: v => v / Environment.ProcessorCount, tags: "cpu");
            context.Register("Process User Time", Unit.Percent, "Process", "% User Time", app, derivate: v => v / Environment.ProcessorCount, tags: "cpu");
            context.Register("Process Privileged Time", Unit.Percent, "Process", "% Privileged Time", app, derivate: v => v / Environment.ProcessorCount, tags: "cpu");

            context.Register("Private MBytes", Unit.MegaBytes, "Process", "Private Bytes", app, derivate: v => v / (1024 * 1024.0), tags: "memory");
            context.Register("Working Set", Unit.MegaBytes, "Process", "Working Set", app, derivate: v => v / (1024 * 1024.0), tags: "memory");

            context.Register("Mb in all Heaps", Unit.MegaBytes, Memory, "# Bytes in all Heaps", app, v => v / (1024 * 1024.0), tags: "memory");
            context.Register("Gen 0 heap size", Unit.MegaBytes, Memory, "Gen 0 heap size", app, v => v / (1024 * 1024.0), tags: "memory");
            context.Register("Gen 1 heap size", Unit.MegaBytes, Memory, "Gen 1 heap size", app, v => v / (1024 * 1024.0), tags: "memory");
            context.Register("Gen 2 heap size", Unit.MegaBytes, Memory, "Gen 2 heap size", app, v => v / (1024 * 1024.0), tags: "memory");
            context.Register("Large Object Heap size", Unit.MegaBytes, Memory, "Large Object Heap size", app, v => v / (1024 * 1024.0), tags: "memory");
            context.Register("Allocated Bytes/second", Unit.KiloBytes, Memory, "Allocated Bytes/sec", app, v => v / 1024.0, tags: "memory");

            context.Register("Time in GC", Unit.Custom("%"), Memory, "% Time in GC", app, tags: "memory");
            context.Register("Pinned Objects", Unit.Custom("Objects"), Memory, "# of Pinned Objects", app, tags: "memory");

            context.Register("Total Exceptions", Unit.Custom("Exceptions"), Exceptions, "# of Exceps Thrown", app, tags: "exceptions");
            context.Register("Exceptions Thrown / Sec", Unit.Custom("Exceptions"), Exceptions, "# of Exceps Thrown / Sec", app, tags: "exceptions");
            context.Register("Except Filters / Sec", Unit.Custom("Filters"), Exceptions, "# of Filters / Sec", app, tags: "exceptions");
            context.Register("Finallys / Sec", Unit.Custom("Finallys"), Exceptions, "# of Finallys / Sec", app, tags: "exceptions");
            context.Register("Throw to Catch Depth / Sec", Unit.Custom("Stack Frames"), Exceptions, "Throw to Catch Depth / Sec", app, tags: "exceptions");

            context.Register("Logical Threads", Unit.Threads, LocksAndThreads, "# of current logical Threads", app, tags: "threads");
            context.Register("Physical Threads", Unit.Threads, LocksAndThreads, "# of current physical Threads", app, tags: "threads");
            context.Register("Contention Rate / Sec", Unit.Custom("Attempts"), LocksAndThreads, "Contention Rate / Sec", app, tags: "threads");
            context.Register("Total Contentions", Unit.Custom("Attempts"), LocksAndThreads, "Total # of Contentions", app, tags: "threads");
            context.Register("Queue Length / sec", Unit.Threads, LocksAndThreads, "Queue Length / sec", app, tags: "threads");

            context.Register("IO Data Operations/sec", Unit.Custom("IOPS"), "Process", "IO Data Operations/sec", app, tags: "disk");
            context.Register("IO Other Operations/sec", Unit.Custom("IOPS"), "Process", "IO Other Operations/sec", app, tags: "disk");

            ThreadPoolMetrics.RegisterThreadPoolGauges(context);
        }

        private static void Register(this MetricsContext context, string name, Unit unit,
            string category, string counter, string instance = null,
            Func<double, double> derivate = null,
            MetricTags tags = default(MetricTags))
        {
            try
            {
                WrappedRegister(context, name, unit, category, counter, instance, derivate, tags);
            }
            catch (UnauthorizedAccessException x)
            {
                var message = "Error reading performance counter data. The application is currently running as user " + GetIdentity() +
                   ". Make sure the user has access to the performance counters. The user needs to be either Admin or belong to Performance Monitor user group.";
                MetricsErrorHandler.Handle(x, message);
            }
            catch (Exception x)
            {
                var message = "Error reading performance counter data. The application is currently running as user " + GetIdentity() +
                   ". Make sure the user has access to the performance counters. The user needs to be either Admin or belong to Performance Monitor user group.";
                MetricsErrorHandler.Handle(x, message);
            }
        }

        private static string GetIdentity()
        {
            try
            {
                return WindowsIdentity.GetCurrent().Name;
            }
            catch (Exception x)
            {
                return "[Unknown user | " + x.Message + " ]";
            }
        }

        private static void WrappedRegister(MetricsContext context, string name, Unit unit,
            string category, string counter, string instance = null,
            Func<double, double> derivate = null,
            MetricTags tags = default(MetricTags))
        {
            log.Debug(() => string.Format("Registering performance counter [{0}] in category [{1}] for instance [{2}]", counter, category, instance ?? "none"));

            if (PerformanceCounterCategory.Exists(category))
            {
                if (instance == null || PerformanceCounterCategory.InstanceExists(instance, category))
                {
                    if (PerformanceCounterCategory.CounterExists(counter, category))
                    {
                        var counterTags = new MetricTags(tags.Tags.Concat(new[] { "PerfCounter" }));
                        if (derivate == null)
                        {
                            context.Advanced.Gauge(name, () => new PerformanceCounterGauge(category, counter, instance), unit, counterTags);
                        }
                        else
                        {
                            context.Advanced.Gauge(name, () => new DerivedGauge(new PerformanceCounterGauge(category, counter, instance), derivate), unit, counterTags);
                        }
                        return;
                    }
                }
            }

            log.ErrorFormat("Performance counter does not exist [{0}] in category [{1}] for instance [{2}]", counter, category, instance ?? "none");
        }
    }
}


text:
#import <XCTest/XCTest.h>

#import "FBIntegrationTestCase.h"
#import "FBApplication.h"
#import "XCUIDevice+FBHelpers.h"

@interface XCUIDeviceHelperTests : FBIntegrationTestCase
@end

@implementation XCUIDeviceHelperTests

- (void)setUp
{
  [super setUp];
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    [self launchApplication];
  });
}

- (void)testScreenshot
{
  XCTAssertNotNil([UIImage imageWithData:[XCUIDevice sharedDevice].fb_screenshot]);
}

- (void)testWifiAddress
{
  NSString *adderss = [XCUIDevice sharedDevice].fb_wifiIPAddress;
  if (!adderss) {
    return;
  }
  NSRange range = [adderss rangeOfString:@"^([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})" options:NSRegularExpressionSearch];
  XCTAssertTrue(range.location != NSNotFound);
}

- (void)testGoToHomeScreen
{
  NSError *error;
  XCTAssertTrue([[XCUIDevice sharedDevice] fb_goToHomescreenWithError:&error]);
  XCTAssertNil(error);
  XCTAssertTrue([FBApplication fb_activeApplication].icons[@"Safari"].exists);
}

@end


text:
from __future__ import (unicode_literals, absolute_import,
                        division, print_function)

from django.conf.urls import patterns, url

from snisi_web.url_regexp import (RGXP_ENTITY, RGXP_PERIOD,
                                  RGXP_PERIODS, RGXP_RECEIPT)

urlpatterns = patterns(
    '',

    url(r'^/mission/{receipt}?$'
        .format(receipt=RGXP_RECEIPT),
        'snisi_cataract.views.cataract_mission_viewer',
        name='cataract_mission'),

    url(r'^/view/{entity}/{period}/?$'
        .format(entity=RGXP_ENTITY, period=RGXP_PERIOD),
        'snisi_cataract.views.cataract_mission_browser',
        name='cataract_missions'),
    url(r'^/view/{entity}/?$'
        .format(entity=RGXP_ENTITY),
        'snisi_cataract.views.cataract_mission_browser',
        name='cataract_missions'),
    url(r'^/view/?$',
        'snisi_cataract.views.cataract_mission_browser',
        name='cataract_missions'),

    url(r'^/dashboard/{entity}/{periods}/?$'
        .format(entity=RGXP_ENTITY, periods=RGXP_PERIODS),
        'snisi_cataract.views.cataract_dashboard', name='cataract_dashboard'),
    url(r'^/dashboard/{entity}/?$'
        .format(entity=RGXP_ENTITY),
        'snisi_cataract.views.cataract_dashboard', name='cataract_dashboard'),
    url(r'^/dashboard/?$',
        'snisi_cataract.views.cataract_dashboard', name='cataract_dashboard'),
)


text:
'use strict';

angular
    .module('softvApp')
    .factory('DevolucionAlmacenFactory', function ($http, $q, globalService, $localStorage) {

        var factory = {};
        var paths = {
            GetMUESTRADevolucionAparatosAlmacen: '/Procesos/GetMUESTRADevolucionAparatosAlmacen',
            GetPROCESODevolucionAparatosAlmacen: '/Procesos/GetPROCESODevolucionAparatosAlmacen'
        };

        factory.GetMUESTRADevolucionAparatosAlmacen = function (ObjDevolucion) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = ObjDevolucion;
            console.log(JSON.stringify(Parametros));
            $http.post(globalService.getUrl() + paths.GetMUESTRADevolucionAparatosAlmacen, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetPROCESODevolucionAparatosAlmacen = function (ObjDevolucion) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {
                'CLV_ORDEN': ObjDevolucion.CLV_ORDEN,
                'TIPOAPARATO': ObjDevolucion.TIPOAPARATO,
                'CLV_CABLEMODEM': ObjDevolucion.CLV_CABLEMODEM,
                'MACCABLEMODEM': ObjDevolucion.MACCABLEMODEM,
                'ESTADOAPARATO': ObjDevolucion.ESTADOAPARATO,
                'USUARIO': $localStorage.currentUser.usuario,
                'PROVIENE': ObjDevolucion.PROVIENE,
                'MARCA': ObjDevolucion.MARCA
            };
            console.log(JSON.stringify(Parametros));
            $http.post(globalService.getUrl() + paths.GetPROCESODevolucionAparatosAlmacen, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        return factory;
    });


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Alectoria canariensis Ach.

### Remarks
null


text:
require "formula"

class Httrack < Formula
  homepage "http://www.httrack.com/"
  # Always use mirror.httrack.com when you link to a new version of HTTrack, as
  # link to download.httrack.com will break on next HTTrack update.
  url "http://mirror.httrack.com/historical/httrack-3.48.19.tar.gz"
  sha1 "7df386a248444c599948dbc77ed705b101151ed4"

  def install
    ENV.deparallelize
    system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}"
    system "make install"
    # Don't need Gnome integration
    rm_rf Dir["#{share}/{applications,pixmaps}"]
  end
end


text:
namespace content {

namespace {

struct FetchResult {
  ServiceWorkerStatusCode status;
  ServiceWorkerFetchEventResult result;
  ServiceWorkerResponse response;
  scoped_ptr<storage::BlobDataHandle> blob_data_handle;
};

void RunAndQuit(const base::Closure& closure,
                const base::Closure& quit,
                base::MessageLoopProxy* original_message_loop) {
  closure.Run();
  original_message_loop->PostTask(FROM_HERE, quit);
}

void RunOnIOThread(const base::Closure& closure) {
  base::RunLoop run_loop;
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&RunAndQuit, closure, run_loop.QuitClosure(),
                 base::MessageLoopProxy::current()));
  run_loop.Run();
}

void RunOnIOThread(
    const base::Callback<void(const base::Closure& continuation)>& closure) {
  base::RunLoop run_loop;
  base::Closure quit_on_original_thread =
      base::Bind(base::IgnoreResult(&base::MessageLoopProxy::PostTask),
                 base::MessageLoopProxy::current().get(),
                 FROM_HERE,
                 run_loop.QuitClosure());
  BrowserThread::PostTask(BrowserThread::IO,
                          FROM_HERE,
                          base::Bind(closure, quit_on_original_thread));
  run_loop.Run();
}

void ReceivePrepareResult(bool* is_prepared) {
  *is_prepared = true;
}

base::Closure CreatePrepareReceiver(bool* is_prepared) {
  return base::Bind(&ReceivePrepareResult, is_prepared);
}

// Contrary to the style guide, the output parameter of this function comes
// before input parameters so Bind can be used on it to create a FetchCallback
// to pass to DispatchFetchEvent.
void ReceiveFetchResult(BrowserThread::ID run_quit_thread,
                        const base::Closure& quit,
                        ChromeBlobStorageContext* blob_context,
                        FetchResult* out_result,
                        ServiceWorkerStatusCode actual_status,
                        ServiceWorkerFetchEventResult actual_result,
                        const ServiceWorkerResponse& actual_response) {
  out_result->status = actual_status;
  out_result->result = actual_result;
  out_result->response = actual_response;
  if (!actual_response.blob_uuid.empty()) {
    out_result->blob_data_handle =
        blob_context->context()->GetBlobDataFromUUID(
            actual_response.blob_uuid);
  }
  if (!quit.is_null())
    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, quit);
}

ServiceWorkerVersion::FetchCallback CreateResponseReceiver(
    BrowserThread::ID run_quit_thread,
    const base::Closure& quit,
    ChromeBlobStorageContext* blob_context,
    FetchResult* result) {
  return base::Bind(&ReceiveFetchResult, run_quit_thread, quit,
                    make_scoped_refptr<ChromeBlobStorageContext>(blob_context),
                    result);
}

void ReadResponseBody(std::string* body,
                      storage::BlobDataHandle* blob_data_handle) {
  ASSERT_TRUE(blob_data_handle);
  scoped_ptr<storage::BlobDataSnapshot> data =
      blob_data_handle->CreateSnapshot();
  ASSERT_EQ(1U, data->items().size());
  *body = std::string(data->items()[0]->bytes(), data->items()[0]->length());
}

void ExpectResultAndRun(bool expected,
                        const base::Closure& continuation,
                        bool actual) {
  EXPECT_EQ(expected, actual);
  continuation.Run();
}

class WorkerActivatedObserver
    : public ServiceWorkerContextObserver,
      public base::RefCountedThreadSafe<WorkerActivatedObserver> {
 public:
  explicit WorkerActivatedObserver(ServiceWorkerContextWrapper* context)
      : context_(context) {}
  void Init() {
    RunOnIOThread(base::Bind(&WorkerActivatedObserver::InitOnIOThread, this));
  }
  // ServiceWorkerContextObserver overrides.
  void OnVersionStateChanged(int64 version_id) override {
    DCHECK_CURRENTLY_ON(BrowserThread::IO);
    const ServiceWorkerVersion* version =
        context_->context()->GetLiveVersion(version_id);
    if (version->status() == ServiceWorkerVersion::ACTIVATED) {
      context_->RemoveObserver(this);
      BrowserThread::PostTask(BrowserThread::UI,
                              FROM_HERE,
                              base::Bind(&WorkerActivatedObserver::Quit, this));
    }
  }
  void Wait() { run_loop_.Run(); }

 private:
  friend class base::RefCountedThreadSafe<WorkerActivatedObserver>;
  ~WorkerActivatedObserver() override {}
  void InitOnIOThread() { context_->AddObserver(this); }
  void Quit() { run_loop_.Quit(); }

  base::RunLoop run_loop_;
  ServiceWorkerContextWrapper* context_;
  DISALLOW_COPY_AND_ASSIGN(WorkerActivatedObserver);
};

scoped_ptr<net::test_server::HttpResponse> VerifyServiceWorkerHeaderInRequest(
    const net::test_server::HttpRequest& request) {
  EXPECT_EQ(request.relative_url, "/service_worker/generated_sw.js");
  std::map<std::string, std::string>::const_iterator it =
      request.headers.find("Service-Worker");
  EXPECT_TRUE(it != request.headers.end());
  EXPECT_EQ("script", it->second);

  scoped_ptr<net::test_server::BasicHttpResponse> http_response(
      new net::test_server::BasicHttpResponse());
  http_response->set_content_type("text/javascript");
  return http_response.Pass();
}

// The ImportsBustMemcache test requires that the imported script
// would naturally be cached in blink's memcache, but the embedded
// test server doesn't produce headers that allow the blink's memcache
// to do that. This interceptor injects headers that give the import
// an experiration far in the future.
class LongLivedResourceInterceptor : public net::URLRequestInterceptor {
 public:
  LongLivedResourceInterceptor(const std::string& body)
      : body_(body) {}
  ~LongLivedResourceInterceptor() override {}

  // net::URLRequestInterceptor implementation
  net::URLRequestJob* MaybeInterceptRequest(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate) const override {
    const char kHeaders[] =
        "HTTP/1.1 200 OK\0"
        "Content-Type: text/javascript\0"
        "Expires: Thu, 1 Jan 2100 20:00:00 GMT\0"
        "\0";
    std::string headers(kHeaders, arraysize(kHeaders));
    return new net::URLRequestTestJob(
        request, network_delegate, headers, body_, true);
  }

 private:
  std::string body_;
  DISALLOW_COPY_AND_ASSIGN(LongLivedResourceInterceptor);
};

void CreateLongLivedResourceInterceptors(
    const GURL& worker_url, const GURL& import_url) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  scoped_ptr<net::URLRequestInterceptor> interceptor;

  interceptor.reset(new LongLivedResourceInterceptor(
      "importScripts('long_lived_import.js');"));
  net::URLRequestFilter::GetInstance()->AddUrlInterceptor(
      worker_url, interceptor.Pass());

  interceptor.reset(new LongLivedResourceInterceptor(
      "// the imported script does nothing"));
  net::URLRequestFilter::GetInstance()->AddUrlInterceptor(
      import_url, interceptor.Pass());
}

void CountScriptResources(
    ServiceWorkerContextWrapper* wrapper,
    const GURL& scope,
    int* num_resources) {
  *num_resources = -1;

  std::vector<ServiceWorkerRegistrationInfo> infos =
     wrapper->context()->GetAllLiveRegistrationInfo();
  if (infos.empty())
    return;

  int version_id;
  size_t index = infos.size() - 1;
  if (infos[index].installing_version.version_id !=
      kInvalidServiceWorkerVersionId)
    version_id = infos[index].installing_version.version_id;
  else if (infos[index].waiting_version.version_id !=
           kInvalidServiceWorkerVersionId)
    version_id = infos[1].waiting_version.version_id;
  else if (infos[index].active_version.version_id !=
           kInvalidServiceWorkerVersionId)
    version_id = infos[index].active_version.version_id;
  else
    return;

  ServiceWorkerVersion* version =
      wrapper->context()->GetLiveVersion(version_id);
  *num_resources = static_cast<int>(version->script_cache_map()->size());
}

}  // namespace

class ServiceWorkerBrowserTest : public ContentBrowserTest {
 protected:
  typedef ServiceWorkerBrowserTest self;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(
        switches::kEnableExperimentalWebPlatformFeatures);
  }

  void SetUpOnMainThread() override {
    ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
    StoragePartition* partition = BrowserContext::GetDefaultStoragePartition(
        shell()->web_contents()->GetBrowserContext());
    wrapper_ = static_cast<ServiceWorkerContextWrapper*>(
        partition->GetServiceWorkerContext());

    // Navigate to the page to set up a renderer page (where we can embed
    // a worker).
    NavigateToURLBlockUntilNavigationsComplete(
        shell(),
        embedded_test_server()->GetURL("/service_worker/empty.html"), 1);

    RunOnIOThread(base::Bind(&self::SetUpOnIOThread, this));
  }

  void TearDownOnMainThread() override {
    RunOnIOThread(base::Bind(&self::TearDownOnIOThread, this));
    wrapper_ = NULL;
  }

  virtual void SetUpOnIOThread() {}
  virtual void TearDownOnIOThread() {}

  ServiceWorkerContextWrapper* wrapper() { return wrapper_.get(); }
  ServiceWorkerContext* public_context() { return wrapper(); }

  void AssociateRendererProcessToPattern(const GURL& pattern) {
    wrapper_->process_manager()->AddProcessReferenceToPattern(
        pattern, shell()->web_contents()->GetRenderProcessHost()->GetID());
  }

 private:
  scoped_refptr<ServiceWorkerContextWrapper> wrapper_;
};

class EmbeddedWorkerBrowserTest : public ServiceWorkerBrowserTest,
                                  public EmbeddedWorkerInstance::Listener {
 public:
  typedef EmbeddedWorkerBrowserTest self;

  EmbeddedWorkerBrowserTest()
      : last_worker_status_(EmbeddedWorkerInstance::STOPPED),
        pause_mode_(DONT_PAUSE) {}
  ~EmbeddedWorkerBrowserTest() override {}

  void TearDownOnIOThread() override {
    if (worker_) {
      worker_->RemoveListener(this);
      worker_.reset();
    }
  }

  void StartOnIOThread() {
    ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO));
    worker_ = wrapper()->context()->embedded_worker_registry()->CreateWorker();
    EXPECT_EQ(EmbeddedWorkerInstance::STOPPED, worker_->status());
    worker_->AddListener(this);

    const int64 service_worker_version_id = 33L;
    const GURL pattern = embedded_test_server()->GetURL("/");
    const GURL script_url = embedded_test_server()->GetURL(
        "/service_worker/worker.js");
    AssociateRendererProcessToPattern(pattern);
    int process_id = shell()->web_contents()->GetRenderProcessHost()->GetID();
    wrapper()->process_manager()->AddProcessReferenceToPattern(
        pattern, process_id);
    worker_->Start(
        service_worker_version_id,
        pattern,
        script_url,
        pause_mode_ != DONT_PAUSE,
        base::Bind(&EmbeddedWorkerBrowserTest::StartOnIOThread2, this));
  }
  void StartOnIOThread2(ServiceWorkerStatusCode status) {
    last_worker_status_ = worker_->status();
    EXPECT_EQ(SERVICE_WORKER_OK, status);
    EXPECT_EQ(EmbeddedWorkerInstance::STARTING, last_worker_status_);

    if (status != SERVICE_WORKER_OK && !done_closure_.is_null())
      done_closure_.Run();
  }

  void StopOnIOThread() {
    ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO));
    EXPECT_EQ(EmbeddedWorkerInstance::RUNNING, worker_->status());

    ServiceWorkerStatusCode status = worker_->Stop();

    last_worker_status_ = worker_->status();
    EXPECT_EQ(SERVICE_WORKER_OK, status);
    EXPECT_EQ(EmbeddedWorkerInstance::STOPPING, last_worker_status_);

    if (status != SERVICE_WORKER_OK && !done_closure_.is_null())
      done_closure_.Run();
  }

 protected:
  // EmbeddedWorkerInstance::Observer overrides:
  void OnStarted() override {
    ASSERT_TRUE(worker_ != NULL);
    ASSERT_FALSE(done_closure_.is_null());
    last_worker_status_ = worker_->status();
    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done_closure_);
  }
  void OnStopped(EmbeddedWorkerInstance::Status old_status) override {
    ASSERT_TRUE(worker_ != NULL);
    ASSERT_FALSE(done_closure_.is_null());
    last_worker_status_ = worker_->status();
    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done_closure_);
  }
  void OnPausedAfterDownload() override {
    if (pause_mode_ == PAUSE_THEN_RESUME)
      worker_->ResumeAfterDownload();
    else if (pause_mode_ == PAUSE_THEN_STOP)
      worker_->Stop();
    else
      ASSERT_TRUE(false);
  }
  void OnReportException(const base::string16& error_message,
                         int line_number,
                         int column_number,
                         const GURL& source_url) override {}
  void OnReportConsoleMessage(int source_identifier,
                              int message_level,
                              const base::string16& message,
                              int line_number,
                              const GURL& source_url) override {}
  bool OnMessageReceived(const IPC::Message& message) override { return false; }

  scoped_ptr<EmbeddedWorkerInstance> worker_;
  EmbeddedWorkerInstance::Status last_worker_status_;

  enum {
    DONT_PAUSE,
    PAUSE_THEN_RESUME,
    PAUSE_THEN_STOP,
  } pause_mode_;

  // Called by EmbeddedWorkerInstance::Observer overrides so that
  // test code can wait for the worker status notifications.
  base::Closure done_closure_;
};

class ServiceWorkerVersionBrowserTest : public ServiceWorkerBrowserTest {
 public:
  typedef ServiceWorkerVersionBrowserTest self;

  ~ServiceWorkerVersionBrowserTest() override {}

  void TearDownOnIOThread() override {
    registration_ = NULL;
    version_ = NULL;
  }

  void InstallTestHelper(const std::string& worker_url,
                         ServiceWorkerStatusCode expected_status) {
    RunOnIOThread(base::Bind(&self::SetUpRegistrationOnIOThread, this,
                             worker_url));

    // Dispatch install on a worker.
    ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED;
    base::RunLoop install_run_loop;
    BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                            base::Bind(&self::InstallOnIOThread, this,
                                       install_run_loop.QuitClosure(),
                                       &status));
    install_run_loop.Run();
    ASSERT_EQ(expected_status, status);

    // Stop the worker.
    status = SERVICE_WORKER_ERROR_FAILED;
    base::RunLoop stop_run_loop;
    BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                            base::Bind(&self::StopOnIOThread, this,
                                       stop_run_loop.QuitClosure(),
                                       &status));
    stop_run_loop.Run();
    ASSERT_EQ(SERVICE_WORKER_OK, status);
  }

  void ActivateTestHelper(
      const std::string& worker_url,
      ServiceWorkerStatusCode expected_status) {
    RunOnIOThread(
        base::Bind(&self::SetUpRegistrationOnIOThread, this, worker_url));
    ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED;
    base::RunLoop run_loop;
    BrowserThread::PostTask(
        BrowserThread::IO,
        FROM_HERE,
        base::Bind(
            &self::ActivateOnIOThread, this, run_loop.QuitClosure(), &status));
    run_loop.Run();
    ASSERT_EQ(expected_status, status);
  }

  void FetchOnRegisteredWorker(
      ServiceWorkerFetchEventResult* result,
      ServiceWorkerResponse* response,
      scoped_ptr<storage::BlobDataHandle>* blob_data_handle) {
    blob_context_ = ChromeBlobStorageContext::GetFor(
        shell()->web_contents()->GetBrowserContext());
    bool prepare_result = false;
    FetchResult fetch_result;
    fetch_result.status = SERVICE_WORKER_ERROR_FAILED;
    base::RunLoop fetch_run_loop;
    BrowserThread::PostTask(BrowserThread::IO,
                            FROM_HERE,
                            base::Bind(&self::FetchOnIOThread,
                                       this,
                                       fetch_run_loop.QuitClosure(),
                                       &prepare_result,
                                       &fetch_result));
    fetch_run_loop.Run();
    ASSERT_TRUE(prepare_result);
    *result = fetch_result.result;
    *response = fetch_result.response;
    *blob_data_handle = fetch_result.blob_data_handle.Pass();
    ASSERT_EQ(SERVICE_WORKER_OK, fetch_result.status);
  }

  void FetchTestHelper(const std::string& worker_url,
                       ServiceWorkerFetchEventResult* result,
                       ServiceWorkerResponse* response,
                       scoped_ptr<storage::BlobDataHandle>* blob_data_handle) {
    RunOnIOThread(
        base::Bind(&self::SetUpRegistrationOnIOThread, this, worker_url));
    FetchOnRegisteredWorker(result, response, blob_data_handle);
  }

  void SetUpRegistrationOnIOThread(const std::string& worker_url) {
    const GURL pattern = embedded_test_server()->GetURL("/service_worker/");
    registration_ = new ServiceWorkerRegistration(
        pattern,
        wrapper()->context()->storage()->NewRegistrationId(),
        wrapper()->context()->AsWeakPtr());
    version_ = new ServiceWorkerVersion(
        registration_.get(),
        embedded_test_server()->GetURL(worker_url),
        wrapper()->context()->storage()->NewVersionId(),
        wrapper()->context()->AsWeakPtr());

    // Make the registration findable via storage functions.
    wrapper()->context()->storage()->NotifyInstallingRegistration(
        registration_.get());

    AssociateRendererProcessToPattern(pattern);
  }

  void StartOnIOThread(const base::Closure& done,
                       ServiceWorkerStatusCode* result) {
    ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO));
    version_->StartWorker(CreateReceiver(BrowserThread::UI, done, result));
  }

  void InstallOnIOThread(const base::Closure& done,
                         ServiceWorkerStatusCode* result) {
    ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO));
    version_->SetStatus(ServiceWorkerVersion::INSTALLING);
    version_->DispatchInstallEvent(
        -1, CreateReceiver(BrowserThread::UI, done, result));
  }

  void ActivateOnIOThread(const base::Closure& done,
                          ServiceWorkerStatusCode* result) {
    ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO));
    version_->SetStatus(ServiceWorkerVersion::ACTIVATING);
    version_->DispatchActivateEvent(
        CreateReceiver(BrowserThread::UI, done, result));
  }

  void FetchOnIOThread(const base::Closure& done,
                       bool* prepare_result,
                       FetchResult* result) {
    ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO));
    ServiceWorkerFetchRequest request(
        embedded_test_server()->GetURL("/service_worker/empty.html"),
        "GET",
        ServiceWorkerHeaderMap(),
        Referrer(),
        false);
    version_->SetStatus(ServiceWorkerVersion::ACTIVATED);
    version_->DispatchFetchEvent(
        request,
        CreatePrepareReceiver(prepare_result),
        CreateResponseReceiver(
            BrowserThread::UI, done, blob_context_.get(), result));
  }

  void StopOnIOThread(const base::Closure& done,
                      ServiceWorkerStatusCode* result) {
    ASSERT_TRUE(version_.get());
    version_->StopWorker(CreateReceiver(BrowserThread::UI, done, result));
  }

  void SyncEventOnIOThread(const base::Closure& done,
                           ServiceWorkerStatusCode* result) {
    ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO));
    version_->SetStatus(ServiceWorkerVersion::ACTIVATED);
    version_->DispatchSyncEvent(
        CreateReceiver(BrowserThread::UI, done, result));
  }

 protected:
  scoped_refptr<ServiceWorkerRegistration> registration_;
  scoped_refptr<ServiceWorkerVersion> version_;
  scoped_refptr<ChromeBlobStorageContext> blob_context_;
};

IN_PROC_BROWSER_TEST_F(EmbeddedWorkerBrowserTest, StartAndStop) {
  // Start a worker and wait until OnStarted() is called.
  base::RunLoop start_run_loop;
  done_closure_ = start_run_loop.QuitClosure();
  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                          base::Bind(&self::StartOnIOThread, this));
  start_run_loop.Run();

  ASSERT_EQ(EmbeddedWorkerInstance::RUNNING, last_worker_status_);

  // Stop a worker and wait until OnStopped() is called.
  base::RunLoop stop_run_loop;
  done_closure_ = stop_run_loop.QuitClosure();
  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                          base::Bind(&self::StopOnIOThread, this));
  stop_run_loop.Run();

  ASSERT_EQ(EmbeddedWorkerInstance::STOPPED, last_worker_status_);
}

IN_PROC_BROWSER_TEST_F(EmbeddedWorkerBrowserTest, StartPaused_ThenResume) {
  pause_mode_ = PAUSE_THEN_RESUME;
  base::RunLoop start_run_loop;
  done_closure_ = start_run_loop.QuitClosure();
  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                          base::Bind(&self::StartOnIOThread, this));
  start_run_loop.Run();
  ASSERT_EQ(EmbeddedWorkerInstance::RUNNING, last_worker_status_);
}

IN_PROC_BROWSER_TEST_F(EmbeddedWorkerBrowserTest,
                       StartPaused_ThenStop) {
  pause_mode_ = PAUSE_THEN_STOP;
  base::RunLoop start_run_loop;
  done_closure_ = start_run_loop.QuitClosure();
  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                          base::Bind(&self::StartOnIOThread, this));
  start_run_loop.Run();
  ASSERT_EQ(EmbeddedWorkerInstance::STOPPED, last_worker_status_);
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, StartAndStop) {
  RunOnIOThread(base::Bind(&self::SetUpRegistrationOnIOThread, this,
                           "/service_worker/worker.js"));

  // Start a worker.
  ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED;
  base::RunLoop start_run_loop;
  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                          base::Bind(&self::StartOnIOThread, this,
                                     start_run_loop.QuitClosure(),
                                     &status));
  start_run_loop.Run();
  ASSERT_EQ(SERVICE_WORKER_OK, status);

  // Stop the worker.
  status = SERVICE_WORKER_ERROR_FAILED;
  base::RunLoop stop_run_loop;
  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                          base::Bind(&self::StopOnIOThread, this,
                                     stop_run_loop.QuitClosure(),
                                     &status));
  stop_run_loop.Run();
  ASSERT_EQ(SERVICE_WORKER_OK, status);
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, StartNotFound) {
  RunOnIOThread(base::Bind(&self::SetUpRegistrationOnIOThread, this,
                           "/service_worker/nonexistent.js"));

  // Start a worker for nonexistent URL.
  ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED;
  base::RunLoop start_run_loop;
  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                          base::Bind(&self::StartOnIOThread, this,
                                     start_run_loop.QuitClosure(),
                                     &status));
  start_run_loop.Run();
  ASSERT_EQ(SERVICE_WORKER_ERROR_START_WORKER_FAILED, status);
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, Install) {
  InstallTestHelper("/service_worker/worker.js", SERVICE_WORKER_OK);
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
                       InstallWithWaitUntil_Fulfilled) {
  InstallTestHelper("/service_worker/worker_install_fulfilled.js",
                    SERVICE_WORKER_OK);
}

// Check that ServiceWorker script requests set a "Service-Worker: script"
// header.
IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
                       ServiceWorkerScriptHeader) {
  embedded_test_server()->RegisterRequestHandler(
      base::Bind(&VerifyServiceWorkerHeaderInRequest));
  InstallTestHelper("/service_worker/generated_sw.js", SERVICE_WORKER_OK);
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
                       Activate_NoEventListener) {
  ActivateTestHelper("/service_worker/worker.js", SERVICE_WORKER_OK);
  ASSERT_EQ(ServiceWorkerVersion::ACTIVATING, version_->status());
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, Activate_Rejected) {
  ActivateTestHelper("/service_worker/worker_activate_rejected.js",
                     SERVICE_WORKER_ERROR_ACTIVATE_WORKER_FAILED);
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
                       InstallWithWaitUntil_Rejected) {
  InstallTestHelper("/service_worker/worker_install_rejected.js",
                    SERVICE_WORKER_ERROR_INSTALL_WORKER_FAILED);
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, FetchEvent_Response) {
  ServiceWorkerFetchEventResult result;
  ServiceWorkerResponse response;
  scoped_ptr<storage::BlobDataHandle> blob_data_handle;
  FetchTestHelper("/service_worker/fetch_event.js",
                  &result, &response, &blob_data_handle);
  ASSERT_EQ(SERVICE_WORKER_FETCH_EVENT_RESULT_RESPONSE, result);
  EXPECT_EQ(301, response.status_code);
  EXPECT_EQ("Moved Permanently", response.status_text);
  ServiceWorkerHeaderMap expected_headers;
  expected_headers["content-language"] = "fi";
  expected_headers["content-type"] = "text/html; charset=UTF-8";
  EXPECT_EQ(expected_headers, response.headers);

  std::string body;
  RunOnIOThread(
      base::Bind(&ReadResponseBody,
                 &body, base::Owned(blob_data_handle.release())));
  EXPECT_EQ("This resource is gone. Gone, gone, gone.", body);
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest,
                       SyncAbortedWithoutFlag) {
  RunOnIOThread(base::Bind(
      &self::SetUpRegistrationOnIOThread, this, "/service_worker/sync.js"));

  // Run the sync event.
  ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED;
  base::RunLoop sync_run_loop;
  BrowserThread::PostTask(BrowserThread::IO,
                          FROM_HERE,
                          base::Bind(&self::SyncEventOnIOThread,
                                     this,
                                     sync_run_loop.QuitClosure(),
                                     &status));
  sync_run_loop.Run();
  ASSERT_EQ(SERVICE_WORKER_ERROR_ABORT, status);
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerVersionBrowserTest, SyncEventHandled) {
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  command_line->AppendSwitch(switches::kEnableServiceWorkerSync);

  RunOnIOThread(base::Bind(
      &self::SetUpRegistrationOnIOThread, this, "/service_worker/sync.js"));
  ServiceWorkerFetchEventResult result;
  ServiceWorkerResponse response;
  scoped_ptr<storage::BlobDataHandle> blob_data_handle;
  // Should 404 before sync event.
  FetchOnRegisteredWorker(&result, &response, &blob_data_handle);
  EXPECT_EQ(404, response.status_code);

  // Run the sync event.
  ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED;
  base::RunLoop sync_run_loop;
  BrowserThread::PostTask(BrowserThread::IO,
                          FROM_HERE,
                          base::Bind(&self::SyncEventOnIOThread,
                                     this,
                                     sync_run_loop.QuitClosure(),
                                     &status));
  sync_run_loop.Run();
  ASSERT_EQ(SERVICE_WORKER_OK, status);

  // Should 200 after sync event.
  FetchOnRegisteredWorker(&result, &response, &blob_data_handle);
  EXPECT_EQ(200, response.status_code);
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerBrowserTest, Reload) {
  const char kPageUrl[] = "/service_worker/reload.html";
  const char kWorkerUrl[] = "/service_worker/fetch_event_reload.js";
  scoped_refptr<WorkerActivatedObserver> observer =
      new WorkerActivatedObserver(wrapper());
  observer->Init();
  public_context()->RegisterServiceWorker(
      embedded_test_server()->GetURL(kPageUrl),
      embedded_test_server()->GetURL(kWorkerUrl),
      base::Bind(&ExpectResultAndRun, true, base::Bind(&base::DoNothing)));
  observer->Wait();

  const base::string16 title1 = base::ASCIIToUTF16("reload=false");
  TitleWatcher title_watcher1(shell()->web_contents(), title1);
  NavigateToURL(shell(), embedded_test_server()->GetURL(kPageUrl));
  EXPECT_EQ(title1, title_watcher1.WaitAndGetTitle());

  const base::string16 title2 = base::ASCIIToUTF16("reload=true");
  TitleWatcher title_watcher2(shell()->web_contents(), title2);
  ReloadBlockUntilNavigationsComplete(shell(), 1);
  EXPECT_EQ(title2, title_watcher2.WaitAndGetTitle());

  shell()->Close();

  base::RunLoop run_loop;
  public_context()->UnregisterServiceWorker(
      embedded_test_server()->GetURL(kPageUrl),
      base::Bind(&ExpectResultAndRun, true, run_loop.QuitClosure()));
  run_loop.Run();
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerBrowserTest,
                       ResponseFromHTTPSServiceWorkerIsMarkedAsSecure) {
  const char kPageUrl[] = "files/service_worker/fetch_event_blob.html";
  const char kWorkerUrl[] = "files/service_worker/fetch_event_blob.js";
  net::SpawnedTestServer https_server(
      net::SpawnedTestServer::TYPE_HTTPS,
      net::BaseTestServer::SSLOptions(
          net::BaseTestServer::SSLOptions::CERT_OK),
      base::FilePath(FILE_PATH_LITERAL("content/test/data/")));
  ASSERT_TRUE(https_server.Start());

  scoped_refptr<WorkerActivatedObserver> observer =
      new WorkerActivatedObserver(wrapper());
  observer->Init();
  public_context()->RegisterServiceWorker(
      https_server.GetURL(kPageUrl),
      https_server.GetURL(kWorkerUrl),
      base::Bind(&ExpectResultAndRun, true, base::Bind(&base::DoNothing)));
  observer->Wait();

  const base::string16 title = base::ASCIIToUTF16("Title");
  TitleWatcher title_watcher(shell()->web_contents(), title);
  NavigateToURL(shell(), https_server.GetURL(kPageUrl));
  EXPECT_EQ(title, title_watcher.WaitAndGetTitle());
  EXPECT_FALSE(shell()->web_contents()->DisplayedInsecureContent());
  NavigationEntry* entry =
      shell()->web_contents()->GetController().GetVisibleEntry();
  EXPECT_EQ(SECURITY_STYLE_AUTHENTICATED, entry->GetSSL().security_style);

  shell()->Close();

  base::RunLoop run_loop;
  public_context()->UnregisterServiceWorker(
      https_server.GetURL(kPageUrl),
      base::Bind(&ExpectResultAndRun, true, run_loop.QuitClosure()));
  run_loop.Run();
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerBrowserTest,
                       ResponseFromHTTPServiceWorkerIsNotMarkedAsSecure) {
  const char kPageUrl[] = "/service_worker/fetch_event_blob.html";
  const char kWorkerUrl[] = "/service_worker/fetch_event_blob.js";
  scoped_refptr<WorkerActivatedObserver> observer =
      new WorkerActivatedObserver(wrapper());
  observer->Init();
  public_context()->RegisterServiceWorker(
      embedded_test_server()->GetURL(kPageUrl),
      embedded_test_server()->GetURL(kWorkerUrl),
      base::Bind(&ExpectResultAndRun, true, base::Bind(&base::DoNothing)));
  observer->Wait();

  const base::string16 title = base::ASCIIToUTF16("Title");
  TitleWatcher title_watcher(shell()->web_contents(), title);
  NavigateToURL(shell(), embedded_test_server()->GetURL(kPageUrl));
  EXPECT_EQ(title, title_watcher.WaitAndGetTitle());
  EXPECT_FALSE(shell()->web_contents()->DisplayedInsecureContent());
  NavigationEntry* entry =
      shell()->web_contents()->GetController().GetVisibleEntry();
  EXPECT_EQ(SECURITY_STYLE_UNAUTHENTICATED, entry->GetSSL().security_style);

  shell()->Close();

  base::RunLoop run_loop;
  public_context()->UnregisterServiceWorker(
      embedded_test_server()->GetURL(kPageUrl),
      base::Bind(&ExpectResultAndRun, true, run_loop.QuitClosure()));
  run_loop.Run();
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerBrowserTest, ImportsBustMemcache) {
  const char kScopeUrl[] = "/service_worker/imports_bust_memcache_scope/";
  const char kPageUrl[] = "/service_worker/imports_bust_memcache.html";
  const char kScriptUrl[] = "/service_worker/worker_with_one_import.js";
  const char kImportUrl[] = "/service_worker/long_lived_import.js";
  const base::string16 kOKTitle(base::ASCIIToUTF16("OK"));
  const base::string16 kFailTitle(base::ASCIIToUTF16("FAIL"));

  RunOnIOThread(
      base::Bind(&CreateLongLivedResourceInterceptors,
                 embedded_test_server()->GetURL(kScriptUrl),
                 embedded_test_server()->GetURL(kImportUrl)));

  TitleWatcher title_watcher(shell()->web_contents(), kOKTitle);
  title_watcher.AlsoWaitForTitle(kFailTitle);
  NavigateToURL(shell(), embedded_test_server()->GetURL(kPageUrl));
  base::string16 title = title_watcher.WaitAndGetTitle();
  EXPECT_EQ(kOKTitle, title);

  // Verify the number of resources in the implicit script cache is correct.
  const int kExpectedNumResources = 2;
  int num_resources = 0;
  RunOnIOThread(
      base::Bind(&CountScriptResources,
                 base::Unretained(wrapper()),
                 embedded_test_server()->GetURL(kScopeUrl),
                 &num_resources));
  EXPECT_EQ(kExpectedNumResources, num_resources);
}

class ServiceWorkerBlackBoxBrowserTest : public ServiceWorkerBrowserTest {
 public:
  typedef ServiceWorkerBlackBoxBrowserTest self;

  void FindRegistrationOnIO(const GURL& document_url,
                            ServiceWorkerStatusCode* status,
                            const base::Closure& continuation) {
    wrapper()->context()->storage()->FindRegistrationForDocument(
        document_url,
        base::Bind(&ServiceWorkerBlackBoxBrowserTest::FindRegistrationOnIO2,
                   this,
                   status,
                   continuation));
  }

  void FindRegistrationOnIO2(
      ServiceWorkerStatusCode* out_status,
      const base::Closure& continuation,
      ServiceWorkerStatusCode status,
      const scoped_refptr<ServiceWorkerRegistration>& registration) {
    *out_status = status;
    if (!registration.get())
      EXPECT_NE(SERVICE_WORKER_OK, status);
    continuation.Run();
  }
};

static int CountRenderProcessHosts() {
  int result = 0;
  for (RenderProcessHost::iterator iter(RenderProcessHost::AllHostsIterator());
       !iter.IsAtEnd();
       iter.Advance()) {
    result++;
  }
  return result;
}

// Flaky timeouts on CrOS and crash on Android: http://crbug.com/387045
#if defined(OS_CHROMEOS) || defined(ANDROID)
#define MAYBE_Registration DISABLED_Registration
#else
#define MAYBE_Registration Registration
#endif
IN_PROC_BROWSER_TEST_F(ServiceWorkerBlackBoxBrowserTest, MAYBE_Registration) {
  // Close the only window to be sure we're not re-using its RenderProcessHost.
  shell()->Close();
  EXPECT_EQ(0, CountRenderProcessHosts());

  const char kWorkerUrl[] = "/service_worker/fetch_event.js";
  const char kScope[] = "/service_worker/";

  // Unregistering nothing should return false.
  {
    base::RunLoop run_loop;
    public_context()->UnregisterServiceWorker(
        embedded_test_server()->GetURL("/"),
        base::Bind(&ExpectResultAndRun, false, run_loop.QuitClosure()));
    run_loop.Run();
  }

  // If we use a worker URL that doesn't exist, registration fails.
  {
    base::RunLoop run_loop;
    public_context()->RegisterServiceWorker(
        embedded_test_server()->GetURL(kScope),
        embedded_test_server()->GetURL("/does/not/exist"),
        base::Bind(&ExpectResultAndRun, false, run_loop.QuitClosure()));
    run_loop.Run();
  }
  EXPECT_EQ(0, CountRenderProcessHosts());

  // Register returns when the promise would be resolved.
  {
    base::RunLoop run_loop;
    public_context()->RegisterServiceWorker(
        embedded_test_server()->GetURL(kScope),
        embedded_test_server()->GetURL(kWorkerUrl),
        base::Bind(&ExpectResultAndRun, true, run_loop.QuitClosure()));
    run_loop.Run();
  }
  EXPECT_EQ(1, CountRenderProcessHosts());

  // Registering again should succeed, although the algo still
  // might not be complete.
  {
    base::RunLoop run_loop;
    public_context()->RegisterServiceWorker(
        embedded_test_server()->GetURL(kScope),
        embedded_test_server()->GetURL(kWorkerUrl),
        base::Bind(&ExpectResultAndRun, true, run_loop.QuitClosure()));
    run_loop.Run();
  }

  // The registration algo might not be far enough along to have
  // stored the registration data, so it may not be findable
  // at this point.

  // Unregistering something should return true.
  {
    base::RunLoop run_loop;
    public_context()->UnregisterServiceWorker(
        embedded_test_server()->GetURL(kScope),
        base::Bind(&ExpectResultAndRun, true, run_loop.QuitClosure()));
    run_loop.Run();
  }
  EXPECT_GE(1, CountRenderProcessHosts()) << "Unregistering doesn't stop the "
                                             "workers eagerly, so their RPHs "
                                             "can still be running.";

  // Should not be able to find it.
  {
    ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED;
    RunOnIOThread(
        base::Bind(&ServiceWorkerBlackBoxBrowserTest::FindRegistrationOnIO,
                   this,
                   embedded_test_server()->GetURL("/service_worker/empty.html"),
                   &status));
    EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, status);
  }
}

IN_PROC_BROWSER_TEST_F(ServiceWorkerBrowserTest, CrossSiteTransfer) {
  // The first page registers a service worker.
  const char kRegisterPageUrl[] = "/service_worker/cross_site_xfer.html";
  const base::string16 kOKTitle1(base::ASCIIToUTF16("OK_1"));
  const base::string16 kFailTitle1(base::ASCIIToUTF16("FAIL_1"));
  content::TitleWatcher title_watcher1(shell()->web_contents(), kOKTitle1);
  title_watcher1.AlsoWaitForTitle(kFailTitle1);

  NavigateToURL(shell(), embedded_test_server()->GetURL(kRegisterPageUrl));
  ASSERT_EQ(kOKTitle1, title_watcher1.WaitAndGetTitle());

  // Force process swapping behavior.
  ShellContentBrowserClient::SetSwapProcessesForRedirect(true);

  // The second pages loads via the serviceworker including a subresource.
  const char kConfirmPageUrl[] =
      "/service_worker/cross_site_xfer_scope/"
      "cross_site_xfer_confirm_via_serviceworker.html";
  const base::string16 kOKTitle2(base::ASCIIToUTF16("OK_2"));
  const base::string16 kFailTitle2(base::ASCIIToUTF16("FAIL_2"));
  content::TitleWatcher title_watcher2(shell()->web_contents(), kOKTitle2);
  title_watcher2.AlsoWaitForTitle(kFailTitle2);

  NavigateToURL(shell(), embedded_test_server()->GetURL(kConfirmPageUrl));
  EXPECT_EQ(kOKTitle2, title_watcher2.WaitAndGetTitle());
}

}  // namespace content


text:
title: rails项目中添加异常邮件提醒
categories:
  - dev
tags:
  - rails
  - exception notification
date: 2015-07-21 12:15:00
---

在一个项目上线之后,需要对网站运行状态进行监控,rails中比较常用的是`exception_notification`对项目进行异常信息处理。

<!-- more -->

### 1. add exception_notification gem

in Gemfile

```
# https://github.com/smartinez87/exception_notification
gem 'exception_notification', '~> 4.1.0'
```

### 2. in app/config/initialize/exception_notification.rb

```ruby
# Only send exception email on Production or Staging server
# type `LOCAL_PRODUCTION=1 rails s -e production` to trigger local production environment
# type `LOCAL_STAGING=1 rails s -e staging` to trigger local staging environment
if (Rails.env.production? || Rails.env.staging?) && !ENV['LOCAL_PRODUCTION'] && !ENV['LOCAL_STAGING']
  Rails.application.config.middleware.use ExceptionNotification::Rack,
    :email => {
      :email_prefix => Rails.application.secrets[:exception_email_prefix],
      :sender_address => '"notifier" ' + Rails.application.secrets[:exception_email_sender_address],
      :exception_recipients => Rails.application.secrets[:notification_receivers]
    }
end
```

### 3. on `config/application.rb` or other `env.rb`

```
  # https://github.com/smartinez87/exception_notification#actionmailer-configuration
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.perform_deliveries = true
  # Config action_mailer
  config.action_mailer.smtp_settings = {
    address:        Rails.application.secrets.action_mailer_smtp_settings["address"],
    port:           587,
    user_name:      Rails.application.secrets.action_mailer_smtp_settings["user_name"],
    password:       Rails.application.secrets.action_mailer_smtp_settings["password"],
    authentication: 'plain',
    enable_starttls_auto: true
  }
```

### 4. set the config in `secrets.yml`

```
default: &DEFAULT
  notification_receivers: &notification_receivers
    - david@example.com

  action_mailer_smtp_settings:
    address: 'smtp.gmail.com'
    user_name: ''
    password: ''

  exception_email_prefix: '[Exception] '
  exception_email_sender_address: '<example@gmail.com>'
  notification_receivers:
    *notification_receivers

staging:
  <<: *DEFAULT
  secret_key_base: ''
```


text:
namespace Question_14_07_GradesDb
{
    using System;
    using System.Collections.Generic;

    public partial class Student
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Student()
        {
            this.Enrollments = new HashSet<Enrollment>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }
}


text:
- Proposal: [SE-0165](0165-dict.md)
- Author: [Nate Cook](https://github.com/natecook1000)
- Review Manager: [Ben Cohen](https://github.com/airspeedswift)
- Status: **Implemented (Swift 4)**
- Decision Notes: [Rationale][rationale]

## Introduction

This proposal comprises a variety of commonly (and less commonly) suggested improvements to the standard library's `Dictionary` type, from merging initializers to dictionary-specific `filter` and `mapValues` methods. The proposed additions to `Dictionary`, and the corresponding changes to `Set`, are detailed in the sections below.

- Suggested Improvements:
    - [Merging initializers and methods](#1-merging-initializers-and-methods)
    - [Key-based subscript with default value](#2-key-based-subscript-with-default-value)
    - [Dictionary-specific map and filter](#3-dictionary-specific-map-and-filter)
    - [Visible `Dictionary` capacity](#4-visible-dictionary-capacity)
    - [Grouping sequence elements](#5-grouping-sequence-elements)
    - [Relevant changes to `Set`](#6-apply-relevant-changes-to-set)
- [Detailed Design](#detailed-design)
    - [Sandbox with Prototype][sandbox]
- [Source Compatibility](#source-compatibility)

---

## 1. Merging initializers and methods

The `Dictionary` type should allow initialization from a sequence of `(Key, Value)` tuples and offer methods that merge a sequence of `(Key, Value)` tuples into a new or existing dictionary, using a closure to combine values for duplicate keys.

- [First message of discussion thread](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160104/006124.html)
- [Initial proposal draft](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160111/006665.html)
- [Prior standalone proposal (SE-100)](https://github.com/apple/swift-evolution/blob/master/proposals/0100-add-sequence-based-init-and-merge-to-dictionary.md)

`Array` and `Set` both have initializers that create a new instance from a sequence of elements. The `Array` initializer is useful for converting other sequences and collections to the "standard" collection type, while the `Set` initializer is essential for recovering set operations after performing any functional operations on a set. For example, filtering a set produces a collection without any set operations available.

```swift
let numberSet = Set(1 ... 100)
let fivesOnly = numberSet.lazy.filter { $0 % 5 == 0 }
```

`fivesOnly` is a `LazyFilterCollection<Set<Int>>` instead of a `Set`—sending that back through the `Set` sequence initializer restores the expected methods.

```swift
let fivesOnlySet = Set(numberSet.lazy.filter { $0 % 5 == 0 })
fivesOnlySet.isSubsetOf(numberSet) // true
```

`Dictionary`, on the other hand, has no such initializer, so a similar operation leaves no room to recover dictionary functionality without building a mutable `Dictionary` via iteration or functional methods. These techniques also don't support type inference from the source sequence, increasing verbosity.

```swift
let numberDictionary = ["one": 1, "two": 2, "three": 3, "four": 4]
let evenOnly = numberDictionary.lazy.filter { (_, value) in
    value % 2 == 0
}

var viaIteration: [String: Int] = [:]
for (key, value) in evenOnly {
    viaIteration[key] = value
}

let viaReduce: [String: Int] = evenOnly.reduce([:]) { (cumulative, kv) in
    var dict = cumulative
    dict[kv.key] = kv.value
    return dict
}
```

Beyond initialization, `Array` and `Set` both also provide a method to add a new block of elements to an existing collection. `Array` provides this via `append(contentsOf:)` for the common appending case or `replaceSubrange(_:with:)` for general inserting or replacing, while the unordered `Set` type lets you pass any sequence to `unionInPlace(_:)` to add elements to an existing set.

Once again, `Dictionary` has no corresponding API -- looping and adding elements one at a time as shown above is the only way to merge new elements into an existing dictionary.

### Proposed solution

This proposal puts forward two new ways to convert `(Key, Value)` sequences to dictionary form: an initializer and a set of merging APIs that handle input data with duplicate keys.

#### Sequence-based initializer

The proposed solution would add a new initializer to `Dictionary` that accepts any sequence of `(Key, Value)` tuple pairs.

```swift
init<S: Sequence where S.Iterator.Element == (key: Key, value: Value)>(
    uniqueKeysWithValues: S)
```

With the proposed initializer, creating a `Dictionary` instance from a sequence of key/value pairs is as easy as creating an `Array` or `Set`:

```swift
let viaProposed = Dictionary(uniqueKeysWithValues: evenOnly)
```

Like `Array.init(_:)` and `Set.init(_:)`, this is a full-width initializer. To ensure this, the initializer has a precondition that each key in the supplied sequence is unique, and traps whenever that condition isn't met. When duplicate keys are possible in the input, the merging initializer described in the next section must be used instead.

The new initializer allows for some convenient uses that aren't currently possible.

- Initializing from a `DictionaryLiteral` (the type, not an actual literal)

    ```swift
    let literal: DictionaryLiteral = ["a": 1, "b": 2, "c": 3, "d": 4]
    let dictFromDL = Dictionary(uniqueKeysWithValues: literal)
    ```

- Converting an array to an indexed dictionary (popular on the thread)

    ```swift
    let names = ["Cagney", "Lacey", "Bensen"]
    let dict = Dictionary(uniqueKeysWithValues: names.enumerated().map { (i, val) in (i + 1, val) })
    // [2: "Lacey", 3: "Bensen", 1: "Cagney"]
    ```

- Initializing from a pair of zipped sequences (examples abound)

    ```swift
    let letters = "abcdef".characters.lazy.map(String.init)
    let dictFromZip = Dictionary(uniqueKeysWithValues: zip(letters, 1...10))
    // ["b": 2, "e": 5, "a": 1, "f": 6, "d": 4, "c": 3]
    ```

    > This particular use is currently blocked by [SR-922](https://bugs.swift.org/browse/SR-922). As a workaround, add `.map {(key: $0, value: $1)}`.

#### Merging initializer and methods

Creating a `Dictionary` from a dictional literal checks the keys for uniqueness, trapping on a duplicate. The sequence-based initializer shown above has the same requirement.

```swift
let duplicates: DictionaryLiteral = ["a": 1, "b": 2, "a": 3, "b": 4]
let letterDict = Dictionary(uniqueKeysWithValues: duplicates)
// error: Duplicate key found: "a"
```

Because some use cases can be forgiving of duplicate keys, this proposal includes a second new initializer. This initializer allows the caller to supply, along with the sequence, a combining closure that's called with the old and new values for any duplicate keys.

```swift
init<S: Sequence>(
    _ keysAndValues: S,
    uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S.Iterator.Element == (key: Key, value: Value)
```

This example shows how one could keep the first value of all those supplied for a duplicate key.

```swift
let letterDict2 = Dictionary(duplicates, uniquingKeysWith: { (first, _) in first })
// ["b": 2, "a": 1]
```

Or the largest value for any duplicate keys.

```swift
let letterDict3 = Dictionary(duplicates, uniquingKeysWith: max)
// ["b": 4, "a": 3]
```

At other times the merging initializer could be used to combine values for duplicate keys. Donnacha Oisín Kidney wrote a neat `frequencies()` method for sequences as an example of such a use in the thread.

```swift
extension Sequence where Iterator.Element: Hashable {
    func frequencies() -> [Iterator.Element: Int] {
        return Dictionary(self.lazy.map { v in (v, 1) }, uniquingKeysWith: +)
    }
}
[1, 2, 2, 3, 1, 2, 4, 5, 3, 2, 3, 1].frequencies()
// [2: 4, 4: 1, 5: 1, 3: 3, 1: 3]
```

This proposal also includes new mutating and non-mutating methods for `Dictionary` that merge the contents of a sequence of `(Key, Value)` tuples into an existing dictionary, `merge(_:uniquingKeysWith:)` and `merging(_:uniquingKeysWith:)`.

```swift
mutating func merge<S: Sequence>(
    _ other: S,
    uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S.Iterator.Element == (key: Key, value: Value)

func merging<S: Sequence>(
    _ other: S,
    uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows -> [Key: Value] where S.Iterator.Element == (key: Key, value: Value)
```

As above, there are a wide variety of uses for the merge.

```swift
// Adding default values
let defaults: [String: Bool] = ["foo": false, "bar": false, "baz": false]
var options: [String: Bool] = ["foo": true, "bar": false]
options.merge(defaults) { (old, _) in old }
// options is now ["foo": true, "bar": false, "baz": false]

// Summing counts repeatedly
var bugCounts: [String: Int] = ["bees": 9, "ants": 112, ...]
while bugCountingSource.hasMoreData() {
    bugCounts.merge(bugCountingSource.countMoreBugs(), uniquingKeysWith: +)
}
```

---

## 2. Key-based subscript with default value

Another common challenge with dictionaries is iteratively making changes to key/value pairs that may or may not already be present. For example, to iteratively add count the frequencies of letters in a string, one might write something like the following:

```swift
let source = "how now brown cow"
var frequencies: [Character: Int] = [:]
for c in source.characters {
    if frequencies[c] == nil {
        frequencies[c] = 1
    } else {
        frequencies[c]! += 1
    }
}
```

Testing for `nil` and assigning through the force unwrapping operator are awkward at best for such a common operation. Furthermore, the `Optional<Value>` return type of the current keyed subscript complicates efficiencies that could be gained for this type of `modify` action under a future ownership model.

### Proposed solution

A keyed subscript with a default value neatly simplifies this usage. Instead of checking for `nil`, one can pass the default value along with the key as a `default` subscript parameter.

```swift
let source = "how now brown cow"
var frequencies: [Character: Int] = [:]
for c in source.characters {
    frequencies[c, default: 0] += 1
}
```

The return type of this subscript is a non-optional `Value`. Note that accessing the subscript as a getter does not store the default value in the dictionary—the following two lines are equivalent:

```swift
let x = frequencies["a", default: 0]
let y = frequencies["a"] ?? 0
```

---

## 3. Dictionary-specific map and filter

The standard `map` and `filter` methods, while always useful and beloved, aren't ideal when applied to dictionaries. In both cases, the desired end-result is frequently another dictionary instead of an array of key-value pairs—even with the sequence-based initializer proposed above this is an inefficient way of doing things.

Additionally, the standard `map` method doesn't gracefully support passing a function when transforming only the *values* of a dictionary. The transform function must accept and return key/value pairs, necessitating a custom closure in nearly every case.

Assuming the addition of a sequence-based initializer, the current `filter` and `map` look like the following:

```swift
let numbers = ["one": 1, "two": 2, "three": 3, "four": 4]
let evens = Dictionary(numbers.lazy.filter { $0.value % 2 == 0 })!
// ["four": 4, "two": 2]
let strings = Dictionary(numbers.lazy.map { (k, v) in (k, String(v)) })!
// ["three": "3", "four": "4", "one": "1", "two": "2"]
```

### Proposed solution

This proposal adds two new methods for `Dictionary`:

1. A `mapValues` method that keeps a dictionary's keys intact while transforming the values. Mapping a dictionary's key/value pairs can't always produce a new dictionary, due to the possibility of key collisions, but mapping only the values can produce a new dictionary with the same underlying layout as the original.

    ```swift
    let strings = numbers.mapValues(String.init)
    // ["three": "3", "four": "4", "one": "1", "two": "2"]
    ```

2. A `Dictionary`-returning `filter` method. While transforming the keys and values of a dictionary can result in key collisions, filtering the elements of a dictionary can at worst replicate the entire dictionary.

    ```swift
    let evens = numbers.filter { $0.value % 2 == 0 }
    // ["four": 4, "two": 2]
    ```

Both of these can be made significantly more efficient than their `Sequence`-sourced counterparts. For example, the `mapValues` method can simply copy the portion of the storage that holds the keys to the new dictionary before transforming the values.

---

## 4. Visible dictionary capacity

As you add elements to a dictionary, it automatically grows its backing storage as necessary. This reallocation is a significant operation—unlike arrays, where the existing elements can be copied to a new block of storage en masse, every key/value pair must be moved over individually, recalculating the hash value for the key to find its position in the larger backing buffer.

While dictionaries uses an exponential growth strategy to make this as efficient as possible, beyond the `init(minimumCapacity:)` initializer they do not expose a way to reserve a specific capacity. In addition, adding a key/value pair to a dictionary is guaranteed not to invalidate existing indices as long as the capacity doesn't change, yet we don't provide any way of seeing a dictionary's current or post-addition capacity.

### Proposed solution

`Dictionary` should add a `capacity` property and a `reserveCapacity(_:)` method, like those used in range-replaceable collections. The `capacity` of a dictionary is the number of elements it can hold without reallocating a larger backing storage, while calling `reserveCapacity(_:)` allocates a large enough buffer to hold the requested number of elements without reallocating.

```swift
var numbers = ["one": 1, "two": 2, "three": 3, "four": 4]
numbers.capacity   // 6
numbers.reserveCapacity(20)
numbers.capacity   // 24
```

Because hashed collections use extra storage capacity to reduce the likelihood and cost of collisions, the value of the `capacity` property won't be equal to the actual size of the backing storage. Likewise, the capacity after calling `reserveCapacity(_:)` will be at least as large as the argument, but usually larger. (In its current implementation, `Dictionary` always has a power of 2-sized backing storage.)

---

## 5. Grouping sequence elements

As a final `Dictionary`-related issue, grouping elements in a sequence by some computed key is a commonly requested addition that we can add as part of this omnibus proposal. Call a new `Dictionary(grouping:by:)` initializer with a closure that converts each value in a sequence to a hashable type `T`; the result is a dictionary with keys of type `T` and values of type `[Iterator.Element]`.

```swift
let names = ["Patti", "Aretha", "Anita", "Gladys"]

// By first letter
Dictionary(grouping: names, by: { $0.characters.first! })
// ["P": ["Patti"], "G": ["Gladys"], "A": ["Aretha", "Anita"]]

// By name length
Dictionary(grouping: names) { $0.utf16.count }
// [5: ["Patti", "Anita"], 6: ["Aretha", "Gladys"]]
```

---

## 6. Apply relevant changes to `Set`

As the `Set` and `Dictionary` types are similar enough to share large chunks of their implementations, it makes sense to look at which of these `Dictionary` enhancements can also be applied to `Set`. Of the symbols proposed above, the following additions would also be useful and appropriate for the `Set` type:

- Add a `Set`-specific `filter` method that returns a new set—this would function essentially as a predicate-based `intersection` method.
- Add a `capacity` property and `reserveCapacity()` method, for the reasons listed above.

## Detailed design

With the exception of the proposed capacity property and method, the proposed additions to `Dictionary`, `Set`, and `Sequence` are available in [this Swift Sandbox][sandbox]. Note that this prototype is not a proposed implementation; rather a way to try out the behavior of the proposed changes.

Collected in one place, these are the new APIs for `Dictionary`, `Set`, and `Sequence`:

```swift
struct Dictionary<Key: Hashable, Value> {
    typealias Element = (key: Key, value: Value)

    // existing declarations

    /// Creates a new dictionary using the key/value pairs in the given sequence.
    /// If the given sequence has any duplicate keys, the result is `nil`.
    init<S: Sequence>(uniqueKeysWithValues: S) where S.Iterator.Element == Element

    /// Creates a new dictionary using the key/value pairs in the given sequence,
    /// using a combining closure to determine the value for any duplicate keys.
    init<S: Sequence>(
        _ keysAndValues: S,
        uniquingKeysWith combine: (Value, Value) throws -> Value
    ) rethrows where S.Iterator.Element == Element

    /// Creates a new dictionary where the keys are the groupings returned by
    /// the given closure and the values are arrays of the elements that
    /// returned each specific key.
    init<S: Sequence>(
    	grouping values: S,
	by keyForValue: (S.Iterator.Element) throws -> Key
    ) rethrows where Value == [S.Iterator.Element]

    /// Merges the key/value pairs in the given sequence into the dictionary,
    /// using a combining closure to determine the value for any duplicate keys.
    mutating func merge<S: Sequence>(
        _ other: S,
        uniquingKeysWith combine: (Value, Value) throws -> Value
    ) rethrows where S.Iterator.Element == Element

    /// Returns a new dictionary created by merging the key/value pairs in the
    /// given sequence into the dictionary, using a combining closure to determine
    /// the value for any duplicate keys.
    func merging<S: Sequence>(
        _ other: S,
        uniquingKeysWith combine: (Value, Value) throws -> Value
    ) rethrows -> [Key: Value] where S.Iterator.Element == Element

    /// Accesses the element with the given key, or the specified default value,
    /// if the dictionary doesn't contain the given key.
    subscript(key: Key, default defaultValue: Value) -> Value { get set }

    /// Returns a new dictionary containing the key/value pairs that satisfy
    /// the given predicate.
    func filter(_ isIncluded: (Key, Value) throws -> Bool) rethrows -> [Key: Value]

    /// Returns a new dictionary containing the existing keys and the results of
    /// mapping the given closure over the dictionary's values.
    func mapValues<T>(_ transform: (Value) throws -> T) rethrows -> [Key: T]

    /// The number of key/value pairs that can be stored by the dictionary without
    /// reallocating storage.
    var capacity: Int { get }

    /// Ensures that the dictionary has enough storage for `capacity` key/value
    /// pairs.
    var reserveCapacity(_ capacity: Int)
}

struct Set<Element: Hashable> {
    // existing declarations

    /// Returns a new set containing the elements that satisfy the given predicate.
    func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> Set

    /// The number of elements that can be stored by the set without
    /// reallocating storage.
    var capacity: Int { get }

    /// Ensures that the set has enough storage for `capacity` elements.
    var reserveCapacity(_ capacity: Int)
}
```

## Alternatives Considered

- An earlier version of this proposal declared the first merging initializer as failable, returning `nil` when a sequence with duplicate keys was passed. That initializer is really only appropriate when working with known unique keys, however, as there isn't a feasible recovery path when there can be duplicate keys. That leaves two possibilities:
	1. The source input can *never* have duplicate keys, and the programmer has to write `!` or unwrap in some other way, or
	2. The source input *can* have duplicate keys, in which case the programmer should be using `init(merging:mergingValues:)` instead.

- An earlier version of this proposal included the addition of two new top-level functions to the standard library: `first(_:_:)` and `last(_:_:)`, which return their first and last arguments, respectively. These new functions would be passed instead of a custom closure to a merging method or initializer:

	```swift
	let firstWins = Dictionary(merging: duplicates, mergingValues: first)
	// ["b": 2, "a": 1]

	let lastWins = Dictionary(merging: duplicates, mergingValues: last)
	// ["b": 4, "a": 3]
	```

	As an alternative to the `first(_:_:)` and `last(_:_:)` functions, at the cost of three additional overloads for the merging initializer and methods, we could allow users to specify the `useFirst` and `useLast` cases of a `MergeCollisionStrategy` enumeration.

	```swift
	extension Dictionary {
	    /// The strategy to use when merging a sequence of key-value pairs into a dictionary.
	    enum MergeCollisionStrategy {
	        /// If there is more than one instance of a key in the sequence to merge, use
	        /// only the first value for the dictionary.
	        case useFirst
	        /// If there is more than one instance of a key in the sequence to merge, use
	        /// only the last value for the dictionary.
	        case useLast
	    }

	    init<S: Sequence>(
	        merging keysAndValues: S,
	        mergingValues strategy: MergeCollisionStrategy
	    )

	    // other merging overloads
	}
	```

	In use, this overload would look similar to the functional version, but may aid in discoverability:

	```swift
	let firstWins = Dictionary(merging: duplicates, mergingValues: .useFirst)
	// ["b": 2, "a": 1]

	let lastWins = Dictionary(merging: duplicates, mergingValues: .useLast)
	// ["b": 4, "a": 3]
	```

- An earlier version of this proposal included a change to both collections' `remove(at:)` method, such that it would return both the removed element and the next valid index in the iteration sequence. This change lets a programmer write code that would remove elements of a dictionary or a set in place, which can't currently be done with as much efficiency due to index invalidation:

    ```swift
    var i = dict.startIndex
    while i != dict.endIndex {
        if shouldRemove(dict[i]) {
            (_, i) = dict.remove(at: i)
        } else {
            dict.formIndex(after: &i)
        }
    }
    ```

    This change to `remove(at:)` has been deferred to a later proposal that can better deal with the impact on existing code.

- The reviewed version of this proposal had different spelling of the merging initializers and methods:

    ```swift
    init<S: Sequence where S.Iterator.Element == (key: Key, value: Value)>(
        _ keysAndValues: S)

    init<S: Sequence>(
        merging keysAndValues: S,
        mergingValues combine: (Value, Value) throws -> Value
    ) rethrows where S.Iterator.Element == (key: Key, value: Value)

    mutating func merge<S: Sequence>(
        _ other: S,
        mergingValues combine: (Value, Value) throws -> Value
    ) rethrows where S.Iterator.Element == (key: Key, value: Value)

    func merged<S: Sequence>(
        with other: S,
        mergingValues combine: (Value, Value) throws -> Value
    ) rethrows -> [Key: Value] where S.Iterator.Element == (key: Key, value: Value)
    ```

    In addition, the `Dictionary(grouping:by:)` initializer was proposed as a `grouped(by:)` method on the `Sequence` protocol. The [rationale][] for accepting the proposal explains the reasons for these changes.

## Source compatibility

All the proposed additions are purely additive and should impose only a minimal source compatibility burden. The addition of same-type returning `filter(_:)` methods to `Dictionary` and `Set` could cause problems if code is relying on the previous behavior of returning an array. For example, the following code would break after this change:

```swift
let digits = Set(0..<10)
let evens = digits.filter { $0 % 2 == 0 }
functionThatTakesAnArray(evens)
```

To mitigate the impact of this on code compiled in Swift 3 mode, `Dictionary` and `Set` will have an additional overload of the `Array`-returning `filter(_:)` that is marked as obsoleted in Swift 4. This will allow Swift 3 code to continue to compile and work as expected:

```swift
extension Set {
    @available(swift, obsoleted: 4)
    func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]

    @available(swift, introduced: 4)
    func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> Set<Element>
}
```

[sandbox]: http://swift.sandbox.bluemix.net/#/repl/58f8e3aee785f75678f428a8
[rationale]: https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170417/035955.html


text:
/*
 * Decompiled with CFR 0_119.
 */
package systemCalls.image;

import imageIO.ImageUtils;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import script.InternalScriptError;
import script.LRhighTokens.TypeDefinition;
import script.Script;
import script.dataObjects.DataObject;
import script.dataObjects.DataType;
import script.dataObjects.ObjObject;
import script.names.NameResolver;
import script.systemCalls.Trap;

public class Trap_RescaleImage
extends Trap {
    public Trap_RescaleImage(Script s) {
        super(s, "rescaleImage");
    }

    @Override
    public DataObject apply() throws InternalScriptError {
        Object hint;
        Object o = this.getObjParam(0, true);
        int width = this.getIntParam(1, true);
        int height = this.getIntParam(2, true);
        int interp = this.getIntParam(3, true);
        if (!(o instanceof BufferedImage)) {
            throw new InternalScriptError("Trap error: The first parameter handed to rescaleImage is no valid image!");
        }
        BufferedImage in = (BufferedImage)o;
        if (width <= 0 || height <= 0) {
            throw new InternalScriptError("Trap error: width and height must be greater than zero, but they are " + width + "," + height);
        }
        if (interp == 0) {
            hint = RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR;
        } else if (interp == 1) {
            hint = RenderingHints.VALUE_INTERPOLATION_BILINEAR;
        } else if (interp == 2) {
            hint = RenderingHints.VALUE_INTERPOLATION_BICUBIC;
        } else {
            throw new InternalScriptError("Trap error: The specified interpolation techinque is not valid!");
        }
        ObjObject obj = new ObjObject(ImageUtils.getScaledInstance(in, width, height, hint, true));
        DataType e = new DataType(this.owner.getNameResolver().getUserDef("Image"));
        obj.explicitCastTo(e);
        return obj;
    }
}