text:
using namespace llvm;

// This function tries to add a symbolic operand in place of the immediate
// Value in the MCInst. The immediate Value has had any PC adjustment made by
// the caller. If the instruction is a branch instruction then IsBranch is true,
// else false. If the getOpInfo() function was set as part of the
// setupForSymbolicDisassembly() call then that function is called to get any
// symbolic information at the Address for this instruction. If that returns
// non-zero then the symbolic information it returns is used to create an MCExpr
// and that is added as an operand to the MCInst. If getOpInfo() returns zero
// and IsBranch is true then a symbol look up for Value is done and if a symbol
// is found an MCExpr is created with that, else an MCExpr with Value is
// created. This function returns true if it adds an operand to the MCInst and
// false otherwise.
bool MCExternalSymbolizer::tryAddingSymbolicOperand(MCInst &MI,
                                                    raw_ostream &cStream,
                                                    int64_t Value,
                                                    uint64_t Address,
                                                    bool IsBranch,
                                                    uint64_t Offset,
                                                    uint64_t InstSize) {
  struct LLVMOpInfo1 SymbolicOp;
  std::memset(&SymbolicOp, '\0', sizeof(struct LLVMOpInfo1));
  SymbolicOp.Value = Value;

  if (!GetOpInfo ||
      !GetOpInfo(DisInfo, Address, Offset, InstSize, 1, &SymbolicOp)) {
    // Clear SymbolicOp.Value from above and also all other fields.
    std::memset(&SymbolicOp, '\0', sizeof(struct LLVMOpInfo1));

    // At this point, GetOpInfo() did not find any relocation information about
    // this operand and we are left to use the SymbolLookUp() call back to guess
    // if the Value is the address of a symbol.  In the case this is a branch
    // that always makes sense to guess.  But in the case of an immediate it is
    // a bit more questionable if it is an address of a symbol or some other
    // reference.  So if the immediate Value comes from a width of 1 byte,
    // InstSize, we will not guess it is an address of a symbol.  Because in
    // object files assembled starting at address 0 this usually leads to
    // incorrect symbolication.
    if (!SymbolLookUp || (InstSize == 1 && !IsBranch))
      return false;

    uint64_t ReferenceType;
    if (IsBranch)
       ReferenceType = LLVMDisassembler_ReferenceType_In_Branch;
    else
       ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
    const char *ReferenceName;
    const char *Name = SymbolLookUp(DisInfo, Value, &ReferenceType, Address,
                                    &ReferenceName);
    if (Name) {
      SymbolicOp.AddSymbol.Name = Name;
      SymbolicOp.AddSymbol.Present = true;
      // If Name is a C++ symbol name put the human readable name in a comment.
      if(ReferenceType == LLVMDisassembler_ReferenceType_DeMangled_Name)
        cStream << ReferenceName;
    }
    // For branches always create an MCExpr so it gets printed as hex address.
    else if (IsBranch) {
      SymbolicOp.Value = Value;
    }
    if(ReferenceType == LLVMDisassembler_ReferenceType_Out_SymbolStub)
      cStream << "symbol stub for: " << ReferenceName;
    else if(ReferenceType == LLVMDisassembler_ReferenceType_Out_Objc_Message)
      cStream << "Objc message: " << ReferenceName;
    if (!Name && !IsBranch)
      return false;
  }

  const MCExpr *Add = nullptr;
  if (SymbolicOp.AddSymbol.Present) {
    if (SymbolicOp.AddSymbol.Name) {
      StringRef Name(SymbolicOp.AddSymbol.Name);
      MCSymbol *Sym = Ctx.GetOrCreateSymbol(Name);
      Add = MCSymbolRefExpr::Create(Sym, Ctx);
    } else {
      Add = MCConstantExpr::Create((int)SymbolicOp.AddSymbol.Value, Ctx);
    }
  }

  const MCExpr *Sub = nullptr;
  if (SymbolicOp.SubtractSymbol.Present) {
      if (SymbolicOp.SubtractSymbol.Name) {
      StringRef Name(SymbolicOp.SubtractSymbol.Name);
      MCSymbol *Sym = Ctx.GetOrCreateSymbol(Name);
      Sub = MCSymbolRefExpr::Create(Sym, Ctx);
    } else {
      Sub = MCConstantExpr::Create((int)SymbolicOp.SubtractSymbol.Value, Ctx);
    }
  }

  const MCExpr *Off = nullptr;
  if (SymbolicOp.Value != 0)
    Off = MCConstantExpr::Create(SymbolicOp.Value, Ctx);

  const MCExpr *Expr;
  if (Sub) {
    const MCExpr *LHS;
    if (Add)
      LHS = MCBinaryExpr::CreateSub(Add, Sub, Ctx);
    else
      LHS = MCUnaryExpr::CreateMinus(Sub, Ctx);
    if (Off)
      Expr = MCBinaryExpr::CreateAdd(LHS, Off, Ctx);
    else
      Expr = LHS;
  } else if (Add) {
    if (Off)
      Expr = MCBinaryExpr::CreateAdd(Add, Off, Ctx);
    else
      Expr = Add;
  } else {
    if (Off)
      Expr = Off;
    else
      Expr = MCConstantExpr::Create(0, Ctx);
  }

  Expr = RelInfo->createExprForCAPIVariantKind(Expr, SymbolicOp.VariantKind);
  if (!Expr)
    return false;

  MI.addOperand(MCOperand::CreateExpr(Expr));
  return true;
}

// This function tries to add a comment as to what is being referenced by a load
// instruction with the base register that is the Pc.  These can often be values
// in a literal pool near the Address of the instruction. The Address of the
// instruction and its immediate Value are used as a possible literal pool entry.
// The SymbolLookUp call back will return the name of a symbol referenced by the
// literal pool's entry if the referenced address is that of a symbol. Or it
// will return a pointer to a literal 'C' string if the referenced address of
// the literal pool's entry is an address into a section with C string literals.
// Or if the reference is to an Objective-C data structure it will return a
// specific reference type for it and a string.
void MCExternalSymbolizer::tryAddingPcLoadReferenceComment(raw_ostream &cStream,
                                                           int64_t Value,
                                                           uint64_t Address) {
  if (SymbolLookUp) {
    uint64_t ReferenceType = LLVMDisassembler_ReferenceType_In_PCrel_Load;
    const char *ReferenceName;
    (void)SymbolLookUp(DisInfo, Value, &ReferenceType, Address, &ReferenceName);
    if(ReferenceType == LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr)
      cStream << "literal pool symbol address: " << ReferenceName;
    else if(ReferenceType ==
            LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr) {
      cStream << "literal pool for: \"";
      cStream.write_escaped(ReferenceName);
      cStream << "\"";
    }
    else if(ReferenceType ==
            LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref)
      cStream << "Objc cfstring ref: @\"" << ReferenceName << "\"";
    else if(ReferenceType ==
            LLVMDisassembler_ReferenceType_Out_Objc_Message)
      cStream << "Objc message: " << ReferenceName;
    else if(ReferenceType ==
            LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref)
      cStream << "Objc message ref: " << ReferenceName;
    else if(ReferenceType ==
            LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref)
      cStream << "Objc selector ref: " << ReferenceName;
    else if(ReferenceType ==
            LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref)
      cStream << "Objc class ref: " << ReferenceName;
  }
}

namespace llvm {
MCSymbolizer *createMCSymbolizer(StringRef TT, LLVMOpInfoCallback GetOpInfo,
                                 LLVMSymbolLookupCallback SymbolLookUp,
                                 void *DisInfo,
                                 MCContext *Ctx,
                                 MCRelocationInfo *RelInfo) {
  assert(Ctx && "No MCContext given for symbolic disassembly");

  return new MCExternalSymbolizer(*Ctx,
                                  std::unique_ptr<MCRelocationInfo>(RelInfo),
                                  GetOpInfo, SymbolLookUp, DisInfo);
}
}


text:
/*
 * $Id: SchemaDateTimeException.hpp 568078 2007-08-21 11:43:25Z amassari $
 */

#if !defined(SCHEMA_DATETIME_EXCEPTION_HPP)
#define SCHEMA_DATETIME_EXCEPTION_HPP

#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/XMLException.hpp>

XERCES_CPP_NAMESPACE_BEGIN

MakeXMLException(SchemaDateTimeException, XMLUTIL_EXPORT)

XERCES_CPP_NAMESPACE_END

#endif

redpajama_set_name: RedPajamaGithub


text:
@charset "gb2312";
/* »ÃµÆƬ */
.banner { height : 280px; width : 670px; overflow : hidden; }
#slide-runner { height : 280px; width : 670px; overflow : hidden; position : absolute; }
#slide-holder img { position : absolute; }
#slide-controls { left : 0; bottom : 0px; width : 670px; height : 34px; display : none; position : absolute; background : url(../images/slide-bg.png) 0 0; }
#slide-controls p.text { float : left; color : #fff; display : inline; line-height : 16px; margin : 10px 0 0 20px; }
#slide-controls p#slide-nav { float : right; height : 24px; display : inline; margin : 5px 0px 0 0; }
#slide-controls p#slide-nav a { float : left; width : 24px; height : 24px; display : inline; font-size : 11px; margin : 0 5px 0 0; line-height : 24px; text-align : center; color: #fff }
#slide-controls p#slide-nav a.on { background-position : 0 -24px; }
#slide-controls p#slide-nav a { background-image : url(../images/silde-nav.png); }
/*×óÎÄÕÂÁбí*/
.topnews { margin: 20px 0; }
.topnews h2 { font-size: 16px; font-weight: bold; line-height: 36px; color: #333; border-bottom: #db6d4c 4px solid; }
.topnews h2 b { }
.topnews h2 span { float: right; font-size: 12px; font-weight: normal; }
.topnews h2 span a { display: inline-block; padding: 0 5px; }
.topnews h2 span a:hover { color: #000 }
.blogs { padding: 30px 0; position: relative; border-bottom: #CCC 1px solid; overflow: hidden }
.blogs h3 { font-size: 16px; font-weight: bold; transition: all .5s; margin-bottom: 10px }
.blogs h3 a { color: #474645; }
.blogs h3 a:hover { color: #066; text-decoration: underline }
.blogs ul { float: right; line-height: 22px; width: 100%; color: #756F71;}
.autor { overflow: hidden; clear: both; margin: 10px 0; display: inline-block; color: #838383; width: 100%;  }
.autor span { margin: 0 10px 0 0; padding-left: 20px }
.autor span a { color: #759b08; }
.autor span a:hover { text-decoration: underline }
.lm { background: url(../images/newsbg01.png) no-repeat left center }
.dtime { background: url(../images/newsbg02.png) no-repeat left center }
.viewnum { background: url(../images/newsbg04.png) no-repeat left center }
.pingl { background: url(../images/newsbg03.png) no-repeat left center }
.tit01 h3 { line-height: 40px; color: #38485A; font-size: 18px; border-bottom: 1px solid #E6E6E6; height: 40px }
/* ¹Ø×¢ÎÒÑùʽ */
.gzwm ul { width: 100%; margin: 30px 0; overflow: hidden }
.gzwm li { width: 52px; margin: 0 18px 0 5px; float: left; }
.gzwm li a { color: #747F8C; width: 52px; text-align: center; padding-top: 60px; float: left; }
.gzwm .rss { background: url(../images/ico_04_1.jpg) no-repeat scroll 0% 0% transparent; }
.gzwm .rss:hover { color: #000; background: url(../images/ico_04.png) no-repeat scroll 0% 0% transparent; }
.gzwm .xlwb { background: url(../images/ico_05_1.jpg) no-repeat scroll 0% 0% transparent; }
.gzwm .xlwb:hover { color: #000; background: url(../images/ico_05.png) no-repeat scroll 0% 0% transparent; }
.gzwm .txwb { background: url(../images/ico_06_1.jpg) no-repeat scroll 0% 0% transparent; }
.gzwm .txwb:hover { color: #000; background: url(../images/ico_06.png) no-repeat scroll 0% 0% transparent; }
.gzwm .wx { background: url(../images/ico_07_1.jpg) no-repeat scroll 0% 0% transparent; }
.gzwm .wx:hover { color: #000; background: url(../images/ico_07.png) no-repeat scroll 0% 0% transparent; }
/*ͼÎÄÁбí*/
.tuwen { width: 100%; clear: both; overflow: hidden; margin: 20px 0 }
.tuwen h3 { line-height: 40px; color: #38485A; font-size: 18px; border-bottom: 1px solid #E6E6E6; height: 40px; margin-bottom: 30px }
.tuwen li { overflow: hidden; clear: both; margin-bottom: 10px }
.tuwen li img { width: 70px; float: left; margin-right: 15px }
.tuwen li b { overflow: hidden; width: 100%; font-weight: normal; color: #333; font-size: 14px; line-height: 30px }
.tuwen li a b:hover { text-decoration: underline; color: #F60 }
.tuwen li span { color: #999; margin-right: 10px }
.tuwen p { margin-top: 5px }
.tulanmu { background: url(../images/lanmbq.png) no-repeat center left; padding-left: 17px }
.tulanmu a { color: #999; }
.tulanmu a:hover { color: #066 }
.tutime { background: url(../images/datepng.png) no-repeat left center; padding-left: 15px }
.tuwen li:hover { background: #f4f3f3 }
/*Ê×Ò³ÓÒ²à¹ã¸æ 300*/
.ad { width: 300px; overflow: hidden; margin: 30px 0 }
.ad img { width: 300px; }
/*ÓÑÇéÁ´½Ó*/
.links { width: 100%; overflow: hidden; clear: both }
.links h3 { line-height: 40px; color: #38485A; font-size: 18px; border-bottom: 1px solid #E6E6E6; height: 40px; margin-bottom: 20px }
.links h3 span { float: right; font-size: 12px; }
.links h3 span a { color: #999; padding: 0 5px }
.links h3 span a:hover { color: #F60; text-decoration: underline }
.links ul { background: #f9f9f9; padding: 10px; overflow: hidden; border: #e9e9e9 1px solid }
.links ul li { float: left; padding: 5px 8px }
.links ul li a:hover { color: #000 }


text:
define(['knockout', 'knockback'], function(ko, kb) {

	var viewOptions = {
		events : {
			"domReady" : "onReady",
		},
		onReady : function() {

		},
		initialize : function() {
			var self = this;
			$(this.el).ready(function() {
				self.on("domReady");
			});

		},
		render : function() {
			var self = this;

			$(this.el).load(window.app.viewFolder + "/"+ this.viewName +".html", function() {
				self.onReady("domReady");
			});
		}
	};

	var view = Backbone.View.extend(viewOptions);

	return {
		extend : function(options) {
			options = options || {};

			if (options.events) {
				options.events = _.extend(viewOptions.events, options.events);
			}
			options._super = view;

			return view.extend(options);
		}
	}

});


text:
<?xml version="1.0"?>
<tool_dependency>
    <package name="libtool" version="2.4">
        <repository name="package_libtool_2_4" owner="iuc" prior_installation_required="True" />
    </package>
    <package name="xz" version="5.0.5">
        <install version="1.0">
            <actions>
                <action type="download_by_url" sha256sum="166c48d2842519bc4f96333bff9e265f8cdda44d38e40594ef3f9bbb52890490">https://depot.galaxyproject.org/software/xz/xz_5.0.5_src_all.tar.bz2</action>

                <action type="set_environment_for_install">
                    <repository name="package_bzlib_1_0" owner="iuc">
                        <package name="bzlib" version="1.0.6" />
                    </repository>
                </action>

                <action type="autoconf" />
                <action type="set_environment">
                    <environment_variable name="LD_LIBRARY_PATH" action="prepend_to">$INSTALL_DIR/lib</environment_variable>
                    <environment_variable name="XZ_ROOT_PATH" action="set_to">$INSTALL_DIR</environment_variable>
                    <environment_variable name="C_INCLUDE_PATH" action="prepend_to">$INSTALL_DIR/include</environment_variable>
                    <environment_variable name="CPLUS_INCLUDE_PATH" action="prepend_to">$INSTALL_DIR/include</environment_variable>
                </action>
            </actions>
        </install>
        <readme>
        XZ Utils is free general-purpose data compression software with high compression ratio. XZ Utils were written for POSIX-like systems,
        but also work on some not-so-POSIX systems. XZ Utils are the successor to LZMA Utils.

        http://tukaani.org/xz/
        </readme>
    </package>
</tool_dependency>


text:
package org.jitsi.service.neomedia;

import java.awt.*;
import org.jitsi.service.neomedia.codec.*;
import org.jitsi.utils.*;

/**
 * An interface that exposes the <tt>Component</tt>s used in media
 * configuration user interfaces.
 *
 * @author Boris Grozev
 */
public interface MediaConfigurationService
{
    /**
     * Returns a <tt>Component</tt> for audio configuration
     *
     * @return A <tt>Component</tt> for audio configuration
     */
    public Component createAudioConfigPanel();

    /**
     * Returns a <tt>Component</tt> for video configuration
     *
     * @return A <tt>Component</tt> for video configuration
     */
    public Component createVideoConfigPanel();

    /**
     * Returns a <tt>Component</tt> for encodings configuration (either audio
     * or video)
     *
     * @param mediaType The type of media -- either MediaType.AUDIO or
     * MediaType.VIDEO
     * @param encodingConfiguration The <tt>EncodingConfiguration</tt> instance
     * to use.
     * @return The <tt>Component</tt> for encodings configuration
     */
    public Component createEncodingControls(
            MediaType mediaType,
            EncodingConfiguration encodingConfiguration);

    /**
     * Returns the <tt>MediaService</tt> instance
     *
     * @return the <tt>MediaService</tt> instance
     */
    public MediaService getMediaService();
}


text:
"""
Module for sending messages to Pushbullet (https://www.pushbullet.com)

.. versionadded:: 2015.8.0

Requires an ``api_key`` in ``/etc/salt/minion``:

.. code-block:: yaml

    pushbullet:
      api_key: 'ABC123abc123ABC123abc123ABC123ab'

For example:

.. code-block:: yaml

    pushbullet:
      device: "Chrome"
      title: "Example push message"
      body: "Message body."

"""

import logging

try:
    import pushbullet

    HAS_PUSHBULLET = True
except ImportError:
    HAS_PUSHBULLET = False

log = logging.getLogger(__name__)

def __virtual__():
    if not HAS_PUSHBULLET:
        return (False, "Missing pushbullet library.")
    if not __salt__["config.get"]("pushbullet.api_key") and not __salt__["config.get"](
        "pushbullet:api_key"
    ):
        return (False, "Pushbullet API Key Unavailable, not loading.")
    return True

class _SaltPushbullet:
    def __init__(self, device_name):
        api_key = __salt__["config.get"]("pushbullet.api_key") or __salt__[
            "config.get"
        ]("pushbullet:api_key")
        self.pb = pushbullet.Pushbullet(api_key)
        self.target = self._find_device_by_name(device_name)

    def push_note(self, title, body):
        push = self.pb.push_note(title, body, device=self.target)
        return push

    def _find_device_by_name(self, name):
        for dev in self.pb.devices:
            if dev.nickname == name:
                return dev

def push_note(device=None, title=None, body=None):
    """
    Pushing a text note.

    :param device:   Pushbullet target device
    :param title:    Note title
    :param body:     Note body

    :return:            Boolean if message was sent successfully.

    CLI Example:

    .. code-block:: bash

        salt "*" pushbullet.push_note device="Chrome" title="Example title" body="Example body."
    """
    spb = _SaltPushbullet(device)
    res = spb.push_note(title, body)

    return res


text:
<?php

namespace Ladybug\Type\ObjectType;

interface VisibilityInterface
{
    const VISIBILITY_PUBLIC = 0;
    const VISIBILITY_PROTECTED = 1;
    const VISIBILITY_PRIVATE = 2;

    /**
     * Gets visibility.
     *
     * @return int
     */
    public function getVisibility();

    /**
     * Sets visibility.
     * @param int $visibility
     */
    public function setVisibility($visibility);
}


text:
void initializePID3(PID_3DOF &PID){
	Eigen::Vector3d zeros = Eigen::Vector3d::Zero();

	PID.e_prop = zeros;
	PID.e_deriv = zeros;
	PID.e_integ = zeros;
}

//Sets integral error to zero
void resetIntegralErrorPID3(PID_3DOF &PID){
	PID.e_integ = Eigen::Vector3d::Zero();
}

//Update Kp, Ki and Kd in the PID
void updateControlParamPID3(PID_3DOF &PID,
	                       Eigen::Vector3d K_p,
	                       Eigen::Vector3d K_i,
	                       Eigen::Vector3d K_d,
	                       Eigen::Vector3d maxInteg){
	PID.K_p = K_p;
	PID.K_d = K_d;
	PID.K_i = K_i;
	PID.maxInteg = maxInteg;
}

//Update all errors
void updateErrorPID3(PID_3DOF &PID,
	                Eigen::Vector3d feedForward,
	                Eigen::Vector3d e_prop,
	                Eigen::Vector3d e_deriv,
	                float dt){
	PID.feedForward = feedForward;
	PID.e_prop = e_prop;
	PID.e_deriv = e_deriv;
	PID.e_integ = PID.e_integ+(e_prop*dt); //e_integ = e_integ + e_prop*dt

	//Saturate integral error between lower and upper bounds
	for (int i = 0; i < 3; i++){
		PID.e_integ(i) = saturate(PID.e_integ(i),
			                     -PID.maxInteg(i),
			                      PID.maxInteg(i));
	}
}

//Calculate output of PID
Eigen::Vector3d outputPID3(PID_3DOF PID){
	Eigen::Vector3d PID_out;
	PID_out =  PID.feedForward +
			   PID.e_prop.cwiseProduct(PID.K_p) +
			   PID.e_deriv.cwiseProduct(PID.K_d) +
			   PID.e_integ.cwiseProduct(PID.K_i);
	return PID_out;
}

//Initialize parameters for position control
void initializePosControlParam(PosControlParam &Param,
	                           double mass, double gz,
	                           double thrustRatio){
	Param.mass = mass;
	Param.gz = gz;
	Param.thrustRatio = thrustRatio;

}

void readROSparameterServer(PID_3DOF &PID, PosControlParam &Param){

  double mass, gz, thrustRatio;
  Eigen::Vector3d Kp, Ki, Kd, maxInteg;

  //Get system properties
  ros::param::get("/px4_control_node/mass", mass);
  ros::param::get("/px4_control_node/gz", gz);
  ros::param::get("/px4_control_node/thrustRatio", thrustRatio);
  initializePosControlParam(Param, mass, gz, thrustRatio);

  //Get controller parameters
  ros::param::get("/px4_control_node/kpx", Kp[0]);
  ros::param::get("/px4_control_node/kpy", Kp[1]);
  ros::param::get("/px4_control_node/kpz", Kp[2]);
  ros::param::get("/px4_control_node/kvx", Kd[0]);
  ros::param::get("/px4_control_node/kvy", Kd[1]);
  ros::param::get("/px4_control_node/kvz", Kd[2]);
  ros::param::get("/px4_control_node/kix", Ki[0]);
  ros::param::get("/px4_control_node/kiy", Ki[1]);
  ros::param::get("/px4_control_node/kiz", Ki[2]);
  ros::param::get("/px4_control_node/maxInteg_x", maxInteg[0]);
  ros::param::get("/px4_control_node/maxInteg_y", maxInteg[1]);
  ros::param::get("/px4_control_node/maxInteg_z", maxInteg[2]);
  updateControlParamPID3(PID, Kp, Ki, Kd, maxInteg);

  //Print all parameter values
  ROS_INFO("mass: %f\tgz: %f\tthrustRatio: %f", mass, gz, thrustRatio);
  ROS_INFO("Kp: %f,\t%f,\t%f", Kp[0], Kp[1], Kp[2]);
  ROS_INFO("Kd: %f,\t%f,\t%f", Kd[0], Kd[1], Kd[2]);
  ROS_INFO("Ki: %f,\t%f,\t%f", Ki[0], Ki[1], Ki[2]);
  ROS_INFO("maxInteg: %f,\t%f,\t%f\n", maxInteg[0], maxInteg[1], maxInteg[2]);

}

void PosController(nav_msgs::Odometry Odom,
	               PVA_structure PVA_ref,
	               PosControlParam Param,
	               double dt,
	               PID_3DOF &PosPID,
	               geometry_msgs::PoseStamped &PoseRef,
	               std_msgs::Float64 &refThrust){

	//Local variables
	double m = Param.mass;
	double gz = Param.gz;
	double maxThrust = Param.thrustRatio*m*gz;

	double yawRef;							//Desired yaw
	Eigen::Vector3d e_Pos, e_Vel; 			//error in position and velocity
	Eigen::Vector3d PosRef, VelRef, AccRef;	//Desired PVA
	Eigen::Vector3d Pos, Vel;				//Current PV
	Eigen::Vector3d feedForward;			//Feedforward vector
	Eigen::Vector3d Fdes;					//Desired force in body frame
	Eigen::Vector3d z_w, z_b;				//z direction in world and body frames
	Eigen::Matrix3d Rbw;					//Rotation from body to world
	Eigen::Matrix3d Rdes;					//Desired rotation
	Eigen::Vector3d z_bdes, x_cdes, y_bdes, x_bdes;

	//Desired states
	PosRef << PVA_ref.Pos.pose.position.x,
	          PVA_ref.Pos.pose.position.y,
	          PVA_ref.Pos.pose.position.z;
	VelRef << PVA_ref.Vel.twist.linear.x,
	          PVA_ref.Vel.twist.linear.y,
	          PVA_ref.Vel.twist.linear.z;
	AccRef << PVA_ref.Acc.accel.linear.x,
	          PVA_ref.Acc.accel.linear.y,
	          PVA_ref.Acc.accel.linear.z;
	yawRef = getHeadingFromQuat(PVA_ref.Pos.pose.orientation);

	//Current states
	Pos << Odom.pose.pose.position.x,
	       Odom.pose.pose.position.y,
	       Odom.pose.pose.position.z;
	Vel << Odom.twist.twist.linear.x,
	       Odom.twist.twist.linear.y,
	       Odom.twist.twist.linear.z;

	//Rotation matrix and z frame vectors
	Rbw = quat2rot(Odom.pose.pose.orientation);
	z_w << 0, 0, 1;
	z_b = Rbw*z_w;

	//Calculate errors (Obs: Odom might be in body or inertial frame)
	e_Pos = PosRef - Pos;
	std::string frameId = Odom.header.frame_id;
  	std::string childFrameId = Odom.child_frame_id;
	if(frameId.compare(childFrameId) == 0){
		e_Vel = VelRef - Vel;
	}
	else{
		e_Vel = VelRef - Rbw*Vel;
	}

	//Translational controller
	feedForward = m*gz*z_w + m*AccRef;
	updateErrorPID3(PosPID, feedForward, e_Pos, e_Vel, dt);
	Fdes = outputPID3(PosPID);

	//Desired thrust in body frame
	refThrust.data = min(max(Fdes.dot(z_b), 0.0),maxThrust)/maxThrust;

	//Find desired attitude from desired force and yaw angle
	z_bdes = normalizeVector3d(Fdes);
	x_cdes << cos(yawRef), sin(yawRef), 0;
	y_bdes = normalizeVector3d(z_bdes.cross(x_cdes));
	x_bdes = y_bdes.cross(z_bdes);
	Rdes << x_bdes, y_bdes, z_bdes;

	//Set references
	PoseRef.pose.position = PVA_ref.Pos.pose.position;
	PoseRef.pose.orientation = rot2quat(Rdes);
}


text:
<?php

namespace backend\modules\i18n\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\modules\i18n\models\I18nMessage;

/**
 * I18nMessageSearch represents the model behind the search form about `backend\modules\i18n\models\I18nMessage`.
 */
class I18nMessageSearch extends I18nMessage
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['language', 'translation', 'sourceMessage', 'category'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = I18nMessage::find()->with('sourceMessageModel')->joinWith('sourceMessageModel');

        $dataProvider = new ActiveDataProvider([
            'query' => $query
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id
        ]);

        $query->andFilterWhere(['like', 'language', $this->language])
            ->andFilterWhere(['like', 'translation', $this->translation])
            ->andFilterWhere(['like', '{{%i18n_source_message}}.message', $this->sourceMessage])
            ->andFilterWhere(['like', '{{%i18n_source_message}}.category', $this->category]);

        return $dataProvider;
    }
}


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />

/**
 * @ignore
 * animate on single property
 * @author yiminghe@gmail.com
 */
KISSY.add('anim/timer/fx', function (S, Dom, undefined) {
    var logger = S.getLogger('s/aim/timer/fx');

    function load(self, cfg) {
        S.mix(self, cfg);
        self.pos = 0;
        self.unit = self.unit || '';
    }

    /**
     * basic animation about single css property or element attribute
     * @class KISSY.Anim.Fx
     * @private
     */
    function Fx(cfg) {
        load(this, cfg);
    }

    Fx.prototype = {
        // default to dom anim
        isCustomFx: 0,

        constructor: Fx,

        /**
         * reset config.
         * @param cfg
         */
        load: function (cfg) {
            load(this, cfg);
        },

        /**
         * process current anim frame.
         * @param pos
         */
        frame: function (pos) {
            if (this.pos === 1) {
                return;
            }

            var self = this,
                anim = self.anim,
                prop = self.prop,
                node = anim.node,
                from = self.from,
                propData = self.propData,
                to = self.to;

            if (pos === undefined) {
                pos = getPos(anim, propData);
            }

            self.pos = pos;

            if (from === to || pos === 0) {
                return;
            }

            var val = self.interpolate(from, to, self.pos);

            self.val = val;

            if (propData.frame) {
                propData.frame.call(self, anim, self);
            }
            // in case completed in frame
            else if (!self.isCustomFx) {
                if (val === /**@type Number @ignore*/undefined) {
                    // 插值出错,直接设置为最终值
                    self.pos = 1;
                    val = to;
                    logger.warn(prop + ' update directly ! : ' + val + ' : ' + from + ' : ' + to);
                } else {
                    val += self.unit;
                }
                self.val = val;
                if (isAttr(node, prop)) {
                    Dom.attr(node, prop, val, 1);
                } else {
                    Dom.css(node, prop, val);
                }
            }
        },

        /**
         * interpolate function
         *
         * @param {Number} from current css value
         * @param {Number} to end css value
         * @param {Number} pos current position from easing 0~1
         * @return {Number} value corresponding to position
         */
        interpolate: function (from, to, pos) {
            // 默认只对数字进行 easing
            if ((typeof from === 'number') &&
                (typeof to === 'number')) {
                return /**@type Number @ignore*/Math.round((from + (to - from) * pos) * 1e5) / 1e5;
            } else {
                return /**@type Number @ignore*/undefined;
            }
        },

        /**
         * current value
         *
         */
        cur: function () {
            var self = this,
                prop = self.prop,
                node = self.anim.node;
            //不是css 或者 attribute 的缓动
            if (self.isCustomFx) {
                return node[prop] || 0;
            }
            else if (isAttr(node, prop)) {
                return Dom.attr(node, prop, undefined, 1);
            } else {
                var parsed,
                    r = Dom.css(node, prop);
                // Empty strings, null, undefined and 'auto' are converted to 0,
                // complex values such as 'rotate(1rad)' or '0px 10px' are returned as is,
                // simple values such as '10px' are parsed to Float.
                return isNaN(parsed = parseFloat(r)) ?
                    !r || r === 'auto' ? 0 : r
                    : parsed;
            }
        }
    };

    function isAttr(node, prop) {
        // support scrollTop/Left now!
        if ((!node.style || node.style[ prop ] == null) &&
            Dom.attr(node, prop, undefined, 1) != null) {
            return 1;
        }
        return 0;
    }

    function getPos(anim, propData) {
        var t = S.now(),
            runTime,
            startTime = anim.startTime,
            delay = propData.delay,
            duration = propData.duration;
        runTime = t - startTime - delay;
        if (runTime <= 0) {
            return 0;
        } else if (runTime >= duration) {
            return 1;
        } else {
            return propData.easing(runTime / duration);
        }
    }

    Fx.Factories = {};

    Fx.getFx = function (cfg) {
        var Constructor = Fx,
            SubClass;
        if (!cfg.isCustomFx && (SubClass = Fx.Factories[cfg.prop])) {
            Constructor = SubClass
        }
        return new Constructor(cfg);
    };

    return Fx;
}, {
    requires: ['dom']
});
/*
 TODO
 支持 transform ,ie 使用 matrix
 - http://shawphy.com/2011/01/transformation-matrix-in-front-end.html
 - http://www.cnblogs.com/winter-cn/archive/2010/12/29/1919266.html
 - 标准:http://www.zenelements.com/blog/css3-transform/
 - ie: http://www.useragentman.com/IETransformsTranslator/
 - wiki: http://en.wikipedia.org/wiki/Transformation_matrix
 - jq 插件: http://plugins.jquery.com/project/2d-transform
 */


text:
package org.itsnat.droid.impl.dom.layout;

/**
 * Created by jmarranz on 29/10/14.
 */
public abstract class DOMScript
{
    protected volatile String code;

    public DOMScript()
    {
    }

    public DOMScript(String code)
    {
        this.code = code;
    }

    public String getCode()
    {
        return code;
    }
}


text:
<?php
declare(strict_types=1);

use app\actions\entire\KDWinAction;
use app\assets\EntireKDWinAsset;
use app\assets\TableResponsiveForceAsset;
use app\components\widgets\AdWidget;
use app\components\widgets\SnsWidget;
use app\components\widgets\kdWin\KDWinTable;
use app\components\widgets\kdWin\LegendWidget;
use yii\bootstrap\ActiveForm;
use yii\helpers\Html;

$this->context->layout ='main';

$title = Yii::t('app', 'Winning Percentage based on K/D');
$this->title = implode(' | ', [
    Yii::$app->name,
    $title,
]);

$this->registerMetaTag(['name' => 'twitter:card', 'content' => 'summary']);
$this->registerMetaTag(['name' => 'twitter:title', 'content' => $title]);
$this->registerMetaTag(['name' => 'twitter:description', 'content' => $title]);
$this->registerMetaTag(['name' => 'twitter:site', 'content' => '@stat_ink']);

TableResponsiveForceAsset::register($this);
?>

<?= Html::encode($title) ?>

<?= Html::encode(Yii::t(
    'app',
    'This website has color-blind support. Please check "Color-Blind Support" in the "Username/Guest" menu of the navbar to enable it.'
  )) ?>

  <?= AdWidget::widget() . "\n" ?>
  <?= SnsWidget::widget() . "\n" ?>

<?= Html::a(
        Html::encode('Splatoon 2'),
        ['entire/kd-win2'],
      ) ?>

<?= Html::encode('Splatoon') ?>

  <?php $_ = ActiveForm::begin([
    'id' => 'filter-form',
    'action' => ['entire/kd-win'],
    'method' => 'get',
    'layout' => 'inline',
  ]); echo "\n" ?>
    <?= implode(' ', [
      $_->field($filter, 'map')->dropDownList($maps)->label(false),
      $_->field($filter, 'weapon')->dropDownList($weapons)->label(false),
      Html::submitButton(
        Yii::t('app', 'Summarize'),
        ['class' => 'btn btn-primary']
      ),
    ]) . "\n" ?>
  <?php ActiveForm::end(); echo "\n" ?>

  <?= LegendWidget::widget() . "\n" ?>

<?php foreach ($rules as $rule) { ?>

      <?= Html::tag(
        'h2',
        Html::encode($rule->name),
        ['class' => $rule->key, 'id' => $rule->key]
      ) . "\n" ?>

        <?= KDWinTable::widget([
          'data' => $rule->data,
          'limit' => KDWinAction::KD_LIMIT,
        ]) . "\n" ?>

<?php } ?>


text:
"enable aexpr";

import { trackInstance } from 'active-group';

export function getValueClass() {
  return class ValueClass {
    constructor(value) {
      this.value = value;
      trackInstance.call(ValueClass, this);
    }
  }
}


text:
ActiveRecord::Schema.define(version: 20170814234454) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "messages", force: :cascade do |t|
    t.bigint "user_id"
    t.bigint "room_id"
    t.string "content"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["room_id"], name: "index_messages_on_room_id"
    t.index ["user_id"], name: "index_messages_on_user_id"
  end

  create_table "questions", force: :cascade do |t|
    t.bigint "user_id"
    t.integer "question_id"
    t.string "response"
    t.integer "emotional_tone_1"
    t.integer "emotional_tone_2"
    t.integer "language_tone_1"
    t.integer "language_tone_2"
    t.integer "social_tone_1"
    t.integer "social_tone_2"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id"], name: "index_questions_on_user_id"
  end

  create_table "rooms", force: :cascade do |t|
    t.string "title"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "top_answers", force: :cascade do |t|
    t.bigint "user_id"
    t.integer "top_emotional_tone"
    t.integer "top_language_tone"
    t.integer "top_social_tone"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id"], name: "index_top_answers_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer "sign_in_count", default: 0, null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.inet "current_sign_in_ip"
    t.inet "last_sign_in_ip"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

end


text:
package io.dockstore.webservice.jdbi;

import io.dockstore.common.DescriptorLanguage;
import io.dockstore.webservice.core.AppTool;
import io.dockstore.webservice.core.SourceControlConverter;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.hibernate.SessionFactory;

public class AppToolDAO extends EntryDAO<AppTool> {
    public AppToolDAO(SessionFactory factory) {
        super(factory);
    }

    @SuppressWarnings("checkstyle:ParameterNumber")
    protected Root<AppTool> generatePredicate(DescriptorLanguage descriptorLanguage, String registry, String organization, String name, String toolname, String description, String author, Boolean checker,
        CriteriaBuilder cb, CriteriaQuery<?> q) {

        final SourceControlConverter converter = new SourceControlConverter();
        final Root<AppTool> entryRoot = q.from(AppTool.class);

        Predicate predicate = getWorkflowPredicate(descriptorLanguage, registry, organization, name, toolname, description, author, checker, cb, converter, entryRoot);

        // apptool is never a checker workflow
        if (checker != null && checker) {
            predicate = cb.isFalse(cb.literal(true));
        }

        q.where(predicate);
        return entryRoot;
    }
}


text:
import tempfile
import traceback
import uuid

import boto3
import botocore.exceptions

def get_s3_bucket(s3_provider):
    try:
        s3 = boto3.resource(
            's3',
            aws_access_key_id=s3_provider.access_key_id,
            aws_secret_access_key=s3_provider.secret_access_key
        )
        try:
            bucket = s3.create_bucket(
                Bucket=s3_provider.bucket_name,
                CreateBucketConfiguration={'LocationConstraint': 'eu-west-1'}
            )
        except:
            bucket = s3.Bucket(s3_provider.bucket_name)
            exists = True
            try:
                s3.meta.client.head_bucket(Bucket=s3_provider.bucket_name)
            except botocore.exceptions.ClientError as e:
                # If a client error is thrown, then check if it was a 404 error.
                # If it was a 404 error, then the bucket does not exist
                error_code = int(e.response['Error']['Code'])
                if error_code == 404:
                    exists = False

                # We raise anyway, whatever the error
                raise
    except:
        print(traceback.format_exc())
        return None
    else:
        return s3

def check_s3_credentials(s3_provider):
    s3 = get_s3_bucket(s3_provider)
    if s3 is None:
        raise RuntimeError('Invalid S3 credentials for %d' % (s3_provider.pk,))

def upload_file_to_s3(datafile, s3_provider, tempfile_path):
    s3 = get_s3_bucket(s3_provider)

    if s3 is None:
        raise RuntimeError('Could not get S3 connection')

    storage_key = str(uuid.uuid4())
    s3.Object(s3_provider.bucket_name, storage_key).put(Body=open(tempfile_path, 'rb'))

    return storage_key

def retrieve_file_from_s3(datafile, s3_provider):
    s3 = get_s3_bucket(s3_provider)

    if s3 is None:
        print('Could not get S3 connection')
        return None

    else:
        try:
            with tempfile.NamedTemporaryFile(delete=False) as tmpfile:
                tmpfilename = tmpfile.name

            s3.Bucket(s3_provider.bucket_name).download_file(datafile.storage_key, tmpfilename)
            return tmpfilename

        except:
            print('Download failed: %s' % traceback.format_exc())
            return None

def delete_file_from_s3(s3_provider, storage_key):
    s3 = get_s3_bucket(s3_provider)

    if s3 is None:
        print('Could not get S3 connection')
        return False

    else:
        try:
            s3.Object(s3_provider.bucket_name, storage_key).delete()
            return True
        except:
            print('Delete failed: %s' % traceback.format_exc())
            return False


text:
@implementation GroupOperationTest

- (instancetype) init
{
    self = [super init];
    if (self)
    {
        OPBlockOperation *block;
        for (int i = 0; i < 10; i++)
        {
            OPBlockOperation *previous = nil;
            if (block)
                previous = block;

            block = [[OPBlockOperation alloc] initWithBlock:^(void(^completion)(void)) {
                NSLog(@"Operation %i", i);
                completion();
            }];

            if (previous)
            {
                [block addDependency:previous];
            }

            [self addOperation:block];
        }
    }
    return self;
}

@end


text:
package org.talend.dataprep.dataset.store.metadata;

import static org.talend.dataprep.util.SortAndOrderHelper.getDataSetMetadataComparator;

import java.util.Comparator;
import java.util.function.Predicate;
import java.util.stream.Stream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.talend.dataprep.api.dataset.DataSetMetadata;
import org.talend.dataprep.lock.DistributedLock;
import org.talend.dataprep.util.SortAndOrderHelper.Order;
import org.talend.dataprep.util.SortAndOrderHelper.Sort;
import org.talend.tql.bean.BeanPredicateVisitor;
import org.talend.tql.parser.Tql;

public abstract class ObjectDataSetMetadataRepository extends DataSetMetadataRepositoryAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(ObjectDataSetMetadataRepository.class);

    protected abstract Stream<DataSetMetadata> source();

    @Override
    public boolean exist(String filter) {
        final Predicate<DataSetMetadata> accept =
                Tql.parse(filter).accept(new BeanPredicateVisitor<>(DataSetMetadata.class));
        return source().anyMatch(accept);
    }

    @Override
    public Stream<DataSetMetadata> list() {
        return source();
    }

    @Override
    public Stream<DataSetMetadata> list(String filter, Sort sortField, Order sortDirection) {
        final Predicate<DataSetMetadata> accept =
                Tql.parse(filter).accept(new BeanPredicateVisitor<>(DataSetMetadata.class));
        final Stream<DataSetMetadata> stream = source().filter(accept);
        if (sortField != null) {
            final Comparator<DataSetMetadata> dataSetMetadataComparator =
                    getDataSetMetadataComparator(sortField, sortDirection);
            return stream.sorted(dataSetMetadataComparator);
        } else {
            return stream;
        }
    }

    @Override
    public int size() {
        return (int) source().count();
    }

    @Override
    public void clear() {
        // Remove all data set (but use lock for remaining asynchronous processes).
        list().forEach(m -> {
            if (m != null) {
                final DistributedLock lock = createDatasetMetadataLock(m.getId());
                try {
                    lock.lock();
                    remove(m.getId());
                } finally {
                    lock.unlock();
                }
            }
        });
        LOGGER.debug("dataset metadata repository cleared.");
    }

    @Override
    public long countAllDataSetsSize() {
        return list().mapToLong(DataSetMetadata::getDataSetSize).sum();
    }

}


text:
<?php
/**
 * EmailPlan
 *
 * PHP version 5
 *
 * @category Class
 * @package  ultracart\v2
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * UltraCart Rest API V2
 *
 * UltraCart REST API Version 2
 *
 * OpenAPI spec version: 2.0.0
 * Contact: support@ultracart.com
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 * Swagger Codegen version: 2.4.15-SNAPSHOT
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace ultracart\v2\models;

use \ArrayAccess;
use \ultracart\v2\ObjectSerializer;

/**
 * EmailPlan Class Doc Comment
 *
 * @category Class
 * @package  ultracart\v2
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */
class EmailPlan implements ModelInterface, ArrayAccess
{
    const DISCRIMINATOR = null;

    /**
      * The original name of the model.
      *
      * @var string
      */
    protected static $swaggerModelName = 'EmailPlan';

    /**
      * Array of property to type mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerTypes = [
        'additional_customers' => 'int',
        'additional_emails' => 'int',
        'additional_fee' => 'float',
        'allow_list_import' => 'bool',
        'allow_tracking_emails' => 'bool',
        'customer_tiers' => '\ultracart\v2\models\EmailPlanAdditional[]',
        'initial_sending_limits' => 'int',
        'plan_customers' => 'int',
        'plan_emails' => 'int',
        'plan_name' => 'string',
        'plan_name_formatted' => 'string',
        'require_order_within_last_days' => 'int',
        'revenue_percent' => 'int',
        'spam_percent_limit' => 'int',
        'total_customers' => 'int',
        'total_emails' => 'int',
        'upgrade_to' => 'int'
    ];

    /**
      * Array of property to format mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerFormats = [
        'additional_customers' => 'int32',
        'additional_emails' => 'int32',
        'additional_fee' => null,
        'allow_list_import' => null,
        'allow_tracking_emails' => null,
        'customer_tiers' => null,
        'initial_sending_limits' => 'int32',
        'plan_customers' => 'int32',
        'plan_emails' => 'int32',
        'plan_name' => null,
        'plan_name_formatted' => null,
        'require_order_within_last_days' => 'int32',
        'revenue_percent' => 'int32',
        'spam_percent_limit' => 'int32',
        'total_customers' => 'int32',
        'total_emails' => 'int32',
        'upgrade_to' => 'int32'
    ];

    /**
     * Array of property to type mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerTypes()
    {
        return self::$swaggerTypes;
    }

    /**
     * Array of property to format mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerFormats()
    {
        return self::$swaggerFormats;
    }

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @var string[]
     */
    protected static $attributeMap = [
        'additional_customers' => 'additional_customers',
        'additional_emails' => 'additional_emails',
        'additional_fee' => 'additional_fee',
        'allow_list_import' => 'allow_list_import',
        'allow_tracking_emails' => 'allow_tracking_emails',
        'customer_tiers' => 'customer_tiers',
        'initial_sending_limits' => 'initial_sending_limits',
        'plan_customers' => 'plan_customers',
        'plan_emails' => 'plan_emails',
        'plan_name' => 'plan_name',
        'plan_name_formatted' => 'plan_name_formatted',
        'require_order_within_last_days' => 'require_order_within_last_days',
        'revenue_percent' => 'revenue_percent',
        'spam_percent_limit' => 'spam_percent_limit',
        'total_customers' => 'total_customers',
        'total_emails' => 'total_emails',
        'upgrade_to' => 'upgrade_to'
    ];

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @var string[]
     */
    protected static $setters = [
        'additional_customers' => 'setAdditionalCustomers',
        'additional_emails' => 'setAdditionalEmails',
        'additional_fee' => 'setAdditionalFee',
        'allow_list_import' => 'setAllowListImport',
        'allow_tracking_emails' => 'setAllowTrackingEmails',
        'customer_tiers' => 'setCustomerTiers',
        'initial_sending_limits' => 'setInitialSendingLimits',
        'plan_customers' => 'setPlanCustomers',
        'plan_emails' => 'setPlanEmails',
        'plan_name' => 'setPlanName',
        'plan_name_formatted' => 'setPlanNameFormatted',
        'require_order_within_last_days' => 'setRequireOrderWithinLastDays',
        'revenue_percent' => 'setRevenuePercent',
        'spam_percent_limit' => 'setSpamPercentLimit',
        'total_customers' => 'setTotalCustomers',
        'total_emails' => 'setTotalEmails',
        'upgrade_to' => 'setUpgradeTo'
    ];

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @var string[]
     */
    protected static $getters = [
        'additional_customers' => 'getAdditionalCustomers',
        'additional_emails' => 'getAdditionalEmails',
        'additional_fee' => 'getAdditionalFee',
        'allow_list_import' => 'getAllowListImport',
        'allow_tracking_emails' => 'getAllowTrackingEmails',
        'customer_tiers' => 'getCustomerTiers',
        'initial_sending_limits' => 'getInitialSendingLimits',
        'plan_customers' => 'getPlanCustomers',
        'plan_emails' => 'getPlanEmails',
        'plan_name' => 'getPlanName',
        'plan_name_formatted' => 'getPlanNameFormatted',
        'require_order_within_last_days' => 'getRequireOrderWithinLastDays',
        'revenue_percent' => 'getRevenuePercent',
        'spam_percent_limit' => 'getSpamPercentLimit',
        'total_customers' => 'getTotalCustomers',
        'total_emails' => 'getTotalEmails',
        'upgrade_to' => 'getUpgradeTo'
    ];

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @return array
     */
    public static function attributeMap()
    {
        return self::$attributeMap;
    }

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @return array
     */
    public static function setters()
    {
        return self::$setters;
    }

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @return array
     */
    public static function getters()
    {
        return self::$getters;
    }

    /**
     * The original name of the model.
     *
     * @return string
     */
    public function getModelName()
    {
        return self::$swaggerModelName;
    }

    /**
     * Associative array for storing property values
     *
     * @var mixed[]
     */
    protected $container = [];

    /**
     * Constructor
     *
     * @param mixed[] $data Associated array of property values
     *                      initializing the model
     */
    public function __construct(array $data = null)
    {
        $this->container['additional_customers'] = isset($data['additional_customers']) ? $data['additional_customers'] : null;
        $this->container['additional_emails'] = isset($data['additional_emails']) ? $data['additional_emails'] : null;
        $this->container['additional_fee'] = isset($data['additional_fee']) ? $data['additional_fee'] : null;
        $this->container['allow_list_import'] = isset($data['allow_list_import']) ? $data['allow_list_import'] : null;
        $this->container['allow_tracking_emails'] = isset($data['allow_tracking_emails']) ? $data['allow_tracking_emails'] : null;
        $this->container['customer_tiers'] = isset($data['customer_tiers']) ? $data['customer_tiers'] : null;
        $this->container['initial_sending_limits'] = isset($data['initial_sending_limits']) ? $data['initial_sending_limits'] : null;
        $this->container['plan_customers'] = isset($data['plan_customers']) ? $data['plan_customers'] : null;
        $this->container['plan_emails'] = isset($data['plan_emails']) ? $data['plan_emails'] : null;
        $this->container['plan_name'] = isset($data['plan_name']) ? $data['plan_name'] : null;
        $this->container['plan_name_formatted'] = isset($data['plan_name_formatted']) ? $data['plan_name_formatted'] : null;
        $this->container['require_order_within_last_days'] = isset($data['require_order_within_last_days']) ? $data['require_order_within_last_days'] : null;
        $this->container['revenue_percent'] = isset($data['revenue_percent']) ? $data['revenue_percent'] : null;
        $this->container['spam_percent_limit'] = isset($data['spam_percent_limit']) ? $data['spam_percent_limit'] : null;
        $this->container['total_customers'] = isset($data['total_customers']) ? $data['total_customers'] : null;
        $this->container['total_emails'] = isset($data['total_emails']) ? $data['total_emails'] : null;
        $this->container['upgrade_to'] = isset($data['upgrade_to']) ? $data['upgrade_to'] : null;
    }

    /**
     * Show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalidProperties = [];

        return $invalidProperties;
    }

    /**
     * Validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properties are valid
     */
    public function valid()
    {
        return count($this->listInvalidProperties()) === 0;
    }

    /**
     * Gets additional_customers
     *
     * @return int
     */
    public function getAdditionalCustomers()
    {
        return $this->container['additional_customers'];
    }

    /**
     * Sets additional_customers
     *
     * @param int $additional_customers additional_customers
     *
     * @return $this
     */
    public function setAdditionalCustomers($additional_customers)
    {
        $this->container['additional_customers'] = $additional_customers;

        return $this;
    }

    /**
     * Gets additional_emails
     *
     * @return int
     */
    public function getAdditionalEmails()
    {
        return $this->container['additional_emails'];
    }

    /**
     * Sets additional_emails
     *
     * @param int $additional_emails additional_emails
     *
     * @return $this
     */
    public function setAdditionalEmails($additional_emails)
    {
        $this->container['additional_emails'] = $additional_emails;

        return $this;
    }

    /**
     * Gets additional_fee
     *
     * @return float
     */
    public function getAdditionalFee()
    {
        return $this->container['additional_fee'];
    }

    /**
     * Sets additional_fee
     *
     * @param float $additional_fee additional_fee
     *
     * @return $this
     */
    public function setAdditionalFee($additional_fee)
    {
        $this->container['additional_fee'] = $additional_fee;

        return $this;
    }

    /**
     * Gets allow_list_import
     *
     * @return bool
     */
    public function getAllowListImport()
    {
        return $this->container['allow_list_import'];
    }

    /**
     * Sets allow_list_import
     *
     * @param bool $allow_list_import allow_list_import
     *
     * @return $this
     */
    public function setAllowListImport($allow_list_import)
    {
        $this->container['allow_list_import'] = $allow_list_import;

        return $this;
    }

    /**
     * Gets allow_tracking_emails
     *
     * @return bool
     */
    public function getAllowTrackingEmails()
    {
        return $this->container['allow_tracking_emails'];
    }

    /**
     * Sets allow_tracking_emails
     *
     * @param bool $allow_tracking_emails allow_tracking_emails
     *
     * @return $this
     */
    public function setAllowTrackingEmails($allow_tracking_emails)
    {
        $this->container['allow_tracking_emails'] = $allow_tracking_emails;

        return $this;
    }

    /**
     * Gets customer_tiers
     *
     * @return \ultracart\v2\models\EmailPlanAdditional[]
     */
    public function getCustomerTiers()
    {
        return $this->container['customer_tiers'];
    }

    /**
     * Sets customer_tiers
     *
     * @param \ultracart\v2\models\EmailPlanAdditional[] $customer_tiers customer_tiers
     *
     * @return $this
     */
    public function setCustomerTiers($customer_tiers)
    {
        $this->container['customer_tiers'] = $customer_tiers;

        return $this;
    }

    /**
     * Gets initial_sending_limits
     *
     * @return int
     */
    public function getInitialSendingLimits()
    {
        return $this->container['initial_sending_limits'];
    }

    /**
     * Sets initial_sending_limits
     *
     * @param int $initial_sending_limits initial_sending_limits
     *
     * @return $this
     */
    public function setInitialSendingLimits($initial_sending_limits)
    {
        $this->container['initial_sending_limits'] = $initial_sending_limits;

        return $this;
    }

    /**
     * Gets plan_customers
     *
     * @return int
     */
    public function getPlanCustomers()
    {
        return $this->container['plan_customers'];
    }

    /**
     * Sets plan_customers
     *
     * @param int $plan_customers plan_customers
     *
     * @return $this
     */
    public function setPlanCustomers($plan_customers)
    {
        $this->container['plan_customers'] = $plan_customers;

        return $this;
    }

    /**
     * Gets plan_emails
     *
     * @return int
     */
    public function getPlanEmails()
    {
        return $this->container['plan_emails'];
    }

    /**
     * Sets plan_emails
     *
     * @param int $plan_emails plan_emails
     *
     * @return $this
     */
    public function setPlanEmails($plan_emails)
    {
        $this->container['plan_emails'] = $plan_emails;

        return $this;
    }

    /**
     * Gets plan_name
     *
     * @return string
     */
    public function getPlanName()
    {
        return $this->container['plan_name'];
    }

    /**
     * Sets plan_name
     *
     * @param string $plan_name plan_name
     *
     * @return $this
     */
    public function setPlanName($plan_name)
    {
        $this->container['plan_name'] = $plan_name;

        return $this;
    }

    /**
     * Gets plan_name_formatted
     *
     * @return string
     */
    public function getPlanNameFormatted()
    {
        return $this->container['plan_name_formatted'];
    }

    /**
     * Sets plan_name_formatted
     *
     * @param string $plan_name_formatted plan_name_formatted
     *
     * @return $this
     */
    public function setPlanNameFormatted($plan_name_formatted)
    {
        $this->container['plan_name_formatted'] = $plan_name_formatted;

        return $this;
    }

    /**
     * Gets require_order_within_last_days
     *
     * @return int
     */
    public function getRequireOrderWithinLastDays()
    {
        return $this->container['require_order_within_last_days'];
    }

    /**
     * Sets require_order_within_last_days
     *
     * @param int $require_order_within_last_days require_order_within_last_days
     *
     * @return $this
     */
    public function setRequireOrderWithinLastDays($require_order_within_last_days)
    {
        $this->container['require_order_within_last_days'] = $require_order_within_last_days;

        return $this;
    }

    /**
     * Gets revenue_percent
     *
     * @return int
     */
    public function getRevenuePercent()
    {
        return $this->container['revenue_percent'];
    }

    /**
     * Sets revenue_percent
     *
     * @param int $revenue_percent revenue_percent
     *
     * @return $this
     */
    public function setRevenuePercent($revenue_percent)
    {
        $this->container['revenue_percent'] = $revenue_percent;

        return $this;
    }

    /**
     * Gets spam_percent_limit
     *
     * @return int
     */
    public function getSpamPercentLimit()
    {
        return $this->container['spam_percent_limit'];
    }

    /**
     * Sets spam_percent_limit
     *
     * @param int $spam_percent_limit spam_percent_limit
     *
     * @return $this
     */
    public function setSpamPercentLimit($spam_percent_limit)
    {
        $this->container['spam_percent_limit'] = $spam_percent_limit;

        return $this;
    }

    /**
     * Gets total_customers
     *
     * @return int
     */
    public function getTotalCustomers()
    {
        return $this->container['total_customers'];
    }

    /**
     * Sets total_customers
     *
     * @param int $total_customers total_customers
     *
     * @return $this
     */
    public function setTotalCustomers($total_customers)
    {
        $this->container['total_customers'] = $total_customers;

        return $this;
    }

    /**
     * Gets total_emails
     *
     * @return int
     */
    public function getTotalEmails()
    {
        return $this->container['total_emails'];
    }

    /**
     * Sets total_emails
     *
     * @param int $total_emails total_emails
     *
     * @return $this
     */
    public function setTotalEmails($total_emails)
    {
        $this->container['total_emails'] = $total_emails;

        return $this;
    }

    /**
     * Gets upgrade_to
     *
     * @return int
     */
    public function getUpgradeTo()
    {
        return $this->container['upgrade_to'];
    }

    /**
     * Sets upgrade_to
     *
     * @param int $upgrade_to upgrade_to
     *
     * @return $this
     */
    public function setUpgradeTo($upgrade_to)
    {
        $this->container['upgrade_to'] = $upgrade_to;

        return $this;
    }
    /**
     * Returns true if offset exists. False otherwise.
     *
     * @param integer $offset Offset
     *
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     *
     * @param integer $offset Offset
     *
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * Sets value based on offset.
     *
     * @param integer $offset Offset
     * @param mixed   $value  Value to be set
     *
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     *
     * @param integer $offset Offset
     *
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Gets the string presentation of the object
     *
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode(
                ObjectSerializer::sanitizeForSerialization($this),
                JSON_PRETTY_PRINT
            );
        }

        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
    }
}


text:
package org.nem.core.model.primitive;

import net.minidev.json.JSONObject;
import org.hamcrest.core.*;
import org.junit.*;
import org.nem.core.serialization.*;
import org.nem.core.test.Utils;

import java.util.function.BiFunction;

public class AmountTest {

	//region constants

	@Test
	public void constantsAreInitializedCorrectly() {
		// Assert:
		Assert.assertThat(Amount.ZERO, IsEqual.equalTo(new Amount(0)));
	}

	//endregion

	//region factories

	@Test
	public void canCreateAmountFromNem() {
		// Act:
		final Amount amount = Amount.fromNem(11);

		// Assert:
		Assert.assertThat(amount.getNumMicroNem(), IsEqual.equalTo(11000000L));
		Assert.assertThat(amount.getNumNem(), IsEqual.equalTo(11L));
	}

	@Test
	public void canCreateAmountFromMicroNem() {
		// Act:
		final Amount amount = Amount.fromMicroNem(11);

		// Assert:
		Assert.assertThat(amount.getNumMicroNem(), IsEqual.equalTo(11L));
		Assert.assertThat(amount.getNumNem(), IsEqual.equalTo(0L));
	}

	//endregion

	//region constructor

	@Test(expected = NegativeBalanceException.class)
	public void cannotBeCreatedAroundNegativeAmount() {
		// Act:
		new Amount(-1);
	}

	@Test
	public void canBeCreatedAroundZeroAmount() {
		// Act:
		final Amount amount = new Amount(0);

		// Assert:
		Assert.assertThat(amount.getNumMicroNem(), IsEqual.equalTo(0L));
	}

	@Test
	public void canBeCreatedAroundPositiveAmount() {
		// Act:
		final Amount amount = new Amount(1);

		// Assert:
		Assert.assertThat(amount.getNumMicroNem(), IsEqual.equalTo(1L));
	}

	//endregion

	//region getNumNem

	@Test
	public void getNumNemRoundsDownToTheNearestWholeNem() {
		// Assert:
		Assert.assertThat(Amount.fromMicroNem(11000000L).getNumNem(), IsEqual.equalTo(11L));
		Assert.assertThat(Amount.fromMicroNem(11000001L).getNumNem(), IsEqual.equalTo(11L));
		Assert.assertThat(Amount.fromMicroNem(11999999L).getNumNem(), IsEqual.equalTo(11L));
	}

	//endregion

	//region add / subtract

	@Test
	public void twoAmountsCanBeAddedTogether() {
		// Arrange:
		final Amount amount1 = new Amount(65);
		final Amount amount2 = new Amount(111);

		// Act:
		final Amount result1 = amount1.add(amount2);
		final Amount result2 = amount2.add(amount1);

		// Assert:
		Assert.assertThat(result1, IsEqual.equalTo(new Amount(176)));
		Assert.assertThat(result2, IsEqual.equalTo(new Amount(176)));
	}

	@Test
	public void smallerAmountCanBeSubtractedFromLargerAmount() {
		// Arrange:
		final Amount amount1 = new Amount(65);
		final Amount amount2 = new Amount(111);

		// Act:
		final Amount result = amount2.subtract(amount1);

		// Assert:
		Assert.assertThat(result, IsEqual.equalTo(new Amount(46)));
	}

	@Test(expected = NegativeBalanceException.class)
	public void largerAmountCannotBeSubtractedFromSmallerAmount() {
		// Arrange:
		final Amount amount1 = new Amount(65);
		final Amount amount2 = new Amount(111);

		// Act:
		amount1.subtract(amount2);
	}

	//endregion

	//region multiply

	@Test
	public void amountCanBeMultipliedByScalar() {
		// Arrange:
		final Amount amount = new Amount(65);

		// Act:
		final Amount result = amount.multiply(3);

		// Assert:
		Assert.assertThat(result, IsEqual.equalTo(new Amount(195)));
	}

	//endregion

	//region inline serialization

	@Test
	public void canWriteAmount() {
		// Arrange:
		final JsonSerializer serializer = new JsonSerializer();
		final Amount amount = new Amount(0x7712411223456L);

		// Act:
		Amount.writeTo(serializer, "Amount", amount);

		// Assert:
		final JSONObject object = serializer.getObject();
		Assert.assertThat(object.size(), IsEqual.equalTo(1));
		Assert.assertThat(object.get("Amount"), IsEqual.equalTo(0x7712411223456L));
	}

	@Test
	public void canRoundtripAmount() {
		// Assert:
		assertCanRoundtripAmount(Amount::readFrom);
	}

	@Test
	public void canRoundtripAmountUsingReadFromOptional() {
		// Assert:
		assertCanRoundtripAmount(Amount::readFromOptional);
	}

	private static void assertCanRoundtripAmount(final BiFunction<Deserializer, String, Amount> readFrom) {
		// Arrange:
		final JsonSerializer serializer = new JsonSerializer();
		final Amount originalAmount = new Amount(0x7712411223456L);

		// Act:
		Amount.writeTo(serializer, "Amount", originalAmount);

		final JsonDeserializer deserializer = Utils.createDeserializer(serializer.getObject());
		final Amount amount = readFrom.apply(deserializer, "Amount");

		// Assert:
		Assert.assertThat(amount, IsEqual.equalTo(originalAmount));
	}

	@Test
	public void canReadNullUsingReadFromOptional() {
		// Arrange:
		final JsonSerializer serializer = new JsonSerializer();

		// Act:
		final JsonDeserializer deserializer = Utils.createDeserializer(serializer.getObject());
		final Amount amount = Amount.readFromOptional(deserializer, "Amount");

		// Assert:
		Assert.assertThat(amount, IsNull.nullValue());
	}

	//endregion
}


text:
from office365.runtime.paths.resource_path import ResourcePath
from office365.sharepoint.base_entity import BaseEntity
from office365.sharepoint.permissions.base_permissions import BasePermissions
from office365.sharepoint.translation.user_resource import UserResource

class UserCustomAction(BaseEntity):
    """Specifies a custom action."""

    def get_property(self, name, default_value=None):
        if name == "DescriptionResource":
            default_value = self.description_resource
        elif name == "TitleResource":
            default_value = self.title_resource
        return super(UserCustomAction, self).get_property(name, default_value)

    @property
    def rights(self):
        """Specifies the permissions needed for the custom action."""
        return self.properties.get("Rights", BasePermissions())

    @property
    def description_resource(self):
        """Gets the SP.UserResource object that corresponds to the Description for this object."""
        return self.properties.get('DescriptionResource',
                                   UserResource(self.context, ResourcePath("DescriptionResource", self.resource_path)))

    @property
    def title_resource(self):
        """Returns the UserResource object that corresponds to the Title for this object."""
        return self.properties.get('TitleResource',
                                   UserResource(self.context, ResourcePath("TitleResource", self.resource_path)))


text:
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <meta name="googlebot" content="noindex, nofollow">

    <link rel="stylesheet" type="text/css" href="/css/result-light.css">

  <title>Visitors per country</title>


text:
import os
from os.path import join
import copy

import numpy as np
import pandas as pd

from fileio.pickle_io import pickle_read

def create_yield_grids():
    """Generate yield grids."""
    os.system('python make_yield_grids.py')  # TODO: doesn't work

def check_grid(fname):
    """If yield grid does not exist, create it.

    Args:
        fname (str): filename (including path) of yield grid.
    """
    if not os.path.isfile(join(fname)):
        create_yield_grids()

class Yields:
    """Yield grids.
    """

    def __init__(self, path_parent, snii_dir, agb_dir, snia_dir,
                 rprocess_dir=None, sprocess_dir=None,
                 snia_model='w70', sprocess_supersolar=False,
                 r_elements=None, s_elements=None,
                 mbins=None):
        """Initialize Yields instance.

        Args:
            path_parent (str): data directory.
            snii_dir (str): directory of SNII yields.
            agb_dir (str): directory of AGB yields.
            snia_dir (str): directory of SNII yields.
            rprocess_dir (str): directory of SNII yields.
            sprocess_dir (str): directory of SNII yields.
            snia_model (str): SNIa model. Defaults to 'w70'.
            sprocess_supersolar (bool): If True use super-solar metallicity
                s-process yields.
            r_elements (list): r-process elements to track.
            s_elements (list): s-process elements to track.
            mbins (array): stellar mass bins. Defaults to None.
        """
        self.path_parent = path_parent
        self.path_yields = join(self.path_parent, 'yields')
        self.path_yldgen = join(self.path_yields, 'general')
        self.path_snii = join(self.path_yields, snii_dir)
        self.path_agb = join(self.path_yields, agb_dir)
        self.path_snia = join(self.path_yields, snia_dir)
        self.sources = dict(snii=snii_dir.split('/')[0],
                            snia=snia_dir.split('/')[0],
                            agb=agb_dir.split('/')[0])
        if rprocess_dir is not None:
            self.path_rprocess = join(self.path_yields, rprocess_dir)
            self.sources['rprocess'] = rprocess_dir.split('/')[0]
        if sprocess_dir is not None:
            self.path_sprocess = join(self.path_yields, sprocess_dir)
            self.sources['sprocess'] = sprocess_dir.split('/')[0]
        if mbins is None:
            mbins = np.concatenate((np.arange(0.1, 8., 0.1),
                                    np.arange(8., 100.1, 1.)))
        self.mass_bins = mbins
        self.n_bins = len(mbins) - 1
        self.n_bins_high = len(np.where(self.mass_bins >= 8.)[0]) - 1
        self.n_bins_low = len(np.where(self.mass_bins < 8.)[0])
        self.ind8 = np.where(self.mass_bins == 8.)[0][0]
        self.mlow = mbins[0]
        self.load_sym()
        self.load_bbmf()
        self.load_rprocess_yields()
        self.load_sprocess_yields(supersolar=sprocess_supersolar)
        self.load_snii_yields()
        self.load_agb_yields()
        self.load_snia_yields(model=snia_model)
        self.concat_ncapture_yields(r_elements=r_elements,
                                    s_elements=s_elements)
        self.load_solar_abund()

    def _check_yield_grids(self, path):
        """Check if yield, mremnant, and meject grids exist.

        Args:
            path (str): path to yield grids.
        """
        suffixes = ['yields', 'meject', 'mremnant']
        fnames = ['interp_{}.pck'.format(it) for it in suffixes]
        for fname in fnames:
            check_grid(join(path, fname))
        self._check_metallicity_grid()

    def _check_metallicity_grid(self):
        """Check if metallicity grid exists."""
        check_grid(join(self.path_yldgen, 'interp_metallicity.pck'))

    def load_sym(self):
        """Load isotopic and elemental symbols and masses."""
        el_sym = pd.read_csv(join(self.path_yldgen, 'sym_atomicnum.txt'),
                             delim_whitespace=True, usecols=[0, 1],
                             names=['num', 'el'])
        self.atomic_num = np.array(el_sym['num'])
        self.element_all = np.array(el_sym['el'])
        snii_sym = pd.read_csv(join(self.path_yldgen, 'species.txt'),
                               delim_whitespace=True, skiprows=1,
                               usecols=[1, 2], names=['name', 'mass'])
        self.snii_sym = np.array(snii_sym['name'])
        self.snii_sym_mass = np.array(snii_sym['mass'])
        self.n_snii_sym = len(self.snii_sym)
        u, indices = np.unique([item.rstrip('0123456789')
                                for item in self.snii_sym], return_index=True)
        indices_s = np.argsort(indices)
        self.element = np.delete(u[indices_s], np.s_[13, 14])
        self.n_elements = len(self.element)

    def load_bbmf(self):
        """Big bang mass fraction of isotopes from WW95/Timmies data file."""
        bbmf = pd.read_csv(join(self.path_yldgen, 'bbmf.txt'),
                           delim_whitespace=True, skiprows=1, usecols=[1],
                           names=['mfrac'])
        self.bbmf = np.array(bbmf['mfrac'])

    def load_solar_abund(self, source='lodders'):
        """Load solar abundances.

        Args:
           source (str): Source of solar abundances. Defaults to 'lodders'.
        """
        if source == 'lodders':
            fin = join(self.path_yldgen, 'lodders03_solar_photosphere.txt')
            solar_ab = pd.read_csv(fin, delim_whitespace=True, skiprows=8,
                                   usecols=[0, 1], names=['el', 'ab'])
            self.solar_element = np.array(solar_ab['el'])
            self.solar_ab = np.array(solar_ab['ab'])
            self.solar_h = np.zeros(self.n_elements)
            self.solar_fe = np.zeros(self.n_elements)
            for i in range(self.n_elements):
                ind = np.where(self.solar_element == self.element[i])[0]
                ind_fe = np.where(self.element == 'Fe')
                self.solar_h[i] = self.solar_ab[ind]
                self.solar_fe[i] = np.log10(
                    10.**(self.solar_ab[ind] - 12.) /
                    10.**(self.solar_ab[ind_fe] - 12.))
        self.calc_solar_mass_fraction()
        # elif source == 'asplund':
        # elif source == 'aspcap':
        # else:
        #     Raise exception

    def calc_solar_mass_fraction(self):
        """Calculate solar mass fracions of isotopes."""
        dominant_isotope = np.array([
            'H1', 'He4', 'Li7', 'Be9', 'B11', 'C12', 'N14', 'O16', 'F19',
            'Ne20', 'Na23', 'Mg24', 'Al27', 'Si28', 'P31', 'S32', 'Cl35',
            'Ar36', 'K39', 'Ca40', 'Sc45', 'Ti48', 'V51', 'Cr52', 'Mn55',
            'Fe56', 'Co59', 'Ni58', 'Cu63', 'Zn64', 'Ga69', 'Ge74', 'As75',
            'Se80', 'Br81', 'Kr84', 'Rb85', 'Sr88', 'Y89', 'Zr90', 'Nb93',
            'Mo98', 'Ba138', 'Eu153'])
        miso = np.array([item.lstrip(''.join(['ABCDEFGHIJKLMNOPQRSTUVWXYZ',
                                              'abcdefghijklmnopqrstuvwxyz']))
                         for item in dominant_isotope])
        miso = miso.astype(int)
        nh = 10.**(self.solar_h - 12.)
        mh = nh * miso
        mfrac = mh / mh.sum()
        self.solar_mfrac = np.zeros(self.n_sym)
        for i in range(len(dominant_isotope)):
            ind = np.where(self.sym == dominant_isotope[i])[0]
            self.solar_mfrac[ind] = mfrac[i]

    def load_snii_yields(self):
        """Load SNII yields.

        Limongi & Chieffi SN II Yields: 1001 metallicities, 92 masses from
        8 to 100 msun, 293 isotopes.

        WW95 yields are also on same metallicity--stellar mass--isotope grid.
        """
        self.snii_z = pickle_read(join(self.path_yldgen, 'interp_metallicity.pck'))
        self.snii_yields = pickle_read(join(self.path_snii, 'interp_yields.pck'))
        self.snii_mej = pickle_read(join(self.path_snii, 'interp_meject.pck'))
        self.snii_rem = pickle_read(join(self.path_snii, 'interp_mremnant.pck'))
        self.snii_agb_z = copy.deepcopy(self.snii_z)
        self.n_z = len(self.snii_agb_z)
        # adjust for a different upper mass limit to the IMF
        self.snii_yields = self.snii_yields[:, :self.n_bins_high, :]
        self.snii_mej = self.snii_mej[:, :self.n_bins_high]
        self.snii_rem = self.snii_rem[:, :self.n_bins_high]

    def load_agb_yields(self):
        """Load AGB yields.

        Karakas AGB Yields: 1001 metallicities, 79 masses from 0.1 to 8
        msun, 70 isotopes.

        Only works for Karakas et al. (2010) AGB yields.

        B8, O14, Ne19, and Si33 are not in the LC yields.  The latter three K10
        yields are always 0 and the B8 yield is essentially zero (<1e-17), so I
        have removed those from agb_sym, agb_yields_in, and agb_yields.
        """
        self._check_yield_grids(self.path_agb)
        agb_sym = pd.read_csv(join(self.path_agb, 'species.txt'),
                              delim_whitespace=True, skiprows=1, usecols=[1],
                              names=['name'])
        self.agb_sym = np.array(agb_sym['name'])
        self.agb_z = pickle_read(join(self.path_yldgen, 'interp_metallicity.pck'))
        agb_yields_in = pickle_read(join(self.path_agb, 'interp_yields.pck'))
        # remove isotopes not in the LC06 yields
        agb_yields_in = np.delete(agb_yields_in, np.s_[6, 13, 23, 47], axis=2)
        self.agb_mej = pickle_read(join(self.path_agb, 'interp_meject.pck'))
        self.agb_rem = pickle_read(join(self.path_agb, 'interp_mremnant.pck'))
        # Create an array with the same elements as the Limongi & Chieffi
        # (2006) SNII yields.
        self.agb_yields = np.zeros((agb_yields_in.shape[0],
                                    agb_yields_in.shape[1],
                                    self.snii_yields.shape[2]))
        ind_agb = np.array([], dtype=int)
        for i in range(len(self.agb_sym)):
            tmp = np.where(self.agb_sym[i] == self.snii_sym)[0]
            ind_agb = np.append(ind_agb, tmp)
        self.agb_yields[:, :, ind_agb] = copy.deepcopy(agb_yields_in)
        if self.mlow == 0.2:
            self.agb_mej = self.agb_mej[:, 1:]
            self.agb_rem = self.agb_rem[:, 1:]
            self.agb_yields = self.agb_yields[:, 1:]

    def load_rprocess_yields(self):
        """Load r-process element yields.

        Cescutti et al. (2006) r-process Ba & Eu yields for M = 12, 15, 30
        Msun that are metallicity independent.
        """
        self.rprocess_yields = pickle_read(join(self.path_rprocess,
                                                'cescutti06_yields.pck'))

    def load_sprocess_yields(self, supersolar=False):
        """Load s-process element yields.

        Busso et al. (2001) s-process Ba yields for M < 8 Msun & Z =
        2e-4--4e-2 (twice solar and twice the maximum Limongi & Chieffi
        metallicity).

        supersolar: if True, use the yields that extend from solar (Z = 2e-2)
        to twice solar (Z = 4e-2), otherwise only use the yields up to solar.
        """
        if supersolar:
            self.sprocess_z = pickle_read(join(self.path_sprocess,
                                               'busso01ext_metallicity.pck'))
            self.sprocess_yields = pickle_read(join(self.path_sprocess,
                                                    'busso01ext_yields.pck'))
        else:
            self.sprocess_yields = pickle_read(join(self.path_sprocess,
                                                    'busso01_yields.pck'))

    def load_snia_yields(self, model):
        """Load SNIa yields.

        Iwamoto et al. (1999) models\:
        cdd1\: CDD1
        cdd2\: CDD2
        w7\: single-degenerate model from Nomoto et al. (1984)
        w70\: zero-metallicity version of W7
        wdd1\: WDD1
        wdd2\: WDD2
        wdd3\: WDD3
        """
        self.snia_yields = pickle_read(join(self.path_snia,
                                            model + '_yields.pck'))

    def concat_ncapture_yields(self, r_elements, s_elements):
        """Create an array of r- and s-process isotopic yields."""
        nclib = pickle_read(join(self.path_yldgen, 'sneden08.pck'))
        # unique elements arranged by atomic number
        elements = np.unique(r_elements + s_elements)
        at_num = []
        for item in elements:
            at_num.append(nclib[item]['Z'])
        at_num = np.array(at_num)
        elements = elements[np.argsort(at_num)]
        self.nc_sym = []
        self.nc_sym_mass = []
        for item in elements:
            n_tmp = len(nclib[item]['Isotope'])
            for i in range(n_tmp):
                self.nc_sym.append(item + str(nclib[item]['Isotope'][i]))
                self.nc_sym_mass.append(nclib[item]['Isotope'][i])
        self.nc_sym = np.array(self.nc_sym)
        self.nc_sym_mass = np.array(self.nc_sym_mass)
        self.n_nc_sym = len(self.nc_sym)
        u, indices = np.unique([item.rstrip('0123456789')
                                for item in self.nc_sym], return_index=True)
        indices_s = np.argsort(indices)
        self.nc_element = u[indices_s]
        # project elemental yields onto relative isotopic abundances
        self.nc_yields = np.zeros((self.n_z, self.n_bins, self.n_nc_sym))
        cnt = 0
        for i in range(len(elements)):
            el = elements[i]
            el_iso = len(nclib[el]['Isotope'])
            if el in r_elements:
                j = np.where(np.array(r_elements) == el)[0]
                self.nc_yields[:, -self.n_bins_high:, cnt:cnt+el_iso] = \
                               (np.ones((self.n_z, self.n_bins_high, el_iso)) *
                                self.rprocess_yields[:, -self.n_bins_high:, j] *
                                nclib[el]['isotopic_fraction[r]'])
            if el in s_elements:
                j = np.where(np.array(s_elements) == el)[0]
                self.nc_yields[:, :self.n_bins_low, cnt:cnt+el_iso] = \
                                (np.ones((self.n_z, self.n_bins_low, el_iso)) *
                                 self.sprocess_yields[:, :, j] *
                                 nclib[el]['isotopic_fraction[s]'])
            cnt += el_iso
        # update arrays
        self.sym = np.append(self.snii_sym, self.nc_sym)
        self.sym_mass = np.append(self.snii_sym_mass, self.nc_sym_mass)
        self.n_sym = len(self.sym)
        self.element = np.append(self.element, self.nc_element)
        self.n_elements = len(self.element)
        self.bbmf = np.append(self.bbmf, np.zeros(self.n_nc_sym))
        if len(self.snia_yields.shape) == 1:
            # metallicity-independent SNIa yields
            self.snia_yields = np.append(self.snia_yields,
                                         np.zeros(self.n_nc_sym))
        elif len(self.snia_yields.shape) == 2:
            # metallicity-dependent SNIa yields
            self.snia_yields = np.append(self.snia_yields,
                                         np.zeros((self.nc_yields.shape[0],
                                                   self.nc_yields.shape[2])),
                                         axis=1)
        self.snii_yields = np.append(self.snii_yields,
                                     self.nc_yields[:, self.ind8:], axis=2)
        self.agb_yields = np.append(self.agb_yields,
                                    self.nc_yields[:, :self.ind8], axis=2)
        self.snii_agb_rem = np.concatenate((self.agb_rem, self.snii_rem),
                                           axis=1)


text:
__author__ = 'tivvit'

from users import Users
from game import Game
from quests import Quests


text:
/**
 * @author      Alex Mourtziapis <alex.mourtziapis@gmail.com>
 * @license     {@link http://opensource.org/licenses/MIT|MIT License}
 */

Code_Reactor.SoundPlayer = function (Code_Reactor) {

  this.player = undefined;

  this.currentTrack = 0;

  this.response = undefined;

  this.isPlaying = false;
};

Code_Reactor.SoundPlayer.prototype = {

  init: function () {

    SC.initialize({
      client_id: '8c4d05ea73a96fa248223b8bbaac971d'
    });

    SC.resolve(Code_Reactor.playlistURL).then(function (response) {
      //console.log(JSON.stringify(response));
      Code_Reactor.SoundPlayer.response = response;
    });
  },

  play: function () {

    if (Code_Reactor.SoundPlayer.player === null) {
      SC.stream('/tracks/' + Code_Reactor.SoundPlayer.response.tracks[Code_Reactor.SoundPlayer.currentTrack].id).then(function (player) {
        Code_Reactor.SoundPlayer.player = player;
        Code_Reactor.SoundPlayer.player.play();
        document.getElementById('song_playin').innerHTML = Code_Reactor.SoundPlayer.response.tracks[Code_Reactor.SoundPlayer.currentTrack].title;
        Code_Reactor.SoundPlayer.isPlaying = true;
        Code_Reactor.SoundPlayer.player.setVolume(1.0);

        Code_Reactor.SoundPlayer.player.on('finish', function () {
          if ((Code_Reactor.SoundPlayer.currentTrack + 1) !== Code_Reactor.SoundPlayer.response.track_count) {
            Code_Reactor.SoundPlayer.currentTrack++;
            Code_Reactor.SoundPlayer.player = null;

            Code_Reactor.SoundPlayer.play();
          }
        });
      });
    } else {
      Code_Reactor.SoundPlayer.toggle();
    }
  },

  toggle: function () {
    if (Code_Reactor.SoundPlayer.player !== null) {

      if (Code_Reactor.SoundPlayer.isPlaying) {

        Code_Reactor.SoundPlayer.player.pause();
        Code_Reactor.SoundPlayer.isPlaying = false;
      } else {

        Code_Reactor.SoundPlayer.player.play();
        Code_Reactor.SoundPlayer.isPlaying = true;
      }
    }
  },

  increase_volume: function () {
    if (Code_Reactor.SoundPlayer.player !== null) {

      var step = 0.1;
      var volume = Code_Reactor.SoundPlayer.player.getVolume();
      if (volume + step > 1.0) {
        volume = 1.0;
      } else {
        volume += step;
      }
      Code_Reactor.SoundPlayer.player.setVolume(volume);
    }
  },

  decrease_volume: function () {
    if (Code_Reactor.SoundPlayer.player !== null) {

      var step = 0.1;
      var volume = Code_Reactor.SoundPlayer.player.getVolume();
      if (volume - step < 0.0) {
        volume = 0.0;
      } else {
        volume -= step;
      }
      Code_Reactor.SoundPlayer.player.setVolume(volume);
    }
  },

  play_next: function () {
    if (Code_Reactor.SoundPlayer.player !== null) {

      if ((Code_Reactor.SoundPlayer.currentTrack + 1) !== Code_Reactor.SoundPlayer.response.track_count) {

        if (Code_Reactor.SoundPlayer.isPlaying) {
          Code_Reactor.SoundPlayer.player.pause();
          Code_Reactor.SoundPlayer.isPlaying = false;
        }

        Code_Reactor.SoundPlayer.currentTrack++;
        Code_Reactor.SoundPlayer.player = null;

        Code_Reactor.SoundPlayer.play();
      }
    }
  },

  play_previous: function () {
    if (Code_Reactor.SoundPlayer.player !== null) {

      if (Code_Reactor.SoundPlayer.currentTrack !== 0) {

        if (Code_Reactor.SoundPlayer.isPlaying) {
          Code_Reactor.SoundPlayer.player.pause();
          Code_Reactor.SoundPlayer.isPlaying = false;
        }

        Code_Reactor.SoundPlayer.currentTrack--;
        Code_Reactor.SoundPlayer.player = null;

        Code_Reactor.SoundPlayer.play();
      }
    }
  }
};


text:
define(["require", "exports", "FS"], function(require, exports, __Bar__) {
    var Bar = __Bar__;

    function IsFoo(value) {
        return value instanceof Bar.Foo;
    }
});


text:
namespace Google.Cloud.Bigtable.Admin.V2.Snippets
{
    // [START bigtableadmin_v2_generated_BigtableInstanceAdmin_ListInstances_async_flattened]
    using Google.Cloud.Bigtable.Admin.V2;
    using System.Threading.Tasks;

    public sealed partial class GeneratedBigtableInstanceAdminClientSnippets
    {
        /// <summary>Snippet for ListInstancesAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task ListInstancesAsync()
        {
            // Create client
            BigtableInstanceAdminClient bigtableInstanceAdminClient = await BigtableInstanceAdminClient.CreateAsync();
            // Initialize request argument(s)
            string parent = "projects/[PROJECT]";
            // Make the request
            ListInstancesResponse response = await bigtableInstanceAdminClient.ListInstancesAsync(parent);
        }
    }
    // [END bigtableadmin_v2_generated_BigtableInstanceAdmin_ListInstances_async_flattened]
}


text:
from django.conf.urls import url, include

from . import views

urlpatterns = [
    url(r'^events/import/?$',
        views.ConferenceImport.as_view(),
        name='event_import'),
    url(r'^persons/import/?$',
        views.PersonImport.as_view(),
        name='person_import'),
    url(r'^tasks/import/?$',
        views.TaskImport.as_view(),
        name='task_import'),
    url(r'^sponsorships/import/?$',
        views.SponsorshipImport.as_view(),
        name='sponsorship_import'),

    url(r'^bulk-import/', include([
        url(r'^$',
            views.BulkImportEventSelect.as_view(),
            name='bulk_import_select'),
        url(r'^(?P<slug>[\w-]+)/person/?$',
            views.PersonBulkImport.as_view(),
            name='bulk_import_person'),
        url(r'^(?P<slug>[\w-]+)/task/?$',
            views.TaskBulkImport.as_view(),
            name='bulk_import_task'),
        url(r'^(?P<slug>[\w-]+)/sponsorship/?$',
            views.SponsorshipBulkImport.as_view(),
            name='bulk_import_sponsorship'),
    ])),
]


text:
								<img src="<?php echo get_bloginfo('template_directory');?>/assets/img/book.png" alt="droit pour le praticien" />

Obtenez l'accès au site pour l'année en cours grâce au code inscrit sur la dernière édition du livre.

							Acheter sur www.publications-droit.ch


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.messaging.servicebus;

import java.util.Objects;

/**
 * Represents the result of a receive message operation with context from Service Bus.
 */
public class ServiceBusReceivedMessageContext {
    private final ServiceBusReceivedMessage message;
    private final String sessionId;
    private final Throwable error;

    /**
     * Creates an instance where a message was successfully received.
     *
     * @param message Message received.
     */
    ServiceBusReceivedMessageContext(ServiceBusReceivedMessage message) {
        this.message = Objects.requireNonNull(message, "'message' cannot be null.");
        this.sessionId = message.getSessionId();
        this.error = null;
    }

    /**
     * Creates an instance where an error occurred such as session-lock-lost.
     *
     * @param sessionId Session id that the error occurred in.
     * @param error AMQP exception that occurred in session.
     */
    ServiceBusReceivedMessageContext(String sessionId, Throwable error) {
        this.sessionId = Objects.requireNonNull(sessionId, "'sessionId' cannot be null.");
        this.error = Objects.requireNonNull(error, "'error' cannot be null.");
        this.message = null;
    }

    /**
     * Gets the session id of the message or that the error occurred in.
     *
     * @return The session id associated with the error or message. {@code null} if there is no session.
     */
    public String getSessionId() {
        return sessionId;
    }

    /**
     * Gets the throwable that occurred.
     *
     * @return The throwable that occurred or {@code null} if there was no error.
     */
    public Throwable getThrowable() {
        return error;
    }

    /**
     * Gets the message received from Service Bus.
     *
     * @return The message received from Service Bus or {@code null} if an exception occurred.
     */
    public ServiceBusReceivedMessage getMessage() {
        return message;
    }

    /**
     * Gets whether or not an error occurred while receiving the next message.
     *
     * @return {@code true} if there was an error when receiving the next message; {@code false} otherwise.
     */
    public boolean hasError() {
        return error != null;
    }
}


text:
import inspect, re

def __functions__(module):
	return [func[0] for func in inspect.getmembers(module, inspect.isfunction)]

def __modules__(module):
	return [mod[0] for mod in inspect.getmembers(module, inspect.ismodule)]

def __fill__(graph, name, fill, indent = 0):
	if name.split('.')[0] in name.split('.')[1: ]: return str(), fill
	if name in fill: return fill[name], fill
	string = '%s
\n' %('\t' * indent)

	for key in graph[name]['modules']:
		if key.startswith('_'): continue
		string += '%s
\n' %('\t' * (indent + 1))
		string += '%s<input id="%s" type="checkbox" onclick="return apiClick(this)" hidden />\n' %(
			'\t' * (indent + 2),
			'%s.%s' %(key, name)
		)
		string += '%s%s\n' %(
			'\t' * (indent + 2),
			'%s.%s' %(key, name),
			key
		)
		fillstring, filldict = __fill__(
			graph,
			'%s.%s' %(key, name),
			fill,
			indent + 2
		)
		string += fillstring
		string += '%s
\n' %('\t' * (indent + 1))

	for key in graph[name]['functions']:
		if key.startswith('_'): continue
		string += '%s
%s
\n' %(
			'\t' * (indent + 1),
			'%s.%s' %(key, name),
			key
		)
	string += '%s
\n' %('\t' * indent)
	fill[name] = string
	return fill[name], fill

def __create__(graph, key, module):
	if key in graph or key.split('.')[0] in key.split('.')[1: ]: return graph
	graph[key] = {
		'base': key.split('.', 1)[1],
		'modules': __modules__(module),
		'functions': __functions__(module),
		'documentation': module.__doc__
	}
	for subkey in ['functions', 'modules']:
		for element in graph[key][subkey]:
			if element.startswith('_'): continue
			try:
				graph = __create__(
					graph,
					'%s.%s' %(element, key),
					getattr(module, element)
				)
			except:
				print module, element
				continue
	return graph

def __docs__(graph, indent = 0):
	embeddedimages = '.*
\n.*\n.*
'
	string = str()
	for key in graph:
		if graph[key]['documentation'] is None: graph[key]['documentation'] = str()
		string += '%s
%s
\n' %(
			'\t'  * indent,
			key,
			re.sub(
				embeddedimages,
				str(),
				graph[key]['documentation']
			)
		)
	return string


text:
'use strict';

angular.module('huellas')

.controller('hogarController', ['$scope', '$routeParams', '$location', 'Articles', '$mdDialog',
    function($scope, $routeParams, $location, Articles, $mdDialog) {

        $scope.find = function() {
            $scope.articles = Articles.query();
        };

        $scope.findOne = function() {

            $scope.article = Articles.get({
                articleId: $routeParams.articleId
            });
        };

        $scope.update = function() {
            $scope.article.$update(function() {
                $location.path('articles/consumo/' + $scope.article._id);
            }, function(errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

        $scope.inicio = function() {
            $location.path('/' + $scope.article._id);
        }

        $scope.cerrar = function() {
            $location.path('/signout');
        }

        $scope.showAdvanced = function(ev) {
            $mdDialog.show({
            controller: DialogController,
            templateUrl: 'partials/dialog.hogar.html',
            parent: angular.element(document.body),
            targetEvent: ev,
            clickOutsideToClose:true,
            fullscreen: $scope.customFullscreen // Only for -xs, -sm breakpoints.
            })
        };

  function DialogController($scope, $mdDialog) {
    $scope.hide = function() {
      $mdDialog.hide();
    };

    $scope.cancel = function() {
      $mdDialog.cancel();
    };

  }
 }]);


text:
//
// str-replace.c
//
// Copyright (c) 2013 Stephen Mathieson
// MIT licensed
//

#include <stdlib.h>
#include <string.h>
#include "occurrences/occurrences.h"
#include "strdup/strdup.h"
#include "str-replace.h"

/*
 * Replace all occurrences of `sub` with `replace` in `str`
 */

char *
str_replace(const char *str, const char *sub, const char *replace) {
  char *pos = (char *) str;
  int count = occurrences(sub, str);

  if (0 >= count) return strdup(str);

  int size = (
        strlen(str)
      - (strlen(sub) * count)
      + strlen(replace) * count
    ) + 1;

  char *result = (char *) malloc(size);
  if (NULL == result) return NULL;
  memset(result, '\0', size);
  char *current;
  while ((current = strstr(pos, sub))) {
    int len = current - pos;
    strncat(result, pos, len);
    strncat(result, replace, strlen(replace));
    pos = current + strlen(sub);
  }

  if (pos != (str + strlen(str))) {
    strncat(result, pos, (str - pos));
  }

  return result;
}