text:
////////////////////////////////////////////////////////////////////////////////
// Please see packet.h for details.
////////////////////////////////////////////////////////////////////////////////

#include "network/packet.h"
#include <arpa/inet.h>
#include <google/protobuf/message.h>
#include <string>
#include "glog/logging.h"
#include "network/regevent.h"

// PacketHeader static methods
void PacketHeader::set_packet_size(unsigned char* header, sp_uint32 _size) {
  sp_uint32 network_order = htonl(_size);
  memcpy(header, &network_order, sizeof(sp_uint32));
}

sp_uint32 PacketHeader::get_packet_size(const char* header) {
  sp_uint32 network_order = *(reinterpret_cast<const sp_uint32*>(header));
  return ntohl(network_order);
}

sp_uint32 PacketHeader::header_size() { return kSPPacketSize; }

// Constructor of the IncomingPacket. We only create the header buffer.
IncomingPacket::IncomingPacket(sp_uint32 _max_packet_size) {
  max_packet_size_ = _max_packet_size;
  position_ = 0;
  // bzero(header_, PacketHeader::size());
  data_ = NULL;
}

// Construct an incoming from a raw data buffer - used for tests only
IncomingPacket::IncomingPacket(unsigned char* _data) {
  memcpy(header_, _data, PacketHeader::header_size());
  data_ = new char[PacketHeader::get_packet_size(header_)];
  memcpy(data_, _data + PacketHeader::header_size(), PacketHeader::get_packet_size(header_));
  position_ = 0;
}

IncomingPacket::~IncomingPacket() { delete[] data_; }

sp_int32 IncomingPacket::UnPackInt(sp_int32* i) {
  if (data_ == NULL) return -1;
  if (position_ + sizeof(sp_int32) > PacketHeader::get_packet_size(header_)) return -1;
  sp_int32 network_order;
  memcpy(&network_order, data_ + position_, sizeof(sp_int32));
  position_ += sizeof(sp_int32);
  *i = ntohl(network_order);
  return 0;
}

sp_int32 IncomingPacket::UnPackString(sp_string* i) {
  sp_int32 size = 0;
  if (UnPackInt(&size) != 0) return -1;
  if (position_ + size > PacketHeader::get_packet_size(header_)) return -1;
  *i = std::string(data_ + position_, size);
  position_ += size;
  return 0;
}

sp_int32 IncomingPacket::UnPackProtocolBuffer(google::protobuf::Message* _proto) {
  sp_int32 sz;
  if (UnPackInt(&sz) != 0) return -1;
  if (position_ + sz > PacketHeader::get_packet_size(header_)) return -1;
  if (!_proto->ParsePartialFromArray(data_ + position_, sz)) return -1;
  position_ += sz;
  return 0;
}

sp_int32 IncomingPacket::UnPackREQID(REQID* _rid) {
  if (position_ + REQID_size > PacketHeader::get_packet_size(header_)) return -1;
  _rid->assign(std::string(data_ + position_, REQID_size));
  position_ += REQID_size;
  return 0;
}

sp_uint32 IncomingPacket::GetTotalPacketSize() const {
  return PacketHeader::get_packet_size(header_) + kSPPacketSize;
}

void IncomingPacket::Reset() { position_ = 0; }

sp_int32 IncomingPacket::Read(struct bufferevent* _buf) {
  if (data_ == NULL) {
    // We are still reading the header
    sp_int32 read_status =
        InternalRead(_buf, header_, PacketHeader::header_size());

    if (read_status != 0) {
      // Header read is either partial or had an error
      return read_status;
    } else {
      // Header just completed - some sanity checking of the header
      if (max_packet_size_ != 0 && PacketHeader::get_packet_size(header_) > max_packet_size_) {
        // Too large packet
        LOG(ERROR) << "Too large packet size " << PacketHeader::get_packet_size(header_)
                   << ". We only accept packet sizes <= " << max_packet_size_ << "\n";

        return -1;
      } else {
        // Create the data
        data_ = new char[PacketHeader::get_packet_size(header_)];

        // bzero(data_, PacketHeader::get_packet_size(header_));
        // reset the position to refer to the data_
      }
    }
  }

  // The header has been completely read. Read the data
  sp_int32 retval =
      InternalRead(_buf, data_, PacketHeader::get_packet_size(header_));
  if (retval == 0) {
    // Successfuly read the packet.
    position_ = 0;
  }

  return retval;
}

sp_int32 IncomingPacket::InternalRead(struct bufferevent* _buf, char* _buffer, sp_uint32 _size) {
  if (evbuffer_get_length(bufferevent_get_input(_buf)) < _size) {
    // We dont have all the data needed
    return 1;
  }
  int removed = evbuffer_remove(bufferevent_get_input(_buf), _buffer, _size);
  if (removed != _size) {
    LOG(ERROR) << "evbuffer remove failed. Expected to remove " << _size
               << " but removed only " << removed;
    return -1;
  }
  return 0;
}

OutgoingPacket::OutgoingPacket(sp_uint32 _packet_size) {
  total_packet_size_ = _packet_size + PacketHeader::header_size();
  buffer_ = evbuffer_new();
  struct evbuffer_iovec iovec;
  CHECK_EQ(evbuffer_reserve_space(buffer_, total_packet_size_, &iovec, 1), 1);
  underlying_data_ = (unsigned char*) iovec.iov_base;
  PacketHeader::set_packet_size(underlying_data_, _packet_size);
  position_ = PacketHeader::header_size();
}

OutgoingPacket::~OutgoingPacket() {
  if (buffer_) {
    evbuffer_free(buffer_);
  }
}

sp_uint32 OutgoingPacket::GetTotalPacketSize() const { return total_packet_size_; }

sp_uint32 OutgoingPacket::GetBytesFilled() const { return position_; }

sp_uint32 OutgoingPacket::GetBytesLeft() const { return total_packet_size_ - position_; }

sp_int32 OutgoingPacket::PackInt(const sp_int32& i) {
  if (sizeof(sp_int32) + position_ > total_packet_size_) {
    return -1;
  }
  sp_int32 network_order = htonl(i);
  memcpy(underlying_data_ + position_, &network_order, sizeof(sp_int32));
  position_ += sizeof(sp_int32);
  return 0;
}

sp_uint32 OutgoingPacket::SizeRequiredToPackProtocolBuffer(sp_int32 _byte_size) {
  return sizeof(sp_int32) + _byte_size;
}

sp_int32 OutgoingPacket::PackProtocolBuffer(const google::protobuf::Message& _proto,
                                            sp_int32 _byte_size) {
  if (PackInt(_byte_size) != 0) return -1;
  if (_byte_size + position_ > total_packet_size_) {
    return -1;
  }
  if (!_proto.SerializeWithCachedSizesToArray((underlying_data_ + position_))) {
    return -1;
  }
  position_ += _byte_size;
  return 0;
}

sp_int32 OutgoingPacket::PackProtocolBuffer(const char* _message,
                                            sp_int32 _byte_size) {
  if (PackInt(_byte_size) != 0) return -1;
  if (_byte_size + position_ > total_packet_size_) {
    return -1;
  }

  memcpy(underlying_data_ + position_, _message, _byte_size);
  position_ += _byte_size;
  return 0;
}

sp_int32 OutgoingPacket::PackREQID(const REQID& _rid) {
  if (REQID_size + position_ > total_packet_size_) {
    return -1;
  }
  memcpy(underlying_data_ + position_, _rid.c_str(), REQID_size);
  position_ += REQID_size;
  return 0;
}

sp_uint32 OutgoingPacket::SizeRequiredToPackString(const std::string& _input) {
  return sizeof(sp_uint32) + _input.size();
}

sp_int32 OutgoingPacket::PackString(const sp_string& i) {
  if (sizeof(sp_uint32) + i.size() + position_ > total_packet_size_) {
    return -1;
  }
  PackInt(i.size());
  memcpy(underlying_data_ + position_, i.c_str(), i.size());
  position_ += i.size();
  return 0;
}

struct evbuffer* OutgoingPacket::release_buffer() {
  struct evbuffer_iovec iovec;
  iovec.iov_base = underlying_data_;
  iovec.iov_len = total_packet_size_;
  CHECK_EQ(evbuffer_commit_space(buffer_, &iovec, 1), 0);
  auto retval = buffer_;
  buffer_ = NULL;
  underlying_data_ = NULL;
  position_ = 0;
  return retval;
}


text:
package specialite.arme.attaque;

import perso.AbstractPerso;
import ressources.sprites.animation.sequence.Animations;
import ressources.sprites.animation.sequence.Sequence;
import specialite.arme.projectile.Boulet;

public class ActionTirMortier extends ActionTir {
    private final Boulet boulet;

    public ActionTirMortier(AbstractPerso source) {
	super(source, 20, 21);
	boulet = new Boulet(source, this);
    }

    @Override
    public Sequence getSequence() {
	Sequence s = Animations.getInstance().getSequence("tir arc", false);
	s.setSequenceur(this);
	return s;
    }

    @Override
    public void commence() {
	super.commence();
	getSource().getAnimation().setVitesse(100);
    }

    @Override
    public Boulet getProjectile() {
	return boulet;
    }

}

redpajama_set_name: RedPajamaGithub


text:
@class ParkingSpot;

@interface WKInterfaceMap (SPM)

- (void)SPMSetCurrentParkingSpot:(nonnull ParkingSpot *)parkingSpot;

@end


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 7.6.1-4-15
description: >
    Allow reserved words as property names by set function within an
    object, verified with hasOwnProperty: package, protected, static
---*/

        var test0 = 0, test1 = 1, test2 = 2;
        var tokenCodes  = {
            set package(value){
                test0 = value;
            },
            get package(){
                return test0;
            },
            set protected(value){
                test1 = value;
            },
            get protected(){
                return test1
            },
            set static(value){
                test2 = value;
            },
            get static(){
                return test2;
            }
        };
        var arr = [
            'package',
            'protected',
            'static'
            ];
        for(var p in tokenCodes) {
            for(var p1 in arr) {
                if(arr[p1] === p) {
                    assert(tokenCodes.hasOwnProperty(arr[p1]), 'tokenCodes.hasOwnProperty(arr[p1]) !== true');
                }
            }
        }


text:
<md-dialog aria-label="Mango (Fruit)"  ng-cloak>
  <form>
    <md-toolbar>

Players

        <md-button class="md-icon-button" ng-click="cancel()">
          <md-icon md-svg-src="assets/img/icons/ic_close_24px.svg" aria-label="Close dialog"></md-icon>
        </md-button>

    </md-toolbar>
    <md-dialog-content>

          <md-list-item class="md-4-line" ng-repeat="player in $root.players" layout="row" layout-align="start center" layout-padding>

{{player.name}}

{{player.dateOfBirth}}

          </md-list-item>

    </md-dialog-content>
    <md-dialog-actions layout="row">

      <md-button ng-click="answer('useful')" style="margin-right:20px;">
        Ok
      </md-button>
    </md-dialog-actions>
  </form>
</md-dialog>


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\RevenueItem */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'id')->textInput() ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'create_time')->textInput() ?>

    <?= $form->field($model, 'update_time')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
'use strict';
module.exports = Number.isFinite || function (val) {
	// Number.isNaN() => val !== val
	if (typeof val !== 'number' || val !== val || val === Infinity || val === -Infinity) {
		return false;
	}

	return true;
};


text:
vb2Py - With
============

Contents of this page:

* General_
* `Default Conversion`_
* `List of Options`_

Specific options:

* EvaluateVariable_
* WithVariablePrefix_
* UseNumericIndex_

General
-------

In VB, ``With`` blocks represent a shorthand for refering to a specific object. Properties and methods of the object can be referenced by just prefixing the name with a '.' and the base object name is infered from the context. Python has no such equivalent and therefore the objects must be written out in full. By default, a ``with`` variable is created and this is used to fully qualify the references. This is *safe* in cases where evaluation of the ``With`` object is expensive [1]_ but may make the code look less clear. To get around this, an option is avaialble to use the actual variable name.

Default Conversion
------------------

VB::

    With MyObject
        .Height = 10
        .Width = .Height * .ScaleFactor
    End With

List of Options
---------------

Here are the options in the INI file::

    [With]
    # Once or EachTime, how many times to evaluate the with variable
    EvaluateVariable = Once
    # Name of with variable (only used if EvaluateVariable is Once)
    WithVariablePrefix = _with
    # Yes or No, use numeric index on with variable (needed if you every have nested Withs and EvaluateVariable = Once)
    UseNumericIndex = Yes

EvaluateVariable
~~~~~~~~~~~~~~~~

Syntax: ``EvaluateVariable = Once | EveryTime``

The default behaviour is to evaluate the ``With`` object once at the start of the block. By setting this option to ``EachTime`` you can force the object to be evaluated each time it is required. This generally looks more natural but can lead to undesired side effects or slow run times depending on how expensive [1]_ the object is to calculate.

VB::

    ' VB2PY-Set: With.EvaluateVariable = EveryTime
    With MyObject
        .Height = 10
        .Width = .Height * .ScaleFactor
    End With
    ' VB2PY-Unset: With.EvaluateVariable

WithVariablePrefix
~~~~~~~~~~~~~~~~~~~~

Syntax: ``WithVariablePrefix = name``

When EvaluateVariable_ is set to ``Once``, this option determines the prefix used to name the variable used in the ``With``. If UseNumericIndex_ is set to ``No`` then this option sets the variable name used, otherwise this is the prefix and the final variable will also include a unique ID number.

VB::

    ' VB2PY-Set: With.WithVariablePrefix = withVariable
    With MyObject
        .Height = 10
        .Width = .Height * .ScaleFactor
    End With
    ' VB2PY-Unset: With.WithVariablePrefix

UseNumericIndex
~~~~~~~~~~~~~~~

Syntax: ``UseNumericIndex = Yes | No``

When EvaluateVariable_ is set to ``Once``, this option determines whether a unique ID number is appended to the WithVariablePrefix_ to determine the variable name used to hold the object. If used, the index is incremented for each ``With`` constuct found. This option is always required to be ``Yes`` where the code includes nested ``With`` blocks *and* EvaluateVariable_ is set to ``Once``. If neither of these conditions applies then it is safe to set this to ``No``

VB::

    ' VB2PY-Set: With.UseNumericIndex = No
    With MyObject
        .Height = 10
        .Width = .Height * .ScaleFactor
    End With
    ' VB2PY-Unset: With.UseNumericIndex

--------------

.. [1] Expensive as in CPU time.


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

	<item
		android:id="@+id/search"
		android:actionViewClass="android.widget.SearchView"
		android:icon="@drawable/ic_action_search"
		android:showAsAction="ifRoom|collapseActionView"
		android:title="@string/filter">
	</item>

</menu>


text:
package code.util

import java.time.format.TextStyle
import java.time.temporal.WeekFields
import java.time.{DayOfWeek, Month}

import com.ibm.icu.text.DateTimePatternGenerator
import net.liftweb.http.S
import net.liftweb.http.js.JE.{JsObj, _}
import net.liftweb.http.js.JsObj
import org.joda.time.{LocalDate, YearMonth}

protected object Localization {
  def pattern(skeleton: String): String =
    DateTimePatternGenerator.getInstance(S.locale).getBestPattern(skeleton)

  def dates: JsObj = {
    val days = DayOfWeek.values().toList span (_ != DayOfWeek.SUNDAY) match {
      case (end, start) => start ++ end
    }
    val months = Month.values().toList

    JsObj(
      "weekStart" -> Num((WeekFields.of(S.locale).getFirstDayOfWeek.getValue + 1) % 7 - 1),
      "months" -> JsArray(months map (_.getDisplayName(TextStyle.FULL, S.locale)) map Str),
      "monthsShort" -> JsArray(months map (_.getDisplayName(TextStyle.SHORT, S.locale)) map Str),
      "days" -> JsArray(days map (_.getDisplayName(TextStyle.FULL, S.locale)) map Str),
      "daysShort" -> JsArray(days map (_.getDisplayName(TextStyle.SHORT, S.locale)) map Str),
      "daysMin" -> JsArray(days map (_.getDisplayName(TextStyle.NARROW, S.locale)) map Str)
    )
  }
}

object DatePicker {

  def apply(input: String, alt: String, date: LocalDate): JsRaw = JsRaw(
    s"""
      | var prevDateValue = null;
      | $$('.date-picker').focus(function(e) {
      |   prevDateValue = $$('.date-picker').val();
      | });
      | $$('.date-picker').blur(function(e) {
      |   $$('.date-picker').val(prevDateValue);
      | });
      | $$.fn.datepicker.dates['${S.locale.getLanguage}'] = ${Localization.dates.toString()};
      | $$('$input').datepicker(${configuration(input, date).toString()}).on('changeDate', function(e) {
      |   $$('$alt').val($$.format.date(e.date, 'yyyy-MM-dd'));
      |   $$('$alt').closest('form').submit();
      | });
    """.stripMargin
  )

  private def configuration(input: String, date: LocalDate): JsObj = {
    val format = Localization.pattern("yyyyMMdd")

    JsObj(
      "format" -> JsObj(
        "toDisplay" -> JsRaw(s"function(date, f, l) { return $$.format.date(date, '$format'); }"),
        "toValue" -> JsRaw("function(date, f, l) { return date; }")
      ),
      "defaultViewDate" -> JsObj(
        "year" -> Num(date.getYear),
        "month" -> Num(date.getMonthOfYear - 1),
        "day" -> Num(date.getDayOfMonth)
      ),
      "beforeShowDay" -> JsRaw(
        s"""
           | function(date) {
           |    if (date.getFullYear() === ${date.getYear} && date.getMonth() === (${date.getMonthOfYear} - 1) && date.getDate() === ${date.getDayOfMonth}) {
           |      $$('$input').val($$.format.date(date, '$format'));
           |      return { classes: 'active' };
           |      } else return {};
           | }
       """.stripMargin
      ),
      "todayHighlight" -> JsTrue,
      "endDate" -> JsRaw("new Date()"),
      "startView" -> Num(0),
      "minViewMode" -> Num(0),
      "maxViewMode" -> Num(2),
      "autoclose" -> JsTrue,
      "language" -> Str(S.locale.getLanguage)
    )
  }
}

object MonthPicker {

  def apply(input: String, alt: String, date: YearMonth): JsRaw = JsRaw(
    s"""
       | var prevDateValue = null;
       | $$('.date-picker').focus(function(e) {
       |   prevDateValue = $$('.date-picker').val();
       | });
       | $$('.date-picker').blur(function(e) {
       |   $$('.date-picker').val(prevDateValue);
       | });
       | $$.fn.datepicker.dates['${S.locale.getLanguage}'] = ${Localization.dates.toString()};
       | $$('$input').datepicker(${configuration(input, date).toString()}).on('changeDate', function(e) {
       |   $$('$alt').val($$.format.date(e.date, 'yyyy-MM-dd'));
       |   $$('$alt').closest('form').submit();
       | });
    """.stripMargin
  )

  private def configuration(input: String, date: YearMonth): JsObj = {
    val format = Localization.pattern("yyyyMM")

    JsObj(
      "format" -> JsObj(
        "toDisplay" -> JsRaw(s"function(date, f, l) { return $$.format.date(date, '$format'); }"),
        "toValue" -> JsRaw("function(date, f, l) { return date; }")
      ),
      "defaultViewDate" -> JsObj(
        "year" -> Num(date.getYear),
        "month" -> Num(date.getMonthOfYear - 1)
      ),
      "beforeShowMonth" -> JsRaw(
        s"""
           | function(date) {
           |    if (date.getFullYear() === ${date.getYear} && date.getMonth() === (${date.getMonthOfYear} - 1)) {
           |      $$('$input').val($$.format.date(date, '$format'));
           |      return { classes: 'active' };
           |    } else return {};
           | }
       """.stripMargin
      ),
      "todayHighlight" -> JsTrue,
      "endDate" -> JsRaw("new Date()"),
      "startView" -> Num(1),
      "minViewMode" -> Num(1),
      "maxViewMode" -> Num(2),
      "autoclose" -> JsTrue,
      "language" -> Str(S.locale.getLanguage)
    )
  }
}


text:
Sistema automatico per produzione infografiche partendo da dati calcistici.

Progetto Multimedia e Tecnologie Interattive - Informatica UniBo

### Antonio Falcone

antonio.falcone89@gmail.com

### Pietro Adduci

pietro.adduci@icloud.com


text:
package org.jaewanyun.plasmidplanner.gui;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

public final class ProgressPanel extends JPanel implements ActionListener {

	private static final long serialVersionUID = 1L;
	private static int maxQueueSize = 100;
	private static HashMap<JButton, Integer> stopButtonAndIdentification;
	private static HashMap<Integer, JPanel> identificationAndPanel;
	private static HashMap<Integer, JProgressBar> identificationAndProgressBar;
	private static HashMap<Integer, JLabel> identificationAndLabel;
	private static HashMap<Integer, Integer> identificationAndProgress;
	private static HashMap<Integer, String> identificationAndDescription;
	@SuppressWarnings("rawtypes")
	private static HashMap<Integer, SwingWorker> identificationAndSwingWorker;
	private static HashSet<Integer> identifications;
	private static ProgressPanel progressPanel;

	private ProgressPanel() {
		super();
		//		super(new FlowLayout(FlowLayout.LEADING));
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

		identifications = new HashSet<>();
		stopButtonAndIdentification = new HashMap<>();
		identificationAndPanel = new HashMap<>();
		identificationAndProgressBar = new HashMap<>();
		identificationAndLabel = new HashMap<>();
		identificationAndProgress = new HashMap<>();
		identificationAndDescription = new HashMap<>();
		identificationAndSwingWorker = new HashMap<>();

		JPanel defaultPanel = new JPanel();
		defaultPanel.setBackground(GUIsettings.progressBarColor);
		defaultPanel.setBorder(BorderFactory.createEmptyBorder());
		add(defaultPanel);

		setBackground(GUIsettings.progressBarColor);
		setBorder(BorderFactory.createEmptyBorder());
	}

	static ProgressPanel getProgressPanel() {
		return progressPanel == null ? progressPanel = new ProgressPanel(): progressPanel;
	}

	public static synchronized int createTask(String description, int max, @SuppressWarnings("rawtypes") SwingWorker worker) {
		Integer id = getUniqueID();

		JPanel panel = new JPanel((new FlowLayout(FlowLayout.LEADING)));
		panel.setBackground(GUIsettings.tabBackgroundColor);
		panel.setBorder(BorderFactory.createEmptyBorder());

		JProgressBar progressBar = new JProgressBar(0, max);
		progressBar.setStringPainted(false);
		progressBar.setPreferredSize(new Dimension(MainFrame.MIN_WIDTH / 2, 14)); // Width is half that of minimum width of JFrame

		JLabel progressDescription = new JLabel(description); // Width conforms to length of string contained within it
		progressDescription.setFont(new Font(progressDescription.getFont().getName(), Font.PLAIN, 10));
		progressDescription.setForeground(GUIsettings.progressTextColor);

		JButton stopButton = new JButton("Cancel");
		stopButton.addActionListener(progressPanel);
		stopButton.setPreferredSize(new Dimension(100, 14));
		stopButton.setFont(new Font(stopButton.getFont().getName(), Font.PLAIN, 9));
		stopButton.setBackground(GUIsettings.tabBackgroundColor);
		stopButton.setForeground(GUIsettings.progressTextColor);

		identificationAndPanel.put(id, panel);
		identificationAndProgressBar.put(id, progressBar);
		identificationAndLabel.put(id, progressDescription);
		stopButtonAndIdentification.put(stopButton, id);
		identificationAndProgress.put(id, 0);
		identificationAndDescription.put(id, description);
		identificationAndSwingWorker.put(id, worker);

		// Flow layout order justified to the left
		panel.add(progressBar);
		panel.add(progressDescription);
		panel.add(stopButton);
		progressPanel.add(panel);

		progressPanel.revalidate();
		progressPanel.repaint();

		identifications.add(id);
		return id;

	}

	private static int getUniqueID() {
		int potentialID = 0;

		while(identifications.contains(potentialID)) {
			potentialID = (int) System.currentTimeMillis() % maxQueueSize;
		}
		return potentialID;
	}

	public static synchronized boolean taskAlreadyCreated(Integer key) {
		return identifications.contains(key);
	}

	//	static synchronized void increment(int id) {
	//		Integer key = id;
	//
	//		if(!identifications.contains(id))
	//			return;
	//
	//		Integer progress = identificationAndProgress.get(key);
	//		JProgressBar bar = identificationAndProgressBar.get(key);
	//		progress++;
	//		bar.setValue(progress);
	//		identificationAndProgress.put(key, progress);
	//	}

	public static void increment(int id, int amount) {
		JProgressBar bar = null;
		Integer progress;
		Integer key = id;

		synchronized(ProgressPanel.class) {

			if(!identifications.contains(id))
				return;

			progress = identificationAndProgress.get(key);
			bar = identificationAndProgressBar.get(key);
			progress += amount;
		}
		bar.setValue(progress);
		identificationAndProgress.put(key, progress);
	}

	public static void setProgress(int id, int progress) {
		JProgressBar bar = null;
		Integer key = id;

		synchronized(ProgressPanel.class) {

			if(!identifications.contains(id))
				return;

			identificationAndProgress.put(id, new Integer(progress));
			bar = identificationAndProgressBar.get(key);
		}
		bar.setValue(progress);
	}

	public static synchronized void setDescription(int id, String progressDescription) {
		//		Integer key = id;

		if(!identifications.contains(id))
			return;

		identificationAndDescription.put(id, progressDescription);
	}

	public static synchronized void clear(Integer id) {
		if(!identifications.contains(id))
			return;

		@SuppressWarnings("rawtypes")
		SwingWorker worker = identificationAndSwingWorker.get(id);
		worker.cancel(true);
		JPanel panel = identificationAndPanel.get(id);
		progressPanel.remove(panel);

		panel = null;

		Set<JButton> buttonSet = stopButtonAndIdentification.keySet();
		JButton[] buttons = buttonSet.toArray(new JButton[buttonSet.size()]);
		for(int j = 0; j < buttons.length; j++) {
			if(stopButtonAndIdentification.get(buttons[j]) == id) {
				stopButtonAndIdentification.remove(buttons[j]);
				break;
			}
		}

		identifications.remove(id);
		identificationAndPanel.remove(id);
		identificationAndProgressBar.remove(id);
		identificationAndLabel.remove(id);
		identificationAndProgress.remove(id);
		identificationAndDescription.remove(id);
		identificationAndSwingWorker.remove(id);

		progressPanel.revalidate();
		progressPanel.repaint();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		Object key = e.getSource();
		Integer id = stopButtonAndIdentification.get(key);

		if(!identifications.contains(id))
			return;

		@SuppressWarnings("rawtypes")
		SwingWorker worker = identificationAndSwingWorker.get(id);
		worker.cancel(true);
		JPanel panel = identificationAndPanel.get(id);

		if(panel != null) {
			progressPanel.remove(panel);
			panel = null;
		}

		identifications.remove(id);
		identificationAndPanel.remove(id);
		identificationAndProgressBar.remove(id);
		identificationAndLabel.remove(id);
		stopButtonAndIdentification.remove(key);
		identificationAndProgress.remove(id);
		identificationAndDescription.remove(id);
		identificationAndSwingWorker.remove(id);

		progressPanel.revalidate();
		progressPanel.repaint();
	}
}


text:
ACCEPTED

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

#### Published in
null

#### Original name
Thlaspi cochlearioides Hook.f. & Thomson

### Remarks
null


text:
package org.wildfly.extension.gravia.service;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.gravia.runtime.spi.ModuleEntriesProvider;
import org.jboss.gravia.utils.IllegalArgumentAssertion;
import org.jboss.vfs.VirtualFile;

/**
 * A provider for module entries that delegates to
 * the given virtual file.
 *
 * @author thomas.diesler@jboss.com
 * @since 22-Nov-2013
 */
public class VirtualFileEntriesProvider implements ModuleEntriesProvider {

    private final VirtualFile rootFile;

    public VirtualFileEntriesProvider(ResourceRoot resourceRoot) {
        IllegalArgumentAssertion.assertNotNull(resourceRoot, "resourceRoot");
        this.rootFile = resourceRoot.getRoot();
    }

    @Override
    public URL getEntry(String path) {
        try {
            VirtualFile child = rootFile.getChild(path);
            return child.asFileURL();
        } catch (MalformedURLException e) {
            return null;
        }
    }

    @Override
    public List<String> getEntryPaths(String path) {
        VirtualFile pathChild = rootFile.getChild(path);
        List<VirtualFile> entries = pathChild.getChildren();
        List<String> result = new ArrayList<String>();
        for (VirtualFile entry : entries) {
            result.add(entry.getPathName());
        }
        return Collections.unmodifiableList(result);
    }

    @Override
    public List<URL> findEntries(String path, String filePattern, boolean recurse) {

        if (filePattern == null)
            filePattern = "*";

        List<URL> result = new ArrayList<URL>();
        VirtualFile pathChild = rootFile.getChild(path);
        Pattern pattern = convertToPattern(filePattern);
        fillResultList(pathChild, pattern, recurse, result);
        return Collections.unmodifiableList(result);
    }

    private void fillResultList(VirtualFile pathChild, Pattern pattern, boolean recurse, List<URL> result) {
        List<VirtualFile> entries = pathChild.getChildren();
        for(VirtualFile vfile : entries) {
            String resname = vfile.getPathName();
            if (resname.startsWith("/")) {
                resname = resname.substring(1);
            }
            int lastIndex = resname.lastIndexOf('/');
            String filename = lastIndex > 0 ? resname.substring(lastIndex + 1) : resname;
            if (pattern.matcher(filename).matches()) {
                try {
                    result.add(vfile.asFileURL());
                } catch (MalformedURLException e) {
                    // ignore
                }
                if (recurse) {
                    fillResultList(vfile, pattern, recurse, result);
                }
            }
        }
    }

    // Convert file pattern (RFC 1960-based Filter) into a RegEx pattern
    private Pattern convertToPattern(String filePattern) {
        filePattern = filePattern.replace("*", ".*");
        return Pattern.compile("^" + filePattern + "$");
    }
}


text:
import re
import ast
from setuptools import setup, find_packages

_version_re = re.compile(r'__version__\s+=\s+(.*)')

with open('withings_cli/cli.py', 'rb') as f:
    __version__ = str(ast.literal_eval(_version_re.search(
        f.read().decode('utf-8')).group(1)))

setup(
    name="withings-cli",
    author="Kim Blomqvist",
    author_email="kblomqvist@iki.fi",
    version=__version__,
    description="A Command-line interface for Withings API",
    keywords=["withings", "cli-utilities"],
    license="MIT",
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        "click",
        "pytoml",
        "requests_oauthlib",
    ],
    entry_points='''
        [console_scripts]
        withings=withings_cli.cli:cli
    ''',
    classifiers=[
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3.6",
        "License :: OSI Approved :: MIT License",
    ],
    url="https://github.com/kblomqvist/withings-cli",
    download_url="https://github.com/kblomqvist/withings-cli/tarball/" + __version__,
)


text:
package io.grpc.internal;

import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.MoreExecutors;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.InternalConfigSelector;
import io.grpc.LoadBalancer.PickSubchannelArgs;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.Status;
import io.grpc.internal.ManagedChannelImpl.ConfigSelectingClientCall;
import io.grpc.internal.ManagedChannelServiceConfig.MethodInfo;
import io.grpc.testing.TestMethodDescriptors;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;

/** Tests for {@link ManagedChannelImpl.ConfigSelectingClientCall}. */
@RunWith(JUnit4.class)
public class ConfigSelectingClientCallTest {
  @Rule
  public MockitoRule mockitoRule = MockitoJUnit.rule();
  private final MethodDescriptor<Void, Void> method = TestMethodDescriptors.voidMethod();

  private TestChannel channel = new TestChannel();
  // The underlying call directly created by the channel.
  private TestCall<?, ?> call;

  @Mock
  private ClientCall.Listener<Void> callListener;

  @Test
  public void configSelectorInterceptsCall() {
    Map<String, ?> rawMethodConfig = ImmutableMap.of(
        "retryPolicy",
        ImmutableMap.of(
            "maxAttempts", 3.0D,
            "initialBackoff", "1s",
            "maxBackoff", "10s",
            "backoffMultiplier", 1.5D,
            "retryableStatusCodes", ImmutableList.of("UNAVAILABLE")
        ));
    final MethodInfo methodInfo = new MethodInfo(rawMethodConfig, true, 4, 4);
    final Metadata.Key<String> metadataKey =
        Metadata.Key.of("test", Metadata.ASCII_STRING_MARSHALLER);
    final CallOptions.Key<String> callOptionsKey = CallOptions.Key.create("test");
    InternalConfigSelector configSelector = new InternalConfigSelector() {
      @Override
      public Result selectConfig(final PickSubchannelArgs args) {
        ManagedChannelServiceConfig config = new ManagedChannelServiceConfig(
            methodInfo,
            ImmutableMap.<String, MethodInfo>of(),
            ImmutableMap.<String, MethodInfo>of(),
            null,
            null,
            null);
        return Result.newBuilder()
            .setConfig(config)
            .setInterceptor(
                // An interceptor that mutates CallOptions based on headers value.
                new ClientInterceptor() {
                  String value = args.getHeaders().get(metadataKey);
                  @Override
                  public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
                      MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
                    callOptions = callOptions.withOption(callOptionsKey, value);
                    return next.newCall(method, callOptions);
                  }
                })
            .build();
      }
    };

    ClientCall<Void, Void> configSelectingClientCall = new ConfigSelectingClientCall<>(
        configSelector,
        channel,
        MoreExecutors.directExecutor(),
        method,
        CallOptions.DEFAULT.withAuthority("bar.authority"));
    Metadata metadata = new Metadata();
    metadata.put(metadataKey, "fooValue");
    configSelectingClientCall.start(callListener, metadata);

    assertThat(call.callOptions.getAuthority()).isEqualTo("bar.authority");
    assertThat(call.callOptions.getOption(MethodInfo.KEY)).isEqualTo(methodInfo);
    assertThat(call.callOptions.getOption(callOptionsKey)).isEqualTo("fooValue");
  }

  @Test
  public void selectionErrorPropagatedToListener() {
    InternalConfigSelector configSelector = new InternalConfigSelector() {
      @Override
      public Result selectConfig(PickSubchannelArgs args) {
        return Result.forError(Status.FAILED_PRECONDITION);
      }
    };

    ClientCall<Void, Void> configSelectingClientCall = new ConfigSelectingClientCall<>(
        configSelector,
        channel,
        MoreExecutors.directExecutor(),
        method,
        CallOptions.DEFAULT);
    configSelectingClientCall.start(callListener, new Metadata());
    ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(null);
    verify(callListener).onClose(statusCaptor.capture(), any(Metadata.class));
    assertThat(statusCaptor.getValue().getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION);

    // The call should not delegate to null and fail methods with NPE.
    configSelectingClientCall.request(1);
  }

  private final class TestChannel extends Channel {

    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
        MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
      TestCall<ReqT, RespT> clientCall = new TestCall<>(callOptions);
      call = clientCall;
      return clientCall;
    }

    @Override
    public String authority() {
      return "foo.authority";
    }
  }

  private static final class TestCall<ReqT, RespT> extends NoopClientCall<ReqT, RespT> {
    // CallOptions actually received from the channel when the call is created.
    final CallOptions callOptions;

    TestCall(CallOptions callOptions) {
      this.callOptions = callOptions;
    }
  }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: jacob
 * Date: 10/10/14
 * Time: 03:00exit
 */
namespace Chencha\Autosuggest\Services;
use Chencha\Autosuggest\Domain\Config as DomainConfig;
use Config as LaravelConfig;
class Config implements DomainConfig  {
    /**
     * Must get configuration item from config file
     * @param $configuration
     * @return mixed
     */
    function get($configuration)
    {
        return LaravelConfig::get($configuration);
    }

}


text:
package ru.bullyboo.text_animation;

import android.os.Handler;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.widget.TextView;

import java.text.DecimalFormat;

import ru.bullyboo.text_animation.exeptions.BuilderDataException;

public class TextCounter{

    public static final int LINEAR_MODE = 1;
    public static final int LINEAR_ACCELERATION_MODE = 2;
    public static final int LINEAR_DECELERATION_MODE = 3;

    public static final int DECELERATION_MODE = 4;
    public static final int DECELERATION_LINEAR_MODE = 5;
    public static final int DECELERATION_ACCELERATION_MODE = 6;

    public static final int ACCELERATION_MODE = 7;
    public static final int ACCELERATION_LINEAR_MODE = 8;
    public static final int ACCELERATION_DECELERATION_MODE = 9;

    public static final int LINEAR_TO_ALPHA_MODE = 10;
    public static final int LINEAR_FROM_ALPHA_MODE = 11;

    public static final int DECELERATION_TO_ALPHA_MODE  = 12;
    public static final int DECELERATION_FROM_ALPHA_MODE  = 13;

    public static final int ACCELERATION_TO_ALPHA_MODE  = 14;
    public static final int ACCELERATION_FROM_ALPHA_MODE  = 15;

    public static final int CUSTOM_MODE  = 16;

    /**
     * Support primitive data types
     */
    public static final int BYTE = 1;
    public static final int SHORT = 2;
    public static final int INT = 3;
    public static final int FLOAT = 4;
    public static final int LONG = 5;
    public static final int DOUBLE = 6;

    /**
     * TextView which will show counter animation
     */
    private TextView textView;

    /**
     * from - start number
     * to - end number
     */
    private Double from, to;

    /**
     * Prefix and Postfix
     * Its use to add to start and end of text counter
     */
    private String prefix = "", postfix = "";

    /**
     * Autodetection parameter type, which will obtain from methods `from();` and `to();` (low priority)
     * User selected parameter type, which will obtain from methods `from();` and `to();` (high priority)=
     *
     * Final type which will use in programm
     */
    private int autoType;
    private int userType;
    private int type;

    /**
     * Selected animation mode
     */
    private int mode = 1;

    /**
     * Duration of animation
     */
    private long duration;

    /**
     * Step. How mush will increase or decrease number value for one frame
     */
    private Double step;

    /**
     * Amoint frames per second (FPS)
     * Default value is 60 frames per second
     *
     * Dynamic of changes fps
     */
    private int fps = 60;
    private Integer fromFps, toFps;

    private int[] fpsDynamic;
    private int[] userFpsDynamic;

    /**
     * Dynamic of changes alpha
     */
    private float alpha = 1;
    private Float fromAlpha, toAlpha;

    private float[] alphaDynamic;
    private float[] userAlphaDynamic;

    /**
     * List custom animations, which will create in ModeBuilder
     */
    private AnimationBuilder partList;

    /**
     * Current number
     * The final number
     */
    private Double currentNumber;
    private double targetNumber;

    /**
     * Object of formater, which will round a number
     */
    private DecimalFormat decimalFormat;

    /**
     * Flag of animation
     * true - animation is playing now
     * false - animation isn`t playing now
     */
    private boolean isAnimate = false;

	/**
	 * TextCounter listener
	 */
	public interface TextCounterListener {
		void onEnd();
	}

	private TextCounterListener listener;

    private TextCounter(){

    }

    public static Builder newBuilder() {
        return new TextCounter().new Builder();
    }

    public void start(){
//        заглушка, чтобы нельзя было запустить анимацию повторно, пока она не закончится
        if(!isAnimate){
            isAnimate = true;
            frame = 0;
            init();
            timer();
        }
    }

    private void init(){
        long amountFrames = fpsDynamic.length + 1;

        currentNumber = from;
        targetNumber = to;
        step = to - from;
        step = step / amountFrames;
    }

    /**
     * Frame`s counter
     */
    private int frame;

    private void timer(){
        new Handler().postDelayed(changeText, fpsDynamic[frame]);
    }

    private Runnable changeText = new Runnable() {
        @Override
        public void run() {
            currentNumber += step;

//            настраиваем прозрачность
            if(alphaDynamic != null){
                textView.setAlpha(alphaDynamic[frame]);
            }
//            прибавляем кадр
            if(frame+1 < fpsDynamic.length) {
                frame++;
            }

//            округляем число
            String roundedDouble = decimalFormat.format(currentNumber);
            roundedDouble = roundedDouble.replace(",", ".");

            changeText(roundedDouble);

//            если увеличиываем число
            if(step > 0){
                if(currentNumber < targetNumber){
                    timer();
                } else {
                    lastTextUpdate();
                    isAnimate = false;
                }

//                если уменьшаем число
            } else if (step < 0){
                if(currentNumber > targetNumber){
                    timer();
                } else {
                    lastTextUpdate();
                    isAnimate = false;
                }
            }
        }
    };

    private void changeText(String current){
        switch (type){
            case BYTE:
                textView.setText(prefix + currentNumber.byteValue() + postfix);
                break;
            case SHORT:
                textView.setText(prefix + currentNumber.shortValue() + postfix);
                break;
            case INT:
                textView.setText(prefix + currentNumber.intValue() + postfix);
                break;
            case FLOAT:
                textView.setText(prefix + current + postfix);
                break;
            case LONG:
                textView.setText(prefix + currentNumber.longValue() + postfix);
                break;
            case DOUBLE:
                textView.setText(prefix + current + postfix);
                break;
            default:
                return;
        }
    }

    private void lastTextUpdate(){
        switch (type){
            case BYTE:
                textView.setText(prefix + to.byteValue() + postfix);
                break;
            case SHORT:
                textView.setText(prefix + to.shortValue() + postfix);
                break;
            case INT:
                textView.setText(prefix + to.intValue() + postfix);
                break;
            case FLOAT:
                textView.setText(prefix + decimalFormat.format(to.floatValue()).replace(",", ".") + postfix);
                break;
            case LONG:
                textView.setText(prefix + to.longValue() + postfix);
                break;
            case DOUBLE:
                textView.setText(prefix + decimalFormat.format(to).replace(",", ".") + postfix);
                break;
            default:
                return;
        }

		if(listener != null) {
			listener.onEnd();
		}
    }

    public class Builder{

        private Builder(){

        }

        public Builder setTextView(@NonNull TextView textView){
            TextCounter.this.textView = textView;
            return this;
        }

        public Builder from(byte fromByte){
            from = Double.valueOf(fromByte);
            autoType = BYTE;
            return this;
        }

        public Builder to(byte toByte){
            to = Double.valueOf(toByte);
            autoType = BYTE;
            return this;
        }

        public Builder from(short fromShort){
            from = Double.valueOf(fromShort);
            autoType = SHORT;
            return this;
        }

        public Builder to(short toShort){
            to = Double.valueOf(toShort);
            autoType = SHORT;
            return this;
        }

        public Builder from(int fromInt){
            from = Double.valueOf(fromInt);
            autoType = INT;
            return this;
        }

        public Builder to(int toInt){
            to = Double.valueOf(toInt);
            autoType = INT;
            return this;
        }

        public Builder from(float fromFloat){
            from = Double.valueOf(fromFloat);
            autoType = FLOAT;
            return this;
        }

        public Builder to(float toFloat){
            to = Double.valueOf(toFloat);
            autoType = FLOAT;
            return this;
        }

        public Builder from(long fromLong){
            from = Double.valueOf(fromLong);
            autoType = LONG;
            return this;
        }

        public Builder to(long toLong){
            to = Double.valueOf(toLong);
            autoType = LONG;
            return this;
        }

        public Builder from(double fromDouble){
            from = fromDouble;
            autoType = DOUBLE;
            return this;
        }

        public Builder to(double toDouble){
            to = toDouble;
            autoType = DOUBLE;
            return this;
        }

        public Builder from(Byte fromByte){
            from = Double.valueOf(fromByte);
            autoType = BYTE;
            return this;
        }

        public Builder to(Byte toByte){
            to = Double.valueOf(toByte);
            autoType = BYTE;
            return this;
        }

        public Builder from(Short fromShort){
            from = Double.valueOf(fromShort);
            autoType = SHORT;
            return this;
        }

        public Builder to(Short toShort){
            to = Double.valueOf(toShort);
            autoType = SHORT;
            return this;
        }

        public Builder from(Integer fromInt){
            from = Double.valueOf(fromInt);
            autoType = INT;
            return this;
        }

        public Builder to(Integer toInt){
            to = Double.valueOf(toInt);
            autoType = INT;
            return this;
        }

        public Builder from(Float fromFloat){
            from = Double.valueOf(fromFloat);
            autoType = FLOAT;
            return this;
        }

        public Builder to(Float toFloat){
            to = Double.valueOf(toFloat);
            autoType = FLOAT;
            return this;
        }

        public Builder from(Long fromLong){
            from = Double.valueOf(fromLong);
            autoType = LONG;
            return this;
        }

        public Builder to(Long toLong){
            to = Double.valueOf(toLong);
            autoType = LONG;
            return this;
        }

        public Builder from(Double fromDouble){
            from = fromDouble;
            autoType = DOUBLE;
            return this;
        }

        public Builder to(Double toDouble){
            to = toDouble;
            autoType = DOUBLE;
            return this;
        }

        public Builder from(String fromDouble){
            from = parseStringToDigitFrom(fromDouble);
            autoType = DOUBLE;
            return this;
        }

        public Builder to(String toDouble){
            to = parseStringToDigitTo(toDouble);
            autoType = DOUBLE;
            return this;
        }

        public Builder setPrefix(String prefix){
            TextCounter.this.prefix = prefix;
            return this;
        }

        public Builder setType(@Type int type){
            userType = type;
            return this;
        }

        public Builder setPostfix(String postfix){
            TextCounter.this.postfix = postfix;
            return this;
        }

        public Builder setDuration(long millis){
            duration = millis;
            return this;
        }

        public Builder setFPS(int fps){
            TextCounter.this.fps = fps;
            return this;
        }

        public Builder setMode(@Mode int mode){
            TextCounter.this.mode = mode;
            return this;
        }

        public Builder setFpsDynamic(int[] dynamic){
            userFpsDynamic = dynamic;
            return this;
        }

        public Builder setRound(int round){
            decimalFormat = new DecimalFormat(getRoundPattern(round));
            return this;
        }

        public Builder setDecimalFormat(DecimalFormat decimalFormat){
            TextCounter.this.decimalFormat = decimalFormat;
            return this;
        }

        public Builder setFromFps(int fromFps){
            TextCounter.this.fromFps = fromFps;
            return this;
        }

        public Builder setToFps(int toFps){
            TextCounter.this.toFps = toFps;
            return this;
        }

        public Builder setFromAlpha(float fromAlpha){
            TextCounter.this.fromAlpha = fromAlpha;
            return this;
        }

        public Builder setToAlpha(float toAlpha){
            TextCounter.this.toAlpha = toAlpha;
            return this;
        }

        public Builder setAlphaDynamic(float[] alphaDynamic){
            TextCounter.this.userAlphaDynamic = userAlphaDynamic;
            return this;
        }

        public Builder setCustomAnimation(@NonNull AnimationBuilder partList){
            TextCounter.this.partList = partList;
            return this;
        }

		public Builder setListener(TextCounterListener listener) {
			TextCounter.this.listener = listener;
			return this;
		}

        public TextCounter build(){

            ModeConstructor constuctor = buildFpsDynamic(new ModeConstructor());
            buildAlphaDynamic(constuctor);

            buildType();

            if(decimalFormat == null){
                decimalFormat = new DecimalFormat(getRoundPattern(0));
            }

            try {
                checkData();
            } catch (BuilderDataException e) {
                e.printStackTrace();
                throw new NullPointerException(BuilderDataException.DIDNT_SET_DATA);
            }

            return TextCounter.this;
        }

        private double parseStringToDigitFrom(String string){

            try {
                return Double.valueOf(string);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            return 0;
        }

        private double parseStringToDigitTo(String string){

            try {
                return Double.valueOf(string);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            return 0;
        }

        private String getRoundPattern(int round){

            StringBuilder roundPattern = new StringBuilder();
            roundPattern.append("#0");

            if (round < 0) {
                return null;
            } else if (round > 0){
                roundPattern.append(".");
                for (int i = 0; i < round; i++){
                    roundPattern.append("0");
                }
            }
            return roundPattern.toString();
        }

        private ModeConstructor buildFpsDynamic(ModeConstructor constuctor){

            if(partList != null){
                fpsDynamic = constuctor.buildFpsDynamic(partList.getFpsList());
                return constuctor;
            }

            if(userFpsDynamic != null){
                fpsDynamic = constuctor.convertFpsToTimePause(userFpsDynamic);
                return constuctor;
            }

            if (fromFps != null && toFps != null){
                fpsDynamic = constuctor.getModeFpsDynamic(mode, duration, fromFps, toFps);
                return constuctor;
            }
            if(fromFps == null && toFps == null){
                fpsDynamic = constuctor.getModeFpsDynamic(mode, duration, fps);
                return constuctor;
            }

            try {
                if(fromFps == null && toFps != null){
                    throw new BuilderDataException(BuilderDataException.FROM_FPS_EQUELS_NULL);
                } else if(fromFps != null && toFps == null){
                    throw new BuilderDataException(BuilderDataException.TO_FPS_EQUELS_NULL);
                } else {
                    throw new BuilderDataException(BuilderDataException.DIDNT_SET_FPS_DATA);
                }
            } catch (BuilderDataException e) {
                e.printStackTrace();
                return constuctor;
            }
        }

        private void buildAlphaDynamic(ModeConstructor constuctor){
            if(partList != null){
                alphaDynamic = constuctor.buildAlphaDynamic(partList.getFpsList());

                if(alphaDynamic != null){
                    return;
                }
            }

            if(userAlphaDynamic != null){
                alphaDynamic = userAlphaDynamic;
                return;
            }

            if (fromAlpha != null && toAlpha != null){
                AlphaBuilder alphaBuilder = AlphaBuilder.newInstance().fromAlpha(fromAlpha).toAlpha(toAlpha);
                alphaDynamic = alphaBuilder.createAlphaDynamic(fpsDynamic.length);
                return;
            }

            if(mode >=10 && mode <= 15){
                alphaDynamic = constuctor.getAlphaDynamic();
                return;
            }

            if (fromAlpha == null && toAlpha == null){
                AlphaBuilder alphaBuilder = AlphaBuilder.newInstance().fromAlpha(alpha).toAlpha(alpha);
                alphaDynamic = alphaBuilder.createAlphaDynamic(fpsDynamic.length);
                return;
            }

            try {
                if(fromAlpha == null && toAlpha != null){
                    throw new BuilderDataException(BuilderDataException.FROM_ALPHA_EQUELS_NULL);
                } else if(fromAlpha != null && toAlpha == null){
                    throw new BuilderDataException(BuilderDataException.TO_ALPHA_EQUELS_NULL);
                } else {
                    throw new BuilderDataException(BuilderDataException.DIDNT_SET_ALPHA_DATA);
                }
            } catch (BuilderDataException e) {
                e.printStackTrace();
                return;
            }
        }

        private void buildType(){
            if (userType == 0){
                type = autoType;
            } else {
                type = userType;
            }
        }

        private void checkData()throws BuilderDataException{
            if(duration == 0 && partList == null){
                throw new BuilderDataException(BuilderDataException.DIDNT_SET_DURATION);
            }
            if(textView == null){
                throw new BuilderDataException(BuilderDataException.DIDNT_SET_TEXT_VIEW);
            }
            if(from == null && to == null){
                throw new BuilderDataException(BuilderDataException.DIDNT_SET_FROM_TO);
            }
        }
    }

    @IntDef({BYTE, SHORT, INT, FLOAT, LONG, DOUBLE})
    public @interface Type {}

    @IntDef({LINEAR_MODE,
            LINEAR_ACCELERATION_MODE,
            LINEAR_DECELERATION_MODE,
            DECELERATION_MODE,
            DECELERATION_LINEAR_MODE,
            DECELERATION_ACCELERATION_MODE,
            ACCELERATION_MODE,
            ACCELERATION_LINEAR_MODE,
            ACCELERATION_DECELERATION_MODE,
            LINEAR_TO_ALPHA_MODE,
            LINEAR_FROM_ALPHA_MODE,
            DECELERATION_TO_ALPHA_MODE,
            DECELERATION_FROM_ALPHA_MODE,
            ACCELERATION_TO_ALPHA_MODE,
            ACCELERATION_FROM_ALPHA_MODE,
            CUSTOM_MODE})
    public @interface Mode {}
}


text:
module.exports = {
  name: 'RunningBalance',
  type: 'select',
  default: '0',
  section: 'accounts',
  title: 'Show Running Balance',
  description: 'Adds a running balance column to the accounts page (does not appear on All Accounts View)',
  options: [
    { name: 'Off', value: '0' },
    { name: 'On: Style any negative running balances red', value: '1' },
    { name: 'On: Do not style negative running balances', value: '2' }
  ],
  isSubFeature: true
};


text:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class FlashText extends Application {
  private String text = "";

  class inner{}
  class inner2{}
  @Override // Override the start method in the Application class
  public void start(Stage primaryStage) {
    StackPane pane = new StackPane();
    Label lblText = new Label("Programming is fun");
    pane.getChildren().add(lblText);

    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          while (true) {
            if (lblText.getText().trim().length() == 0)
              text = "Welcome";
            else
              text = "";

            Platform.runLater(new Runnable() {
              @Override
              public void run() {
                lblText.setText(text);
              }
            });

            Thread.sleep(200);
          }
        }
        catch (InterruptedException ex) {
        }
      }
    }).start();

    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          while (true) {
            if (lblText.getText().trim().length() == 0)
              text = "Welcome";
            else
              text = "";

            Platform.runLater(new Runnable() {
              @Override
              public void run() {
                lblText.setText(text);
              }
            });

            Thread.sleep(200);
          }
        }
        catch (InterruptedException ex) {
        }
      }
    }).start();

    // Create a scene and place it in the stage
    Scene scene = new Scene(pane, 200, 50);
    primaryStage.setTitle("FlashText"); // Set the stage title
    primaryStage.setScene(scene); // Place the scene in the stage
    primaryStage.show(); // Display the stage
  }

  /**
   * The main method is only needed for the IDE with limited
   * JavaFX support. Not needed for running from the command line.
   */
  public static void main(String[] args) {
    launch(args);
  }
}


text:
"""Regression tests for optimize.

"""
from __future__ import division, print_function, absolute_import

import numpy as np
from numpy.testing import assert_almost_equal
from pytest import raises as assert_raises

import scipy.optimize

class TestRegression(object):

    def test_newton_x0_is_0(self):
        # Regression test for gh-1601
        tgt = 1
        res = scipy.optimize.newton(lambda x: x - 1, 0)
        assert_almost_equal(res, tgt)

    def test_newton_integers(self):
        # Regression test for gh-1741
        root = scipy.optimize.newton(lambda x: x**2 - 1, x0=2,
                                    fprime=lambda x: 2*x)
        assert_almost_equal(root, 1.0)

    def test_lmdif_errmsg(self):
        # This shouldn't cause a crash on Python 3
        class SomeError(Exception):
            pass
        counter = [0]

        def func(x):
            counter[0] += 1
            if counter[0] < 3:
                return x**2 - np.array([9, 10, 11])
            else:
                raise SomeError()
        assert_raises(SomeError,
                      scipy.optimize.leastsq,
                      func, [1, 2, 3])


text:
import lib.webinterface

from lib.events import subscribe, EventPropagationStop
from settings import ORIGIN

@subscribe('request')
def check_host(req):
    host = ORIGIN[1] + ':%d' % ORIGIN[2] if ORIGIN != 80 else ''
    if 'host' not in req.headers or req.headers['host'][0] != host:
        req.reply(lib.webinterface.Http400Error().build_response().build(req))
        raise EventPropagationStop()


text:
<?php

use opensrs\domains\forwarding\ForwardingGet;

/**
 * @group forwarding
 * @group ForwardingGet
 */
class ForwardingGetTest extends PHPUnit_Framework_TestCase
{
    protected $func = 'fwdGet';

    protected $validSubmission = array(
        'attributes' => array(
            /*
             * Required: 1 of 2
             *
             * cookie: cookie to be deleted
             * bypass: relevant domain, required
             *   only if cookie is not sent
             */
            'cookie' => '',
            'bypass' => '',

            /*
             * Required
             *
             * domain: relevant domain
             */
            'domain' => '',
            ),
        );

    /**
     * Valid submission should complete with no
     * exception thrown.
     *
     *
     * @group validsubmission
     */
    public function testValidSubmission()
    {
        $data = json_decode(json_encode($this->validSubmission));

        $data->cookie = md5(time());

        $ns = new ForwardingGet('array', $data);

        $this->assertTrue($ns instanceof ForwardingGet);
    }

    /**
     * Invalid submission should throw an exception.
     *
     *
     * @group invalidsubmission
     */
    public function testInvalidSubmissionFieldsMissing()
    {
        $data = json_decode(json_encode($this->validSubmission));

        $this->setExpectedExceptionRegExp(
            'opensrs\Exception',
            '/(domain|cookie).*not defined/'
            );

        $ns = new ForwardingGet('array', $data);
    }

    /**
     * Invalid submission should throw an exception.
     *
     *
     * @group invalidsubmission
     */
    public function testInvalidSubmissionFieldsCookieAndBypassSent()
    {
        $data = json_decode(json_encode($this->validSubmission));

        $data->cookie = md5(time());
        $data->attributes->domain = 'phptest'.time().'.com';

        $this->setExpectedExceptionRegExp(
          'opensrs\Exception',
        '/.*cookie.*domain.*cannot.*one.*call.*/'
          );

        $ns = new ForwardingGet('array', $data);
    }
}


text:
package org.apache.xerces.impl.xs.identity;

import org.apache.xerces.impl.xpath.XPathException;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.util.XMLChar;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xs.ShortList;
import org.apache.xerces.xs.XSTypeDefinition;

/**
 * Schema identity constraint selector.
 *
 * @xerces.internal
 *
 * @author Andy Clark, IBM
 * @version $Id$
 */
public class Selector {

    //
    // Data
    //

    /** XPath. */
    protected final Selector.XPath fXPath;

    /** Identity constraint. */
    protected final IdentityConstraint fIdentityConstraint;

    // the Identity constraint we're the matcher for.  Only
    // used for selectors!
    protected IdentityConstraint fIDConstraint;

    /** XPath default namespace. */
    protected String fXpathDefaultNamespace;

    //
    // Constructors
    //

    /** Constructs a selector. */
    public Selector(Selector.XPath xpath, IdentityConstraint identityConstraint, String xpathDefaultNamespace) {
        fXPath = xpath;
        fIdentityConstraint = identityConstraint;
        fXpathDefaultNamespace = xpathDefaultNamespace;
    } // <init>(Selector.XPath,IdentityConstraint)

    //
    // Public methods
    //

    /** Returns the selector XPath. */
    public org.apache.xerces.impl.xpath.XPath getXPath() {
        return fXPath;
    } // getXPath():org.apache.xerces.v1.schema.identity.XPath

    /** Returns the identity constraint. */
    public IdentityConstraint getIDConstraint() {
        return fIdentityConstraint;
    } // getIDConstraint():IdentityConstraint

    // factory method

    /** Creates a selector matcher.
     * @param activator     The activator for this selector's fields.
     * @param initialDepth  The depth in the document at which this matcher began its life;
     *                          used in correctly handling recursive elements.
     */
    public XPathMatcher createMatcher(FieldActivator activator, int initialDepth) {
        return new Selector.Matcher(fXPath, activator, initialDepth);
    } // createMatcher(FieldActivator):XPathMatcher

    //
    // Object methods
    //

    /** Returns a string representation of this object. */
    public String toString() {
        return fXPath.toString();
    } // toString():String

    /** Return value of xpathDefaultNamespace. */
    public String getXPathDefaultNamespace() {
        return fXpathDefaultNamespace;
    }

    //
    // Classes
    //

    /**
     * Schema identity constraint selector XPath expression.
     *
     * @author Andy Clark, IBM
     * @version $Id$
     */
    public static class XPath
    extends org.apache.xerces.impl.xpath.XPath {

        //
        // Constructors
        //

        /** Constructs a selector XPath expression. */
        public XPath(String xpath, SymbolTable symbolTable,
                     NamespaceContext context) throws XPathException {
            super(normalize(xpath), symbolTable, context);
            // verify that an attribute is not selected
            for (int i=0;i<fLocationPaths.length;i++) {
                org.apache.xerces.impl.xpath.XPath.Axis axis =
                fLocationPaths[i].steps[fLocationPaths[i].steps.length-1].axis;
                if (axis.type == XPath.Axis.ATTRIBUTE) {
                    throw new XPathException("c-selector-xpath");
                }
            }

        } // <init>(String,SymbolTable,NamespacesScope)

        private static String normalize(String xpath) {
            // NOTE: We have to prefix the selector XPath with "./" in
            //       order to handle selectors such as "." that select
            //       the element container because the fields could be
            //       relative to that element. -Ac
            //       Unless xpath starts with a descendant node -Achille Fokoue
            //      ... or a '.' or a '/' - NG
            //  And we also need to prefix exprs to the right of | with ./ - NG
            StringBuffer modifiedXPath = new StringBuffer(xpath.length()+5);
            int unionIndex = -1;
            do {
                if(!(XMLChar.trim(xpath).startsWith("/") || XMLChar.trim(xpath).startsWith("."))) {
                    modifiedXPath.append("./");
                }
                unionIndex = xpath.indexOf('|');
                if(unionIndex == -1) {
                    modifiedXPath.append(xpath);
                    break;
                }
                modifiedXPath.append(xpath.substring(0,unionIndex+1));
                xpath = xpath.substring(unionIndex+1, xpath.length());
            } while(true);
            return modifiedXPath.toString();
        }

    } // class Selector.XPath

    /**
     * Selector matcher.
     *
     * @author Andy Clark, IBM
     */
    public class Matcher
    extends XPathMatcher {

        //
        // Data
        //

        /** Field activator. */
        protected final FieldActivator fFieldActivator;

        /** Initial depth in the document at which this matcher was created. */
        protected final int fInitialDepth;

        /** Element depth. */
        protected int fElementDepth;

        /** Depth at match. */
        protected int fMatchedDepth;

        //
        // Constructors
        //

        /** Constructs a selector matcher. */
        public Matcher(Selector.XPath xpath, FieldActivator activator,
                int initialDepth) {
            super(xpath);
            fFieldActivator = activator;
            fInitialDepth = initialDepth;
        } // <init>(Selector.XPath,FieldActivator)

        //
        // XMLDocumentFragmentHandler methods
        //

        public void startDocumentFragment(){
            super.startDocumentFragment();
            fElementDepth = 0;
            fMatchedDepth = -1;
        } // startDocumentFragment()

        /**
         * The start of an element. If the document specifies the start element
         * by using an empty tag, then the startElement method will immediately
         * be followed by the endElement method, with no intervening methods.
         *
         * @param element    The name of the element.
         * @param attributes The element attributes.
         *
         */
        public void startElement(QName element, XMLAttributes attributes) {
            super.startElement(element, attributes);
            fElementDepth++;
            // activate the fields, if selector is matched
            //int matched = isMatched();

            if (isMatched()) {
/*            (fMatchedDepth == -1 && ((matched & MATCHED) == MATCHED)) ||
                    ((matched & MATCHED_DESCENDANT) == MATCHED_DESCENDANT)) { */
                fMatchedDepth = fElementDepth;
                fFieldActivator.startValueScopeFor(fIdentityConstraint, fInitialDepth);
                int count = fIdentityConstraint.getFieldCount();
                for (int i = 0; i < count; i++) {
                    Field field = fIdentityConstraint.getFieldAt(i);
                    XPathMatcher matcher = fFieldActivator.activateField(field, fInitialDepth);
                    matcher.startElement(element, attributes);
                }
            }

        } // startElement(QName,XMLAttrList,int)

        public void endElement(QName element, XSTypeDefinition type, boolean nillable, Object actualValue, short valueType, ShortList itemValueType) {
            super.endElement(element, type, nillable, actualValue, valueType, itemValueType);
            if (fElementDepth-- == fMatchedDepth) {
                fMatchedDepth = -1;
                fFieldActivator.endValueScopeFor(fIdentityConstraint, fInitialDepth);
            }
        }

        /** Returns the identity constraint. */
        public IdentityConstraint getIdentityConstraint() {
            return fIdentityConstraint;
        } // getIdentityConstraint():IdentityConstraint

        /** get the initial depth at which this selector matched. */
        public int getInitialDepth() {
            return fInitialDepth;
        } // getInitialDepth():  int

    } // class Matcher

} // class Selector


text:
<?php
// Don't load directly
defined( 'WPINC' ) or die;

class Tribe__Events__Aggregator__API__Origins extends Tribe__Events__Aggregator__API__Abstract {

	/**
	 * @var array
	 */
	public $origins;

	/**
	 * @var bool Whether EA is enabled or not.
	 *           While EA might be ready to work on a license and functional level
	 *           the user might disable it; this flag tracks that choice.
	 */
	protected $is_ea_disabled = true;

	/**
	 * @var array An array of origins that will still be available when EA has
	 *            been disabled by the user.
	 */
	protected $available_when_disabled = array( 'csv' );

	public function __construct() {
		parent::__construct();

		$this->origins = array(
			'csv' => (object) array(
				'id' => 'csv',
				'name' => __( 'CSV File', 'the-events-calendar' ),
				'disabled' => false,
			),
			'facebook' => (object) array(
				'id' => 'facebook',
				'name' => __( 'Facebook', 'the-events-calendar' ),
				'disabled' => true,
				'upsell' => true,
			),
			'gcal' => (object) array(
				'id' => 'gcal',
				'name' => __( 'Google Calendar', 'the-events-calendar' ),
				'disabled' => true,
				'upsell' => true,
			),
			'ical' => (object) array(
				'id' => 'ical',
				'name' => __( 'iCalendar', 'the-events-calendar' ),
				'disabled' => true,
				'upsell' => true,
			),
			'ics' => (object) array(
				'id' => 'ics',
				'name' => __( 'ICS File', 'the-events-calendar' ),
				'disabled' => true,
				'upsell' => true,
			),
			'meetup' => (object) array(
				'id' => 'meetup',
				'name' => __( 'Meetup', 'the-events-calendar' ),
				'disabled' => true,
				'upsell' => true,
			),
			'url' => (object) array(
				'id' => 'url',
				'name' => __( 'Other URL (beta)', 'the-events-calendar' ),
				'disabled' => true,
				'upsell' => true,
			),
		);

		$this->is_ea_disabled = tribe_get_option( 'tribe_aggregator_disable', false );
	}

	/**
	 * Get event-aggregator origins
	 *
	 * @return array
	 */
	public function get() {
		if ( tribe( 'events-aggregator.main' )->is_service_active() ) {
			$this->enable_service_origins();
		}

		$origins = $this->origins;
		$origins = array_filter( $origins, array( $this, 'is_origin_available' ) );

		/**
		 * The origins (sources) that EA can import from
		 *
		 * @param array $origins The origins
		 */
		$origins = apply_filters( 'tribe_aggregator_origins', $origins );

		return $origins;
	}

	/**
	 * Get event-aggregator origins from the service or cache
	 *
	 * @return array
	 */
	private function enable_service_origins() {
		$cached_origins = get_transient( "{$this->cache_group}_origins" );
		if ( $cached_origins ) {
			$this->origins = $cached_origins;
			return $this->origins;
		}

		$service_origins = $this->fetch_origin_data();

		if ( is_wp_error( $service_origins ) ) {
			return $this->origins;
		}

		if ( empty( $service_origins->origin ) ) {
			return $this->origins;
		}

		// enable the options for any that come back from the Service
		foreach ( $service_origins->origin as $origin ) {
			if ( ! empty( $this->origins[ $origin->id ] ) ) {
				$this->origins[ $origin->id ]->disabled = false;
			}
		}

		// use the specified expiration if available
		if ( isset( $this->origins->expiration ) ) {
			$expiration = $this->origins->expiration;
			unset( $this->origins->expiration );
		} else {
			$expiration = 6 * HOUR_IN_SECONDS;
		}

		set_transient( "{$this->cache_group}_origins", $this->origins, $expiration );

		return $this->origins;
	}

	/**
	 * Fetches origin data from the service and sets necessary transients
	 */
	private function fetch_origin_data() {
		$cached = tribe_get_var( 'events-aggregator.origins-data' );
		if ( empty( $cached ) ) {
			// try to see if we have a lock in place
			$cached = get_transient( "{$this->cache_group}_fetch_lock" );
		}

		if ( ! empty( $cached ) ) {
			return $cached;
		}

		list( $origin_data, $error ) = $this->service->get_origins( true );
		$origin_data = (object) $origin_data;

		if ( empty( $error ) ) {
			if ( ! get_transient( "{$this->cache_group}_origin_oauth" ) && ! empty( $origin_data->oauth ) ) {
				set_transient( "{$this->cache_group}_origin_oauth", $origin_data->oauth, 6 * HOUR_IN_SECONDS );
			}

			if ( ! get_transient( "{$this->cache_group}_origin_limit" ) && ! empty( $origin_data->limit ) ) {
				set_transient( "{$this->cache_group}_origin_limit", $origin_data->limit, 6 * HOUR_IN_SECONDS );
			}
		} elseif ( 403 == wp_remote_retrieve_response_code( $error ) ) {
			// store the origins data for 5' only
			$origin_data->expiration = 300;
			// and avoid bugging the service for 5'
			set_transient( "{$this->cache_group}_fetch_lock", $origin_data, 300 );
		}

		tribe_set_var( 'events-aggregator.origins-data', $origin_data );

		return $origin_data;

	}

	/**
	 * Returns whether oauth for a given origin is enabled
	 *
	 * @param string $origin Origin
	 *
	 * @return boolean
	 */
	public function is_oauth_enabled( $origin ) {
		if ( ! tribe( 'events-aggregator.main' )->is_service_active() ) {
			return false;
		}

		$cached_oauth_settings = get_transient( "{$this->cache_group}_origin_oauth" );
		if ( $cached_oauth_settings && isset( $cached_oauth_settings->$origin ) ) {
			return (bool) $cached_oauth_settings->$origin;
		}

		$service_origins = $this->fetch_origin_data();

		if ( ! isset( $service_origins->oauth->$origin ) ) {
			return false;
		}

		return (bool) $service_origins->oauth->$origin;
	}

	/**
	 * Get origin limit values
	 *
	 * @param string $type Type of limit to retrieve
	 *
	 * @return int
	 */
	public function get_limit( $type = 'import' ) {
		$cached_limit_settings = get_transient( "{$this->cache_group}_origin_limit" );
		if ( $cached_limit_settings && isset( $cached_limit_settings->$type ) ) {
			return (int) $cached_limit_settings->$type;
		}

		$service_origins = $this->fetch_origin_data();

		if ( ! isset( $service_origins->limit->$type ) ) {
			return false;
		}

		return (int) $service_origins->limit->$type;
	}

	public function get_name( $id ) {
		$this->get();

		if ( empty( $this->origins[ $id ] ) ) {
			return __( 'Event Aggregator', 'the-events-calendar' );
		}
		return $this->origins[ $id ]->name;
	}

	/**
	 * Whether an origin is available or not in respect to the user possibility
	 * to disable EA functions.
	 *
	 * @param stdClass|string $origin The origin to check for availability as an object
	 *                                or a slug.
	 *
	 * @return bool
	 */
	public function is_origin_available( $origin ) {
		if ( is_object( $origin ) ) {
			$origin = $origin->id;
		}

		return $this->is_ea_disabled ? in_array( $origin, $this->available_when_disabled ) : true;
	}
}


text:
//-----------------------------------------------------------------------
// <copyright file="ClearData.cs" company="None">
// Copyright (c) IIHOSHI Yoshinori.
// Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------

#pragma warning disable SA1600 // Elements should be documented

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ThScoreFileConverter.Core.Helpers;
using ThScoreFileConverter.Core.Models;
using ThScoreFileConverter.Core.Models.Th128;
using ThScoreFileConverter.Helpers;

namespace ThScoreFileConverter.Models.Th128;

internal class ClearData : Th10.Chapter, IClearData // per route
{
    public const string ValidSignature = "CR";
    public const ushort ValidVersion = 0x0003;
    public const int ValidSize = 0x0000066C;

    public ClearData(Th10.Chapter chapter)
        : base(chapter, ValidSignature, ValidVersion, ValidSize)
    {
        var levels = EnumHelper<Level>.Enumerable;

        using var stream = new MemoryStream(this.Data, false);
        using var reader = new BinaryReader(stream);

        this.Route = (RouteWithTotal)reader.ReadInt32();

        this.Rankings = levels.ToDictionary(
            level => level,
            _ => Enumerable.Range(0, 10).Select(_ => BinaryReadableHelper.Create<ScoreData>(reader)).ToList()
                as IReadOnlyList<Th10.IScoreData<StageProgress>>);

        this.TotalPlayCount = reader.ReadInt32();
        this.PlayTime = reader.ReadInt32();
        this.ClearCounts = levels.ToDictionary(level => level, _ => reader.ReadInt32());
    }

    public RouteWithTotal Route { get; }

    public IReadOnlyDictionary<Level, IReadOnlyList<Th10.IScoreData<StageProgress>>> Rankings { get; }

    public int TotalPlayCount { get; }

    public int PlayTime { get; }    // = seconds * 60fps

    public IReadOnlyDictionary<Level, int> ClearCounts { get; }

    public static bool CanInitialize(Th10.Chapter chapter)
    {
        return chapter.Signature.Equals(ValidSignature, StringComparison.Ordinal)
            && (chapter.Version == ValidVersion)
            && (chapter.Size == ValidSize);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
com.caverock.androidsvg
</TITLE>

<META NAME="date" CONTENT="2014-06-02">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package com.caverock.androidsvg

Class Summary

CSSParser
A very simple CSS parser that is not very compliant with the CSS spec but
 hopefully parses almost all the CSS we are likely to strike in an SVG file.

CSSParser.Attrib

CSSParser.Rule

CSSParser.Ruleset

CSSParser.Selector

LibConfig
Configure debugging on or off.

PreserveAspectRatio
The SVGPositioning class tells the renderer how to scale and position the
 SVG document in the current viewport.

SimpleAssetResolver
A sample implementation of SVGExternalFileResolver that retrieves files from
 an application's "assets" folder.

SVG
AndroidSVG is a library for reading, parsing and rendering SVG documents on Android devices.

SVGAndroidRenderer
The rendering part of AndroidSVG.

SVGExternalFileResolver
Resolver class used by the renderer when processing Text and Image elements.

SVGParser
SVG parser code.

Enum Summary

CSSParser.MediaType

PreserveAspectRatio.Alignment
Determines how the document is to me positioned relative to the viewport (normally the canvas).

PreserveAspectRatio.Scale
Determine whether the scaled document fills the viewport entirely or is scaled to
 fill the viewport without overflowing.

Exception Summary

SVGParseException
Thrown by the parser if a problem is found in the SVG file.

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes


text:
package com.joeburdick.redditsounds.data.model.reddit;

import com.google.gson.annotations.SerializedName;

public class Link {
    @SerializedName("thumbnail") public String thumbnailUrl;
    @SerializedName("permalink") public String permalink;
    @SerializedName("url") public String url;
    @SerializedName("title") public String title;
    @SerializedName("num_comments") public int commentCount;
    @SerializedName("ups") public int upvoteCount;
    @SerializedName("name") public String name;
    public String kind;
}


text:
namespace Dropbox.Api.TeamLog
{
    using sys = System;
    using col = System.Collections.Generic;
    using re = System.Text.RegularExpressions;

    using enc = Dropbox.Api.Stone;

    /// <summary>
    /// <para>The admin console app policy object</para>
    /// </summary>
    public class AdminConsoleAppPolicy
    {
        #pragma warning disable 108

        /// <summary>
        /// <para>The encoder instance.</para>
        /// </summary>
        internal static enc.StructEncoder<AdminConsoleAppPolicy> Encoder = new AdminConsoleAppPolicyEncoder();

        /// <summary>
        /// <para>The decoder instance.</para>
        /// </summary>
        internal static enc.StructDecoder<AdminConsoleAppPolicy> Decoder = new AdminConsoleAppPolicyDecoder();

        /// <summary>
        /// <para>Initializes a new instance of the <see cref="AdminConsoleAppPolicy" />
        /// class.</para>
        /// </summary>
        public AdminConsoleAppPolicy()
        {
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is Allow</para>
        /// </summary>
        public bool IsAllow
        {
            get
            {
                return this is Allow;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a Allow, or <c>null</c>.</para>
        /// </summary>
        public Allow AsAllow
        {
            get
            {
                return this as Allow;
            }
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is Block</para>
        /// </summary>
        public bool IsBlock
        {
            get
            {
                return this is Block;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a Block, or <c>null</c>.</para>
        /// </summary>
        public Block AsBlock
        {
            get
            {
                return this as Block;
            }
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is Default</para>
        /// </summary>
        public bool IsDefault
        {
            get
            {
                return this is Default;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a Default, or <c>null</c>.</para>
        /// </summary>
        public Default AsDefault
        {
            get
            {
                return this as Default;
            }
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is Other</para>
        /// </summary>
        public bool IsOther
        {
            get
            {
                return this is Other;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a Other, or <c>null</c>.</para>
        /// </summary>
        public Other AsOther
        {
            get
            {
                return this as Other;
            }
        }

        #region Encoder class

        /// <summary>
        /// <para>Encoder for  <see cref="AdminConsoleAppPolicy" />.</para>
        /// </summary>
        private class AdminConsoleAppPolicyEncoder : enc.StructEncoder<AdminConsoleAppPolicy>
        {
            /// <summary>
            /// <para>Encode fields of given value.</para>
            /// </summary>
            /// <param name="value">The value.</param>
            /// <param name="writer">The writer.</param>
            public override void EncodeFields(AdminConsoleAppPolicy value, enc.IJsonWriter writer)
            {
                if (value is Allow)
                {
                    WriteProperty(".tag", "allow", writer, enc.StringEncoder.Instance);
                    Allow.Encoder.EncodeFields((Allow)value, writer);
                    return;
                }
                if (value is Block)
                {
                    WriteProperty(".tag", "block", writer, enc.StringEncoder.Instance);
                    Block.Encoder.EncodeFields((Block)value, writer);
                    return;
                }
                if (value is Default)
                {
                    WriteProperty(".tag", "default", writer, enc.StringEncoder.Instance);
                    Default.Encoder.EncodeFields((Default)value, writer);
                    return;
                }
                if (value is Other)
                {
                    WriteProperty(".tag", "other", writer, enc.StringEncoder.Instance);
                    Other.Encoder.EncodeFields((Other)value, writer);
                    return;
                }
                throw new sys.InvalidOperationException();
            }
        }

        #endregion

        #region Decoder class

        /// <summary>
        /// <para>Decoder for  <see cref="AdminConsoleAppPolicy" />.</para>
        /// </summary>
        private class AdminConsoleAppPolicyDecoder : enc.UnionDecoder<AdminConsoleAppPolicy>
        {
            /// <summary>
            /// <para>Create a new instance of type <see cref="AdminConsoleAppPolicy"
            /// />.</para>
            /// </summary>
            /// <returns>The struct instance.</returns>
            protected override AdminConsoleAppPolicy Create()
            {
                return new AdminConsoleAppPolicy();
            }

            /// <summary>
            /// <para>Decode based on given tag.</para>
            /// </summary>
            /// <param name="tag">The tag.</param>
            /// <param name="reader">The json reader.</param>
            /// <returns>The decoded object.</returns>
            protected override AdminConsoleAppPolicy Decode(string tag, enc.IJsonReader reader)
            {
                switch (tag)
                {
                    case "allow":
                        return Allow.Decoder.DecodeFields(reader);
                    case "block":
                        return Block.Decoder.DecodeFields(reader);
                    case "default":
                        return Default.Decoder.DecodeFields(reader);
                    default:
                        return Other.Decoder.DecodeFields(reader);
                }
            }
        }

        #endregion

        /// <summary>
        /// <para>The allow object</para>
        /// </summary>
        public sealed class Allow : AdminConsoleAppPolicy
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<Allow> Encoder = new AllowEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<Allow> Decoder = new AllowDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="Allow" /> class.</para>
            /// </summary>
            private Allow()
            {
            }

            /// <summary>
            /// <para>A singleton instance of Allow</para>
            /// </summary>
            public static readonly Allow Instance = new Allow();

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="Allow" />.</para>
            /// </summary>
            private class AllowEncoder : enc.StructEncoder<Allow>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(Allow value, enc.IJsonWriter writer)
                {
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="Allow" />.</para>
            /// </summary>
            private class AllowDecoder : enc.StructDecoder<Allow>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="Allow" />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override Allow Create()
                {
                    return Allow.Instance;
                }

            }

            #endregion
        }

        /// <summary>
        /// <para>The block object</para>
        /// </summary>
        public sealed class Block : AdminConsoleAppPolicy
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<Block> Encoder = new BlockEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<Block> Decoder = new BlockDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="Block" /> class.</para>
            /// </summary>
            private Block()
            {
            }

            /// <summary>
            /// <para>A singleton instance of Block</para>
            /// </summary>
            public static readonly Block Instance = new Block();

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="Block" />.</para>
            /// </summary>
            private class BlockEncoder : enc.StructEncoder<Block>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(Block value, enc.IJsonWriter writer)
                {
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="Block" />.</para>
            /// </summary>
            private class BlockDecoder : enc.StructDecoder<Block>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="Block" />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override Block Create()
                {
                    return Block.Instance;
                }

            }

            #endregion
        }

        /// <summary>
        /// <para>The default object</para>
        /// </summary>
        public sealed class Default : AdminConsoleAppPolicy
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<Default> Encoder = new DefaultEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<Default> Decoder = new DefaultDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="Default" /> class.</para>
            /// </summary>
            private Default()
            {
            }

            /// <summary>
            /// <para>A singleton instance of Default</para>
            /// </summary>
            public static readonly Default Instance = new Default();

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="Default" />.</para>
            /// </summary>
            private class DefaultEncoder : enc.StructEncoder<Default>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(Default value, enc.IJsonWriter writer)
                {
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="Default" />.</para>
            /// </summary>
            private class DefaultDecoder : enc.StructDecoder<Default>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="Default" />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override Default Create()
                {
                    return Default.Instance;
                }

            }

            #endregion
        }

        /// <summary>
        /// <para>The other object</para>
        /// </summary>
        public sealed class Other : AdminConsoleAppPolicy
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<Other> Encoder = new OtherEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<Other> Decoder = new OtherDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="Other" /> class.</para>
            /// </summary>
            private Other()
            {
            }

            /// <summary>
            /// <para>A singleton instance of Other</para>
            /// </summary>
            public static readonly Other Instance = new Other();

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="Other" />.</para>
            /// </summary>
            private class OtherEncoder : enc.StructEncoder<Other>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(Other value, enc.IJsonWriter writer)
                {
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="Other" />.</para>
            /// </summary>
            private class OtherDecoder : enc.StructDecoder<Other>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="Other" />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override Other Create()
                {
                    return Other.Instance;
                }

            }

            #endregion
        }
    }
}