text:
lychee.define('lychee.game.Jukebox').requires([
	'lychee.game.Loop'
]).includes([
	'lychee.Jukebox'
]).exports(function(lychee, global) {

	var Class = function(maxPoolSize, loop) {

		lychee.Jukebox.call(this, maxPoolSize);

		this.__clock = 0;
		this.__effects = {};
		this.__effectId = 0;

		if (loop instanceof lychee.game.Loop) {
			loop.bind('update', this.update, this);
		}

	};

	Class.prototype = {

		update: function(clock, delta) {

			for (var e in this.__effects) {

				var effect = this.__effects[e];
				if (effect === null) continue;

				if (effect.end <= this.__clock) {

					if (effect.type === 'fade-out') {
						this.stop(effect.id);
					}

					this.__effects[e] = null;
					continue;

				}

				var pos = (this.__clock - effect.start) / (effect.end - effect.start);
				if (effect.type === 'fade-in') {
					this.setVolume(effect.id, pos * effect.diff);
				} else if (effect.type === 'fade-out') {
					this.setVolume(effect.id, (1 - pos) * effect.diff);
				}

			}

			this.__clock = clock;

		},

		fadeIn: function(id, duration, loop, volume) {

			id = typeof id === 'string' ? id : null;
			duration = typeof duration === 'number' ? duration : 1000;
			loop = loop === true ? true : false;
			volume = typeof volume === 'number' ? volume : 1;

			if (id !== null) {

				this.play(id, loop);
				this.setVolume(id, 0);

				var effect = {
					id: id,
					type: 'fade-in',
					start: this.__clock,
					end: this.__clock + duration,
					diff: volume
				};

				this.__effects[++this.__effectId] = effect;

			}

		},

		fadeOut: function(id, duration) {

			id = typeof id === 'string' ? id : null;
			duration = typeof duration === 'number' ? duration : 1000;

			if (id !== null) {

				var currentVolume = this.getVolume(id);

				var effect = {
					id: id,
					type: 'fade-out',
					start: this.__clock,
					end: this.__clock + duration,
					diff: currentVolume
				};

				this.__effects[++this.__effectId] = effect;

			}

		},

		removeEffects: function(id, type) {

			id = typeof id === 'string' ? id : null;
			type = typeof type === 'string' ? type : null;

			var found = false;

			for (var e in this.__effects) {

				if (
					this.__effects[e] !== null
					&& (id === null || this.__effects[e].id === id)
					&& (type === null || this.__effects[e].type === type)
				) {
					this.__effects[e] = null;
					found = true;
				}

			}

			return found;

		}

	};

	return Class;

});


text:
// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System;
using System.Collections.ObjectModel;
using System.Data.Objects;
using System.Linq;
using Microsoft.TeamFoundation.Migration.EntityModel;
using Microsoft.TeamFoundation.Migration.Shell.ViewModel;

namespace Microsoft.TeamFoundation.Migration.Shell.Model
{
    public class ConflictViewModel : ModelObject
    {
        #region Fields
        RTConflict m_conflict;
        private RuntimeManager m_host;
        #endregion

        #region Constructors
        public ConflictViewModel(RTConflict conflict)
        {
            m_conflict = conflict;
            m_host = RuntimeManager.GetInstance();
        }
        #endregion

        #region Properties
        // Selected RTConflict properties
        public int Id { get { return m_conflict.Id; } }
        public string ConflictDetails { get { return m_conflict.ConflictDetails; } }
        public string ScopeHint { get { return m_conflict.ScopeHint; } }
        public Guid ScopeId { get { return m_conflict.ScopeId; } }

        // TODO: Map to enum values
        public int Status { get { return m_conflict.Status; } }

        // Collections and relationships
        /// <summary>
        /// ResolvedByRule
        /// </summary>
        private ConflictResolutionRuleViewModel m_resolvedByRule;

        public ConflictResolutionRuleViewModel ResolvedByRule
        {
            get
            {
                if (m_resolvedByRule == null)
                {
                    if (! m_conflict.ResolvedByRuleReference.IsLoaded)
                    {
                        m_conflict.ResolvedByRuleReference.Load();
                    }

                    m_resolvedByRule = new ConflictResolutionRuleViewModel(m_conflict.ResolvedByRule);
                }

                return m_resolvedByRule;
            }
        }

        /// <summary>
        /// ConflictType
        /// </summary>
        private ConflictTypeViewModel m_conflictType;

        public ConflictTypeViewModel ConflictType
        {
            get
            {
                if (m_conflictType == null)
                {
                    if (!m_conflict.ConflictTypeReference.IsLoaded)
                    {
                        m_conflict.ConflictTypeReference.Load();
                    }

                    m_conflictType = new ConflictTypeViewModel(m_conflict.ConflictType);
                }

                return m_conflictType;
            }
        }

        /// <summary>
        /// MigrationSourceViewModel
        ///
        /// A reference to the system that was the source of the item in conflict.
        /// </summary>
        private MigrationSourceViewModel m_sourceSideMigrationSource;

        public MigrationSourceViewModel SourceSideMigrationSource
        {
            get
            {
                if (m_sourceSideMigrationSource == null)
                {
                    if (!m_conflict.SourceSideMigrationSourceReference.IsLoaded)
                    {
                        m_conflict.SourceSideMigrationSourceReference.Load();
                    }

                    m_sourceSideMigrationSource = new MigrationSourceViewModel(m_conflict.SourceSideMigrationSource);
                }

                return m_sourceSideMigrationSource;
            }
        }

        private ObservableCollection<ConflictContentReservationViewModel> m_conflictContentReservations;

        private ObservableCollection<ConflictContentReservationViewModel> ConflictContentReservations
        {
            get
            {
                // Static loading for now... could be moved to AutoRefresh
                if (m_conflictContentReservations == null)
                {
                    m_conflictContentReservations = new ObservableCollection<ConflictContentReservationViewModel>();

                    ObjectQuery<RTConflictContentReservation> contentReservationSet = m_conflict.ContentReservation.CreateSourceQuery();

                    m_conflictContentReservations.Clear();

                    var query = (from c in contentReservationSet
                                 orderby c.ItemId descending
                                 select c).Take(m_host.MaxQueryResults);

                    foreach (RTConflictContentReservation contentReservation in query)
                    {
                        m_conflictContentReservations.Add(new ConflictContentReservationViewModel(contentReservation));
                    }
                }

                return m_conflictContentReservations;
            }
        }

        // View support
        ObservableCollection<ResolutionActionViewModel> m_supportedResolutionActions;

        public ObservableCollection<ResolutionActionViewModel> SupportedResolutionActions
        {
            // DEBUG DEBUG DEBUG
            // DEBUG DEBUG DEBUG
            // DEBUG DEBUG DEBUG
            get
            {
                if (m_supportedResolutionActions == null)
                {
                    // TODO: Clean up path to resolution actions in adapters
                    //ConfigurationViewModelManager configHost = ConfigurationViewModelManager.GetInstance();
                    //IConflictResolutionService conflictResolutionService = (IConflictResolutionService)configHost.GetService(typeof(IConflictResolutionService));
                    //m_supportedResolutionActions = conflictResolutionService.ListResolutionActions(this.ConflictType.ReferenceName, this.ScopeId, this.SourceSideMigrationSource.UniqueId);
                }
                return m_supportedResolutionActions;
            }
            // DEBUG DEBUG DEBUG
            // DEBUG DEBUG DEBUG
            // DEBUG DEBUG DEBUG
        }
        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
app.filter('bondMkt',function(){
	return function(bondMktCode){
		let bondMkt;
		switch(bondMktCode){
			case "1":bondMkt=".IB";break;
			case "2":bondMkt=".SH";break;
			case "3":bondMkt=".SZ";break;
		}
		return bondMkt ;
	};
});


text:
from google.cloud import aiplatform_v1

async def sample_list_data_items():
    # Create a client
    client = aiplatform_v1.DatasetServiceAsyncClient()

    # Initialize request argument(s)
    request = aiplatform_v1.ListDataItemsRequest(
        parent="parent_value",
    )

    # Make the request
    page_result = client.list_data_items(request=request)

    # Handle the response
    async for response in page_result:
        print(response)

# [END aiplatform_v1_generated_DatasetService_ListDataItems_async]


text:
import json
import re
import pprint
from urllib.request import urlopen, Request
from urllib.error import HTTPError

def get_charset(req):
    charset = "utf-8"
    match = re.match(r".* charset=(.+)", req.getheader("Content-Type"))
    if match:
        charset = match.group(1)
    return charset

def pyro_call(object_name, method, callback):
    request = Request("http://127.0.0.1:8080/pyro/{0}/{1}".format(object_name, method),
                      # headers={"x-pyro-options": "oneway", "x-pyro-gateway-key": "secretgatewaykey"}
                      )
    with urlopen(request) as req:
        charset = get_charset(req)
        data = req.read().decode(charset)
    if data:
        callback(json.loads(data))
    else:
        callback(None)

def write_result(result):
    pprint.pprint(result, width=40)

try:
    print("\nLIST--->")
    pyro_call("Pyro.NameServer", "list", write_result)
except HTTPError as x:
    print("Error:", x)
    print("Error response data:", x.read())

try:
    print("\nMETA--->")
    pyro_call("Pyro.NameServer", "$meta", write_result)
except HTTPError as x:
    print("Error:", x)
    print("Error response data:", x.read())

try:
    print("\nLOOKUP--->")
    pyro_call("Pyro.NameServer", "lookup?name=Pyro.NameServer", write_result)
except HTTPError as x:
    print("Error:", x)
    print("Error response data:", x.read())

try:
    print("\nONEWAY_SLOW--->")
    pyro_call("test.echoserver", "oneway_slow", write_result)
except HTTPError as x:
    print("Error:", x)
    print("Error response data:", x.read())

try:
    print("\nSLOW--->")
    pyro_call("test.echoserver", "slow", write_result)
except HTTPError as x:
    print("Error:", x)
    print("Error response data:", x.read())

# Note that there is a nicer way to pass the parameters, you can probably
# grab them from a function's vargs and/or kwargs and convert those to
# a querystring using the appropriate library function.
# Then you can call the method as usual and don't have to worry about adding the querystring
# (or sticking it in a POST request if the params are too large)...


text:
var cdb = require('cartodb.js');
var _ = require('underscore');
var TileJSONView = require('./tile_json_view');

/**
 * View model for TileJSON tab content.
 */
module.exports = cdb.core.Model.extend({

  defaults: {
    name: 'tile_json',
    label: 'TileJSON',
    layer: undefined // will be set when valid
  },

  createView: function() {
    this.set({
      layer: undefined
    });
    return new TileJSONView({
      model: this
    });
  },

  hasAlreadyAddedLayer: function(baseLayers) {
    var urlTemplate = this.get('layer').get('urlTemplate');
    return _.any(baseLayers.custom(), function(customLayer) {
      return customLayer.get('urlTemplate') === urlTemplate;
    });
  }
});


text:
#import "SDImageLoader.h"
#import "SDWebImageCacheKeyFilter.h"
#import "SDImageCodersManager.h"
#import "SDImageCoderHelper.h"
#import "SDAnimatedImage.h"
#import "UIImage+Metadata.h"
#import "SDInternalMacros.h"
#import "SDImageCacheDefine.h"
#import "objc/runtime.h"

SDWebImageContextOption const SDWebImageContextLoaderCachedImage = @"loaderCachedImage";

static void * SDImageLoaderProgressiveCoderKey = &SDImageLoaderProgressiveCoderKey;

id<SDProgressiveImageCoder> SDImageLoaderGetProgressiveCoder(id<SDWebImageOperation> operation) {
    NSCParameterAssert(operation);
    return objc_getAssociatedObject(operation, SDImageLoaderProgressiveCoderKey);
}

void SDImageLoaderSetProgressiveCoder(id<SDWebImageOperation> operation, id<SDProgressiveImageCoder> progressiveCoder) {
    NSCParameterAssert(operation);
    objc_setAssociatedObject(operation, SDImageLoaderProgressiveCoderKey, progressiveCoder, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

UIImage * _Nullable SDImageLoaderDecodeImageData(NSData * _Nonnull imageData, NSURL * _Nonnull imageURL, SDWebImageOptions options, SDWebImageContext * _Nullable context) {
    NSCParameterAssert(imageData);
    NSCParameterAssert(imageURL);

    UIImage *image;
    id<SDWebImageCacheKeyFilter> cacheKeyFilter = context[SDWebImageContextCacheKeyFilter];
    NSString *cacheKey;
    if (cacheKeyFilter) {
        cacheKey = [cacheKeyFilter cacheKeyForURL:imageURL];
    } else {
        cacheKey = imageURL.absoluteString;
    }
    SDImageCoderOptions *coderOptions = SDGetDecodeOptionsFromContext(context, options, cacheKey);
    BOOL decodeFirstFrame = SD_OPTIONS_CONTAINS(options, SDWebImageDecodeFirstFrameOnly);
    CGFloat scale = [coderOptions[SDImageCoderDecodeScaleFactor] doubleValue];

    // Grab the image coder
    id<SDImageCoder> imageCoder = context[SDWebImageContextImageCoder];
    if (!imageCoder) {
        imageCoder = [SDImageCodersManager sharedManager];
    }

    if (!decodeFirstFrame) {
        // check whether we should use `SDAnimatedImage`
        Class animatedImageClass = context[SDWebImageContextAnimatedImageClass];
        if ([animatedImageClass isSubclassOfClass:[UIImage class]] && [animatedImageClass conformsToProtocol:@protocol(SDAnimatedImage)]) {
            image = [[animatedImageClass alloc] initWithData:imageData scale:scale options:coderOptions];
            if (image) {
                // Preload frames if supported
                if (options & SDWebImagePreloadAllFrames && [image respondsToSelector:@selector(preloadAllFrames)]) {
                    [((id<SDAnimatedImage>)image) preloadAllFrames];
                }
            } else {
                // Check image class matching
                if (options & SDWebImageMatchAnimatedImageClass) {
                    return nil;
                }
            }
        }
    }
    if (!image) {
        image = [imageCoder decodedImageWithData:imageData options:coderOptions];
    }
    if (image) {
        BOOL shouldDecode = !SD_OPTIONS_CONTAINS(options, SDWebImageAvoidDecodeImage);
        BOOL lazyDecode = [coderOptions[SDImageCoderDecodeUseLazyDecoding] boolValue];
        if (lazyDecode) {
            // lazyDecode = NO means we should not forceDecode, highest priority
            shouldDecode = NO;
        }
        if (shouldDecode) {
            image = [SDImageCoderHelper decodedImageWithImage:image];
        }
        // assign the decode options, to let manager check whether to re-decode if needed
        image.sd_decodeOptions = coderOptions;
    }

    return image;
}

UIImage * _Nullable SDImageLoaderDecodeProgressiveImageData(NSData * _Nonnull imageData, NSURL * _Nonnull imageURL, BOOL finished,  id<SDWebImageOperation> _Nonnull operation, SDWebImageOptions options, SDWebImageContext * _Nullable context) {
    NSCParameterAssert(imageData);
    NSCParameterAssert(imageURL);
    NSCParameterAssert(operation);

    UIImage *image;
    id<SDWebImageCacheKeyFilter> cacheKeyFilter = context[SDWebImageContextCacheKeyFilter];
    NSString *cacheKey;
    if (cacheKeyFilter) {
        cacheKey = [cacheKeyFilter cacheKeyForURL:imageURL];
    } else {
        cacheKey = imageURL.absoluteString;
    }
    SDImageCoderOptions *coderOptions = SDGetDecodeOptionsFromContext(context, options, cacheKey);
    BOOL decodeFirstFrame = SD_OPTIONS_CONTAINS(options, SDWebImageDecodeFirstFrameOnly);
    CGFloat scale = [coderOptions[SDImageCoderDecodeScaleFactor] doubleValue];

    // Grab the progressive image coder
    id<SDProgressiveImageCoder> progressiveCoder = SDImageLoaderGetProgressiveCoder(operation);
    if (!progressiveCoder) {
        id<SDProgressiveImageCoder> imageCoder = context[SDWebImageContextImageCoder];
        // Check the progressive coder if provided
        if ([imageCoder respondsToSelector:@selector(initIncrementalWithOptions:)]) {
            progressiveCoder = [[[imageCoder class] alloc] initIncrementalWithOptions:coderOptions];
        } else {
            // We need to create a new instance for progressive decoding to avoid conflicts
            for (id<SDImageCoder> coder in [SDImageCodersManager sharedManager].coders.reverseObjectEnumerator) {
                if ([coder conformsToProtocol:@protocol(SDProgressiveImageCoder)] &&
                    [((id<SDProgressiveImageCoder>)coder) canIncrementalDecodeFromData:imageData]) {
                    progressiveCoder = [[[coder class] alloc] initIncrementalWithOptions:coderOptions];
                    break;
                }
            }
        }
        SDImageLoaderSetProgressiveCoder(operation, progressiveCoder);
    }
    // If we can't find any progressive coder, disable progressive download
    if (!progressiveCoder) {
        return nil;
    }

    [progressiveCoder updateIncrementalData:imageData finished:finished];
    if (!decodeFirstFrame) {
        // check whether we should use `SDAnimatedImage`
        Class animatedImageClass = context[SDWebImageContextAnimatedImageClass];
        if ([animatedImageClass isSubclassOfClass:[UIImage class]] && [animatedImageClass conformsToProtocol:@protocol(SDAnimatedImage)] && [progressiveCoder respondsToSelector:@selector(animatedImageFrameAtIndex:)]) {
            image = [[animatedImageClass alloc] initWithAnimatedCoder:(id<SDAnimatedImageCoder>)progressiveCoder scale:scale];
            if (image) {
                // Progressive decoding does not preload frames
            } else {
                // Check image class matching
                if (options & SDWebImageMatchAnimatedImageClass) {
                    return nil;
                }
            }
        }
    }
    if (!image) {
        image = [progressiveCoder incrementalDecodedImageWithOptions:coderOptions];
    }
    if (image) {
        BOOL shouldDecode = !SD_OPTIONS_CONTAINS(options, SDWebImageAvoidDecodeImage);
        BOOL lazyDecode = [coderOptions[SDImageCoderDecodeUseLazyDecoding] boolValue];
        if (lazyDecode) {
            // lazyDecode = NO means we should not forceDecode, highest priority
            shouldDecode = NO;
        }
        if (shouldDecode) {
            image = [SDImageCoderHelper decodedImageWithImage:image];
        }
        // assign the decode options, to let manager check whether to re-decode if needed
        image.sd_decodeOptions = coderOptions;
        // mark the image as progressive (completed one are not mark as progressive)
        image.sd_isIncremental = !finished;
    }

    return image;
}


text:
using Container;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataAccessLibrary
{
    public class CommentsOperationDal : Base
    {
        public List<COMMENTS> get_SiteComments(int SiteID)
        {
            var result = (from inc in base.DbObject.COMMENTS
                          where inc.SiteID == SiteID
                          select inc).ToList();
            return result;
        }

        public List<COMMENTS> take_only(int adet)
        {
            return base.DbObject.COMMENTS.Take(adet).ToList();
        }

        public bool add_Comments(COMMENTS value)
        {
            bool result = false;
            try
            {
                base.DbObject.COMMENTS.Add(value);
                base.DbObject.SaveChanges();
                result = true;
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }

        public bool delete_Comments(int ID)
        {
            bool result = false;
            try
            {
                var result1 = (from inc in base.DbObject.COMMENTS where inc.ID == ID select inc).FirstOrDefault();
                base.DbObject.COMMENTS.Remove(result1);
                result = true;
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }

        public List<CommentsInfo> Get_Site_Comments_Spesific(string _SiteID)
        {
            var result = base.DbObject.Database.SqlQuery<CommentsInfo>(" Select Name as UserName, Date , Comment from COMMENTS  " +
                                      " inner join USERS on USERS.ID = COMMENTS.SenderID  where SiteID = " + _SiteID +" order by COMMENTS.ID desc " ).ToList();

            return result;

        }
    }
}


text:
require 'mpd32api/version'
require 'mpd32api/mapping'
require 'unimidi'

module Mpd32Api
  def Mpd32Api.get_midi_input_device
    UniMIDI::Input.gets
  end

  def Mpd32Api.get_midi_output_device
    UniMIDI::Output.gets
  end

  class Library
    def initialize(input_device, output_device)
      input_device.instance_of?(UniMIDI::CoreMIDIAdapter::Input) ?
          @input = input_device :
          @input = UniMIDI::Input.use(input_device)
      output_device.instance_of?(UniMIDI::CoreMIDIAdapter::Output) ?
        @output = output_device :
        @output = UniMIDI::Output.use(output_device)
    end

    def start_read_input
      @input.open
      loop {
        message = @input.gets
        p message
      }
    end

    def send_msg(message)
      @output.open { |output|
        output.puts(message)
      }
    end

    def switch_to_control_bank(x)
      self.send_msg Mpd32Api::MIDI_MAPPING[:control_bank][x]
    end

    def switch_to_pad_bank(x)
      self.send_msg Mpd32Api::MIDI_MAPPING[:pad_bank][x]
    end

    def note_repeat(x)
      self.send_msg Mpd32Api::MIDI_MAPPING[:note_repeat][x]
    end

    def time_division(x)
      self.send_msg Mpd32Api::MIDI_MAPPING[:time_division][x]
    end

    def showcase
      Mpd32Api::MIDI_MAPPING.each do |kx,vx|
        vx.each do |ky,vy|
          self.send_msg vy
          sleep 1
        end
      end
    end
  end
end


text:
<?php
class Anvander_model extends CI_Model{

    public $table;
    public $id;
    public $username;
    public $password;
    public $status;

    public function __construct()
    {
        parent::__construct();
        $this->table="anvander";
        $this->id="id";
        $this->username="namn";
        $this->password="lasnord";
        $this->status="status";

    }

    //get all rows of table
    function get(){
        $this->db->order_by($this->id,'desc');
        $query=$this->db->get($this->table);
        return $query->result();
    }

    //get data from table by condition or array of condition
    function group_by($wheres=array(),$group_by){
        //$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
        $this->db->group_by($group_by);
        $this->db->where($wheres);
        $query=$this->db->get($this->table);
        return $query->result();
    }

    function order_by($order_by){
        //$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
        $this->db->order_by($order_by);
        $query=$this->db->get($this->table);
        return $query->result();
    }

    function get_where($wheres){
        //$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
        $query=$this->db->get_where($this->table, $wheres);
        return $query->result();
    }

    function get_where_column($wheres,$column){

        //$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
        $query=$this->db->get_where($this->table, $wheres);
        $value =$query->row();
        return (isset($value->$column))? $value->$column : "";
    }

    function get_or_where(){
        //$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
        $query=$this->db->query("
        select * from account where status='1' and (type='seller' or type='customer')
        ");
        return $query->result();
    }
    function get_name($wheres){
        //$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
        $query=$this->db->get_where($this->table, $wheres);
        $value =$query->row();
        return (isset($value->name))? $value->name : "";
    }

    //deletes data from table by condtion or array of condition
    function delete($wheres){
        $this->db->delete($this->table,$wheres);
    }

    //inset array of data to table
    function insert($data){
        $this->db->insert($this->table,$data);
        return $this->last_id();
    }

    //updates data or array of data by condition or array of condition
    function update($data,$wheres){
        $str = $this->db->update($this->table, $data, $wheres);
        return $str;
    }

    function check_email_exist($wheres){
        //$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
        $query=$this->db->get_where($this->table, $wheres);
        $result=$query->num_rows();
        if($result==0){
            return false;
        }else{
            return true;
        }
    }

    //check tha table if is empty or not
    function check_empty(){
        return $this->db->count_all($this->table);
    }

    function last_id(){

        $this->db->select($this->id);
        $this->db->from($this->table);
        $this->db->limit(1);
        $this->db->order_by($this->id, "desc");
        $query=$this->db->get();
        $result=$query->result();
        if(empty($result)){
            return 1;
        }else{
            foreach ($result as $key => $value) {
                return $value->{$this->id}++;
            }
        }
    }

    function last_row(){

        $this->db->select('name');
        $this->db->from($this->table);
        $this->db->limit(1);
        $this->db->order_by($this->id, "desc");
        $query=$this->db->get();
        $result=$query->row_array();
        return $result;
    }
   function accounts_json($where){
$result = array();
        $this->db->select('namn,status,email');
$this->db->where($where);
        $query = $this->db->get('anvander');
        if($query->num_rows() > 0){
            foreach ($query->result_array() as $row){
  $result[] = array("name"=> $row['namn'],"status"=> $row['status'],"email"=> $row['email']);

            }
            echo json_encode($result); //format the array into json data
        }
    }

    function update_premission($data,$wheres){
        $str = $this->db->update($this->table, $data, $wheres);
 $result[] = array("check"=>  $str);
         echo json_encode($result);
    }

}
?>


text:
// **********************************************************************
//
// <copyright>
//
//  BBN Technologies
//  10 Moulton Street
//  Cambridge, MA 02138
//  (617) 873-8000
//
//  Copyright (C) BBNT Solutions LLC. All rights reserved.
//
// </copyright>
// **********************************************************************
//
// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/quadtree/MutableDistance.java,v $
// $RCSfile: MutableDistance.java,v $
// $Revision: 1.3 $
// $Date: 2004/10/14 18:06:31 $
// $Author: dietrick $
//
// **********************************************************************

package com.bbn.openmap.util.quadtree;

/**
 * A *really* simple class used as a changable double.
 */
public class MutableDistance {
    public double value = 0;

    public MutableDistance(double distance) {
        value = distance;
    }
}


text:
import { AbstractModule, Component, ComponentSymbol, RegistryKey } from "@tmorin/ceb-inversion-core"
import { Gateway, GatewaySymbol } from "@tmorin/ceb-messaging-core"
import { CommandForwarder } from "./command"
import { EventBridge } from "./event"
import { QueryForwarder } from "./query"

/**
 * The options of {@link DomAdapterModule}.
 */
export interface DomAdapterModuleOptions {
  /**
   * The {@link RegistryKey} of the {@link Gateway} instance.
   * By default {@link GatewaySymbol}.
   */
  gatewayRegistryKey: RegistryKey
  /**
   * The Event Target where the global listeners are added.
   * @default `window`
   */
  target: EventTarget
}

/**
 * The module registers global Event listeners forwarding messages to a given {@link Gateway}.
 *
 * @example Register the module
 * ```typescript
 * import {ContainerBuilder} from "@tmorin/ceb-inversion-core"
 * import {SimpleModule} from "@tmorin/ceb-messaging-simple"
 * import {DomAdapterModule} from "@tmorin/ceb-messaging-adapt-dom"
 * const container = ContainerBuilder.get()
 *   .module(new SimpleModule())
 *   .module(new DomAdapterModule())
 *   .build()
 * ```
 */
export class DomAdapterModule extends AbstractModule {
  private readonly options: DomAdapterModuleOptions

  /**
   * @param partialOptions Options of the module.
   */
  constructor(partialOptions: Partial<DomAdapterModuleOptions> = {}) {
    super()
    this.options = {
      gatewayRegistryKey: GatewaySymbol,
      target: window,
      ...partialOptions,
    }
  }

  async configure(): Promise<void> {
    // COMMAND
    this.registry.registerFactory<Component>(
      ComponentSymbol,
      (registry) =>
        new CommandForwarder(this.options.target, registry.resolve<Gateway>(this.options.gatewayRegistryKey))
    )
    // EVENT
    this.registry.registerFactory<Component>(
      ComponentSymbol,
      (registry) => new EventBridge(this.options.target, registry.resolve<Gateway>(this.options.gatewayRegistryKey))
    )
    // QUERY
    this.registry.registerFactory<Component>(
      ComponentSymbol,
      (registry) => new QueryForwarder(this.options.target, registry.resolve<Gateway>(this.options.gatewayRegistryKey))
    )
  }
}


text:
package mma.sepnotican.dao;

import mma.sepnotican.entity.Contact;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.domain.Pageable;

public interface ContactRepository extends JpaRepository<Contact, Long> {

    Page<Contact> findAll(Pageable pageable);

    @Query("select count(c) from Contact c")
    int getContactsCount();
}


text:
#include <stdlib.h>    // malloc, exit
#include <stdio.h>     // printf
#include <string.h>    // strerror
#include <errno.h>     // errno
#include <sys/stat.h>  // stat
#include <zstd.h>      // presumes zstd library is installed

static off_t fsize_orDie(const char *filename)
{
    struct stat st;
    if (stat(filename, &st) == 0) return st.st_size;
    /* error */
    perror(filename);
    exit(1);
}

static FILE* fopen_orDie(const char *filename, const char *instruction)
{
    FILE* const inFile = fopen(filename, instruction);
    if (inFile) return inFile;
    /* error */
    perror(filename);
    exit(2);
}

static void* malloc_orDie(size_t size)
{
    void* const buff = malloc(size);
    if (buff) return buff;
    /* error */
    perror("malloc");
    exit(3);
}

static void* loadFile_orDie(const char* fileName, size_t* size)
{
    off_t const buffSize = fsize_orDie(fileName);
    FILE* const inFile = fopen_orDie(fileName, "rb");
    void* const buffer = malloc_orDie(buffSize);
    size_t const readSize = fread(buffer, 1, buffSize, inFile);
    if (readSize != (size_t)buffSize) {
        fprintf(stderr, "fread: %s : %s \n", fileName, strerror(errno));
        exit(4);
    }
    fclose(inFile);
    *size = buffSize;
    return buffer;
}

/* createDict() :
   `dictFileName` is supposed to have been created using `zstd --train` */
static ZSTD_DDict* createDict_orDie(const char* dictFileName)
{
    size_t dictSize;
    printf("loading dictionary %s \n", dictFileName);
    void* const dictBuffer = loadFile_orDie(dictFileName, &dictSize);
    ZSTD_DDict* const ddict = ZSTD_createDDict(dictBuffer, dictSize);
    if (ddict==NULL) { fprintf(stderr, "ZSTD_createDDict error \n"); exit(5); }
    free(dictBuffer);
    return ddict;
}

static void decompress(const char* fname, const ZSTD_DDict* ddict)
{
    size_t cSize;
    void* const cBuff = loadFile_orDie(fname, &cSize);
    unsigned long long const rSize = ZSTD_getDecompressedSize(cBuff, cSize);
    if (rSize==0) {
        fprintf(stderr, "%s : original size unknown \n", fname);
        exit(6);
    }
    void* const rBuff = malloc_orDie(rSize);

    ZSTD_DCtx* const dctx = ZSTD_createDCtx();
    size_t const dSize = ZSTD_decompress_usingDDict(dctx, rBuff, rSize, cBuff, cSize, ddict);

    if (dSize != rSize) {
        fprintf(stderr, "error decoding %s : %s \n", fname, ZSTD_getErrorName(dSize));
        exit(7);
    }

    /* success */
    printf("%25s : %6u -> %7u \n", fname, (unsigned)cSize, (unsigned)rSize);

    ZSTD_freeDCtx(dctx);
    free(rBuff);
    free(cBuff);
}

int main(int argc, const char** argv)
{
    const char* const exeName = argv[0];

    if (argc<3) {
        printf("wrong arguments\n");
        printf("usage:\n");
        printf("%s [FILES] dictionary\n", exeName);
        return 1;
    }

    /* load dictionary only once */
    const char* const dictName = argv[argc-1];
    ZSTD_DDict* const dictPtr = createDict_orDie(dictName);

    int u;
    for (u=1; u<argc-1; u++) decompress(argv[u], dictPtr);

    ZSTD_freeDDict(dictPtr);
    printf("All %u files correctly decoded (in memory) \n", argc-2);
    return 0;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="app_label" msgid="8016145283189546017">"Daxiletmə Cihazları"</string>
    <string name="keyboard_layouts_label" msgid="6688773268302087545">"Android klaviaturası"</string>
    <string name="keyboard_layout_english_uk_label" msgid="6664258463319999632">"İngilis (BK)"</string>
    <string name="keyboard_layout_english_us_label" msgid="8994890249649106291">"İngilis (ABŞ)"</string>
    <string name="keyboard_layout_english_us_intl" msgid="3705168594034233583">"İngilis (ABŞ), Beynəlxalq üslub"</string>
    <string name="keyboard_layout_english_us_colemak_label" msgid="4194969610343455380">"İngilis (ABŞ), Colemak üslubu"</string>
    <string name="keyboard_layout_english_us_dvorak_label" msgid="793528923171145202">"İngilis (ABŞ), Dvorak üslubu"</string>
    <string name="keyboard_layout_german_label" msgid="8451565865467909999">"Alman"</string>
    <string name="keyboard_layout_french_label" msgid="813450119589383723">"Fransız"</string>
    <string name="keyboard_layout_french_ca_label" msgid="365352601060604832">"Fransız dili (Kanada)"</string>
    <string name="keyboard_layout_russian_label" msgid="8724879775815042968">"Rus"</string>
    <string name="keyboard_layout_russian_mac_label" msgid="3795866869038264796">"Rus, Mac üslubu"</string>
    <string name="keyboard_layout_spanish_label" msgid="7091555148131908240">"İspan"</string>
    <string name="keyboard_layout_swiss_french_label" msgid="4659191025396371684">"İsverçə Fransızı"</string>
    <string name="keyboard_layout_swiss_german_label" msgid="2305520941993314258">"İsveçrə Almanı"</string>
    <string name="keyboard_layout_belgian" msgid="2011984572838651558">"Belçikalı"</string>
    <string name="keyboard_layout_bulgarian" msgid="8951224309972028398">"Bolqar"</string>
    <string name="keyboard_layout_italian" msgid="6497079660449781213">"İtalyan"</string>
    <string name="keyboard_layout_danish" msgid="8036432066627127851">"Danimarkalı"</string>
    <string name="keyboard_layout_norwegian" msgid="9090097917011040937">"Norveçli"</string>
    <string name="keyboard_layout_swedish" msgid="732959109088479351">"İsveç"</string>
    <string name="keyboard_layout_finnish" msgid="5585659438924315466">"Fin"</string>
    <string name="keyboard_layout_croatian" msgid="4172229471079281138">"Xorvat"</string>
    <string name="keyboard_layout_czech" msgid="1349256901452975343">"Çex"</string>
    <string name="keyboard_layout_estonian" msgid="8775830985185665274">"Eston"</string>
    <string name="keyboard_layout_hungarian" msgid="4154963661406035109">"Macar"</string>
    <string name="keyboard_layout_icelandic" msgid="5836645650912489642">"İslandiyalı"</string>
    <string name="keyboard_layout_brazilian" msgid="5117896443147781939">"Braziliyalı"</string>
    <string name="keyboard_layout_portuguese" msgid="2888198587329660305">"Portuqal"</string>
    <string name="keyboard_layout_slovak" msgid="2469379934672837296">"Slovak"</string>
    <string name="keyboard_layout_slovenian" msgid="1735933028924982368">"Sloven"</string>
    <string name="keyboard_layout_turkish" msgid="7736163250907964898">"Türk"</string>
    <string name="keyboard_layout_ukrainian" msgid="8176637744389480417">"Ukrayna"</string>
    <string name="keyboard_layout_arabic" msgid="5671970465174968712">"Ərəb"</string>
    <string name="keyboard_layout_greek" msgid="7289253560162386040">"Yunan"</string>
    <string name="keyboard_layout_hebrew" msgid="7241473985890173812">"İvrit"</string>
    <string name="keyboard_layout_lithuanian" msgid="6943110873053106534">"Litva"</string>
    <string name="keyboard_layout_spanish_latin" msgid="5690539836069535697">"İspan (Latın)"</string>
    <string name="keyboard_layout_latvian" msgid="4405417142306250595">"Latış"</string>
</resources>


text:
package io.jboot.db.datasource;

import com.jfinal.kit.PathKit;
import io.jboot.core.spi.JbootSpiLoader;
import io.jboot.exception.JbootException;
import io.jboot.support.seata.JbootSeataManager;
import io.jboot.utils.StrUtil;
import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlShardingDataSourceFactory;

import javax.sql.DataSource;
import java.io.File;

public class DataSourceBuilder {

    private DataSourceConfig config;

    public DataSourceBuilder(DataSourceConfig datasourceConfig) {
        this.config = datasourceConfig;
    }

    public DataSource build() {

        String shardingConfigYaml = config.getShardingConfigYaml();

        // 不启用分库分表的配置
        if (StrUtil.isBlank(shardingConfigYaml)) {
            DataSource ds = createDataSource(config);
            return JbootSeataManager.me().wrapDataSource(ds);
        }

        File yamlFile = shardingConfigYaml.startsWith(File.separator)
                ? new File(shardingConfigYaml)
                : new File(PathKit.getRootClassPath(), shardingConfigYaml);

        try {
            return YamlShardingDataSourceFactory.createDataSource(yamlFile);
        } catch (Exception e) {
            throw new JbootException(e);
        }
    }

    private DataSource createDataSource(DataSourceConfig dsc) {

        String factory = dsc.getFactory();
        if (StrUtil.isBlank(factory)) {
            return new HikariDataSourceFactory().createDataSource(dsc);
        }

        switch (factory) {
            case "hikari":
            case "hikariCP":
            case "hikaricp":
                return new HikariDataSourceFactory().createDataSource(dsc);
            case "druid":
                return new DruidDataSourceFactory().createDataSource(dsc);
            default:
                DataSourceFactory dataSourceFactory = JbootSpiLoader.load(DataSourceFactory.class, factory);
                if (dataSourceFactory == null) {
                    throw new NullPointerException("Can not load DataSourceFactory spi for name: " + factory);
                }
                return dataSourceFactory.createDataSource(dsc);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Orleans.Runtime;
using Orleans.TestingHost;
using UnitTests.Tester;

namespace Tester.StreamingTests
{
    [Serializable]
    public class Sender
    {
        protected bool Equals(Sender other)
        {
            return string.Equals(PhotoUrl, other.PhotoUrl) && string.Equals(ProfileUrl, other.ProfileUrl) && string.Equals(LoginProvider, other.LoginProvider) && string.Equals(Name, other.Name) && IsSelf == other.IsSelf;
        }

        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = (PhotoUrl != null ? PhotoUrl.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ (ProfileUrl != null ? ProfileUrl.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ (LoginProvider != null ? LoginProvider.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ (Name != null ? Name.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ IsSelf.GetHashCode();
                return hashCode;
            }
        }

        public string PhotoUrl { get; set; }
        public string ProfileUrl { get; set; }
        public string LoginProvider { get; set; }
        public string Name { get; set; }
        public bool IsSelf { get; set; }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != GetType()) return false;
            return Equals((Sender) obj);
        }
    }

    [Serializable]
    public class Comment
    {
        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = (Id != null ? Id.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ (ThreadId != null ? ThreadId.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ (CommentText != null ? CommentText.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ (Sender != null ? Sender.GetHashCode() : 0);
                return hashCode;
            }
        }

        public string Id { get; set; }
        public string ThreadId { get; set; }
        public string CommentText { get; set; }
        public Sender Sender { get; set; }

        protected bool Equals(Comment other)
        {
            return string.Equals(Id, other.Id) && string.Equals(ThreadId, other.ThreadId) && string.Equals(CommentText, other.CommentText) && Equals(Sender, other.Sender);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != GetType()) return false;
            return Equals((Comment) obj);
        }
    }

    [Serializable]
    public class EventData
    {
        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = (CategoryId != null ? CategoryId.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ (StreamId != null ? StreamId.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ (CommentId != null ? CommentId.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ (Comment != null ? Comment.GetHashCode() : 0);
                return hashCode;
            }
        }

        public string CategoryId { get; set; }
        public string StreamId { get; set; }
        public string CommentId { get; set; }
        public Comment Comment { get; set; }

        protected bool Equals(EventData other)
        {
            return string.Equals(CategoryId, other.CategoryId) && string.Equals(StreamId, other.StreamId) && string.Equals(CommentId, other.CommentId) && Equals(Comment, other.Comment);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != GetType()) return false;
            return Equals((EventData) obj);
        }
    }

    [Serializable]
    public class Event
    {
        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = (Name != null ? Name.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ (EventData != null ? EventData.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ (Nonce != null ? Nonce.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ (Timestamp != null ? Timestamp.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ (Signature != null ? Signature.GetHashCode() : 0);
                return hashCode;
            }
        }

        public string Name { get; set; }
        public List<EventData> EventData { get; set; }
        public string Nonce { get; set; }
        public string Timestamp { get; set; }
        public string Signature { get; set; }

        protected bool Equals(Event other)
        {
            return string.Equals(Name, other.Name) && EventData.SequenceEqual(other.EventData) && string.Equals(Nonce, other.Nonce) && string.Equals(Timestamp, other.Timestamp) && string.Equals(Signature, other.Signature);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != GetType()) return false;
            return Equals((Event) obj);
        }
    }

    [DeploymentItem("OrleansConfigurationForStreamingUnitTests.xml")]
    [DeploymentItem("OrleansProviders.dll")]
    [DeploymentItem("Orleans.KafkaStreamProvider.dll")]
    [TestClass]
    public class KafkaCustomEventTests : UnitTestSiloHost
    {
        private const string KafkaStreamProviderName = "KafkaProvider";                 // must match what is in OrleansConfigurationForStreamingUnitTests.xml

        private readonly CustomEventTestRunner _runner;
        private static TestingSiloHost _host;

        public KafkaCustomEventTests()
            : base(new TestingSiloOptions()
            {
                StartFreshOrleans = false,
                StartSecondary = false,
                SiloConfigFile = new FileInfo("OrleansConfigurationForStreamingUnitTests.xml"),
            })
        {
            _runner = new CustomEventTestRunner(KafkaStreamProviderName, logger);
            _host = this;
        }

        // Use ClassCleanup to run code after all tests in a class have run
        [ClassCleanup]
        public static void MyClassCleanup()
        {
            _host.StopAllSilos();
        }

        [TestMethod, TestCategory("Functional"), TestCategory("KafkaStreamProvider"), TestCategory("Streaming")]
        public async Task SimpleCustomEventTaskTest()
        {
            logger.Info("************************ SimpleCustomEventTask *********************************");
            string valueToSend = @"
                event=newComment&
                eventData=[{
                    'categoryID': '17235654',
                    'streamID': 'strm1',
                    'commentID': '2a9f579657c044f380a4a0e1b6fc2af8',
                    'comment': {
                        'ID': '2a9f579657c044f380a4a0e1b6fc2af8',
                        'threadID': '',
                        'commentText': 'This is a comment!',
                        'sender': {
                            'photoURL': 'http://graph.facebook.com/100002990175600/picture?type=square',
                            'profileURL': http://www.facebook.com/profile.php?id=100002990175600',
                            'loginProvider': 'Facebook',
                            'name': 'Mark Zuck',
                            'isSelf':true
                        }
                    }
                 }]&
                nonce=b7a00b88e1b9469599e5f53049eb1b6d&
                timestamp=1332079751& ;
                signature=gCLCNiNxt8xGkzqzP7MugKLv2Ak=";

            await _runner.SimpleCustomEventTask(valueToSend);
        }

        [TestMethod, TestCategory("Functional"), TestCategory("KafkaStreamProvider"), TestCategory("Streaming")]
        public async Task SimpleCustomEventTaskTestComplexType()
        {
            var sender = new Sender()
            {
                PhotoUrl = "http://graph.facebook.com/100002990175600/picture?type=square",
                ProfileUrl = "http://www.facebook.com/profile.php?id=100002990175600",
                LoginProvider = "Facebook",
                Name = "Jessie Eizenberg",
                IsSelf = true
            };

            var comment = new Comment()
            {
                Id = "2a9f579657c044f380a4a0e1b6fc2af8",
                CommentText = "This is a comment!",
                Sender = sender,
                ThreadId = string.Empty
            };

            var eventData = new EventData()
            {
                CategoryId = "17235654",
                StreamId = "strm1",
                CommentId = "2a9f579657c044f380a4a0e1b6fc2af8",
                Comment = comment
            };

            var newEvent = new Event()
            {
                Name = "newComment",
                EventData = new List<EventData>() {eventData},
                Nonce = "b7a00b88e1b9469599e5f53049eb1b6d",
                Timestamp = "1332079751",
                Signature = "gCLCNiNxt8xGkzqzP7MugKLv2Ak"
            };

            await _runner.SimpleCustomEventTask(newEvent);
        }
    }
}


text:
// Search complete
//
WWHFrame.WWHSearch.fSearchPairsComplete();


text:
<?php

namespace Magento\Sales\Controller\Guest;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class PrintAction extends \Magento\Sales\Controller\AbstractController\PrintAction
{
    /**
     * @param Context $context
     * @param OrderLoader $orderLoader
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        \Magento\Sales\Controller\Guest\OrderLoader $orderLoader,
        PageFactory $resultPageFactory
    ) {
        parent::__construct($context, $orderLoader, $resultPageFactory);
    }
}


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Metaprogramação em Ruby. WAT?</title>

		<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
		<meta name="author" content="Hakim El Hattab">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/moon.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

Metaprogramação em Ruby

WAT?

						Criado pro Paulo Diniz / @paulodiniz

O que é metaprogramação?

Código que escreve código

						“Metaprogramação é a programação de programas que escrevem ou manipulam outros programas (ou a si próprios) assim como seus dados, ou que fazem parte do trabalho em tempo de compilação. Em alguns casos, isso permite que os programadores sejam mais produtivos ao evitar que parte do código seja escrita manualmente..”

No magic, just Ruby

Self, who am I?

self é sempre uma referência ao receiver atual

class User
  puts self
  def say
     puts self
     puts 'hello'
  end
end
=> User

u = User.new
u.say
=> #<User:0x007fa6a8beace8>
=> hello

Tudo é um objeto

Classes são objetos, da classe Class

Eigenclass

						Classe "escondida", específica do objeto

Pode-se abrir a eigenclass de um objeto com class << object

u = User.new
class << u
  def highlander
    puts 'There must be only one'
  end
end

class User
  class << self
    def count
      @count ||= 0
    end
  end
end

Eigenclass

Ruby esconde, mas a classe de um objeto é a sua Eigenclass

Method lookup chain

Método chamado no receiver, primeiro procura na class, depois sempre na superclass

Difícil?

Include

Executado no escopo da classe, ou seja, os métodos viram métodos de instância

Extend

Executado no escopo da eigenclass, ou seja, os métodos viram métodos de classe

define_method

Nome explicativo

define_method

Define métodos dinamicamente, tomando um bloco como parâmetro. Tornando-o muito poderoso para escrever DSLs

define_method

Extramente útil para definir métodos em módulos, e incluí-los em classes

Podemos definir métodos no escopo de uma classe ou da sua eigenclass, ou seja, podemos definir métodos de classe ou de instância.

Exemplo

require 'active_support'

module Upcasor
  extend ActiveSupport::Concern

  module ClassMethods
    def upcases(*attrs)
      attrs.each do |attr|
        define_method "#{attr}_upcased" do
          self.send(attr).upcase
        end
      end
    end
  end
end

class Person
  include Upcasor
  attr_accessor :name

  upcases :name
end

p = Person.new
p.name = 'my name'
puts p.name_upcased

=> 'MY NAME'


text:
#ifndef WEBRTC_MODULES_REMOTE_BITRATE_ESTIMATOR_OVERUSE_DETECTOR_H_
#define WEBRTC_MODULES_REMOTE_BITRATE_ESTIMATOR_OVERUSE_DETECTOR_H_

#include <list>

#include "webrtc/base/constructormagic.h"
#include "webrtc/modules/interface/module_common_types.h"
#include "webrtc/modules/remote_bitrate_estimator/include/bwe_defines.h"
#include "webrtc/typedefs.h"

namespace webrtc {
enum RateControlRegion;

bool AdaptiveThresholdExperimentIsEnabled();

class OveruseDetector {
 public:
  explicit OveruseDetector(const OverUseDetectorOptions& options);
  virtual ~OveruseDetector();

  // Update the detection state based on the estimated inter-arrival time delta
  // offset. |timestamp_delta| is the delta between the last timestamp which the
  // estimated offset is based on and the last timestamp on which the last
  // offset was based on, representing the time between detector updates.
  // |num_of_deltas| is the number of deltas the offset estimate is based on.
  // Returns the state after the detection update.
  BandwidthUsage Detect(double offset,
                        double timestamp_delta,
                        int num_of_deltas,
                        int64_t now_ms);

  // Returns the current detector state.
  BandwidthUsage State() const;

 private:
  void UpdateThreshold(double modified_offset, int64_t now_ms);
  void InitializeExperiment();

  const bool in_experiment_;
  double k_up_;
  double k_down_;
  double overusing_time_threshold_;
  // Must be first member variable. Cannot be const because we need to be
  // copyable.
  webrtc::OverUseDetectorOptions options_;
  double threshold_;
  int64_t last_update_ms_;
  double prev_offset_;
  double time_over_using_;
  int overuse_counter_;
  BandwidthUsage hypothesis_;

  DISALLOW_COPY_AND_ASSIGN(OveruseDetector);
};
}  // namespace webrtc

#endif  // WEBRTC_MODULES_REMOTE_BITRATE_ESTIMATOR_OVERUSE_DETECTOR_H_


text:
from django.db.models import Q
from contentcuration import models as cc_models
from rest_framework.decorators import api_view
from rest_framework.response import Response
from contentcuration import serializers

def get_accessible_contentnodes(request):
    exclude_channel = request.query_params.get('exclude_channel', '')

    # Get tree_ids for channels accessible to the user
    tree_ids = cc_models.Channel.objects \
        .select_related('main_tree') \
        .filter(Q(deleted=False) & (Q(public=True) | Q(editors=request.user) | Q(viewers=request.user))) \

    if exclude_channel is not None:
        tree_ids = tree_ids.exclude(pk=exclude_channel)

    tree_ids = tree_ids.values_list('main_tree__tree_id', flat=True)

    return cc_models.ContentNode.objects \
        .filter(tree_id__in=tree_ids)

@api_view(['GET'])
def search_items(request):
    """
    Keyword search of items (i.e. non-topics)
    """
    search_query = request.query_params.get('q', '').strip()

    if search_query == '':
        # TODO maybe return a proper error code
        return Response([])

    queryset = get_accessible_contentnodes(request).exclude(kind='topic')
    queryset = queryset.filter(title__icontains=search_query)
    # Using same serializer as Tree View UI to match props of ImportListItem
    serializer = serializers.SimplifiedContentNodeSerializer(queryset[:50], many=True)
    return Response(serializer.data)

@api_view(['GET'])
def search_topics(request):
    """
    Keyword search of topics
    """
    search_query = request.query_params.get('q', '').strip()

    if search_query == '':
        return Response([])

    queryset = get_accessible_contentnodes(request).filter(kind='topic')
    queryset = queryset.filter(title__icontains=search_query)
    serializer = serializers.SimplifiedContentNodeSerializer(queryset[:50], many=True)
    return Response(serializer.data)


text:
package com.sun.swingset3;

import java.awt.Component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.logging.Level;
import javax.swing.Icon;
import javax.swing.ImageIcon;

/**
 * Wrapper class which encapsulates a GUI component to be displayed
 * as a SwingSet3 demo.
 * @author Amy Fowler
 */
public class Demo {

    public enum State { UNINITIALIZED, INITIALIZING, INITIALIZED, RUNNING, STOPPED, FAILED }

    private static final String IMAGE_EXTENSIONS[] = {".gif", ".png", ".jpg"};

    public static String deriveCategoryFromPackageName(String className) {
        String parts[] = className.split("\\.");
        // return the right-most package name
        return parts.length >= 2? parts[parts.length-2] : "general";
    }

    public static String deriveCategoryFromPackageName(Class demoClass) {
        String packageName = demoClass.getPackage() != null?
            demoClass.getPackage().getName() : null;
        if (packageName != null) {
            // if root package is swingset3, then remove it
            String swingsetPackageName = Demo.class.getPackage().getName();
            if (packageName.startsWith(swingsetPackageName + ".demos.")) {
                packageName = packageName.replaceFirst(swingsetPackageName + ".demos.",
                        "");
            }
        }
        return packageName != null? packageName : "general";
    }

    public static String deriveNameFromClassName(String className) {
        String simpleName = className.substring(className.lastIndexOf(".")+1, className.length());
        return convertToDemoName(simpleName);
    }

    public static String deriveNameFromClassName(Class demoClass) {
        String className = demoClass.getSimpleName();
        return convertToDemoName(className);
    }

    private static String convertToDemoName(String simpleClassName) {
        StringBuffer nameBuffer = new StringBuffer();
        if (simpleClassName.endsWith("Demo")) {
            nameBuffer.append(simpleClassName.substring(0, simpleClassName.indexOf("Demo")));
            nameBuffer.append(" ");
            nameBuffer.append("Demo");
        }
        return nameBuffer.toString();
    }

    private Class<?> demoClass;
    private String name;
    private String category;
    private String shortDescription; // used for tooltips
    private String iconPath;
    private Icon icon;
    private String[] sourceFilePaths;
    private URL[] sourceFiles;

    private Component component;

    private State state;

    private Exception failException;

    private PropertyChangeSupport pcs;

    public Demo(Class<?> demoClass) {
        this.demoClass = demoClass;

        initializeProperties();
    }

    protected void initializeProperties() {

        // First look for DemoProperties annotation if it exists
        DemoProperties properties = demoClass.getAnnotation(DemoProperties.class);
        if (properties != null) {
            this.name = properties.value();
            this.category = properties.category();
            this.shortDescription = properties.description();
            this.iconPath = properties.iconFile();
            this.sourceFilePaths = properties.sourceFiles();
        } else {
            this.name = deriveNameFromClassName(demoClass);
            this.category = deriveCategoryFromPackageName(demoClass);
            this.shortDescription = "No demo description, run it to find out...";
        }
        state = State.UNINITIALIZED;
        pcs = new PropertyChangeSupport(this);
    }

    public Class getDemoClass() {
        return demoClass;
    }

    public String getName() {
        return name;
    }

    public String getCategory() {
        return category;
    }

    public Icon getIcon() {
        if (icon == null) {
            if (iconPath != null && !iconPath.equals("")) {
                // icon packageName was specified in DemoProperties annotation
                icon = getIconFromPath(iconPath);
            } else {
                // Look for icon with same name as demo class
                for(String ext : IMAGE_EXTENSIONS) {
                    icon = getIconFromPath(getIconImagePath(ext));
                    if (icon != null) {
                        break;
                    }
                }
            }
        }
        return icon;
    }

    protected String getIconImagePath(String extension) {
        // by default look for an image with the same name as the demo class
        return "resources/images/" +
                demoClass.getSimpleName() + extension;
    }

    private Icon getIconFromPath(String path) {
        Icon icon = null;
        URL imageURL = demoClass.getResource(path);
        if (imageURL != null) {
            icon = new ImageIcon(imageURL);
        }
        return icon;
    }

    public String getShortDescription() {
        return shortDescription;
    }

    public URL getHTMLDescription() {
        // by default look for an html file with the same name as the demo class
        return demoClass.getResource("resources/" +
                demoClass.getSimpleName() + ".html");
    }

    public URL[] getSourceFiles() {
        // If not already cached, then look them up
        if (sourceFiles == null) {
            ArrayList<URL> pathURLs = new ArrayList<URL>();

            // Get any names registered in DemoProperties meta-data.
            // If meta-data is not specified then sourceFilePaths contains
            // one empty string. In this case we skip it.
            if (!(sourceFilePaths.length == 1 && sourceFilePaths[0].length() == 0)) {
                for (String path : sourceFilePaths) {
                    URL url = getClass().getClassLoader().getResource(path);
                    if (url == null) {
                        SwingSet3.logger.log(Level.WARNING,
                                "unable to load source file '" + path + "'");
                    } else {
                        pathURLs.add(url);
                    }
                }
            }

            this.sourceFiles = pathURLs.toArray(new URL[pathURLs.size()]);
        }

        return sourceFiles;
    }

    void startInitializing() {
        setState(Demo.State.INITIALIZING);
    }

    void setDemoComponent(Component component) {
        if (component != null && !demoClass.isInstance(component)) {
            setState(State.FAILED);
            IllegalArgumentException e =
                    new IllegalArgumentException("component must be an instance of " +
                    demoClass.getCanonicalName());
            failException = e;
            throw e;
        }
        Component old = this.component;
        this.component = component;

        if (component != null) {
            init();
        } else {
            setState(State.UNINITIALIZED);
        }
        pcs.firePropertyChange("demoComponent", old, component);

    }

    public Component createDemoComponent() {
        Component component = null;
        try {
            component = (Component)demoClass.newInstance();
            setDemoComponent(component);
        } catch (Exception e) {
            System.err.println(e);
            e.printStackTrace();
            failException = e;
            setState(State.FAILED);
        }
        return component;
    }

    public Component getDemoComponent() {
        return component;
    }

    public State getState() {
        return state;
    }

    protected void setState(State state) {
        State oldState = this.state;
        this.state = state;
        SwingSet3.logger.log(Level.FINE, "***>" +getName() + ":setState="+state);
        pcs.firePropertyChange("state", oldState, state);
    }

    public void addPropertyChangeListener(PropertyChangeListener pcl) {
        pcs.addPropertyChangeListener(pcl);
    }

    public void removePropertyChangeListener(PropertyChangeListener pcl) {
        pcs.removePropertyChangeListener(pcl);
    }

    private void init() {
        setState(State.INITIALIZED);
        try {
            Method initMethod = demoClass.getMethod("init", (Class[])null);
            initMethod.invoke(component, (Object[])null);
        } catch (NoSuchMethodException nsme) {
            // okay, no init method exists
        } catch (IllegalAccessException iae) {
            SwingSet3.logger.log(Level.SEVERE, "unable to init demo: "+demoClass.getName(), iae);
            failException = iae;
            setState(State.FAILED);
        } catch (java.lang.reflect.InvocationTargetException ite) {
            SwingSet3.logger.log(Level.SEVERE, "init method failed for demo: "+demoClass.getName(), ite);
            failException = ite;
            setState(State.FAILED);
        } catch (NullPointerException npe) {
            SwingSet3.logger.log(Level.SEVERE, "init method called before demo was instantiated: "
                    +demoClass.getName(), npe);
            failException = npe;
            setState(State.FAILED);
        }
    }

    public void start() {

        try {
            Method startMethod = demoClass.getMethod("start", (Class[])null);
            startMethod.invoke(component, (Object[])null);
            setState(State.RUNNING);
        } catch (NoSuchMethodException nsme) {
            setState(State.RUNNING);
            // okay, no start method exists
        } catch (IllegalAccessException iae) {
            SwingSet3.logger.log(Level.SEVERE, "unable to start demo: "+demoClass.getName(), iae);
            failException = iae;
            setState(State.FAILED);
        } catch (java.lang.reflect.InvocationTargetException ite) {
            SwingSet3.logger.log(Level.SEVERE, "start method failed for demo: "+demoClass.getName(), ite);
            failException = ite;
            setState(State.FAILED);
        } catch (NullPointerException npe) {
            SwingSet3.logger.log(Level.SEVERE, "start method called before demo was instantiated: "
                    +demoClass.getName(), npe);
            failException = npe;
            setState(State.FAILED);
        }
    }

    public void stop() {
        setState(State.STOPPED);
        try {
            Method stopMethod = demoClass.getMethod("stop", (Class[])null);
            stopMethod.invoke(component, (Object[])null);

        } catch (NoSuchMethodException nsme) {
            // okay, no stop method exists

        } catch (IllegalAccessException iae) {
            SwingSet3.logger.log(Level.SEVERE, "unable to stop demo: "+demoClass.getName(), iae);
            failException = iae;
            setState(State.FAILED);
        } catch (java.lang.reflect.InvocationTargetException ite) {
            SwingSet3.logger.log(Level.SEVERE, "stop method failed for demo: "+demoClass.getName(), ite);
            failException = ite;
            setState(State.FAILED);
        } catch (NullPointerException npe) {
            SwingSet3.logger.log(Level.SEVERE, "stop method called before demo was instantiated: "
                    +demoClass.getName(), npe);
        }
    }
}


text:
Stringsetting.data.simpleData.pIdKey

概述[ 依赖 jquery.ztree.core 核心 js ]

节点数据中保存其父节点唯一标识的属性名称。[setting.data.simpleData.enable = true 时生效]

默认值:"pId"

setting 举例

1. 使用简单 Array 格式的数据

var setting = {
	data: {
		simpleData: {
			enable: true,
			idKey: "id",
			pIdKey: "pId",
			rootPId: 0
		}
	}
};
var treeNodes = [
    {"id":1, "pId":0, "name":"test1"},
    {"id":11, "pId":1, "name":"test11"},
    {"id":12, "pId":1, "name":"test12"},
    {"id":111, "pId":11, "name":"test111"}
];
......


text:
using extensions::AppWindow;
using extensions::AppWindowRegistry;

namespace chromeos {

namespace {

#if BUILDFLAG(ENABLE_PLUGINS)
bool IsPepperPlugin(const base::FilePath& plugin_path) {
  content::WebPluginInfo plugin_info;
  return content::PluginService::GetInstance()->GetPluginInfoByPath(
             plugin_path, &plugin_info) &&
         plugin_info.is_pepper_plugin();
}
#endif

void RebootDevice() {
  chromeos::PowerManagerClient::Get()->RequestRestart(
      power_manager::REQUEST_RESTART_OTHER, "kiosk app session");
}

// Sends a SIGFPE signal to plugin subprocesses that matches |child_ids|
// to trigger a dump.
void DumpPluginProcess(const std::set<int>& child_ids) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  bool dump_requested = false;

  content::BrowserChildProcessHostIterator iter(
      content::PROCESS_TYPE_PPAPI_PLUGIN);
  while (!iter.Done()) {
    const content::ChildProcessData& data = iter.GetData();
    if (child_ids.count(data.id) == 1) {
      // Send a signal to dump the plugin process.
      if (kill(data.GetProcess().Handle(), SIGFPE) == 0) {
        dump_requested = true;
      } else {
        PLOG(WARNING) << "Failed to send SIGFPE to plugin process"
                      << ", pid=" << data.GetProcess().Pid()
                      << ", type=" << data.process_type
                      << ", name=" << data.name;
      }
    }
    ++iter;
  }

  // Wait a bit to let dump finish (if requested) before rebooting the device.
  const int kDumpWaitSeconds = 10;
  content::GetUIThreadTaskRunner({})->PostDelayedTask(
      FROM_HERE, base::BindOnce(&RebootDevice),
      base::Seconds(dump_requested ? kDumpWaitSeconds : 0));
}

}  // namespace

class AppSession::AppWindowHandler : public AppWindowRegistry::Observer {
 public:
  explicit AppWindowHandler(AppSession* app_session)
      : app_session_(app_session) {}
  AppWindowHandler(const AppWindowHandler&) = delete;
  AppWindowHandler& operator=(const AppWindowHandler&) = delete;
  ~AppWindowHandler() override {}

  void Init(Profile* profile, const std::string& app_id) {
    DCHECK(!window_registry_);
    window_registry_ = AppWindowRegistry::Get(profile);
    if (window_registry_)
      window_registry_->AddObserver(this);
    app_id_ = app_id;
  }

 private:
  // extensions::AppWindowRegistry::Observer overrides:
  void OnAppWindowAdded(AppWindow* app_window) override {
    if (app_window->extension_id() != app_id_)
      return;

    app_session_->OnAppWindowAdded(app_window);
    app_window_created_ = true;
  }

  void OnAppWindowRemoved(AppWindow* app_window) override {
    if (!app_window_created_ ||
        !window_registry_->GetAppWindowsForApp(app_id_).empty()) {
      return;
    }

    app_session_->OnLastAppWindowClosed();
    window_registry_->RemoveObserver(this);
  }

  const raw_ptr<AppSession> app_session_;
  raw_ptr<AppWindowRegistry> window_registry_ = nullptr;
  std::string app_id_;
  bool app_window_created_ = false;
};

#if BUILDFLAG(ENABLE_PLUGINS)
class AppSession::PluginHandlerDelegateImpl
    : public KioskSessionPluginHandlerDelegate {
 public:
  explicit PluginHandlerDelegateImpl(AppSession* owner) : owner_(owner) {}
  PluginHandlerDelegateImpl(const PluginHandlerDelegateImpl&) = delete;
  PluginHandlerDelegateImpl& operator=(const PluginHandlerDelegateImpl&) =
      delete;
  ~PluginHandlerDelegateImpl() override = default;

  // KioskSessionPluginHandlerDelegate:
  bool ShouldHandlePlugin(const base::FilePath& plugin_path) const override {
    // Note that BrowserChildProcessHostIterator in DumpPluginProcess also needs
    // to be updated when adding more plugin types here.
    return IsPepperPlugin(plugin_path);
  }
  void OnPluginCrashed(const base::FilePath& plugin_path) override {
    if (owner_->is_shutting_down())
      return;
    owner_->metrics_service_->RecordKioskSessionPluginCrashed();
    owner_->is_shutting_down_ = true;

    LOG(ERROR) << "Reboot due to plugin crash, path=" << plugin_path.value();
    RebootDevice();
  }

  void OnPluginHung(const std::set<int>& hung_plugins) override {
    if (owner_->is_shutting_down())
      return;
    owner_->metrics_service_->RecordKioskSessionPluginHung();
    owner_->is_shutting_down_ = true;

    LOG(ERROR) << "Plugin hung detected. Dump and reboot.";
    DumpPluginProcess(hung_plugins);
  }

 private:
  AppSession* const owner_;
};
#endif

AppSession::AppSession()
    : AppSession(base::BindOnce(chrome::AttemptUserExit),
                 g_browser_process->local_state()) {}

AppSession::AppSession(base::OnceClosure attempt_user_exit,
                       PrefService* local_state)
    : AppSession(std::move(attempt_user_exit),
                 local_state,
                 std::make_unique<AppSessionMetricsService>(local_state)) {}

AppSession::~AppSession() {
  if (!is_shutting_down())
    metrics_service_->RecordKioskSessionStopped();
}

// static
std::unique_ptr<AppSession> AppSession::CreateForTesting(
    base::OnceClosure attempt_user_exit,
    PrefService* local_state,
    const std::vector<std::string>& crash_dirs) {
  return base::WrapUnique(new AppSession(
      std::move(attempt_user_exit), local_state,
      AppSessionMetricsService::CreateForTesting(local_state, crash_dirs)));
}

void AppSession::RegisterLocalStatePrefs(PrefRegistrySimple* registry) {
  registry->RegisterDictionaryPref(prefs::kKioskMetrics);
}

void AppSession::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterBooleanPref(prefs::kNewWindowsInKioskAllowed, false);
}

void AppSession::Init(Profile* profile, const std::string& app_id) {
  SetProfile(profile);
  app_window_handler_ = std::make_unique<AppWindowHandler>(this);
  app_window_handler_->Init(profile, app_id);
  CreateBrowserWindowHandler(absl::nullopt);
#if BUILDFLAG(ENABLE_PLUGINS)
  plugin_handler_ = std::make_unique<KioskSessionPluginHandler>(
      plugin_handler_delegate_.get());
#endif
  metrics_service_->RecordKioskSessionStarted();
}

void AppSession::InitForWebKiosk(Browser* browser) {
  SetProfile(browser->profile());
  CreateBrowserWindowHandler(browser->app_name());
  metrics_service_->RecordKioskSessionWebStarted();
}

void AppSession::SetAttemptUserExitForTesting(base::OnceClosure closure) {
  attempt_user_exit_ = std::move(closure);
}

void AppSession::SetOnHandleBrowserCallbackForTesting(
    base::RepeatingCallback<void(bool is_closing)> callback) {
  on_handle_browser_callback_ = std::move(callback);
}

KioskSessionPluginHandlerDelegate*
AppSession::GetPluginHandlerDelegateForTesting() {
  return plugin_handler_delegate_.get();
}

AppSession::AppSession(
    base::OnceClosure attempt_user_exit,
    PrefService* local_state,
    std::unique_ptr<AppSessionMetricsService> metrics_service)
    :
#if BUILDFLAG(ENABLE_PLUGINS)
      plugin_handler_delegate_(
          std::make_unique<PluginHandlerDelegateImpl>(this)),
#endif
      attempt_user_exit_(std::move(attempt_user_exit)),
      metrics_service_(std::move(metrics_service)) {
}

void AppSession::SetProfile(Profile* profile) {
  profile_ = profile;
}

void AppSession::CreateBrowserWindowHandler(
    absl::optional<std::string> web_app_name) {
  browser_window_handler_ = std::make_unique<AppSessionBrowserWindowHandler>(
      profile_, web_app_name,
      base::BindRepeating(&AppSession::OnHandledNewBrowserWindow,
                          weak_ptr_factory_.GetWeakPtr()),
      base::BindRepeating(&AppSession::OnLastAppWindowClosed,
                          weak_ptr_factory_.GetWeakPtr()));
}

void AppSession::OnHandledNewBrowserWindow(bool is_closing) {
  if (on_handle_browser_callback_)
    on_handle_browser_callback_.Run(is_closing);
}

void AppSession::OnAppWindowAdded(AppWindow* app_window) {
  if (is_shutting_down())
    return;

#if BUILDFLAG(ENABLE_PLUGINS)
  plugin_handler_->Observe(app_window->web_contents());
#endif
}

void AppSession::OnGuestAdded(content::WebContents* guest_web_contents) {
  // Bail if the session is shutting down.
  if (is_shutting_down())
    return;

  // Bail if the guest is not a WebViewGuest.
  if (!extensions::WebViewGuest::FromWebContents(guest_web_contents))
    return;

#if BUILDFLAG(ENABLE_PLUGINS)
  plugin_handler_->Observe(guest_web_contents);
#endif
}

void AppSession::OnLastAppWindowClosed() {
  if (is_shutting_down())
    return;
  is_shutting_down_ = true;
  metrics_service_->RecordKioskSessionStopped();

  std::move(attempt_user_exit_).Run();
}

Browser* AppSession::GetSettingsBrowserForTesting() {
  if (browser_window_handler_) {
    return browser_window_handler_->GetSettingsBrowserForTesting();  // IN-TEST
  }
  return nullptr;
}

}  // namespace chromeos


text:
namespace gfx {
struct PresentationFeedback;
}

namespace viz {
struct BeginFrameArgs;
}

namespace cc {
struct BeginMainFrameMetrics;
struct CommitState;
struct WebVitalMetrics;

struct ApplyViewportChangesArgs {
  // Scroll offset delta of the inner (visual) viewport.
  gfx::Vector2dF inner_delta;

  // Elastic overscroll effect offset delta. This is used only on Mac. a.k.a
  // "rubber-banding" overscroll.
  gfx::Vector2dF elastic_overscroll_delta;

  // "Pinch-zoom" page scale delta. This is a multiplicative delta. i.e.
  // main_thread_scale * delta == impl_thread_scale.
  float page_scale_delta;

  // Indicates that a pinch gesture is currently active or not; used to allow
  // subframe compositors to throttle their re-rastering during the gesture.
  bool is_pinch_gesture_active;

  // How much the top controls have been shown or hidden. The ratio runs
  // between a set min-height (default 0) and 1 (full-shown). This is additive.
  float top_controls_delta;

  // How much the bottom controls have been shown or hidden. The ratio runs
  // between a set min-height (default 0) and 1 (full-shown). This is additive.
  float bottom_controls_delta;

  // Whether the browser controls have been locked to fully hidden or shown or
  // whether they can be freely moved.
  BrowserControlsState browser_controls_constraint;

  // Set to true when a scroll gesture being handled on the compositor has
  // ended.
  bool scroll_gesture_did_end;
};

using ManipulationInfo = uint32_t;
constexpr ManipulationInfo kManipulationInfoNone = 0;
constexpr ManipulationInfo kManipulationInfoWheel = 1 << 0;
constexpr ManipulationInfo kManipulationInfoTouch = 1 << 1;
constexpr ManipulationInfo kManipulationInfoPrecisionTouchPad = 1 << 2;
constexpr ManipulationInfo kManipulationInfoPinchZoom = 1 << 3;
constexpr ManipulationInfo kManipulationInfoScrollbar = 1 << 4;

struct PaintBenchmarkResult {
  double record_time_ms = 0;
  double record_time_caching_disabled_ms = 0;
  double record_time_subsequence_caching_disabled_ms = 0;
  double raster_invalidation_and_convert_time_ms = 0;
  double paint_artifact_compositor_update_time_ms = 0;
  size_t painter_memory_usage = 0;
};

// A LayerTreeHost is bound to a LayerTreeHostClient. The main rendering
// loop (in ProxyMain or SingleThreadProxy) calls methods on the
// LayerTreeHost, which then handles them and also calls into the equivalent
// methods on its LayerTreeHostClient when applicable.
//
// One important example of a LayerTreeHostClient is (via additional
// indirections) Blink.
class LayerTreeHostClient {
 public:
  virtual void WillBeginMainFrame() = 0;
  // Marks finishing compositing-related tasks on the main thread. In threaded
  // mode, this corresponds to DidCommit().

  // For a LayerTreeHostClient backed by Blink, BeginMainFrame will:
  // -Dispatch BeginMainFrame-aligned input events.
  // -Advance frame-synchronized animations and callbacks. These include
  // gesture animations, autoscroll animations, declarative
  // CSS animations (including both main-thread and compositor thread
  // animations), and script-implemented requestAnimationFrame animations.
  //
  // Note: CSS animations which run on the main thread invalidate rendering
  // phases as appropriate. CSS animations which run on the compositor
  // invalidate styles, and then update transforms or opacity on the Layer tree.
  // Compositor animations need to be updated here, because there is no
  // other mechanism by which the compositor syncs animation state for these
  // animations to Blink.
  virtual void BeginMainFrame(const viz::BeginFrameArgs& args) = 0;

  virtual void BeginMainFrameNotExpectedSoon() = 0;
  virtual void BeginMainFrameNotExpectedUntil(base::TimeTicks time) = 0;
  // This is called immediately after notifying the impl thread that it should
  // do a commit, possibly before the commit has finished (depending on whether
  // features::kNonBlockingCommit is enabled). It is meant for work that must
  // happen prior to returning control to the main thread event loop.
  virtual void DidBeginMainFrame() = 0;
  virtual void WillUpdateLayers() = 0;
  virtual void DidUpdateLayers() = 0;

  virtual void DidObserveFirstScrollDelay(
      base::TimeDelta first_scroll_delay,
      base::TimeTicks first_scroll_timestamp) = 0;
  // Notification that the proxy started or stopped deferring main frame updates
  virtual void OnDeferMainFrameUpdatesChanged(bool) = 0;

  // Notification that the proxy started or stopped deferring commits. |reason|
  // indicates why commits are/were deferred. |trigger| indicates why the commit
  // restarted. |trigger| is always provided on restarts, when |defer_status|
  // switches to false.
  virtual void OnDeferCommitsChanged(
      bool defer_status,
      PaintHoldingReason reason,
      absl::optional<PaintHoldingCommitTrigger> trigger) = 0;

  // Notification that rendering has been paused or resumed.
  virtual void OnPauseRenderingChanged(bool) = 0;

  // Visual frame-based updates to the state of the LayerTreeHost are expected
  // to happen only in calls to LayerTreeHostClient::UpdateLayerTreeHost, which
  // should mutate/invalidate the layer tree or other page parameters as
  // appropriate.
  //
  // For a LayerTreeHostClient backed by Blink, this method will update
  // (Blink's notions of) style, layout, paint invalidation and compositing
  // state. (The "compositing state" will result in a mutated layer tree on the
  // LayerTreeHost via additional interface indirections which lead back to
  // mutations on the LayerTreeHost.)
  virtual void UpdateLayerTreeHost() = 0;

  // Notifies the client of viewport-related changes that occured in the
  // LayerTreeHost since the last commit. This typically includes things
  // related to pinch-zoom, browser controls (aka URL bar), overscroll, etc.
  virtual void ApplyViewportChanges(const ApplyViewportChangesArgs& args) = 0;

  // Notifies the client about scroll and input related changes that occurred in
  // the LayerTreeHost since the last commit.
  virtual void UpdateCompositorScrollState(
      const CompositorCommitData& commit_data) = 0;

  // Request a LayerTreeFrameSink from the client. When the client has one it
  // should call LayerTreeHost::SetLayerTreeFrameSink. This will result in
  // either DidFailToInitializeLayerTreeFrameSink or
  // DidInitializeLayerTreeFrameSink being called.
  virtual void RequestNewLayerTreeFrameSink() = 0;
  virtual void DidInitializeLayerTreeFrameSink() = 0;
  virtual void DidFailToInitializeLayerTreeFrameSink() = 0;
  virtual void WillCommit(const CommitState&) = 0;
  // Report that a commit to the impl thread has completed. The
  // commit_start_time is the time that the impl thread began processing the
  // commit, or base::TimeTicks() if the commit did not require action by the
  // impl thread.
  virtual void DidCommit(base::TimeTicks commit_start_time,
                         base::TimeTicks commit_finish_time) = 0;
  virtual void DidCommitAndDrawFrame() = 0;
  virtual void DidReceiveCompositorFrameAck() = 0;
  virtual void DidCompletePageScaleAnimation() = 0;
  virtual void DidPresentCompositorFrame(
      uint32_t frame_token,
      const gfx::PresentationFeedback& feedback) = 0;
  // Mark the frame start and end time for UMA and UKM metrics that require
  // the time from the start of BeginMainFrame to the Commit, or early out.
  virtual void RecordStartOfFrameMetrics() = 0;
  // This is called immediately after notifying the impl thread that it should
  // do a commit, possibly before the commit has finished (depending on whether
  // features::kNonBlockingCommit is enabled). It is meant to record the time
  // when the main thread is finished with its part of a main frame, and will
  // return control to the main thread event loop.
  virtual void RecordEndOfFrameMetrics(
      base::TimeTicks frame_begin_time,
      ActiveFrameSequenceTrackers trackers) = 0;
  // Return metrics information for the stages of BeginMainFrame. This is
  // ultimately implemented by Blink's LocalFrameUKMAggregator. It must be a
  // distinct call from the FrameMetrics above because the BeginMainFrameMetrics
  // for compositor latency must be gathered before the layer tree is
  // committed to the compositor, which is before the call to
  // RecordEndOfFrameMetrics.
  virtual std::unique_ptr<BeginMainFrameMetrics> GetBeginMainFrameMetrics() = 0;
  virtual void NotifyThroughputTrackerResults(CustomTrackerResults results) = 0;

  // Should only be implemented by Blink.
  virtual std::unique_ptr<WebVitalMetrics> GetWebVitalMetrics() = 0;

  virtual void RunPaintBenchmark(int repeat_count,
                                 PaintBenchmarkResult& result) {}

 protected:
  virtual ~LayerTreeHostClient() = default;
};

// LayerTreeHost->WebThreadScheduler callback interface. Instances of this class
// must be safe to use on both the compositor and main threads.
class LayerTreeHostSchedulingClient {
 public:
  // Called unconditionally when BeginMainFrame runs on the main thread.
  virtual void DidRunBeginMainFrame() = 0;
};

}  // namespace cc

#endif  // CC_TREES_LAYER_TREE_HOST_CLIENT_H_


text:
#define _GNU_SOURCE
#include <sched.h>
#include <sys/types.h>
#include <time.h>
#include <pcap.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>

#include "util.h"

/**************************************
 * The time difference in millisecond *
 **************************************/
double delta_time (struct timeval *now, struct timeval *before)
{
    time_t delta_seconds;
    time_t delta_microseconds;

    /* compute delta in second, 1/10's and 1/1000's second units */
    delta_seconds      = now->tv_sec  - before->tv_sec;
    delta_microseconds = now->tv_usec - before->tv_usec;

    if (delta_microseconds < 0) {
        /* manually carry a one from the seconds field */
        delta_microseconds += 1000000;    /* 1e6 */
        --delta_seconds;
    }
    return ((double)(delta_seconds * 1000) + (double)delta_microseconds/1000);
}

void print_stats(int type, void *pd, struct timeval *start, unsigned long long pkts, unsigned long long bytes)
{
    struct pcap_stat pcapStat;
    //pfring_stat pfringStat;

    struct timeval endTime;
    double deltaMillisec;
    static u_int64_t lastPkts = 0, lastBytes = 0;
    static struct timeval lastTime;
    unsigned long long diffPkts, diffBytes;
    unsigned long long recv = 0, drop = 0;

    if (start->tv_sec == 0) {
        gettimeofday(start, NULL);
    }

    gettimeofday(&endTime, NULL);
    deltaMillisec = delta_time(&endTime, start);

    if (type == PCAP && pcap_stats(pd, &pcapStat) >= 0) {
        recv = pcapStat.ps_recv;
        drop = pcapStat.ps_drop;
    }
//    else if (type == PFRING && pfring_stats(pd, &pfringStat) >= 0) {
//        recv = pfringStat.recv;
//        drop = pfringStat.drop;
//    }

    if (recv != 0 || drop != 0) {
        printf("=========================\n");
        printf("Absolute Stats: %llu pkts rcvd, %llu pkts dropped\n", recv, drop);
        printf("%llu pkts [%.1f pkt/sec] - %llu bytes [%.2f Mbit/sec]\n",
                pkts, (pkts*1000.0)/deltaMillisec,
                bytes, (bytes*8.0)/(deltaMillisec*1000));

        if (lastTime.tv_sec > 0) {
            deltaMillisec = delta_time(&endTime, &lastTime);
            diffPkts = pkts - lastPkts;
            diffBytes = bytes - lastBytes;
            printf("=========================\n");
            printf("Interval Stats: %.1f s\n", deltaMillisec/1000);
            printf("%llu pkts [%.2f pkt/sec] - %llu bytes [%.2f Mbit/sec]\n",
                   diffPkts, (diffPkts*1000.0)/deltaMillisec,
                   diffBytes, (diffBytes*8.0)/(deltaMillisec*1000));
        }
    }
    else {
        printf("=========================\n");
        printf("No packets seen in this interval\n");
    }

    lastTime.tv_sec = endTime.tv_sec;
    lastTime.tv_usec = endTime.tv_usec;
    lastPkts = pkts;
    lastBytes = bytes;

    printf("=========================\n");
}


text:
package org.edx.mobile.view.adapters;

import android.content.Context;
import android.support.annotation.ColorInt;
import android.support.v4.widget.TextViewCompat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.google.inject.Inject;

import org.edx.mobile.R;
import org.edx.mobile.core.IEdxEnvironment;
import org.edx.mobile.discussion.DiscussionThread;
import org.edx.mobile.third_party.iconify.IconDrawable;
import org.edx.mobile.third_party.iconify.IconView;
import org.edx.mobile.third_party.iconify.Iconify;

public class DiscussionPostsAdapter extends BaseListAdapter<DiscussionThread> {

    private boolean voteCountsEnabled;

    @ColorInt
    private final int edx_brand_primary_base;
    @ColorInt
    private final int edx_grayscale_neutral_light;
    @ColorInt
    private final int edx_grayscale_neutral_xx_light;
    @ColorInt
    private final int edx_grayscale_neutral_white;

    @Inject
    public DiscussionPostsAdapter(Context context, IEdxEnvironment environment) {
        super(context, R.layout.row_discussion_thread, environment);
        edx_brand_primary_base = context.getResources().getColor(R.color.edx_brand_primary_base);
        edx_grayscale_neutral_light = context.getResources().getColor(R.color.edx_grayscale_neutral_light);
        edx_grayscale_neutral_xx_light = context.getResources().getColor(R.color.edx_grayscale_neutral_xx_light);
        edx_grayscale_neutral_white = context.getResources().getColor(R.color.edx_grayscale_neutral_white);
    }

    @Override
    public void render(BaseViewHolder tag, DiscussionThread discussionThread) {
        ViewHolder holder = (ViewHolder) tag;

        Iconify.IconValue iconValue = Iconify.IconValue.fa_comments;
        if (discussionThread.getType() == DiscussionThread.ThreadType.QUESTION) {
            iconValue = discussionThread.isHasEndorsed() ?
                    Iconify.IconValue.fa_check_square_o : Iconify.IconValue.fa_question;
        }
        holder.discussionPostTypeIcon.setIcon(iconValue);

        String threadTitle = discussionThread.getTitle();
        holder.discussionPostTitle.setText(threadTitle);

        holder.discussionPostClosedIcon.setVisibility(discussionThread.isClosed() ? View.VISIBLE : View.GONE);
        holder.discussionPostPinIcon.setVisibility(discussionThread.isPinned() ? View.VISIBLE : View.GONE);
        holder.discussionPostFollowIcon.setVisibility(discussionThread.isFollowing() ? View.VISIBLE : View.GONE);

        {
            String authorLabel = discussionThread.getAuthorLabel();
            if (authorLabel != null) {
                holder.discussionPostAuthor.setVisibility(View.VISIBLE);
                holder.discussionPostAuthor.setText(getContext().getString(R.string.discussion_priviledged_author_attribution, authorLabel));

            } else {
                holder.discussionPostAuthor.setVisibility(View.GONE);
            }
        }

        {
            final String text;
            final Iconify.IconValue icon;
            @ColorInt
            final int indicatorColor;
            if (voteCountsEnabled) {
                text = Integer.toString(discussionThread.getVoteCount());
                icon = Iconify.IconValue.fa_plus;
                indicatorColor = discussionThread.isVoted() ? edx_brand_primary_base : edx_grayscale_neutral_light;
            } else {
                text = Integer.toString(discussionThread.getCommentCount());
                icon = Iconify.IconValue.fa_comment;
                indicatorColor = discussionThread.getUnreadCommentCount() == 0 ? edx_grayscale_neutral_light : edx_brand_primary_base;
            }
            holder.discussionPostIndicatorTextView.setText(text);
            holder.discussionPostIndicatorTextView.setTextColor(indicatorColor);

            final IconDrawable iconDrawable = new IconDrawable(getContext(), icon).sizePx((int) holder.discussionPostIndicatorTextView.getTextSize()).color(indicatorColor);
            if (voteCountsEnabled) {
                TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(
                        holder.discussionPostIndicatorTextView, iconDrawable, null, null, null);
            } else {
                TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(
                        holder.discussionPostIndicatorTextView, null, null, iconDrawable, null);
            }

        }
        holder.discussionPostRow.setBackgroundColor(discussionThread.isRead() ? edx_grayscale_neutral_xx_light : edx_grayscale_neutral_white);
    }

    @Override
    public BaseViewHolder getTag(View convertView) {
        return new ViewHolder(convertView);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    }

    public void setVoteCountsEnabled(boolean voteCountsEnabled) {
        this.voteCountsEnabled = voteCountsEnabled;
    }

    private static class ViewHolder extends BaseViewHolder {
        final View discussionPostRow;
        final IconView discussionPostTypeIcon;
        final TextView discussionPostTitle;
        final IconView discussionPostClosedIcon;
        final IconView discussionPostPinIcon;
        final IconView discussionPostFollowIcon;
        final TextView discussionPostAuthor;
        final TextView discussionPostIndicatorTextView;

        public ViewHolder(View convertView) {
            discussionPostRow = convertView;
            discussionPostTypeIcon = (IconView) convertView.findViewById(R.id.discussion_post_type_icon);
            discussionPostTitle = (TextView) convertView.findViewById(R.id.discussion_post_title);
            discussionPostClosedIcon = (IconView) convertView.findViewById(R.id.discussion_post_closed_icon);
            discussionPostPinIcon = (IconView) convertView.findViewById(R.id.discussion_post_pin_icon);
            discussionPostFollowIcon = (IconView) convertView.findViewById(R.id.discussion_post_following_icon);
            discussionPostAuthor = (TextView) convertView.findViewById(R.id.discussion_post_author);
            discussionPostIndicatorTextView = (TextView) convertView.findViewById(R.id.discussion_post_indicator_text);
        }

    }
}