text:
describe("REPLConsole", function() {
  SpecHelper.prepareStageElement();

  describe(".installInto()", function() {
    beforeEach(function() {
      this.elm = document.createElement('div');
      this.elm.innerHTML = '

';
      this.stageElement.appendChild(this.elm);
    });

    context("install console without options", function() {
      beforeEach(function() {
        this.console = REPLConsole.installInto('console');
      });
      it("should have data-prompt-label", function() {
        assert.equal(this.console.prompt, 'data-prompt-label');
      });
      it("should have data-remote-path", function() {
        assert.equal(this.console.remotePath, 'data-remote-path');
      });
    });

    context("install console with {remotePath: 'opt-remote-path'}", function() {
      beforeEach(function() {
        this.console = REPLConsole.installInto('console', {remotePath: 'opt-remote-path'});
      });
      it("should have opt-remote-path", function() {
        assert.equal(this.console.remotePath, 'opt-remote-path');
      });
    });
  });

  describe("#install()", function() {
    beforeEach(function() {
      this.elm = document.createElement("div");
      this.stageElement.appendChild(this.elm);
    });

    context("install console", function() {
      beforeEach(function() {
        var replConsole = new REPLConsole;
        replConsole.install(this.elm);
      });
      it("should have .console", function() {
        assert.ok(hasClass(this.elm, "console"));
      });
      it("should have a inner", function() {
        assert.equal(this.elm.getElementsByClassName("console-inner").length, 1);
      });
      it("should have a resizer", function() {
        assert.equal(this.elm.getElementsByClassName("resizer").length, 1);
      });
      it("should have a close button", function() {
        assert.equal(this.elm.getElementsByClassName("close-button").length, 1);
      });
    });
  });

  describe("console actions", function() {
    describe("close action", function() {
      beforeEach(function() {
        this.elm = document.createElement("div");
        this.elmId = this.elm.id = SpecHelper.randomString();
        this.stageElement.appendChild(this.elm);
        var replConsole = new REPLConsole;
        replConsole.install(this.elm);
      });

      context("click close button", function() {
        beforeEach(function() {
          var closeButton = this.elm.getElementsByClassName("close-button")[0];
          SpecHelper.triggerEvent(closeButton, "click");
        });
        it("should be removed from the parent node", function() {
          assert.isNull(document.getElementById(this.elmId));
        });
      });
    });
  });
});


text:
"""
Create a list.
Print list in Yaml format.
Print list in JSON format.
"""
import json
import yaml

myList = []

# create a list beginning with 10 nums.
for i in range(10):
    myList.append(i)

# Add a dict with 3 Australia states and with abbreviations
myList.append({'NSW': 'New South Wales', 'VIC': 'Victoria', 'TAS': 'Tasmansia'})

print "\nHere is my list:"
print myList

print "print in expanded YAML format to myList.yml\n"
with open("myList.yml", 'w') as f:
    f.write(yaml.dump(myList, default_flow_style=False))
f.close()

print "print in JSON format to myList.json\n"
with open("myList.json", 'w') as f:
    json.dump(myList, f)
f.close()

redpajama_set_name: RedPajamaGithub


text:
package org.apereo.cas.services.web;

import lombok.RequiredArgsConstructor;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.theme.AbstractThemeResolver;

import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This is {@link RequestHeaderThemeResolver}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
@RequiredArgsConstructor
public class RequestHeaderThemeResolver extends AbstractThemeResolver {
    private final String themeHeaderName;

    @Nonnull
    @Override
    public String resolveThemeName(final HttpServletRequest request) {
        val theme = request.getHeader(this.themeHeaderName);
        return StringUtils.defaultIfBlank(theme, getDefaultThemeName());
    }

    @Override
    public void setThemeName(
        @Nonnull
        final HttpServletRequest httpServletRequest,
        final HttpServletResponse httpServletResponse,
        final String theme) {
    }
}


text:
namespace utils {

    template<class T>
    class shared_vector {
    public:

        T pop() {
          boost::lock_guard<boost::mutex> lock(mutex);
          if (storage.empty()) {
            return T();
          }

          std::string val = storage.back();
          storage.pop_back();
          return val;
        }

        void push(T val) {
          boost::lock_guard<boost::mutex> lock(mutex);
          storage.push_back(val);
        }

        void reverse() {
          boost::lock_guard<boost::mutex> lock(mutex);
          std::reverse(storage.begin(), storage.end());
        }

        int size() {
          boost::lock_guard<boost::mutex> lock(mutex);
          return storage.size();
        }

    private:
        boost::mutex mutex;
        std::vector<T> storage;
    };

    class progress {
    public:

        int current_progress;
        int total;

        progress(int total_);

    public:

        void increment();

        void finish();

    private:

        void show_bar();

        boost::mutex mutex;

    };

    class parse_uri {
    public:

        std::string uri_scheme;
        std::string uri_domain;
        std::string uri_tld;
        std::string uri_path;

        const std::string &get_scheme() const;

        const std::string &get_domain() const;

        const std::string &get_path() const;

        const std::string &get_tld() const;

        parse_uri(const std::string &uri);

    private:

        int parse_scheme(int start, const std::string &uri);

        int parse_domains(int start, const std::string &uri);

        int parse_path(int start, const std::string &uri);

    };

    void fix_utf8_string(std::string &str);

}

#endif //EXTRACTOR_UTILS_COMMON_H


text:
import React from 'react';

class LoadPage extends React.Component {
  constructor (props) {
      super(props);
  }

  render () {
    let visibility = 'block';
    if (this.props.visibility === false) {
      visibility = 'none';
    }

    return (

    );
  }
}

LoadPage.propTypes = {
  visibility: React.PropTypes.bool
};

LoadPage.displayName = 'LoadPage';

export default LoadPage;


text:
package org.clafer.ast.analysis;

import java.util.HashMap;
import java.util.Map;
import org.clafer.assertion.Assertion;
import org.clafer.ast.AstBoolExpr;
import org.clafer.ast.AstCard;
import org.clafer.ast.AstChildRelation;
import org.clafer.ast.AstClafer;
import org.clafer.ast.AstCompare;
import org.clafer.ast.AstConcreteClafer;
import org.clafer.ast.AstConstant;
import org.clafer.ast.AstConstraint;
import org.clafer.ast.AstExpr;
import org.clafer.ast.AstExprRewriter;
import org.clafer.ast.AstGlobal;
import org.clafer.ast.AstIfThenElse;
import org.clafer.ast.AstJoin;
import org.clafer.ast.AstJoinParent;
import org.clafer.ast.AstJoinRef;
import org.clafer.ast.AstMembership;
import org.clafer.ast.AstNot;
import org.clafer.ast.AstSetExpr;
import org.clafer.ast.AstSetTest;
import org.clafer.ast.AstThis;
import org.clafer.ast.AstUpcast;
import static org.clafer.ast.Asts.compare;
import static org.clafer.ast.Asts.constant;
import static org.clafer.ast.Asts.equal;
import static org.clafer.ast.Asts.global;
import static org.clafer.ast.Asts.ifThenElse;
import static org.clafer.ast.Asts.join;
import static org.clafer.ast.Asts.membership;
import static org.clafer.ast.Asts.test;
import org.clafer.ast.Card;
import org.clafer.ast.ProductType;
import org.clafer.common.Util;
import org.clafer.objective.Objective;

/**
 * Optimizes the expressions inside the constraints. Assumes type checking has
 * already passed.
 *
 * @author jimmy
 */
public class OptimizerAnalyzer extends AstExprRewriter<Analysis> implements Analyzer {

    @Override
    public Analysis analyze(Analysis analysis) {
        Map<AstConstraint, AstBoolExpr> constraintExprs = new HashMap<>(analysis.getConstraints().size());
        for (AstConstraint constraint : analysis.getConstraints()) {
            constraintExprs.put(constraint, rewrite(analysis.getExpr(constraint), analysis));
        }
        Map<Objective, AstSetExpr> objectiveExprs = new HashMap<>(analysis.getObjectives().length);
        for (Objective objective : analysis.getObjectives()) {
            objectiveExprs.put(objective, rewrite(analysis.getExpr(objective), analysis));
        }
        Map<Assertion, AstBoolExpr> assertionExprs = new HashMap<>(analysis.getAssertions().length);
        for (Assertion assertion : analysis.getAssertions()) {
            assertionExprs.put(assertion, rewrite(analysis.getExpr(assertion), analysis));
        }
        return analysis
                .setConstraintExprs(constraintExprs)
                .setObjectiveExprs(objectiveExprs)
                .setAssertionExprs(assertionExprs);
    }

    @Override
    public AstExpr visit(AstGlobal ast, Analysis a) {
        Card globalCard = a.getGlobalCard(ast.getType());
        if (globalCard.isExact() && (a.getFormat(ast.getType()).equals(Format.LowGroup) || globalCard.getLow() == 1)) {
            return constant(ast.getType(), Util.fromTo(0, globalCard.getLow()));
        }
        return ast;
    }

    @Override
    public AstExpr visit(AstJoin ast, Analysis a) {
        if (ast.getRight() instanceof AstChildRelation) {
            AstSetExpr left = rewrite(ast.getLeft(), a);
            AstClafer right = ((AstChildRelation) ast.getRight()).getChildType();
            if (left instanceof AstGlobal) {
                return global(right);
            } else if (left instanceof AstConstant && right instanceof AstConcreteClafer) {
                // TODO what if right is abstract?
                Card childCard = a.getCard((AstConcreteClafer) right);
                if (Format.ParentGroup.equals(a.getFormat(right))) {
                    AstConstant constant = (AstConstant) left;
                    if (constant.getType().arity() == 1) {
                        int[] value = constant.getValue()[0];
                        assert childCard.isExact();
                        int[] childConstant = new int[value.length * childCard.getLow()];
                        for (int i = 0; i < constant.getValue().length; i++) {
                            for (int j = 0; j < childCard.getLow(); j++) {
                                childConstant[i * childCard.getLow() + j]
                                        = i * value[i] + j;
                            }
                        }
                        return constant(right, childConstant);
                    }
                }
                assert childCard.getLow() != a.getScope(right) :
                        "Didn't run scope analysis before format analysis?";
            }
            return join(left, ast.getRight());
        }
        return ast;
    }

    @Override
    public AstExpr visit(AstJoinParent ast, Analysis a) {
        AstSetExpr children = rewrite(ast.getChildren(), a);
        if (children instanceof AstThis) {
            ProductType type = a.getCommonSupertype(ast);
            if (a.getScope(type) == 1) {
                return constant(type, 0);
            }
        } else if (children instanceof AstGlobal) {
            ProductType childType = a.getCommonSupertype(ast.getChildren());
            if (childType.isClaferType()) {
                AstClafer childClafer = childType.getClaferType();
                if (childClafer instanceof AstConcreteClafer) {
                    AstConcreteClafer concreteChildType = (AstConcreteClafer) childClafer;
                    if (a.getCard(concreteChildType).hasLow()) {
                        return global(concreteChildType.getParent());
                    }
                }
            }
        } else if (children instanceof AstConstant) {
            AstConstant constant = (AstConstant) children;
            ProductType type = a.getCommonSupertype(ast);
            if (constant.getValue().length > 0 && a.getScope(type) == 1) {
                return constant(type, 0);
            }
        }
        return ast;
    }
    // TDODO: rewrite for all (global)

    @Override
    public AstExpr visit(AstNot ast, Analysis a) {
        AstBoolExpr expr = ast.getExpr();
        if (expr instanceof AstNot) {
            AstNot not = (AstNot) expr;
            return not.getExpr();
        } else if (expr instanceof AstSetTest) {
            AstSetTest test = (AstSetTest) expr;
            return test(test.getLeft(), test.getOp().negate(), test.getRight());
        } else if (expr instanceof AstCompare) {
            AstCompare compare = (AstCompare) expr;
            return compare(compare.getLeft(), compare.getOp().negate(), compare.getRight());
        } else if (expr instanceof AstMembership) {
            AstMembership membership = (AstMembership) expr;
            return membership(membership.getMember(), membership.getOp().negate(), membership.getSet());
        }
        return ast;
    }

    private boolean isZero(AstSetExpr expr) {
        if (expr instanceof AstConstant) {
            AstConstant constant = (AstConstant) expr;
            if (constant.getType().isInt()) {
                if (constant.getValue().length == 1) {
                    return constant.getValue()[0].length == 1 && constant.getValue()[0][0] == 0;
                }
            }
        }
        return false;
    }

    private AstSetExpr removeUpCast(AstSetExpr expr) {
        if (expr instanceof AstUpcast) {
            return removeUpCast(((AstUpcast) expr).getBase());
        }
        return expr;
    }

    private AstExpr rewriteIfThenElse(AstBoolExpr antecedent,
            AstSetExpr consequentLeft, AstSetExpr consequentRight, AstSetExpr alternativeLeft, AstSetExpr alternativeRight,
            Analysis analysis) {
        // rewrite
        //   if a then b = c else b = d
        // to
        //   b = (if a then c else d)
        if (consequentLeft.equals(alternativeLeft)) {
            return equal(consequentLeft,
                    ifThenElse(antecedent, consequentRight, alternativeRight));
        }
        // rewrite
        //   if a then b = c else none b
        // to
        //   b = (if a then c else {})
        if (consequentLeft instanceof AstJoinRef) {
            AstJoinRef joinRef = (AstJoinRef) consequentLeft;
            if (alternativeLeft instanceof AstCard && isZero(alternativeRight)) {
                AstCard card = (AstCard) alternativeLeft;
                if (removeUpCast(joinRef.getDeref()).equals(removeUpCast(card.getSet()))) {
                    return equal(consequentLeft,
                            ifThenElse(antecedent,
                                    consequentRight,
                                    constant(analysis.getType(consequentRight).getCommonSupertype().getClaferType())
                            ));
                }
            }
        }

        return null;
    }

    @Override
    public AstExpr visit(AstIfThenElse ast, Analysis a) {
        if (ast.getConsequent() instanceof AstSetTest && ast.getAlternative() instanceof AstSetTest) {
            AstBoolExpr antecedent = ast.getAntecedent();
            AstSetTest consequent = (AstSetTest) ast.getConsequent();
            AstSetTest alternative = (AstSetTest) ast.getAlternative();

            AstExpr rewrite = rewriteIfThenElse(antecedent, consequent.getLeft(), consequent.getRight(), alternative.getLeft(), alternative.getRight(), a);
            if (rewrite != null) {
                return rewrite;
            }
            rewrite = rewriteIfThenElse(antecedent, consequent.getLeft(), consequent.getRight(), alternative.getRight(), alternative.getLeft(), a);
            if (rewrite != null) {
                return rewrite;
            }
            rewrite = rewriteIfThenElse(antecedent, consequent.getRight(), consequent.getLeft(), alternative.getLeft(), alternative.getRight(), a);
            if (rewrite != null) {
                return rewrite;
            }
            rewrite = rewriteIfThenElse(antecedent, consequent.getRight(), consequent.getLeft(), alternative.getRight(), alternative.getLeft(), a);
            if (rewrite != null) {
                return rewrite;
            }
        }
        return ast;
    }
}


text:
![Build Status](https://andremarques023.visualstudio.com/_apis/public/build/definitions/c98afab6-e9a0-4e74-85eb-4d27f9829548/24/badge "Visual Studio Team Services") ![Build Status](https://ci.appveyor.com/api/projects/status/f1k6thlnwuyg1h3m?svg=true "AppVeyor")

This extension provides diagnostic tasks to help you diagnose and profile build or release definitions. With these tasks, you can gather information (such as variable values) and troubleshoot common issues during the different stages of your pipeline.

## Usage

Currently, this extension has the following tasks:

* Add Build Tag - Add a tag for the current build.
* Attach Summary Markdown - Upload and attach summary markdown section to the current timeline record.
* Log Variables - Log predefined variables provided by Build or Release Management to the console.
* Set Variable - Sets a variable to be exposed to the following tasks as an environment variable.
* Update Build Number - Update the build number for the current build.

## Add Build Tag

Builds can be tagged for easy searching. This task adds a tag for the current build. The following options are available:

* Tag - The tag to add to the build.

![Add Build Tag](https://github.com/andremarques023/vsts-extensions/raw/master/DiagnosticTasks/Images/addbuildtag-task-1.png)

## Attach Summary Markdown

Markdown based sections can be added to both Build and Release summary pages. This task uploads and attach summary sections to the Build or Release timeline record. The following options are available:

* Section name - The summary section name.
* Markdown file path - Relative path from the repository root to the markdown file.

## Log Variables

Team Build brings a number of predefined variables that can be used in build (and release) definitions and scripts. Variables are generated by the agent in the scope of a particular job (prior to it starting) or generated on the server side and sent to the agent as part of the job.

This task logs these variables to the console. The following options are available:

* Agent variables.
* Build variables.
* Common variables.
* Release variables.
* System variables.

![Log Variables](https://github.com/andremarques023/vsts-extensions/raw/master/DiagnosticTasks/Images/logvariables-task-1.png)

>__Note:__ Variable values are automatically logged when a release is in progress (at the Logs hub) by Release Management.

## Set Variable

This task sets a variable. The first task can set a variable, and following tasks are able to use the variable. The following options are available:

* Variable name - The name of the variable to be set.
* Variable value - The value to be set.

## Update Build Number

This task updates the build number. It uses a logging command to emit the new number via standard output. The following options are available:

* Build number - The build number to be set for the current build.

![Update Build Number](https://github.com/andremarques023/vsts-extensions/raw/master/DiagnosticTasks/Images/updatebuildnumber-task-1.png)


text:
[![Build Status](https://travis-ci.org/boneskull/jquery.preempt.png?branch=master)](https://travis-ci.org/boneskull/jquery.preempt)
[![Coverage Status](https://coveralls.io/repos/boneskull/jquery.preempt/badge.png?branch=)](https://coveralls.io/r/boneskull/jquery.preempt?branch=master)
[![Built with Grunt](https://cdn.gruntjs.com/builtwith.png)](http://gruntjs.com/)

[jQuery](http://jquery.com) plugin to take legacy inline JS (i.e. `onclick`
and `href="javascript:..."`) and create event handlers to be run before or
after the inlined code (or both!).

> #### (Why would I need this?)
> My use case was that I was writing a [GreaseMonkey](https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/)-like [script](https://github.com/boneskull/fb-bugmonkey-markdown) against a page with inline JS and my
jQuery events were not behaving.  Works for me; your mileage may vary.

## Installation

Use the [jsDelivr CDN](http://www.jsdelivr.com/#!jquery.preempt).

## Usage

```javascript

// given <button onclick="doSomething()">do something</button>
// or <a href="javascript:doSomethingElse()">do something else</a>

// Basic usage:
$('button').preempt({
  attr: 'onclick',
  event: 'click',
}, function doSomethingBeforeSomething() {
  // do something else
});

// Restoring the inline JS:
$('button').preempt({
  attr: 'onclick',
  event: 'click',
  restore: true
});

// Fancy usage:
$('button').preempt({
  attr: 'onclick',
  event: 'click',
  before: function executedBeforeInlineJS(event, data) {
    // stuff; return false to halt propagation to inline JS
  },
  after: function exectedAfterInlineJS(event, data) {
    // things; return false to prevent the default action and stop propagation
  },
  // will execute the after() function even if the inlined JS returned false.
  forcePropagation: true,
  data: {
    before: 'some data to be passed to the before() function',
    after: 'some data to be passed to the after() function',
  }
});
```

## Author
[Christopher Hiller](http://boneskull.github.io)


text:
using System;
using System.IO;
using System.Threading.Tasks;
using Elasticsearch.Net;
using Newtonsoft.Json;

namespace Nest
{
	using System.Threading;
	using MultiSearchCreator = Func<IApiCallDetails, Stream, MultiSearchResponse>;

	public partial interface IElasticClient
	{
		///
		/// The multi search API allows to execute several search requests within the same API.
		/// <para> </para>http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-multi-search.html
		///
		/// <param name="selector">A descriptor that describes the search operations on the multi search api</param>
		IMultiSearchResponse MultiSearch(Func<MultiSearchDescriptor, IMultiSearchRequest> selector);

		/// <inheritdoc/>
		IMultiSearchResponse MultiSearch(IMultiSearchRequest request);

		/// <inheritdoc/>
		Task<IMultiSearchResponse> MultiSearchAsync(Func<MultiSearchDescriptor, IMultiSearchRequest> selector, CancellationToken cancellationToken = default(CancellationToken));

		/// <inheritdoc/>
		Task<IMultiSearchResponse> MultiSearchAsync(IMultiSearchRequest request, CancellationToken cancellationToken = default(CancellationToken));
	}

	public partial class ElasticClient
	{
		/// <inheritdoc />
		public IMultiSearchResponse MultiSearch(Func<MultiSearchDescriptor, IMultiSearchRequest> selector) =>
			this.MultiSearch(selector?.Invoke(new MultiSearchDescriptor()));

		/// <inheritdoc />
		public IMultiSearchResponse MultiSearch(IMultiSearchRequest request)
		{
			return this.Dispatcher.Dispatch<IMultiSearchRequest, MultiSearchRequestParameters, MultiSearchResponse>(
				request,
				(p, d) =>
				{
					var converter = CreateMultiSearchDeserializer(p);
					var serializer = this.ConnectionSettings.StatefulSerializer(converter);
					var creator = new MultiSearchCreator((r, s) => serializer.Deserialize<MultiSearchResponse>(s));
					request.RequestParameters.DeserializationOverride(creator);
					return this.LowLevelDispatch.MsearchDispatch<MultiSearchResponse>(p, (object)p);
				}
			);
		}

		/// <inheritdoc />
		public Task<IMultiSearchResponse> MultiSearchAsync(Func<MultiSearchDescriptor, IMultiSearchRequest> selector, CancellationToken cancellationToken = default(CancellationToken)) =>
			this.MultiSearchAsync(selector?.Invoke(new MultiSearchDescriptor()), cancellationToken);

		/// <inheritdoc />
		public Task<IMultiSearchResponse> MultiSearchAsync(IMultiSearchRequest request, CancellationToken cancellationToken = default(CancellationToken))
		{
			return this.Dispatcher.DispatchAsync<IMultiSearchRequest, MultiSearchRequestParameters, MultiSearchResponse, IMultiSearchResponse>(
				request,
				cancellationToken,
				(p, d, c) =>
				{
					var converter = CreateMultiSearchDeserializer(p);
					var serializer = this.ConnectionSettings.StatefulSerializer(converter);
					var creator = new MultiSearchCreator((r, s) => serializer.Deserialize<MultiSearchResponse>(s));
					request.RequestParameters.DeserializationOverride(creator);
					return this.LowLevelDispatch.MsearchDispatchAsync<MultiSearchResponse>(p, (object)p, c);
				}
			);
		}

		private JsonConverter CreateMultiSearchDeserializer(IMultiSearchRequest request)
		{
			if (request.Operations != null)
			{
				foreach (var operation in request.Operations.Values)
					CovariantSearch.CloseOverAutomagicCovariantResultSelector(this.Infer, operation);
			}

			return new MultiSearchResponseJsonConverter(this.ConnectionSettings, request);
		}
	}
}


text:
/**
 * A socket based program to send a file over the network after dividing it into parts and sending each part separately
 * @author Dhaval Kapil
 * MIT license http://www.opensource.org/licenses/mit-license.php
 */

package dhaval;

import java.io.*;

public class Packets
{   static void divide(File f)
    throws Exception
    {   FileInputStream in = new FileInputStream(f);
        long length = f.length();
        long limit = length/10;
        int bytes_read;
        long total_bytes = 0;
        byte[] buffer = new byte[4096];
        for(int i = 0;i<10;i++)
        {   FileOutputStream out = new FileOutputStream(Settings.packetSendFile + i);
            while((bytes_read=in.read(buffer))!=-1)
            {   out.write(buffer, 0, bytes_read);
                total_bytes += bytes_read;
                if(total_bytes>limit)
                break;
            }
            out.close();
            total_bytes = 0;
        }
        in.close();
    }
    static void conquer(File f)
    throws Exception
    {   FileOutputStream out = new FileOutputStream(f);
        int bytes_read;
        byte[] buffer = new byte[4096];
        for(int i = 0;i<10;i++)
        {   FileInputStream in = new FileInputStream(Settings.packetReceiveFile + i);
            while((bytes_read=in.read(buffer))!=-1)
            {   out.write(buffer, 0, bytes_read);
            }
            in.close();
        }
        out.close();
    }
}


text:
1. Add BKHitSlop to your Podfile.
2. In your terminal, run `pod install`.

## Usage

1. Add `#import <BKHitSlop/BKHitSlop.h>` to your source file (or to your prefix header, if you want to access it anywhere in your project).
2. Implement the method `myButton.bk_hitSlop = UIEdgeInsetsMake(-50, -50, -50, -50);
` on your button (or other UIView) - or your preferred UIEdgeInsets value. Negative values are ignored.

## FAQ

**Q:** How does it work?
**A:** Simple! UIViews have a method `-pointInside:withEvent:` which decides whether an event's point (presumably, a touch's point) lies inside itself. When you touch the screen, the UIView hierarchy queries for the "best" view to respond to that touch. BKHitSlop swaps the implementation out for our own. This is (mostly) safe.

When you set the hit slop, first, we check if the point would normally be considered inside the view, according to the original implementation - if so, we just short-circuit and return YES. Otherwise, the views' bounds are inset by the UIEdgeInsets value.

_Aside: This is why the inset's components don't have any effect unless negative. Note that a negative inset goes **outward** rather than **inward**._

Anyways, once we've done that to figure out the new rectangle to test, we use `CGRectContainsPoint` to see if the point is inside that rectangle.


text:
@interface ZRMoveCellTableViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSMutableArray * listData;
@end

@implementation ZRMoveCellTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view setBackgroundColor: globalVar.colors.viewBgColor];
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    [self.view addSubview:tableView];

    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self.view);
    }];
    NSMutableArray *array = [NSMutableArray arrayWithObjects:
                             @"张三",@"张四",@"张五",
                             @"李三",@"李四",@"李五",
                             @"李六",@"王三",@"王四",
                             @"王五",@"王六",@"王七",
                             @"王八",@"王九",@"王十",
                             nil];
    self.listData = array;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *reuseId = @"TableSampleIdentifier";
    ZRMovableCell *cell = (ZRMovableCell *)[tableView dequeueReusableCellWithIdentifier:reuseId];
    if (cell == nil) {
        cell = [[ZRMovableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseId];
    }
    //他只能在这里
    [tableView setEditing:YES animated:YES];

    return cell;
}

#pragma mark - UITableViewDelegate
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}

- (BOOL)tableView:(UITableView *)tableview shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {

    [tableView beginUpdates];
    NSInteger fromRow = [sourceIndexPath row];
    NSInteger toRow = [destinationIndexPath row];
    id object = [self.listData objectAtIndex:fromRow];
    [self.listData removeObjectAtIndex:fromRow];
    [self.listData insertObject:object atIndex:toRow];
    [tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
//    [tableView reloadData];
    [tableView endUpdates];
}

@end


text:
import {Component} from "angular2/core";

@Component({
    selector:"two-way",
    templateUrl: "../../assets/templates/demo_components/twoWayBinding.html"
})

export class TwoWayBinding {
    private name:string;

    constructor() {
        this.name = "Angular";
    }
}


text:
namespace os_crypt {
namespace switches {

#if BUILDFLAG(IS_APPLE)

// Uses mock keychain for testing purposes, which prevents blocking dialogs
// from causing timeouts.
COMPONENT_EXPORT(OS_CRYPT) extern const char kUseMockKeychain[];

#endif  // BUILDFLAG(IS_APPLE)

}  // namespace switches
}  // namespace os_crypt

#endif  // COMPONENTS_OS_CRYPT_OS_CRYPT_SWITCHES_H_


text:
package com.project.studyalarmmanager;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.NotificationCompat;

/**
 * Created by r028367 on 08/02/2017.
 */

public interface INotification {
    public NotificationCompat.Builder builderNotification(Context context, Intent intent, String title, String message, int id);
}


text:
package jahmm.toolbox;

import jahmm.Hmm;
import jahmm.observables.Observation;
import java.util.List;

/**
 *
 * An interface that enables generating a sequence of interactions based on a
 * given Hidden Markov Model.
 *
 * @author kommusoft
 * @param <TObs> The type of observations regarding the Hidden Markov Model.
 * @param <TInt> The type of interactions regarding the Hidden Markov Model.
 * @param <THmm> The type of the Hidden Markov Model.
 */
public interface MarkovGenerator<TObs extends Observation, TInt extends Observation, THmm extends Hmm<TObs, TInt, THmm>> {

    /**
     * Finds a new state according to the initial (pi) probabilities of each
     * state.
     */
    void newSequence();

    /**
     * Generates a new (pseudo) random interaction.
     *
     * @return The generated observation.
     */
    TInt interaction();

    /**
     * Generates a new (pseudo) random interaction sequence and start a new one.
     *
     * @param length The length of the sequence.
     * @return An observation sequence.
     */
    List<TInt> interactionSequence(int length);

    /**
     * Returns the state number of the current state.
     *
     * @return A state number.
     */
    int stateNb();

    /**
     * Gets the stored Hidden Markov Model.
     *
     * @return The stored hidden Markov Model.
     */
    THmm getHmm();

}


text:
#!/c/xampp/php/php
<?php
use Kafoso\SvnNumber;
use Kafoso\SvnNumber\Bash\Command as BashCommand;
use Kafoso\SvnNumber\SvnAction\Diff;
use Kafoso\SvnNumber\SvnAction\Status;
use Kafoso\SvnNumber\SvnAction\Status\Line;
use Kafoso\SvnNumber\SvnAction\Status\Staging;

require(readlink(dirname(__FILE__)) . "/lib/bootstrap.php");

try {
    $bashCommand = new BashCommand;
    $svnNumber = new SvnNumber($argv, $bashCommand);
    if (false == $svnNumber->hasAction()) {
        $svnNumber->exec("svn"); // To show help hints
        exit;
    }

    $staging = new Staging(__DIR__ . "/data/staging.txt");

    function printStatus(Status $status, $forceOutputAll = false){
        if (false === $forceOutputAll && $status->getSvnNumber()->hasRequestedNumbers()) {
            exit($status->getOutput($status->getSvnNumber()->getRequestedNumbers()));
        } else {
            exit($status->getOutput(null));
        }
    }

    if (in_array($svnNumber->getAction(), array("commit-staged", "stage", "stage-all", "unstage", "unstage-all"))) {
        switch ($svnNumber->getAction()) {
            case "commit-staged":
                $stagedFilePaths = $staging->getStagedFilePaths();
                $status = new Status($svnNumber, $staging);
                $commitingFilePaths = array();
                foreach ($status->getLines() as $line) {
                    if (in_array($line->getFilePath(), $stagedFilePaths)) {
                        $commitingFilePaths[] = escapeshellarg($line->getFilePath());
                    }
                }
                $svnNumber->exec(sprintf(
                    "svn commit %s %s",
                    implode(" ", $commitingFilePaths),
                    $svnNumber->getAdditionalArgsStr()
                ));
                $staging->clear()->save();
                $status = new Status($svnNumber, $staging);
                exit(printStatus($status, true));
            case "stage":
                if ($svnNumber->hasRequestedNumbers()) {
                    $status = new Status($svnNumber, $staging);
                    $lines = array_intersect_key(
                        $status->getLines(),
                        array_flip($svnNumber->getRequestedNumbers())
                    );
                    foreach ($lines as $line) {
                        echo "Staged file: " . $line->getFilePath() . PHP_EOL;
                        $staging->addLine($line);
                    }
                    $staging->save();
                    exit(printStatus($status, true));
                } else {
                    throw new \InvalidArgumentException("Command 'svn-number stage #' requires at least one number");
                }
                break;
            case "stage-all":
                $status = new Status($svnNumber, $staging);
                $staging->clear();
                foreach ($status->getLines() as $line) {
                    echo "Staged file: " . $line->getFilePath() . PHP_EOL;
                    $staging->addLine($line);
                }
                $staging->save();
                exit(printStatus($status));
            case "unstage":
                if ($svnNumber->hasRequestedNumbers()) {
                    $status = new Status($svnNumber, $staging);
                    $lines = array_intersect_key(
                        $status->getLines(),
                        array_flip($svnNumber->getRequestedNumbers())
                    );
                    foreach ($lines as $line) {
                        echo "Unstaged file: " . $line->getFilePath() . PHP_EOL;
                        $staging->removeLine($line);
                    }
                    $staging->save();
                    exit(printStatus($status, true));
                } else {
                    throw new \InvalidArgumentException("Command 'svn-number unstage #' requires at least one number");
                }
                break;
            case "unstage-all":
                $staging->clear()->save();
                echo "Unstaged all files." . PHP_EOL;
                $status = new Status($svnNumber, $staging);
                exit(printStatus($status));
        }
    } else if (in_array($svnNumber->getAction(), array("st", "status"))) {
        $status = new Status($svnNumber, $staging);
        printStatus($status);
    } else if (in_array($svnNumber->getAction(), array("di", "diff"))) {
        $diff = new Diff($svnNumber);
        if ($svnNumber->hasRequestedNumbers()) {
            $status = new Status($svnNumber, $staging);
            $allLinesInformation = $status->getLineInformationFromFileNumbers($svnNumber->getRequestedNumbers());
            $filePaths = array_map(function(Line $line){
                return $line->getFilePath();
            }, $allLinesInformation);
            exit($diff->getOutputForFilePaths($filePaths));
        } else {
            exit($diff->getOutputAll());
        }
    } else if (in_array($svnNumber->getAction(), array(
            "ci",
            "commit",
        ))) {
        /**
         * Apply same action to multiple files (bulk). E.g.:
         *      # svn commit foo.txt bar.txt -m "Two files committed"
         */
        if ($svnNumber->hasRequestedNumbers()) {
            $status = new Status($svnNumber, $staging);
            $filePaths = array_map(function(Line $line){
                return escapeshellarg($line->getFilePath());
            }, $status->getLineInformationFromFileNumbers($svnNumber->getRequestedNumbers()));
            $svnNumber->exec(sprintf(
                "svn %s %s %s",
                $svnNumber->getAction(),
                implode(" ", $filePaths),
                $svnNumber->getAdditionalArgsStr()
            ));
            exit;
        }
    } else if (in_array($svnNumber->getAction(), array(
            "add",
            "ann",
            "annotate",
            "blame",
            "del",
            "delete",
            "praise",
            "remove",
            "resolve",
            "revert",
            "rm",
        ))) {
        /**
         * Apply same action to multiple files individually through a loop. E.g.:
         *      # svn revert foo.txt
         *      # svn revert bar.txt
         */
        if ($svnNumber->hasRequestedNumbers()) {
            $status = new Status($svnNumber, $staging);
            $allLinesInformations = $status->getLineInformationFromFileNumbers($svnNumber->getRequestedNumbers());
            foreach ($allLinesInformations as $number => $line) {
                $svnNumber->exec(sprintf(
                    "svn %s %s %s",
                    $svnNumber->getAction(),
                    escapeshellarg($line->getFilePath()),
                    $svnNumber->getAdditionalArgsStr()
                ));
            }
            exit;
        }
    }

    $output = $svnNumber->exec(sprintf(
        "svn %s %s",
        $svnNumber->getAction(),
        $svnNumber->getAdditionalArgsStr()
    ));
    exit(implode(PHP_EOL, $output));
} catch (\Exception $e) {
    $message = implode(PHP_EOL, array_map(function($v){
        return str_repeat(" ", 4) . $v;
    }, preg_split("/\n|\r\n?/", $e->getMessage(), -1, PREG_SPLIT_NO_EMPTY)));
    exit("svn-number Exception: " . PHP_EOL . $message);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MasterPage : System.Web.UI.MasterPage
{
    public string user = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (AccessControl.IsLoggedIn(this.Page))
        {
            user = "Logged in as " + AccessControl.GetLoggedUser(this.Page);
            // all the buttons are invisible at first
            logoutButton.Visible = true;
            updateButton.Visible = true;
            galleryButton.Visible = true;
        }
        else
        {
            loginButton.Visible = true;
            registrationButton.Visible = true;
        }

        if (AccessControl.IsAdmin(this.Page))
            adminButton.Visible = true;

        VisitorCounter.LogPageLoad(this.Page);
    }
}


text:
package org.springframework.web.util;

import javax.servlet.ServletContext;

abstract public class ServletContextPropertyUtils
{
    public ServletContextPropertyUtils(){}
    public static String resolvePlaceholders(String p0, ServletContext p1){ return null; }
    public static String resolvePlaceholders(String p0, ServletContext p1, boolean p2){ return null; }
}


text:
class C1 { async }
class C2 { async; constructor() {} }
class C3 { async = 5.1; constructor() {} }

assert((new C1).async === undefined);
assert((new C2).async === undefined);
assert((new C3).async === 5.1);

try {
  eval('class C1 { async* }');
  assert(false);
} catch (e) {
  assert(e instanceof SyntaxError);
}


text:
console.log("loading " + module.id);
var cody = require('./../index.js');

//!! basis objects (passed to Item constructor or created with addDefaults have a parent that is an integer)
//Objects created with the contructor Item have a parent and parentId that are integers
//only after "pickParent" become the parent instance variable a real (Item) object

function Item(basis, app) {
  // copy from basis
  for (var a in basis) {
    if (basis.hasOwnProperty(a)) {
      this[a] = basis[a];
    }
  }

  // replace 'template' by the real object and add 'templateId'
  this.templateId = this.template;
  this.template = app.getTemplate(this.templateId);
  if (typeof this.template === "undefined") {
    app.err("Item.constructor", "did not find a template with id = " + this.templateId + " for item " + this.id + " / " + this.name);
  }

  // add a 'parentId' for consistency
  //  this.parent will be replaced once all items are created in 'pickParent'
  this.parentId = this.parent;
}

module.exports = Item;

Item.addDefaults = function(basis, parent) {
  if (typeof parent === "undefined") { parent = {}; }

  basis.name = basis.name || Item.kDefaultName;
  basis.parent = basis.parent || parent.id;
  basis.user = basis.user || parent.user;
  basis.sortorder = basis.sortorder || 9999;
  basis.orderby = basis.orderby || parent.orderby;
  basis.dated = basis.dated || new Date();
  basis.validfrom = basis.validfrom || new Date();
  basis.validto = basis.validto || cody.Application.endOfTime();
  basis.template = basis.template || parent.template.defaultchild;
  basis.showcontent = basis.showcontent || Item.kContent;
  basis.needslogin = basis.needslogin || parent.needslogin;
  basis.defaultrequest = basis.defaultrequest || "list";
  basis.alloweddomains = basis.alloweddomains || parent.alloweddomains;

  return basis;
};

Item.orderbyList = [ { id: 'M', name: 'Manual'},
                     { id: 'A', name: 'Alphabetical'},
                     { id: 'D', name: 'Chronological'} ];
Item.showcontentList = [ { id: 'Y', name: 'Content'},
                         { id: 'S', name: 'First subitem'},
                         { id: 'N', name: 'All subitems'},
                         { id: 'D', name: 'Don\'t show subitems'},
                         { id: 'L', name: 'Lightbox (not yet implemented)'} ];

Item.prototype.pickParent = function(itemList) {
  this.parent = itemList[this.parentId];
};

Item.loadItems = function(connection, store) {
  connection.query('select * from items', [], function(err, result) {
    if (err) { console.log(err); throw(new Error("Item.loadItems failed with sql errors")); }
    store(result);
  });
};

// values for orderby
Item.kManual        = 'M';
Item.kAlphabetical  = 'A';
Item.kDate          = 'D';

// values for showcontent
Item.kContent     = 'Y';
Item.kNothing     = 'N';
Item.kSubItem     = 'S';
Item.kNoSubitems  = 'D';
Item.kLightBox    = 'L';

Item.kDefaultName  = 'New item';

Item.prototype.getId = function() {
  return this.id;
};
Item.prototype.getAllowedDomains = function() {
  return this.alloweddomains;
};

Item.prototype.needsLogin = function() {
  return (this.needslogin) && (this.needslogin === "Y");
};

Item.prototype.setTemplate = function(templateId, controller) {
  this.templateId = templateId;
  if (typeof controller !== "undefined") {
    this.template = controller.app.getTemplate(templateId);
    if (typeof this.template === "undefined") {
      controller.feedBack("Couldn't find the template with id = " + templateId + " for item " + this.id + " / " + this.name);
    }
  }
};

Item.prototype.scrapeFrom = function(controller) {
  // update all item info from the controller
  this.dated = controller.getDate("dated");
  this.validfrom = controller.getDate("validfrom");
  this.validto = controller.getDate("validto");
  this.needslogin = controller.getParam("needslogin");
  this.showcontent = controller.getParam("showcontent");
  this.alloweddomains = controller.getParam("alloweddomains");
  this.setTemplate(controller.getParam("template"), controller);
  this.orderby = controller.getParam("orderby");
  this.defaultrequest = controller.getParam("defaultrequest", this.defaultrequest || "list");
  // user is only filled at creation time
};

Item.prototype.doUpdate = function(controller, finish) {
  var self = this;

  var values = [self.name, self.parentId, self.user, self.templateId, self.orderby, self.sortorder,
                self.dated, self.validfrom, self.validto, self.showcontent, self.needslogin,
                self.defaultrequest, self.alloweddomains];

  // new or existing record?
  if ((typeof self.id === "undefined") || (self.id === 0)) {

    //console.log("Item.doUpdate -> insert item " + self.name);
    controller.query("insert into items (name, parent, user, template, orderby, sortorder, " +
                     " dated, validfrom, validto, showcontent, needslogin, " +
                     " defaultrequest, alloweddomains) " +
                     "values (?, ?, ?, ?, ?, ?,  ?, ?, ?, ?, ?,  ?, ?)", values,
      function(err, result) {
        if (err) {
          console.log("Item.doUpdate -> erroring inserting item: " + self.name);
          console.log(err);
        } else {
          self.id = result.insertId;
          console.log("Item.doUpdate -> inserted item: " + self.id);
          if (typeof finish === "function") { finish(); }
        }
    });

  } else {
    //console.log("Item.doUpdate -> update item " + self.id + " - " + self.name);
    values.push(self.id);
    controller.query("update items set name = ?, parent = ?, user = ?, template = ?, orderby = ?, sortorder = ?, " +
                     " dated = ?, validfrom = ?, validto = ?, showcontent = ?, needslogin = ?, " +
                     " defaultrequest = ?, alloweddomains = ? " +
                     "where id = ?", values,
      function(err) {
        if (err) {
          console.log("Item.doUpdate -> erroring updating item: " + self.id);
          console.log(err);
        } else {
          console.log("Item.doUpdate -> updated item: " + self.id);
          if (typeof finish === "function") { finish(); }
        }
    });
  }
};

Item.prototype.doDelete = function(controller, finish) {
  var self = this;

  controller.query("delete from items where id = ?", [ self.id ], function() {
    delete controller.app.items[self.id];
    console.log("Item.doDelete -> deleted item: " + self.id);

    controller.query("delete from pages where item = ?", [ self.id ], function(err) {
      if (err) {
        console.log("Item.doDelete -> erroring deleting all pages from item: " + self.id);
        console.log(err);
      } else {
        controller.app.deletePagesForItem(self.id, function() {
          console.log("Item.doDelete -> deleted all pages from item: " + self.id);

          controller.query("delete from content where item=?", [ self.id ], function(err) {
            if (err) {
              console.log(err);
            } else {
              console.log("Item.doDelete -> deleted all content of item: " + self.id);
              if (typeof finish === "function") { finish(); }
            }
          });
        });
      }
    });
  });
};


text:
using RootSystem = System;
using System.Linq;
using System.Collections.Generic;
namespace Windows.Kinect
{
    //
    // Windows.Kinect.JointOrientation
    //
    [RootSystem.Runtime.InteropServices.StructLayout(RootSystem.Runtime.InteropServices.LayoutKind.Sequential)]
    public struct JointOrientation
    {
        public Windows.Kinect.JointType JointType { get; set; }
        public Windows.Kinect.Vector4 Orientation { get; set; }

        public override int GetHashCode()
        {
            return JointType.GetHashCode() ^ Orientation.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            if (!(obj is JointOrientation))
            {
                return false;
            }

            return this.Equals((JointOrientation)obj);
        }

        public bool Equals(JointOrientation obj)
        {
            return JointType.Equals(obj) && Orientation.Equals(obj);
        }

        public static bool operator ==(JointOrientation a, JointOrientation b)
        {
            return a.Equals(b);
        }

        public static bool operator !=(JointOrientation a, JointOrientation b)
        {
            return !(a.Equals(b));
        }
    }

}


text:
<scientilla-backend-layout>

PhD management

                        1.
                        Select institute

                    <button
                        class="btn btn-primary btn-add-item"
                        ng-click="vm.openModal(vm.models.INSTITUTE, vm.actions.ADD)"
                    >
                        Add
                    </button>

                        {{ institute.name }}

                                <button
                                    class="action-button"
                                    ng-click="vm.openModal(vm.models.INSTITUTE, vm.actions.EDIT, institute)"
                                ></button>

                                <button
                                    class="action-button"
                                    ng-click="vm.delete(vm.models.INSTITUTE, institute)"
                                    scientilla-click-confirm="Do you want to delete this institute?"
                                ></button>

                        No institutes found...

                        2.
                        Select course

                    <button
                        class="btn btn-primary btn-add-item"
                        ng-click="vm.openModal(vm.models.COURSE, vm.actions.ADD, vm.selectedInstitute)"
                        ng-disabled="!vm.selectedInstitute"
                    >
                        Add
                    </button>

                        {{ course.name }}

                                <button
                                    class="action-button"
                                    ng-click="vm.openModal(vm.models.COURSE, vm.actions.EDIT, vm.selectedInstitute, course)"
                                ></button>

                                <button
                                    class="action-button"
                                    ng-click="vm.delete(vm.models.COURSE, course)"
                                    scientilla-click-confirm="Do you want to delete this course?"
                                ></button>

                        No institute selected...

                        No courses found...

                        3.
                        Get cycles

                    <button
                        class="btn btn-primary btn-add-item"
                        ng-click="vm.openModal(vm.models.CYCLE, vm.actions.ADD, vm.selectedInstitute, vm.selectedCourse)"
                        ng-disabled="!vm.selectedCourse"
                    >
                        Add
                    </button>

                        {{ cycle.name }}

                                <button
                                    class="action-button"
                                    ng-click="vm.openModal(vm.models.CYCLE, vm.actions.EDIT, vm.selectedInstitute, vm.selectedCourse, cycle)"
                                ></button>

                                <button
                                    class="action-button"
                                    ng-click="vm.delete(vm.models.CYCLE, cycle)"
                                    scientilla-click-confirm="Do you want to delete this cycle?"
                                ></button>

                        No course selected...

                        No cycles found...

        <scientilla-loading is-loading="vm.loading"></scientilla-loading>

</scientilla-backend-layout>


text:
ezedit

The fast and easy way to give your clients control of their online presence.

About ezedit

EZEDIT is a Platform as a Service (PAAS) for web designers to give their clients full control of the digital content on their website. Using EZEDIT is as simple as including the generated script tag in the site HTML, and your client can update their site in realtime.

Try ezedit

Try EZEDIT for free today, and free yourself from continuously updating client websites you've already finished.


text:
DELIMITER /
alter table COI_DISC_DETAILS
    ADD CONSTRAINT FK_ENTITY_DISPOSITION_CODE FOREIGN KEY (ENTITY_DISPOSITION_CODE)
    REFERENCES COI_DISPOSITION_STATUS (COI_DISPOSITION_CODE)
/

DELIMITER ;


text:
function [p_val, stat] = testchi2hist(varargin)

% TESTCHI2HIST uses the chi2 test to compare a histograms to a standard.
% --------------------------------------------------------------
% [p_val stat] = testchi2hist(h_obs, h_stan, p_name, p_val, ...)
% --------------------------------------------------------------
% Description: uses the chi2 test to compare a histograms to a standard.
% Input:       {h_obs} observed histogram.
%              {h_stan} standard histogram, must be defined on the same
%                   bins as {h_obs}.
%              <{p_name, p_val}> pairs to modify the test. Currently
%                   available:
%                   'noSamples' - if 'equal', then the total number of
%                       samples in both histograms is expected to be
%                       identical. If 'nonequal', then the total number of
%                       samples is considered non-equal among the two
%                       histograms, even if it equals in practice. By
%                       default, the number of samples is assumed equal.
% Output:      {p_val} P-value.
%              {test} test statistic.

% © Liran Carmel
% Classification: Hypothesis testing
% Last revision date: 27-Oct-2005

% parse input line
[h_obs h_stan is_equal] = parseInput(varargin{:});

% remove zeros
zeros = find(~h_stan);
common = find(~h_obs(zeros));
h_obs(zeros(common)) = [];
h_stan(zeros(common)) = [];

% compute test statistics
if length(zeros) == length(common)
    stat = sum( (h_obs - h_stan).^2 ./ h_stan );
else
    stat = nan;
end

% test identity of distributions
if is_equal
    dof = length(h_obs) - 1;
else
    dof = length(h_obs);
end
p_val = 1 - chi2cdf(stat,dof);

% #########################################################################
function [h_obs, h_stan, is_equal] = parseInput(varargin)

% PARSEINPUT parses input line.
% ----------------------------------------------
% [h_obs h_stan is_equal] = parseInput(varargin)
% ----------------------------------------------
% Description: parses the input line.
% Input:       {varargin} original input line.
% Output:      {h_obs} observed histogram.
%              {h_stan} standard histogram.
%              {is_equal} indicates whether the number of samples in both
%                   histograms are equal or not.

% check number of input arguments
error(nargchk(2,Inf,nargin));

% first argument is always {h_obs}
error(chkvar(varargin{1},'integer','vector',{mfilename,'',1}));
h_obs = varargin{1};

% second argument is always {h_stan}
error(chkvar(varargin{2},'double','vector',{mfilename,'',2}));
h_stan = varargin{2};

% check consistency
if length(h_obs) ~= length(h_stan)
    error('The two histograms should have the same length');
end

% defaults
is_equal = true;

% loop on instructions
for ii = 3:2:nargin
    errmsg = {mfilename,'',ii+1};
    switch str2keyword(varargin{ii},6)
        case 'nosamp'   % instruction: noSamples
            error(chkvar(varargin{ii+1},'char','vector',errmsg));
            switch str2keyword(varargin{ii+1},3)
                case 'equ'
                    is_equal = true;
                case 'non'
                    is_equal = false;
                otherwise
                    error('%s: undefined option of ''noSamples''',...
                        varargin{ii+1});
            end
        otherwise
            error('%s: undefined instruction',varargin{ii});
    end
end


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

<TITLE>
Code128Writer
</TITLE>

<META NAME="date" CONTENT="2012-02-04">

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

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.google.zxing.oned

Class Code128Writer

java.lang.Object
  com.google.zxing.oned.OneDimensionalCodeWriter
      com.google.zxing.oned.UPCEANWriter
          com.google.zxing.oned.Code128Writer

All Implemented Interfaces:
Writer

public final class Code128Writer
extends UPCEANWriter

This object renders a CODE128 code as a BitMatrix.

Author:

erik.barbara@gmail.com (Erik Barbara)

Constructor Summary

Code128Writer()

Method Summary

 byte[]
encode(java.lang.String contents)

          Encode the contents to byte array expression of one-dimensional barcode.

 BitMatrix
encode(java.lang.String contents,
       BarcodeFormat format,
       int width,
       int height,
       java.util.Map<EncodeHintType,?> hints)

          Encode the contents following specified format.

Methods inherited from class com.google.zxing.oned.OneDimensionalCodeWriter

appendPattern, encode

Methods inherited from class java.lang.Object

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

Constructor Detail

Code128Writer

public Code128Writer()

Method Detail

encode

public BitMatrix encode(java.lang.String contents,
                        BarcodeFormat format,
                        int width,
                        int height,
                        java.util.Map<EncodeHintType,?> hints)
                 throws WriterException

Description copied from class: OneDimensionalCodeWriter

Encode the contents following specified format.
 width and height are required size. This method may return bigger size
 BitMatrix when specified size is too small. The user can set both width and
 height to zero to get minimum size barcode. If negative value is set to width
 or height, IllegalArgumentException is thrown.

Specified by:
encode in interface Writer
Overrides:
encode in class OneDimensionalCodeWriter

Parameters:
contents - The contents to encode in the barcode
format - The barcode format to generate
width - The preferred width in pixels
height - The preferred height in pixels
hints - Additional parameters to supply to the encoder

Throws:

WriterException

encode

public byte[] encode(java.lang.String contents)

Description copied from class: OneDimensionalCodeWriter

Encode the contents to byte array expression of one-dimensional barcode.
 Start code and end code should be included in result, and side margins should not be included.

Specified by:
encode in class OneDimensionalCodeWriter

Returns:
a byte array of horizontal pixels (0 = white, 1 = black)

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
define(["exports", "foo"], function (exports, _foo) {
  "use strict";

  var _foo2 = babelHelpers.interopRequire(_foo);

  var _foo22 = babelHelpers.interopRequire(_foo);

  _foo2;
  _foo22;
});


text:
layout: post
title: Betrayed
date: 2013-07-26 21:17
author: admin
comments: true
---
I can't believe I'm sharing this on the internet but it's true.

BW has been cheating on me.

Yes, she's been watching a new netflix series without me!. *

She calls it 'tabletto'-her little movie watching tablet she bought for her trip. And it was love at first sight. In hindsight I should have seen this coming,the way she spent hours with it under her blanket at night caressing its face.

"What are you doing?" I would ask and she told me she was reading the New York Times. I never thought it would come to this. I believed her.

I was told the new tablet purchase was for downloading books - you know - all proffessory and the like. So gullible like I am, I believed her. I feel so betrayed.

But as soon as she left our happy little home she broke the one sacred rule in our household:

She watched a show on the TV without me!

I thought for sure we had the talk before we left: "Be true to me" I said  - reminding her of our sacred vows to consume mindless drivel on the TV together for ever and ever. (I'm pretty sure that's what the minister said on our wedding day. Something about sickness and in health too, but I don't really recall, because I was so nervous I thought I was going to pass out)

Anyway, the TV watching.

Like newlyweds we were, we watched so many shows together. The cooking shows, the real estate shows, the west wing, game of thrones, a series about mormons and even NFL football games!

But with a click of a button on her tablet she pressed play - never thinking of the consequences. I'll never be able  to catch up with her manic watching of episode after episode.

There's just no way this will ever work now. Our circle of trust has been broken.

It wasn't always like this. We used to make tea and hold hands with the pale blue glow reflecting off the walls and our happy faces and with a farting dog at our feet we'd bask in the glow of the characters on the big screen, for they seemed larger than life.

But now, it's different.

She'll always be a season or two ahead of me now. It will never be like it was before.

"But I didn't know it would upset you so much" she said when I asked her why, oh why, oh why???!! How could she do this?

"You can catch up" she said, but it was too late. She knew too much. Her life included new characters now with stories I knew nothing of.

In despair I resorted to old Carol Burnett reruns on youtube. It was all I could handle. The one show that didn't remind me of her.

I tried to watch other shows on netflix but the pain was so great. Every series listed was just too harsh a reminder of the good times we once had.

She told me: "I'll stop". But she doesn't understand the pain. Watching an episode knowing she's already watched it. Oh, I can't even imagine the horror.

"You'll like the show" she said,trying to convince me to watch and watch to get our TV watching clocks synched once again but I can't somehow feel like this will never be the same again. "It's weird, you'll like it" she said. "Don't tell me the name! I don't want to know!" I said as I quickly changed the topic.

I needed something new to talk about. Another topic - the weather, the dog, her work, something.

I asked her when she was coming back?

"Soon" , she replied

"Good" I said, "I found this show...looks pretty good....."

Less than 2 weeks to go. Not that I'm counting.

* "Orange is the New Black" On netflix.


text: This is a custom help book for the PUnQlite framework.


text:
ALTER TABLE GSPANOTHER.C_TABLE
ADD CONSTRAINT PK_B_TABLE1 PRIMARY KEY
(
  C_ID
);
CREATE UNIQUE INDEX PK_B_TABLE1 ON GSPANOTHER.C_TABLE
(
  C_ID
);


text:
package org.apache.jackrabbit.oak.segment.standby.codec;

import static org.apache.jackrabbit.oak.segment.standby.codec.Messages.newGetSegmentRequest;
import static org.junit.Assert.assertEquals;

import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test;

public class GetSegmentRequestEncoderTest {

    @Test
    public void encodeRequest() throws Exception {
        EmbeddedChannel channel = new EmbeddedChannel(new GetSegmentRequestEncoder());
        channel.writeOutbound(new GetSegmentRequest("clientId", "segmentId"));
        String message = (String) channel.readOutbound();
        assertEquals(newGetSegmentRequest("clientId", "segmentId"), message);
    }

}


text:
import logging

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.mail import get_connection
from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.translation import override

from wagtail.admin.auth import users_with_page_permission
from wagtail.core.models import GroupApprovalTask, TaskState, WorkflowState
from wagtail.core.utils import camelcase_to_underscore
from wagtail.users.models import UserProfile

logger = logging.getLogger('wagtail.admin')

class OpenedConnection:
    """Context manager for mail connections to ensure they are closed when manually opened"""
    def __init__(self, connection):
        self.connection = connection

    def __enter__(self):
        self.connection.open()
        return self.connection

    def __exit__(self, type, value, traceback):
        self.connection.close()
        return self.connection

def send_mail(subject, message, recipient_list, from_email=None, **kwargs):
    """
    Wrapper around Django's EmailMultiAlternatives as done in send_mail().
    Custom from_email handling and special Auto-Submitted header.
    """
    if not from_email:
        if hasattr(settings, 'WAGTAILADMIN_NOTIFICATION_FROM_EMAIL'):
            from_email = settings.WAGTAILADMIN_NOTIFICATION_FROM_EMAIL
        elif hasattr(settings, 'DEFAULT_FROM_EMAIL'):
            from_email = settings.DEFAULT_FROM_EMAIL
        else:
            # We are no longer using the term `webmaster` except in this case, where we continue to match Django's default: https://github.com/django/django/blob/stable/3.2.x/django/conf/global_settings.py#L223
            from_email = 'webmaster@localhost'

    connection = kwargs.get('connection', False) or get_connection(
        username=kwargs.get('auth_user', None),
        password=kwargs.get('auth_password', None),
        fail_silently=kwargs.get('fail_silently', None),
    )
    multi_alt_kwargs = {
        'connection': connection,
        'headers': {
            'Auto-Submitted': 'auto-generated',
        }
    }
    mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, **multi_alt_kwargs)
    html_message = kwargs.get('html_message', None)
    if html_message:
        mail.attach_alternative(html_message, 'text/html')

    return mail.send()

def send_moderation_notification(revision, notification, excluded_user=None):
    # Get list of recipients
    if notification == 'submitted':
        # Get list of publishers
        include_superusers = getattr(settings, 'WAGTAILADMIN_NOTIFICATION_INCLUDE_SUPERUSERS', True)
        recipient_users = users_with_page_permission(revision.page, 'publish', include_superusers)
    elif notification in ['rejected', 'approved']:
        # Get submitter
        recipient_users = [revision.user]
    else:
        return False

    if excluded_user:
        recipient_users = [user for user in recipient_users if user != excluded_user]

    return send_notification(recipient_users, notification, {'revision': revision})

def send_notification(recipient_users, notification, extra_context):
    # Get list of email addresses
    email_recipients = [
        recipient for recipient in recipient_users
        if recipient.is_active and recipient.email and getattr(
            UserProfile.get_for_user(recipient),
            notification + '_notifications'
        )
    ]

    # Return if there are no email addresses
    if not email_recipients:
        return True

    # Get template
    template_subject = 'wagtailadmin/notifications/' + notification + '_subject.txt'
    template_text = 'wagtailadmin/notifications/' + notification + '.txt'
    template_html = 'wagtailadmin/notifications/' + notification + '.html'

    # Common context to template
    context = {
        "settings": settings,
    }
    context.update(extra_context)

    connection = get_connection()

    with OpenedConnection(connection) as open_connection:

        # Send emails
        sent_count = 0
        for recipient in email_recipients:
            try:
                # update context with this recipient
                context["user"] = recipient

                # Translate text to the recipient language settings
                with override(recipient.wagtail_userprofile.get_preferred_language()):
                    # Get email subject and content
                    email_subject = render_to_string(template_subject, context).strip()
                    email_content = render_to_string(template_text, context).strip()

                kwargs = {}
                if getattr(settings, 'WAGTAILADMIN_NOTIFICATION_USE_HTML', False):
                    kwargs['html_message'] = render_to_string(template_html, context)

                # Send email
                send_mail(email_subject, email_content, [recipient.email], connection=open_connection, **kwargs)
                sent_count += 1
            except Exception:
                logger.exception(
                    "Failed to send notification email '%s' to %s",
                    email_subject, recipient.email
                )

    return sent_count == len(email_recipients)

class Notifier:
    """Generic class for sending event notifications: callable, intended to be connected to a signal to send
    notifications using rendered templates. """

    notification = ''
    template_directory = 'wagtailadmin/notifications/'

    def __init__(self, valid_classes):
        # the classes of the calling instance that the notifier can handle
        self.valid_classes = valid_classes

    def can_handle(self, instance, **kwargs):
        """Returns True if the Notifier can handle sending the notification from the instance, otherwise False"""
        return isinstance(instance, self.valid_classes)

    def get_valid_recipients(self, instance, **kwargs):
        """Returns a set of the final list of recipients for the notification message"""
        return set()

    def get_template_base_prefix(self, instance, **kwargs):
        return camelcase_to_underscore(type(instance).__name__) + '_'

    def get_context(self, instance, **kwargs):
        return {'settings': settings}

    def get_template_set(self, instance, **kwargs):
        """Return a dictionary of template paths for the templates: by default, a text message"""
        template_base = self.get_template_base_prefix(instance) + self.notification

        template_text = self.template_directory + template_base + '.txt'

        return {
            'text': template_text,
        }

    def send_notifications(self, template_set, context, recipients, **kwargs):
        raise NotImplementedError

    def __call__(self, instance=None, **kwargs):
        """Send notifications from an instance (intended to be the signal sender), returning True if all sent correctly
        and False otherwise"""

        if not self.can_handle(instance, **kwargs):
            return False

        recipients = self.get_valid_recipients(instance, **kwargs)

        if not recipients:
            return True

        template_set = self.get_template_set(instance, **kwargs)

        context = self.get_context(instance, **kwargs)

        return self.send_notifications(template_set, context, recipients, **kwargs)

class EmailNotificationMixin:
    """Mixin for sending email notifications upon events"""

    def get_recipient_users(self, instance, **kwargs):
        """Gets the ideal set of recipient users, without accounting for notification preferences or missing email addresses"""

        return set()

    def get_valid_recipients(self, instance, **kwargs):
        """Filters notification recipients to those allowing the notification type on their UserProfile, and those
        with an email address"""
        return {
            recipient for recipient in self.get_recipient_users(instance, **kwargs)
            if recipient.is_active and recipient.email and getattr(
                UserProfile.get_for_user(recipient),
                self.notification + '_notifications'
            )
        }

    def get_template_set(self, instance, **kwargs):
        """Return a dictionary of template paths for the templates for the email subject and the text and html
        alternatives"""
        template_base = self.get_template_base_prefix(instance) + self.notification

        template_subject = self.template_directory + template_base + '_subject.txt'
        template_text = self.template_directory + template_base + '.txt'
        template_html = self.template_directory + template_base + '.html'

        return {
            'subject': template_subject,
            'text': template_text,
            'html': template_html,
        }

    def send_emails(self, template_set, context, recipients, **kwargs):

        connection = get_connection()
        sent_count = 0
        try:
            with OpenedConnection(connection) as open_connection:

                # Send emails
                for recipient in recipients:
                    try:

                        # update context with this recipient
                        context["user"] = recipient

                        # Translate text to the recipient language settings
                        with override(recipient.wagtail_userprofile.get_preferred_language()):
                            # Get email subject and content
                            email_subject = render_to_string(template_set['subject'], context).strip()
                            email_content = render_to_string(template_set['text'], context).strip()

                        kwargs = {}
                        if getattr(settings, 'WAGTAILADMIN_NOTIFICATION_USE_HTML', False):
                            kwargs['html_message'] = render_to_string(template_set['html'], context)

                        # Send email
                        send_mail(email_subject, email_content, [recipient.email], connection=open_connection, **kwargs)
                        sent_count += 1
                    except Exception:
                        logger.exception(
                            "Failed to send notification email '%s' to %s",
                            email_subject, recipient.email
                        )
        except (TimeoutError, ConnectionError):
            logger.exception("Mail connection error, notification sending skipped")

        return sent_count == len(recipients)

    def send_notifications(self, template_set, context, recipients, **kwargs):
        return self.send_emails(template_set, context, recipients, **kwargs)

class BaseWorkflowStateEmailNotifier(EmailNotificationMixin, Notifier):
    """A base notifier to send email updates for WorkflowState events"""

    def __init__(self):
        super().__init__((WorkflowState,))

    def get_context(self, workflow_state, **kwargs):
        context = super().get_context(workflow_state, **kwargs)
        context['page'] = workflow_state.page
        context['workflow'] = workflow_state.workflow
        return context

class WorkflowStateApprovalEmailNotifier(BaseWorkflowStateEmailNotifier):
    """A notifier to send email updates for WorkflowState approval events"""

    notification = 'approved'

    def get_recipient_users(self, workflow_state, **kwargs):
        triggering_user = kwargs.get('user', None)
        recipients = {}
        requested_by = workflow_state.requested_by
        if requested_by != triggering_user:
            recipients = {requested_by}

        return recipients

class WorkflowStateRejectionEmailNotifier(BaseWorkflowStateEmailNotifier):
    """A notifier to send email updates for WorkflowState rejection events"""

    notification = 'rejected'

    def get_recipient_users(self, workflow_state, **kwargs):
        triggering_user = kwargs.get('user', None)
        recipients = {}
        requested_by = workflow_state.requested_by
        if requested_by != triggering_user:
            recipients = {requested_by}

        return recipients

    def get_context(self, workflow_state, **kwargs):
        context = super().get_context(workflow_state, **kwargs)
        task_state = workflow_state.current_task_state.specific
        context['task'] = task_state.task
        context['task_state'] = task_state
        context['comment'] = task_state.get_comment()
        return context

class WorkflowStateSubmissionEmailNotifier(BaseWorkflowStateEmailNotifier):
    """A notifier to send email updates for WorkflowState submission events"""

    notification = 'submitted'

    def get_recipient_users(self, workflow_state, **kwargs):
        triggering_user = kwargs.get('user', None)
        recipients = get_user_model().objects.none()
        include_superusers = getattr(settings, 'WAGTAILADMIN_NOTIFICATION_INCLUDE_SUPERUSERS', True)
        if include_superusers:
            recipients = get_user_model().objects.filter(is_superuser=True)
        if triggering_user:
            recipients.exclude(pk=triggering_user.pk)

        return recipients

    def get_context(self, workflow_state, **kwargs):
        context = super().get_context(workflow_state, **kwargs)
        context['requested_by'] = workflow_state.requested_by
        return context

class BaseGroupApprovalTaskStateEmailNotifier(EmailNotificationMixin, Notifier):
    """A base notifier to send email updates for GroupApprovalTask events"""

    def __init__(self):
        super().__init__((TaskState,))

    def can_handle(self, instance, **kwargs):
        if super().can_handle(instance, **kwargs) and isinstance(instance.task.specific, GroupApprovalTask):
            return True
        return False

    def get_context(self, task_state, **kwargs):
        context = super().get_context(task_state, **kwargs)
        context['page'] = task_state.workflow_state.page
        context['task'] = task_state.task.specific
        return context

    def get_recipient_users(self, task_state, **kwargs):
        triggering_user = kwargs.get('user', None)

        group_members = get_user_model().objects.filter(groups__in=task_state.task.specific.groups.all())

        recipients = group_members

        include_superusers = getattr(settings, 'WAGTAILADMIN_NOTIFICATION_INCLUDE_SUPERUSERS', True)
        if include_superusers:
            superusers = get_user_model().objects.filter(is_superuser=True)
            recipients = recipients | superusers

        if triggering_user:
            recipients = recipients.exclude(pk=triggering_user.pk)

        return recipients

class GroupApprovalTaskStateSubmissionEmailNotifier(BaseGroupApprovalTaskStateEmailNotifier):
    """A notifier to send email updates for GroupApprovalTask submission events"""

    notification = 'submitted'


text:
from django.forms import ModelForm, BooleanField, Textarea, FileInput, TextInput, CharField
from cog.models import *
from cog.forms.forms_image import ImageForm
from cog.models.constants import RESEARCH_KEYWORDS_MAX_CHARS
from django.forms.models import BaseModelFormSet
from cog.forms.forms_utils import validate_image

class AboutusForm(ModelForm):

    class Meta:
        model = Project

        fields = ('long_name', 'description', 'external_homepage',  # ABOUTUS
                  'mission',  # MISSION
                  'vision',   # VISION
                  'values',   # VALUES
                  'history',  # HISTORY
                  'projectContacts', 'technicalSupport', 'meetingSupport', 'getInvolved',  # CONTACTUS
                  'site',
                  )

        widgets = {
            'description':  Textarea(attrs={'rows': 8}),
            'mission':     Textarea(attrs={'rows': 8}),
            'vision':      Textarea(attrs={'rows': 8}),
            'values':      Textarea(attrs={'rows': 8}),
            'history':     Textarea(attrs={'rows': 12}),
        }

# Custom form to define custom widget, and use 'delete_image' field
class OrganizationForm(ImageForm):

    class Meta:
        model = Organization
        fields = "__all__"
        widgets = {
            'name': TextInput(attrs={'size': 30}),
            'url': TextInput(attrs={'size': 30}),
            'image': FileInput(),
        }

# Custom form to define custom widget, and use 'delete_image' field
class FundingSourceForm(ImageForm):

    class Meta:
        model = FundingSource
        fields = "__all__"
        widgets = {
            'name': TextInput(attrs={'size': 30}),
            'url': TextInput(attrs={'size': 30}),
            'image': FileInput(),
        }

# Custom form to define custom widget, and use 'delete_image' field
class CollaboratorForm(ImageForm):

    class Meta:
        model = Collaborator
        fields = "__all__"
        widgets = {
            'first_name': TextInput(attrs={'size': 20}),
            'last_name': TextInput(attrs={'size': 20}),
            'institution': TextInput(attrs={'size': 15}),
            'researchKeywords': TextInput(attrs={'size': 20}),
            'image': FileInput(),
        }

    # override form clean() method to execute image validation
    def clean(self):

        # invoke superclass cleaning method
        super(CollaboratorForm, self).clean()

        # additional validation on 'image' field
        validate_image(self, 'image')

        return self.cleaned_data


text:
require 'spec_helper'
require 'rest_spec_helper'
require 'rhc/commands/domain'

describe RHC::Commands::Domain do
  let(:rest_client){ MockRestClient.new }
  before{ user_config }

  describe 'default action' do
    before{ rest_client }
    context 'when run with no domains' do
      let(:arguments) { ['domain'] }

      it { expect { run }.to exit_with_code(1) }
      it { run_output.should match(/To create your first domain.*rhc create-domain/m) }
    end
    context 'when help is shown' do
      let(:arguments) { ['domain', '--noprompt', '--help'] }

      it { expect { run }.to exit_with_code(0) }
      it { run_output.should match(/configure.*delete.*leave.*list.*rename/m) }
    end
  end

  describe 'show' do
    before{ rest_client }
    let(:arguments) { ['domain', 'show'] }

    context 'when run with no domains' do
      it { expect { run }.to exit_with_code(1) }
      it { run_output.should match(/In order to deploy applications, you must create a domain/m) }
    end

    context 'when run with one domain no apps' do
      before{ rest_client.add_domain("onedomain") }

      it { expect { run }.to exit_with_code(0) }
      it "should match output" do
        output = run_output
        output.should match("The domain onedomain exists but has no applications. You can use")
      end
    end

    context 'when run with multiple domain no apps' do
      before do
        rest_client.add_domain("firstdomain")
        rest_client.add_domain("seconddomain")
      end
      it { expect { run }.to exit_with_code(0) }
      it "should match output" do
        output = run_output
        output.should match("The domain firstdomain exists but has no applications. You can use")
        output.should_not match("Applications in seconddomain")
      end
    end

    context 'when run with one domain multiple apps' do
      before do
        d = rest_client.add_domain("appdomain")
        a = d.add_application("app_no_carts", "testframework-1.0")
        a = d.add_application("app_multi_carts", "testframework-1.0")
        a.add_cartridge("testcart-1")
        a.add_cartridge("testcart-2")
        a.add_cartridge("testcart-3")
      end
      it { expect { run }.to exit_with_code(0) }
      it "should match output" do
        output = run_output
        output.should match("app_no_carts")
        output.should match("app_multi_carts")
        output.should match("testframework-1.0")
        output.should match("testcart-1")
        output.should match("testcart-2")
        output.should match("testcart-3")
      end
    end

    context 'when run with an app without cartridges' do
      before do
        d = rest_client.add_domain("appdomain")
        a = d.add_application("app_no_carts")
      end
      it { expect { run }.to exit_with_code(0) }
      it "should match output" do
        output = run_output
        output.should match("app_no_carts")
        output.should match(/127.0.0.1\s*$/m)
      end
    end
  end

  describe 'list' do
    before{ rest_client }
    let(:arguments) { ['domain', 'list'] }

    context 'when run with no domains' do
      it { expect { run }.to exit_with_code(1) }
      it { run_output.should match(/In order to deploy applications.*rhc create-domain/) }
    end

    context 'when run with one domain no apps' do
      before{ rest_client.add_domain("onedomain") }

      it { expect { run }.to exit_with_code(0) }
      it "should match output" do
        output = run_output
        output.should match("You have access to 1 domain\\.")
        output.should match("onedomain")
      end

      context 'when has no creation date, members, or allowed_gear_sizes' do
        before{ rest_client.domains.first.attributes.merge(:creation_date => nil, :allowed_gear_sizes => nil, :members => nil, :id => '123') }
        it { expect { run }.to exit_with_code(0) }
        it "should match output" do
          output = run_output
          output.should match("onedomain")
          output.should_not match ("Allowed Gear Sizes:")
          output.should_not match ("Created:")
          output.should_not match ("Members:")
          output.should_not match ("ID:.*")
        end
      end
      context 'when an ID is present and differs from name' do
        let(:arguments) { ['domain', 'list', '--ids'] }
        before{ rest_client.domains.first.attributes['id'] = '123' }
        it { expect { run }.to exit_with_code(0) }
        it "should match output" do
          output = run_output
          output.should match("onedomain")
          output.should match ("ID:.*123")
        end
      end
      context 'when an ID is present and identical to name' do
        let(:arguments) { ['domain', 'list', '--ids'] }
        before{ rest_client.domains.first.attributes['id'] = 'onedomain' }
        it { expect { run }.to exit_with_code(0) }
        it "should not match output" do
          run_output.should_not match ("ID:.*123")
        end
      end
      context 'when an ID is present and name is not' do
        let(:arguments) { ['domain', 'list', '--ids'] }
        before{ rest_client.domains.first.attributes['id'] = 'onedomain' }
        before{ rest_client.domains.first.instance_variable_set(:@name, nil) }
        it { expect { run }.to exit_with_code(0) }
        it "should match output" do
          run_output.should match ("onedomain")
          run_output.should_not match ("ID:.*")
        end
      end
    end

    context 'when run with one owned domain' do
      let(:arguments) { ['domains', '--mine'] }
      before{ d = rest_client.add_domain('mine', true); rest_client.stub(:owned_domains).and_return([d]) }

      it { expect { run }.to exit_with_code(0) }
      it "should match output" do
        output = run_output
        output.should match("You have access to 1 domain\\.")
        output.should match("mine")
        output.should match("Created")
        output.should match("Allowed Gear Sizes: small")
      end
    end

    context 'when run with multiple domains and extra domain info' do
      before do
        rest_client.add_domain("firstdomain")
        rest_client.add_domain("seconddomain", true)
      end
      it { expect { run }.to exit_with_code(0) }
      it "should match output" do
        output = run_output
        output.should match("You have access to 2 domains")
        output.should match("seconddomain \\(owned by a_user_name\\)")
        output.should match("Created")
        output.should match("Allowed Gear Sizes: small")
      end
    end
  end

  describe 'create' do
    before{ rest_client }
    let(:arguments) { ['domain', 'create', 'testnamespace'] }

    context 'when no issues with ' do

      it "should create a domain" do
        expect { run }.to exit_with_code(0)
        rest_client.domains[0].name.should == 'testnamespace'
      end
      it { run_output.should match(/Creating.*'testnamespace'.*done/m) }
    end
  end

  describe 'rename' do
    before{ rest_client }
    let(:arguments) { ['domain', 'rename', 'olddomain', 'alterednamespace'] }

    context 'when no issues with ' do
      before{ rest_client.add_domain("olddomain") }

      it "should update a domain" do
        expect { run }.to exit_with_code(0)
        rest_client.domains[0].name.should == 'alterednamespace'
      end
      it { run_output.should match(/Renaming domain 'olddomain' to 'alterednamespace'.*done.*?Applications created in this domain will use the new name in their URL./m) }
    end

    context 'when there is no domain' do
      it "should not create a domain" do
        expect { run }.to exit_with_code(127)
        rest_client.domains.empty?.should be_true
      end
      it { run_output.should match("not found") }
    end
  end

  describe 'update' do
    before{ rest_client }
    let(:arguments) { ['domain', 'update', 'olddomain', 'alterednamespace'] }

    before{ rest_client.add_domain("olddomain") }
    it "should update a domain" do
      expect { run }.to exit_with_code(0)
      rest_client.domains[0].name.should == 'alterednamespace'
    end
    it { run_output.should match(/This command is deprecated.*Renaming domain 'olddomain' to 'alterednamespace'.*done.*?Applications created in this domain will use the new name in their URL./m) }
  end

  describe 'alter alias has been removed' do
    let(:arguments) { ['domain', 'alter', 'olddomain', 'alterednamespace'] }
    it{ expect { run }.to exit_with_code(1) }
  end

  describe 'configure' do
    context "no settings" do
      before{ rest_client.add_domain("domain1") }
      let(:arguments) { ['domain', 'configure', '-n', 'domain1'] }
      it("should succeed"){ expect { run }.to exit_with_code(0) }
      it("should display the domain config"){ run_output.should match(/Domain domain1 configuration/m) }
      it("should not display the domain config without gear sizes"){ run_output.should_not match(/Allowed Gear Sizes/) }

      context "server supports allowed gear sizes" do
        before{ rest_client.domains.first.should_receive(:allowed_gear_sizes).and_return([]) }
        it("should display the domain config"){ run_output.should match(/Domain domain1 configuration.*Allowed Gear Sizes:\s+<none>/m) }
      end
      context "server supports allowed gear sizes" do
        before{ rest_client.domains.first.should_receive(:allowed_gear_sizes).and_return(['small', 'medium']) }
        it("should display the domain config"){ run_output.should match(/Domain domain1 configuration.*Allowed Gear Sizes:\s+small, medium/m) }
      end
    end

    context "when server does not support allowed-gear-sizes" do
      before do
        rest_client.add_domain("domain1")
        rest_client.api.should_receive(:has_param?).with(:add_domain, 'allowed_gear_sizes').and_return(false)
      end
      let(:arguments) { ['domain', 'configure', '--allowed-gear-sizes', 'small'] }
      it("display a message"){ run_output.should match 'The server does not support --allowed-gear-sizes' }
    end

    context "against a server that supports gear sizes" do
      let(:username){ 'test_user' }
      let(:password){ 'password' }
      let(:server){ 'test.domain.com' }
      let(:supports_allowed_gear_sizes?){ true }
      before{ subject.class.any_instance.stub(:namespace_context).and_return('domain1') }
      before do
        stub_api
        challenge{ stub_one_domain('domain1', nil, mock_user_auth) }
      end

      context "with --allowed-gear-sizes singular" do
        before do
          stub_api_request(:put, "domains/domain1/update", nil).
            with(:body => {:allowed_gear_sizes => ['valid']}).
            to_return({:body => {:type => 'domain', :data => {:name => 'domain1', :allowed_gear_sizes => ['valid']}, :messages => [{:severity => 'info', :text => 'Updated allowed gear sizes'},]}.to_json, :status => 200})
        end
        let(:arguments) { ['domain', 'configure', '--trace', '--allowed-gear-sizes', 'valid'] }
      it("should succeed"){ expect { run }.to exit_with_code(0) }
      it("should display the domain config"){ run_output.should match(/Domain domain1 configuration.*Allowed Gear Sizes:\s+valid/m) }
      end

      context "with --allowed-gear-sizes multiple" do
        before do
          stub_api_request(:put, "domains/domain1/update", nil).
            with(:body => {:allowed_gear_sizes => ['one', 'two']}).
            to_return({:body => {:type => 'domain', :data => {:name => 'domain1', :allowed_gear_sizes => ['one', 'two']}, :messages => [{:severity => 'info', :text => 'Updated allowed gear sizes'},]}.to_json, :status => 200})
        end
        let(:arguments) { ['domain', 'configure', '--trace', '--allowed-gear-sizes', 'one,two'] }
        it("should succeed"){ expect { run }.to exit_with_code(0) }
        it("should display the domain config"){ run_output.should match(/Domain domain1 configuration.*Allowed Gear Sizes:\s+one, two/m) }
      end

      context "with --allowed-gear-sizes" do
        let(:arguments) { ['domain', 'configure', 'domain1', '--trace', '--allowed-gear-sizes'] }
        it("raise an invalid option"){ expect{ run }.to raise_error(OptionParser::InvalidOption, /Provide a comma delimited list of valid gear/) }
      end

      context "with --allowed-gear-sizes=false" do
        before do
          stub_api_request(:put, "domains/domain1/update", nil).
            with(:body => {:allowed_gear_sizes => ['false']}).
            to_return({:body => {:type => 'domain', :messages => [{:field => 'allowed_gear_sizes', :exit_code => 10, :severity => 'error', :text => 'The specified gear size is invalid: false'},]}.to_json, :status => 422})
        end
        let(:arguments) { ['domain', 'configure', '--allowed-gear-sizes=false'] }
        it("should succeed"){ expect { run }.to exit_with_code(1) }
        it("should display the domain config"){ run_output.should match(/Updating domain configuration.*The specified gear size is invalid/m) }
      end

      context "with --no-allowed-gear-sizes" do
        before do
          stub_api_request(:put, "domains/domain1/update", nil).
            with(:body => {:allowed_gear_sizes => []}).
            to_return({:body => {:type => 'domain', :data => {:name => 'domain1', :allowed_gear_sizes => []}, :messages => [{:severity => 'info', :text => 'Updated allowed gear sizes'},]}.to_json, :status => 200})
        end
        let(:arguments) { ['domain', 'configure', '--no-allowed-gear-sizes'] }
        it("should succeed"){ expect { run }.to exit_with_code(0) }
        it("should display the domain config"){ run_output.should match(/Domain domain1 configuration.*Allowed Gear Sizes:\s+<none>/m) }
      end

      context "with --allowed-gear-sizes and --no-allowed-gear-sizes" do
        let(:arguments) { ['domain', 'configure', 'domain1', '--trace', '--no-allowed-gear-sizes', '--allowed-gear-sizes', 'small'] }
        it("raise an invalid option"){ expect{ run }.to raise_error(OptionParser::InvalidOption, /--allowed-gear-sizes.*--no-allowed-gear-sizes/) }
      end
    end
  end

  describe 'leave' do
    before{ rest_client.add_domain("deleteme") }
    let(:arguments) { ['domain', 'leave', '-n', 'deleteme'] }

    it "should leave the domain" do
      rest_client.domains.first.should_receive(:leave).and_return(RHC::Rest::Membership::Member.new)
      expect { run }.to exit_with_code(0)
    end
  end

  describe 'delete' do
    before{ rest_client }
    let(:arguments) { ['domain', 'delete', 'deleteme'] }

    context 'when no issues with ' do
      before{ rest_client.add_domain("deleteme") }

      it "should delete a domain" do
        expect { run }.to exit_with_code(0)
        rest_client.domains.empty?.should be_true
      end
    end

    context 'when there is a different domain' do
      before{ rest_client.add_domain("dontdelete") }

      it "should error out" do
        expect { run }.to exit_with_code(127)
        rest_client.domains[0].name.should == 'dontdelete'
      end
      it { run_output.should match("Domain deleteme not found") }
    end

    context 'when there are applications on the domain' do
      before do
        domain = rest_client.add_domain("deleteme")
        domain.add_application 'testapp1', 'mock-1.0'
      end
      it "should error out" do
        expect { run }.to exit_with_code(1)
        rest_client.domains[0].name.should == 'deleteme'
      end
      it { run_output.should match("Applications must be empty") }
    end

    context 'when delete is forced' do
      let(:arguments) { ['domain', 'delete', 'deleteme', '--force'] }
      before do
        domain = rest_client.add_domain("deleteme")
        domain.add_application 'testapp1', 'mock-1.0'
      end
      it "should delete successfully" do
        expect { run }.to exit_with_code(0)
        rest_client.domains.empty?.should be_true
      end
    end

  end

  describe 'help' do
    let(:arguments) { ['domain', '--help'] }

    context 'help is run' do
      it "should display help" do
        expect { run }.to exit_with_code(0)
      end
      it('should output usage') { run_output.should match("Usage: rhc domain") }
    end
  end
end


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
Trees shrubs hardy Brit. Isles 2:252. 1914

#### Original name
null

### Remarks
null