text:
package com.github.ckwen.je.x.otp;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 *

 * Title: OTPStorePushTest
 *

 *

 * Description:
 *

 *
 * @author Eric.CK.Wen
 * @created 2016年9月27日 下午7:58:23
 * @modified [who date description]
 * @check [who date description]
 */
public class OTPStorePushTest {

    private CloseableHttpClient httpclient;

    private CloseableHttpResponse response;

    @Before
    public void setUp() throws Exception {
        httpclient = HttpClients.createDefault();
    }

    @After
    public void tearDown() throws Exception {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void testGet() {

        HttpGet get = new HttpGet("http://pre-prod.cuflash.com/api/info/anyExtractList/");
        try {
            response = httpclient.execute(get);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("deprecation")
    @Test
    public void testPostLogin() {
        // String url = "http://pre-prod.cuflash.com/api/login";

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", "13604119999"));
        params.add(new BasicNameValuePair("password", "123456"));

        String queryString = URLEncodedUtils.format(params, "utf-8");
        URI uri = null;
        try {
            uri = URIUtils.createURI("http", "pre-prod.cuflash.com", 80, "/api/login", queryString, null);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        HttpPost post = new HttpPost(uri);

        try {
            response = httpclient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("deprecation")
    @Test
    public void testPostStorePush() {
        // String url = "http://pre-prod.cuflash.com/api/mystore/push";

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("id", "17"));
        params.add(new BasicNameValuePair("price", "13"));
        params.add(new BasicNameValuePair("quantity", "1"));
        params.add(new BasicNameValuePair("instanceType", "1"));

        String queryString = URLEncodedUtils.format(params, "utf-8");
        URI uri = null;
        try {
            uri = URIUtils.createURI("http", "pre-prod.cuflash.com", 80, "/api/mystore/push", queryString, null);

        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        HttpPost post = new HttpPost(uri);

        post.setHeader("Cookie", "JSESSIONID=F8AE8E56EC0FBDE1586850CB392552C9");

        for (int i = 0; i < 2; i++) {
            try {
                response = httpclient.execute(post);
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    System.out.println(EntityUtils.toString(entity));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}


text:
"""Juju GUI server entry point.

Arguments example:
    --guiroot="/var/lib/juju/agents/unit-juju-gui-0/charm/juju-gui/build-prod"
    --apiurl="wss://ec2-75-101-177-185.compute-1.example.com:17070"
    --apiversion="go"
    --sslpath="/etc/ssl/juju-gui"
    --tests_root="/var/lib/juju/agents/unit-juju-gui-0/charm/juju-gui/test/"
    --insecure
    --sandbox
    --logging=debug|info|warning|error
    --charmworldurl="https://manage.jujucharms.com/"

The --sslpath option is ignored if --insecure is set.
The --apiurl and --apiversion options are ignored if --sandbox is set.
"""

from guiserver import manage

if __name__ == '__main__':
    manage.setup()
    manage.run()

redpajama_set_name: RedPajamaGithub


text:
// -----------------------------------------------------------------------
// <copyright file="Trace.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

using System.Diagnostics;
using Cinchcast.Roque.Core;

namespace Cinchcast.Roque.Common
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// Work service implementation example
    /// </summary>
    public class Trace : ITrace
    {

        public void TraceVerbose(string format, params object[] arguments)
        {
            RoqueTrace.Source.Trace(TraceEventType.Verbose, format, arguments);
        }

        public void TraceInformation(string format, params object[] arguments)
        {
            RoqueTrace.Source.Trace(TraceEventType.Information, format, arguments);
        }

        public void TraceError(string format, params object[] arguments)
        {
            RoqueTrace.Source.Trace(TraceEventType.Error, format, arguments);
        }

        public void TraceWarning(string format, params object[] arguments)
        {
            RoqueTrace.Source.Trace(TraceEventType.Warning, format, arguments);
        }

        public void TracePing()
        {
            RoqueTrace.Source.Trace(TraceEventType.Information, "ping");
        }

        public void TraceInformationString(string message)
        {
            RoqueTrace.Source.Trace(TraceEventType.Information, message);
        }
    }
}


text:
/* GENERAL */
.italic {
  font-style: italic;
}

/* I could use li > span here to save me from adding the bold class, but it seems that this way things get more clear. Am I right? */
.bold {
  font-weight: bold;
}

.border {
  border: 1px solid #c9c9c9;
}

/* CARD */
.card {
  width: 300px;
  padding: 0 18px 18px;
  border-radius: 8px;
  box-shadow: 5px 5px 1px #bababa;
  background: #fafafa;
}

.card .title {
  padding: 0 0 5px;
}

.card .image {
  border-radius: 4px;
}

.card .info {
  width: 262px; /* It would be nice to write something like this here: result = card width - side padding - border width . Is there a way to do this? */
  padding: 0 18px 10px;
  margin: 18px 0 0;
  text-align: justify;
  background: white;
}

/* Would it be better to use .card > .info > .list? Or should I use a single class card-info-list? Or neither xD ? So many possibilities! */
.card .info .list {
  padding: 0;
  list-style: none;
}


text:
.scroller {
	overflow: hidden;
	color: white;
	margin: 0;
	text-align: center;
	font-family: 'Orbitron', sans-serif;
	text-shadow: 4px 4px 12px black;
}

.scroller a:link {
	color: yellow;
}

.scroller a:visited {
	color: yellow;
}

.scroller > div {
	position: absolute;
	margin-left: 120%;
	animation: wave 2s ease-in-out infinite alternate, skew 2s ease-in-out 0.5s infinite alternate;
}

.scroller > div > div {
	position: absolute;
	white-space: nowrap;
	font-size: 60px;
	font-weight: bold;
	color: yellow;
	animation: scrolling 180s linear infinite, colors 8s linear infinite;
}

@keyframes wave {
	from { top: 45%; }
	to   { top: 55%; }
}

@keyframes skew {
	from { transform: skewY(-1.5deg); }
	to   { transform: skewY(1.5deg); }
}

@keyframes scrolling {
	from { left: 0; }
	to   { left: -64000px; }
}

@keyframes colors {
	from { filter: hue-rotate(0deg); -webkit-filter: hue-rotate(0deg); }
	to { filter: hue-rotate(360deg); -webkit-filter: hue-rotate(360deg); }
}


text:
A Ruby script designed to print out a timeline of upcoming events from multiple Google Calendars.

## Getting Started

- Tested with Ruby 2.3.3
- `bundle install --path=vendor/bundle`
- Can make use of `wkhtmltopdf`, if available, to automate display and printing.
  - Tested with `wkhtmltopdf` version 0.12.4 on OSX.
- You will need to create a [Google API Project](https://console.developers.google.com/apis/api/calendar) with an OAuth 2.0 client ID.
  - Download the provided credentials as JSON, and store in `client_secret.json`
- You will need to populate the `calendars.json` with a list of Google Calendar ID's

## Initial Run

- `bundle exec ruby timeline_printout.rb`
- You will be prompted, at the command line, to authorize the script (via OAuth 2.0), to access calendars that your user has access to.

## Usage

- To generate the HTML timeline: `bundle exec ruby timeline_printout.rb > timeline_printout.rb`
- To generate and open the HTML timeline with `wkhtmltopdf`: `./bin/timeline_printout`

## License

See [LICENSE](LICENSE) file.


text:
@implementation MHSlideMenuItem

- (instancetype)initWithTitle:(NSString *)title image:(UIImage *)image selectedImage:(UIImage *)selectedImage{

    self = [super init];
    if (self) {
        if (title) {
            _title = title;
        }
        if (image) {
            _icon = image;
        }
        if (selectedImage) {
            _selectedIcon = selectedImage;
        }
    }
    return self;
}

@end


text:
import {StyleSheet} from 'react-native'
import { Metrics, Colors } from '../../Themes/'

export default StyleSheet.create({
  navButtonLeft: {
    marginTop: Metrics.doubleBaseMargin,
    marginLeft: Metrics.baseMargin,
    backgroundColor: Colors.transparent,
    width: Metrics.icons.medium
  },
  navButtonRight: {
    // marginTop: Metrics.doubleBaseMargin,
    // marginRight: Metrics.baseMargin,
    backgroundColor: Colors.transparent,
    width: Metrics.icons.medium
  }
})


text:
<?php

namespace Guttmann;

use \DateTime;

class FinancialYear
{

    /**
     * @var DateTime
     */
    private $startDate;

    /**
     * @var DateTime
     */
    private $endDate;

    public function __construct(DateTime $startDate, DateTime $endDate)
    {
        $this->startDate = $startDate;
        $this->endDate = $endDate;
    }

    public function getStartDate()
    {
        return $this->startDate;
    }

    public function getEndDate()
    {
        return $this->endDate;
    }

    /**
     * Get the FinancialYear that contains the given $date
     *
     * @param DateTime $date
     * @return FinancialYear
     */
    public static function getByDate(DateTime $date)
    {
        $month = $date->format('n');
        $year = $date->format('Y');

        if ($month <= 6) {
            $startYear = $year - 1;
        } else {
            $startYear = $year;
        }

        $startDateTime = DateTime::createFromFormat('Y-m-d H:i:s', $startYear . '-07-01 00:00:00');
        $endDateTime = DateTime::createFromFormat('Y-m-d H:i:s', ($startYear + 1) . '-06-30 23:59:59');

        return new FinancialYear($startDateTime, $endDateTime);
    }

    /**
     * Get an array of FinancialYears that encompass the $rangeStart and $rangeEnd dates
     *
     * @param DateTime $rangeStart
     * @param DateTime $rangeEnd
     * @return FinancialYear[]
     */
    public static function getByDateRange(DateTime $rangeStart, DateTime $rangeEnd)
    {
        $startFinancialYear = self::getByDate($rangeStart);
        $endFinancialYear = self::getByDate($rangeEnd);

        if ($startFinancialYear > $endFinancialYear) {
            throw new \Exception('End date is before start date');
        }

        $startYear = $startFinancialYear->getStartDate()->format('Y');
        $endYear = $endFinancialYear->getStartDate()->format('Y');

        $financialYears = array();

        for ($i = $startYear; $i <= $endYear; $i += 1) {
            $financialYears[] = self::getByDate(
                DateTime::createFromFormat('Y-m-d H:i:s', $i . '-07-01 00:00:00')
            );
        }

        return $financialYears;
    }

}


text:
require 'spec_helper'

require 'mv/core/services/create_migration_validators_table'

describe Mv::Core::ActiveRecord::BaseDecorator do
  def db
    ::ActiveRecord::Base.connection
  end

  before do
    db.drop_table(:table_name) if db.data_source_exists?(:table_name)
    db.create_table :table_name do |t|
      t.column :column_name, column_type
    end

  end

  let(:klass) {
    Object.send(:remove_const, :TestBaseDecoratorClass) if defined?(TestBaseDecoratorClass)

    TestBaseDecoratorClass = Class.new(::ActiveRecord::Base) do
      self.table_name = 'table_name'

      enforce_migration_validations
    end
  }

  subject { klass.new(column_name: :column_value) }

  let(:column_type) { :string }

  context 'when migration validators table is not initialized' do
    it 'does not raise an error' do
      expect { subject.valid? }.not_to raise_error
    end
  end

  context 'when migration validators table properly initialized' do
    before do
      Mv::Core::Services::CreateMigrationValidatorsTable.new.execute

      create(:migration_validator,
             table_name: :table_name,
             column_name: :column_name,
             validation_type: validation_type,
             options: opts)
    end

    describe "when custom validation defined" do
      let(:validation_type) { :custom }
      let(:opts) { { statement: '{column_name} IS NOT NULL'} }

      it { is_expected.not_to validate_presence_of(:column_name) }
    end

    describe "when presence validation defined" do
      let(:validation_type) { :presence }
      let(:opts) { {} }

      it { is_expected.to validate_presence_of(:column_name) }
    end

    describe "when uniqueness validation defined" do
      let(:validation_type) { :uniqueness }
      let(:opts) { {} }

      it { is_expected.to validate_uniqueness_of(:column_name) }
    end

    describe "when absence validation defined" do
      let(:validation_type) { :absence }
      let(:opts) { {} }

      it { is_expected.to validate_absence_of(:column_name) }
    end

    describe "when inclusion validation defined" do
      let(:validation_type) { :inclusion }

      describe "array" do
        let(:opts) { { in: ['str1', 'str2'] } }

        it { is_expected.to validate_inclusion_of(:column_name).in_array(['str1', 'str2']) }
      end

      describe "range" do
        let(:column_type) { :integer }
        let(:opts) { { in: 1..3 } }

        it { is_expected.to validate_inclusion_of(:column_name).in_range(1..3) }
      end
    end

    describe "when exclusion validation defined" do
      let(:validation_type) { :exclusion }

      describe "array" do
        let(:opts) { { in: ['str1', 'str2'] } }

        it { is_expected.to validate_exclusion_of(:column_name).in_array(['str1', 'str2']) }
      end

      describe "range" do
        let(:column_type) { :integer }
        let(:opts) { { in: 1..3 } }

        it { is_expected.to validate_exclusion_of(:column_name).in_range(1..3) }
      end
    end

    describe "when length validation defined" do
      let(:validation_type) { :length }

      describe ":in" do
        let(:opts) { { in: 1..3 } }

        it { is_expected.to validate_length_of(:column_name) }
      end

      describe ":is" do
        let(:opts) { { is: 1 } }

        it { is_expected.to validate_length_of(:column_name).is_equal_to(1) }
      end

      describe ":within" do
        let(:opts) { { within: 1..3 } }

        it { is_expected.to validate_length_of(:column_name) }
      end

      describe ":minimum" do
        let(:opts) { { minimum: 1 } }

        it { is_expected.to validate_length_of(:column_name).is_at_least(1) }
      end

      describe ":maximum" do
        let(:opts) { { maximum: 1 } }

        it { is_expected.to validate_length_of(:column_name).is_at_most(1) }
      end
    end
  end

end


text:
<?php if ( ! defined('EXT')) { exit('Invalid file request'); }

// -----------------------------------------------------------------------------

/**
 * Model used for database interactions with polling module and fieldtype
 */
class Vwm_polls_m extends CI_Model {

	private $entry_id, $field_id, $field_name;
	public $poll_options = array();
	public $valid_poll_option_ids = array();
	public $total_votes = 0;
	private $hash;

	/**
	 * Model construct
	 *
	 * @access public
	 * @return void
	 */
	public function __construct()
	{
		// Load helper functions
		$this->load->helper('vwm_polls');
	}

	/**
	 * Set entry ID
	 *
	 * @access public
	 * @param $entry_id int Entry ID
	 * @return object
	 */
	public function entry_id($entry_id)
	{
		$this->entry_id = abs((int)$entry_id);
		return $this;
	}

	/**
	 * Set field ID and field name
	 *
	 * @access public
	 * @param $field_id int Field ID
	 * @return object
	 */
	public function field_id($field_id)
	{
		$this->field_id = abs((int)$field_id);

		// Generate field name while we are at it
		$this->field_name = 'field_id_' . $this->field_id;

		return $this;
	}

	public function set_hash($hash)
	{
		$this->hash = $hash;
		return $this;
	}

	/**
	 * Get poll options for a given poll
	 *
	 * @access public
	 * @param $order string Option order ("custom", "alphabetical", "reverse_alphabetical", "asc", "desc", or "random")
	 * @param $other_votes bool
	 * @return array
	 */
	public function poll_options($order = 'custom', $other_votes = FALSE)
	{
		$this->db
			->where('entry_id', $this->entry_id)
			->where('field_id', $this->field_id);

		switch ($order)
		{
			case 'alphabetical':
				$this->db->order_by('text', 'ASC');
				break;
			case 'reverse_alphabetical':
				$this->db->order_by('text', 'DESC');
				break;
			case 'asc':
				$this->db->order_by('votes', 'ASC');
				break;
			case 'desc':
				$this->db->order_by('votes', 'DESC');
				break;
			case 'random':
				$this->db->order_by('id', 'RANDOM');
				break;
			default: // Defalut to "custom"
				$this->db->order_by('custom_order', 'ASC');
				break;
		}

		// Get poll options
		$query = $this->db->get('vwm_polls_options');

		// Reset poll options, total votes, & valid poll option IDs
		$this->poll_options = array();
		$this->total_votes = 0;
		$this->valid_poll_option_ids = array();

		if ($query->num_rows() > 0)
		{
			foreach ($query->result() as $row)
			{
				// Add this option ID to the array of valid poll option IDs
				$this->valid_poll_option_ids[] = $row->id;

				// Update votes total
				$this->total_votes += $row->votes;

				$this->poll_options[$row->id] = array(
					'id' => $row->id,
					'order' => $row->custom_order,
					'type' => $row->type,
					'color' => $row->color,
					'text' => htmlspecialchars($row->text, ENT_QUOTES, 'UTF-8'),
					'votes' => $row->votes
				);
			}
		}

		// If we need to grab all the "other" votes
		if ($other_votes)
		{
			$this->poll_other_options();
		}

		return $this->poll_options;
	}

	/**
	 * Get all other votes for this poll and add to poll_options array
	 *
	 * @access public
	 * @return object
	 */
	public function poll_other_options()
	{
		$where_in = $this->poll_options ? array_keys($this->poll_options) : '';

		$query = $this->db
			->where_in('poll_option_id', $where_in)
			->get('vwm_polls_other_votes');

		if ($query->num_rows() > 0)
		{
			foreach ($query->result() as $row)
			{
				$this->poll_options[$row->poll_option_id]['other_votes'][] = htmlspecialchars($row->text, ENT_QUOTES, 'UTF-8');
			}
		}

		return $this;
	}

	/**
	 * Prep options for template
	 *
	 * Add in option_name and user_vote
	 *
	 * @access public
	 * @return void
	 */
	public function poll_options_template_prep()
	{
		// Search cookies for previous votes
		$previous_votes = $this->previous_votes();

		foreach ($this->poll_options as &$option)
		{
			$option['other_name'] = $option['type'] == 'other' ? 'vwm_polls_other_options[' . $option['id'] . ']' : NULL; // Used in EE templates so user can submit a text input
			$option['user_vote'] = in_array($option['id'], $previous_votes) ? TRUE : FALSE; // Check cookies to see if user has voted for this option
		}
	}

	/**
	 * Get user previous votes from cookies
	 *
	 * @access private
	 * @return array
	 */
	public function previous_votes()
	{
		$votes = array();
		$cookie = ee()->input->cookie($this->entry_id . '-' . $this->field_id);

		if ( !empty($cookie) )
		{
			$votes = json_decode($cookie, TRUE);
		}

		return $votes;
	}

	/**
	 * Update (or delete) a poll option
	 *
	 * @access public
	 * @param $id int Option ID
	 * @param $type string Option type ("defined" or "other")
	 * @param $color string Option hex color
	 * @param $text string Option text
	 * @param $order bool|string "defined" or "other"
	 * @return void
	 */
	public function update_option($id, $type, $color, $text, $order = false)
	{
		// Option type (make sure it is either "defined" or "other")
		$type = in_array($type, array('defined', 'other')) ? $type : 'defined';

		// Option color
		$color = hex_color($color);

		// Option text (trimmed)
		$text = trim($text);

		// If the text has a value (update option)
		if ($text)
		{
			$data = array(
				'type' => $type,
				'text' => $text,
				'color' => $color
			);

			if ($order !== false) { // strict type check since this could be 0
				$data['custom_order'] = $order;
			}

			$this->db
				->where('id', $id)
				->where('entry_id', $this->entry_id)
				->where('field_id', $this->field_id)
				->update('vwm_polls_options', $data);
		}
		// If there is no text (delete option)
		else
		{
			$this->remove_option($id);
		}
	}

	/**
	 * Delete a poll option
	 *
	 * @access public
	 * @param $id int Option ID
	 * @return bool
	 */
	public function remove_option($id)
	{
		// Remove all "other" votes
		$this->db
			->where('poll_option_id', $id)
			->delete('vwm_polls_other_votes');

		// Remove poll option
		$this->db
			->where('id', $id)
			->where('entry_id', $this->entry_id)
			->where('field_id', $this->field_id)
			->limit(1)
			->delete('vwm_polls_options');

		return $this->db->affected_rows() > 0 ? TRUE : FALSE;
	}

	/**
	 * Insert a new option
	 *
	 * @access public
	 * @param $type string Option type ("defined" or "other")
	 * @param $color string Option hex color
	 * @param $text string Option text
	 * @param $order int Option order
	 * @return bool
	 */
	public function insert_option($type, $color, $text, $order = 0)
	{
		// Order
		$order = abs((int)$order);

		// Option type (make sure it is either "defined" or "other")
		$type = in_array($type, array('defined', 'other')) ? $type : 'defined';

		// Option color
		$color = hex_color($color);

		// Option text (trimmed)
		$text = trim($text);

		// If the text is has a value (insert option)
		if ($text)
		{
			$data = array(
				'custom_order' => $order,
				'type' => $type,
				'text' => $text,
				'color' => $color,
				'entry_id' => $this->entry_id,
				'field_id' => $this->field_id
			);

			$this->db->insert('vwm_polls_options', $data);

			return $this->db->affected_rows() > 0 ? TRUE : FALSE;
		}

		return FALSE;
	}

	/**
	 * Get poll settings
	 *
	 * @access public
	 * @return array
	 */
	public function poll_settings()
	{
		$settings = array();

		// Get poll data
		$query = $this->db
			->where('entry_id', $this->entry_id)
			->limit(1)
			->get('channel_data');

		if ($query->num_rows() > 0)
		{
			$data = $query->row_array();

			// Make sure this field has poll settings
			if ( isset($data[$this->field_name]) )
			{
				$settings = json_decode($data[$this->field_name], TRUE);
			}
		}

		return $settings;
	}

	/**
	 * Cast a vote
	 *
	 * @access public
	 * @param $option_id int Option ID
	 * @return void
	 */
	public function cast_vote($option_id)
	{
		$member_id = $this->session->userdata('member_id');

		$data = array(
			'entry_id' => $this->entry_id,
			'field_id' => $this->field_id,
			'poll_option_id' => $option_id,
			'member_id' => empty($member_id) ? NULL : (int)$member_id,
			'ip_address' => $this->session->userdata('ip_address'),
			'hash' => $this->hash,
			'timestamp' => ee()->localize->now
		);

		// Update poll votes table
		$this->db->insert('vwm_polls_votes', $data);

		// Update poll options table (+1 to the votes tally)
		$this->db
			->where('id', $option_id)
			->set('votes', 'votes + 1', FALSE)
			->update('vwm_polls_options');
	}

	/**
	 * Remove all votes for a provided member and return number of removed votes
	 *
	 * @param int $entry_id
	 * @param int $field_id
	 * @param int $member_id
	 * @return int
	 */
	public function remove_votes($entry_id, $field_id, $member_id)
	{
		if ( empty($member_id) )
		{
			return FALSE;
		}

		// Key value array of option ID and total number of votes
		$options = array();

		// Get all votes this user made for this poll
		$votes = $this->db
			->where('entry_id', $entry_id)
			->where('field_id', $field_id)
			->where('member_id', $member_id)
			->get('vwm_polls_votes')->result_array();

		if ( !empty($votes) )
		{
			foreach($votes as $vote)
			{
				if ( isset($options[ $vote['poll_option_id'] ]) )
				{
					$options[ $vote['poll_option_id'] ]++;
				}
				else
				{
					$options[ $vote['poll_option_id'] ] = 1;
				}
			}
		}

		if ( !empty($options) )
		{
			foreach($options as $option_id => $total)
			{
				$this->db
					->where('id', $option_id)
					->set('votes', 'votes - ' . $total, FALSE)
					->update('vwm_polls_options');

				// @todo need to remove other votes
			}
		}

		// Remove all votes this user made for this poll
		$this->db
			->where('entry_id', $entry_id)
			->where('field_id', $field_id)
			->where('member_id', $member_id)
			->delete('vwm_polls_votes');

		return $this->db->affected_rows();
	}

	/**
	 * Record an "other" vote
	 *
	 * @access public
	 * @param $option_id int Option ID
	 * @param $text string Other option text
	 * @return void
	 */
	public function record_other_vote($option_id, $text)
	{
		$data = array(
			'poll_option_id' => $option_id,
			'text' => $text
		);

		$this->db->insert('vwm_polls_other_votes', $data);
	}

}

// EOF


text:
package com.hunantv.fw.view;

import java.io.IOException;
import java.io.Writer;

import com.alibaba.fastjson.JSON;
import com.hunantv.fw.result.Result;

public class JsonView extends AbsView {

	public JsonView(Object v) {
		this.v = v;
	}

	@Override
	public String render() {
		if (v instanceof Result)
			return ((Result) v).toJson();
		return JSON.toJSONString(v);
	}

	@Override
    public void renderTo(Writer out) throws IOException {
	    out.write(this.render());
    }
}


text:
function ConvertPtToMm {
<#
    .SYNOPSIS
        Convert points into millimeters
#>
    [CmdletBinding()]
    [OutputType([System.Single])]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias('pt')]
        [System.Single] $Point
    )
    process {

        return [System.Math]::Round(($Point / 72) * 25.4, 2);

    }
} #end function ConvertPtToMm

function ConvertPxToMm {
<#
    .SYNOPSIS
        Convert pixels into millimeters (default 96dpi)
#>
    [CmdletBinding()]
    [OutputType([System.Single])]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias('px')]
        [System.Single] $Pixel,

        [Parameter(ValueFromPipelineByPropertyName)]
        [System.Int16] $Dpi = 96
    )
    process {

        return [System.Math]::Round((25.4 / $Dpi) * $Pixel, 2);

    }
} #end function ConvertPxToMm

function ConvertInToMm {
<#
    .SYNOPSIS
        Convert inches into millimeters
#>
    [CmdletBinding()]
    [OutputType([System.Single])]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias('in')]
        [System.Single] $Inch
    )
    process {

        return [System.Math]::Round($Inch * 25.4, 2);

    }
} #end function ConvertInToMm

function ConvertMmToIn {
<#
    .SYNOPSIS
        Convert millimeters into inches
#>
    [CmdletBinding()]
    [OutputType([System.Single])]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias('mm','Millimetre')]
        [System.Single] $Millimeter
    )
    process {

        return [System.Math]::Round($Millimeter / 25.4, 2);

    }
} #end function ConvertMmToIn

function ConvertMmToPt {
<#
    .SYNOPSIS
        Convert millimeters into points
#>
    [CmdletBinding()]
    [OutputType([System.Single])]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias('mm','Millimetre')]
        [System.Single] $Millimeter
    )
    process {
        return ((ConvertMmToIn $Millimeter) / 0.0138888888888889);

    }
} #end function ConvertMmToPt

function ConvertMmToTwips {
<#
    .SYNOPSIS
        Convert millimeters into twips
    .NOTES
        1 twip = 1/20th pt
#>
    [CmdletBinding()]
    [OutputType([System.Single])]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias('mm','Millimetre')]
        [System.Single] $Millimeter
    )
    process {

        return (ConvertMmToIn -Millimeter $Millimeter) * 1440;

    }
} #end function ConvertMmToTwips

function ConvertMmToOctips {
<#
    .SYNOPSIS
        Convert millimeters into octips
    .NOTES
        1 "octip" = 1/8th pt
#>
    [CmdletBinding()]
    [OutputType([System.Single])]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias('mm','Millimetre')]
        [System.Single] $Millimeter
    )
    process {

        return (ConvertMmToIn -Millimeter $Millimeter) * 576;

    }
} #end function ConvertMmToOctips

function ConvertMmToEm {
<#
    .SYNOPSIS
        Convert millimeters into em
#>
    [CmdletBinding()]
    [OutputType([System.Single])]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias('mm','Millimetre')]
        [System.Single] $Millimeter
    )
    process {

        return [System.Math]::Round($Millimeter / 4.23333333333333, 2);

    }
} #end function ConvertMmToEm

function ConvertMmToPx {
<#
    .SYNOPSIS
        Convert millimeters into pixels (default 96dpi)
#>
    [CmdletBinding()]
    [OutputType([System.Single])]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias('mm','Millimetre')]
        [System.Single] $Millimeter,

        [Parameter(ValueFromPipelineByPropertyName)]
        [System.Int16] $Dpi = 96
    )
    process {

        $pixels = [System.Int16] ((ConvertMmToIn -Millimeter $Millimeter) * $Dpi);
        if ($pixels -lt 1) { return 1; }
        else { return $pixels; }

    }
} #end function ConvertMmToPx


text:
// [START kms_iam_get_policy]

using Google.Cloud.Iam.V1;
using Google.Cloud.Kms.V1;
using System;

public class IamGetPolicySample
{
    public Policy IamGetPolicy(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the resource name.
        CryptoKeyName resourceName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // The resource name could also be a key ring.
        // var resourceName = new KeyRingName(projectId, locationId, keyRingId);

        // Get the current IAM policy.
        Policy policy = client.IAMPolicyClient.GetIamPolicy(
            new GetIamPolicyRequest
            {
                ResourceAsResourceName = resourceName
            });

        // Print the policy.
        foreach (Binding b in policy.Bindings)
        {
            String role = b.Role;

            foreach (String member in b.Members)
            {
                // ...
            }
        }

        // Return the policy.
        return policy;
    }
}
// [END kms_iam_get_policy]


text:
<?php

declare(strict_types=1);

namespace BlueEvent\Event\Config;

use Laminas\Config\Reader\Ini;

class IniConfig implements ConfigReader
{
    /**
     * @param string $path
     * @return array
     */
    public function readConfig(string $path): array
    {
        $reader = new Ini();
        return $reader->fromFile($path);
    }
}


text:
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.core.paginator import InvalidPage, Paginator
from django.db import models
from django.http import HttpResponseRedirect
from django.template.response import SimpleTemplateResponse, TemplateResponse
from django.utils.datastructures import SortedDict
import sys
if sys.version_info.major < 3:
   from django.utils.encoding import force_unicode as force_text, smart_unicode as smart_text
else:
   from django.utils.encoding import force_text, smart_text
from django.utils.html import escape, conditional_escape
from django.utils.safestring import mark_safe
from django.utils.text import capfirst
from django.utils.translation import ugettext as _

from xadmin.util import lookup_field, display_for_field, label_for_field, boolean_icon

from xadmin.views.base import ModelAdminView, filter_hook, inclusion_tag, csrf_protect_m

# List settings
ALL_VAR = 'all'
ORDER_VAR = 'o'
PAGE_VAR = 'p'
TO_FIELD_VAR = 't'
COL_LIST_VAR = '_cols'
ERROR_FLAG = 'e'

DOT = '.'

# Text to display within change-list table cells if the value is blank.
EMPTY_CHANGELIST_VALUE = _('Null')

class FakeMethodField(object):
    """
    This class used when a column is an model function, wrap function as a fake field to display in select columns.
    """
    def __init__(self, name, verbose_name):
        # Initial comm field attrs
        self.name = name
        self.verbose_name = verbose_name
        self.primary_key = False

class ResultRow(dict):
    pass

class ResultItem(object):

    def __init__(self, field_name, row):
        self.classes = []
        self.text = ' '
        self.wraps = []
        self.tag = 'td'
        self.tag_attrs = []
        self.allow_tags = False
        self.btns = []
        self.menus = []
        self.is_display_link = False
        self.row = row
        self.field_name = field_name
        self.field = None
        self.attr = None
        self.value = None

    @property
    def label(self):
        text = mark_safe(
            self.text) if self.allow_tags else conditional_escape(self.text)
        if force_text(text) == '':
            text = mark_safe(' ')
        for wrap in self.wraps:
            text = mark_safe(wrap % text)
        return text

    @property
    def tagattrs(self):
        return mark_safe(
            '%s%s' % ((self.tag_attrs and ' '.join(self.tag_attrs) or ''),
            (self.classes and (' class="%s"' % ' '.join(self.classes)) or '')))

class ResultHeader(ResultItem):

    def __init__(self, field_name, row):
        super(ResultHeader, self).__init__(field_name, row)
        self.tag = 'th'
        self.tag_attrs = ['scope="col"']
        self.sortable = False
        self.allow_tags = True
        self.sorted = False
        self.ascending = None
        self.sort_priority = None
        self.url_primary = None
        self.url_remove = None
        self.url_toggle = None

class ListAdminView(ModelAdminView):
    """
    Display models objects view. this class has ordering and simple filter features.
    """
    list_display = ('__str__',)
    list_display_links = ()
    list_display_links_details = False
    list_select_related = None
    list_per_page = 50
    list_max_show_all = 200
    list_exclude = ()
    list_thumb_fields = []
    search_fields = ()
    paginator_class = Paginator
    ordering = None

    # Change list templates
    object_list_template = None

    def init_request(self, *args, **kwargs):

        if not self.has_view_permission():
            raise PermissionDenied

        request = self.request
        request.session['LIST_QUERY'] = (self.model_info, self.request.META['QUERY_STRING'])

        self.pk_attname = self.opts.pk.attname
        self.lookup_opts = self.opts
        self.list_display = self.get_list_display()
        self.list_display_links = self.get_list_display_links()

        # Get page number parameters from the query string.
        try:
            self.page_num = int(request.GET.get(PAGE_VAR, 0))
        except ValueError:
            self.page_num = 0

        # Get params from request
        self.show_all = ALL_VAR in request.GET
        self.to_field = request.GET.get(TO_FIELD_VAR)
        self.params = dict(request.GET.items())

        if PAGE_VAR in self.params:
            del self.params[PAGE_VAR]
        if ERROR_FLAG in self.params:
            del self.params[ERROR_FLAG]

    @filter_hook
    def get_list_display(self):
        """
        Return a sequence containing the fields to be displayed on the list.
        """
        self.base_list_display = (COL_LIST_VAR in self.request.GET and self.request.GET[COL_LIST_VAR] != "" and \
            self.request.GET[COL_LIST_VAR].split('.')) or self.list_display
        return list(self.base_list_display)

    @filter_hook
    def get_list_display_links(self):
        """
        Return a sequence containing the fields to be displayed as links
        on the changelist. The list_display parameter is the list of fields
        returned by get_list_display().
        """
        if self.list_display_links or not self.list_display:
            return self.list_display_links
        else:
            # Use only the first item in list_display as link
            return list(self.list_display)[:1]

    def make_result_list(self):
        # Get search parameters from the query string.
        self.base_queryset = self.queryset()
        self.list_queryset = self.get_list_queryset()
        self.ordering_field_columns = self.get_ordering_field_columns()
        self.paginator = self.get_paginator()

        # Get the number of objects, with admin filters applied.
        self.result_count = self.paginator.count

        # Get the total number of objects, with no admin filters applied.
        # Perform a slight optimization: Check to see whether any filters were
        # given. If not, use paginator.hits to calculate the number of objects,
        # because we've already done paginator.hits and the value is cached.
        if not self.list_queryset.query.where:
            self.full_result_count = self.result_count
        else:
            self.full_result_count = self.base_queryset.count()

        self.can_show_all = self.result_count <= self.list_max_show_all
        self.multi_page = self.result_count > self.list_per_page

        # Get the list of objects to display on this page.
        if self.list_per_page == 0 or (self.show_all and self.can_show_all) or not self.multi_page:
            self.result_list = self.list_queryset._clone()
        else:
            if self.page_num >= self.paginator.num_pages:
                self.page_num = 0
            try:
                self.result_list = self.paginator.page(
                    self.page_num + 1).object_list
            except InvalidPage:
                if ERROR_FLAG in self.request.GET.keys():
                    return SimpleTemplateResponse('xadmin/views/invalid_setup.html', {
                        'title': _('Database error'),
                    })
                return HttpResponseRedirect(self.request.path + '?' + ERROR_FLAG + '=1')
        self.has_more = self.result_count > (
            self.list_per_page * self.page_num + len(self.result_list))

    @filter_hook
    def get_result_list(self):
        return self.make_result_list()

    @filter_hook
    def post_result_list(self):
        return self.make_result_list()

    @filter_hook
    def get_list_queryset(self):
        """
        Get model queryset. The query has been filted and ordered.
        """
        # First, get queryset from base class.
        queryset = self.queryset()

        # Use select_related() if one of the list_display options is a field
        # with a relationship and the provided queryset doesn't already have
        # select_related defined.
        if not queryset.query.select_related:
            if self.list_select_related:
                queryset = queryset.select_related()
            elif self.list_select_related is None:
                related_fields = []
                for field_name in self.list_display:
                    try:
                        field = self.opts.get_field(field_name)
                    except models.FieldDoesNotExist:
                        pass
                    else:
                        if isinstance(field.rel, models.ManyToOneRel):
                            related_fields.append(field_name)
                if related_fields:
                    queryset = queryset.select_related(*related_fields)
            else:
                pass

        # Then, set queryset ordering.
        queryset = queryset.order_by(*self.get_ordering())

        # Return the queryset.
        return queryset

    # List ordering
    def _get_default_ordering(self):
        ordering = []
        if self.ordering:
            ordering = self.ordering
        elif self.opts.ordering:
            ordering = self.opts.ordering
        return ordering

    @filter_hook
    def get_ordering_field(self, field_name):
        """
        Returns the proper model field name corresponding to the given
        field_name to use for ordering. field_name may either be the name of a
        proper model field or the name of a method (on the admin or model) or a
        callable with the 'admin_order_field' attribute. Returns None if no
        proper model field name can be matched.
        """
        try:
            field = self.opts.get_field(field_name)
            return field.name
        except models.FieldDoesNotExist:
            # See whether field_name is a name of a non-field
            # that allows sorting.
            if callable(field_name):
                attr = field_name
            elif hasattr(self, field_name):
                attr = getattr(self, field_name)
            else:
                attr = getattr(self.model, field_name)
            return getattr(attr, 'admin_order_field', None)

    @filter_hook
    def get_ordering(self):
        """
        Returns the list of ordering fields for the change list.
        First we check the get_ordering() method in model admin, then we check
        the object's default ordering. Then, any manually-specified ordering
        from the query string overrides anything. Finally, a deterministic
        order is guaranteed by ensuring the primary key is used as the last
        ordering field.
        """
        ordering = list(super(ListAdminView, self).get_ordering()
                        or self._get_default_ordering())
        if ORDER_VAR in self.params and self.params[ORDER_VAR]:
            # Clear ordering and used params
            ordering = [pfx + self.get_ordering_field(field_name) for n, pfx, field_name in
                        map(
                        lambda p: p.rpartition('-'),
                        self.params[ORDER_VAR].split('.'))
                        if self.get_ordering_field(field_name)]

        # Ensure that the primary key is systematically present in the list of
        # ordering fields so we can guarantee a deterministic order across all
        # database backends.
        pk_name = self.opts.pk.name
        if not (set(ordering) & set(['pk', '-pk', pk_name, '-' + pk_name])):
            # The two sets do not intersect, meaning the pk isn't present. So
            # we add it.
            ordering.append('-pk')

        return ordering

    @filter_hook
    def get_ordering_field_columns(self):
        """
        Returns a SortedDict of ordering field column numbers and asc/desc
        """

        # We must cope with more than one column having the same underlying sort
        # field, so we base things on column numbers.
        ordering = self._get_default_ordering()
        ordering_fields = SortedDict()
        if ORDER_VAR not in self.params or not self.params[ORDER_VAR]:
            # for ordering specified on ModelAdmin or model Meta, we don't know
            # the right column numbers absolutely, because there might be more
            # than one column associated with that ordering, so we guess.
            for field in ordering:
                if field.startswith('-'):
                    field = field[1:]
                    order_type = 'desc'
                else:
                    order_type = 'asc'
                for attr in self.list_display:
                    if self.get_ordering_field(attr) == field:
                        ordering_fields[field] = order_type
                        break
        else:
            for p in self.params[ORDER_VAR].split('.'):
                none, pfx, field_name = p.rpartition('-')
                ordering_fields[field_name] = 'desc' if pfx == '-' else 'asc'
        return ordering_fields

    def get_check_field_url(self, f):
        """
        Return the select column menu items link.
        We must use base_list_display, because list_display maybe changed by plugins.
        """
        fields = [fd for fd in self.base_list_display if fd != f.name]
        if len(self.base_list_display) == len(fields):
            if f.primary_key:
                fields.insert(0, f.name)
            else:
                fields.append(f.name)
        return self.get_query_string({COL_LIST_VAR: '.'.join(fields)})

    def get_model_method_fields(self):
        """
        Return the fields info defined in model. use FakeMethodField class wrap method as a db field.
        """
        methods = []
        for name in dir(self):
            try:
                if getattr(getattr(self, name), 'is_column', False):
                    methods.append((name, getattr(self, name)))
            except:
                pass
        return [FakeMethodField(name, getattr(method, 'short_description', capfirst(name.replace('_', ' '))))
                for name, method in methods]

    @filter_hook
    def get_context(self):
        """
        Prepare the context for templates.
        """
        self.title = _('%s List') % force_text(self.opts.verbose_name)

        model_fields = [(f, f.name in self.list_display, self.get_check_field_url(f))
                        for f in (list(self.opts.fields) + self.get_model_method_fields()) if f.name not in self.list_exclude]

        new_context = {
            'model_name': force_text(self.opts.verbose_name_plural),
            'title': self.title,
            'cl': self,
            'model_fields': model_fields,
            'clean_select_field_url': self.get_query_string(remove=[COL_LIST_VAR]),
            'has_add_permission': self.has_add_permission(),
            'app_label': self.app_label,
            'brand_name': self.opts.verbose_name_plural,
            'brand_icon': self.get_model_icon(self.model),
            'add_url': self.model_admin_url('add'),
            'result_headers': self.result_headers(),
            'results': self.results()
        }
        context = super(ListAdminView, self).get_context()
        context.update(new_context)
        return context

    @filter_hook
    def get_response(self, context, *args, **kwargs):
        pass

    @csrf_protect_m
    @filter_hook
    def get(self, request, *args, **kwargs):
        """
        The 'change list' admin view for this model.
        """
        response = self.get_result_list()
        if response:
            return response

        context = self.get_context()
        context.update(kwargs or {})

        response = self.get_response(context, *args, **kwargs)

        return response or TemplateResponse(request, self.object_list_template or
                                            self.get_template_list('views/model_list.html'), context, current_app=self.admin_site.name)

    @filter_hook
    def post_response(self, *args, **kwargs):
        pass

    @csrf_protect_m
    @filter_hook
    def post(self, request, *args, **kwargs):
        return self.post_result_list() or self.post_response(*args, **kwargs) or self.get(request, *args, **kwargs)

    @filter_hook
    def get_paginator(self):
        return self.paginator_class(self.list_queryset, self.list_per_page, 0, True)

    @filter_hook
    def get_page_number(self, i):
        if i == DOT:
            return mark_safe(u'... ')
        elif i == self.page_num:
            return mark_safe(u'%d ' % (i + 1))
        else:
            return mark_safe(u'%d ' % (escape(self.get_query_string({PAGE_VAR: i})), (i == self.paginator.num_pages - 1 and ' class="end"' or ''), i + 1))

    # Result List methods
    @filter_hook
    def result_header(self, field_name, row):
        ordering_field_columns = self.ordering_field_columns
        item = ResultHeader(field_name, row)
        text, attr = label_for_field(field_name, self.model,
                                     model_admin=self,
                                     return_attr=True
                                     )
        item.text = text
        item.attr = attr
        if attr and not getattr(attr, "admin_order_field", None):
            return item

        # OK, it is sortable if we got this far
        th_classes = ['sortable']
        order_type = ''
        new_order_type = 'desc'
        sort_priority = 0
        sorted = False
        # Is it currently being sorted on?
        if field_name in ordering_field_columns:
            sorted = True
            order_type = ordering_field_columns.get(field_name).lower()
            sort_priority = list(ordering_field_columns.keys()).index(field_name) + 1
            th_classes.append('sorted %sending' % order_type)
            new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type]

        # build new ordering param
        o_list_asc = []  # URL for making this field the primary sort
        o_list_desc = []  # URL for making this field the primary sort
        o_list_remove = []  # URL for removing this field from sort
        o_list_toggle = []  # URL for toggling order type for this field
        make_qs_param = lambda t, n: ('-' if t == 'desc' else '') + str(n)

        for j, ot in ordering_field_columns.items():
            if j == field_name:  # Same column
                param = make_qs_param(new_order_type, j)
                # We want clicking on this header to bring the ordering to the
                # front
                o_list_asc.insert(0, j)
                o_list_desc.insert(0, '-' + j)
                o_list_toggle.append(param)
                # o_list_remove - omit
            else:
                param = make_qs_param(ot, j)
                o_list_asc.append(param)
                o_list_desc.append(param)
                o_list_toggle.append(param)
                o_list_remove.append(param)

        if field_name not in ordering_field_columns:
            o_list_asc.insert(0, field_name)
            o_list_desc.insert(0, '-' + field_name)

        item.sorted = sorted
        item.sortable = True
        item.ascending = (order_type == "asc")
        item.sort_priority = sort_priority

        menus = [
            ('asc', o_list_asc, 'caret-up', _(u'Sort ASC')),
            ('desc', o_list_desc, 'caret-down', _(u'Sort DESC')),
        ]
        if sorted:
            row['num_sorted_fields'] = row['num_sorted_fields'] + 1
            menus.append((None, o_list_remove, 'times', _(u'Cancel Sort')))
            item.btns.append('' % (
                self.get_query_string({ORDER_VAR: '.'.join(o_list_toggle)}), 'sort-up' if order_type == "asc" else 'sort-down'))

        item.menus.extend(['
 %s
' %
                         (
                             (' class="active"' if sorted and order_type == i[
                              0] else ''),
                           self.get_query_string({ORDER_VAR: '.'.join(i[1])}), i[2], i[3]) for i in menus])
        item.classes.extend(th_classes)

        return item

    @filter_hook
    def result_headers(self):
        """
        Generates the list column headers.
        """
        row = ResultRow()
        row['num_sorted_fields'] = 0
        row.cells = [self.result_header(
            field_name, row) for field_name in self.list_display]
        return row

    @filter_hook
    def result_item(self, obj, field_name, row):
        """
        Generates the actual list of data.
        """
        item = ResultItem(field_name, row)
        try:
            f, attr, value = lookup_field(field_name, obj, self)
        except (AttributeError, ObjectDoesNotExist):
            item.text = mark_safe("%s" % EMPTY_CHANGELIST_VALUE)
        else:
            if f is None:
                item.allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    item.allow_tags = True
                    item.text = boolean_icon(value)
                else:
                    item.text = smart_text(value)
            else:
                if isinstance(f.rel, models.ManyToOneRel):
                    field_val = getattr(obj, f.name)
                    if field_val is None:
                        item.text = mark_safe("%s" % EMPTY_CHANGELIST_VALUE)
                    else:
                        item.text = field_val
                else:
                    if f.name in self.list_thumb_fields:
                        item.text = display_for_field(value, f, show_thumb=True)
                    else:
                        item.text = display_for_field(value, f)
                if isinstance(f, models.DateField)\
                    or isinstance(f, models.TimeField)\
                        or isinstance(f, models.ForeignKey):
                    item.classes.append('nowrap')

            item.field = f
            item.attr = attr
            item.value = value

        # If list_display_links not defined, add the link tag to the first field
        if (item.row['is_display_first'] and not self.list_display_links) \
                or field_name in self.list_display_links:
            item.row['is_display_first'] = False
            item.is_display_link = True
            if self.list_display_links_details:
                item_res_uri = self.model_admin_url("detail", getattr(obj, self.pk_attname))
                if item_res_uri:
                    edit_url = self.model_admin_url("change", getattr(obj, self.pk_attname))
                    item.wraps.append('%%s'
                                     % (item_res_uri, edit_url, _(u'Details of %s') % str(obj)))
            else:
                url = self.url_for_result(obj)
                item.wraps.append(u'%%s' % url)

        return item

    @filter_hook
    def result_row(self, obj):
        row = ResultRow()
        row['is_display_first'] = True
        row['object'] = obj
        row.cells = [self.result_item(
            obj, field_name, row) for field_name in self.list_display]
        return row

    @filter_hook
    def results(self):
        results = []
        for obj in self.result_list:
            results.append(self.result_row(obj))
        return results

    @filter_hook
    def url_for_result(self, result):
        return self.get_object_url(result)

    # Media
    @filter_hook
    def get_media(self):
        media = super(ListAdminView, self).get_media() + self.vendor('xadmin.page.list.js', 'xadmin.page.form.js')
        if self.list_display_links_details:
            media += self.vendor('xadmin.plugin.details.js', 'xadmin.form.css')
        return media

    # Blocks
    @inclusion_tag('xadmin/includes/pagination.html')
    def block_pagination(self, context, nodes, page_type='normal'):
        """
        Generates the series of links to the pages in a paginated list.
        """
        paginator, page_num = self.paginator, self.page_num

        pagination_required = (
            not self.show_all or not self.can_show_all) and self.multi_page
        if not pagination_required:
            page_range = []
        else:
            ON_EACH_SIDE = {'normal': 5, 'small': 3}.get(page_type, 3)
            ON_ENDS = 2

            # If there are 10 or fewer pages, display links to every page.
            # Otherwise, do some fancy
            if paginator.num_pages <= 10:
                page_range = range(paginator.num_pages)
            else:
                # Insert "smart" pagination links, so that there are always ON_ENDS
                # links at either end of the list of pages, and there are always
                # ON_EACH_SIDE links at either end of the "current page" link.
                page_range = []
                if page_num > (ON_EACH_SIDE + ON_ENDS):
                    page_range.extend(range(0, ON_EACH_SIDE - 1))
                    page_range.append(DOT)
                    page_range.extend(
                        range(page_num - ON_EACH_SIDE, page_num + 1))
                else:
                    page_range.extend(range(0, page_num + 1))
                if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
                    page_range.extend(
                        range(page_num + 1, page_num + ON_EACH_SIDE + 1))
                    page_range.append(DOT)
                    page_range.extend(range(
                        paginator.num_pages - ON_ENDS, paginator.num_pages))
                else:
                    page_range.extend(range(page_num + 1, paginator.num_pages))

        need_show_all_link = self.can_show_all and not self.show_all and self.multi_page
        return {
            'cl': self,
            'pagination_required': pagination_required,
            'show_all_url': need_show_all_link and self.get_query_string({ALL_VAR: ''}),
            'page_range': map(self.get_page_number, page_range),
            'ALL_VAR': ALL_VAR,
            '1': 1,
        }


text:
package com.github.anba.es6draft.runtime.objects.collection;

import java.util.Iterator;
import java.util.Map.Entry;

import com.github.anba.es6draft.runtime.Realm;
import com.github.anba.es6draft.runtime.types.ScriptObject;
import com.github.anba.es6draft.runtime.types.builtins.OrdinaryObject;

/**
 * 23.2.5.3 Properties of Set Iterator Instances
 */
public final class SetIteratorObject extends OrdinaryObject {
    /** [[IteratedSet]] / [[SetNextIndex]] */
    Iterator<Entry<Object, Void>> iterator;

    /** [[SetIterationKind]] */
    final SetIterationKind iterationKind;

    SetIteratorObject(Realm realm, SetObject set, SetIterationKind kind, ScriptObject prototype) {
        this(realm, set.getSetData().iterator(), kind, prototype);
    }

    SetIteratorObject(Realm realm, Iterator<Entry<Object, Void>> iterator, SetIterationKind kind,
            ScriptObject prototype) {
        super(realm);
        this.iterator = iterator;
        this.iterationKind = kind;
        setPrototype(prototype);
    }

    /**
     * 23.2.5.3 Properties of Set Iterator Instances
     */
    public enum SetIterationKind {
        Key, Value, KeyValue
    }

    /**
     * [[IteratedSet]] / [[SetNextIndex]]
     *
     * @return the internal iterator
     */
    public Iterator<Entry<Object, Void>> getIterator() {
        return iterator;
    }

    /**
     * [[IteratedSet]] / [[SetNextIndex]]
     *
     * @param iterator
     *            the internal iterator
     */
    public void setIterator(Iterator<Entry<Object, Void>> iterator) {
        this.iterator = iterator;
    }

    /**
     * [[SetIterationKind]]
     *
     * @return the iteration kind
     */
    public SetIterationKind getIterationKind() {
        return iterationKind;
    }
}


text:
<?php
session_start();
    class page2
    {
        public static function header()
        {
            #si se necesita la hora :v
            ini_set("date.timezone","America/El_Salvador");

            /*Arreglo que tiene informacio del header, rutas y ubicaciones que se mandan a llamar*/

            $session=false;
            $filename=basename($_SERVER['PHP_SELF']); ?>
            <!DOCTYPE html>

					<?php require 'inc/emeral_links.php'; ?>
					<?php require 'inc/emeral_inc.php'; ?>

            <?php
            if(isset($_SESSION['nombre_apellido_usuario']))
            {
				$session=true;
                if( $session ){

					 require 'inc/menu_sesion.php';
				}

			}
			else
			{

				require 'inc/menu.php';

			} ?>

                                verified_user

                                <form method='post' action='login.php' enctype='multipart/form-data'>

                                        <input name='alias' id='alias' autocomplete='off' type='text' class='validate'>
                                        Nombre de Usuario

                                        <input name='clave' id='clave' autocomplete='off' type='password' class='validate'>
                                        Contraseña

                                    <button type='submit' name='enviar' class='btn blue'>verified_userIniciar Sesion</button>
                                </form>

                                        REGÍSTRATE AHORA

                            Cerrar

        <?php
		}

        /* se establecen funciones de nombre, valor y consulta al siguiente combobox*/

         public static function setCombo($name, $value, $query)
        {
            $data =Database::getRows($query,null);
            $combo="<select class='col l12 s12' name='$name' requeried>";
            if($value == null)
            {
                $combo .= "<option value='' disabled selected>Selecione una opcion</option>";
            }
            foreach($data as $row)
            {
                $combo .="<option value='$row[0]'";
                if(isset($_POST[$name])==$row[0] || $value == $row[0])
                {
                    $combo.="selected";
                }
                $combo .=">$row[1]</option>";
            }
            $combo.="</select>
                    $name";
            print($combo);
		 }

         public static function setCombo_texto($name, $value, $query)
        {
            $data =Database::getRows($query,null);
            $combo="
            <select class='col l12 s12' name='$name' requeried>";
            if($value == null)
            {
                $combo .= "<option value='' disabled selected>Selecione una opcion</option>";
            }
            foreach($data as $row)
            {
                $combo .="<option value='$row[0]'";
                if(isset($_POST[$name])==$row[0] || $value == $row[0])
                {
                    $combo.="selected";
                }
                $combo .=">$row[1]</option>";
            }
            $combo.="</select>
            $name
                    ";
            return $combo;
        }

public static function footer()
{ ?>

					<?php require 'inc/palette.php'; ?>
				<?php require 'inc/script.php'; ?>

<?php  }

	}
?>


text:
"use strict";

var _interopRequire = require("babel-runtime/helpers/interop-require")["default"];

Object.defineProperty(exports, "__esModule", {
  value: true
});

var isUndefined = require("lodash").isUndefined;

var includeIoMixin = _interopRequire(require("./io-mixin"));

var Void = {
  /* jshint unused: false */

  read: function read(io) {
    return undefined;
  },

  write: function write(value, io) {
    if (!isUndefined(value)) {
      throw new Error("XDR Write Error: trying to write value to a void slot");
    }
  },

  isValid: function isValid(value) {
    return isUndefined(value);
  } };

exports.Void = Void;
includeIoMixin(Void);


text:
package pl.java.scalatech.fetch;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

import org.assertj.core.util.Lists;
import org.junit.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import com.google.common.io.Files;

public class DownloadFileTest {
    private final String YAMAHA = "http://foto.scigacz.pl/gallery/aktualnosci/Yamaha_XJ6_naked/yamaha_XJ6_black.jpg";

    @Test
    public void shouldDownloadFile() throws IOException {
        List<HttpMessageConverter<?>> messageConverters = Lists.newArrayList();
        messageConverters.add(new ByteArrayHttpMessageConverter());

        RestTemplate restTemplate = new RestTemplate(messageConverters);

        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> entity = new HttpEntity<>(headers);

        ResponseEntity<byte[]> response = restTemplate.exchange(YAMAHA, HttpMethod.GET, entity, byte[].class);

        if (response.getStatusCode() == HttpStatus.OK) {
            Files.write(response.getBody(), Paths.get("yamaha.jpg").toFile());
        }

    }
}


text:
namespace Battleship.GameC.Model.Ships
{
    public enum ShipClass
    {
        Carrier,
        Battleship,
        Cruiser,
        Submarine,
        Destroyer
    }
}


text:
package elasticsearch

import "github.com/vektra/cypress"

type Plugin struct {
	Host     string `description:"host:port of elasticsearch node"`
	Index    string `description:"fixed index to use if set"`
	Prefix   string `description:"index prefix to use with dated indices (cypress)"`
	Logstash bool   `description:"use logstash format indices"`
}

func (p *Plugin) Description() string {
	return `Write messages to Elasticsearch. By default, indices are generated per day with the prefix of 'cypress'`
}

func (p *Plugin) Receiver() (cypress.Receiver, error) {
	s := &Send{
		Host:     p.Host,
		Index:    p.Index,
		Prefix:   p.Prefix,
		Logstash: p.Logstash,
	}

	err := s.Init()
	if err != nil {
		return nil, err
	}

	return s, nil
}

func init() {
	cypress.AddPlugin("elasticsearch", func() cypress.Plugin { return &Plugin{} })
}


text:
package accounts

import "github.com/rackspace/gophercloud"

// GetOptsBuilder allows extensions to add additional headers to the Get
// request.
type GetOptsBuilder interface {
	ToAccountGetMap() (map[string]string, error)
}

// GetOpts is a structure that contains parameters for getting an account's
// metadata.
type GetOpts struct {
	Newest bool `h:"X-Newest"`
}

// ToAccountGetMap formats a GetOpts into a map[string]string of headers.
func (opts GetOpts) ToAccountGetMap() (map[string]string, error) {
	return gophercloud.BuildHeaders(opts)
}

// Get is a function that retrieves an account's metadata. To extract just the
// custom metadata, call the ExtractMetadata method on the GetResult. To extract
// all the headers that are returned (including the metadata), call the
// ExtractHeader method on the GetResult.
func Get(c *gophercloud.ServiceClient, opts GetOptsBuilder) GetResult {
	var res GetResult
	h := c.AuthenticatedHeaders()

	if opts != nil {
		headers, err := opts.ToAccountGetMap()
		if err != nil {
			res.Err = err
			return res
		}

		for k, v := range headers {
			h[k] = v
		}
	}

	resp, err := c.Request("HEAD", getURL(c), gophercloud.RequestOpts{
		MoreHeaders: h,
		OkCodes:     []int{204},
	})
	res.Header = resp.Header
	res.Err = err
	return res
}

// UpdateOptsBuilder allows extensions to add additional headers to the Update
// request.
type UpdateOptsBuilder interface {
	ToAccountUpdateMap() (map[string]string, error)
}

// UpdateOpts is a structure that contains parameters for updating, creating, or
// deleting an account's metadata.
type UpdateOpts struct {
	Metadata          map[string]string
	ContentType       string `h:"Content-Type"`
	DetectContentType bool   `h:"X-Detect-Content-Type"`
	TempURLKey        string `h:"X-Account-Meta-Temp-URL-Key"`
	TempURLKey2       string `h:"X-Account-Meta-Temp-URL-Key-2"`
}

// ToAccountUpdateMap formats an UpdateOpts into a map[string]string of headers.
func (opts UpdateOpts) ToAccountUpdateMap() (map[string]string, error) {
	headers, err := gophercloud.BuildHeaders(opts)
	if err != nil {
		return nil, err
	}
	for k, v := range opts.Metadata {
		headers["X-Account-Meta-"+k] = v
	}
	return headers, err
}

// Update is a function that creates, updates, or deletes an account's metadata.
// To extract the headers returned, call the Extract method on the UpdateResult.
func Update(c *gophercloud.ServiceClient, opts UpdateOptsBuilder) UpdateResult {
	var res UpdateResult
	h := make(map[string]string)

	if opts != nil {
		headers, err := opts.ToAccountUpdateMap()
		if err != nil {
			res.Err = err
			return res
		}
		for k, v := range headers {
			h[k] = v
		}
	}

	resp, err := c.Request("POST", updateURL(c), gophercloud.RequestOpts{
		MoreHeaders: h,
		OkCodes:     []int{204},
	})
	res.Header = resp.Header
	res.Err = err
	return res
}


text:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class Driver {
	public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
		int num_features=0;
		Configuration conf=new Configuration();
		FileSystem hdfs=FileSystem.get(conf);
		//args[0] is the path to the file which has features of the input waiting to be classified.
		BufferedReader br = new BufferedReader(new InputStreamReader(hdfs.open(new Path(args[0]))));
		String line=null;
		while((line=br.readLine())!=null){
			String[] feat=line.toString().split("\\ ");
			for(int i=0;i<feat.length;i++)
				conf.setFloat("feat"+i, Float.parseFloat(feat[i]));
			num_features=feat.length;
			break;
		}
		br.close();
		hdfs.close();
		conf.setInt("num_features",num_features);
		//args[1] is the name of the entity to be classified.
		conf.set("name",args[1]);
		Job job = new Job(conf,"KNN Classification MapReduce");
		job.setJarByClass(Driver.class);
		//args[2] is the path to the input file which will be used for training.
		FileInputFormat.setInputPaths(job, new Path(args[2]));
		//args[3] is the path to the output file.
		FileOutputFormat.setOutputPath(job, new Path(args[3]));
		job.setMapperClass(Map.class);
		//job.setCombinerClass(Reduce.class);
		job.setReducerClass(Reduce.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		job.waitForCompletion(true);
	}
}


text:
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                ORYAC

                        About

                        Services

                        Team

                        Contact


text:
package org.elasticsearch.xpack.core.ml.job.process.autodetect.state;

import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.xpack.core.ml.job.config.Job;
import org.elasticsearch.xpack.core.ml.job.results.Result;
import org.elasticsearch.xpack.core.ml.utils.ExponentialAverageCalculationContext;
import org.elasticsearch.xpack.core.ml.utils.ToXContentParams;

import java.io.IOException;
import java.time.Instant;
import java.util.Objects;

import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg;
import static org.elasticsearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg;

/**
 * Stats that give more insight into timing of various operations performed as part of anomaly detection job.
 */
public class TimingStats implements ToXContentObject, Writeable {

    public static final ParseField BUCKET_COUNT = new ParseField("bucket_count");
    public static final ParseField TOTAL_BUCKET_PROCESSING_TIME_MS = new ParseField("total_bucket_processing_time_ms");
    public static final ParseField MIN_BUCKET_PROCESSING_TIME_MS = new ParseField("minimum_bucket_processing_time_ms");
    public static final ParseField MAX_BUCKET_PROCESSING_TIME_MS = new ParseField("maximum_bucket_processing_time_ms");
    public static final ParseField AVG_BUCKET_PROCESSING_TIME_MS = new ParseField("average_bucket_processing_time_ms");
    public static final ParseField EXPONENTIAL_AVG_BUCKET_PROCESSING_TIME_MS =
        new ParseField("exponential_average_bucket_processing_time_ms");
    public static final ParseField EXPONENTIAL_AVG_CALCULATION_CONTEXT = new ParseField("exponential_average_calculation_context");
    public static final ParseField EXPONENTIAL_AVG_BUCKET_PROCESSING_TIME_PER_HOUR_MS =
        new ParseField("exponential_average_bucket_processing_time_per_hour_ms");

    public static final ParseField TYPE = new ParseField("timing_stats");

    public static final ConstructingObjectParser<TimingStats, Void> PARSER =
        new ConstructingObjectParser<>(
            TYPE.getPreferredName(),
            true,
            args -> {
                String jobId = (String) args[0];
                long bucketCount = (long) args[1];
                Double minBucketProcessingTimeMs = (Double) args[2];
                Double maxBucketProcessingTimeMs = (Double) args[3];
                Double avgBucketProcessingTimeMs = (Double) args[4];
                Double exponentialAvgBucketProcessingTimeMs = (Double) args[5];
                ExponentialAverageCalculationContext exponentialAvgCalculationContext = (ExponentialAverageCalculationContext) args[6];
                return new TimingStats(
                    jobId,
                    bucketCount,
                    minBucketProcessingTimeMs,
                    maxBucketProcessingTimeMs,
                    avgBucketProcessingTimeMs,
                    exponentialAvgBucketProcessingTimeMs,
                    getOrDefault(exponentialAvgCalculationContext, new ExponentialAverageCalculationContext()));
            });

    static {
        PARSER.declareString(constructorArg(), Job.ID);
        PARSER.declareLong(constructorArg(), BUCKET_COUNT);
        PARSER.declareDouble(optionalConstructorArg(), MIN_BUCKET_PROCESSING_TIME_MS);
        PARSER.declareDouble(optionalConstructorArg(), MAX_BUCKET_PROCESSING_TIME_MS);
        PARSER.declareDouble(optionalConstructorArg(), AVG_BUCKET_PROCESSING_TIME_MS);
        PARSER.declareDouble(optionalConstructorArg(), EXPONENTIAL_AVG_BUCKET_PROCESSING_TIME_MS);
        PARSER.declareObject(optionalConstructorArg(), ExponentialAverageCalculationContext.PARSER, EXPONENTIAL_AVG_CALCULATION_CONTEXT);
    }

    public static String documentId(String jobId) {
        return jobId + "_timing_stats";
    }

    private final String jobId;
    private long bucketCount;
    private Double minBucketProcessingTimeMs;
    private Double maxBucketProcessingTimeMs;
    private Double avgBucketProcessingTimeMs;
    private Double exponentialAvgBucketProcessingTimeMs;
    private final ExponentialAverageCalculationContext exponentialAvgCalculationContext;

    public TimingStats(
            String jobId,
            long bucketCount,
            @Nullable Double minBucketProcessingTimeMs,
            @Nullable Double maxBucketProcessingTimeMs,
            @Nullable Double avgBucketProcessingTimeMs,
            @Nullable Double exponentialAvgBucketProcessingTimeMs,
            ExponentialAverageCalculationContext exponentialAvgCalculationContext) {
        this.jobId = Objects.requireNonNull(jobId);
        this.bucketCount = bucketCount;
        this.minBucketProcessingTimeMs = minBucketProcessingTimeMs;
        this.maxBucketProcessingTimeMs = maxBucketProcessingTimeMs;
        this.avgBucketProcessingTimeMs = avgBucketProcessingTimeMs;
        this.exponentialAvgBucketProcessingTimeMs = exponentialAvgBucketProcessingTimeMs;
        this.exponentialAvgCalculationContext = Objects.requireNonNull(exponentialAvgCalculationContext);
    }

    public TimingStats(String jobId) {
        this(jobId, 0, null, null, null, null, new ExponentialAverageCalculationContext());
    }

    public TimingStats(TimingStats lhs) {
        this(
            lhs.jobId,
            lhs.bucketCount,
            lhs.minBucketProcessingTimeMs,
            lhs.maxBucketProcessingTimeMs,
            lhs.avgBucketProcessingTimeMs,
            lhs.exponentialAvgBucketProcessingTimeMs,
            new ExponentialAverageCalculationContext(lhs.exponentialAvgCalculationContext));
    }

    public TimingStats(StreamInput in) throws IOException {
        this.jobId = in.readString();
        this.bucketCount = in.readLong();
        this.minBucketProcessingTimeMs = in.readOptionalDouble();
        this.maxBucketProcessingTimeMs = in.readOptionalDouble();
        this.avgBucketProcessingTimeMs = in.readOptionalDouble();
        this.exponentialAvgBucketProcessingTimeMs = in.readOptionalDouble();
        this.exponentialAvgCalculationContext = in.readOptionalWriteable(ExponentialAverageCalculationContext::new);
    }

    public String getJobId() {
        return jobId;
    }

    public long getBucketCount() {
        return bucketCount;
    }

    /** Calculates total bucket processing time as a product of the all-time average bucket processing time and the number of buckets. */
    public double getTotalBucketProcessingTimeMs() {
        return avgBucketProcessingTimeMs != null
            ? bucketCount * avgBucketProcessingTimeMs
            : 0.0;
    }

    public Double getMinBucketProcessingTimeMs() {
        return minBucketProcessingTimeMs;
    }

    public Double getMaxBucketProcessingTimeMs() {
        return maxBucketProcessingTimeMs;
    }

    public Double getAvgBucketProcessingTimeMs() {
        return avgBucketProcessingTimeMs;
    }

    public Double getExponentialAvgBucketProcessingTimeMs() {
        return exponentialAvgBucketProcessingTimeMs;
    }

    public Double getExponentialAvgBucketProcessingTimePerHourMs() {
        return exponentialAvgCalculationContext.getCurrentExponentialAverageMs();
    }

    // Visible for testing
    ExponentialAverageCalculationContext getExponentialAvgCalculationContext() {
        return exponentialAvgCalculationContext;
    }

    /**
     * Updates the statistics (min, max, avg, exponential avg) for the given data point (bucket processing time).
     */
    public void updateStats(double bucketProcessingTimeMs) {
        if (bucketProcessingTimeMs < 0.0) {
            throw new IllegalArgumentException("bucketProcessingTimeMs must be non-negative, was: " + bucketProcessingTimeMs);
        }
        if (minBucketProcessingTimeMs == null || bucketProcessingTimeMs < minBucketProcessingTimeMs) {
            minBucketProcessingTimeMs = bucketProcessingTimeMs;
        }
        if (maxBucketProcessingTimeMs == null || bucketProcessingTimeMs > maxBucketProcessingTimeMs) {
            maxBucketProcessingTimeMs = bucketProcessingTimeMs;
        }
        if (avgBucketProcessingTimeMs == null) {
            avgBucketProcessingTimeMs = bucketProcessingTimeMs;
        } else {
            // Calculate the cumulative moving average (see https://en.wikipedia.org/wiki/Moving_average#Cumulative_moving_average) of
            // bucket processing times.
            avgBucketProcessingTimeMs = (bucketCount * avgBucketProcessingTimeMs + bucketProcessingTimeMs) / (bucketCount + 1);
        }
        if (exponentialAvgBucketProcessingTimeMs == null) {
            exponentialAvgBucketProcessingTimeMs = bucketProcessingTimeMs;
        } else {
            // Calculate the exponential moving average (see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average) of
            // bucket processing times.
            exponentialAvgBucketProcessingTimeMs = (1 - ALPHA) * exponentialAvgBucketProcessingTimeMs + ALPHA * bucketProcessingTimeMs;
        }
        bucketCount++;
        exponentialAvgCalculationContext.increment(bucketProcessingTimeMs);
    }

    public void setLatestRecordTimestamp(Instant latestRecordTimestamp) {
        exponentialAvgCalculationContext.setLatestTimestamp(latestRecordTimestamp);
    }

    /**
     * Constant smoothing factor used for calculating exponential moving average. Represents the degree of weighting decrease.
     */
    private static double ALPHA = 0.01;

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeString(jobId);
        out.writeLong(bucketCount);
        out.writeOptionalDouble(minBucketProcessingTimeMs);
        out.writeOptionalDouble(maxBucketProcessingTimeMs);
        out.writeOptionalDouble(avgBucketProcessingTimeMs);
        out.writeOptionalDouble(exponentialAvgBucketProcessingTimeMs);
        out.writeOptionalWriteable(exponentialAvgCalculationContext);
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject();
        if (params.paramAsBoolean(ToXContentParams.FOR_INTERNAL_STORAGE, false)) {
            builder.field(Result.RESULT_TYPE.getPreferredName(), TYPE.getPreferredName());
        }
        builder.field(Job.ID.getPreferredName(), jobId);
        builder.field(BUCKET_COUNT.getPreferredName(), bucketCount);
        if (params.paramAsBoolean(ToXContentParams.INCLUDE_CALCULATED_FIELDS, false)) {
            builder.field(TOTAL_BUCKET_PROCESSING_TIME_MS.getPreferredName(), getTotalBucketProcessingTimeMs());
        }
        if (minBucketProcessingTimeMs != null) {
            builder.field(MIN_BUCKET_PROCESSING_TIME_MS.getPreferredName(), minBucketProcessingTimeMs);
        }
        if (maxBucketProcessingTimeMs != null) {
            builder.field(MAX_BUCKET_PROCESSING_TIME_MS.getPreferredName(), maxBucketProcessingTimeMs);
        }
        if (avgBucketProcessingTimeMs != null) {
            builder.field(AVG_BUCKET_PROCESSING_TIME_MS.getPreferredName(), avgBucketProcessingTimeMs);
        }
        if (exponentialAvgBucketProcessingTimeMs != null) {
            builder.field(EXPONENTIAL_AVG_BUCKET_PROCESSING_TIME_MS.getPreferredName(), exponentialAvgBucketProcessingTimeMs);
        }
        if (params.paramAsBoolean(ToXContentParams.INCLUDE_CALCULATED_FIELDS, false)) {
            Double expAvgBucketProcessingTimePerHourMs = getExponentialAvgBucketProcessingTimePerHourMs();
            if (expAvgBucketProcessingTimePerHourMs != null) {
                builder.field(EXPONENTIAL_AVG_BUCKET_PROCESSING_TIME_PER_HOUR_MS.getPreferredName(), expAvgBucketProcessingTimePerHourMs);
            }
        }
        if (params.paramAsBoolean(ToXContentParams.FOR_INTERNAL_STORAGE, false)) {
            builder.field(EXPONENTIAL_AVG_CALCULATION_CONTEXT.getPreferredName(), exponentialAvgCalculationContext);
        }
        builder.endObject();
        return builder;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) return true;
        if (o == null || getClass() != o.getClass()) return false;
        TimingStats that = (TimingStats) o;
        return Objects.equals(this.jobId, that.jobId)
            && this.bucketCount == that.bucketCount
            && Objects.equals(this.minBucketProcessingTimeMs, that.minBucketProcessingTimeMs)
            && Objects.equals(this.maxBucketProcessingTimeMs, that.maxBucketProcessingTimeMs)
            && Objects.equals(this.avgBucketProcessingTimeMs, that.avgBucketProcessingTimeMs)
            && Objects.equals(this.exponentialAvgBucketProcessingTimeMs, that.exponentialAvgBucketProcessingTimeMs)
            && Objects.equals(this.exponentialAvgCalculationContext, that.exponentialAvgCalculationContext);
    }

    @Override
    public int hashCode() {
        return Objects.hash(
            jobId,
            bucketCount,
            minBucketProcessingTimeMs,
            maxBucketProcessingTimeMs,
            avgBucketProcessingTimeMs,
            exponentialAvgBucketProcessingTimeMs,
            exponentialAvgCalculationContext);
    }

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

    private static <T> T getOrDefault(@Nullable T value, T defaultValue) {
        return value != null ? value : defaultValue;
    }
}


text:
package io.js.J2V8Interop.mixins;

import io.js.J2V8Interop.*;

import com.eclipsesource.v8.*;

import java.util.*;
import java.lang.reflect.*;

public class JavaCreateInstanceMixin
{
    public static V8Object inject(InteropRuntime runtime)
    {
        V8 v8rt = runtime.getV8Runtime();
        JavaObjectHeap javaHeap = runtime.getHeap();

        JavaCallback __javaCreateInstance = new JavaCallback() {
            public V8Value invoke(final V8Object receiver, final V8Array parameters) {
                V8Stackframe f = new V8Stackframe();

                V8Object jsClass = f.getObject(parameters, 0);
                V8Object jsInstance = f.getObject(parameters, 1);

                String __javaPackage = jsClass.getString("__javaPackage");
                String __javaClassName = jsClass.getString("__javaClassName");
                //int __javaClassHash = jsClass.getInteger("__javaClassHash");

                // Class<?> javaClass = JavaTypeInfoGenerator._types.get(__javaClassHash);
                Class<?> javaClass;
                Constructor<?> javaCtor;

                try {
                    System.out.println("creating Java instance of: " + __javaPackage + "." + __javaClassName);
                    javaClass = Class.forName(__javaPackage + "." + __javaClassName);
                    // TODO: parameter mapping
                    javaCtor = javaClass.getConstructor();
                    Object javaObj = javaCtor.newInstance(new Object[] {});

                    JavaHeapEntry heapEntry = javaHeap.put(javaObj);
                    jsInstance.add("__ptr", heapEntry.javaPtr);

                    System.out.println("created Java instance with ptr: " + heapEntry.javaPtr);

                    return heapEntry.jsPtr;
                }
                catch (Exception e)
                {
                    throw new RuntimeException(e);
                }
                finally
                {
                    f.close();
                }
            }
        };
        return v8rt.registerJavaMethod(__javaCreateInstance, "__javaCreateInstance");
    }
}


text:
local utils = require "lualib.utils"
local env = import "agent/env"

function Analysis(pid, proto, param)
	local pobj = env.get_player(pid)
	if proto == "c2gs_ping" then
		if pobj then
			pobj:client_ping(param.session)
		end
	elseif proto == "c2gs_ctrl_data" then
		if pobj then
			pobj:sync_ctrl(param)
		end
	elseif proto == "c2gs_rtt_data" then
		if pobj then
			skynet_send(pobj.m_SceneAgent, "c2gs_rtt_data", pobj.m_GameID, pobj.m_ID, param)
		end
	end
end


text:
from setuptools import setup, find_packages

version = "0.24"
setup(name="staffjoy",
      packages=find_packages(),
      version=version,
      description="Staffjoy API Wrapper in Python",
      author="Philip Thomas",
      author_email="philip@staffjoy.com",
      license="MIT",
      url="https://github.com/staffjoy/client_python",
      download_url="https://github.com/StaffJoy/client_python/archive/%s.tar.gz" % version,
      keywords=["staffjoy-api", "staffjoy", "staff joy"],
      install_requires=["requests[security]"], )