text:
package com.lucidchart.open.nark.controllers

import com.lucidchart.open.nark.Global
import com.lucidchart.open.nark.models.{AlertModel, DynamicAlertModel, DynamicAlertTagModel, SubscriptionModel, TagConverter, UserModel}
import com.lucidchart.open.nark.models.records.{Comparisons, DynamicAlert, Pagination, Subscription, AlertType}
import com.lucidchart.open.nark.request.{AppAction, AppFlash, AuthAction, DynamicAlertAction}
import com.lucidchart.open.nark.views

import java.util.UUID
import play.api.data._
import play.api.data.Forms._
import play.api.data.format.Formats._
import play.api.Play.configuration
import play.api.Play.current
import scala.math.BigDecimal
import validation.Constraints

object DynamicAlertsController extends DynamicAlertsController
class DynamicAlertsController extends AppController {

	private case class CreateFormSubmission(
		name: String,
		tags: List[String],
		searchTarget: String,
		matchExpr: String,
		buildTarget: String,
		errorThreshold: BigDecimal,
		warnThreshold: BigDecimal,
		comparison: Comparisons.Value,
		frequency: Int,
		dataSeconds: Int,
		dropNullPoints: Int,
		dropNullTargets: Boolean,
		subscribe: Boolean
	)

	private case class EditFormSubmission(
		name: String,
		tags: List[String],
		searchTarget: String,
		matchExpr: String,
		buildTarget: String,
		errorThreshold: BigDecimal,
		warnThreshold: BigDecimal,
		comparison: Comparisons.Value,
		frequency: Int,
		active: Boolean,
		dataSeconds: Int,
		dropNullPoints: Int,
		dropNullTargets: Boolean
	)

	private val createAlertForm = Form(
		mapping(
			"name" -> text.verifying(Constraints.minLength(1)),
			"tags" -> text.verifying("Max 25 characters per tag.", tags => tags.length == 0 || tags.split(",").filter(_.length > 25).isEmpty)
			              .verifying(Constraints.pattern("^[a-zA-Z0-9\\.\\-_,]*$".r, error = "Only alpha-numberic text and periods (.), dashes (-), and underscores (_) allowed"))
			              .transform[List[String]](str => if(str.length == 0) List[String]() else str.split(",").map(_.trim.toLowerCase).toList, _.mkString(",")),
			"search_target" -> text,
			"match_expr" -> text.verifying("Invalid regular expression.", { expression =>
				try {
					expression.r
					true
				}
				catch {
					case e: Exception => false
				}
			}),
			"build_target" -> text,
			"error_threshold" -> bigDecimal,
			"warn_threshold" -> bigDecimal,
			"comparison" -> number.verifying("Invalid comparison type", x => Comparisons.values.map(_.id).contains(x)).transform[Comparisons.Value](Comparisons(_), _.id),
			"frequency" -> number.verifying(Constraints.min(1)),
			"data_seconds" -> number.verifying("Must be positive", x => x > 0),
			"drop_null_points" -> number.verifying("Must be positive", x => x >= 0),
			"drop_null_targets" -> boolean,
			"subscribe" -> boolean
		)(CreateFormSubmission.apply)(CreateFormSubmission.unapply)
	)

	private val editAlertForm = Form(
		mapping(
			"name" -> text.verifying(Constraints.minLength(1)),
			"tags" -> text.verifying("Max 25 characters per tag.", tags => tags.length == 0 || tags.split(",").filter(_.length > 25).isEmpty)
			              .verifying(Constraints.pattern("^[a-zA-Z0-9\\.\\-_,]*$".r, error = "Only alpha-numberic text and periods (.), dashes (-), and underscores (_) allowed"))
			              .transform[List[String]](str => if(str.length == 0) List[String]() else str.split(",").map(_.trim.toLowerCase).toList, _.mkString(",")),
			"search_target" -> text,
			"match_expr" -> text,
			"build_target" -> text,
			"error_threshold" -> bigDecimal,
			"warn_threshold" -> bigDecimal,
			"comparison" -> number.verifying("Invalid comparison type", x => Comparisons.values.map(_.id).contains(x)).transform[Comparisons.Value](Comparisons(_), _.id),
			"frequency" -> number.verifying(Constraints.min(1)),
			"active" -> boolean,
			"data_seconds" -> number.verifying("Must be positive", x => x > 0),
			"drop_null_points" -> number.verifying("Must be positive", x => x >= 0),
			"drop_null_targets" -> boolean
		)(EditFormSubmission.apply)(EditFormSubmission.unapply)
	)

	/**
	 * Show the form for creating a dynamic alert
	 */
	def create() = AuthAction.authenticatedUser { implicit user =>
		AppAction { implicit request =>
			val form = createAlertForm.fill(CreateFormSubmission("", Nil, "", "", "", 0, 0, Comparisons.<, 60, configuration.getInt("alerts.secondsToCheckData").get, 1, true,true))
			Ok(views.html.dynamicalerts.create(form))
		}
	}

	/**
	 * Create the dynamic alert in the database
	 */
	def createSubmit() = AuthAction.authenticatedUser { implicit user =>
		AppAction { implicit request =>
			createAlertForm.bindFromRequest().fold(
				formWithErrors => {
					Ok(views.html.dynamicalerts.create(formWithErrors))
				},
				data => {
					val alert = new DynamicAlert(
						data.name,
						user.id,
						data.searchTarget,
						data.matchExpr,
						data.buildTarget,
						data.comparison,
						data.frequency,
						data.warnThreshold,
						data.errorThreshold,
						data.dataSeconds,
						data.dropNullPoints,
						data.dropNullTargets
					)
					DynamicAlertModel.createDynamicAlert(alert)
					DynamicAlertTagModel.updateTagsForAlert(alert.id, data.tags)
					var msg = "Dynamic Alert created successfully."
					if (data.subscribe) {
						val subscription = new Subscription(user.id, alert.id, AlertType(1))
						SubscriptionModel.createSubscription(subscription)
						msg = msg.concat(" Subscribed to this alert.")
					}
					Redirect(routes.DynamicAlertsController.view(alert.id)).flashing(AppFlash.success(msg))
				}
			)
		}
	}

	/**
	 * Search for a particular dynamic alert
	 * @param term the search term to use when looking for alerts
	 * @param page the page number of results to show
	 */
	def search(term: String, page: Int) = AuthAction.maybeAuthenticatedUser { implicit user =>
		AppAction { implicit request =>
			val realPage = page.max(1)
			val (found, matches) = DynamicAlertModel.search(term, realPage - 1)
			val tags = TagConverter.toTagMap(DynamicAlertTagModel.findTagsForAlert(matches.map{_.id}))
			Ok(views.html.dynamicalerts.search(term, Pagination[DynamicAlert](realPage, found, DynamicAlertModel.configuredLimit, matches), tags))
		}
	}

	/**
	 * View a dynamic alert
	 * @param id the id of the dynamic alert to view
	 */
	def view(id: UUID) = AuthAction.maybeAuthenticatedUser { implicit user =>
		DynamicAlertAction.existingAlert(id) { alert =>
			AppAction { implicit request =>
				val creator = UserModel.findUserByID(alert.userId)
				val tags = DynamicAlertTagModel.findTagsForAlert(alert.id)
				val subscriptions = SubscriptionModel.getSubscriptionsByAlert(alert.id)
				val propagatedAlerts = AlertModel.findAlertByDynamicAlert(alert.id)
				Ok(views.html.dynamicalerts.view(alert, propagatedAlerts, creator, tags, subscriptions))
			}
		}
	}

	/**
	 * Edit a dynamic alert
	 * @param id the id of the dynamic alert to edit
	 */
	def edit(id: UUID) = AuthAction.authenticatedUser { implicit user =>
		DynamicAlertAction.alertManagementAccess(id, user.id) { alert =>
			AppAction { implicit request =>
				val form = editAlertForm.fill(EditFormSubmission(
					alert.name,
					DynamicAlertTagModel.findTagsForAlert(alert.id).map(_.tag),
					alert.searchTarget,
					alert.matchExpr,
					alert.buildTarget,
					alert.errorThreshold,
					alert.warnThreshold,
					alert.comparison,
					alert.frequency,
					alert.active,
					alert.dataSeconds,
					alert.dropNullPoints,
					alert.dropNullTargets
				))
				Ok(views.html.dynamicalerts.edit(form, id))
			}
		}
	}

	/**
	 * Edit a particular dynamic alert
	 * @param id the id of the alert to edit
	 */
	def editSubmit(alertId: UUID) = AuthAction.authenticatedUser { implicit user =>
		DynamicAlertAction.alertManagementAccess(alertId, user.id) { alert =>
			AppAction { implicit request =>
				editAlertForm.bindFromRequest().fold(
					formWithErrors => {
						Ok(views.html.dynamicalerts.edit(formWithErrors, alertId))
					},
					data => {
						val editedAlert = alert.copy(
							name = data.name,
							searchTarget = data.searchTarget,
							matchExpr = data.matchExpr,
							buildTarget = data.buildTarget,
							errorThreshold = data.errorThreshold,
							warnThreshold = data.warnThreshold,
							comparison = data.comparison,
							frequency = data.frequency,
							active = data.active,
							dataSeconds = data.dataSeconds,
							dropNullPoints = data.dropNullPoints,
							dropNullTargets = data.dropNullTargets
						)

						DynamicAlertModel.editDynamicAlert(editedAlert)
						DynamicAlertTagModel.updateTagsForAlert(editedAlert.id, data.tags)
						Redirect(routes.DynamicAlertsController.view(alertId)).flashing(AppFlash.success("Changes saved."))
					}
				)
			}
		}
	}

	/**
	 * Deleted dynamic alerts
	 */
	def deleted(term: String, page: Int) = AuthAction.authenticatedUser { implicit user =>
		AppAction { implicit request =>
			val realPage = page.max(1)
			val (found, matches) = DynamicAlertModel.searchDeleted(user.id, term, realPage - 1)
			val tags = TagConverter.toTagMap(DynamicAlertTagModel.findTagsForAlert(matches.map(_.id)))
			Ok(views.html.dynamicalerts.deleted(term, Pagination[DynamicAlert](realPage, found, DynamicAlertModel.configuredLimit, matches), tags))
		}
	}

	/**
	 * Recover a dynamic alert
	 */
	def recover(alertId: UUID) = AuthAction.authenticatedUser { implicit user =>
		DynamicAlertAction.alertManagementAccess(alertId, user.id, allowDeleted = true) { alert =>
			AppAction { implicit request =>
				DynamicAlertModel.editDynamicAlert(alert.copy(deleted = false))
				Redirect(routes.DynamicAlertsController.edit(alertId)).flashing(AppFlash.success("Dynamic alert was recovered successfully."))
			}
		}
	}

	/**
	 * Delete a dynamic alert
	 */
	def delete(alertId: UUID) = AuthAction.authenticatedUser { implicit user =>
		DynamicAlertAction.alertManagementAccess(alertId, user.id) { alert =>
			AppAction { implicit request =>
				DynamicAlertModel.editDynamicAlert(alert.copy(deleted = true))
				Redirect(routes.HomeController.index()).flashing(AppFlash.success("Dynamic alert was deleted successfully."))
			}
		}
	}
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class publicar_model extends CI_Model{

  public function __construct()
  {
    parent::__construct();
    $this->load->database();
    //Codeigniter : Write Less Do More
  }

  function guardarPublicar($publicar){

    $id = $publicar['ID'];
    if($id+0 > 0){
      //Actualizar
      $this->db->where('ID=',$id);
      unset($publicar['ID']);
      $this->db->update('publicar',$publicar);
    }else{
      $this->db->insert('publicar',$publicar);
    }
  }

  function listarPublicaciones(){
    $query = $this->db->get('publicar');

    return $query->result();
  }

  function eliminarPublicar($id){

    $this->db->where('ID=',$id);
    $this->db->delete('publicar');
  }

  function cargarPublicar($id){
    $publicar = new stdClass();
    $publicar->ID = 0;
    $publicar->NombrePuesto = "";
    $publicar->Descripcion = "";
    $publicar->Requisitos = "";
    $publicar->NivelAcademico = "";
    $publicar->EdadMaxima = "";
    $publicar->Horario = "";
    $publicar->Salario = "";
    $publicar->Comentario = "";
    $publicar->Empresa = "";

    $query = $this->db->where('ID=',$id);
    $query = $this->db->get('publicar');

    $rs = $query->result();
    if(count($rs) > 0){
      $publicar = $rs[0];
    }
    return $publicar;
  }
}

redpajama_set_name: RedPajamaGithub


text:
package spakeout;

import java.util.ArrayList;
import java.util.List;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

public class Voystick {

	static List<Voystickable> subscribers = new ArrayList<Voystickable>();
	private static Handler mHandler;

	static {

		mHandler = new Handler(Looper.getMainLooper()) {
			@Override
			public void handleMessage(Message inputMessage) {
				for (Voystickable sub : subscribers) {
					sub.onVoystickEvent((VoystickEvent) inputMessage.obj);
				}
			}
		};

		new Thread(new VoystickPoller()).start();
	}

	public static void unsubscribe(Voystickable sub) {
		subscribers.remove(sub);
	}

	public static void subscribe(Voystickable sub) {
		if (!subscribers.contains(sub)) {
  		subscribers.add(sub);
		}
	}

	public static void fireAudioJoystickEvent(VoystickEvent e) {
		mHandler.obtainMessage(0, e).sendToTarget();
	}

}


text:
import sys

import ipaddress as ipa  # https://docs.python.org/3/library/ipaddress.html

from . import lookup

class Network(object):
    """
    Subclass of Host that represents an IP network to be scanned.

    Keywork arguments:
    cidr -- ipa.IPv4Network object
    related_hosts -- set of valid Hosts found by scanning each cidr in cidrs
    """

    def __init__(self, cidr):
        """
        cidr parameter should be an ipaddress.IPv4Network
        """
        if not cidr:
            raise ValueError
        if sys.version_info[0] == 2:
            cidr = unicode(cidr)
        # Raises ValueError if cidr is not a valid network
        self.cidr = ipa.ip_network(cidr, strict=False)
        self.related_hosts = set()
        self.type = "network"

    def __str__(self):
        return str(self.cidr)

    def __hash__(self):
        return hash(("cidr", self.cidr))

    def __eq__(self, other):
        return self.cidr == other.cidr

    def add_related_host(self, new_host):
        self.related_hosts.add(new_host)

    def print_as_csv_lines(self):
        """Overrides method from Host. Yields each Host in related_hosts as csv line"""
        yield ["Target: " + str(self.cidr)]

        if self.related_hosts:
            yield ["IP", "Reverse domains"]
            for host in self.related_hosts:
                yield [
                    ", ".join([str(ip) for ip in host.ips]),
                    ", ".join([", ".join(ip.rev_domains) for ip in host.ips]),
                ]
        else:
            yield ["No results"]


text:
package javax.print.attribute.standard;

import javax.print.attribute.Attribute;
import javax.print.attribute.SetOfIntegerSyntax;
import javax.print.attribute.DocAttribute;
import javax.print.attribute.PrintRequestAttribute;
import javax.print.attribute.PrintJobAttribute;

/**
 * Class PageRanges is a printing attribute class, a set of integers, that
 * identifies the range(s) of print-stream pages that the Printer object uses
 * for each copy of each document which are to be printed. Nothing is printed
 * for any pages identified that do not exist in the document(s). The attribute
 * is associated with print-stream pages, not application-numbered pages
 * (for example, the page numbers found in the headers and or footers for
 * certain word processing applications).
 *

 * In most cases, the exact pages to be printed will be generated by a device
 * driver and this attribute would not be required. However, when printing an
 * archived document which has already been formatted, the end user may elect to
 * print just a subset of the pages contained in the document. In this case, if
 * a page range of "n-m" is specified, the first page
 * to be printed will be page n. All subsequent pages of the document
 * will be printed through and including page m.
 *

 * If a PageRanges attribute is not specified for a print job, all pages of
 * the document will be printed. In other words, the default value for the
 * PageRanges attribute is always {{1, Integer.MAX_VALUE}}.
 *

 * The effect of a PageRanges attribute on a multidoc print job (a job with
 * multiple documents) depends on whether all the docs have the same page ranges
 * specified or whether different docs have different page ranges specified, and
 * on the (perhaps defaulted) value of the {@link MultipleDocumentHandling
 * MultipleDocumentHandling} attribute.
 *

 *

 * If all the docs have the same page ranges specified, then any value of {@link
 * MultipleDocumentHandling MultipleDocumentHandling} makes sense, and the
 * printer's processing depends on the {@link MultipleDocumentHandling
 * MultipleDocumentHandling} value:
 *

 *

 * SINGLE_DOCUMENT -- All the input docs will be combined together into one
 * output document. The specified page ranges of that output document will be
 * printed.
 *

 *

 * SINGLE_DOCUMENT_NEW_SHEET -- All the input docs will be combined together
 * into one output document, and the first impression of each input doc will
 * always start on a new media sheet. The specified page ranges of that output
 * document will be printed.
 *

 *

 * SEPARATE_DOCUMENTS_UNCOLLATED_COPIES -- For each separate input doc, the
 * specified page ranges will be printed.
 *

 *

 * SEPARATE_DOCUMENTS_COLLATED_COPIES -- For each separate input doc, the
 * specified page ranges will be printed.
 *

 *

 *

 * SEPARATE_DOCUMENTS_UNCOLLATED_COPIES -- For each separate input doc, its own
 * specified page ranges will be printed..
 *

 *

 * SEPARATE_DOCUMENTS_COLLATED_COPIES -- For each separate input doc, its own
 * specified page ranges will be printed..
 *

 *

 *

 * IPP Compatibility: The PageRanges attribute's canonical array form
 * gives the lower and upper bound for each range of pages to be included in
 * and IPP "page-ranges" attribute. See class {@link
 * javax.print.attribute.SetOfIntegerSyntax SetOfIntegerSyntax} for an
 * explanation of canonical array form. The category name returned by
 * getName() gives the IPP attribute name.
 *

 *
 * @author  David Mendenhall
 * @author  Alan Kaminsky
 */
public final class PageRanges   extends SetOfIntegerSyntax
        implements DocAttribute, PrintRequestAttribute, PrintJobAttribute {

    private static final long serialVersionUID = 8639895197656148392L;

    /**
     * Construct a new page ranges attribute with the given members. The
     * members are specified in "array form;" see class {@link
     * javax.print.attribute.SetOfIntegerSyntax SetOfIntegerSyntax} for an
     * explanation of array form.
     *
     * @param  members  Set members in array form.
     *
     * @exception  NullPointerException
     *     (unchecked exception) Thrown if members is null or
     *     any element of members is null.
     * @exception  IllegalArgumentException
     *     (unchecked exception) Thrown if any element of
     *   members is not a length-one or length-two array. Also
     *     thrown if members is a zero-length array or if any
     *     member of the set is less than 1.
     */
    public PageRanges(int[][] members) {
        super (members);
        if (members == null) {
            throw new NullPointerException("members is null");
        }
        myPageRanges();
    }
    /**
     * Construct a new  page ranges attribute with the given members in
     * string form.
     * See class {@link javax.print.attribute.SetOfIntegerSyntax
     * SetOfIntegerSyntax}
     * for explanation of the syntax.
     *
     * @param  members  Set members in string form.
     *
     * @exception  NullPointerException
     *     (unchecked exception) Thrown if members is null or
     *     any element of members is null.
     * @exception  IllegalArgumentException
     *     (Unchecked exception) Thrown if members does not
     *    obey  the proper syntax.  Also
     *     thrown if the constructed set-of-integer is a
     *     zero-length array or if any
     *     member of the set is less than 1.
     */
    public PageRanges(String members) {
        super(members);
        if (members == null) {
            throw new NullPointerException("members is null");
        }
        myPageRanges();
    }

    private void myPageRanges() {
        int[][] myMembers = getMembers();
        int n = myMembers.length;
        if (n == 0) {
            throw new IllegalArgumentException("members is zero-length");
        }
        int i;
        for (i = 0; i < n; ++ i) {
          if (myMembers[i][0] < 1) {
            throw new IllegalArgumentException("Page value < 1 specified");
          }
        }
    }

    /**
     * Construct a new page ranges attribute containing a single integer. That
     * is, only the one page is to be printed.
     *
     * @param  member  Set member.
     *
     * @exception  IllegalArgumentException
     *     (Unchecked exception) Thrown if member is less than
     *     1.
     */
    public PageRanges(int member) {
        super (member);
        if (member < 1) {
            throw new IllegalArgumentException("Page value < 1 specified");
        }
    }

    /**
     * Construct a new page ranges attribute containing a single range of
     * integers. That is, only those pages in the one range are to be printed.
     *
     * @param  lowerBound  Lower bound of the range.
     * @param  upperBound  Upper bound of the range.
     *
     * @exception  IllegalArgumentException
     *     (Unchecked exception) Thrown if a null range is specified or if a
     *     non-null range is specified with lowerBound less than
     *     1.
     */
    public PageRanges(int lowerBound, int upperBound) {
        super (lowerBound, upperBound);
        if (lowerBound > upperBound) {
            throw new IllegalArgumentException("Null range specified");
        } else if (lowerBound < 1) {
            throw new IllegalArgumentException("Page value < 1 specified");
        }
    }

    /**
     * Returns whether this page ranges attribute is equivalent to the passed
     * in object. To be equivalent, all of the following conditions must be
     * true:
     *

     *

     * object is not null.
     *

     * object is an instance of class PageRanges.
     *

     * This page ranges attribute's members and object's members
     * are the same.
     *

     *
     * @param  object  Object to compare to.
     *
     * @return  True if object is equivalent to this page ranges
     *          attribute, false otherwise.
     */
    public boolean equals(Object object) {
        return (super.equals(object) && object instanceof PageRanges);
    }

    /**
     * Get the printing attribute class which is to be used as the "category"
     * for this printing attribute value.
     *

     * For class PageRanges, the category is class PageRanges itself.
     *
     * @return  Printing attribute class (category), an instance of class
     *          {@link java.lang.Class java.lang.Class}.
     */
    public final Class<? extends Attribute> getCategory() {
        return PageRanges.class;
    }

    /**
     * Get the name of the category of which this attribute value is an
     * instance.
     *

     * For class PageRanges, the category name is "page-ranges".
     *
     * @return  Attribute category name.
     */
    public final String getName() {
        return "page-ranges";
    }

}


text:
.. _notebook_mdgxs_part_ii:

================================
MDGXS Part II: Advanced Features
================================

.. only:: html

    .. notebook:: mdgxs-part-ii.ipynb

.. only:: latex

    IPython notebooks must be viewed in the online HTML documentation.


text:
import React from 'react';
import moment from 'moment';
import DatePicker from 'react-datepicker';
import { registerLocale } from 'react-datepicker';
import fr from 'date-fns/locale/fr';
import {Calendar, CalendarControls} from 'react-yearly-calendar';

import async from 'async';
moment.updateLocale('fr',{
    months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
    monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),
    monthsParseExact : true,
    weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
    weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
    weekdaysMin : 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay : '[Aujourd'hui à] LT',
        nextDay : '[Demain à] LT',
        nextWeek : 'dddd [à] LT',
        lastDay : '[Hier à] LT',
        lastWeek : 'dddd [dernier à] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : 'dans %s',
        past : 'il y a %s',
        s : 'quelques secondes',
        m : 'une minute',
        mm : '%d minutes',
        h : 'une heure',
        hh : '%d heures',
        d : 'un jour',
        dd : '%d jours',
        M : 'un mois',
        MM : '%d mois',
        y : 'un an',
        yy : '%d ans'
    },
    dayOfMonthOrdinalParse : /\d{1,2}(er|e)/,
    ordinal : function (number) {
        return number + (number === 1 ? 'er' : 'e');
    },
    meridiemParse : /PD|MD/,
    isPM : function (input) {
        return input.charAt(0) === 'M';
    },
    // In case the meridiem units are not separated around 12, then implement
    // this function (look at locale/id.js for an example).
    // meridiemHour : function (hour, meridiem) {
    //     return /* 0-23 hour, given meridiem token and hour 1-12 */ ;
    // },
    meridiem : function (hours, minutes, isLower) {
        return hours < 12 ? 'PD' : 'MD';
    },
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // Used to determine first week of the year.
    }
});
moment.weekdays(true)
registerLocale('fr', fr);

require('./App.css');
require('./react-yearly-calendar.css');
require('react-datepicker/dist/react-datepicker.css');

const backendUrl = process.env.REACT_APP_BACKEND_URL || "";
console.log("using backend url:", backendUrl);

class Option extends React.Component {
    render() {
        return (
            <option value={this.props.val.id}>{this.props.val.name}</option>
        );
    }
}

class SelectList extends React.Component {
    constructor(props) {
        super(props);
        this.onChange = this.onChange.bind(this);
    }

    render() {
        if (this.props.values && this.props.values.length <= 1) {
            return null;
        }
        const options = [<Option val='' key='-1' />];
        if (this.props.values) {
            this.props.values.forEach(function (val) {
                options.push(<Option val={val} key={val.id} />);
            });
        }

        return (

                {this.props.label}<select className='select-form' value={this.props.selected} id={this.props.id} onChange={this.onChange}>
                    {options}
                </select>

        );
    }
    onChange (e) {
        this.props.changeFunc(e.target.value);
    }
}

function isWeekday(d) {
    const dow = d.weekday();
    return dow < 5;
}

class JNTDatePicker extends React.Component {
    render() {
        const jnts = [];
        this.props.jnts.forEach(function (e) {
            jnts.push(moment(e, 'YYYY-MM-DD'));
        });
        const date = this.props.date.toDate();
        return (

                Date ({this.props.date.format('dddd')})

                    <DatePicker selected={date} onChange={this.props.changeDate} dateFormat='dd/MM/yyyy' filterDate={this.isWeekday} locale='fr' excludeDates={jnts} />
                    <input type='button' onClick={this.props.previousDay} value='Jour précédent' className="button" style={{ display: 'table-cell' }} />
                    <input type='button' onClick={this.props.nextDay} value='Jour suivant' className="button" style={{ display: 'table-cell' }} />

        );
    }
}

function Comment(props) {
    return (

Remarque<textarea id='comment' value={props.comment} onChange={props.updateComment} />

    );
}

function arrayToMap(a) {
  const m = {};
    for (let i = 0; i = 200 && response.status < 300) {
        return response.json();
    } else {
        return response.json().then(function (body) {
            throw body;
        });
    }
}

function fetcher(url, cb) {
    fetch(url).then(checkStatus)
        .then(function (content) {
            cb(null, content)
        }).catch(function (ex) {
            cb(ex, null);
        });
};

function canUserBeDisplayed(user, d) {
    return !user.leave_date || moment(user.leave_date) >= d;
}

function filterSubMenu(id, sublist, name) {
    if (id === -1) {
        return [];
    }

    const lst = [];
    for (let i = 0; i < sublist.list.length; i++) {
        const elem = sublist.list[i];
        if (elem[name] === id) {
            lst.push(elem);
        }
    }
    return lst;
}

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            today: moment(),
            weeklyTasks: {},
            user_id: -1,
            category_id: -1,
            project_id: -1,
            activity_id: -1,
            allocation_id: -1,
            users: {},
            categories: {},
            projects: {},
            activities: {},
            allocations: {},
            errorMsg: '',
            comment: '',
            jnts: new Set(),
        };
        this.dailyTasks = this.dailyTasks.bind(this);
        this.getProjectActivities = this.getProjectActivities.bind(this);
        this.getCategoryProjects = this.getCategoryProjects.bind(this);
        this.filterUsers = this.filterUsers.bind(this);
        this.goToToday = this.goToToday.bind(this);
        this.getWorkingDayCss = this.getWorkingDayCss.bind(this);
        this.isWorkingDay = this.isWorkingDay.bind(this);
        this.previousDay = this.previousDay.bind(this);
        this.nextDay = this.nextDay.bind(this);
        this.changeComment = this.changeComment.bind(this);
        this.changeUser = this.changeUser.bind(this);
        this.changeCategory = this.changeCategory.bind(this);
        this.changeProject = this.changeProject.bind(this);
        this.changeActivity = this.changeActivity.bind(this);
        this.changeAllocation = this.changeAllocation.bind(this);
        this.deleteDailyTasks = this.deleteDailyTasks.bind(this);
        this.changeDate = this.changeDate.bind(this);
        this.addTaskAndNextDay = this.addTaskAndNextDay.bind(this);
        this.addTask = this.addTask.bind(this);
    }

    componentDidMount() {
        const that = this;
        async.parallel({
            categories: function (cb) {
                fetcher(backendUrl + '/categories', cb);
            },
            activities: function (cb) {
                fetcher(backendUrl + '/activities', cb);
            },
            projects: function (cb) {
                fetcher(backendUrl + '/projects', cb);
            },
            allocations: function (cb) {
                fetcher(backendUrl + '/allocations', cb);
            },
            users: function (cb) {
                fetcher(backendUrl + '/users', cb);
            },
            jnts: function (cb) {
                fetcher(backendUrl + '/jnt', cb);
            }
        }, function (err, results) {
            if (err) {
                console.error('error in async parrallel', err);
                that.setState({ errorMsg: err });
            } else {
                const jntJson = results['jnts'];

                const jnts = new Set();

                for (let i = 0; i < jntJson.length; i++) {
                    jnts.add(jntJson[i]);
                }

                delete results['jnts'];
                const state = { jnts: jnts }
                for (const k in results) {
                    state[k] = {};
                    state[k]['dict'] = arrayToMap(results[k]);
                    state[k]['list'] = results[k];
                }
                that.setState(state);

                if (!that.isWorkingDay(that.state.today)) {
                    that.nextDay();
                }
            }
        });
    }

    dailyTasks() {
        if (!this.state.today) {
            return [];
        }
        const today = this.state.today.format('YYYY-MM-DD');
        if (today in this.state.weeklyTasks) {
            return this.state.weeklyTasks[today];
        }
        return [];
    }

    getProjectActivities(projectId) {
        return filterSubMenu(projectId, this.state.activities, 'project_id');
    }

    getCategoryProjects(categoryId) {
        return filterSubMenu(categoryId, this.state.projects, 'category_id');
    }

    filterUsers(today) {
        const users = [];
        if (this.state.users.list) {
            const current_date = today.startOf('day');
            for (let user of this.state.users.list) {
                if (canUserBeDisplayed(user, current_date)) {
                    users.push(user);
                }
            }
        }
        return users;
    }

    render() {
        const dailyTasks = this.dailyTasks();
        const that = this;
        const categoryProjects = this.getCategoryProjects(this.state.category_id);
        const projectActivities = this.getProjectActivities(this.state.project_id);
        const users = this.filterUsers(this.state.today);

        return (

                <form className='task-table'>
                    <SelectList values={users} label='Trigramme' cssclass='user' changeFunc={this.changeUser} selected={this.state.user_id} />
                    <JNTDatePicker date={this.state.today} previousDay={this.previousDay} nextDay={this.nextDay} jnts={this.state.jnts} changeDate={this.changeDate} />
                    <SelectList values={this.state.categories.list} label='Catégorie' cssclass='category-select' id='category' changeFunc={this.changeCategory} selected={this.state.category_id} />
                    <SelectList values={categoryProjects} label='Projet' cssclass='project-select' id='project' changeFunc={this.changeProject} selected={this.state.project_id} />
                    <SelectList values={projectActivities} label='Activité' cssclass='activity-select' id='activity' changeFunc={this.changeActivity} selected={this.state.activity_id} />
                    <SelectList values={this.state.allocations.list} label='Temps' cssclass='allocation-select' id='allocation' changeFunc={this.changeAllocation} selected={this.state.allocation_id} />
                    <Comment comment={this.state.comment} updateComment={this.changeComment} />

                            <input type='button' onClick={this.addTask} value='Ajouter cette tâche' />

                            <input type='button' onClick={this.addTaskAndNextDay} value='Ajouter cette tâche et aller au prochain jour' />

                </form>

{this.state.errorMsg}

                <DailySummary tasks={dailyTasks} deleteTasks={this.deleteDailyTasks} date={this.state.today} />

                <WeeklySummary tasks={this.state.weeklyTasks} date={this.state.today} isWorkingDay={this.isWorkingDay} />

                        <CalendarControls
                            year={this.state.today.year()}
                            showTodayButton={true}
                            //onPrevYear={() => this.onPrevYear()}
                            //onNextYear={() => this.onNextYear()}
                            goToToday={this.goToToday} />
                        <Calendar year={this.state.today.year()} onPickDate={this.changeDate} selectedDay={this.state.today} customClasses={function (d) { return that.getWorkingDayCss(d) } } />

                Télécharger en csv

        );
    }

    goToToday() {
        this.changeDate(moment());
    }

    getWorkingDayCss(d) {
        if (this.isWorkingDay(d)) {
            const dStr = d.format('YYYY-MM-DD');
            if (!(dStr in this.state.weeklyTasks)) {
                return '';
            }
            const tasks = this.state.weeklyTasks[dStr];
            let total = 0;
            for (let i = 0; i < tasks.length; i++) {
                total += tasks[i].allocation.value;
            }
            switch (parseInt(total * 100)) {
                case 100:
                    return 'day-ok';
                case 75:
                    return 'day-75';
                case 50:
                    return 'day-50';
                case 25:
                    return 'day-25';
                default:
                    return '';
            }
        }
        return 'jnt';
    }

    isWorkingDay(d) {
        if (this.state.jnts.has(d.format('YYYY-MM-DD'))) {
            return false;
        }
        return isWeekday(d);
    }

    previousDay() {
        let d = this.state.today.clone().add(-1, 'day');
        while (!this.isWorkingDay(d)) {
            d.add(-1, 'day');
        }
        this.changeDate(d);
    }

    nextDay() {
        let d = this.state.today.clone().add(1, 'day');
        while (!this.isWorkingDay(d)) {
            d.add(1, 'day');
        }
        this.changeDate(d);
    }

    changeComment(e) {
        this.setState({ comment: e.target.value });
    }

    changeUser(user_id) {
        const that = this;
        fetch(backendUrl + '/users/' + user_id + '/tasks').then(function (response) {
            return response.json();
        }).then(function (content) {
            const weeklyTasks = {};
            for (let i = 0; i < content.length; i++) {
                const task = content[i];
                if (!(task.date in weeklyTasks)) {
                    weeklyTasks[task.date] = [];
                }
                weeklyTasks[task.date].push({
                    id: task.id,
                    activity: that.state.activities.dict[task.activity_id],
                    project: that.state.projects.dict[task.project_id],
                    allocation: that.state.allocations.dict[task.allocation_id],
                    comment: task.comment,
                    date: task.date
                });
            }
            that.setState({ user_id: parseInt(user_id), weeklyTasks: weeklyTasks });
        }).catch(function (ex) {
            console.error(ex);
            that.setState({ errorMsg: 'Error in receiving user tasks' + ex });
        });
    }

    changeCategory(category_id) {
        const categoryId = parseInt(category_id);
        const projects = this.getCategoryProjects(categoryId);
        if (projects.length === 1) {
            const projectId = projects[0].id;
            this.setState({ category_id: categoryId, project_id: projectId, activity_id: -1 });
            this.changeProject(projectId);
        } else {
            this.setState({ category_id: categoryId, project_id: -1, activity_id: -1 });
        }
    }

    changeProject(project_id) {
        const projectId = parseInt(project_id);
        const activities = this.getProjectActivities(projectId);
        if (activities.length === 0) {
            const projects = this.getCategoryProjects(this.state.category_id);
            const project = projects.find(p => p.id === projectId);
            this.setState({ errorMsg: `Pas d'activité pour le projet "${project.name}" en base, veuillez en ajouter au moins une.` });
        } else if (activities.length === 1) {
            this.setState({ project_id: projectId, activity_id: activities[0].id });
        } else {
            this.setState({ project_id: projectId, activity_id: -1 });
        }
    }

    changeActivity(activity_id) {
        this.setState({ activity_id: parseInt(activity_id) });
    }

    changeAllocation(allocation_id) {
        this.setState({ allocation_id: parseInt(allocation_id) });
    }

    deleteDailyTasks(indexes) {
        const that = this;
        fetch(backendUrl + '/tasks/' + indexes.join(), {
            method: 'DELETE',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }

        }).then(function (response) {
            return response.json();
        }).then(function (content) {
            const dailyTasks = [];
            const oldTasks = that.dailyTasks();
            for (let i = 0; i < oldTasks.length; i++) {
                if (indexes.indexOf(oldTasks[i].id) >= 0) {
                    continue;
                }
                dailyTasks.push(oldTasks[i]);
            }
            const weeklyTasks = that.state.weeklyTasks;
            const today = that.state.today.format('YYYY-MM-DD');
            weeklyTasks[today] = dailyTasks;
            that.setState({ weeklyTasks: weeklyTasks, errorMsg: '' });
        }).catch(function (ex) {
            console.error(ex)
            that.setState({ errorMsg: ex });
        });
    }

    changeDate(d) {
        d = moment(d);
        let user_id = this.state.user_id;
        if (this.state.user_id && (this.state.user_id in this.state.users.dict)) {
            const current_date = d.startOf('day');
            let user = this.state.users.dict[this.state.user_id];
            if (!canUserBeDisplayed(user, current_date)) {
                user_id = -1;
            }
        }
        this.setState({ today: d, errorMsg: '', user_id: user_id });
    }

    addTaskAndNextDay(event) {
        event.preventDefault();
        this.addTask(event, this.nextDay);
    }

    addTask(event, cb) {
        event.preventDefault();
        if (!isWeekday(this.state.today)) {
            this.setState({ errorMsg: 'Veuillez sélectionner un jour de la semaine entre lundi et vendredi.' });
            return;
        }
        if (this.state.allocation_id === -1 || this.state.user_id === -1 || this.state.project_id === -1 || this.state.activity_id === -1 || this.state.category_id === -1) {
            this.setState({ errorMsg: 'Veuillez sélectionner un choix valide.' });
            return;
        }
        const today = this.state.today.format('YYYY-MM-DD');

        const that = this;
        fetch(backendUrl + '/users/' + this.state.user_id + '/tasks', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                activity_id: this.state.activity_id,
                allocation_id: this.state.allocation_id,
                comment: this.state.comment,
                date: today
            })
        }).then(checkStatus)
            .then(function (content) {
                const weeklyTasks = {};
                for (let k in that.state.weeklyTasks) {
                    weeklyTasks[k] = that.state.weeklyTasks[k];
                }

                if (!(today in weeklyTasks))
                    weeklyTasks[today] = [];
                weeklyTasks[today].push({
                    id: content.id,
                    activity: that.state.activities.dict[that.state.activity_id],
                    project: that.state.projects.dict[that.state.project_id],
                    allocation: that.state.allocations.dict[that.state.allocation_id],
                    comment: that.state.comment,
                    date: today
                });
                that.setState({ weeklyTasks: weeklyTasks, errorMsg: '' });
                if (cb) {
                    cb();
                }
            }).catch(function (ex) {
                that.setState({ errorMsg: ex });
            });
    }
}

class DailyTask extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            checked: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    render() {
        return (

<input type="checkbox" value={this.state.checked} onChange={this.handleClick} /> {this.props.project.name}	{this.props.activity.name}	{this.props.allocation.name}	{this.props.comment}

        );
    }
    handleClick() {
        const newState = !this.state.checked;
        this.setState({ checked: newState });
        this.props.handleTaskClick(this.props.index, newState);
    }
}

class DailySummary extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            checkedIndexes: {},
        };
        this.deleteTasks = this.deleteTasks.bind(this);
        this.handleTaskClick = this.handleTaskClick.bind(this);
    }
    render() {
        const rows = [];
        this.props.tasks.forEach(function (task) {
            rows.push(<DailyTask project={task.project} key={task.id} index={task.id} activity={task.activity} allocation={task.allocation} comment={task.comment} handleTaskClick={this.handleTaskClick} />);
        }.bind(this));
        return (

Journée en cours: {this.props.date.format('dddd DD MMMM YYYY')}

                            Projet	Activité	Temps	Remarque

                        {rows}

                <input type="button" value="Effacer les tâches" onClick={this.deleteTasks} />

        );
    }

    deleteTasks() {
        const indexes = [];
        for (let k in this.state.checkedIndexes) {
            if (this.state.checkedIndexes[k])
                indexes.push(parseInt(k));
        }
        this.props.deleteTasks(indexes);
        this.setState({ checkedIndexes: {} });
    }

    handleTaskClick(index, checked) {
        const checkedIndexes = {};
        for (const k in this.state.checkedIndexes) {
            checkedIndexes[k] = this.state.checkedIndexes[k];
        }
        checkedIndexes[index] = checked;
        this.setState({ checkedIndexes: checkedIndexes });
    }
}

class WeeklySummary extends React.Component {
    render() {
        const dow = this.props.date.weekday();

        const projects = {};
        const defaultAllocation = { allocation: { name: '', value: 0 } }
        const sumDays = {};
        let total = 0;
        const dates = []
        for (let i = 0; i < 5; i++) {
            sumDays[i] = 0;
            const d = this.props.date.clone().add(i - dow, 'day');
            dates.push(d);
            const date = d.format('YYYY-MM-DD');
            if (date in this.props.tasks) {

                const dailyProject = this.props.tasks[date];

                for (let j = 0; j < dailyProject.length; j++) {
                    const projectName = dailyProject[j].project.name;
                    if (!(projectName in projects)) {
                        projects[projectName] = {};
                    }
                    const activity = dailyProject[j].activity.name;
                    if (!(activity in projects[projectName])) {
                        projects[projectName][activity] = [defaultAllocation, defaultAllocation, defaultAllocation, defaultAllocation, defaultAllocation];
                    }
                    projects[projectName][activity][i] = dailyProject[j];
                    sumDays[i] += dailyProject[j].allocation.value;
                    total += dailyProject[j].allocation.value;
                }
            }
        }

        const rows = [];
        for (let p in projects) {
            let key = p;
            for (const activity in projects[p]) {
                key += activity;
                const columns = [];
                for (let i = 0; i < 5; i++) {
                    const task = projects[p][activity][i];
                    const taskKey = parseInt(task.id) + dates[i].format('YYYY-MM-DD');
                    columns.push({task.allocation.name}	);
                }
                rows.push(
{p}	{activity}	{columns}
);
            }
        }

        const totalCells = [];
        const dateNames = []
        let workingDaysInWeek = 0;
        for (let i = 0; i < 5; i++) {
            const s = parseInt(i);
            const workingDay = this.props.isWorkingDay(dates[i]);
            totalCells.push(<TotalCell total={sumDays[s]} key={'totalCell' + s} workingDay={workingDay} />);
            let selectedCss = '';
            if (dates[i].format('YYYY-MM-DD') === this.props.date.format('YYYY-MM-DD')) {
                selectedCss = 'selected';
            }
            dateNames.push({dates[i].format('dddd (DD/MM)')}	);
            if (workingDay) {
                workingDaysInWeek++;
            }
        }

        const totalCss = total === workingDaysInWeek ? 'green' : 'grey';
        return (

Semaine en cours

                        Projet	Activité	{dateNames}Total

                    {rows}

Total	{totalCells}{total} / {workingDaysInWeek}

        );
    }
}

class TotalCell extends React.Component {
    render() {
        let css = '';
        let total = '';
        if (this.props.workingDay) {
            total = this.props.total;
            switch (parseInt(total * 100)) {
                case 100:
                    css = 'green';
                    break;
                case 75:
                    css = 'limegreen';
                    break;
                case 50:
                    css = 'darkseagreen';
                    break;
                case 25:
                    css = 'lightgreen';
                    break;
                default:
                    css = 'red';
            }
        }
        return (
            {total}
        );
    }
}

export default App;


text:
int main(void)
{
	int x;
	char *answer;
	if ((answer=malloc(21*(sizeof (char))))==NULL)
	{
		fprintf(stderr,"Not enough space, shutting down programm.\n");
		return -1;
	}
	printf("Do you want to read a joke or to tell me one?\n(answer with 'read' or 'tell', type exit for the obvious reason)\n");
	fgets(answer,6,stdin);
	while (0!=strcmp(answer,"exit\n"))
	{
		if (0==strcmp(answer,"read\n"))
		{
			fprintf(stderr,"Let me choose one, hit Enter when ready to laugh :P\n");
			getchar();
			if(read())
			{
				fprintf(stderr,"I found no jokes!! Pls update me :P\n");
			}
		}
		else if (0==strcmp(answer,"tell\n"))
		{
			fprintf(stderr,"Okie dokie, go on then :D\n");
			if(tell()==1)
			{
				fprintf(stderr,"No space available buddy...\n");
			}
			fprintf(stderr,"Hahahahaha, nice one! :D\n");
		}
		else
		{
			fprintf(stderr,"Please select a valid choice:\n");
		}
		fprintf(stderr,"(answer with 'read' or 'tell', type exit for the obvious reason)\n");
		fgets(answer,6,stdin);
	}
	free(answer);
	return 0;
}


text:
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JRPCTester {
    public static void main(String[] args) throws Throwable {
        JsonRpcHttpClient client;
        System.out.println("Enter your user: default is root");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String username = br.readLine();
        if (username.equals(""))
            username = "root";
        System.out.println("Enter your password: default is root");
        String password = br.readLine();
        if (password.equals(""))
            password = "root";

        // Authentication.
        try {
            System.out.println("Enter your URL:default is http://localhost:8080/");
            String url = br.readLine();
            if (!url.equals("")) {
                client = new JsonRpcHttpClient(new URL(url));
            } else {
                client = new JsonRpcHttpClient(new URL("http://localhost:8080/"));
            }
            String token = client.invoke("authenticateUser", new Object[]{username, password}, String.class);
            if (token.equals("Failed")) {
                System.out.print("Auth Failed");
                System.exit(1);
            }
            System.out.println("your token is: " + token);

            while (true) {
                System.out.println("*******************************");
                System.out.println("1: getSwitchesUsageStatus");
                System.out.println("2: getVMsUsageStatus");
                System.out.println("3: getOrdersList");
                System.out.println("4: getOrderInfoByID");
                System.out.println("5: getRunningSlices");
                System.out.println("6: orderSlice");
                System.out.println("7: deleteOrderByID");
                System.out.println("8: getRunningSliceInfoByID");
                System.out.println("0: exit");
                System.out.println("*******************************");
                int cmd = Integer.parseInt(br.readLine());
                switch (cmd) {
                    case 1:
                        System.out.println("switchesUsageStatus:\n" + client.invoke("getSwitchesUsageStatus", new Object[]{token}, String.class));
                        break;
                    case 2:
                        System.out.println("vmsUsageStatus:\n" + client.invoke("getVMsUsageStatus", new Object[]{token}, String.class));
                        break;
                    case 3:
                        System.out.println("getOrdersList:\n" + client.invoke("getOrdersList", new Object[]{token}, String.class));
                        break;
                    case 4:
                        System.out.println("Enter orderID:");
                        String orderID = br.readLine();
                        System.out.println("getOrderInfoByID:\n" + client.invoke("getOrderInfoByID", new Object[]{token, orderID}, String.class));
                        break;
                    case 5:
                        System.out.println("getRunningSlices:\n" + client.invoke("getRunningSlices", new Object[]{token}, String.class));
                        break;
                    case 6:
                        System.out.println("Enter order JSON file path(default is $CLASSPATH/order.json):");
                        byte[] encoded = Files.readAllBytes(Paths.get("util/JRPCTester/order.json"));
                        String order = new String(encoded, Charset.defaultCharset());
                        String orderingStatus = client.invoke("orderSlice", new Object[]{token, order}, String.class);
                        System.out.println("OrderingStatus:\n" + orderingStatus);
                        break;
                    case 7:
                        System.out.println("Enter orderId");
                        String orderId = br.readLine();
                        String status = client.invoke("deleteOrderByID", new Object[]{token, orderId}, String.class);
                        System.out.println(status);
                        break;
                    case 8:
                        System.out.println("Enter orderId");
                        String orderId1 = br.readLine();
                        String status1 = client.invoke("getRunningSliceInfoById", new Object[]{token, orderId1}, String.class);
                        System.out.println(status1);
                        break;
                    case 0:
                        System.out.println("Bye");
                        System.exit(1);
                    default:
                        System.out.println("Error");
                }
            }
        } catch (Exception e) {
            System.out.println(e);
            System.exit(1);
        }
    }
}


text:
#pragma once

#include <crest/wave/solver.hpp>
#include <crest/geometry/indexed_mesh.hpp>
#include <crest/quadrature/simpsons.hpp>
#include <crest/util/stat.hpp>

#include <string>
#include <cmath>

#include <boost/optional.hpp>

struct OfflineParameters
{
    unsigned int oversampling;
    double mesh_resolution;

    std::string basis_export_file;
    std::string basis_import_file;

    unsigned int dense_fallback_threshold;
    double iterative_tolerance;

    OfflineParameters()
            : oversampling(0),
              mesh_resolution(0.0),
              dense_fallback_threshold(300),
              iterative_tolerance(10.0 * std::numeric_limits<double>::epsilon())
    { }

    OfflineParameters & with_oversampling(unsigned int oversampling)
    {
        this->oversampling = oversampling;
        return *this;
    }

    OfflineParameters & with_mesh_resolution(double mesh_resolution)
    {
        this->mesh_resolution = mesh_resolution;
        return *this;
    }

    OfflineParameters & with_basis_export_file(std::string path)
    {
        this->basis_export_file = path;
        return *this;
    }

    OfflineParameters & with_basis_import_file(std::string path)
    {
        this->basis_import_file = path;
        return *this;
    }

    OfflineParameters & with_dense_fallback_threshold(unsigned int threshold)
    {
        this->dense_fallback_threshold = threshold;
        return *this;
    }

    OfflineParameters & with_iterative_tolerance(double iterative_tolerance)
    {
        this->iterative_tolerance = iterative_tolerance;
        return *this;
    }
};

struct OnlineParameters
{
    double end_time;
    uint64_t sample_count;
    int load_quadrature_strength;
    bool use_coarse_rhs;
    bool use_coarse_mass_matrix;
    double iterative_tolerance;
    bool measure_error;
    double max_error_before_abort;

    std::string integrator_name;

    OnlineParameters()
            : end_time(0.0),
              sample_count(0),
              load_quadrature_strength(4),
              use_coarse_rhs(false),
              use_coarse_mass_matrix(false),
              iterative_tolerance(10.0 * std::numeric_limits<double>::epsilon()),
              measure_error(true),
              max_error_before_abort(std::numeric_limits<double>::max())
    {}

    OnlineParameters & with_end_time(double end_time)
    {
        this->end_time = end_time;
        return *this;
    }

    OnlineParameters & with_sample_count(uint64_t sample_count)
    {
        this->sample_count = sample_count;
        return *this;
    }

    OnlineParameters & with_integrator_name(std::string name)
    {
        this->integrator_name = name;
        return *this;
    }

    OnlineParameters & with_coarse_rhs(bool use_coarse_rhs)
    {
        this->use_coarse_rhs = use_coarse_rhs;
        return *this;
    }

    OnlineParameters & with_coarse_mass_matrix(bool use_coarse_mass_matrix)
    {
        this->use_coarse_mass_matrix = use_coarse_mass_matrix;
        return *this;
    }

    OnlineParameters & with_iterative_tolerance(double iterative_tolerance)
    {
        this->iterative_tolerance = iterative_tolerance;
        return *this;
    }

    OnlineParameters & with_error_measurement(bool measure_error)
    {
        this->measure_error = measure_error;
        return *this;
    }

    double dt() const
    {
        return end_time / (sample_count - 1);
    }
};

struct ExperimentInput
{
    std::string                         name;
    OfflineParameters                   offline_parameters;
    boost::optional<OnlineParameters>   online_parameters;

    ExperimentInput & with_name(std::string name)
    {
        this->name = name;
        return *this;
    }

    ExperimentInput & with_offline_parameters(OfflineParameters parameters)
    {
        this->offline_parameters = parameters;
        return *this;
    }

    ExperimentInput & with_online_parameters(OnlineParameters parameters)
    {
        this->online_parameters = parameters;
        return *this;
    }
};

struct MeshDetails
{
    int num_coarse_vertices;
    int num_coarse_elements;
    int num_fine_vertices;
    int num_fine_elements;

    // h is diameter of element
    double h_max_coarse;
    double h_min_coarse;
    double h_max_fine;
    double h_min_fine;

    MeshDetails() : num_coarse_vertices(0),
                    num_coarse_elements(0),
                    num_fine_vertices(0),
                    num_fine_elements(0),
                    h_max_coarse(0.0),
                    h_min_coarse(0.0),
                    h_max_fine(0.0),
                    h_min_fine(0.0)
    { }
};

std::pair<double, double> extremal_diameters(const crest::IndexedMesh<double, int> & mesh)
{
    double hmin_squared = std::numeric_limits<double>::max();
    double hmax_squared = 0.0;

    for (int element = 0; element < mesh.num_elements(); ++element)
    {
        const auto triangle = mesh.triangle_for(element);
        const auto diameter_squared = crest::diameter_squared(triangle);
        if (diameter_squared > hmax_squared) {
            hmax_squared = diameter_squared;
        }
        if (diameter_squared < hmin_squared) {
            hmin_squared = diameter_squared;
        }
    }

    return std::make_pair(std::sqrt(hmin_squared), std::sqrt(hmax_squared));
};

MeshDetails details_from_meshes(const crest::IndexedMesh<double, int> & coarse,
                                const crest::IndexedMesh<double, int> & fine)
{
    MeshDetails details;
    details.num_coarse_elements = coarse.num_elements();
    details.num_coarse_vertices = coarse.num_vertices();
    details.num_fine_elements = fine.num_elements();
    details.num_fine_vertices = fine.num_vertices();

    std::tie(details.h_min_coarse, details.h_max_coarse) = extremal_diameters(coarse);
    std::tie(details.h_min_fine, details.h_max_fine) = extremal_diameters(fine);

    return details;
}

struct ErrorSummary
{
    double l2;
    double h1;
    double h1_semi;

    ErrorSummary & with_l2(double error)
    {
        this->l2 = error;
        return *this;
    }

    ErrorSummary & with_h1(double error)
    {
        this->h1 = error;
        return *this;
    }

    ErrorSummary & with_h1_semi(double error)
    {
        this->h1_semi = error;
        return *this;
    }
};

struct OfflineTiming
{
    double mesh_construction;
    double basis_construction;
    double total;

    OfflineTiming() : mesh_construction(0.0), basis_construction(0.0), total(0.0) {}
};

struct OfflineResult
{
    MeshDetails mesh_details;
    OfflineTiming timing;

    std::unordered_map<std::string, crest::AccumulatedDensityHistogram> stats;

    OfflineResult & with_mesh_details(MeshDetails mesh_details)
    {
        this->mesh_details = mesh_details;
        return *this;
    }

    OfflineResult & with_timing(OfflineTiming timing)
    {
        this->timing = timing;
        return *this;
    }

    OfflineResult & with_stats(std::unordered_map<std::string, crest::AccumulatedDensityHistogram> stats)
    {
        this->stats = stats;
        return *this;
    }
};

typedef crest::wave::SolveTiming OnlineTiming;

struct OnlineResult
{
    ErrorSummary error_summary;
    OnlineTiming timing;
    bool converged;

    OnlineResult & with_error_summary(ErrorSummary summary)
    {
        this->error_summary = summary;
        return *this;
    }

    OnlineResult & with_timing(OnlineTiming timing)
    {
        this->timing = timing;
        return *this;
    }

    OnlineResult & with_convergence(bool converged)
    {
        this->converged = converged;
        return *this;
    }

    OnlineResult() : converged(false) {}
};

struct ExperimentResult
{
    std::string                         name;
    OfflineParameters                   offline_parameters;
    boost::optional<OnlineParameters>   online_parameters;
    OfflineResult                       offline_result;
    boost::optional<OnlineResult>       online_result;

    ExperimentResult & with_name(std::string name)
    {
        this->name = name;
        return *this;
    }

    ExperimentResult & with_offline_parameters(OfflineParameters param)
    {
        this->offline_parameters = param;
        return *this;
    }

    ExperimentResult & with_online_parameters(OnlineParameters param)
    {
        this->online_parameters = param;
        return *this;
    }

    ExperimentResult & with_online_parameters(boost::optional<OnlineParameters> param)
    {
        this->online_parameters = param;
        return *this;
    }

    ExperimentResult & with_offline_result(OfflineResult result)
    {
        this->offline_result = result;
        return *this;
    }

    ExperimentResult & with_online_result(OnlineResult result)
    {
        this->online_result = result;
        return *this;
    }

    ExperimentResult & with_online_result(boost::optional<OnlineResult> result)
    {
        this->online_result = result;
        return *this;
    }
};

void verify_parameter_validity(const OfflineParameters & parameters);
void verify_parameter_validity(const OnlineParameters & parameters);

class Experiment
{
public:
    virtual ~Experiment() {}

    OfflineResult run_offline(const OfflineParameters & parameters)
    {
        crest::Timer timer;
        verify_parameter_validity(parameters);
        auto result = solve_offline(parameters);
        result.timing.total = timer.elapsed();
        return result;
    }

    OnlineResult run_online(const OnlineParameters & parameters,
                            crest::wave::Integrator<double> & integrator)
    {
        verify_parameter_validity(parameters);
        return solve_online(parameters, integrator);
    }

protected:
    virtual OfflineResult solve_offline(const OfflineParameters & parameters) = 0;
    virtual OnlineResult solve_online(const OnlineParameters & parameters,
                                      crest::wave::Integrator<double> & integrator) = 0;

    /**
     * Helper function for implementing solve()
     */
    template <typename BasisImpl, typename Function2dt, typename Function2dt_x, typename Function2dt_y>
    OnlineResult solve_and_analyze(const Function2dt & u,
                                   const Function2dt_x & u_x,
                                   const Function2dt_y & u_y,
                                   const OnlineParameters & parameters,
                                   const crest::Basis<double, BasisImpl> & basis,
                                   const crest::wave::InitialConditions<double> & initial_conditions,
                                   const crest::wave::ConstrainedSystem<double> & system,
                                   crest::wave::Integrator<double> & integrator,
                                   const crest::wave::Initializer<double> & initializer,
                                   double assembly_time) const
    {
        const auto dt = parameters.dt();
        crest::wave::Parameters<double> param;
        param.num_samples = parameters.sample_count;
        param.dt = dt;

        if (parameters.measure_error) {
            const auto error_transformer = crest::wave::make_error_transformer<4>(
                    basis, u, u_x, u_y, parameters.max_error_before_abort);
            auto result = crest::wave::solve(system, initial_conditions,
                                             integrator, initializer, param, error_transformer);

            // Augment the result with the given assembly time. Yes, I know, this is very hacky and
            // very poorly designed (last minute additions)
            result.timing.assembly_time = assembly_time;

            if (result.converged) {

                std::vector<double> l2_error_at_each_step;
                std::vector<double> h1_semi_error_at_each_step;
                std::vector<double> h1_error_at_each_step;

                for (const auto sample_error : result.result)
                {
                    l2_error_at_each_step.push_back(sample_error.l2);
                    h1_semi_error_at_each_step.push_back(sample_error.h1_semi);
                    h1_error_at_each_step.push_back(sample_error.h1);
                }

                ErrorSummary errors;

                switch (param.num_samples) {
                    case 1:
                        errors.h1 = h1_error_at_each_step.back();
                        errors.l2 = l2_error_at_each_step.back();
                        errors.h1_semi = h1_semi_error_at_each_step.back();
                        break;

                    default:
                        // TODO: Support even number of samples. Simpsons will currently throw when it
                        // is given an even number of samples
                        errors.l2 = crest::composite_simpsons(l2_error_at_each_step.begin(),
                                                              l2_error_at_each_step.end(),
                                                              dt);
                        errors.h1_semi = crest::composite_simpsons(h1_semi_error_at_each_step.begin(),
                                                                   h1_semi_error_at_each_step.end(),
                                                                   dt);
                        errors.h1 = crest::composite_simpsons(h1_error_at_each_step.begin(),
                                                              h1_error_at_each_step.end(),
                                                              dt);
                        break;
                }

                return OnlineResult()
                        .with_error_summary(errors)
                        .with_timing(result.timing)
                        .with_convergence(result.converged);
            } else {
                // If the simulation did not converge, we do not want to compute an error at all,
                // particularly because we might have an odd number of samples (in which case the above would throw)
                // This last part is of course unfortunate, but I don't want to spend time on fixing that at the moment.
                return OnlineResult()
                        .with_timing(result.timing)
                        .with_convergence(result.converged);
            }

        } else {
            const auto ignore_transformer = crest::wave::IgnoreTransformer<double>();
            auto result = crest::wave::solve(system, initial_conditions, integrator,
                                             initializer, param, ignore_transformer);
            // Augment the result with the given assembly time. Yes, I know, this is very hacky and
            // very poorly designed (last minute additions)
            result.timing.assembly_time = assembly_time;
            return OnlineResult()
                    .with_timing(result.timing)
                    .with_convergence(result.converged);
        };
    };
};

inline void verify_parameter_validity(const OnlineParameters & parameters)
{
    if (parameters.end_time <= 0.0 || !std::isfinite(parameters.end_time))
    {
        throw std::invalid_argument("Final time T must be finite and greater than zero.");
    }

    if (parameters.sample_count < 1) {
        throw std::invalid_argument("Number of samples N must be 1 or greater.");
    }

    if (parameters.sample_count % 2 == 0) {
        throw std::invalid_argument("Number of samples must be an odd number.");
    }
}

inline void verify_parameter_validity(const OfflineParameters & parameters)
{
    if (parameters.mesh_resolution <= 0.0 || !std::isfinite(parameters.mesh_resolution))
    {
        throw std::invalid_argument("Spatial resolution h must be finite and greater than zero.");
    }
}


text:
using Newtonsoft.Json;

namespace CSharpTradeOffers.Community
{
    public class Profile
    {
        public const string Type = "profileSave";

        // ToDo: Better Property Names for the weblinks need to be checked with the input ids from the profile edit page
        [JsonProperty("weblink_1_title")]
        public string Weblink1Title { get; set; }
        [JsonProperty("weblink_1_url")]
        public string Weblink1Url { get; set; }

        [JsonProperty("weblink_2_title")]
        public string Weblink2Title { get; set; }
        [JsonProperty("weblink_2_url")]
        public string Weblink2Url { get; set; }

        [JsonProperty("weblink_3_title")]
        public string Weblink3Title { get; set; }
        [JsonProperty("weblink_3_url")]
        public string Weblink3Url { get; set; }

        [JsonProperty("personaName")]
        public string PersonaName { get; set; }
        [JsonProperty("real_name")]
        public string RealName { get; set; }

        [JsonProperty("country")]
        public string Country { get; set; }
        [JsonProperty("state")]
        public string State { get; set; }
        [JsonProperty("city")]
        public string City { get; set; }

        [JsonProperty("customURL")]
        public string CustomUrl { get; set; }

        [JsonProperty("summary")]
        public string Summary { get; set; }

        [JsonProperty("favorite_badge_badgeid")]
        public ulong? FavoriteBadgeBadgeId { get; set; }
        [JsonProperty("favorite_badge_communityitemid")]
        public ulong? FavoriteBadgeCommunityItemId { get; set; }

        [JsonProperty("primary_group_steamid")]
        public ulong? PrimaryGroupSteamId { get; set; }
    }
}


text:
Allows to set one property in {@link _cWidget#properties}, but instead of parsing - it will treat it's content as text.
This way, text inside the directive does not require to be quoted.

##Example

<lavabuild:template_result as="single_view">
<text_input>
	<x:property_string name="value">I'm a "happy" string.</x:property_string>
</text_input>
</lavabuild:template_result>

Note: the content of the directive is parsed just like any other part of template, so this will NOT work
(cause inside there is a character sequence which represents an opening block):

```xml
<x:property_string name="value">this is a very {#bad()} string</x:property_string>
```

The right way:

{literal:}

  1

<x:property_string name="value">{literal:}this is a very {#bad()} string{:literal}</x:property_string>

{:literal}


text:
import d3 from 'd3';
import _ from 'lodash';

import {View} from './view';
import * as level from '../level';

export class LevelSelectorView extends View {
  get title() {
    return 'Quantum game';
  }
  get className() {
    return 'view--level-selector';
  }
  initialize() {
    const listOfElements = d3.select('.level-selector > ul')
      .selectAll('li')
      .data(level.levels)
      .enter()
      .append('li')
      .attr('class', 'level-item unselectable')
      .text((d) => `[${d.group}] ${d.i}. ${d.name} `)
      .on('click', (d) => {
        this.game.gameBoard.loadLevel(d.id);
        this.game.setView('game');
      });

    // as of now it is a version for developers
    // for users - graphical icons (of the new elements) or display:none;
    const elementsEncountered = {};
    level.levels.forEach((d) => {
      d.newTiles = [];
      d.tiles.forEach((tile) => {
        if (!_.has(elementsEncountered, tile.name)) {
          elementsEncountered[tile.name] = true;
          d.newTiles.push(tile.name);
        }
      });
    });

    listOfElements.append('span')
      .style('font-size', '1.5vh')
      .text((d) =>
        _(d.tiles)
          .groupBy('name')
          .keys()
          .filter((tile) => !_.includes(['Detector', 'Rock', 'Source'], tile))
          .value()
          .join(' ')
      );

    listOfElements.append('span')
      .style('font-size', '1.5vh')
      .text((d) => d.newTiles.length ? ` (NEW: ${d.newTiles.join(' ')})` : '');

    this.bindMenuEvents()
  }
  bindMenuEvents() {
    d3.select('.view--level-selector .bottom-bar__back-to-game-button').on('click', () => {
      this.game.setView('game');
    });
  }
}


text:
<!doctype html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no">
<title>Mobilebone.js API文档-Mobilebone.VERSION</title>
<link rel="stylesheet" href="../src/mobilebone.css">
<link rel="stylesheet" href="docs.css">

Mobilebone.VERSION

Mobilebone当前的版本号。

属性

只读

属性值

目前的版本号是:


text:
from xml.sax import make_parser
from xml.sax.handler import feature_namespaces
import xml.sax.handler

def readGo(filename):
    """DEPRECATED"""
    terms = Dict(default=[])

    for line in file(filename):
        if "GI:" in line:# or "KEGG:" in line:
            continue
        tokens = line.rstrip().split("\t")
        try:
            terms[tokens[0]].append(tokens[4])
        except:
            print line

    return terms

def readCommonNames(filename):
    """DEPRECATED"""
    commonNames = {}

    for line in file(filename):
        tokens = line.rstrip().split("\t")

        if tokens[1] != '-':
            commonNames[tokens[0]] = tokens[1]
    return commonNames

class GoTerm:
    def __init__(self):
        self.accession = ""
        self.name = ""
        self.definition = ""
        self.is_a = []
        self.part_of = []
        self.synonym = []

class AllTerm(GoTerm):
    def __init__(self):
        GoTerm.__init__(self)

        self.accession = "all"
        self.name = "all"
        self.defintion = "top-level term"

class GoHandler(xml.sax.handler.ContentHandler):
    def __init__(self, base):
        self.terms = {}
        self.term = None
        self.elm = ""
        self.base = base

    def startElement(self, name, attrs):
        if name == "go:term":
            self.term = GoTerm()
        elif name == "go:is_a":
            ref = attrs["rdf:resource"]
            if ref.startswith(self.base):
                self.term.is_a.append(ref[len(self.base):])
        elif name == "go:part_of":
            ref = attrs["rdf:resource"]
            if ref.startswith(self.base):
                self.term.part_of.append(ref[len(self.base):])
        self.elm = name

    def endElement(self, name):
        if name == "go:term":
            self.terms[self.term.accession] = self.term
        self.elm = ""

    def characters(self, text):
        if self.elm == "go:accession":
            self.term.accession += text
        elif self.elm == "go:name":
            self.term.name += text
        elif self.elm == "go:definition":
            self.term.definition += text
        elif self.elm == "go:synonym":
            if 'GO' in text:
                self.term.synonym.append(text)

class GoDatabase:
    def __init__(self, filename):
        # Create a parser
        parser = make_parser()

        # Tell the parser we are not interested in XML namespaces
        parser.setFeature(feature_namespaces, 0)

        # Create the handler
        dh = GoHandler("http://www.geneontology.org/go#")

        # Tell the parser to use our handler
        parser.setContentHandler(dh)

        # Parse the input
        parser.parse(filename)

        self.terms = dh.terms

        # add top level term
        self.terms["all"] = AllTerm()

    def getAllParents(self, goid, touched=None, count=0, ret=True):
        if touched == None:
            touched = {}

        if goid in self.terms:
            term = self.terms[goid]
            parents =  term.is_a + term.part_of

            for parent in parents:
                if parent not in touched and parent != "all":
                    touched[parent] = count
                    count += 1

            for parent in parents:
                self.getAllParents(parent, touched, count, False)

        if ret:
            parents = touched.keys()
            parents.sort(key=lambda x: touched[x])
            return parents


text:
require 'earth_tools/result/base'

module EarthTools::Result

  ##
  # The sunrise/sunset result.
  class SunriseSunset < Base

    ##
    # The date of the sunrise/sunset data as a hash
    # @return [Hash] Hash containing year, month, and day as integers
    def date
      { :year => Time.now.year, :month => @data['date']['month'].to_i, :day => @data['date']['day'].to_i }
    end

    ##
    # The sunrise time
    # @return [Time] the sunrise time
    def sunrise
      create_time @data['morning']['sunrise']
    end

    ##
    # The sunset time
    # @return [Time] the sunset time
    def sunset
      create_time @data['evening']['sunset']
    end

    ##
    # The twilight time for the specified time and type
    # @param [Symbol] the time (:morning or :evening)
    # @param [Symbol] the type (:astronomical, :civil, or :nautical)
    # @return [Time] the requested twilight time
    def twilight(time, type)
      time = time.to_sym if time.is_a?(String)
      type = type.to_sym if type.is_a?(String)
      send "#{time}_#{type}_twilight" if [:morning, :evening].include?(time) && [:astronomical, :civil, :nautical].include?(type)
    end

    ##
    # The morning twilight time for the specified type
    # @param [Symbol] the type of morning twilight time
    # @return [Time] the specified morning twilight time
    def morning_twilight(type)
      twilight :morning, type
    end

    ##
    # The evening twilight time for the specified type
    # @param [Symbol] the type of evening twilight time
    # @return [Time] the specified evening twilight time
    def evening_twilight(type)
      twilight :evening, type
    end

    ##
    # The evening astronomical twilight time
    # @return [Time] the astronomical twilight time for the evening
    def evening_astronomical_twilight
      create_time @data['evening']['twilight']['astronomical']
    end

    ##
    # The evening civil twilight time
    # @return [Time] the civil twilight time for the evening
    def evening_civil_twilight
      create_time @data['evening']['twilight']['civil']
    end

    ##
    # The evening nautical twilight time
    # @return [Time] the nautical twilight time for the evening
    def evening_nautical_twilight
      create_time @data['evening']['twilight']['nautical']
    end

    ##
    # The morning astronomical twilight time
    # @return [Time] the astronomical twilight time for the morning
    def morning_astronomical_twilight
      create_time @data['morning']['twilight']['astronomical']
    end

    ##
    # The morning civil twilight time
    # @return [Time] the civil twilight time for the morning
    def morning_civil_twilight
      create_time @data['morning']['twilight']['civil']
    end

    ##
    # The morning nautical twilight time
    # @return [Time] the nautical twilight time for the morning
    def morning_nautical_twilight
      create_time @data['morning']['twilight']['nautical']
    end

    ##
    # The number of hours offset from UTC disregarding any correction for daylight saving time
    # See {http://en.wikipedia.org/wiki/UTC_offset}.
    # @return [Integer] the UTC offset
    def utc_offset
      @data['date']['timezone'].to_i
    end

    private

    ##
    # Parses time
    # @returns [Time] The parse time
    def create_time(time)
      times = time.split(':').collect{|s| s.to_i}
      Time.new(date[:year], date[:month], date[:day], times[0], times[1], times[2], utc_offset * 3600)
    end

  end
end


text:
.class public Landroid/filterfw/core/FinalPort;
.super Landroid/filterfw/core/FieldPort;
.source "FinalPort.java"

# direct methods
.method public constructor <init>(Landroid/filterfw/core/Filter;Ljava/lang/String;Ljava/lang/reflect/Field;Z)V
    .registers 5
    .param p1, "filter"    # Landroid/filterfw/core/Filter;
    .param p2, "name"    # Ljava/lang/String;
    .param p3, "field"    # Ljava/lang/reflect/Field;
    .param p4, "hasDefault"    # Z

    .prologue
    .line 28
    invoke-direct {p0, p1, p2, p3, p4}, Landroid/filterfw/core/FieldPort;-><init>(Landroid/filterfw/core/Filter;Ljava/lang/String;Ljava/lang/reflect/Field;Z)V

    .line 27
    return-void
.end method

# virtual methods
.method protected declared-synchronized setFieldFrame(Landroid/filterfw/core/Frame;Z)V
    .registers 6
    .param p1, "frame"    # Landroid/filterfw/core/Frame;
    .param p2, "isAssignment"    # Z

    .prologue
    monitor-enter p0

    .line 33
    :try_start_1
    invoke-virtual {p0}, Landroid/filterfw/core/FinalPort;->assertPortIsOpen()V

    .line 34
    invoke-virtual {p0, p1, p2}, Landroid/filterfw/core/FinalPort;->checkFrameType(Landroid/filterfw/core/Frame;Z)V

    .line 35
    iget-object v0, p0, Landroid/filterfw/core/FinalPort;->mFilter:Landroid/filterfw/core/Filter;

    invoke-virtual {v0}, Landroid/filterfw/core/Filter;->getStatus()I

    move-result v0

    if-eqz v0, :cond_33

    .line 36
    new-instance v0, Ljava/lang/RuntimeException;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v2, "Attempting to modify "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p0}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v1

    const-string/jumbo v2, "!"

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-direct {v0, v1}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;)V

    throw v0
    :try_end_30
    .catchall {:try_start_1 .. :try_end_30} :catchall_30

    :catchall_30
    move-exception v0

    monitor-exit p0

    throw v0

    .line 38
    :cond_33
    :try_start_33
    invoke-super {p0, p1, p2}, Landroid/filterfw/core/FieldPort;->setFieldFrame(Landroid/filterfw/core/Frame;Z)V

    .line 39
    const/4 v0, 0x0

    invoke-super {p0, v0}, Landroid/filterfw/core/FieldPort;->transfer(Landroid/filterfw/core/FilterContext;)V
    :try_end_3a
    .catchall {:try_start_33 .. :try_end_3a} :catchall_30

    monitor-exit p0

    .line 32
    return-void
.end method

.method public toString()Ljava/lang/String;
    .registers 3

    .prologue
    .line 45
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v1, "final "

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-super {p0}, Landroid/filterfw/core/FieldPort;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method


text:
namespace metis::storage {

class METIS_API IODevicePrivate : public Private {
 public:
  IODevicePrivate(Opaque *publ, MemPool *mempool) : Private(publ, mempool) {
  }

  ~IODevicePrivate();

#if METIS_STATS_ENABLE
  usize read_count{0};
  usize read_amount{0};
  usize write_count{0};
  usize write_amount{0};
#endif  // METIS_STATS_ENABLE
};

}  // namespace metis::storage


text:
#ifndef MBED_CMSIS_NVIC_H
#define MBED_CMSIS_NVIC_H

#define NVIC_NUM_VECTORS             (182)
#define NVIC_RAM_VECTOR_ADDRESS      0x20000000    // Location of vectors in RAM

#endif


text: @(contactForm: Form[Contact])


text:
#ifndef IEEE802_1X_H
#define IEEE802_1X_H

struct hostapd_data;
struct sta_info;
struct eapol_state_machine;
struct hostapd_config;
struct hostapd_bss_config;

#ifdef _MSC_VER
#pragma pack(push, 1)
#endif /* _MSC_VER */

/* RFC 3580, 4. RC4 EAPOL-Key Frame */

struct ieee802_1x_eapol_key {
	u8 type;
	u16 key_length;
	u8 replay_counter[8]; /* does not repeat within the life of the keying
			       * material used to encrypt the Key field;
			       * 64-bit NTP timestamp MAY be used here */
	u8 key_iv[16]; /* cryptographically random number */
	u8 key_index; /* key flag in the most significant bit:
		       * 0 = broadcast (default key),
		       * 1 = unicast (key mapping key); key index is in the
		       * 7 least significant bits */
	u8 key_signature[16]; /* HMAC-MD5 message integrity check computed with
			       * MS-MPPE-Send-Key as the key */

	/* followed by key: if packet body length = 44 + key length, then the
	 * key field (of key_length bytes) contains the key in encrypted form;
	 * if packet body length = 44, key field is absent and key_length
	 * represents the number of least significant octets from
	 * MS-MPPE-Send-Key attribute to be used as the keying material;
	 * RC4 key used in encryption = Key-IV + MS-MPPE-Recv-Key */
} STRUCT_PACKED;

#ifdef _MSC_VER
#pragma pack(pop)
#endif /* _MSC_VER */

void ieee802_1x_receive(struct hostapd_data *hapd, const u8 *sa, const u8 *buf,
			size_t len);
void ieee802_1x_new_station(struct hostapd_data *hapd, struct sta_info *sta);
void ieee802_1x_free_station(struct sta_info *sta);

void ieee802_1x_tx_key(struct hostapd_data *hapd, struct sta_info *sta);
void ieee802_1x_abort_auth(struct hostapd_data *hapd, struct sta_info *sta);
void ieee802_1x_set_sta_authorized(struct hostapd_data *hapd,
				   struct sta_info *sta, int authorized);
void ieee802_1x_dump_state(FILE *f, const char *prefix, struct sta_info *sta);
int ieee802_1x_init(struct hostapd_data *hapd);
void ieee802_1x_deinit(struct hostapd_data *hapd);
int ieee802_1x_tx_status(struct hostapd_data *hapd, struct sta_info *sta,
			 const u8 *buf, size_t len, int ack);
u8 * ieee802_1x_get_identity(struct eapol_state_machine *sm, size_t *len);
u8 * ieee802_1x_get_radius_class(struct eapol_state_machine *sm, size_t *len,
				 int idx);
const u8 * ieee802_1x_get_key(struct eapol_state_machine *sm, size_t *len);
void ieee802_1x_notify_port_enabled(struct eapol_state_machine *sm,
				    int enabled);
void ieee802_1x_notify_port_valid(struct eapol_state_machine *sm,
				  int valid);
void ieee802_1x_notify_pre_auth(struct eapol_state_machine *sm, int pre_auth);
int ieee802_1x_get_mib(struct hostapd_data *hapd, char *buf, size_t buflen);
int ieee802_1x_get_mib_sta(struct hostapd_data *hapd, struct sta_info *sta,
			   char *buf, size_t buflen);
void hostapd_get_ntp_timestamp(u8 *buf);
char *eap_type_text(u8 type);

const char *radius_mode_txt(struct hostapd_data *hapd);
int radius_sta_rate(struct hostapd_data *hapd, struct sta_info *sta);

#endif /* IEEE802_1X_H */


text:
class GitRepository
  attr_reader :repository_dir

  def initialize(repository_dir)
    raise "nil repository passed to GitRepository constructor" if repository_dir.nil?
    @repository_dir = repository_dir
  end

  # Use a hash to only have a single instance per physical repository dir
  @@instances = {}
  def self.get(repository_dir)
    if ! @@instances.has_key?(repository_dir)
      @@instances[repository_dir] = GitRepository.new(repository_dir)
    end

    return @@instances[repository_dir]
  end

  def in_repository
    Dir.chdir(@repository_dir) { yield }
  end

  def git_diff_tree(from, to=nil)
    in_repository do
      if to.nil?
        return `git-diff-tree --no-commit-id -C --cc #{from}`
      else
        return `git-diff-tree --no-commit-id -C --cc #{from}..#{to}`
      end
    end
  end

  def git_show(sha1)
    if @blob_cache.nil?
      @blob_cache = {}
    end

    return @blob_cache[sha1] if @blob_cache.has_key?(sha1)

    @blob_cache[sha1] = CACHE.cache_block('git_show/' + @repository_dir + '/' + sha1, 0) do
      in_repository do
        `git-show --pretty=raw #{sha1}`
      end
    end
  end

  def git_get_full_revision(partial_sha1)
    cache_key = 'partial_revision/' + @repository_dir + '/' + partial_sha1

    CACHE.cache_block(cache_key, 0) do
      in_repository do
        rev = `git-rev-list -n 1 #{partial_sha1} || echo -n FAILURE`
        (rev != 'FAILURE') ? rev.chomp : nil
      end
    end
  end

  def git_diff_status_from_parent(sha1)
    in_repository do
      stat = `git diff #{sha1}^ #{sha1} --name-status`

      return stat.map do |line|
        match = line.chomp.match(/^(.)\s+(.+)$/)
        { :change_type => match[1],
          :file => match[2]
        }
      end
    end
  end

  def git_rev_list(from, to)
    in_repository do
      `git-rev-list #{from}..#{to}`.split("\n")
    end
  end

  def git_rev_parse(rev_id)
    cache_key = 'rev_parse/' + @repository_dir + '/' + rev_id

    if !CACHE.nil?
      if result = CACHE[cache_key]
        return result
      end
    end

    rev = in_repository do
      `git-rev-list --max-count=1 #{rev_id} 2>/dev/null`.chomp
    end

    if !CACHE.nil?
      CACHE[cache_key] = rev
    end

    return rev.empty? ? nil : rev
  end

  def git_list_branches
    in_repository do
      `git-branch --no-color`.split("\n").map do |line|
        raise "Bad line from git-branch: #{line}" unless line.match(/^..(.+)$/)
        $1
      end
    end
  end

  def git_add_remote(name, url)
    in_repository do
      `git-remote add #{name} #{url} 2>/dev/null`
    end
  end

  def git_fetch_from(other_repository)

    # Only do this once
    if !@has_fetched_from.nil? &&
        @has_fetched_from.has_key?(other_repository)
      return
    end

    in_repository do
      output = `git-fetch #{other_repository} 2>&1`
      raise "Error from git-fetch: #{output}" if $? != 0
    end

    if @has_fetched_from.nil?
      @has_fetched_from = {}
    end
    @has_fetched_from[other_repository] = 1
  end

  def git_log(from, to, flags="")
    in_repository do
      output = `git-log #{flags} #{from}..#{to}`
      raise "Error from git-log: #{output}" if $? != 0
      output
    end
  end

  def branch(name)
    GitBranch.new(self, name)
  end

end