text:
**Tela de Listagem**

• Tela para listar as atividades, podendo filtrar pelo "Status" e pela "Situação";
• A cada atividade listada, deve-se checar o "Status" dela e se for "Concluído", alterar a cor de fundo da linha;
• Na linha de cada atividade listada, exibir um botão de "Editar" para acessar a tela de edição da atividade;
• No final da tela, exibir um botão para incluir uma nova atividade.

**Tela de Cadastro/Alteração**

• Tela para fazer a manutenção das atividades, podendo alterar os campos disponíveis,respeitando as regras citadas a seguir.

**Tecnologias utilizadas**

• PHP
• Mysql
• HTML
• CSS
• Bootstrap
• Javascript/Jquery/Ajax
• GIT

##instruções

• O dump da base está no diretório /bd-mysql/atividade.sql
• Configurar os dados de conexão no /config/BDConfig.php
• Configurar o path local em /config/properties.php (linha 7)

######Contatos
##deigmar@gmail.com

redpajama_set_name: RedPajamaGithub


text:
import type { ScrumbleSprintType } from '../../types/Scrumble';

export type ActionType =
  | {|
      type: 'PUT_SPRINTS',
      payload: {|
        sprints: ScrumbleSprintType[],
        doAdapt: boolean,
      |},
    |}
  | {|
      type: 'SET_CURRENT_SPRINT',
      payload: {|
        sprintId: number,
      |},
    |}
  | {|
      type: 'CHANGE_CURRENT_SPRINT',
      payload: {|
        sprintId: number,
      |},
    |}
  | {|
      type: 'CLEAR_SPRINTS',
    |}
  | {|
      type: 'FETCH_CURRENT_SPRINT',
    |}
  | {|
      type: 'FETCH_SPRINTS',
    |};

export function putSprints(sprints: ScrumbleSprintType[], doAdapt: boolean = false): ActionType {
  return {
    type: 'PUT_SPRINTS',
    payload: { sprints, doAdapt },
  };
}

export function setCurrentSprint(sprintId: number): ActionType {
  return {
    type: 'SET_CURRENT_SPRINT',
    payload: { sprintId },
  };
}

export function changeCurrentSprint(sprintId: number): ActionType {
  return {
    type: 'CHANGE_CURRENT_SPRINT',
    payload: { sprintId },
  };
}

export function clearSprints(): ActionType {
  return { type: 'CLEAR_SPRINTS' };
}

export function fetchCurrentSprint(): ActionType {
  return { type: 'FETCH_CURRENT_SPRINT' };
}

export function fetchSprints(): ActionType {
  return { type: 'FETCH_SPRINTS' };
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Hysterangium simlensis K.S. Thind & I.P.S. Thind

### Remarks
null


text:
package vn.techplus.filmon.Adapter;

import java.util.List;

import vn.techplus.filmon.FilmOnApplication;
import vn.techplus.filmon.R;
import vn.techplus.filmon.model.Category;
import vn.techplus.filmon.model.ChannelManagement;
import vn.techplus.filmon.model.ManualChannel;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class CategoryAdapter extends ArrayAdapter<Category> {
	public List<Category> mCategories;
	private int mResource;
	private LayoutInflater mInflater;
	private ImageLoader mImageLoader;
	private DisplayImageOptions mOptions;

	public CategoryAdapter(Context context, int resource, List<Category> categories) {
		super(context, resource, categories);
		// TODO Auto-generated constructor stub
		mCategories = categories;
		mInflater = LayoutInflater.from(context);
		mResource = resource;

		mImageLoader = ImageLoader.getInstance();
		mOptions = FilmOnApplication.getDisplayOption(0);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		View view = convertView;
		ViewHolder holder;
		if (view == null) {
			view = mInflater.inflate(mResource, null);
			holder = new ViewHolder();
			holder.imgView = (ImageView) view.findViewById(R.id.imgCategory);
			holder.txtView = (TextView) view.findViewById(R.id.txtCategoryItem);

			view.setTag(holder);
		} else {
			holder = (ViewHolder) view.getTag();
		}

		Category category = mCategories.get(position);
		holder.txtView.setText(category.getName());
		if (category.getId().equals(ChannelManagement.MY_CATEGORY_ID))
			holder.imgView.setImageResource(R.drawable.my_channel);
		else if (category.getId().equals(ManualChannel.SPECIAL_CATEGORY_ID))
			holder.imgView.setImageResource(R.drawable.special_offer);
		else
			mImageLoader.displayImage(category.getLogo(), holder.imgView, mOptions);

		return view;
	}

	class ViewHolder {
		public ImageView imgView;
		public TextView txtView;
	}
}


text:
'use strict';
module.exports = {
  up: function(queryInterface, Sequelize) {
    return queryInterface.createTable('SaladComponents', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING
      },
      weight: {
        type: Sequelize.FLOAT
      },
      callorie: {
        type: Sequelize.FLOAT
      },
      price: {
        type: Sequelize.FLOAT
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: function(queryInterface, Sequelize) {
    return queryInterface.dropTable('SaladComponents');
  }
};


text:
package flag

import (
	"bytes"
	"fmt"
	"io"
	"strings"

	"github.com/spf13/pflag"
)

// NamedFlagSets stores named flag sets in the order of calling FlagSet.
type NamedFlagSets struct {
	// Order is an ordered list of flag set names.
	Order []string
	// FlagSets stores the flag sets by name.
	FlagSets map[string]*pflag.FlagSet
	// NormalizeNameFunc is the normalize function which used to initialize FlagSets created by NamedFlagSets.
	NormalizeNameFunc func(f *pflag.FlagSet, name string) pflag.NormalizedName
}

// FlagSet returns the flag set with the given name and adds it to the
// ordered name list if it is not in there yet.
func (nfs *NamedFlagSets) FlagSet(name string) *pflag.FlagSet {
	if nfs.FlagSets == nil {
		nfs.FlagSets = map[string]*pflag.FlagSet{}
	}
	if _, ok := nfs.FlagSets[name]; !ok {
		flagSet := pflag.NewFlagSet(name, pflag.ExitOnError)
		flagSet.SetNormalizeFunc(pflag.CommandLine.GetNormalizeFunc())
		if nfs.NormalizeNameFunc != nil {
			flagSet.SetNormalizeFunc(nfs.NormalizeNameFunc)
		}
		nfs.FlagSets[name] = flagSet
		nfs.Order = append(nfs.Order, name)
	}
	return nfs.FlagSets[name]
}

// PrintSections prints the given names flag sets in sections, with the maximal given column number.
// If cols is zero, lines are not wrapped.
func PrintSections(w io.Writer, fss NamedFlagSets, cols int) {
	for _, name := range fss.Order {
		fs := fss.FlagSets[name]
		if !fs.HasFlags() {
			continue
		}

		wideFS := pflag.NewFlagSet("", pflag.ExitOnError)
		wideFS.AddFlagSet(fs)

		var zzz string
		if cols > 24 {
			zzz = strings.Repeat("z", cols-24)
			wideFS.Int(zzz, 0, strings.Repeat("z", cols-24))
		}

		var buf bytes.Buffer
		fmt.Fprintf(&buf, "\n%s flags:\n\n%s", strings.ToUpper(name[:1])+name[1:], wideFS.FlagUsagesWrapped(cols))

		if cols > 24 {
			i := strings.Index(buf.String(), zzz)
			lines := strings.Split(buf.String()[:i], "\n")
			fmt.Fprint(w, strings.Join(lines[:len(lines)-1], "\n"))
			fmt.Fprintln(w)
		} else {
			fmt.Fprint(w, buf.String())
		}
	}
}


text:
FROM google/dart:2.0

COPY ./ ./

RUN pub get

RUN pub run build_runner build

CMD ANGEL_ENV=production dart bin/main.dart --type=postgres


text:
#ifndef FREERDP_LIB_CORE_GATEWAY_NCACN_HTTP_H
#define FREERDP_LIB_CORE_GATEWAY_NCACN_HTTP_H

#include <freerdp/api.h>

#include "rpc.h"
#include "http.h"

FREERDP_LOCAL BOOL rpc_ncacn_http_ntlm_init(rdpContext* context, RpcChannel* channel);
FREERDP_LOCAL void rpc_ncacn_http_ntlm_uninit(RpcChannel* channel);

FREERDP_LOCAL BOOL rpc_ncacn_http_send_in_channel_request(RpcChannel* inChannel);
FREERDP_LOCAL BOOL rpc_ncacn_http_recv_in_channel_response(RpcChannel* inChannel,
                                                           HttpResponse* response);

FREERDP_LOCAL BOOL rpc_ncacn_http_send_out_channel_request(RpcChannel* outChannel,
                                                           BOOL replacement);
FREERDP_LOCAL BOOL rpc_ncacn_http_recv_out_channel_response(RpcChannel* outChannel,
                                                            HttpResponse* response);

#endif /* FREERDP_LIB_CORE_GATEWAY_NCACN_HTTP_H */


text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package test.fixtures.patch;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
import java.util.BitSet;
import java.util.Arrays;
import com.facebook.thrift.*;
import com.facebook.thrift.annotations.*;
import com.facebook.thrift.async.*;
import com.facebook.thrift.meta_data.*;
import com.facebook.thrift.server.*;
import com.facebook.thrift.transport.*;
import com.facebook.thrift.protocol.*;

@SuppressWarnings({ "unused", "serial" })
public class MyStructField10Patch implements TBase, java.io.Serializable, Cloneable {
  private static final TStruct STRUCT_DESC = new TStruct("MyStructField10Patch");
  private static final TField ASSIGN_FIELD_DESC = new TField("assign", TType.I32, (short)1);
  private static final TField CLEAR_FIELD_DESC = new TField("clear", TType.BOOL, (short)2);

  /**
   * Assigns to a (set) value.
   *
   * If set, all other operations are ignored.
   *
   * Note: Optional and union fields must be set before assigned.
   *
   *
   * @see MyEnum
   */
  public final MyEnum assign;
  /**
   * Clears a value. Applies first.
   */
  public final Boolean clear;
  public static final int ASSIGN = 1;
  public static final int CLEAR = 2;

  public MyStructField10Patch(
      MyEnum assign,
      Boolean clear) {
    this.assign = assign;
    this.clear = clear;
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public MyStructField10Patch(MyStructField10Patch other) {
    if (other.isSetAssign()) {
      this.assign = TBaseHelper.deepCopy(other.assign);
    } else {
      this.assign = null;
    }
    if (other.isSetClear()) {
      this.clear = TBaseHelper.deepCopy(other.clear);
    } else {
      this.clear = null;
    }
  }

  public MyStructField10Patch deepCopy() {
    return new MyStructField10Patch(this);
  }

  /**
   * Assigns to a (set) value.
   *
   * If set, all other operations are ignored.
   *
   * Note: Optional and union fields must be set before assigned.
   *
   *
   * @see MyEnum
   */
  public MyEnum getAssign() {
    return this.assign;
  }

  // Returns true if field assign is set (has been assigned a value) and false otherwise
  public boolean isSetAssign() {
    return this.assign != null;
  }

  /**
   * Clears a value. Applies first.
   */
  public Boolean isClear() {
    return this.clear;
  }

  // Returns true if field clear is set (has been assigned a value) and false otherwise
  public boolean isSetClear() {
    return this.clear != null;
  }

  @Override
  public boolean equals(Object _that) {
    if (_that == null)
      return false;
    if (this == _that)
      return true;
    if (!(_that instanceof MyStructField10Patch))
      return false;
    MyStructField10Patch that = (MyStructField10Patch)_that;

    if (!TBaseHelper.equalsNobinary(this.isSetAssign(), that.isSetAssign(), this.assign, that.assign)) { return false; }

    if (!TBaseHelper.equalsNobinary(this.isSetClear(), that.isSetClear(), this.clear, that.clear)) { return false; }

    return true;
  }

  @Override
  public int hashCode() {
    return Arrays.deepHashCode(new Object[] {assign, clear});
  }

  // This is required to satisfy the TBase interface, but can't be implemented on immutable struture.
  public void read(TProtocol iprot) throws TException {
    throw new TException("unimplemented in android immutable structure");
  }

  public static MyStructField10Patch deserialize(TProtocol iprot) throws TException {
    MyEnum tmp_assign = null;
    Boolean tmp_clear = null;
    TField __field;
    iprot.readStructBegin();
    while (true)
    {
      __field = iprot.readFieldBegin();
      if (__field.type == TType.STOP) {
        break;
      }
      switch (__field.id)
      {
        case ASSIGN:
          if (__field.type == TType.I32) {
            tmp_assign = MyEnum.findByValue(iprot.readI32());
          } else {
            TProtocolUtil.skip(iprot, __field.type);
          }
          break;
        case CLEAR:
          if (__field.type == TType.BOOL) {
            tmp_clear = iprot.readBool();
          } else {
            TProtocolUtil.skip(iprot, __field.type);
          }
          break;
        default:
          TProtocolUtil.skip(iprot, __field.type);
          break;
      }
      iprot.readFieldEnd();
    }
    iprot.readStructEnd();

    MyStructField10Patch _that;
    _that = new MyStructField10Patch(
      tmp_assign
      ,tmp_clear
    );
    _that.validate();
    return _that;
  }

  public void write(TProtocol oprot) throws TException {
    validate();

    oprot.writeStructBegin(STRUCT_DESC);
    if (this.assign != null) {
      if (isSetAssign()) {
        oprot.writeFieldBegin(ASSIGN_FIELD_DESC);
        oprot.writeI32(this.assign == null ? 0 : this.assign.getValue());
        oprot.writeFieldEnd();
      }
    }
    if (this.clear != null) {
      oprot.writeFieldBegin(CLEAR_FIELD_DESC);
      oprot.writeBool(this.clear);
      oprot.writeFieldEnd();
    }
    oprot.writeFieldStop();
    oprot.writeStructEnd();
  }

  @Override
  public String toString() {
    return toString(1, true);
  }

  @Override
  public String toString(int indent, boolean prettyPrint) {
    return TBaseHelper.toStringHelper(this, indent, prettyPrint);
  }

  public void validate() throws TException {
    // check for required fields
  }

}


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

public class OrderButtonGroup : MonoBehaviour
{
	public Action<string> callback;

	public OrderMode mode = OrderMode.Radial360;

	public float offest;

	private bool bInit;

	private Vector3 point = Vector3.zero;

	private Vector3 size;

	private int len;

	private List<OrderButton> orders = new List<OrderButton>();

	public GameObject root;

	public GameObject rotationObj;

	private BoxCollider col;

	private bool bShow;

	private Vector3 rotation = Vector3.zero;

	private Camera uiCamera;

	private void Awake()
	{
		this.bInit = false;
	}

	private void OnDisable()
	{
		this.bInit = false;
	}

	private void OnEnable()
	{
		this.OnInit();
	}

	private void OnDestory()
	{
		this.callback = null;
		if (this.orders != null)
		{
			this.orders.Clear();
		}
		this.col = null;
		this.root = null;
		OrderButton.Current = null;
	}

	private void OnInit()
	{
		this.bInit = true;
		this.bShow = false;
		this.col = base.GetComponent<BoxCollider>();
		GameObject gameObject = GameObject.FindGameObjectWithTag("UICamera");
		if (gameObject != null)
		{
			this.uiCamera = gameObject.GetComponent<Camera>();
		}
		this.size = ((!(this.col != null)) ? new Vector3(20f, 20f) : this.col.size);
		this.orders.Clear();
		OrderButton[] componentsInChildren = base.GetComponentsInChildren<OrderButton>(true);
		if (componentsInChildren != null)
		{
			this.orders = new List<OrderButton>(componentsInChildren);
			this.len = this.orders.Count;
		}
		if (this.orders != null)
		{
			this.orders.Sort(new Comparison<OrderButton>(OrderButtonGroup.SortByName));
		}
		if (this.root != null)
		{
			this.root.SetActive(false);
		}
		if (this.rotationObj != null)
		{
			this.rotationObj.SetActive(false);
		}
	}

	public static int SortByName(OrderButton a, OrderButton b)
	{
		return string.Compare(a.name, b.name);
	}

	private void Update()
	{
		if (!this.bInit)
		{
			return;
		}
		if (Input.GetMouseButtonDown(0))
		{
			if (this.ClickOrderGameObject(Input.mousePosition))
			{
				if (this.root != null)
				{
					this.root.SetActive(true);
					this.bShow = true;
				}
				if (this.rotationObj != null)
				{
					this.rotationObj.SetActive(true);
				}
			}
		}
		else if (Input.GetMouseButton(0))
		{
			if (!this.bShow)
			{
				return;
			}
			if (this.ClickOrderGameObject(Input.mousePosition))
			{
				if (OrderButton.Current != null)
				{
					OrderButton.Current.SetState(UIButtonColor.State.Normal, false);
				}
			}
			else
			{
				int orderIndex = this.GetOrderIndex(Input.mousePosition);
				if (orderIndex < 0)
				{
					if (OrderButton.Current != null)
					{
						OrderButton.Current.SetState(UIButtonColor.State.Normal, false);
					}
				}
				else if (orderIndex < this.len)
				{
					if (OrderButton.Current != null)
					{
						OrderButton.Current.SetState(UIButtonColor.State.Normal, false);
					}
					OrderButton.Current = this.orders[orderIndex];
					OrderButton.Current.SetState(UIButtonColor.State.Hover, false);
				}
				if (this.rotationObj != null)
				{
					this.rotation.z = this.GetAngle(Input.mousePosition);
					this.rotationObj.transform.localEulerAngles = this.rotation;
				}
			}
		}
		else if (Input.GetMouseButtonUp(0))
		{
			if (!this.bShow)
			{
				return;
			}
			if (!this.ClickOrderGameObject(Input.mousePosition))
			{
				int orderIndex2 = this.GetOrderIndex(Input.mousePosition);
				if (orderIndex2 >= 0 && orderIndex2 < this.len)
				{
					if (OrderButton.Current != null)
					{
						OrderButton.Current.SetState(UIButtonColor.State.Normal, false);
					}
					OrderButton.Current = this.orders[orderIndex2];
					OrderButton.Current.SetState(UIButtonColor.State.Normal, false);
					if (this.callback != null)
					{
						this.callback(OrderButton.Current.Text);
					}
				}
			}
			if (this.root != null)
			{
				this.root.SetActive(false);
			}
			if (this.rotationObj != null)
			{
				this.rotationObj.SetActive(false);
			}
			this.bShow = false;
		}
	}

	private bool ClickOrderGameObject(Vector3 position)
	{
		if (this.uiCamera != null)
		{
			position = this.uiCamera.ScreenToWorldPoint(position);
			this.point = base.transform.InverseTransformPoint(position);
			return this.point.x >= -this.size.x * 0.5f && this.point.x <= this.size.x * 0.5f && this.point.y >= -this.size.y * 0.5f && this.point.y <= this.size.y * 0.5f;
		}
		return false;
	}

	private float GetAngle(Vector3 position)
	{
		if (this.uiCamera != null)
		{
			position = this.uiCamera.ScreenToWorldPoint(position);
			this.point = base.transform.InverseTransformPoint(position);
			this.point.z = 0f;
			float num = Vector3.Angle(Vector3.left, this.point);
			if (this.point.y < 0f)
			{
				num = 360f - num;
			}
			num += 360f;
			num %= 360f;
			num -= this.offest;
			return -num;
		}
		return 0f;
	}

	private int GetOrderIndex(Vector3 position)
	{
		if (this.len <= 0)
		{
			return -1;
		}
		if (!(this.uiCamera != null))
		{
			return -1;
		}
		position = this.uiCamera.ScreenToWorldPoint(position);
		this.point = base.transform.InverseTransformPoint(position);
		this.point.z = 0f;
		float num = Vector3.Angle(Vector3.left, this.point);
		if (this.point.y < 0f)
		{
			num = 360f - num;
		}
		num += 360f;
		num %= 360f;
		if (this.mode != OrderMode.Radial180)
		{
			float num2 = (float)(360 / this.len);
			num2 = num / num2;
			return Mathf.RoundToInt(num2);
		}
		float num3 = (float)(180 / (this.len - 1));
		if (num <= 180f)
		{
			num3 = num / num3;
			return Mathf.RoundToInt(num3);
		}
		if (num <= 180f + num3 / 2f)
		{
			return this.len - 1;
		}
		if (num > 360f - num3 / 2f)
		{
			return 0;
		}
		return -1;
	}
}


text:
require "rack/oauth2"
require "retriable/no_kernel"
require "shutl/network_retry"

require "shutl/auth/version"
require "shutl/auth/access_token_request"
require "shutl/auth/authenticated_request"
require "shutl/auth/authenticator"
require "faraday"

require 'logger'

module Shutl
  class UnauthorizedAccess < ::StandardError
    attr_reader :status

    def initialize(message = nil, status = nil)
      super(message)
      @status = status
    end
  end

  class Error              < ::StandardError;  end

  module Auth
    class InvalidUrl          < Shutl::Error; end
    class InvalidCredentials  < Shutl::Error; end
    class InternalServerError < Shutl::Error; end

    extend self

    attr_accessor :client_id, :client_secret, :url

    def config
      yield self
    end

    def logger
      return ::Rails.logger if Kernel.const_defined?(:Rails)
      return ::Shutl.logger if Shutl.respond_to? :logger
      Logger.new('/dev/null')
    end
  end
end


text:
#include "ContainsStringPredicate.h"

ContainsStringPredicate::word_list_rep_type ContainsStringPredicate::feature_lookup;
ContainsStringPredicate::bool2D ContainsStringPredicate::seen;


text:
Ext.define('Pandora.store.Stations', {
    extend: 'Ext.data.Store',
    requires: 'Pandora.model.Station',
    model: 'Pandora.model.Station'
});


text:
class ConversationSummarizer

  LENGTH = 140

  def initialize(conversation)
    @conversation = conversation
  end

  def summary
    @conversation.subject || tweet_sized_snippet_from_first_message
  end

  def tweet_sized_snippet_from_first_message
    @conversation.messages.first.content[0...LENGTH]
  end

end


text:
var Server = require('./server/server.js')
var server = new Server()

server.start()


text:
source environ.sh

STABLE

SRC=http://www.ferzkopp.net/Software/SDL_gfx-2.0/SDL_gfx-2.0.25.tar.gz
DIR=SDL_gfx-2.0.25

CONFIGURE_ARGS="--host=${HOST} --disable-shared --disable-sdltest"
configure_template $*


text:
package com.svbio.cloudkeeper.model.api.staging;

import java.io.IOException;

/**
 * Signals that an exception has occurred while accessing a staging area.
 *
 * This exception is a high-level exception that may have a wide range of causes.
 */
public class StagingException extends IOException {
    private static final long serialVersionUID = -6021945648711805388L;

    /**
     * Constructs a new exception with the specified detail message.
     *
     * @param message detail message (which is saved for later retrieval by the {@link #getMessage()} method)
     */
    public StagingException(String message) {
        super(message);
    }

    /**
     * Constructs a new exception with the specified detail message and cause.
     *
     * @param message detail message (which is saved for later retrieval by the {@link #getMessage()} method)
     * @param cause cause (which is saved for later retrieval by the {@link #getCause()} method)
     */
    public StagingException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Constructs a new exception with the specified cause.
     *
     * @param cause cause (which is saved for later retrieval by the {@link #getCause()} method)
     */
    public StagingException(Throwable cause) {
        super(cause);
    }
}


text:
package cgeo.geocaching.utils;

import static org.assertj.core.api.Java6Assertions.assertThat;

import cgeo.geocaching.connector.gc.GCConstants;

import junit.framework.TestCase;
import org.apache.commons.io.IOUtils;
import org.assertj.core.api.Assertions;

import android.text.SpannableString;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Pattern;

public class TextUtilsTest extends TestCase {

    private static String readCachePage(final String geocode) {
        InputStream is = null;
        BufferedReader br = null;
        try {
            is = TextUtilsTest.class.getResourceAsStream("/cgeo/geocaching/test/mock/" + geocode + ".html");
            br = new BufferedReader(new InputStreamReader(is), 150000);

            final StringBuilder buffer = new StringBuilder();
            String line;

            while ((line = br.readLine()) != null) {
                buffer.append(line).append('\n');
            }

            return TextUtils.replaceWhitespace(buffer.toString());
        } catch (final IOException e) {
            Assertions.fail("cannot read cache page", e);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(br);
        }
        return null;
    }

    public static void testRegEx() {
        final String page = readCachePage("GC2CJPF");
        assertThat(TextUtils.getMatch(page, GCConstants.PATTERN_LOGIN_NAME, true, "???")).isEqualTo("ra_sch");
    }

    public static void testReplaceWhitespaces() {
        assertThat(TextUtils.replaceWhitespace("  foo\n\tbar   \r   baz  ")).isEqualTo("foo bar baz ");
    }

    public static void testControlCharactersCleanup() {
        final Pattern patternAll = Pattern.compile("(.*)", Pattern.DOTALL);
        assertThat(TextUtils.getMatch("some" + '\u001C' + "control" + (char) 0x1D + "characters removed", patternAll, "")).isEqualTo("some control characters removed");
        assertThat(TextUtils.getMatch("newline\nalso\nremoved", patternAll, "")).isEqualTo("newline also removed");
    }

    public static void testGetMatch() {
        final Pattern patternAll = Pattern.compile("foo(...)");
        final String text = "abc-foobar-def-fooxyz-ghi-foobaz-jkl";
        assertThat(TextUtils.getMatch(text, patternAll, false, 1, null, false)).isEqualTo("bar");
        assertThat(TextUtils.getMatch(text, patternAll, false, 1, null, true)).isEqualTo("baz");
    }

    public static void testTrimSpanned() {
        assertTrimSpanned(" ", "");
        assertTrimSpanned("\n", "");
        assertTrimSpanned("a ", "a");
        assertTrimSpanned("a\n", "a");
    }

    private static void assertTrimSpanned(final String input, final String expected) {
        assertThat(TextUtils.trimSpanned(new SpannableString(input)).toString()).isEqualTo(new SpannableString(expected).toString());
    }

    public static void testStripHtml() {
        assertThat(TextUtils.stripHtml("foo bar")).isEqualTo("foo bar");
        assertThat(TextUtils.stripHtml("
foo bar
")).isEqualTo("foo bar");
    }
}


text:
package org.qi4j.tutorials.cargo.step2;

import org.qi4j.api.concern.ConcernOf;
import org.qi4j.api.injection.scope.This;
import org.qi4j.api.property.Property;

public class SequencingConcern
    extends ConcernOf<ShippingService>
    implements ShippingService
{
    @This
    private HasSequence generator;

    @Override
    public int makeBooking( Cargo cargo, Voyage voyage )
    {
        int ok = next.makeBooking( cargo, voyage );
        if( ok < 0 )
        {
            return ok;
        }
        Property<Integer> gen = generator.sequence();
        ok = gen.get();
        generator.sequence().set( ok + 1 );
        return ok;
    }
}


text:
package org.apache.spark.sql.crossdata.config

import org.apache.log4j.Logger
import org.apache.spark.sql.crossdata.config.StreamingConstants._
import org.apache.spark.sql.crossdata.models._
import org.apache.spark.sql.types.StructType
import scala.collection.JavaConversions._

object StreamingConfig extends CoreConfig {

  override lazy val logger = Logger.getLogger("StreamingConfig")

  lazy val streamingConfig = config.getConfig(StreamingConstants.StreamingConfPath)

  lazy val streamingConfigMap: Map[String, String] =
    streamingConfig.entrySet().map(entry => (entry.getKey, streamingConfig.getAnyRef(entry.getKey).toString)).toMap

  def createEphemeralTableModel(ident: String, opts : Map[String, String], userSchema: Option[StructType] = None) : EphemeralTableModel = {

    val finalOptions = getEphemeralTableOptions(ident, opts)

    val connectionsModel = ConnectionHostModel(extractConnection(finalOptions, ZKConnection), extractConnection(finalOptions, KafkaConnection))

    val topics = finalOptions(KafkaTopic)
      .split(",").map(_.split(":")).map{
      case l if l.size == 2 => TopicModel(l(0), l(1).toInt)
    }.toSeq

    val groupId = finalOptions(KafkaGroupId)
    val partition = finalOptions.get(KafkaPartition)
    val kafkaAdditionalOptions = finalOptions.filter{case (k, v) => k.startsWith(KafkaAdditionalOptionsKey)}
    val storageLevel = finalOptions(ReceiverStorageLevel)
    val kafkaOptions = KafkaOptionsModel(connectionsModel, topics, groupId, partition, kafkaAdditionalOptions, storageLevel)
    val minW = finalOptions(AtomicWindow).toInt
    val maxW = finalOptions(MaxWindow).toInt
    val outFormat = finalOptions(OutputFormat) match {
      case "JSON" => EphemeralOutputFormat.JSON
      case other => EphemeralOutputFormat.ROW
    }

    val checkpointDirectory = s"${finalOptions(CheckpointDirectory)}/$ident"
    val sparkOpts = finalOptions.filter{case (k, v) => k.startsWith(SparkConfPath)}
    validateSparkConfig(sparkOpts)

    val ephemeralOptions = EphemeralOptionsModel(kafkaOptions, minW, maxW, outFormat, checkpointDirectory, sparkOpts)

    EphemeralTableModel(ident, ephemeralOptions, userSchema)
  }

  def extractConnection(options: Map[String, String], connection: String): Seq[ConnectionModel] = {
    options(connection).split(",").map {
      case c if c.split(":").length == 2 => {
        val host_port = c.split(":")
        ConnectionModel(host_port(0), host_port(1).toInt)
      }
    }
  }

  private def getEphemeralTableOptions(ephTable: String, opts : Map[String, String]): Map[String, String] = {

    listMandatoryEphemeralTableKeys.foreach{ mandatoryOption =>
      if (opts.get(mandatoryOption).isEmpty) notFound(mandatoryOption)
    }
    streamingConfigMap ++ opts
  }

  // Return default value
  def notFound(key: String) = {
    logError(s"Mandatory parameter $key not specified, you have to specify it")
    throw new RuntimeException(key)
  }

  private def validateSparkConfig(config: Map[String, String]): Unit = {
    config.get(SparkCoresMax).foreach{ maxCores =>
      if (maxCores.toInt < 2) throw new RuntimeException(s"At least 2 cores are required to launch streaming applications")
    }
  }

}


text:
'''
Stateful, singleton, paradrop daemon command center.
See docstring for NexusBase class for information on settings.

SETTINGS QUICK REFERENCE:
    # assuming the following import
    from paradrop.base import nexus

    nexus.core.info.version
    nexus.core.info.pdid
'''

import os
import yaml
import json

import smokesignal
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks, returnValue

from . import output, settings
from paradrop.lib.utils import pdosq

# Global access. Assign this wherever you instantiate the Nexus object:
#       nexus.core = MyNexusSubclass()
core = None

class NexusBase(object):
    '''
    Resolving these values to their final forms:
        1 - module imported, initial values assigned(as written below)
        2 - class is instatiated, passed settings to replace values
        3 - instance chooses appropriate values based on current state(production or local)
            Each category has its own method for initialization here
            (see: resolveNetwork, resolvePaths)

    '''
    VERSION = 1                                         # nexus.core.info.version
    PDID = None                                         # nexus.core.info.pdid

    def __init__(self, stealStdio=True, printToConsole=True):
        '''
        The one big thing this function leaves out is reactor.start(). Call this externally
        *after * initializing a nexus object.
        '''
        self.session = None
        self.wamp_connected = False
        self.jwt_valid = False

        self.info = AttrWrapper()
        resolveInfo(self, settings.CONFIG_FILE)
        self.info.setOnChange(self.onInfoChange)

        # initialize output. If filepath is set, logs to file.
        # If stealStdio is set intercepts all stderr and stdout and interprets it internally
        # If printToConsole is set (defaults True) all final output is rendered to stdout
        output.out.startLogging(filePath=settings.LOG_DIR, stealStdio=stealStdio, printToConsole=printToConsole)

        # register onStop for the shutdown call
        reactor.addSystemEventTrigger('before', 'shutdown', self.onStop)

        # The reactor needs to be runnnig before this call is fired, since we start the session
        # here. Assuming callLater doesn't fire until thats happened
        reactor.callLater(0, self.onStart)

    def onStart(self):
        pdid = self.info.pdid if self.provisioned() else 'UNPROVISIONED'
        output.out.usage('%s coming up' % (pdid))

    def onStop(self):
        self.save()

        output.out.usage('%s going down' % (self.info.pdid))
        smokesignal.clear_all()
        output.out.endLogging()

    @inlineCallbacks
    def connect(self, sessionClass, debug=False):
        '''
        Takes the given session class and attempts to connect to the crossbar fabric.

        If an existing session is connected, it is cleanly closed.
        '''

        if (self.session is not None):
            yield self.session.leave()

        self.wamp_connected = False

        output.out.info('Connecting to wamp router at URI: %s' % str(self.info.wampRouter))

        # Setting self.session here only works for the first connection but
        # becomes stale if the connection fails and we reconnect.
        # In that case a new session object is automatically created.
        # For this reason, we also update this session reference in BaseSession.onJoin.
        self.session = yield sessionClass.start(self.info.wampRouter, self.info.pdid, debug=debug)
        returnValue(self.session)

    def onInfoChange(self, key, value):
        '''
        Called when an internal setting is changed. Trigger a save automatically.
        '''
        self.save()

    def save(self):
        ''' Ehh. Ideally this should happen asynchronously. '''
        saveDict = self.info.__dict__['contents']
        saveDict['version'] = self.info.version

        writeYaml(saveDict, settings.CONFIG_FILE)

    #########################################################
    # High Level Methods
    #########################################################

    def provisioned(self):
        '''
        Checks if this[whatever] appears to be provisioned or not
        '''

        return self.info.pdid is not None

    def provision(self, pdid, pdserver=settings.PDSERVER, wampRouter=settings.WAMP_ROUTER):
        self.info.pdid = pdid
        self.info.pdserver = pdserver
        self.info.wampRouter = wampRouter

    #########################################################
    # Keys
    #########################################################

    def saveKey(self, key, name):
        ''' Save the key with the given name. Overwrites by default '''
        path = settings.KEY_DIR + name

        with open(path, 'wb') as f:
            f.write(key)

    def getKey(self, name):
        ''' Returns the given key or None '''
        path = settings.KEY_DIR + name

        if os.path.isfile(path):
            with open(path, 'rb') as f:
                return f.read()

        return None

    #########################################################
    # Misc
    #########################################################

    def __repr__(self):
        ''' Dump everything '''
        dic = dict(info=self.info.contents)
        return json.dumps(dic, sort_keys=True, indent=4)

#########################################################
# Utils
#########################################################

class AttrWrapper(object):
    '''
    Simple attr interceptor to make accessing settings simple.

    Stores values in an internal dict called contents.

    Does not allow modification once _lock() is called. Respect it.

    Once you've filled it up with the appropriate initial values, set
    onChange to assign
    '''

    def __init__(self):
        self.__dict__['contents'] = {}

        # Called when a value changes unless None
        self.__dict__['onChange'] = None

        # Lock the contents of this wrapper. Can read valued, cant write them
        self.__dict__['locked'] = False

    def _lock(self):
        self.__dict__['locked'] = True

    def setOnChange(self, func):
        assert(callable(func))
        self.__dict__['onChange'] = func

    def __repr__(self):
        return str(self.contents)

    def __getattr__(self, name):
        return self.__dict__['contents'][name]

    def __setattr__(self, k, v):
        if self.__dict__['locked']:
            raise AttributeError('This attribute wrapper is locked. You cannot change its values.')

        self.contents[k] = v

        if self.__dict__['onChange'] is not None:
            self.__dict__['onChange'](k, v)

def resolveInfo(nexus, path):
    '''
    Given a path to the config file, load its contents and assign it to the
    config file as appropriate.
    '''

    # Check to make sure we have a default settings file
    if not os.path.isfile(path):
        createDefaultInfo(path)

    contents = pdosq.read_yaml_file(path)

    # Sanity check contents of info and throw it out if bad
    if not validateInfo(contents):
        output.out.err('Saved configuration data invalid, destroying it.')
        os.remove(path)
        createDefaultInfo(path)
        contents = pdosq.read_yaml_file(path, default={})
        writeYaml(contents, path)

    nexus.info.pdid = contents['pdid']
    nexus.info.version = contents['version']
    nexus.info.pdserver = contents['pdserver']
    nexus.info.wampRouter = contents['wampRouter']

def createDefaultInfo(path):
    default = {
        'version': 1,
        'pdid': None,
        'pdserver': settings.PDSERVER,
        'wampRouter': settings.WAMP_ROUTER
    }

    writeYaml(default, path)

def validateInfo(contents):
    '''
    Error checking on the read YAML file. This is a temporary method.

    :
        param contents:
            the read - in yaml to check
    :
        type contents:
            dict.
    :
        returns:
            True if valid, else false
    '''
    INFO_REQUIRES = ['version', 'pdid', 'pdserver', 'wampRouter']

    for k in INFO_REQUIRES:
        if k not in contents:
            output.out.err('Contents is missing: ' + str(k))
            return False

    return True

def writeYaml(contents, path):
    ''' Overwrites content with YAML representation at given path '''
    # print 'Writing ' + str(contents) + ' to path ' + str(path)

    with open(path, 'w') as f:
        f.write(yaml.safe_dump(contents, default_flow_style=False))


text:
/**
 * Created by Administrator on 2016/4/1.
 */
function Carousel(target,setting){
    //基于bootstrap carousel

    //carouse.r_init([{src:'/Resource/picture/1432190687378.jpg',alt:'',describe:'what the fuck','active':true},{src:'/Resource/picture/1432190687378.jpg',alt:'',describe:'what the fuck'},{src:'/Resource/picture/1432190687378.jpg',alt:'',describe:'what the fuck'}]);
    // bootstrap 默认的参数
    Carousel.prototype.setting={
        interval:5000,
        keyboard:true,
        wrap:true,
        pause:"hover",

        showControls:true
    }
    if(setting){
        this.setting = Carousel.prototype.setting;
        for(var x in setting){
            this.setting[x] = setting[x];
        }
    }

    this.items = [];
    this.target = target;
    var $this = this;
    this.html ={};
    this.html.Indicators = {};
    this.html.Slides = {};

    this.html.Indicators.h='
';
    this.html.Indicators.f='
';
    this.html.Indicators.items=[];
    this.html.Slides.h = '
';
    this.html.Slides.f = '
';
    this.html.Slides.items=[];
    this.html.Control = {};
    this.html.Control.Previous= ''
    + ''
    + 'Previous'
    + '';
    this.html.Control.Next = ''
    + ''
    + 'Next'
    + '';
    Carousel.prototype.r_init=function(data){
        $this.items = [];
        for(x in data){
            $this.items.push(data[x]);
        }
        $this.html.Indicators.items=[];
        $this.html.Slides.items=[];
        $this._build();
    }
    Carousel.prototype._build = function(){
        var id = 'carousel-example-generic'+(new Date().getTime());
        var i=0;
        for(var x in $this.items){
            var html;
            if(this.items[x]['active']){
                html = '
'
                +''
                +'
'
                +$this.items[x]['describe']
                +'
'
                +'
';
            }else{
                html = '
'
                +''
                +'
'
                +$this.items[x]['describe']
                +'
'
                +'
';
            }
            $this.html.Slides.items.push(html);
            if(this.items[x]['active']){
                html = '

';
            }else{
                html = '

';
            }
            $this.html.Indicators.items.push(html);
            i++;
        }

        var html ='
'+
            $this.html.Indicators.h+$this.html.Indicators.items.join('')+$this.html.Indicators.f
            +$this.html.Slides.h+$this.html.Slides.items.join('')+$this.html.Slides.f;
        if($this.setting.showControls){
            html = html+$this.html.Control.Previous.replace('href="#carousel-example-generic"','href="#'+id+'"')
            +$this.html.Control.Next.replace('href="#carousel-example-generic"','href="#'+id+'"');
        }
        html = html+'
';

        $('#'+$this.target).html(html);

        $('#'+id).carousel({interval:$this.setting['interval']});
    }
}


text:
namespace blink {

PassRefPtr<PicturePattern> PicturePattern::create(PassRefPtr<const SkPicture> picture,
    RepeatMode repeatMode)
{
    return adoptRef(new PicturePattern(picture, repeatMode));
}

PicturePattern::PicturePattern(PassRefPtr<const SkPicture> picture, RepeatMode mode)
    : Pattern(mode)
    , m_tilePicture(picture)
{
    // All current clients use RepeatModeXY, so we only support this mode for now.
    ASSERT(isRepeatXY());

    // FIXME: we don't have a good way to account for DL memory utilization.
}

PicturePattern::~PicturePattern()
{
}

PassRefPtr<SkShader> PicturePattern::createShader()
{
    SkMatrix localMatrix = affineTransformToSkMatrix(m_patternSpaceTransformation);
    SkRect tileBounds = m_tilePicture->cullRect();

    return adoptRef(SkShader::CreatePictureShader(m_tilePicture.get(),
        SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode, &localMatrix, &tileBounds));
}

} // namespace blink


text:
@interface ATMeCellView : UIView

@property (nonatomic,strong)ATMeCellItem *meCellItem;

@end


text:
package demo

import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorSystem
import akka.actor.Props
import scala.concurrent.Await
import scala.concurrent.duration._
import java.util.Calendar
import scala.language.postfixOps
import raft._
import scala.util.Success
import scala.util.Failure

class Sequencer extends Actor with RaftClient with ActorLogging {
  import context._

  def schedule = system.scheduler.scheduleOnce(50 millis, self, "sequence")

  override def preStart() = schedule
  override def postRestart(reason: Throwable) = {}

  def receive = {
    case "sequence" =>
      decide("get") onComplete {
        case Success(x) => log.info(s"Got $x")
        case Failure(t) => log.info(s"Error ${t.getMessage()}")
      }

      schedule
  }
}

object Main extends App {
  implicit val system = ActorSystem("raft")
  val members = Raft(3)
  val client = system.actorOf(Props[Sequencer], "client")

  println("Running raft demo - press enter key to exit")
  Console.readLine

  system.shutdown
}


text:
namespace ash {
namespace {

ui::TestDisplaySnapshot* CreateInternalSnapshot() {
  ui::TestDisplaySnapshot* output = new ui::TestDisplaySnapshot();
  output->set_type(ui::DISPLAY_CONNECTION_TYPE_INTERNAL);
  return output;
}

ui::TestDisplaySnapshot* CreateVGASnapshot() {
  ui::TestDisplaySnapshot* output = new ui::TestDisplaySnapshot();
  output->set_type(ui::DISPLAY_CONNECTION_TYPE_VGA);
  return output;
}

ui::DisplayConfigurator::DisplayStateList CreateOutputs(
    const ScopedVector<ui::TestDisplaySnapshot>& displays) {
  ui::DisplayConfigurator::DisplayStateList outputs;
  for (size_t i = 0; i < displays.size(); ++i) {
    ui::DisplayConfigurator::DisplayState state;
    state.display = displays[i];
    outputs.push_back(state);
  }

  return outputs;
}

class ProjectingObserverTest : public testing::Test {
 public:
  ProjectingObserverTest() : observer_(new ProjectingObserver()) {
    chromeos::FakeDBusThreadManager* dbus_manager =
        new chromeos::FakeDBusThreadManager();
    fake_power_client_ = new chromeos::FakePowerManagerClient();

    dbus_manager->SetPowerManagerClient(
        scoped_ptr<chromeos::PowerManagerClient>(fake_power_client_));

    // Takes ownership of |dbus_manager|.
    chromeos::DBusThreadManager::InitializeForTesting(dbus_manager);
  }

  virtual ~ProjectingObserverTest() {
    chromeos::DBusThreadManager::Shutdown();
  }

 protected:
  scoped_ptr<ProjectingObserver> observer_;
  chromeos::FakePowerManagerClient* fake_power_client_;  //  Not owned.

  DISALLOW_COPY_AND_ASSIGN(ProjectingObserverTest);
};

}  // namespace

TEST_F(ProjectingObserverTest, CheckNoDisplay) {
  ScopedVector<ui::TestDisplaySnapshot> displays;
  ui::DisplayConfigurator::DisplayStateList outputs = CreateOutputs(displays);
  observer_->OnDisplayModeChanged(outputs);

  EXPECT_EQ(1, fake_power_client_->num_set_is_projecting_calls());
  EXPECT_FALSE(fake_power_client_->is_projecting());
}

TEST_F(ProjectingObserverTest, CheckWithoutInternalDisplay) {
  ScopedVector<ui::TestDisplaySnapshot> displays;
  displays.push_back(CreateVGASnapshot());
  ui::DisplayConfigurator::DisplayStateList outputs = CreateOutputs(displays);
  observer_->OnDisplayModeChanged(outputs);

  EXPECT_EQ(1, fake_power_client_->num_set_is_projecting_calls());
  EXPECT_FALSE(fake_power_client_->is_projecting());
}

TEST_F(ProjectingObserverTest, CheckWithInternalDisplay) {
  ScopedVector<ui::TestDisplaySnapshot> displays;
  displays.push_back(CreateInternalSnapshot());
  ui::DisplayConfigurator::DisplayStateList outputs = CreateOutputs(displays);
  observer_->OnDisplayModeChanged(outputs);

  EXPECT_EQ(1, fake_power_client_->num_set_is_projecting_calls());
  EXPECT_FALSE(fake_power_client_->is_projecting());
}

TEST_F(ProjectingObserverTest, CheckWithTwoVGADisplays) {
  ScopedVector<ui::TestDisplaySnapshot> displays;
  displays.push_back(CreateVGASnapshot());
  displays.push_back(CreateVGASnapshot());
  ui::DisplayConfigurator::DisplayStateList outputs = CreateOutputs(displays);
  observer_->OnDisplayModeChanged(outputs);

  EXPECT_EQ(1, fake_power_client_->num_set_is_projecting_calls());
  // We need at least 1 internal display to set projecting to on.
  EXPECT_FALSE(fake_power_client_->is_projecting());
}

TEST_F(ProjectingObserverTest, CheckWithInternalAndVGADisplays) {
  ScopedVector<ui::TestDisplaySnapshot> displays;
  displays.push_back(CreateInternalSnapshot());
  displays.push_back(CreateVGASnapshot());
  ui::DisplayConfigurator::DisplayStateList outputs = CreateOutputs(displays);
  observer_->OnDisplayModeChanged(outputs);

  EXPECT_EQ(1, fake_power_client_->num_set_is_projecting_calls());
  EXPECT_TRUE(fake_power_client_->is_projecting());
}

TEST_F(ProjectingObserverTest, CheckWithVGADisplayAndOneCastingSession) {
  ScopedVector<ui::TestDisplaySnapshot> displays;
  displays.push_back(CreateVGASnapshot());
  ui::DisplayConfigurator::DisplayStateList outputs = CreateOutputs(displays);
  observer_->OnDisplayModeChanged(outputs);

  observer_->OnCastingSessionStartedOrStopped(true);

  EXPECT_EQ(2, fake_power_client_->num_set_is_projecting_calls());
  // Need at least one internal display to set projecting state to |true|.
  EXPECT_FALSE(fake_power_client_->is_projecting());
}

TEST_F(ProjectingObserverTest, CheckWithInternalDisplayAndOneCastingSession) {
  ScopedVector<ui::TestDisplaySnapshot> displays;
  displays.push_back(CreateInternalSnapshot());
  ui::DisplayConfigurator::DisplayStateList outputs = CreateOutputs(displays);
  observer_->OnDisplayModeChanged(outputs);

  observer_->OnCastingSessionStartedOrStopped(true);

  EXPECT_EQ(2, fake_power_client_->num_set_is_projecting_calls());
  EXPECT_TRUE(fake_power_client_->is_projecting());
}

TEST_F(ProjectingObserverTest, CheckProjectingAfterClosingACastingSession) {
  ScopedVector<ui::TestDisplaySnapshot> displays;
  displays.push_back(CreateInternalSnapshot());
  ui::DisplayConfigurator::DisplayStateList outputs = CreateOutputs(displays);
  observer_->OnDisplayModeChanged(outputs);

  observer_->OnCastingSessionStartedOrStopped(true);
  observer_->OnCastingSessionStartedOrStopped(true);

  EXPECT_EQ(3, fake_power_client_->num_set_is_projecting_calls());
  EXPECT_TRUE(fake_power_client_->is_projecting());

  observer_->OnCastingSessionStartedOrStopped(false);

  EXPECT_EQ(4, fake_power_client_->num_set_is_projecting_calls());
  EXPECT_TRUE(fake_power_client_->is_projecting());
}

TEST_F(ProjectingObserverTest,
       CheckStopProjectingAfterClosingAllCastingSessions) {
  ScopedVector<ui::TestDisplaySnapshot> displays;
  displays.push_back(CreateInternalSnapshot());
  ui::DisplayConfigurator::DisplayStateList outputs = CreateOutputs(displays);
  observer_->OnDisplayModeChanged(outputs);

  observer_->OnCastingSessionStartedOrStopped(true);
  observer_->OnCastingSessionStartedOrStopped(false);

  EXPECT_EQ(3, fake_power_client_->num_set_is_projecting_calls());
  EXPECT_FALSE(fake_power_client_->is_projecting());
}

TEST_F(ProjectingObserverTest,
       CheckStopProjectingAfterDisconnectingSecondOutput) {
  ScopedVector<ui::TestDisplaySnapshot> displays;
  displays.push_back(CreateInternalSnapshot());
  displays.push_back(CreateVGASnapshot());
  ui::DisplayConfigurator::DisplayStateList outputs = CreateOutputs(displays);
  observer_->OnDisplayModeChanged(outputs);

  // Remove VGA output.
  outputs.erase(outputs.begin() + 1);
  observer_->OnDisplayModeChanged(outputs);

  EXPECT_EQ(2, fake_power_client_->num_set_is_projecting_calls());
  EXPECT_FALSE(fake_power_client_->is_projecting());
}

}  // namespace ash


text:
package com.hazelcast.internal.partition.impl;

import com.hazelcast.instance.impl.Node;
import com.hazelcast.instance.impl.NodeState;
import com.hazelcast.internal.partition.InternalPartitionService;
import com.hazelcast.logging.ILogger;

/**
 * A periodic task to publish partition state to cluster members in a predefined interval.
 */
class PublishPartitionRuntimeStateTask implements Runnable {
    private final Node node;
    private final InternalPartitionServiceImpl partitionService;
    private final ILogger logger;

    PublishPartitionRuntimeStateTask(Node node, InternalPartitionServiceImpl partitionService) {
        this.node = node;
        this.partitionService = partitionService;
        logger = node.getLogger(InternalPartitionService.class);
    }

    @Override
    public void run() {
        if (partitionService.isLocalMemberMaster()) {
            MigrationManager migrationManager = partitionService.getMigrationManager();
            boolean migrationAllowed = migrationManager.areMigrationTasksAllowed()
                    && !partitionService.isFetchMostRecentPartitionTableTaskRequired();
            if (!migrationAllowed) {
                logger.fine("Not publishing partition runtime state since migration is not allowed.");
                return;
            }

            if (migrationManager.hasOnGoingMigration()) {
                logger.info("Remaining migration tasks: " + partitionService.getMigrationQueueSize()
                    + ". (" + migrationManager.getStats().formatToString(logger.isFineEnabled()) + ")");
            } else if (node.getState() == NodeState.ACTIVE) {
                partitionService.checkClusterPartitionRuntimeStates();
            }
        }
    }
}


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

    Copyright 2013 Ordina

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

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

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

-->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="bagMutatieLeveringValidator" class="nl.ordina.bag.etl.validation.BAGExtractLeveringValidator">
		<property name="klantnummer" value="${bagLeveringInfo.klantnummer}"/>
		<property name="productcode" value="${bagLeveringInfo.mutatie.productcode}"/>
		<property name="gebiedType" value="${bagLeveringInfo.gebiedType}"/>
		<property name="gegevensvariant" value="${bagLeveringInfo.gegevensvariant}"/>
		<property name="formaat" value="${bagLeveringInfo.formaat}"/>
		<property name="producttype" value="${bagLeveringInfo.mutatie.producttype}"/>
		<property name="productversie" value="${bagLeveringInfo.productversie}"/>
	</bean>

	<bean id="mutatiesFileLoader" class="nl.ordina.bag.etl.loader.MutatiesFileLoader">
		<property name="bagMutatiesDAO" ref="bagMutatiesDAO"/>
		<property name="bagExtractLeveringValidator" ref="bagMutatieLeveringValidator"/>
	</bean>

	<bean id="mutatiesFileProcessor" class="nl.ordina.bag.etl.processor.MutatiesFileProcessor">
		<property name="bagMutatiesDAO" ref="bagMutatiesDAO"/>
	</bean>

	<bean id="mutationListener" class="nl.ordina.bag.etl.processor.DefaultMutationListener"/>

	<bean id="mutatiesProcessor" class="nl.ordina.bag.etl.processor.MutatiesProcessor">
		<property name="bagMutatiesDAO" ref="bagMutatiesDAO"/>
		<property name="bagDAO" ref="bagDAO"/>
		<property name="bagObjectFactory" ref="bagObjectFactory"/>
		<property name="mutationListener" ref="mutationListener"/>
	</bean>

	<bean id="mutatiesLoader" class="nl.ordina.bag.etl.loader.MutatiesLoader">
		<property name="bagMutatiesDAO" ref="bagMutatiesDAO"/>
		<property name="bagDAO" ref="bagDAO"/>
		<property name="mutatiesFileProcessor" ref="mutatiesFileProcessor"/>
		<property name="mutatiesProcessor" ref="mutatiesProcessor"/>
	</bean>

</beans>


text:
package com.twu.biblioteca;

class BookBuilder implements Builder<Book> {
    private String title = "unnamed";
    private String author = "anonymous";
    private String year = "never";

    static BookBuilder aBook() {
        return new BookBuilder();
    }

    @Override
    public Book build() {
        return new Book(title, author, year);
    }

    BookBuilder titled(String title) {
        this.title = title;
        return this;
    }

    BookBuilder writtenBy(String author) {
        this.author = author;
        return this;
    }

    BookBuilder in(String year) {
        this.year = year;
        return this;
    }

    @Override
    public String toString() {
        return build().toString();
    }
}


text:
#define _GNU_SOURCE  // Needed for sched_setaffinity().
#include <assert.h>
#include <sched.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>

#include "avionics/common/avionics_messages.h"
#include "avionics/common/pack_avionics_messages.h"
#include "avionics/linux/aio.h"
#include "avionics/linux/q7_slow_status.h"
#include "avionics/linux/q7_slow_status_types.h"
#include "avionics/network/aio_labels.h"
#include "avionics/network/aio_node.h"
#include "avionics/network/message_type.h"
#include "common/macros.h"
#include "control/control_params.h"
#include "control/control_system.h"
#include "control/control_telemetry.h"
#include "control/control_types.h"
#include "control/estimator/estimator_ground.h"
#include "control/ground_telemetry.h"
#include "control/pack_control_telemetry.h"
#include "control/pack_ground_telemetry.h"
#include "control/system_params.h"
#include "control/system_types.h"
#include "sim/pack_sim_messages.h"

static const AioNode kThisNode = kAioNodeGsEstimator;

#if defined(MAKANI_HITL)

#include "control/avionics/avionics_sim.h"
#include "sim/cvt_sim_messages.h"
#include "sim/sim_messages.h"

static const MessageType *GetSubscribeTypes(int32_t *num_subscribe_types) {
  static const MessageType kRealFlightSubscribeTypes[] = {
      kMessageTypeSimSensor, kMessageTypeSimCommand};

  *num_subscribe_types = ARRAYSIZE(kRealFlightSubscribeTypes);
  return kRealFlightSubscribeTypes;
}

#else

static const MessageType *GetSubscribeTypes(int32_t *num_subscribe_types) {
  static const MessageType kRealFlightSubscribeTypes[] = {
      kMessageTypeFlightComputerImu, kMessageTypeFlightComputerSensor,
      kMessageTypeNovAtelSolution, kMessageTypeNovAtelCompass};

  *num_subscribe_types = ARRAYSIZE(kRealFlightSubscribeTypes);
  return kRealFlightSubscribeTypes;
}

#endif  // defined(MAKANI_HITL)

static GroundEstimatorState g_state;

// Function called periodically by AIO.
//
// Periodically calls GroundEstimateStep, then sends the resulting
// command, synchronization, and telemetry messages.
//
// During HITL simulations, waits until the first simulator message is
// received, then uses these messages to overwrite portions of the
// CVT.  Timeouts can cause the estimator to exit if messages are not
// being received from the simulator.
//
// Returns:
//   Whether or not the estimator should keep running.
static bool AioCallback(void *arg) {
  UNUSED(arg);

#if defined(MAKANI_HITL)

  SimCommandMessage sim_command = {0U, 0U, false};
  if (CvtGetSimCommandMessage(kAioNodeSimulator, &sim_command, NULL, NULL)) {
    if (sim_command.stop) {
      return false;
    }
  }

  SimSensorMessage sensor_message;
  uint16_t sequence;
  int64_t timestamp;
  bool updated = CvtGetSimSensorMessage(kAioNodeSimulator, &sensor_message,
                                        &sequence, &timestamp);

  // During HITL simulations, the controller will not run until the
  // first simulator message is received. Two timeouts are used to
  // terminate the controller if communication with the simulator is
  // interrupted:
  //   (1) the controller will wait at most sim_init_timeout seconds
  //       for the first simulator message,
  //   (2) once the controller is running, it will terminate if it does not hear
  //       from the simulator for sim_update_timeout seconds.
  const HitlControlParams *hitl_params = &GetControlParams()->hitl;
  static bool started = false;
  static int32_t iters_without_update = 0;
  if (updated) {
    iters_without_update = 0;
    started = true;
  } else {
    iters_without_update++;
    if (!started) {
      return iters_without_update * GetSystemParams()->ts <
             hitl_params->sim_init_timeout;
    } else if (iters_without_update * GetSystemParams()->ts >=
               hitl_params->sim_update_timeout) {
      return false;
    }
  }

  if (updated) {
    // If the simulator is running with a different HITL configuration than
    // the controller, exit.
    //
    // The sim_level only needs to get set once, but the logic stays better
    // contained this way.
    GetSystemParamsUnsafe()->hitl.config.sim_level = kSimulatorHitlLevelAsync;
    if (!HitlConfigurationsEquivalent(&sensor_message.hitl_config,
                                      &GetSystemParams()->hitl.config)) {
      assert(false);
      return false;
    }

    // Write the most recent sensor message to the CVT.
    UpdateGroundEstimatorCvtFromSimSensorMessage(&sensor_message, sequence,
                                                 timestamp);
  }

#else

  assert(!(bool)"Non-HITL flights will not run with asserts turned on.");

#endif  // defined(MAKANI_HITL)

  EstimatorGroundStep(GetSystemParams(), GetControlParams(), &g_state);

  AIO_SEND_PACKED(kMessageTypeGroundEstimate, PackGroundEstimateMessage,
                  PACK_GROUNDESTIMATEMESSAGE_SIZE, &g_state.ground_estimate);

  AIO_SEND_PACKED(kMessageTypeGroundTelemetry, PackGroundTelemetry,
                  PACK_GROUNDTELEMETRY_SIZE, GetGroundTelemetryMessage());

  static int32_t q7_slow_status_counter = 0;
  ++q7_slow_status_counter;
  if (q7_slow_status_counter >= Q7_SLOW_STATUS_DECIMATION) {
    q7_slow_status_counter = 0;
    AIO_SEND_PACKED(kMessageTypeQ7SlowStatus, PackQ7SlowStatusMessage,
                    PACK_Q7SLOWSTATUSMESSAGE_SIZE, GetQ7SlowStatusMessage());
  }

  return true;  // Always continue execution.
}

// TODO: Move rt functoins into a common lib.

// Lock us to CPU1 to avoid conflicting with IRQ handling.
static bool SetCpuAffinity(void) {
  cpu_set_t set;
  CPU_ZERO(&set);
  CPU_SET(1, &set);
  if (sched_setaffinity(getpid(), sizeof(set), &set) == -1) {
    assert(!(bool)"Could not set CPU affinity.");
    return false;
  }
  return true;
}

// Raise our priority and set us to SCHED_FIFO.
static bool SetRealTimeSchedPriority(void) {
  struct sched_param param = {
      .sched_priority = 49,
  };
  if (sched_setscheduler(0, SCHED_FIFO, &param) == -1) {
    assert(!(bool)"Could not set real time priority/scheduling policy.");
    return false;
  }
  return true;
}

// Lock all to keep them resident.
static bool LockMemoryPages(void) {
  if (mlockall(MCL_CURRENT | MCL_FUTURE) == -1) {
    assert(!(bool)"Could not lock memory pages.");
    return false;
  }
  return true;
}

// Pre fault in a large stack to avoid page allocation at runtime.
static bool PreFaultStack(void) {
  // The default stack ulimit is 8K.
  uint8_t stack_allocation[8 * 1024];

  // Touch the memory to force the kernel to fault in our pages.
  memset(stack_allocation, 0, sizeof(stack_allocation));
  return true;
}

static bool EnterRealTimeMode(void) {
  return SetCpuAffinity() && SetRealTimeSchedPriority() && LockMemoryPages() &&
         PreFaultStack();
}

// Entry point for the ground estimator when run on the ground estimator node
int main(int argc, char **argv) {
  UNUSED(argc);
  UNUSED(argv);

  int32_t num_subscribe_types;
  const MessageType *subscribe_types = GetSubscribeTypes(&num_subscribe_types);

  if (!EnterRealTimeMode()) return -1;

  EstimatorGroundInit(&g_state);
  // Initialize the slow status message.
  Q7SlowStatusContext q7_slow_status_context;
  if (!Q7SlowStatusInit(&q7_slow_status_context)) {
    if (kThisNode != q7_slow_status_context.node) {
      assert(!(bool)"IP address/AioNode mismatch.");
      return -1;
    }
  }
  Q7SlowStatusInitMessage(&q7_slow_status_context, GetQ7SlowStatusMessage());

  AioLoopStart(kThisNode, GetSystemParams()->comms.aio_port, subscribe_types,
               num_subscribe_types, AioCallback, NULL,
               (int32_t)(GetSystemParams()->ts * 1000000));
  AioClose();

  return 0;
}


text:
import * as ts from "typescript";
import * as Lint from "../index";
export declare class Rule extends Lint.Rules.AbstractRule {
    static DEFAULT_ALLOWED_BLANKS: number;
    static metadata: Lint.IRuleMetadata;
    static FAILURE_STRING_FACTORY(allowed: number): string;
    /**
     * Disable the rule if the option is provided but non-numeric or less than the minimum.
     */
    isEnabled(): boolean;
    apply(sourceFile: ts.SourceFile): Lint.RuleFailure[];
}
export declare function getTemplateRanges(sourceFile: ts.SourceFile): ts.TextRange[];


text:
import hashlib

def make_hash( url ):
    return hashlib.sha224( url ).hexdigest()


text:
import crm from './modules/crm';
import book from './modules/book';
import test from './modules/test';
import index from './modules/index';

export default [
    crm,
    book,
    test,
    index,
];


text:
#ifndef __MICROPY_INCLUDED_PY_PARSE_H__
#define __MICROPY_INCLUDED_PY_PARSE_H__

#include <stdint.h>

#include "py/mpconfig.h"

struct _mp_lexer_t;

// a mp_parse_node_t is:
//  - 0000...0000: no node
//  - xxxx...xxx1: a small integer; bits 1 and above are the signed value, 2's complement
//  - xxxx...xx00: pointer to mp_parse_node_struct_t
//  - xx...x00010: an identifier; bits 5 and above are the qstr
//  - xx...x00110: an integer; bits 5 and above are the qstr holding the value
//  - xx...x01010: a decimal; bits 5 and above are the qstr holding the value
//  - xx...x01110: a string; bits 5 and above are the qstr holding the value
//  - xx...x10010: a string of bytes; bits 5 and above are the qstr holding the value
//  - xx...x10110: a token; bits 5 and above are mp_token_kind_t

#define MP_PARSE_NODE_NULL      (0)
#define MP_PARSE_NODE_SMALL_INT (0x1)
#define MP_PARSE_NODE_ID        (0x02)
#define MP_PARSE_NODE_INTEGER   (0x06)
#define MP_PARSE_NODE_DECIMAL   (0x0a)
#define MP_PARSE_NODE_STRING    (0x0e)
#define MP_PARSE_NODE_BYTES     (0x12)
#define MP_PARSE_NODE_TOKEN     (0x16)

typedef mp_uint_t mp_parse_node_t; // must be pointer size

typedef struct _mp_parse_node_struct_t {
    uint32_t source_line;       // line number in source file
    uint32_t kind_num_nodes;    // parse node kind, and number of nodes
    mp_parse_node_t nodes[];    // nodes
} mp_parse_node_struct_t;

// macros for mp_parse_node_t usage
// some of these evaluate their argument more than once

#define MP_PARSE_NODE_IS_NULL(pn) ((pn) == MP_PARSE_NODE_NULL)
#define MP_PARSE_NODE_IS_LEAF(pn) ((pn) & 3)
#define MP_PARSE_NODE_IS_STRUCT(pn) ((pn) != MP_PARSE_NODE_NULL && ((pn) & 3) == 0)
#define MP_PARSE_NODE_IS_STRUCT_KIND(pn, k) ((pn) != MP_PARSE_NODE_NULL && ((pn) & 3) == 0 && MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)(pn)) == (k))

#define MP_PARSE_NODE_IS_SMALL_INT(pn) (((pn) & 0x1) == MP_PARSE_NODE_SMALL_INT)
#define MP_PARSE_NODE_IS_ID(pn) (((pn) & 0x1f) == MP_PARSE_NODE_ID)
#define MP_PARSE_NODE_IS_TOKEN(pn) (((pn) & 0x1f) == MP_PARSE_NODE_TOKEN)
#define MP_PARSE_NODE_IS_TOKEN_KIND(pn, k) ((pn) == (MP_PARSE_NODE_TOKEN | ((k) << 5)))

#define MP_PARSE_NODE_LEAF_KIND(pn) ((pn) & 0x1f)
#define MP_PARSE_NODE_LEAF_ARG(pn) (((mp_uint_t)(pn)) >> 5)
#define MP_PARSE_NODE_LEAF_SMALL_INT(pn) (((mp_int_t)(pn)) >> 1)
#define MP_PARSE_NODE_STRUCT_KIND(pns) ((pns)->kind_num_nodes & 0xff)
#define MP_PARSE_NODE_STRUCT_NUM_NODES(pns) ((pns)->kind_num_nodes >> 8)

mp_parse_node_t mp_parse_node_new_leaf(mp_int_t kind, mp_int_t arg);
void mp_parse_node_free(mp_parse_node_t pn);

void mp_parse_node_print(mp_parse_node_t pn, mp_uint_t indent);

typedef enum {
    MP_PARSE_SINGLE_INPUT,
    MP_PARSE_FILE_INPUT,
    MP_PARSE_EVAL_INPUT,
} mp_parse_input_kind_t;

typedef enum {
    MP_PARSE_ERROR_MEMORY,
    MP_PARSE_ERROR_UNEXPECTED_INDENT,
    MP_PARSE_ERROR_UNMATCHED_UNINDENT,
    MP_PARSE_ERROR_INVALID_SYNTAX,
} mp_parse_error_kind_t;

// returns MP_PARSE_NODE_NULL on error, and then parse_error_kind_out is valid
mp_parse_node_t mp_parse(struct _mp_lexer_t *lex, mp_parse_input_kind_t input_kind, mp_parse_error_kind_t *parse_error_kind_out);

#endif // __MICROPY_INCLUDED_PY_PARSE_H__


text:
package com.wandrell.example.mule.wss.testing.integration.client.cxf.unsecure;

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;

import com.wandrell.example.mule.wss.testing.util.config.context.ClientContextPaths;
import com.wandrell.example.mule.wss.testing.util.config.properties.ClientSimplePropertiesPaths;
import com.wandrell.example.mule.wss.testing.util.test.integration.client.AbstractITClientFlow;

/**
 * Integration tests for an unsecure simple client flow testing that it handles
 * messages correctly.
 *
 * @author Bernardo Martínez Garrido
 */
@ContextConfiguration(ClientContextPaths.UNSECURE)
@TestPropertySource({ ClientSimplePropertiesPaths.UNSECURE })
public final class ITUnsecureClientSimple extends AbstractITClientFlow {

    /**
     * Default constructor.
     */
    public ITUnsecureClientSimple() {
        super();
    }
}


text:
package org.apache.drill.exec.physical.base;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.exec.proto.CoordinationProtos;
import org.apache.drill.shaded.guava.com.google.common.base.Preconditions;

import java.util.List;

/**
 *  The type of scan operator, which allows to scan schemaless tables ({@link org.apache.drill.exec.planner.logical.DynamicDrillTable} with null selection)
 */
@JsonTypeName("schemaless-scan")
public class SchemalessScan extends AbstractFileGroupScan implements SubScan {

  private final String selectionRoot;

  @JsonCreator
  public SchemalessScan(@JsonProperty("userName") String userName,
                        @JsonProperty("selectionRoot") String selectionRoot) {
    super(userName);
    this.selectionRoot = selectionRoot;
  }

  public SchemalessScan(final SchemalessScan that) {
    super(that);
    this.selectionRoot = that.selectionRoot;
  }

  @JsonProperty
  public String getSelectionRoot() {
    return selectionRoot;
  }

  @Override
  public void applyAssignments(List<CoordinationProtos.DrillbitEndpoint> endpoints) {
  }

  @Override
  public SubScan getSpecificScan(int minorFragmentId) {
    return this;
  }

  @Override
  public int getMaxParallelizationWidth() {
    return 1;
  }

  @Override
  public String getDigest() {
    return toString();
  }

  @Override
  public String toString() {
    String pattern = "SchemalessScan [selectionRoot = %s]";
    return String.format(pattern, selectionRoot);
  }

  @Override
  public PhysicalOperator getNewWithChildren(List<PhysicalOperator> children) {
    Preconditions.checkArgument(children.isEmpty());
    return new SchemalessScan(this);
  }

  @Override
  public GroupScan clone(List<SchemaPath> columns) {
    return this;
  }

  @Override
  public ScanStats getScanStats() {
    return ScanStats.ZERO_RECORD_TABLE;
  }

  @Override
  public boolean supportsPartitionFilterPushdown() {
    return false;
  }

}


text:
@interface LoadingButton()

@property (nonatomic, strong) UIActivityIndicatorView * loader;
@property (nonatomic, strong) UIImage * originalImage;
@property (nonatomic, assign) BOOL wasUserInteractionEnabled;
@property (nonatomic, assign) BOOL wasEnabled;

@end

//################################################################################
@implementation LoadingButton

//################################################################################
- (void) showLoader
{
    [self showLoaderWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
}

//################################################################################
- (void) showLoaderWithActivityIndicatorStyle:(UIActivityIndicatorViewStyle)style
{
    if (self.loader) return;

    UIButton * button = self;

    self.wasEnabled = self.enabled;
    self.wasUserInteractionEnabled = self.userInteractionEnabled;

    button.userInteractionEnabled = NO;
    button.enabled = NO;

    self.originalImage = self.currentImage;

    UIActivityIndicatorView * loader = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style];
    self.loader = loader;

    loader.hidesWhenStopped = NO;
    [loader startAnimating];
    [button addSubview:loader];

    // stub image for remove setted image
    UIColor * stubColor = [UIColor clearColor];
    CGSize size = loader.frame.size;

    // cuter inset
    size.width  *= 1.5;
    size.height *= 1.5;

    UIImage * stubImage = [UIImage imageWithColor:stubColor size:size];
    [button setImage:stubImage forState:UIControlStateNormal];

    // centersize
    CGRect rect = button.imageView.frame;
    CGPoint center = CGPointMake(
                                 rect.origin.x + rect.size.width/2,
                                 rect.origin.y + rect.size.height/2
                                 );
    [loader setCenter:center];
}

//################################################################################
- (void) hideLoader
{
    UIButton * button = self;

    button.enabled = self.wasEnabled;
    button.userInteractionEnabled = self.wasUserInteractionEnabled;

    UIImage * originalImage = self.originalImage;
    [button setImage:originalImage forState:UIControlStateNormal];
    self.originalImage = nil;

    [self.loader removeFromSuperview];
    self.loader = nil;
}

//################################################################################
@end
//################################################################################


text:
Shard of Chaos

**School** evocation [chaos]; **Level** cleric 2

**Casting Time** 1 standard action

**Components** V, S, DF

**Range** close (25 ft. + 5 ft./2 levels)

**Effect** dart-shaped projectile of chaotic energy

**Duration** instantaneous (1d6 rounds)

**Saving Throw** Will partial (see text); **Spell Resistance** yes

You hurl a multicolored shard of congealed chaos from your holy symbol, affecting any one target in range as a ranged touch attack.

A lawful creature struck by the shard takes 1d8 points of damage per two caster levels (maximum 5d8). A lawful outsider instead takes 1d6 points of damage per caster level (maximum 10d6) and is slowed (as _ [slow](spells/slow#_slow)_) for 1 round. A successful Will save reduces the damage to half and negates the slow effect. The bolt has no effect on chaotic creatures. This spell deals only half damage to creatures that are neither lawful nor chaotic, and they are not slowed.


text:
from __future__ import absolute_import, print_function, division

import re

import collections
import six
from netlib import multidict
from netlib import strutils

# See also: http://lucumr.pocoo.org/2013/7/2/the-updated-guide-to-unicode/

if six.PY2:  # pragma: no cover
    def _native(x):
        return x

    def _always_bytes(x):
        return x
else:
    # While headers _should_ be ASCII, it's not uncommon for certain headers to be utf-8 encoded.
    def _native(x):
        return x.decode("utf-8", "surrogateescape")

    def _always_bytes(x):
        return strutils.always_bytes(x, "utf-8", "surrogateescape")

class Headers(multidict.MultiDict):
    """
    Header class which allows both convenient access to individual headers as well as
    direct access to the underlying raw data. Provides a full dictionary interface.

    Example:

    .. code-block:: python

        # Create headers with keyword arguments
        >>> h = Headers(host="example.com", content_type="application/xml")

        # Headers mostly behave like a normal dict.
        >>> h["Host"]
        "example.com"

        # HTTP Headers are case insensitive
        >>> h["host"]
        "example.com"

        # Headers can also be created from a list of raw (header_name, header_value) byte tuples
        >>> h = Headers([
            (b"Host",b"example.com"),
            (b"Accept",b"text/html"),
            (b"accept",b"application/xml")
        ])

        # Multiple headers are folded into a single header as per RFC7230
        >>> h["Accept"]
        "text/html, application/xml"

        # Setting a header removes all existing headers with the same name.
        >>> h["Accept"] = "application/text"
        >>> h["Accept"]
        "application/text"

        # bytes(h) returns a HTTP1 header block.
        >>> print(bytes(h))
        Host: example.com
        Accept: application/text

        # For full control, the raw header fields can be accessed
        >>> h.fields

    Caveats:
        For use with the "Set-Cookie" header, see :py:meth:`get_all`.
    """

    def __init__(self, fields=(), **headers):
        """
        Args:
            fields: (optional) list of ``(name, value)`` header byte tuples,
                e.g. ``[(b"Host", b"example.com")]``. All names and values must be bytes.
            **headers: Additional headers to set. Will overwrite existing values from `fields`.
                For convenience, underscores in header names will be transformed to dashes -
                this behaviour does not extend to other methods.
                If ``**headers`` contains multiple keys that have equal ``.lower()`` s,
                the behavior is undefined.
        """
        super(Headers, self).__init__(fields)

        for key, value in self.fields:
            if not isinstance(key, bytes) or not isinstance(value, bytes):
                raise TypeError("Header fields must be bytes.")

        # content_type -> content-type
        headers = {
            _always_bytes(name).replace(b"_", b"-"): _always_bytes(value)
            for name, value in six.iteritems(headers)
        }
        self.update(headers)

    @staticmethod
    def _reduce_values(values):
        # Headers can be folded
        return ", ".join(values)

    @staticmethod
    def _kconv(key):
        # Headers are case-insensitive
        return key.lower()

    def __bytes__(self):
        if self.fields:
            return b"\r\n".join(b": ".join(field) for field in self.fields) + b"\r\n"
        else:
            return b""

    if six.PY2:  # pragma: no cover
        __str__ = __bytes__

    def __delitem__(self, key):
        key = _always_bytes(key)
        super(Headers, self).__delitem__(key)

    def __iter__(self):
        for x in super(Headers, self).__iter__():
            yield _native(x)

    def get_all(self, name):
        """
        Like :py:meth:`get`, but does not fold multiple headers into a single one.
        This is useful for Set-Cookie headers, which do not support folding.
        See also: https://tools.ietf.org/html/rfc7230#section-3.2.2
        """
        name = _always_bytes(name)
        return [
            _native(x) for x in
            super(Headers, self).get_all(name)
        ]

    def set_all(self, name, values):
        """
        Explicitly set multiple headers for the given key.
        See: :py:meth:`get_all`
        """
        name = _always_bytes(name)
        values = [_always_bytes(x) for x in values]
        return super(Headers, self).set_all(name, values)

    def insert(self, index, key, value):
        key = _always_bytes(key)
        value = _always_bytes(value)
        super(Headers, self).insert(index, key, value)

    def items(self, multi=False):
        if multi:
            return (
                (_native(k), _native(v))
                for k, v in self.fields
            )
        else:
            return super(Headers, self).items()

    def replace(self, pattern, repl, flags=0):
        """
        Replaces a regular expression pattern with repl in each "name: value"
        header line.

        Returns:
            The number of replacements made.
        """
        if isinstance(pattern, six.text_type):
            pattern = strutils.escaped_str_to_bytes(pattern)
        if isinstance(repl, six.text_type):
            repl = strutils.escaped_str_to_bytes(repl)
        pattern = re.compile(pattern, flags)
        replacements = 0

        fields = []
        for name, value in self.fields:
            line, n = pattern.subn(repl, name + b": " + value)
            try:
                name, value = line.split(b": ", 1)
            except ValueError:
                # We get a ValueError if the replacement removed the ": "
                # There's not much we can do about this, so we just keep the header as-is.
                pass
            else:
                replacements += n
            fields.append((name, value))
        self.fields = tuple(fields)
        return replacements

def parse_content_type(c):
    """
        A simple parser for content-type values. Returns a (type, subtype,
        parameters) tuple, where type and subtype are strings, and parameters
        is a dict. If the string could not be parsed, return None.

        E.g. the following string:

            text/html; charset=UTF-8

        Returns:

            ("text", "html", {"charset": "UTF-8"})
    """
    parts = c.split(";", 1)
    ts = parts[0].split("/", 1)
    if len(ts) != 2:
        return None
    d = collections.OrderedDict()
    if len(parts) == 2:
        for i in parts[1].split(";"):
            clause = i.split("=", 1)
            if len(clause) == 2:
                d[clause[0].strip()] = clause[1].strip()
    return ts[0].lower(), ts[1].lower(), d

def assemble_content_type(type, subtype, parameters):
    if not parameters:
        return "{}/{}".format(type, subtype)
    params = "; ".join(
        "{}={}".format(k, v)
        for k, v in parameters.items()
    )
    return "{}/{}; {}".format(
        type, subtype, params
    )


text:
"""Factory methods for epinet derived from resnet."""

import dataclasses
from typing import Callable, Optional, Sequence

from enn.checkpoints import base as checkpoints_base
from enn.checkpoints import epinet as checkpoints_epinet
from enn.networks import base as networks_base
from enn.networks import priors as enn_priors
from enn.networks.epinet import base as epinet_base
from enn.networks.epinet import last_layer
from enn.networks.epinet import priors

PriorFnCtor = Callable[[], enn_priors.PriorFn]

@dataclasses.dataclass
class ResnetFinalEpinetConfig:
  """Configuration options for ResNet + final layer MLP epinet."""
  base_checkpoint: checkpoints_base.EnnCheckpoint
  index_dim: int
  num_classes: int
  epinet_hiddens: Sequence[int]
  prior_epinet_hiddens: Optional[Sequence[int]] = None
  base_logits_scale: float = 1
  epi_prior_scale: float = 1
  add_prior_scale: float = 1
  prior_fn_ctor: Optional[PriorFnCtor] = None
  freeze_base: bool = True
  parse_hidden: epinet_base.BaseHiddenParser = last_layer.parse_base_hidden
  seed: int = 23

class ResnetFinalEpinet(networks_base.EnnArray):
  """ResNet + final layer MLP epinet."""

  def __init__(self, config: ResnetFinalEpinetConfig):
    epinet_pieces = _make_enn_from_config(config)
    enn = epinet_pieces.enn
    super().__init__(enn.apply, enn.init, enn.indexer)

def make_checkpoint_from_config(
    name: str,
    load_fn: checkpoints_base.ParamsStateLoadFn,
    config: ResnetFinalEpinetConfig,
    tuned_eval_temperature: Optional[float] = None,
) -> checkpoints_epinet.EpinetCheckpoint:
  """Returns an EpinetCheckpoint from ResnetFinalEpinetConfig.

  Args:
    name: string identifier for checkpoint.
    load_fn: gives params, state for epinet. Base network init from base_cpt.
    config: ResnetFinalEpinetConfig, which includes base_cpt as component.
    tuned_eval_temperature: Optional temperature rescaling for evaluation.
  """
  return checkpoints_epinet.EpinetCheckpoint(
      name=name,
      load_fn=load_fn,
      epinet_ctor=lambda: _make_enn_from_config(config).epinet,
      parse_hidden=config.parse_hidden,
      base_cpt=config.base_checkpoint,
      base_scale=config.base_logits_scale,
      tuned_eval_temperature=tuned_eval_temperature,
  )

@dataclasses.dataclass
class _EpinetPieces:
  """Wraps the key components necessary to create either ENN or checkpoint."""
  enn: networks_base.EnnArray  # Entire network (base+epi).
  epinet: epinet_base.EpinetWithState  # Epinet applied on top of base net.

def _make_enn_from_config(config: ResnetFinalEpinetConfig) -> _EpinetPieces:
  """Wires together the epinet."""
  # Make the last layer epinet
  epinet = last_layer.MLPEpinetWithPrior(
      index_dim=config.index_dim,
      num_classes=config.num_classes,
      epinet_hiddens=config.epinet_hiddens,
      prior_epinet_hiddens=config.prior_epinet_hiddens,
      prior_scale=config.epi_prior_scale,
      drop_inputs=True,
  )

  if config.prior_fn_ctor:
    # Form the extra additive prior functions
    prior_fn = config.prior_fn_ctor()

    # Combined epinet is epinet_head with additive prior
    epinet = priors.combine_epinet_and_prior(
        epinet, prior_fn, config.add_prior_scale)

  # Form the ENN by combining them all
  enn = epinet_base.combine_base_epinet_as_enn(
      base_checkpoint=config.base_checkpoint,
      epinet=epinet,
      parse_hidden=config.parse_hidden,
      base_scale=config.base_logits_scale,
      freeze_base=config.freeze_base,
  )

  return _EpinetPieces(enn, epinet)


text:
package com.amazonaws.services.mainframemodernization.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.mainframemodernization.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * AlternateKeyMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class AlternateKeyMarshaller {

    private static final MarshallingInfo<Boolean> ALLOWDUPLICATES_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("allowDuplicates").build();
    private static final MarshallingInfo<Integer> LENGTH_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("length").build();
    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("name").build();
    private static final MarshallingInfo<Integer> OFFSET_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("offset").build();

    private static final AlternateKeyMarshaller instance = new AlternateKeyMarshaller();

    public static AlternateKeyMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(AlternateKey alternateKey, ProtocolMarshaller protocolMarshaller) {

        if (alternateKey == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(alternateKey.getAllowDuplicates(), ALLOWDUPLICATES_BINDING);
            protocolMarshaller.marshall(alternateKey.getLength(), LENGTH_BINDING);
            protocolMarshaller.marshall(alternateKey.getName(), NAME_BINDING);
            protocolMarshaller.marshall(alternateKey.getOffset(), OFFSET_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}