text:
package org.apache.myfaces.trinidadinternal.renderkit.core.pages;

import java.io.IOException;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.faces.FacesException;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.myfaces.trinidad.context.RequestContext;
import org.apache.myfaces.trinidad.render.InternalView;
import org.apache.myfaces.trinidad.render.RenderUtils;

import org.apache.myfaces.trinidadinternal.util.nls.LocaleUtils;

/**
 * Generic entry point for all UIX JSPs.
 * <p>
 * @version $Name:  $ ($Revision: adfrt/faces/adf-faces-impl/src/main/java/oracle/adfinternal/view/faces/renderkit/core/pages/GenericEntry.java#0 $) $Date: 05-jan-2006.13:18:09 $
 */
public class GenericEntry extends InternalView
{
  static public String getViewId()
  {
    return _GENERIC_ENTRY_VIEW_ID;
  }

  /**
   * Key identifying the color picker entry.
   */
  static public final String COLOR_PICKER_ENTRY    = "cp";

  /**
   * Key identifying the calendar dialog entry.
   */
  static public final String CALENDAR_DIALOG_ENTRY    = "cd";

  /**
   * Key identifying the inline date picker entry.
   */
  static public final String INLINE_DATE_PICKER_ENTRY    = "idp";

  /**
   * Key identifying the "new" frame redirect entry.
   */
  static public final String NEW_FRAME_REDIRECT_ENTRY = "fred";

  public GenericEntry()
  {
  }

  @Override
  public UIViewRoot createView(FacesContext context, String viewId)
  {
    return null;
  }

  @Override
  public UIViewRoot restoreView(FacesContext context, String viewId)
  {
    return null;
  }

  @Override
  public void renderView(
    FacesContext context,
    UIViewRoot   viewToRender) throws IOException, FacesException
  {
    String entryKey = (String) context.getExternalContext().getRequestParameterMap().get(__ENTRY_KEY_PARAM);
    if (entryKey == null)
    {
      RequestContext requestContext = RequestContext.getCurrentInstance();
      if (requestContext != null)
      {
        Object o = requestContext.getPageFlowScope().get(__ENTRY_KEY_PARAM);
        if (o != null)
          entryKey = o.toString();
      }
    }

    service(context,entryKey);
  }

  /*
  public static boolean isGenericEntryPage(String viewId)
  {
    if (viewId == null)
      return false;

    // In theory, this should be just "equals()", not starts-with;  but
    // extension-mapped views don't have the view ID you'd expect - it
    // includes the extension
    return viewId.startsWith(_GENERIC_ENTRY_VIEW_ID);
  }

  public static boolean isGenericEntryPage(FacesContext context)
  {
    if (context.getViewRoot() == null)
      return false;

    return isGenericEntryPage(context.getViewRoot().getViewId());
  }
  */

  public static String getEntryKeyParam()
  {
    return __ENTRY_KEY_PARAM;
  }

  public static UIViewRoot getGenericEntryViewRoot(FacesContext context)
  {
    ViewHandler viewHandler = context.getApplication().getViewHandler();
    UIViewRoot uvr = viewHandler.createView(context, _GENERIC_ENTRY_VIEW_ID);
    return uvr;
  }

  public static String getGenericEntryURL(
    FacesContext  context,
    String        jspName)
  {
    String name = getGenericEntryPath(context);
    StringBuffer sb = new StringBuffer(name.length() +
                                       1 +
                                       __ENTRY_KEY_PARAM.length() +
                                       1 +
                                       jspName.length());
    sb.append(name);
    if (name.indexOf('?') < 0)
      sb.append('?');
    else
      sb.append('&');

    sb.append(__ENTRY_KEY_PARAM);
    sb.append('=');
    sb.append(jspName);

    return sb.toString();
  }

  static public String getGenericEntryPath(FacesContext context)
  {
    String url = context.getApplication().getViewHandler().
      getActionURL(context, _GENERIC_ENTRY_VIEW_ID);

    return url;
  }

  @SuppressWarnings("unchecked")
  static private void service(FacesContext context, String name)
    throws IOException
  {
    if (_processReturnDialog(context,name))
    {
      return;
    }

    HttpServletResponse response =
      (HttpServletResponse) context.getExternalContext().getResponse();

    if (!_isValidEntry(name))
    {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }

    // Only use "text/html" for now, even if the browser thinks
    // it supports "text/html".
    String contentType = "text/html";
    String encoding = JspUtils.getEncoding(context, "UTF-8");

    if (encoding == null)
      response.setContentType(contentType);
    else
      response.setContentType(contentType +
                              "; charset=" + encoding);

    // =-=AEW Getting the Writer straight off of the ServletResponse
    // means losing buffered and unsynchronized goodness
    ResponseWriter responseWriter = context.getRenderKit().createResponseWriter(
      response.getWriter(),
      contentType,
      encoding);
    context.setResponseWriter(responseWriter);

    Map<String, String> requestParams =
      context.getExternalContext().getRequestParameterMap();

    String localeName = requestParams.get("loc");
    if (localeName != null)
    {
      Locale locale =
        LocaleUtils.getLocaleForIANAString(localeName);
      // Push the locale into JSF land
      context.getViewRoot().setLocale(locale);
    }

    _service(context, name);
  }

  static private void _service(
    FacesContext context,
    String jspName) throws IOException
  {
    // Prepare the view tree
    if (NEW_FRAME_REDIRECT_ENTRY.equals(jspName))
      FredJSP.service(context);
    else if (CALENDAR_DIALOG_ENTRY.equals(jspName))
      CalendarDialogJSP.service(context);
    else if (INLINE_DATE_PICKER_ENTRY.equals(jspName))
      InlineDatePickerJSP.service(context);
    else if (COLOR_PICKER_ENTRY.equals(jspName))
      ColorPickerJSP.service(context);
    else
    {
      assert(false);
    }

    // And render
    ResponseWriter rw = context.getResponseWriter();
    rw.startDocument();
    RenderUtils.encodeRecursive(context, context.getViewRoot());
    rw.endDocument();
  }

  static private boolean _processReturnDialog(
    FacesContext context,
    String jspName)
  {
    if (CALENDAR_DIALOG_ENTRY.equals(jspName))
      return CalendarDialogJSP.processReturnDialog(context);
    else
      return false;
  }

  static private boolean _isValidEntry(String name)
  {
    return _VALID_ENTRIES.contains(name);
  }

  //
  // Parameter that is used to store the key for the JSP name.
  //
  static final String __ENTRY_KEY_PARAM = "_t";
  static private final Set<String> _VALID_ENTRIES;

  static
  {
    _VALID_ENTRIES = new HashSet<String>();
    _VALID_ENTRIES.add(NEW_FRAME_REDIRECT_ENTRY);
    _VALID_ENTRIES.add(CALENDAR_DIALOG_ENTRY);
    _VALID_ENTRIES.add(INLINE_DATE_PICKER_ENTRY);
    _VALID_ENTRIES.add(COLOR_PICKER_ENTRY);
  }

  static private final String _GENERIC_ENTRY_VIEW_ID = "/__ADFv__";
}


text:
    <form name="mainFrm">

            <input type="hidden" ng-model="model.type" />

                Type
                <input type="text" class="form-control" value="#{.Name}#" disabled />

                ID
                <input type="text" ng-model="model.Id" class="form-control" value="" />

                Label
                <input type="text" ng-model="model.name" class="form-control" value="" />

                Description
                <textarea ng-model="model.description"  class="form-control" rows="3"></textarea>

                Host
                <input type="text" class="form-control" ng-model="model.attrib_host" />

                Pairing Key
                <input type="text" class="form-control" ng-model="model.attrib_pairingKey" />

            <button ng-click="submitForm()" class="btn btn-primary">Create</button>

    </form>

redpajama_set_name: RedPajamaGithub


text:
import json
import math

class DataSet:
    def __init__(self, target_attr = None, data = None):
        self.entropy_all = 0
        self.target_attr = target_attr
        self.attr_entropy = dict()  #entropy for each attribute
        if data is not None:
            self.data = data
            self.process()
        else:
            self.data = list()

    def load_from_file(self, file_name):
        """read data from a json file"""
        f = open(file_name, 'r')
        self.data = json.load(f)
        f.close()
        self.process()

    def entropy(self):
        """get total entropy"""
        if self.entropy_all == 0:
            target_attr_space = dict()
            total = 0
            for i in self.data:
                t = i[self.target_attr]
                if t not in target_attr_space.keys():
                    target_attr_space[t] = 1
                else:
                    target_attr_space[t] = target_attr_space[t] + 1
                total = total + 1

            for k, v in target_attr_space.items():
                #print('{0} - {1}'.format(k, v))
                self.entropy_all = self.entropy_all -(v/total)*math.log2(v/total)

        return self.entropy_all

    def gain(self, attr):
        """calculate information gain for a single attribute"""
        attr_space = dict()
        for i in self.data:
            t = i[attr]
            if t not in attr_space.keys():
                attr_space[t] = dict()

            tmp = i[self.target_attr]
            if tmp not in attr_space[t].keys():
                attr_space[t][tmp] = 0

            attr_space[t][tmp] = attr_space[t][tmp] + 1

        sss = self.entropy_all
        for k, v in attr_space.items():
            s = 0
            total = 0
            for kk, vv in v.items():
                total = total + vv

            for kk, vv in v.items():
                s = s - (vv/total)*math.log2(vv/total)

            sss = sss - (total/len(self.data)) * s

        return sss

    def process(self):
        """calculate all the information gain for each attribute"""
        self.entropy()
        for i in self.data[0].keys():
            if i == self.target_attr:
                continue
            if i not in self.attr_entropy.keys():
                self.attr_entropy[i] = self.gain(i)

    def get_highest_entropy_attr(self):
        """get the attribute with has the highest information gain,
        this attribute should be the root for this dataset according
        to id3 algorithm
        """
        attr = None
        e = 0
        for k, v in self.attr_entropy.items():
            if e < v:
                attr = k
                e = v

        return attr

    def get_attr_values(self, attr):
        """get all values of one attriute"""
        t = list()
        for i in self.data:
            if i[attr] not in t:
                t.append(i[attr])

        return t

    def get_subset_by_attr(self, attr, value):
        "get a sub dataset based on a attrbute and one of its value"
        t = list()
        for i in self.data:
            if i[attr] == value:
                t.append(i)

        return DataSet(self.target_attr, t)

if __name__ == '__main__':
    d = DataSet('Play_ball')
    d.load_from_file('day.json')
    print('total entropy is {0}'.format(d.entropy()))
    print('entropy is {0}'.format(d.gain('Wind')))
    print('entropy is {0}'.format(d.gain('Outlook')))
    print('entropy is {0}'.format(d.gain('Humidity')))
    print('entropy is {0}'.format(d.gain('Temperature')))
    s = 0
    for k, v in d.attr_entropy.items():
        print('{0} \t\t {1}'.format(k, v))
        s = s + v

    print('highest attr is {0}'.format(d.get_highest_entropy_attr()))

    for i in d.get_attr_values('Outlook'):
        print(i)

    x = d.get_subset_by_attr('Outlook', 'Sunny')
    for i in x.data:
        print(i)
    print('Outook Sunny entropy is {0}'.format(x.entropy()))


text:
package org.jboss.jandex;

import java.util.Set;

public final class ClassSummary {
    private final DotName name;
    private final DotName superclassName;
    private final Set<DotName> annotations;

    ClassSummary(DotName name, DotName superclassName, Set<DotName> annotations) {
        this.name = name;
        this.superclassName = superclassName;
        this.annotations = annotations;
    }

    public DotName name() {
        return name;
    }

    public DotName superclassName() {
        return superclassName;
    }

    public Set<DotName> annotations() {
        return annotations;
    }

    public int annotationsCount() {
        return annotations.size();
    }
}


text:
/** @type import("@babel/core").ConfigFunction */
module.exports = (api) => ({
  plugins: [
    "@babel/plugin-syntax-dynamic-import",
    "@babel/plugin-proposal-class-properties",
  ],
  presets: [
    [
      "@babel/preset-env",
      {
        useBuiltIns: "usage",
        corejs: 3,
        targets: (() => {
          switch (api.env()) {
            case "browser":
              return "defaults";
            case "node":
              return { node: true };
            default:
              throw new Error();
          }
        })(),
      },
    ],
    "@babel/preset-react",
    "@babel/preset-typescript",
  ],
  sourceType: "unambiguous",
});


text:
BEEEON_OBJECT_BEGIN(BeeeOn, LoggingQueryProfiler)
BEEEON_OBJECT_CASTABLE(QueryProfiler)
BEEEON_OBJECT_PROPERTY("topCount", &LoggingQueryProfiler::setTopCount)
BEEEON_OBJECT_HOOK("cleanup", &LoggingQueryProfiler::reportStats)
BEEEON_OBJECT_END(BeeeOn, LoggingQueryProfiler)

using namespace std;
using namespace Poco;
using namespace BeeeOn;

LoggingQueryProfiler::LoggingQueryProfiler():
	m_topCount(10)
{
}

void LoggingQueryProfiler::setTopCount(int count)
{
	if (count < 0) {
		throw InvalidArgumentException(
			"topCount must be non-negative");
	}

	m_topCount = count;
}

void LoggingQueryProfiler::use(const string &key)
{
	static Occasionally occasionally;

	Mutex::ScopedLock guard(m_lock);

	auto result = m_stats.emplace(key, 1);
	if (!result.second)
		result.first->second += 1;

	occasionally.execute([&]() {
		reportTopStats();
	});
}

void LoggingQueryProfiler::reportTopStats(int count, Message::Priority prio)
{
	if (count == 0)
		return;

	multimap<uint64_t, string> sorted;

	ScopedLockWithUnlock<Mutex> guard(m_lock);
	for (const auto &pair : m_stats)
		sorted.emplace(pair.second, pair.first);

	guard.unlock();
	string record;

	record += "queries usage stats:";

	for (auto it = sorted.rbegin(); it != sorted.rend(); ++it) {
		if (count >= 0 && count-- == 0)
			break;

		record += "\n";
		record += it->second + ": " + to_string(it->first);
	}

	logger().log(Message{
		logger().name(), record, prio, __FILE__, __LINE__});
}

void LoggingQueryProfiler::reportTopStats()
{
	reportTopStats(m_topCount, Message::PRIO_INFORMATION);
}

void LoggingQueryProfiler::reportStats()
{
	reportTopStats(-1, Message::PRIO_NOTICE);
}


text:
body.opr-texiao-jump {
    animation: page_jump 2s ease;
    -webkit-animation: page_jump 2s ease
}
section:not(:last-child) {
    margin-bottom: 50px;
}

section .content > img {
    float: left;
    margin-right: 30px;
}

.button-wrapper{
    position: fixed;
    right: 0;
    top: 0;
}

@keyframes page_jump {
    from {
        transform: translateY(0);
        -ms-transform: translateY(0);
        -moz-transform: translateY(0);
        -webkit-transform: translateY(0);
        -o-transform: translateY(0)
    }
    17% {
        transform: translateY(-200px);
        -ms-transform: translateY(-200px);
        -moz-transform: translateY(-200px);
        -webkit-transform: translateY(-200px);
        -o-transform: translateY(-200px)
    }
    33% {
        transform: translateY(0);
        -ms-transform: translateY(0);
        -moz-transform: translateY(0);
        -webkit-transform: translateY(0);
        -o-transform: translateY(0)
    }
    49% {
        transform: translateY(-100px);
        -ms-transform: translateY(-100px);
        -moz-transform: translateY(-100px);
        -webkit-transform: translateY(-100px);
        -o-transform: translateY(-100px)
    }
    66% {
        transform: translateY(0);
        -ms-transform: translateY(0);
        -moz-transform: translateY(0);
        -webkit-transform: translateY(0);
        -o-transform: translateY(0)
    }
    83% {
        transform: translateY(-50px);
        -ms-transform: translateY(-50px);
        -moz-transform: translateY(-50px);
        -webkit-transform: translateY(-50px);
        -o-transform: translateY(-50px)
    }
    to {
        transform: translateY(0);
        -ms-transform: translateY(0);
        -moz-transform: translateY(0);
        -webkit-transform: translateY(0);
        -o-transform: translateY(0)
    }
}

@-webkit-keyframes page_jump {
    from {
        transform: translateY(0);
        -ms-transform: translateY(0);
        -moz-transform: translateY(0);
        -webkit-transform: translateY(0);
        -o-transform: translateY(0)
    }
    17% {
        transform: translateY(-200px);
        -ms-transform: translateY(-200px);
        -moz-transform: translateY(-200px);
        -webkit-transform: translateY(-200px);
        -o-transform: translateY(-200px)
    }
    33% {
        transform: translateY(0);
        -ms-transform: translateY(0);
        -moz-transform: translateY(0);
        -webkit-transform: translateY(0);
        -o-transform: translateY(0)
    }
    49% {
        transform: translateY(-100px);
        -ms-transform: translateY(-100px);
        -moz-transform: translateY(-100px);
        -webkit-transform: translateY(-100px);
        -o-transform: translateY(-100px)
    }
    66% {
        transform: translateY(0);
        -ms-transform: translateY(0);
        -moz-transform: translateY(0);
        -webkit-transform: translateY(0);
        -o-transform: translateY(0)
    }
    83% {
        transform: translateY(-50px);
        -ms-transform: translateY(-50px);
        -moz-transform: translateY(-50px);
        -webkit-transform: translateY(-50px);
        -o-transform: translateY(-50px)
    }
    to {
        transform: translateY(0);
        -ms-transform: translateY(0);
        -moz-transform: translateY(0);
        -webkit-transform: translateY(0);
        -o-transform: translateY(0)
    }
}


text:
import os
import json

import pytest
import six

from django.conf import settings

from olympia.lib.settings_base import get_raven_release

@pytest.mark.parametrize('key', (
    'SHARED_STORAGE', 'GUARDED_ADDONS_PATH', 'TMP_PATH', 'MEDIA_ROOT'))
def test_base_paths_bytestring(key):
    """Make sure all relevant base paths are bytestrings.

    Filenames and filesystem paths are generally handled as byte-strings
    and we are running into various errors if they're not.

    One of many examples would be

    >>> os.path.join(u'path1', u'pæth2'.encode('utf-8'))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib64/python2.7/posixpath.py", line 80, in join
        path += '/' + b
    UnicodeDecodeError: 'ascii' codec can't decode byte...

    See https://github.com/mozilla/addons-server/issues/3579 for context.
    """
    assert isinstance(getattr(settings, key), six.string_types)

def test_raven_release_config():
    version_json = os.path.join(settings.ROOT, 'version.json')
    original = None

    # There is a version.json that contains `version: origin/master`
    # by default in the repository. We should ignore that and fetch
    # the git commit.
    assert len(get_raven_release()) == 40

    # Cleanup for tests
    if os.path.exists(version_json):
        with open(version_json) as fobj:
            original = fobj.read()

        os.remove(version_json)

    # by default, if no version.json exists it simply fetches a git-sha
    assert len(get_raven_release()) == 40

    # It fetches `version` from the version.json
    with open(version_json, 'w') as fobj:
        fobj.write(json.dumps({
            'version': '2018.07.19'
        }))

    assert get_raven_release() == '2018.07.19'

    os.remove(version_json)

    # Or tries to get the commit from version.json alternatively
    with open(version_json, 'w') as fobj:
        fobj.write(json.dumps({
            'commit': '1111111'
        }))

    assert get_raven_release() == '1111111'

    if original:
        with open(version_json, 'w') as fobj:
            fobj.write(original)

    # Usual state of things, version is empty but commit is set
    with open(version_json, 'w') as fobj:
        fobj.write(json.dumps({
            'version': '',
            'commit': '1111111'
        }))

    assert get_raven_release() == '1111111'

    if original:
        with open(version_json, 'w') as fobj:
            fobj.write(original)


text:
<?php

?>
<?php

/**
 * userReports actions.
 *
 * @package    sf_sandbox
 * @subpackage userReports
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class userReportsActions extends sfActions
{
  public function checkAccess($reports,$check_view = false)
  {
    if($reports->getUsersId()!=$this->getUser()->getAttribute('id'))
    {
      $this->redirect('accessForbidden/index');
    }
  }

  public function executeIndex(sfWebRequest $request)
  {
    $this->user_reportss = Doctrine_Core::getTable('UserReports')
      ->createQuery()
      ->addWhere('users_id=?',$this->getUser()->getAttribute('id'))
      ->orderBy('sort_order, name')
      ->execute();

    app::setPageTitle('Tasks Reports',$this->getResponse());
  }

  public function executeView(sfWebRequest $request)
  {
    $this->forward404Unless($this->tasks_reports = Doctrine_Core::getTable('UserReports')->find(array($request->getParameter('id'))), sprintf('Object tasks_reports does not exist (%s).', $request->getParameter('id')));

    $this->checkAccess($this->tasks_reports, true);

    app::setPageTitle($this->tasks_reports->getName(),$this->getResponse());
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = new UserReportsForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new UserReportsForm();

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($user_reports = Doctrine_Core::getTable('UserReports')->find(array($request->getParameter('id'))), sprintf('Object user_reports does not exist (%s).', $request->getParameter('id')));
    $this->checkAccess($user_reports);
    $this->form = new UserReportsForm($user_reports);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($user_reports = Doctrine_Core::getTable('UserReports')->find(array($request->getParameter('id'))), sprintf('Object user_reports does not exist (%s).', $request->getParameter('id')));
    $this->checkAccess($user_reports);
    $this->form = new UserReportsForm($user_reports);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($user_reports = Doctrine_Core::getTable('UserReports')->find(array($request->getParameter('id'))), sprintf('Object user_reports does not exist (%s).', $request->getParameter('id')));
    $this->checkAccess($user_reports);
    $user_reports->delete();

    switch($request->getParameter('redirect_to'))
    {
      case 'commonReports': $this->redirect('commonReports/index');
        break;
      default: $this->redirect('userReports/index');
        break;
    }
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {

      $form->setFieldValue('tasks_type_id',$form['tasks_type_id']->getValue());
      $form->setFieldValue('tasks_status_id',$form['tasks_status_id']->getValue());
      $form->setFieldValue('tasks_label_id',$form['tasks_label_id']->getValue());

      $form->setFieldValue('assigned_to',$form['assigned_to']->getValue());

      $form->setFieldValue('projects_type_id',$form['projects_type_id']->getValue());
      $form->setFieldValue('projects_status_id',$form['projects_status_id']->getValue());
      $form->setFieldValue('projects_id',$form['projects_id']->getValue());

      $user_reports = $form->save();

      switch($request->getParameter('redirect_to'))
      {
        case 'view': $this->redirect('userReports/view?id=' . $user_reports->getId());
          break;
        default: $this->redirect('userReports/index');
          break;
      }
    }
  }
}


text:
package apple.scenekit;

import apple.NSObject;
import apple.foundation.NSArray;
import apple.foundation.NSCoder;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import apple.foundation.protocol.NSCopying;
import apple.foundation.protocol.NSSecureCoding;
import apple.scenekit.struct.SCNVector3;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.ByValue;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.MappedReturn;
import org.moe.natj.general.ann.NFloat;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.ProtocolClassMethod;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

/**
 * SCNPhysicsVehicleWheel
 * <p>
 * SCNPhysicsVehicleWheel represents a wheel that can be attached to a SCNPhysicsVehicle instance.
 */
@Generated
@Library("SceneKit")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class SCNPhysicsVehicleWheel extends NSObject implements NSCopying, NSSecureCoding {
    static {
        NatJ.register();
    }

    @Generated
    protected SCNPhysicsVehicleWheel(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    @Generated
    @Owned
    @Selector("alloc")
    public static native SCNPhysicsVehicleWheel alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native SCNPhysicsVehicleWheel allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("description")
    public static native String description_static();

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    @Generated
    @Owned
    @Selector("new")
    public static native SCNPhysicsVehicleWheel new_objc();

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("supportsSecureCoding")
    public static native boolean supportsSecureCoding();

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();

    /**
     * Initializes and returns a wheel.
     */
    @Generated
    @Selector("wheelWithNode:")
    public static native SCNPhysicsVehicleWheel wheelWithNode(SCNNode node);

    /**
     * The wheel axle in the vehicle chassis space. Defaults to (-1,0,0).
     */
    @Generated
    @Selector("axle")
    @ByValue
    public native SCNVector3 axle();

    /**
     * The wheel connection point relative to the chassis. Defaults to the node position.
     */
    @Generated
    @Selector("connectionPosition")
    @ByValue
    public native SCNVector3 connectionPosition();

    @Generated
    @Owned
    @Selector("copyWithZone:")
    @MappedReturn(ObjCObjectMapper.class)
    public native Object copyWithZone(VoidPtr zone);

    @Generated
    @Selector("encodeWithCoder:")
    public native void encodeWithCoder(NSCoder coder);

    /**
     * The wheel friction slip coefficient. Defaults to 1.
     */
    @Generated
    @Selector("frictionSlip")
    @NFloat
    public native double frictionSlip();

    @Generated
    @Selector("init")
    public native SCNPhysicsVehicleWheel init();

    @Generated
    @Selector("initWithCoder:")
    public native SCNPhysicsVehicleWheel initWithCoder(NSCoder coder);

    /**
     * The wheel maximum suspension force in newtons. Defaults to 6000.
     */
    @Generated
    @Selector("maximumSuspensionForce")
    @NFloat
    public native double maximumSuspensionForce();

    /**
     * The wheel maximum suspension travel in centimeters. Defaults to 500.
     */
    @Generated
    @Selector("maximumSuspensionTravel")
    @NFloat
    public native double maximumSuspensionTravel();

    /**
     * The node of the receiver.
     */
    @Generated
    @Selector("node")
    public native SCNNode node();

    /**
     * The wheel radius. Defaults to the half of the max dimension of the bounding box of the node.
     */
    @Generated
    @Selector("radius")
    @NFloat
    public native double radius();

    /**
     * The wheel axle in the vehicle chassis space. Defaults to (-1,0,0).
     */
    @Generated
    @Selector("setAxle:")
    public native void setAxle(@ByValue SCNVector3 value);

    /**
     * The wheel connection point relative to the chassis. Defaults to the node position.
     */
    @Generated
    @Selector("setConnectionPosition:")
    public native void setConnectionPosition(@ByValue SCNVector3 value);

    /**
     * The wheel friction slip coefficient. Defaults to 1.
     */
    @Generated
    @Selector("setFrictionSlip:")
    public native void setFrictionSlip(@NFloat double value);

    /**
     * The wheel maximum suspension force in newtons. Defaults to 6000.
     */
    @Generated
    @Selector("setMaximumSuspensionForce:")
    public native void setMaximumSuspensionForce(@NFloat double value);

    /**
     * The wheel maximum suspension travel in centimeters. Defaults to 500.
     */
    @Generated
    @Selector("setMaximumSuspensionTravel:")
    public native void setMaximumSuspensionTravel(@NFloat double value);

    /**
     * The wheel radius. Defaults to the half of the max dimension of the bounding box of the node.
     */
    @Generated
    @Selector("setRadius:")
    public native void setRadius(@NFloat double value);

    /**
     * The wheel steering axis in the vehicle chassis space. Defaults to (0,-1,0).
     */
    @Generated
    @Selector("setSteeringAxis:")
    public native void setSteeringAxis(@ByValue SCNVector3 value);

    /**
     * The wheel suspension compression. Defaults to 4.4.
     */
    @Generated
    @Selector("setSuspensionCompression:")
    public native void setSuspensionCompression(@NFloat double value);

    /**
     * The wheel suspension damping. Defaults to 2.3.
     */
    @Generated
    @Selector("setSuspensionDamping:")
    public native void setSuspensionDamping(@NFloat double value);

    /**
     * The wheel suspension rest length. Defaults to 1.6.
     */
    @Generated
    @Selector("setSuspensionRestLength:")
    public native void setSuspensionRestLength(@NFloat double value);

    /**
     * The wheel suspension stiffness. Defaults to 2.0.
     */
    @Generated
    @Selector("setSuspensionStiffness:")
    public native void setSuspensionStiffness(@NFloat double value);

    /**
     * The wheel steering axis in the vehicle chassis space. Defaults to (0,-1,0).
     */
    @Generated
    @Selector("steeringAxis")
    @ByValue
    public native SCNVector3 steeringAxis();

    @Generated
    @ProtocolClassMethod("supportsSecureCoding")
    public boolean _supportsSecureCoding() {
        return supportsSecureCoding();
    }

    /**
     * The wheel suspension compression. Defaults to 4.4.
     */
    @Generated
    @Selector("suspensionCompression")
    @NFloat
    public native double suspensionCompression();

    /**
     * The wheel suspension damping. Defaults to 2.3.
     */
    @Generated
    @Selector("suspensionDamping")
    @NFloat
    public native double suspensionDamping();

    /**
     * The wheel suspension rest length. Defaults to 1.6.
     */
    @Generated
    @Selector("suspensionRestLength")
    @NFloat
    public native double suspensionRestLength();

    /**
     * The wheel suspension stiffness. Defaults to 2.0.
     */
    @Generated
    @Selector("suspensionStiffness")
    @NFloat
    public native double suspensionStiffness();
}


text:
package com.t2t.top.exception;

import org.apache.commons.lang3.ArrayUtils;

public class BaseRuntimeException extends RuntimeException {

    private static final long serialVersionUID = 4346150683764930045L;

    private int code;

    private String msg;

    public BaseRuntimeException() {
        super();
    }

    public BaseRuntimeException(Throwable cause) {
        super(cause);
    }

    public BaseRuntimeException(String message) {
        super(message);
    }

    public BaseRuntimeException(String message, Throwable cause) {
        super(message, cause);
    }

    public BaseRuntimeException(int code, String msg) {
        super(msg);
        this.code = code;
        this.msg = msg;
    }

    public BaseRuntimeException(int code, String msg, Throwable cause) {
        super(cause);
        this.code = code;
        this.msg = msg;
    }

    public BaseRuntimeException(int code, String... msgs) {
        super(ArrayUtils.toString(msgs));
        this.code = code;
        this.msg = ArrayUtils.toString(msgs);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}


text:
@implementation AnalyticsKitDebugProvider

#pragma mark -
#pragma mark Lifecycle

-(void)applicationWillEnterForeground{}

-(void)applicationDidEnterBackground{}

-(void)applicationWillTerminate{}

-(void)uncaughtException:(NSException *)exception{}

#pragma mark -
#pragma mark Event Logging

-(void)logScreen:(NSString *)screenName{}

-(void)logEvent:(NSString *)value {}

-(void)logEvent:(NSString *)event withProperty:(NSString *)key andValue:(NSString *)value {}

-(void)logEvent:(NSString *)event withProperties:(NSDictionary *)dict {}

-(void)logEvent:(NSString *)eventName timed:(BOOL)timed{}

-(void)logEvent:(NSString *)eventName withProperties:(NSDictionary *)dict timed:(BOOL)timed{}

-(void)endTimedEvent:(NSString *)eventName withProperties:(NSDictionary *)dict{}

-(void)showDebugAlert:(NSString *)message{
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AnalyticsKit Received Error"
                                                             message:message
                                                            delegate:self cancelButtonTitle:@"Ok"
                                                   otherButtonTitles:nil];
            #if !__has_feature(objc_arc)
            [alert autorelease];
            #endif
            [alert show];
        }];
}

-(void)logError:(NSString *)name message:(NSString *)message exception:(NSException *)exception{
    NSString *detail = [NSString stringWithFormat:@"%@\n\n%@\n\n%@", name, message, exception];
    [self showDebugAlert:detail];
}

-(void)logError:(NSString *)name message:(NSString *)message error:(NSError *)error{
    NSString *detail = [NSString stringWithFormat:@"%@\n\n%@\n\n%@", name, message, error];
    [self showDebugAlert:detail];
}

@end


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/prdf/plat/pegasus/prdfPlatCenMemUtils.C $        */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2014,2015                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

/** @file  prdfPlatCenMemUtils.C
 *  @brief Hostboot Utility functions related to Centaur
 */

#include <prdfCenMemUtils.H>
#include <prdfExtensibleChip.H>
#include <prdfCenMembufDataBundle.H>

using namespace TARGETING;

namespace PRDF
{

namespace MemUtils
{

//------------------------------------------------------------------------------

int32_t mcifirCleanup( ExtensibleChip *i_mbChip,
                       STEP_CODE_DATA_STRUCT & i_sc )
{
    #define PRDF_FUNC "[MemUtils::mcifirCleanup] "

    int32_t l_rc = SUCCESS;

    // In hostboot, we need to clear associated bits in the MCIFIR bits.
    do
    {
        CenMembufDataBundle * mbdb = getMembufDataBundle(i_mbChip);
        ExtensibleChip * mcsChip = mbdb->getMcsChip();
        if ( NULL == mcsChip )
        {
            PRDF_ERR( PRDF_FUNC "CenMembufDataBundle::getMcsChip() failed" );
            l_rc = FAIL;
            break;
        }

        // Clear the associated MCIFIR bits for all attention types.
        // NOTE: If there are any active attentions left in the Centaur the
        //       associated MCIFIR bit will be redriven with the next packet on
        //       the bus.
        SCAN_COMM_REGISTER_CLASS * firand = mcsChip->getRegister("MCIFIR_AND");

        firand->setAllBits();
        firand->ClearBit(12); // CS
        firand->ClearBit(15); // RE
        firand->ClearBit(16); // SPA
        firand->ClearBit(17); // maintenance command complete

        l_rc = firand->Write();
        if ( SUCCESS != l_rc )
        {
            PRDF_ERR( PRDF_FUNC "MCIFIR_AND write failed" );
            break;
        }

    } while (0);

    return l_rc;

    #undef PRDF_FUNC
}

} // end namespace MemUtils

} // end namespace PRDF


text:
<?php

namespace WarGaming\Api\Model\WoT;

use WarGaming\Api\Model\Collection;

/**
 * Clan collection
 *
 * @author Vitaliy Zhuk <zhuk2205@gmail.com>
 */
class ClanCollection extends Collection
{
    /**
     * @var array|Clan[]
     */
    protected $storage;

    /**
     * Get accounts
     *
     * @return AccountCollection|Account[]
     */
    public function getAccounts()
    {
        $accounts = new AccountCollection();

        foreach ($this->storage as $clan) {
            $accounts->addCollection($clan->members);
        }

        return $accounts;
    }
}


text:
<?xml version="1.0" ?>
<!--
// Licensed to Julian Hyde under one or more contributor license
// agreements. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
//
// Julian Hyde licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Base resource file for ResGen example.
  -->
<resourceBundle locale="en_US">
  <message name="HappyBirthday">
    <text>Happy Birthday, {0}! You don''t look {1,number}.</text>
  </message>
  <exception name="TooYoung" className="RuntimeException">
    <text>{0} has not been born yet.</text>
  </exception>

  <!-- The following example contains a single apostrophe, which will cause
       the rest of the message to be misinterpreted. The author of the message
       should probably have doubled up the apostrophe. -->
  <exception name="ShouldGiveWarning" className="RuntimeException">
    <text>You don't look {1,number}, {0}!</text>
  </exception>

  <!-- The following resource contains HTML markup, to test that it is escaped
       correctly when generating javadoc. -->
  <message name="WithMarkup">
    <text><![CDATA[This <tag is="not">very</kosher>.]]></text>
  </message>
</resourceBundle>


text:
<?php

final class PhabricatorRepositoryMirrorQuery
  extends PhabricatorCursorPagedPolicyAwareQuery {

  private $ids;
  private $phids;
  private $repositoryPHIDs;

  public function withIDs(array $ids) {
    $this->ids = $ids;
    return $this;
  }

  public function withPHIDs(array $phids) {
    $this->phids = $phids;
    return $this;
  }

  public function withRepositoryPHIDs(array $repository_phids) {
    $this->repositoryPHIDs = $repository_phids;
    return $this;
  }

  protected function loadPage() {
    $table = new PhabricatorRepositoryMirror();
    $conn_r = $table->establishConnection('r');

    $data = queryfx_all(
      $conn_r,
      'SELECT * FROM %T %Q %Q %Q',
      $table->getTableName(),
      $this->buildWhereClause($conn_r),
      $this->buildOrderClause($conn_r),
      $this->buildLimitClause($conn_r));

    return $table->loadAllFromArray($data);
  }

  protected function willFilterPage(array $mirrors) {
    assert_instances_of($mirrors, 'PhabricatorRepositoryMirror');

    $repository_phids = mpull($mirrors, 'getRepositoryPHID');
    if ($repository_phids) {
      $repositories = id(new PhabricatorRepositoryQuery())
        ->setViewer($this->getViewer())
        ->withPHIDs($repository_phids)
        ->execute();
      $repositories = mpull($repositories, null, 'getPHID');
    } else {
      $repositories = array();
    }

    foreach ($mirrors as $key => $mirror) {
      $phid = $mirror->getRepositoryPHID();
      if (empty($repositories[$phid])) {
        unset($mirrors[$key]);
        continue;
      }
      $mirror->attachRepository($repositories[$phid]);
    }

    return $mirrors;
  }

  protected function buildWhereClause(AphrontDatabaseConnection $conn_r) {
    $where = array();

    if ($this->ids) {
      $where[] = qsprintf(
        $conn_r,
        'id IN (%Ld)',
        $this->ids);
    }

    if ($this->phids) {
      $where[] = qsprintf(
        $conn_r,
        'phid IN (%Ls)',
        $this->phids);
    }

    if ($this->repositoryPHIDs) {
      $where[] = qsprintf(
        $conn_r,
        'repositoryPHID IN (%Ls)',
        $this->repositoryPHIDs);
    }

    $where[] = $this->buildPagingClause($conn_r);

    return $this->formatWhereClause($where);
  }

  public function getQueryApplicationClass() {
    return 'PhabricatorDiffusionApplication';
  }

}


text:
package io.joern.x2cpg.passes.base

import io.joern.x2cpg.Defines
import io.shiftleft.codepropertygraph.Cpg
import io.shiftleft.codepropertygraph.generated.nodes._
import io.shiftleft.codepropertygraph.generated.{EdgeTypes, EvaluationStrategies, NodeTypes}
import io.shiftleft.passes.CpgPass
import io.shiftleft.semanticcpg.language._
import overflowdb.BatchedUpdate

import scala.collection.mutable
import scala.util.Try

case class NameAndSignature(name: String, signature: String, fullName: String)

/** This pass has no other pass as prerequisite.
  */
class MethodStubCreator(cpg: Cpg) extends CpgPass(cpg) {

  // Since the method fullNames for fuzzyc are not unique, we do not have
  // a 1to1 relation and may overwrite some values. This is ok for now.
  private val methodFullNameToNode   = mutable.LinkedHashMap[String, Method]()
  private val methodToParameterCount = mutable.LinkedHashMap[NameAndSignature, Int]()

  override def run(dstGraph: BatchedUpdate.DiffGraphBuilder): Unit = {
    for (method <- cpg.method) {
      methodFullNameToNode.put(method.fullName, method)
    }

    for (call <- cpg.call if call.methodFullName != Defines.DynamicCallUnknownFallName) {
      methodToParameterCount.put(NameAndSignature(call.name, call.signature, call.methodFullName), call.argument.size)
    }

    for (
      (NameAndSignature(name, signature, fullName), parameterCount) <- methodToParameterCount
      if !methodFullNameToNode.contains(fullName)
    ) {
      createMethodStub(name, fullName, signature, parameterCount, dstGraph)
    }
  }

  override def finish(): Unit = {
    methodFullNameToNode.clear()
    methodToParameterCount.clear()
    super.finish()
  }

  private def addLineNumberInfo(methodNode: NewMethod, fullName: String): NewMethod = {
    val s = fullName.split(":")
    if (s.size == 5 && Try { s(1).toInt }.isSuccess && Try { s(2).toInt }.isSuccess) {
      val filename      = s(0)
      val lineNumber    = s(1).toInt
      val lineNumberEnd = s(2).toInt
      methodNode
        .filename(filename)
        .lineNumber(lineNumber)
        .lineNumberEnd(lineNumberEnd)
    } else {
      methodNode
    }
  }

  private def createMethodStub(
    name: String,
    fullName: String,
    signature: String,
    parameterCount: Int,
    dstGraph: DiffGraphBuilder
  ): NewMethod = {
    val methodNode = addLineNumberInfo(
      NewMethod()
        .name(name)
        .fullName(fullName)
        .isExternal(true)
        .signature(signature)
        .astParentType(NodeTypes.NAMESPACE_BLOCK)
        .astParentFullName("<global>")
        .order(0),
      fullName
    )

    dstGraph.addNode(methodNode)

    (1 to parameterCount).foreach { parameterOrder =>
      val nameAndCode = s"p$parameterOrder"
      val param = NewMethodParameterIn()
        .code(nameAndCode)
        .order(parameterOrder)
        .name(nameAndCode)
        .evaluationStrategy(EvaluationStrategies.BY_VALUE)
        .typeFullName("ANY")

      dstGraph.addNode(param)
      dstGraph.addEdge(methodNode, param, EdgeTypes.AST)
    }

    val blockNode = NewBlock()
      .order(1)
      .argumentIndex(1)
      .typeFullName("ANY")

    dstGraph.addNode(blockNode)
    dstGraph.addEdge(methodNode, blockNode, EdgeTypes.AST)

    val methodReturn = NewMethodReturn()
      .order(2)
      .code("RET")
      .evaluationStrategy(EvaluationStrategies.BY_VALUE)
      .typeFullName("ANY")

    dstGraph.addNode(methodReturn)
    dstGraph.addEdge(methodNode, methodReturn, EdgeTypes.AST)

    methodNode
  }

}


text:
// Copyright (c) 2015 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Globalization;
using System.Text;
using System.Collections.Generic;
using Enyim.Caching.Memcached.Results;

namespace Enyim.Caching.Memcached.Protocol.Text
{
	public class StoreOperationBase : SingleItemOperation
	{
		private static readonly ArraySegment<byte> DataTerminator = new ArraySegment<byte>(new byte[2] { (byte)'\r', (byte)'\n' });
		private StoreCommand command;
		private CacheItem value;
		private uint expires;
		private ulong cas;

		internal StoreOperationBase(StoreCommand mode, string key, CacheItem value, uint expires, ulong cas)
			: base(key)
		{
			this.command = mode;
			this.value = value;
			this.expires = expires;
			this.cas = cas;
		}

		protected internal override System.Collections.Generic.IList<ArraySegment<byte>> GetBuffer()
		{
			// todo adjust the size to fit a request using a fnv hashed key
			var sb = new StringBuilder(128);
			var buffers = new List<ArraySegment<byte>>(3);

			switch (this.command)
			{
				case StoreCommand.Add: sb.Append("add "); break;
				case StoreCommand.Replace: sb.Append("replace "); break;
				case StoreCommand.Set: sb.Append("set "); break;
				case StoreCommand.Append: sb.Append("append "); break;
				case StoreCommand.Prepend: sb.Append("prepend "); break;
				case StoreCommand.CheckAndSet: sb.Append("cas "); break;
				default: throw new MemcachedClientException(command + " is not supported.");
			}

			sb.Append(this.Key);
			sb.Append(" ");
			sb.Append(this.value.Flags.ToString(CultureInfo.InvariantCulture));
			sb.Append(" ");
			sb.Append(this.expires.ToString(CultureInfo.InvariantCulture));
			sb.Append(" ");

			var data = this.value.Data;
			sb.Append(Convert.ToString(data.Count, CultureInfo.InvariantCulture));

			if (command == StoreCommand.CheckAndSet)
			{
				sb.Append(" ");
				sb.Append(Convert.ToString(this.cas, CultureInfo.InvariantCulture));
			}

			sb.Append(TextSocketHelper.CommandTerminator);

			TextSocketHelper.GetCommandBuffer(sb.ToString(), buffers);
			buffers.Add(data);
			buffers.Add(StoreOperationBase.DataTerminator);

			return buffers;
		}

		protected internal override IOperationResult ReadResponse(PooledSocket socket)
		{
			return new TextOperationResult
			{
				Success = String.Compare(TextSocketHelper.ReadResponse(socket), "STORED", StringComparison.Ordinal) == 0
			};
		}

		protected internal override bool ReadResponseAsync(PooledSocket socket, System.Action<bool> next)
		{
			throw new System.NotSupportedException();
		}
	}
}

#region [ License information          ]

#endregion


text:
class CreateSpreeDesignOptions < ActiveRecord::Migration[4.2]
  def change
    create_table :spree_design_options do |t|
      enable_extension 'hstore'

      t.string :name
      t.string :label
      t.hstore :meta, default: {}
      t.integer :position
      t.boolean :active, default: true

      t.string :medium

      t.references :design_configuration

      t.timestamp :deleted_at
      t.timestamps null: false
    end
  end
end


text:
<?php

class Kohana_Migration_Statement_CreateTable extends Kohana_Migration_Statement {

	protected $_tableName;
	protected $_engine;
	protected $_charset;

	/**
	 * @var Kohana_Migration_Column[]
	 */
	protected $_columns = array();
	/**
	 * @var Kohana_Migration_Index[]
	 */
	protected $_indexes = array();
	/**
	 * @var Kohana_Migration_Key[]
	 */
	protected $_keys = array();
	protected $_primaryKey = null;

	/**
	 * Default options for creating the table.
	 * @var array
	 * id - If string, it creates a integer, auto-increment column. If false, it does not.
	 * created - If string, create a timestamp created column. If false, it does not.
	 * modified - If string, it creates a timestamp modified column. If false, it does not.
	 * primary_key - If string or array, it is the column name(s) of the primary key. If true, it is the id column. If false there is no Primary Key.
	 * engine - The engine to use.
	 * charset - The charset to use.
	 */
	protected $_default_options = array(
		'id' => 'id',
		'created' => 'created',
		'modified' => 'modified',
		'primary_key' => true,
		'engine' => 'InnoDB',
		'charset' => 'utf8',
	);

	/**
	 * Create a new table.
	 * @see $_default_options
	 * @param string $name - The name of the table.
	 * @param array|null $args - An optional array of options for the table.
	 */
	public function __construct($name, $args = null)
	{
		$this->_tableName = $name;

		if (is_array($args))
		{
			$args = array_merge($this->_default_options, $args);
		}
		else
		{
			$args = $this->_default_options;
		}

		if ($args['id'] !== false)
		{
			$this->addColumn('integer', $args['id'], array('size' => 11, 'null' => false, 'unsigned' => true, 'auto_increment' => true));
			if (true === $args['primary_key'])
			{
				$this->primaryKey($args['id']);
			}
		}

		if ($args['created'] !== false)
		{
			$this->addColumn('integer', $args['created'], array('null' => false, 'unsigned' => true));
		}

		if ($args['modified'] !== false)
		{
			$this->addColumn('integer', $args['modified'], array('null' => false));
		}

		if (is_string($args['primary_key']) or is_array($args['primary_key']))
		{
			$this->primaryKey($args['primary_key']);
		}

		$this->engine($args['engine']);
		$this->charset($args['charset']);
	}

	/**
	 * Generate SQL statement
	 * @return string
	 */
	public function toSQL()
	{
		$sql = "CREATE TABLE `{$this->_tableName}` (\n\t";

		$rows = array();

		foreach ($this->_columns as $column)
		{
			$rows[] = $column->toSQL();
		}

		// Insert the PK
		if (!is_null($this->_primaryKey))
		{
			$pk = is_array($this->_primaryKey) ? implode('`, `', $this->_primaryKey) : $this->_primaryKey;
			$rows[] = "PRIMARY KEY( `$pk` )";
		}

		// Generate any other indexes/keys here
		foreach ($this->_keys as $name => $key)
		{
			$rows[] = $key->toSQL();
		}
		foreach ($this->_indexes as $name => $index)
		{
			$rows[] = $index->toSQL();
		}

		$sql .= implode(",\n\t", $rows);

		$sql .= "\n) ENGINE={$this->_engine} DEFAULT CHARSET={$this->_charset};\n\n";

		return $sql;
	}

	/**
	 * Set the engine for this table.
	 * @param string $engine - The name of the engine to use.
	 */
	public function engine($engine)
	{
		$this->_engine = $engine;
	}

	/**
	 * Set the charset for this table.
	 * @param string $charset - The name of the charset to use.
	 */
	public function charset($charset)
	{
		$this->_charset = $charset;
	}

	/**
	 * Set the primary key for this table.
	 * @param string|array $columnName - The column name(s) for the primary key.
	 */
	public function primaryKey($columnName)
	{
		$this->_primaryKey = $columnName;
	}

	/**
	 * Set the name of this table.
	 * @param string $tableName - The name for the table.
	 */
	public function tableName($tableName)
	{
		$this->_tableName = $tableName;
	}

	/**
	 * Add a column to this table.
	 * @param string $type - The type of column to add.
	 * @param string $name - The name of the new column.
	 * @param array|null $traits - An optional array of traits for this column.
	 */
	public function addColumn($type, $name, $traits = null)
	{
		$this->_columns[$name] = new Kohana_Migration_Column($name, $type, $traits);
	}

	/**
	 * Add an index to this table.
	 * @param array $columns - An array of columns to put the index on.
	 * @param array|null $traits - An optional array of traits for the index.
	 */
	public function addIndex($columns, $traits = null)
	{
		$index = new Kohana_Migration_Index($columns, $traits);
		$this->_indexes[$index->getName()] = $index;
	}

	/**
	 * Add a key to this table.
	 * @param array $columns - An array of columns to put the key on.
	 * @param array|null $traits - An optional array of traits for the key.
	 */
	public function addKey($columns, $traits = null)
	{
		$key = new Kohana_Migration_Key($columns, $traits);
		$this->_keys[$key->getName()] = $key;
	}

	/**
	 * Add a foreign key to this table.
	 * @see Kohana_Migration_Key_Foreign::$_traits
	 * @param array $near_columns - An array of columns in the near table to match to foreign columns.
	 * @param string $far_table - The name of the foreign table.
	 * @param $far_columns - An array with a 1:1 matching of column names on the foreign table.
	 * @param array|null $traits - An optional array of traits to apply to this table.
	 */
	public function addForeignKey($near_columns, $far_table, $far_columns, $traits = null)
	{
		$key = new Kohana_Migration_Key_Foreign($near_columns, $far_table, $far_columns, $traits);
		$this->_keys[$key->getName()] = $key;
	}

	public function __set($type, $value)
	{
		if (Kohana_Migration_Column::isType($type))
		{
			// $t->integer = array( 'name', 'option' => $value );
			if (is_array($value))
			{
				$name = array_shift($value);
				$this->addColumn($type, $name, $value);
			}
			// $t->integer = 'name';
			else
			{
				$this->addColumn($type, $value);
			}
		}
		else if (Kohana_Migration_Index::isType($type))
		{
			if (is_array($value))
			{
				// $t->index = array( array( "column_name", "another_column" ), array( "btree" ) );
				if (2 <= count($value))
				{
					$one = reset($value);
					$two = next($value);
					if (is_array($one) and is_array($two))
					{
						$this->addIndex($one, array_merge(array($type), $two));
					}
					// $t->index = array( "column_name", array( "btree" ) );
					else if (is_array($two))
					{
						$this->addIndex(array($one => null), array_merge(array($type), $two));
					}
					// $t->index = array( "column_name", "another_column", "and_another" );
					else
					{
						$this->addIndex($value, array($type));
					}
				}
			}
			// $t->index = "column_name"
			else
			{
				$this->addIndex(array($value => null), array($type));
			}
		}
		else if (Kohana_Migration_Key::isType($type))
		{
			if (is_array($value))
			{
				// $t->index = array( array( "column_name", "another_column" ), array( "btree" ) );
				if (2 <= count($value))
				{
					$one = reset($value);
					$two = next($value);
					if (is_array($one) and is_array($two))
					{
						$this->addKey($one, array_merge(array($type), $two));
					}
					// $t->index = array( "column_name", array( "btree" ) );
					else if (is_array($two))
					{
						$this->addKey(array($one => null), array_merge(array($type), $two));
					}
					// $t->index = array( "column_name", "another_column", "and_another" );
					else
					{
						$this->addKey($value, array($type));
					}
				}
			}
			// $t->index = "column_name"
			else
			{
				$this->addKey(array($value => null), array($type));
			}
		}
	}
}


text:
require 'spec_helper'

describe Gitlab::SidekiqMiddleware::Monitor do
  let(:monitor) { described_class.new }

  describe '#call' do
    let(:worker) { double }
    let(:job) { { 'jid' => 'job-id' } }
    let(:queue) { 'my-queue' }

    it 'calls Gitlab::SidekiqDaemon::Monitor' do
      expect(Gitlab::SidekiqDaemon::Monitor.instance).to receive(:within_job)
        .with(anything, 'job-id', 'my-queue')
        .and_call_original

      expect { |blk| monitor.call(worker, job, queue, &blk) }.to yield_control
    end

    it 'passthroughs the return value' do
      result = monitor.call(worker, job, queue) do
        'value'
      end

      expect(result).to eq('value')
    end

    context 'when cancel happens' do
      subject do
        monitor.call(worker, job, queue) do
          raise Gitlab::SidekiqDaemon::Monitor::CancelledError
        end
      end

      it 'skips the job' do
        expect { subject }.to raise_error(Sidekiq::JobRetry::Skip)
      end

      it 'puts job in DeadSet' do
        ::Sidekiq::DeadSet.new.clear

        expect do
          subject rescue Sidekiq::JobRetry::Skip
        end.to change { ::Sidekiq::DeadSet.new.size }.by(1)
      end
    end
  end
end


text:
"""
main.py -- Udacity conference server-side Python App Engine
    HTTP controller handlers for memcache & task queue access

$Id$

created by wesc on 2014 may 24

"""

__author__ = 'wesc+api@google.com (Wesley Chun)'

import webapp2
from google.appengine.api import app_identity
from google.appengine.api import mail
from google.appengine.api import memcache
from conference import ConferenceApi

class SetAnnouncementHandler(webapp2.RequestHandler):
    def get(self):
        """Set Announcement in Memcache."""
        # TODO 1
        # use _cacheAnnouncement() to set announcement in Memcache
        ConferenceApi._cacheAnnouncement()

class SendConfirmationEmailHandler(webapp2.RequestHandler):
    def post(self):
        """Send email confirming Conference creation."""
        mail.send_mail(
            'noreply@%s.appspotmail.com' % (
                app_identity.get_application_id()),     # from
            self.request.get('email'),                  # to
            'You created a new Conference!',            # subj
            'Hi, you have created the following '         # body
            'conference:\r\n\r\n%s' % self.request.get(
                'conferenceInfo')
        )

class setFeaturedSpeakerHandler(webapp2.RequestHandler):
    def post(self):
        """Set featured speaker in memcache"""
        websafeKey = self.request.get('websafeKey')
        speaker = self.request.get('speaker')

        sessions = ConferenceApi._getSessionsBySpeaker(websafeKey, speaker)
        if sessions.count() > 1:
            featuredSpeakerNotice = "%s is a featured speaker for %s sessions" \
                              % (speaker, sessions.count())
            memcache.set(websafeKey, featuredSpeakerNotice)

app = webapp2.WSGIApplication([
    ('/crons/set_announcement', SetAnnouncementHandler),
    ('/tasks/send_confirmation_email', SendConfirmationEmailHandler),
    ('/tasks/featured_speaker', setFeaturedSpeakerHandler),
], debug=True)


text:
using Newtonsoft.Json;

namespace WebApi.Models.Requests.Groups
{
    public class UpdateGroupRequest
    {
        [JsonProperty("newgroupname")]
        public string NewGroupName { get; set; }
        [JsonProperty("groupid")]
        public string GroupId { get; set; }
    }
}


text:
'use strict';

/* jshint ignore:start */
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */
/* jshint ignore:end */

var Q = require('q');  /* jshint ignore:line */
var _ = require('lodash');  /* jshint ignore:line */
var Page = require('../../../../base/Page');  /* jshint ignore:line */
var ReservationList = require('./task/reservation').ReservationList;
var deserialize = require(
    '../../../../base/deserialize');  /* jshint ignore:line */
var serialize = require('../../../../base/serialize');  /* jshint ignore:line */
var values = require('../../../../base/values');  /* jshint ignore:line */

var TaskList;
var TaskPage;
var TaskInstance;
var TaskContext;

/* jshint ignore:start */
/**
 * @description Initialize the TaskList
 *
 * @param {Twilio.Taskrouter.V1} version - Version of the resource
 * @param {string} workspaceSid - The ID of the Workspace that holds this Task
 */
/* jshint ignore:end */
TaskList = function TaskList(version, workspaceSid) {
  /* jshint ignore:start */
  /**
   * @param {string} sid - sid of instance
   *
   * @returns {Twilio.Taskrouter.V1.WorkspaceContext.TaskContext}
   */
  /* jshint ignore:end */
  function TaskListInstance(sid) {
    return TaskListInstance.get(sid);
  }

  TaskListInstance._version = version;
  // Path Solution
  TaskListInstance._solution = {workspaceSid: workspaceSid};
  TaskListInstance._uri = _.template(
    '/Workspaces/<%= workspaceSid %>/Tasks' // jshint ignore:line
  )(TaskListInstance._solution);
  /* jshint ignore:start */
  /**
   * Streams TaskInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param {object} [opts] - Options for request
   * @param {number} [opts.priority] -
   *          Retrieve the list of all Tasks in the workspace with the specified priority.
   * @param {string|list} [opts.assignmentStatus] -
   *          Returns the list of all Tasks in the workspace with the specified AssignmentStatus.
   * @param {string} [opts.workflowSid] -
   *          Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value.
   * @param {string} [opts.workflowName] -
   *          Returns the list of Tasks that are being controlled by the Workflow with the specified FriendlyName value.
   * @param {string} [opts.taskQueueSid] -
   *          Returns the list of Tasks that are currently waiting in the TaskQueue identified by the Sid specified.
   * @param {string} [opts.taskQueueName] -
   *          Returns the list of Tasks that are currently waiting in the TaskQueue identified by the FriendlyName specified.
   * @param {string} [opts.evaluateTaskAttributes] -
   *          Provide a task attributes expression, and this will return tasks which match the attributes.
   * @param {string} [opts.ordering] -
   *          Use this parameter to control the order of the Tasks returned.
   * @param {boolean} [opts.hasAddons] - The has_addons
   * @param {number} [opts.limit] -
   *         Upper limit for the number of records to return.
   *         each() guarantees never to return more than limit.
   *         Default is no limit
   * @param {number} [opts.pageSize] -
   *         Number of records to fetch per request,
   *         when not set will use the default value of 50 records.
   *         If no pageSize is defined but a limit is defined,
   *         each() will attempt to read the limit with the most efficient
   *         page size, i.e. min(limit, 1000)
   * @param {Function} [opts.callback] -
   *         Function to process each record. If this and a positional
   *         callback are passed, this one will be used
   * @param {Function} [opts.done] -
   *          Function to be called upon completion of streaming
   * @param {Function} [callback] - Function to process each record
   */
  /* jshint ignore:end */
  TaskListInstance.each = function each(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};
    if (opts.callback) {
      callback = opts.callback;
    }
    if (_.isUndefined(callback)) {
      throw new Error('Callback function must be provided');
    }

    var done = false;
    var currentPage = 1;
    var currentResource = 0;
    var limits = this._version.readLimits({
      limit: opts.limit,
      pageSize: opts.pageSize
    });

    function onComplete(error) {
      done = true;
      if (_.isFunction(opts.done)) {
        opts.done(error);
      }
    }

    function fetchNextPage(fn) {
      var promise = fn();
      if (_.isUndefined(promise)) {
        onComplete();
        return;
      }

      promise.then(function(page) {
        _.each(page.instances, function(instance) {
          if (done || (!_.isUndefined(opts.limit) && currentResource >= opts.limit)) {
            done = true;
            return false;
          }

          currentResource++;
          callback(instance, onComplete);
        });

        if ((limits.pageLimit && limits.pageLimit <= currentPage)) {
          onComplete();
        } else if (!done) {
          currentPage++;
          fetchNextPage(_.bind(page.nextPage, page));
        }
      });

      promise.catch(onComplete);
    }

    fetchNextPage(_.bind(this.page, this, _.merge(opts, limits)));
  };

  /* jshint ignore:start */
  /**
   * Lists TaskInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param {object} [opts] - Options for request
   * @param {number} [opts.priority] -
   *          Retrieve the list of all Tasks in the workspace with the specified priority.
   * @param {string|list} [opts.assignmentStatus] -
   *          Returns the list of all Tasks in the workspace with the specified AssignmentStatus.
   * @param {string} [opts.workflowSid] -
   *          Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value.
   * @param {string} [opts.workflowName] -
   *          Returns the list of Tasks that are being controlled by the Workflow with the specified FriendlyName value.
   * @param {string} [opts.taskQueueSid] -
   *          Returns the list of Tasks that are currently waiting in the TaskQueue identified by the Sid specified.
   * @param {string} [opts.taskQueueName] -
   *          Returns the list of Tasks that are currently waiting in the TaskQueue identified by the FriendlyName specified.
   * @param {string} [opts.evaluateTaskAttributes] -
   *          Provide a task attributes expression, and this will return tasks which match the attributes.
   * @param {string} [opts.ordering] -
   *          Use this parameter to control the order of the Tasks returned.
   * @param {boolean} [opts.hasAddons] - The has_addons
   * @param {number} [opts.limit] -
   *         Upper limit for the number of records to return.
   *         list() guarantees never to return more than limit.
   *         Default is no limit
   * @param {number} [opts.pageSize] -
   *         Number of records to fetch per request,
   *         when not set will use the default value of 50 records.
   *         If no page_size is defined but a limit is defined,
   *         list() will attempt to read the limit with the most
   *         efficient page size, i.e. min(limit, 1000)
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  TaskListInstance.list = function list(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};
    var deferred = Q.defer();
    var allResources = [];
    opts.callback = function(resource, done) {
      allResources.push(resource);

      if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) {
        done();
      }
    };

    opts.done = function(error) {
      if (_.isUndefined(error)) {
        deferred.resolve(allResources);
      } else {
        deferred.reject(error);
      }
    };

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    this.each(opts);
    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Retrieve a single page of TaskInstance records from the API.
   * Request is executed immediately
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param {object} [opts] - Options for request
   * @param {number} [opts.priority] -
   *          Retrieve the list of all Tasks in the workspace with the specified priority.
   * @param {string|list} [opts.assignmentStatus] -
   *          Returns the list of all Tasks in the workspace with the specified AssignmentStatus.
   * @param {string} [opts.workflowSid] -
   *          Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value.
   * @param {string} [opts.workflowName] -
   *          Returns the list of Tasks that are being controlled by the Workflow with the specified FriendlyName value.
   * @param {string} [opts.taskQueueSid] -
   *          Returns the list of Tasks that are currently waiting in the TaskQueue identified by the Sid specified.
   * @param {string} [opts.taskQueueName] -
   *          Returns the list of Tasks that are currently waiting in the TaskQueue identified by the FriendlyName specified.
   * @param {string} [opts.evaluateTaskAttributes] -
   *          Provide a task attributes expression, and this will return tasks which match the attributes.
   * @param {string} [opts.ordering] -
   *          Use this parameter to control the order of the Tasks returned.
   * @param {boolean} [opts.hasAddons] - The has_addons
   * @param {string} [opts.pageToken] - PageToken provided by the API
   * @param {number} [opts.pageNumber] -
   *          Page Number, this value is simply for client state
   * @param {number} [opts.pageSize] - Number of records to return, defaults to 50
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  TaskListInstance.page = function page(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};

    var deferred = Q.defer();
    var data = values.of({
      'Priority': _.get(opts, 'priority'),
      'AssignmentStatus': serialize.map(_.get(opts, 'assignmentStatus'), function(e) { return e; }),
      'WorkflowSid': _.get(opts, 'workflowSid'),
      'WorkflowName': _.get(opts, 'workflowName'),
      'TaskQueueSid': _.get(opts, 'taskQueueSid'),
      'TaskQueueName': _.get(opts, 'taskQueueName'),
      'EvaluateTaskAttributes': _.get(opts, 'evaluateTaskAttributes'),
      'Ordering': _.get(opts, 'ordering'),
      'HasAddons': serialize.bool(_.get(opts, 'hasAddons')),
      'PageToken': opts.pageToken,
      'Page': opts.pageNumber,
      'PageSize': opts.pageSize
    });

    var promise = this._version.page({uri: this._uri, method: 'GET', params: data});

    promise = promise.then(function(payload) {
      deferred.resolve(new TaskPage(this._version, payload, this._solution));
    }.bind(this));

    promise.catch(function(error) {
      deferred.reject(error);
    });

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Retrieve a single target page of TaskInstance records from the API.
   * Request is executed immediately
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param {string} [targetUrl] - API-generated URL for the requested results page
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  TaskListInstance.getPage = function getPage(targetUrl, callback) {
    var deferred = Q.defer();

    var promise = this._version._domain.twilio.request({method: 'GET', uri: targetUrl});

    promise = promise.then(function(payload) {
      deferred.resolve(new TaskPage(this._version, payload, this._solution));
    }.bind(this));

    promise.catch(function(error) {
      deferred.reject(error);
    });

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * create a TaskInstance
   *
   * @param {object} [opts] - Options for request
   * @param {number} [opts.timeout] -
   *          The amount of time in seconds the task is allowed to live up to a maximum of 2 weeks.
   * @param {number} [opts.priority] - Override priority for the Task.
   * @param {string} [opts.taskChannel] -
   *          When MultiTasking is enabled specify the type of the task by passing either TaskChannel Unique Name or Task Channel Sid.
   * @param {string} [opts.workflowSid] -
   *          The WorkflowSid for the Workflow that you would like to handle routing for this Task.
   * @param {string} [opts.attributes] -
   *          Url-encoded JSON string describing the attributes of this task.
   * @param {function} [callback] - Callback to handle processed record
   *
   * @returns {Promise} Resolves to processed TaskInstance
   */
  /* jshint ignore:end */
  TaskListInstance.create = function create(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};

    var deferred = Q.defer();
    var data = values.of({
      'Timeout': _.get(opts, 'timeout'),
      'Priority': _.get(opts, 'priority'),
      'TaskChannel': _.get(opts, 'taskChannel'),
      'WorkflowSid': _.get(opts, 'workflowSid'),
      'Attributes': _.get(opts, 'attributes')
    });

    var promise = this._version.create({uri: this._uri, method: 'POST', data: data});

    promise = promise.then(function(payload) {
      deferred.resolve(new TaskInstance(
        this._version,
        payload,
        this._solution.workspaceSid,
        this._solution.sid
      ));
    }.bind(this));

    promise.catch(function(error) {
      deferred.reject(error);
    });

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Constructs a task
   *
   * @param {string} sid - The sid
   *
   * @returns {Twilio.Taskrouter.V1.WorkspaceContext.TaskContext}
   */
  /* jshint ignore:end */
  TaskListInstance.get = function get(sid) {
    return new TaskContext(this._version, this._solution.workspaceSid, sid);
  };

  return TaskListInstance;
};

/* jshint ignore:start */
/**
 * Initialize the TaskPage
 *
 * @param {V1} version - Version of the resource
 * @param {Response<string>} response - Response from the API
 * @param {TaskSolution} solution - Path solution
 *
 * @returns TaskPage
 */
/* jshint ignore:end */
TaskPage = function TaskPage(version, response, solution) {
  // Path Solution
  this._solution = solution;

  Page.prototype.constructor.call(this, version, response, this._solution);
};

_.extend(TaskPage.prototype, Page.prototype);
TaskPage.prototype.constructor = TaskPage;

/* jshint ignore:start */
/**
 * Build an instance of TaskInstance
 *
 * @param {TaskPayload} payload - Payload response from the API
 *
 * @returns TaskInstance
 */
/* jshint ignore:end */
TaskPage.prototype.getInstance = function getInstance(payload) {
  return new TaskInstance(this._version, payload, this._solution.workspaceSid);
};

/* jshint ignore:start */
/**
 * Initialize the TaskContext
 *
 * @property {string} accountSid - The ID of the account that owns this Task
 * @property {number} age - The number of seconds since this task was created.
 * @property {task.status} assignmentStatus -
 *          Returns the list of all Tasks in the workspace with the specified AssignmentStatus.
 * @property {string} attributes -
 *          The user-defined JSON string describing the custom attributes of this work.
 * @property {string} addons -
 *          The addon data for all installed addons is returned with this attribute
 * @property {Date} dateCreated -
 *          Date this task was created, given as ISO 8601 format.
 * @property {Date} dateUpdated -
 *          Date this task was updated, given as ISO 8601 format.
 * @property {number} priority -
 *          Retrieve the list of all Tasks in the workspace with the specified priority.
 * @property {string} reason - The reason the task was canceled  or completed
 * @property {string} sid - The unique ID of the Task
 * @property {string} taskQueueSid -
 *          Returns the list of Tasks that are currently waiting in the TaskQueue identified by the Sid specified.
 * @property {string} taskQueueFriendlyName - The task_queue_friendly_name
 * @property {string} taskChannelSid - The ID of the Task Channel
 * @property {string} taskChannelUniqueName - The unique name of the Task Channel
 * @property {number} timeout -
 *          The amount of time in seconds the task is allowed to live
 * @property {string} workflowSid -
 *          Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value.
 * @property {string} workflowFriendlyName - The workflow_friendly_name
 * @property {string} workspaceSid - The ID of the Workspace that holds this Task
 * @property {string} url - The url
 * @property {string} links - The links
 *
 * @param {V1} version - Version of the resource
 * @param {TaskPayload} payload - The instance payload
 * @param {sid} workspaceSid - The ID of the Workspace that holds this Task
 * @param {sid} sid - The sid
 */
/* jshint ignore:end */
TaskInstance = function TaskInstance(version, payload, workspaceSid, sid) {
  this._version = version;

  // Marshaled Properties
  this.accountSid = payload.account_sid; // jshint ignore:line
  this.age = deserialize.integer(payload.age); // jshint ignore:line
  this.assignmentStatus = payload.assignment_status; // jshint ignore:line
  this.attributes = payload.attributes; // jshint ignore:line
  this.addons = payload.addons; // jshint ignore:line
  this.dateCreated = deserialize.iso8601DateTime(payload.date_created); // jshint ignore:line
  this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); // jshint ignore:line
  this.priority = deserialize.integer(payload.priority); // jshint ignore:line
  this.reason = payload.reason; // jshint ignore:line
  this.sid = payload.sid; // jshint ignore:line
  this.taskQueueSid = payload.task_queue_sid; // jshint ignore:line
  this.taskQueueFriendlyName = payload.task_queue_friendly_name; // jshint ignore:line
  this.taskChannelSid = payload.task_channel_sid; // jshint ignore:line
  this.taskChannelUniqueName = payload.task_channel_unique_name; // jshint ignore:line
  this.timeout = deserialize.integer(payload.timeout); // jshint ignore:line
  this.workflowSid = payload.workflow_sid; // jshint ignore:line
  this.workflowFriendlyName = payload.workflow_friendly_name; // jshint ignore:line
  this.workspaceSid = payload.workspace_sid; // jshint ignore:line
  this.url = payload.url; // jshint ignore:line
  this.links = payload.links; // jshint ignore:line

  // Context
  this._context = undefined;
  this._solution = {workspaceSid: workspaceSid, sid: sid || this.sid, };
};

Object.defineProperty(TaskInstance.prototype,
  '_proxy', {
  get: function() {
    if (!this._context) {
      this._context = new TaskContext(this._version, this._solution.workspaceSid, this._solution.sid);
    }

    return this._context;
  }
});

/* jshint ignore:start */
/**
 * fetch a TaskInstance
 *
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed TaskInstance
 */
/* jshint ignore:end */
TaskInstance.prototype.fetch = function fetch(callback) {
  return this._proxy.fetch(callback);
};

/* jshint ignore:start */
/**
 * update a TaskInstance
 *
 * @param {object} [opts] - Options for request
 * @param {string} [opts.attributes] -
 *          The user-defined JSON data describing the custom attributes of this task.
 * @param {task.status} [opts.assignmentStatus] -
 *          A 'pending' or 'reserved' Task may be canceled by posting AssignmentStatus='canceled'.
 * @param {string} [opts.reason] -
 *          This is only required if the Task is canceled or completed.
 * @param {number} [opts.priority] - Override priority for the Task.
 * @param {string} [opts.taskChannel] - The task_channel
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed TaskInstance
 */
/* jshint ignore:end */
TaskInstance.prototype.update = function update(opts, callback) {
  return this._proxy.update(opts, callback);
};

/* jshint ignore:start */
/**
 * remove a TaskInstance
 *
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed TaskInstance
 */
/* jshint ignore:end */
TaskInstance.prototype.remove = function remove(callback) {
  return this._proxy.remove(callback);
};

/* jshint ignore:start */
/**
 * Access the reservations
 *
 * @returns {Twilio.Taskrouter.V1.WorkspaceContext.TaskContext.ReservationList}
 */
/* jshint ignore:end */
TaskInstance.prototype.reservations = function reservations() {
  return this._proxy.reservations;
};

/* jshint ignore:start */
/**
 * Produce a plain JSON object version of the TaskInstance for serialization.
 * Removes any circular references in the object.
 *
 * @returns Object
 */
/* jshint ignore:end */
TaskInstance.prototype.toJSON = function toJSON() {
  let clone = {};
  _.forOwn(this, function(value, key) {
    if (!_.startsWith(key, '_') && ! _.isFunction(value)) {
      clone[key] = value;
    }
  });
  return clone;
};

/* jshint ignore:start */
/**
 * Initialize the TaskContext
 *
 * @property {Twilio.Taskrouter.V1.WorkspaceContext.TaskContext.ReservationList} reservations -
 *          reservations resource
 *
 * @param {V1} version - Version of the resource
 * @param {sid} workspaceSid - The workspace_sid
 * @param {sid} sid - The sid
 */
/* jshint ignore:end */
TaskContext = function TaskContext(version, workspaceSid, sid) {
  this._version = version;

  // Path Solution
  this._solution = {workspaceSid: workspaceSid, sid: sid, };
  this._uri = _.template(
    '/Workspaces/<%= workspaceSid %>/Tasks/<%= sid %>' // jshint ignore:line
  )(this._solution);

  // Dependents
  this._reservations = undefined;
};

/* jshint ignore:start */
/**
 * fetch a TaskInstance
 *
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed TaskInstance
 */
/* jshint ignore:end */
TaskContext.prototype.fetch = function fetch(callback) {
  var deferred = Q.defer();
  var promise = this._version.fetch({uri: this._uri, method: 'GET'});

  promise = promise.then(function(payload) {
    deferred.resolve(new TaskInstance(
      this._version,
      payload,
      this._solution.workspaceSid,
      this._solution.sid
    ));
  }.bind(this));

  promise.catch(function(error) {
    deferred.reject(error);
  });

  if (_.isFunction(callback)) {
    deferred.promise.nodeify(callback);
  }

  return deferred.promise;
};

/* jshint ignore:start */
/**
 * update a TaskInstance
 *
 * @param {object} [opts] - Options for request
 * @param {string} [opts.attributes] -
 *          The user-defined JSON data describing the custom attributes of this task.
 * @param {task.status} [opts.assignmentStatus] -
 *          A 'pending' or 'reserved' Task may be canceled by posting AssignmentStatus='canceled'.
 * @param {string} [opts.reason] -
 *          This is only required if the Task is canceled or completed.
 * @param {number} [opts.priority] - Override priority for the Task.
 * @param {string} [opts.taskChannel] - The task_channel
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed TaskInstance
 */
/* jshint ignore:end */
TaskContext.prototype.update = function update(opts, callback) {
  if (_.isFunction(opts)) {
    callback = opts;
    opts = {};
  }
  opts = opts || {};

  var deferred = Q.defer();
  var data = values.of({
    'Attributes': _.get(opts, 'attributes'),
    'AssignmentStatus': _.get(opts, 'assignmentStatus'),
    'Reason': _.get(opts, 'reason'),
    'Priority': _.get(opts, 'priority'),
    'TaskChannel': _.get(opts, 'taskChannel')
  });

  var promise = this._version.update({uri: this._uri, method: 'POST', data: data});

  promise = promise.then(function(payload) {
    deferred.resolve(new TaskInstance(
      this._version,
      payload,
      this._solution.workspaceSid,
      this._solution.sid
    ));
  }.bind(this));

  promise.catch(function(error) {
    deferred.reject(error);
  });

  if (_.isFunction(callback)) {
    deferred.promise.nodeify(callback);
  }

  return deferred.promise;
};

/* jshint ignore:start */
/**
 * remove a TaskInstance
 *
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed TaskInstance
 */
/* jshint ignore:end */
TaskContext.prototype.remove = function remove(callback) {
  var deferred = Q.defer();
  var promise = this._version.remove({uri: this._uri, method: 'DELETE'});

  promise = promise.then(function(payload) {
    deferred.resolve(payload);
  }.bind(this));

  promise.catch(function(error) {
    deferred.reject(error);
  });

  if (_.isFunction(callback)) {
    deferred.promise.nodeify(callback);
  }

  return deferred.promise;
};

Object.defineProperty(TaskContext.prototype,
  'reservations', {
  get: function() {
    if (!this._reservations) {
      this._reservations = new ReservationList(
        this._version,
        this._solution.workspaceSid,
        this._solution.sid
      );
    }
    return this._reservations;
  }
});

module.exports = {
  TaskList: TaskList,
  TaskPage: TaskPage,
  TaskInstance: TaskInstance,
  TaskContext: TaskContext
};


text: Name of an environment variable to be set to the username during the build.


text:
package org.sitenv.service.ccda.smartscorecard.repositories.inmemory;

import org.sitenv.service.ccda.smartscorecard.entities.inmemory.TemplateIdsR21;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Transactional(readOnly = true)
@Repository
public interface TemplateIdRepository21 extends JpaRepository<TemplateIdsR21, Integer>{

	@Transactional(readOnly = true)
	@Query("SELECT CASE WHEN COUNT(c) > 0 THEN true ELSE false END FROM TemplateIdsR21 c WHERE c.templateId = :templateId")
	boolean findByTemplateId(@Param("templateId")String templateId);

	@Transactional(readOnly = true)
	@Query("SELECT CASE WHEN COUNT(c) > 0 THEN true ELSE false END FROM TemplateIdsR21 c WHERE c.templateId = :templateId and c.extension = :extension")
	boolean findByTemplateIdAndExtension(@Param("templateId")String templateId, @Param("extension")String extension);
}


text:
import * as actions from "@nteract/actions";
import { Save, SaveFailed, SaveFulfilled, SetAppHostAction, SetGithubTokenAction } from "@nteract/actions";
import { AppRecord, AppRecordProps, makeAppRecord } from "@nteract/types";
import { RecordOf } from "immutable";

function setGithubToken(
  state: AppRecord,
  action: SetGithubTokenAction
): RecordOf<AppRecordProps> {
  return state.set("githubToken", action.payload.githubToken);
}

function save(state: AppRecord): RecordOf<AppRecordProps> {
  return state.set("isSaving", true);
}

function saveFailed(state: AppRecord): RecordOf<AppRecordProps> {
  return state.set("isSaving", false);
}

function saveFulfilled(state: AppRecord): RecordOf<AppRecordProps> {
  return state.set("isSaving", false).set("lastSaved", new Date());
}

function setAppHost(
  state: AppRecord,
  action: SetAppHostAction
): RecordOf<AppRecordProps> {
  return state.set("host", action.payload.host);
}

export default function handleApp(
  state: AppRecord = makeAppRecord(),
  action:
    | SetGithubTokenAction
    | Save
    | SaveFulfilled
    | SaveFailed
    | SetAppHostAction
): RecordOf<AppRecordProps> {
  switch (action.type) {
    case actions.SAVE:
      return save(state);
    case actions.SAVE_FAILED:
      return saveFailed(state);
    case actions.SAVE_FULFILLED:
      return saveFulfilled(state);
    case actions.SET_GITHUB_TOKEN:
      return setGithubToken(state, action);
    case actions.SET_APP_HOST:
      return setAppHost(state, action);
    default:
      return state;
  }
}