text:
<?php

namespace common\modules\lead\models\query;

use common\modules\lead\models\LeadDialer;
use common\modules\lead\models\LeadDialerType;
use yii\db\ActiveQuery;

/**
 * This is the ActiveQuery class for LeadDialer.
 *
 * @see LeadDialer
 */
class LeadDialerQuery extends ActiveQuery {

	/**
	 * @inheritdoc
	 * @return LeadDialer[]|array
	 */
	public function all($db = null) {
		return parent::all($db);
	}

	/**
	 * @inheritdoc
	 * @return LeadDialer|array|null
	 */
	public function one($db = null) {
		return parent::one($db);
	}

	public function toCall(): self {
		$this->activeType();
		$this->toCallsStatus();
		$this->toCallOrder();
		return $this;
	}

	public function toCallOrder(): self {
		$this->orderBy([
			LeadDialer::tableName() . '.priority' => SORT_DESC,
			LeadDialer::tableName() . '.last_at' => SORT_ASC,
		]);
		return $this;
	}

	public function toCallsStatus(): self {
		$this->andWhere([LeadDialer::tableName() . '.status' => LeadDialer::toCallStatuses()]);
		return $this;
	}

	public function activeType(): self {
		$this->joinWith('type');
		$this->andWhere([LeadDialerType::tableName() . '.status' => LeadDialerType::STATUS_ACTIVE]);
		return $this;
	}

	public function userType(int $userId): self {
		$this->joinWith('type');
		$this->andWhere([LeadDialerType::tableName() . '.user_id' => $userId]);
		return $this;
	}

	public function type(int $type): self {
		$this->andWhere([LeadDialer::tableName() . '.type_id' => $type]);
		return $this;
	}
}


text:
// This rollup config performs the minimum transforms needed to build
// a package that imports React from esm module source:
// - Handles imports to commonjs modules, since react is only distributed
//   as commonjs
// - Replaces process.env.NODE_ENV

import {nodeResolve} from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import replace from '@rollup/plugin-replace';
export default {
  input: ['js/tests/tests.js'],
  output: {
    dir: './tests',
    format: 'esm',
    sourcemap: true,
  },
  plugins: [
    nodeResolve({
      extensions: ['.js'],
    }),
    replace({
      'process.env.NODE_ENV': JSON.stringify('development'),
    }),
    commonjs(),
  ],
};

redpajama_set_name: RedPajamaGithub


text:
id: bad87fee1348bd9aedb08845
title: Responsively Style Radio Buttons
required:
  - link: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css'
    raw: true
challengeType: 0
videoUrl: ''
localeTitle: ''
---

## Description

 يمكنك استخدام صفوف col-xs-* في Bootstrap على عناصر form أيضًا! بهذه الطريقة ، سيتم توزيع أزرار الراديو الخاصة بنا بشكل متساوٍ عبر الصفحة ، بغض النظر عن مدى اتساع دقة الشاشة. ضع كلا من أزرار الراديو داخل عنصر <div class="row"> . ثم تداخل كل منها داخل عنصر <div class="col-xs-6"> . ملاحظة: كتذكير ، تعد أزرار الاختيار عناصر input من نوع radio .

## Instructions

## Tests

```yml
tests:
  - text: ''
    testString: 'assert($("div.row:has(input[type=\"radio\"])").length > 0, "Nest all of your radio buttons inside one <code>div</code> with the class <code>row</code>.");'
  - text: ''
    testString: 'assert($("div.col-xs-6:has(input[type=\"radio\"])").length > 1, "Nest each of your radio buttons inside its own <code>div</code> with the class <code>col-xs-6</code>.");'
  - text: تأكد من أن كل عنصر من عناصر <code>div</code> لديه علامة إغلاق.
    testString: 'assert(code.match(/<\/div>/g) && code.match(/<div/g) && code.match(/<\/div>/g).length === code.match(/<div/g).length, "Make sure each of your <code>div</code> elements has a closing tag.");'

```

## Challenge Seed

```html
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">
<style>
  h2 {
    font-family: Lobster, Monospace;
  }

  .thick-green-border {
    border-color: green;
    border-width: 10px;
    border-style: solid;
    border-radius: 50%;
  }
</style>

<div class="container-fluid">
  <div class="row">
    <div class="col-xs-8">
      <h2 class="text-primary text-center">CatPhotoApp</h2>
    </div>
    <div class="col-xs-4">
      <a href="#"><img class="img-responsive thick-green-border" src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
    </div>
  </div>
  <img src="https://bit.ly/fcc-running-cats" class="img-responsive" alt="Three kittens running towards the camera.">
  <div class="row">
    <div class="col-xs-4">
      <button class="btn btn-block btn-primary"><i class="fa fa-thumbs-up"></i> Like</button>
    </div>
    <div class="col-xs-4">
      <button class="btn btn-block btn-info"><i class="fa fa-info-circle"></i> Info</button>
    </div>
    <div class="col-xs-4">
      <button class="btn btn-block btn-danger"><i class="fa fa-trash"></i> Delete</button>
    </div>
  </div>
  <p>Things cats <span class="text-danger">love:</span></p>
  <ul>
    <li>cat nip</li>
    <li>laser pointers</li>
    <li>lasagna</li>
  </ul>
  <p>Top 3 things cats hate:</p>
  <ol>
    <li>flea treatment</li>
    <li>thunder</li>
    <li>other cats</li>
  </ol>
  <form action="/submit-cat-photo">
    <label><input type="radio" name="indoor-outdoor"> Indoor</label>
    <label><input type="radio" name="indoor-outdoor"> Outdoor</label>
    <label><input type="checkbox" name="personality"> Loving</label>
    <label><input type="checkbox" name="personality"> Lazy</label>
    <label><input type="checkbox" name="personality"> Crazy</label>
    <input type="text" placeholder="cat photo URL" required>
    <button type="submit">Submit</button>
  </form>
</div>

```

## Solution

```js
// solution required
```


text:
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */

import Page = require('../../../base/Page');
import Response = require('../../../http/response');
import V1 = require('../V1');
import { SerializableClass } from '../../../interfaces';

/**
 * @description Initialize the VoiceList
 *
 * @param version - Version of the resource
 */
declare function VoiceList(version: V1): VoiceListInstance;

interface VoiceListInstance {
  countries?: object;
  numbers?: object;
}

interface VoicePayload extends VoiceResource, Page.TwilioResponsePayload {
}

interface VoiceResource {
  links: string;
  name: string;
  url: string;
}

interface VoiceSolution {
}

declare class VoiceInstance extends SerializableClass {
  /**
   * Initialize the VoiceContext
   *
   * @property name - The name
   * @property url - The url
   * @property links - The links
   *
   * @param version - Version of the resource
   * @param payload - The instance payload
   */
  constructor(version: V1, payload: VoicePayload);

  links: string;
  name: string;
  /**
   * Produce a plain JSON object version of the VoiceInstance for serialization.
   * Removes any circular references in the object.
   */
  toJSON(): any;
  url: string;
}

declare class VoicePage extends Page<V1, VoicePayload, VoiceResource, VoiceInstance> {
  /**
   * Initialize the VoicePage
   *
   * @param version - Version of the resource
   * @param response - Response from the API
   * @param solution - Path solution
   */
  constructor(version: V1, response: Response<string>, solution: VoiceSolution);

  /**
   * Build an instance of VoiceInstance
   *
   * @param payload - Payload response from the API
   */
  getInstance(payload: VoicePayload): VoiceInstance;
}

export { VoiceInstance, VoiceList, VoiceListInstance, VoicePage, VoicePayload, VoiceResource, VoiceSolution }


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* rendering object for HTML
 elements */

#include "nsCOMPtr.h"
#include "nsFrame.h"
#include "nsHTMLParts.h"
#include "nsPresContext.h"
#include "nsLineLayout.h"
#include "nsStyleConsts.h"
#include "nsGkAtoms.h"
#include "nsRenderingContext.h"
#include "nsLayoutUtils.h"

#ifdef ACCESSIBILITY
#include "nsIServiceManager.h"
#include "nsAccessibilityService.h"
#endif

//FOR SELECTION
#include "nsIContent.h"
#include "nsFrameSelection.h"
//END INCLUDES FOR SELECTION

class BRFrame : public nsFrame {
public:
  NS_DECL_FRAMEARENA_HELPERS

  friend nsIFrame* NS_NewBRFrame(nsIPresShell* aPresShell, nsStyleContext* aContext);

  virtual ContentOffsets CalcContentOffsetsFromFramePoint(nsPoint aPoint);

  virtual bool PeekOffsetNoAmount(bool aForward, int32_t* aOffset);
  virtual bool PeekOffsetCharacter(bool aForward, int32_t* aOffset,
                                     bool aRespectClusters = true);
  virtual bool PeekOffsetWord(bool aForward, bool aWordSelectEatSpace, bool aIsKeyboardSelect,
                                int32_t* aOffset, PeekWordState* aState);

  NS_IMETHOD Reflow(nsPresContext* aPresContext,
                    nsHTMLReflowMetrics& aDesiredSize,
                    const nsHTMLReflowState& aReflowState,
                    nsReflowStatus& aStatus);
  virtual void AddInlineMinWidth(nsRenderingContext *aRenderingContext,
                                 InlineMinWidthData *aData);
  virtual void AddInlinePrefWidth(nsRenderingContext *aRenderingContext,
                                  InlinePrefWidthData *aData);
  virtual nscoord GetMinWidth(nsRenderingContext *aRenderingContext);
  virtual nscoord GetPrefWidth(nsRenderingContext *aRenderingContext);
  virtual nsIAtom* GetType() const;
  virtual nscoord GetBaseline() const;

  virtual bool IsFrameOfType(uint32_t aFlags) const
  {
    return nsFrame::IsFrameOfType(aFlags & ~(nsIFrame::eReplaced |
                                             nsIFrame::eLineParticipant));
  }

#ifdef ACCESSIBILITY
  virtual already_AddRefed<Accessible> CreateAccessible();
#endif

protected:
  BRFrame(nsStyleContext* aContext) : nsFrame(aContext) {}
  virtual ~BRFrame();

  nscoord mAscent;
};

nsIFrame*
NS_NewBRFrame(nsIPresShell* aPresShell, nsStyleContext* aContext)
{
  return new (aPresShell) BRFrame(aContext);
}

NS_IMPL_FRAMEARENA_HELPERS(BRFrame)

BRFrame::~BRFrame()
{
}

NS_IMETHODIMP
BRFrame::Reflow(nsPresContext* aPresContext,
                nsHTMLReflowMetrics& aMetrics,
                const nsHTMLReflowState& aReflowState,
                nsReflowStatus& aStatus)
{
  DO_GLOBAL_REFLOW_COUNT("BRFrame");
  DISPLAY_REFLOW(aPresContext, this, aReflowState, aMetrics, aStatus);
  aMetrics.height = 0; // BR frames with height 0 are ignored in quirks
                       // mode by nsLineLayout::VerticalAlignFrames .
                       // However, it's not always 0.  See below.
  aMetrics.width = 0;
  aMetrics.ascent = 0;

  // Only when the BR is operating in a line-layout situation will it
  // behave like a BR.
  nsLineLayout* ll = aReflowState.mLineLayout;
  if (ll) {
    // Note that the compatibility mode check excludes AlmostStandards
    // mode, since this is the inline box model.  See bug 161691.
    if ( ll->LineIsEmpty() ||
         aPresContext->CompatibilityMode() == eCompatibility_FullStandards ) {
      // The line is logically empty; any whitespace is trimmed away.
      //
      // If this frame is going to terminate the line we know
      // that nothing else will go on the line. Therefore, in this
      // case, we provide some height for the BR frame so that it
      // creates some vertical whitespace.  It's necessary to use the
      // line-height rather than the font size because the
      // quirks-mode fix that doesn't apply the block's min
      // line-height makes this necessary to make BR cause a line
      // of the full line-height

      // We also do this in strict mode because BR should act like a
      // normal inline frame.  That line-height is used is important
      // here for cases where the line-height is less than 1.
      nsRefPtr<nsFontMetrics> fm;
      nsLayoutUtils::GetFontMetricsForFrame(this, getter_AddRefs(fm),
        nsLayoutUtils::FontSizeInflationFor(this));
      aReflowState.rendContext->SetFont(fm); // FIXME: maybe not needed?
      if (fm) {
        nscoord logicalHeight = aReflowState.CalcLineHeight();
        aMetrics.height = logicalHeight;
        aMetrics.ascent =
          nsLayoutUtils::GetCenteredFontBaseline(fm, logicalHeight);
      }
      else {
        aMetrics.ascent = aMetrics.height = 0;
      }

      // XXX temporary until I figure out a better solution; see the
      // code in nsLineLayout::VerticalAlignFrames that zaps minY/maxY
      // if the width is zero.
      // XXX This also fixes bug 10036!
      // Warning: nsTextControlFrame::CalculateSizeStandard depends on
      // the following line, see bug 228752.
      aMetrics.width = 1;
    }

    // Return our reflow status
    uint32_t breakType = aReflowState.mStyleDisplay->mBreakType;
    if (NS_STYLE_CLEAR_NONE == breakType) {
      breakType = NS_STYLE_CLEAR_LINE;
    }

    aStatus = NS_INLINE_BREAK | NS_INLINE_BREAK_AFTER |
      NS_INLINE_MAKE_BREAK_TYPE(breakType);
    ll->SetLineEndsInBR(true);
  }
  else {
    aStatus = NS_FRAME_COMPLETE;
  }

  aMetrics.SetOverflowAreasToDesiredBounds();

  mAscent = aMetrics.ascent;

  NS_FRAME_SET_TRUNCATION(aStatus, aReflowState, aMetrics);
  return NS_OK;
}

/* virtual */ void
BRFrame::AddInlineMinWidth(nsRenderingContext *aRenderingContext,
                           nsIFrame::InlineMinWidthData *aData)
{
  aData->ForceBreak(aRenderingContext);
}

/* virtual */ void
BRFrame::AddInlinePrefWidth(nsRenderingContext *aRenderingContext,
                            nsIFrame::InlinePrefWidthData *aData)
{
  aData->ForceBreak(aRenderingContext);
}

/* virtual */ nscoord
BRFrame::GetMinWidth(nsRenderingContext *aRenderingContext)
{
  nscoord result = 0;
  DISPLAY_MIN_WIDTH(this, result);
  return result;
}

/* virtual */ nscoord
BRFrame::GetPrefWidth(nsRenderingContext *aRenderingContext)
{
  nscoord result = 0;
  DISPLAY_PREF_WIDTH(this, result);
  return result;
}

nsIAtom*
BRFrame::GetType() const
{
  return nsGkAtoms::brFrame;
}

nscoord
BRFrame::GetBaseline() const
{
  return mAscent;
}

nsIFrame::ContentOffsets BRFrame::CalcContentOffsetsFromFramePoint(nsPoint aPoint)
{
  ContentOffsets offsets;
  offsets.content = mContent->GetParent();
  if (offsets.content) {
    offsets.offset = offsets.content->IndexOf(mContent);
    offsets.secondaryOffset = offsets.offset;
    offsets.associateWithNext = true;
  }
  return offsets;
}

bool
BRFrame::PeekOffsetNoAmount(bool aForward, int32_t* aOffset)
{
  NS_ASSERTION (aOffset && *aOffset <= 1, "aOffset out of range");
  int32_t startOffset = *aOffset;
  // If we hit the end of a BR going backwards, go to its beginning and stay there.
  if (!aForward && startOffset != 0) {
    *aOffset = 0;
    return true;
  }
  // Otherwise, stop if we hit the beginning, continue (forward) if we hit the end.
  return (startOffset == 0);
}

bool
BRFrame::PeekOffsetCharacter(bool aForward, int32_t* aOffset,
                             bool aRespectClusters)
{
  NS_ASSERTION (aOffset && *aOffset <= 1, "aOffset out of range");
  // Keep going. The actual line jumping will stop us.
  return false;
}

bool
BRFrame::PeekOffsetWord(bool aForward, bool aWordSelectEatSpace, bool aIsKeyboardSelect,
                        int32_t* aOffset, PeekWordState* aState)
{
  NS_ASSERTION (aOffset && *aOffset <= 1, "aOffset out of range");
  // Keep going. The actual line jumping will stop us.
  return false;
}

#ifdef ACCESSIBILITY
already_AddRefed<Accessible>
BRFrame::CreateAccessible()
{
  nsAccessibilityService* accService = nsIPresShell::AccService();
  if (!accService) {
    return nullptr;
  }
  nsIContent *parent = mContent->GetParent();
  if (parent &&
      parent->IsRootOfNativeAnonymousSubtree() &&
      parent->GetChildCount() == 1) {
    // This
 is the only node in a text control, therefore it is the hacky
    // "bogus node" used when there is no text in the control
    return nullptr;
  }
  return accService->CreateHTMLBRAccessible(mContent,
                                            PresContext()->PresShell());
}
#endif


text:
- A little recap on our previous meetings
- How to debug in Eclipse
- Debugging problems
- Finish all String problems
- Declaring (static) methods
- Introduction to JUnit


text:
<preference-headers
    xmlns:android="http://schemas.android.com/apk/res/android">

    <header android:icon="@drawable/ic_menu_camera"
            android:title="Intent"
            android:summary="Launches an Intent.">
        <intent android:action="android.intent.action.VIEW"
                android:data="http://www.android.com" />
    </header>

</preference-headers>


text:
/* ========================================================================
 * DOM-based Routing
 * Based on http://goo.gl/EUTi53 by Paul Irish
 *
 * Only fires on body classes that match. If a body class contains a dash,
 * replace the dash with an underscore when adding it to the object below.
 *
 * .noConflict()
 * The routing is enclosed within an anonymous function so that you can
 * always reference jQuery with $, even when in .noConflict() mode.
 *
 * Google CDN, Latest jQuery
 * To use the default WordPress version of jQuery, go to lib/config.php and
 * remove or comment out: add_theme_support('jquery-cdn');
 * ======================================================================== */

(function($) {

// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
var Roots = {
  // All pages
  common: {
    init: function() {
      // JavaScript to be fired on all pages
    }
  },
  // Home page
  home: {
    init: function() {
      // JavaScript to be fired on the home page
    }
  },
  // About us page, note the change from about-us to about_us.
  about_us: {
    init: function() {
      // JavaScript to be fired on the about us page
    }
  }
};

// The routing fires all common scripts, followed by the page specific scripts.
// Add additional events for more control over timing e.g. a finalize event
var UTIL = {
  fire: function(func, funcname, args) {
    var namespace = Roots;
    funcname = (funcname === undefined) ? 'init' : funcname;
    if (func !== '' && namespace[func] && typeof namespace[func][funcname] === 'function') {
      namespace[func][funcname](args);
    }
  },
  loadEvents: function() {
    UTIL.fire('common');

    $.each(document.body.className.replace(/-/g, '_').split(/\s+/),function(i,classnm) {
      UTIL.fire(classnm);
    });
  }
};

$(document).ready(UTIL.loadEvents);

})(jQuery); // Fully reference jQuery after this point.

//********** Scroll Direction Check *************//
var felcsoki=0;
var lecsoki=0;
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel"; //FF doesn't recognize mousewheel as of FF3.x
$(document).bind(mousewheelevt, function(e) {
        var evt = window.event || e; //equalize event object
        evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
        var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta; //check for detail first, because it is used by Opera and FF
        if(delta > 0) {
            //console.log('Felfele');
            if (felcsoki++ >= 2 ) {
              lecsoki=0;

              $('.fixedhead').addClass('show');
              $('body').attr('data-offset','65');

            }

            }
        else
            {
            //console.log('Lefele');
            if (lecsoki++ > 2 ) {
              felcsoki=0;
              $('.fixedhead').addClass('show');
              $('body').attr('data-offset','65');
            }
            }

    if (window.pageYOffset < 65) {
      $('.navbar').removeClass('show');
    }

    }

);

//*********** Smooth scroll *************

jQuery(document).ready(function() {

  $('.is_dark').waypoint(function() {
    $('.navbar').removeClass('redbg');
    $('.navbar').addClass('whitebg');
  }, { offset: 65 });
  $('.is_light').waypoint(function() {
    $('.navbar').removeClass('whitebg');
    $('.navbar').addClass('redbg');
  }, { offset: 65 });
  $('.is_opaque').waypoint(function() {
    $('.navbar').removeClass('redbg');
    $('.navbar').removeClass('whitebg');
  }, { offset: 65 });

  /************* Main header Fixing ***********/
  var htop = $('.navbar').offset().top - parseFloat($('.navbar').css('marginTop').replace(/auto/, 0));
  $(window).scroll(function (event) {
    var y = $(this).scrollTop();
    if (y-3 >= htop) {
      $('.navbar').addClass('fixedhead');
    } else {
      $('.navbar').removeClass('fixedhead');
    }
    //$('body').attr('data-offset' ,  $('.banner').height() );
  });
  /************* End of fixing ***********/

  $('.popup-zoom').magnificPopup({
    type: 'image',
    closeOnContentClick: true,
    closeBtnInside: false,
    fixedContentPos: true,
    mainClass: 'mfp-with-zoom', // class to remove default margin from left and right side
    image: {
      verticalFit: true
    },
    zoom: {
      enabled: true,
      duration: 300 // don't foget to change the duration also in CSS
    }
  });

  $('.popup-3d').magnificPopup({
    disableOn: 480,
    type: 'iframe',
    mainClass: 'mfp-with-zoom',
    removalDelay: 160,
    preloader: false,

    fixedContentPos: true,
    zoom: {
      enabled: true,
      duration: 300 // don't foget to change the duration also in CSS
    }
  });

  $('.home--videoblock').fitVids();

  $('.navbar-nav a').click(function(e) {
    $('.navbar-nav a').blur();
    document.getElementById('nav-toggle').checked = false;
  });

  $(window).resize(function () {
    $('.navbar-nav a').blur();
    document.getElementById('nav-toggle').checked = false;
  });

  $('.home__headcircle a').click(function(e) {
    e.preventDefault();
    $('.footer--contactblock').addClass('inverse');
    $('.js_inverseon').addClass('active');
    $('.js_inverseoff').removeClass('active');
    $('.tablist a:last').tab('show');
    //$('.footer--contactblock #contact_type').attr('value','Forkjøpsrett');
  });

  $('.js_inverseon').click(function(e) {
    e.preventDefault();
    $(this).addClass('active');
    $('.js_inverseoff').removeClass('active');
    $('.footer--contactblock').addClass('inverse');
    //$('.footer--contactblock #contact_type').attr('value','Forkjøpsrett');
  });

  $('.js_inverseoff').click(function(e) {
    e.preventDefault();
    $(this).addClass('active');
    $('.js_inverseon').removeClass('active');
    $('.footer--contactblock').removeClass('inverse');
    //$('.footer--contactblock #contact_type').attr('value','Interesse');
  });

});


text:
package co.aikar.commands;

import co.aikar.timings.lib.MCTiming;

import java.lang.reflect.Method;

public class BukkitRegisteredCommand extends RegisteredCommand<BukkitCommandExecutionContext> {
    private final MCTiming timing;
    BukkitRegisteredCommand(BaseCommand scope, String command, Method method, String prefSubCommand) {
        super(scope, command, method, prefSubCommand);
        BukkitCommandManager manager = (BukkitCommandManager) scope.manager;
        this.timing = manager.getTimings().of("Command: " + this.command, manager.commandTiming);
    }

    @Override
    public void preCommand() {
        timing.startTiming();
        super.preCommand();
    }

    @Override
    public void postCommand() {
        super.postCommand();
        timing.stopTiming();
    }
}


text:
local lgi = require("lgi");
require "string"
local pango = lgi.Pango
local fm = lgi.PangoCairo.FontMap.get_default()
local pango_context = lgi.Pango.FontMap.create_context(fm)

if not SILE.shapers then SILE.shapers = { } end
SILE.shapers.pango = {}

SILE.settings.declare({
  name = "shaper.spacepattern",
  type = "string",
  default = "%s+",
  help = "The Lua pattern used for splitting words on spaces"
})

function itemize(s, pal)
  return pango.itemize(pango_context, s, 0, string.len(s), pal, nil)
end

function _shape(s, item)
  local offset = item.offset
  local length = item.length
  local analysis = item.analysis
  local pgs = pango.GlyphString.new()
  pango.shape(string.sub(s,1+offset), length, analysis, pgs)
  return pgs
end

local palcache = {}
local spacecache = {}
local function getPal(options)
  if options.pal then
    pal = options.pal
    return pal
  end
  local p = std.string.pickle(options)
  if palcache[p] then return palcache[p]
  else
    pal = pango.AttrList.new();
    if options.language then pal:insert(pango.Attribute.language_new(pango.Language.from_string(options.language))) end
    if options.font then pal:insert(pango.Attribute.family_new(options.font)) end
    if options.weight then pal:insert(pango.Attribute.weight_new(tonumber(options.weight))) end
    if options.size then pal:insert(pango.Attribute.size_new(options.size * 1024 * 0.75)) end -- I don't know why 0.75
    if options.style then pal:insert(pango.Attribute.style_new(
      options.style == "italic" and pango.Style.ITALIC or pango.Style.NORMAL)) end
    if options.variant then pal:insert(pango.Attribute.variant_new(
      options.variant == "smallcaps" and pango.Variant.SMALL_CAPS or pango.Variant.NORMAL)) end
  end
  if options.language then
    pango_context:set_language(pango.Language.from_string(options.language))
  end
  palcache[p] = pal
  return pal
end

local function measureSpace( pal )
  local ss = SILE.settings.get("document.spaceskip")
  if ss then return ss end
  if spacecache[pal] then return spacecache[pal] end
  local spaceitem = itemize(" ",pal)[1]
  local g = (_shape(" ",spaceitem).glyphs)[1]
  local spacewidth = g.geometry.width / 1024;
  spacecache[pal] = SILE.length.new({ length = spacewidth * 1.2, shrink = spacewidth/3, stretch = spacewidth /2 }) -- XXX
  return spacecache[pal]
end

local dimcache = {}
function SILE.shapers.pango.measureDim(char)
  local options = SILE.font.loadDefaults({})
  local pal = getPal(options)
  if dimcache[pal] and dimcache[pal][char] then return dimcache[pal][char] end
  if not dimcache[pal] then dimcache[pal] = {} end
  local charitem = itemize(char,pal)[1]
  local g = (_shape(char,charitem).glyphs)[1]
  if char == "x" then
    local font = charitem.analysis.font
    local rect = font:get_glyph_extents(g.glyph)
    dimcache[pal][char] = -rect.y/1024
  else
    dimcache[pal][char] = g.geometry.width / 1024
  end
  return dimcache[pal][char]
end

function SILE.shapers.pango.shape(text, options)
  if not options then options = {} end
  options = SILE.font.loadDefaults(options)

  local pal = getPal(options)
  local nodes = {}
  local gluewidth = measureSpace(pal)
  for token in SU.gtoke(text, SILE.settings.get("shaper.spacepattern")) do
    if (token.separator) then
      table.insert(nodes, SILE.nodefactory.newGlue({ width = gluewidth }))
    else
      local items = itemize(token.string, pal)
      local nnode = {}
      for i in pairs(items) do
        local pgs = _shape(token.string, items[i])
        -- Sum the glyphs in this string
        local text = string.sub(token.string,1+items[i].offset, items[i].length)
        local depth, height = 0,0
        local font = items[i].analysis.font
        local glyphs = {}
        for g in pairs(pgs.glyphs) do
          local rect = font:get_glyph_extents(pgs.glyphs[g].glyph)
          local desc = rect.y + rect.height
          local asc  = -rect.y
          if desc > depth then depth = desc end
          if asc > height then height = asc end
          table.insert(glyphs, pgs.glyphs[g].glyph)
        end
        table.insert(nnode, SILE.nodefactory.newHbox({
          depth = depth / 1024,
          height= height / 1024,
          width = SILE.length.new({ length= pgs:get_width() / 1024 }),
          value = {font = font, text = text, glyphString = pgs, glyphs = glyphs, options = options }
        }))
      end
      table.insert(nodes, SILE.nodefactory.newNnode({
        nodes = nnode,
        text = token.string,
        pal = pal,
        options = options,
        language = options.language
      }))
    end
  end
  return nodes
end

SILE.shaper = SILE.shapers.pango

--
-- local s = "ltr שָׁוְא ltr"
--

-- for i in pairs(items) do
--   local offset = items[i].offset
--   local length = items[i].length
--   local analysis = items[i].analysis
--   local pgs = pango.GlyphString.new()
--   pango.shape(string.sub(s,1+offset), length, analysis, pgs)
--   return pgs
--   cr:move_to(x, 50)
--   cr:show_glyph_string(analysis.font, pgs)
--   x = x + pgs:get_width()/1024
--   print(x)
-- end


text:
FactoryGirl.define do
  factory :template do
    name "MyString"
    content "MyString"
  end
end


text:
/**
 * @class PromiseProcessor
 * @extends AudioWorkletProcessor
 *
 * This processor creates and resolves a promise in its `process` method. When
 * the handler passed to `then()` is called, a counter that is global in the
 * global scope is incremented. There are two copies of this
 * AudioWorkletNode/Processor, so the counter should always be even in the
 * process method of the AudioWorklet processing, since the Promise completion
 * handler are resolved in between render quanta.
 *
 * After a few iterations of the test, one of the worklet posts back the string
 * "ok" to the main thread, and the test is considered a success.
 */
var idx = 0;

class PromiseProcessor extends AudioWorkletProcessor {
  constructor(options) {
    super(options);
  }

  process(inputs, outputs) {
    if (idx % 2 != 0) {
      this.port.postMessage("ko");
      // Don't bother continuing calling process in this case, the test has
      // already failed.
      return false;
    }
    Promise.resolve().then(() => {
      idx++;
      if (idx == 100) {
        this.port.postMessage("ok");
      }
    });
    // Ensure process is called again.
    return true;
  }
}

registerProcessor('promise-processor', PromiseProcessor);


text:
using System;
using NPOI.SS.Formula.Eval;
using System.Globalization;

namespace NPOI.SS.Formula.Functions
{
    public class CHAR : Fixed1ArgFunction
    {
        public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0)
        {
            int arg;
            try
            {
                arg = TextFunction.EvaluateIntArg(arg0, srcRowIndex, srcColumnIndex);
                if (arg < 0 || arg >= 256)
                {
                    throw new EvaluationException(ErrorEval.VALUE_INVALID);
                }

            }
            catch (EvaluationException e)
            {
                return e.GetErrorEval();
            }
            return new StringEval(Convert.ToString((char)arg, CultureInfo.CurrentCulture));
        }
    }
}


text:
//========================================================================
//Copyright 2007-2008 David Yu dyuproject@gmail.com
//------------------------------------------------------------------------
//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.
//========================================================================

package com.dyuproject.util.http;

import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.mortbay.util.StringUtil;
import org.mortbay.util.UrlEncoded;

/**
 * A parameter map where the values of the parameter names are url encoded on toString()
 *
 * @author David Yu
 * @created Sep 11, 2008
 */

public final class UrlEncodedParameterMap extends HashMap<String,String>
{

    private static final long serialVersionUID = 2009100616L;

    private String _url;

    public UrlEncodedParameterMap()
    {

    }

    public UrlEncodedParameterMap(String url)
    {
        _url = url;
    }

    public String getUrl()
    {
        return _url;
    }

    public UrlEncodedParameterMap setUrl(String url)
    {
        _url = url;
        return this;
    }

    public UrlEncodedParameterMap add(String key, String value)
    {
        put(key, value);
        return this;
    }

    public String toString()
    {
        StringBuilder buffer = new StringBuilder().append(getUrl());
        char separator = getUrl().lastIndexOf('?')==-1 ? '?' : '&';
        for(Map.Entry<String,String> entry : entrySet())
        {
            buffer.append(separator)
                .append(entry.getKey())
                .append('=')
                .append(UrlEncoded.encodeString(entry.getValue()));
            separator = '&';
        }
        return buffer.toString();
    }

    public String toStringRFC3986()
    {
        StringBuilder buffer = new StringBuilder().append(getUrl());
        char separator = getUrl().lastIndexOf('?')==-1 ? '?' : '&';
        for(Map.Entry<String,String> entry : entrySet())
        {
            buffer.append(separator)
                .append(entry.getKey())
                .append('=')
                .append(encodeRFC3986(entry.getValue()));
            separator = '&';
        }
        return buffer.toString();
    }

    public byte[] getUrlFormEncodedBytes(String charset) throws UnsupportedEncodingException
    {
        StringBuilder buffer = new StringBuilder();
        for(Map.Entry<String,String> entry : entrySet())
        {
            buffer.append('&')
                .append(entry.getKey())
                .append('=')
                .append(UrlEncoded.encodeString(entry.getValue(), charset));
        }
        return buffer.substring(1).getBytes(charset);
    }

    public byte[] getUrlFormEncodedBytesRFC3986(String charset) throws UnsupportedEncodingException
    {
        StringBuilder buffer = new StringBuilder();
        for(Map.Entry<String,String> entry : entrySet())
        {
            buffer.append('&')
                .append(entry.getKey())
                .append('=')
                .append(encodeRFC3986(entry.getValue(), charset));
        }
        return buffer.substring(1).getBytes(charset);
    }

    public void prettyPrint(PrintStream out)
    {
        for(Map.Entry<String,String> entry : entrySet())
        {
            out.print(entry.getKey());
            out.print(" = ");
            out.println(entry.getValue());
        }
    }

    /**
     * Gets the url encoded value from the given {@code key}.
     */
    public String getEncoded(String key)
    {
        String value = get(key);
        return value==null ? null : encode(value);
    }

    /**
     * Gets the url encoded value from the given {@code key}.
     */
    public String encodedGet(String key)
    {
        return getEncoded(key);
    }

    /**
     * Encodes (url encoding) the {@code value} with the default charset UTF-8.
     */
    public static String encode(String value)
    {
        return encode(value, StringUtil.__UTF8);
    }

    /**
     * Encodes (url encoding) the {@code value} with the specified {@code charset}.
     */
    public static String encode(String value, String charset)
    {
        return UrlEncoded.encodeString(value, charset);
    }

    /**
     * Decodes (url encoding) the {@code value} with the default charset UTF-8.
     */
    public static String decode(String value)
    {
        return UrlEncoded.decodeString(value, 0, value.length(), StringUtil.__UTF8);
    }

    /**
     * Decodes (url encoding) the {@code value} with the specified {@code charset}.
     */
    public static String decode(String value, String charset)
    {
        return UrlEncoded.decodeString(value, 0, value.length(), charset);
    }

    /**
     * Decodes (url encoding) the {@code value} with the specified {@code charset},
     * starting at {@code start} with the length {@code len}.
     */
    public static String decode(String value, int start, int len, String charset)
    {
        return UrlEncoded.decodeString(value, start, len, charset);
    }

    /**
     * Encodes the value using RFC 3986 url encoding - which basically
     * skips {'-', '.', '_', '~'}.
     */
    public static String encodeRFC3986(String value)
    {
        return encodeRFC3986(value, StringUtil.__UTF8);
    }

    /* From UrlEncoded snippet customized to skip {'-', '.', '_', '~'} */
    /**
     * Encodes the value with the given {@code charset} using RFC 3986
     * url encoding - which basically skips {'-', '.', '_', '~'}.
     *
     * @param value string to encode
     * @return encoded string.
     */
    public static String encodeRFC3986(String value, String charset)
    {
        byte[] bytes=null;
        try
        {
            bytes=value.getBytes(charset);
        }
        catch(UnsupportedEncodingException e)
        {
            // Log.warn(LogSupport.EXCEPTION,e);
            bytes=value.getBytes();
        }

        int len=bytes.length;
        byte[] encoded= new byte[bytes.length*3];
        int n=0;
        boolean noEncode=true;

        for (int i=0;i<len;i++)
        {
            byte b = bytes[i];

            if (b==' ')
            {
                noEncode=false;
                //encoded[n++]=(byte)'+';
                encoded[n++]=(byte)'%';
                encoded[n++]=(byte)'2';
                encoded[n++]=(byte)'0';
            }
            else if (b>='a' && b<='z' ||
                     b>='A' && b<='Z' ||
                     b>='0' && b<='9')
            {
                encoded[n++]=b;
            }
            else
            {
                switch(b)
                {
                    case '-':
                    case '.':
                    case '_':
                    case '~':
                        encoded[n++] = b;
                        continue;
                }
                noEncode=false;
                encoded[n++]=(byte)'%';
                byte nibble= (byte) ((b&0xf0)>>4);
                if (nibble>=10)
                    encoded[n++]=(byte)('A'+nibble-10);
                else
                    encoded[n++]=(byte)('0'+nibble);
                nibble= (byte) (b&0xf);
                if (nibble>=10)
                    encoded[n++]=(byte)('A'+nibble-10);
                else
                    encoded[n++]=(byte)('0'+nibble);
            }
        }

        if (noEncode)
            return value;

        try
        {
            return new String(encoded,0,n,charset);
        }
        catch(UnsupportedEncodingException e)
        {
            // Log.warn(LogSupport.EXCEPTION,e);
            return new String(encoded,0,n);
        }
    }

}


text:
lnug.github.io
==============

The London Node User Group Website

How to run
----------
You can serve this with *any* static web server, but we'll use [mongoose](https://code.google.com/p/mongoose/).

1. `git clone git@github.com:lnug/lnug.github.io.git`
2. `cd lnug.github.io`
3. `brew install mongoose`
4. `mongoose .`
5. go to http://localhost:8080


text:
using System;
using BACnet.Types;
using BACnet.Types.Schemas;

namespace BACnet.Ashrae
{
	public  partial class NetworkAddress
	{
		public ushort NetworkNumber { get; private set; }

		public byte[] MacAddress { get; private set; }

		public NetworkAddress(ushort networkNumber, byte[] macAddress)
		{
			this.NetworkNumber = networkNumber;
			this.MacAddress = macAddress;
		}

		public static readonly ISchema Schema = new SequenceSchema(false,
			new FieldSchema("NetworkNumber", 255, Value<ushort>.Schema),
			new FieldSchema("MacAddress", 255, Value<byte[]>.Schema));

		public static NetworkAddress Load(IValueStream stream)
		{
			stream.EnterSequence();
			var networkNumber = Value<ushort>.Load(stream);
			var macAddress = Value<byte[]>.Load(stream);
			stream.LeaveSequence();
			return new NetworkAddress(networkNumber, macAddress);
		}

		public static void Save(IValueSink sink, NetworkAddress value)
		{
			sink.EnterSequence();
			Value<ushort>.Save(sink, value.NetworkNumber);
			Value<byte[]>.Save(sink, value.MacAddress);
			sink.LeaveSequence();
		}
	}
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

//
// PUT NO INCLUDES BEFORE HERE !!!!
//
#include <stdlib.h>
#ifdef _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#endif
#include "azure_c_shared_utility/gballoc.h"

#include <stddef.h>
#include <string.h>
#include <stdint.h>
//
// PUT NO CLIENT LIBRARY INCLUDES BEFORE HERE !!!!
//
#include "azure_c_shared_utility/base64.h"
#include "azure_c_shared_utility/xlogging.h"

#define splitInt(intVal, bytePos)   (char)((intVal >> (bytePos << 3)) & 0xFF)
#define joinChars(a, b, c, d) (uint32_t)((uint32_t)a + ((uint32_t)b << 8) + ((uint32_t)c << 16) + ((uint32_t)d << 24))

static char base64char(unsigned char val)
{
    char result;

    if (val < 26)
    {
        result = 'A' + (char)val;
    }
    else if (val < 52)
    {
        result = 'a' + ((char)val - 26);
    }
    else if (val < 62)
    {
        result = '0' + ((char)val - 52);
    }
    else if (val == 62)
    {
        result = '+';
    }
    else
    {
        result = '/';
    }

    return result;
}

static char base64b16(unsigned char val)
{
    const uint32_t base64b16values[4] = {
        joinChars('A', 'E', 'I', 'M'),
        joinChars('Q', 'U', 'Y', 'c'),
        joinChars('g', 'k', 'o', 's'),
        joinChars('w', '0', '4', '8')
    };
    return splitInt(base64b16values[val >> 2], (val & 0x03));
}

static char base64b8(unsigned char val)
{
    const uint32_t base64b8values = joinChars('A', 'Q', 'g', 'w');
    return splitInt(base64b8values, val);
}

static int base64toValue(char base64character, unsigned char* value)
{
    int result = 0;
    if (('A' <= base64character) && (base64character <= 'Z'))
    {
        *value = base64character - 'A';
    }
    else if (('a' <= base64character) && (base64character <= 'z'))
    {
        *value = ('Z' - 'A') + 1 + (base64character - 'a');
    }
    else if (('0' <= base64character) && (base64character <= '9'))
    {
        *value = ('Z' - 'A') + 1 + ('z' - 'a') + 1 + (base64character - '0');
    }
    else if ('+' == base64character)
    {
        *value = 62;
    }
    else if ('/' == base64character)
    {
        *value = 63;
    }
    else
    {
        *value = 0;
        result = -1;
    }
    return result;
}

static size_t numberOfBase64Characters(const char* encodedString)
{
    size_t length = 0;
    unsigned char junkChar;
    while (base64toValue(encodedString[length],&junkChar) != -1)
    {
        length++;
    }
    return length;
}

/*returns the count of original bytes before being base64 encoded*/
/*notice NO validation of the content of encodedString. Its length is validated to be a multiple of 4.*/
static size_t Base64decode_len(const char *encodedString)
{
    size_t result;
    size_t sourceLength = strlen(encodedString);

    if (sourceLength == 0)
    {
        result = 0;
    }
    else
    {
        result = sourceLength / 4 * 3;
        if (encodedString[sourceLength - 1] == '=')
        {
            if (encodedString[sourceLength - 2] == '=')
            {
                result --;
            }
            result--;
        }
    }
    return result;
}

static void Base64decode(unsigned char *decodedString, const char *base64String)
{

    size_t numberOfEncodedChars;
    size_t indexOfFirstEncodedChar;
    size_t decodedIndex;

    //
    // We can only operate on individual bytes.  If we attempt to work
    // on anything larger we could get an alignment fault on some
    // architectures
    //

    numberOfEncodedChars = numberOfBase64Characters(base64String);
    indexOfFirstEncodedChar = 0;
    decodedIndex = 0;
    while (numberOfEncodedChars >= 4)
    {
        unsigned char c1;
        unsigned char c2;
        unsigned char c3;
        unsigned char c4;
        (void)base64toValue(base64String[indexOfFirstEncodedChar], &c1);
        (void)base64toValue(base64String[indexOfFirstEncodedChar + 1], &c2);
        (void)base64toValue(base64String[indexOfFirstEncodedChar + 2], &c3);
        (void)base64toValue(base64String[indexOfFirstEncodedChar + 3], &c4);
        decodedString[decodedIndex] = (c1 << 2) | (c2 >> 4);
        decodedIndex++;
        decodedString[decodedIndex] = ((c2 & 0x0f) << 4) | (c3 >> 2);
        decodedIndex++;
        decodedString[decodedIndex] = ((c3 & 0x03) << 6) | c4;
        decodedIndex++;
        numberOfEncodedChars -= 4;
        indexOfFirstEncodedChar += 4;

    }

    if (numberOfEncodedChars == 2)
    {
        unsigned char c1;
        unsigned char c2;
        (void)base64toValue(base64String[indexOfFirstEncodedChar], &c1);
        (void)base64toValue(base64String[indexOfFirstEncodedChar + 1], &c2);
        decodedString[decodedIndex] = (c1 << 2) | (c2 >> 4);
    }
    else if (numberOfEncodedChars == 3)
    {
        unsigned char c1;
        unsigned char c2;
        unsigned char c3;
        (void)base64toValue(base64String[indexOfFirstEncodedChar], &c1);
        (void)base64toValue(base64String[indexOfFirstEncodedChar + 1], &c2);
        (void)base64toValue(base64String[indexOfFirstEncodedChar + 2], &c3);
        decodedString[decodedIndex] = (c1 << 2) | (c2 >> 4);
        decodedIndex++;
        decodedString[decodedIndex] = ((c2 & 0x0f) << 4) | (c3 >> 2);
    }
}

BUFFER_HANDLE Base64_Decoder(const char* source)
{
    BUFFER_HANDLE result;
    /*Codes_SRS_BASE64_06_008: [If source is NULL then Base64_Decode shall return NULL.]*/
    if (source == NULL)
    {
        LogError("invalid parameter const char* source=%p", source);
        result = NULL;
    }
    else
    {
        if ((strlen(source) % 4) != 0)
        {
            /*Codes_SRS_BASE64_06_011: [If the source string has an invalid length for a base 64 encoded string then Base64_Decode shall return NULL.]*/
            LogError("Invalid length Base64 string!");
            result = NULL;
        }
        else
        {
            if ((result = BUFFER_new()) == NULL)
            {
                /*Codes_SRS_BASE64_06_010: [If there is any memory allocation failure during the decode then Base64_Decode shall return NULL.]*/
                LogError("Could not create a buffer to decoding.");
            }
            else
            {
                size_t sizeOfOutputBuffer = Base64decode_len(source);
                /*Codes_SRS_BASE64_06_009: [If the string pointed to by source is zero length then the handle returned shall refer to a zero length buffer.]*/
                if (sizeOfOutputBuffer > 0)
                {
                    if (BUFFER_pre_build(result, sizeOfOutputBuffer) != 0)
                    {
                        /*Codes_SRS_BASE64_06_010: [If there is any memory allocation failure during the decode then Base64_Decode shall return NULL.]*/
                        LogError("Could not prebuild a buffer for base 64 decoding.");
                        BUFFER_delete(result);
                        result = NULL;
                    }
                    else
                    {
                        Base64decode(BUFFER_u_char(result), source);
                    }
                }
            }
        }
    }
    return result;
}

static STRING_HANDLE Base64_Encode_Internal(const unsigned char* source, size_t size)
{
    STRING_HANDLE result;
    size_t neededSize = 0;
    char* encoded;
    size_t currentPosition = 0;
    neededSize += (size == 0) ? (0) : ((((size - 1) / 3) + 1) * 4);
    neededSize += 1; /*+1 because \0 at the end of the string*/
    /*Codes_SRS_BASE64_06_006: [If when allocating memory to produce the encoding a failure occurs then Base64_Encode shall return NULL.]*/
    encoded = (char*)malloc(neededSize);
    if (encoded == NULL)
    {
        result = NULL;
        LogError("Base64_Encode:: Allocation failed.");
    }
    else
    {
        /*b0            b1(+1)          b2(+2)
        7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
        |----c1---| |----c2---| |----c3---| |----c4---|
        */

        size_t destinationPosition = 0;
        while (size - currentPosition >= 3)
        {
            char c1 = base64char(source[currentPosition] >> 2);
            char c2 = base64char(
                ((source[currentPosition] & 3) << 4) |
                    (source[currentPosition + 1] >> 4)
            );
            char c3 = base64char(
                ((source[currentPosition + 1] & 0x0F) << 2) |
                    ((source[currentPosition + 2] >> 6) & 3)
            );
            char c4 = base64char(
                source[currentPosition + 2] & 0x3F
            );
            currentPosition += 3;
            encoded[destinationPosition++] = c1;
            encoded[destinationPosition++] = c2;
            encoded[destinationPosition++] = c3;
            encoded[destinationPosition++] = c4;

        }
        if (size - currentPosition == 2)
        {
            char c1 = base64char(source[currentPosition] >> 2);
            char c2 = base64char(
                ((source[currentPosition] & 0x03) << 4) |
                    (source[currentPosition + 1] >> 4)
            );
            char c3 = base64b16(source[currentPosition + 1] & 0x0F);
            encoded[destinationPosition++] = c1;
            encoded[destinationPosition++] = c2;
            encoded[destinationPosition++] = c3;
            encoded[destinationPosition++] = '=';
        }
        else if (size - currentPosition == 1)
        {
            char c1 = base64char(source[currentPosition] >> 2);
            char c2 = base64b8(source[currentPosition] & 0x03);
            encoded[destinationPosition++] = c1;
            encoded[destinationPosition++] = c2;
            encoded[destinationPosition++] = '=';
            encoded[destinationPosition++] = '=';
        }

        /*null terminating the string*/
        encoded[destinationPosition] = '\0';
        /*Codes_SRS_BASE64_06_007: [Otherwise Base64_Encode shall return a pointer to STRING, that string contains the base 64 encoding of input.]*/
        result = STRING_new_with_memory(encoded);
        if (result == NULL)
        {
            free(encoded);
            LogError("Base64_Encode:: Allocation failed for return value.");
        }
    }
    return result;
}

STRING_HANDLE Base64_Encode_Bytes(const unsigned char* source, size_t size)
{
    STRING_HANDLE result;
    /*Codes_SRS_BASE64_02_001: [If source is NULL then Base64_Encode_Bytes shall return NULL.] */
    if (source == NULL)
    {
        result = NULL;
    }
    /*Codes_SRS_BASE64_02_002: [If source is not NULL and size is zero, then Base64_Encode_Bytes shall produce an empty STRING_HANDLE.] */
    else if (size == 0)
    {
        result = STRING_new(); /*empty string*/
    }
    else
    {
        result = Base64_Encode_Internal(source, size);
    }
    return result;
}

STRING_HANDLE Base64_Encode(BUFFER_HANDLE input)
{
    STRING_HANDLE result;
    /*the following will happen*/
    /*1. the "data" of the binary shall be "eaten" 3 characters at a time and produce 4 base64 encoded characters for as long as there are more than 3 characters still to process*/
    /*2. the remaining characters (1 or 2) shall be encoded.*/
    /*there's a level of assumption that 'a' corresponds to 0b000000 and that '_' corresponds to 0b111111*/
    /*the encoding will use the optional [=] or [==] at the end of the encoded string, so that other less standard aware libraries can do their work*/
    /*these are the bits of the 3 normal bytes to be encoded*/

    /*Codes_SRS_BASE64_06_001: [If input is NULL then Base64_Encode shall return NULL.]*/
    if (input == NULL)
    {
        result = NULL;
        LogError("Base64_Encode:: NULL input");
    }
    else
    {
        size_t inputSize;
        const unsigned char* inputBinary;
        if ((BUFFER_content(input, &inputBinary) != 0) ||
            (BUFFER_size(input, &inputSize) != 0))
        {
            result = NULL;
            LogError("Base64_Encode:: BUFFER_routines failure.");
        }
        else
        {
            result = Base64_Encode_Internal(inputBinary, inputSize);
        }
    }
    return result;
}


text:
//---------------------------------------------------------------------------
//	Greenplum Database
//	Copyright (C) 2012 EMC Corp.
//
//	@filename:
//		COptimizer.cpp
//
//	@doc:
//		Optimizer class implementation
//---------------------------------------------------------------------------
//
// 优化器类实现

#include "gpos/common/CBitSet.h"
#include "gpos/error/CErrorHandlerStandard.h"
#include "gpos/io/CFileDescriptor.h"

#include "naucrates/dxl/operators/CDXLNode.h"
#include "naucrates/md/IMDProvider.h"

#include "naucrates/traceflags/traceflags.h"
#include "gpopt/base/CAutoOptCtxt.h"
#include "gpopt/base/CQueryContext.h"
#include "gpopt/engine/CEngine.h"
#include "gpopt/engine/CEnumeratorConfig.h"
#include "gpopt/engine/CStatisticsConfig.h"
#include "gpopt/exception.h"
#include "gpopt/minidump/CMiniDumperDXL.h"
#include "gpopt/minidump/CMinidumperUtils.h"
#include "gpopt/minidump/CSerializableStackTrace.h"
#include "gpopt/minidump/CSerializableQuery.h"
#include "gpopt/minidump/CSerializablePlan.h"
#include "gpopt/minidump/CSerializableOptimizerConfig.h"
#include "gpopt/minidump/CSerializableMDAccessor.h"
#include "gpopt/mdcache/CMDAccessor.h"
#include "gpopt/translate/CTranslatorDXLToExpr.h"
#include "gpopt/translate/CTranslatorExprToDXL.h"

#include "gpopt/optimizer/COptimizerConfig.h"
#include "gpopt/optimizer/COptimizer.h"
#include "gpopt/cost/ICostModel.h"

#include <fstream>

using namespace gpos;
using namespace gpdxl;
using namespace gpmd;
using namespace gpopt;

//---------------------------------------------------------------------------
//	@function:
//		COptimizer::PrintQuery
//
//	@doc:
//		Helper function to print query expression
//
//---------------------------------------------------------------------------
//
// 打印查询表达式
void
COptimizer::PrintQuery
	(
	IMemoryPool *pmp,  //内存操作
	CExpression *pexprTranslated,  //
	CQueryContext *pqc  //
	)
{
	CAutoTrace at(pmp);
	at.Os() << std::endl << "Algebrized query: " << std::endl << *pexprTranslated;

	DrgPexpr *pdrgpexpr = COptCtxt::PoctxtFromTLS()->Pcteinfo()->PdrgPexpr(pmp);
	const ULONG ulCTEs = pdrgpexpr->UlLength();
	if (0 < ulCTEs)
	{
		at.Os() << std::endl << "Common Table Expressions: ";
		for (ULONG ul = 0; ul < ulCTEs; ul++)
		{
			at.Os() << std::endl << *(*pdrgpexpr)[ul];
		}
	}
	pdrgpexpr->Release();

	CExpression *pexprPreprocessed = pqc->Pexpr();
	(void) pexprPreprocessed->PdpDerive();
	at.Os() << std::endl << "Algebrized preprocessed query: " << std::endl << *pexprPreprocessed;
}

//---------------------------------------------------------------------------
//	@function:
//		COptimizer::PrintPlan
//
//	@doc:
//		Helper function to print query plan
//
//---------------------------------------------------------------------------
//
// 打印(物理)查询计划
void
COptimizer::PrintPlan
	(
	IMemoryPool *pmp,
	CExpression *pexprPlan
	)
{
	CAutoTrace at(pmp);
	at.Os() << std::endl << "Physical plan: " << std::endl << *pexprPlan;
}

//---------------------------------------------------------------------------
//	@function:
//		COptimizer::DumpSamples
//
//	@doc:
//		Helper function to dump plan samples
//
//---------------------------------------------------------------------------
void
COptimizer::DumpSamples
	(
	IMemoryPool *pmp,
	CEnumeratorConfig *pec,
	ULONG ulSessionId,
	ULONG ulCmdId
	)
{
	GPOS_ASSERT(NULL != pec);

	CWStringDynamic *pstr = CDXLUtils::PstrSerializeSamplePlans(pmp, pec, true /*fIndent*/);
	pec->DumpSamples(pstr, ulSessionId, ulCmdId);
	GPOS_DELETE(pstr);
	GPOS_CHECK_ABORT;

	pec->FitCostDistribution();
	pstr = CDXLUtils::PstrSerializeCostDistr(pmp, pec, true /*fIndent*/);
	pec->DumpCostDistr(pstr, ulSessionId, ulCmdId);
	GPOS_DELETE(pstr);
}

//---------------------------------------------------------------------------
//	@function:
//		COptimizer::DumpQueryOrPlan
//
//	@doc:
//		Print query tree or plan tree
//
//---------------------------------------------------------------------------
//
// 打印查询树或计划树
void
COptimizer::PrintQueryOrPlan
	(
	IMemoryPool *pmp,
	CExpression *pexpr,
	CQueryContext *pqc
	)
{
	GPOS_ASSERT(NULL != pexpr);

	if (NULL != pqc)
	{
		if (GPOS_FTRACE(EopttracePrintQuery))
		{
			PrintQuery(pmp, pexpr, pqc);
		}
	}
	else
	{
		if (GPOS_FTRACE(EopttracePrintPlan))
		{
			PrintPlan(pmp, pexpr);
		}
	}
}

//---------------------------------------------------------------------------
//	@function:
//		COptimizer::PdxlnOptimize
//
//	@doc:
//		Optimize given query
//		the function is oblivious of trace flags setting/resetting which
//		must happen at the caller side if needed
//
//---------------------------------------------------------------------------
//
// 优化给定的查询
CDXLNode *
COptimizer::PdxlnOptimize
	(
	IMemoryPool *pmp,
	CMDAccessor *pmda,
	const CDXLNode *pdxlnQuery,
	const DrgPdxln *pdrgpdxlnQueryOutput,
	const DrgPdxln *pdrgpdxlnCTE,
	IConstExprEvaluator *pceeval,
	ULONG ulHosts,	// actual number of data nodes in the system
	ULONG ulSessionId,
	ULONG ulCmdId,
	DrgPss *pdrgpss,
	COptimizerConfig *poconf,
	const CHAR *szMinidumpFileName 	// name of minidump file to be created
	)
{
	GPOS_ASSERT(NULL != pmda);
	GPOS_ASSERT(NULL != pdxlnQuery);
	GPOS_ASSERT(NULL != pdrgpdxlnQueryOutput);
	GPOS_ASSERT(NULL != poconf);

	BOOL fMinidump = GPOS_FTRACE(EopttraceMinidump);

	// If minidump was requested, open the minidump file and initialize
	// minidumper. (We create the minidumper object even if we're not
	// dumping, but without the Init-call, it will stay inactive.)
	CMiniDumperDXL mdmp(pmp);
	CAutoP<std::wofstream> wosMinidump;
	CAutoP<COstreamBasic> osMinidump;
	if (fMinidump)
	{
		CHAR szFileName[GPOS_FILE_NAME_BUF_SIZE];

		CMinidumperUtils::GenerateMinidumpFileName(szFileName, GPOS_FILE_NAME_BUF_SIZE, ulSessionId, ulCmdId, szMinidumpFileName);

		// Note: std::wofstream won't throw an error on failure. The stream is merely marked as
		// failed. We could check the state, and avoid the overhead of serializing the
		// minidump if it failed, but it's hardly worth optimizing for an error case.
		wosMinidump = GPOS_NEW(pmp) std::wofstream(szFileName);
		osMinidump = GPOS_NEW(pmp) COstreamBasic(wosMinidump.Pt());

		mdmp.Init(osMinidump.Pt());
	}
	CDXLNode *pdxlnPlan = NULL;
	CErrorHandlerStandard errhdl;
	GPOS_TRY_HDL(&errhdl)
	{
		CSerializableStackTrace serStack;
		CSerializableOptimizerConfig serOptConfig(pmp, poconf);
		CSerializableMDAccessor serMDA(pmda);
		CSerializableQuery serQuery(pmp, pdxlnQuery, pdrgpdxlnQueryOutput, pdrgpdxlnCTE);

		{
			poconf->AddRef();
			if (NULL != pceeval)
			{
				pceeval->AddRef();
			}

			// install opt context in TLS
			CAutoOptCtxt aoc(pmp, pmda, pceeval, poconf);

			// translate DXL Tree -> Expr Tree
			CTranslatorDXLToExpr dxltr(pmp, pmda);
			CExpression *pexprTranslated =	dxltr.PexprTranslateQuery(pdxlnQuery, pdrgpdxlnQueryOutput, pdrgpdxlnCTE);
			GPOS_CHECK_ABORT;
			gpdxl::DrgPul *pdrgpul = dxltr.PdrgpulOutputColRefs();
			gpmd::DrgPmdname *pdrgpmdname = dxltr.Pdrgpmdname();

			CQueryContext *pqc = CQueryContext::PqcGenerate(pmp, pexprTranslated, pdrgpul, pdrgpmdname, true /*fDeriveStats*/);
			GPOS_CHECK_ABORT;

			PrintQueryOrPlan(pmp, pexprTranslated, pqc);

			CWStringDynamic strTrace(pmp);
			COstreamString oss(&strTrace);

			// if the number of inlinable CTEs is greater than the cutoff, then
			// disable inlining for this query
			if (!GPOS_FTRACE(EopttraceEnableCTEInlining) ||
				CUtils::UlInlinableCTEs(pexprTranslated) > poconf->Pcteconf()->UlCTEInliningCutoff())
			{
				COptCtxt::PoctxtFromTLS()->Pcteinfo()->DisableInlining();
			}

			GPOS_CHECK_ABORT;
			// optimize logical expression tree into physical expression tree.
			// 优化逻辑表达式树为物理表达式树
			CExpression *pexprPlan = PexprOptimize(pmp, pqc, pdrgpss);
			GPOS_CHECK_ABORT;

			PrintQueryOrPlan(pmp, pexprPlan);

			// translate plan into DXL
			// 将查询计划转化为DXL
			pdxlnPlan = Pdxln(pmp, pmda, pexprPlan, pqc->PdrgPcr(), pdrgpmdname, ulHosts);
			GPOS_CHECK_ABORT;

			if (fMinidump)
			{
				CSerializablePlan serPlan(pmp, pdxlnPlan, poconf->Pec()->UllPlanId(), poconf->Pec()->UllPlanSpaceSize());
				CMinidumperUtils::Finalize(&mdmp, true /* fSerializeErrCtxt*/);
				GPOS_CHECK_ABORT;
			}

			if (GPOS_FTRACE(EopttraceSamplePlans))
			{
				DumpSamples(pmp, poconf->Pec(), ulSessionId, ulCmdId);
				GPOS_CHECK_ABORT;
			}

			// cleanup
			pexprTranslated->Release();
			pexprPlan->Release();
			GPOS_DELETE(pqc);
		}
	}
	GPOS_CATCH_EX(ex)
	{
		if (fMinidump)
		{
			CMinidumperUtils::Finalize(&mdmp, false /* fSerializeErrCtxt*/);
			HandleExceptionAfterFinalizingMinidump(ex);
		}

		GPOS_RETHROW(ex);
	}
	GPOS_CATCH_END;

	return pdxlnPlan;
}

//---------------------------------------------------------------------------
//	@function:
//		COptimizer::HandleExceptionAfterFinalizingMinidump
//
//	@doc:
//		Handle exception after finalizing minidump
//
//---------------------------------------------------------------------------
void
COptimizer::HandleExceptionAfterFinalizingMinidump
	(
	CException &ex
	)
{
	if (NULL != ITask::PtskSelf() &&
		!ITask::PtskSelf()->Perrctxt()->FPending())
	{
		// if error context has no pending exception, then minidump creation
		// might have reset the error,
		// in this case we need to raise the original exception
		GPOS_RAISE
			(
			ex.UlMajor(),
			ex.UlMinor(),
			GPOS_WSZ_LIT("re-raising exception after finalizing minidump")
			);
	}

	// otherwise error is still pending, re-throw original exception
	GPOS_RETHROW(ex);
}

// This function provides an entry point to check for a plan with CTE,
// if both CTEProducer and CTEConsumer are executed on the same locality.
// If it is not the case, the plan is bogus and cannot be executed
// by the executor and an exception is raised.
//
// To be able to enter the recursive logic, the execution locality of root
// is determined before the recursive call.
void
COptimizer::CheckCTEConsistency
	(
	IMemoryPool *pmp,
	CExpression *pexpr
	)
{
	HMUlUl *phmulul = GPOS_NEW(pmp) HMUlUl(pmp);
	CDrvdPropPlan *pdpplanChild = CDrvdPropPlan::Pdpplan(pexpr->PdpDerive());
	CDistributionSpec *pdsChild = pdpplanChild->Pds();

	CUtils::EExecLocalityType eelt = CUtils::ExecLocalityType(pdsChild);
	CUtils::ValidateCTEProducerConsumerLocality(pmp, pexpr, eelt, phmulul);
	phmulul->Release();
}

//---------------------------------------------------------------------------
//	@function:
//		COptimizer::PexprOptimize
//
//	@doc:
//		Optimize query in given query context
//
//---------------------------------------------------------------------------
//
// 优化查询
CExpression *
COptimizer::PexprOptimize
	(
	IMemoryPool *pmp,
	CQueryContext *pqc,
	DrgPss *pdrgpss
	)
{
	CEngine eng(pmp);
	eng.Init(pqc, pdrgpss);
	eng.Optimize();

	GPOS_CHECK_ABORT;

	CExpression *pexprPlan = eng.PexprExtractPlan();
	(void) pexprPlan->PrppCompute(pmp, pqc->Prpp());

	CheckCTEConsistency(pmp, pexprPlan);

	GPOS_CHECK_ABORT;

	return pexprPlan;
}

//---------------------------------------------------------------------------
//	@function:
//		COptimizer::Pdxln
//
//	@doc:
//		Translate an optimizer expression into a DXL tree
//
//---------------------------------------------------------------------------
//
// 将优化器表达式转化为DXL树
CDXLNode *
COptimizer::Pdxln
	(
	IMemoryPool *pmp,
	CMDAccessor *pmda,
	CExpression *pexpr,
	DrgPcr *pdrgpcr,
	DrgPmdname *pdrgpmdname,
	ULONG ulHosts
	)
{
	GPOS_ASSERT(0 < ulHosts);
	DrgPi *pdrgpiHosts = GPOS_NEW(pmp) DrgPi(pmp);

	for (ULONG ul = 0; ul < ulHosts; ul++)
	{
		pdrgpiHosts->Append(GPOS_NEW(pmp) INT(ul));
	}

	CTranslatorExprToDXL ptrexprtodxl(pmp, pmda, pdrgpiHosts);
	CDXLNode *pdxlnPlan = ptrexprtodxl.PdxlnTranslate(pexpr, pdrgpcr, pdrgpmdname);

	return pdxlnPlan;
}

// EOF


text:
package org.jetbrains.tutorials.actions;

import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import org.jetbrains.annotations.NotNull;

/**
 * @author Anna Bulenkova
 */
public class BaseActionGroup extends ActionGroup {
    @NotNull
    @Override
    public AnAction[] getChildren(AnActionEvent anActionEvent) {
        return new AnAction[]{new MyAction()};
    }
    class MyAction extends AnAction {
        public MyAction() {
           super("Dynamically Added Action");
        }
        @Override
        public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
            //does nothing
        }
    }
}


text:
# GodEye

[![Version](https://img.shields.io/cocoapods/v/Log4G.svg?style=flat)](http://cocoapods.org/pods/GodEye)
[![License](https://img.shields.io/cocoapods/l/Log4G.svg?style=flat)](http://cocoapods.org/pods/GodEye)
[![Platform](https://img.shields.io/cocoapods/p/Log4G.svg?style=flat)](http://cocoapods.org/pods/GodEye)
[![Carthage compatible](https://img.shields.io/badge/Carthage-Compatible-brightgreen.svg?style=flat)](https://github.com/Carthage/Carthage)

Automaticly display Log,Crash,Network,ANR,Leak,CPU,RAM,FPS,NetFlow,Folder and etc with one line of code based on Swift. Just like God opened his eyes.

**[中文文档](./README_CN.md)**

It's so huge that I split it into several independent components:

* [Log4G](https://github.com/zixun/Log4G) — Simple, lightweight logging framework written in Swift.
* [AssistiveButton](https://github.com/zixun/AssistiveButton) — Simple Assistive Button.
* [AppBaseKit](https://github.com/zixun/AppBaseKit) — A handy kit of Swift extensions and wrapped class to boost your productivity.
* [AppSwizzle](https://github.com/zixun/AppSwizzle) — lightweight and flexible method swizzling wrapped by swift.
* [LeakEye](https://github.com/zixun/LeakEye) — LeakEye is a memory leak monitor.
* [NetworkEye](https://github.com/zixun/NetworkEye) — NetworkEye is a network monitor,automatic catch the request and response infomation of all kinds of request send.
* [ANREye](https://github.com/zixun/ANREye) — ANREye is an ANR (Application Not Responding) monitor,automatic catch the ANR and return stacktrace of all threads.
* [ASLEye](https://github.com/zixun/ASLEye) — ASLEye is an ASL(Apple System Log) monitor, automatic catch the log from NSLog by asl module.
* [CrashEye](https://github.com/zixun/CrashEye) — CrashEye is an ios crash monitor,automatic catch exception crash & signal crash and return the stacktrace.
* [SystemEye](https://github.com/zixun/SystemEye) — SystemEye is a system monitor,automatic catch the infomation of cpu,memory....etc.

## Features

- [x] monitor for the log and point out log type.
- [x] monitor for the crash, include Uncatched Exception and Signal.
- [x] monitor for the network, all information of request and response.
- [x] monitor for the ANR, tell you the stacktrace of all threads.
- [x] monitor for the memory leak, tell you the leak object's class name.
- [x] a terminal for you to customized your commands and things what to do.
- [x] monitor for the cpu usage of system and application.
- [x] monitor for the ram usage of system and application.
- [x] monitor for the FPS.
- [x] monitor for the netflow of system and application.
- [x] a file browser for look through the sandbox, .app and root directory.
- [x] custom and runtime setting

## Characteristics

- [x] richly: comprehensive feature
- [x] conveniently: one line code access
- [x] automaticly: no code intrusion
- [x] safety: no compile code in release

## Preview

## Book and Principle

**I has wrote a book named [《iOS监控编程》](https://www.qingdan.us/product/25),each chapter records the course function of the implementation details and the way to explore.sorry for english friends,this book wrote by chineses.**

## Installation

### CocoaPods
GodEye is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "GodEye"
```

#### Not build in Release

First, add configurations in Podfile.

```ruby
pod 'GodEye', '~> 1.0.0', :configurations => ['Debug']
```

Then, find `Other Swift Flags` in your target's `Build Settings`,add `DEBUG` in Debug scheme.

Finally, add `DEBUG` macro in makeEye:

```swift
#if DEBUG
    GodEye.makeEye(with: self.window!)
#endif
```

### Carthage
Or, if you're using [Carthage](https://github.com/Carthage/Carthage), add GodEye to your Cartfile:

```
github "zixun/GodEye"
```

#### Add GodEye to Embed Frameworks
On your application targets' `"General"` settings tab, in the "Embed Frameworks" section, drag and drop `GodEye.framework` from the Carthage/Build folder on disk.

#### Add Dependency to Linked Frameworks and Libraries
On your application targets' `"General"` settings tab, in the "Linked Frameworks and Libraries" section, drag and drop the dependency framework used in GodEye from the Carthage/Build folder on disk.

#### Add Run Script
On your application targets' "Build Phases" settings tab, click the "+" icon and choose "New Run Script Phase". Create a Run Script in which you specify your shell (ex: /bin/sh), add the following contents to the script area below the shell:

```
/usr/local/bin/carthage copy-frameworks
```

and add the paths to the frameworks you want to use under "Input Files":

## OpenSource Application Use GodEye

[CocoaChinaPlus](https://github.com/zixun/CocoaChinaPlus) is an open source application wrote by swift, now the GodEye is work well in it!

## Usage

import at AppDelegate:

```swift
import GodEye
```

making GodEye at `application:didFinishLaunchingWithOptions`:

```ruby
GodEye.makeEye(with:self.window!)
```

well, make GodEye with one line code as above will use default configuration.We also can custom our configuration:

```swift
let configuration = Configuration()
configuration.command.add(command: "test", description: "test command") { () -> (String) in
    return "this is test command result"
}
configuration.command.add(command: "info", description: "print test info") { () -> (String) in
    return "info"
}

GodEye.makeEye(with: self.window!, configuration: configuration)
```

the example above is custom command configuration, we also can custom control and switch configuration.see detail at `ControlConfiguration` and `SwitchConfiguration`

## Example

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Author

twitter: [@zixun_](https://twitter.com/zixun_)

email: chenyl.exe@gmail.com

github: [zixun](https://github.com/zixun)

blog: [子循(SubCycle)](http://zixun.github.io/)

## Thanks
First is Github, it gives me a lot of ideas and inspiration, and even ready-made code:

* Log monitor inspired by [AELog](https://github.com/tadija/AELog)
* Crash monitor inspired by [GT](https://github.com/Tencent/GT)
* ANR monitor inspired by [Watchdog](https://github.com/wojteklu/Watchdog)
* Network monitor inspired by [NetworkEye](https://github.com/coderyi/NetworkEye)

Secondly is StackOverFlow, it answers a lot of problems encountered in the author's writing and development,here are a few images of deep:

* CPU usage of application:[ios-get-cpu-usage-from-application](https://stackoverflow.com/questions/8223348/ios-get-cpu-usage-from-application)
* CPU usage of system:[get-cpu-percent-usage](https://stackoverflow.com/questions/6785069/get-cpu-percent-usage)

Finally, thanks to several great blog:

* Memory Leak inspired by MrPeak's PLeakSniffer: [http://mrpeak.cn/blog/leak](http://mrpeak.cn/blog/leak)
* wereadteam's MLeaksFinder: [https://wereadteam.github.io/2016/02/22/MLeaksFinder](https://wereadteam.github.io/2016/02/22/MLeaksFinder)

## License

GodEye is available under the MIT license. See the LICENSE file for more info.


text:
package com.konifar.materialcat.events;

import com.konifar.materialcat.models.pojo.Photo;

import java.util.List;

public class PhotoSearchCallbackEvent {

    private boolean success;
    private List<Photo> photos;
    private String sort;

    public PhotoSearchCallbackEvent(boolean success, String sort) {
        this.success = success;
        this.sort = sort;
    }

    public PhotoSearchCallbackEvent(boolean success, List<Photo> photos, String sort) {
        this.success = success;
        this.photos = photos;
        this.sort = sort;
    }

    public boolean isSuccess() {
        return success;
    }

    public List<Photo> getPhotos() {
        return photos;
    }

    public String getSort() {
        return sort;
    }

}


text:
This package highlights registered keyword, regardless of file extension.
This package works as temporary grammar.
![short animation](https://raw.githubusercontent.com/BlueSilverCat/highlight-registered-keyword/master/highlight-registered-keyword.gif?raw=true)

This package use the CSON npm package.

Sorry, Im bad at English.
For the reason, this is confusing description.

## How to use

1 Set PatternsFilePath. PatternsFilePath specifies CSON file that defines keyword.
e.g.

```.coffee
"highlight-registered-keyword": [
  {
    class: "keyword"
    pattern: "/WhiteCat|BlackCat/g"
    fileTypes:["txt"]
  }
  {
    class: "comment"
    pattern: "///.*$/g"
    fileTypes:["c", "cpp", "js"]
  }
  {
    class: "comment"
    pattern: "/#.*$/g"
    fileTypes:["py"]
  }
  {
    class: "blockcomment"
    pattern: "//\\*[\\S\\s]*?\\*//g"
    fileTypes:["c", "cpp", "js"]
  }
  {
    class: "blockcomment"
    pattern: "/'''[\\S\\s]*?'''/g"
    fileTypes:["py"]
  }
  {
    class: "keyword"
    pattern: "/\\251|\\xAE/g"
  }
  {
    class: "windowslinebreak"
    pattern: "/\\cM\\cJ/g"
    disable: true
  }
  {
    class: "badSpace"
    pattern: "/\u00A0|\u2000|\u2001|\u2002|\u2003|\u2004|\u2005|\u2006|\u2007|\u2008|\u2009|\u200A|\u202F|\u205F|\u3000/g"
  }
  {
    class: "badZeroWidthSpace"
    pattern: "/\u200B|\u200C|\u200D|\uFEFF/g"
  }
  {
    class: "escapeSequence"
    pattern: "/\\\\./g"
  }
  {
    class: "literal"
    pattern: "/\".*?\"/g"
  }
  {
    class: "ISBN"
    pattern: "/(ISBN-13 ?((978)|(979))-\\d{1,9}-\\d{1,9}-\\d{1,9}-\\d)|(ISBN-10 ?\\d{1,9}-\\d{1,9}-\\d{1,9}-\\d)/g"
  }
  {
    class: "surrogatePairs"
    pattern: "/\u{2000B}|\u{2123D}|\u{2131B}|\u{2146E}|\u{218BD}|\u{20B9F}|\u{216B4}|\u{21E34}|\u{231C4}|\u{235C4}/g"
  }
]
```

2 Register style to your styles.less. like this.

```.css
atom-text-editor .highlight {
  &.highlight-registered-keyword {
    .region {
      background-color: hsla(180, 60%, 50%, 0.5);
    }
    &.comment {
      .region {
        background-color: hsla(120, 50%, 25%, 0.5);
      }
    }
    &.blockcomment {
      .region {
        background-color: hsla(60, 50%, 25%, 0.5);
      }
    }
    &.windowslinebreak {
      .region {
        background-color: hsla(40, 50%, 25%, 0.5);
      }
    }
    &.escapeSequence {
      .region {
        background-color: hsla(300, 50%, 25%, 0.5);
      }
    }
    &.keyword {
      .region {
        background-color: hsla(0, 60%, 50%, 0.5);
      }
    }
    &.literal {
      .region {
        background-color: hsla(320, 60%, 50%, 0.5);
      }
    }
    &.badSpace {
      .region {
        background-color: hsla(0, 60%, 50%, 0.5);
        border: solid;
        border-color: hsla(120, 60%, 50%, 0.5);
      }
      .region:after {
        content: '_';
        color: hsla(240, 100%, 50%, 1);
      }
    }
    &.badZeroWidthSpace {
      .region {
        background-color: hsla(0, 100%, 50%, 1);
        border: solid;
        border-color: hsla(0, 100%, 50%, 1);
       }
    }
    &.ISBN {
      .region {
        background-color: hsla(60, 60%, 50%, 0.5);
      }
    }
    &.surrogatePairs {
      .region {
        background-color: hsla(300, 100%, 50%, 1);
        border: solid;
        border-color: hsla(0, 100%, 50%, 1);
      }
    }
  }
}
```

3 Activate package.
Press `Alt+Ctrl+Shift+h` or `F5`
If this package does not work, use `highlight-registered-keyword:show` command to check patterns.
![screenshot](https://raw.githubusercontent.com/BlueSilverCat/highlight-registered-keyword/master/sample.png?raw=true)

## Commands

-   `highlight-registered-keyword:markAll`
    Highlight keywords in all editors.
    Default key: `Alt+Ctrl+Shift+h`.
-   `highlight-registered-keyword:unmarkAll`
    Unhighlight keywords in all editors.
    Default key: none.
-   `highlight-registered-keyword:mark`
    Highlight keywords in an only active editor.
    Default key: `F5`.
-   `highlight-registered-keyword:unmark`
    Unhighlight keywords in an only active editor.
    Default key: none.
-   `highlight-registered-keyword:show`
    Show current valid configs.
    Default key: none.
-   `highlight-registered-keyword:open`
    Open PatternsFile that has been specified by PatternsFilePath.
    Default key: none.
-   `highlight-registered-keyword:settings`
    Open package settings.
    Default key: none.

## About file that has been specified by FilePath.

Patterns is array of Object.
Object properties are `pattern`, `class`, `fileTypes` and `disable`.
`pattern` is a String that was quoted regular expression.
Like this `"/.*ABC.*/gmiy"`.
Valid flags are `g`, `m`, `i` and `y`.
`class` is a String that represents CSS class.
`disable` is Boolean that represents this pattern is disable.
`disable` is optional. If you don't describe this, it set to false.
`fileTypes` is Array of String that specify the target filetypes.
`fileTypes` is optional. If you don't describe this, it set to `["*"]`(all filetype).
If you use `\`, it need escaping like this `\\`.
e.g. `\d` is `\\d`.
If you want to match `\`, you have to write like this `\\\\`

```.coffee
"highlight-registered-keyword": [
  {
    # /\\\d+?\\/g; matching string is like this \12345\
    class: "keyword"
    pattern: "/\\\\\\d+?\\\\/g"
    disable: false
    fileTypes: ["*"]
  }
]
```

## About style.less

This package insert div element to near the keyword.
Div element's class contained `highlight`, `highlight-registered-keyword`, and _`specified-class`_

```.html
<div class="highlight highlight-registered-keyword comment">
	<div class="region" style="..."></div>
</div>
```

But div element not containes keyword.
For the above reason, you must to specify region class.

```.css
atom-text-editor .highlight&.highlight-registered-keyword&.comment .region {
  	background-color: hsla(0, 60%, 50%, 0.5);
}
// or
atom-text-editor .highlight-registered-keyword&.comment .region {
  	background-color: hsla(0, 60%, 50%, 0.5);
}
```

Valid style: background, border...
Invalid style: font, color...

## Known problem

-   Lag on particular pattern.
    e.g. `"/(.*?)/g"`
-   Multi line pattern cannot updates highlight status.
    e.g. `"//\\*[\\S\\s]*?\\*//g"`


text:
cask 'keyboardcleantool' do
  version :latest
  sha256 :no_check

  # bettertouchtool.net was verified as official when first introduced to the cask
  url 'https://bettertouchtool.net/KeyboardCleanTool.zip'
  name 'KeyboardCleanTool'
  homepage 'https://blog.boastr.net/keyboardcleantool/'
  license :gratis

  app 'KeyboardCleanTool.app'
end


text:
/**
 * Naive, pure JS implementation of core ui-router services
 *
 * @internalapi @module vanilla
 */ /** */
export * from './interface';
export * from './q';
export * from './injector';
export * from './baseLocationService';
export * from './hashLocationService';
export * from './memoryLocationService';
export * from './pushStateLocationService';
export * from './memoryLocationConfig';
export * from './browserLocationConfig';
export * from './utils';
export * from './plugins';


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/compute/v1/compute.proto

namespace Google\Cloud\Compute\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 *
 * Generated from protobuf message google.cloud.compute.v1.SecurityPoliciesScopedList
 */
class SecurityPoliciesScopedList extends \Google\Protobuf\Internal\Message
{
    /**
     * A list of SecurityPolicies contained in this scope.
     *
     * Generated from protobuf field repeated .google.cloud.compute.v1.SecurityPolicy security_policies = 127783791;
     */
    private $security_policies;
    /**
     * Informational warning which replaces the list of security policies when the list is empty.
     *
     * Generated from protobuf field optional .google.cloud.compute.v1.Warning warning = 50704284;
     */
    private $warning = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type array<\Google\Cloud\Compute\V1\SecurityPolicy>|\Google\Protobuf\Internal\RepeatedField $security_policies
     *           A list of SecurityPolicies contained in this scope.
     *     @type \Google\Cloud\Compute\V1\Warning $warning
     *           Informational warning which replaces the list of security policies when the list is empty.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Compute\V1\Compute::initOnce();
        parent::__construct($data);
    }

    /**
     * A list of SecurityPolicies contained in this scope.
     *
     * Generated from protobuf field repeated .google.cloud.compute.v1.SecurityPolicy security_policies = 127783791;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getSecurityPolicies()
    {
        return $this->security_policies;
    }

    /**
     * A list of SecurityPolicies contained in this scope.
     *
     * Generated from protobuf field repeated .google.cloud.compute.v1.SecurityPolicy security_policies = 127783791;
     * @param array<\Google\Cloud\Compute\V1\SecurityPolicy>|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setSecurityPolicies($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Compute\V1\SecurityPolicy::class);
        $this->security_policies = $arr;

        return $this;
    }

    /**
     * Informational warning which replaces the list of security policies when the list is empty.
     *
     * Generated from protobuf field optional .google.cloud.compute.v1.Warning warning = 50704284;
     * @return \Google\Cloud\Compute\V1\Warning|null
     */
    public function getWarning()
    {
        return $this->warning;
    }

    public function hasWarning()
    {
        return isset($this->warning);
    }

    public function clearWarning()
    {
        unset($this->warning);
    }

    /**
     * Informational warning which replaces the list of security policies when the list is empty.
     *
     * Generated from protobuf field optional .google.cloud.compute.v1.Warning warning = 50704284;
     * @param \Google\Cloud\Compute\V1\Warning $var
     * @return $this
     */
    public function setWarning($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Compute\V1\Warning::class);
        $this->warning = $var;

        return $this;
    }

}


text:
require 'time'

module RspecLogFormatter
  module Analysis
    class Result
      def initialize(build_number, time, outcome, description, spec_path, message=nil, klass=nil,duration=nil)
        @time = Time.parse(time)
        @build_number = (build_number || -1).to_i
        @description = description
        @outcome = outcome
        @spec_path = spec_path
        @message = message
        @klass = klass
        @duration = duration.to_f
      end

      attr_accessor :build_number, :description, :duration
      attr_reader :message, :klass, :time

      def failure?
        @outcome == "failed"
      end

      def success?
        @outcome == "passed"
      end
    end
  end
end


text:
package com.griddynamics.jagger.util.generators;

import com.google.common.collect.Lists;
import com.griddynamics.jagger.engine.e1.Provider;
import com.griddynamics.jagger.engine.e1.collector.CollectThreadsTestListener;
import com.griddynamics.jagger.engine.e1.collector.limits.LimitSetConfig;
import com.griddynamics.jagger.engine.e1.collector.test.TestListener;
import com.griddynamics.jagger.engine.e1.scenario.WorkloadTask;
import com.griddynamics.jagger.engine.e1.sessioncomparation.BaselineSessionProvider;
import com.griddynamics.jagger.user.test.configurations.JLoadTest;
import org.apache.commons.lang.StringUtils;

import java.util.List;

import static com.griddynamics.jagger.util.generators.TerminationGenerator.generateTermination;
import static com.griddynamics.jagger.util.generators.TestDefinitionGenerator.generatePrototype;
import static com.griddynamics.jagger.util.generators.WorkloadGenerator.generateLoad;

/**
 * @author asokol
 *         created 11/6/16
 *         Generates {@link WorkloadTask} entity from user-defined {@link JLoadTest} entity.
 */
class TestGenerator {
    static WorkloadTask generateFromTest(JLoadTest jLoadTest,
                                         BaselineSessionProvider baselineSessionProvider,
                                         LimitSetConfig limitSetConfig, String testGroupName) {
        WorkloadTask task = generatePrototype(jLoadTest.getTestDescription());
        task.setName(getName(jLoadTest.getId(), testGroupName));
        task.setParentTaskId(testGroupName);
        task.setVersion("0");

        List<Provider<TestListener>> testListeners = Lists.newArrayList(jLoadTest.getListeners());
        testListeners.add(new CollectThreadsTestListener());
        task.setTestListeners(testListeners);

        task.setTerminateStrategyConfiguration(generateTermination(jLoadTest.getTermination()));

        task.setClockConfiguration(generateLoad(jLoadTest.getLoad()));

        task.setLimits(LimitGenerator.generate(jLoadTest.getLimits(), baselineSessionProvider, limitSetConfig));

        return task;
    }

    public static String getName(String id, String testGroupName) {
        if (StringUtils.isBlank(id)){
            return testGroupName;
        }
        return String.format("%s [%s]", testGroupName, id);
    }
}