text:
package org.apache.struts2.showcase.person;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;

@Result(location="list-people.ftl", type="freemarker")
public class ListPeopleAction extends ActionSupport {

    private static final long serialVersionUID = 3608017189783645371L;

    PersonManager personManager;
    List people = new ArrayList();

    public void setPersonManager(PersonManager personManager) {
        this.personManager = personManager;
    }

    public String execute() {
        people.addAll(personManager.getPeople());

        return SUCCESS;
    }

    public List getPeople() {
        return people;
    }

    public int getPeopleCount() {
        return people.size();
    }

}


text:
using System;
using System.Collections.Generic;
using UnityEngine;
using Rayman;

public class TargetingSystem{
	private CActorEntity _owner;
	private SensoryMemory _memory;

	private CActorEntity _currTarget = null;
	private float _targetDis = float.MaxValue;

	private Regulator _regulator;

	public TargetingSystem(){
		_regulator = new Regulator(5);
	}

	public void Init(CActorEntity owner, SensoryMemory memory){
		_owner = owner;
		_memory = memory;
	}

	/* 从记忆中, 需找离我们最近的敌人 */
	public void Update(){
		bool isReady = _regulator.Update();
		if (!isReady)return;

		_currTarget = null;
		_targetDis = float.MaxValue;

		List<CActorEntity> opponents = _memory.GetListOfRecentlySensedOpponents();
		if(opponents.Count == 0)return;

		//TODO: 如果视线间有阻挡, 就不会是目标
		for (int i = 0; i < opponents.Count; ++i){
			CActorEntity unit = opponents[i];
			if (unit.dead)continue;

			float dis = AIUtil.ManhattanDistanceBetween(_owner, unit);
			if (dis > _targetDis)continue;

			_targetDis = dis;
			_currTarget = unit;
		}
	}

	public CActorEntity target{
		get{
			if (_currTarget == null)return null;
			if (_currTarget.dead)_currTarget = null;
			return _currTarget;
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
def _extract_match(toc, index, seperator=','):
    """
    Extracts a path between seperators (,)

    :toc (str) Table of contents
    :index (int) Index of match

    returns full path from match
    """
    length = len(toc)
    start_index = index
    while toc[start_index] != seperator and start_index >= 0:
        start_index -= 1
    end_index = index
    while toc[end_index] != seperator and end_index < length - 1:
        end_index += 1
    if end_index == length - 1:
        end_index += 1
    match = toc[start_index+1:end_index].replace(seperator, '')
    return match


text:
using SimpleGraphs
include("algConnectivity.jl")

function DisconnectedEdges(A::Symmetric)
    n = size(A)[1]
    dis = Array(Tuple{Int,Int},0)
    for i = 1:n
        for j = i+1:n
            if A[i,j] == 0
                dis = cat(1,dis,(i,j))
            end
        end
    end
    return dis
end

function SelectGreedyEdge(e::Array,dis::Array)
    # Select the edge that will increase the algebraic centrality the most
    # Input: eigenvector associated with λ_2
    # Output: index where edge should be added
    improv_max = typemin(Float64)
    choice = Tuple{Int,Int}
    for edge in dis
        improv = (e[edge[1]]-e[edge[2]])^2
        x = improv > improv_max
        if improv > improv_max
            improv_max = improv
            choice = edge
        end
    end
    return choice
end

function addEdge!(g::SimpleGraphs.SimpleGraph,e::Tuple,dis::Array)
    # add edge to graph, and delete edge from disconnectedEdges list
    c = maximum(e)
    r = minimum(e)
    add!(g,c,r)
    deleteat!(dis,findin(dis,[e]))
end

function growOptimalA(n,e;prog=false)
    n = 100
    edg = 3*n
    g = RandomTree(n)
    A = Symmetric(adjacency(g))
    disconnectedEdges = DisconnectedEdges(A)
    for i=1:(edg-n+1)
        if mod(i,500) == 0 && prog
            println(i)
        end
        centrality = AlgConnectivity(g,false,vecs=true)
        greedyEdge = SelectGreedyEdge(centrality[2],disconnectedEdges)
        addEdge!(g,greedyEdge,disconnectedEdges)
    end
    c = AlgConnectivity(g,false)
    return g,c
end


text:
package com.lv.filter;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.BASE64Decoder;

/**
 * 拦截器
 */
public class HTTPBasicAuthorizeAttribute implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        int resultStatusCode = checkHTTPBasicAuthorize(request);
        if (resultStatusCode != 200) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.setContentType("application/json; charset=utf-8");
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

            ObjectMapper mapper = new ObjectMapper();
            Map<String, String> map = new HashMap<>();
            map.put("code", "100");
            map.put("message", "你还没有登录呢!");
            httpResponse.getWriter().write(mapper.writeValueAsString(map));
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

    private int checkHTTPBasicAuthorize(ServletRequest request) {
        try {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            String auth = httpRequest.getHeader("Authorization");
            if ((auth != null) && (auth.length() > 6)) {
                String HeadStr = auth.substring(0, 5).toLowerCase();
                if (HeadStr.compareTo("basic") == 0) {
                    auth = auth.substring(6, auth.length());
                    String decodedAuth = getFromBASE64(auth);
                    if (decodedAuth != null) {
                        String[] UserArray = decodedAuth.split(":");

                        if (UserArray != null && UserArray.length == 2) {
                            String name = "test";
                            String password = "test";
                            if (UserArray[0].compareTo(name) == 0 && UserArray[1].compareTo(password) == 0) {
                                return 200;
                            }
                        }
                    }
                }
            }
            return 100;
        } catch (Exception ex) {
            return 100;
        }

    }

    private String getFromBASE64(String s) {
        if (s == null)
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return new String(b);
        } catch (Exception e) {
            return null;
        }
    }

}


text:
package gherkin.lexer;

public interface Lexer {
    /**
     * Lexes the source.
     *
     * @param source a string containing Gherkin source.
     */
    public void scan(String source);
}


text:
#ifndef _ASM_STRING_H_
#define _ASM_STRING_H_

#ifdef __KERNEL__ /* only set these up for kernel code */

#define __HAVE_ARCH_MEMSET 1
#define __HAVE_ARCH_MEMCPY 1

extern void *memset(void *, int, __kernel_size_t);
extern void *memcpy(void *, const void *, __kernel_size_t);

#else /* KERNEL */

/*
 *	let user libraries deal with these,
 *	IMHO the kernel has no place defining these functions for user apps
 */

#define __HAVE_ARCH_STRCPY 1
#define __HAVE_ARCH_STRNCPY 1
#define __HAVE_ARCH_STRCAT 1
#define __HAVE_ARCH_STRNCAT 1
#define __HAVE_ARCH_STRCMP 1
#define __HAVE_ARCH_STRNCMP 1
#define __HAVE_ARCH_STRCHR 1
#define __HAVE_ARCH_STRRCHR 1
#define __HAVE_ARCH_STRSTR 1
#define __HAVE_ARCH_STRLEN 1
#define __HAVE_ARCH_STRNLEN 1
#define __HAVE_ARCH_MEMSET 1
#define __HAVE_ARCH_MEMCPY 1
#define __HAVE_ARCH_MEMMOVE 1
#define __HAVE_ARCH_MEMSCAN 1
#define __HAVE_ARCH_MEMCMP 1
#define __HAVE_ARCH_MEMCHR 1
#define __HAVE_ARCH_STRTOK 1

#endif /* KERNEL */
#endif /* _ASM_STRING_H_ */


text:
using CharacterMap.Core;
using CharacterMap.Helpers;
using CharacterMap.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;

namespace CharacterMap.Services
{
    public class AddToCollectionResult
    {
        public AddToCollectionResult(bool success, InstalledFont font, UserFontCollection collection)
        {
            Success = success;
            Font = font;
            Collection = collection;
        }

        public InstalledFont Font { get; }
        public bool Success { get; }
        public UserFontCollection Collection { get; }

        public string GetMessage()
        {
            if (Collection.IsSystemSymbolCollection)
                return Localization.Get("NotificationAddedToCollection", Font.Name, Localization.Get("OptionSymbolFonts/Text"));
            else
                return Localization.Get("NotificationAddedToCollection", Font.Name, Collection.Name);
        }
    }

    public class UserCollectionsService
    {
        private UserFontCollection _symbolCollection = null;
        public UserFontCollection SymbolCollection
        {
            get => _symbolCollection;
            set { value.IsSystemSymbolCollection = true; _symbolCollection = value; }
        }
        public List<UserFontCollection> Items { get; private set; } = new List<UserFontCollection>();

        private StorageFolder _collectionsFolder;

        public bool IsSymbolFont(InstalledFont font)
        {
            return font != null && (font.IsSymbolFont || SymbolCollection.Fonts.Contains(font.Name));
        }

        public async Task LoadCollectionsAsync()
        {
            List<UserFontCollection> collections = new List<UserFontCollection>();

            if (Items.Count > 0)
                return;

            await Task.Run(async () =>
            {
                var folder = _collectionsFolder = await GetCollectionsFolderAsync().AsTask().ConfigureAwait(false);
                var files = await folder.GetFilesAsync().AsTask().ConfigureAwait(false);

                var tasks = files.Select(file =>
                {
                    return Task.Run(async () =>
                    {
                        try
                        {
                            UserFontCollection collection;
                            if (file.FileType == ".json")
                                collection = await ConvertFromLegacyFormatAsync(file, folder).ConfigureAwait(false);
                            else
                                collection = await LoadCollectionAsync(file).ConfigureAwait(false);

                            return collection;
                        }
                        catch
                        {
                            // Possibly corrupted. What to do? Delete file?
                            return null;
                        }
                    });
                }).ToList();

                await Task.WhenAll(tasks).ConfigureAwait(false);

                foreach (var task in tasks)
                {
                    if (task.Result is UserFontCollection collection)
                    {
                        if (collection.File.DisplayName != "Symbol")
                        {
                            collections.Add(collection);
                        }
                        else
                        {
                            SymbolCollection = collection;
                        }
                    }
                }

                if (SymbolCollection == null)
                {
                    SymbolCollection = await CreateCollectionAsync("Symbol", "Symbol").ConfigureAwait(false);
                }

                collections = collections.OrderBy(c => c.Name).ToList();
            });

            Items.Clear();
            Items.AddRange(collections);
        }

        public bool DoesCollectionExist(string name)
        {
            return TryGetCollection(name) != null;
        }

        public UserFontCollection TryGetCollection(string name)
        {
            return Items.FirstOrDefault(i => string.CompareOrdinal(i.Name, name) > 0);
        }

        public async Task<UserFontCollection> CreateCollectionAsync(string name, string fileName = null)
        {
            var file = await _collectionsFolder.CreateFileAsync(
                $"{fileName ?? Guid.NewGuid().ToString()}", CreationCollisionOption.GenerateUniqueName).AsTask().ConfigureAwait(false);

            var collection = new UserFontCollection { Name = name, File = file };
            await SaveCollectionAsync(collection).ConfigureAwait(false);

            if (fileName == null)
            {
                Items.Add(collection);
                Items = Items.OrderBy(i => i.Name).ToList();
            }

            return collection;
        }

        public async Task DeleteCollectionAsync(UserFontCollection collection)
        {
            await collection.File.DeleteAsync().AsTask().ConfigureAwait(false);
            Items.Remove(collection);
        }

        public async Task RenameCollectionAsync(string name, UserFontCollection collection)
        {
            collection.Name = name;
            await SaveCollectionAsync(collection).ConfigureAwait(false);
            Items = Items.OrderBy(i => i.Name).ToList();
        }

        public Task SaveCollectionAsync(UserFontCollection collection)
        {
            return Task.Run(async () =>
            {
                using var stream = await collection.File.OpenStreamForWriteAsync().ConfigureAwait(false);
                using var reader = new StreamWriter(stream);
                stream.SetLength(0);
                reader.Write(collection.Name);
                foreach (var item in collection.Fonts)
                {
                    reader.WriteLine();
                    reader.Write(item);
                }
            });

        }

        public async Task<AddToCollectionResult> AddToCollectionAsync(InstalledFont font, UserFontCollection collection)
        {
            if (!collection.Fonts.Contains(font.Name))
            {
                collection.Fonts.Add(font.Name);
                await SaveCollectionAsync(collection);
                return new AddToCollectionResult(true, font, collection);
            }

            return new AddToCollectionResult(false, null, null);
        }

        public Task RemoveFromCollectionAsync(InstalledFont font, UserFontCollection collection)
        {
            if (collection.Fonts.Remove(font.Name))
            {
                return SaveCollectionAsync(collection);
            }

            return Task.CompletedTask;
        }

        public async Task RemoveFromAllCollectionsAsync(InstalledFont font)
        {
            if (SymbolCollection.Fonts.Contains(font.Name))
                await RemoveFromCollectionAsync(font, SymbolCollection).ConfigureAwait(false);

            foreach (var collection in Items)
            {
                if (collection.Fonts.Contains(font.Name))
                    await RemoveFromCollectionAsync(font, collection).ConfigureAwait(false);
            }
        }

        private IAsyncOperation<StorageFolder> GetCollectionsFolderAsync()
        {
            return ApplicationData.Current.LocalCacheFolder.CreateFolderAsync("Collections", CreationCollisionOption.OpenIfExists);
        }

        private async Task<UserFontCollection> LoadCollectionAsync(StorageFile file)
        {
            string name;
            HashSet<string> items = new HashSet<string>();

            using (var stream = await file.OpenStreamForReadAsync().ConfigureAwait(false))
            using (var reader = new StreamReader(stream))
            {
                name = reader.ReadLine();
                while (!reader.EndOfStream)
                    items.Add(reader.ReadLine());
            }

            return new UserFontCollection { File = file, Fonts = items, Name = name };
        }

        private async Task<UserFontCollection> ConvertFromLegacyFormatAsync(StorageFile file, StorageFolder folder)
        {
            // Legacy Collection format used .json files.
            // JSON lib was dropped to improve perf and reduce RAM,
            // so manually parse.

            string name;
            HashSet<string> items = new HashSet<string>();

            using (var stream = await file.OpenStreamForReadAsync().ConfigureAwait(false))
            using (var reader = new StreamReader(stream))
            {
                string s = reader.ReadToEnd();

                //{"Name":"
                s = s.Remove(0, 9);
                var i = s.IndexOf("\"");
                name = s.Substring(0, i);
                s = s.Remove(0, s.IndexOf("[") + 1);

                while (true)
                {
                    var c = s.IndexOf(",");
                    if (c >= 0)
                    {
                        var n = s.Substring(1, c - 2);
                        items.Add(n);
                        s = s.Remove(0, c + 1);
                    }
                    else
                    {
                        s = s.Replace("]}", string.Empty);
                        if (s.Length > 2)
                        {
                            s = s.Substring(1, s.Length - 2);
                            if (!string.IsNullOrEmpty(s))
                                items.Add(s);
                        }

                        break;
                    }
                }
            }

            var collection = new UserFontCollection { File = file, Fonts = items, Name = name };
            var newFile = await folder.CreateFileAsync(file.DisplayName, CreationCollisionOption.OpenIfExists).AsTask().ConfigureAwait(false);
            collection.File = newFile;
            await SaveCollectionAsync(collection).ConfigureAwait(false);
            await file.DeleteAsync().AsTask().ConfigureAwait(false);
            return collection;
        }
    }
}


text:
package logger;

abstract public class Log {

    public static void log(String msg, String ip, String socket, int port) {
        WriteLog.serverLogger(msg, ip, socket, port);
    }
}


text:
require "testing_env"

class IntegrationCommandTests < Homebrew::TestCase
  def cmd_output(*args)
    cmd_args = %W[
      -W0
      -I#{HOMEBREW_LIBRARY_PATH}/test/lib
      -rconfig
    ]
    cmd_args << "-rsimplecov" if ENV["HOMEBREW_TESTS_COVERAGE"]
    cmd_args << (HOMEBREW_LIBRARY_PATH/"../brew.rb").resolved_path.to_s
    cmd_args += args
    Bundler.with_original_env do
      ENV["HOMEBREW_BREW_FILE"] = HOMEBREW_PREFIX/"bin/brew"
      ENV["HOMEBREW_INTEGRATION_TEST"] = args.join " "
      ENV["HOMEBREW_TEST_TMPDIR"] = TEST_TMPDIR
      Utils.popen_read(RUBY_PATH, *cmd_args).chomp
    end
  end

  def cmd(*args)
    output = cmd_output(*args)
    assert_equal 0, $?.exitstatus
    output
  end

  def cmd_fail(*args)
    output = cmd_output(*args)
    assert_equal 1, $?.exitstatus
    output
  end

  def testball
    "#{File.expand_path("..", __FILE__)}/testball.rb"
  end

  def test_prefix
    assert_equal HOMEBREW_PREFIX.to_s,
                 cmd("--prefix")
  end

  def test_version
    assert_match HOMEBREW_VERSION.to_s,
                 cmd("--version")
  end

  def test_cache
    assert_equal HOMEBREW_CACHE.to_s,
                 cmd("--cache")
  end

  def test_cache_formula
    assert_match %r{#{HOMEBREW_CACHE}/testball-},
                 cmd("--cache", testball)
  end

  def test_cellar
    assert_equal HOMEBREW_CELLAR.to_s,
                 cmd("--cellar")
  end

  def test_cellar_formula
    assert_match "#{HOMEBREW_CELLAR}/testball",
                 cmd("--cellar", testball)
  end

  def test_env
    assert_match /CMAKE_PREFIX_PATH="#{HOMEBREW_PREFIX}[:"]/,
                 cmd("--env")
  end

  def test_prefix_formula
    assert_match "#{HOMEBREW_CELLAR}/testball",
                 cmd("--prefix", testball)
  end

  def test_repository
    assert_match HOMEBREW_REPOSITORY.to_s,
                 cmd("--repository")
  end
end


text:
/**
 * EECE 252 Example Code
 * AVR Standard I/O over UART: Universal Asynchronous Receiver / Transmitter
 *
 * Allows you to use printf/scanf using your AVR and a USB-to-serial converter,
 * like the Bus Pirate. If you're about to use this to gather debug information,
 * you might want to see if the Logic Analyzer isn't a better fit to your needs.
 */

//If you do not specify F_CPU at the compile time (e.g. on the GCC command line),
//assume 8MHz.
#ifndef F_CPU
#define F_CPU 8000000UL
#endif

//If you do not specify BAUD at the compile time (e.g. on the GCC command line),
//assume 19.2k-baud.
#ifndef BAUD
#define BAUD 19200
#endif

#include <avr/io.h>
#include <util/setbaud.h>
#include <stdio.h>

#include "uart_communications.h"

#define USART_STATUS        UCSR0A
#define READY_TO_TRANSMIT   UDRE0
#define DATA_RECIEVED       RXC0

#define USE_EIGHT_BIT_DATA

//Set up function: sets up stdin/stdout for use with printf/scanf.
static inline void set_up_special_files();

//Functions that wait for transmission or receipt to occur.
static void wait_until_ready_to_transmit();
static void wait_until_data_is_received();

//Low-level functions which directly modify the transmit/receieve buffers.
static void place_into_transmit_buffer(char c);
static inline char read_contents_of_receive_buffer();

//Special wrapper functions which allow use of this library with printf, scanf, and other stdio functions.
static inline int send_via_uart_stdio_compatible(char c, FILE * pipe_to_transmit_from);
static inline int receieve_via_uart_stdio_compatible(FILE * pipe_to_receive_into);

//Create an input and output "pipe" device, which can be used as stdin/out/error replacements.
static FILE uart_transmit_pipe = FDEV_SETUP_STREAM(send_via_uart_stdio_compatible, NULL, _FDEV_SETUP_WRITE);
static FILE uart_receive_pipe  = FDEV_SETUP_STREAM(NULL, receieve_via_uart_stdio_compatible, _FDEV_SETUP_READ);

/**
 * Sets up the device to use STDIO over serial.
 */
void set_up_stdio_over_serial() {
    initialize_uart();
    set_up_special_files();
}

/**
 * Sets up the raw UART (Universal Asynchronous Receiver/Transmitter) for general use.
 * Does not set up the UART for use with stdin/stdout/stderr.
 */
void initialize_uart() {

    //These values are automatically generated by <util/setbaud.h>
    //They're a tad
    UBRR0H = UBRRH_VALUE;
    UBRR0L = UBRRL_VALUE;

    #if USE_2X
      UCSR0A |= _BV(U2X0);
    #else
      UCSR0A &= ~(_BV(U2X0));
    #endif

    //Set up use of 8-bit data packets...
    UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);

    //And take ownership of the Rx/Tx lines on the AVR.
    UCSR0B = (1 << RXEN0)  | (1 << TXEN0);
}

/**
 * Sends the provided character over the serial line.
 */
inline void send_via_uart(char c) {
  wait_until_ready_to_transmit();
  place_into_transmit_buffer(c);
}

/**
 * Waits for and recieves a single character over the serial line.
 *
 * This kind of function is known as a "blocking" function-- as execution
 * can't continue until it's complete!
 */
inline char receieve_via_uart() {
  wait_until_data_is_received();
  return read_contents_of_receive_buffer();
}

/**
 * Sets up the standard 'pipes' (stdio, stdout, and stderr) to transmit
 * over the serial line.
 */
static inline void set_up_special_files() {

  //Replace the standard output and standard error with our new transmission
  //method. We treat the output and error identically, as we only have one line
  //with which to send data.
  stdout = stderr = &uart_transmit_pipe;

  //Replace the standard input with our new reciept method.
  stdin = &uart_receive_pipe;
}

/**
 * A wrapper for send_via_uart which is compatible with the standard I/O functions.
 */
static inline int send_via_uart_stdio_compatible(char character, FILE * output_file) {

  //The standard I/O functions end their line with '\n', but most serial terminals
  //expect \r\n. If we're about to send a \n, we interject a '\r' first.
  if(character == '\n') {
    send_via_uart('\r');
  }

  send_via_uart(character);

  return 1;
}

/**
 * A wrapper for receieve_via_uart which is compatible with the standard I/O functions.
 */
static inline int receieve_via_uart_stdio_compatible(FILE * input_file) {
  return receieve_via_uart();
}

/**
 * Places a single character directly into the transmit buffer,
 * initiating transmission.
 */
static inline void place_into_transmit_buffer(char c) {
    UDR0 = c;
}

/**
 * Returns the current content of the recieve buffer,
 * and (indirectly) clears the read buffer.
 */
static inline char read_contents_of_receive_buffer() {
  return UDR0;
}

/**
 * Waits until the device is ready to transmit-- we may have to wait
 * if the device still is in the proces of transmitting data.
 */
static inline void wait_until_ready_to_transmit() {
    loop_until_bit_is_set(USART_STATUS, READY_TO_TRANSMIT);
}

/**
 * Waits until we've recieved at least a single byte of data.
 */
static inline void wait_until_data_is_received() {
    loop_until_bit_is_set(USART_STATUS, DATA_RECIEVED);
}


text:
Activates a standby coordinator host and makes it the active coordinator for the Greenplum Database system.

## Synopsis

```
gpactivatestandby [-d <standby_coordinator_datadir>] [-f] [-a] [-q]
    [-l <logfile_directory>]

gpactivatestandby -v

gpactivatestandby -? | -h | --help
```

## Description

The `gpactivatestandby` utility activates a backup, standby coordinator host and brings it into operation as the active coordinator instance for a Greenplum Database system. The activated standby coordinator effectively becomes the Greenplum Database coordinator, accepting client connections on the coordinator port.

When you initialize a standby coordinator, the default is to use the same port as the active coordinator. For information about the coordinator port for the standby coordinator, see [gpinitstandby](gpinitstandby.html).

You must run this utility from the coordinator host you are activating, not the failed coordinator host you are deactivating. Running this utility assumes you have a standby coordinator host configured for the system \(see [gpinitstandby](gpinitstandby.html)\).

The utility will perform the following steps:

-   Stops the synchronization process \(`walreceiver`\) on the standby coordinator
-   Updates the system catalog tables of the standby coordinator using the logs
-   Activates the standby coordinator to be the new active coordinator for the system
-   Restarts the Greenplum Database system with the new coordinator host

A backup, standby Greenplum coordinator host serves as a 'warm standby' in the event of the primary Greenplum coordinator host becoming non-operational. The standby coordinator is kept up to date by transaction log replication processes \(the `walsender` and `walreceiver`\), which run on the primary coordinator and standby coordinator hosts and keep the data between the primary and standby coordinator hosts synchronized.

If the primary coordinator fails, the log replication process is shutdown, and the standby coordinator can be activated in its place by using the `gpactivatestandby` utility. Upon activation of the standby coordinator, the replicated logs are used to reconstruct the state of the Greenplum coordinator host at the time of the last successfully committed transaction.

In order to use `gpactivatestandby` to activate a new primary coordinator host, the coordinator host that was previously serving as the primary coordinator cannot be running. The utility checks for a `postmaster.pid` file in the data directory of the deactivated coordinator host, and if it finds it there, it will assume the old coordinator host is still active. In some cases, you may need to remove the `postmaster.pid` file from the deactivated coordinator host data directory before running `gpactivatestandby` \(for example, if the deactivated coordinator host process was terminated unexpectedly\).

After activating a standby coordinator, run `ANALYZE` to update the database query statistics. For example:

```
psql <dbname> -c 'ANALYZE;'
```

After you activate the standby coordinator as the primary coordinator, the Greenplum Database system no longer has a standby coordinator configured. You might want to specify another host to be the new standby with the [gpinitstandby](gpinitstandby.html) utility.

## Options

-a \(do not prompt\)
:   Do not prompt the user for confirmation.

-d standby\_coordinator\_datadir
:   The absolute path of the data directory for the coordinator host you are activating.

:   If this option is not specified, `gpactivatestandby` uses the value of the `COORDINATOR_DATA_DIRECTORY` environment variable setting on the coordinator host you are activating. If this option is specified, it overrides any setting of `COORDINATOR_DATA_DIRECTORY`.

:   If a directory cannot be determined, the utility returns an error.

-f \(force activation\)
:   Use this option to force activation of the backup coordinator host. Use this option only if you are sure that the standby and primary coordinator hosts are consistent.

-l logfile\_directory
:   The directory to write the log file. Defaults to `~/gpAdminLogs`.

-q \(no screen output\)
:   Run in quiet mode. Command output is not displayed on the screen, but is still written to the log file.

-v \(show utility version\)
:   Displays the version, status, last updated date, and check sum of this utility.

-? \| -h \| --help \(help\)
:   Displays the online help.

## Example

Activate the standby coordinator host and make it the active coordinator instance for a Greenplum Database system \(run from backup coordinator host you are activating\):

```
gpactivatestandby -d /gpdata
```

## See Also

[gpinitsystem](gpinitsystem.html), [gpinitstandby](gpinitstandby.html)


text:
Sacred Texts
Legends and Sagas
Celtic
Index
Previous
Next

Traditions and Hearthside Stories of West Cornwall, Vol. 2, by William Bottrell, [1873], at sacred-texts.com

The Mermaid of Zennor.

Zennor folks tell the following story, which, according to them, accounts for a singular carving on a bench-end in their Church.

Hundreds of years ago a very beautiful and richly attired lady attended service in Zennor Church occasionally—now and then she went to Morvah also;—her visits were by no means regular,—often long intervals would elapse between them.

Yet whenever she came the people were enchanted with her good looks and sweet singing. Although Zennor folks were remarkable for their fine psalmody, she excelled them all; and they wondered how, after the scores of years that they had seen

p. 289

her, she continued to look so young and fair. No one knew whence she came nor whither she went; yet many watched her as far as they could see from Tregarthen Hill.

She took some notice of a fine young man, called Mathey Trewella, who was the best singer in the parish. He once followed her, but he never returned; after that she was never more seen in Zennor Church, and it might not have been known to this day who or what she was but for the merest accident.

One Sunday morning a vessel cast anchor about a mile from Pendower Cove; soon after a mermaid came close alongside and hailed the ship. Rising out of the water as far as her waist, with her yellow hair floating around her, she told the captain that she was returning from church, and requested him to trip his anchor just for a minute, as the fluke of it rested on the door of her dwelling, and she was anxious to get in to her children.

Others say that while she was out on the ocean a-fishing of a Sunday morning, the anchor was dropped on the trap-door which gave access to her submarine abode. Finding, on her return, how she was hindered from opening her door, she begged the captain to have the anchor raised that she might enter her dwelling to dress her children and be ready in time for church.

However it may be, her polite request had a magical effect upon the sailors, for they immediately "worked with a will," hove anchor and set sail, not wishing to remain a moment longer than they could help near her habitation. Sea-faring men, who understood most about mermaids, regarded their appearance as a token that bad luck was near at hand. It was believed they could take such shapes as suited their purpose, and that they had often allured men to live with them.

When Zennor folks learnt that a mermaid dwelt near Pen-dower, and what she had told the captain, they concluded—it was, this sea-lady who had visited their church, and enticed Trewella to her abode. To commemorate these somewhat unusual events they had the figure she bore—when in her ocean-home—carved in holy-oak, which may still be seen.

Click to enlarge

Next: Glossary of Local Words


text:
<?php

namespace Larabros\Dockstead;

use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\ProcessBuilder;

trait ProcessTrait
{
    /**
     * Builds a ``Process``.
     *
     * @param array $process
     *
     * @return Process
     */
    protected function createProcess(array $process)
    {
        return (new ProcessBuilder($process))->getProcess();
    }

    /**
     * Runs a ``Process``.
     *
     * @param Process $process
     *
     * @return string
     *
     * @throws ProcessFailedException
     */
    protected function runProcess(Process $process)
    {
        try {
            $process->mustRun();
            $message = $process->getOutput();
        } catch (ProcessFailedException $e) {
            $message = '<error>'.$e->getMessage().'</error>';
        }

        return $message;
    }
}


text:
package obsmetrics // import "go.opentelemetry.io/collector/internal/obsreportconfig/obsmetrics"

import (
	"go.opencensus.io/stats"
	"go.opencensus.io/tag"
)

const (
	// ExporterKey used to identify exporters in metrics and traces.
	ExporterKey = "exporter"

	// SentSpansKey used to track spans sent by exporters.
	SentSpansKey = "sent_spans"
	// FailedToSendSpansKey used to track spans that failed to be sent by exporters.
	FailedToSendSpansKey = "send_failed_spans"

	// SentMetricPointsKey used to track metric points sent by exporters.
	SentMetricPointsKey = "sent_metric_points"
	// FailedToSendMetricPointsKey used to track metric points that failed to be sent by exporters.
	FailedToSendMetricPointsKey = "send_failed_metric_points"

	// SentLogRecordsKey used to track logs sent by exporters.
	SentLogRecordsKey = "sent_log_records"
	// FailedToSendLogRecordsKey used to track logs that failed to be sent by exporters.
	FailedToSendLogRecordsKey = "send_failed_log_records"
)

var (
	TagKeyExporter, _ = tag.NewKey(ExporterKey)

	ExporterPrefix                 = ExporterKey + NameSep
	ExportTraceDataOperationSuffix = NameSep + "traces"
	ExportMetricsOperationSuffix   = NameSep + "metrics"
	ExportLogsOperationSuffix      = NameSep + "logs"

	// Exporter metrics. Any count of data items below is in the final format
	// that they were sent, reasoning: reconciliation is easier if measurements
	// on backend and exporter are expected to be the same. Translation issues
	// that result in a different number of elements should be reported in a
	// separate way.
	ExporterSentSpans = stats.Int64(
		ExporterPrefix+SentSpansKey,
		"Number of spans successfully sent to destination.",
		stats.UnitDimensionless)
	ExporterFailedToSendSpans = stats.Int64(
		ExporterPrefix+FailedToSendSpansKey,
		"Number of spans in failed attempts to send to destination.",
		stats.UnitDimensionless)
	ExporterSentMetricPoints = stats.Int64(
		ExporterPrefix+SentMetricPointsKey,
		"Number of metric points successfully sent to destination.",
		stats.UnitDimensionless)
	ExporterFailedToSendMetricPoints = stats.Int64(
		ExporterPrefix+FailedToSendMetricPointsKey,
		"Number of metric points in failed attempts to send to destination.",
		stats.UnitDimensionless)
	ExporterSentLogRecords = stats.Int64(
		ExporterPrefix+SentLogRecordsKey,
		"Number of log record successfully sent to destination.",
		stats.UnitDimensionless)
	ExporterFailedToSendLogRecords = stats.Int64(
		ExporterPrefix+FailedToSendLogRecordsKey,
		"Number of log records in failed attempts to send to destination.",
		stats.UnitDimensionless)
)


text:
<title>Class: 'NMR sample identifier'</title>
<meta http-equiv='content-type' content='text/html;charset=utf8'>
<link rel='stylesheet' href='../default.css' type='text/css' />

Class: 'NMR sample identifier'

http://nmrML.org/nmrCV#NMR:1400124

Annotations (3)

comment "PRS: rename 'reference' to 'identifier'" (en)

comment "def: A reference to information on the provenance of the NMR sample.
   synonym: NMR sample reference" (string)

label "NMR sample identifier" (string)

Superclasses (1)

'external reference identifier'

Usage (1)

Class: 'NMR sample identifier'


text:
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.Linq;

// Editor window for replacing all sprites in animation clips
public class ReplaceSpritesInClip : EditorWindow
{
	// The original sprite's text you want to replace
	private string originalSpriteText = "";

	// The sprite's text you want to change to
	private string replaceSpriteText = "";

	// Bool to track if the button was pushed
	private bool changeAllSprites = false;
	private static int columnWidth = 300;

	// Sprites of the clip
	private Sprite[] sprites;

	// Animation clips selected to change
	private List<AnimationClip> animationClips;

	// Current scroll position
	private Vector2 scrollPos = Vector2.zero;

	// Re-initialize animation clips on creation
	public ReplaceSpritesInClip(){
		animationClips = new List<AnimationClip>();
	}

	// On changing the selection update the animation clips to change
	void OnSelectionChange() {
		if (Selection.objects.Length > 1 )
		{
			Debug.Log ("Length? " + Selection.objects.Length);
			animationClips.Clear();
			foreach ( Object o in Selection.objects )
			{
				if ( o is AnimationClip ) animationClips.Add((AnimationClip)o);
			}
		}
		else if (Selection.activeObject is AnimationClip) {
			animationClips.Clear();
			animationClips.Add((AnimationClip)Selection.activeObject);
		} else {
			animationClips.Clear();
		}

		this.Repaint();
	}

	[MenuItem ("Window/Animation Replace Sprites")]
	static void Init ()
	{
		GetWindow (typeof (ReplaceSpritesInClip));
	}

	public void OnGUI()
	{
		// Make sure there is at least one animation clip selected
		if (animationClips.Count > 0 ) {
			scrollPos = GUILayout.BeginScrollView(scrollPos, GUIStyle.none);

			EditorGUILayout.BeginHorizontal();
			GUILayout.Label("Animation Clip:", GUILayout.Width(columnWidth));

			if ( animationClips.Count == 1 )
			{
				animationClips[0] = ((AnimationClip)EditorGUILayout.ObjectField(
					animationClips[0],
					typeof(AnimationClip),
					true,
					GUILayout.Width(columnWidth))
					);
			}
			else
			{
				GUILayout.Label("Multiple Anim Clips: " + animationClips.Count, GUILayout.Width(columnWidth));
			}
			EditorGUILayout.EndHorizontal();

			GUILayout.Space(20);

			EditorGUILayout.BeginHorizontal();

			EditorGUILayout.LabelField ("Sprites:");

			EditorGUILayout.EndHorizontal();

			EditorGUILayout.BeginHorizontal();

			GUILayout.Label("Original Sprite Text:", GUILayout.Width(columnWidth));
			GUILayout.Label("Replacement Sprite Text:", GUILayout.Width(columnWidth));

			EditorGUILayout.EndHorizontal();

			EditorGUILayout.BeginHorizontal();
			originalSpriteText = EditorGUILayout.TextField(originalSpriteText, GUILayout.Width(columnWidth));
			replaceSpriteText = EditorGUILayout.TextField(replaceSpriteText, GUILayout.Width(columnWidth));
			if (GUILayout.Button("Replace All Sprites")) {
				changeAllSprites = true;
			}

			EditorGUILayout.EndHorizontal();

			// Iterate through the animation clips
			foreach (AnimationClip clip in animationClips) {

				// Iterate through the bindings for the current animation clip
				foreach (var binding in AnimationUtility.GetObjectReferenceCurveBindings (clip))
				{
					// If the binding is a sprite type then get the keyframes
					if (binding.propertyName == "m_Sprite") {
						// Get the keyframes for this sprite
						ObjectReferenceKeyframe[] keyframes = AnimationUtility.GetObjectReferenceCurve (clip, binding);
						// Show the sprite's path and the keyframes length for this binding
						EditorGUILayout.LabelField (binding.path + "/" + binding.propertyName + ", Keys: " + keyframes.Length);

						// Loop through the keyframes to change the sprite
						for (int i = 0; i < keyframes.Length; i++) {
							// If the button is pushed then change the sprite
							if (changeAllSprites) {
								// The keyframe's value is the sprite
								Sprite keyframeSprite = (Sprite)keyframes[i].value;
								// If the sprite exists get the name of the sprite
								if (keyframeSprite != null) {
									string spriteName = keyframeSprite.name;
									// Replace the text in the sprite's name to the replacement text
									string newSpriteName = spriteName.Replace(originalSpriteText, replaceSpriteText);
									Debug.Log(newSpriteName);

									// Get all the sprites in the project
									GetAllSprites();

									// Make sure we have at least one sprite
									if (sprites.Length > 0) {
										// Loop through all the sprites to get the one matching the new sprite name
										foreach (Sprite sprite in sprites) {
											if (sprite != null && sprite.name == newSpriteName) {
												// Cache the time for this keyframe
												float timeForKey = keyframes[i].time;
												// Create a new ObjectReferenceKeyframe for the sprite
												keyframes[i] = new ObjectReferenceKeyframe();
												// set the time
												keyframes[i].time = timeForKey;
												// set reference for the sprite you want
												keyframes[i].value = sprite;
												// Set the new keyframes to the binding of the animation clip
												AnimationUtility.SetObjectReferenceCurve(clip, binding, keyframes);
												Debug.Log("Sprite changed to " + sprite.name);
												// Break the loop since we already found it
												break;
											}
										}
									}
								}
							}
							// Show the sprite in the editor window
							EditorGUILayout.ObjectField (keyframes[i].value, typeof (Sprite), false);
						}
					}
				}
			}
			// Reset the button if pushed
			changeAllSprites = false;
			GUILayout.Space(40);
			GUILayout.EndScrollView();
		} else {
			GUILayout.Label("Please select an Animation Clip");
		}
	}

	void OnInspectorUpdate() {
		this.Repaint();
	}

	// Get all the sprites in the project
	void GetAllSprites() {
		// Possible file extensions for the sprite images
		string[] extensions = new string[] {".png",".psd",".jpg",".bmp"};
		// Get all the files with those extensions
		string[] files = AssetDatabase.GetAllAssetPaths().Where(x=>extensions.Contains(System.IO.Path.GetExtension(x))).ToArray();

		// Create a sprite list and add sprites to this list
		List<Sprite> spriteList = new List<Sprite>();
		foreach (string filename in files) {
			Object[] objects = AssetDatabase.LoadAllAssetRepresentationsAtPath(filename);
			spriteList.AddRange(objects.Select(x=>(x as Sprite)).ToList());
		}
		// Convert the list to an array for this window to use
		sprites = spriteList.ToArray();
	}
}


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/arc/net/arc_net_host_impl.h"

#include <utility>

#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/posix/eintr_wrapper.h"
#include "base/stl_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "chromeos/login/login_state/login_state.h"
#include "chromeos/network/device_state.h"
#include "chromeos/network/managed_network_configuration_handler.h"
#include "chromeos/network/network_configuration_handler.h"
#include "chromeos/network/network_connection_handler.h"
#include "chromeos/network/network_handler.h"
#include "chromeos/network/network_state.h"
#include "chromeos/network/network_state_handler.h"
#include "chromeos/network/network_type_pattern.h"
#include "chromeos/network/network_util.h"
#include "chromeos/network/onc/onc_utils.h"
#include "components/arc/arc_browser_context_keyed_service_factory_base.h"
#include "components/arc/arc_prefs.h"
#include "components/arc/session/arc_bridge_service.h"
#include "components/prefs/pref_service.h"
#include "components/user_manager/user_manager.h"
#include "third_party/cros_system_api/dbus/shill/dbus-constants.h"

namespace {

constexpr int kGetNetworksListLimit = 100;
// Delay in millisecond before asking for a network property update when no IP
// configuration can be retrieved for a network.
constexpr base::TimeDelta kNetworkPropertyUpdateDelay =
    base::TimeDelta::FromMilliseconds(5000);

chromeos::NetworkStateHandler* GetStateHandler() {
  return chromeos::NetworkHandler::Get()->network_state_handler();
}

chromeos::ManagedNetworkConfigurationHandler* GetManagedConfigurationHandler() {
  return chromeos::NetworkHandler::Get()
      ->managed_network_configuration_handler();
}

chromeos::NetworkConnectionHandler* GetNetworkConnectionHandler() {
  return chromeos::NetworkHandler::Get()->network_connection_handler();
}

std::vector<const chromeos::NetworkState*> GetActiveNetworks() {
  std::vector<const chromeos::NetworkState*> active_networks;
  GetStateHandler()->GetActiveNetworkListByType(
      chromeos::NetworkTypePattern::Default(), &active_networks);
  return active_networks;
}

bool IsDeviceOwner() {
  // Check whether the logged-in Chrome OS user is allowed to add or remove WiFi
  // networks. The user account state changes immediately after boot. There is a
  // small window when this may return an incorrect state. However, after things
  // settle down this is guranteed to reflect the correct user account state.
  return user_manager::UserManager::Get()->GetActiveUser()->GetAccountId() ==
         user_manager::UserManager::Get()->GetOwnerAccountId();
}

std::string GetStringFromONCDictionary(const base::Value* dict,
                                       const char* key,
                                       bool required) {
  DCHECK(dict->is_dict());
  const base::Value* string_value =
      dict->FindKeyOfType(key, base::Value::Type::STRING);
  if (!string_value) {
    LOG_IF(ERROR, required) << "Required property " << key << " not found.";
    return std::string();
  }
  std::string result = string_value->GetString();
  LOG_IF(ERROR, required && result.empty())
      << "Required property " << key << " is empty.";
  return result;
}

arc::mojom::SecurityType TranslateONCWifiSecurityType(
    const base::DictionaryValue* dict) {
  std::string type = GetStringFromONCDictionary(dict, onc::wifi::kSecurity,
                                                true /* required */);
  if (type == onc::wifi::kWEP_PSK)
    return arc::mojom::SecurityType::WEP_PSK;
  if (type == onc::wifi::kWEP_8021X)
    return arc::mojom::SecurityType::WEP_8021X;
  if (type == onc::wifi::kWPA_PSK)
    return arc::mojom::SecurityType::WPA_PSK;
  if (type == onc::wifi::kWPA_EAP)
    return arc::mojom::SecurityType::WPA_EAP;
  return arc::mojom::SecurityType::NONE;
}

arc::mojom::TetheringClientState TranslateTetheringState(
    const std::string& tethering_state) {
  if (tethering_state == onc::tethering_state::kTetheringConfirmedState)
    return arc::mojom::TetheringClientState::CONFIRMED;
  else if (tethering_state == onc::tethering_state::kTetheringNotDetectedState)
    return arc::mojom::TetheringClientState::NOT_DETECTED;
  else if (tethering_state == onc::tethering_state::kTetheringSuspectedState)
    return arc::mojom::TetheringClientState::SUSPECTED;
  NOTREACHED() << "Invalid tethering state: " << tethering_state;
  return arc::mojom::TetheringClientState::NOT_DETECTED;
}

arc::mojom::WiFiPtr TranslateONCWifi(const base::DictionaryValue* dict) {
  arc::mojom::WiFiPtr wifi = arc::mojom::WiFi::New();

  // Optional; defaults to 0.
  dict->GetInteger(onc::wifi::kFrequency, &wifi->frequency);

  wifi->bssid =
      GetStringFromONCDictionary(dict, onc::wifi::kBSSID, false /* required */);
  wifi->hex_ssid = GetStringFromONCDictionary(dict, onc::wifi::kHexSSID,
                                              true /* required */);

  // Optional; defaults to false.
  dict->GetBoolean(onc::wifi::kHiddenSSID, &wifi->hidden_ssid);

  wifi->security = TranslateONCWifiSecurityType(dict);

  // Optional; defaults to 0.
  dict->GetInteger(onc::wifi::kSignalStrength, &wifi->signal_strength);

  return wifi;
}

// Extracts WiFi's tethering client state from a dictionary of WiFi properties.
arc::mojom::TetheringClientState GetWifiTetheringClientState(
    const base::DictionaryValue* dict) {
  std::string tethering_state;
  dict->GetString(onc::wifi::kTetheringState, &tethering_state);
  return TranslateTetheringState(tethering_state);
}

arc::mojom::IPConfigurationPtr TranslateONCIPConfig(
    const base::Value* ip_dict) {
  DCHECK(ip_dict->is_dict());

  arc::mojom::IPConfigurationPtr configuration =
      arc::mojom::IPConfiguration::New();

  const base::Value* ip_address = ip_dict->FindKeyOfType(
      onc::ipconfig::kIPAddress, base::Value::Type::STRING);
  if (ip_address && !ip_address->GetString().empty()) {
    configuration->ip_address = ip_address->GetString();
    const base::Value* routing_prefix = ip_dict->FindKeyOfType(
        onc::ipconfig::kRoutingPrefix, base::Value::Type::INTEGER);
    if (routing_prefix)
      configuration->routing_prefix = routing_prefix->GetInt();
    else
      LOG(ERROR) << "Required property RoutingPrefix not found.";
    configuration->gateway = GetStringFromONCDictionary(
        ip_dict, onc::ipconfig::kGateway, true /* required */);
  }

  const base::Value* name_servers = ip_dict->FindKeyOfType(
      onc::ipconfig::kNameServers, base::Value::Type::LIST);
  if (name_servers) {
    for (const auto& entry : name_servers->GetList())
      configuration->name_servers.push_back(entry.GetString());
  }

  const base::Value* type =
      ip_dict->FindKeyOfType(onc::ipconfig::kType, base::Value::Type::STRING);
  configuration->type = type && type->GetString() == onc::ipconfig::kIPv6
                            ? arc::mojom::IPAddressType::IPV6
                            : arc::mojom::IPAddressType::IPV4;

  configuration->web_proxy_auto_discovery_url = GetStringFromONCDictionary(
      ip_dict, onc::ipconfig::kWebProxyAutoDiscoveryUrl, false /* required */);

  return configuration;
}

// Returns true if the IP configuration is valid enough for ARC. Empty IP
// config objects can be generated when IPv4 DHCP or IPv6 autoconf has not
// completed yet.
bool IsValidIPConfiguration(const arc::mojom::IPConfiguration& ip_config) {
  return !ip_config.ip_address.empty() && !ip_config.gateway.empty();
}

// Returns an IPConfiguration vector from the IPConfigs ONC property, which may
// include multiple IP configurations (e.g. IPv4 and IPv6).
std::vector<arc::mojom::IPConfigurationPtr> IPConfigurationsFromONCIPConfigs(
    const base::Value* dict) {
  const base::Value* ip_config_list =
      dict->FindKey(onc::network_config::kIPConfigs);
  if (!ip_config_list || !ip_config_list->is_list())
    return {};
  std::vector<arc::mojom::IPConfigurationPtr> result;
  for (const auto& entry : ip_config_list->GetList()) {
    arc::mojom::IPConfigurationPtr config = TranslateONCIPConfig(&entry);
    if (config && IsValidIPConfiguration(*config))
      result.push_back(std::move(config));
  }
  return result;
}

// Returns an IPConfiguration vector from ONC property |property|, which will
// include a single IP configuration.
std::vector<arc::mojom::IPConfigurationPtr> IPConfigurationsFromONCProperty(
    const base::Value* dict,
    const char* property_key) {
  const base::Value* ip_dict = dict->FindKey(property_key);
  if (!ip_dict)
    return {};
  arc::mojom::IPConfigurationPtr config = TranslateONCIPConfig(ip_dict);
  if (!config || !IsValidIPConfiguration(*config))
    return {};
  std::vector<arc::mojom::IPConfigurationPtr> result;
  result.push_back(std::move(config));
  return result;
}

arc::mojom::ConnectionStateType TranslateONCConnectionState(
    const base::DictionaryValue* dict) {
  std::string connection_state = GetStringFromONCDictionary(
      dict, onc::network_config::kConnectionState, false /* required */);

  if (connection_state == onc::connection_state::kConnected)
    return arc::mojom::ConnectionStateType::CONNECTED;
  if (connection_state == onc::connection_state::kConnecting)
    return arc::mojom::ConnectionStateType::CONNECTING;
  return arc::mojom::ConnectionStateType::NOT_CONNECTED;
}

// Translates a shill connection state into a mojo ConnectionStateType.
// This is effectively the inverse function of shill.Service::GetStateString
// defined in platform2/shill/service.cc, with in addition some of shill's
// connection states translated to the same ConnectionStateType value.
arc::mojom::ConnectionStateType TranslateConnectionState(
    const std::string& state) {
  if (state == shill::kStateReady)
    return arc::mojom::ConnectionStateType::CONNECTED;
  if (state == shill::kStateAssociation || state == shill::kStateConfiguration)
    return arc::mojom::ConnectionStateType::CONNECTING;
  if ((state == shill::kStateIdle) || (state == shill::kStateFailure) ||
      (state == shill::kStateDisconnect) || (state == ""))
    return arc::mojom::ConnectionStateType::NOT_CONNECTED;
  if (chromeos::NetworkState::StateIsPortalled(state))
    return arc::mojom::ConnectionStateType::PORTAL;
  if (state == shill::kStateOnline)
    return arc::mojom::ConnectionStateType::ONLINE;

  // The remaining cases defined in shill dbus-constants are legacy values from
  // Flimflam and are not expected to be encountered. These are: kStateCarrier,
  // kStateActivationFailure, and kStateOffline.
  NOTREACHED() << "Unknown connection state: " << state;
  return arc::mojom::ConnectionStateType::NOT_CONNECTED;
}

bool IsActiveNetworkState(const chromeos::NetworkState* network) {
  if (!network)
    return false;

  const std::string& state = network->connection_state();
  return state == shill::kStateReady || state == shill::kStateOnline ||
         state == shill::kStateAssociation ||
         state == shill::kStateConfiguration || state == shill::kStatePortal ||
         state == shill::kStateNoConnectivity ||
         state == shill::kStateRedirectFound ||
         state == shill::kStatePortalSuspected;
}

void TranslateONCNetworkTypeDetails(const base::DictionaryValue* dict,
                                    arc::mojom::NetworkConfiguration* mojo) {
  std::string type = GetStringFromONCDictionary(
      dict, onc::network_config::kType, true /* required */);
  // This property will be updated as required by the relevant network types
  // below.
  mojo->tethering_client_state = arc::mojom::TetheringClientState::NOT_DETECTED;
  if (type == onc::network_type::kCellular) {
    mojo->type = arc::mojom::NetworkType::CELLULAR;
  } else if (type == onc::network_type::kEthernet) {
    mojo->type = arc::mojom::NetworkType::ETHERNET;
  } else if (type == onc::network_type::kVPN) {
    mojo->type = arc::mojom::NetworkType::VPN;
  } else if (type == onc::network_type::kWiFi) {
    mojo->type = arc::mojom::NetworkType::WIFI;
    const base::DictionaryValue* wifi_dict = nullptr;
    dict->GetDictionary(onc::network_config::kWiFi, &wifi_dict);
    DCHECK(wifi_dict);
    mojo->wifi = TranslateONCWifi(wifi_dict);
    mojo->tethering_client_state = GetWifiTetheringClientState(wifi_dict);
  } else {
    NOTREACHED() << "Unknown network type: " << type;
  }
}

// Parse a shill IPConfig dictionary and appends the resulting mojo
// IPConfiguration object to the given |ip_configs| vector.
void AddIpConfiguration(std::vector<arc::mojom::IPConfigurationPtr>& ip_configs,
                        const base::Value* shill_ipconfig) {
  if (!shill_ipconfig || !shill_ipconfig->is_dict())
    return;

  auto ip_config = arc::mojom::IPConfiguration::New();
  if (const auto* address_property =
          shill_ipconfig->FindStringPath(shill::kAddressProperty))
    ip_config->ip_address = *address_property;

  if (const auto* gateway_property =
          shill_ipconfig->FindStringPath(shill::kGatewayProperty))
    ip_config->gateway = *gateway_property;

  ip_config->routing_prefix =
      shill_ipconfig->FindIntPath(shill::kPrefixlenProperty).value_or(0);

  ip_config->type = (ip_config->routing_prefix < 64)
                        ? arc::mojom::IPAddressType::IPV4
                        : arc::mojom::IPAddressType::IPV6;

  if (const auto* dns_list =
          shill_ipconfig->FindListKey(shill::kNameServersProperty)) {
    for (const auto& dns_value : dns_list->GetList()) {
      const std::string& dns = dns_value.GetString();
      if (dns.empty())
        continue;

      // When manually setting DNS, up to 4 addresses can be specified in the
      // UI. Unspecified entries can show up as 0.0.0.0 and should be removed.
      if (dns == "0.0.0.0")
        continue;

      ip_config->name_servers.push_back(dns);
    }
  }

  if (IsValidIPConfiguration(*ip_config))
    ip_configs.push_back(std::move(ip_config));
}

// Add shill's Device properties to the given mojo NetworkConfiguration objects.
// This adds the network interface and current IP configurations.
void AddDeviceProperties(arc::mojom::NetworkConfiguration* network,
                         const std::string& device_path) {
  const auto* device = GetStateHandler()->GetDeviceState(device_path);
  if (!device)
    return;

  network->network_interface = device->interface();

  std::vector<arc::mojom::IPConfigurationPtr> ip_configs;
  for (const auto& kv : device->ip_configs())
    AddIpConfiguration(ip_configs, kv.second.get());

  // If the DeviceState had any IP configuration, always use them and ignore
  // any other IP configuration previously obtained through NetworkState.
  if (!ip_configs.empty())
    network->ip_configs = std::move(ip_configs);
}

arc::mojom::NetworkConfigurationPtr TranslateONCConfiguration(
    const chromeos::NetworkState* network_state,
    const base::Value* shill_dict,
    const base::DictionaryValue* onc_dict) {
  auto mojo = arc::mojom::NetworkConfiguration::New();

  mojo->connection_state = TranslateONCConnectionState(onc_dict);

  mojo->guid = GetStringFromONCDictionary(onc_dict, onc::network_config::kGUID,
                                          true /* required */);

  // crbug.com/761708 - VPNs do not currently have an IPConfigs array,
  // so in order to fetch the parameters (particularly the DNS server list),
  // fall back to StaticIPConfig or SavedIPConfig.
  // TODO(b/145960788) Remove IP configuration retrieval from ONC properties.
  std::vector<arc::mojom::IPConfigurationPtr> ip_configs =
      IPConfigurationsFromONCIPConfigs(onc_dict);
  if (ip_configs.empty()) {
    ip_configs = IPConfigurationsFromONCProperty(
        onc_dict, onc::network_config::kStaticIPConfig);
  }
  if (ip_configs.empty()) {
    ip_configs = IPConfigurationsFromONCProperty(
        onc_dict, onc::network_config::kSavedIPConfig);
  }
  // b/155129178 Also use cached shill properties if available.
  if (shill_dict) {
    for (const auto* property :
         {shill::kIPConfigProperty, shill::kStaticIPConfigProperty,
          shill::kSavedIPConfigProperty}) {
      if (!ip_configs.empty())
        break;

      AddIpConfiguration(ip_configs, shill_dict->FindKey(property));
    }
  }
  mojo->ip_configs = std::move(ip_configs);

  mojo->guid = GetStringFromONCDictionary(onc_dict, onc::network_config::kGUID,
                                          true /* required */);
  TranslateONCNetworkTypeDetails(onc_dict, mojo.get());

  if (network_state) {
    mojo->connection_state =
        TranslateConnectionState(network_state->connection_state());
    AddDeviceProperties(mojo.get(), network_state->device_path());
  }

  return mojo;
}

const chromeos::NetworkState* GetShillBackedNetwork(
    const chromeos::NetworkState* network) {
  if (!network)
    return nullptr;

  // Non-Tether networks are already backed by Shill.
  const std::string type = network->type();
  if (type.empty() || !chromeos::NetworkTypePattern::Tether().MatchesType(type))
    return network;

  // Tether networks which are not connected are also not backed by Shill.
  if (!network->IsConnectedState())
    return nullptr;

  // Connected Tether networks delegate to an underlying Wi-Fi network.
  DCHECK(!network->tether_guid().empty());
  return GetStateHandler()->GetNetworkStateFromGuid(network->tether_guid());
}

// Convenience helper for translating a vector of NetworkState objects to a
// vector of mojo NetworkConfiguration objects.
std::vector<arc::mojom::NetworkConfigurationPtr> TranslateNetworkStates(
    const std::string& arc_vpn_path,
    const chromeos::NetworkStateHandler::NetworkStateList& network_states,
    const std::map<std::string, base::Value>& shill_network_properties) {
  std::vector<arc::mojom::NetworkConfigurationPtr> networks;
  for (const chromeos::NetworkState* state : network_states) {
    const std::string& network_path = state->path();
    if (network_path == arc_vpn_path) {
      // Never tell Android about its own VPN.
      continue;
    }
    // For tethered networks, the underlying WiFi networks are not part of
    // active networks. Replace any such tethered network with its underlying
    // backing network, because ARC cannot match its datapath with the tethered
    // network configuration.
    state = GetShillBackedNetwork(state);
    if (!state) {
      continue;
    }

    const auto it = shill_network_properties.find(network_path);
    const auto* shill_dict =
        (it != shill_network_properties.end()) ? &it->second : nullptr;
    const auto onc_dict =
        chromeos::network_util::TranslateNetworkStateToONC(state);
    auto network = TranslateONCConfiguration(state, shill_dict, onc_dict.get());
    network->is_default_network = state == GetStateHandler()->DefaultNetwork();
    network->service_name = network_path;
    networks.push_back(std::move(network));
  }
  return networks;
}

void ForgetNetworkSuccessCallback(
    base::OnceCallback<void(arc::mojom::NetworkResult)> callback) {
  std::move(callback).Run(arc::mojom::NetworkResult::SUCCESS);
}

void ForgetNetworkFailureCallback(
    base::OnceCallback<void(arc::mojom::NetworkResult)> callback,
    const std::string& error_name,
    std::unique_ptr<base::DictionaryValue> error_data) {
  VLOG(1) << "ForgetNetworkFailureCallback: " << error_name;
  std::move(callback).Run(arc::mojom::NetworkResult::FAILURE);
}

void StartConnectSuccessCallback(
    base::OnceCallback<void(arc::mojom::NetworkResult)> callback) {
  std::move(callback).Run(arc::mojom::NetworkResult::SUCCESS);
}

void StartConnectFailureCallback(
    base::OnceCallback<void(arc::mojom::NetworkResult)> callback,
    const std::string& error_name,
    std::unique_ptr<base::DictionaryValue> error_data) {
  VLOG(1) << "StartConnectFailureCallback: " << error_name;
  std::move(callback).Run(arc::mojom::NetworkResult::FAILURE);
}

void StartDisconnectSuccessCallback(
    base::OnceCallback<void(arc::mojom::NetworkResult)> callback) {
  std::move(callback).Run(arc::mojom::NetworkResult::SUCCESS);
}

void StartDisconnectFailureCallback(
    base::OnceCallback<void(arc::mojom::NetworkResult)> callback,
    const std::string& error_name,
    std::unique_ptr<base::DictionaryValue> error_data) {
  VLOG(1) << "StartDisconnectFailureCallback: " << error_name;
  std::move(callback).Run(arc::mojom::NetworkResult::FAILURE);
}

void ArcVpnSuccessCallback() {
  DVLOG(1) << "ArcVpnSuccessCallback";
}

void ArcVpnErrorCallback(const std::string& error_name,
                         std::unique_ptr<base::DictionaryValue> error_data) {
  LOG(ERROR) << "ArcVpnErrorCallback: " << error_name;
}

}  // namespace

namespace arc {
namespace {

// Singleton factory for ArcNetHostImpl.
class ArcNetHostImplFactory
    : public internal::ArcBrowserContextKeyedServiceFactoryBase<
          ArcNetHostImpl,
          ArcNetHostImplFactory> {
 public:
  // Factory name used by ArcBrowserContextKeyedServiceFactoryBase.
  static constexpr const char* kName = "ArcNetHostImplFactory";

  static ArcNetHostImplFactory* GetInstance() {
    return base::Singleton<ArcNetHostImplFactory>::get();
  }

 private:
  friend base::DefaultSingletonTraits<ArcNetHostImplFactory>;
  ArcNetHostImplFactory() = default;
  ~ArcNetHostImplFactory() override = default;
};

}  // namespace

// static
ArcNetHostImpl* ArcNetHostImpl::GetForBrowserContext(
    content::BrowserContext* context) {
  return ArcNetHostImplFactory::GetForBrowserContext(context);
}

// static
ArcNetHostImpl* ArcNetHostImpl::GetForBrowserContextForTesting(
    content::BrowserContext* context) {
  return ArcNetHostImplFactory::GetForBrowserContextForTesting(context);
}

ArcNetHostImpl::ArcNetHostImpl(content::BrowserContext* context,
                               ArcBridgeService* bridge_service)
    : arc_bridge_service_(bridge_service) {
  arc_bridge_service_->net()->SetHost(this);
  arc_bridge_service_->net()->AddObserver(this);
}

ArcNetHostImpl::~ArcNetHostImpl() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (observing_network_state_) {
    GetStateHandler()->RemoveObserver(this, FROM_HERE);
    GetNetworkConnectionHandler()->RemoveObserver(this);
  }
  arc_bridge_service_->net()->RemoveObserver(this);
  arc_bridge_service_->net()->SetHost(nullptr);
}

void ArcNetHostImpl::SetPrefService(PrefService* pref_service) {
  pref_service_ = pref_service;
}

void ArcNetHostImpl::OnConnectionReady() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  if (chromeos::NetworkHandler::IsInitialized()) {
    GetStateHandler()->AddObserver(this, FROM_HERE);
    GetNetworkConnectionHandler()->AddObserver(this);
    observing_network_state_ = true;
  }

  // If the default network is an ARC VPN, that means Chrome is restarting
  // after a crash but shill still thinks a VPN is connected. Nuke it.
  const chromeos::NetworkState* default_network =
      GetShillBackedNetwork(GetStateHandler()->DefaultNetwork());
  if (default_network && default_network->type() == shill::kTypeVPN &&
      default_network->GetVpnProviderType() == shill::kProviderArcVpn) {
    VLOG(0) << "Disconnecting stale ARC VPN " << default_network->path();
    GetNetworkConnectionHandler()->DisconnectNetwork(
        default_network->path(), base::Bind(&ArcVpnSuccessCallback),
        base::Bind(&ArcVpnErrorCallback));
  }
}

void ArcNetHostImpl::OnConnectionClosed() {
  // Make sure shill doesn't leave an ARC VPN connected after Android
  // goes down.
  AndroidVpnStateChanged(arc::mojom::ConnectionStateType::NOT_CONNECTED);

  if (!observing_network_state_)
    return;

  GetStateHandler()->RemoveObserver(this, FROM_HERE);
  GetNetworkConnectionHandler()->RemoveObserver(this);
  observing_network_state_ = false;
}

void ArcNetHostImpl::GetNetworks(mojom::GetNetworksRequestType type,
                                 GetNetworksCallback callback) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  chromeos::NetworkStateHandler::NetworkStateList network_states;
  if (type == mojom::GetNetworksRequestType::ACTIVE_ONLY) {
    // Retrieve list of currently active networks.
    GetStateHandler()->GetActiveNetworkListByType(
        chromeos::NetworkTypePattern::Default(), &network_states);
  } else {
    // Otherwise retrieve list of configured or visible WiFi networks.
    bool configured_only =
        type == mojom::GetNetworksRequestType::CONFIGURED_ONLY;
    chromeos::NetworkTypePattern network_pattern =
        chromeos::onc::NetworkTypePatternFromOncType(onc::network_type::kWiFi);
    GetStateHandler()->GetNetworkListByType(
        network_pattern, configured_only, !configured_only /* visible_only */,
        kGetNetworksListLimit, &network_states);
  }

  std::vector<mojom::NetworkConfigurationPtr> networks = TranslateNetworkStates(
      arc_vpn_service_path_, network_states, shill_network_properties_);
  std::move(callback).Run(mojom::GetNetworksResponseType::New(
      arc::mojom::NetworkResult::SUCCESS, std::move(networks)));
}

void ArcNetHostImpl::CreateNetworkSuccessCallback(
    base::OnceCallback<void(const std::string&)> callback,
    const std::string& service_path,
    const std::string& guid) {
  VLOG(1) << "CreateNetworkSuccessCallback";

  cached_guid_ = guid;
  cached_service_path_ = service_path;

  std::move(callback).Run(guid);
}

void ArcNetHostImpl::CreateNetworkFailureCallback(
    base::OnceCallback<void(const std::string&)> callback,
    const std::string& error_name,
    std::unique_ptr<base::DictionaryValue> error_data) {
  VLOG(1) << "CreateNetworkFailureCallback: " << error_name;
  std::move(callback).Run(std::string());
}

void ArcNetHostImpl::CreateNetwork(mojom::WifiConfigurationPtr cfg,
                                   CreateNetworkCallback callback) {
  if (!IsDeviceOwner()) {
    std::move(callback).Run(std::string());
    return;
  }

  std::unique_ptr<base::DictionaryValue> properties(new base::DictionaryValue);
  std::unique_ptr<base::DictionaryValue> wifi_dict(new base::DictionaryValue);

  if (!cfg->hexssid.has_value() || !cfg->details) {
    std::move(callback).Run(std::string());
    return;
  }
  mojom::ConfiguredNetworkDetailsPtr details =
      std::move(cfg->details->get_configured());
  if (!details) {
    std::move(callback).Run(std::string());
    return;
  }

  properties->SetKey(onc::network_config::kType,
                     base::Value(onc::network_config::kWiFi));
  wifi_dict->SetKey(onc::wifi::kHexSSID, base::Value(cfg->hexssid.value()));
  wifi_dict->SetKey(onc::wifi::kAutoConnect, base::Value(details->autoconnect));
  if (cfg->security.empty()) {
    wifi_dict->SetKey(onc::wifi::kSecurity,
                      base::Value(onc::wifi::kSecurityNone));
  } else {
    wifi_dict->SetKey(onc::wifi::kSecurity, base::Value(cfg->security));
    if (details->passphrase.has_value()) {
      wifi_dict->SetKey(onc::wifi::kPassphrase,
                        base::Value(details->passphrase.value()));
    }
  }
  properties->SetWithoutPathExpansion(onc::network_config::kWiFi,
                                      std::move(wifi_dict));

  std::string user_id_hash = chromeos::LoginState::Get()->primary_user_hash();
  // TODO(crbug.com/730593): Remove AdaptCallbackForRepeating() by updating
  // the callee interface.
  auto repeating_callback =
      base::AdaptCallbackForRepeating(std::move(callback));
  GetManagedConfigurationHandler()->CreateConfiguration(
      user_id_hash, *properties,
      base::Bind(&ArcNetHostImpl::CreateNetworkSuccessCallback,
                 weak_factory_.GetWeakPtr(), repeating_callback),
      base::Bind(&ArcNetHostImpl::CreateNetworkFailureCallback,
                 weak_factory_.GetWeakPtr(), repeating_callback));
}

bool ArcNetHostImpl::GetNetworkPathFromGuid(const std::string& guid,
                                            std::string* path) {
  const chromeos::NetworkState* network =
      GetShillBackedNetwork(GetStateHandler()->GetNetworkStateFromGuid(guid));
  if (network) {
    *path = network->path();
    return true;
  }

  if (cached_guid_ == guid) {
    *path = cached_service_path_;
    return true;
  }
  return false;
}

void ArcNetHostImpl::ForgetNetwork(const std::string& guid,
                                   ForgetNetworkCallback callback) {
  if (!IsDeviceOwner()) {
    std::move(callback).Run(mojom::NetworkResult::FAILURE);
    return;
  }

  std::string path;
  if (!GetNetworkPathFromGuid(guid, &path)) {
    std::move(callback).Run(mojom::NetworkResult::FAILURE);
    return;
  }

  cached_guid_.clear();
  // TODO(crbug.com/730593): Remove AdaptCallbackForRepeating() by updating
  // the callee interface.
  auto repeating_callback =
      base::AdaptCallbackForRepeating(std::move(callback));
  GetManagedConfigurationHandler()->RemoveConfiguration(
      path, base::Bind(&ForgetNetworkSuccessCallback, repeating_callback),
      base::Bind(&ForgetNetworkFailureCallback, repeating_callback));
}

void ArcNetHostImpl::StartConnect(const std::string& guid,
                                  StartConnectCallback callback) {
  std::string path;
  if (!GetNetworkPathFromGuid(guid, &path)) {
    std::move(callback).Run(mojom::NetworkResult::FAILURE);
    return;
  }

  // TODO(crbug.com/730593): Remove AdaptCallbackForRepeating() by updating
  // the callee interface.
  auto repeating_callback =
      base::AdaptCallbackForRepeating(std::move(callback));
  GetNetworkConnectionHandler()->ConnectToNetwork(
      path, base::Bind(&StartConnectSuccessCallback, repeating_callback),
      base::Bind(&StartConnectFailureCallback, repeating_callback),
      false /* check_error_state */, chromeos::ConnectCallbackMode::ON_STARTED);
}

void ArcNetHostImpl::StartDisconnect(const std::string& guid,
                                     StartDisconnectCallback callback) {
  std::string path;
  if (!GetNetworkPathFromGuid(guid, &path)) {
    std::move(callback).Run(mojom::NetworkResult::FAILURE);
    return;
  }

  // TODO(crbug.com/730593): Remove AdaptCallbackForRepeating() by updating
  // the callee interface.
  auto repeating_callback =
      base::AdaptCallbackForRepeating(std::move(callback));
  GetNetworkConnectionHandler()->DisconnectNetwork(
      path, base::Bind(&StartDisconnectSuccessCallback, repeating_callback),
      base::Bind(&StartDisconnectFailureCallback, repeating_callback));
}

void ArcNetHostImpl::GetWifiEnabledState(GetWifiEnabledStateCallback callback) {
  bool is_enabled = GetStateHandler()->IsTechnologyEnabled(
      chromeos::NetworkTypePattern::WiFi());
  std::move(callback).Run(is_enabled);
}

void ArcNetHostImpl::SetWifiEnabledState(bool is_enabled,
                                         SetWifiEnabledStateCallback callback) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  chromeos::NetworkStateHandler::TechnologyState state =
      GetStateHandler()->GetTechnologyState(
          chromeos::NetworkTypePattern::WiFi());
  // WiFi can't be enabled or disabled in these states.
  if ((state == chromeos::NetworkStateHandler::TECHNOLOGY_PROHIBITED) ||
      (state == chromeos::NetworkStateHandler::TECHNOLOGY_UNINITIALIZED) ||
      (state == chromeos::NetworkStateHandler::TECHNOLOGY_UNAVAILABLE)) {
    VLOG(1) << "SetWifiEnabledState failed due to WiFi state: " << state;
    std::move(callback).Run(false);
    return;
  }
  GetStateHandler()->SetTechnologyEnabled(
      chromeos::NetworkTypePattern::WiFi(), is_enabled,
      chromeos::network_handler::ErrorCallback());
  std::move(callback).Run(true);
}

void ArcNetHostImpl::StartScan() {
  GetStateHandler()->RequestScan(chromeos::NetworkTypePattern::WiFi());
}

void ArcNetHostImpl::ScanCompleted(const chromeos::DeviceState* /*unused*/) {
  auto* net_instance =
      ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->net(), ScanCompleted);
  if (!net_instance)
    return;

  net_instance->ScanCompleted();
}

void ArcNetHostImpl::DeviceListChanged() {
  auto* net_instance = ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->net(),
                                                   WifiEnabledStateChanged);
  if (!net_instance)
    return;

  bool is_enabled = GetStateHandler()->IsTechnologyEnabled(
      chromeos::NetworkTypePattern::WiFi());
  net_instance->WifiEnabledStateChanged(is_enabled);
}

std::string ArcNetHostImpl::LookupArcVpnServicePath() {
  chromeos::NetworkStateHandler::NetworkStateList state_list;
  GetStateHandler()->GetNetworkListByType(
      chromeos::NetworkTypePattern::VPN(), true /* configured_only */,
      false /* visible_only */, kGetNetworksListLimit, &state_list);

  for (const chromeos::NetworkState* state : state_list) {
    const chromeos::NetworkState* shill_backed_network =
        GetShillBackedNetwork(state);
    if (!shill_backed_network)
      continue;
    if (shill_backed_network->GetVpnProviderType() == shill::kProviderArcVpn) {
      return shill_backed_network->path();
    }
  }
  return std::string();
}

void ArcNetHostImpl::ConnectArcVpn(const std::string& service_path,
                                   const std::string& /* guid */) {
  DVLOG(1) << "ConnectArcVpn " << service_path;
  arc_vpn_service_path_ = service_path;

  GetNetworkConnectionHandler()->ConnectToNetwork(
      service_path, base::Bind(&ArcVpnSuccessCallback),
      base::Bind(&ArcVpnErrorCallback), false /* check_error_state */,
      chromeos::ConnectCallbackMode::ON_COMPLETED);
}

std::unique_ptr<base::Value> ArcNetHostImpl::TranslateStringListToValue(
    const std::vector<std::string>& string_list) {
  std::unique_ptr<base::Value> result =
      std::make_unique<base::Value>(base::Value::Type::LIST);
  for (const auto& item : string_list) {
    result->Append(item);
  }
  return result;
}

std::unique_ptr<base::DictionaryValue>
ArcNetHostImpl::TranslateVpnConfigurationToOnc(
    const mojom::AndroidVpnConfiguration& cfg) {
  std::unique_ptr<base::DictionaryValue> top_dict =
      std::make_unique<base::DictionaryValue>();

  // Name, Type
  top_dict->SetKey(
      onc::network_config::kName,
      base::Value(cfg.session_name.empty() ? cfg.app_label : cfg.session_name));
  top_dict->SetKey(onc::network_config::kType,
                   base::Value(onc::network_config::kVPN));

  // StaticIPConfig dictionary
  top_dict->SetKey(onc::network_config::kIPAddressConfigType,
                   base::Value(onc::network_config::kIPConfigTypeStatic));
  top_dict->SetKey(onc::network_config::kNameServersConfigType,
                   base::Value(onc::network_config::kIPConfigTypeStatic));

  std::unique_ptr<base::DictionaryValue> ip_dict =
      std::make_unique<base::DictionaryValue>();
  ip_dict->SetKey(onc::ipconfig::kType, base::Value(onc::ipconfig::kIPv4));
  ip_dict->SetKey(onc::ipconfig::kIPAddress, base::Value(cfg.ipv4_gateway));
  ip_dict->SetKey(onc::ipconfig::kRoutingPrefix, base::Value(32));
  ip_dict->SetKey(onc::ipconfig::kGateway, base::Value(cfg.ipv4_gateway));

  ip_dict->SetWithoutPathExpansion(onc::ipconfig::kNameServers,
                                   TranslateStringListToValue(cfg.nameservers));
  ip_dict->SetWithoutPathExpansion(onc::ipconfig::kSearchDomains,
                                   TranslateStringListToValue(cfg.domains));
  ip_dict->SetWithoutPathExpansion(
      onc::ipconfig::kIncludedRoutes,
      TranslateStringListToValue(cfg.split_include));
  ip_dict->SetWithoutPathExpansion(
      onc::ipconfig::kExcludedRoutes,
      TranslateStringListToValue(cfg.split_exclude));

  top_dict->SetWithoutPathExpansion(onc::network_config::kStaticIPConfig,
                                    std::move(ip_dict));

  // VPN dictionary
  std::unique_ptr<base::DictionaryValue> vpn_dict =
      std::make_unique<base::DictionaryValue>();
  vpn_dict->SetKey(onc::vpn::kHost, base::Value(cfg.app_name));
  vpn_dict->SetKey(onc::vpn::kType, base::Value(onc::vpn::kArcVpn));

  // ARCVPN dictionary
  std::unique_ptr<base::DictionaryValue> arcvpn_dict =
      std::make_unique<base::DictionaryValue>();
  arcvpn_dict->SetKey(
      onc::arc_vpn::kTunnelChrome,
      base::Value(cfg.tunnel_chrome_traffic ? "true" : "false"));
  vpn_dict->SetWithoutPathExpansion(onc::vpn::kArcVpn, std::move(arcvpn_dict));

  top_dict->SetWithoutPathExpansion(onc::network_config::kVPN,
                                    std::move(vpn_dict));

  return top_dict;
}

void ArcNetHostImpl::AndroidVpnConnected(
    mojom::AndroidVpnConfigurationPtr cfg) {
  std::unique_ptr<base::DictionaryValue> properties =
      TranslateVpnConfigurationToOnc(*cfg);
  std::string service_path = LookupArcVpnServicePath();
  if (!service_path.empty()) {
    VLOG(1) << "AndroidVpnConnected: reusing " << service_path;
    GetManagedConfigurationHandler()->SetProperties(
        service_path, *properties,
        base::Bind(&ArcNetHostImpl::ConnectArcVpn, weak_factory_.GetWeakPtr(),
                   service_path, std::string()),
        base::Bind(&ArcVpnErrorCallback));
    return;
  }

  VLOG(1) << "AndroidVpnConnected: creating new ARC VPN";
  std::string user_id_hash = chromeos::LoginState::Get()->primary_user_hash();
  GetManagedConfigurationHandler()->CreateConfiguration(
      user_id_hash, *properties,
      base::Bind(&ArcNetHostImpl::ConnectArcVpn, weak_factory_.GetWeakPtr()),
      base::Bind(&ArcVpnErrorCallback));
}

void ArcNetHostImpl::AndroidVpnStateChanged(mojom::ConnectionStateType state) {
  VLOG(1) << "AndroidVpnStateChanged: state=" << state
          << " service=" << arc_vpn_service_path_;

  if (state != arc::mojom::ConnectionStateType::NOT_CONNECTED ||
      arc_vpn_service_path_.empty()) {
    return;
  }

  // DisconnectNetwork() invokes DisconnectRequested() through the
  // observer interface, so make sure it doesn't generate an unwanted
  // mojo call to Android.
  std::string service_path(arc_vpn_service_path_);
  arc_vpn_service_path_.clear();

  GetNetworkConnectionHandler()->DisconnectNetwork(
      service_path, base::Bind(&ArcVpnSuccessCallback),
      base::Bind(&ArcVpnErrorCallback));
}

void ArcNetHostImpl::SetAlwaysOnVpn(const std::string& vpn_package,
                                    bool lockdown) {
  // pref_service_ should be set by ArcServiceLauncher.
  DCHECK(pref_service_);
  pref_service_->SetString(prefs::kAlwaysOnVpnPackage, vpn_package);
  pref_service_->SetBoolean(prefs::kAlwaysOnVpnLockdown, lockdown);
}

void ArcNetHostImpl::DisconnectArcVpn() {
  arc_vpn_service_path_.clear();

  auto* net_instance = ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->net(),
                                                   DisconnectAndroidVpn);
  if (!net_instance) {
    LOG(ERROR) << "User requested VPN disconnection but API is unavailable";
    return;
  }
  net_instance->DisconnectAndroidVpn();
}

void ArcNetHostImpl::DisconnectRequested(const std::string& service_path) {
  if (arc_vpn_service_path_ != service_path) {
    return;
  }

  // This code path is taken when a user clicks the blue Disconnect button
  // in Chrome OS.  Chrome is about to send the Disconnect call to shill,
  // so update our local state and tell Android to disconnect the VPN.
  VLOG(1) << "DisconnectRequested " << service_path;
  DisconnectArcVpn();
}

void ArcNetHostImpl::NetworkConnectionStateChanged(
    const chromeos::NetworkState* network) {
  const chromeos::NetworkState* shill_backed_network =
      GetShillBackedNetwork(network);
  if (!shill_backed_network)
    return;

  if (arc_vpn_service_path_ != shill_backed_network->path() ||
      shill_backed_network->IsConnectingOrConnected()) {
    return;
  }

  // This code path is taken when shill disconnects the Android VPN
  // service.  This can happen if a user tries to connect to a Chrome OS
  // VPN, and shill's VPNProvider::DisconnectAll() forcibly disconnects
  // all other VPN services to avoid a conflict.
  VLOG(1) << "NetworkConnectionStateChanged " << shill_backed_network->path();
  DisconnectArcVpn();
}

void ReceiveShillPropertiesFailure(
    const std::string& service_path,
    const std::string& error_name,
    std::unique_ptr<base::DictionaryValue> error_data) {
  LOG(ERROR) << "Failed to get shill Service properties for " << service_path
             << ": " << error_name;
}

void ArcNetHostImpl::NetworkPropertiesUpdated(
    const chromeos::NetworkState* network) {
  if (!IsActiveNetworkState(network))
    return;

  chromeos::NetworkHandler::Get()
      ->network_configuration_handler()
      ->GetShillProperties(
          network->path(),
          base::BindOnce(&ArcNetHostImpl::ReceiveShillProperties,
                         weak_factory_.GetWeakPtr()),
          base::Bind(&ReceiveShillPropertiesFailure, network->path()));
}

void ArcNetHostImpl::ReceiveShillProperties(
    const std::string& service_path,
    const base::DictionaryValue& shill_properties) {
  // Ignore properties received after the network has disconnected.
  const auto* network = GetStateHandler()->GetNetworkState(service_path);
  if (!IsActiveNetworkState(network))
    return;

  base::InsertOrAssign(shill_network_properties_, service_path,
                       shill_properties.Clone());
  UpdateActiveNetworks();
}

void ArcNetHostImpl::UpdateActiveNetworks() {
  auto* net_instance = ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->net(),
                                                   ActiveNetworksChanged);
  if (!net_instance)
    return;

  const auto active_networks = GetActiveNetworks();
  auto network_configurations = TranslateNetworkStates(
      arc_vpn_service_path_, active_networks, shill_network_properties_);

  // A newly connected network may not immediately have any usable IP config
  // object if IPv4 dhcp or IPv6 autoconf have not completed yet. Schedule
  // with a few seconds delay a forced property update for that service to
  // ensure the IP configuration is sent to ARC. Ensure that at most one such
  // request is scheduled for a given service.
  for (const auto& network : network_configurations) {
    if (!network->ip_configs->empty())
      continue;

    if (!network->service_name)
      continue;

    const std::string& path = network->service_name.value();
    if (pending_service_property_requests_.insert(path).second) {
      LOG(WARNING) << "No IP configuration for " << path;
      // TODO(hugobenichi): add exponential backoff for the case when IP
      // configuration stays unavailable.
      base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
          FROM_HERE,
          base::BindOnce(&ArcNetHostImpl::RequestUpdateForNetwork,
                         weak_factory_.GetWeakPtr(), path),
          kNetworkPropertyUpdateDelay);
    }
  }

  net_instance->ActiveNetworksChanged(std::move(network_configurations));
}

void ArcNetHostImpl::RequestUpdateForNetwork(const std::string& service_path) {
  // TODO(hugobenichi): skip the request if the IP configuration for this
  // service has been received since then and ARC has been notified about it.
  pending_service_property_requests_.erase(service_path);
  GetStateHandler()->RequestUpdateForNetwork(service_path);
}

void ArcNetHostImpl::NetworkListChanged() {
  // Forget properties of disconnected networks
  base::EraseIf(shill_network_properties_, [](const auto& entry) {
    return !IsActiveNetworkState(
        GetStateHandler()->GetNetworkState(entry.first));
  });
  for (const auto* network : GetActiveNetworks())
    NetworkPropertiesUpdated(network);
}

void ArcNetHostImpl::OnShuttingDown() {
  DCHECK(observing_network_state_);
  GetStateHandler()->RemoveObserver(this, FROM_HERE);
  GetNetworkConnectionHandler()->RemoveObserver(this);
  observing_network_state_ = false;
}

}  // namespace arc


text:
require 'spec_helper'

module Gitlab::Markdown
  describe UserReferenceFilter do
    include FilterSpecHelper

    let(:project)   { create(:empty_project, :public) }
    let(:user)      { create(:user) }
    let(:reference) { user.to_reference }

    it 'requires project context' do
      expect { described_class.call('') }.to raise_error(ArgumentError, /:project/)
    end

    it 'ignores invalid users' do
      exp = act = "Hey #{invalidate_reference(reference)}"
      expect(filter(act).to_html).to eq(exp)
    end

    %w(pre code a style).each do |elem|
      it "ignores valid references contained inside '#{elem}' element" do
        exp = act = "<#{elem}>Hey #{reference}</#{elem}>"
        expect(filter(act).to_html).to eq exp
      end
    end

    context 'mentioning @all' do
      let(:reference) { User.reference_prefix + 'all' }

      before do
        project.team << [project.creator, :developer]
      end

      it 'supports a special @all mention' do
        doc = filter("Hey #{reference}")
        expect(doc.css('a').length).to eq 1
        expect(doc.css('a').first.attr('href'))
          .to eq urls.namespace_project_url(project.namespace, project)
      end

      it 'adds to the results hash' do
        result = reference_pipeline_result("Hey #{reference}")
        expect(result[:references][:user]).to eq [project.creator]
      end
    end

    context 'mentioning a user' do
      it 'links to a User' do
        doc = filter("Hey #{reference}")
        expect(doc.css('a').first.attr('href')).to eq urls.user_url(user)
      end

      it 'links to a User with a period' do
        user = create(:user, name: 'alphA.Beta')

        doc = filter("Hey #{user.to_reference}")
        expect(doc.css('a').length).to eq 1
      end

      it 'links to a User with an underscore' do
        user = create(:user, name: 'ping_pong_king')

        doc = filter("Hey #{user.to_reference}")
        expect(doc.css('a').length).to eq 1
      end

      it 'includes a data-user attribute' do
        doc = filter("Hey #{reference}")
        link = doc.css('a').first

        expect(link).to have_attribute('data-user')
        expect(link.attr('data-user')).to eq user.namespace.owner_id.to_s
      end

      it 'adds to the results hash' do
        result = reference_pipeline_result("Hey #{reference}")
        expect(result[:references][:user]).to eq [user]
      end
    end

    context 'mentioning a group' do
      let(:group)     { create(:group) }
      let(:reference) { group.to_reference }

      it 'links to the Group' do
        doc = filter("Hey #{reference}")
        expect(doc.css('a').first.attr('href')).to eq urls.group_url(group)
      end

      it 'includes a data-group attribute' do
        doc = filter("Hey #{reference}")
        link = doc.css('a').first

        expect(link).to have_attribute('data-group')
        expect(link.attr('data-group')).to eq group.id.to_s
      end

      it 'adds to the results hash' do
        result = reference_pipeline_result("Hey #{reference}")
        expect(result[:references][:user]).to eq group.users
      end
    end

    it 'links with adjacent text' do
      doc = filter("Mention me (#{reference}.)")
      expect(doc.to_html).to match(/\(<a.+>#{reference}<\/a>\.\)/)
    end

    it 'includes default classes' do
      doc = filter("Hey #{reference}")
      expect(doc.css('a').first.attr('class')).to eq 'gfm gfm-project_member'
    end

    it 'supports an :only_path context' do
      doc = filter("Hey #{reference}", only_path: true)
      link = doc.css('a').first.attr('href')

      expect(link).not_to match %r(https?://)
      expect(link).to eq urls.user_path(user)
    end
  end
end


text:
*   Handle nil values returned from Base model search at Artist#find_by_name and ReleaseGroup#find_by_artist_and_title [#24]

# 0.7.6 (June 14, 2013) ##

*   Improves urls attribute to return an array if there are multiple urls for a relation type. [#19]

# 0.7.5 (May 6, 2013) ##

*   Created new track_search binding to allow searching for tracks. [#18]
*   Adds release group urls. [#17]

# 0.1.0 (July 18, 2011) ##

*   Initial version.


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.kubernetesconfiguration.fluent.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;

/** Updatable properties of an Extension Patch Request. */
@Fluent
public final class PatchExtensionProperties {
    /*
     * Flag to note if this extension participates in auto upgrade of minor
     * version, or not.
     */
    @JsonProperty(value = "autoUpgradeMinorVersion")
    private Boolean autoUpgradeMinorVersion;

    /*
     * ReleaseTrain this extension participates in for auto-upgrade (e.g.
     * Stable, Preview, etc.) - only if autoUpgradeMinorVersion is 'true'.
     */
    @JsonProperty(value = "releaseTrain")
    private String releaseTrain;

    /*
     * Version of the extension for this extension, if it is 'pinned' to a
     * specific version. autoUpgradeMinorVersion must be 'false'.
     */
    @JsonProperty(value = "version")
    private String version;

    /*
     * Configuration settings, as name-value pairs for configuring this
     * extension.
     */
    @JsonProperty(value = "configurationSettings")
    @JsonInclude(value = JsonInclude.Include.NON_NULL, content = JsonInclude.Include.ALWAYS)
    private Map<String, String> configurationSettings;

    /*
     * Configuration settings that are sensitive, as name-value pairs for
     * configuring this extension.
     */
    @JsonProperty(value = "configurationProtectedSettings")
    @JsonInclude(value = JsonInclude.Include.NON_NULL, content = JsonInclude.Include.ALWAYS)
    private Map<String, String> configurationProtectedSettings;

    /**
     * Get the autoUpgradeMinorVersion property: Flag to note if this extension participates in auto upgrade of minor
     * version, or not.
     *
     * @return the autoUpgradeMinorVersion value.
     */
    public Boolean autoUpgradeMinorVersion() {
        return this.autoUpgradeMinorVersion;
    }

    /**
     * Set the autoUpgradeMinorVersion property: Flag to note if this extension participates in auto upgrade of minor
     * version, or not.
     *
     * @param autoUpgradeMinorVersion the autoUpgradeMinorVersion value to set.
     * @return the PatchExtensionProperties object itself.
     */
    public PatchExtensionProperties withAutoUpgradeMinorVersion(Boolean autoUpgradeMinorVersion) {
        this.autoUpgradeMinorVersion = autoUpgradeMinorVersion;
        return this;
    }

    /**
     * Get the releaseTrain property: ReleaseTrain this extension participates in for auto-upgrade (e.g. Stable,
     * Preview, etc.) - only if autoUpgradeMinorVersion is 'true'.
     *
     * @return the releaseTrain value.
     */
    public String releaseTrain() {
        return this.releaseTrain;
    }

    /**
     * Set the releaseTrain property: ReleaseTrain this extension participates in for auto-upgrade (e.g. Stable,
     * Preview, etc.) - only if autoUpgradeMinorVersion is 'true'.
     *
     * @param releaseTrain the releaseTrain value to set.
     * @return the PatchExtensionProperties object itself.
     */
    public PatchExtensionProperties withReleaseTrain(String releaseTrain) {
        this.releaseTrain = releaseTrain;
        return this;
    }

    /**
     * Get the version property: Version of the extension for this extension, if it is 'pinned' to a specific version.
     * autoUpgradeMinorVersion must be 'false'.
     *
     * @return the version value.
     */
    public String version() {
        return this.version;
    }

    /**
     * Set the version property: Version of the extension for this extension, if it is 'pinned' to a specific version.
     * autoUpgradeMinorVersion must be 'false'.
     *
     * @param version the version value to set.
     * @return the PatchExtensionProperties object itself.
     */
    public PatchExtensionProperties withVersion(String version) {
        this.version = version;
        return this;
    }

    /**
     * Get the configurationSettings property: Configuration settings, as name-value pairs for configuring this
     * extension.
     *
     * @return the configurationSettings value.
     */
    public Map<String, String> configurationSettings() {
        return this.configurationSettings;
    }

    /**
     * Set the configurationSettings property: Configuration settings, as name-value pairs for configuring this
     * extension.
     *
     * @param configurationSettings the configurationSettings value to set.
     * @return the PatchExtensionProperties object itself.
     */
    public PatchExtensionProperties withConfigurationSettings(Map<String, String> configurationSettings) {
        this.configurationSettings = configurationSettings;
        return this;
    }

    /**
     * Get the configurationProtectedSettings property: Configuration settings that are sensitive, as name-value pairs
     * for configuring this extension.
     *
     * @return the configurationProtectedSettings value.
     */
    public Map<String, String> configurationProtectedSettings() {
        return this.configurationProtectedSettings;
    }

    /**
     * Set the configurationProtectedSettings property: Configuration settings that are sensitive, as name-value pairs
     * for configuring this extension.
     *
     * @param configurationProtectedSettings the configurationProtectedSettings value to set.
     * @return the PatchExtensionProperties object itself.
     */
    public PatchExtensionProperties withConfigurationProtectedSettings(
        Map<String, String> configurationProtectedSettings) {
        this.configurationProtectedSettings = configurationProtectedSettings;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
{% extends "base_standard_nav.html" %}

{% block head %}

{% endblock %}

{% block content %}
<form id="add_classroom">
  Create a new classroom named:
  <input type="text" class="text_input" id="add_class_text_field" />
  <input type="button" id="add_class_submit" value="Add" />
</form>

Classrooms

Enroll a student in a class:

Classroom

Student

  <form class="table-row" id="enroll_student_form">

      <select id="classroom_select" name="class"></select>

      <select id="student_select" name="student"></select>

      <input type="button" id="enroll_student_button" value="Enroll"
       onclick="cr.classroom.enrollStudentViaButton();" />

  </form>

{% endblock %}