text:
package examples;

import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.json.simple.parser.ParseException;

import com.github.jreddit.oauth.RedditOAuthAgent;
import com.github.jreddit.oauth.app.RedditApp;
import com.github.jreddit.oauth.app.RedditInstalledApp;
import com.github.jreddit.oauth.param.RedditDuration;
import com.github.jreddit.oauth.param.RedditScope;
import com.github.jreddit.oauth.param.RedditScopeBuilder;

public class ExampleUserCodeFlowAuthorization {

    public static void main(String[] args) throws OAuthSystemException, OAuthProblemException, ParseException {

        // Information about the app
        String userAgent = "jReddit: Reddit API Wrapper for Java";
        String clientID = "PfnhLt3VahLrbg";
        String redirectURI = "https://github.com/snkas/jReddit";

        // Reddit application
        RedditApp redditApp = new RedditInstalledApp(clientID, redirectURI);

        // Create OAuth agent
        RedditOAuthAgent agent = new RedditOAuthAgent(userAgent, redditApp);

        // Create scope
        RedditScopeBuilder scope = new RedditScopeBuilder().addScope(RedditScope.FLAIR);

        // Show URI for the user
        System.out.println(agent.generateCodeFlowURI(scope, RedditDuration.PERMANENT));

    }

}


text:
package matchers

import (
	"fmt"
	"reflect"

	"github.com/onsi/gomega/format"
)

type EqualMatcher struct {
	Expected interface{}
}

func (matcher *EqualMatcher) Match(actual interface{}) (success bool, err error) {
	if actual == nil && matcher.Expected == nil {
		return false, fmt.Errorf("Refusing to compare <nil> to <nil>.\nBe explicit and use BeNil() instead.  This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.")
	}
	return reflect.DeepEqual(actual, matcher.Expected), nil
}

func (matcher *EqualMatcher) FailureMessage(actual interface{}) (message string) {
	actualString, actualOK := actual.(string)
	expectedString, expectedOK := matcher.Expected.(string)
	if actualOK && expectedOK {
		return format.MessageWithDiff(actualString, "to equal", expectedString)
	}

	return format.Message(actual, "to equal", matcher.Expected)
}

func (matcher *EqualMatcher) NegatedFailureMessage(actual interface{}) (message string) {
	return format.Message(actual, "not to equal", matcher.Expected)
}

redpajama_set_name: RedPajamaGithub


text:
{% extends "flatpages/foundation.html" %}

{% block title %}Thanks for your support!{% endblock %}

{% block content %}

Thanks for your support!

Thank you for supporting Django. If you like, you can use one of the badges below to show your support and help us bring in other donors.

Copy and paste the source below each image to link to our donation page.

<textarea rows="3" cols="60" class="codedump"></textarea>
126x54 I donated to Django (green)

<textarea rows="3" cols="60" class="codedump"></textarea>
126x54 I donated to Django (grey)

{% endblock %}


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

using ASC.Web.Studio.PublicResources;

namespace ASC.Web.Studio.UserControls.Common.Comments
{
    [ToolboxData("<{0}:CommentsList runat=server></{0}:CommentsList>")]
    public sealed class CommentsList : WebControl
    {
        public delegate string FCKBasePathRequestHandler();

        public CommentsList()
        {
        }

        #region Members

        private static bool _isClientScriptRegistered;
        private int _maxDepthLevel = 8;

        private string JsObjName
        {
            get { return String.IsNullOrEmpty(BehaviorID) ? "__comments" + UniqueID : BehaviorID; }
        }

        private IList<CommentInfo> _items = new List<CommentInfo>(0);

        private string _objectID = string.Empty;
        private bool _isShowAddCommentBtn = true;
        private bool _showCaption = true;

        #endregion

        #region Properties

        public string FckDomainName { get; set; }

        public string OnEditedCommentJS { get; set; }
        public string OnRemovedCommentJS { get; set; }
        public string OnCanceledCommentJS { get; set; }

        public int MaxDepthLevel
        {
            get { return _maxDepthLevel; }
            set { _maxDepthLevel = value; }
        }

        public bool IsShowAddCommentBtn
        {
            get { return _isShowAddCommentBtn; }
            set { _isShowAddCommentBtn = value; }
        }

        public bool ShowCaption
        {
            get { return _showCaption; }
            set { _showCaption = value; }
        }

        public string BehaviorID { get; set; }

        public IList<CommentInfo> Items
        {
            get { return _items; }
            set { _items = value; }
        }

        public string ModuleName { get; set; }

        public string JavaScriptCallBackAddComment { get; set; }

        public string ConfirmRemoveCommentMessage { get; set; }

        public string ObjectID
        {
            get { return _objectID; }
            set { _objectID = value; }
        }

        public int TotalCount { get; set; }

        public bool? InitJS { get; set; }

        #endregion

        #region Methods

        public static bool IsActiveOrHasActiveComments(CommentInfo item)
        {
            if (item == null)
                return false;

            if (!item.Inactive)
                return true;

            //then if Inactive == true
            if (item.CommentList == null || item.CommentList.Count == 0)
                return false;

            foreach (var c in item.CommentList)
            {
                if (IsActiveOrHasActiveComments(c))
                {
                    return true;
                }
            }
            return false;
        }

        public static List<CommentInfo> CleanInactive(List<CommentInfo> items)
        {
            if (items == null)
                return null;

            for (var i = 0; i < items.Count; i++)
            {
                if (!IsActiveOrHasActiveComments(items[i]))
                {
                    items.RemoveAt(i);
                    i--;
                }
                else
                {
                    items[i].CommentList = CleanInactive(items[i].CommentList.ToList());
                }
            }
            return items;
        }

        private void RegisterClientScripts()
        {
            Page
                .RegisterBodyScripts("~/UserControls/Common/ckeditor/ckeditor-connector.js",
                    "~/js/uploader/ajaxupload.js",
                    "~/UserControls/Common/Comments/js/comments.js",
                    "~/js/third-party/highlight.pack.js")
                .RegisterInlineScript("hljs.initHighlightingOnLoad();")
                .RegisterStyle("~/UserControls/Common/Comments/css/codehighlighter/vs.less");

            var uploadPath = string.Format("{0}://{1}:{2}{3}", Page.Request.GetUrlRewriter().Scheme, Page.Request.GetUrlRewriter().Host, Page.Request.GetUrlRewriter().Port, VirtualPathUtility.ToAbsolute("~/") + "fckuploader.ashx");
            uploadPath += "?esid=" + FckDomainName;

            Items = CleanInactive(Items.ToList());

            var paramsScript = string.Format(@"
                        CommentsManagerObj.javaScriptCallBackAddComment = '{0}';
                        CommentsManagerObj.moduleName = '{1}';
                        ",
                                            JavaScriptCallBackAddComment,
                                            ModuleName);

            paramsScript += string.Format(@"
                    CommentsManagerObj._jsObjName = '{0}';
                    CommentsManagerObj.CkUploadHandlerPath = '{1}';
                    CommentsManagerObj.maxLevel = {2};
                    CommentsManagerObj.comments = '{3}';
                    CommentsManagerObj.isEmpty = {4};
                    CommentsManagerObj.isShowAddCommentBtn = {5};
                    CommentsManagerObj.objectID = '{6}',
                    CommentsManagerObj.showCaption = {7};
                    CommentsManagerObj.maxDepthLevel = {8};
                    CommentsManagerObj.total = {9};
                    ",
                                             JsObjName,
                                             uploadPath,
                                             MaxDepthLevel,
                                              Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(Items))),
                                             IsEmptyComments(_items).ToString().ToLower(),
                                             _isShowAddCommentBtn.ToString().ToLower(),
                                             _objectID,
                                             _showCaption.ToString().ToLower(),
                                             _maxDepthLevel,
                                             TotalCount);

            paramsScript += string.Format(@"
                    CommentsManagerObj.OnEditedCommentJS = '{0}';
                    CommentsManagerObj.OnRemovedCommentJS = '{1}';
                    CommentsManagerObj.OnCanceledCommentJS = '{2}';
                    CommentsManagerObj.FckDomainName = '{3}';",
                                          OnEditedCommentJS,
                                          OnRemovedCommentJS,
                                          OnCanceledCommentJS,
                                          FckDomainName);

            if (!InitJS.HasValue || InitJS.Value)
            {
                paramsScript += string.Format("CommentsManagerObj.Init();");
            }

            Page.RegisterInlineScript(paramsScript);

        }

        #endregion

        #region Events

        private Confirm confirm;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (Visible)
            {
                RegisterClientScripts();
                _isClientScriptRegistered = true;
            }

            confirm = (Confirm)Page.LoadControl(Confirm.Location);
            confirm.Title = Resource.ConfirmRemoveCommentTitle;
            confirm.SelectTitle = ConfirmRemoveCommentMessage;
            Controls.Add(confirm);
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (!_isClientScriptRegistered)
                RegisterClientScripts();

            writer.Write("

");

            confirm.RenderControl(writer);
        }

        #endregion

        #region Methods

        public static bool IsEmptyComments(IList<CommentInfo> comments)
        {
            if (comments == null)
                return true;

            foreach (var c in comments)
            {
                if (!c.Inactive)
                {
                    return false;
                }
                if (c.CommentList != null && !IsEmptyComments(c.CommentList))
                {
                    return false;
                }
            }
            return true;
        }

        #endregion
    }
}


text:
package org.topbraid.spin.model.update.impl;

import org.topbraid.spin.model.print.PrintContext;
import org.topbraid.spin.model.update.Create;
import org.topbraid.spin.util.JenaUtil;
import org.topbraid.spin.vocabulary.SP;

import com.hp.hpl.jena.enhanced.EnhGraph;
import com.hp.hpl.jena.graph.Node;

public class CreateImpl extends UpdateImpl implements Create {

	public CreateImpl(Node node, EnhGraph graph) {
		super(node, graph);
	}

	@Override
	public void printSPINRDF(PrintContext p) {
		p.printKeyword("CREATE");
		p.print(" ");
		printSilent(p);
		p.printKeyword("GRAPH");
		p.print(" ");
		p.printURIResource(JenaUtil.getResourceProperty(this, SP.graphIRI));
	}
}


text:
<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="magefan" translate="label" sortOrder="110">
            Promotion - News
        </tab>

            <class>separator-top</class>
            Promotion - News
            <tab>magefan</tab>
            <resource>Magefan_Blog::config_blog</resource>
            <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                Information
                <field id="version" translate="label comment" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                    <frontend_model>Magefan\Blog\Block\Adminhtml\System\Config\Form\Info</frontend_model>
                </field>
            </group>
            <group id="index_page" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                Index Page

                <field id="title" translate="label comment" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                    Title
                </field>
                <field id="meta_keywords" translate="label comment" type="textarea" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                    Meta Keywords
                </field>
                <field id="meta_description" translate="label comment" type="textarea" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
                    Meta Description
                </field>
            </group>

            <group id="post_view" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
                Post View

                <group id="related_posts" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                    Related Posts
                    <field id="enabled" translate="label comment" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                        Display Related Posts
                        <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                    </field>

                    <field id="number_of_posts" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                        Number of Posts
                        <depends>
                            <field id="enabled">1</field>
                        </depends>
                    </field>
                </group>

                <group id="related_products" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                    Related Products
                    <field id="enabled" translate="label comment" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                        Display Related Products
                        <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                    </field>

                    <field id="number_of_products" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                        Number of Products
                        <depends>
                            <field id="enabled">1</field>
                        </depends>
                    </field>
                </group>

                <group id="comments" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
                    Comments
                    <field id="type" translate="label comment" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                        Comments
                        <source_model>Magefan\Blog\Model\Config\Source\CommetType</source_model>
                    </field>

                    <field id="number_of_comments" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                        Number of Comments
                        <depends>
                            <field id="type">facebook</field>
                        </depends>
                    </field>

                    <field id="fb_app_id" translate="label comment" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
                        Facebook Application ID
                        <depends>
                            <field id="type">facebook</field>
                        </depends>
                        <comment><![CDATA[

                                How do I get a Facebook Application ID?

                        ]]></comment>
                    </field>

                    <field id="disqus_forum_shortname" translate="label comment" type="text" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
                        Your Disqus Forum Shortname
                        <validate>required-entry</validate>
                        <depends>
                            <field id="type">disqus</field>
                        </depends>
                        <comment><![CDATA[

                                What's a shortname?

                        ]]></comment>
                    </field>
                </group>
            </group>

            <group id="post_list" translate="label" type="text" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
                Post List
                <field id="posts_per_page" translate="label comment" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                    Posts Per Page
                </field>
            </group>

            <group id="sidebar" translate="label" type="text" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1">
                Sidebar
                <group id="search" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                    Search Form Widget
                    <field id="enabled" translate="label comment" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                        Enabled
                        <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                    </field>
                    <field id="sort_order" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                        Sort Order
                    </field>
                </group>
                <group id="categories" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                    Categories Widget
                    <field id="enabled" translate="label comment" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                        Enabled
                        <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                    </field>
                    <field id="sort_order" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                        Sort Order
                    </field>
                </group>
                <group id="recent_posts" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
                    Recent Posts Widget
                    <field id="enabled" translate="label comment" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                        Enabled
                        <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                    </field>
                    <field id="posts_per_page" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                        Posts Number
                    </field>
                    <field id="sort_order" translate="label comment" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
                        Sort Order
                    </field>
                </group>
                <group id="archive" translate="label" type="text" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
                    Archive Widget
                    <field id="enabled" translate="label comment" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                        Enabled
                        <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                    </field>
                    <field id="sort_order" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                        Sort Order
                    </field>
                </group>
                <group id="rss_feed" translate="label" type="text" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1">
                    Rss Feed
                    <field id="enabled" translate="label comment" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                        Enabled
                        <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                    </field>
                    <field id="sort_order" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                        Sort Order
                    </field>
                    <field id="title" translate="label comment" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
                        Feed Title
                    </field>
                    <field id="description" translate="label comment" type="textarea" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
                        Feed Description
                    </field>
                </group>
            </group>

            <group id="permalink" translate="label" type="text" sortOrder="70" showInDefault="1" showInWebsite="1" showInStore="1">
                Permalink Settings
                <field id="route" translate="label comment" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                    Route
                    <comment>E.g.: "blog" will make the post accessible from mystore.com/blog/</comment>
                </field>
                <field id="type" translate="label comment" type="select" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                    Permalink Type
                     <source_model>Magefan\Blog\Model\Config\Source\PermalinkType</source_model>
                </field>

                <field id="post_route" translate="label comment" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
                    Post Route
                    <depends>
                        <field id="type">default</field>
                    </depends>
                    <comment>E.g.: "post" will make the post accessible from mystore.com/{blog_route}/post/post-title/</comment>
                </field>
                <field id="category_route" translate="label comment" type="text" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
                    Category Route
                    <depends>
                        <field id="type">default</field>
                    </depends>
                    <comment>E.g.: "category" will make the category accessible from mystore.com/{blog_route}/category/category-title/</comment>
                </field>
                <field id="archive_route" translate="label comment" type="text" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1">
                    Archive Route
                    <depends>
                        <field id="type">default</field>
                    </depends>
                    <comment>E.g.: "archive" will make the archive accessible from mystore.com/{blog_route}/archive/2016-02/</comment>
                </field>
                <field id="search_route" translate="label comment" type="text" sortOrder="60" showInDefault="1" showInWebsite="1" showInStore="1">
                    Search Route
                    <comment>E.g.: "search" will make the search accessible from mystore.com/{blog_route}/search/query/</comment>
                </field>
            </group>

    </system>
</config>


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CallListDataAccess</title>
<meta name="date" content="2017-08-19">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

data

Class CallListDataAccess

java.lang.Object

data.CallListDataAccess

public class CallListDataAccess
extends java.lang.Object

This data-access class retrieves patient call lists and email messages.

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
CallListDataAccess.LastMeasurementDateType

This enum indicates a type for a last measurement date collected in a
 call list.

Constructor Summary

Constructors

Constructor and Description

CallListDataAccess()

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static java.util.ArrayList<Patient>
getCallList(int clinicId,
           java.lang.String subject,
           CallListDataAccess.LastMeasurementDateType[] dateType,
           java.lang.Object referenceCharacters)

This method uses the getCallList procedure in the database to find and
 return the list of patients to be contacted.

static java.util.ArrayList<EmailMessage>
getEmailMessages(int clinicId,
                java.lang.String subject)

This method uses the getEmailMessages procedure in the database to find
 and return the list of email messages to be sent to selected patients in
 the call list.

Methods inherited from class java.lang.Object

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

Constructor Detail

CallListDataAccess

public CallListDataAccess()

Method Detail

getCallList

public static java.util.ArrayList<Patient> getCallList(int clinicId,
                                                       java.lang.String subject,
                                                       CallListDataAccess.LastMeasurementDateType[] dateType,
                                                       java.lang.Object referenceCharacters)

This method uses the getCallList procedure in the database to find and
 return the list of patients to be contacted.

Parameters:

clinicId - the clinic ID

subject - the call list subject

dateType - the last measurement date type determined from the result
 set

referenceCharacters - the character string

Returns:

the list of patients or null if no list is found

getEmailMessages

public static java.util.ArrayList<EmailMessage> getEmailMessages(int clinicId,
                                                                 java.lang.String subject)

This method uses the getEmailMessages procedure in the database to find
 and return the list of email messages to be sent to selected patients in
 the call list.

Parameters:

clinicId - the clinic ID

subject - the call list subject

Returns:

the list of email messages or null if no messages are found

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package com.intellij.openapi.editor.ex.util;

import com.intellij.psi.tree.IElementType;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NotNull;

/**
 * Expands {@link SegmentArray} contract by providing ability to attach additional data to target segment,
 * E.g., by holding mappings like {@code 'index <-> (data, (start; end))'}.
 * <p/>
 * Not thread-safe.
 */
public class SegmentArrayWithData extends SegmentArray {
  private DataStorage myStorage;

  public SegmentArrayWithData(@NotNull DataStorage storage) {
    myStorage = storage;
  }

  @NotNull
  public DataStorage createStorage() {
    return myStorage.createStorage();
  }

  public void setElementAt(int i, int startOffset, int endOffset, int data) {
    setElementAt(i, startOffset, endOffset);
    myStorage.setData(i, data);
  }

  @Override
  public void remove(int startIndex, int endIndex) {
    myStorage.remove(startIndex, endIndex, mySegmentCount);
    super.remove(startIndex, endIndex);
  }

  public void replace(int startIndex, int endIndex, @NotNull SegmentArrayWithData newData) {
    int oldLen = endIndex - startIndex;
    int newLen = newData.getSegmentCount();

    int delta = newLen - oldLen;
    if (delta < 0) {
      remove(endIndex + delta, endIndex);
    }
    else if (delta > 0) {
      SegmentArrayWithData deltaData = new SegmentArrayWithData(myStorage.createStorage());
      for (int i = oldLen; i < newLen; i++) {
        deltaData.setElementAt(i - oldLen, newData.getSegmentStart(i), newData.getSegmentEnd(i), newData.getSegmentData(i));
      }
      insert(deltaData, startIndex + oldLen);
    }

    int common = Math.min(newLen, oldLen);
    replace(startIndex, newData, common);
  }

  protected void replace(int startOffset, @NotNull SegmentArrayWithData data, int len) {
    myStorage.replace(data.myStorage, startOffset, len);
    super.replace(startOffset, data, len);
  }

  public void insert(@NotNull SegmentArrayWithData segmentArray, int startIndex) {
    myStorage.insert(segmentArray.myStorage, startIndex, segmentArray.getSegmentCount(), mySegmentCount);
    super.insert(segmentArray, startIndex);
  }

  public int getSegmentData(int index) {
    if(index < 0 || index >= mySegmentCount) {
      throw new IndexOutOfBoundsException("Wrong index: " + index);
    }
    return myStorage.getData(index);
  }

  static int @NotNull [] reallocateArray(int @NotNull [] array, int index) {
    if (index < array.length) return array;
    return ArrayUtil.realloc(array, calcCapacity(array.length, index));
  }

  @NotNull
  public SegmentArrayWithData copy() {
    final SegmentArrayWithData sa = new SegmentArrayWithData(createStorage());
    sa.mySegmentCount = mySegmentCount;
    sa.myStarts = myStarts.clone();
    sa.myEnds = myEnds.clone();
    sa.myStorage = myStorage.copy();
    return sa;
  }

  /**
   * Unpacks state from segment data returned by
   *
   * @param data see {@link SegmentArrayWithData#getSegmentData(int)}
   * @return lexer state stored in data
   */
  public int unpackStateFromData(int data) {
    return myStorage.unpackStateFromData(data);
  }

  /**
   * Unpacks token type from segment data returned by
   * {@link SegmentArrayWithData#getSegmentData(int)}
   *
   * @param data to unpack
   * @return element type stored in data
   * @throws IndexOutOfBoundsException if encoded IElementType can not be found in IElementType registry
   */
  @NotNull
  public IElementType unpackTokenFromData(int data) {
    return myStorage.unpackTokenFromData(data);
  }

  /**
   * Packs tokenType and lexer state in data
   *
   * @param tokenType          lexer current token type
   * @param state              lexer current state
   * @param isRestartableState true if state is restartable
   * @return packed lexer state and tokenType in data
   */
  public int packData(@NotNull IElementType tokenType, int state, boolean isRestartableState) {
    return myStorage.packData(tokenType, state, isRestartableState);
  }
}


text:
<?php

namespace app\modules\time\models;
use yii\db\ActiveQuery;
use yii\db\Expression;

/**
 * This is the ActiveQuery class for [[TimeTrack]].
 *
 * @see Activity
 */
class TimeTrackQuery extends ActiveQuery
{
    public function active()
    {
        return $this->andWhere(['stop' => null]);
    }

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

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

    /**
     * @return array
     */
    public function getStat()
    {
        return $this->select([
            'timeTrack.id as id',
            'name',
            'activityId',
            new Expression('DATE(start) as date'),
            new Expression('sum(TIMESTAMPDIFF(SECOND, start, stop)) sum'),
        ])
            ->leftJoin('activity', 'timeTrack.activityId = activity.id')
            ->where(['NOT', ['stop' => null]])
            ->groupBy([
                'id',
                'name',
                'date',
                'activityId',
            ])
            ->indexBy('id')
            ->asArray()->all();
    }

    /** @return ActiveQuery */
    public function getSumSeconds()
    {
        return $this->select([
            new Expression('sum(TIMESTAMPDIFF(SECOND, start, stop)) sum'),
        ]);
    }
}


text:
'use strict';

/* https://github.com/angular/protractor/blob/master/docs/toc.md */

describe('my app', function() {

  it('should automatically redirect to /view1 when location hash/fragment is empty', function() {
    browser.get('index.html');
    expect(browser.getLocationAbsUrl()).toMatch("/v");
  });

  describe('mugencalc', function() {

    beforeEach(function() {
      browser.get('index.html#/mugencalc');
    });

    it('should render view1 when user navigates to /v', function() {
      expect(element.all(by.css('[ng-view] p')).first().getText()).
        toMatch(/partial for view 1/);
    });

  });

});


text:
class AuthObject < ActiveRecord::Base
  belongs_to :application
end


text:
package net.spanbroek.judith.runtime;

import net.spanbroek.judith.runtime.Object;

class BooleanBuilder {

    private World world;
    private Object booleanToBe;

    public static void build(World world) {
        BooleanBuilder builder = new BooleanBuilder(world);
        builder.declareEqualsMethod();
        builder.declareNotMethod();
        builder.declareAndMethod();
        builder.declareOrMethod();
        builder.declareBoolean();
    }

    private BooleanBuilder(World world) {
        this.world = world;
        booleanToBe = new Object(world.get("Object"), world);
        booleanToBe.setNativeObject(false);
    }

    private void declareEqualsMethod() {
        class BooleanEqualsMethod extends Method {
            public BooleanEqualsMethod() {
                super("equals", "boolean");
            }
            protected void execute(Scope scope) {
                boolean self = (Boolean)scope.get("self").getNativeObject();
                boolean bool = (Boolean)scope.get("boolean").getNativeObject();
                scope.set("result", world.wrap(self == bool));
            }
        }
        booleanToBe.declare(new BooleanEqualsMethod());
    }

    private void declareNotMethod() {
        class BooleanNotMethod extends Method {
            public BooleanNotMethod() {
                super("not");
            }
            protected void execute(Scope scope) {
                scope.set(
                  "result",
                  world.wrap(!(Boolean)scope.get("self").getNativeObject())
                );
            }
        }
        booleanToBe.declare(new BooleanNotMethod());
    }

    private void declareAndMethod() {
        class BooleanAndMethod extends Method {
            public BooleanAndMethod() {
                super("and", "boolean");
            }
            protected void execute(Scope scope) {
                boolean self = (Boolean)scope.get("self").getNativeObject();
                boolean bool = (Boolean)scope.get("boolean").getNativeObject();
                scope.set("result", world.wrap(self && bool));
            }
        }
        booleanToBe.declare(new BooleanAndMethod());
    }

    private void declareOrMethod() {
        class BooleanOrMethod extends Method {
            public BooleanOrMethod() {
                super("or", "boolean");
            }
            protected void execute(Scope scope) {
                boolean self = (Boolean)scope.get("self").getNativeObject();
                boolean bool = (Boolean)scope.get("boolean").getNativeObject();
                scope.set("result", world.wrap(self || bool));
            }
        }
        booleanToBe.declare(new BooleanOrMethod());
    }

    private void declareBoolean() {
        class BooleanMethod extends Method {
            public BooleanMethod() {
                super("Boolean");
            }
            protected void execute(Scope scope) {
                scope.set("result", booleanToBe.copy());
            }
        }
        world.get("Objects").declare(new BooleanMethod());
        world.setBoolean(booleanToBe);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fusaria autographica delineata, Edn 1 no. 40 (1916)

#### Original name
Gibberella heterochroma Wollenw.

### Remarks
null


text:
package android.framework.util.jar;

import org.apache.commons.compress.utils.Charsets;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import android.framework.libcore.io.Streams;

/**
 * The {@code Manifest} class is used to obtain attribute information for a
 * {@code JarFile} and its entries.
 */
public class Manifest implements Cloneable {
    static final int LINE_LENGTH_LIMIT = 72;

    private static final byte[] LINE_SEPARATOR = new byte[] { '\r', '\n' };

    private static final byte[] VALUE_SEPARATOR = new byte[] { ':', ' ' };

    private static final Attributes.Name NAME_ATTRIBUTE = new Attributes.Name("Name");

    private static final Field BAIS_BUF = getByteArrayInputStreamField("buf");
    private static final Field BAIS_POS = getByteArrayInputStreamField("pos");

    private static Field getByteArrayInputStreamField(String name) {
        try {
            Field f = ByteArrayInputStream.class.getDeclaredField(name);
            f.setAccessible(true);
            return f;
        } catch (Exception ex) {
            throw new AssertionError(ex);
        }
    }

    private Attributes mainAttributes = new Attributes();

    private HashMap<String, Attributes> entries = new HashMap<String, Attributes>();

    static class Chunk {
        int start;
        int end;

        Chunk(int start, int end) {
            this.start = start;
            this.end = end;
        }
    }

    private HashMap<String, Chunk> chunks;

    /**
     * The end of the main attributes section in the manifest is needed in
     * verification.
     */
    private int mainEnd;

    /**
     * Creates a new {@code Manifest} instance.
     */
    public Manifest() {
    }

    /**
     * Creates a new {@code Manifest} instance using the attributes obtained
     * from the input stream.
     *
     * @param is
     *            {@code InputStream} to parse for attributes.
     * @throws IOException
     *             if an IO error occurs while creating this {@code Manifest}
     */
    public Manifest(InputStream is) throws IOException {
        read(is);
    }

    /**
     * Creates a new {@code Manifest} instance. The new instance will have the
     * same attributes as those found in the parameter {@code Manifest}.
     *
     * @param man
     *            {@code Manifest} instance to obtain attributes from.
     */
    @SuppressWarnings("unchecked")
    public Manifest(Manifest man) {
        mainAttributes = (Attributes) man.mainAttributes.clone();
        entries = (HashMap<String, Attributes>) ((HashMap<String, Attributes>) man
                .getEntries()).clone();
    }

    Manifest(InputStream is, boolean readChunks) throws IOException {
        if (readChunks) {
            chunks = new HashMap<String, Chunk>();
        }
        read(is);
    }

    /**
     * Resets the both the main attributes as well as the entry attributes
     * associated with this {@code Manifest}.
     */
    public void clear() {
        entries.clear();
        mainAttributes.clear();
    }

    /**
     * Returns the {@code Attributes} associated with the parameter entry
     * {@code name}.
     *
     * @param name
     *            the name of the entry to obtain {@code Attributes} from.
     * @return the Attributes for the entry or {@code null} if the entry does
     *         not exist.
     */
    public Attributes getAttributes(String name) {
        return getEntries().get(name);
    }

    /**
     * Returns a map containing the {@code Attributes} for each entry in the
     * {@code Manifest}.
     *
     * @return the map of entry attributes.
     */
    public Map<String, Attributes> getEntries() {
        return entries;
    }

    /**
     * Returns the main {@code Attributes} of the {@code JarFile}.
     *
     * @return main {@code Attributes} associated with the source {@code
     *         JarFile}.
     */
    public Attributes getMainAttributes() {
        return mainAttributes;
    }

    /**
     * Creates a copy of this {@code Manifest}. The returned {@code Manifest}
     * will equal the {@code Manifest} from which it was cloned.
     *
     * @return a copy of this instance.
     */
    @Override
    public Object clone() {
        return new Manifest(this);
    }

    /**
     * Writes out the attribute information of the receiver to the specified
     * {@code OutputStream}.
     *
     * @param os
     *            The {@code OutputStream} to write to.
     * @throws IOException
     *             If an error occurs writing the {@code Manifest}.
     */
    public void write(OutputStream os) throws IOException {
        write(this, os);
    }

    /**
     * Merges name/attribute pairs read from the input stream {@code is} into this manifest.
     *
     * @param is
     *            The {@code InputStream} to read from.
     * @throws IOException
     *             If an error occurs reading the manifest.
     */
    public void read(InputStream is) throws IOException {
        byte[] buf;
        if (is instanceof ByteArrayInputStream) {
            buf = exposeByteArrayInputStreamBytes((ByteArrayInputStream) is);
        } else {
            buf = Streams.readFullyNoClose(is);
        }

        if (buf.length == 0) {
            return;
        }

        // a workaround for HARMONY-5662
        // replace EOF and NUL with another new line
        // which does not trigger an error
        byte b = buf[buf.length - 1];
        if (b == 0 || b == 26) {
            buf[buf.length - 1] = '\n';
        }

        // Attributes.Name.MANIFEST_VERSION is not used for
        // the second parameter for RI compatibility
        InitManifest im = new InitManifest(buf, mainAttributes, null);
        mainEnd = im.getPos();
        im.initEntries(entries, chunks);
    }

    /**
     * Returns a byte[] containing all the bytes from a ByteArrayInputStream.
     * Where possible, this returns the actual array rather than a copy.
     */
    private static byte[] exposeByteArrayInputStreamBytes(ByteArrayInputStream bais) {
        byte[] buffer;
        synchronized (bais) {
            byte[] buf;
            int pos;
            try {
                buf = (byte[]) BAIS_BUF.get(bais);
                pos = BAIS_POS.getInt(bais);
            } catch (IllegalAccessException iae) {
                throw new AssertionError(iae);
            }
            int available = bais.available();
            if (pos == 0 && buf.length == available) {
                buffer = buf;
            } else {
                buffer = new byte[available];
                System.arraycopy(buf, pos, buffer, 0, available);
            }
            bais.skip(available);
        }
        return buffer;
    }

    /**
     * Returns the hash code for this instance.
     *
     * @return this {@code Manifest}'s hashCode.
     */
    @Override
    public int hashCode() {
        return mainAttributes.hashCode() ^ getEntries().hashCode();
    }

    /**
     * Determines if the receiver is equal to the parameter object. Two {@code
     * Manifest}s are equal if they have identical main attributes as well as
     * identical entry attributes.
     *
     * @param o
     *            the object to compare against.
     * @return {@code true} if the manifests are equal, {@code false} otherwise
     */
    @Override
    public boolean equals(Object o) {
        if (o == null) {
            return false;
        }
        if (!mainAttributes.equals(((Manifest) o).mainAttributes)) {
            return false;
        }
        return getEntries().equals(((Manifest) o).getEntries());
    }

    Chunk getChunk(String name) {
        return chunks.get(name);
    }

    void removeChunks() {
        chunks = null;
    }

    int getMainAttributesEnd() {
        return mainEnd;
    }

    /**
     * Writes out the attribute information of the specified manifest to the
     * specified {@code OutputStream}
     *
     * @param manifest
     *            the manifest to write out.
     * @param out
     *            The {@code OutputStream} to write to.
     * @throws IOException
     *             If an error occurs writing the {@code Manifest}.
     */
    static void write(Manifest manifest, OutputStream out) throws IOException {
        CharsetEncoder encoder = Charsets.UTF_8.newEncoder();
        ByteBuffer buffer = ByteBuffer.allocate(LINE_LENGTH_LIMIT);

        String version = manifest.mainAttributes.getValue(Attributes.Name.MANIFEST_VERSION);
        if (version != null) {
            writeEntry(out, Attributes.Name.MANIFEST_VERSION, version, encoder, buffer);
            Iterator<?> entries = manifest.mainAttributes.keySet().iterator();
            while (entries.hasNext()) {
                Attributes.Name name = (Attributes.Name) entries.next();
                if (!name.equals(Attributes.Name.MANIFEST_VERSION)) {
                    writeEntry(out, name, manifest.mainAttributes.getValue(name), encoder, buffer);
                }
            }
        }
        out.write(LINE_SEPARATOR);
        Iterator<String> i = manifest.getEntries().keySet().iterator();
        while (i.hasNext()) {
            String key = i.next();
            writeEntry(out, NAME_ATTRIBUTE, key, encoder, buffer);
            Attributes attrib = manifest.entries.get(key);
            Iterator<?> entries = attrib.keySet().iterator();
            while (entries.hasNext()) {
                Attributes.Name name = (Attributes.Name) entries.next();
                writeEntry(out, name, attrib.getValue(name), encoder, buffer);
            }
            out.write(LINE_SEPARATOR);
        }
    }

    private static void writeEntry(OutputStream os, Attributes.Name name,
            String value, CharsetEncoder encoder, ByteBuffer bBuf) throws IOException {
        String nameString = name.getName();
        os.write(nameString.getBytes(Charsets.US_ASCII));
        os.write(VALUE_SEPARATOR);

        encoder.reset();
        bBuf.clear().limit(LINE_LENGTH_LIMIT - nameString.length() - 2);

        CharBuffer cBuf = CharBuffer.wrap(value);

        while (true) {
            CoderResult r = encoder.encode(cBuf, bBuf, true);
            if (CoderResult.UNDERFLOW == r) {
                r = encoder.flush(bBuf);
            }
            os.write(bBuf.array(), bBuf.arrayOffset(), bBuf.position());
            os.write(LINE_SEPARATOR);
            if (CoderResult.UNDERFLOW == r) {
                break;
            }
            os.write(' ');
            bBuf.clear().limit(LINE_LENGTH_LIMIT - 1);
        }
    }
}


text:
package rewrite

import (
	"testing"

	api "k8s.io/api/core/v1"
	extensions "k8s.io/api/extensions/v1beta1"
	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/intstr"

	"k8s.io/ingress/core/pkg/ingress/defaults"
)

const (
	defRoute = "/demo"
)

func buildIngress() *extensions.Ingress {
	defaultBackend := extensions.IngressBackend{
		ServiceName: "default-backend",
		ServicePort: intstr.FromInt(80),
	}

	return &extensions.Ingress{
		ObjectMeta: meta_v1.ObjectMeta{
			Name:      "foo",
			Namespace: api.NamespaceDefault,
		},
		Spec: extensions.IngressSpec{
			Backend: &extensions.IngressBackend{
				ServiceName: "default-backend",
				ServicePort: intstr.FromInt(80),
			},
			Rules: []extensions.IngressRule{
				{
					Host: "foo.bar.com",
					IngressRuleValue: extensions.IngressRuleValue{
						HTTP: &extensions.HTTPIngressRuleValue{
							Paths: []extensions.HTTPIngressPath{
								{
									Path:    "/foo",
									Backend: defaultBackend,
								},
							},
						},
					},
				},
			},
		},
	}
}

type mockBackend struct {
	redirect bool
}

func (m mockBackend) GetDefaultBackend() defaults.Backend {
	return defaults.Backend{SSLRedirect: m.redirect}
}

func TestWithoutAnnotations(t *testing.T) {
	ing := buildIngress()
	_, err := NewParser(mockBackend{}).Parse(ing)
	if err != nil {
		t.Errorf("unexpected error with ingress without annotations: %v", err)
	}
}

func TestRedirect(t *testing.T) {
	ing := buildIngress()

	data := map[string]string{}
	data[rewriteTo] = defRoute
	ing.SetAnnotations(data)

	i, err := NewParser(mockBackend{}).Parse(ing)
	if err != nil {
		t.Errorf("Unexpected error with ingress: %v", err)
	}
	redirect, ok := i.(*Redirect)
	if !ok {
		t.Errorf("expected a Redirect type")
	}
	if redirect.Target != defRoute {
		t.Errorf("Expected %v as redirect but returned %s", defRoute, redirect.Target)
	}
}

func TestSSLRedirect(t *testing.T) {
	ing := buildIngress()

	data := map[string]string{}
	data[rewriteTo] = defRoute
	ing.SetAnnotations(data)

	i, _ := NewParser(mockBackend{true}).Parse(ing)
	redirect, ok := i.(*Redirect)
	if !ok {
		t.Errorf("expected a Redirect type")
	}
	if !redirect.SSLRedirect {
		t.Errorf("Expected true but returned false")
	}

	data[sslRedirect] = "false"
	ing.SetAnnotations(data)

	i, _ = NewParser(mockBackend{false}).Parse(ing)
	redirect, ok = i.(*Redirect)
	if !ok {
		t.Errorf("expected a Redirect type")
	}
	if redirect.SSLRedirect {
		t.Errorf("Expected false but returned true")
	}
}

func TestForceSSLRedirect(t *testing.T) {
	ing := buildIngress()

	data := map[string]string{}
	data[rewriteTo] = defRoute
	ing.SetAnnotations(data)

	i, _ := NewParser(mockBackend{true}).Parse(ing)
	redirect, ok := i.(*Redirect)
	if !ok {
		t.Errorf("expected a Redirect type")
	}
	if redirect.ForceSSLRedirect {
		t.Errorf("Expected false but returned true")
	}

	data[forceSSLRedirect] = "true"
	ing.SetAnnotations(data)

	i, _ = NewParser(mockBackend{false}).Parse(ing)
	redirect, ok = i.(*Redirect)
	if !ok {
		t.Errorf("expected a Redirect type")
	}
	if !redirect.ForceSSLRedirect {
		t.Errorf("Expected true but returned false")
	}
}
func TestAppRoot(t *testing.T) {
	ing := buildIngress()

	data := map[string]string{}
	data[appRoot] = "/app1"
	ing.SetAnnotations(data)

	i, _ := NewParser(mockBackend{true}).Parse(ing)
	redirect, ok := i.(*Redirect)
	if !ok {
		t.Errorf("expected a App Context")
	}
	if redirect.AppRoot != "/app1" {
		t.Errorf("Unexpected value got in AppRoot")
	}

}


text:
"""
Django settings for rss_reader project.

For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '&4bbeqzo=i@oaq(xy-c$vxct-zu2$r9!42g&bmq1d3+rgq8dt%'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR,  'templates'),
)

# Application definition

DEFAULT_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

THIRD_PARTY_APPS = (
    'djangular',
    'rest_framework',
    'watson',
    'rest_auth',
    'django_extensions'
)

LOCAL_APPS = (
    'main',
)

INSTALLED_APPS = DEFAULT_APPS + THIRD_PARTY_APPS + LOCAL_APPS

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'rss_reader.urls'

WSGI_APPLICATION = 'rss_reader.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'feeddb',
        'USER': 'combustible',
        'PASSWORD': 'lemons',
        'HOST': 'localhost',
        'PORT': '',
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/

STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),)

STATIC_URL = '/static/'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Genius Dashboard - Bootstrap Admin Template</title>
	<meta name="description" content="Genius Dashboard - Bootstrap Admin Template.">
	<meta name="author" content="Łukasz Holeczek">
	<meta name="keyword" content="Genius, Dashboard, Bootstrap, Admin, Template, Theme, Responsive, Fluid, Retina">

	<meta name="viewport" content="width=device-width, initial-scale=1">

	<link href="assets/css/bootstrap.min.css" rel="stylesheet">
	<link href="assets/css/style.min.css" rel="stylesheet">
	<link href="assets/css/retina.min.css" rel="stylesheet">
	<link href="assets/css/print.css" rel="stylesheet" type="text/css" media="print"/>

	<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
	<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
	<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
	<link rel="apple-touch-icon-precomposed" sizes="57x57" href="assets/ico/apple-touch-icon-57-precomposed.png">
	<link rel="shortcut icon" href="assets/ico/favicon.png">

						Create your account

					<form class="form-horizontal register" action="index.html" method="post">

						<fieldset class="col-sm-12">

							  	Your URL

										<input type="text" class="form-control" id="url"/>
										.brix.io

							  	Username

										<input type="text" class="form-control" id="username"/>

							  	Password

										<input type="password" class="form-control" id="password"/>

								<input type="checkbox" name="agree"/>
								I agree to Term of Use

								<button type="submit" class="btn btn-primary btn-lg col-xs-12">Create Account!</button>

								or use your facebook account

						</fieldset>

					</form>

						Register via Facebook


text:
package com.qulice.xml;

import com.jcabi.log.Logger;
import com.jcabi.xml.StrictXML;
import com.jcabi.xml.XML;
import com.jcabi.xml.XMLDocument;
import com.qulice.spi.Environment;
import com.qulice.spi.ValidationException;
import com.qulice.spi.Validator;
import difflib.Delta;
import difflib.DiffUtils;
import difflib.Patch;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.xml.sax.SAXException;

/**
 * Validates XML files for formatting.
 *
 * @author Yegor Bugayenko (yegor@tpc2.com)
 * @version $Id$
 */
@SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops",
    "PMD.ExceptionAsFlowControl" })
public final class XmlValidator implements Validator {

    /**
     * New line escaped, for use in regex.
     */
    private static final String ESCAPED_EOL = "\\n";

    /**
     * Pattern for lines starting with XML attributes.
     */
    private static final Pattern ATTRS_PATTERN = Pattern.compile("^ *[^ <].*");

    /**
     * Should XML format be checked.
     */
    private final transient boolean format;

    /**
     * Constructor.
     */
    public XmlValidator() {
        this(true);
    }

    /**
     * Constructor with XML formatting option.
     * @param formatting Should XML formatting be checked.
     */
    public XmlValidator(final boolean formatting) {
        this.format = formatting;
    }

    @Override
    public void validate(final Environment env) throws ValidationException {
        try {
            for (final File file : env.files("*.xml")) {
                final String name = file.getAbsolutePath().substring(
                    env.basedir().toString().length()
                );
                if (env.exclude("xml", name)) {
                    Logger.info(this, "%s: skipped", name);
                    continue;
                }
                Logger.info(this, "%s: to be validated", name);
                final XML document = new XMLDocument(file);
                try {
                    new StrictXML(document);
                } catch (final IllegalStateException ex) {
                    if (ex.getCause() != null
                        && ex.getCause() instanceof SAXException) {
                        Logger.warn(
                            // @checkstyle LineLength (1 line)
                            this, "Failed to validate file %s against schema(s). Cause: %s",
                            name,
                            ex.toString()
                        );
                    } else {
                        throw new IllegalStateException(ex);
                    }
                } catch (final IllegalArgumentException ex) {
                    throw new ValidationException(ex);
                }
                if (this.format) {
                    XmlValidator.formatting(
                        file.toString(), FileUtils.readFileToString(file)
                    );
                }
            }
        } catch (final IOException ex) {
            throw new IllegalStateException(ex);
        }
    }

    @Override
    public String name() {
        return "XML";
    }

    /**
     * Check formatting of given XML.
     * @param name Name of XML file.
     * @param before XML to check.
     * @throws ValidationException In case of validation error.
     */
    private static void formatting(final String name, final String before)
        throws ValidationException {
        // @checkstyle MultipleStringLiterals (3 lines)
        final String after = new Prettifier(before).prettify()
            .replace("\r\n", "\n");
        final String bnormalized = before.replace("\r\n", "\n");
        final List<String> blines =
            Arrays.asList(bnormalized.split(XmlValidator.ESCAPED_EOL, -1));
        final Patch filter = XmlValidator.filter(
            DiffUtils.diff(
                blines,
                Arrays.asList(after.split(XmlValidator.ESCAPED_EOL, -1))
            )
        );
        if (!filter.getDeltas().isEmpty()) {
            final int context = 5;
            throw new ValidationException(
                // @checkstyle LineLength (1 line)
                "The provided XML %s is not well formatted, it should look like this:\n%s\npatch:\n%s",
                name, after,
                StringUtils.join(
                    DiffUtils.generateUnifiedDiff(
                        "before", "after", blines,
                        filter, context
                    ), "\n"
                )
            );
        }
    }

    /**
     * Remove unwanted deltas.
     * @param diff Patch to filter.
     * @return Patch with unwanted deltas removed.
     * @todo #469:30min Remove the method below and find a way to format tags
     *  correctly in XML. Attributes should be indented by 4 spaces, just like
     *  XML tags, but in IT xml-violations there is a tag that our Prettifier
     *  want to be indented by 3 spaces which is wrong. Another problem is
     *  that in the parent tag, attributes are indented to match the first
     *  attribute, this is also wrong - all attributes on new line should be
     *  indented by 4 spaces.
     */
    private static Patch filter(final Patch diff) {
        final Patch patch = new Patch();
        for (final Delta delta : diff.getDeltas()) {
            final List<?> prev = delta.getOriginal().getLines();
            if (
                prev.size() != 1 || delta.getRevised().getLines().size() != 1
                    || !XmlValidator.ATTRS_PATTERN
                        .matcher(prev.get(0).toString()).matches()
                ) {
                patch.addDelta(delta);
            }
        }
        return patch;
    }
}


text:
<?php
namespace Rez\MainBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Validator\Constraints as Assert;

use Rez\MainBundle\Entity\Room;

class RoomType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
                ->add('room_type', null, array(
                    'label'         => 'Tip Camera'
                    ,'attr'         => array('class' => 'form-control')
                    ,'label_attr'   => array('class' => 'col-sm-3 control-label')
                ))
                ->add('meal_type', null, array(
                    'label'         => 'Tip Masa'
                    ,'attr'         => array('class' => 'form-control')
                    ,'label_attr'   => array('class' => 'col-sm-3 control-label')
                ))
				->add('transport', 'choice', array(
					'label'		=> 'Tip Transport',
					'choices'   => Room::$transports,
					'expanded'	=> false
                    ,'label_attr'   => array('class' => 'col-sm-3 control-label')
					// 'data'		=> Booking::FLIGHT_TYPE_1WAY
				))
                ->add('extra_services', null, array(
                    'label'         => 'Servicii suplimentare'
                    ,'attr'         => array('class' => 'form-control')
                    ,'label_attr'   => array('class' => 'col-sm-3 control-label')
                ))
                ->add('save', 'submit', array(
                    'attr'      => array('class' => 'btn btn-primary')
                    ,'label'    => 'Salveaza!'
                ))
                ;
    }

    public function getName()
    {
        return 'room';
    }
}


text:
/*!
 *
 * \file combine_parallel_batch_matmul.cc
 * \brief Combine parallel batch matmuls into a single one.
 *
 * This pass replaces batch_matmul that share the same lhs node with a
 * single batch matmul.Elemwise and broadcast ops following batch_matmul are also
 * combined if possible.
 *
 * This prevents launching multiple kernels in networks with multiple
 * convolution branches, such as Inception block.
 */

#include <tvm/relay/analysis.h>
#include <tvm/relay/attrs/nn.h>
#include <tvm/relay/attrs/transform.h>
#include <tvm/relay/expr_functor.h>
#include <tvm/relay/op_attr_types.h>
#include <tvm/relay/transform.h>

#include <unordered_map>
#include <unordered_set>

#include "./combine_parallel_op.h"
#include "./expr_subst.h"
#include "pattern_utils.h"

namespace tvm {
namespace relay {

class ParallelBatchMatmulCombiner : public ParallelOpCombiner {
 public:
  explicit ParallelBatchMatmulCombiner(uint64_t min_num_branches)
      : ParallelOpCombiner("nn.batch_matmul", min_num_branches) {}

 protected:
  bool IsSupportedOp(const CallNode* n) { return true; }

  bool CanOpsBeCombined(const CallNode* a, const CallNode* b) {
    StructuralEqual eq;
    const auto* attrs_a = a->attrs.as<BatchMatmulAttrs>();
    const auto* attrs_b = b->attrs.as<BatchMatmulAttrs>();
    ICHECK(attrs_a);
    ICHECK(attrs_b);
    const auto* rhs_a = a->args[1]->type_as<TensorTypeNode>();
    const auto* rhs_b = b->args[1]->type_as<TensorTypeNode>();
    const auto* restype_a = a->type_as<TensorTypeNode>();
    const auto* restype_b = b->type_as<TensorTypeNode>();
    // shape[2] is the contraction axis and automatically consistent
    // if it were valid batch_matmul ops

    // TODO(jcf94): Add full support of layout format
    if (!(attrs_a->transpose_a == false && attrs_a->transpose_b == true &&
          attrs_b->transpose_a == false && attrs_b->transpose_b == true)) {
      LOG(WARNING) << "For legacy reason, this pass only supports"
                   << " (transpose_a=false, transpose_b=true) now, skip combining these two with:"
                   << " batch_matmul_a: " << attrs_a->transpose_a << ", " << attrs_a->transpose_b
                   << " batch_matmul_b: " << attrs_b->transpose_a << ", " << attrs_b->transpose_b;
      return false;
    }

    auto res = eq(rhs_a->dtype, rhs_b->dtype) && eq(restype_a->dtype, restype_b->dtype) &&
               (rhs_a->shape.size() == 3) && (rhs_b->shape.size() == 3) &&
               eq(rhs_a->shape[0], rhs_b->shape[0]) && eq(attrs_a->out_dtype, attrs_b->out_dtype);
    return res;
  }

  Call MakeCombinedOp(const Group& branches) {
    Expr data = branches[0][0]->args[0];

    Array<Expr> weights;
    for (const auto& branch : branches) {
      auto call = branch[0];
      weights.push_back(call->args[1]);
    }
    Expr new_weight = MakeConcatenate(Tuple(weights), 1);

    const auto* origin_attrs = branches[0][0]->attrs.as<BatchMatmulAttrs>();
    ICHECK(origin_attrs);
    return Downcast<Call>(MakeBatchMatmul(data, new_weight, origin_attrs->out_dtype,
                                          origin_attrs->transpose_a, origin_attrs->transpose_b));
  }

  bool IsArgCompatible(const CallNode* a, const CallNode* b, size_t index) { return true; }

  Call MakeCombinedCallFromFollowingOps(const Expr& data, const Group& branches, size_t depth,
                                        size_t parent_index) {
    Array<Expr> new_args;
    const CallNode* call = branches[0][depth];

    for (size_t i = 0; i < call->args.size(); i++) {
      if (i == parent_index) {
        new_args.push_back(data);
        continue;
      }

      Array<Expr> tuple;
      for (const auto& branch : branches) {
        tuple.push_back(branch[depth]->args[i]);
      }

      auto concat = MakeConcatenate(Tuple(tuple), -1);
      new_args.push_back(std::move(concat));
    }

    return Call(call->op, new_args, call->attrs, {});
  }

  void UpdateGroupOutput(const Expr& data, const Group& branches, size_t depth,
                         ExprSubstMap* subst_map) {
    int64_t index = 0;

    for (const auto& branch : branches) {
      const CallNode* batch_matmul = branch[0];
      auto feature_dim = batch_matmul->args[1]->type_as<TensorTypeNode>()->shape[1];
      auto fpp = tir::as_const_int(feature_dim);
      int64_t features = *fpp;
      Array<Integer> begin;
      Array<Integer> end;
      for (size_t i = 0; i < 2; i++) {
        begin.push_back(0);
        end.push_back(-1);
      }
      begin.push_back(index);
      index += features;
      end.push_back(features);
      Array<Integer> strides(begin.size(), 1);
      auto slice = MakeStridedSlice(data, begin, end, strides, "size");
      subst_map->insert({GetRef<Expr>(branch[depth]), slice});
    }
  }
};

/*! \brief Combine parallel batch_matmul if number of branches >= min_num_branches */
Expr CombineParallelBatchMatmul(const Expr& expr, uint64_t min_num_branches) {
  return ParallelBatchMatmulCombiner(min_num_branches).Combine(expr);
}

namespace transform {

Pass CombineParallelBatchMatmul(uint64_t min_num_branches) {
  runtime::TypedPackedFunc<Function(Function, IRModule, PassContext)> pass_func =
      [=](Function f, IRModule m, PassContext pc) {
        return Downcast<Function>(CombineParallelBatchMatmul(f, min_num_branches));
      };
  return CreateFunctionPass(pass_func, 4, "CombineParallelBatchMatmul", {"InferType"});
}

TVM_REGISTER_GLOBAL("relay._transform.CombineParallelBatchMatmul")
    .set_body_typed(CombineParallelBatchMatmul);

}  // namespace transform

}  // namespace relay
}  // namespace tvm


text:
package org.tribbloid.spookystuff.sparkbinding

import org.apache.spark.rdd.RDD
import org.apache.spark.{Partition, TaskContext}
import org.tribbloid.spookystuff.entity.PageRow
import org.tribbloid.spookystuff.utils.Utils

import scala.language.implicitConversions
import scala.reflect.ClassTag

/**
 * Created by peng on 2/12/15.
 */
trait PageRowRDDOverrides extends RDD[PageRow]{
  this: PageRowRDD =>

  override def getPartitions: Array[Partition] = firstParent[PageRow].partitions

  override val partitioner = store.partitioner

  override def compute(split: Partition, context: TaskContext) =
    firstParent[PageRow].iterator(split, context)
  //-----------------------------------------------------------------------

  private implicit def selfToPageRowRDD(self: RDD[PageRow]): PageRowRDD = this.copy(store = self)

  override def filter(f: PageRow => Boolean): PageRowRDD = super.filter(f)

  override def distinct(): PageRowRDD = super.distinct()

  override def distinct(numPartitions: Int)(implicit ord: Ordering[PageRow] = null): PageRowRDD =
    super.distinct(numPartitions)(ord)

  override def repartition(numPartitions: Int = partitions.length)(implicit ord: Ordering[PageRow] = null): PageRowRDD =
    super.repartition(numPartitions)(ord)

  override def coalesce(numPartitions: Int = partitions.length, shuffle: Boolean = false)(implicit ord: Ordering[PageRow] = null): PageRowRDD =
    super.coalesce(numPartitions, shuffle)(ord)

  override def sample(withReplacement: Boolean,
                      fraction: Double,
                      seed: Long = Utils.random.nextLong()): PageRowRDD =
    super.sample(withReplacement, fraction, seed)

  override def union(other: RDD[PageRow]): PageRowRDD = other match {

    case other: PageRowRDD =>
      this.copy(
        super.union(other.store),
        this.keys ++ other.keys.toSeq.reverse
      )
    case _ => super.union(other)
  }

  override def ++(other: RDD[PageRow]): PageRowRDD = this.union(other)

  override def sortBy[K](
                          f: (PageRow) => K,
                          ascending: Boolean = true,
                          numPartitions: Int = partitions.length)
                        (implicit ord: Ordering[K], ctag: ClassTag[K]): PageRowRDD = super.sortBy(f, ascending, numPartitions)(ord, ctag)

  override def intersection(other: RDD[PageRow]): PageRowRDD = other match {

    case other: PageRowRDD =>
      this.copy(
        super.intersection(other.store),
        this.keys.intersect(other.keys)//TODO: need validation that it won't change sequence
      )
    case _ => super.intersection(other)
  }

  override def intersection(other: RDD[PageRow], numPartitions: Int): PageRowRDD = other match {

    case other: PageRowRDD =>
      this.copy(
        super.intersection(other.store),
        this.keys.intersect(other.keys)
      )
    case _ => super.intersection(other, numPartitions)
  }
  //-------------------all before this lines are self typed wrappers--------------------

}


text:
namespace ash {
namespace internal {

OverlayEventFilter::OverlayEventFilter()
    : delegate_(NULL) {
}

OverlayEventFilter::~OverlayEventFilter() {
  delegate_ = NULL;
}

ui::EventResult OverlayEventFilter::OnKeyEvent(ui::KeyEvent* event) {
  if (!delegate_)
    return ui::ER_UNHANDLED;

  // Do not consume a translated key event which is generated by an IME (e.g.,
  // ui::VKEY_PROCESSKEY) since the key event is generated in response to a key
  // press or release before showing the ovelay. This is important not to
  // confuse key event handling JavaScript code in a page.
  if (event->type() == ui::ET_TRANSLATED_KEY_PRESS ||
      event->type() == ui::ET_TRANSLATED_KEY_RELEASE) {
    return ui::ER_UNHANDLED;
  }

  if (delegate_ && delegate_->IsCancelingKeyEvent(event))
    Cancel();

  // Handle key events only when they are sent to a child of the delegate's
  // window.
  aura::Window* target = static_cast<aura::Window*>(event->target());
  if (delegate_ && delegate_->GetWindow()->Contains(target))
    target->delegate()->OnKeyEvent(event);

  // Always handled: other windows shouldn't receive input while we're
  // displaying an overlay.
  return ui::ER_CONSUMED;
}

ui::EventResult OverlayEventFilter::OnMouseEvent(ui::MouseEvent* event) {
  // Handle mouse events only when they are sent to a child of the delegate's
  // window.
  aura::Window* target = static_cast<aura::Window*>(event->target());
  if (delegate_ && delegate_->GetWindow()->Contains(target)) {
    target->delegate()->OnMouseEvent(event);
    return ui::ER_CONSUMED;
  }
  return ui::ER_UNHANDLED;
}

void OverlayEventFilter::OnLoginStateChanged(
    user::LoginStatus status) {
  Cancel();
}

void OverlayEventFilter::OnAppTerminating() {
  Cancel();
}

void OverlayEventFilter::OnLockStateChanged(bool locked) {
  Cancel();
}

void OverlayEventFilter::Activate(Delegate* delegate) {
  delegate_ = delegate;
}

void OverlayEventFilter::Deactivate() {
  delegate_ = NULL;
}

void OverlayEventFilter::Cancel() {
  if (delegate_)
    delegate_->Cancel();
}
}  // namespace internal
}  // namespace ash


text:
<?php

namespace Antares\Extension\Events;

class Installing extends Base {

}


text:
<?php

namespace SymfonyId\AdminBundle\Exception;

/**
 * @author Muhammad Surya Ihsanuddin <surya.kejawen@gmail.com>
 */
class KeyNotMatchException extends \InvalidArgumentException
{
    public function __construct($expectation, $expected, $code = 0, \Exception $previous = null)
    {
        parent::__construct(sprintf('Key not match. Expectation "%d" got "%d"', $expectation, $expected), $code, $previous);
    }
}


text:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UIWidgets;

namespace UIWidgetsSamples
{
	[RequireComponent(typeof(CenteredSlider))]
	public class CenteredSliderLabel : MonoBehaviour
	{
		[SerializeField]
		Text label;

		CenteredSlider slider;

		void Start()
		{
			slider = GetComponent<CenteredSlider>();
			if (slider!=null)
			{
				slider.OnValuesChange.AddListener(ValueChanged);
				ValueChanged(slider.Value);
			}
		}

		void ValueChanged(int value)
		{
			label.text = value.ToString();
		}

		void OnDestroy()
		{
			if (slider!=null)
			{
				slider.OnValuesChange.RemoveListener(ValueChanged);
			}
		}
	}
}


text:
import SlidingStage from "../base/SlidingStage.js";

/**
 * SlidingStage component in the Plain reference design system
 *
 * @inherits SlidingStage
 */
class PlainSlidingStage extends SlidingStage {}

export default PlainSlidingStage;


text:
/*========================================================================
  Include Files
 ==========================================================================*/
#include <pthread.h>
#include "venc_debug.h"
#include "venc_thread.h"
#include <stdlib.h>

typedef struct venc_thread_type
{
  thread_fn_type pfn;
  int priority;
  pthread_t thread;
  void* thread_data;
} venc_thread_type;

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
static void* venc_thread_entry(void* thread_data)
{
  venc_thread_type* thread = (venc_thread_type*) thread_data;
  return (void*) thread->pfn(thread->thread_data);
}

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
int venc_thread_create(void** handle,
                       thread_fn_type pfn,
                       void* thread_data,
                       int priority)
{
  int result = 0;
  venc_thread_type* thread = (venc_thread_type*) malloc(sizeof(venc_thread_type));
  *handle = thread;

  if (thread)
  {
    int create_result;
    thread->pfn = pfn;
    thread->thread_data = thread_data;
    thread->priority = priority;
    create_result = pthread_create(&thread->thread,
        NULL,
        venc_thread_entry,
        (void*) thread);
    if (create_result != 0)
    {
      VENC_MSG_ERROR("failed to create thread");
      result = 1;
    }
  }
  else
  {
    VENC_MSG_ERROR("failed to allocate thread");
    result = 1;
  }
  return result;
}

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
int venc_thread_destroy(void* handle, int* thread_result)
{
  int result = 0;
  venc_thread_type* thread = (venc_thread_type*) handle;

  if (thread)
  {
    if (pthread_join(thread->thread, (void**) thread_result) != 0)
    {
      VENC_MSG_ERROR("failed to join thread");
      result = 1;
    }
    free(thread);
  }
  else
  {
    VENC_MSG_ERROR("handle is null");
    result = 1;
  }
  return result;
}


text:
"use strict";

module.exports = function(context){
    var admin = context.user.rol==='admin';
    return context.be.tableDefAdapt({
        name:'users',
        editable:admin,
        fields:[
            {name:'username'              , typeName:'text'   , nullable:false},
            {name:'md5pass'               , typeName:'text'                   },
            {name:'active_until'          , typeName:'date'                   },
            {name:'locked_since'          , typeName:'date'                   },
            {name:'rol'                   , typeName:'text'                   },
        ],
        primaryKey:['username']
    });
}