text:
alter table KORREKSJON rename column BBS_DATO to OPPRINNELIG_DATO;

drop sequence NIBEUTVEKSLING_SEQUENCE;
create sequence NIBEUTVEKSLING_SEQUENCE;


text:
var each = require('std/each')

module.exports = function makePromise() {
	var dependants = []
	var result

	return result = {
		depend:depend,
		fulfill:fulfill
	}

	function depend(fn) {
		if (result.fulfillment) { return fn.apply(this, result.fulfillment) }
		dependants.push(fn)
	}

	function fulfill() {
		result.fulfillment = slice(arguments, 0)
		each(dependants, function(fn) {
			fn.apply(this, result.fulfillment)
		})
	}
}

redpajama_set_name: RedPajamaGithub


text:
package io.vertx.ext.amqp;

/**
 * Outgoing message-delivery state
 */
public enum DeliveryState {
  /**
   * Message has been settled by the remote peer.
   */
  SETTLED,

  /**
   * Delivery is still pending and the state is not known.
   */
  UNKNOWN,

  /**
   * The link has failed due to the underlying network connection failure. The
   * message associated with this delivery is in-doubt.
   */
  LINK_FAILED
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/Count_down/Count_down.iml" filepath="$PROJECT_DIR$/Count_down/Count_down.iml" />
      <module fileurl="file://$PROJECT_DIR$/FlycoTabLayout_Lib/FlycoTabLayout_Lib.iml" filepath="$PROJECT_DIR$/FlycoTabLayout_Lib/FlycoTabLayout_Lib.iml" />
      <module fileurl="file://$PROJECT_DIR$/MarqueeView/MarqueeView.iml" filepath="$PROJECT_DIR$/MarqueeView/MarqueeView.iml" />
      <module fileurl="file://$PROJECT_DIR$/ShoppingApp2.iml" filepath="$PROJECT_DIR$/ShoppingApp2.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
      <module fileurl="file://$PROJECT_DIR$/extensiblepageindicator/extensiblepageindicator.iml" filepath="$PROJECT_DIR$/extensiblepageindicator/extensiblepageindicator.iml" />
      <module fileurl="file://$PROJECT_DIR$/lib_1/lib_1.iml" filepath="$PROJECT_DIR$/lib_1/lib_1.iml" />
      <module fileurl="file://$PROJECT_DIR$/pullToRefreshlibrary/pullToRefreshlibrary.iml" filepath="$PROJECT_DIR$/pullToRefreshlibrary/pullToRefreshlibrary.iml" />
      <module fileurl="file://$PROJECT_DIR$/rollviewpager/rollviewpager.iml" filepath="$PROJECT_DIR$/rollviewpager/rollviewpager.iml" />
      <module fileurl="file://$PROJECT_DIR$/volley/volley.iml" filepath="$PROJECT_DIR$/volley/volley.iml" />
    </modules>
  </component>
</project>


text:
package ca.phon.opgraph.app.components;

import java.io.*;

import javax.swing.*;
import javax.swing.text.html.*;

import ca.phon.opgraph.*;
import ca.phon.opgraph.exceptions.*;

/**
 * A component to show inputs and output values from a node's {@link OpContext}.
 */
public class ContextViewerPanel extends JEditorPane {
	/** The processing context being debugged */
	private Processor processor;

	/** The node currently being viewed */
	private OpNode node;

	/**
	 * Default constructor.
	 */
	public ContextViewerPanel() {
		this.processor = null;
		this.node = null;

		// Set up editor kit
		final HTMLEditorKit kit = new HTMLEditorKit();
		final StyleSheet style = kit.getStyleSheet();
		style.addRule("body { padding: 5px; }");
		style.addRule("ul { margin: 5px 15px; }");
		style.addRule(".error { font-family: Courier,Courier New,Console,System; color: #ff0000; white-space: pre; }");

		// Initialize
		setEditorKit(kit);
		setEditable(false);

		updateDebugInfo();
	}

	/**
	 * Gets the processing context this component is using for displaying
	 * debug information on a node.
	 *
	 * @return the context, or null if no context is being used
	 */
	public Processor getProcessingContext() {
		return processor;
	}

	/**
	 * Sets the processing context this component should use for displaying
	 * debug information on a node.
	 *
	 * @param context  the context, or null if no context should be used
	 */
	public void setProcessingContext(Processor context) {
		if(this.processor != context) {
			this.processor = context;
			updateDebugInfo();
		}
	}

	/**
	 * Gets the node whose debug information this component is currently displaying.
	 *
	 * @return the node
	 */
	public OpNode getNode() {
		return node;
	}

	/**
	 * Sets the node whose debug information this component should display.
	 *
	 * @param node the node to set
	 */
	public void setNode(OpNode node) {
		if(this.node != node) {
			this.node = node;
			updateDebugInfo();
		}
	}

	/**
	 * Updates the debug info for the current node/processing context.
	 */
	public void updateDebugInfo() {
		String text = "No debug info available";
		if(processor != null) {
			final OpContext context = processor.getContext().findChildContext(node);
			if(context != null) {
				final StringBuilder sb = new StringBuilder();
				sb.append("");

				// check for error
				final ProcessingException processException = processor.getError();
				if(processException != null) {
					final ByteArrayOutputStream out = new ByteArrayOutputStream();
					final PrintStream ps = new PrintStream(out);
					processException.printStackTrace(ps);
					sb.append("
Error
");
					try {
						sb.append("
Stack Trace:
" + new String(out.toByteArray(), "UTF-8") + "

");
					} catch (UnsupportedEncodingException e) {
					}
				}

				sb.append("Inputs:
");
				for(InputField field : node.getInputFields()) {
					sb.append("
");
					sb.append(field.getKey());
					sb.append(": ");

					final Object value = context.get(field);
					String valueTxt = (value != null ? value.toString() : "undefined");
					if(valueTxt.length() > 200)
						valueTxt = valueTxt.substring(0, 200) + '\u2026';
					sb.append(valueTxt);

					sb.append("
");
				}
				sb.append("
Outputs:
");
				for(OutputField field : node.getOutputFields()) {
					sb.append("
");
					sb.append(field.getKey());
					sb.append(": ");

					final Object value = context.get(field);
					String valueTxt = (value != null ? value.toString() : "undefined");
					if(valueTxt.length() > 200)
						valueTxt = valueTxt.substring(0, 200) + '\u2026';
					sb.append(valueTxt);

					sb.append("
");
				}
				sb.append("
");
				sb.append("");

				text = sb.toString();
			}
		}

		setText(text);
	}
}


text:
import {Polling, clearPollCounter, resetPollCounter} from "../components/polling";
import utils from "../../../../test/mocha/testUtils";
import {shallow, mount} from "enzyme";
import sinon from "sinon";
import React from "react";
import ReactDOM from "react-dom";

var assert = utils.assert;

describe("Polling", () => {
  describe('Counters', () => {

    it('resetPollCounter calls cb after set time', done => {
      let called = false;
      resetPollCounter(100, () => {
        called = true;
        assert.ok(called);
        done();
      });
    });

    it('clearRefreshCounter stops counter', done => {
      let called = false;
      resetPollCounter(100, () => {
        called = true;
      });

      clearPollCounter();
      setTimeout(() => {
        assert.notOk(called);
        done();
      }, 200);
    });
  });

  describe('Component', () => {
    var clock;
    beforeEach(() => {
      clock = sinon.useFakeTimers();
    });

    afterEach(() => {
      clock.restore();
    });

    it('renders slider with correct info', () => {
      const wrapper = shallow(<Polling
        startValue={10}
        min={1}
        max={20}
        stepSize={1}
        onPoll={() => {}}
                            />);

      const props = wrapper.find('input').props();

      assert.deepEqual(props.value, 10);
      assert.deepEqual(props.step, 1);
      assert.deepEqual(props.min, 1);
      assert.deepEqual(props.max, 21);
    });

    it('turns polling off if value is max', () => {
      const wrapper = mount(<Polling
        startValue={10}
        min={1}
        max={20}
        stepSize={1}
        onPoll={() => {}}
                            />);

      wrapper.find('input').simulate('change', {target: {value: 21}});
      const isOff = wrapper.find('.faux__polling-info-value--off').text();
      assert.deepEqual(isOff.toLowerCase(), "off");
    });

    it('turns polling off if value is max', (done) => {
      let pollCalled = false;
      const onPoll = () => {
        pollCalled = true;
        assert.ok(pollCalled);
        done();
      };
      mount(<Polling
        startValue={1}
        min={1}
        max={20}
        stepSize={1}
        onPoll={onPoll}
      />);

      clock.tick(1010);

    });
  });
});


text:
function Sprinter(skill, color) {

  this.distance = 0; // distance traveled by the runner
  this.speed = 0; // acceleration (amount of velocity gained each "stride")
  this.velocity = 0; // "momentum"

	/** AI variables */
  this.skill = skill; // chance of correctly striding
  this.previousKey = null;

  this.color = color;
  this.finished = false; // whether to recieve input or draw the time
  this.time = 0; // stopwatch
}

/**
 * draws the runner
 */
Sprinter.prototype.draw = function(lane, laneWidth) {

  var y = (lane * laneWidth) + (laneWidth / 2); // figure out y

  fill(this.color);
  stroke(255);
  strokeWeight(2);
  ellipse(this.distance, y, laneWidth / 2);

  if (this.finished) {
		// draw the time

    textSize(laneWidth / 2);
    noStroke();
    fill(255);
    textAlign(RIGHT);
    text((this.time / 1000).toFixed(2), width - laneWidth, y);
  }
};

/**
 * handles distance based upon velocity,
 * handles velocity based upon speed & resistance
 * handles finish, stops stopwatch
 */
Sprinter.prototype.update = function() {

  if (this.finished) {
		// don't allow movement
		return;
	} else {

    if (this.finished = (this.distance > width)) // set whether the runner finished the race
      this.time = new Date().getTime() - startTime; // stop stopwatch
  }

	/* move the Sprinter */
  this.velocity = (this.velocity > 3) ? 3 : this.velocity; // constrain velocity

  this.distance += this.velocity; // movement
  this.velocity += this.speed; // acceleration
  this.velocity *= 0.99; // resistance
  this.speed = 0; // reset acceleration
};

/**
 * handles key press & previousKey
 * accelerates the runner
 */
Sprinter.prototype.run = function(key) {

  if (this.previousKey != null) { // only if they've strided in the past

		// LEFT_ARROW + RIGHT_ARROW = 76, therefore;
		// 76 - LEFT_ARROW = RIGHT_ARROW &
		// 76 - RIGHT_ARROW = LEFT_ARROW
    if (this.previousKey != key && (this.previousKey + key === 76)) {
			// they've tapped the correct key

      this.speed += (this.velocity / 75 + 0.06); // accelerate
    } else {
			// they've pressed the wrong key

			/* cut off momentum */
      this.speed = 0;
      this.velocity = 0;
    }

  } else {
		// no previous key press

    this.speed += (this.velocity / 75 + 0.06);
  }

	// keep track of key
  this.previousKey = key;
};


text:
@interface CASToken ()

@property (nonatomic, assign, readwrite) CASTokenType type;

@end

@implementation CASToken

#pragma mark - debug

+ (NSString *)stringForType:(CASTokenType)type {
    switch (type) {
        case CASTokenTypeUnknown:
            return @"unknown";
        case CASTokenTypeIndent:
            return @"indent";
        case CASTokenTypeOutdent:
            return @"outdent";
        case CASTokenTypeEOS:
            return @"EOS";
        case CASTokenTypeSemiColon:
            return @"semicolon";
        case CASTokenTypeCarat:
            return @"carat";
        case CASTokenTypeNewline:
            return @"newline";
        case CASTokenTypeLeftSquareBrace:
            return @"left square brace";
        case CASTokenTypeRightSquareBrace:
            return @"right square brace";
        case CASTokenTypeLeftCurlyBrace:
            return @"left curly brace";
        case CASTokenTypeRightCurlyBrace:
            return @"right curly brace";
        case CASTokenTypeLeftRoundBrace:
            return @"left round brace";
        case CASTokenTypeRightRoundBrace:
            return @"right round brace";
        case CASTokenTypeColor:
            return @"color";
        case CASTokenTypeString:
            return @"string";
        case CASTokenTypeUnit:
            return @"unit";
        case CASTokenTypeBoolean:
            return @"boolean";
        case CASTokenTypeRef:
            return @"ref";
        case CASTokenTypeOperator:
            return @"operator";
        case CASTokenTypeSpace:
            return @"space";
        case CASTokenTypeSelector:
            return @"selector";
    }
}

- (NSString *)description {
    if (self.value) {
        return [NSString stringWithFormat:@"%@ %@", [self.class stringForType:self.type], self.value];
    }
    return [self.class stringForType:self.type];
}

#pragma mark - Factory

+ (instancetype)tokenOfType:(CASTokenType)type {
    CASToken *token = self.class.new;
    token.type = type;
    return token;
}

+ (instancetype)tokenOfType:(CASTokenType)type value:(id)value {
    CASToken *token = self.class.new;
    token.type = type;
    token.value = value;
    return token;
}

#pragma mark - Helpers

- (NSString *)stringValue {
    if ([self.value isKindOfClass:NSString.class]) {
        return self.value;
    }
    return [self.value stringValue];
}

- (BOOL)isWhitespace {
    return self.type == CASTokenTypeIndent
        || self.type == CASTokenTypeOutdent
        || self.type == CASTokenTypeNewline
        || self.type == CASTokenTypeSpace;
}

- (BOOL)valueIsEqualTo:(id)value {
    return [self.value isEqual:value];
}

- (BOOL)isPossiblySelector {
    return self.type == CASTokenTypeRef
        || self.type == CASTokenTypeCarat
        || self.type == CASTokenTypeLeftSquareBrace
        || self.type == CASTokenTypeRightSquareBrace
        || self.type == CASTokenTypeSelector
        || self.type == CASTokenTypeNewline
        || self.type == CASTokenTypeSpace
        || self.type == CASTokenTypeOperator
        || [self valueIsEqualTo:@":"]
        || [self valueIsEqualTo:@","];
}

- (BOOL)isPossiblyVar {
    return self.type == CASTokenTypeIndent
        || self.type == CASTokenTypeSpace
        || self.type == CASTokenTypeRef
        || [self valueIsEqualTo:@"="];
}

- (BOOL)isPossiblyExpression {
    return self.type == CASTokenTypeUnit
        || self.type == CASTokenTypeSpace
        || self.type == CASTokenTypeLeftRoundBrace
        || self.type == CASTokenTypeRightRoundBrace
        || (self.type == CASTokenTypeOperator);
}

- (BOOL)isPossiblySelectorDelimiter{
    return self.type == CASTokenTypeLeftCurlyBrace || self.type == CASTokenTypeIndent;
}

- (BOOL)isEqual:(id)object
{
    if ([object isKindOfClass:[CASToken class]]) {
        CASToken *other = object;

        return other.type == self.type && ([other.value isEqual:self.value] || other.value == self.value);
    }
    else {
        return NO;
    }
}

#pragma mark - NSCoding

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [self init];
    if (self != nil) {
        self.type       = [aDecoder decodeIntegerForKey:NSStringFromSelector(@selector(type))];
        self.value      = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(value))];
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeInteger:self.type forKey:NSStringFromSelector(@selector(type))];
    [aCoder encodeObject:self.value forKey:NSStringFromSelector(@selector(value))];
}

@end


text:
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Integration;

namespace WebDumpViewer
{
    partial class MyImageBox
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.protectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.markKeepToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.elementHost1 = new System.Windows.Forms.Integration.ElementHost();
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.panel1 = new System.Windows.Forms.Panel();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.contextMenuStrip1.SuspendLayout();
            this.tableLayoutPanel1.SuspendLayout();
            this.panel1.SuspendLayout();
            this.SuspendLayout();
            //
            // pictureBox1
            //
            this.pictureBox1.ContextMenuStrip = this.contextMenuStrip1;
            this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.pictureBox1.Location = new System.Drawing.Point(0, 0);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(150, 170);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            this.pictureBox1.Click += new System.EventHandler(this.PictureBox1_Click);
            //
            // contextMenuStrip1
            //
            this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.deleteToolStripMenuItem,
            this.protectToolStripMenuItem,
            this.markKeepToolStripMenuItem});
            this.contextMenuStrip1.Name = "contextMenuStrip1";
            this.contextMenuStrip1.Size = new System.Drawing.Size(131, 70);
            //
            // deleteToolStripMenuItem
            //
            this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
            this.deleteToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
            this.deleteToolStripMenuItem.Text = "Delete";
            this.deleteToolStripMenuItem.Click += new System.EventHandler(this.DeleteToolStripMenuItem_Click);
            //
            // protectToolStripMenuItem
            //
            this.protectToolStripMenuItem.Name = "protectToolStripMenuItem";
            this.protectToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
            this.protectToolStripMenuItem.Text = "Protect";
            this.protectToolStripMenuItem.Click += new System.EventHandler(this.protectToolStripMenuItem_Click);
            //
            // markKeepToolStripMenuItem
            //
            this.markKeepToolStripMenuItem.Name = "markKeepToolStripMenuItem";
            this.markKeepToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
            this.markKeepToolStripMenuItem.Text = "Mark Keep";
            this.markKeepToolStripMenuItem.Click += new System.EventHandler(this.markKeepToolStripMenuItem_Click);
            //
            // elementHost1
            //
            this.elementHost1.ContextMenuStrip = this.contextMenuStrip1;
            this.elementHost1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.elementHost1.Location = new System.Drawing.Point(3, 3);
            this.elementHost1.Name = "elementHost1";
            this.elementHost1.Size = new System.Drawing.Size(144, 144);
            this.elementHost1.TabIndex = 2;
            this.elementHost1.Text = "elementHost1";
            this.elementHost1.Child = null;
            //
            // tableLayoutPanel1
            //
            this.tableLayoutPanel1.ColumnCount = 1;
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel1.Controls.Add(this.elementHost1, 0, 0);
            this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            this.tableLayoutPanel1.RowCount = 2;
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
            this.tableLayoutPanel1.Size = new System.Drawing.Size(150, 170);
            this.tableLayoutPanel1.TabIndex = 4;
            this.tableLayoutPanel1.MouseClick += new System.Windows.Forms.MouseEventHandler(this.TableLayoutPanel1_MouseClick);
            //
            // panel1
            //
            this.panel1.Controls.Add(this.pictureBox1);
            this.panel1.Controls.Add(this.tableLayoutPanel1);
            this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.panel1.Location = new System.Drawing.Point(0, 0);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(150, 170);
            this.panel1.TabIndex = 3;
            //
            // timer1
            //
            this.timer1.Tick += new System.EventHandler(this.Timer1_Tick);
            //
            // MyImageBox
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.panel1);
            this.Name = "MyImageBox";
            this.Size = new System.Drawing.Size(150, 170);
            this.MouseEnter += new System.EventHandler(this.MyImageBox_MouseEnter);
            this.MouseLeave += new System.EventHandler(this.MyImageBox_MouseLeave);
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.contextMenuStrip1.ResumeLayout(false);
            this.tableLayoutPanel1.ResumeLayout(false);
            this.panel1.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private PictureBox pictureBox1;
        private ContextMenuStrip contextMenuStrip1;
        private ToolStripMenuItem deleteToolStripMenuItem;
        private ElementHost elementHost1;
        private ToolStripMenuItem protectToolStripMenuItem;
        private TableLayoutPanel tableLayoutPanel1;
        private Panel panel1;
        private Timer timer1;
        private ToolStripMenuItem markKeepToolStripMenuItem;
    }
}


text:
#include "barrier.h"

#include "base/logging.h"
#include "base/mutex.h"
#include "base/time_utils.h"
#include "thread.h"

namespace art {

Barrier::Barrier(int count)
    : count_(count),
      lock_("GC barrier lock", kThreadSuspendCountLock),
      condition_("GC barrier condition", lock_) {
}

void Barrier::Pass(Thread* self) {
  MutexLock mu(self, lock_);
  SetCountLocked(self, count_ - 1);
}

void Barrier::Wait(Thread* self) {
  Increment(self, -1);
}

void Barrier::Init(Thread* self, int count) {
  MutexLock mu(self, lock_);
  SetCountLocked(self, count);
}

void Barrier::Increment(Thread* self, int delta) {
  MutexLock mu(self, lock_);
  SetCountLocked(self, count_ + delta);

  // Increment the count.  If it becomes zero after the increment
  // then all the threads have already passed the barrier.  If
  // it is non-zero then there is still one or more threads
  // that have not yet called the Pass function.  When the
  // Pass function is called by the last thread, the count will
  // be decremented to zero and a Broadcast will be made on the
  // condition variable, thus waking this up.
  while (count_ != 0) {
    condition_.Wait(self);
  }
}

bool Barrier::Increment(Thread* self, int delta, uint32_t timeout_ms) {
  MutexLock mu(self, lock_);
  SetCountLocked(self, count_ + delta);
  bool timed_out = false;
  if (count_ != 0) {
    uint32_t timeout_ns = 0;
    uint64_t abs_timeout = NanoTime() + MsToNs(timeout_ms);
    for (;;) {
      timed_out = condition_.TimedWait(self, timeout_ms, timeout_ns);
      if (timed_out || count_ == 0) return timed_out;
      // Compute time remaining on timeout.
      uint64_t now = NanoTime();
      int64_t time_left = abs_timeout - now;
      if (time_left <= 0) return true;
      timeout_ns = time_left % (1000*1000);
      timeout_ms = time_left / (1000*1000);
    }
  }
  return timed_out;
}

void Barrier::SetCountLocked(Thread* self, int count) {
  count_ = count;
  if (count == 0) {
    condition_.Broadcast(self);
  }
}

Barrier::~Barrier() {
  if (gAborting == 0) {
    // Only check when not aborting.
    CHECK_EQ(count_, 0) << "Attempted to destroy barrier with non zero count";
  } else {
    if (count_ != 0) {
      LOG(WARNING) << "Attempted to destroy barrier with non zero count " << count_;
    }
  }
}

}  // namespace art


text:
package models;

import javax.persistence.Entity;

import play.db.jpa.Blob;
import play.db.jpa.Model;

/**
 * Classe Profil représentant les informations de base sur un individu.

 * Rappel : la gestion d'un identifiant est déjà fourni par héritage.
 */
@Entity
public class Profil extends Model {
	public String nom;
	public String prenom;

	public String telFixe;
	public String telPortable;
	public String email;

	public Blob photo;

	// TODO Gérer un référentiel de départements
	public String departement;

	// TODO Gérer un référentiel de services
	public String service;

	// TODO Gérer un référentiel de postes
	public String poste;

	public String localisation;

	public String hasPhoto = "FALSE";

	/**
	 * Constructeur basic.

	 * Rappel : un identifiant est déjà fourni par héritage.
	 *
	 * @param nom
	 * @param prenom
	 */
	public Profil(String nom, String prenom) {
		this.nom = nom;
		this.prenom = prenom;
	}

	/**
	 * Constructeur basic.

	 * Rappel : un identifiant est déjà fourni par héritage.
	 */
	public Profil() {
	}

}


text:
namespace Ui {
class MainWindow;
}

class newMember;
class DatabaseManager;
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    DatabaseManager *mpDbManager;
    EmailingService *mpEmailingService;
    PrintingService *mpPrintingService;
    QSqlQueryModel *mpShowingModel;
    QSqlQueryModel *mpReturnedRecord;
    QSqlQueryModel *mpSearchModel;
    QSqlQueryModel *mpPaymentsToConfirmModel;
    QSqlQueryModel *mpMonthAlertModel;
    AddMembersDialog *mpAddMembersDialog;
    QModelIndexList mpSelectedRowsIndexesList;
    QMessageBox::StandardButton reply;
    bool isItHistory;

    int currentMonth;
    int userAction;
    int alertChoice;
    int pyamentTrackShowMode;
    int defaulMonthCount;
    int setViewEditChoice;
    QString selectedYear;

    void setCurrentMonth();
    int getCurrentMonth();
    void setUserAction(int action);
    int getUserAction();
    void setAlertChoice(int choice);
    int getAlertChoice();
    void setPaymentTrackShowMode(int mode);
    int getPaymentTrackShowMode();
    void setDefaultMonthCount(int monthCount);
    int getDefaultMonthCount();
    void setYear();
    QString getYear();

    void printThis(QTableView *tableToPrint);
    void setSearchItemsInvisible();
    void clearAddMemberFields();
    void DisnableEditRemoveBtn();
    void enableFeatures();
    void disableFeatures();
    void setConfCorrPayVisible();
    void setConfCorrPayInvisible();
    void setDisplayBtnsVisible();
    void setDisplayBtnsInvisible();
    void hideColumns();
    void showColumns();

private slots:
    void Exit();
    void displayAllInPaymentTab();
    void FindMember();
    void EditMemberBasicInfo();
    void EnableEditRemoveBtn();
    void SelectedRows();
    void DeleteMember();
    void ConfirmPayment();
    void displaySlectedMonthDefaults();
    void EnableBtns();
    void GetOneMonthAlerts();
    void GetTwoMonthsAlerts();
    void GetThreeMonthsAlerts();
    void showActiveMembers();
    void enableSearchFields();
    void displayAlertsOnGui(QSqlQueryModel *mMonthAlertModel);
    void displayAllmembersAllYear(QSqlQueryModel *monthAlertModel);
    void CorrectPayment();
    void GetHigherThanThreeAlerts();
    void displayTableOnGui(QSqlQueryModel *mpShowingModel);
    void printPaymentInfo();
    void printBasicInfo();
    void showCurrentPayments();
    void showPaymentsHistory();
    void displayPaymentsModel(QSqlQueryModel *monthAlertModel);
    void sendEmail();
    void openAddMemberForm();
    void setSearchItemsVisible();
    void setPaymentsItemsInvislable();
    void enableGoSearchBtn();
    void disabledAddMemberFields();
    void enabledAddMemberFields();
    void startEditing();
    void startViewing();
    void startAddition();
    void checkYear();
    void displaySlectedMemberPayments();
    void showInactiveMembers();
    void deactivateMembership();
    void activateMembership();
};

#endif // MAINWINDOW_H


text:
package com.mcoding.base.dst.service.income.impl;

import com.mcoding.base.core.CommonException;
import com.mcoding.base.core.PageView;
import com.mcoding.base.dst.bean.income.DstIncomeOrder;
import com.mcoding.base.dst.bean.income.DstIncomeOrderExample;
import com.mcoding.base.dst.bean.income.DstIncomeOrderProduct;
import com.mcoding.base.dst.persistence.income.DstIncomeOrderMapper;
import com.mcoding.base.dst.service.income.DstIncomeMemberService;
import com.mcoding.base.dst.service.income.DstIncomeOrderProductService;
import com.mcoding.base.dst.service.income.DstIncomeOrderService;
import com.mcoding.base.member.bean.member.Member;
import com.mcoding.base.member.service.member.MemberService;
import com.mcoding.base.order.bean.order.Order;

import java.util.List;
import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("dstIncomeOrderService")
public class DstIncomeOrderServiceImpl implements DstIncomeOrderService {
    @Resource
    protected DstIncomeOrderMapper dstIncomeOrderMapper;

    @Resource
    protected DstIncomeOrderProductService dstIncomeOrderProductService;

    @Resource
    protected DstIncomeMemberService dstIncomeMemberService;

    @Resource
    protected MemberService memberService;

    @CacheEvict(value={"dstIncomeOrder"}, allEntries=true)
    @Override
    public void addObj(DstIncomeOrder t) {
        this.dstIncomeOrderMapper.insertSelective(t);
    }

    @CacheEvict(value={"dstIncomeOrder"}, allEntries=true)
    @Override
    public void deleteObjById(int id) {
        this.dstIncomeOrderMapper.deleteByPrimaryKey(id);
    }

    @CacheEvict(value={"dstIncomeOrder"}, allEntries=true)
    @Override
    public void modifyObj(DstIncomeOrder t) {
        if (t.getId() == null || t.getId() ==0) {
            throw new NullPointerException("id 为空,无法更新");
        }
        this.dstIncomeOrderMapper.updateByPrimaryKeySelective(t);
    }

    @Cacheable(value="dstIncomeOrder", key="'DstIncomeOrderService_' + #root.methodName + '_' +#id")
    @Override
    public DstIncomeOrder queryObjById(int id) {
        return this.dstIncomeOrderMapper.selectByPrimaryKey(id);
    }

    @Cacheable(value="dstIncomeOrder", key="'DstIncomeOrderService_' + #root.methodName + '_'+ #example.toJson()")
    @Override
    public List<DstIncomeOrder> queryAllObjByExample(DstIncomeOrderExample example) {
        return this.dstIncomeOrderMapper.selectByExample(example);
    }

    @Cacheable(value="dstIncomeOrder", key="'DstIncomeOrderService_' + #root.methodName + '_'+ #example.toJson()")
    @Override
    public PageView<DstIncomeOrder> queryObjByPage(DstIncomeOrderExample example) {
        PageView<DstIncomeOrder> pageView = example.getPageView();
        if (pageView == null) {
            pageView = new PageView<>(1, 10);
            example.setPageView(pageView);
        }
        pageView.setQueryResult(this.dstIncomeOrderMapper.selectByExampleByPage(example));
        return pageView;
    }

    @Transactional
    @CacheEvict(value={"dstIncomeOrder"}, allEntries=true)
	@Override
	public DstIncomeOrder addIncome(Order order, List<DstIncomeOrderProduct> incomeOrderProducts, Member member) {
		int incomeTotal = 0;
		int pointTotal = 0;
		int levelId = 0;
		String levelName = null;
		for(DstIncomeOrderProduct dstIncomeOrderProduct: incomeOrderProducts){
			levelId = dstIncomeOrderProduct.getLevelId();
			levelName = dstIncomeOrderProduct.getLevelName();
			incomeTotal = incomeTotal + dstIncomeOrderProduct.getIncomeTotal();
			pointTotal = pointTotal + dstIncomeOrderProduct.getPointTotal();
		}

		DstIncomeOrder dstIncomeOrder = new DstIncomeOrder();
		dstIncomeOrder.setMemberId(member.getId());
		dstIncomeOrder.setMemberName(member.getName());
		dstIncomeOrder.setLevelId(levelId);
		dstIncomeOrder.setLevelName(levelName);
		dstIncomeOrder.setOrderId(order.getId());
		dstIncomeOrder.setOrderNo(order.getOrderNo());
		dstIncomeOrder.setOrderMemberId(order.getMemberId());
		dstIncomeOrder.setOrderMemberName(order.getMemberNickName());
		dstIncomeOrder.setOrderAmountTotal(order.getAmountTotal());
		dstIncomeOrder.setOrderAmountPay(order.getAmountPay());
		dstIncomeOrder.setIncomeAmountTotal(incomeTotal);
		dstIncomeOrder.setPointAmountTotal(pointTotal);
		dstIncomeOrder.setIncomeType(DstIncomeOrder.TYPE_INCOME);
		this.addObj(dstIncomeOrder);

		for(DstIncomeOrderProduct dstIncomeOrderProduct : incomeOrderProducts){
			dstIncomeOrderProduct.setIncomeOrderId(dstIncomeOrder.getId());
			this.dstIncomeOrderProductService.addObj(dstIncomeOrderProduct);
		}

		this.dstIncomeMemberService.addIncome(incomeTotal, pointTotal, member);
		return dstIncomeOrder;
	}

    @Transactional
	@Override
	public void refundIncome(int orderId) {
		DstIncomeOrderExample exRefund = new DstIncomeOrderExample();
		exRefund.createCriteria().andOrderIdEqualTo(orderId).andIncomeTypeEqualTo(DstIncomeOrder.TYPE_REFUND);
		List<DstIncomeOrder> list = this.queryAllObjByExample(exRefund);

		if (CollectionUtils.isNotEmpty(list)) {
			throw new CommonException("已经有退费记录了,无法在执行退费");
		}

		DstIncomeOrderExample exIncomeOrder = new DstIncomeOrderExample();
		exIncomeOrder.createCriteria().andOrderIdEqualTo(orderId).andIncomeTypeEqualTo(DstIncomeOrder.TYPE_INCOME);
		list = this.queryAllObjByExample(exIncomeOrder);

		for(DstIncomeOrder incomeOrder: list){
			int income = -incomeOrder.getIncomeAmountTotal();
			int point = -incomeOrder.getPointAmountTotal();

			incomeOrder.setId(null);
			incomeOrder.setCreateTime(null);
			incomeOrder.setIncomeType(DstIncomeOrder.TYPE_REFUND);
			incomeOrder.setIncomeAmountTotal(income);
			incomeOrder.setPointAmountTotal(point);

			this.addObj(incomeOrder);
			this.dstIncomeMemberService.addIncome(income, point, this.memberService.queryObjById(incomeOrder.getMemberId()));
		}

	}
}


text:
layout: relation
title: 'det'
shortdef: 'determiner'
udver: '2'
---

This document is a placeholder for the language-specific documentation
for `det`.


text:
package org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.pig.PigException;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhyPlanVisitor;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.POStatus;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.Result;
import org.apache.pig.data.DataByteArray;
import org.apache.pig.data.DataType;
import org.apache.pig.impl.plan.OperatorKey;
import org.apache.pig.impl.plan.NodeIdGenerator;
import org.apache.pig.impl.plan.VisitorException;

public class GTOrEqualToExpr extends BinaryComparisonOperator {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    transient private final Log log = LogFactory.getLog(getClass());

    public GTOrEqualToExpr(OperatorKey k) {
        this(k, -1);
    }

    public GTOrEqualToExpr(OperatorKey k, int rp) {
        super(k, rp);
        resultType = DataType.BOOLEAN;
    }

    @Override
    public String name() {
        return "Greater Than or Equal" + "[" + DataType.findTypeName(resultType) + "]" +" - " + mKey.toString();
    }

    @Override
    public void visit(PhyPlanVisitor v) throws VisitorException {
        v.visitGTOrEqual(this);
    }

    @Override
    public Result getNext(Boolean bool) throws ExecException {
        byte status;
        Result left, right;

        switch (operandType) {
        case DataType.BYTEARRAY: {
            Result r = accumChild(null, dummyDBA);
            if (r != null) {
                return r;
            }
            left = lhs.getNext(dummyDBA);
            right = rhs.getNext(dummyDBA);
            return doComparison(left, right);
                            }

        case DataType.DOUBLE: {
            Result r = accumChild(null, dummyDouble);
            if (r != null) {
                return r;
            }
            left = lhs.getNext(dummyDouble);
            right = rhs.getNext(dummyDouble);
            return doComparison(left, right);
                            }

        case DataType.FLOAT: {
            Result r = accumChild(null, dummyFloat);
            if (r != null) {
                return r;
            }
            left = lhs.getNext(dummyFloat);
            right = rhs.getNext(dummyFloat);
            return doComparison(left, right);
                            }

        case DataType.INTEGER: {
            Result r = accumChild(null, dummyInt);
            if (r != null) {
                return r;
            }
            left = lhs.getNext(dummyInt);
            right = rhs.getNext(dummyInt);
            return doComparison(left, right);
                            }

        case DataType.LONG: {
            Result r = accumChild(null, dummyLong);
            if (r != null) {
                return r;
            }
            left = lhs.getNext(dummyLong);
            right = rhs.getNext(dummyLong);
            return doComparison(left, right);
                            }

        case DataType.CHARARRAY: {
            Result r = accumChild(null, dummyString);
            if (r != null) {
                return r;
            }
            left = lhs.getNext(dummyString);
            right = rhs.getNext(dummyString);
            return doComparison(left, right);
                            }

        default: {
            int errCode = 2067;
            String msg = this.getClass().getSimpleName() + " does not know how to " +
            "handle type: " + DataType.findTypeName(operandType);
            throw new ExecException(msg, errCode, PigException.BUG);
        }

        }
    }

    @SuppressWarnings("unchecked")
    private Result doComparison(Result left, Result right) {
        if (trueRef == null) initializeRefs();
        if (left.returnStatus != POStatus.STATUS_OK) return left;
        if (right.returnStatus != POStatus.STATUS_OK) return right;
        // if either operand is null, the result should be
        // null
        if(left.result == null || right.result == null) {
            left.result = null;
            left.returnStatus = POStatus.STATUS_NULL;
            return left;
        }
        assert(left.result instanceof Comparable);
        assert(right.result instanceof Comparable);
        if (((Comparable)left.result).compareTo((Comparable)right.result) >= 0) {
            left.result = trueRef;
        } else {
            left.result = falseRef;
        }
        return left;
    }

    @Override
    public GTOrEqualToExpr clone() throws CloneNotSupportedException {
        GTOrEqualToExpr clone = new GTOrEqualToExpr(new OperatorKey(mKey.scope,
            NodeIdGenerator.getGenerator().getNextNodeId(mKey.scope)));
        clone.cloneHelper(this);
        return clone;
    }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('hs_access_control', '0003_auto_20150824_2215'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='useraccess',
            name='admin',
        ),
    ]


text:
package org.artifactory.storage.db.security.entity;

import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSet;
import org.apache.commons.lang.StringUtils;
import org.artifactory.util.PathUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * Date: 9/3/12
 * Time: 12:24 PM
 *
 * @author freds
 */
public class PermissionTarget {
    private static final String DELIMITER = ",";

    private final long permTargetId;
    private final String name;
    private final List<String> includes;
    private final List<String> excludes;

    /**
     * Initialized as null, and can (and should) be set only once
     */
    private ImmutableSet<String> repoKeys = null;

    public PermissionTarget(long id, String name, List<String> includes, List<String> excludes) {
        if (id <= 0L) {
            throw new IllegalArgumentException("Permission target id cannot be zero or negative!");
        }
        if (StringUtils.isBlank(name)) {
            throw new IllegalArgumentException("Permission target name cannot be null!");
        }
        this.permTargetId = id;
        this.name = name;
        this.includes = includes == null ? Collections.<String>emptyList() : includes;
        this.excludes = excludes == null ? Collections.<String>emptyList() : excludes;
    }

    public PermissionTarget(long id, String name, String includes, String excludes) {
        this(id, name,
                PathUtils.includesExcludesPatternToStringList(includes),
                PathUtils.includesExcludesPatternToStringList(excludes));
    }

    public long getPermTargetId() {
        return permTargetId;
    }

    public String getName() {
        return name;
    }

    public List<String> getIncludes() {
        return includes;
    }

    public List<String> getExcludes() {
        return excludes;
    }

    public String getIncludesPattern() {
        if (includes == null || includes.isEmpty()) {
            return null;
        }
        return PathUtils.collectionToDelimitedString(includes, DELIMITER);
    }

    public String getExcludesPattern() {
        if (excludes == null || excludes.isEmpty()) {
            return null;
        }
        return PathUtils.collectionToDelimitedString(excludes, DELIMITER);
    }

    public Collection<String> getRepoKeys() {
        if (repoKeys == null) {
            throw new IllegalStateException(
                    "Permission Target object was not initialized correctly! List of repo keys missing.");
        }
        return repoKeys;
    }

    public void setRepoKeys(Set<String> repoKeys) {
        if (this.repoKeys != null) {
            throw new IllegalStateException("Cannot set repository keys already set!");
        }
        if (repoKeys == null) {
            throw new IllegalArgumentException("Cannot set repository keys to null");
        }
        this.repoKeys = ImmutableSet.copyOf(repoKeys);
    }

    public boolean isIdentical(PermissionTarget pt) {
        if (pt == this) {
            return true;
        }
        if (pt == null) {
            return false;
        }
        if (pt.permTargetId != this.permTargetId
                || !StringUtils.equals(pt.name, this.name)
                || !Objects.equal(pt.includes, this.includes)
                || !Objects.equal(pt.excludes, this.excludes)
                || !Objects.equal(pt.repoKeys, this.repoKeys)
                ) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "PermissionTarget{" +
                "permTargetId=" + permTargetId +
                ", name='" + name + '\'' +
                ", includes=" + includes +
                ", excludes=" + excludes +
                ", repoKeys=" + repoKeys +
                '}';
    }
}


text:
from debate import Debate
from debates import Debates


text:
layout: post
title: Byte saving techniques
comments: true
categories: [jquery, javascript, performance]
tags: [jquery, javascript]
---

This is a collection of Javascript wizardry that can shave of your code.

## Arguments
---

### Use one-letter positional arguments, in alphabetical order

Since arguments will need to be as short as posible, and will likely be reused with their lifetime, it's best to treat theme as positionals instead of trying to give theme meaning through their name. While using one-leter names mariginally aids readability for a single function, keeping a consitent approach helps readability across all functions.

function(t,d,v,i,f){...} //before
function(a,b,c,d,e){...} //after

### Test aruments presence instead of length

Use `in` to check whether a given arument was passed

arguments.length>1||(cb=alert) // before
1 in arguments||(cb=alert)     // after

If only truthy arguments are of interest, you can even boil that down to

arguments[0]&&(cb=alert)       // works only if arguments[0] coerces to true
Embed functionality within arguments

Save delimiters by processing stuff within (unused) arguments

a+=b<<1;x(a,1); // before
x(a+=b<<1,1);   // after

### Reuse parenthesis of the function call

There are some functions which take no argument, and obviously you can reuse the parentheses when calling them. See @snowlord's RPN function.

((a=b.pop(),b.pop())+c+a); // before
(b.pop(a=b.pop())+c+a);    // after

If you're not sure if a function really takes no arguments, see if its .length is 0.

### `setInterval` and `setTimeout` hacks

Use strings instead of functions in setInterval and setTimeout.

setInterval(function(){console.log("z")},100) // before
setInterval('console.log("z")',100) // after

`setInterval` and `setTimeout` default to the browser's fastest possible time interval (usually 1ms in most modern browsers) if the second argument is left out.

setInterval('console.log("z")',1) // before
setInterval('console.log("z")') // after

## Variables
---

### Use placeholder arguments instead of var

Save bytes on the `var` declaration by putting placeholder arguments in the function declaration.

function(a){var b=1;...} // before
function(a,b){b=1;...}   // after

Please be careful as sometimes var declaration is shorter. Take the right decision in each case.

function(a,b,c,d){b=1;c=2;d=3;...} // before
function(a){var b=1,c=2,d=3;...}   // after

### Re-use variables where possible

Careful reuse of a variable that is no longer needed can save bytes.

setTimeout(function(){for(var i=10;i--;)... }, a) // before
setTimeout(function(){for(a=10;a--;)... }, a)     // after

### Assign wherever possible

Since assignment returns the assigned value, perform assignment and evaluation at the same time to save bytes. A good example of this is @jed's JSONP function, where the string script is assigned in the createElement method.

a=this.localStorage;if(a){...} // before
if(a=this.localStorage){...}   // after

### Use an array to swap variables

An array can be used as a temporary placeholder to avoid declaring another variable.

var a=1,b=2,c;c=a;a=b;b=c // before
var a=1,b=2;a=[b,b=a][0]  // after
var a=1,b=2;a=b^a^(b=a)   // after - not as useful, but can come in handy

Alternatively, for numbers you can save another two bytes:

var a=1,b=2;a=[b,b=a][0]  // before
var a=1,b=2;a+=b-(b=a)    // after

### Exploit coercion

JavaScript coercion is a blessing and a curse, but sometimes it can be very useful. @jed's pubsub function decrements a negative variable, and then concatenates the results with a string, resulting in a string like someString-123, which is exploited later by using the hyphen as a split token to return the original string.

### Choose small data format

Required data will often be represented as Array or Object. In many cases, these byte-hungry formats can be replaced by strings. The Date.parse polyfill shows a great example of a conversion table that'd usually be an Object.

## Loops
---

### Omit loop bodies

If you can perform all the logic you need within the conditional part of a loop, you don't need the loop body. For an example, see @jed's timeAgo function.

### Use for over while

`for` and `while` require the same number of bytes, but for gives you more control and assignment opportunity.

while(i--){...} // before
for(;i--;){...} // after

i=10;while(i--){...} // before
for(i=10;i--;){...}  // after

FYI, the second argument to a for-loop can be omitted, too - it will only stop the loop if it returns anything false-y at all.

### Use index presence to iterate arrays of truthy items

When iterating over an array of objects that you know are truthy, short circuit on object presence to save bytes.

for(a=[1,2,3,4,5],l=a.length,i=0;i<l;i++){b=a[i];...}
for(a=[1,2,3,4,5],i=0;b=a[i++];){...}

### Use for..in with assignment to get the keys of an object

a=[];i=0;for(b in window)a[i++]=b // before
a=[];i=0;for(a[i++]in window)     // after
a=Object.keys(window)             // ES6 (not same as key in window, only returns own)

Coercion Hint: you can coerce the counter from an array: `i=a=[];for(a[i++]in window);`

### Use reverse loops where possible

If an array can be iterated reversely, it may save some bytes:

for(a=0;a<x.length;a++)...     // before
for(a=x.length;a--;)...        // after

Use both for body and counting expression for multiple operations

for(i=3;i--;foo(),bar());   // before
for(i=3;i--;)foo(),bar();   // before
for(i=3;i--;bar())foo();    // after
for..in will not iterate over false - use this to trigger iteration

If for..in encounters anything but an object (or string in any browser but ye olde IE), e.g. false or 0, it will silently continue without iteration.

if(c)for(a in b)x(b[a]); // before
for(a in c&&b)x(b[a]);   // after

## Operators
---
### Understand operator precedence

This Mozilla page is an excellent resource to get started.

### Understand bitwise operator hacks

### Use `~` with indexOf to test presence

hasAnF="This sentence has an f.".indexOf("f")>=0 // before
hasAnF=~"This sentence has an f.".indexOf("f")   // after

### Use `,` to chain expressions on one conditional line

with(document){open();write("hello");close()}
with(document)open(),write("hello"),close()

### Use `[]._` instead of undefined

`""._, 1.._` and `0[0]` also work, but are slower. void 0 is faster than undefined but longer than the alternatives.

### Remove unnecessary space after an operator

Whitespace isn't always needed after an operator and may sometimes be omitted:

typeof [] // before
typeof[]  // after

## Numbers
---

###Use `~~` and `0|` instead of `Math.floor` for positive numbers

Both of these operator combos will floor numbers (note that since ~ has lower precedence than |, they are not identical).

rand10=Math.floor(Math.random()*10) // before
rand10=0|Math.random()*10           // after

If you are flooring a quotient where the divisor is a multiple of 2, a bit-shift-right will perform both operations in one statement:

Math.floor(a/2) // before
a>>1            // after

Math.floor(a / 4) // before
a>>2            // after
Use A + 0.5 | 0 instead of Math.round for positive numbers

Math.round(a) // before
a+.5|0        // after

Also, for negative number just change `+.5|0 to -.5|0`

Math.round(-a) // before
-a-.5|0        // after

### Use AeB format for large denary numbers

This is equivalent to `A*Math.pow(10,B)`.

million=1000000 // before
million=1e6     // after

Use `A<<B` format for large binary numbers

This is equivalent to `A*Math.pow(2,B)`. See @jed's [rgb2hex](https://gist.github.com/983535) for an example.

color=0x100000 // before
color=1<<20    // after

### Use `1/0` instead of Infinity

It's shorter. Besides, division by zero gets you free internet points.

[Infinity,-Infinity] // before
[1/0,-1/0]           // after

### Use division instead of isFinite()

Division of 1 by any finite number results nonzero "truthy" value.

if(isFinite(a)) // before
if(1/a)         // after

### Exploit the "falsiness" of 0

When comparing numbers, it's often shorter to munge the value to 0 first.

a==1||console.log("not one") // before
~-a&&console.log("not one")  // after

### Use `~` to coerce any non-number to -1,

Used together with the unary -, this is a great way to increment numerical variables not yet initialized. This is used on @jed's JSONP implementation.

i=i||0;i++ // before
i=-~i      // after

It can also be used to decrement a variable by flipping around the negation and complement:

i=i||0;i-- // before
i=~-i      // after

### Use ^ to check if numbers are not equal

if(a!=123) // before
if(a^123) // after

### Use number base for character to number conversion

`parseInt(n, 36)` is not only a very small character to number conversion, it also has the added value of being case-insensitive, which may save a .toLowerCase(), like in subzey's parseRoman function.

### Use current date to generate random integers

As seen in aemkei\'s Tetris game.

i=0|Math.random()*100 // before
i=new Date%100 // after

_Note: Do not use in fast loops, because the milliseconds might not change!_

## Strings
---

### Prefer `slice` over `substr` over `substring`

Prefer `slice(start,stop)` over `substr(start,length)` over `substring(start,stop)`. Omit the second parameter to fetch everything to the end of the string. Do not use negative positions. It may be shorter (e.g. s.substr(-n) fetches the last n characters) but does not work in Internet Explorer (including version 9).

### Split using ''

Use `s.split('')` to create a character array from a string. Unfortunately you can not use s[i] to access the characters in the string. This does not work in Internet Explorer (including version 9).

### Split using 0

Save two bytes by using a number as a delimiter in a string to be split, as seen in @jed's timeAgo function.

"alpha,bravo,charlie".split(",") // before
"alpha0bravo0charlie".split(0)   // after

### Use the little-known .link method

Strings have a built-in .link method that creates an HTML link. This is used in @jed's linkify function.

html=""+text+"" // before
html=text.link(url)                   // after

Strings also have several other methods related to HTML, as documented here.

### Use `.search` instead of `.indexOf`

First, because this RegExp implicit is 1 byte shorter, but you get the added value of coercion of undefined to /undefined/ instead of '' being matched at position zero. This is used in @atk's base64decoder function.

Warning: This will fail when you search with an invalid regular expression. For example, '.' as /./ matches any character, '+' as /+/ gives an error so you'd want to ensure you know what the value is.

### Use `.replace` or `.exec` for powerful string iteration

Since the .replace method can take a function as its second argument, it can handle a lot of iteration bookkeeping for you. You can see this exploited in @jed's templates and UUID functions.

### Use `Array` to repeat a string

for(a="",i=32;i--;)a+=0 // before
a=Array(33).join(0)     // after
a="0".repeat(32)        // ES6

## Conditionals
---

### Use `&&` and `||` where possible

if(a)if(b)return c // before
return a&&b&&c     // after

if(!a)a=Infinity // before
a=a||Infinity    // after

### Coercion to test for types

Instead of using typeof `x=='string'`, you can use `''+x===x`.

Instead of using typeof `x=='number'`, you can use `+x===x`. `+x` will coerce x to a number or NaN, so if it is anything else but a number, this will turn false. Warning: If someone goes really crazy on the prototypes, this will probably fail.

Instead of using typeof `x=='function'`, you can use `/^f/.test(typeof x)` as in @tkissing's template engine.

### Type-specific methods to test for types

Another way to test types is to check if type-specific methods are available. (Seen on @adius DOMinate)

Test the variable x with the shortest type specific method:

| Type | Test |
| String | x.big |
| Number | x.toFixed |
|Array | x.pop (x.map works on fewer browsers) |
| Function | x.call |
| textNode | x.data |

This technique is even faster than string comparison!

**Warning:** This will lead to wrong results if properties or methods with those names were added.

## Arrays
---

### Use elision

Array elision can be used in some cases to save bytes. See @jed's router API for a real-world example.

[undefined,undefined,2] // before
[,,2]                   // after

// Note: Be mindful of elided elements at the end of the element list
[2,undefined,undefined] // before length is 3
[2,,]                   // after length is 2

You may notice that the undefined turns empty. In fact, when we coerce an array into a string, the undefined turns to empty string. See one exploitation from @aemkei's Digital Segment Display

b="";b+=x // before
b=[b]+x   // after
// Bonus: b=x+[b] uses same bytes as b=[b]+x, while b="";b=x+b uses one more byte over b="";b+=x.
Another exploitation is also useful:

((b=[1,2][a])?b:'') // before
[[1,2][a]]          // after

### Use coercion to do .join(',')

You can use `''+array` instead of `array.join(',')` since the default separator of arrays is `","`.

Warning: this will only work if the contents of the Array are true-ish (except false) and consist of Strings (will not be quoted!), Numbers or Booleans, Objects and Arrays within arrays may lead to unwanted results:

''+[1,true,false,{x:1},0,'',2,['test',2]]
// "1,true,false,[object Object],0,,2,test,2"

### String coercion with array literal []

''+1e3+3e7 // before
[1e3]+3e7  // after

See @jed's [UUID](https://gist.github.com/982883) function.

### Use coercion to build strings with commas in them

"rgb("+(x+8)+","+(y-20)+","+z+")"; // before
"rgb("+[x+8,y-20,z]+")";           // after

Or if the first or last values are static:

"rgb(255,"+(y-20)+",0)"; // before
"rgb(255,"+[y-20,"0)"];  // after

### Use Arrays as Objects

When you need to return an Object, re-use an already declared Array to store properties. An Array is of type 'object', after all. Make sure the field names don't collide with any of Array's intrinsic properties.

### Test if Array has Several Elements

You can write if(array[1]) instead of if(array.length > 1).

Warning: This doesn't work when the item array[1] is falsy! So only use it when you can be sure that it's not. You can use if(1 in array) in that case.

## Regular Expressions
---

### Use shortcuts

`\d` is short for `[0-9]` and `\w` is short for `[A-Za-z0-9_]`. `\s` matches whitespace. Upper case shortcuts are inverted, e.g. `\D` matches non-digits. You can use these shortcuts inside character classes, e.g. `[\dA-F]` matches hex characters.

`\b` does not match a character but a word boundary where a word and a non-word character met (or vice versa). \B matches everywhere except at word boundaries. Some other shortcuts do not work, e.g. \Q...\E. For a full list check the ECMA column in the Regular Expression Flavor Comparison.

`/a|b/` is the same as `/(a|b)/`.

Sometimes it's shorter to use `<.*?>` (ungreedy matching) instead of `<[^>]*>` to match (for example) an HTML tag. But this may also change the runtime and behavior of the regular expression in rare cases.

In the replacement string, $& refers to the entire match and `$`` and `$'` refer to everything before and after the match, so `/(x)/,'$1'` can be replaced with `/x/,'$&'`.

### Denormalize to shorten

While `/\d{2}/` looks smarter, `/\d\d/` is shorter.

### Don't escape

In many cases almost no escaping (with `\`) is needed even if you are using characters that have a meaning in regular expressions. For example, `[[\]-]` is a character class with the three characters `[, ]` (this needs to be escaped) and `-` (no need to escape this if it's the last character in the class).

### eval() for a regexp literal can be shorter than RegExp()

Prefer `/\d/g` over `new RegExp('\\d','g')` if possible. If you need to build a regular expression at runtime, consider using `eval()`.

// we escape the first curly bracket so if `p` is a number it won't be
// interpreted as an invalid repetition operator.
r=new RegExp("\\\\{"+p+"}","g") // before
r=eval("/\\\\{"+p+"}/g")    // after

### eval() around String.replace() instead of callback

If a callback is used to achieve a certain effect on the output, one can use replace to build the expression that achieves the same effect and evaluate it (the more complicated the matches are, the less this will help):

x.replace(/./,function(c){m=m+c.charCodeAt(0)&255})  // before
eval(x.replace(/./,'m=m+"$&".charCodeAt(0)&255;'))   // after

## Booleans
---

### Use ! to create booleans

true and false can be created by combining the ! operator with numbers.

[true,false] // before
[!0,!1]      // after

Boolean coercion can be useful, too. If coerced to Number (e.g. by prefixing a +), true will coerce to 1, false to 0. So a program that will test one condition to output 2 and another one to output 1 and 0 if none is met, can be reduced:

x>7?2:x>4?1:0 // before
+(x>7)+(x>4)  // after

One way that minifiers are able to shave bytes off of JavaScript code is changing the way booleans are used, from David Walsh blog:

true === !0 // before, save 2 chars
false === !1 // after, save 3 chars

## Functions
---

### Shorten function names

Assign prototype functions to short variables. This may also be faster in more complex cases.

a=Math.random(),b=Math.random() // before
r=Math.random;a=r(),b=r()       // after

### Use named functions for recursion

Recursion is often more terse than looping, because it offloads bookkeeping to the stack. This is used in @jed's walk function.

### Use named functions for saving state

If state needs to be saved between function calls, name the function and use it as a container. This is used for a counter in @jed's JSONP function.

function(i){return function(){console.log("called "+(++i)+" times")}}(0) // before
(function a(){console.log("called "+(a.i=-~a.i)+" times")})           // after
0,function a(){console.log("called "+(a.i=-~a.i)+" times")}           // another alternative

### Omit () on new calls w/o arguments

new Object is equivalent to new Object()

now = +new Date() // before
now = +new Date   // after

### Omit the new keyword when possible

Some constructors don't actually require the new keyword.

r=new RegExp(".",g) // before
r=RegExp(".",g)     // after

l=new Function("x","console.log(x)") // before
l=Function("x","console.log(x)")     // after

### The return statement

When returning anything but an expression starting with an alphanumeric character, there's no need to use a space after return:

return ['foo',42,'bar']; // before
return['foo',42,'bar'];  // after
return {x:42,y:417}; // before
return{x:42,y:417};  // after
return .01; // before
return.01;  // after

### Use the right closure for the job

If you need to execute a function instantly, use the most appropriate closure.

;(function(){...})() // before
new function(){...}  // after, if you plan on returning an object and can use `this`
!function(){...}()   // after, if you don't need to return anything

### Shorten function with Function

This is most useful with multiple function calls. However, both parameters must be strings, which may be a good or bad thing, so use this wisely.

function a(a){return a}
function b(b){return b}
function c(c){return c} //before

var f=Function,
a=f('a','return a'),
b=f('b','return b'),
c=f('c','return c') //after

## In the browser
---

### Use browser objects to avoid logic

Instead of writing your own logic, you can use browser anchor elements to parse URLs as in @jed's parseURL, and text nodes to escape HTML as in @eligrey's escapeHTML.

### Use global scope

Since window is the global object in a browser, you can directly reference any property of it. This is well known for things like document and location, but it's also useful for other properties like innerWidth, as shown in @bmiedlar's screensaver.

### A better way to getElementById()

Saves 27 bytes.

document.getElementById('a').innerHTML = "foo"; // before
a.innerHTML = "foo"; // after

### Delimiters

Only use ; where necessary. Encapsulate in other statements if possible, e.g.

x=this;a=[].slice.call(arguments,1); // before
a=[x=this].slice.call(arguments,1);  // after

## APIs
---

### Pass static data via argument where possible

### Use extra bytes to provide default values

### Do one thing and do it well

## Other resources

+ Ben Alman's explanation of his JS1K entry
+ Marijn Haverbeke's explanation of his JS1K entry
+ Martin Kleppe's presentation about his 140byt.es and JS1K entries
+ Suggested Closure Compiler optimizations
+ Angus Croll's blog
+ Aivo Paas's jscrush
+ Cody Brocious's post on superpacking JS demos

## References

+ [140bytes](https://github.com/jed/140bytes/wiki/Byte-saving-techniques)


text:
struct Foo;

impl Foo {
    fn foo(self: *const Self) {}
    //~^ ERROR `*const Foo` cannot be used as the type of `self` without
}

trait Bar {
    fn bar(self: *const Self);
    //~^ ERROR `*const Self` cannot be used as the type of `self` without
}

impl Bar for () {
    fn bar(self: *const Self) {}
    //~^ ERROR `*const ()` cannot be used as the type of `self` without
}

fn main() {}


text:
module Smooth
  Version = '0.0.7'
  Name = 'Smooth.io'
  Description = 'Smooth makes it extremely easy to build a backend for your web and mobile apps.'
end


text:
Two player 2D game created with Love2D

You will need to download the game engine here: https://www.love2d.org/

You can run the game by simply dragging whole game directory onto love app.

<img src="https://github.com/cohadar/snakes-of-twilight/blob/master/screenshot.png">


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Radoslav Mladenov | Web Designer / Developer</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

    <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet">

    <link href="css/creative.min.css" rel="stylesheet">

    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                 Radoslav Mladenov

                        About

                        Services

                        Portfolio

                        Contact

WEB DEVELOPER

                Contact

We've got what you need!

At Your Service

PORTFOLIO

                                    Category

                                    Wedding site

                                    Category

                                    Wordpress site

                                    Category

                                    Under Construction

Let's Get In Touch!

+359889716708

r.mladenovbg@gmail.com


text:
<!DOCTYPE html>

<title>File System API demo</title>

File System API Demos

Persistent File System

show Persistent Root

<textarea id="p_text" rows="5" cols="40"></textarea>

save to Persistent "foo.txt"

load from Persistent "foo.txt"

Temporary File System

show Temporary Root

<textarea id="t_text" rows="5" cols="40"></textarea>

save to Temporary "foo.txt"

load from Temporary "foo.txt"


text:
class GeneratorExamples {
  *stmt_yield(): Generator<number, void, void> {
    yield 0; // ok
    yield ""; // error: string ~> number
  }

  *stmt_next(): Generator<void, void, number> {
    var a = yield;
    if (a) {
      (a : number); // ok
    }

    var b = yield;
    if (b) {
      (b : string); // error: number ~> string
    }
  }

  *stmt_return_ok(): Generator<void, number, void> {
    return 0; // ok
  }

  *stmt_return_err(): Generator<void, number, void> {
    return ""; // error: string ~> number
  }

  *infer_stmt() {
    var x: ?boolean = yield 0;
    return "";
  }

  *widen_next() {
    var x = yield 0;
    if (x == null) {
    } else if (typeof x === "number") {
    } else if (typeof x === "boolean") {
    } else {
      (x : string) // ok, sherlock
    }
  }

  *widen_yield() {
    yield 0;
    yield "";
    yield true;
  }

  *delegate_next_generator() {
    function *inner() {
      var x: ?number = yield; // error: string ~> number
    }
    yield *inner();
  }

  *delegate_yield_generator() {
    function *inner() {
      yield "";
    }

    yield *inner();
  }

  *delegate_return_generator() {
    function *inner() {
      return "";
    }

    var x: number = yield *inner(); // error: string ~> number
  }

  // only generators can make use of a value passed to next
  *delegate_next_iterable(xs: Array<number>) {
    yield *xs;
  }

  *delegate_yield_iterable(xs: Array<number>) {
    yield *xs;
  }

  *delegate_return_iterable(xs: Array<number>) {
    var x: void = yield *xs // ok: Iterator has no yield value
  }

  *generic_yield<Y>(y: Y): Generator<Y,void,void> {
    yield y;
  }

  *generic_return<R>(r: R): Generator<void,R,void> {
    return r;
  }

  *generic_next<N>(): Generator<void,N,N> {
    var n = yield undefined;
    invariant(n != null);
    return n;
  }
}

var examples = new GeneratorExamples();

for (var x of examples.infer_stmt()) { (x : string) } // error: number ~> string

// We miss reporting an error number ~> boolean from the arg passed in the next
// call (below) to x in the infer_stmt function (above) via yield. This is a
// bug, arising due to a bad interaction between generics and union types (which
// appear in the signature of iterators, which in turn generators depend on). In
// particular, the error reappears when the iteration in the above line is
// commented.
var infer_stmt_next = examples.infer_stmt().next(0).value;
if (typeof infer_stmt_next === "undefined") {
} else if (typeof infer_stmt_next === "number") {
} else {
  (infer_stmt_next : boolean) // error: string ~> boolean
}

examples.widen_next().next(0)
examples.widen_next().next("")
examples.widen_next().next(true)

for (var x of examples.widen_yield()) {
  if (typeof x === "number") {
  } else if (typeof x === "boolean") {
  } else {
    (x : string) // ok, sherlock
  }
}

examples.delegate_next_generator().next("");

for (var x of examples.delegate_yield_generator()) {
  (x : number) // error: string ~> number
}

examples.delegate_next_iterable([]).next(""); // error: Iterator has no next value

for (var x of examples.delegate_yield_iterable([])) {
  (x : string) // error: number ~> string
}


text:
A [cookiecutter](https://github.com/audreyr/cookiecutter) template for Django 1.10 / Python 3 only, that is *really* optimized for running on twelve-factor-app platforms (like Heroku or DigitalOcean).

[![Build status](https://travis-ci.org/dulacp/cookiecutter-django-herokuapp.svg?branch=master)](https://travis-ci.org/dulacp/cookiecutter-django-herokuapp?branch=master)

## Concept

I tried to be minimalistic, I mean no choice has been made concerning :
- **the css library**, specify which one you want in the bower.json file
- **external django apps**, I don't see the point to choose this for you ;)

In fact the only choice made here is deploying on a [Twelve-Factor App Platform](http://12factor.net/).

## Requirements

This cookiecutter template uses features that exists only in cookiecutter 0.9.0 or higher.

## Features
---------

- Python 3 only, sorry guys but I had to move on...
- For [Django 1.10](https://docs.djangoproject.com/en/1.10/)
- Heroku optimized stack
- Gulp tasks to build the static files and support livereload
- Static served by `whitenoise` from the django app (advice to setup a cache instance above like CloudFlare)
- Instructions on how to configure the Amazon S3 bucket
- Instructions on how to deploy the app in less than 5 minutes

## Q&A

#### Why using `waitress` as the production server
> Gunicorn is actually designed to be used behing a buffering reverse proxy (e.g. nginx). In other words, without this buffering reverse proxy you expose your production server to a *slow network* attacks. If you want to dig on this particular topic, read the great article of @etianen *[Don't use Gunicorn to host your Django sites on Heroku](http://blog.etianen.com/blog/2014/01/19/gunicorn-heroku-django/)*

## Usage

First, get cookiecutter.

```sh
$ pip install cookiecutter
```

Now run it against this repo.

```sh
$ cookiecutter https://github.com/dulacp/cookiecutter-django-herokuapp.git
```

You'll be prompted for some questions, answer them, then it will create a Django project for you.

## Static handling

### Live reloading and Sass CSS compilation

You can take advantage of live reloading and Sass / Compass CSS compilation with the included Gulp tasks.

Make sure that [nodejs](http://nodejs.org/download/) is installed. Then in the project root run :

```sh
$ npm install
```

Now you just need :

```sh
$ gulp launch
```

Now your turn !


text:
package google_api

import proto "github.com/gogo/protobuf/proto"
import fmt "fmt"
import math "math"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// ### System parameter configuration
//
// A system parameter is a special kind of parameter defined by the API
// system, not by an individual API. It is typically mapped to an HTTP header
// and/or a URL query parameter. This configuration specifies which methods
// change the names of the system parameters.
type SystemParameters struct {
	// Define system parameters.
	//
	// The parameters defined here will override the default parameters
	// implemented by the system. If this field is missing from the service
	// config, default system parameters will be used. Default system parameters
	// and names is implementation-dependent.
	//
	// Example: define api key for all methods
	//
	//     system_parameters
	//       rules:
	//         - selector: "*"
	//           parameters:
	//             - name: api_key
	//               url_query_parameter: api_key
	//
	//
	// Example: define 2 api key names for a specific method.
	//
	//     system_parameters
	//       rules:
	//         - selector: "/ListShelves"
	//           parameters:
	//             - name: api_key
	//               http_header: Api-Key1
	//             - name: api_key
	//               http_header: Api-Key2
	//
	// **NOTE:** All service configuration rules follow "last one wins" order.
	Rules []*SystemParameterRule `protobuf:"bytes,1,rep,name=rules" json:"rules,omitempty"`
}

func (m *SystemParameters) Reset()                    { *m = SystemParameters{} }
func (m *SystemParameters) String() string            { return proto.CompactTextString(m) }
func (*SystemParameters) ProtoMessage()               {}
func (*SystemParameters) Descriptor() ([]byte, []int) { return fileDescriptorSystemParameter, []int{0} }

func (m *SystemParameters) GetRules() []*SystemParameterRule {
	if m != nil {
		return m.Rules
	}
	return nil
}

// Define a system parameter rule mapping system parameter definitions to
// methods.
type SystemParameterRule struct {
	// Selects the methods to which this rule applies. Use '*' to indicate all
	// methods in all APIs.
	//
	// Refer to [selector][google.api.DocumentationRule.selector] for syntax details.
	Selector string `protobuf:"bytes,1,opt,name=selector,proto3" json:"selector,omitempty"`
	// Define parameters. Multiple names may be defined for a parameter.
	// For a given method call, only one of them should be used. If multiple
	// names are used the behavior is implementation-dependent.
	// If none of the specified names are present the behavior is
	// parameter-dependent.
	Parameters []*SystemParameter `protobuf:"bytes,2,rep,name=parameters" json:"parameters,omitempty"`
}

func (m *SystemParameterRule) Reset()         { *m = SystemParameterRule{} }
func (m *SystemParameterRule) String() string { return proto.CompactTextString(m) }
func (*SystemParameterRule) ProtoMessage()    {}
func (*SystemParameterRule) Descriptor() ([]byte, []int) {
	return fileDescriptorSystemParameter, []int{1}
}

func (m *SystemParameterRule) GetSelector() string {
	if m != nil {
		return m.Selector
	}
	return ""
}

func (m *SystemParameterRule) GetParameters() []*SystemParameter {
	if m != nil {
		return m.Parameters
	}
	return nil
}

// Define a parameter's name and location. The parameter may be passed as either
// an HTTP header or a URL query parameter, and if both are passed the behavior
// is implementation-dependent.
type SystemParameter struct {
	// Define the name of the parameter, such as "api_key" . It is case sensitive.
	Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
	// Define the HTTP header name to use for the parameter. It is case
	// insensitive.
	HttpHeader string `protobuf:"bytes,2,opt,name=http_header,json=httpHeader,proto3" json:"http_header,omitempty"`
	// Define the URL query parameter name to use for the parameter. It is case
	// sensitive.
	UrlQueryParameter string `protobuf:"bytes,3,opt,name=url_query_parameter,json=urlQueryParameter,proto3" json:"url_query_parameter,omitempty"`
}

func (m *SystemParameter) Reset()                    { *m = SystemParameter{} }
func (m *SystemParameter) String() string            { return proto.CompactTextString(m) }
func (*SystemParameter) ProtoMessage()               {}
func (*SystemParameter) Descriptor() ([]byte, []int) { return fileDescriptorSystemParameter, []int{2} }

func (m *SystemParameter) GetName() string {
	if m != nil {
		return m.Name
	}
	return ""
}

func (m *SystemParameter) GetHttpHeader() string {
	if m != nil {
		return m.HttpHeader
	}
	return ""
}

func (m *SystemParameter) GetUrlQueryParameter() string {
	if m != nil {
		return m.UrlQueryParameter
	}
	return ""
}

func init() {
	proto.RegisterType((*SystemParameters)(nil), "google.api.SystemParameters")
	proto.RegisterType((*SystemParameterRule)(nil), "google.api.SystemParameterRule")
	proto.RegisterType((*SystemParameter)(nil), "google.api.SystemParameter")
}

func init() { proto.RegisterFile("google/api/system_parameter.proto", fileDescriptorSystemParameter) }

var fileDescriptorSystemParameter = []byte{
	// 251 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x90, 0xcd, 0x4a, 0x03, 0x31,
	0x14, 0x85, 0x99, 0x69, 0x15, 0xbd, 0x05, 0x7f, 0x6e, 0x5d, 0x04, 0x5d, 0xb4, 0xce, 0xaa, 0xab,
	0x0c, 0x28, 0xae, 0x5c, 0xd9, 0x8d, 0x76, 0x37, 0x8e, 0x0f, 0x30, 0xc4, 0x7a, 0x69, 0x0b, 0x99,
	0x26, 0xde, 0x24, 0x42, 0x5f, 0xc7, 0x27, 0x95, 0x49, 0x75, 0x5a, 0x06, 0xe9, 0x2e, 0xb9, 0xe7,
	0x83, 0xef, 0x70, 0xe0, 0x76, 0x61, 0xcc, 0x42, 0x53, 0xae, 0xec, 0x2a, 0x77, 0x1b, 0xe7, 0xa9,
	0xae, 0xac, 0x62, 0x55, 0x93, 0x27, 0x96, 0x96, 0x8d, 0x37, 0x08, 0x5b, 0x44, 0x2a, 0xbb, 0xca,
	0x66, 0x70, 0xf1, 0x16, 0xa9, 0xe2, 0x0f, 0x72, 0xf8, 0x00, 0x47, 0x1c, 0x34, 0x39, 0x91, 0x8c,
	0x7b, 0x93, 0xc1, 0xdd, 0x48, 0xee, 0x78, 0xd9, 0x81, 0xcb, 0xa0, 0xa9, 0xdc, 0xd2, 0xd9, 0x1a,
	0x86, 0xff, 0xa4, 0x78, 0x0d, 0x27, 0x8e, 0x34, 0xcd, 0xbd, 0x61, 0x91, 0x8c, 0x93, 0xc9, 0x69,
	0xd9, 0xfe, 0xf1, 0x11, 0xa0, 0x2d, 0xe7, 0x44, 0x1a, 0x75, 0x37, 0x87, 0x74, 0x7b, 0x78, 0xf6,
	0x05, 0xe7, 0x9d, 0x18, 0x11, 0xfa, 0x6b, 0x55, 0xd3, 0xaf, 0x27, 0xbe, 0x71, 0x04, 0x83, 0xa5,
	0xf7, 0xb6, 0x5a, 0x92, 0xfa, 0x20, 0x16, 0x69, 0x8c, 0xa0, 0x39, 0xbd, 0xc4, 0x0b, 0x4a, 0x18,
	0x06, 0xd6, 0xd5, 0x67, 0x20, 0xde, 0xec, 0xb6, 0x12, 0xbd, 0x08, 0x5e, 0x06, 0xd6, 0xaf, 0x4d,
	0xd2, 0x4a, 0xa6, 0x39, 0x9c, 0xcd, 0x4d, 0xbd, 0xd7, 0x72, 0x7a, 0xd5, 0xe9, 0x51, 0x34, 0x33,
	0x17, 0xc9, 0x77, 0xda, 0x7f, 0x7e, 0x2a, 0x66, 0xef, 0xc7, 0x71, 0xf6, 0xfb, 0x9f, 0x00, 0x00,
	0x00, 0xff, 0xff, 0xc9, 0x8a, 0x6c, 0x74, 0x9b, 0x01, 0x00, 0x00,
}


text:
Provides a HTTP v1.1 docset for [Dash](http://kapeli.com/dash). To install this
docset, simply clone it to your local disk and add it to Dash.


text:
/**
 * ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
 * @version v20.2.0
 * @link http://www.ag-grid.com/
 * @license MIT
 */
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("../utils");
function simpleHttpRequest(params) {
    return new utils_1.Promise(function (resolve) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', params.url);
        httpRequest.send();
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                var httpResponse = JSON.parse(httpRequest.responseText);
                resolve(httpResponse);
            }
        };
    });
}
exports.simpleHttpRequest = simpleHttpRequest;


text:
package io.opensec.six.oval.model.results;

import io.opensec.six.oval.model.common.ClassEnumeration;
import org.mongodb.morphia.annotations.Property;

/**
 * The ClassDirectives presents a set of flags that describe
 * what information has been included in the results document
 * for a specific OVAL Definition class.
 *
 * @author  Akihito Nakamura, AIST
 * @see OVAL Language
 */
public class ClassDirectivesType
    extends DirectivesType
{

    @Property( "class" )
    private ClassEnumeration  definition_class;
    //{required}

    /**
     * Constructor.
     */
    public ClassDirectivesType()
    {
    }

    /**
     * Constructor.
     */
    public ClassDirectivesType(
                    final ClassEnumeration definitionClass,
                    final DirectiveType definitionTrue,
                    final DirectiveType definitionFalse,
                    final DirectiveType definitionUnknown,
                    final DirectiveType definitionError,
                    final DirectiveType definitionNotEvaluated,
                    final DirectiveType definitionNotApplicable
                    )
    {
        super(
                        definitionTrue,
                        definitionFalse,
                        definitionUnknown,
                        definitionError,
                        definitionNotEvaluated,
                        definitionNotApplicable
        );

        setDefinitionClass( definitionClass );
    }

    /**
     */
    public void setDefinitionClass(
                    final ClassEnumeration definition_class
                    )
    {
        this.definition_class = definition_class;
    }

    public ClassEnumeration getDefinitionClass()
    {
        return definition_class;
    }

    //**************************************************************
    //  java.lang.Object
    //**************************************************************

    @Override
    public int hashCode()
    {
        final int  prime = 37;
        int  result = super.hashCode();

        ClassEnumeration  definitionClass = getDefinitionClass();
        result = prime * result + ((definitionClass == null) ? 0 : definitionClass.hashCode());

        return result;
    }

    @Override
    public boolean equals(
                    final Object obj
                    )
    {
        if (!(obj instanceof ClassDirectivesType)) {
            return false;
        }

        if (super.equals( obj )) {
            ClassDirectivesType  other = (ClassDirectivesType)obj;
            if (getDefinitionClass() == other.getDefinitionClass()) {
                return true;
            }
        }

        return false;
    }

}
// ClassDirectivesType


text:
from gbdxtools.rda.util import deprecation

class Deprecations(object):
    pass


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.eboji.persist.dao.GgRoomMemMapper" >
  <resultMap id="BaseResultMap" type="com.eboji.persist.pojo.GgRoomMem" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="k" property="k" jdbcType="VARCHAR" />
    <result column="v" property="v" jdbcType="VARCHAR" />
    <result column="status" property="status" jdbcType="INTEGER" />
    <result column="createdate" property="createdate" jdbcType="TIMESTAMP" />
    <result column="modifydate" property="modifydate" jdbcType="TIMESTAMP" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    id, k, v, `status`, createdate, modifydate
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.eboji.persist.pojo.GgRoomMemExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from gg_room_mem
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select
    <include refid="Base_Column_List" />
    from gg_room_mem
    where id = #{id,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from gg_room_mem
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <delete id="deleteByExample" parameterType="com.eboji.persist.pojo.GgRoomMemExample" >
    delete from gg_room_mem
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.eboji.persist.pojo.GgRoomMem" useGeneratedKeys="true" keyProperty="id" >
    insert into gg_room_mem (k, v, `status`,
      createdate, modifydate)
    values (#{k,jdbcType=VARCHAR}, #{v,jdbcType=VARCHAR}, #{status,jdbcType=INTEGER},
      #{createdate,jdbcType=TIMESTAMP}, #{modifydate,jdbcType=TIMESTAMP})
  </insert>
  <insert id="insertSelective" parameterType="com.eboji.persist.pojo.GgRoomMem" useGeneratedKeys="true" keyProperty="id" >
    insert into gg_room_mem
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="k != null" >
        k,
      </if>
      <if test="v != null" >
        v,
      </if>
      <if test="status != null" >
        `status`,
      </if>
      <if test="createdate != null" >
        createdate,
      </if>
      <if test="modifydate != null" >
        modifydate,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="k != null" >
        #{k,jdbcType=VARCHAR},
      </if>
      <if test="v != null" >
        #{v,jdbcType=VARCHAR},
      </if>
      <if test="status != null" >
        #{status,jdbcType=INTEGER},
      </if>
      <if test="createdate != null" >
        #{createdate,jdbcType=TIMESTAMP},
      </if>
      <if test="modifydate != null" >
        #{modifydate,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.eboji.persist.pojo.GgRoomMemExample" resultType="java.lang.Integer" >
    select count(*) from gg_room_mem
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update gg_room_mem
    <set >
      <if test="record.id != null" >
        id = #{record.id,jdbcType=BIGINT},
      </if>
      <if test="record.k != null" >
        k = #{record.k,jdbcType=VARCHAR},
      </if>
      <if test="record.v != null" >
        v = #{record.v,jdbcType=VARCHAR},
      </if>
      <if test="record.status != null" >
        `status` = #{record.status,jdbcType=INTEGER},
      </if>
      <if test="record.createdate != null" >
        createdate = #{record.createdate,jdbcType=TIMESTAMP},
      </if>
      <if test="record.modifydate != null" >
        modifydate = #{record.modifydate,jdbcType=TIMESTAMP},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update gg_room_mem
    set id = #{record.id,jdbcType=BIGINT},
      k = #{record.k,jdbcType=VARCHAR},
      v = #{record.v,jdbcType=VARCHAR},
      `status` = #{record.status,jdbcType=INTEGER},
      createdate = #{record.createdate,jdbcType=TIMESTAMP},
      modifydate = #{record.modifydate,jdbcType=TIMESTAMP}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.eboji.persist.pojo.GgRoomMem" >
    update gg_room_mem
    <set >
      <if test="k != null" >
        k = #{k,jdbcType=VARCHAR},
      </if>
      <if test="v != null" >
        v = #{v,jdbcType=VARCHAR},
      </if>
      <if test="status != null" >
        `status` = #{status,jdbcType=INTEGER},
      </if>
      <if test="createdate != null" >
        createdate = #{createdate,jdbcType=TIMESTAMP},
      </if>
      <if test="modifydate != null" >
        modifydate = #{modifydate,jdbcType=TIMESTAMP},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.eboji.persist.pojo.GgRoomMem" >
    update gg_room_mem
    set k = #{k,jdbcType=VARCHAR},
      v = #{v,jdbcType=VARCHAR},
      `status` = #{status,jdbcType=INTEGER},
      createdate = #{createdate,jdbcType=TIMESTAMP},
      modifydate = #{modifydate,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=BIGINT}
  </update>
</mapper>


text:
package org.apache.camel.processor.interceptor;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;

/**
 * This test ensures non-regression for bug CAMEL-10322.
 */
public class AdviceWithWeaveByStringOnChoiceTest extends ContextTestSupport {

    @Test
    public void testWeaveByToStringShoultNotThrowUnsupportedOperationException() throws Exception {
        context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() {
            @Override
            public void configure() throws Exception {
                weaveByToString(".*mock:foo.*").replace().to("mock:bar");
            }
        });
        context.start();

        getMockEndpoint("mock:foo").expectedMessageCount(0);
        getMockEndpoint("mock:bar").expectedMessageCount(1);

        template.sendBody("direct:start", "Hello World");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start").choice().when(simple("true")).to("mock:foo");
            }
        };
    }

}


text:
package com.sequenceiq.cloudbreak.shell.converter;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.shell.core.Completion;
import org.springframework.shell.core.MethodTarget;

import com.sequenceiq.cloudbreak.shell.completion.PlatformVariant;
import com.sequenceiq.cloudbreak.shell.model.ShellContext;

public class PlatformVariantConverter extends AbstractConverter<PlatformVariant> {

    @Autowired
    private ShellContext context;

    public PlatformVariantConverter() {
    }

    @Override
    public boolean supports(Class<?> type, String optionContext) {
        return PlatformVariant.class.isAssignableFrom(type);
    }

    @Override
    public boolean getAllPossibleValues(List<Completion> completions, Class<?> targetType, String existingData, String optionContext, MethodTarget target) {
        try {
            return getAllPossibleValues(completions, context.getVariantsByPlatform(context.getActiveCloudPlatform()));
        } catch (Exception e) {
            return false;
        }
    }
}


text: Simple crossword creator program


text:
Remove records from FilesCollection and files from FS.

  - `selector` {*Object*} - See [Mongo Selectors](http://docs.meteor.com/#selectors)
  - `cb` {*Function*} - Callback, with one `error` argument
  - Returns {*FilesCollection*} - Current FilesCollection instance

```js
import { FilesCollection } from 'meteor/ostrio:files';

const Images = new FilesCollection({collectionName: 'Images'});

// Usage:
// Drop collection's data and remove all associated files from FS
Images.remove({});
// Remove particular file
Images.remove({_id: 'Rfy2HLutYK4XWkwhm'});
// Equals to above
Images.findOne({_id: 'Rfy2HLutYK4XWkwhm'}).remove();

// Direct Collection usage
// Remove record(s) ONLY from collection
Images.collection.remove({});

// Using callback
Images.remove({_id: 'Rfy2HLutYK4XWkwhm'}, (error) => {
  if (error) {
    console.error(`File wasn't removed, error:  ${error.reason}`);
  } else {
    console.info('File successfully removed');
  }
});
```

*Use onBeforeRemove to avoid unauthorized actions, for more info see [onBeforeRemove callback](https://github.com/VeliovGroup/Meteor-Files/wiki/Constructor#use-onbeforeremove-to-avoid-unauthorized-remove)*

```js
import { FilesCollection } from 'meteor/ostrio:files';

const Images = new FilesCollection({
  collectionName: 'Images',
  allowClientCode: true,
  onBeforeRemove(cursor) {
    const records = cursor.fetch();

    if (records && records.length) {
      if (this.userId) {
        const user = this.user();
        // Assuming user.profile.docs is array
        // with file's records _id(s)

        for (let i = 0, len = records.length; i < len; i++) {
          const file = records[i];
          if (!~user.profile.docs.indexOf(file._id)) {
            // Return false if at least one document
            // is not owned by current user
            return false;
          }
        }
      }
    }

    return true;
  }
});
```