text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

#ifndef KUDU_COMMON_KEYENCODER_H
#define KUDU_COMMON_KEYENCODER_H

#ifndef __aarch64__
#include <emmintrin.h>
#include <smmintrin.h>
#endif

#include <climits>
#include <cstdint>
#include <cstring>
#include <ostream>

#include <glog/logging.h>

#include "kudu/common/common.pb.h"
#include "kudu/common/types.h"
#include "kudu/gutil/endian.h"
#include "kudu/gutil/macros.h"
#include "kudu/gutil/mathlimits.h"
#include "kudu/gutil/port.h"
#include "kudu/gutil/type_traits.h"
#include "kudu/util/logging.h"
#include "kudu/util/memory/arena.h"
#include "kudu/util/slice.h"
#include "kudu/util/status.h"

// The SSE-based encoding is not yet working. Don't define this!
#undef KEY_ENCODER_USE_SSE

namespace kudu {

template<DataType Type, typename Buffer, class Enable = void>
struct KeyEncoderTraits {
};

// This complicated-looking template magic defines a specialization of the
// KeyEncoderTraits struct for any integral type. This avoids a bunch of
// code duplication for all of our different size/signed-ness variants.
template<DataType Type, typename Buffer>
struct KeyEncoderTraits<Type,
                        Buffer,
                        typename base::enable_if<
                          base::is_integral<
                            typename DataTypeTraits<Type>::cpp_type
                          >::value
                        >::type
                       > {
 private:
  typedef typename DataTypeTraits<Type>::cpp_type cpp_type;
  typedef typename MathLimits<cpp_type>::UnsignedType unsigned_cpp_type;

  static unsigned_cpp_type SwapEndian(unsigned_cpp_type x) {
    switch (sizeof(x)) {
      case 1: return x;
      case 2: return BigEndian::FromHost16(x);
      case 4: return BigEndian::FromHost32(x);
      case 8: return BigEndian::FromHost64(x);
      case 16: return BigEndian::FromHost128(x);
      default: LOG(FATAL) << "bad type size of: " << sizeof(x);
    }
    return 0;
  }

 public:
  static void Encode(cpp_type key, Buffer* dst) {
    Encode(&key, dst);
  }

  static void Encode(const void* key_ptr, Buffer* dst) {
    unsigned_cpp_type key_unsigned;
    memcpy(&key_unsigned, key_ptr, sizeof(key_unsigned));

    // To encode signed integers, swap the MSB.
    if (MathLimits<cpp_type>::kIsSigned) {
      key_unsigned ^= static_cast<unsigned_cpp_type>(1) << (sizeof(key_unsigned) * CHAR_BIT - 1);
    }
    key_unsigned = SwapEndian(key_unsigned);
    dst->append(reinterpret_cast<const char*>(&key_unsigned), sizeof(key_unsigned));
  }

  static void EncodeWithSeparators(const void* key, bool is_last, Buffer* dst) {
    Encode(key, dst);
  }

  static Status DecodeKeyPortion(Slice* encoded_key,
                                 bool /*is_last*/,
                                 Arena* /*arena*/,
                                 uint8_t* cell_ptr) {
    if (PREDICT_FALSE(encoded_key->size() < sizeof(cpp_type))) {
      return Status::InvalidArgument("key too short", KUDU_REDACT(encoded_key->ToDebugString()));
    }

    unsigned_cpp_type val;
    memcpy(&val,  encoded_key->data(), sizeof(cpp_type));
    val = SwapEndian(val);
    if (MathLimits<cpp_type>::kIsSigned) {
      val ^= static_cast<unsigned_cpp_type>(1) << (sizeof(val) * CHAR_BIT - 1);
    }
    memcpy(cell_ptr, &val, sizeof(val));
    encoded_key->remove_prefix(sizeof(cpp_type));
    return Status::OK();
  }
};

template<typename Buffer>
struct KeyEncoderTraits<BINARY, Buffer> {
  static void Encode(const void* key, Buffer* dst) {
    Encode(*reinterpret_cast<const Slice*>(key), dst);
  }

  // simple slice encoding that just adds to the buffer
  inline static void Encode(const Slice& s, Buffer* dst) {
    dst->append(reinterpret_cast<const char*>(s.data()),s.size());
  }
  static void EncodeWithSeparators(const void* key, bool is_last, Buffer* dst) {
    EncodeWithSeparators(*reinterpret_cast<const Slice*>(key), is_last, dst);
  }

  // slice encoding that uses a separator to retain lexicographic
  // comparability.
  //
  // This implementation is heavily optimized for the case where the input
  // slice has no '\0' bytes. We assume this is common in most user-generated
  // compound keys.
  inline static void EncodeWithSeparators(const Slice& s, bool is_last, Buffer* dst) {
    if (is_last) {
      dst->append(reinterpret_cast<const char*>(s.data()), s.size());
    } else {
      // If we're a middle component of a composite key, we need to add a \x00
      // at the end in order to separate this component from the next one. However,
      // if we just did that, we'd have issues where a key that actually has
      // \x00 in it would compare wrong, so we have to instead add \x00\x00, and
      // encode \x00 as \x00\x01.
      int old_size = dst->size();
      dst->resize(old_size + s.size() * 2 + 2);

      const uint8_t* srcp = s.data();
      uint8_t* dstp = reinterpret_cast<uint8_t*>(&(*dst)[old_size]);
      int len = s.size();
      int rem = len;

      while (rem >= 16) {
        if (!SSEEncodeChunk<16>(&srcp, &dstp)) {
          goto slow_path;
        }
        rem -= 16;
      }
      while (rem >= 8) {
        if (!SSEEncodeChunk<8>(&srcp, &dstp)) {
          goto slow_path;
        }
        rem -= 8;
      }
      // Roll back to operate in 8 bytes at a time.
      if (len > 8 && rem > 0) {
        dstp -= 8 - rem;
        srcp -= 8 - rem;
        if (!SSEEncodeChunk<8>(&srcp, &dstp)) {
          // TODO: optimize for the case where the input slice has '\0'
          // bytes. (e.g. move the pointer to the first zero byte.)
          dstp += 8 - rem;
          srcp += 8 - rem;
          goto slow_path;
        }
        rem = 0;
        goto done;
      }

      slow_path:
      EncodeChunkLoop(&srcp, &dstp, rem);

      done:
      *dstp++ = 0;
      *dstp++ = 0;
      dst->resize(dstp - reinterpret_cast<uint8_t*>(&(*dst)[0]));
    }
  }

  static Status DecodeKeyPortion(Slice* encoded_key,
                                 bool is_last,
                                 Arena* arena,
                                 uint8_t* cell_ptr) {
    if (is_last) {
      Slice* dst_slice = reinterpret_cast<Slice *>(cell_ptr);
      if (PREDICT_FALSE(!arena->RelocateSlice(*encoded_key, dst_slice))) {
        return Status::RuntimeError("OOM");
      }
      encoded_key->remove_prefix(encoded_key->size());
      return Status::OK();
    }

    uint8_t* separator = static_cast<uint8_t*>(memmem(encoded_key->data(), encoded_key->size(),
                                                      "\0\0", 2));
    if (PREDICT_FALSE(separator == NULL)) {
      return Status::InvalidArgument("Missing separator after composite key string component",
                                     KUDU_REDACT(encoded_key->ToDebugString()));
    }

    uint8_t* src = encoded_key->mutable_data();
    int max_len = separator - src;
    uint8_t* dst_start = static_cast<uint8_t*>(arena->AllocateBytes(max_len));
    uint8_t* dst = dst_start;

    for (int i = 0; i < max_len; i++) {
      if (i >= 1 && src[i - 1] == '\0' && src[i] == '\1') {
        continue;
      }
      *dst++ = src[i];
    }

    int real_len = dst - dst_start;
    Slice slice(dst_start, real_len);
    memcpy(cell_ptr, &slice, sizeof(Slice));
    encoded_key->remove_prefix(max_len + 2);
    return Status::OK();
  }

 private:
  // Encode a chunk of 'len' bytes from '*srcp' into '*dstp', incrementing
  // the pointers upon return.
  //
  // This uses SSE2 operations to operate in 8 or 16 bytes at a time, fast-pathing
  // the case where there are no '\x00' bytes in the source.
  //
  // Returns true if the chunk was successfully processed, false if there was one
  // or more '\0' bytes requiring the slow path.
  //
  // REQUIRES: len == 16 or 8
  template<int LEN>
  static bool SSEEncodeChunk(const uint8_t** srcp, uint8_t** dstp) {
    #ifdef __aarch64__
    return false;
    #else
    COMPILE_ASSERT(LEN == 16 || LEN == 8, invalid_length);
    __m128i data;
    if (LEN == 16) {
      // Load 16 bytes (unaligned) into the XMM register.
      data = _mm_loadu_si128(reinterpret_cast<const __m128i*>(*srcp));
    } else if (LEN == 8) {
      // Load 8 bytes (unaligned) into the XMM register
      data = reinterpret_cast<__m128i>(_mm_load_sd(reinterpret_cast<const double*>(*srcp)));
    }
    // Compare each byte of the input with '\0'. This results in a vector
    // where each byte is either \x00 or \xFF, depending on whether the
    // input had a '\x00' in the corresponding position.
    __m128i zeros = reinterpret_cast<__m128i>(_mm_setzero_pd());
    __m128i zero_bytes = _mm_cmpeq_epi8(data, zeros);

    // Check whether the resulting vector is all-zero.
    bool all_zeros;
    if (LEN == 16) {
      all_zeros = _mm_testz_si128(zero_bytes, zero_bytes);
    } else { // LEN == 8
      all_zeros = _mm_cvtsi128_si64(zero_bytes) == 0;
    }

    // If it's all zero, we can just store the entire chunk.
    if (PREDICT_FALSE(!all_zeros)) {
      return false;
    }

    if (LEN == 16) {
      _mm_storeu_si128(reinterpret_cast<__m128i*>(*dstp), data);
    } else {
      _mm_storel_epi64(reinterpret_cast<__m128i*>(*dstp), data);  // movq m64, xmm
    }
    *dstp += LEN;
    *srcp += LEN;
    return true;
    #endif //__aarch64__
  }

  // Non-SSE loop which encodes 'len' bytes from 'srcp' into 'dst'.
  static void EncodeChunkLoop(const uint8_t** srcp, uint8_t** dstp, int len) {
    while (len--) {
      if (PREDICT_FALSE(**srcp == '\0')) {
        *(*dstp)++ = 0;
        *(*dstp)++ = 1;
      } else {
        *(*dstp)++ = **srcp;
      }
      (*srcp)++;
    }
  }
};

// Forward declaration is necessary for friend declaration in KeyEncoder.
template<typename Buffer>
class EncoderResolver;

// The runtime version of the key encoder
template <typename Buffer>
class KeyEncoder {
 public:

  // Encodes the provided key to the provided buffer
  void Encode(const void* key, Buffer* dst) const {
    encode_func_(key, dst);
  }

  // Special encoding for composite keys.
  void Encode(const void* key, bool is_last, Buffer* dst) const {
    encode_with_separators_func_(key, is_last, dst);
  }

  void ResetAndEncode(const void* key, Buffer* dst) const {
    dst->clear();
    Encode(key, dst);
  }

  // Decode the next component out of the composite key pointed to by '*encoded_key'
  // into *cell_ptr.
  // After decoding encoded_key is advanced forward such that it contains the remainder
  // of the composite key.
  // 'is_last' should be true when we expect that this component is the last (or only) component
  // of the composite key.
  // Any indirect data (eg strings) are allocated out of 'arena'.
  Status Decode(Slice* encoded_key,
                bool is_last,
                Arena* arena,
                uint8_t* cell_ptr) const {
    return decode_key_portion_func_(encoded_key, is_last, arena, cell_ptr);
  }

 private:
  friend class EncoderResolver<Buffer>;
  template<typename EncoderTraitsClass>
  explicit KeyEncoder(EncoderTraitsClass t)
    : encode_func_(EncoderTraitsClass::Encode),
      encode_with_separators_func_(EncoderTraitsClass::EncodeWithSeparators),
      decode_key_portion_func_(EncoderTraitsClass::DecodeKeyPortion) {
  }

  typedef void (*EncodeFunc)(const void* key, Buffer* dst);
  const EncodeFunc encode_func_;
  typedef void (*EncodeWithSeparatorsFunc)(const void* key, bool is_last, Buffer* dst);
  const EncodeWithSeparatorsFunc encode_with_separators_func_;

  typedef Status (*DecodeKeyPortionFunc)(Slice* enc_key, bool is_last,
                                       Arena* arena, uint8_t* cell_ptr);
  const DecodeKeyPortionFunc decode_key_portion_func_;

 private:
  DISALLOW_COPY_AND_ASSIGN(KeyEncoder);
};

template <typename Buffer>
extern const KeyEncoder<Buffer>& GetKeyEncoder(const TypeInfo* typeinfo);

extern const bool IsTypeAllowableInKey(const TypeInfo* typeinfo);

} // namespace kudu

#endif


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.

package org.chromium.chromoting.accountswitcher;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.Spinner;

import org.chromium.chromoting.AccountsAdapter;

/**
 * This class implements a basic UI for a user account switcher.
 */
public class AccountSwitcherBasic extends AccountSwitcherBase {
    /** Only accounts of this type will be selectable. */
    private static final String ACCOUNT_TYPE = "com.google";

    private String mSelectedAccount;

    private Spinner mAccountsSpinner;
    private LinearLayout mContainer;

    /**
     * The registered callback instance.
     */
    private Callback mCallback;

    /**
     * Constructs an account-switcher, using the given Context to create any Views. Called from
     * the activity's onCreate() method.
     * @param context Context used for creating Views and performing UI operations.
     * @param callback Callback for receiving notifications from the account-switcher.
     */
    public AccountSwitcherBasic(Context context, Callback callback) {
        mCallback = callback;
        mAccountsSpinner = new Spinner(context);
        mAccountsSpinner.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        mContainer = new LinearLayout(context);
        mContainer.setOrientation(LinearLayout.VERTICAL);
        mContainer.addView(mAccountsSpinner);
    }

    @Override
    public View getView() {
        return mContainer;
    }

    @Override
    public void setNavigation(View view) {
        mContainer.removeAllViews();
        mContainer.addView(mAccountsSpinner);
        mContainer.addView(view);
    }

    @Override
    public void setSelectedAndRecentAccounts(String selected, String[] recents) {
        // This implementation does not support recents.
        mSelectedAccount = selected;
    }

    @Override
    public String[] getRecentAccounts() {
        return new String[0];
    }

    @Override
    public void reloadAccounts() {
        Context context = getView().getContext();
        Account[] accounts = AccountManager.get(context).getAccountsByType(ACCOUNT_TYPE);
        if (accounts.length == 0) {
            mCallback.onAccountsListEmpty();
            return;
        }

        // Arbitrarily default to the first account if the currently-selected account is not in the
        // list.
        int selectedIndex = 0;
        for (int i = 0; i < accounts.length; i++) {
            if (accounts[i].name.equals(mSelectedAccount)) {
                selectedIndex = i;
                break;
            }
        }
        mSelectedAccount = accounts[selectedIndex].name;

        AccountsAdapter adapter = new AccountsAdapter(getView().getContext(), accounts);
        mAccountsSpinner.setAdapter(adapter);
        mAccountsSpinner.setSelection(selectedIndex);
        mAccountsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int itemPosition,
                    long itemId) {
                Account selected = (Account) parent.getItemAtPosition(itemPosition);
                mSelectedAccount = selected.name;
                mCallback.onAccountSelected(mSelectedAccount);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        mCallback.onAccountSelected(mSelectedAccount);
    }
}

redpajama_set_name: RedPajamaGithub


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

namespace Test.Framework.Data
{
    public sealed class RepositoryFactory
    {
        #region Nested Class for Singleton

        class Nested
        {
            static Nested()
            {
                instance.Initialize();
            }

            internal static readonly RepositoryFactory instance = new RepositoryFactory();
        }

        #endregion

        #region Private Members

        private HashSet<string> register;

        #endregion

        #region Public Instance

        public static RepositoryFactory Instance
        {
            get
            {
                return Nested.instance;
            }
        }

        #endregion

        #region Private Constructor / Methods

        private RepositoryFactory() { }

        private void Initialize()
        {
            if (register == null)
            {
                register = new HashSet<string>();
            }
        }

        public T Get<T>(params object[] args) where T : class
        {
            T instance = null;
            Ensure.Argument.IsNotNull(args, "args");
            Ensure.Argument.IsNotEmpty(args, "args");
            var input = args[0].ToString();
            var typeName = string.Format("{0}_{1}", typeof(T).Name, input);

            return GetInstance<T>(args, ref instance, typeName);
        }

        public T Get<I, T>(IDatabase database)
            where I : class
            where T : class, I
        {
            T instance = null;
            Ensure.Argument.IsNotNull(database, "database");
            object[] args = new object[] { database };
            var input = args[0].ToString();
            var typeName = typeof(T).Name + "_" + input;
            return GetInstance<I, T>(args, ref instance, typeName);
        }

        public T Get<I, T>(params object[] args)
            where I : class
            where T : class, I
        {
            T instance = null;
            Ensure.Argument.IsNotNull(args, "args");
            Ensure.Argument.IsNotEmpty(args, "args");
            var input = args[0].ToString();
            var typeName = string.Format("{0}_{1}", typeof(T).Name, input);
            return GetInstance<I, T>(args, ref instance, typeName);
        }

        public T Get<I, T>(string connectionString, params object[] args)
            where I : class
            where T : class, I
        {
            T instance = null;
            Ensure.Argument.IsNotNull(args, "args");
            Ensure.Argument.IsNotEmpty(args, "args");
            var input = args[0].ToString();
            var typeName = string.Format("{0}_{1}_{2}", typeof(T).Name, input, connectionString);
            return GetInstance<I, T>(args, ref instance, typeName);
        }

        public T Get<I, T, C>(string connectionString, params object[] args)
            where I : class
            where T : class, I
            where C : class
        {
            T instance = null;
            var context = Container.Resolve<C>(connectionString);
            Ensure.Argument.IsNotNull(context, "context");
            args[0] = context;
            Ensure.Argument.IsNotNull(args, "args");
            Ensure.Argument.IsNotEmpty(args, "args");
            var input = args[0].ToString();
            var typeName = string.Format("{0}_{1}_{2}", typeof(T).Name, input, connectionString);
            return GetInstance<I, T>(args, ref instance, typeName);
        }

        #endregion

        #region Private Methods
        private T GetInstance<I, T>(object[] args, ref T instance, string typeName)
            where I : class
            where T : class, I
        {
            if (register.Contains(typeName))
                return Container.Resolve<T>(typeName);

            var abstractType = typeof(T);

            var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
                .SelectMany(s => s.GetTypes())
                .Where(p => p.IsClass && !p.IsAbstract && abstractType.IsAssignableFrom(p));

            var concreteType = types.FirstOrDefault();

            if (concreteType == null)
                throw new InvalidOperationException(String.Format("No implementation of {0} was found", abstractType));

            instance = Activator.CreateInstance(concreteType, args) as T;

            register.Add(typeName);

            Container.RegisterInstance<T>(typeName, instance);

            return instance;
        }
        private T GetInstance<T>(object[] args, ref T instance, string typeName) where T : class
        {
            if (register.Contains(typeName))
                return Container.Resolve<T>(typeName);

            var abstractType = typeof(T);

            var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
                .SelectMany(s => s.GetTypes())
                .Where(p => p.IsClass && !p.IsAbstract && abstractType.IsAssignableFrom(p));

            var concreteType = types.FirstOrDefault();

            if (concreteType == null)
            {
                throw new InvalidOperationException(String.Format("No implementation of {0} was found", abstractType));
            }

            instance = Activator.CreateInstance(concreteType, args) as T;

            register.Add(typeName);

            Container.RegisterInstance<T>(typeName, instance);

            return instance;
        }
        #endregion
    }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using Newtonsoft.Json;
using TrackableEntities;
using TrackableEntities.Client;
using SampleWebApi.Inheritance.Shared.Entities.Models;

namespace SampleWebApi.Inheritance.ConsoleClient
{
    class Program
    {
        static void Main(string[] args)
        {
            // Main method

            Console.WriteLine("Press Enter to start");
            Console.ReadLine();

            // Create http client
            const string serviceBaseAddress = "http://localhost:" + "49640" + "/";
            var client = new HttpClient { BaseAddress = new Uri(serviceBaseAddress) };

            List<Product> products = GetProducts(client).ToList();
            foreach (var p in products)
                PrintProduct(p);

            // Select individual product
            Console.WriteLine("\nProduct to update {ProductId}:");
            int productId = int.Parse(Console.ReadLine());
            var product = products.Single(p => p.ProductId == productId);

            // Track changes
            var changeTracker = new ChangeTrackingCollection<Product>(product);

            // Update product
            product.UnitPrice++;

            // Get changes
            var changedProduct = changeTracker.GetChanges().SingleOrDefault();

            // Submit changes
            Product updatedProduct;
            if (product is DiscontinuedProduct)
                updatedProduct = UpdateEntity(client, (DiscontinuedProduct)product);
            else
                updatedProduct = UpdateEntity(client, product);

            // Merge changes
            changeTracker.MergeChanges(updatedProduct);

            Console.WriteLine("Updated product:");
            PrintProduct(product);

            // Keep console open
            Console.WriteLine("\nPress any key to exit");
            Console.ReadKey(true);
        }

        private static IEnumerable<Category> GetCategories(HttpClient client)
        {
            const string request = "api/Category";
            var response = client.GetAsync(request).Result;
            response.EnsureSuccessStatusCode();
            var result = response.Content.ReadAsAsync<IEnumerable<Category>>().Result;
            return result;
        }

        private static IEnumerable<Product> GetProducts
            (HttpClient client)
        {
            string request = "api/Product";
            var response = client.GetAsync(request).Result;
            response.EnsureSuccessStatusCode();

            var result = ReadContentAsAsync<IEnumerable<Product>>(response).Result;
            return result;
        }

        private static T UpdateEntity<T>(HttpClient client, T entity)
        {
            string request = "api/Product";
            var content = GetObjectContent(entity);
            var response = client.PutAsync(request, content).Result;
            response.EnsureSuccessStatusCode();

            var result = ReadContentAsAsync<T>(response).Result;
            return result;
        }

        private static async Task<T> ReadContentAsAsync<T>(HttpResponseMessage response)
        {
            var jsonFormatter = new JsonMediaTypeFormatter { SerializerSettings = { TypeNameHandling = TypeNameHandling.Auto } };
            var result = await response.Content.ReadAsAsync<T>(new MediaTypeFormatter[] { jsonFormatter });
            return result;
        }

        private static ObjectContent<T> GetObjectContent<T>(T entity)
        {
            var jsonFormatter = new JsonMediaTypeFormatter { SerializerSettings = { TypeNameHandling = TypeNameHandling.Auto } };
            var content = new ObjectContent<T>(entity, jsonFormatter);
            return content;
        }

        private static void PrintCategory(Category c)
        {
            Console.WriteLine("{0} {1}",
                c.CategoryId,
                c.CategoryName);
        }

        private static void PrintProduct(Product p)
        {
            // See if this is a discontinued product
            var discProduct = p as DiscontinuedProduct;

            Console.WriteLine("{0} {1} {2} {3}",
                p.ProductId,
                p.ProductName,
                p.UnitPrice.GetValueOrDefault().ToString("C"),
                discProduct != null
                    ? string.Format("Discontinued: {0}",
                    discProduct.DiscontinuedDate.GetValueOrDefault().ToShortDateString())
                    : string.Empty);
        }
    }
}


text:
/***************************************************************************/
/*                                                                         */
/*  pfrload.h                                                              */
/*                                                                         */
/*    FreeType PFR loader (specification).                                 */
/*                                                                         */
/*  Copyright 2002-2018 by                                                 */
/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
/*                                                                         */
/*  This file is part of the FreeType project, and may only be used,       */
/*  modified, and distributed under the terms of the FreeType project      */
/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
/*  this file you indicate that you have read the license and              */
/*  understand and accept it fully.                                        */
/*                                                                         */
/***************************************************************************/

#ifndef PFRLOAD_H_
#define PFRLOAD_H_

#include "pfrobjs.h"
#include FT_INTERNAL_STREAM_H

FT_BEGIN_HEADER

  /* some size checks should be always done (mainly to prevent */
  /* excessive allocation for malformed data), ...             */
#define PFR_CHECK_SIZE( x )  do                       \
                             {                        \
                               if ( p + (x) > limit ) \
                                 goto Too_Short;      \
                             } while ( 0 )

  /* ... and some only if intensive checking is explicitly requested */
#ifdef PFR_CONFIG_NO_CHECKS
#define PFR_CHECK( x )  do { } while ( 0 )
#else
#define PFR_CHECK  PFR_CHECK_SIZE
#endif

#define PFR_NEXT_BYTE( p )    FT_NEXT_BYTE( p )
#define PFR_NEXT_INT8( p )    FT_NEXT_CHAR( p )
#define PFR_NEXT_SHORT( p )   FT_NEXT_SHORT( p )
#define PFR_NEXT_USHORT( p )  FT_NEXT_USHORT( p )
#define PFR_NEXT_LONG( p )    FT_NEXT_OFF3( p )
#define PFR_NEXT_ULONG( p )   FT_NEXT_UOFF3( p )

 /* handling extra items */

  typedef FT_Error
  (*PFR_ExtraItem_ParseFunc)( FT_Byte*    p,
                              FT_Byte*    limit,
                              FT_Pointer  data );

  typedef struct  PFR_ExtraItemRec_
  {
    FT_UInt                  type;
    PFR_ExtraItem_ParseFunc  parser;

  } PFR_ExtraItemRec;

  typedef const struct PFR_ExtraItemRec_*  PFR_ExtraItem;

  FT_LOCAL( FT_Error )
  pfr_extra_items_skip( FT_Byte*  *pp,
                        FT_Byte*  limit );

  FT_LOCAL( FT_Error )
  pfr_extra_items_parse( FT_Byte*      *pp,
                         FT_Byte*       limit,
                         PFR_ExtraItem  item_list,
                         FT_Pointer     item_data );

  /* load a PFR header */
  FT_LOCAL( FT_Error )
  pfr_header_load( PFR_Header  header,
                   FT_Stream   stream );

  /* check a PFR header */
  FT_LOCAL( FT_Bool )
  pfr_header_check( PFR_Header  header );

  /* return number of logical fonts in this file */
  FT_LOCAL( FT_Error )
  pfr_log_font_count( FT_Stream   stream,
                      FT_UInt32   log_section_offset,
                      FT_Long    *acount );

  /* load a pfr logical font entry */
  FT_LOCAL( FT_Error )
  pfr_log_font_load( PFR_LogFont  log_font,
                     FT_Stream    stream,
                     FT_UInt      face_index,
                     FT_UInt32    section_offset,
                     FT_Bool      size_increment );

  /* load a physical font entry */
  FT_LOCAL( FT_Error )
  pfr_phy_font_load( PFR_PhyFont  phy_font,
                     FT_Stream    stream,
                     FT_UInt32    offset,
                     FT_UInt32    size );

  /* finalize a physical font */
  FT_LOCAL( void )
  pfr_phy_font_done( PFR_PhyFont  phy_font,
                     FT_Memory    memory );

  /* */

FT_END_HEADER

#endif /* PFRLOAD_H_ */

/* END */


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="8dp"
    tools:context="com.github.oryanmat.trellowidget.activity.ConfigActivity">

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:indeterminate="true" />

    <RelativeLayout
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible">

        <LinearLayout
            android:id="@+id/linear"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="16dp">

            <TextView
                style="?android:windowTitleStyle"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="@string/board" />

            <Spinner
                android:id="@+id/boardSpinner"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />

            <TextView
                style="?android:windowTitleStyle"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingTop="8dp"
                android:text="@string/list" />

            <Spinner
                android:id="@+id/listSpinner"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>

        <LinearLayout
            style="?android:buttonBarStyle"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/linear"
            android:gravity="end"
            android:orientation="horizontal">

            <Button
                android:id="@+id/cancelButton"
                style="?android:buttonBarButtonStyle"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="cancel"
                android:text="@android:string/cancel" />

            <Button
                android:id="@+id/okButton"
                style="?android:buttonBarButtonStyle"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="ok"
                android:text="@android:string/ok" />
        </LinearLayout>
    </RelativeLayout>
</RelativeLayout>


text:
package service

import (
	"github.com/tidepool-org/platform/application"
	"github.com/tidepool-org/platform/auth"
	"github.com/tidepool-org/platform/errors"
	"github.com/tidepool-org/platform/service"
	"github.com/tidepool-org/platform/service/api"
	"github.com/tidepool-org/platform/service/server"
)

type Service struct {
	*application.Application
	secret         string
	authClientImpl auth.Client
	api            *api.API
	server         *server.Standard
}

func New() *Service {
	return &Service{
		Application: application.New(),
	}
}

func (s *Service) Initialize(provider application.Provider) error {
	if err := s.Application.Initialize(provider); err != nil {
		return err
	}

	if err := s.initializeSecret(); err != nil {
		return err
	}
	if err := s.initializeAPI(); err != nil {
		return err
	}
	return s.initializeServer()
}

func (s *Service) Terminate() {
	s.terminateServer()
	s.terminateAPI()
	s.terminateSecret()

	s.Application.Terminate()
}

func (s *Service) Run() error {
	if s.server == nil {
		return errors.New("service not initialized")
	}

	s.Logger().Debug("Finalizing middleware")

	if err := s.api.InitializeMiddleware(); err != nil {
		return errors.Wrap(err, "unable to initialize middleware")
	}

	return s.server.Serve()
}

func (s *Service) Secret() string {
	return s.secret
}

func (s *Service) AuthClient() auth.Client {
	return s.authClientImpl
}

func (s *Service) SetAuthClient(authClientImpl auth.Client) {
	s.authClientImpl = authClientImpl
}

func (s *Service) API() service.API {
	return s.api
}

func (s *Service) initializeSecret() error {
	s.Logger().Debug("Initializing secret")

	secret := s.ConfigReporter().GetWithDefault("secret", "")
	if secret == "" {
		return errors.New("secret is missing")
	}
	s.secret = secret

	return nil
}

func (s *Service) terminateSecret() {
	if s.secret != "" {
		s.Logger().Debug("Terminating secret")
		s.secret = ""
	}
}

func (s *Service) initializeAPI() error {
	s.Logger().Debug("Creating api")

	a, err := api.New(s)
	if err != nil {
		return errors.Wrap(err, "unable to create api")
	}
	s.api = a

	return nil
}

func (s *Service) terminateAPI() {
	if s.api != nil {
		s.Logger().Debug("Destroying api")
		s.api = nil
	}
}

func (s *Service) initializeServer() error {
	s.Logger().Debug("Loading server config")

	cfg := server.NewConfig()
	if err := cfg.Load(s.ConfigReporter().WithScopes("server")); err != nil {
		return errors.Wrap(err, "unable to load server config")
	}

	s.Logger().Debug("Creating server")

	svr, err := server.NewStandard(cfg, s.Logger(), s.API())
	if err != nil {
		return errors.Wrap(err, "unable to create server")
	}
	s.server = svr

	return nil
}

func (s *Service) terminateServer() {
	if s.server != nil {
		if err := s.server.Shutdown(); err != nil {
			s.Logger().Errorf("Error while destroying the server: %v", err)
		}
		s.server = nil
	}
}


text:
namespace ash {

namespace {
std::unique_ptr<views::TestViewsDelegate> MakeTestViewsDelegate() {
  return std::make_unique<AshTestViewsDelegate>();
}
}  // namespace

AshTestHelper::InitParams::InitParams() = default;
AshTestHelper::InitParams::InitParams(InitParams&&) = default;
AshTestHelper::InitParams::~InitParams() = default;

class AshTestHelper::BluezDBusManagerInitializer {
 public:
  BluezDBusManagerInitializer() { bluez::BluezDBusManager::InitializeFake(); }
  ~BluezDBusManagerInitializer() {
    device::BluetoothAdapterFactory::Shutdown();
    bluez::BluezDBusManager::Shutdown();
  }
};

class AshTestHelper::PowerPolicyControllerInitializer {
 public:
  PowerPolicyControllerInitializer() {
    chromeos::PowerPolicyController::Initialize(
        chromeos::PowerManagerClient::Get());
  }
  ~PowerPolicyControllerInitializer() {
    chromeos::PowerPolicyController::Shutdown();
  }
};

AshTestHelper::AshTestHelper(ui::ContextFactory* context_factory)
    : AuraTestHelper(context_factory),
      system_monitor_(std::make_unique<base::SystemMonitor>()) {
  views::ViewsTestHelperAura::SetFallbackTestViewsDelegateFactory(
      &MakeTestViewsDelegate);

  // TODO(jamescook): Can we do this without changing command line?
  // Use the origin (1,1) so that it doesn't overlap with the native mouse
  // cursor.
  if (!base::SysInfo::IsRunningOnChromeOS() &&
      !command_line_->GetProcessCommandLine()->HasSwitch(
          ::switches::kHostWindowBounds)) {
    // TODO(oshima): Disable native events instead of adding offset.
    command_line_->GetProcessCommandLine()->AppendSwitchASCII(
        ::switches::kHostWindowBounds, "10+10-800x600");
  }

  TabletModeController::SetUseScreenshotForTest(false);

  display::ResetDisplayIdForTest();
  display::SetInternalDisplayIds({});

  CrasAudioClient::InitializeFake();
  // Create CrasAudioHandler for testing since g_browser_process is not
  // created in AshTestBase tests.
  CrasAudioHandler::InitializeForTesting();

  // Reset the global state for the cursor manager. This includes the
  // last cursor visibility state, etc.
  wm::CursorManager::ResetCursorVisibilityStateForTest();

  // Clears the saved state so that test doesn't use on the wrong
  // default state.
  shell::ToplevelWindow::ClearSavedStateForTest();
}

AshTestHelper::~AshTestHelper() {
  if (app_list_test_helper_)
    TearDown();

  // Ensure the next test starts with a null display::Screen.  This must be done
  // here instead of in TearDown() since some tests test access to the Screen
  // after the shell shuts down (which they use TearDown() to trigger).
  ScreenAsh::DeleteScreenForShutdown();

  // This should never have a meaningful effect, since either there is no
  // ViewsTestHelperAura instance or the instance is currently in its
  // destructor.
  views::ViewsTestHelperAura::SetFallbackTestViewsDelegateFactory(nullptr);
}

void AshTestHelper::SetUp() {
  SetUp(InitParams());
}

void AshTestHelper::TearDown() {
  saved_desk_test_helper_.reset();

  ambient_ash_test_helper_.reset();

  // The AppListTestHelper holds a pointer to the AppListController the Shell
  // owns, so shut the test helper down first.
  app_list_test_helper_.reset();

  // Stop event dispatch like we do in ChromeBrowserMainExtraPartsAsh.
  Shell::Get()->ShutdownEventDispatch();

  Shell::DeleteInstance();
  // Suspend the tear down until all resources are returned via
  // CompositorFrameSinkClient::ReclaimResources()
  base::RunLoop().RunUntilIdle();

  chromeos::LoginState::Shutdown();

  CrasAudioHandler::Shutdown();
  CrasAudioClient::Shutdown();

  // The PowerPolicyController holds a pointer to the PowerManagementClient, so
  // shut the controller down first.
  power_policy_controller_initializer_.reset();
  chromeos::PowerManagerClient::Shutdown();
  RgbkbdClient::Shutdown();

  TabletModeController::SetUseScreenshotForTest(true);

  // Destroy all owned objects to prevent tests from depending on their state
  // after this returns.
  test_keyboard_controller_observer_.reset();
  session_controller_client_.reset();
  test_views_delegate_.reset();
  new_window_delegate_provider_.reset();
  bluez_dbus_manager_initializer_.reset();
  system_tray_client_.reset();
  assistant_service_.reset();
  notifier_settings_controller_.reset();
  prefs_provider_.reset();
  statistics_provider_.reset();
  command_line_.reset();

  // Purge ColorProviderManager between tests so that we don't accumulate
  // ColorProviderInitializers. crbug.com/1349232.
  ui::ColorProviderManager::ResetForTesting();

  AuraTestHelper::TearDown();

  // Cleanup the global state for InputMethodManager, but only if
  // it was setup by this test helper. This allows tests to implement
  // their own override, and in that case we shouldn't call Shutdown
  // otherwise the global state will be deleted twice.
  if (input_method_manager_) {
    input_method::InputMethodManager::Shutdown();
    input_method_manager_ = nullptr;
  }
}

aura::Window* AshTestHelper::GetContext() {
  aura::Window* root_window = Shell::GetRootWindowForNewWindows();
  if (!root_window)
    root_window = Shell::GetPrimaryRootWindow();
  DCHECK(root_window);
  return root_window;
}

aura::WindowTreeHost* AshTestHelper::GetHost() {
  auto* manager = Shell::Get()->window_tree_host_manager();
  const int64_t id = manager->GetPrimaryDisplayId();
  return manager->GetAshWindowTreeHostForDisplayId(id)->AsWindowTreeHost();
}

aura::TestScreen* AshTestHelper::GetTestScreen() {
  // If a test needs this, we may need to refactor TestScreen such that its
  // methods can operate atop some sort of real screen/host/display, and hook
  // them to the ones provided by the shell.  For now, not bothering.
  NOTIMPLEMENTED();
  return nullptr;
}

aura::client::FocusClient* AshTestHelper::GetFocusClient() {
  return Shell::Get()->focus_controller();
}

aura::client::CaptureClient* AshTestHelper::GetCaptureClient() {
  return wm::CaptureController::Get();
}

void AshTestHelper::SetUp(InitParams init_params) {
  // Build `ui_stabilizer_` only for a pixel diff test.
  if (init_params.pixel_test_init_params) {
    // Constructing `ui_stabilizer_` sets the locale. Therefore, building
    // `ui_stabilizer_` before the code that establishes the Ash UI.
    ui_stabilizer_ = std::make_unique<AshTestUiStabilizer>(
        *init_params.pixel_test_init_params);
  }

  // This block of objects are conditionally initialized here rather than in the
  // constructor to make it easier for test classes to override them.
  if (!input_method::InputMethodManager::Get()) {
    // |input_method_manager_| is not owned and is cleaned up in TearDown()
    // by calling InputMethodManager::Shutdown().
    input_method_manager_ = new input_method::MockInputMethodManager();
    input_method::InputMethodManager::Initialize(input_method_manager_);
  }

  if (!bluez::BluezDBusManager::IsInitialized()) {
    bluez_dbus_manager_initializer_ =
        std::make_unique<BluezDBusManagerInitializer>();
  }
  if (!RgbkbdClient::Get())
    RgbkbdClient::InitializeFake();
  if (!chromeos::PowerManagerClient::Get())
    chromeos::PowerManagerClient::InitializeFake();
  if (!chromeos::PowerPolicyController::IsInitialized()) {
    power_policy_controller_initializer_ =
        std::make_unique<PowerPolicyControllerInitializer>();
  }
  if (!NewWindowDelegate::GetInstance()) {
    new_window_delegate_provider_ =
        std::make_unique<TestNewWindowDelegateProvider>(
            std::make_unique<TestNewWindowDelegate>());
  }
  if (!views::ViewsDelegate::GetInstance())
    test_views_delegate_ = MakeTestViewsDelegate();

  chromeos::LoginState::Initialize();

  ambient_ash_test_helper_ = std::make_unique<AmbientAshTestHelper>();

  ShellInitParams shell_init_params;
  shell_init_params.delegate = std::move(init_params.delegate);
  if (!shell_init_params.delegate)
    shell_init_params.delegate = std::make_unique<TestShellDelegate>();
  shell_init_params.context_factory = GetContextFactory();
  shell_init_params.local_state = init_params.local_state;
  shell_init_params.keyboard_ui_factory =
      std::make_unique<TestKeyboardUIFactory>();
  Shell::CreateInstance(std::move(shell_init_params));
  Shell* shell = Shell::Get();

  // The dark/light mode educational nudge is expected to be shown when session
  // state changed to ACTIVE. This means it might be shown above the shelf in
  // all the tests with an active user session. This setting here make it will
  // not be shown by default in tests. As keep it shown will change the
  // operations needed in many of the tests, e.g, when productive launcher is
  // shown as well, we need one more click outside of the launcher to dismiss
  // the nudge first before dismissing the launcher.
  shell->dark_light_mode_controller()->SetShowNudgeForTesting(false);

  // Set up a test wallpaper controller client before signing in any users. At
  // the time a user logs in, Wallpaper controller relies on
  // WallpaperControllerClient to check if user data should be synced.
  wallpaper_controller_client_ =
      std::make_unique<TestWallpaperControllerClient>();
  shell->wallpaper_controller()->SetClient(wallpaper_controller_client_.get());

  // Disable the notification delay timer used to prevent non system
  // notifications from showing up right after login. This needs to be done
  // before any user sessions are added since the delay timer starts right
  // after that.
  SessionStateNotificationBlocker::SetUseLoginNotificationDelayForTest(false);

  // Cursor is visible by default in tests.
  shell->cursor_manager()->ShowCursor();

  shell->assistant_controller()->SetAssistant(assistant_service_.get());

  shell->system_tray_model()->SetClient(system_tray_client_.get());

  session_controller_client_ = std::make_unique<TestSessionControllerClient>(
      shell->session_controller(), prefs_provider_.get());
  session_controller_client_->InitializeAndSetClient();
  if (init_params.start_session)
    session_controller_client_->CreatePredefinedUserSessions(1);

  // Requires the AppListController the Shell creates.
  app_list_test_helper_ = std::make_unique<AppListTestHelper>();

  Shell::GetPrimaryRootWindow()->Show();
  Shell::GetPrimaryRootWindow()->GetHost()->Show();

  // Don't change the display size due to host size resize.
  display::test::DisplayManagerTestApi(shell->display_manager())
      .DisableChangeDisplayUponHostResize();

  // Create the test keyboard controller observer to respond to
  // OnLoadKeyboardContentsRequested().
  test_keyboard_controller_observer_ =
      std::make_unique<TestKeyboardControllerObserver>(
          shell->keyboard_controller());

  // Tests that change the display configuration generally don't care about the
  // notifications and the popup UI can interfere with things like cursors.
  shell->screen_layout_observer()->set_show_notifications_for_testing(false);

  // Disable display change animations in unit tests.
  DisplayConfigurationControllerTestApi(
      shell->display_configuration_controller())
      .SetDisplayAnimator(false);

  // Remove the app dragging animations delay for testing purposes.
  shell->overview_controller()->set_delayed_animation_task_delay_for_test(
      base::TimeDelta());

  // Tests expect empty wallpaper.
  shell->wallpaper_controller()->CreateEmptyWallpaperForTesting();

  // Move the mouse cursor to far away so that native events don't interfere
  // with test expectations.
  Shell::GetPrimaryRootWindow()->MoveCursorTo(gfx::Point(-1000, -1000));
  shell->cursor_manager()->EnableMouseEvents();

  // Changing GestureConfiguration shouldn't make tests fail. These values
  // prevent unexpected events from being generated during tests. Such as
  // delayed events which create race conditions on slower tests.
  ui::GestureConfiguration* gesture_config =
      ui::GestureConfiguration::GetInstance();
  gesture_config->set_max_touch_down_duration_for_click_in_ms(800);
  gesture_config->set_long_press_time_in_ms(1000);
  gesture_config->set_max_touch_move_in_pixels_for_click(5);

  // Fake the |ec_lid_angle_driver_status_| in the unittests.
  AccelerometerReader::GetInstance()->SetECLidAngleDriverStatusForTesting(
      ECLidAngleDriverStatus::NOT_SUPPORTED);

  // Call `StabilizeUIForPixelTest()` after the user session is activated (if
  // any) in the test setup.
  if (ui_stabilizer_) {
    DCHECK(init_params.pixel_test_init_params);
    StabilizeUIForPixelTest();
  }

  saved_desk_test_helper_ = std::make_unique<SavedDeskTestHelper>();
}

display::Display AshTestHelper::GetSecondaryDisplay() const {
  return display::test::DisplayManagerTestApi(Shell::Get()->display_manager())
      .GetSecondaryDisplay();
}

void AshTestHelper::SimulateUserLogin(const AccountId& account_id,
                                      user_manager::UserType user_type) {
  session_controller_client_->AddUserSession(
      account_id, account_id.GetUserEmail(), user_type);
  session_controller_client_->SwitchActiveUser(account_id);
  session_controller_client_->SetSessionState(
      session_manager::SessionState::ACTIVE);
}

void AshTestHelper::StabilizeUIForPixelTest() {
  const gfx::Size primary_display_size =
      display::Screen::GetScreen()
          ->GetDisplayNearestWindow(Shell::GetPrimaryRootWindow())
          .size();
  ui_stabilizer_->StabilizeUi(primary_display_size);
}

}  // namespace ash


text:
package puzzles

import (
	"errors"
	"log"
	"math"
	"sort"
	"strconv"
	"strings"
)

func NewDay3Puzzle() *Puzzle {
	return &Puzzle{
		Title:             "Day 3: Crossed Wires",
		Slug:              "03-crossed-wires",
		PuzzleSolverIface: &Day3Solver{},
	}
}

type Day3Solver struct{}

func (s *Day3Solver) Solve(input []string) (ResultIface, error) {
	var result Result
	result.DayNum = 3

	part1, err := s.Part1(input)
	if err != nil {
		return nil, err
	}

	part2, err := s.Part2(input)
	if err != nil {
		return nil, err
	}

	result.Part1 = part1
	result.Part2 = part2
	return &result, nil
}

func (s *Day3Solver) Part1(inputs []string) (string, error) {
	c := NewWireClient()
	if err := c.InitializeWirePaths(inputs); err != nil {
		return "", err
	}

	c.ProcessInstructions()
	intResult := c.FindShortestDistance()
	result := strconv.Itoa(intResult)

	return result, nil
}

func (s *Day3Solver) Part2(inputs []string) (string, error) {
	c := NewWireClient()
	if err := c.InitializeWirePaths(inputs); err != nil {
		return "", err
	}

	c.ProcessInstructions()
	intResult := c.FindFewestSteps()
	result := strconv.Itoa(intResult)

	return result, nil
}

type WireInstruction struct {
	Direction string
	Distance  int
}

type WireCoordinate struct {
	X     int
	Y     int
	Steps int
}

type WireClient struct {
	WireAInstructions []WireInstruction
	WireBInstructions []WireInstruction
	WireACoordinates  []WireCoordinate
	WireBCoordinates  []WireCoordinate
	WireCrossings     []WireCoordinate
}

func NewWireClient() *WireClient {
	return new(WireClient)
}

func (c *WireClient) InitializeWirePaths(pathStrings []string) error {
	if len(pathStrings) != 2 {
		return errors.New("Client requires two path strings.")
	}

	c.WireAInstructions = []WireInstruction{}
	c.WireBInstructions = []WireInstruction{}

	for i, pathString := range pathStrings {
		paths := strings.Split(pathString, ",")
		for _, path := range paths {
			direction := string(path[0])
			distance, err := strconv.Atoi(path[1:])
			if err != nil {
				log.Fatal("Strconv error: ", err)
			}

			instruction := WireInstruction{direction, distance}
			if i == 0 {
				c.WireAInstructions = append(c.WireAInstructions, instruction)
			} else {
				c.WireBInstructions = append(c.WireBInstructions, instruction)
			}
		}
	}

	return nil
}

func (c *WireClient) ProcessInstructions() {
	c.TraceWirePaths()
	c.FindWireCrossings()
}

func (c *WireClient) TraceWirePaths() {
	processInstructions := func(instructionSet []WireInstruction) []WireCoordinate {
		coordinateSet := []WireCoordinate{WireCoordinate{0, 0, 0}}

		for _, instruction := range instructionSet {
			// D -> -y U -> +y
			// L -> -x R -> +x
			for i := 0; i < instruction.Distance; i++ {
				prev := coordinateSet[len(coordinateSet)-1]
				new := WireCoordinate{X: prev.X, Y: prev.Y, Steps: prev.Steps}

				switch instruction.Direction {
				case "U":
					new.Y++
				case "R":
					new.X++
				case "D":
					new.Y--
				case "L":
					new.X--
				}

				new.Steps++
				coordinateSet = append(coordinateSet, new)
			}
		}

		return coordinateSet[1:]
	}

	c.WireACoordinates = processInstructions(c.WireAInstructions)
	c.WireBCoordinates = processInstructions(c.WireBInstructions)
}

func (c *WireClient) FindWireCrossings() {
	var wireCrossings []WireCoordinate

	for _, a := range c.WireACoordinates {
		for _, b := range c.WireBCoordinates {
			if a.X == b.X && a.Y == b.Y {
				new := WireCoordinate{X: a.X, Y: a.Y, Steps: a.Steps + b.Steps}
				wireCrossings = append(wireCrossings, new)
			}
		}
	}

	c.WireCrossings = wireCrossings
}

func (c *WireClient) FindShortestDistance() int {
	distances := c.FindCrossingDistances()
	sort.Ints(distances)
	return distances[0]
}

func (c *WireClient) FindCrossingDistances() []int {
	var distances []int

	for _, crossing := range c.WireCrossings {
		distance := int(math.Abs(float64(crossing.X))) + int(math.Abs(float64(crossing.Y)))
		distances = append(distances, distance)
	}

	return distances
}

func (c *WireClient) FindFewestSteps() int {
	var steps []int

	for _, crossing := range c.WireCrossings {
		steps = append(steps, crossing.Steps)
	}

	sort.Ints(steps)
	return steps[0]
}


text:
using Api;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler.Encoder;
using Microsoft.Owin.Security.Jwt;
using Owin;
using WebConfigurationManager = System.Web.Configuration.WebConfigurationManager;

[assembly: OwinStartup(typeof(Startup))]

namespace Api
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var issuer = WebConfigurationManager.AppSettings["Auth0Domain"];
            var audience = WebConfigurationManager.AppSettings["Auth0ClientID"];
            var secret = TextEncodings.Base64Url.Decode(
                WebConfigurationManager.AppSettings["Auth0ClientSecret"]);

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] {audience},
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                    },
                });
        }
    }
}


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.util.PopupUtil;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.wm.impl.welcomeScreen.recentProjects.RecentProjectFilteringTree;
import com.intellij.openapi.wm.impl.welcomeScreen.recentProjects.RecentProjectPanelComponentFactory;
import com.intellij.openapi.wm.impl.welcomeScreen.NewRecentProjectPanel;
import com.intellij.ui.IdeUICustomization;
import com.intellij.ui.SearchTextField;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

/**
 * @author Konstantin Bulenkov
 */
final class ManageRecentProjectsAction extends DumbAwareAction {
  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    Disposable disposable = Disposer.newDisposable();
    Project project = e.getRequiredData(CommonDataKeys.PROJECT);

    RecentProjectFilteringTree recentProjectFilteringTree = RecentProjectPanelComponentFactory.createComponent(disposable);
    JComponent recentProjectTree = recentProjectFilteringTree.getComponent();
    SearchTextField searchTextField = recentProjectFilteringTree.installSearchField();

    PopupUtil.applyNewUIBackground(recentProjectTree);
    PopupUtil.applyNewUIBackground(searchTextField);
    JBPopup popup = JBPopupFactory.getInstance().createComponentPopupBuilder(recentProjectTree, recentProjectTree)
      .setTitle(IdeUICustomization.getInstance().projectMessage("popup.title.recent.projects"))
      .setFocusable(true)
      .setRequestFocus(true)
      .setMayBeParent(true)
      .setDimensionServiceKey(null, "manage.recent.projects.popup", false)
      .setMovable(true)
      .setResizable(true)
      .setNormalWindowLevel(true)
      .createPopup();
    Disposer.register(popup, disposable);

    popup.showCenteredInCurrentWindow(project);
  }

  @Override
  public void update(@NotNull AnActionEvent e) {
    Project project = e.getProject();
    boolean enable = project != null && !RecentProjectListActionProvider.getInstance().getActions(false).isEmpty();
    e.getPresentation().setEnabledAndVisible(enable);
  }
}


text:
package errors

import (
	"errors"
)

var (
	NoSuchPodErr               = errors.New("no such pod exists")
	NoSuchTaskErr              = errors.New("no such task exists")
	ReconciliationCancelledErr = errors.New("explicit task reconciliation cancelled")
	NoSuitableOffersErr        = errors.New("no suitable offers for pod/task")
)


text:
__all__ = ['Parser', 'ParserError']

from error import MarkedYAMLError
from tokens import *
from events import *
from scanner import *

class ParserError(MarkedYAMLError):
    pass

class Parser:
    # Since writing a recursive-descendant parser is a straightforward task, we
    # do not give many comments here.
    # Note that we use Python generators. If you rewrite the parser in another
    # language, you may replace all 'yield'-s with event handler calls.

    DEFAULT_TAGS = {
        u'!':   u'!',
        u'!!':  u'tag:yaml.org,2002:',
    }

    def __init__(self):
        self.current_event = None
        self.yaml_version = None
        self.tag_handles = {}
        self.event_generator = self.parse_stream()

    def check_event(self, *choices):
        # Check the type of the next event.
        if self.current_event is None:
            try:
                self.current_event = self.event_generator.next()
            except StopIteration:
                pass
        if self.current_event is not None:
            if not choices:
                return True
            for choice in choices:
                if isinstance(self.current_event, choice):
                    return True
        return False

    def peek_event(self):
        # Get the next event.
        if self.current_event is None:
            try:
                self.current_event = self.event_generator.next()
            except StopIteration:
                pass
        return self.current_event

    def get_event(self):
        # Get the next event.
        if self.current_event is None:
            try:
                self.current_event = self.event_generator.next()
            except StopIteration:
                pass
        value = self.current_event
        self.current_event = None
        return value

    def __iter__(self):
        # Iterator protocol.
        return self.event_generator

    def parse_stream(self):
        # STREAM-START implicit_document? explicit_document* STREAM-END

        # Parse start of stream.
        token = self.get_token()
        yield StreamStartEvent(token.start_mark, token.end_mark,
                encoding=token.encoding)

        # Parse implicit document.
        if not self.check_token(DirectiveToken, DocumentStartToken,
                StreamEndToken):
            self.tag_handles = self.DEFAULT_TAGS
            token = self.peek_token()
            start_mark = end_mark = token.start_mark
            yield DocumentStartEvent(start_mark, end_mark,
                    explicit=False)
            for event in self.parse_block_node():
                yield event
            token = self.peek_token()
            start_mark = end_mark = token.start_mark
            explicit = False
            while self.check_token(DocumentEndToken):
                token = self.get_token()
                end_mark = token.end_mark
                explicit = True
            yield DocumentEndEvent(start_mark, end_mark,
                    explicit=explicit)

        # Parse explicit documents.
        while not self.check_token(StreamEndToken):
            token = self.peek_token()
            start_mark = token.start_mark
            version, tags = self.process_directives()
            if not self.check_token(DocumentStartToken):
                raise ParserError(None, None,
                        "expected '<document start>', but found %r"
                        % self.peek_token().id,
                        self.peek_token().start_mark)
            token = self.get_token()
            end_mark = token.end_mark
            yield DocumentStartEvent(start_mark, end_mark,
                    explicit=True, version=version, tags=tags)
            if self.check_token(DirectiveToken,
                    DocumentStartToken, DocumentEndToken, StreamEndToken):
                yield self.process_empty_scalar(token.end_mark)
            else:
                for event in self.parse_block_node():
                    yield event
            token = self.peek_token()
            start_mark = end_mark = token.start_mark
            explicit = False
            while self.check_token(DocumentEndToken):
                token = self.get_token()
                end_mark = token.end_mark
                explicit=True
            yield DocumentEndEvent(start_mark, end_mark,
                    explicit=explicit)

        # Parse end of stream.
        token = self.get_token()
        yield StreamEndEvent(token.start_mark, token.end_mark)

    def process_directives(self):
        # DIRECTIVE*
        self.yaml_version = None
        self.tag_handles = {}
        while self.check_token(DirectiveToken):
            token = self.get_token()
            if token.name == u'YAML':
                if self.yaml_version is not None:
                    raise ParserError(None, None,
                            "found duplicate YAML directive", token.start_mark)
                major, minor = token.value
                if major != 1:
                    raise ParserError(None, None,
                            "found incompatible YAML document (version 1.* is required)",
                            token.start_mark)
                self.yaml_version = token.value
            elif token.name == u'TAG':
                handle, prefix = token.value
                if handle in self.tag_handles:
                    raise ParserError(None, None,
                            "duplicate tag handle %r" % handle.encode('utf-8'),
                            token.start_mark)
                self.tag_handles[handle] = prefix
        if self.tag_handles:
            value = self.yaml_version, self.tag_handles.copy()
        else:
            value = self.yaml_version, None
        for key in self.DEFAULT_TAGS:
            if key not in self.tag_handles:
                self.tag_handles[key] = self.DEFAULT_TAGS[key]
        return value

    def parse_block_node(self):
        return self.parse_node(block=True)

    def parse_flow_node(self):
        return self.parse_node()

    def parse_block_node_or_indentless_sequence(self):
        return self.parse_node(block=True, indentless_sequence=True)

    def parse_node(self, block=False, indentless_sequence=False):
        # block_node    ::= ALIAS | properties? block_content
        # flow_node     ::= ALIAS | properties? flow_content
        # properties    ::= TAG ANCHOR? | ANCHOR TAG?
        # block_content     ::= block_collection | flow_collection | SCALAR
        # flow_content      ::= flow_collection | SCALAR
        # block_collection  ::= block_sequence | block_mapping
        # block_node_or_indentless_sequence ::= ALIAS | properties?
        #                                       (block_content | indentless_block_sequence)
        if self.check_token(AliasToken):
            token = self.get_token()
            yield AliasEvent(token.value, token.start_mark, token.end_mark)
        else:
            anchor = None
            tag = None
            start_mark = end_mark = tag_mark = None
            if self.check_token(AnchorToken):
                token = self.get_token()
                start_mark = token.start_mark
                end_mark = token.end_mark
                anchor = token.value
                if self.check_token(TagToken):
                    token = self.get_token()
                    tag_mark = token.start_mark
                    end_mark = token.end_mark
                    tag = token.value
            elif self.check_token(TagToken):
                token = self.get_token()
                start_mark = tag_mark = token.start_mark
                end_mark = token.end_mark
                tag = token.value
                if self.check_token(AnchorToken):
                    token = self.get_token()
                    end_mark = token.end_mark
                    anchor = token.value
            if tag is not None and tag != u'!':
                handle, suffix = tag
                if handle is not None:
                    if handle not in self.tag_handles:
                        raise ParserError("while parsing a node", start_mark,
                                "found undefined tag handle %r" % handle.encode('utf-8'),
                                tag_mark)
                    tag = self.tag_handles[handle]+suffix
                else:
                    tag = suffix
            #if tag == u'!':
            #    raise ParserError("while parsing a node", start_mark,
            #            "found non-specific tag '!'", tag_mark,
            #            "Please check 'http://pyyaml.org/wiki/YAMLNonSpecificTag' and share your opinion.")
            if start_mark is None:
                start_mark = end_mark = self.peek_token().start_mark
            event = None
            collection_events = None
            implicit = (tag is None or tag == u'!')
            if indentless_sequence and self.check_token(BlockEntryToken):
                end_mark = self.peek_token().end_mark
                event = SequenceStartEvent(anchor, tag, implicit,
                        start_mark, end_mark)
                collection_events = self.parse_indentless_sequence()
            else:
                if self.check_token(ScalarToken):
                    token = self.get_token()
                    end_mark = token.end_mark
                    if (token.plain and tag is None) or tag == u'!':
                        implicit = (True, False)
                    elif tag is None:
                        implicit = (False, True)
                    else:
                        implicit = (False, False)
                    event = ScalarEvent(anchor, tag, implicit, token.value,
                            start_mark, end_mark, style=token.style)
                elif self.check_token(FlowSequenceStartToken):
                    end_mark = self.peek_token().end_mark
                    event = SequenceStartEvent(anchor, tag, implicit,
                            start_mark, end_mark, flow_style=True)
                    collection_events = self.parse_flow_sequence()
                elif self.check_token(FlowMappingStartToken):
                    end_mark = self.peek_token().end_mark
                    event = MappingStartEvent(anchor, tag, implicit,
                            start_mark, end_mark, flow_style=True)
                    collection_events = self.parse_flow_mapping()
                elif block and self.check_token(BlockSequenceStartToken):
                    end_mark = self.peek_token().start_mark
                    event = SequenceStartEvent(anchor, tag, implicit,
                            start_mark, end_mark, flow_style=False)
                    collection_events = self.parse_block_sequence()
                elif block and self.check_token(BlockMappingStartToken):
                    end_mark = self.peek_token().start_mark
                    event = MappingStartEvent(anchor, tag, implicit,
                            start_mark, end_mark, flow_style=False)
                    collection_events = self.parse_block_mapping()
                elif anchor is not None or tag is not None:
                    # Empty scalars are allowed even if a tag or an anchor is
                    # specified.
                    event = ScalarEvent(anchor, tag, (implicit, False), u'',
                            start_mark, end_mark)
                else:
                    if block:
                        node = 'block'
                    else:
                        node = 'flow'
                    token = self.peek_token()
                    raise ParserError("while scanning a %s node" % node, start_mark,
                            "expected the node content, but found %r" % token.id,
                            token.start_mark)
            yield event
            if collection_events is not None:
                for event in collection_events:
                    yield event

    def parse_block_sequence(self):
        # BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
        token = self.get_token()
        start_mark = token.start_mark
        while self.check_token(BlockEntryToken):
            token = self.get_token()
            if not self.check_token(BlockEntryToken, BlockEndToken):
                for event in self.parse_block_node():
                    yield event
            else:
                yield self.process_empty_scalar(token.end_mark)
        if not self.check_token(BlockEndToken):
            token = self.peek_token()
            raise ParserError("while scanning a block collection", start_mark,
                    "expected <block end>, but found %r" % token.id, token.start_mark)
        token = self.get_token()
        yield SequenceEndEvent(token.start_mark, token.end_mark)

    def parse_indentless_sequence(self):
        # (BLOCK-ENTRY block_node?)+
        while self.check_token(BlockEntryToken):
            token = self.get_token()
            if not self.check_token(BlockEntryToken,
                    KeyToken, ValueToken, BlockEndToken):
                for event in self.parse_block_node():
                    yield event
            else:
                yield self.process_empty_scalar(token.end_mark)
        token = self.peek_token()
        yield SequenceEndEvent(token.start_mark, token.start_mark)

    def parse_block_mapping(self):
        # BLOCK-MAPPING_START
        #   ((KEY block_node_or_indentless_sequence?)?
        #   (VALUE block_node_or_indentless_sequence?)?)*
        # BLOCK-END
        token = self.get_token()
        start_mark = token.start_mark
        while self.check_token(KeyToken, ValueToken):
            if self.check_token(KeyToken):
                token = self.get_token()
                if not self.check_token(KeyToken, ValueToken, BlockEndToken):
                    for event in self.parse_block_node_or_indentless_sequence():
                        yield event
                else:
                    yield self.process_empty_scalar(token.end_mark)
            if self.check_token(ValueToken):
                token = self.get_token()
                if not self.check_token(KeyToken, ValueToken, BlockEndToken):
                    for event in self.parse_block_node_or_indentless_sequence():
                        yield event
                else:
                    yield self.process_empty_scalar(token.end_mark)
            else:
                token = self.peek_token()
                yield self.process_empty_scalar(token.start_mark)
        if not self.check_token(BlockEndToken):
            token = self.peek_token()
            raise ParserError("while scanning a block mapping", start_mark,
                    "expected <block end>, but found %r" % token.id, token.start_mark)
        token = self.get_token()
        yield MappingEndEvent(token.start_mark, token.end_mark)

    def parse_flow_sequence(self):
        # flow_sequence     ::= FLOW-SEQUENCE-START
        #                       (flow_sequence_entry FLOW-ENTRY)*
        #                       flow_sequence_entry?
        #                       FLOW-SEQUENCE-END
        # flow_sequence_entry   ::= flow_node | KEY flow_node? (VALUE flow_node?)?
        #
        # Note that while production rules for both flow_sequence_entry and
        # flow_mapping_entry are equal, their interpretations are different.
        # For `flow_sequence_entry`, the part `KEY flow_node? (VALUE flow_node?)?`
        # generate an inline mapping (set syntax).
        token = self.get_token()
        start_mark = token.start_mark
        while not self.check_token(FlowSequenceEndToken):
            if self.check_token(KeyToken):
                token = self.get_token()
                yield MappingStartEvent(None, None, True,
                        token.start_mark, token.end_mark,
                        flow_style=True)
                if not self.check_token(ValueToken,
                        FlowEntryToken, FlowSequenceEndToken):
                    for event in self.parse_flow_node():
                        yield event
                else:
                    yield self.process_empty_scalar(token.end_mark)
                if self.check_token(ValueToken):
                    token = self.get_token()
                    if not self.check_token(FlowEntryToken, FlowSequenceEndToken):
                        for event in self.parse_flow_node():
                            yield event
                    else:
                        yield self.process_empty_scalar(token.end_mark)
                else:
                    token = self.peek_token()
                    yield self.process_empty_scalar(token.start_mark)
                token = self.peek_token()
                yield MappingEndEvent(token.start_mark, token.start_mark)
            else:
                for event in self.parse_flow_node():
                    yield event
            if not self.check_token(FlowEntryToken, FlowSequenceEndToken):
                token = self.peek_token()
                raise ParserError("while scanning a flow sequence", start_mark,
                        "expected ',' or ']', but got %r" % token.id, token.start_mark)
            if self.check_token(FlowEntryToken):
                self.get_token()
        token = self.get_token()
        yield SequenceEndEvent(token.start_mark, token.end_mark)

    def parse_flow_mapping(self):
        # flow_mapping      ::= FLOW-MAPPING-START
        #                       (flow_mapping_entry FLOW-ENTRY)*
        #                       flow_mapping_entry?
        #                       FLOW-MAPPING-END
        # flow_mapping_entry    ::= flow_node | KEY flow_node? (VALUE flow_node?)?
        token = self.get_token()
        start_mark = token.start_mark
        while not self.check_token(FlowMappingEndToken):
            if self.check_token(KeyToken):
                token = self.get_token()
                if not self.check_token(ValueToken,
                        FlowEntryToken, FlowMappingEndToken):
                    for event in self.parse_flow_node():
                        yield event
                else:
                    yield self.process_empty_scalar(token.end_mark)
                if self.check_token(ValueToken):
                    token = self.get_token()
                    if not self.check_token(FlowEntryToken, FlowMappingEndToken):
                        for event in self.parse_flow_node():
                            yield event
                    else:
                        yield self.process_empty_scalar(token.end_mark)
                else:
                    token = self.peek_token()
                    yield self.process_empty_scalar(token.start_mark)
            else:
                for event in self.parse_flow_node():
                    yield event
                yield self.process_empty_scalar(self.peek_token().start_mark)
            if not self.check_token(FlowEntryToken, FlowMappingEndToken):
                token = self.peek_token()
                raise ParserError("while scanning a flow mapping", start_mark,
                        "expected ',' or '}', but got %r" % token.id, token.start_mark)
            if self.check_token(FlowEntryToken):
                self.get_token()
        if not self.check_token(FlowMappingEndToken):
            token = self.peek_token()
            raise ParserError("while scanning a flow mapping", start_mark,
                    "expected '}', but found %r" % token.id, token.start_mark)
        token = self.get_token()
        yield MappingEndEvent(token.start_mark, token.end_mark)

    def process_empty_scalar(self, mark):
        return ScalarEvent(None, None, (True, False), u'', mark, mark)


text:
<!DOCTYPE Linker_Placement_File>
<Root name="Flash Section Placement">
  <MemorySegment name="FLASH" start="$(FLASH_PH_START)" size="$(FLASH_PH_SIZE)">
    <ProgramSection alignment="0x100" load="Yes" name=".vectors" start="$(FLASH_START)" />
    <ProgramSection alignment="4" load="Yes" name=".init" />
    <ProgramSection alignment="4" load="Yes" name=".init_rodata" />
    <ProgramSection alignment="4" load="Yes" name=".text" />
    <ProgramSection alignment="4" keep="Yes" load="Yes" name=".crypto_data" inputsections="*(SORT(.crypto_data*))" address_symbol="__start_crypto_data" end_symbol="__stop_crypto_data" />
    <ProgramSection alignment="4" keep="Yes" load="Yes" name=".nrf_queue" inputsections="*(.nrf_queue*)" address_symbol="__start_nrf_queue" end_symbol="__stop_nrf_queue" />
    <ProgramSection alignment="4" keep="Yes" load="Yes" name=".log_const_data" inputsections="*(SORT(.log_const_data*))" address_symbol="__start_log_const_data" end_symbol="__stop_log_const_data" />
    <ProgramSection alignment="4" keep="Yes" load="Yes" name=".log_backends" inputsections="*(SORT(.log_backends*))" address_symbol="__start_log_backends" end_symbol="__stop_log_backends" />
    <ProgramSection alignment="4" keep="Yes" load="Yes" name=".nrf_balloc" inputsections="*(.nrf_balloc*)" address_symbol="__start_nrf_balloc" end_symbol="__stop_nrf_balloc" />
    <ProgramSection alignment="4" keep="Yes" load="No" name=".nrf_sections" address_symbol="__start_nrf_sections" />
    <ProgramSection alignment="4" keep="Yes" load="Yes" name=".log_dynamic_data"  inputsections="*(SORT(.log_dynamic_data*))" runin=".log_dynamic_data_run"/>
    <ProgramSection alignment="4" keep="Yes" load="Yes" name=".log_filter_data"  inputsections="*(SORT(.log_filter_data*))" runin=".log_filter_data_run"/>
    <ProgramSection alignment="4" load="Yes" name=".dtors" />
    <ProgramSection alignment="4" load="Yes" name=".ctors" />
    <ProgramSection alignment="4" load="Yes" name=".rodata" />
    <ProgramSection alignment="4" load="Yes" name=".ARM.exidx" address_symbol="__exidx_start" end_symbol="__exidx_end" />
    <ProgramSection alignment="4" load="Yes" runin=".fast_run" name=".fast" />
    <ProgramSection alignment="4" load="Yes" runin=".data_run" name=".data" />
    <ProgramSection alignment="4" load="Yes" runin=".tdata_run" name=".tdata" />
  </MemorySegment>
  <MemorySegment name="RAM" start="$(RAM_PH_START)" size="$(RAM_PH_SIZE)">
    <ProgramSection alignment="0x100" load="No" name=".vectors_ram" start="$(RAM_START)" address_symbol="__app_ram_start__"/>
    <ProgramSection alignment="4" keep="Yes" load="No" name=".nrf_sections_run" address_symbol="__start_nrf_sections_run" />
    <ProgramSection alignment="4" keep="Yes" load="No" name=".log_dynamic_data_run" address_symbol="__start_log_dynamic_data" end_symbol="__stop_log_dynamic_data" />
    <ProgramSection alignment="4" keep="Yes" load="No" name=".log_filter_data_run" address_symbol="__start_log_filter_data" end_symbol="__stop_log_filter_data" />
    <ProgramSection alignment="4" keep="Yes" load="No" name=".nrf_sections_run_end" address_symbol="__end_nrf_sections_run" />
    <ProgramSection alignment="4" load="No" name=".fast_run" />
    <ProgramSection alignment="4" load="No" name=".data_run" />
    <ProgramSection alignment="4" load="No" name=".tdata_run" />
    <ProgramSection alignment="4" load="No" name=".bss" />
    <ProgramSection alignment="4" load="No" name=".tbss" />
    <ProgramSection alignment="4" load="No" name=".non_init" />
    <ProgramSection alignment="4" size="__HEAPSIZE__" load="No" name=".heap" />
    <ProgramSection alignment="8" size="__STACKSIZE__" load="No" place_from_segment_end="Yes" name=".stack"  address_symbol="__StackLimit" end_symbol="__StackTop"/>
    <ProgramSection alignment="8" size="__STACKSIZE_PROCESS__" load="No" name=".stack_process" />
  </MemorySegment>
</Root>


text:
"""Little python halStats wrapper.
"""
import argparse
import os
import sys
import copy
import subprocess
from multiprocessing import Pool

def runShellCommand(command, ascii=True):
    try:
        process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,
                                   stderr=sys.stderr, bufsize=-1)
        output, nothing = process.communicate()
        sts = process.wait()
        if sts != 0:
            raise RuntimeError("Command: %s exited with non-zero status %i" %
                               (command, sts))
        return output.decode() if ascii else output
    except KeyboardInterrupt:
        raise RuntimeError("Aborting %s" % command)

def runParallelShellCommands(cmdList, numProc):
    if numProc == 1 or len(cmdList) == 1:
        for cmd in cmdList:
            runShellCommand(cmd)
    elif len(cmdList) > 0:
        mpPool = Pool(processes=min(numProc, len(cmdList)))
        result = mpPool.map_async(runShellCommand, cmdList)
        # specifying a timeout allows keyboard interrupts to work?!
        # http://stackoverflow.com/questions/1408356/keyboard-interrupts-with-pythons-multiprocessing-pool
        try:
            result.get(20000000)
        except KeyboardInterrupt:
            mpPool.terminate()
            raise RuntimeError("Keyboard interrupt")
        if not result.successful():
            raise "One or more of commands %s failed" % str(cmdList)

def getHalGenomes(halPath):
    return runShellCommand("halStats %s --genomes" % halPath).split()

def getHalNumSegments(halPath, genomeName):
    res = runShellCommand("halStats %s --numSegments %s" %
                          (halPath, genomeName)).split()
    return tuple([int(x) for x in res])

def getHalStats(halPath):
    res = runShellCommand("halStats %s" % (halPath)).split("\n")
    outList = []
    foundHeader = False
    for line in res:
        tokens = line.strip().split(",")
        if len(tokens) == 6 and tokens[0] == "GenomeName":
            foundHeader = True
        elif len(tokens) == 6 and foundHeader:
            outList.append(tuple(tokens))
    return outList

def getHalTotalStats(halPath):
    allStats = getHalStats(halPath)
    totals = (0, 0, 0, 0, 0)
    for genome in allStats:
        assert len(genome) == 6
        totals = tuple(sum(t) for t in zip(totals, genome)[1:])
    return totals

def getHalSequenceStats(halPath, genomeName):
    res = runShellCommand("halStats %s --sequenceStats %s" %
                          (halPath, genomeName)).split("\n")
    outList = []
    for line in res[1:]:
        tokens = line.strip().split(",")
        if len(tokens) == 4:
            outList.append((tokens[0], int(tokens[1]), int(tokens[2]),
                            int(tokens[3])))
    return outList

def getHalRootName(halPath):
    return runShellCommand("halStats %s --root" % halPath).strip()

def getHalParentName(halPath, genomeName):
    res = runShellCommand("halStats %s --parent %s" % (halPath, genomeName))
    return res.strip()

def getHalChildrenNames(halPath, genomeName):
    return runShellCommand("halStats %s --children %s" %
                           (halPath, genomeName)).split()

def getHalGenomeLength(halPath, genomeName):
    for genomeStats in getHalStats(halPath):
        if genomeStats[0] == genomeName:
            return int(genomeStats[2])
    return None

def getHalTree(halPath):
    return runShellCommand("halStats %s --tree" % halPath).strip()

def getHalBaseComposition(halPath, genomeName, step):
    strList = runShellCommand("halStats %s --baseComp %s,%d" % (
        halPath, genomeName, step)).split()
    return [float(x) for x in strList]

def getHalGenomeMetaData(halPath, genomeName):
    res = runShellCommand("halStats %s --genomeMetaData %s" % (halPath,
                                                               genomeName))
    if res.strip() == '':
        return dict()
    return dict([line.split("\t") for line in res.strip().split("\n")])


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Zao.CrsPlat.RolebasedAccessManagement
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}


text: An RGB based circle tracking with id encoding


text: Obliterated, use https://github.com/Rykka/localbundle.vim instead.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../../../doc/otp_doc.css" type="text/css">
<title>Erlang -- CosTransactions_Terminator</title>

User's Guide
Reference Manual
Release Notes
PDF
Top
cosTransactions
Reference Manual
Version 1.3.1

Expand All
Contract All
Table of Contents

cosTransactions

                  Top of manual page

start/0

stop/0

start_factory/0

start_factory/1

stop_factory/1

CosTransactions_Control

                  Top of manual page

get_coordinator/1

get_terminator/1

CosTransactions_Coordinator

                  Top of manual page

create_subtransaction/1

get_transaction_name/1

get_parent_status/1

get_status/1

get_top_level_status/1

hash_top_level_tran/1

hash_transaction/1

is_descendant_transaction/2

is_same_transaction/2

is_top_level_transaction/1

register_resource/2

register_subtran_aware/2

rollback_only/1

CosTransactions_RecoveryCoordinator

                  Top of manual page

replay_completion/3

CosTransactions_Resource

                  Top of manual page

commit/1

commit_one_phase/1

forget/1

prepare/1

rollback/1

CosTransactions_SubtransactionAwareResource

                  Top of manual page

commit_subtransaction/2

rollback_subtransaction/1

CosTransactions_Terminator

                  Top of manual page

commit/2

rollback/1

CosTransactions_TransactionFactory

                  Top of manual page

create/2

CosTransactions_Terminator

MODULE

CosTransactions_Terminator

MODULE SUMMARY

This module implements the OMG CosTransactions::Terminator interface.

DESCRIPTION

To get access to the record definitions for the structures use:

-include_lib("cosTransactions/include/CosTransactions.hrl").

EXPORTS

commit(Terminator, ReportHeuristics) -> Return

Types:

Terminator = #objref

ReportHeuristics = boolean()

Return =  ok | {'EXCEPTION', E}

E = #'CosTransactions_HeuristicMixed'{} | #'CosTransactions_HeuristicHazrd'{} | #'CosTransactions_TransactionRolledBack'{}

This operation initiates the two-phase commit protocol. If the transaction has not been marked
          'rollback only' and all the participants agree to commit, the operation terminates normally. Otherwise,
          the TransactionRolledBack is raised. If the parameter ReportHeuristics is true and inconsistent
          outcomes by raising an Heuristic Exception.

rollback(Terminator) -> Return

Types:

Terminator = #objref

Return = ok

This operation roles back the transaction.

Copyright © 1999-2016 Ericsson AB. All Rights Reserved.


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="20dp"
    android:height="20dp"
    android:viewportWidth="20"
    android:viewportHeight="20"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M1.771,18.583V10.688H18.229V18.583ZM1.771,9.312V1.417H18.229V9.312Z"/>
</vector>


text:
<!DOCTYPE html>

<title>Brandon Himpfen Media</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:700,600,400">
<link rel="stylesheet" href="css/reset.css" media="screen">
<link rel="stylesheet" href="css/font-awesome.min.css" media="screen">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        Toggle navigation

      </button>
      Brandon Himpfen Media

      Copyright © Brandon Himpfen Media, a Brandon Himpfen Holdings company. - All Rights Reserved.


text:
TARGET_TYPE := dynamicLibrary

# The output binary you want to create.
TARGET_NAME := simpleAI.o

# The paths where source files are located.
SOURCE_DIRS := ../src/

# The compiler you want to use.
CC := g++

# The linker you want to use.
LD := g++

# The archival utility you want to use (for creating static libraries)
AR := ar

# Any preprocessor definitions you want to give to the compiler.
# PREFIX EACH DEFINE WITH "-D".
DEFINES := $(BUILD_SCRIPT_DEFINES)

# The include paths that the compiler (and dependency generation) should search.
# PREFIX EACH INCLUDE DIRECTORY WITH "-I".
INCLUDES := $(SIMPLEAI_INCLUDES)

# Flags passed to the compiler.
# -D defines and -I include options should go in DEFINES and INCLUDES, not here.
CFLAGS := -Wall -O2

# Flags passed to the linker.
# **NOTE CAREFULLY** sometimes the ordering of linking multiple libraries is important.
LFLAGS := $(SIMPLEAI_LFLAGS)

####################################################################
# Should not need to modify anything below this point in the file.
####################################################################

# The shell to use when executing commands
SHELL = /bin/bash

# The directory to put .d dependency files.
DEPDIR := deps

# The directory to put .o object files.
OBJDIR := objs

# All .c, .C, .cc, .cpp, and .cxx files from the SOURCE_DIRS. Each filename includes the relative path.
SOURCES := $(foreach DIR, $(SOURCE_DIRS), $(wildcard $(DIR)/*.c) $(wildcard $(DIR)/*.C) $(wildcard $(DIR)/*.cc) $(wildcard $(DIR)/*.cpp) $(wildcard $(DIR)/*.cxx))

# All the dependency files, from the corresponding source files, including the a new path that refers to the dependency directory.
DEPENDENCIES := $(foreach DEP, $(SOURCES), $(DEPDIR)/$(notdir $(basename $(DEP))).d)

# All the object files, from the corresponding source files, including a new path that refers to the object directory.
OBJECTS := $(foreach OBJ, $(SOURCES), $(OBJDIR)/$(notdir $(basename $(OBJ))).o)

# Cause an error if the TARGET_TYPE specified by the user is invalid.
ifneq ($(TARGET_TYPE),executable)
ifneq ($(TARGET_TYPE),staticLibrary)
ifneq ($(TARGET_TYPE),sharedLibrary)
ifneq ($(TARGET_TYPE),dynamicLibrary)
$(error Invalid TARGET_TYPE. Choices are: "executable", "staticLibrary", or "dynamicLibrary".)
endif
endif
endif
endif

# Tell the makefile to look for source files where the user specified them.
vpath %.c   $(SOURCE_DIRS)
vpath %.C   $(SOURCE_DIRS)
vpath %.cc  $(SOURCE_DIRS)
vpath %.cpp $(SOURCE_DIRS)
vpath %.cxx $(SOURCE_DIRS)

# The make rules

# "make" defaults to "make all" since "all" is the first specified target.
# "make all" builds the user-specified target.
all: $(TARGET_NAME)

# Tell the makefile that "all" and "clean" are not actually files.
.PHONY: all clean

#
# There are four versions of compiling/linking below, depending on TARGET_TYPE.
# To keep maximum flexibility, we intentionally did not simplify redundant parts
# of the build process across the four versions.
#
# Note that the $(CC) command produces the .o object file AND the .d dependency
# in one execution, which is a little faster than doing it in two steps.
#

##############################################
# In this case, the target is an executable
ifeq ($(TARGET_TYPE),executable)

$(TARGET_NAME): $(DEPDIR) $(OBJDIR) $(OBJECTS)
	@echo -n Linking executable...
	@$(LD) -o $@ $(OBJECTS) $(LFLAGS)
	@echo done.

$(OBJDIR)/%.o: %.c
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.C
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.cc
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.cpp
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.cxx
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

endif
##############################################

##############################################
# In this case, the target is a static library.
ifeq ($(TARGET_TYPE),staticLibrary)

$(TARGET_NAME): $(DEPDIR) $(OBJDIR) $(OBJECTS)
	@echo -n Creating static library...
	@$(AR) rcs $@ $(OBJECTS)
	@echo done.

$(OBJDIR)/%.o: %.c
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.C
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.cc
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.cpp
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.cxx
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

endif
##############################################

##############################################
# In this case, the target is a shared library.
ifeq ($(TARGET_TYPE),sharedLibrary)

$(TARGET_NAME): $(DEPDIR) $(OBJDIR) $(OBJECTS)
	@echo -n Creating shared library...
	@$(LD) -fPIC -shared -o $@ $(OBJECTS) $(LFLAGS)
	@echo done.

$(OBJDIR)/%.o: %.c
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -fPIC -shared -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.C
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -fPIC -shared -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.cc
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -fPIC -shared -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.cpp
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -fPIC -shared -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.cxx
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -fPIC -shared -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

endif
##############################################

##############################################
# In this case, the target is a dynamic library.
ifeq ($(TARGET_TYPE),dynamicLibrary)

$(TARGET_NAME): $(DEPDIR) $(OBJDIR) $(OBJECTS)
	@echo -n Creating dynamic library...
	@$(LD) -fPIC -shared -o $@ $(OBJECTS) $(LFLAGS)
	@echo done.

$(OBJDIR)/%.o: %.c
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -fPIC -shared -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.C
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -fPIC -shared -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.cc
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -fPIC -shared -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.cpp
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -fPIC -shared -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

$(OBJDIR)/%.o: %.cxx
	@echo Compiling $<
	@$(CC) -MD -MF $(DEPDIR)/$(notdir $(@:.o=.d)) -fPIC -shared -c -o $@ $< $(CFLAGS) $(DEFINES) $(INCLUDES)

endif
##############################################

# The dependency directory should be created if it doesnt exist
$(DEPDIR):
	@mkdir -p $(DEPDIR)

# The object directory should be created if it doesnt exist
$(OBJDIR):
	@mkdir -p $(OBJDIR)

# Removes EVERYTHING in the object and dependency
# directories, even if the makefile did not create them.
clean:
	@echo -n Cleaning up...
	@-rm -rf $(OBJDIR) $(DEPDIR) $(TARGET_NAME)
	@echo done.

# Don't include all the dependency files if we are just doing a "make clean".
ifneq ($(MAKECMDGOALS),clean)
-include $(DEPENDENCIES)
endif