text:
/*
 * Public Domain 2014 John Howard, Wesley Ebisuzaki
 *
 *  Initialize the global variables
 *  change from original  int variable = value;
 *  to                    init() {
 *                          variable = value;
 *                        }
 *
 * needed to make wgrib2 a callable routine
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "grb2.h"
#include "wgrib2.h"
#include "fnlist.h"

#ifdef USE_G2CLIB
#include "grib2.h"
gribfield *grib_data;
int free_gribfield;			// flag for allocated gribfield
#endif

/* global variables .. can be modified by funtions */

extern int mode;		/*-2=finalize, -1=initialize,  0 .. N is verbosity mode */
extern int header;    		/* file header flag */
extern int flush_mode;		/* flush of output 1 = yes */
extern int WxText;		/* decode NDFD keys */

extern int use_g2clib;		/* use g2clib/emulation code for decoding */
extern int use_gctpc;		/* use gctpc for geolocation */
extern int use_proj4;		/* use Proj4 for geolocation */

extern int fix_ncep_2_flag;
extern int fix_ncep_3_flag;
extern int fix_ncep_4_flag;

extern int for_mode, for_start, for_end, for_step;
extern int for_n_mode, for_n_start, for_n_end, for_n_step;

extern int match, match_fs;
extern int match_flag;

extern int fgrep, fgrep_flag, fgrep_count;
#ifdef USE_REGEX
extern int egrep, egrep_flag, egrep_count;
#endif

extern int last_message;	/* last message to process if set */

extern struct seq_file inv_file;

extern enum input_type input;
extern enum output_order_type output_order, output_order_wanted;

extern char inv_out[INV_BUFFER]; 		/* inv functions write to this buffer */

extern int only_submsg;    /* if only_submsg > 0 .. only process submsg number (only_submsg) */

// extern int io_buffer_cnt;                  /* rd_grib_msg.c */
// extern long int pos_input;

/* output file variables */

extern int file_append;
extern int dump_msg, dump_submsg;
extern int ieee_little_endian;

extern int decode;		/* decode grib file flag */

extern const char *item_deliminator;
extern const char *nl;
extern const char *end_inv;	/* string to write after end of inventory */

/* current grib location */
extern long int pos;
extern unsigned long int len;
extern int submsg, msg_no, inv_no;

/* lat lon array .. used by Latlon.c to store location information */
extern int latlon;
extern int warn_nonzero_min_sec;
extern int GDS_change_no;
extern int old_GDS_size;
extern int GDS_max_size;
extern unsigned char *old_gds;
extern int nx, ny, res, scan;
extern unsigned int nx_, ny_;
extern unsigned int npnts;
extern int use_scale, input_scale, dec_scale, bin_scale,  max_bits, wanted_bits;
extern enum output_grib_type grib_type;
extern int use_bitmap;

extern const char **vectors, *default_vectors[];   /* New_grid.c */

/* Match.c */
#ifdef USE_REGEX
extern int match_count;
extern int regex_type;
#endif
extern int match_extra_fn_n;
/* Match_fs.c */
extern int match_count_fs;

extern int use_ext_name;		/* ExtName.c */
extern int WxNum;			/* wxtext.c */
extern char *WxTable, **WxKeys;

extern const char *text_format;		/* File.c */
extern int text_column;			/* File.c */

#ifdef USE_TIGGE
extern int tigge;			/* Tigge.c */
#endif

// extern long int pos_input;		/* seq read of grib */

extern FILE *err_file;			/* EOF.c */
extern FILE *err_str_file;

extern int save_translation;		/* Misc */

extern char *match_extra_fn_arg1[MATCH_EXTRA_FN];		/* match_inv_add */
extern char *match_extra_fn_arg2[MATCH_EXTRA_FN];
extern int match_extra_fn_n;

extern char ndates_fmt[NAMELEN];

void init_globals(void) {
    int i;

#ifdef USE_G2CLIB
    free_gribfield = 0;			// flag for allocated gribfield
#endif

    mode=0;             /* -2=finalize, -1=initialize,  0 .. N is verbosity mode */
    header=1;           /* file header flag */
    flush_mode = 0;	/* flush of output 1 = yes */
    WxText = 0;		/* decode NDFD keys */

    use_g2clib = DEFAULT_G2CLIB;        /* use g2clib/emulation code for decoding */
    use_gctpc = DEFAULT_GCTPC;          /* use gctpc for geolocation */
    use_proj4 = DEFAULT_PROJ4;          /* use Proj4 for geolocation */

    fix_ncep_2_flag = 0;
    fix_ncep_3_flag = 0;
    fix_ncep_4_flag = 0;

    for_mode = 0;
    for_n_mode = 0;

    match = match_fs = 0;

    fgrep = fgrep_flag = fgrep_count = 0;
#ifdef USE_REGEX
    egrep = egrep_flag = egrep_count = 0;
#endif
    match_extra_fn_n = 0;

    last_message = 0;   /* last message to process if set */
    /* set inv_file to stdout */
    if (fopen_file(&inv_file,"-","w") != 0) fatal_error("Could not set inv_file to stdout","");

    input = all_mode;
    output_order = output_order_wanted = wesn;

    only_submsg = 0;    /* if only_submsg > 0 .. only process submsg number (only_submsg) */

    /* output file variables */

    file_append = 0;
    dump_msg = 0, dump_submsg = 0;
    ieee_little_endian = 0;

    decode = 0;         /* decode grib file flag */

    item_deliminator = ":";
    nl = "\n\t";
    end_inv = "\n";     /* string to write after end of inventory */

    /* lat lon array .. used by Latlon.c to store location information */
    latlon = 0;
    warn_nonzero_min_sec = 1;
    GDS_change_no = 0;
    old_GDS_size = 0;
    use_scale = input_scale = 0;
    max_bits = 16;
    wanted_bits = 12;
    grib_type = simple;
    use_bitmap = 0;		/* when complex packing, do not use bitmap */

    vectors = default_vectors;	/* New_grid.c */

#ifdef USE_REGEX
    match_count = 0;		/* for Match.c */
    regex_type = 0;
#endif
    match_count_fs = 0;		/* Match_fs.c */

    use_ext_name = 0;		/* ExtName.c */
    WxTable = NULL;		/* wxtest.c */
    WxKeys = NULL;
    WxNum = 0;			/*  wxtext.c */

    text_format = "%g";		/* File.c */
    text_column = 1;

#ifdef USE_TIGGE
    tigge = 0;			/* Tigge.c */
#endif

    save_translation = 0;	/* Scan.c */

    init_mem_buffers();         /* mem_buffer.c */

//    io_buffer_cnt = 0;                  /* rd_grib_msg.c */
//    pos_input = 0;

    err_file = err_str_file = NULL;

    for (i = 0; i < MATCH_EXTRA_FN; i++) {
	match_extra_fn_arg1[i] = NULL;
	match_extra_fn_arg2[i] = NULL;
    }
    match_extra_fn_n = 0;
    strncpy(ndates_fmt," %s",4);
    return;
}


text:
<!doctype html>

    <link rel="stylesheet" href="../flashcard.css">

Angular Flash Cards

<= click the icon

click here yo

redpajama_set_name: RedPajamaGithub


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

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.wesleyware.daowiz

Class  Constraints

java.lang.Object
  |
  +--com.wesleyware.daowiz.Constraints

public class Constraints
extends java.lang.Object

This is an immutable object representaion of DB constraints.
 It is used in the construction of a DB field object.

Author:
Wesley Williams

Constructor Summary

Constraints(boolean notNullIn,
            boolean primaryKeyIn,
            boolean foreignKeyIn,
            boolean defaultValueIn)

          Constructs an immutable representation of DB field constraints.

Method Summary

 boolean
equals(java.lang.Object value)

          Indicates is this given object is equal to this field

 boolean
hasDefaultValue()

          Indicates is the field has a default value

 boolean
isForeignKey()

          Indicates if the field is or is part of a foreign key/

 boolean
isNotNull()

          Indicates of if the DB field allows null values

 boolean
isPrimaryKey()

          Indicates is the field is part of the primary key.

Methods inherited from class java.lang.Object

clone, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Constraints

public Constraints(boolean notNullIn,
                   boolean primaryKeyIn,
                   boolean foreignKeyIn,
                   boolean defaultValueIn)

Constructs an immutable representation of DB field constraints.

Parameters:
notNullIn - indicator of if the DB field is not null
primaryKeyIn - indicator of if the DB field is or is part of the primary key
foreignKeyIn - indicator of if the DB field is or is part of a foreign key
defaultValueIn - indicator of if the DB field has a default value

Method Detail

isNotNull

public boolean isNotNull()

Indicates of if the DB field allows null values

Returns:
indicator of if the DB field is not null

isPrimaryKey

public boolean isPrimaryKey()

Indicates is the field is part of the primary key.

Returns:
indicator of if the DB field is or is part of the primary key

isForeignKey

public boolean isForeignKey()

Indicates if the field is or is part of a foreign key/

Returns:
indicator of if the DB field is or is part of a foreign key

hasDefaultValue

public boolean hasDefaultValue()

Indicates is the field has a default value

Returns:
indicator of if the DB field has a default value

equals

public boolean equals(java.lang.Object value)

Indicates is this given object is equal to this field

Overrides:
equals in class java.lang.Object

Returns:
indicator of if the given object has the same constraints

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
function with_jquery(f) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.textContent = "(" + f.toString() + ")(jQuery)";
    document.body.appendChild(script);
}

with_jquery(function($) {

    function hide_show_users() {
        var present_users = $("#present-users");
        $("

").insertAfter(present_users);
        var users_button_table = $("#users-button-table");
        users_button_table.append("

");
        var users_button_row = $('#users-button-row');
        users_button_row.append("Hide Users	");
        users_button_row.append("Show Users	");
        var hide_users = $("#hide-users");
        var show_users = $('#show-users');
        var users_show_hide_buttons = $(".users-show-hide-button");

        users_button_table.css({"border-bottom":"1px dotted #cecece", "width":"100%"});
        users_show_hide_buttons.css({"color":"darkblue", "font-weight":"bold", "padding-bottom":"5px"});
        present_users.css({"margin-bottom":"5px"});
        users_show_hide_buttons.on("mouseover", function() {
            users_show_hide_buttons.css({"text-decoration":"underline", "cursor":"pointer"});
        });
        users_show_hide_buttons.on("mouseout", function() {
            users_show_hide_buttons.css({"text-decoration":"none", "cursor":"default"});
        });

        present_users.hide();
        hide_users.hide();

        show_users.on("click", function() {
            present_users.show();
            hide_users.show();
            show_users.hide();
        });
        hide_users.on("click", function() {
            present_users.hide();
            show_users.show();
            hide_users.hide();
        });
    }

    function hide_show_info() {
        var room_desc = $("#roomdesc");
        var room_tags = $('#room-tags');
        var sidebar_menu = $('#sidebar-menu');
        $("

").insertBefore(sidebar_menu);
        var info_button_table = $("#info-button-table");
        info_button_table.append("

");
        var info_button_row = $('#info-button-row');
        info_button_row.append("Hide Info	");
        info_button_row.append("Show Info	");
        var hide_info = $("#hide-info");
        var show_info = $('#show-info');
        var info_show_hide_buttons = $(".info-show-hide-button");

        info_button_table.css({"border-top":"1px dotted #cecece", "width":"100%", "border-bottom":"1px dotted #cecece"});
        info_show_hide_buttons.css({"color":"darkblue", "font-weight":"bold", "padding-top":"5px", "padding-bottom":"5px"});
        sidebar_menu.css({"padding-top":"5px"})
        info_show_hide_buttons.on("mouseover", function() {
            info_show_hide_buttons.css({"text-decoration":"underline", "cursor":"pointer"});
        });
        info_show_hide_buttons.on("mouseout", function() {
            info_show_hide_buttons.css({"text-decoration":"none", "cursor":"default"});
        });

        room_desc.hide();
        room_tags.hide();
        hide_info.hide();

        show_info.on("click", function() {
            room_desc.show();
            room_tags.show();
            hide_info.show();
            show_info.hide();
        });
        hide_info.on("click", function() {
            room_desc.hide();
            room_tags.hide();
            hide_info.hide();
            show_info.show();
        });
    }

    hide_show_users();
    hide_show_info();
});


text:
from pyactiveresource.activeresource import ActiveResource
from twisted.internet.defer import Deferred, DeferredQueue
from twisted.internet.threads import deferToThread
from twisted.python import log
import time

class Issue(ActiveResource):
    pass

class CallTracker(object):

    def __init__(self, uniqueid, callerid, templates, usermap):
        self.callerid = callerid
        self.uniqueid = uniqueid
        self.templates = templates
        self.usermap = usermap

        self.startTime = None
        self.stopTime = None
        self.callDuration = None
        self.callAnswered = False
        self.talkDuration = None
        self.talkStart = None
        self.queueMember = None

        self.issue = None
        self._issue_placeholders = {}

        self._ar_queue = DeferredQueue()
        self._ar_queue_poll()

    def start(self):
        self.startTime = time.time()

        # create ticket
        f = self._blockingCreateIssue
        log.msg("Submit: %s" % f)
        self._ar_queue_submit(f).addCallback(self._logBlockingCompleted, f)

    def answer(self, member):
        self.talkStart = time.time()
        self.callAnswered = True
        self.queueMember = member

        # map and assign ticket to member
        f = self._blockingAssignIssue
        log.msg("Submit: %s" % f)
        self._ar_queue_submit(f).addCallback(self._logBlockingCompleted, f)

    def hangup(self):
        self.endTime = time.time()
        self.callDuration = self.endTime - self.startTime

        if (self.callAnswered):
            self.talkDuration = self.endTime - self.talkStart

        # update ticket status here
        f = self._blockingUpdateHangupIssue
        log.msg("Submit: %s" % f)
        self._ar_queue_submit(f).addCallback(self._logBlockingCompleted, f)

    def _logBlockingCompleted(self, result, f):
        log.msg("Completed: %s" % f)

    def _mergeIssueWithTemplate(self, tmpl_name):
        changed = False
        if self.templates.has_section(tmpl_name):
            for (k,v) in self.templates.items(tmpl_name):
                setattr(self.issue, k, v % self._issue_placeholders)
                changed = True

        tmpl_custom_fields_name = tmpl_name + "/custom_fields"
        if self.templates.has_section(tmpl_custom_fields_name):
            custom_fields = []
            for (k, v) in self.templates.items(tmpl_custom_fields_name):
                custom_fields.append({
                    'id': k,
                    'value': v % self._issue_placeholders
                    })
            if len(custom_fields):
                self.issue.custom_fields = custom_fields
                changed = True

        return changed

    def _blockingCreateIssue(self):
        self._issue_placeholders['callerid'] = self.callerid
        self._issue_placeholders['uniqueid'] = self.uniqueid
        self._issue_placeholders['startTime'] = self.startTime

        self.issue = Issue()
        self._mergeIssueWithTemplate("IssueCreate")

        self.issue.save()

    def _blockingAssignIssue(self):
        self._issue_placeholders['queueMember'] = self.queueMember
        self._issue_placeholders['callAnswered'] = self.callAnswered

        changed = False
        try:
            userid = int(self.usermap[self.queueMember])
            self._issue_placeholders['assigned_to_id'] = userid
            changed = self._mergeIssueWithTemplate("IssueAssign")
        except KeyError:
            changed = self._mergeIssueWithTemplate("IssueUserNotFound")

        if changed:
            self.issue.save()

    def _blockingUpdateHangupIssue(self):
        self._issue_placeholders['stopTime'] = self.stopTime
        self._issue_placeholders['callDuration'] = self.callDuration
        self._issue_placeholders['talkDuration'] = self.talkDuration
        changed = False
        if self.callAnswered:
            changed = self._mergeIssueWithTemplate("IssueHangupAnswered")
        else:
            changed = self._mergeIssueWithTemplate("IssueHangupNotAnswered")

        if changed:
            self.issue.save()

    def _ar_queue_submit(self, f, *args, **kwds):
        d = Deferred()
        invocation = (f, args, kwds, d)
        self._ar_queue.put(invocation)

        return d

    def _ar_queue_poll(self, result=None):
        d = self._ar_queue.get()
        d.addCallbacks(self._ar_queue_invoke, log.err)

    def _ar_queue_invoke(self, invocation):
        f, args, kwds, d2 = invocation
        d = deferToThread(f, *args, **kwds)
        d.addCallbacks(self._ar_queue_poll, log.err)
        d.chainDeferred(d2)

    def __repr__(self):
        return "CallTracker(\"%s\", \"%s\")" % (self.uniqueid, self.callerid)

class Application(object):
    """Application for the call duration callback mechanism"""

    def __init__(self, config):
        self.trackers = {}
        self.config = config

    def agiRequestReceived(self, agi):
        uniqueid = agi.variables['agi_uniqueid']
        callerid = agi.variables['agi_callerid']
        usermap = dict(self.config.items("UserMap"))
        callTracker = CallTracker(uniqueid, callerid, self.config, usermap)
        callTracker.start()
        self.trackers[uniqueid] = callTracker

        agi.finish()
        return agi

    def amiConnectionMade(self, ami):
        def amiChannelHangup(ami, event):
            uniqueid = event['uniqueid']
            try:
                callTracker = self.trackers.pop(uniqueid)
                callTracker.hangup()
            except KeyError:
                pass

        def amiAgentConnected(ami, event):
            uniqueid = event['uniqueid']
            try:
                callTracker = self.trackers[uniqueid]
                callTracker.answer(event['member'])
            except KeyError:
                pass

        ami.registerEvent('Hangup', amiChannelHangup)
        ami.registerEvent('AgentConnect', amiAgentConnected)

        return ami

# copy&paste from starpy/manager.py, converted to ReconnectingClientFactory
from twisted.internet import protocol, reactor
from starpy import manager
class MyAMIFactory(protocol.ReconnectingClientFactory):
    """A reconnecting factory for AMI protocols"""
    protocol = manager.AMIProtocol
    maxDelay = 300 # 5 minutes

    def __init__(self, username, secret, app):
        self.username = username
        self.secret = secret

        # Another hack to get application up and running after ami login.
        # Normally we'd implement that in the subclass of AMIProtocol...
        self.app = app

    def startedConnecting(self, connector):
        """XXX: Work around messy implementation in starpy"""
        self.loginDefer = Deferred()
        self.loginDefer.addCallback(self.loginComplete)

    def loginComplete(self, ami):
        """Reset retry delay after a successfull login"""
        self.resetDelay()
        self.app.amiConnectionMade(ami)

def makeService(twisted_config):
    from ConfigParser import RawConfigParser
    from starpy import fastagi
    from twisted.application import internet

    # Read configuration
    f = twisted_config['config']
    config = RawConfigParser()
    config.readfp(open(f), f)

    # Set Redmine REST API connection parameters
    Issue.set_site(config.get('Astminer', 'RedmineSite'))
    Issue.set_user(config.get('Astminer', 'RedmineUser'))
    Issue.set_password(config.get('Astminer', 'RedminePassword'))

    app = Application(config)

    # Connect to asterisk manager interface
    f = MyAMIFactory(
            config.get('Astminer', 'ManagerUser'),
            config.get('Astminer', 'ManagerPassword'),
            app)
    reactor.connectTCP(
            config.get('Astminer', 'ManagerHost'),
            int(config.get('Astminer', 'ManagerPort')),
            f)

    # Setup FastAGI listener
    f = fastagi.FastAGIFactory(app.agiRequestReceived)
    service = internet.TCPServer(
            int(config.get('Astminer', 'AgiPort')), f)

    return service


text:
'use strict';

module.exports = function(app) {
	var users = require('../../app/controllers/users.server.controller');
	var elections = require('../../app/controllers/elections.server.controller');

	// Elections Routes
	app.route('/elections')
		.get(elections.list)
		.post(users.requiresLogin, elections.create);

	app.route('/elections/:electionId')
		.get(elections.read)
		.put(users.requiresLogin, elections.hasAuthorization, elections.update)
		.delete(users.requiresLogin, elections.hasAuthorization, elections.delete);

	// Finish by binding the Election middleware
	app.param('electionId', elections.electionByID);
};


text:
module Azure::Network::Mgmt::V2018_07_01
  module Models
    #
    # Application Gateway autoscale configuration.
    #
    class ApplicationGatewayAutoscaleConfiguration

      include MsRestAzure

      # @return [ApplicationGatewayAutoscaleBounds] Autoscale bounds
      attr_accessor :bounds

      #
      # Mapper for ApplicationGatewayAutoscaleConfiguration class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ApplicationGatewayAutoscaleConfiguration',
          type: {
            name: 'Composite',
            class_name: 'ApplicationGatewayAutoscaleConfiguration',
            model_properties: {
              bounds: {
                client_side_validation: true,
                required: true,
                serialized_name: 'bounds',
                type: {
                  name: 'Composite',
                  class_name: 'ApplicationGatewayAutoscaleBounds'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
package boofcv.alg.filter.kernel.impl;

import boofcv.alg.filter.kernel.KernelMath;
import boofcv.alg.filter.kernel.SteerableCoefficients;
import boofcv.alg.filter.kernel.SteerableKernel;
import boofcv.struct.convolve.Kernel2D;
import boofcv.struct.convolve.Kernel2D_F32;

/**
 *

 * Implementation of {@link SteerableKernel} for floating point kernels.
 *

 *
 * @author Peter Abeles
 */
public class SteerableKernel_F32 implements SteerableKernel<Kernel2D_F32> {

	// stores the output kernel
	private Kernel2D_F32 output;

	// definition of steerable function
	private SteerableCoefficients coef;
	private Kernel2D basis[];

	@Override
	public void setBasis( SteerableCoefficients coef ,
						  Kernel2D... basis )
	{
		this.coef = coef;
		this.basis = basis;

		int width = basis[0].width;
		output = new Kernel2D_F32(width);
	}

	@Override
	public Kernel2D_F32 compute( double angle ) {
		// set the output to zero
		KernelMath.fill(output,0);

		int N = output.width*output.width;

		for( int i = 0; i < basis.length; i++ ) {
			double c = coef.compute(angle,i);

			Kernel2D_F32 k = (Kernel2D_F32)basis[i];

			for( int j = 0; j < N; j++ ) {
				output.data[j] += (k.data[j])*c;
			}
		}

		return output;
	}

	@Override
	public int getBasisSize() {
		return basis.length;
	}

	@Override
	public Kernel2D_F32 getBasis( int index ) {
		return (Kernel2D_F32)basis[index];
	}
}


text:
/**
 * React Native App
 * https://github.com/ztplz/CNode-react-native
 * email: mysticzt@gmail.com
 */

import React, { Component } from 'react';
import {
  View,
  Text,
  Image,
  FlatList,
  Keyboard,
  Platform,
  TextInput,
  RefreshControl,
  TouchableHighlight,
  TouchableOpacity,
  StyleSheet
} from 'react-native';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import MessageRow from '../../components/MessageRow';
import MessageReplyTextInput from '../../components/MessageReplyTextInput';
import * as actions from '../../actions/havereadMessageActions';
import LoadingPage from '../../components/LoadingPage';
import { DeviceHeight, DeviceWidth, pixel } from '../../utils/deviceSize';
import NetErrorPage from '../../components/NetErrorPage';
import {
  NIGHT_HEADER_COLOR,
  NIGHT_BACKGROUND_COLOR,
  NIGHT_REFRESH_COLOR
} from '../../constants/themecolor';

class HavereadMessage extends Component {
  static navigationOptions = ({ navigation, screenProps}) => ({
    title: '已读消息',
    headerTintColor: '#ffffff',
    headerStyle: {
      backgroundColor: screenProps.isNightMode? NIGHT_HEADER_COLOR : screenProps.themeColor
    },
  });

  constructor(props) {
    super(props);
    this.listeners = null;
    this.state = {
      keyboardHeight: 0,
      isKeyboardOpened: false,
      text: null,
    };
    this.updateKeyboardSpace = this.updateKeyboardSpace.bind(this);
    this.resetKeyboardSpace = this.resetKeyboardSpace.bind(this);
  }

  componentDidMount() {
    this.props.actions.getHavereadMessageData({isLoading: true, isloaded: false, accesstoken: this.props.accesstoken, error: '', timeout: 10000});
    const updateListener = Platform.OS === 'android' ? 'keyboardDidShow' : 'keyboardWillShow';
    const resetListener = Platform.OS === 'android' ? 'keyboardDidHide' : 'keyboardWillHide';
    this.listeners = [
      Keyboard.addListener(updateListener, this.updateKeyboardSpace),
      Keyboard.addListener(resetListener, this.resetKeyboardSpace)
    ];
  }

  componentWillUnmount() {
    this.listeners.forEach(listener => listener.remove());
  }

  updateKeyboardSpace(event) {
    if (!event.endCoordinates) {
      return;
    }

    const keyboardSpaceHeight = DeviceHeight - event.endCoordinates.screenY;
    this.setState({
      keyboardHeight: keyboardSpaceHeight,
      isKeyboardOpened: true
    });

  }

  resetKeyboardSpace(event) {
    this.setState({
      keyboardHeight: 0,
      isKeyboardOpened: false
    });
  }

  refreshHavereadMessage() {
    this.props.actions.refreshHavereadMessageData({isRefreshing: true, accesstoken: this.props.accesstoken, error: '', timeout: 10000})
  }

  sendReply() {
    this.props.actions.havereadMessageReply({timeout: 10000, topic_id: this.props.replyTopicId, params: { reply_id: this.props.replyId, accesstoken: this.props.accesstoken, content: '@' + this.props.replyName + '  ' + this.props.replyText}});
    this.props.actions.replyTextInputShow({isReply: false, replyName: '', text: '', replyId: '', replyTopicId: ''});
    Keyboard.dismiss();
  }

  renderHeader() {
    if(this.props.data.length === 0) {
      return (
        <View style={styles.flatlistHeader}>
          <Text style={styles.flatlistHeaderText}>列表为空</Text>
        </View>
      )
    }

    return null;
  }

  render() {
    const { screenProps, isLoading, isLoaded, isRefreshing, isReply, replyName, replyId, replyTopicId, replyText, accesstoken, error, data, actions, navigation } = this.props;

    if(isLoading) {
      return (
        <LoadingPage
          screenProps={screenProps}
          title='正在加载已读消息...'
        />
      )
    }

    if(!isLoading && isLoaded) {
      return (
        <View style={[styles.container, { backgroundColor: screenProps.isNightMode? NIGHT_BACKGROUND_COLOR : null }]}>
          <FlatList
            data={data}
            renderItem={({item}) => <MessageRow replyTextInputShow={actions.replyTextInputShow} item={item} navigation={navigation} currentReplyName={replyName} currentText={replyText} />}
            ListHeaderComponent={() => this.renderHeader() }
            ItemSeparatorComponent={() => <View style={{paddingLeft: 8, paddingRight: 8, height: pixel, backgroundColor: '#85757a'}}></View>}
            // onRefresh={() => this.refreshHavereadMessage() }
            // refreshing={isRefreshing}
            refreshControl={
              <RefreshControl
                refreshing={isRefreshing}
                onRefresh={() => this.refreshHavereadMessage()}
                tintColor={screenProps.isNightMode? NIGHT_REFRESH_COLOR : null }
              />
            }
            keyExtractor={(item, index) => 'has_read_messages' + item.id + index }
          />
          {
            this.state.isKeyboardOpened?
              <View style={{marginBottom: this.state.keyboardHeight, flexDirection: 'row', alignItems: 'center', borderWidth: pixel, paddingTop: 5, paddingBottom: 5}}>
                <MessageReplyTextInput   style={{width: DeviceWidth - 61, borderWidth: 1, borderColor: '#79757e', borderRadius: 5, marginLeft: 8, marginRight: 8, paddingLeft: 10}} placeholder={' 回复 ' + replyName + ':'}    fontSize={17} autoCapitalize='none' value={replyText} onChangeText={(text) => actions.havereadMessageTextChange({text})} />
                  <TouchableOpacity
                    onPress={() => this.sendReply()}
                  >
                    <View style={{backgroundColor: '#72aad9', height: 30, width: 37, alignItems: 'center', justifyContent: 'center', borderRadius: 5, marginRight: 8}}>
                      <Text>发送</Text>
                    </View>
                  </TouchableOpacity>
              </View>
              :
              null
          }
          { isReply? <TextInput  onBlur={() => this.props.actions.replyTextInputShow({isReply: false, replyName: this.props.replyName, text: replyText, replyId: replyId, replyTopicId: replyTopicId})} autoFocus={isReply} caretHidden={true} style={styles.textinputStyle} /> : null}
        </View>
      )
    }

    if(error) {
      return (
        <NetErrorPage
          error={error}
          handler={() => actions.getHavereadMessageData({isLoading: true, isLoaded: false, accesstoken: accesstoken, error: '', timeout: 10000})}
        />
      )
    }

    return null;

  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  textinputStyle: {
    // height: 40
  },
  flatlistHeader: {
    height: 45,
    alignItems: 'center',
    justifyContent: 'center'
  },
  flatlistHeaderText: {
    fontSize: 20
  }
});

const mapStateToProps = state => {
  const stateOfHavereadMessage  = state.HavereadMessageState.toJS();
  return {
    isLoading: stateOfHavereadMessage.isLoading,
    isLoaded: stateOfHavereadMessage.isLoaded,
    isRefreshing: stateOfHavereadMessage.isRefreshing,
    isReply: stateOfHavereadMessage.isReply,
    replyName: stateOfHavereadMessage.replyName,
    replyId: stateOfHavereadMessage.replyId,
    replyTopicId: stateOfHavereadMessage.replyTopicId,
    replyText: stateOfHavereadMessage.replyText,
    error: stateOfHavereadMessage.error,
    data: stateOfHavereadMessage.data,
    accesstoken: state.GlobalState.get('accesstoken')
  }
}

const mapDispatchToProps = dispatch => {
  return {
    actions: bindActionCreators(actions, dispatch)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(HavereadMessage);


text:
package com.intellij.openapi.editor.impl;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.util.DocumentUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.util.Objects;

public class CustomFoldRegionImpl extends FoldRegionImpl implements CustomFoldRegion {
  private final CustomFoldRegionRenderer myRenderer;

  private int myWidthInPixels;
  private int myHeightInPixels;
  private GutterIconRenderer myGutterIconRenderer;

  CustomFoldRegionImpl(@NotNull EditorImpl editor,
                       int startOffset,
                       int endOffset,
                       @NotNull CustomFoldRegionRenderer renderer) {
    super(editor, startOffset, endOffset, "", null, true);
    myRenderer = renderer;
    doUpdate();
  }

  @Override
  void alignToValidBoundaries() {
    Document document = getDocument();
    int startOffset = intervalStart();
    int endOffset = intervalEnd();
    if (startOffset == DocumentUtil.getLineStartOffset(startOffset, document) &&
        endOffset == DocumentUtil.getLineEndOffset(endOffset, document)) {
      myEditor.getFoldingModel().myAffectedCustomRegions.add(this);
    }
    else {
      invalidate("Line alignment broken");
    }
  }

  @Override
  public @NotNull CustomFoldRegionRenderer getRenderer() {
    return myRenderer;
  }

  @Override
  public int getWidthInPixels() {
    return myWidthInPixels;
  }

  @Override
  public int getHeightInPixels() {
    return myHeightInPixels;
  }

  @Override
  public @Nullable GutterIconRenderer getGutterIconRenderer() {
    return myGutterIconRenderer;
  }

  @Override
  public void update() {
    ApplicationManager.getApplication().assertIsDispatchThread();
    if (myEditor.isDisposed() || !isValid()) return;
    if (myEditor.myDocumentChangeInProgress) {
      throw new IllegalStateException("Custom fold region shouldn't be updated during document change");
    }
    int oldWidth = myWidthInPixels;
    int oldHeight = myHeightInPixels;
    GutterIconRenderer oldIconRenderer = myGutterIconRenderer;
    doUpdate();
    int changeFlags = 0;
    if (oldWidth != myWidthInPixels) changeFlags |= InlayModel.ChangeFlags.WIDTH_CHANGED;
    if (oldHeight != myHeightInPixels) changeFlags |= InlayModel.ChangeFlags.HEIGHT_CHANGED;
    if (!Objects.equals(oldIconRenderer, myGutterIconRenderer)) changeFlags |= InlayModel.ChangeFlags.GUTTER_ICON_PROVIDER_CHANGED;
    if (changeFlags != 0) {
      myEditor.getFoldingModel().notifyListenersOnPropertiesChange(this, changeFlags);
    }
    else {
      repaint();
    }
  }

  @Override
  public void repaint() {
    if (isValid() && !myEditor.isDisposed()) {
      if (myEditor.getFoldingModel().isInBatchFoldingOperation()) {
        myEditor.getFoldingModel().myRepaintRequested = true;
      }
      else {
        JComponent component = myEditor.getContentComponent();
        if (component.isShowing()) {
          Point location = getLocation();
          if (location != null) {
            component.repaint(0, location.y, component.getWidth(), myHeightInPixels);
          }
        }
      }
    }
  }

  private void doUpdate() {
    myWidthInPixels = Math.max(0, myRenderer.calcWidthInPixels(this));
    myHeightInPixels = Math.max(myEditor.getLineHeight(), myRenderer.calcHeightInPixels(this));
    myGutterIconRenderer = myRenderer.calcGutterIconRenderer(this);
  }

  @Override
  public Point getLocation() {
    int startOffset = getStartOffset();
    FoldRegion visibleRegion = myEditor.getFoldingModel().getCollapsedRegionAtOffset(startOffset);
    return visibleRegion == this ? new Point(myEditor.getContentComponent().getInsets().left,
                                             myEditor.visualLineToY(myEditor.offsetToVisualLine(startOffset)))
                                 : null;
  }

  @Override
  public String toString() {
    return super.toString() + ", renderer: " + myRenderer + ", size: " + myWidthInPixels + "x" + myHeightInPixels;
  }
}


text:
	window[ window.webextension_library_name ].detect = ( function () {

		var detector_counter = 0;

		function detect ( rq ) {

			// init

				var root_element = rq.root || rq.root_element || document;
				var target_element = rq.target_element || document;
				var callback = rq.callback;
				var method = rq.method || "normal";
				var selector = rq.selector || "*";
				var detector_id = detector_counter;
				var attributes = rq.attributes || false;

			// increase the counter

				detector_counter += 1;

			if ( method === "normal" ) {

				root_element = root_element || document;

				var element_arr = root_element.querySelectorAll( selector );

				for ( var i = 0; i < element_arr.length; i++ ) {

					if ( element_arr[ i ].dataset[ "detected_" + detector_id ] !== "1" ) {

						element_arr[ i ].dataset[ "detected_" + detector_id ] = "1";
						callback( element_arr[ i ] );

					};

				};

				var observer = new MutationObserver( function ( records ) {

					var element_arr = root_element.querySelectorAll( selector );

					if ( element_arr ) {

						for ( var i = 0; i < element_arr.length; i++ ) {

							if ( element_arr[ i ].dataset[ "detected_" + detector_id ] !== "1" ) {

								element_arr[ i ].dataset[ "detected_" + detector_id ] = "1";
								callback( element_arr[ i ] );

							};

						};

					};

				});

				observer.observe( root_element, { childList: true, subtree: true } );

				return { observer: observer };

			} else if ( method === "once" ) {

				return new Promise( function ( resolve ) {

					var element = root_element.querySelector( selector );

					if ( element ) {

						resolve( element );

					} else {

						var observer = new MutationObserver( function () {

							var element = root_element.querySelector( selector );

							if ( element ) {

								resolve( element );
								observer.disconnect( root_element );

							};

						})

						observer.observe( root_element, { childList: true, subtree: true, attributes } );

					};

				});

			} else if ( method === "wait_for" ) {

				return new Promise( function ( resolve ) {

					var resolved = false;
					var element = $( selector, root_element ).get( 0 );

					if ( element ) {

						resolve( element );

					} else {

						var observer = new MutationObserver( function () {

							if ( resolved === false ) {

								element = $( selector, root_element ).get( 0 );

								if ( element ) {

									resolve( element );
									observer.disconnect( root_element );
									resolved = true;

								};

							};

						});

						observer.observe( root_element, {

							childList: true,
							subtree: true,

						});

					};

				});

			} else if ( method === "detect_attribute_change" ) {

				var observer = new MutationObserver( function ( records ) {

					callback( target_element, records );

				});

				observer.observe( target_element, { attributes: true } );

			} else if ( method === "detect_changes" ) {

				var observer = new MutationObserver( function ( records ) {

					callback( target_element, records );

				});

				observer.observe( target_element, {

					attributes: true,
					childList: true,
					subtree: true,

				});

			} else if ( method === "detect_new_element" ) {

				var observer = new MutationObserver( function ( records ) {

					callback( target_element, records );

				});

				observer.observe( target_element, {

					attributes: true,
					childList: true,
					subtree: true,

				});

			};

		};

		return detect;

	} () );


text:
package com.yahoo.sketches.theta;

/**
 * See Update Return State
 *
 * @author Lee Rhodes
 */
public enum UpdateReturnState {

  /**
   * Indicates a normal sketch update response and the action that was taken by the sketch.
   */
  InsertedCountIncremented, //all UpdateSketches

  /**
   * Indicates a normal sketch update response and the action that was taken by the sketch.
   */
  InsertedCountNotIncremented, //used by enhancedHashInsert for Alpha

  /**
   * Indicates a normal sketch update response and the action that was taken by the sketch.
   */
  RejectedDuplicate, //all UpdateSketches hashUpdate(), enhancedHashInsert

  /**
   * Indicates a normal sketch update response and the action that was taken by the sketch.
   */
  RejectedNullOrEmpty, //UpdateSketch.update(arr[])

  /**
   * Indicates a normal sketch update response and the action that was taken by the sketch.
   */
  RejectedOverTheta; //all UpdateSketches.hashUpdate()
}


text:
package org.spongepowered.common.data.manipulator.immutable.item;

import com.google.common.collect.ImmutableList;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.immutable.item.ImmutableLoreData;
import org.spongepowered.api.data.manipulator.mutable.item.LoreData;
import org.spongepowered.api.data.value.immutable.ImmutableListValue;
import org.spongepowered.api.text.Text;
import org.spongepowered.common.data.manipulator.immutable.common.AbstractImmutableListData;
import org.spongepowered.common.data.manipulator.mutable.item.SpongeLoreData;
import org.spongepowered.common.text.SpongeTexts;

import java.util.List;

public class ImmutableSpongeLoreData extends AbstractImmutableListData<Text, ImmutableLoreData, LoreData> implements ImmutableLoreData {

    public ImmutableSpongeLoreData() {
        this(ImmutableList.of(Text.of()));
    }

    public ImmutableSpongeLoreData(List<Text> lore) {
        super(ImmutableLoreData.class, lore, Keys.ITEM_LORE, SpongeLoreData.class);
    }

    @Override
    public DataContainer toContainer() {
        return super.toContainer().set(Keys.ITEM_LORE.getQuery(), SpongeTexts.asJson(this.getValue()));
    }
}


text:
+++

title = "Número 336"

date = "1989-02-01"

numero = "336"

artistas = ["Eurythmics", "Pet Shop Boys", "Virus", "Rod Stewart", "UB40", "Morrisey", "The Smiths", "Los Enanitos Verdes", "David Lee Roth", "Los Redonditos de Ricota", "Patricio Rey y sus Redonditos de Ricota", "Prince", "Alberto Cedrola", "New Order", "Roy Orbison", "Depeche Mode", "Los Pericos", "Rod Stewart", "Keith Richards", "Manuel Wirtz", "Tom Jones", "Gene Simmons", "Paul Stanley", "Rick Astley", "Los Twist", "Robert Cray Band", "Robert Cray"]
Colaboradores=["Daniel Osvaldo Ripoll", "Juan Manuel Cibeira", "Eduardo Fortunato", "Marta Ferro", "Rodrigo Fresán", "María José Gayoso"]

peliculas = ["Woodstock de Michael Wadleigh"]

discos = ["Technique/New Order", "Mysterie Girl/Roy Orbison", "101/Depeche Mode", "En El Fondo de Mi Mente/Christopher Cross", "Introspectivo/Pet Shop Boys", "...Y Justicia Para Todos/Metallica"]

espacios = ["The Marquee (Londres)", "Prix D´Ami (CABA)"]

poster1 = "Eurythmics"

+++

**Póster**:  Eurythmics.

**Nota de tapa**: Pet Shop Boys.

**Reportajes**: Keith Richards. Manuel Wirtz. Stevie Winwood. Rick Astley. Los Twist.

**Entrevistas**: Los Pericos. Tom Jones.

**Notas sobre**:

- Show de Rod Stewart.

- Robert Cray Band.

**Secciones**:

- Data: Virus, Rod Stewart, UB40, Morrisey, The Smiths, Los Enanitos Verdes, David Lee Roth, Los Redonditos de Ricota, Prince, Alberto Cedrola, New Order, Roy Orbison, Depeche Mode, The Marquee.

- Video: Woodstock de Michael Wadleigh.

- En Primera Persona: Gene Simmons y Paul Stanley.

- El Cazador Oculto por Rodrigo Fresán.

- Charts. Cartelera. Discos. Correo.


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/system/phonehub/multidevice_feature_opt_in_view.h"

#include <memory>
#include <string>

#include "ash/components/multidevice/logging/logging.h"
#include "ash/components/phonehub/multidevice_feature_access_manager.h"
#include "ash/components/phonehub/util/histogram_util.h"
#include "ash/constants/ash_features.h"
#include "ash/public/cpp/new_window_delegate.h"
#include "ash/strings/grit/ash_strings.h"
#include "ash/style/ash_color_provider.h"
#include "ash/system/phonehub/phone_hub_metrics.h"
#include "ash/system/phonehub/phone_hub_view_ids.h"
#include "ui/base/metadata/metadata_impl_macros.h"

namespace ash {

using ash::phonehub::util::LogPermissionOnboardingPromoAction;
using ash::phonehub::util::LogPermissionOnboardingPromoShown;
using ash::phonehub::util::PermissionsOnboardingScreenEvent;
using ash::phonehub::util::PermissionsOnboardingSetUpMode;
using multidevice_setup::mojom::Feature;

namespace {

// URL of the multidevice settings page with the URL parameter that will
// start up the opt-in-flow.
// TODO: Update this URL once the new access setup dialog has been updated
constexpr char kMultideviceSettingsUrl[] =
    "chrome://os-settings/multidevice/"
    "features?showPhonePermissionSetupDialog&mode=%d";

PermissionsOnboardingSetUpMode GetPermissionSetupMode(
    phonehub::MultideviceFeatureAccessManager*
        multidevice_feature_access_manager) {
  bool can_request_notification_access =
      multidevice_feature_access_manager->GetNotificationAccessStatus() ==
      phonehub::MultideviceFeatureAccessManager::AccessStatus::
          kAvailableButNotGranted;
  bool can_request_apps_acess =
      features::IsEcheSWAEnabled() &&
      multidevice_feature_access_manager->IsAccessRequestAllowed(
          Feature::kEche) &&
      multidevice_feature_access_manager->GetAppsAccessStatus() ==
          phonehub::MultideviceFeatureAccessManager::AccessStatus::
              kAvailableButNotGranted;
  bool can_request_camera_roll_access =
      features::IsPhoneHubCameraRollEnabled() &&
      multidevice_feature_access_manager->IsAccessRequestAllowed(
          Feature::kPhoneHubCameraRoll) &&
      multidevice_feature_access_manager->GetCameraRollAccessStatus() ==
          phonehub::MultideviceFeatureAccessManager::AccessStatus::
              kAvailableButNotGranted;

  PA_LOG(INFO) << "MultideviceFeatureOptInView can_request_notification_access:"
               << can_request_notification_access
               << ", can_request_apps_acess:" << can_request_apps_acess
               << ", can_request_camera_roll_access:"
               << can_request_camera_roll_access;
  if (can_request_notification_access && can_request_camera_roll_access &&
      can_request_apps_acess) {
    return PermissionsOnboardingSetUpMode::kAllPermissions;
  } else if (can_request_notification_access && can_request_apps_acess &&
             !can_request_camera_roll_access) {
    return PermissionsOnboardingSetUpMode::kNotificationAndMessagingApps;
  } else if (can_request_apps_acess && can_request_camera_roll_access &&
             !can_request_notification_access) {
    return PermissionsOnboardingSetUpMode::kMessagingAppsAndCameraRoll;
  } else if (can_request_notification_access &&
             can_request_camera_roll_access && !can_request_apps_acess) {
    return PermissionsOnboardingSetUpMode::kNotificationAndCameraRoll;
  } else if (!can_request_notification_access &&
             !can_request_camera_roll_access && can_request_apps_acess) {
    return PermissionsOnboardingSetUpMode::kMessagingApps;
  } else if (!can_request_notification_access && !can_request_apps_acess &&
             can_request_camera_roll_access) {
    return PermissionsOnboardingSetUpMode::kCameraRoll;
  } else if (!can_request_camera_roll_access && !can_request_apps_acess &&
             can_request_notification_access) {
    return PermissionsOnboardingSetUpMode::kNotification;
  }

  return PermissionsOnboardingSetUpMode::kNone;
}

int GetDescriptionStringId(phonehub::MultideviceFeatureAccessManager*
                               multidevice_feature_access_manager) {
  PermissionsOnboardingSetUpMode permission_setup_mode =
      GetPermissionSetupMode(multidevice_feature_access_manager);
  switch (permission_setup_mode) {
    case PermissionsOnboardingSetUpMode::kCameraRoll:
      return IDS_ASH_PHONE_HUB_CAMERA_ROLL_OPT_IN_DESCRIPTION;
    case PermissionsOnboardingSetUpMode::kMessagingApps:
      return IDS_ASH_PHONE_HUB_APPS_OPT_IN_DESCRIPTION;
    case PermissionsOnboardingSetUpMode::kNotificationAndCameraRoll:
      return IDS_ASH_PHONE_HUB_NOTIFICATION_AND_CAMERA_ROLL_OPT_IN_DESCRIPTION;
    case PermissionsOnboardingSetUpMode::kNotification:
      return IDS_ASH_PHONE_HUB_NOTIFICATION_OPT_IN_DESCRIPTION;
    case PermissionsOnboardingSetUpMode::kNotificationAndMessagingApps:
      return IDS_ASH_PHONE_HUB_NOTIFICATION_AND_APPS_OPT_IN_DESCRIPTION;
    case PermissionsOnboardingSetUpMode::kMessagingAppsAndCameraRoll:
      return IDS_ASH_PHONE_HUB_CAMERA_ROLL_AND_APPS_OPT_IN_DESCRIPTION;
    case PermissionsOnboardingSetUpMode::kAllPermissions:
      return IDS_ASH_PHONE_HUB_ALL_FEATURES_OPT_IN_DESCRIPTION;
    case PermissionsOnboardingSetUpMode::kNone:
    default:
      // Just return the default strings since the MultideviceFeatureOptInView
      // will be invisible.
      return IDS_ASH_PHONE_HUB_NOTIFICATION_OPT_IN_DESCRIPTION;
  }
}

std::string GetMultiDeviceSettingUrl(
    PermissionsOnboardingSetUpMode permission_setup_mode) {
  return base::StringPrintf(kMultideviceSettingsUrl,
                            static_cast<int>(permission_setup_mode));
}

}  // namespace

MultideviceFeatureOptInView::MultideviceFeatureOptInView(
    phonehub::MultideviceFeatureAccessManager*
        multidevice_feature_access_manager)
    : SubFeatureOptInView(
          PhoneHubViewID::kMultideviceFeatureOptInView,
          GetDescriptionStringId(multidevice_feature_access_manager),
          IDS_ASH_PHONE_HUB_NOTIFICATION_OPT_IN_SET_UP_BUTTON),
      multidevice_feature_access_manager_(multidevice_feature_access_manager) {
  DCHECK(multidevice_feature_access_manager_);
  setup_mode_ = GetPermissionSetupMode(multidevice_feature_access_manager_);
  access_manager_observation_.Observe(multidevice_feature_access_manager_);
  // Checks and updates its visibility upon creation.
  UpdateVisibility(/*was_visible=*/false);
}

MultideviceFeatureOptInView::~MultideviceFeatureOptInView() = default;

void MultideviceFeatureOptInView::SetUpButtonPressed() {
  // Opens the set up dialog in settings to start the opt in flow.
  LogPermissionOnboardingPromoAction(
      PermissionsOnboardingScreenEvent::kSetUpOrDone);
  // This intentionally uses GetInstance() to open an OS Settings page in ash.
  std::string url = GetMultiDeviceSettingUrl(setup_mode_);
  PA_LOG(INFO) << "MultideviceFeatureOptInView SetUpButtonPressed target url:"
               << url;
  NewWindowDelegate::GetInstance()->OpenUrl(
      GURL(url), NewWindowDelegate::OpenUrlFrom::kUserInteraction,
      NewWindowDelegate::Disposition::kNewForegroundTab);
}

void MultideviceFeatureOptInView::DismissButtonPressed() {
  // Dismiss this view if user chose to opt out and update the bubble size.
  LogPermissionOnboardingPromoAction(
      PermissionsOnboardingScreenEvent::kDismissOrCancel);
  SetVisible(false);
  multidevice_feature_access_manager_->DismissSetupRequiredUi();
}

void MultideviceFeatureOptInView::OnNotificationAccessChanged() {
  UpdateVisibility(/*was_visible=*/GetVisible());
}

void MultideviceFeatureOptInView::OnCameraRollAccessChanged() {
  UpdateVisibility(/*was_visible=*/GetVisible());
}

void MultideviceFeatureOptInView::UpdateVisibility(bool was_visible) {
  DCHECK(multidevice_feature_access_manager_);
  // Refresh the permission status if changed
  phonehub::util::PermissionsOnboardingSetUpMode current_mode =
      GetPermissionSetupMode(multidevice_feature_access_manager_);
  if (current_mode != setup_mode_) {
    setup_mode_ = current_mode;
    RefreshDescription(
        GetDescriptionStringId(multidevice_feature_access_manager_));
  }
  SetVisible(setup_mode_ != PermissionsOnboardingSetUpMode::kNone &&
             !multidevice_feature_access_manager_
                  ->HasMultideviceFeatureSetupUiBeenDismissed());
  if (!was_visible && GetVisible()) {
    LogPermissionOnboardingPromoShown(setup_mode_);
  }
  PreferredSizeChanged();
}

BEGIN_METADATA(MultideviceFeatureOptInView, views::View)
END_METADATA

}  // namespace ash


text:
<?php

namespace Channel;

/**
 *
 */
#class MeterToSensor extends InternalCalc {
class MeterToSensor extends Channel {

    /**
     * Accept only childs with meter attribute set
     */
    public function addChild( $channel ) {
        $childs = $this->getChilds();
        if (empty($childs)) {
            $new  = new \ORM\Channel($channel);
            if ($new->getType() == 0) {
                // Is an alias, get real channel
                $guid = $new->getChannel();
                $new = new \ORM\Tree;
                $new->filterByGuid($guid)->findOne();
            }

            if ($new->getMeter() == 0) {
                throw new \Exception('"SensorToMeter" accept only a meter channel as child!');
            }

        }
        // Add child or throw exception about only 1 child...
        return parent::addChild($channel);
    }

    /**
     *
     */
    public function read( $request ) {

        $this->before_read($request);

        // Fetch additional row BEFORE start timestamp
        $request['start'] = $this->start - self::$secondsPerPeriod[$this->period[1]];

        $buffer = $this->getChild(1)->read($request)->rewind();
        $last1 = $buffer->current();
        $buffer->next();
        $last2 = $buffer->current();
        $key = $buffer->key();
        $buffer->next();

        $result = new \Buffer;

        while ($row = $buffer->current()) {
            $fact = 3600 / ($row['timestamp'] - $last2['timestamp']);

            // Smooth a bit by calculate average of this and last consumption
            $row['data'] = ($last1['consumption'] + $last2['consumption'] + $row['consumption']) / 3 * $fact;
            $row['min']  = $row['min'] * $fact;
            $row['max']  = $row['max'] * $fact;

            // Remember row before adjust consumption
            $last1 = $last2;
            $last2 = $row;

            // Set timestamp to last timestamp, which is now in $last1
            $row['timestamp'] = $last1['timestamp'];
            $row['datetime']  = $last1['datetime'];
            $row['consumption'] = 0;
            $result->write($row, $key);

            $key = $buffer->key();
            $buffer->next();
        }

        return $this->after_read($result);
    }
}


text:
package es.us.master.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@FacesValidator("emailValidator")
public class EmailValidator implements Validator {

    private final static String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    private final static Pattern EMAIL_COMPILED_PATTERN = Pattern.compile(EMAIL_PATTERN);

    /**
     * Validate method.
     */
    public void validate(FacesContext fc, UIComponent c, Object o) throws ValidatorException {
        // No value is not ok
        if (o == null || "".equals((String)o)) {
            FacesMessage msg = new FacesMessage("No email value!", "Email Validation Error");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);
        }

        // The email matcher
        Matcher matcher = EMAIL_COMPILED_PATTERN.matcher((String)o);

        if (!matcher.matches()) {   // Email doesn't match
            FacesMessage msg = new FacesMessage("Invalid email value!", "Email Validation Error");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);
        }

    }
}


text:
function write_neuralynx_nts(filename, nts);

% WRITE_NEURALYNX_NTS writes spike timestamps to a NTS file
%
% Use as
%   write_neuralynx_nts(filename, nts)
%
% See also READ_NEURALYNX_NTS

% Copyright (C) 2007, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: write_neuralynx_nts.m 945 2010-04-21 17:41:20Z roboos $

if ~isa(nts.TimeStamp, 'uint64')
  error('timestamps should be uint64');
end

fid  = fopen(filename, 'wb', 'ieee-le');

% construct the header
buf  = [];
buf  = [buf sprintf('######## Neuralynx Data File Header\r\n')];
buf  = [buf sprintf('## File Name: %s\r\n', filename)];
buf  = [buf sprintf('## Time Opened: (m/d/y): %s  At Time: %s\r\n', datestr(clock, 'mm/dd/yy'), datestr(clock, 'HH:MM:SS'))];
f = fieldnames(nts.hdr);
for i=1:length(f)
  v = getfield(nts.hdr, f{i});
  switch class(v)
    case 'char'
      buf = [buf sprintf('-%s\t%s\r\n', f{i}, v)];
    case 'double'
      buf = [buf sprintf('-%s\t%g\r\n', f{i}, v)];
    otherwise
      error('unknown class in writing header');
  end
end

% pad the rest of the header with zeros and write it to file
buf((end+1):16384) = 0;
fwrite(fid, buf);

% The format of a clustered electrode record is
%   int64 TimeStamp

fwrite(fid, nts.TimeStamp, 'uint64');

% close the file
fclose(fid);


text:
`bower install angular-user-management --save`

* Load the dependencies in to your app.

* Load the modules you want to use in your HTML.
```html
<script src="bower_components/angular-user-management/dist/registration/registration.js"></script>
<script src="bower_components/angular-user-management/dist/registration/templates.js"></script>
```

* Inject the modules as a dependency of your main app module.
```javascript
angular.module('app', [
    'user-management.password',
    'user-management.profile',
    'user-management.registration',
    'user-management.verification'
]);
```

These settings are extended with defaults defined in the services so you can provide values to override with here.

It's planned to deprecate this method of configuring settings, moving towards a factory of settings.

# i18n

All strings are marked as translatable using [angular-gettext](https://github.com/rubenv/angular-gettext) syntax.

# Tests

- `grunt test`

When working on tests, make sure the dist is up-to-date:
- `grunt dist`
- `grunt karma:dev` will watch dist and test files and run again when they change (helpful)


text:
using UnityEngine;
using System.Collections;

public interface IPipeableEffect {

	void PipelineInitialize(GameObject caster, GameObject target);
	IEnumerator PipelineTrigger();
	Stats.StatList Pipe (Stats.StatList statList);

}


text:
<?php

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

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

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

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

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

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

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

    <?= $form->field($model, 'text')->textarea(['rows' => 6]) ?>

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

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

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

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

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


text:
package ciscoasa

import "fmt"

// ListAccessOutRules returns a collection of access control element objects.
func (s *accessService) ListAccessOutRules(iface string) (*ExtendedACEObjectCollection, error) {
	result := &ExtendedACEObjectCollection{}
	page := 0

	for {
		offset := page * s.pageLimit
		u := fmt.Sprintf("/api/access/out/%s/rules?limit=%d&offset=%d", iface, s.pageLimit, offset)

		req, err := s.newRequest("GET", u, nil)
		if err != nil {
			return nil, err
		}

		e := &ExtendedACEObjectCollection{}
		_, err = s.do(req, e)
		if err != nil {
			return nil, err
		}

		result.RangeInfo = e.RangeInfo
		result.Items = append(result.Items, e.Items...)
		result.Kind = e.Kind
		result.SelfLink = e.SelfLink

		if e.RangeInfo.Offset+e.RangeInfo.Limit == e.RangeInfo.Total {
			break
		}
		page++
	}

	return result, nil
}

// CreateAccessOutRule creates an access control element.
func (s *accessService) CreateAccessOutRule(iface, src, srcService, dst, dstService, timeRange string, active, permit bool) (string, error) {
	u := fmt.Sprintf("/api/access/out/%s/rules", iface)

	e := &ExtendedACEObject{
		Active: active,
		Permit: permit,
		Kind:   "object#ExtendedACE",
	}

	var err error
	if e.SrcAddress, err = s.Objects.objectFromAddress(src); err != nil {
		return "", err
	}
	if e.SrcService, err = s.Objects.objectFromService(srcService); err != nil {
		return "", err
	}
	if e.DstAddress, err = s.Objects.objectFromAddress(dst); err != nil {
		return "", err
	}
	if e.DstService, err = s.Objects.objectFromService(dstService); err != nil {
		return "", err
	}

	if timeRange != "" {
		t := &TimeRange{
			ObjectID: timeRange,
			Kind:     "objectRef#TimeRange",
		}
		e.TimeRange = t
	}

	req, err := s.newRequest("POST", u, e)
	if err != nil {
		return "", err
	}

	resp, err := s.do(req, nil)
	if err != nil {
		return "", err
	}

	return idFromResponse(resp)
}

// GetAccessOutRule retrieves an access control element.
func (s *accessService) GetAccessOutRule(iface string, ruleID string) (*ExtendedACEObject, error) {
	u := fmt.Sprintf("/api/access/out/%s/rules/%s", iface, ruleID)

	req, err := s.newRequest("GET", u, nil)
	if err != nil {
		return nil, err
	}

	e := &ExtendedACEObject{}
	_, err = s.do(req, e)

	return e, err
}

// UpdateAccessOutRule updates an access control element.
func (s *accessService) UpdateAccessOutRule(iface, ruleID, src, srcService, dst, dstService, timeRange string, active, permit bool) (string, error) {
	u := fmt.Sprintf("/api/access/out/%s/rules/%s", iface, ruleID)

	e := &ExtendedACEObject{
		Active: active,
		Permit: permit,
		Kind:   "object#ExtendedACE",
	}

	var err error
	if e.SrcAddress, err = s.Objects.objectFromAddress(src); err != nil {
		return "", err
	}
	if e.SrcService, err = s.Objects.objectFromService(srcService); err != nil {
		return "", err
	}
	if e.DstAddress, err = s.Objects.objectFromAddress(dst); err != nil {
		return "", err
	}
	if e.DstService, err = s.Objects.objectFromService(dstService); err != nil {
		return "", err
	}

	if timeRange != "" {
		t := &TimeRange{
			ObjectID: timeRange,
			Kind:     "objectRef#TimeRange",
		}
		e.TimeRange = t
	}

	req, err := s.newRequest("PUT", u, e)
	if err != nil {
		return "", err
	}

	resp, err := s.do(req, nil)
	if err != nil {
		return "", err
	}

	return idFromResponse(resp)
}

// DeleteAccessOutRule deletes an access control element.
func (s *accessService) DeleteAccessOutRule(iface string, ruleID string) error {
	u := fmt.Sprintf("/api/access/out/%s/rules/%s", iface, ruleID)

	req, err := s.newRequest("DELETE", u, nil)
	if err != nil {
		return err
	}

	_, err = s.do(req, nil)

	return err
}


text:
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;

namespace Apress.Recipes.WebApi.SelfHost
{
    public class HtmlController : ApiController
    {
        public HttpResponseMessage Get(string filename)
        {
            var response = new HttpResponseMessage
            {
                Content =
                    new StreamContent(File.Open(AppDomain.CurrentDomain.BaseDirectory + "/files/" + filename,
                        FileMode.Open))
            };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
            return response;
        }
    }
}


text:
"""
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

import pytest

from byceps.services.authorization import service

def test_assign_permission_to_role(admin_app_with_db, permission, role):
    role_permission_ids_before = get_permission_ids_for_role(role)
    assert permission.id not in role_permission_ids_before

    service.assign_permission_to_role(permission.id, role.id)

    role_permission_ids_after = get_permission_ids_for_role(role)
    assert permission.id in role_permission_ids_after

def test_deassign_permission_from_role(admin_app_with_db, permission, role):
    service.assign_permission_to_role(permission.id, role.id)

    role_permission_ids_before = get_permission_ids_for_role(role)
    assert permission.id in role_permission_ids_before

    service.deassign_permission_from_role(permission.id, role.id)

    role_permission_ids_after = get_permission_ids_for_role(role)
    assert permission.id not in role_permission_ids_after

@pytest.fixture
def permission():
    return service.create_permission('board_topic_hide', 'Hide board topics')

@pytest.fixture
def role():
    return service.create_role('board_moderator', 'Board Moderator')

def get_permission_ids_for_role(role):
    return {p.id for p in role.permissions}


text:
var marker, map = L.map('map', {
    center: [40.44695, -345.23437],
    layers: L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png'),
    zoom: 2,
});

/* easy-button plugin */
L.easyButton('fa-map-marker', function(btn, map){

    btn.button.style.display = 'none';

    if(marker!==undefined)
        map.removeLayer(marker);

     map.findAccuratePosition({
        maxWait: 10000,
        desiredAccuracy: 20
    });

}).addTo(map);

function onAccuratePositionFound (e) {

    document.getElementById('progress').style.display = "none";
    document.getElementsByClassName('easy-button-button')[0].style.display = 'block';

    map.setView(e.latlng, 16);
    marker = L.marker(e.latlng).addTo(map);
}

function onAccuratePositionProgress (e) {
    document.getElementById('progress').style.display = "block";
}

map.on('accuratepositionprogress', onAccuratePositionProgress);
map.on('accuratepositionfound', onAccuratePositionFound);


text:
<ion-view id="mainGame" view-title="Leader Board" ng-controller="gameController as hc">
    <ion-content>

Top Players

                Player
                Score

                {{item.name | initials }}
                {{item.gameplay.counter}}

        </ion-content>
    </ion-view>


text:
package com.jf.djplayer.sortable;

import com.jf.djplayer.bean.Song;

import java.io.File;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by JF on 2016/1/29.
 * 根据文件名来进行排序
 */
public class SortByFileName implements SongListSortable,Comparator<Song> {

    File lhsFile;
    File rhsFile;

    @Override
    public void sort(List<Song> songInfoList) {
        Collections.sort(songInfoList,this);
    }

    @Override
    public int compare(Song lhs, Song rhs) {
        lhsFile = new File(lhs.getFileAbsolutePath());
        rhsFile = new File(rhs.getFileAbsolutePath());
        return rhsFile.getName().compareTo(lhsFile.getName());
    }
}


text:
package catan.common.chat;

import catan.common.crypto.Username;
import catan.common.event.EventType;

/**
 * Created by Greg on 8/13/2014.
 * Enum sent along inside of a ChatEvent to indicate it's purpose.
 * Functions as a routing aid, and allows the server to rebroadcast it the right direction.
 */
public enum ChatEventType implements EventType {

    Broadcast(null),  //Message should be rebroadcast to all clients connected to the server.
    Lobby(null), //Message should be rebroadcast to only the clients in a local Group.
    Private(Username.class); //Message should be forwarded to only the destination client.

    private final Class type;

    ChatEventType(Class type) {
        this.type = type;
    }

    @Override
    public Class getType() {
        return type;
    }

}


text:
from runner.koan import *

class AboutLambdas(Koan):
    def test_lambdas_can_be_assigned_to_variables_and_called_explicitly(self):
        add_one = lambda n: n + 1
        self.assertEqual(__, add_one(10))

    # ------------------------------------------------------------------

    def make_order(self, order):
        return lambda qty: str(qty) + " " + order + "s"

    def test_accessing_lambda_via_assignment(self):
        sausages = self.make_order('sausage')
        eggs = self.make_order('egg')

        self.assertEqual(__, sausages(3))
        self.assertEqual(__, eggs(2))

    def test_accessing_lambda_without_assignment(self):
        self.assertEqual(__, self.make_order('spam')(39823))


text:
WP-Custom-Template
==================

## How to use

Templates can be defined in 'setting' page. You can load templates in posts using shortcode, `[template <template_name>]`

It is useful when you put same contents over many posts.


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

    Copyright 2015 Red Hat, Inc. and/or its affiliates
    and other contributors as indicated by the @author tags.

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

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

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

-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <include
    layout="@layout/layout_toolbar"/>

  <FrameLayout
    android:foreground="?android:windowContentOverlay"
    android:padding="16dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
      android:orientation="vertical"
      android:layout_gravity="center"
      android:layout_width="match_parent"
      android:layout_height="wrap_content">

      <TextView
        android:text="@string/label_authorization_title"
        android:textColor="@color/text_primary"
        android:textSize="@dimen/text_primary"
        android:gravity="center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

      <Space
        android:layout_width="match_parent"
        android:layout_height="8dp"/>

      <TextView
        android:text="@string/label_authorization_support"
        android:textColor="@color/text_secondary"
        android:textSize="@dimen/text_secondary"
        android:gravity="center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

      <Space
        android:layout_width="match_parent"
        android:layout_height="8dp"/>

      <TextView
        android:text="@string/label_authorization_description"
        android:textColor="@color/text_secondary"
        android:textSize="@dimen/text_secondary"
        android:gravity="center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

      <Space
        android:layout_width="match_parent"
        android:layout_height="16dp"/>

      <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
          android:id="@+id/edit_host"
          android:hint="@string/hint_host"
          android:inputType="textUri"
          android:singleLine="true"
          android:layout_weight="4"
          android:layout_width="0dp"
          android:layout_height="wrap_content"/>

        <Space
          android:layout_width="16dp"
          android:layout_height="match_parent"/>

        <EditText
          android:id="@+id/edit_port"
          android:hint="@string/hint_port"
          android:inputType="number"
          android:singleLine="true"
          android:layout_weight="1"
          android:layout_width="0dp"
          android:layout_height="wrap_content"/>

      </LinearLayout>

      <Space
        android:layout_width="match_parent"
        android:layout_height="16dp"/>

      <Button
        android:id="@+id/button_authorize"
        android:text="@string/button_authorize"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    </LinearLayout>

  </FrameLayout>

</LinearLayout>


text:
module ValidationScenarios
  module With
    ##
    #
    # Declares a scenario context. All Model validations for this scenario will be activated within
    # the block.
    #
    #   Controller:
    #     class ReviewController < ApplicationController
    #       def update
    #         with_scenario :reviewer do
    #           @event.save!
    #         end
    #       end
    #
    # Any validates_xxx defined in the Event for the scenario :reviewer will be activated, all other
    # validations are still working.
    #
    def with_scenario(name, &blk)
      Thread.current[:validation_scenarios_with_scenario] = Scenario.new(name)
      yield
    ensure
      Thread.current[:validation_scenarios_with_scenario] = nil
    end
  end
end


text:
/**
 * A store that synchronizes a layers array of an OpenLayers.Map with a
 * layer store holding GeoExt.data.model.layer.Base instances.
 *
 * @class GeoExt.data.store.Layers
 */
Ext.define('GeoExt.data.store.Layers', {
    extend: 'Ext.data.Store',
    alternateClassName: ['GeoExt.data.LayerStore'],
    requires: [
        'GeoExt.data.model.Layer'
    ],

    mixins: [
        'GeoExt.mixin.SymbolCheck'
    ],

    // <debug>
    symbols: [
        'ol.Collection#clear',
        'ol.Collection#forEach',
        'ol.Collection#getArray',
        'ol.Collection#insertAt',
        'ol.Collection#on',
        'ol.Collection#push',
        'ol.Collection#remove',
        'ol.layer.Layer',
        'ol.layer.Layer#get',
        'ol.layer.Layer#on',
        'ol.layer.Layer#set',
        'ol.Map',
        'ol.Map#getLayers'
    ],
    // </debug>

    model: 'GeoExt.data.model.Layer',

    config: {
        /**
         * A configured map or a configuration object for the map constructor.
         *
         * @cfg {ol.Map/Object} map
         */
        map: null
    },

    /**
     * Constructs an instance of the layer store.
     *
     * @param {Object} config The configuration object.
     */
    constructor: function(config) {
        var me = this;

        me.callParent([config]);

        if (config.map) {
            this.bindMap(config.map);
        }
    },

    /**
     * Bind this store to a map instance; once bound, the store is synchronized
     * with the map and vice-versa.
     *
     * @param {ol.Map} map The map instance.
     */
    bindMap: function(map) {
        var me = this;

        if (!me.map) {
            me.map = map;
        }

        if (map instanceof ol.Map) {
            var mapLayers = map.getLayers();
            mapLayers.forEach(function(layer) {
                me.loadRawData(layer, true);
            });

            mapLayers.forEach(function(layer) {
                layer.on('propertychange', me.onChangeLayer, me);
            });
            mapLayers.on('add', me.onAddLayer, me);
            mapLayers.on('remove', me.onRemoveLayer, me);
        }

        me.on({
            'load': me.onLoad,
            'clear': me.onClear,
            'add': me.onAdd,
            'remove': me.onRemove,
            'update': me.onStoreUpdate,
            'scope': me
        });

        me.data.on({
            'replace': me.onReplace,
            'scope': me
        });
        me.fireEvent('bind', me, map);
    },

    /**
     * Unbind this store from the map it is currently bound.
     */
    unbindMap: function() {
        var me = this;

        if (me.map && me.map.getLayers()) {
            me.map.getLayers().un('add', me.onAddLayer, me);
            me.map.getLayers().un('remove', me.onRemoveLayer, me);
        }
        me.un('load', me.onLoad, me);
        me.un('clear', me.onClear, me);
        me.un('add', me.onAdd, me);
        me.un('remove', me.onRemove, me);
        me.un('update', me.onStoreUpdate, me);

        me.data.un('replace', me.onReplace, me);

        me.map = null;
    },

    /**
     * Handler for layer changes. When layer order changes, this moves the
     * appropriate record within the store.
     *
     * @param {ol.ObjectEvent} evt The emitted `ol.Object` event.
     * @private
     */
    onChangeLayer: function(evt) {
        var layer = evt.target;
        var recordIndex = this.findBy(function(rec) {
            return rec.getOlLayer() === layer;
        });
        if (recordIndex > -1) {
            var record = this.getAt(recordIndex);
            if (evt.key === 'title') {
                record.set('title', layer.get('title'));
            } else {
                this.fireEvent('update', this, record, Ext.data.Record.EDIT);
            }
        }
    },

    /**
     * Handler for a layer collection's `add` event.
     *
     * @param {ol.CollectionEvent} evt The emitted `ol.Collection` event.
     * @private
     */
    onAddLayer: function(evt) {
        var layer = evt.element;
        var index = this.map.getLayers().getArray().indexOf(layer);
        var me = this;
        layer.on('propertychange', me.onChangeLayer, me);
        if (!me._adding) {
            me._adding = true;
            var result = me.proxy.reader.read(layer);
            me.insert(index, result.records);
            delete me._adding;
        }
    },

    /**
     * Handler for layer collection's `remove` event.
     *
     * @param {ol.CollectionEvent} evt The emitted `ol.Collection` event.
     * @private
     */
    onRemoveLayer: function(evt) {
        var me = this;
        if (!me._removing) {
            var layer = evt.element;
            var rec = me.getByLayer(layer);
            if (rec) {
                me._removing = true;
                layer.un('propertychange', me.onChangeLayer, me);
                me.remove(rec);
                delete me._removing;
            }
        }
    },

    /**
     * Handler for a store's `load` event.
     *
     * @param {Ext.data.Store} store The store that loaded.
     * @param {Ext.data.Model[]} records An array of loades model instances.
     * @param {Boolean} successful Whether loading was successful or not.
     * @private
     */
    onLoad: function(store, records, successful) {
        var me = this;
        if (successful) {
            if (!Ext.isArray(records)) {
                records = [records];
            }
            if (!me._addRecords) {
                me._removing = true;
                me.map.getLayers().forEach(function(layer) {
                    layer.un('propertychange', me.onChangeLayer, me);
                });
                me.map.getLayers().clear();
                delete me._removing;
            }
            var len = records.length;
            if (len > 0) {
                var layers = new Array(len);
                for (var i = 0; i < len; i++) {
                    layers[i] = records[i].getOlLayer();
                    layers[i].on('propertychange', me.onChangeLayer, me);
                }
                me._adding = true;
                me.map.getLayers().extend(layers);
                delete me._adding;
            }
        }
        delete me._addRecords;
    },

    /**
     * Handler for a store's `clear` event.
     *
     * @private
     */
    onClear: function() {
        var me = this;
        me._removing = true;
        me.map.getLayers().forEach(function(layer) {
            layer.un('propertychange', me.onChangeLayer, me);
        });
        me.map.getLayers().clear();
        delete me._removing;
    },

    /**
     * Handler for a store's `add` event.
     *
     * @param {Ext.data.Store} store The store to which a model instance was
     *     added.
     * @param {Ext.data.Model[]} records The array of model instances that were
     *     added.
     * @param {Number} index The index at which the model instances were added.
     * @private
     */
    onAdd: function(store, records, index) {
        var me = this;
        if (!me._adding) {
            me._adding = true;
            var layer;
            for (var i = 0, ii = records.length; i < ii; ++i) {
                layer = records[i].getOlLayer();
                layer.on('propertychange', me.onChangeLayer, me);
                if (index === 0) {
                    me.map.getLayers().push(layer);
                } else {
                    me.map.getLayers().insertAt(index, layer);
                }
            }
            delete me._adding;
        }
    },

    /**
     * Handler for a store's `remove` event.
     *
     * @param {Ext.data.Store} store The store from which a model instances
     *     were removed.
     * @param {Ext.data.Model[]} records The array of model instances that were
     *     removed.
     * @private
     */
    onRemove: function(store, records) {
        var me = this;
        var record;
        var layer;
        var found;
        var i;
        var ii;

        if (!me._removing) {
            var compareFunc = function(el) {
                if (el === layer) {
                    found = true;
                }
            };
            for (i = 0, ii = records.length; i < ii; ++i) {
                record = records[i];
                layer = record.getOlLayer();
                found = false;
                layer.un('propertychange', me.onChangeLayer, me);
                me.map.getLayers().forEach(compareFunc);
                if (found) {
                    me._removing = true;
                    me.removeMapLayer(record);
                    delete me._removing;
                }
            }
        }
    },

    /**
     * Handler for a store's `update` event.
     *
     * @param {Ext.data.Store} store The store which was updated.
     * @param {Ext.data.Model} record The model instance that was updated.
     * @param {String} operation The operation, either Ext.data.Model.EDIT,
     *     Ext.data.Model.REJECT or Ext.data.Model.COMMIT.
     * @private
     */
    onStoreUpdate: function(store, record, operation) {
        if (operation === Ext.data.Record.EDIT) {
            if (record.modified && record.modified.title) {
                var layer = record.getOlLayer();
                var title = record.get('title');
                if (title !== layer.get('title')) {
                    layer.set('title', title);
                }
            }
        }
    },

    /**
     * Removes a record's layer from the bound map.
     *
     * @param {Ext.data.Model} record The removed model instance.
     * @private
     */
    removeMapLayer: function(record) {
        this.map.getLayers().remove(record.getOlLayer());
    },

    /**
     * Handler for a store's data collections' `replace` event.
     *
     * @param {String} key The associated key.
     * @param {Ext.data.Model} oldRecord In this case, a record that has
     *     been replaced.
     * @private
     */
    onReplace: function(key, oldRecord) {
        this.removeMapLayer(oldRecord);
    },

    /**
     * Get the record for the specified layer.
     *
     * @param {ol.layer.Base} layer The layer to get a model instance for.
     * @return {Ext.data.Model} The corresponding model instance or undefined if
     *     not found.
     */
    getByLayer: function(layer) {
        var index = this.findBy(function(r) {
            return r.getOlLayer() === layer;
        });
        if (index > -1) {
            return this.getAt(index);
        }
    },

    /**
     * Unbinds listeners by calling #unbind prior to being destroyed.
     *
     * @private
     */
    destroy: function() {
        this.unbind();
        this.callParent();
    },

    /**
     * Overload loadRecords to set a flag if `addRecords` is `true` in the load
     * options. ExtJS does not pass the load options to "load" callbacks, so
     * this is how we provide that information to `onLoad`.
     *
     * @param {Ext.data.Model[]} records The array of records to load.
     * @param {Object} options The loading options.
     * @param {Boolean} [options.addRecords=false] Pass `true` to add these
     *     records to the existing records, `false` to remove the Store's
     *     existing records first.
     * @private
     */
    loadRecords: function(records, options) {
        if (options && options.addRecords) {
            this._addRecords = true;
        }
        this.callParent(arguments);
    },

    /**
     * @inheritdoc
     *
     * The event firing behaviour of Ext.4.1 is reestablished here. See also:
     * [This discussion on the Sencha forum](http://www.sencha.com/forum/
     * showthread.php?253596-beforeload-is-not-fired-by-loadRawData).
     */
    loadRawData: function(data, append) {
        var me = this;
        var result = me.proxy.reader.read(data);
        var records = result.records;

        if (result.success) {
            me.totalCount = result.total;
            me.loadRecords(records, append ? me.addRecordsOptions : undefined);
            me.fireEvent('load', me, records, true);
        }
    }

});


text:
require 'sass'
require 'sassc'
require 'zendesk_apps_support/sass_functions'

module ZendeskAppsSupport
  class StylesheetCompiler
    def initialize(source, app_id, url_prefix)
      @source = source
      @app_id = app_id
      @url_prefix = url_prefix
    end

    def compile(sassc: false)
      options = {
        syntax: :scss, app_asset_url_builder: self
      }
      if sassc
        compiler_class = SassC
        options[:style] = :compressed
      else
        compiler_class = Sass
      end
      compiler_class::Engine.new(wrapped_source.dup, options).render
    end

    def app_asset_url(name)
      "#{@url_prefix}#{name}"
    end

    private

    def wrapped_source
      ".app-#{@app_id} {#{@source}}"
    end
  end
end


text:
package svk.sglubos.calculationlib.data;

public class VariableType {
	protected String name;
	protected String symbol;
	protected String unit;

	public VariableType(String name, String symbol, String unit) {
		this.name = name;
		this.symbol = symbol;
                this.unit = unit;
	}

	public String getUnit() {
		return unit;
	}

	public String getName() {
		return name;
	}

	public String getSymbol() {
		return symbol;
	}
}


text:
./bin/create-topic.sh enrichments
./bin/create-topic.sh indexing