text:
This entity contains a harmonised description of a generic crop. This entity is primarily associated with the agricultural vertical and related IoT applications.

<AgriCrop><Generic Attributes>

| Attribute Name | Attribute Type | Description                                                                   | Mandatory /Optional | May be Null |
|----------------|----------------|-------------------------------------------------------------------------------|--------------------|-------------|
| id             | Text           | Unique id of this instance of this entity.                                    | M                  | N           |
| type           | Text           | Must be equal to "**AgriCrop**".                                              | M                  | N           |
| dateCreated    | DateTime       | Entity creation timestamp.                                                    | M                  | N           |
| dateModified   | DateTime       | Timestamp of the last modification of the entity.                             | M                  | Y           |
| source         | URL            | A sequence of characters giving the source of the entity data as a URL.       | M                  | Y           |
| dataProvider   | Text           | A sequence of characters identifying the originator of the harmonised entity. | M                  | Y           |

<AgriCrop><Entity Specific Attributes>

| Attribute Name     | Attribute Type     | Description                                                                                | Mandatory /Optional | May be Null |
|--------------------|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------|-------------|
| name               | Text               | The name of this crop.                                                                                | M                  | N           |
| alternateName      | Text               | An alternative name for this crop.                                                                                | O                  | Y           |
| description        | Text               | A description of this crop.                                                                                | O                  | Y           |
| refAgriSoil        | Array of Reference | An array containing a JSON encoded sequence of characters that reference the unique Ids of the recommended soil(s).                                                                                | O                  | Y           |
| refAgriFertilizer  | Array of Reference | An array containing a JSON encoded sequence of characters that reference the unique Ids of the recommended fertiliser product(s).                                                                  | O                  | Y           |
| refAgriPest        | Array of Reference | An array containing a JSON encoded sequence of characters that reference the unique Ids of the pest(s) known to attack this crop.                                                                  | O                  | Y           |
| plantingInterval   | Array of Text      | An array containing a JSON encoded sequence of characters of the recommended planting interval date(s) for this crop. Using The ISO8601 sequence of characters for each repeating date interval:

**interval**, **description**

Where **interval** is in the form of start date/end date
--MM-DD/--MM-DD

 Meaning repeat each year from this start date to this end date.                                                                      | O                  | Y           |
| harvestingInterval | Array of Text      | An array containing a JSON encoded sequence of characters of the recommended harvesting interval date(s) for this crop. Using The ISO8601 sequence of characters for each repeating date interval:

**interval** , **description**

                                          Where **interval** is in the form of                                           start date/end date
 --MM-DD/--MM-DD

Meaning repeat each year between the specified start date and the specified end date.                                                                                | O                  | Y           |
| wateringFrequency  | Text               | A description of the recommended watering schedule. A choice from an enumerated list. One of:

**daily, weekly, biweekly, monthly, onDemand, other**                                                                                | O                  | Y           |

#### AgriCrop JSON

The JSON code can be downloaded from:

<https://gist.github.com/GSMADeveloper/00685ca0edd54411cad5be84ee658da8>
```json
{
  "id": "df72dc57-1eb9-42a3-88a9-8647ecc954b4",
  "type": "AgriCrop",
  "dateCreated": {
    "value": "2016-08-22T19:20+00:00",
    "type": "DateTime"
  },
  "dateModified": {
    "value": "2016-08-22T19:20+00:00",
    "type": "DateTime"
  },
  "source": {
    "value": "http://www.samplefarmproduct.com",
    "type": "URL"
  },
  "dataProvider": {
    "value": "OperatorA",
    "type": "Text"
  },
  "name": {
    "value": "Wheat",
    "type": "Text"
  },
  "alternateName": {
    "value": "Triticum aestivum",
    "type": "Text"
  },
  "description": {
    "value": "Spring wheat",
    "type": "Text"
  },
  "refAgriSoil": [
    "00411b56-bd1b-4551-96e0-a6e7fde9c840",
    "e8a8389a-edf5-4345-8d2c-b98ac1ce8e2a"
  ],
  "refAgriFertilizer": [
    "1b0d6cf7-320c-4a2b-b2f1-4575ea850c73",
    "380973c8-4d3b-4723-a899-0c0c5cc63e7e"
  ],
  "refAgriPest": [
    "10b52f07-079a-4390-8237-bf6a1c049a85",
    "66bdb09b-4fe0-4932-a267-f9eda4474d2a"
  ],
  "plantingInterval": [
    "-09-28/-10-12, Best Season",
    "-10-11/-10-18, Season OK"
  ],
  "harvestingInterval": [
    "-03-21/-04-01, Best Season",
    "-04-02/-04-15, Season OK"
  ],
  "wateringFrequency": {
    "value": "weekly",
    "type": "Text"
  }
}
```


text:
package cn.cloudself.bean;

/**
 * @author HerbLuo
 * @version 1.0.0.d
 *          <p>
 *          change logs:
 *          2017/5/5 HerbLuo 首次创建
 */
@SuppressWarnings("unused")
public class EntitysWithVersion<T> {

    private String version;
    private Iterable<T> entity;

    public EntitysWithVersion() {
    }

    public EntitysWithVersion(String version, Iterable<T> entity) {
        this.version = version;
        this.entity = entity;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public Iterable<T> getEntity() {
        return entity;
    }

    public void setEntity(Iterable<T> entity) {
        this.entity = entity;
    }

    @Override
    public String toString() {
        return "EntitysWithVersion{" +
                "version='" + version + '\'' +
                ", entity=" + entity +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        EntitysWithVersion<?> that = (EntitysWithVersion<?>) o;

        if (version != null ? !version.equals(that.version) : that.version != null)
            return false;
        return entity != null ? entity.equals(that.entity) : that.entity == null;
    }

    @Override
    public int hashCode() {
        int result = version != null ? version.hashCode() : 0;
        result = 31 * result + (entity != null ? entity.hashCode() : 0);
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<object name="portal_javascripts" meta_type="JavaScripts Registry">

  <javascript
    id="++resource++plone.app.jquerytools.dateinput.js"
    enabled="True" />

  <javascript
    cacheable="True"
    compression="safe"
    cookable="True"
    enabled="True"
    expression=""
    id="++resource++bda.plone.ticketshop.js"
    inline="False" />

</object>


text:
#include <sound/driver.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/gus.h>
#include <sound/info.h>

struct gus_proc_private {
	int rom;		/* data are in ROM */
	unsigned int address;
	unsigned int size;
	struct snd_gus_card * gus;
};

static long snd_gf1_mem_proc_dump(struct snd_info_entry *entry, void *file_private_data,
			          struct file *file, char __user *buf,
			          unsigned long count, unsigned long pos)
{
	long size;
	struct gus_proc_private *priv = entry->private_data;
	struct snd_gus_card *gus = priv->gus;
	int err;

	size = count;
	if (pos + size > priv->size)
		size = (long)priv->size - pos;
	if (size > 0) {
		if ((err = snd_gus_dram_read(gus, buf, pos, size, priv->rom)) < 0)
			return err;
		return size;
	}
	return 0;
}

static long long snd_gf1_mem_proc_llseek(struct snd_info_entry *entry,
					void *private_file_data,
					struct file *file,
					long long offset,
					int orig)
{
	struct gus_proc_private *priv = entry->private_data;

	switch (orig) {
	case 0:	/* SEEK_SET */
		file->f_pos = offset;
		break;
	case 1:	/* SEEK_CUR */
		file->f_pos += offset;
		break;
	case 2: /* SEEK_END, offset is negative */
		file->f_pos = priv->size + offset;
		break;
	default:
		return -EINVAL;
	}
	if (file->f_pos > priv->size)
		file->f_pos = priv->size;
	return file->f_pos;
}

static void snd_gf1_mem_proc_free(struct snd_info_entry *entry)
{
	struct gus_proc_private *priv = entry->private_data;
	kfree(priv);
}

static struct snd_info_entry_ops snd_gf1_mem_proc_ops = {
	.read = snd_gf1_mem_proc_dump,
	.llseek = snd_gf1_mem_proc_llseek,
};

int snd_gf1_mem_proc_init(struct snd_gus_card * gus)
{
	int idx;
	char name[16];
	struct gus_proc_private *priv;
	struct snd_info_entry *entry;

	for (idx = 0; idx < 4; idx++) {
		if (gus->gf1.mem_alloc.banks_8[idx].size > 0) {
			priv = kzalloc(sizeof(*priv), GFP_KERNEL);
			if (priv == NULL)
				return -ENOMEM;
			priv->gus = gus;
			sprintf(name, "gus-ram-%i", idx);
			if (! snd_card_proc_new(gus->card, name, &entry)) {
				entry->content = SNDRV_INFO_CONTENT_DATA;
				entry->private_data = priv;
				entry->private_free = snd_gf1_mem_proc_free;
				entry->c.ops = &snd_gf1_mem_proc_ops;
				priv->address = gus->gf1.mem_alloc.banks_8[idx].address;
				priv->size = entry->size = gus->gf1.mem_alloc.banks_8[idx].size;
			}
		}
	}
	for (idx = 0; idx < 4; idx++) {
		if (gus->gf1.rom_present & (1 << idx)) {
			priv = kzalloc(sizeof(*priv), GFP_KERNEL);
			if (priv == NULL)
				return -ENOMEM;
			priv->rom = 1;
			priv->gus = gus;
			sprintf(name, "gus-rom-%i", idx);
			if (! snd_card_proc_new(gus->card, name, &entry)) {
				entry->content = SNDRV_INFO_CONTENT_DATA;
				entry->private_data = priv;
				entry->private_free = snd_gf1_mem_proc_free;
				entry->c.ops = &snd_gf1_mem_proc_ops;
				priv->address = idx * 4096 * 1024;
				priv->size = entry->size = gus->gf1.rom_memory;
			}
		}
	}
	return 0;
}


text:
<?php

/**
 * ProductAlert Price Customer collection
 *
 * @category    Mage
 * @package     Mage_ProductAlert
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_ProductAlert_Model_Mysql4_Price_Customer_Collection
    extends Mage_ProductAlert_Model_Resource_Price_Customer_Collection
{
}


text:
from common.challenge import MatasanoChallenge
from common.hash.sha1 import SHA1
from common.mac.hash import HashBasedMAC
from common.tools.misc import RandomByteGenerator

class Set4Challenge28(MatasanoChallenge):

    MESSAGE = 'foo bar baz'

    def _check_valid_mac(self, sha1mac):
        mac = sha1mac.value(self.MESSAGE)
        return sha1mac.validate(self.MESSAGE, mac)

    def _check_invalid_mac(self, sha1mac):
        mac = sha1mac.value(self.MESSAGE)
        return not sha1mac.validate(self.MESSAGE + ' qux', mac)

    def validate(self):
        key = RandomByteGenerator().value()
        sha1mac = HashBasedMAC(key, SHA1)
        valid_mac_ok = self._check_valid_mac(sha1mac)
        invalid_mac_ok = self._check_invalid_mac(sha1mac)
        return valid_mac_ok and invalid_mac_ok


text:
export EditorTranspiler from './EditorTranspiler'
export WebPlayer from './WebPlayer'
export GithubCorner from './GithubCorner'
export HamburgerButton from './HamburgerButton'
export Disqus from './Disqus'
export Author from './Author'
export PageHeader from './PageHeader'
export StarCount from './StarCount'
export GithubRepositoryLink from './GithubRepositoryLink'
export Link from './Link'
export SectionHeader from './SectionHeader'


text:
<!doctype html>

  <meta charset="UTF-8">
  <base href="/">

  <title>Job Hunter</title>

  <link rel="stylesheet" href="libs/bootstrap/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="libs/angular-xeditable/dist/css/xeditable.css">
  <link rel="stylesheet" href="css/style.css">

            Job Hunter

Home

                Jobs

Find Jobs:

Hired

We Work Remotely

Github

StackOverflow

AngelList

Indeed

Log Out

Sign Up

Log In

Fork on Github

Get in touch

                  Tweet


text:
{% extends "base.html" %}

{% block title %}CodeArena{% endblock %}

{% load staticfiles %}

{% block content %}

Welcome to CodeArena!

Collaborate.Code.Discuss

{% endblock %}


text:
package com.fasteque.leanback.widget.card;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.v17.leanback.widget.BaseCardView;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fasteque.leanback.R;

/**
 * A subclass of {@link BaseCardView} with an {@link ImageView} as its main region.
 */
public class IconCardView extends BaseCardView {

	private RelativeLayout layout;
	private LinearLayout textContainer;
	private ImageView icon;
	private TextView primaryText;
	private TextView secondaryText;

	/**
	 * Create an IconCardView.
	 *
	 * @param context
	 *          The Context the view is running in, through which it can access the current theme, resources, etc.
	 */
	public IconCardView(Context context) {
		this(context, null);
	}

	/**
	 * Create an IconCardView.
	 *
	 * @param context
	 *          The Context the view is running in, through which it can access the current theme, resources, etc.
	 * @param attrs
	 *          The attributes of the XML tag that is inflating the view.
	 */
	public IconCardView(Context context, AttributeSet attrs) {
		this(context, attrs, R.attr.imageCardViewStyle);
	}

	/**
	 * Create an IconCardView.
	 *
	 * @param context
	 *          The Context the view is running in, through which it can access the current theme, resources, etc.
	 * @param styleResId
	 *          The resourceId of the theme you want to apply.
	 */
	public IconCardView(Context context, int styleResId) {
		super(new ContextThemeWrapper(context, styleResId), null, 0);
		initIconCardView(styleResId);
	}

	/**
	 * Create an IconCardView.
	 *
	 * @param context
	 *          The Context the view is running in, through which it can access the current theme, resources, etc.
	 * @param attrs
	 *          The attributes of the XML tag that is inflating the view.
	 * @param defStyleAttr
	 *          An attribute in the current theme that contains a reference to a style resource that supplies default
	 *          values for the view. Can be 0 to not look for defaults.
	 */
	public IconCardView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(getStyledContext(context, attrs, defStyleAttr), attrs, defStyleAttr);
		initIconCardView(getIconCardViewStyle(context, attrs, defStyleAttr));
	}

	@Override
	public boolean hasOverlappingRendering() {
		return false;
	}

	private void initIconCardView(int styleResId) {
		setFocusable(true);
		setFocusableInTouchMode(true);
		setCardType(CARD_TYPE_MAIN_ONLY);

		Context context = getContext();

		LayoutInflater inflater = LayoutInflater.from(context);
		inflater.inflate(R.layout.card_view_icon, this);
		TypedArray cardAttrs = context.obtainStyledAttributes(styleResId, R.styleable.IconCardView);

		int backgroundColor = cardAttrs.getInt(R.styleable.IconCardView_icon_background_color,
						ContextCompat.getColor(context, R.color.default_background));
		int textBackgroundColor = cardAttrs.getInt(R.styleable.IconCardView_icon_text_background_color,
						ContextCompat.getColor(context, R.color.default_accent));
		int primaryTextColor = cardAttrs.getInt(R.styleable.IconCardView_icon_primary_text_color,
						ContextCompat.getColor(context, R.color.white));
		int secondaryTextColor = cardAttrs.getInt(R.styleable.IconCardView_icon_secondary_text_color,
						ContextCompat.getColor(context, R.color.white));

		int drawableResource = cardAttrs.getInt(R.styleable.IconCardView_icon_image, -1);

		layout = (RelativeLayout) findViewById(R.id.card_view_icon_container);
		textContainer = (LinearLayout) findViewById(R.id.card_view_icon_text_container);
		icon = (ImageView) findViewById(R.id.card_view_icon_image);
		primaryText = (TextView) findViewById(R.id.card_view_icon_primary_text);
		secondaryText = (TextView) findViewById(R.id.card_view_icon_secondary_text);

		setCardBackgroundColor(backgroundColor);
		setDetailBackgroundColor(textBackgroundColor);
		setPrimaryTextColor(primaryTextColor);
		setSecondaryTextColor(secondaryTextColor);
		if (drawableResource != -1) {
			setIcon(drawableResource);
		}

		cardAttrs.recycle();
	}

	/**
	 *
	 * @param width
	 * @param height
	 */
	public void setLayoutDimensions(int width, int height) {
		ViewGroup.LayoutParams lp = layout.getLayoutParams();
		lp.width = width;
		lp.height = height;
		layout.setLayoutParams(lp);
	}

	/**
	 *
	 * @param drawable
	 */
	public void setIcon(Drawable drawable) {
		icon.setImageDrawable(drawable);
	}

	/**
	 *
	 * @param drawable
	 */
	public void setIcon(@DrawableRes int drawable) {
		icon.setImageResource(drawable);
	}

	/**
	 *
	 * @param width
	 * @param height
	 */
	public void setIconDimensions(int width, int height) {
		ViewGroup.LayoutParams lp = icon.getLayoutParams();
		lp.width = width;
		lp.height = height;
		icon.setLayoutParams(lp);
	}

	/**
	 *
	 * @param titleText
	 */
	public void setPrimaryText(CharSequence titleText) {
		primaryText.setText(titleText);
	}

	/**
	 *
	 * @param detailText
	 */
	public void setSecondaryText(CharSequence detailText) {
		secondaryText.setText(detailText);
	}

	/**
	 *
	 * @param color
	 */
	public void setPrimaryTextColor(@ColorInt int color) {
		primaryText.setTextColor(color);
	}

	/**
	 *
	 * @param color
	 */
	public void setSecondaryTextColor(@ColorInt int color) {
		secondaryText.setTextColor(color);
	}

	/**
	 *
	 * @param color
	 */
	public void setCardBackgroundColor(@ColorInt int color) {
		setBackgroundColor(color);
	}

	/**
	 *
	 * @param color
	 */
	public void setDetailBackgroundColor(@ColorInt int color) {
		textContainer.setBackgroundColor(color);
	}

	/**
	 *
	 * @return
	 */
	public RelativeLayout getLayout() {
		return layout;
	}

	/**
	 *
	 * @return
	 */
	public LinearLayout getTextContainer() {
		return textContainer;
	}

	/**
	 *
	 * @return
	 */
	public ImageView getIcon() {
		return icon;
	}

	/**
	 *
	 * @return
	 */
	public TextView getPrimaryText() {
		return primaryText;
	}

	/**
	 *
	 * @return
	 */
	public TextView getSecondaryText() {
		return secondaryText;
	}

	private static Context getStyledContext(Context context, AttributeSet attrs, int defStyleAttr) {
		int style = getIconCardViewStyle(context, attrs, defStyleAttr);
		return new ContextThemeWrapper(context, style);
	}

	private static int getIconCardViewStyle(Context context, AttributeSet attrs, int defStyleAttr) {
		int style = attrs == null ? 0 : attrs.getStyleAttribute();

		if (style == 0) {
			TypedArray styledAttrs = context.obtainStyledAttributes(R.styleable.IconCardView);
			style = styledAttrs.getResourceId(R.styleable.IconCardView_icon_theme, 0);
			styledAttrs.recycle();
		}

		return style;
	}
}


text:
module com.azure.resourcemanager.hardwaresecuritymodules {
    requires transitive com.azure.core.management;

    exports com.azure.resourcemanager.hardwaresecuritymodules;
    exports com.azure.resourcemanager.hardwaresecuritymodules.fluent;
    exports com.azure.resourcemanager.hardwaresecuritymodules.fluent.models;
    exports com.azure.resourcemanager.hardwaresecuritymodules.models;

    opens com.azure.resourcemanager.hardwaresecuritymodules.fluent.models to
        com.azure.core,
        com.fasterxml.jackson.databind;
    opens com.azure.resourcemanager.hardwaresecuritymodules.models to
        com.azure.core,
        com.fasterxml.jackson.databind;
}


text:
using System.Windows.Controls;

namespace HexHelper.View
{
    /// <summary>
    /// Interaction logic for MessageListControl.xaml
    /// </summary>
    public partial class MessageListControl : UserControl
    {
        public MessageListControl()
        {
            InitializeComponent();
        }
    }
}


text:
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

import * as actions from '../../redux/actions';

import _ from 'lodash';

import Patient from '../patient/';
import { clinicPatientFromAccountInfo } from '../../core/personutils';

/**
 * Expose "Smart" Component that is connect-ed to Redux
 */
export function getFetchers(dispatchProps, ownProps, stateProps, api) {
  const fetchers = [
    dispatchProps.fetchPatient.bind(null, api, ownProps.match.params.id),
  ];

  if (!stateProps.fetchingPendingSentInvites.inProgress && !stateProps.fetchingPendingSentInvites.completed) {
    fetchers.push(dispatchProps.fetchPendingSentInvites.bind(null, api));
  }

  if (!stateProps.fetchingAssociatedAccounts.inProgress && !stateProps.fetchingAssociatedAccounts.completed) {
    // Need fetchAssociatedAccounts here because the result includes of data donation accounts sharing info
    // and permissions for the patients in a care team
    fetchers.push(dispatchProps.fetchAssociatedAccounts.bind(null, api));
  }

  if (stateProps.selectedClinicId && !_.get(stateProps, [
    'clinics',
    stateProps.selectedClinicId,
    'patients',
    ownProps.match.params.id,
    'permissions',
  ])) {
    // Need to fetch the patient for the clinic in order to have the permissions provided. Normally
    // these would be here after navigating from the patients list, but they will not upon reload.
    // We need to search for the patient via the current patient id.
    fetchers.push(dispatchProps.fetchPatientFromClinic.bind(null, api, stateProps.selectedClinicId, ownProps.match.params.id));
  }

  return fetchers;
};

export function mapStateToProps(state) {
  let user = null;
  let patient = null;
  let clinicPatient;
  let permissions = {};
  let permsOfLoggedInUser = {};

  const {
    allUsersMap,
    clinics,
    currentPatientInViewId,
    loggedInUserId,
    membershipPermissionsInOtherCareTeams,
    permissionsOfMembersInTargetCareTeam,
    selectedClinicId,
    working,
  } = state.blip;

  const {
    fetchingUser,
    fetchingPatient,
    fetchingPendingSentInvites,
    fetchingAssociatedAccounts,
    updatingDataDonationAccounts,
    updatingPatientBgUnits,
    updatingPatient,
    updatingClinicPatient,
  } = working;

  if (allUsersMap){
    if (loggedInUserId) {
      user = allUsersMap[loggedInUserId];
    }

    if (currentPatientInViewId) {

      patient = allUsersMap[currentPatientInViewId];
      if (selectedClinicId) clinicPatient = _.get(clinics, [selectedClinicId, 'patients', currentPatientInViewId]);

      permissions = _.get(
        permissionsOfMembersInTargetCareTeam,
        currentPatientInViewId,
        {}
      );
      // if the logged-in user is viewing own data, we pass through their own permissions as permsOfLoggedInUser
      if (currentPatientInViewId === loggedInUserId) {
        permsOfLoggedInUser = permissions;
      }
      // otherwise, we need to pull the perms of the loggedInUser wrt the patient in view from membershipPermissionsInOtherCareTeams
      else {
        permsOfLoggedInUser = clinicPatient?.permissions || _.get(
          membershipPermissionsInOtherCareTeams,
          currentPatientInViewId,
          {}
        );
      }
    }
  }

  return {
    user: user,
    fetchingUser: fetchingUser.inProgress,
    patient: { permissions, ...patient },
    clinicPatient,
    permsOfLoggedInUser: permsOfLoggedInUser,
    fetchingPatient: fetchingPatient.inProgress,
    fetchingPendingSentInvites: fetchingPendingSentInvites,
    fetchingAssociatedAccounts: fetchingAssociatedAccounts,
    dataDonationAccounts: state.blip.dataDonationAccounts,
    dataDonationAccountsFetched: fetchingPendingSentInvites.completed && fetchingAssociatedAccounts.completed,
    updatingDataDonationAccounts: updatingDataDonationAccounts.inProgress,
    updatingPatientBgUnits: updatingPatientBgUnits.inProgress,
    updatingPatient: updatingPatient.inProgress || updatingClinicPatient.inProgress,
    dataSources: state.blip.dataSources || [],
    authorizedDataSource: state.blip.authorizedDataSource,
    selectedClinicId,
  };
}

let mapDispatchToProps = dispatch => bindActionCreators({
  acknowledgeNotification: actions.sync.acknowledgeNotification,
  fetchAssociatedAccounts: actions.async.fetchAssociatedAccounts,
  fetchPatient: actions.async.fetchPatient,
  fetchPendingSentInvites: actions.async.fetchPendingSentInvites,
  fetchDataSources: actions.async.fetchDataSources,
  updateDataDonationAccounts: actions.async.updateDataDonationAccounts,
  updatePatient: actions.async.updatePatient,
  updatePatientSettings: actions.async.updateSettings,
  connectDataSource: actions.async.connectDataSource,
  disconnectDataSource: actions.async.disconnectDataSource,
  fetchPatientFromClinic: actions.async.fetchPatientFromClinic,
  updateClinicPatient: actions.async.updateClinicPatient,
}, dispatch);

let mergeProps = (stateProps, dispatchProps, ownProps) => {
  var api = ownProps.api;

  const patientUpdateAction = patient => {
    dispatchProps.updatePatient(api, patient);
    if (stateProps.selectedClinicId) {
      dispatchProps.updateClinicPatient(api, stateProps.selectedClinicId, patient.userid, clinicPatientFromAccountInfo(patient));
    }
  }

  return Object.assign({}, stateProps, _.pick(dispatchProps, 'acknowledgeNotification'), {
    fetchers: getFetchers(dispatchProps, ownProps, stateProps, api),
    onUpdateDataDonationAccounts: dispatchProps.updateDataDonationAccounts.bind(null, api),
    onUpdatePatient: patientUpdateAction,
    onUpdatePatientSettings: dispatchProps.updatePatientSettings.bind(null, api),
    fetchDataSources: dispatchProps.fetchDataSources.bind(null, api),
    connectDataSource: dispatchProps.connectDataSource.bind(null, api),
    disconnectDataSource: dispatchProps.disconnectDataSource.bind(null, api),
    trackMetric: ownProps.trackMetric,
    queryParams: ownProps.location.query,
    api: api
  });
};

export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(Patient);


text:
package hookbot

import (
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

type WebsocketHandlerFunc func(*websocket.Conn, *http.Request)

func (wrapped WebsocketHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Printf("Failed to upgrade: %v", err)
		// Don't send any response here, Upgrade already does that on error.
		return
	}

	wrapped(conn, r)
}


text:
class RestEvent < Event

  def initialize
    super
    @command = "rest"
  end

  def run(entity)
    entity.hp = entity.max_hp
    print "#{entity.name}'s HP is fully restored!\n\n"
  end

end


text:
package org.gradle.api.internal.file.archive;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.gradle.api.GradleException;
import org.gradle.api.InvalidUserDataException;
import org.gradle.api.UncheckedIOException;
import org.gradle.api.file.FileVisitDetails;
import org.gradle.api.file.FileVisitor;
import org.gradle.api.file.RelativePath;
import org.gradle.api.internal.file.AbstractFileTreeElement;
import org.gradle.api.internal.file.FileSystemSubset;
import org.gradle.api.internal.file.collections.DirectoryFileTree;
import org.gradle.api.internal.file.collections.DirectoryFileTreeFactory;
import org.gradle.api.internal.file.collections.FileSystemMirroringFileTree;
import org.gradle.api.internal.file.collections.MinimalFileTree;
import org.gradle.api.internal.file.collections.SingletonFileTree;
import org.gradle.internal.hash.FileHasher;
import org.gradle.internal.nativeintegration.filesystem.Chmod;
import org.gradle.internal.nativeintegration.filesystem.FileSystem;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicBoolean;

public class ZipFileTree implements MinimalFileTree, FileSystemMirroringFileTree {
    private final File zipFile;
    private final File tmpDir;
    private final Chmod chmod;
    private final DirectoryFileTreeFactory directoryFileTreeFactory;
    private final FileHasher fileHasher;

    public ZipFileTree(File zipFile, File tmpDir, Chmod chmod, DirectoryFileTreeFactory directoryFileTreeFactory, FileHasher fileHasher) {
        this.zipFile = zipFile;
        this.tmpDir = tmpDir;
        this.chmod = chmod;
        this.directoryFileTreeFactory = directoryFileTreeFactory;
        this.fileHasher = fileHasher;
    }

    public String getDisplayName() {
        return String.format("ZIP '%s'", zipFile);
    }

    public DirectoryFileTree getMirror() {
        return directoryFileTreeFactory.create(getExpandedDir());
    }

    public void visit(FileVisitor visitor) {
        if (!zipFile.exists()) {
            throw new InvalidUserDataException(String.format("Cannot expand %s as it does not exist.", getDisplayName()));
        }
        if (!zipFile.isFile()) {
            throw new InvalidUserDataException(String.format("Cannot expand %s as it is not a file.", getDisplayName()));
        }

        AtomicBoolean stopFlag = new AtomicBoolean();

        try {
            ZipFile zip = new ZipFile(zipFile);
            File expandedDir = getExpandedDir();
            try {
                // The iteration order of zip.getEntries() is based on the hash of the zip entry. This isn't much use
                // to us. So, collect the entries in a map and iterate over them in alphabetical order.
                Map<String, ZipEntry> entriesByName = new TreeMap<String, ZipEntry>();
                Enumeration entries = zip.getEntries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = (ZipEntry) entries.nextElement();
                    entriesByName.put(entry.getName(), entry);
                }
                Iterator<ZipEntry> sortedEntries = entriesByName.values().iterator();
                while (!stopFlag.get() && sortedEntries.hasNext()) {
                    ZipEntry entry = sortedEntries.next();
                    if (entry.isDirectory()) {
                        visitor.visitDir(new DetailsImpl(zipFile, expandedDir, entry, zip, stopFlag, chmod));
                    } else {
                        visitor.visitFile(new DetailsImpl(zipFile, expandedDir, entry, zip, stopFlag, chmod));
                    }
                }
            } finally {
                zip.close();
            }
        } catch (Exception e) {
            throw new GradleException(String.format("Could not expand %s.", getDisplayName()), e);
        }
    }

    private File getBackingFile() {
        return zipFile;
    }

    private File getExpandedDir() {
        String expandedDirName = zipFile.getName() + "_" + fileHasher.hash(zipFile);
        return new File(tmpDir, expandedDirName);
    }

    private static class DetailsImpl extends AbstractFileTreeElement implements FileVisitDetails {
        private final File originalFile;
        private final File expandedDir;
        private final ZipEntry entry;
        private final ZipFile zip;
        private final AtomicBoolean stopFlag;
        private File file;

        public DetailsImpl(File originalFile, File expandedDir, ZipEntry entry, ZipFile zip, AtomicBoolean stopFlag, Chmod chmod) {
            super(chmod);
            this.originalFile = originalFile;
            this.expandedDir = expandedDir;
            this.entry = entry;
            this.zip = zip;
            this.stopFlag = stopFlag;
        }

        public String getDisplayName() {
            return String.format("zip entry %s!%s", originalFile, entry.getName());
        }

        public void stopVisiting() {
            stopFlag.set(true);
        }

        public File getFile() {
            if (file == null) {
                file = new File(expandedDir, entry.getName());
                if (!file.exists()) {
                    copyTo(file);
                }
            }
            return file;
        }

        public long getLastModified() {
            return entry.getTime();
        }

        public boolean isDirectory() {
            return entry.isDirectory();
        }

        public long getSize() {
            return entry.getSize();
        }

        public InputStream open() {
            try {
                return zip.getInputStream(entry);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public RelativePath getRelativePath() {
            return new RelativePath(!entry.isDirectory(), entry.getName().split("/"));
        }

        public int getMode() {
            int unixMode = entry.getUnixMode() & 0777;
            if (unixMode == 0) {
                //no mode infos available - fall back to defaults
                if (isDirectory()) {
                    unixMode = FileSystem.DEFAULT_DIR_MODE;
                } else {
                    unixMode = FileSystem.DEFAULT_FILE_MODE;
                }
            }
            return unixMode;
        }
    }

    @Override
    public void registerWatchPoints(FileSystemSubset.Builder builder) {
        builder.add(zipFile);
    }

    @Override
    public void visitTreeOrBackingFile(FileVisitor visitor) {
        File backingFile = getBackingFile();
        if (backingFile!=null) {
            new SingletonFileTree(backingFile).visit(visitor);
        } else {
            visit(visitor);
        }
    }
}


text:
rm -Rf app/cache/prod/*
rm -Rf app/logs/*
php app/console asset:install --env=prod
php app/console assetic:dump
chown -R jarnal:www-data .
chmod -R 755 .
chmod -R 775 app/cache/
chmod -R 775 app/logs/
rm -Rf app/cache/prod/*
rm -Rf app/logs/*


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2017 Couchbase, Inc
 *
 *   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.
 */

/*
 * Benchmarks relating to the VBucket class.
 */

#include "benchmark_memory_tracker.h"
#include "checkpoint_manager.h"
#include "engine_fixture.h"
#include "ep_bucket.h"
#include "fakes/fake_executorpool.h"
#include "item.h"
#include "kv_bucket.h"
#include "stored_value_factories.h"

#include "../tests/module_tests/thread_gate.h"

#include <mock/mock_synchronous_ep_engine.h>
#include <programs/engine_testapp/mock_server.h>

#include <folly/portability/GTest.h>

#include <algorithm>
#include <thread>

enum class Store { Couchstore = 0, RocksDB = 1, Magma = 2 };

static std::string to_string(Store store) {
    switch (store) {
    case Store::Couchstore:
        return "couchdb";
    case Store::RocksDB:
        return "rocksdb";
    case Store::Magma:
        return "magma";
    }
    throw std::invalid_argument("to_string(Store): invalid enumeration " +
                                std::to_string(int(store)));
}

enum class FlushMode { Insert = 0, Replace = 1 };

static std::string to_string(FlushMode mode) {
    switch (mode) {
    case FlushMode::Insert:
        return "insert";
    case FlushMode::Replace:
        return "replace";
    }
    throw std::invalid_argument("to_string(FlushMode): invalid enumeration " +
                                std::to_string(int(mode)));
}

class VBucketBench : public EngineFixture {
protected:
    void SetUp(const benchmark::State& state) override {
        store = Store(state.range(0));
        varConfig = "backend=" + to_string(store) +
                    // A number of benchmarks require more than the default
                    // 100MB bucket quota - bump to ~1GB.
                    ";max_size=1000000000";
        EngineFixture::SetUp(state);
        if (state.thread_index == 0) {
            engine->getKVBucket()->setVBucketState(Vbid(0),
                                                   vbucket_state_active);
        }
    }

    void TearDown(const benchmark::State& state) override {
        if (state.thread_index == 0) {
            ASSERT_EQ(ENGINE_SUCCESS,
                      engine->getKVBucket()->deleteVBucket(vbid, nullptr));
            executorPool->runNextTask(
                    AUXIO_TASK_IDX,
                    "Removing (dead) vb:0 from memory and disk");
        }
        EngineFixture::TearDown(state);
    }

    /// Flush all items in the vBucket to disk.
    size_t flushAllItems(Vbid vbid) {
        size_t itemsFlushed = 0;
        auto& ep = dynamic_cast<EPBucket&>(*engine->getKVBucket());
        EPBucket::MoreAvailable moreAvailable;
        do {
            const auto res = ep.flushVBucket(vbid);
            moreAvailable = res.moreAvailable;
            itemsFlushed += res.numFlushed;
        } while (moreAvailable == EPBucket::MoreAvailable::Yes);
        return itemsFlushed;
    }

    Store store;
};

/**
 * Benchmark fixture for VBucket tests which includes a memoryTracker to
 * allow monitoring of current/peak memory usage.
 */
class MemTrackingVBucketBench : public VBucketBench {
protected:
    void SetUp(const benchmark::State& state) override {
        if (state.thread_index == 0) {
            memoryTracker = BenchmarkMemoryTracker::getInstance();
            memoryTracker->reset();
        }
        VBucketBench::SetUp(state);
    }

    void TearDown(const benchmark::State& state) override {
        if (state.thread_index == 0) {
            memoryTracker->destroyInstance();
        }
        VBucketBench::TearDown(state);
    }

    BenchmarkMemoryTracker* memoryTracker = nullptr;
};

/*
 * Fixture for CheckpointManager benchmarks
 */
class CheckpointBench : public EngineFixture {
protected:
    void SetUp(const benchmark::State& state) override {
        // Allow many checkpoints
        varConfig =
                "max_size=1000000000;max_checkpoints=100000000;chk_max_items=1";

        EngineFixture::SetUp(state);
        if (state.thread_index == 0) {
            engine->getKVBucket()->setVBucketState(Vbid(0),
                                                   vbucket_state_active);
        }
    }

    void TearDown(const benchmark::State& state) override {
        if (state.thread_index == 0) {
            engine->getKVBucket()->deleteVBucket(vbid, this);
        }
        EngineFixture::TearDown(state);
    }
};

/**
 * Benchmark queueing items into a vBucket.
 * Items have a 10% chance of being a duplicate key of a previous item (to
 * model de-dupe).
 */
BENCHMARK_DEFINE_F(MemTrackingVBucketBench, QueueDirty)
(benchmark::State& state) {
    const auto itemCount = state.range(1);

    std::default_random_engine gen;
    auto makeKeyWithDuplicates = [&gen](int i) {
        // 10% of the time; return a key which is the same as a previous one.
        std::uniform_real_distribution<> dis(0, 1.0);
        if (dis(gen) < 0.1) {
            return std::string("key") + std::to_string((i + 1) / 2);
        } else {
            return std::string("key") + std::to_string(i);
        }
    };

    int itemsQueuedTotal = 0;

    // Pre-size the VBucket's hashtable to a sensible size.
    auto* vb = engine->getKVBucket()->getVBucket(vbid).get();
    vb->ht.resize(itemCount);

    // Memory size before queuing.
    const size_t baseBytes = memoryTracker->getCurrentAlloc();

    // Maximum memory during queueing.
    size_t peakBytes = 0;

    const std::string value(1, 'x');
    while (state.KeepRunning()) {
        // Benchmark: Add the given number of items to checkpoint manager.
        // Note we don't include the time taken to make the item.
        for (int i = 0; i < itemCount; ++i) {
            state.PauseTiming();
            const auto key = makeKeyWithDuplicates(i);
            auto item = make_item(vbid, key, value);
            state.ResumeTiming();
            ASSERT_EQ(ENGINE_SUCCESS, engine->getKVBucket()->set(item, cookie));
            ++itemsQueuedTotal;
        }

        state.PauseTiming();
        peakBytes = std::max(peakBytes, memoryTracker->getMaxAlloc());
        /// Cleanup VBucket
        vb->ht.clear();
        vb->checkpointManager->clear(*vb, 0);
        state.ResumeTiming();
    }

    state.SetItemsProcessed(itemsQueuedTotal);
    // Peak memory usage while queuing, minus baseline.
    state.counters["PeakQueueBytes"] = peakBytes - baseBytes;
    state.counters["PeakBytesPerItem"] = (peakBytes - baseBytes) / itemCount;
}

BENCHMARK_DEFINE_F(MemTrackingVBucketBench, FlushVBucket)
(benchmark::State& state) {
    const auto itemCount = state.range(1);
    int itemsFlushedTotal = 0;
    auto mode = FlushMode(state.range(2));

    // Memory size before flushing.
    size_t baseBytes = 0;

    // Maximum memory during flushing.
    size_t peakBytes = 0;

    // Pre-size the VBucket's hashtable to a sensible size or things are going
    // to get slow for large numbers of items.
    engine->getKVBucket()->getVBucket(vbid)->ht.resize(itemCount);

    std::string value(1, 'x');
    if (mode == FlushMode::Replace) {
        for (int i = 0; i < itemCount; ++i) {
            auto item = make_item(
                    vbid, std::string("key") + std::to_string(i), value);
            ASSERT_EQ(ENGINE_SUCCESS, engine->getKVBucket()->set(item, cookie));
        }

        // Make sure we have something in the vBucket the first time round
        size_t itemsFlushed = flushAllItems(vbid);
        ASSERT_EQ(itemCount, itemsFlushed);
    }

    while (state.KeepRunning()) {
        // Add the given number of items to checkpoint manager.
        state.PauseTiming();
        if (mode == FlushMode::Insert) {
            // Delete the vBucket so that we can measure the Insert path
            auto result = engine->getKVBucket()->deleteVBucket(vbid, cookie);
            if (result != ENGINE_SUCCESS) {
                // Deferred deletion is running, wait until complete
                EXPECT_EQ(ENGINE_EWOULDBLOCK, result);
                executorPool->runNextTask(
                        AUXIO_TASK_IDX,
                        "Removing (dead) vb:0 from memory and disk");
            }
            engine->getKVBucket()->setVBucketState(vbid, vbucket_state_active);

            {
                auto vb = engine->getVBucket(vbid);
                EXPECT_EQ(0, vb->getNumItems());
            }

            // Pre-size the VBucket's hashtable to a sensible size or things are
            // going to get slow for large numbers of items.
            engine->getKVBucket()->getVBucket(vbid)->ht.resize(itemCount);
        }

        for (int i = 0; i < itemCount; ++i) {
            auto item = make_item(
                    vbid, std::string("key") + std::to_string(i), value);
            ASSERT_EQ(ENGINE_SUCCESS, engine->getKVBucket()->set(item, cookie));
        }

        baseBytes = memoryTracker->getCurrentAlloc();
        state.ResumeTiming();

        // Benchmark.
        size_t itemsFlushed = flushAllItems(vbid);

        ASSERT_EQ(itemCount, itemsFlushed);
        peakBytes = std::max(peakBytes, memoryTracker->getMaxAlloc());
        itemsFlushedTotal += itemsFlushed;
    }
    state.SetItemsProcessed(itemsFlushedTotal);
    state.SetLabel(std::string("store:" + to_string(store) +
                               " mode:" + to_string(mode))
                           .c_str());
    // Peak memory usage while flushing, minus baseline.
    state.counters["PeakFlushBytes"] = peakBytes - baseBytes;
    state.counters["PeakBytesPerItem"] = (peakBytes - baseBytes) / itemCount;
}

BENCHMARK_DEFINE_F(VBucketBench, CreateDeleteStoredValue)
(benchmark::State& state) {
    auto factory = std::make_unique<StoredValueFactory>(engine->getEpStats());

    const std::string value(1, 'x');
    while (state.KeepRunning()) {
        auto item = make_item(vbid, "key", value);
        benchmark::DoNotOptimize(item);
        auto sv = (*factory)(item, nullptr);
        benchmark::DoNotOptimize(sv);
    }
}

/*
 * MB-31834: Load throughput degradation when the number of checkpoints
 * eligible for removing is high.
 * At both checkpoint-removing and CM:queueDirty we acquire the CM::queueLock.
 * If the number of checkpoints eligible for removing is high, then any slow
 * operation under lock in CheckpointRemover delays frontend operations.
 * Note that the CheckpointRemover is O(N) in the size of the
 * CM::checkpointList. The regression is caused by a change in MB-30916 where we
 * started with deallocating checkpoint memory under lock.
 *
 * This benchmark measures resource contention between a mc:worker (frontend
 * thread) executing CM::queueDirty and the ClosedUnrefCheckpointRemoverTask
 * when the number of checkpoint eligible for removing is high.
 */
BENCHMARK_DEFINE_F(CheckpointBench, QueueDirtyWithManyClosedUnrefCheckpoints)
(benchmark::State& state) {
    // Test approach:
    // - Fix the number of checkpoints to be removed and run the
    //     CheckpointRemover in a background thread.
    // - Fix the number of checkpoint to be removed at each CheckpointRemover
    //     run (must be in the order of 10^3 to catch the regression scenario).
    // - Enqueue items into the CheckpointMaanager in the frontend thread.
    //     Break when the CheckpointRemover has done. Measure (A) the number
    //     of items enqueued and (B) the runtime of the frontend thread.
    // - Output the average runtime of frontend operations (B/A), which is the
    //     measured metric for this benchmark

    ASSERT_EQ(1, state.max_iterations);

    const size_t numCheckpoints = state.range(0);
    const size_t numCkptToRemovePerIteration = state.range(1);

    auto* vb = engine->getKVBucket()->getVBucket(vbid).get();
    auto* ckptMgr = vb->checkpointManager.get();

    // Same queued_item used for both checkpointList pre-filling and
    // front-end queueDirty().
    // Note that we will generate many 1-item checkpoints even if we enqueue
    // always the same identical item. That is because we have 'chk_max_items=1'
    // in configuration, which leads to the following order of steps at every
    // call to CM::queueDirty:
    // 1) close the open checkpoint
    // 2) create a new open checkpoint
    // 3) enqueue the new mutation (note that de-duplication happens here).
    //     The new mutation will be inserted into the /new/ (empty) open
    //     checkpoint. So, there will be no de-duplication.
    queued_item qi{
            new Item(StoredDocKey(std::string("key"), CollectionID::Default),
                     vbid,
                     queue_op::mutation,
                     /*revSeq*/ 0,
                     /*bySeq*/ 0)};

    // Pre-fill CM with the defined number of checkpoints
    for (size_t i = 0; i < numCheckpoints; ++i) {
        ckptMgr->queueDirty(*vb,
                            qi,
                            GenerateBySeqno::Yes,
                            GenerateCas::Yes,
                            /*preLinkDocCtx*/ nullptr);
    }

    // Simulate the Flusher, this makes all but the current checkpoint eligible
    // for removing (cannot remove checkpoint flusher is in).
    std::vector<queued_item> items;
    ckptMgr->getNextItemsForPersistence(items);
    ckptMgr->itemsPersisted();

    ThreadGate tg(2);

    // Note: numUnrefItems is also the number of removed checkpoints as
    //     we have 1 item per checkpoint.
    size_t numUnrefItems = 0;
    size_t numCkptRemoverRuns = 0;
    std::atomic<bool> bgDone{false};
    auto removeCkpt = [&tg,
                       ckptMgr,
                       vb,
                       numCkptToRemovePerIteration,
                       &numUnrefItems,
                       &numCheckpoints,
                       &numCkptRemoverRuns,
                       &bgDone]() {
        tg.threadUp();
        bool newOpenCheckpointCreated;
        while (true) {
            auto removed = ckptMgr->removeClosedUnrefCheckpoints(
                    *vb, newOpenCheckpointCreated, numCkptToRemovePerIteration);
            numUnrefItems += removed;
            numCkptRemoverRuns++;

            // Once all but the last item (in last checkpoint) is removed,
            // break.
            if (numUnrefItems >= numCheckpoints - 1) {
                break;
            }
        }
        // Done, exit frontend thread
        bgDone = true;
    };

    // Note: thread started but still blocked on ThreadGate
    std::thread bgThread(removeCkpt);

    size_t itemsQueuedTotal = 0;
    size_t runtime = 0;
    while (state.KeepRunning()) {
        tg.threadUp();
        auto begin = std::chrono::steady_clock::now();
        while (!bgDone) {
            ckptMgr->queueDirty(*vb,
                                qi,
                                GenerateBySeqno::Yes,
                                GenerateCas::Yes,
                                /*preLinkDocCtx*/ nullptr);
            itemsQueuedTotal++;
        }

        runtime = std::chrono::duration_cast<std::chrono::nanoseconds>(
                          std::chrono::steady_clock::now() - begin)
                          .count();
    }
    ASSERT_TRUE(itemsQueuedTotal);

    state.counters["NumCheckpointsRemoverRuns"] = numCkptRemoverRuns;
    state.counters["NumCheckpointsRemovedPerIteration"] =
            numUnrefItems / numCkptRemoverRuns;
    state.counters["ItemsEnqueued"] = itemsQueuedTotal;
    // Clang-scan-build complains about a possible division on 0.. guess
    // it doesn't know that the ASSERT_TRUE above would terminate the method
    if (itemsQueuedTotal > 0) {
        state.counters["AvgQueueDirtyRuntime"] = runtime / itemsQueuedTotal;
    }

    bgThread.join();
}

// Run with couchstore backend(0); item counts from 1..10,000,000
BENCHMARK_REGISTER_F(MemTrackingVBucketBench, QueueDirty)
        ->Args({0, 1})
        ->Args({0, 100})
        ->Args({0, 10000})
        ->Args({0, 1000000});

static void FlushArguments(benchmark::internal::Benchmark* b) {
    // Add couchstore (0), rocksdb (1), and magma (2) variants for a range of
    // sizes.
    for (auto items = 1; items <= 1000000; items *= 100) {
        // Insert mode
        b->Args({std::underlying_type<Store>::type(Store::Couchstore),
                 items,
                 0});
        // Replace mode
        b->Args({std::underlying_type<Store>::type(Store::Couchstore),
                 items,
                 1});
#ifdef EP_USE_ROCKSDB
        b->Args({std::underlying_type<Store>::type(Store::RocksDB), items, 0});
        b->Args({std::underlying_type<Store>::type(Store::RocksDB), items, 1});
#endif
#ifdef EP_USE_MAGMA
        b->Args({std::underlying_type<Store>::type(Store::Magma), items, 0});
        b->Args({std::underlying_type<Store>::type(Store::Magma), items, 1});
#endif
    }
}

BENCHMARK_REGISTER_F(MemTrackingVBucketBench, FlushVBucket)
        ->Apply(FlushArguments);

// Arguments: numCheckpoints, numCkptToRemovePerIteration
BENCHMARK_REGISTER_F(CheckpointBench, QueueDirtyWithManyClosedUnrefCheckpoints)
        ->Args({1000000, 1000})
        ->Iterations(1);


text:
package org.apache.wicket.markup.html.internal;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;

/**
 * Mock page for testing.
 *
 * @author Joonas Hamalainen
 *
 */
public class AjaxEnclosurePage_2 extends WebPage
{
	private static final long serialVersionUID = 1L;

	private final Label label1 = new Label("label1", "Test Label 1");
	private final Label label2 = new Label("label2", "Test Label 2");
	private final Label enclosure2Marker = new Label("enclosure2Marker", "enclosure2Marker Label");
	private AjaxLink<Void> toggleLabel1Link;
	private AjaxLink<Void> toggleLabel2Link;

	private final WebMarkupContainer container1;

	/**
	 * Construct.
	 */
	public AjaxEnclosurePage_2()
	{
		addLinks();

		container1 = new WebMarkupContainer("container1");
		label1.setOutputMarkupId(true);
		label2.setOutputMarkupId(true);
		container1.add(label1);
		container1.add(label2);
		container1.add(enclosure2Marker);
		add(container1);
	}

	private void addLinks()
	{
		toggleLabel1Link = new AjaxLink<Void>("toggleLabel1Link")
		{
			@Override
			public void onClick(AjaxRequestTarget target)
			{
				label1.setVisible(!label1.isVisible());
				target.addComponent(label1);
			}

		};
		add(toggleLabel1Link);

		toggleLabel2Link = new AjaxLink<Void>("toggleLabel2Link")
		{
			@Override
			public void onClick(AjaxRequestTarget target)
			{
				label2.setVisible(!label2.isVisible());
				target.addComponent(label2);
			}
		};
		add(toggleLabel2Link);
	}

	public static long getSerialversionuid()
	{
		return serialVersionUID;
	}

	public Label getLabel1()
	{
		return label1;
	}

	public Label getLabel2()
	{
		return label2;
	}

	public AjaxLink<Void> getToggleLabel1Link()
	{
		return toggleLabel1Link;
	}

	public AjaxLink<Void> getToggleLabel2Link()
	{
		return toggleLabel2Link;
	}

	public Label getEnclosure2Marker()
	{
		return enclosure2Marker;
	}
}


text:
package org.deziras.collection;

import org.deziras.util.TraversableOnce;

/**
 * Created by Glavo on 17-8-16.
 *
 * @author Glavo
 * @since 0.1.0
 */
public interface Iterator<A>
		extends java.util.Iterator<A>, java.util.Enumeration<A>,TraversableOnce<A> {

	@Override
	default boolean hasMoreElements() {
		return hasNext();
	}

	@Override
	default A nextElement() {
		return next();
	}

	@Override
	default void remove() {
		throw new UnsupportedOperationException("Iterator#remove");
	}

	@Override
	default Iterator<A> iterator() {
		return this;
	}

}


text:
package org.wave.resources.generators;

import java.io.IOException;
import java.io.Writer;

import javax.annotation.processing.Filer;
import javax.lang.model.element.Element;
import javax.tools.FileObject;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;

import org.wave.resources.exceptions.ResourcesException;
import org.wave.resources.factories.ContentFactory;
import org.wave.resources.factories.PropertiesFactory;
import org.wave.resources.messages.ErrorMessage;
import org.wave.resources.units.CompilationUnit;
import org.wave.resources.units.PropertiesUnit;
import org.wave.resources.units.ResourceUnit;
import org.wave.resources.utils.PropertiesUtil;
import org.wave.resources.utils.SourcesUtil;

public class FileGenerator {

	private Filer filer;

	public FileGenerator(Filer filer) {
		this.filer = filer;
	}

	public void generateProperties(Element element) throws ResourcesException {
		this.writePropertiesFile(element, StandardLocation.SOURCE_OUTPUT);
		this.writePropertiesFile(element, StandardLocation.CLASS_OUTPUT);
	}

	public void generateSources(Element element) throws ResourcesException {
		try {
			this.writeSourceFile(element, new PropertiesUnit());

			for (Element enumConstant : SourcesUtil.getEnumConstants(element)) {
				this.writeSourceFile(enumConstant, new ResourceUnit());
			}
		} catch (IOException e) {
			throw new ResourcesException(ErrorMessage.UNEXPECTED_EXCEPTION, e.getMessage());
		}
	}

	private void writePropertiesFile(Element element, StandardLocation location) throws ResourcesException {
		String packageName = PropertiesUtil.getPackageName(element);
		String propertiesName = PropertiesUtil.getPropertiesName(element);

		String comments = "Properties generated by Resources.";

		try {
			FileObject fileObject = this.filer.createResource(location, packageName, propertiesName);
			Writer writer = fileObject.openWriter();

			java.util.Properties properties = PropertiesFactory.create(element);
			properties.store(writer, comments);

			writer.flush();
			writer.close();
		} catch (IOException e) {
			throw new ResourcesException(ErrorMessage.UNEXPECTED_EXCEPTION, e.getMessage());
		}
	}

	private void writeSourceFile(Element element, CompilationUnit compilationUnit) throws IOException {
		CharSequence content = ContentFactory.create(compilationUnit, element);

		JavaFileObject fileObject = this.filer.createSourceFile(SourcesUtil.getQualifiedName(element));
		Writer writer = fileObject.openWriter();
		writer.append(content);
		writer.flush();
		writer.close();
	}

}


text:
package com.yammer.schedulizer.entities;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableSet;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Type;
import org.joda.time.LocalDate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "assignable_days")
public class AssignableDay extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "date")
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
    @NotNull
    private LocalDate date;

    @ManyToOne
    @JoinColumn(name = "group_id")
    private Group group;

    @OneToMany(mappedBy = "assignableDay")
    @Cascade({CascadeType.DELETE})
    private Set<Assignment> assignments = new HashSet<>();

    /* package private */ AssignableDay() {
        // Required by Hibernate
    }

    public AssignableDay(Group group, LocalDate date) {
        this.group = group;
        this.date = date;
    }

    public long getId() {
        return id;
    }

    @JsonProperty("date")
    public String getDateString() {
        return date.toString();
    }

    @JsonIgnore
    public LocalDate getDate() {
        return date;
    }

    public void setDate(LocalDate date) {
        this.date = date;
    }

    public long getGroupId() {
        return group.getId();
    }

    @JsonIgnore
    public Group getGroup() {
        return group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }

    public Set<Assignment> getAssignments() {
        return ImmutableSet.copyOf(assignments);
    }

    public void setAssignments(Set<Assignment> assignments) {
        this.assignments = ImmutableSet.copyOf(assignments);
    }
}


text:
/// <reference path="fourslash.ts" />

// Regression test for GH#43107

//// import * as something from "path";/**
////  * some comment here
////  * and there
////  */
//// import * as somethingElse from "anotherpath";
//// import * as AnotherThing from "somepath";/**
////  * some comment here
////  * and there
////  */
//// import * as AnotherThingElse from "someotherpath";

verify.organizeImports('');


text:
#ifndef ALIANALYSISTASKSEDSTARSPECTRA_H
#define ALIANALYSISTASKSEDSTARSPECTRA_H

/* $Id$ */

/// \class AliAnalysisTaskSEDStarSpectra

#include <TH2F.h>
#include <TH3F.h>
#include <THnSparse.h>

#include "AliAnalysisTaskSE.h"

class AliRDHFCutsDStartoKpipi;
class AliNormalizationCounter;

class AliAnalysisTaskSEDStarSpectra : public AliAnalysisTaskSE
{

 public:

  AliAnalysisTaskSEDStarSpectra();
  AliAnalysisTaskSEDStarSpectra(const Char_t* name,AliRDHFCutsDStartoKpipi* cuts);
  virtual ~AliAnalysisTaskSEDStarSpectra();

  /// Implementation of interface methods
  virtual void UserCreateOutputObjects();
  virtual void Init();
  virtual void LocalInit() {Init();}
  virtual void UserExec(Option_t *option);
  virtual void Terminate(Option_t *option);

  void SetAODMismatchProtection(Int_t opt=1) {fAODProtection=opt;}

  /// Background simulation
  void     SideBandBackground(AliAODRecoCascadeHF *part, AliRDHFCutsDStartoKpipi *cuts, Int_t isSel, TList *listout, TH1F** histlist);
  void     WrongSignForDStar(AliAODRecoCascadeHF *part, AliRDHFCutsDStartoKpipi *cuts, TList *listout);
    /// histos
  void   FillSpectrum(AliAODRecoCascadeHF *part, Int_t isDStar, AliRDHFCutsDStartoKpipi *cuts, Int_t isSel, TList *listout,TH1F** histlist);
  void     DefineHistograms();
  Int_t CheckOrigin(TClonesArray* arrayMC, const AliAODMCParticle *mcPartCandidate) const;
  void CreateImpactParameterHistos();

  /// set analysis type
  void     SetAnalysisType(Int_t anaType) {fAnalysis = anaType;}
  void     PrintAnalysisType() {printf("Analysis type: %d\n(0: Heidelberg\t1: Utrecht)",fAnalysis);}

  /// set MC usage
  void     SetMC(Bool_t theMCon) {fUseMCInfo = theMCon;}
  Bool_t   GetMC() const {return fUseMCInfo;}
 /// set rare mesons
  void     SetRareSearch(Bool_t theRareOn) {fDoSearch = theRareOn;}
  Bool_t   GetRareSearch() const {return fDoSearch;}
  /// impact par study
  void SetDoImpactParameterHistos(Bool_t doImp=kTRUE){fDoImpParDstar=doImp;}
  Bool_t GetDoImpactParameterHistos() const {return fDoImpParDstar;}

  Float_t GetTrueImpactParameterD0(const AliAODMCHeader *mcHeader, TClonesArray* arrayMC, const AliAODMCParticle *partDp) const;

  void SetDoDStarVsY(Bool_t theDStarVsY) {fDoDStarVsY = theDStarVsY;}

 private:

  AliAnalysisTaskSEDStarSpectra(const AliAnalysisTaskSEDStarSpectra &source);
  AliAnalysisTaskSEDStarSpectra& operator=(const AliAnalysisTaskSEDStarSpectra& source);

  enum{kDzMass, kDstarMass, kDeltaMass,kptMass, ketaMass,kDzSgn, kDstarSgn, kDeltaSgn,kptSgn, ketaSgn,kDzBkg, kDstarBkg, kDeltaBkg,kptBkg, ketaBkg, kSideBandMass, kWrongSignMass};

  TH1F** fAllhist;               // Histogramlist all
  TH1F** fPIDhist;               // Histogramlist with PID
  Int_t fNPtBins;                // Number of ptbins specified in the cutfile
  Int_t  fEvents;                ///  n. of events
  Int_t  fAnalysis;		 ///  0: HD;	1: UU;
  Double_t fD0Window;		 ///  select width on D0Mass
  Double_t fPeakWindow;          ///  select width on DstarMass
  Bool_t fUseMCInfo;             ///  Use MC info
  Bool_t fDoSearch;              ///  Rare mesons
  TList *fOutput;                //!<!  User output
  TList *fOutputAll;             //!<!  User output2
  TList *fOutputPID;             //!<!  User output3
  Int_t  fNSigma;                ///  n sigma for kaon PID
  AliRDHFCutsDStartoKpipi *fCuts; /// Cuts - sent to output slot 3
  // define the histograms
  TH1F *fCEvents;             //!<!
  TH2F *fTrueDiff2;           //!<!
  TH1F *fDeltaMassD1;         //!<!
  AliNormalizationCounter *fCounter;//!<!Counter for normalization slot 4
  Int_t fAODProtection;  /// flag to activate protection against AOD-dAOD mismatch.
                           /// -1: no protection,  0: check AOD/dAOD nEvents only,  1: check AOD/dAOD nEvents + TProcessID
  Bool_t fDoImpParDstar;  /// imppar studies
  Int_t  fNImpParBins;   /// nunber of bins in impact parameter histos
  Float_t fLowerImpPar;  /// lower limit in impact parameter (um)
  Float_t fHigherImpPar; /// higher limit in impact parameter (um)
  Bool_t  fDoDStarVsY;   /// flag to enable D* vs y

  THnSparseF *fHistMassPtImpParTCDs[5];//!<! histograms for impact paramter studies

  /// \cond CLASSIMP
  ClassDef(AliAnalysisTaskSEDStarSpectra,10); /// class for D* spectra
  /// \endcond
};

#endif


text:
package org.openhds.web.cvt;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import org.openhds.domain.service.SitePropertiesService;

public class ResidencyStartTypeCodeConverter implements Converter {

	SitePropertiesService siteProperties;

	String inmigrationValue;
	String birthValue;
	String enumerationValue;

	ResidencyStartTypeCodeConverter(SitePropertiesService siteProperties) {
		this.siteProperties = siteProperties;
		inmigrationValue = siteProperties.getInmigrationCode();
		birthValue = siteProperties.getBirthCode();
		enumerationValue = siteProperties.getEnumerationCode();
	}

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {

		if (arg2 != null && arg2.equals(inmigrationValue) || arg2.equals(birthValue) || arg2.equals(enumerationValue))
			return arg2;
		else {
			FacesMessage message = new FacesMessage("Residency Start Type can only contain the values " + inmigrationValue + ", " + birthValue + " or " + enumerationValue);
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ConverterException(message);
		}
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
		if (arg2 instanceof String) {
			if (arg2.equals(inmigrationValue) || arg2.equals(birthValue) || arg2.equals(enumerationValue))
				return arg2.toString();
		}
		return null;
	}
}


text:
'use strict';

exports.__esModule = true;

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _form = require('./form');

var _form2 = _interopRequireDefault(_form);

var _alertBox = require('./alertBox');

var _alertBox2 = _interopRequireDefault(_alertBox);

var _base = require('./base');

var _base2 = _interopRequireDefault(_base);

var _helpers = require('../helpers');

var _system = require('../system');

var system = _interopRequireWildcard(_system);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/// XXX: ?????????????
var objectId = 1;

var FakeTextInput = function (_Base) {
  (0, _inherits3.default)(FakeTextInput, _Base);

  function FakeTextInput(props) {
    (0, _classCallCheck3.default)(this, FakeTextInput);

    // just for control
    var _this = (0, _possibleConstructorReturn3.default)(this, _Base.call(this, props));

    _this.objectId = objectId++;

    _this.displayName = 'FakeTextInput';

    _this.state = {
      value: null
    };

    _this.onChange = _this.onChange.bind(_this);

    _this.inputDebounce = null;
    return _this;
  }

  FakeTextInput.prototype.onChange = function onChange(evt) {
    var _this2 = this;

    var newValue = evt.target.value;

    this.setValue(newValue);

    if (this.inputDebounce) {
      clearTimeout(this.inputDebounce);
    }

    // to avoid junk throw
    // TODO: maybe a helper for debounce would be cool
    this.inputDebounce = setTimeout(function () {
      if (_this2.props.onChange) {
        _this2.props.onChange((0, _helpers.createEvent)(evt, _this2, newValue));
      }
    }, system.bounceTime);
  };

  FakeTextInput.prototype.getValue = function getValue() {
    return this.state.value;
  };

  FakeTextInput.prototype.getImmediateValue = function getImmediateValue() {
    return this.refs.input.value;
  };

  FakeTextInput.prototype.setValue = function setValue(value) {
    this.setState({
      value: value,
      focused: false
    });
  };

  FakeTextInput.prototype.makeId = function makeId(props) {
    var nextId = [props.caquiRelatedForm, props.name].filter(function (x) {
      return !!x;
    });
    if (nextId.length) {
      this.id = nextId.join('.');
    } else {
      this.id = null;
    }
  };

  FakeTextInput.prototype.componentWillReceiveProps = function componentWillReceiveProps(props) {
    this.setState({
      value: props.value
    });
    this.makeId(props);
  };

  FakeTextInput.prototype.componentWillMount = function componentWillMount() {
    this.setState({
      value: this.props.value
    });
    this.makeId(this.props);
  };

  FakeTextInput.prototype.focus = function focus() {
    this.refs.input.focus();
  };

  FakeTextInput.prototype.blur = function blur() {
    this.refs.input.blur();
  };

  FakeTextInput.prototype.render = function render() {
    var props = this.props;
    var label = props.label;
    var placeholder = props.placeholder;

    var alertBox = null;

    if (this.id) {
      alertBox = _react2.default.createElement(_alertBox2.default, {
        silence: true,
        namespace: this.id });
    }

    var placeholderEl = _react2.default.createElement(
      'span',
      { className: 'caqui-fake-text-input-placeholder' },
      placeholder || label
    );

    return _react2.default.createElement(
      _form2.default.Group,
      props,
      label && _react2.default.createElement(
        'label',
        null,
        label
      ),
      _react2.default.createElement(
        'div',
        {
          className: 'caqui-fake-text-input',
          tabIndex: props.tabIndex || '0',
          ref: 'input' },
        this.state.value || this.props.children || placeholderEl
      ),
      alertBox
    );
  };

  return FakeTextInput;
}(_base2.default);

FakeTextInput.propTypes = {
  label: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.string, _react2.default.PropTypes.element]),
  placeholder: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.string, _react2.default.PropTypes.element])
};
FakeTextInput.defaultProps = {
  label: null,
  placeholder: null
};
exports.default = (0, _helpers.modelize)(FakeTextInput);


text:
<?php

namespace Magento\Setup\Console\Command;

use Magento\Framework\Code\GeneratedFiles;
use Magento\Setup\Model\ObjectManagerProvider;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
use Magento\Framework\App\DeploymentConfig;
use Magento\Framework\Module\Status;

abstract class AbstractModuleManageCommand extends AbstractModuleCommand
{
    /**
     * Names of input arguments or options
     */
    const INPUT_KEY_ALL = 'all';
    const INPUT_KEY_FORCE = 'force';

    /**
     * @var GeneratedFiles
     */
    protected $generatedFiles;

    /**
     * @var DeploymentConfig
     */
    protected $deploymentConfig;

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->addOption(
            self::INPUT_KEY_FORCE,
            'f',
            InputOption::VALUE_NONE,
            'Bypass dependencies check'
        );
        $this->addOption(
            self::INPUT_KEY_ALL,
            null,
            InputOption::VALUE_NONE,
            ($this->isEnable() ? 'Enable' : 'Disable') . ' all modules'
        );

        parent::configure();
    }

    /**
     * {@inheritdoc}
     */
    protected function isModuleRequired()
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $isEnable = $this->isEnable();
        if ($input->getOption(self::INPUT_KEY_ALL)) {
            /** @var \Magento\Framework\Module\FullModuleList $fullModulesList */
            $fullModulesList = $this->objectManager->get('Magento\Framework\Module\FullModuleList');
            $modules = $fullModulesList->getNames();
        } else {
            $modules = $input->getArgument(self::INPUT_KEY_MODULES);
        }
        $messages = $this->validate($modules);
        if (!empty($messages)) {
            $output->writeln(implode(PHP_EOL, $messages));
            // we must have an exit code higher than zero to indicate something was wrong
            return \Magento\Framework\Console\Cli::RETURN_FAILURE;
        }
        try {
            $modulesToChange = $this->getStatus()->getModulesToChange($isEnable, $modules);
        } catch (\LogicException $e) {
            $output->writeln('<error>' . $e->getMessage() . '</error>');
            // we must have an exit code higher than zero to indicate something was wrong
            return \Magento\Framework\Console\Cli::RETURN_FAILURE;
        }
        if (!empty($modulesToChange)) {
            $force = $input->getOption(self::INPUT_KEY_FORCE);
            if (!$force) {
                $constraints = $this->getStatus()->checkConstraints($isEnable, $modulesToChange);
                if ($constraints) {
                    $output->writeln(
                        "<error>Unable to change status of modules because of the following constraints:</error>"
                    );
                    $output->writeln('<error>' . implode("</error>\n<error>", $constraints) . '</error>');
                    // we must have an exit code higher than zero to indicate something was wrong
                    return \Magento\Framework\Console\Cli::RETURN_FAILURE;
                }
            }
            $this->setIsEnabled($isEnable, $modulesToChange, $output);
            $this->cleanup($input, $output);
            $this->getGeneratedFiles()->requestRegeneration();
            if ($force) {
                $output->writeln(
                    '<error>Alert: You used the --force option.'
                    . ' As a result, modules might not function properly.</error>'
                );
            }
        } else {
            $output->writeln('<info>No modules were changed.</info>');
        }
    }

    /**
     * Enable/disable modules
     *
     * @param bool $isEnable
     * @param string[] $modulesToChange
     * @param OutputInterface $output
     * @return void
     */
    private function setIsEnabled($isEnable, $modulesToChange, $output)
    {
        $this->getStatus()->setIsEnabled($isEnable, $modulesToChange);
        if ($isEnable) {
            $output->writeln('<info>The following modules have been enabled:</info>');
            $output->writeln('<info>- ' . implode("\n- ", $modulesToChange) . '</info>');
            $output->writeln('');
            if ($this->getDeploymentConfig()->isAvailable()) {
                $output->writeln(
                    '<info>To make sure that the enabled modules are properly registered,'
                    . " run 'setup:upgrade'.</info>"
                );
            }
        } else {
            $output->writeln('<info>The following modules have been disabled:</info>');
            $output->writeln('<info>- ' . implode("\n- ", $modulesToChange) . '</info>');
            $output->writeln('');
        }
    }

    /**
     * Get module status
     *
     * @return Status
     */
    private function getStatus()
    {
        return $this->objectManager->get(Status::class);
    }

    /**
     * Validate list of modules and return error messages
     *
     * @param string[] $modules
     * @return string[]
     */
    protected function validate(array $modules)
    {
        $messages = [];
        if (empty($modules)) {
            $messages[] = '<error>No modules specified. Specify a space-separated list of modules' .
                ' or use the --all option</error>';
        }
        return $messages;
    }

    /**
     * Is it "enable" or "disable" command
     *
     * @return bool
     */
    abstract protected function isEnable();

    /**
     * Get deployment config
     *
     * @return DeploymentConfig
     * @deprecated
     */
    private function getDeploymentConfig()
    {
        if (!($this->deploymentConfig instanceof DeploymentConfig)) {
            return $this->objectManager->get(DeploymentConfig::class);
        }
        return $this->deploymentConfig;
    }

    /**
     * Get deployment config
     *
     * @return GeneratedFiles
     * @deprecated
     */
    private function getGeneratedFiles()
    {
        if (!($this->generatedFiles instanceof GeneratedFiles)) {
            return $this->objectManager->get(GeneratedFiles::class);
        }
        return $this->generatedFiles;
    }
}


text:
namespace osgViewer
{
class StatsHandler;
class DisplaySettings;
}

namespace SurgSim
{

namespace Input
{
class CommonDevice;
}

namespace Devices
{
class KeyboardDevice;
class MouseDevice;
}

namespace Graphics
{

class OsgCamera;
class OsgTrackballZoomManipulator;

SURGSIM_STATIC_REGISTRATION(OsgView);

/// OSG-based implementation of graphics view class.
///
/// A Graphics::OsgView wraps a osgViewer::View to provide a visualization of the scene to the user.
///
/// A Graphics::OsgCamera controls the viewpoint of this View.
class OsgView : public View
{
public:
	/// Constructor
	/// \post	The view has no camera.
	/// \post	The position of the view is (0, 0).
	/// \post	The dimensions of the view are 800 x 600.
	/// \post	The window border is enabled.
	/// \param	name	Name of the view
	explicit OsgView(const std::string& name);

	/// Destructor
	~OsgView();

	SURGSIM_CLASSNAME(SurgSim::Graphics::OsgView);

	void setPosition(const std::array<int, 2>& position) override;

	std::array<int, 2> getPosition() const override;

	void setDimensions(const std::array<int, 2>& dimensions) override;

	std::array<int, 2> getDimensions() const override;

	void setDimensionsDouble(const std::array<double, 2>& dimensions) override;

	std::array<double, 2> getDimensionsDouble() const override;

	void setWindowBorderEnabled(bool enabled) override;

	bool isWindowBorderEnabled() const override;

	/// Sets the camera which provides the viewpoint in the scene
	/// Only allows OsgCamera components, any other will not be set and it will return false.
	/// \param	camera	Camera whose image will be shown in this view
	/// \return	True if it succeeded, false if it failed
	void setCamera(std::shared_ptr<SurgSim::Framework::Component> camera) override;

	/// Enables a camera manipulator, implemented via a trackball, this is a temporary solution as it uses
	/// the OSG input events rather than reading from the OpenSurgSim input.
	/// \param val whether to enable the manipulator or not.
	void enableManipulator(bool val);

	/// \return whether the manipulator is enabled or not.
	bool isManipulatorEnabled();

	/// As the camera is not accessible from here and as it cannot be controlled from the outside
	/// any more we let the user set the parameters from here.
	/// \param	position	The position of the camera.
	/// \param	lookat  	The location the camera looks at.
	void setManipulatorParameters(const SurgSim::Math::Vector3d& position, const SurgSim::Math::Vector3d& lookat);

	/// Set the camera manipulator position.
	/// \param position The position of the camera.
	void setManipulatorPosition(const SurgSim::Math::Vector3d& position);

	/// \return The position of the camera.
	SurgSim::Math::Vector3d getManipulatorPosition();

	/// Set the camera manipulator lookAt.
	/// \param lookAt The location the camera looks at.
	void setManipulatorLookAt(const SurgSim::Math::Vector3d& lookAt);

	/// \return The location the camera looks at.
	SurgSim::Math::Vector3d getManipulatorLookAt();

	/// Enable osg modelview uniforms mapping, in this mode osg replaces the gl builtins with osg_* names, for
	/// uniforms and vertex attributes
	/// \param val Whether to enable osg uniform mapping, default false
	void setOsgMapsUniforms(bool val);

	/// \return the state of the osg modelview mapping mode.
	bool getOsgMapsUniforms();

	/// Return the keyboard to be used with this view.
	/// \return A keyboard device
	std::shared_ptr<SurgSim::Input::CommonDevice> getKeyboardDevice();

	/// Turn on/off the keyboard device to be used.
	/// \param val Indicate whether or not to use keyboard device
	void enableKeyboardDevice(bool val);

	/// \return Whether the keyboard device is enabled.
	bool isKeyboardDeviceEnabled();

	/// Return the mouse to be used with this view.
	/// \return A mouse device
	std::shared_ptr<SurgSim::Input::CommonDevice> getMouseDevice();

	/// Turn on/off the mouse device to be used.
	/// \param val Indicate whether or not to use mouse device
	void enableMouseDevice(bool val);

	/// \return Whether the mouse device is enabled.
	bool isMouseDeviceEnabled();

	void update(double dt) override;

	/// \return the OSG view which performs the actual work involved in setting up and rendering to a window
	osg::ref_ptr<osgViewer::View> getOsgView() const;

protected:
	/// Initialize the view
	/// \post The view's window is setup.
	bool doInitialize() override;

	/// Wake up the view
	bool doWakeUp() override;

	/// Determine Screen Size
	int doSetTargetScreen(int val) override;

	/// \return The DisplaySettings to be used in this view
	virtual osg::ref_ptr<osg::DisplaySettings> createDisplaySettings() const;
private:

	/// Patch the StatsHandler rendering
	/// \param statsHandler The statshandler that will be patched.
	void fixupStatsHandler(osgViewer::StatsHandler* statsHandler);

	/// Position of the view on the screen (in pixels)
	std::array<int, 2> m_position;
	/// Dimensions of the view on the screen (in pixels)
	std::array<int, 2> m_dimensions;
	std::array<int, 2> m_screenDimensions = {};
	/// Whether the view window has a border
	bool m_isWindowBorderEnabled;

	/// Whether the next update will be the first time the view has been updated
	/// On the first update, the view window is setup.
	bool m_isFirstUpdate;
	/// Whether the settings have been changed and the window needs to be updated
	bool m_areWindowSettingsDirty;

	/// OSG view which performs the actual work involved in setting up and rendering to a window
	osg::ref_ptr<osgViewer::View> m_view;

	/// Wether to enable osg uniform mapping
	bool m_osgMapUniforms;

	osg::ref_ptr<OsgTrackballZoomManipulator> m_manipulator;
	SurgSim::Math::Vector3d m_manipulatorPosition;
	SurgSim::Math::Vector3d m_manipulatorLookat;

	/// Indicate if a keyboard device is enabled
	bool m_keyboardEnabled;
	std::shared_ptr<SurgSim::Devices::KeyboardDevice> m_keyboardDevice;

	/// Indicate if a mouse device is enabled
	bool m_mouseEnabled;
	std::shared_ptr<SurgSim::Devices::MouseDevice> m_mouseDevice;
};

};  // namespace Graphics

};  // namespace SurgSim

#endif  // SURGSIM_GRAPHICS_OSGVIEW_H


text:
int main(int argc, const char* argv[]) {
  return updater::KSAdminAppMain(argc, argv);
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Shooter 2 players Example — Networked-Aframe</title>
    <meta name="description" content="Shooter 2 players Example — Networked-Aframe" />


text:
/* Automatically generated by version.sh, do not manually edit! */
#ifndef AVUTIL_FFVERSION_H
#define AVUTIL_FFVERSION_H
#define FFMPEG_VERSION "git-2016-02-26-3b60668"
#endif /* AVUTIL_FFVERSION_H */


text:
/* This file is part of the cmail project (http://cmail.rocks/)
 * (c) 2015 Fabian "cbdev" Stumpf
 * License: Simplified BSD (2-Clause)
 * For further information, consult LICENSE.txt
 */

ssize_t network_read(CONNECTION* client, char* buffer, unsigned bytes){
	int status;

	#ifndef CMAIL_NO_TLS
	switch(client->tls_mode){
		case TLS_NONE:
			//non-tls client
			return recv(client->fd, buffer, bytes, 0);
		case TLS_NEGOTIATE:
			//tls handshake not completed
			status = gnutls_handshake(client->tls_session);
			if(status){
				if(gnutls_error_is_fatal(status)){
					logprintf(LOG_ERROR, "TLS Handshake reported fatal error: %s\n", gnutls_strerror(status));
					return -2;
				}
				logprintf(LOG_WARNING, "TLS Handshake reported nonfatal error: %s\n", gnutls_strerror(status));
				return -1;
			}

			logprintf(LOG_INFO, "TLS Handshake completed\n");
			return 0;
		case TLS_ONLY:
			//read with tls
			return gnutls_record_recv(client->tls_session, buffer, bytes);
	}
	#else
	return recv(client->fd, buffer, bytes, 0);
	#endif

	logprintf(LOG_ERROR, "Network read with invalid TLSMODE\n");
	return -2;
}

int network_connect(char* host, uint16_t port, char* bind_host){
	int sockfd = -1, error;
	char port_str[20];
	struct addrinfo hints = {
		.ai_family = AF_UNSPEC,
		.ai_socktype = SOCK_STREAM
	};
	struct addrinfo* head, *iter, *bind_head, *bind_iter;

	snprintf(port_str, sizeof(port_str), "%d", port);

	error = getaddrinfo(host, port_str, &hints, &head);
	if(error){
		logprintf(LOG_WARNING, "getaddrinfo: %s\r\n", gai_strerror(error));
		return -1;
	}

	for(iter = head; iter; iter = iter->ai_next){
		sockfd = socket(iter->ai_family, iter->ai_socktype, iter->ai_protocol);
		if(sockfd < 0){
			continue;
		}

		if(bind_host){
			//resolve the bind host
			hints.ai_family = iter->ai_family;
			error = getaddrinfo(bind_host, "0", &hints, &bind_head);
			if(error){
				logprintf(LOG_WARNING, "Failed to resolve local side for outbound connection: %s\r\n", gai_strerror(error));
				close(sockfd);
				sockfd = -1;
				continue;
			}

			for(bind_iter = bind_head; sockfd >= 0 && bind_iter; bind_iter = bind_iter->ai_next){
				if(!bind(sockfd, bind_iter->ai_addr, bind_iter->ai_addrlen)){
					break;
				}

				logprintf(LOG_WARNING, "Failed to bind local side for outbound connection: %s\r\n", strerror(errno));
				if(!bind_iter->ai_next){
					close(sockfd);
					sockfd = -1;
					logprintf(LOG_WARNING, "Current socket incompatible with bind host: %s\r\n", strerror(errno));
				}
			}
		}

		if(sockfd < 0){
			continue;
		}

		error = connect(sockfd, iter->ai_addr, iter->ai_addrlen);
		if(error != 0){
			close(sockfd);
			sockfd = -1;
			continue;
		}

		break;
	}

	freeaddrinfo(head);
	iter = NULL;

	if(sockfd < 0){
		logprintf(LOG_WARNING, "Failed to create client socket: %s\n", strerror(errno));
		return -1;
	}

	if(error != 0){
		logprintf(LOG_WARNING, "Failed to connect: %s\n", strerror(errno));
		return -1;
	}

	return sockfd;
}

int network_listener(char* bindhost, char* port){
	int fd = -1, status, yes = 1;
	struct addrinfo hints;
	struct addrinfo* info;
	struct addrinfo* addr_it;

	memset(&hints, 0, sizeof(hints));

	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE;

	status = getaddrinfo(bindhost, port, &hints, &info);
	if(status){
		logprintf(LOG_ERROR, "Failed to get socket info for %s port %s: %s\n", bindhost, port, gai_strerror(status));
		return -1;
	}

	for(addr_it = info; addr_it != NULL; addr_it = addr_it->ai_next){
		fd = socket(addr_it->ai_family, addr_it->ai_socktype, addr_it->ai_protocol);
		if(fd < 0){
			continue;
		}

		if(setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&yes, sizeof(yes)) < 0){
			logprintf(LOG_WARNING, "Failed to set IPV6_V6ONLY on socket for %s port %s: %s\n", bindhost, port, strerror(errno));
		}

		yes = 1;
		if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(yes)) < 0){
			logprintf(LOG_WARNING, "Failed to set SO_REUSEADDR on socket\n");
		}

		status = bind(fd, addr_it->ai_addr, addr_it->ai_addrlen);
		if(status < 0){
			close(fd);
			continue;
		}

		break;
	}

	freeaddrinfo(info);

	if(!addr_it){
		logprintf(LOG_ERROR, "Failed to create listening socket for %s port %s\n", bindhost, port);
		return -1;
	}

	status = listen(fd, LISTEN_QUEUE_LENGTH);
	if(status < 0){
		logprintf(LOG_ERROR, "Failed to listen on socket: %s", strerror(errno));
		close(fd);
		return -1;
	}

	return fd;
}


text:
from mongoengine import StringField, MapField, URLField, ImageField

from web.contentment.util import D_

from .base import Block
from .content_ import render_text_block

from web.component.asset.xml.templates import text_block_content
from web.component.asset.xml.importers import text_block_content as text_block_content_importer
from web.contentment.util.model import Properties

class DescriptionBlock(Block):
	__icon__ = 'asterisk'

class TextBlock(Block):
	__icon__ = 'font'

	__xml_exporters__ = {
		'content': text_block_content,
	}

	__xml_importers__ = {
		'content': text_block_content_importer,
	}

	content = MapField(StringField(), default=dict, simple=False)  # TODO: TranslatedField.
	format = StringField(default='html', choices=['html', 'textile', 'md', 'rest'])  # TODO: Dynamic.

	# Data Portability

	def __html_stream__(self, context=None):
		return render_text_block(context, self, D_(self.content))

	def __json__(self):
		return dict(super(TextBlock, self).as_json,
				target = self._data['target'].id
			)

	def __text__(self):
		return ''  # TODO: Content extraction.

class QuoteBlock(Block):
	__icon__ = 'wc-b-quote'

	pass

class ButtonBlock(Block):
	__icon__ = 'wc-b-button'

	label = MapField(StringField(), db_field='c', default=dict)  # TODO: TranslatedField.
	target = URLField(db_field='t')

class ImageBlock(Block):
	__icon__ = 'wc-b-image'

	image = ImageField(db_field='i')
	source = URLField(db_field='s')
	target = URLField(db_field='t')
	caption = MapField(StringField(), db_field='c', default=dict)  # TODO: TranslatedField.


text:
class BufferCommand
  class << self
    def up(buffer)
      buffer.move_line(-1)
    end

    def down(buffer)
      buffer.move_line(1)
    end

    def left(buffer)
      buffer.move_point(-1)
    end

    def right(buffer)
      buffer.move_point(1)
    end

    def change_line(buffer)
      buffer.change_line
    end

    def buffer_delete(buffer)
      buffer.delete(-1)
    end

    def buffer_del2(buffer)
      buffer.delete(-2)
    end

    def eval_current_buffer(buffer)
      eval(buffer.content.to_string)
    end

    def set_copy_mark(buffer)
      buffer.set_copy_mark
    end

    def copy(buffer)
      buffer.copy
    end

    def paste_string(buffer)
      buffer.paste_string
    end
  end
end


text:
if [ -z "$1" ]
then
    echo "usage: $0 <app_path>"
    exit 65
fi

APP_PATH=$1
shift
THIS_DIR=`dirname $0`
PYTHON_EXEC_PATH="Contents/MacOS/python"
RESOURCES_PATH="Contents/Resources"

if [ ! -e "$APP_PATH/$RESOURCES_PATH" ]
then
    echo "$APP_PATH/$RESOURCES_PATH does not exist"
    exit 66
fi

if [ ! -e "$APP_PATH/$PYTHON_EXEC_PATH" ]
then
    echo "$APP_PATH/$PYTHON_EXEC_PATH does not exist"
    exit 67
fi

PYTHONHOME="$APP_PATH/$RESOURCES_PATH" ${APP_PATH}/${PYTHON_EXEC_PATH} ${THIS_DIR}/runtestsuite.py $@


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/ship/crafted/capacitor/shared_energy_saver_battery_mk3.iff"
	result.attribute_template_id = 8
	result.stfName("space_crafting_n","energy_saver_battery_mk3")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
package com.payneteasy.superfly.spisupport;

import com.googlecode.jdbcproc.daofactory.annotation.AStoredProcedure;

/**
 * DAO to work with HOTP algorithm.
 *
 * @author Roman Puchkovskiy
 */
public interface HOTPDao {
    /**
     * Returns HOTP data for the given user.
     *
     * @param username    name of the user
     * @return HOTP data
     */
    @AStoredProcedure(name = "get_hotp_data")
    HOTPData getHOTPData(String username);

    /**
     * Increments an HOTP value for the given user.
     *
     * @param username    name of the user
     * @param newValue    value to set for the counter
     */
    @AStoredProcedure(name = "update_hotp_counter")
    void updateCounter(String username, long newValue);

    /**
     * Resets HOTP sequence for the given user.
     *
     * @param username    name of the user
     * @param hotpSalt    new salt for HOTP
     */
    @AStoredProcedure(name="reset_hotp")
    void resetHOTP(String username, String hotpSalt);
}