text:
/**
 * The wire widget that uses a canvas to render
 * @class Wire
 * @namespace WireIt
 * @extends WireIt.CanvasElement
 * @constructor
 * @param  {WireIt.Terminal}    terminal1   Source terminal
 * @param  {WireIt.Terminal}    terminal2   Target terminal
 * @param  {HTMLElement} parentEl    Container of the CANVAS tag
 * @param  {Obj}                options      Styling configuration
 */
WireIt.Wire = function( terminal1, terminal2, parentEl, options) {

   /**
    * Reference to the parent dom element
    * @property parentEl
    * @type HTMLElement
    */
   this.parentEl = parentEl;

   /**
    * Source terminal
    * @property terminal1
    * @type WireIt.Terminal
    */
   this.terminal1 = terminal1;

   /**
    * Target terminal
    * @property terminal2
    * @type WireIt.Terminal || WireIt.TerminalProxy
    */
   this.terminal2 = terminal2;

   // Init the options property
   this.setOptions(options || {});

   // Create the canvas element and append it to parentEl
   WireIt.Wire.superclass.constructor.call(this, this.parentEl);

   // CSS classname
   YAHOO.util.Dom.addClass(this.element, this.options.className);

   // Call addWire on both terminals
   this.terminal1.addWire(this);
   this.terminal2.addWire(this);
};

YAHOO.lang.extend(WireIt.Wire, WireIt.CanvasElement, {

   /**
    * @method setOptions
    */
   setOptions: function(options) {
      /**
       * Wire styling, and properties:
       *

       *
className: CSS class name of the canvas element (default 'WireIt-Wire')

       *
coeffMulDirection: Parameter for bezier style

       *
cap: default 'round'

       *
bordercap: default 'round'

       *
width: Wire width (default to 3)

       *
borderwidth: Border Width (default to 1)

       *
color: Wire color (default to rgb(173, 216, 230) )

       *
bordercolor: Border color (default to #0000ff )

       *

       * @property options
       */
      this.options = {};
      this.options.className = options.className || 'WireIt-Wire';
      this.options.coeffMulDirection = YAHOO.lang.isUndefined(options.coeffMulDirection) ? 100 : options.coeffMulDirection;

      // Syling
      this.options.drawingMethod = options.drawingMethod || 'bezier';
      this.options.cap = options.cap || 'round';
      this.options.bordercap = options.bordercap || 'round';
      this.options.width = options.width || 3;
      this.options.borderwidth = options.borderwidth || 1;
      this.options.color = options.color || 'rgb(173, 216, 230)';
      this.options.bordercolor = options.bordercolor || '#0000ff';
   },

   /**
    * Remove a Wire from the Dom
    * @method remove
    */
   remove: function() {

      // Remove the canvas from the dom
      this.parentEl.removeChild(this.element);

      // Remove the wire reference from the connected terminals
      if(this.terminal1 && this.terminal1.removeWire) {
         this.terminal1.removeWire(this);
      }
      if(this.terminal2 && this.terminal2.removeWire) {
         this.terminal2.removeWire(this);
      }

      // Remove references to old terminals
      this.terminal1 = null;
      this.terminal2 = null;
   },

   /**
    * Redraw the Wire
    * @method drawBezierCurve
    */
   drawBezierCurve: function() {

      // Get the positions of the terminals
      var p1 = this.terminal1.getXY();
      var p2 = this.terminal2.getXY();

      // Coefficient multiplicateur de direction
      // 100 par defaut, si distance(p1,p2) < 100, on passe en distance/2
      var coeffMulDirection = this.options.coeffMulDirection;

      var distance=Math.sqrt(Math.pow(p1[0]-p2[0],2)+Math.pow(p1[1]-p2[1],2));
      if(distance < coeffMulDirection){
         coeffMulDirection = distance/2;
      }

      // Calcul des vecteurs directeurs d1 et d2 :
      var d1 = [this.terminal1.options.direction[0]*coeffMulDirection,
                this.terminal1.options.direction[1]*coeffMulDirection];
      var d2 = [this.terminal2.options.direction[0]*coeffMulDirection,
                this.terminal2.options.direction[1]*coeffMulDirection];

      var bezierPoints=[];
      bezierPoints[0] = p1;
      bezierPoints[1] = [p1[0]+d1[0],p1[1]+d1[1]];
      bezierPoints[2] = [p2[0]+d2[0],p2[1]+d2[1]];
      bezierPoints[3] = p2;
      var min = [p1[0],p1[1]];
      var max = [p1[0],p1[1]];
      for(var i=1 ; i<bezierPoints.length ; i++){
         var p = bezierPoints[i];
         if(p[0] < min[0]){
            min[0] = p[0];
         }
         if(p[1] < min[1]){
            min[1] = p[1];
         }
         if(p[0] > max[0]){
            max[0] = p[0];
         }
         if(p[1] > max[1]){
            max[1] = p[1];
         }
      }
      // Redimensionnement du canvas
      var margin = [4,4];
      min[0] = min[0]-margin[0];
      min[1] = min[1]-margin[1];
      max[0] = max[0]+margin[0];
      max[1] = max[1]+margin[1];
      var lw = Math.abs(max[0]-min[0]);
      var lh = Math.abs(max[1]-min[1]);

      this.SetCanvasRegion(min[0],min[1],lw,lh);

      var ctxt = this.getContext();
      for(var i = 0 ; i<bezierPoints.length ; i++){
         bezierPoints[i][0] = bezierPoints[i][0]-min[0];
         bezierPoints[i][1] = bezierPoints[i][1]-min[1];
      }

      // Draw the border
      ctxt.lineCap = this.options.bordercap;
      ctxt.strokeStyle = this.options.bordercolor;
      ctxt.lineWidth = this.options.width+this.options.borderwidth*2;
      ctxt.beginPath();
      ctxt.moveTo(bezierPoints[0][0],bezierPoints[0][1]);
      ctxt.bezierCurveTo(bezierPoints[1][0],bezierPoints[1][1],bezierPoints[2][0],bezierPoints[2][1],bezierPoints[3][0],bezierPoints[3][1]);
      ctxt.stroke();

      // Draw the inner bezier curve
      ctxt.lineCap = this.options.cap;
      ctxt.strokeStyle = this.options.color;
      ctxt.lineWidth = this.options.width;
      ctxt.beginPath();
      ctxt.moveTo(bezierPoints[0][0],bezierPoints[0][1]);
      ctxt.bezierCurveTo(bezierPoints[1][0],bezierPoints[1][1],bezierPoints[2][0],bezierPoints[2][1],bezierPoints[3][0],bezierPoints[3][1]);
      ctxt.stroke();

   },

   /**
    * This function returns terminal1 if the first argument is terminal2 and vice-versa
    * @method getOtherTerminal
    * @param   {WireIt.Terminal} terminal
    * @return  {WireIt.Terminal} terminal    the terminal that is NOT passed as argument
    */
   getOtherTerminal: function(terminal) {
      return (terminal == this.terminal1) ? this.terminal2 : this.terminal1;
   },

   /**
    * Drawing methods for arrows
    * @method drawArrows
    */
   drawArrows: function()
   {
   	var d = 7; // arrow width/2
      var redim = d+3; //we have to make the canvas a little bigger because of arrows
      var margin=[4+redim,4+redim];

      // Get the positions of the terminals
      var p1 = this.terminal1.getXY();
      var p2 = this.terminal2.getXY();

      var distance=Math.sqrt(Math.pow(p1[0]-p2[0],2)+Math.pow(p1[1]-p2[1],2));

      var min=[ Math.min(p1[0],p2[0])-margin[0], Math.min(p1[1],p2[1])-margin[1]];
      var max=[ Math.max(p1[0],p2[0])+margin[0], Math.max(p1[1],p2[1])+margin[1]];

      // Redimensionnement du canvas

      var lw=Math.abs(max[0]-min[0])+redim;
      var lh=Math.abs(max[1]-min[1])+redim;

      p1[0]=p1[0]-min[0];
      p1[1]=p1[1]-min[1];
      p2[0]=p2[0]-min[0];
      p2[1]=p2[1]-min[1];

      this.SetCanvasRegion(min[0],min[1],lw,lh);

      var ctxt=this.getContext();

      // Draw the border
      ctxt.lineCap=this.options.bordercap;
      ctxt.strokeStyle=this.options.bordercolor;
      ctxt.lineWidth=this.options.width+this.options.borderwidth*2;
      ctxt.beginPath();
      ctxt.moveTo(p1[0],p1[1]);
      ctxt.lineTo(p2[0],p2[1]);
      ctxt.stroke();

      // Draw the inner bezier curve
      ctxt.lineCap=this.options.cap;
      ctxt.strokeStyle=this.options.color;
      ctxt.lineWidth=this.options.width;
      ctxt.beginPath();
      ctxt.moveTo(p1[0],p1[1]);
      ctxt.lineTo(p2[0],p2[1]);
      ctxt.stroke();

   	/* start drawing arrows */

   	var t1 = p1;
   	var t2 = p2;

   	var z = [0,0]; //point on the wire with constant distance (dlug) from terminal2
   	var dlug = 20; //arrow length
   	var t = 1-(dlug/distance);
   	z[0] = Math.abs( t1[0] +  t*(t2[0]-t1[0]) );
   	z[1] = Math.abs( t1[1] + t*(t2[1]-t1[1]) );

   	//line which connects the terminals: y=ax+b
   	var W = t1[0] - t2[0];
   	var Wa = t1[1] - t2[1];
   	var Wb = t1[0]*t2[1] - t1[1]*t2[0];
   	if (W != 0)
   	{
   		a = Wa/W;
   		b = Wb/W;
   	}
   	else
   	{
   		a = 0;
   	}
   	//line perpendicular to the main line: y = aProst*x + b
   	if (a == 0)
   	{
   		aProst = 0;
   	}
   	else
   	{
   		aProst = -1/a;
   	}
   	bProst = z[1] - aProst*z[0]; //point z lays on this line

   	//we have to calculate coordinates of 2 points, which lay on perpendicular line and have the same distance (d) from point z
   	var A = 1 + Math.pow(aProst,2);
   	var B = 2*aProst*bProst - 2*z[0] - 2*z[1]*aProst;
   	var C = -2*z[1]*bProst + Math.pow(z[0],2) + Math.pow(z[1],2) - Math.pow(d,2) + Math.pow(bProst,2);
   	var delta = Math.pow(B,2) - 4*A*C;
   	if (delta < 0) { return; }

   	var x1 = (-B + Math.sqrt(delta)) / (2*A);
   	var x2 = (-B - Math.sqrt(delta)) / (2*A);
   	var y1 = aProst*x1 + bProst;
   	var y2 = aProst*x2 + bProst;

   	if(t1[1] == t2[1]) {
   	      var o = (t1[0] > t2[0]) ? 1 : -1;
      	   x1 = t2[0]+o*dlug;
      	   x2 = x1;
      	   y1 -= d;
      	   y2 += d;
   	}

   	//triangle fill
   	ctxt.fillStyle = this.options.color;
   	ctxt.beginPath();
   	ctxt.moveTo(t2[0],t2[1]);
   	ctxt.lineTo(x1,y1);
   	ctxt.lineTo(x2,y2);
   	ctxt.fill();

   	//triangle border
   	ctxt.strokeStyle = this.options.bordercolor;
   	ctxt.lineWidth = this.options.borderwidth;
   	ctxt.beginPath();
   	ctxt.moveTo(t2[0],t2[1]);
   	ctxt.lineTo(x1,y1);
   	ctxt.lineTo(x2,y2);
   	ctxt.lineTo(t2[0],t2[1]);
   	ctxt.stroke();

   },

   /**
    * Drawing method for arrows
    * @method drawStraight
    */
   drawStraight: function()
   {
      var margin = [4,4];

      // Get the positions of the terminals
      var p1 = this.terminal1.getXY();
      var p2 = this.terminal2.getXY();

      var min=[ Math.min(p1[0],p2[0])-margin[0], Math.min(p1[1],p2[1])-margin[1]];
      var max=[ Math.max(p1[0],p2[0])+margin[0], Math.max(p1[1],p2[1])+margin[1]];

      // Redimensionnement du canvas
      var lw=Math.abs(max[0]-min[0]);
      var lh=Math.abs(max[1]-min[1]);

      // Convert points in canvas coordinates
      p1[0] = p1[0]-min[0];
      p1[1] = p1[1]-min[1];
      p2[0] = p2[0]-min[0];
      p2[1] = p2[1]-min[1];

      this.SetCanvasRegion(min[0],min[1],lw,lh);

      var ctxt=this.getContext();

      // Draw the border
      ctxt.lineCap=this.options.bordercap;
      ctxt.strokeStyle=this.options.bordercolor;
      ctxt.lineWidth=this.options.width+this.options.borderwidth*2;
      ctxt.beginPath();
      ctxt.moveTo(p1[0],p1[1]);
      ctxt.lineTo(p2[0],p2[1]);
      ctxt.stroke();

      // Draw the inner bezier curve
      ctxt.lineCap=this.options.cap;
      ctxt.strokeStyle=this.options.color;
      ctxt.lineWidth=this.options.width;
      ctxt.beginPath();
      ctxt.moveTo(p1[0],p1[1]);
      ctxt.lineTo(p2[0],p2[1]);
      ctxt.stroke();
   },

   /**
    * @method redraw
    */
   redraw: function() {
      if(this.options.drawingMethod == 'straight') {
         this.drawStraight();
      }
      else if(this.options.drawingMethod == 'arrows') {
         this.drawArrows();
      }
      else if(this.options.drawingMethod == 'bezier') {
         this.drawBezierCurve();
      }
      else {
         throw new Error("WireIt.Wire unable to find '"+this.drawingMethod+"' drawing method.");
      }
   },

   /**
    * @method wireDrawnAt
    * @return {Boolean} true if the wire is at x,y
    */
   wireDrawnAt: function(x,y) {
      var ctxt = this.getContext();
	   var imgData = ctxt.getImageData(x,y,1,1);
	   var pixel = imgData.data;
	   return !( pixel[0] == 0 && pixel[1] == 0 && pixel[2] == 0 && pixel[3] == 0 );
   },

   /**
    * Called by the Layer when the mouse moves over the canvas element.
    * Note: the event is not listened directly, to receive the event event if the wire is behind another wire
    * @method onWireMove
    * @param {Integer} x left position of the mouse (relative to the canvas)
    * @param {Integer} y top position of the mouse (relative to the canvas)
    */
   onMouseMove: function(x,y) {

      if(typeof this.mouseInState === undefined) {
         this.mouseInState = false;
      }

	   if( this.wireDrawnAt(x,y) ) {
			if(!this.mouseInState) {
			   this.mouseInState=true;
			   this.onWireIn(x,y);
			}
			// should we call both ??
			// else {
			this.onWireMove(x,y);
			// }
	   }
	   else {
	      if(this.mouseInState) {
	         this.mouseInState=false;
			   this.onWireOut(x,y);
	      }
	   }

   },

   /**
    * When the mouse moves over a wire
    * Note: this will only work within a layer
    * @method onWireMove
    * @param {Integer} x left position of the mouse (relative to the canvas)
    * @param {Integer} y top position of the mouse (relative to the canvas)
    */
   onWireMove: function(x,y) {
      console.log("onWireMove",x,y);
   },

   /**
    * When the mouse comes into the wire
    * Note: this will only work within a layer
    * @method onWireIn
    * @param {Integer} x left position of the mouse (relative to the canvas)
    * @param {Integer} y top position of the mouse (relative to the canvas)
    */
   onWireIn: function(x,y) {
      this.options.color = 'rgb(255, 0, 0)';
      this.redraw();
   },

   /**
    * When the mouse comes out of the wire
    * Note: this will only work within a layer
    * @method onWireOut
    * @param {Integer} x left position of the mouse (relative to the canvas)
    * @param {Integer} y top position of the mouse (relative to the canvas)
    */
   onWireOut: function(x,y) {
       this.options.color = 'rgb(173, 216, 230)';
      this.redraw();
   },

   /**
    * When the mouse clicked on the canvas
    * Note: this will only work within a layer
    * @method onClick
    * @param {Integer} x left position of the mouse (relative to the canvas)
    * @param {Integer} y top position of the mouse (relative to the canvas)
    */
   onClick: function(x,y) {
 	   if( this.wireDrawnAt(x,y) ) {
 	      this.onWireClick(x,y);
      }
   },

   /**
    * When the mouse clicked on the wire
    * Note: this will only work within a layer
    * @method onWireClick
    * @param {Integer} x left position of the mouse (relative to the canvas)
    * @param {Integer} y top position of the mouse (relative to the canvas)
    */
   onWireClick: function(x,y) {
 	   console.log("onWireClick",x,y);
   }

});


text:
import pytest

from core import models

@pytest.mark.parametrize('filename, ext', [
    ('image.png', '.png'),
    ('noext', ''),
])
def test_get_file_path(filename, ext):
    new_filename = models._get_file_path(None, filename)
    assert new_filename.endswith(f'{ext}')

redpajama_set_name: RedPajamaGithub


text:
package cn.elvea.platform.commons.oapis.feishu.service;

import com.larksuite.oapi.service.authen.v1.AuthenService;
import com.larksuite.oapi.service.contact.v3.ContactService;

/**
 * 基于飞书官方SDK二次封装
 * <p>
 * https://github.com/larksuite/oapi-sdk-java
 *
 * @author elvea
 * @since 0.0.1
 */
public interface LarkService {

    /**
     * @see AuthenService
     */
    AuthenService getAuthenService();

    /**
     * @see ContactService
     */
    ContactService getContactService();

}


text:
(function(app) {
    app.controller("productCategoryAddController", productCategoryAddController);

    productCategoryAddController.$inject = ["$scope", "apiService", "notificationService", "$state", "commonService"];

    function productCategoryAddController($scope, apiService, notificationService, $state, commonService) {
        $scope.productCategory = {
            CreatedDate: new Date(),
            Status: true,
            Name: "Danh mục 1"
        };
        $scope.GetSeoTitle = GetSeoTitle;

        function GetSeoTitle() {
            $scope.productCategory.Alias = commonService.getSeoTitle($scope.productCategory.Name);
        }

        $scope.addproductCategory = addproductCategory;

        function addproductCategory() {
            apiService.post("/api/productcategory/create",
                $scope.productCategory,
                function(result) {
                    notificationService.displaySuccess(result.data.Name + " đã được thêm mới.");
                    $state.go("product_categories");
                },
                function(error) {
                    notificationService.displayError("Thêm mới không thành công");
                });
        }

        function loadParentCategory() {
            apiService.get("/api/productcategory/getallparents",
                null,
                function(result) {
                    $scope.parentCategories = result.data;
                },
                function() {
                    console.log("Can not get list parent");
                });
        }

        loadParentCategory();

    }

})(angular.module("unishop.product_categories"));


text:
using PFM.DataAccessLayer.Repositories.Interfaces;
using PFM.DataAccessLayer.Entities;
using Microsoft.EntityFrameworkCore;

namespace PFM.DataAccessLayer.Repositories.Implementations
{
    public class FrequenceOptionRepository : IFrequenceOptionRepository
    {
        private readonly PFMContext _db;

        public FrequenceOptionRepository(PFMContext db)
        {
            this._db = db;
        }

        public DbSet<FrequenceOption> GetList()
        {
            return _db.Set<FrequenceOption>();
        }
    }
}


text:
package org.apache.mxnet

import org.apache.mxnet.init.Base._
import org.apache.mxnet.utils.CToScalaUtils

import scala.collection.mutable.ListBuffer

/**
  * This object will generate the Scala documentation of the new Scala API
  * Two file namely: SymbolAPIBase.scala and NDArrayAPIBase.scala
  * The code will be executed during Macros stage and file live in Core stage
  */
private[mxnet] object APIDocGenerator{
  case class absClassArg(argName : String, argType : String, argDesc : String, isOptional : Boolean)
  case class absClassFunction(name : String, desc : String,
                           listOfArgs: List[absClassArg], returnType : String)

  def main(args: Array[String]) : Unit = {
    val FILE_PATH = args(0)
    absClassGen(FILE_PATH, true)
    absClassGen(FILE_PATH, false)
  }

  def absClassGen(FILE_PATH : String, isSymbol : Boolean) : Unit = {
    // scalastyle:off
    val absClassFunctions = getSymbolNDArrayMethods(isSymbol)
    // TODO: Add Filter to the same location in case of refactor
    val absFuncs = absClassFunctions.filterNot(_.name.startsWith("_")).map(absClassFunction => {
      val scalaDoc = generateAPIDocFromBackend(absClassFunction)
      val defBody = generateAPISignature(absClassFunction, isSymbol)
      s"$scalaDoc\n$defBody"
    })
    val packageName = if (isSymbol) "SymbolAPIBase" else "NDArrayAPIBase"
    val apacheLicence = "/*\n* Licensed to the Apache Software Foundation (ASF) under one or more\n* contributor license agreements.  See the NOTICE file distributed with\n* this work for additional information regarding copyright ownership.\n* The ASF licenses this file to You under the Apache License, Version 2.0\n* (the \"License\"); you may not use this file except in compliance with\n* the License.  You may obtain a copy of the License at\n*\n*    http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n"
    val scalaStyle = "// scalastyle:off"
    val packageDef = "package org.apache.mxnet"
    val imports = "import org.apache.mxnet.annotation.Experimental"
    val absClassDef = s"abstract class $packageName"
    val finalStr = s"$apacheLicence\n$scalaStyle\n$packageDef\n$imports\n$absClassDef {\n${absFuncs.mkString("\n")}\n}"
    import java.io._
    val pw = new PrintWriter(new File(FILE_PATH + s"$packageName.scala"))
    pw.write(finalStr)
    pw.close()
  }

  // Generate ScalaDoc type
  def generateAPIDocFromBackend(func : absClassFunction) : String = {
    val desc = func.desc.split("\n").map({ currStr =>
      s"  * $currStr"
    })
    val params = func.listOfArgs.map({ absClassArg =>
      val currArgName = absClassArg.argName match {
                case "var" => "vari"
                case "type" => "typeOf"
                case _ => absClassArg.argName
      }
      s"  * @param $currArgName\t\t${absClassArg.argDesc}"
    })
    val returnType = s"  * @return ${func.returnType}"
    s"  /**\n${desc.mkString("\n")}\n${params.mkString("\n")}\n$returnType\n  */"
  }

  def generateAPISignature(func : absClassFunction, isSymbol : Boolean) : String = {
    var argDef = ListBuffer[String]()
    func.listOfArgs.foreach(absClassArg => {
      val currArgName = absClassArg.argName match {
        case "var" => "vari"
        case "type" => "typeOf"
        case _ => absClassArg.argName
      }
      if (absClassArg.isOptional) {
        argDef += s"$currArgName : Option[${absClassArg.argType}] = None"
      }
      else {
        argDef += s"$currArgName : ${absClassArg.argType}"
      }
    })
    var returnType = func.returnType
    if (isSymbol) {
      argDef += "name : String = null"
      argDef += "attr : Map[String, String] = null"
    } else {
      argDef += "out : Option[NDArray] = None"
      returnType = "org.apache.mxnet.NDArrayFuncReturn"
    }
    val experimentalTag = "@Experimental"
    s"$experimentalTag\ndef ${func.name} (${argDef.mkString(", ")}) : $returnType"
  }

  // List and add all the atomic symbol functions to current module.
  private def getSymbolNDArrayMethods(isSymbol : Boolean): List[absClassFunction] = {
    val opNames = ListBuffer.empty[String]
    val returnType = if (isSymbol) "Symbol" else "NDArray"
    _LIB.mxListAllOpNames(opNames)
    // TODO: Add '_linalg_', '_sparse_', '_image_' support
    opNames.map(opName => {
      val opHandle = new RefLong
      _LIB.nnGetOpHandle(opName, opHandle)
      makeAtomicSymbolFunction(opHandle.value, opName, "org.apache.mxnet." + returnType)
    }).toList
  }

  // Create an atomic symbol function by handle and function name.
  private def makeAtomicSymbolFunction(handle: SymbolHandle, aliasName: String, returnType : String)
  : absClassFunction = {
    val name = new RefString
    val desc = new RefString
    val keyVarNumArgs = new RefString
    val numArgs = new RefInt
    val argNames = ListBuffer.empty[String]
    val argTypes = ListBuffer.empty[String]
    val argDescs = ListBuffer.empty[String]

    _LIB.mxSymbolGetAtomicSymbolInfo(
      handle, name, desc, numArgs, argNames, argTypes, argDescs, keyVarNumArgs)

    val realName = if (aliasName == name.value) "" else s"(a.k.a., ${name.value})"

    val argList = argNames zip argTypes zip argDescs map { case ((argName, argType), argDesc) =>
      val typeAndOption = CToScalaUtils.argumentCleaner(argType, returnType)
      new absClassArg(argName, typeAndOption._1, argDesc, typeAndOption._2)
    }
    new absClassFunction(aliasName, desc.value, argList.toList, returnType)
  }
}


text:
from django.conf.urls import patterns, url
from mysite import settings

from polls import views

urlpatterns = patterns("",
        url(r"^$", views.index, name="index"),
	url(r"^sound$", views.sound, name="sound")
)


text:
@if (session('success'))

{{ session('success') }}

@elseif (session('error'))

{{ session('error') }}

@endif


text:
enum {
	kTagParentNode = 1,
};

#pragma mark - HelloWorldLayer

@interface HelloWorldLayer2 ()
-(void) addNewSpriteAtPosition:(CGPoint)pos;
-(void) createMenu;
-(void) initPhysics;
@end

@implementation HelloWorldLayer2

// Helper class method that creates a Scene with the HelloWorldLayer as the only child.
+(CCScene *) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];

	// 'layer' is an autorelease object.
	HelloWorldLayer2 *layer = [HelloWorldLayer2 node];

	// add layer as a child to scene
	[scene addChild: layer];

	// return the scene
	return scene;
}

-(id) init
{
	if( (self=[super init])) {

		// enable events
#ifdef __CC_PLATFORM_IOS
		self.touchEnabled = YES;
		self.accelerometerEnabled = YES;
#elif defined(__CC_PLATFORM_MAC)
		self.mouseEnabled = YES;
#endif

		CGSize s = [[CCDirector sharedDirector] winSize];

		// title
		CCLabelTTF *label = [CCLabelTTF labelWithString:@"Multi touch the screen" fontName:@"Marker Felt" fontSize:36];
		label.position = ccp( s.width / 2, s.height - 30);
		[self addChild:label z:-1];

		// reset button
		[self createMenu];

		// init physics
		[self initPhysics];

#if 1
		// Use batch node. Faster
		CCSpriteBatchNode *parent = [CCSpriteBatchNode batchNodeWithFile:@"grossini_dance_atlas.png" capacity:100];
		_spriteTexture = [parent texture];
#else
		// doesn't use batch node. Slower
		_spriteTexture = [[CCTextureCache sharedTextureCache] addImage:@"grossini_dance_atlas.png"];
		CCNode *parent = [CCNode node];
#endif
		[self addChild:parent z:0 tag:kTagParentNode];

		[self addNewSpriteAtPosition:ccp(200,200)];

		[self scheduleUpdate];
	}

	return self;
}

-(void) initPhysics
{
	CGSize s = [[CCDirector sharedDirector] winSize];

	_space = cpSpaceNew();

	cpSpaceSetGravity( _space, cpv(0, -100) );

	//
	// rogue shapes
	// We have to free them manually
	//
	// bottom
	_walls[0] = cpSegmentShapeNew( _space->staticBody, cpv(0,0), cpv(s.width,0), 0.0f);

	// top
	_walls[1] = cpSegmentShapeNew( _space->staticBody, cpv(0,s.height), cpv(s.width,s.height), 0.0f);

	// left
	_walls[2] = cpSegmentShapeNew( _space->staticBody, cpv(0,0), cpv(0,s.height), 0.0f);

	// right
	_walls[3] = cpSegmentShapeNew( _space->staticBody, cpv(s.width,0), cpv(s.width,s.height), 0.0f);

	for( int i=0;i<4;i++) {
		cpShapeSetElasticity( _walls[i], 1.0f );
		cpShapeSetFriction( _walls[i], 1.0f );
		cpSpaceAddStaticShape(_space, _walls[i] );
	}

	_debugLayer = [CCPhysicsDebugNode debugNodeForCPSpace:_space];
	_debugLayer.visible = NO;
	[self addChild:_debugLayer z:100];
}

-(void) update:(ccTime) delta
{
	// Should use a fixed size step based on the animation interval.
	int steps = 2;
	CGFloat dt = [[CCDirector sharedDirector] animationInterval]/(CGFloat)steps;

	for(int i=0; i<steps; i++){
		cpSpaceStep(_space, dt);
	}
}

-(void) createMenu
{
	// Default font size will be 22 points.
	[CCMenuItemFont setFontSize:22];

	// Reset Button
	CCMenuItemLabel *reset = [CCMenuItemFont itemWithString:@"Reset" block:^(id sender){
		[[CCDirector sharedDirector] replaceScene: [HelloWorldLayer2 scene]];
	}];

	// Debug Button
	CCMenuItemLabel *debug = [CCMenuItemFont itemWithString:@"Toggle Debug" block:^(id sender){
		[_debugLayer setVisible: !_debugLayer.visible];
	}];

	// to avoid a retain-cycle with the menuitem and blocks
	__block id copy_self = self;

	// Achievement Menu Item using blocks
	CCMenuItem *itemAchievement = [CCMenuItemFont itemWithString:@"Achievements" block:^(id sender) {

		GKAchievementViewController *achivementViewController = [[GKAchievementViewController alloc] init];
		achivementViewController.achievementDelegate = copy_self;

		AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];

		[[app navController] presentModalViewController:achivementViewController animated:YES];

	}];

	// Leaderboard Menu Item using blocks
	CCMenuItem *itemLeaderboard = [CCMenuItemFont itemWithString:@"Leaderboard" block:^(id sender) {

		GKLeaderboardViewController *leaderboardViewController = [[GKLeaderboardViewController alloc] init];
		leaderboardViewController.leaderboardDelegate = copy_self;

		AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];

		[[app navController] presentModalViewController:leaderboardViewController animated:YES];

	}];

	CCMenu *menu = [CCMenu menuWithItems:itemAchievement, itemLeaderboard, debug, reset, nil];

	[menu alignItemsVertically];

	CGSize size = [[CCDirector sharedDirector] winSize];
	[menu setPosition:ccp( size.width/2, size.height/2)];

	[self addChild: menu z:-1];
}

-(void) addNewSpriteAtPosition:(CGPoint)pos
{
	// physics body
	int num = 4;
	cpVect verts[] = {
		cpv(-24,-54),
		cpv(-24, 54),
		cpv( 24, 54),
		cpv( 24,-54),
	};

	cpBody *body = cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, CGPointZero));
	cpBodySetPos( body, pos );
	cpSpaceAddBody(_space, body);

	cpShape* shape = cpPolyShapeNew(body, num, verts, CGPointZero);
	cpShapeSetElasticity( shape, 0.5f );
	cpShapeSetFriction( shape, 0.5f );
	cpSpaceAddShape(_space, shape);

	// sprite
	CCNode *parent = [self getChildByTag:kTagParentNode];
	int posx = CCRANDOM_0_1() * 200.0f;
	int posy = CCRANDOM_0_1() * 200.0f;
	posx = (posx % 4) * 85;
	posy = (posy % 3) * 121;

	CCPhysicsSprite *sprite = [CCPhysicsSprite spriteWithTexture:_spriteTexture rect:CGRectMake(posx, posy, 85, 121)];
	[parent addChild: sprite];
	[sprite setCPBody:body];
	[sprite setPosition: pos];
}

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	for( UITouch *touch in touches ) {
		CGPoint location = [touch locationInView: [touch view]];

		location = [[CCDirector sharedDirector] convertToGL: location];

		[self addNewSpriteAtPosition: location];
	}
}

- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{
	static float prevX=0, prevY=0;

#define kFilterFactor 0.05f

	float accelX = (float) acceleration.x * kFilterFactor + (1- kFilterFactor)*prevX;
	float accelY = (float) acceleration.y * kFilterFactor + (1- kFilterFactor)*prevY;

	prevX = accelX;
	prevY = accelY;

	cpVect v;
	if( [[CCDirector sharedDirector] interfaceOrientation] == UIInterfaceOrientationLandscapeRight )
		v = cpv( -accelY, accelX);
	else
		v = cpv( accelY, -accelX);

	cpSpaceSetGravity( _space, cpvmult(v, 200) );
}

#pragma mark GameKit delegate

-(void) achievementViewControllerDidFinish:(GKAchievementViewController *)viewController
{
	AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
	[[app navController] dismissModalViewControllerAnimated:YES];
}

-(void) leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
	AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
	[[app navController] dismissModalViewControllerAnimated:YES];
}

@end


text:
package org.apache.drill.exec.physical.impl.scan;

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

import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.exec.physical.impl.scan.ScanTestUtils.ScanFixture;
import org.apache.drill.exec.physical.impl.scan.ScanTestUtils.ScanFixtureBuilder;
import org.apache.drill.exec.physical.impl.scan.framework.BasicScanFactory;
import org.apache.drill.exec.physical.impl.scan.framework.ManagedReader;
import org.apache.drill.exec.physical.impl.scan.framework.ManagedScanFramework.ScanFrameworkBuilder;
import org.apache.drill.exec.physical.impl.scan.framework.SchemaNegotiator;
import org.apache.drill.exec.physical.resultSet.ResultSetLoader;
import org.apache.drill.exec.physical.resultSet.RowSetLoader;
import org.apache.drill.exec.record.VectorContainer;
import org.apache.drill.exec.record.metadata.SchemaBuilder;
import org.apache.drill.exec.record.metadata.TupleMetadata;
import org.apache.drill.test.SubOperatorTest;
import org.apache.drill.exec.physical.rowSet.RowSet.SingleRowSet;
import org.apache.drill.test.rowSet.RowSetUtilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Test of the scan operator framework. Here the focus is on the
 * implementation of the scan operator itself. This operator is
 * based on a number of lower-level abstractions, each of which has
 * its own unit tests. To make this more concrete: review the scan
 * operator code paths. Each path should be exercised by one or more
 * of the tests here. If, however, the code path depends on the
 * details of another, supporting class, then tests for that class
 * appear elsewhere.
 */
public class BaseScanOperatorExecTest extends SubOperatorTest {
  static final Logger logger = LoggerFactory.getLogger(BaseScanOperatorExecTest.class);

  /**
   * Base class for the "mock" readers used in this test. The mock readers
   * follow the normal (enhanced) reader API, but instead of actually reading
   * from a data source, they just generate data with a known schema.
   * They also expose internal state such as identifying which methods
   * were actually called.
   */
  protected static abstract class BaseMockBatchReader implements ManagedReader<SchemaNegotiator> {
    protected boolean openCalled;
    protected boolean closeCalled;
    protected int startIndex;
    protected int batchCount;
    protected int batchLimit;
    protected ResultSetLoader tableLoader;

    protected void makeBatch() {
      RowSetLoader writer = tableLoader.writer();
      int offset = (batchCount - 1) * 20 + startIndex;
      writeRow(writer, offset + 10, "fred");
      writeRow(writer, offset + 20, "wilma");
    }

    protected void writeRow(RowSetLoader writer, int col1, String col2) {
      writer.start();
      if (writer.column(0) != null) {
        writer.scalar(0).setInt(col1);
      }
      if (writer.column(1) != null) {
        writer.scalar(1).setString(col2);
      }
      writer.save();
    }

    @Override
    public void close() {
      closeCalled = true;
    }
  }

  /**
   * Mock reader that pretends to have a schema at open time
   * like an HBase or JDBC reader.
   */
  protected static class MockEarlySchemaReader extends BaseMockBatchReader {

    @Override
    public boolean open(SchemaNegotiator schemaNegotiator) {
      openCalled = true;
      TupleMetadata schema = new SchemaBuilder()
          .add("a", MinorType.INT)
          .addNullable("b", MinorType.VARCHAR, 10)
          .buildSchema();
      schemaNegotiator.tableSchema(schema, true);
      tableLoader = schemaNegotiator.build();
      return true;
    }

    @Override
    public boolean next() {
      batchCount++;
      if (batchCount > batchLimit) {
        return false;
      }

      makeBatch();
      return true;
    }
  }

  protected TupleMetadata expectedSchema() {
    return new SchemaBuilder()
        .add("a", MinorType.INT)
        .addNullable("b", MinorType.VARCHAR, 10)
        .buildSchema();
  }

  protected SingleRowSet makeExpected() {
    return makeExpected(0);
  }

  protected SingleRowSet makeExpected(int offset) {
    SingleRowSet expected = fixture.rowSetBuilder(expectedSchema())
        .addRow(offset + 10, "fred")
        .addRow(offset + 20, "wilma")
        .build();
    return expected;
  }

  protected void verifyBatch(int offset, VectorContainer output) {
    SingleRowSet expected = makeExpected(offset);
    RowSetUtilities.verify(expected, fixture.wrap(output));
  }

  public static class BaseScanFixtureBuilder extends ScanFixtureBuilder {

    public ScanFrameworkBuilder builder = new ScanFrameworkBuilder();
    public final List<ManagedReader<SchemaNegotiator>> readers = new ArrayList<>();

    public BaseScanFixtureBuilder() {
      super(fixture);
    }

    @Override
    public ScanFrameworkBuilder builder() { return builder; }

    public void addReader(ManagedReader<SchemaNegotiator> reader) {
      readers.add(reader);
    }

    public void addReaders(List<ManagedReader<SchemaNegotiator>> readers) {
      this.readers.addAll(readers);
    }

    @SuppressWarnings("unchecked")
    public void addReaders(ManagedReader<SchemaNegotiator>...readers) {
      for (ManagedReader<SchemaNegotiator> reader : readers) {
        addReader(reader);
      }
    }

    @Override
    public ScanFixture build() {
      builder.setReaderFactory(new BasicScanFactory(readers.iterator()));
      return super.build();
    }
  }

  @SafeVarargs
  public static BaseScanFixtureBuilder simpleBuilder(ManagedReader<SchemaNegotiator>...readers) {
    BaseScanFixtureBuilder builder = new BaseScanFixtureBuilder();
    builder.projectAll();
    builder.addReaders(readers);
    return builder;
  }

  @SafeVarargs
  public static ScanFixture simpleFixture(ManagedReader<SchemaNegotiator>...readers) {
    return simpleBuilder(readers).build();
  }
}


text:
#import "HSRazerTartarusProDevice.h"

@implementation HSRazerTartarusProDevice

- (id)initWithDevice:(IOHIDDeviceRef)device manager:(id)manager {
    self = [super initWithDevice:device manager:manager];
    if (self) {
        // The name of the Razer Device. This should match the actual product name (i.e. Razer Tartarus V2).
        self.name               = @"Razer Tartarus Pro";

        // The product ID of the Razer Device. This can be found in "About This Mac > System Report".
        // This should be a constant that's defined in razer.h, as you'll also need to manually update
        // HSRazerManger.m if you add a new Razer device to this extension.
        self.productID          = USB_PID_RAZER_TARTARUS_PRO;

        //  16 bit parameter for request, low byte first. Each device can have a different index.
        self.index              = 0x02;

        // Number of backlight rows and columns:
        self.backlightRows      = 4;
        self.backlightColumns   = 6;

        // The ID of the scroll wheel. If supplied, this will enable the event tap which ignores scroll wheel movements:
        self.scrollWheelID      = 56;

        // Which modes does this device support?
        self.supportsBacklightToOff             = YES;
        self.supportsBacklightToStaticColor     = YES;
        self.supportsBacklightToCustom          = YES;

        //
        // NOTE: Whilst Synapse 3 supports more effects, I believe they're done in
        //       software, not hardware, unlike the Razer Tartarus V2.
        //

        // Which Status Lights does this device support?
        self.supportsOrangeStatusLight          = YES;
        self.supportsGreenStatusLight           = YES;
        self.supportsBlueStatusLight            = YES;

        // A dictionary of button names. On the left is what is returned by IOHID, on the right is what we want to
        // label the buttons in Hammerspoon:
        self.buttonNames        = @{
            @"30" : @"1",
            @"31": @"2",
            @"32": @"3",
            @"33": @"4",
            @"34": @"5",
            @"43": @"6",
            @"20": @"7",
            @"26": @"8",
            @"8": @"9",
            @"21": @"10",
            @"57": @"11",
            @"4": @"12",
            @"22": @"13",
            @"7": @"14",
            @"9": @"15",
            @"225": @"16",
            @"29": @"17",
            @"27": @"18",
            @"6": @"19",
            @"44": @"20",
            @"56": @"Scroll Wheel",
            @"226": @"Mode",
            @"82": @"Up",
            @"81": @"Down",
            @"80": @"Left",
            @"79": @"Right"
        };

        // A dictionary of remapping values. On the left is "dummy" keys. On the right is actual HID Keyboard codes.
        // You can use this website to help determine the HID Keyboard codes: https://hidutil-generator.netlify.app
        self.remapping          = @{
            @"0x100000001" : @"0x70000001E",
            @"0x100000002" : @"0x70000001F",
            @"0x100000003" : @"0x700000020",
            @"0x100000004" : @"0x700000021",
            @"0x100000005" : @"0x700000022",
            @"0x100000006" : @"0x70000002B",
            @"0x100000007" : @"0x700000014",
            @"0x100000008" : @"0x70000001A",
            @"0x100000009" : @"0x700000008",
            @"0x100000010" : @"0x700000015",
            @"0x100000011" : @"0x700000039",
            @"0x100000012" : @"0x700000004",
            @"0x100000013" : @"0x700000016",
            @"0x100000014" : @"0x700000007",
            @"0x100000015" : @"0x700000009",
            @"0x100000016" : @"0x7000000E1",
            @"0x100000017" : @"0x70000001D",
            @"0x100000018" : @"0x70000001B",
            @"0x100000019" : @"0x700000006",
            @"0x100000020" : @"0x70000002C",
            @"0x100000021" : @"0x700000035",
            @"0x100000022" : @"0x700000052",
            @"0x100000023" : @"0x700000051",
            @"0x100000024" : @"0x700000050",
            @"0x100000025" : @"0x70000004F"
        };
    }
    return self;
}

#pragma mark - LED Backlights

- (HSRazerResult*)setBacklightToOff {
    return [self setBacklightToStaticColor:[NSColor blackColor]];
}

- (HSRazerResult*)setBacklightToStaticColor:(NSColor*)color {

    // Split NSColor into RGB Components:
    // SOURCE: https://developer.apple.com/library/archive/qa/qa1576/_index.html
    CGFloat redFloatValue, greenFloatValue, blueFloatValue;
    int redIntValue, greenIntValue, blueIntValue;

    NSColor *convertedColor = [color colorUsingColorSpace:[NSColorSpace genericRGBColorSpace]];
    [convertedColor getRed:&redFloatValue green:&greenFloatValue blue:&blueFloatValue alpha:NULL];

    redIntValue = redFloatValue * 255.99999f;
    greenIntValue = greenFloatValue * 255.99999f;
    blueIntValue = blueFloatValue * 255.99999f;

    NSNumber *red = [NSNumber numberWithInt:redIntValue];
    NSNumber *green = [NSNumber numberWithInt:greenIntValue];
    NSNumber *blue = [NSNumber numberWithInt:blueIntValue];

    /*
     ================================================================================================
     Direction   ID      000000      # Params    CMD Class   Command     Sub-CMD     Params
     ================================================================================================
     00          1f      000000      44          0f          03          00          00 00 00 14 ff0000 ff0000 ff0000 ff0000 ff0000
                                                                         0           1  2  3  4  5 6 7  8      11     14     17

                                                                                ff0000 ff0000 ff0000 ff0000 ff0000 ff0000 ff0000 ff0000
                                                                                20     23     26     29     32     35     38     41

                                                                                ff0000 ff0000 ff0000 ff0000 ff0000 ff0000 ff0000 ff0000 00
                                                                                44     47     50     53     56     59     62     65     68
     */

    NSMutableDictionary *arguments = [[NSMutableDictionary alloc]initWithCapacity:69];

    [arguments setObject:@0x00 forKey:@0];
    [arguments setObject:@0x00 forKey:@1];
    [arguments setObject:@0x00 forKey:@2];
    [arguments setObject:@0x00 forKey:@3];
    [arguments setObject:@0x14 forKey:@4];
    // All the colour data goes here.
    [arguments setObject:@0x00 forKey:@68];

    int count = 5;
    for (int buttonID = 1; buttonID <= 21; buttonID++)
    {
        [arguments setObject:red    forKey:[NSNumber numberWithInt:count++]];
        [arguments setObject:green  forKey:[NSNumber numberWithInt:count++]];
        [arguments setObject:blue   forKey:[NSNumber numberWithInt:count++]];
    }

    // Send the report to the Razer USB Device:
    return [self sendRazerReportToDeviceWithTransactionID:0x1f commandClass:0x0f commandID:0x03 arguments:arguments];
}

- (HSRazerResult*)setBacklightToCustomWithColors:(NSMutableDictionary *)customColors {
    /*
     ================================================================================================
     Direction   ID      000000      # Params    CMD Class   Command     Sub-CMD     Params
     ================================================================================================
     00          1f      000000      44          0f          03          00          00 00 00 14 ff0000 ff0000 ff0000 ff0000 ff0000
                                                                         0           1  2  3  4  5 6 7  8      11     14     17

                                                                                ff0000 ff0000 ff0000 ff0000 ff0000 ff0000 ff0000 ff0000
                                                                                20     23     26     29     32     35     38     41

                                                                                ff0000 ff0000 ff0000 ff0000 ff0000 ff0000 ff0000 ff0000 00
                                                                                44     47     50     53     56     59     62     65     68
     */

    NSMutableDictionary *arguments = [[NSMutableDictionary alloc]initWithCapacity:69];

    [arguments setObject:@0x00 forKey:@0];
    [arguments setObject:@0x00 forKey:@1];
    [arguments setObject:@0x00 forKey:@2];
    [arguments setObject:@0x00 forKey:@3];
    [arguments setObject:@0x14 forKey:@4];
    // All the colour data goes here between keys 5 and 67.
    [arguments setObject:@0x00 forKey:@68];

    int count = 5;
    for (int buttonID = 1; buttonID <= 21; buttonID++)
    {
        NSColor *currentColor = customColors[@(buttonID)];
        if (currentColor) {
            CGFloat redFloatValue, greenFloatValue, blueFloatValue;
            int redIntValue, greenIntValue, blueIntValue;

            NSColor *convertedColor = [currentColor colorUsingColorSpace:[NSColorSpace genericRGBColorSpace]];
            [convertedColor getRed:&redFloatValue green:&greenFloatValue blue:&blueFloatValue alpha:NULL];

            redIntValue = redFloatValue * 255.99999f;
            greenIntValue = greenFloatValue * 255.99999f;
            blueIntValue = blueFloatValue * 255.99999f;

            NSNumber *red = [NSNumber numberWithInt:redIntValue];
            NSNumber *green = [NSNumber numberWithInt:greenIntValue];
            NSNumber *blue = [NSNumber numberWithInt:blueIntValue];

            [arguments setObject:red    forKey:[NSNumber numberWithInt:count++]];
            [arguments setObject:green  forKey:[NSNumber numberWithInt:count++]];
            [arguments setObject:blue   forKey:[NSNumber numberWithInt:count++]];
        } else {
            NSNumber *red = [NSNumber numberWithInt:0];
            NSNumber *green = [NSNumber numberWithInt:0];
            NSNumber *blue = [NSNumber numberWithInt:0];

            [arguments setObject:red    forKey:[NSNumber numberWithInt:count++]];
            [arguments setObject:green  forKey:[NSNumber numberWithInt:count++]];
            [arguments setObject:blue   forKey:[NSNumber numberWithInt:count++]];
        }
    }

    // Send the report to the Razer USB Device:
    return [self sendRazerReportToDeviceWithTransactionID:0x1f commandClass:0x0f commandID:0x03 arguments:arguments];
}

#pragma mark - LED Brightness

- (HSRazerResult*)getBrightness {
    // Setup Arguments:
    NSDictionary *arguments = @{
        @0 : @0x00,
        @1 : @0x00,
        @2 : @0x00,
    };

    // Send the report to the Razer USB Device:
    HSRazerResult* result = [self sendRazerReportToDeviceWithTransactionID:0x1f commandClass:0x0f commandID:0x84 arguments:arguments];

    // The brightness comes back on argument 2 as 0-255, so we convert it to 0-100 range:
    if ([result success]) {
        unsigned char argumentTwo = [result argumentTwo];
        result.brightness = @(round(argumentTwo / 2.55));
    }

    return result;
}

- (HSRazerResult*)setBrightness:(NSNumber *)brightness {

    /*
     ================================================================================================
     Direction   ID      000000      # Params    CMD Class   Command     Sub-CMD     Params
     ================================================================================================
     00          1f      000000      03          0f          04          01          00 7f
                                                                         0           1  2
     */

    // We get the brightness in a 0-100 range, and we need to convert it to 0-255:
    brightness = @(round([brightness integerValue] * 2.55));

    // Setup Arguments:
    NSDictionary *arguments = @{
        @0 : @0x01,         // Sub Command
        @1 : @0x00,         // Reserved
        @2 : brightness,    // Brightness Value
    };

    // Send the report to the Razer USB Device:
    HSRazerResult* result = [self sendRazerReportToDeviceWithTransactionID:0x1f commandClass:0x0f commandID:0x04 arguments:arguments];

    // The brightness comes back on argument 2 as 0-255, so we convert it to 0-100 range:
    if ([result success]) {
        unsigned char argumentTwo = [result argumentTwo];
        result.brightness = @(round(argumentTwo / 2.55));
    }

    return result;
}

#pragma mark - Status Lights

- (HSRazerResult*)setOrangeStatusLight:(BOOL)active {

    /*
     =======================================================================================================
     Direction   ID      000000      # Params    CMD Class   Command     Sub-CMD     Params
     =======================================================================================================
     00          1f      000000      09          0f          02          01          0b 01 00 01 01 ff 00 00
                                                                         0           1  2  3  4  5  6  7  8
    */

    // First we need to get the green and blue status:
    HSRazerResult *greenResult = [self getGreenStatusLight];
    HSRazerResult *blueResult = [self getBlueStatusLight];

    NSNumber *greenStatus = @0x00;
    if ([greenResult success]) {
        int argumentSeven = [greenResult argumentSeven];
        if (argumentSeven == 0xff) {
            greenStatus = @0xff;
        }
    }

    NSNumber *blueStatus = @0x00;
    if ([blueResult success]) {
        int argumentEight = [blueResult argumentEight];
        if (argumentEight == 0xff) {
            blueStatus = @0xff;
        }
    }

    unsigned char onOrOff = 0x00;
    if (active) {
        onOrOff = 0xff;
    }

    // Setup Arguments:
    NSDictionary *arguments = @{
        @0 : @0x01,
        @1 : @0x0b,
        @2 : @0x01,
        @3 : @0x00,
        @4 : @0x01,
        @5 : @0x01,
        @6 : @(onOrOff),        // Orange
        @7 : greenStatus,       // Green
        @8 : blueStatus,        // Blue
    };

    // Send the report to the Razer USB Device:
    return [self sendRazerReportToDeviceWithTransactionID:0x1f commandClass:0x0f commandID:0x02 arguments:arguments];
}

- (HSRazerResult*)getOrangeStatusLight {
    /*
     =======================================================================================================
     Direction   ID      000000      # Params    CMD Class   Command     Sub-CMD     Params
     =======================================================================================================
     00          1f      000000      06          0f          02          00          00 08 00 01 00
    */

    // Setup Arguments:
    NSDictionary *arguments = @{
        @0 : @0x01,
        @1 : @0x0b,
        @2 : @0x01,
        @3 : @0x00,
        @4 : @0x01,
        @5 : @0x01,
        @6 : @0x00,     // Orange Status
        @7 : @0x00,     // Green Status
        @8 : @0x00,     // Blue Status
    };

    // Send the report to the Razer USB Device:
    HSRazerResult* result = [self sendRazerReportToDeviceWithTransactionID:0x1f commandClass:0x0f commandID:0x82 arguments:arguments];

    // The status comes back on argument two:
    if ([result success]) {
        int argumentSix = [result argumentSix];
        if (argumentSix == 0xff) {
            result.orangeStatusLight = YES;
        } else {
            result.orangeStatusLight = NO;
        }
    }

    return result;
}

- (HSRazerResult*)setGreenStatusLight:(BOOL)active {
    /*
     =======================================================================================================
     Direction   ID      000000      # Params    CMD Class   Command     Sub-CMD     Params
     =======================================================================================================
     00          1f      000000      09          0f          02          01          0b 01 00 01 01 00 ff 00
                                                                         0           1  2  3  4  5  6  7  8
    */

    // First we need to get the orange and blue status:
    HSRazerResult *orangeResult = [self getOrangeStatusLight];
    HSRazerResult *blueResult = [self getBlueStatusLight];

    NSNumber *orangeStatus = @0x00;
    if ([orangeResult success]) {
        int argumentSix = [orangeResult argumentSix];
        if (argumentSix == 0xff) {
            orangeStatus = @0xff;
        }
    }

    NSNumber *blueStatus = @0x00;
    if ([blueResult success]) {
        int argumentEight = [blueResult argumentEight];
        if (argumentEight == 0xff) {
            blueStatus = @0xff;
        }
    }

    unsigned char onOrOff = 0x00;
    if (active) {
        onOrOff = 0xff;
    }

    // Setup Arguments:
    NSDictionary *arguments = @{
        @0 : @0x01,
        @1 : @0x0b,
        @2 : @0x01,
        @3 : @0x00,
        @4 : @0x01,
        @5 : @0x01,
        @6 : orangeStatus,      // Orange
        @7 : @(onOrOff),        // Green
        @8 : blueStatus,        // Blue
    };

    // Send the report to the Razer USB Device:
    return [self sendRazerReportToDeviceWithTransactionID:0x1f commandClass:0x0f commandID:0x02 arguments:arguments];
}

- (HSRazerResult*)getGreenStatusLight {

    // Setup Arguments:
    NSDictionary *arguments = @{
        @0 : @0x01,
        @1 : @0x0b,
        @2 : @0x01,
        @3 : @0x00,
        @4 : @0x01,
        @5 : @0x01,
        @6 : @0x00,
        @7 : @0x00, // Green Status
        @8 : @0x00,
    };

    // Send the report to the Razer USB Device:
    HSRazerResult* result = [self sendRazerReportToDeviceWithTransactionID:0x1f commandClass:0x0f commandID:0x82 arguments:arguments];

    // The status comes back on argument two:
    if ([result success]) {
        int argumentSeven = [result argumentSeven];
        if (argumentSeven == 0xff) {
            result.greenStatusLight = YES;
        } else {
            result.greenStatusLight = NO;
        }
    }

    return result;
}

- (HSRazerResult*)setBlueStatusLight:(BOOL)active {
    /*
     =======================================================================================================
     Direction   ID      000000      # Params    CMD Class   Command     Sub-CMD     Params
     =======================================================================================================
     00          1f      000000      09          0f          02          01          0b 01 00 01 01 00 00 ff
                                                                         0           1  2  3  4  5  6  7  8
    */

    // First we need to get the orange and green status:
    HSRazerResult *orangeResult = [self getOrangeStatusLight];
    HSRazerResult *greenResult = [self getGreenStatusLight];

    NSNumber *orangeStatus = @0x00;
    if ([orangeResult success]) {
        int argumentSix = [orangeResult argumentSix];
        if (argumentSix == 0xff) {
            orangeStatus = @0xff;
        }
    }

    NSNumber *greenStatus = @0x00;
    if ([greenResult success]) {
        int argumentSeven = [greenResult argumentSeven];
        if (argumentSeven == 0xff) {
            greenStatus = @0xff;
        }
    }

    unsigned char onOrOff = 0x00;
    if (active) {
        onOrOff = 0xff;
    }

    // Setup Arguments:
    NSDictionary *arguments = @{
        @0 : @0x01,
        @1 : @0x0b,
        @2 : @0x01,
        @3 : @0x00,
        @4 : @0x01,
        @5 : @0x01,
        @6 : orangeStatus,
        @7 : greenStatus,
        @8 : @(onOrOff),
    };

    // Send the report to the Razer USB Device:
    return [self sendRazerReportToDeviceWithTransactionID:0x1f commandClass:0x0f commandID:0x02 arguments:arguments];
}

- (HSRazerResult*)getBlueStatusLight {

    // Setup Arguments:
    NSDictionary *arguments = @{
        @0 : @0x01,
        @1 : @0x0b,
        @2 : @0x01,
        @3 : @0x00,
        @4 : @0x01,
        @5 : @0x01,
        @6 : @0x00,
        @7 : @0x00,
        @8 : @0x00, // Blue Status
    };

    // Send the report to the Razer USB Device:
    HSRazerResult* result = [self sendRazerReportToDeviceWithTransactionID:0x1f commandClass:0x0f commandID:0x82 arguments:arguments];

    // The status comes back on argument two:
    if ([result success]) {
        int argumentEight = [result argumentEight];
        if (argumentEight == 0xff) {
            result.blueStatusLight = YES;
        } else {
            result.blueStatusLight = NO;
        }
    }

    return result;
}

@end


text:
title: AesiDebugRunnerSettings.writeExternal - aesi-intellij
---

[aesi-intellij](../../index.html) / [org.metaborg.paplj.debugger](../index.html) / [AesiDebugRunnerSettings](index.html) / [writeExternal](.)

# writeExternal

`fun writeExternal(element: Element?): `[`Unit`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html)


text:
package org.barisakkurt.istanbulandroid;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class BaseActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_base);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.base, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case R.id.menu_about:
			openAboutActivity();
			return true;

		case R.id.menu_contact:
			openContactActivity();
			return true;

		case R.id.menu_rate_app:
			openRateApp();
			return true;

		case R.id.menu_settings:
			openSettingsActivity();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}

	}

	public void openAboutActivity() {
		Intent myIntent = new Intent(this, AboutActivity.class);
		startActivity(myIntent);
	}

	public void openSettingsActivity() {
		Intent myIntent = new Intent(this, SettingsActivity.class);
		startActivity(myIntent);
	}

	public void openContactActivity() {
		Intent myIntent = new Intent(this, ContactActivity.class);
		startActivity(myIntent);
	}

	public void openRateApp() {
		Intent browserIntent = new Intent(
				Intent.ACTION_VIEW,
				Uri.parse("https://play.google.com/store/search?q=sorun%20istanbul"));
		startActivity(browserIntent);
	}

	// returns true if device is online
	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}
}


text:
(async function(testRunner) {
  let {page, session, dp} = await testRunner.startWithFrameControl(
      'Tests renderer: frames redirection chain.');

  let RendererTestHelper =
      await testRunner.loadScript('../helpers/renderer-test-helper.js');
  let {httpInterceptor, frameNavigationHelper, virtualTimeController} =
      await (new RendererTestHelper(testRunner, dp, page)).init();

  httpInterceptor.addResponse('http://www.example.com/', null,
      ['HTTP/1.1 302 Found', 'Location: http://www.example.com/1']);

  httpInterceptor.addResponse('http://www.example.com/1',
      `
        <frameset>
          <frame id="frameA" src='http://www.example.com/frameA/'>
          <frame id="frameB" src='http://www.example.com/frameB/'>
        </frameset>
      `);

  // Frame A
  httpInterceptor.addResponse('http://www.example.com/frameA/',
      `

        HELLO WORLD 1
      `);

  httpInterceptor.addResponse('http://www.example.com/frameA/1', null,
      ['HTTP/1.1 301 Moved', 'Location: /frameA/2']);

  httpInterceptor.addResponse('http://www.example.com/frameA/2',
      `<p>FRAME A</p>`);

  // Frame B
  httpInterceptor.addResponse('http://www.example.com/frameB/',
      `
        <title>HELLO WORLD 2</title>

      `);

  httpInterceptor.addResponse('http://www.example.com/iframe/',
      `

        HELLO WORLD 1
      `);

  httpInterceptor.addResponse('http://www.example.com/iframe/1', null,
      ['HTTP/1.1 302 Found', 'Location: /iframe/2']);

  httpInterceptor.addResponse('http://www.example.com/iframe/2', null,
      ['HTTP/1.1 301 Moved', 'Location: 3']);

  httpInterceptor.addResponse('http://www.example.com/iframe/3',
      `<p>IFRAME B</p>`);

  // Frame redirection requests are handled in an arbitrary order, so disable
  // requested url logging to ensure test's stability.
  httpInterceptor.setDisableRequestedUrlsLogging(true);

  await virtualTimeController.grantInitialTime(1000, 1000,
    null,
    async () => {
      testRunner.log(await session.evaluate(
        `document.getElementById('frameA').contentDocument.body.innerHTML`));
      testRunner.log(await session.evaluate(
        `document.getElementById('frameB').contentDocument.` +
        `getElementById('iframe').contentDocument.body.innerHTML`));

      frameNavigationHelper.logFrames();
      frameNavigationHelper.logScheduledNavigations();

      httpInterceptor.hasRequestedUrls([
          'http://www.example.com/',
          'http://www.example.com/1',
          'http://www.example.com/frameA/',
          'http://www.example.com/frameA/1',
          'http://www.example.com/frameA/2',
          'http://www.example.com/frameB/',
          'http://www.example.com/iframe/',
          'http://www.example.com/iframe/1',
          'http://www.example.com/iframe/2',
          'http://www.example.com/iframe/3']);

      testRunner.completeTest();
    }
  );

  await frameNavigationHelper.navigate('http://www.example.com/');
})


text:
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.defaultFileTemplateUsage;

import com.intellij.codeInspection.*;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.fileTemplates.impl.FileTemplateConfigurable;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author cdr
 */
public class DefaultFileTemplateUsageInspection extends AbstractBaseJavaLocalInspectionTool {

  /**
   * @deprecated unused, left for compatibility
   */
  @Deprecated
  public boolean CHECK_FILE_HEADER = true;

  /**
   * @deprecated unused, left for compatibility
   */
  @Deprecated
  public boolean CHECK_TRY_CATCH_SECTION = true;

  /**
   * @deprecated unused, left for compatibility
   */
  @Deprecated
  public boolean CHECK_METHOD_BODY = true;

  @Override
  @NotNull
  public String getGroupDisplayName() {
    return getGeneralGroupName();
  }

  @Override
  @NotNull
  @NonNls
  public String getShortName() {
    return "DefaultFileTemplate";
  }

  @Override
  public ProblemDescriptor @Nullable [] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
    ProblemDescriptor descriptor = FileHeaderChecker.checkFileHeader(file, manager, isOnTheFly);
    return descriptor == null ? null : new ProblemDescriptor[]{descriptor};
  }

  @Override
  public boolean isEnabledByDefault() {
    return true;
  }

  public static LocalQuickFix createEditFileTemplateFix(FileTemplate templateToEdit, ReplaceWithFileTemplateFix replaceTemplateFix) {
    return new EditFileTemplateFix(templateToEdit, replaceTemplateFix);
  }

  private static class EditFileTemplateFix implements LocalQuickFix {
    private final FileTemplate myTemplateToEdit;
    private final ReplaceWithFileTemplateFix myReplaceTemplateFix;

    EditFileTemplateFix(FileTemplate templateToEdit, ReplaceWithFileTemplateFix replaceTemplateFix) {
      myTemplateToEdit = templateToEdit;
      myReplaceTemplateFix = replaceTemplateFix;
    }

    @Override
    @NotNull
    public String getFamilyName() {
      return InspectionsBundle.message("default.file.template.edit.template");
    }

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

    @Override
    public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
      final FileTemplateConfigurable configurable = new FileTemplateConfigurable(project);
      configurable.setTemplate(myTemplateToEdit, null);
      boolean ok = ShowSettingsUtil.getInstance().editConfigurable(project, configurable);
      if (ok) {
        WriteCommandAction.runWriteCommandAction(project, () -> {
          FileTemplateManager.getInstance(project).saveAllTemplates();
          myReplaceTemplateFix.applyFix(project, descriptor);
        });
      }
    }
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
		<meta name="generator" content="JsDoc Toolkit" />

		<title>JsDoc Reference - s</title>
		<link href="../css/default.css" type="text/css" rel="stylesheet" media="all" />

Class Index | File Index

Classes

_global_

dom

dom.clone

s

				Generated by JsDoc Toolkit 2.4.0 on Mon Oct 18 2010 10:10:15 GMT+0100 (BST)

				HTML template: Codeview

					Namespace s

					Settings object which contains customisable information for FixedColumns instance

Defined in:  FixedColumns.js.

Namespace Summary

									Constructor Attributes
									Constructor Name and Description

											s

Field Summary

										Field Attributes
										Field Name and Description

											<static>

												s.columns

Number of columns to fix in position

											<static>

												s.dt

DataTables settings objects

								Namespace Detail

								s

								Field Detail

									<static>

									{int}

									s.columns

									Number of columns to fix in position

Default Value:

												1

									<static>

									{object}

									s.dt

									DataTables settings objects

Default Value:

												null


text:
from __future__ import annotations
from typing import Iterable, Sequence, Optional, Iterator, Union, Callable
from typing_extensions import Protocol
from ezdxf.math import (
    Vec2,
    UVec,
    intersection_line_line_2d,
    is_point_in_polygon_2d,
    has_clockwise_orientation,
    TOLERANCE,
    BoundingBox2d,
)
import enum

__all__ = [
    "greiner_hormann_union",
    "greiner_hormann_difference",
    "greiner_hormann_intersection",
    "cohen_sutherland_line_clipping_2d",
    "Clipping",
    "ClippingPolygon2d",
    "ClippingRect2d",
]

class Clipping(Protocol):
    def clip_polygon(self, polygon: Iterable[Vec2]) -> Sequence[Vec2]:
        """Returns the clipped polygon."""
        ...

    def clip_polyline(
        self, polyline: Iterable[Vec2]
    ) -> Sequence[Sequence[Vec2]]:
        """Returns the parts of the clipped polyline."""
        ...

    def clip_line(self, start: Vec2, end: Vec2) -> Sequence[Vec2]:
        """Returns the clipped line."""
        ...

    def is_inside(self, point: Vec2) -> bool:
        """Returns ``True`` if `point is inside the clipping path."""
        ...

def _clip_polyline(
    polyline: Iterable[Vec2],
    line_clipper: Callable[[Vec2, Vec2], Sequence[Vec2]],
) -> Sequence[Sequence[Vec2]]:
    """Returns the parts of the clipped polyline."""
    vertices = list(polyline)
    if len(vertices) < 2:
        return []
    result: list[Vec2] = []
    parts: list[list[Vec2]] = []
    start = vertices[0]
    for end in vertices[1:]:
        clipped_line = line_clipper(start, end)
        start = end
        if len(clipped_line) == 2:
            if result:
                clip_start, clip_end = clipped_line
                if result[-1].isclose(clip_start):
                    result.append(clip_end)
                    continue
                parts.append(result)
            result = list(clipped_line)
    if result:
        parts.append(result)
    return parts

class ClippingPolygon2d:
    """The clipping path is an arbitrary polygon."""

    def __init__(self, vertices: Iterable[Vec2], ccw_check=True):
        clip = list(vertices)
        if len(clip) > 1:
            if clip[0].isclose(clip[-1]):
                clip.pop()
        if len(clip) < 3:
            raise ValueError(
                "more than 3 vertices as clipping polygon required"
            )
        if ccw_check and has_clockwise_orientation(clip):
            clip.reverse()
        self._clipping_polygon: list[Vec2] = clip

    def clip_polyline(
        self, polyline: Iterable[Vec2]
    ) -> Sequence[Sequence[Vec2]]:
        """Returns the parts of the clipped polyline."""
        return _clip_polyline(polyline, self.clip_line)

    def clip_line(self, start: Vec2, end: Vec2) -> Sequence[Vec2]:
        """Returns the clipped line."""

        def is_inside(point: Vec2) -> bool:
            # is point left of line:
            return (clip_end.x - clip_start.x) * (point.y - clip_start.y) - (
                clip_end.y - clip_start.y
            ) * (point.x - clip_start.x) >= 0.0

        def edge_intersection() -> Vec2:
            return intersection_line_line_2d(
                (edge_start, edge_end), (clip_start, clip_end)
            )

        # The clipping polygon is always treated as a closed polyline!
        clip_start = self._clipping_polygon[-1]
        edge_start = start
        edge_end = end
        for clip_end in self._clipping_polygon:
            if is_inside(edge_start):
                if not is_inside(edge_end):
                    edge_end = edge_intersection()
            elif is_inside(edge_end):
                if not is_inside(edge_start):
                    edge_start = edge_intersection()
            else:
                return tuple()
            clip_start = clip_end
        return edge_start, edge_end

    def clip_polygon(self, polygon: Iterable[Vec2]) -> Sequence[Vec2]:
        """Returns the clipped polygon."""

        def is_inside(point: Vec2) -> bool:
            # is point left of line:
            return (clip_end.x - clip_start.x) * (point.y - clip_start.y) - (
                clip_end.y - clip_start.y
            ) * (point.x - clip_start.x) > 0.0

        def edge_intersection() -> Vec2:
            return intersection_line_line_2d(
                (edge_start, edge_end), (clip_start, clip_end)
            )

        # The clipping polygon is always treated as a closed polyline!
        clip_start = self._clipping_polygon[-1]
        clipped = list(polygon)
        for clip_end in self._clipping_polygon:
            # next clipping edge to test: clip_start -> clip_end
            if not clipped:  # no subject vertices left to test
                break

            vertices = clipped.copy()
            if len(vertices) > 1 and vertices[0].isclose(vertices[-1]):
                vertices.pop()

            clipped.clear()
            edge_start = vertices[-1]
            for edge_end in vertices:
                # next polygon edge to test: edge_start -> edge_end
                if is_inside(edge_end):
                    if not is_inside(edge_start):
                        clipped.append(edge_intersection())
                    clipped.append(edge_end)
                elif is_inside(edge_start):
                    clipped.append(edge_intersection())
                edge_start = edge_end
            clip_start = clip_end
        return clipped

    def is_inside(self, point: Vec2) -> bool:
        """Returns ``True`` if `point` is inside the clipping polygon."""
        return is_point_in_polygon_2d(point, self._clipping_polygon) >= 0

class ClippingRect2d:
    """The clipping path is a rectangle parallel to the x- and y-axis.

    This class will get an optimized implementation in the future.

    """

    def __init__(self, bottom_left: Vec2, top_right: Vec2):
        self._bbox = BoundingBox2d((bottom_left, top_right))
        bottom_left = self._bbox.extmin
        top_right = self._bbox.extmax
        self._clipping_polygon = ClippingPolygon2d(
            [
                bottom_left,
                Vec2(top_right.x, bottom_left.y),
                top_right,
                Vec2(bottom_left.x, top_right.y),
            ],
            ccw_check=False,
        )

    def clip_polygon(self, polygon: Iterable[Vec2]) -> Sequence[Vec2]:
        """Returns the clipped polygon."""
        return self._clipping_polygon.clip_polygon(polygon)

    def clip_polyline(
        self, polyline: Iterable[Vec2]
    ) -> Sequence[Sequence[Vec2]]:
        """Returns the parts of the clipped polyline."""
        return _clip_polyline(polyline, self.clip_line)

    def clip_line(self, start: Vec2, end: Vec2) -> Sequence[Vec2]:
        """Returns the clipped line."""
        return cohen_sutherland_line_clipping_2d(
            self._bbox.extmin, self._bbox.extmax, start, end
        )

    def is_inside(self, point: Vec2) -> bool:
        """Returns ``True`` if `point` is inside the clipping rectangle."""
        return self._bbox.inside(point)

def clip_polygon_2d(
    clip: Iterable[UVec],
    subject: Iterable[UVec],
    ccw_check: bool = True,
) -> Sequence[Vec2]:
    """Clip the `subject` polygon by the **convex** clipping polygon `clip`.

    Implements the `Sutherland–Hodgman`_ algorithm for clipping polygons.

    Args:
        clip: the convex clipping polygon as iterable of vertices
        subject: the polygon to clip as an iterable of vertices
        ccw_check: check if the clipping polygon is in counter-clockwise
            orientation if ``True``, set to ``False`` if the ccw check is done
            by the caller

    Returns:
        the clipped subject as list of :class:`~ezdxf.math.Vec2`

    .. _Sutherland–Hodgman: https://de.wikipedia.org/wiki/Algorithmus_von_Sutherland-Hodgman

    """
    clipper = ClippingPolygon2d(Vec2.generate(clip), ccw_check)
    return clipper.clip_polygon(Vec2.generate(subject))

# Based on the paper "Efficient Clipping of Arbitrary Polygons" by
# Günther Greiner and Kai Hormann,
# ACM Transactions on Graphics 1998;17(2):71-83
# Available at: http://www.inf.usi.ch/hormann/papers/Greiner.1998.ECO.pdf

class _Node:
    def __init__(
        self,
        vtx: Union[Vec2, _Node],
        alpha: float = 0.0,
        intersect=False,
        entry=True,
        checked=False,
    ):
        self.vtx: Vec2
        if isinstance(vtx, _Node):
            self.vtx = vtx.vtx
        else:
            self.vtx = vtx

        # Reference to the next vertex of the polygon
        self.next: _Node = None  # type: ignore

        # Reference to the previous vertex of the polygon
        self.prev: _Node = None  # type: ignore

        # Reference to the corresponding intersection vertex in the other polygon
        self.neighbour: _Node = None  # type: ignore

        # True if intersection is an entry point, False if exit
        self.entry: bool = entry

        # Intersection point's relative distance from previous vertex
        self.alpha: float = alpha

        # True if vertex is an intersection
        self.intersect: bool = intersect

        # True if the vertex has been checked (last phase)
        self.checked: bool = checked

    def set_checked(self):
        self.checked = True
        if self.neighbour and not self.neighbour.checked:
            self.neighbour.set_checked()

class IntersectionError(Exception):
    pass

class GHPolygon:
    first: _Node = None  # type: ignore
    max_x: float = 1e6

    def add(self, node: _Node):
        """Add a polygon vertex node."""

        self.max_x = max(self.max_x, node.vtx.x)
        if self.first is None:
            self.first = node
            self.first.next = node
            self.first.prev = node
        else:  # insert as last node
            first = self.first
            last = first.prev
            first.prev = node
            node.next = first
            node.prev = last
            last.next = node

    @staticmethod
    def build(vertices: Iterable[UVec]) -> GHPolygon:
        """Build a new GHPolygon from an iterable of vertices."""
        polygon = GHPolygon()
        _vertices = Vec2.list(vertices)
        for v in _vertices:
            polygon.add(_Node(v))
        return polygon

    @staticmethod
    def insert(vertex: _Node, start: _Node, end: _Node):
        """Insert and sort an intersection node.

        This function inserts an intersection node between two other
        start- and end node of an edge. The start and end node cannot be
        an intersection node (that is, they must be actual vertex nodes of
        the original polygon). If there are multiple intersection nodes
        between the start- and end node, then the new node is inserted
        based on its alpha value.
        """
        curr = start
        while curr != end and curr.alpha < vertex.alpha:
            curr = curr.next

        vertex.next = curr
        prev = curr.prev
        vertex.prev = prev
        prev.next = vertex
        curr.prev = vertex

    def __iter__(self) -> Iterator[_Node]:
        assert self.first is not None
        s = self.first
        while True:
            yield s
            s = s.next
            if s is self.first:
                return

    @property
    def first_intersect(self) -> Optional[_Node]:
        for v in self:
            if v.intersect and not v.checked:
                return v
        return None

    @property
    def points(self) -> list[Vec2]:
        points = [v.vtx for v in self]
        if not points[0].isclose(points[-1]):
            points.append(points[0])
        return points

    def unprocessed(self):
        for v in self:
            if v.intersect and not v.checked:
                return True
        return False

    def union(self, clip: GHPolygon) -> list[list[Vec2]]:
        return self.clip(clip, False, False)

    def intersection(self, clip: GHPolygon) -> list[list[Vec2]]:
        return self.clip(clip, True, True)

    def difference(self, clip: GHPolygon) -> list[list[Vec2]]:
        return self.clip(clip, False, True)

    def clip(self, clip: GHPolygon, s_entry, c_entry) -> list[list[Vec2]]:
        """Clip this polygon using another one as a clipper.

        This is where the algorithm is executed. It allows you to make
        a UNION, INTERSECT or DIFFERENCE operation between two polygons.

        Given two polygons A, B the following operations may be performed:

        A|B ... A OR B  (Union of A and B)
        A&B ... A AND B (Intersection of A and B)
        A\\B ... A - B
        B\\A ... B - A

        The entry records store the direction the algorithm should take when
        it arrives at that entry point in an intersection. Depending on the
        operation requested, the direction is set as follows for entry points
        (f=forward, b=backward; exit points are always set to the opposite):

              Entry
              A   B
              -----
        A|B   b   b
        A&B   f   f
        A\\B  b   f
        B\\A  f   b

        f = True, b = False when stored in the entry record
        """
        # Phase 1: Find intersections
        for subject_vertex in self:
            if not subject_vertex.intersect:
                for clipper_vertex in clip:
                    if not clipper_vertex.intersect:
                        ip, us, uc = line_intersection(
                            subject_vertex.vtx,
                            next_vertex_node(subject_vertex.next).vtx,
                            clipper_vertex.vtx,
                            next_vertex_node(clipper_vertex.next).vtx,
                        )
                        if ip is None:
                            continue
                        subject_node = _Node(
                            ip, us, intersect=True, entry=False
                        )
                        clipper_node = _Node(
                            ip, uc, intersect=True, entry=False
                        )
                        subject_node.neighbour = clipper_node
                        clipper_node.neighbour = subject_node

                        self.insert(
                            subject_node,
                            subject_vertex,
                            next_vertex_node(subject_vertex.next),
                        )
                        clip.insert(
                            clipper_node,
                            clipper_vertex,
                            next_vertex_node(clipper_vertex.next),
                        )

        # Phase 2: Identify entry/exit points
        s_entry ^= is_inside_polygon(self.first.vtx, clip)
        for subject_vertex in self:
            if subject_vertex.intersect:
                subject_vertex.entry = s_entry
                s_entry = not s_entry

        c_entry ^= is_inside_polygon(clip.first.vtx, self)
        for clipper_vertex in clip:
            if clipper_vertex.intersect:
                clipper_vertex.entry = c_entry
                c_entry = not c_entry

        # Phase 3: Construct clipped polygons
        clipped_polygons: list[list[Vec2]] = []
        while self.unprocessed():
            current: _Node = self.first_intersect  # type: ignore
            clipped = GHPolygon()
            clipped.add(_Node(current))
            while True:
                current.set_checked()
                if current.entry:
                    while True:
                        current = current.next
                        clipped.add(_Node(current))
                        if current.intersect:
                            break
                else:
                    while True:
                        current = current.prev
                        clipped.add(_Node(current))
                        if current.intersect:
                            break

                current = current.neighbour
                if current.checked:
                    break

            clipped_polygons.append(clipped.points)
        return clipped_polygons

def next_vertex_node(v: _Node) -> _Node:
    """Return the next non-intersecting vertex after the one specified."""
    c = v
    while c.intersect:
        c = c.next
    return c

def is_inside_polygon(vertex: Vec2, polygon: GHPolygon) -> bool:
    """Returns ``True`` if  `vertex` is inside `polygon` (odd-even rule).

    This function calculates the "winding" number for a point, which
    represents the number of times a ray emitted from the point to
    infinity intersects any edge of the polygon.

    An even winding number means the point lies OUTSIDE the polygon;
    an odd number means it lies INSIDE it.
    """
    winding_number: int = 0
    infinity = Vec2(polygon.max_x * 2, vertex.y)
    for node in polygon:
        if not node.intersect:
            if (
                line_intersection(
                    vertex,
                    infinity,
                    node.vtx,
                    next_vertex_node(node.next).vtx,
                )[0]
                is not None
            ):
                winding_number += 1
    return bool(winding_number % 2)

_ERROR = None, 0, 0

def line_intersection(
    s1: Vec2, s2: Vec2, c1: Vec2, c2: Vec2, tol: float = TOLERANCE
) -> tuple[Optional[Vec2], float, float]:
    """Returns the intersection point between two lines.

    This special implementation excludes the line end points as intersection
    points!

    Algorithm based on: http://paulbourke.net/geometry/lineline2d/
    """
    den = (c2.y - c1.y) * (s2.x - s1.x) - (c2.x - c1.x) * (s2.y - s1.y)
    if abs(den) < tol:
        return _ERROR

    us = ((c2.x - c1.x) * (s1.y - c1.y) - (c2.y - c1.y) * (s1.x - c1.x)) / den
    uc = ((s2.x - s1.x) * (s1.y - c1.y) - (s2.y - s1.y) * (s1.x - c1.x)) / den

    lwr = 0.0 + tol
    upr = 1.0 - tol
    # Line end points are excluded as intersection points:
    # us =~ 0.0; us =~ 1.0
    # uc =~ 0.0; uc =~ 1.0
    if (lwr < us < upr) and (lwr < uc < upr):
        return (
            Vec2(s1.x + us * (s2.x - s1.x), s1.y + us * (s2.y - s1.y)),
            us,
            uc,
        )
    return _ERROR

class BooleanOperation(enum.Enum):
    UNION = "union"
    DIFFERENCE = "difference"
    INTERSECTION = "intersection"

def greiner_hormann_intersection(
    p1: Iterable[UVec], p2: Iterable[UVec]
) -> list[list[Vec2]]:
    """Returns the INTERSECTION of polygon `p1` &  polygon `p2`.
    This algorithm works only for polygons with real intersection points
    and line end points on face edges are not considered as such intersection
    points!

    """
    return greiner_hormann(p1, p2, BooleanOperation.INTERSECTION)

def greiner_hormann_difference(
    p1: Iterable[UVec], p2: Iterable[UVec]
) -> list[list[Vec2]]:
    """Returns the DIFFERENCE of polygon `p1` - polygon `p2`.
    This algorithm works only for polygons with real intersection points
    and line end points on face edges are not considered as such intersection
    points!

    """
    return greiner_hormann(p1, p2, BooleanOperation.DIFFERENCE)

def greiner_hormann_union(
    p1: Iterable[UVec], p2: Iterable[UVec]
) -> list[list[Vec2]]:
    """Returns the UNION of polygon `p1` | polygon `p2`.
    This algorithm works only for polygons with real intersection points
    and line end points on face edges are not considered as such intersection
    points!

    """
    return greiner_hormann(p1, p2, BooleanOperation.UNION)

def greiner_hormann(
    p1: Iterable[UVec], p2: Iterable[UVec], op: BooleanOperation
) -> list[list[Vec2]]:
    """Implements a 2d clipping function to perform 3 boolean operations:

    - UNION: p1 | p2 ... p1 OR p2
    - INTERSECTION: p1 & p2 ... p1 AND p2
    - DIFFERENCE: p1 \\ p2 ... p1 - p2

    Based on the paper "Efficient Clipping of Arbitrary Polygons" by
    Günther Greiner and Kai Hormann.
    This algorithm works only for polygons with real intersection points
    and line end points on face edges are not considered as such intersection
    points!

    """
    polygon1 = GHPolygon.build(p1)
    polygon2 = GHPolygon.build(p2)

    if op == BooleanOperation.UNION:
        return polygon1.union(polygon2)
    elif op == BooleanOperation.DIFFERENCE:
        return polygon1.difference(polygon2)
    elif op == BooleanOperation.INTERSECTION:
        return polygon1.intersection(polygon2)
    raise ValueError(f"unknown or unsupported boolean operation: {op}")

LEFT = 0x1
RIGHT = 0x2
BOTTOM = 0x4
TOP = 0x8

def cohen_sutherland_line_clipping_2d(
    w_min: Vec2, w_max: Vec2, p0: Vec2, p1: Vec2
) -> Sequence[Vec2]:
    """Cohen-Sutherland 2D line clipping algorithm, source:
    https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm

    Args:
        w_min: bottom-left corner of the clipping rectangle
        w_max: top-right corner of the clipping rectangle
        p0: start-point of the line to clip
        p1: end-point of the line to clip

    """

    def encode(x: float, y: float) -> int:
        code: int = 0
        if x < x_min:
            code |= LEFT
        elif x > x_max:
            code |= RIGHT
        if y < y_min:
            code |= BOTTOM
        elif y > y_max:
            code |= TOP
        return code

    x0, y0 = p0
    x1, y1 = p1
    x_min, y_min = w_min
    x_max, y_max = w_max
    code0 = encode(x0, y0)
    code1 = encode(x1, y1)
    x = x0
    y = y0
    while True:
        if not (code0 | code1):  # ACCEPT
            # bitwise OR is 0: both points inside window; trivially accept and
            # exit loop:
            return Vec2(x0, y0), Vec2(x1, y1)
        if code0 & code1:  # REJECT
            # bitwise AND is not 0: both points share an outside zone (LEFT,
            # RIGHT, TOP, or BOTTOM), so both must be outside window;
            # exit loop
            return tuple()

        # failed both tests, so calculate the line segment to clip
        # from an outside point to an intersection with clip edge
        # At least one endpoint is outside the clip rectangle; pick it
        code = code1 if code1 > code0 else code0

        # Now find the intersection point;
        # use formulas:
        # slope = (y1 - y0) / (x1 - x0)
        # x = x0 + (1 / slope) * (ym - y0), where ym is y_min or y_max
        # y = y0 + slope * (xm - x0), where xm is x_min or x_max
        # No need to worry about divide-by-zero because, in each case, the
        # code bit being tested guarantees the denominator is non-zero
        if code & TOP:  # point is above the clip window
            x = x0 + (x1 - x0) * (y_max - y0) / (y1 - y0)
            y = y_max
        elif code & BOTTOM:  # point is below the clip window
            x = x0 + (x1 - x0) * (y_min - y0) / (y1 - y0)
            y = y_min
        elif code & RIGHT:  # point is to the right of clip window
            y = y0 + (y1 - y0) * (x_max - x0) / (x1 - x0)
            x = x_max
        elif code & LEFT:  # point is to the left of clip window
            y = y0 + (y1 - y0) * (x_min - x0) / (x1 - x0)
            x = x_min

        if code == code0:
            x0 = x
            y0 = y
            code0 = encode(x0, y0)
        else:
            x1 = x
            y1 = y
            code1 = encode(x1, y1)


text:
define(["require", "exports", "tslib", "../aurelia"], function (require, exports, tslib_1, au) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var ClickCounter = /** @class */ (function () {
        function ClickCounter() {
            this.count = 0;
        }
        ClickCounter.prototype.increment = function () {
            this.count++;
        };
        ClickCounter = tslib_1.__decorate([
            au.customElement("click-counter")
        ], ClickCounter);
        return ClickCounter;
    }());
    exports.ClickCounter = ClickCounter;
});
//# sourceMappingURL=click-counter.js.map


text:
//var googleDecodedPath = [];
//var googleEncodedPath;
//var googleElevationForLocations; //asynchronous
var pathInGeoJSON = {
	"type": "LineString",
	"coordinates": []
};
var pathForMySQL; 			//example: LineString(0 0,0 3,3 3,3 0,0 0)
var placePointAForMySQL; 	//example: POINT(31.5 42.2)
var placePointBForMySQL;

// Vars with facts about the hike
var pathLength = 0;
var pathMaxElevation = 0;
var pathMinElevation = 0;
var pathElevationDifference = 0;
var pathElevationIncrease = 0;
var pathElevationDecrease = 0;
var estimatedDurationAtoB = 0;
var estimatedDurationBtoA = 0;
var hikeDifficultyFromAToB = "N/A";
var hikeDifficultyFromAToBToA = "N/A";
var hikeDifficultyFromBToA = "N/A";

function initialize_vars(path){

	setPlacePointForMySQL(path);

	pathForMySQL = "LineString(";

	//SET var
	for (var i = 0; i < path.length; i++) {
		leafletPath.push(new L.LatLng(path[i][0], path[i][1]));
		pathInGeoJSON.coordinates.push([Number(path[i][1]), Number(path[i][0])]);
		pathForMySQL += Number(path[i][0]) +" "+ Number(path[i][1]) +",";
	} //END for

	pathForMySQL = pathForMySQL.slice(0, -1); //remove last char, which is a ","
	pathForMySQL += ")";

} //END initialize_vars()

function updateHikeName(element){

	if(element != undefined){
		// get input from form
		hikeName = document.getElementById(element.id).value;
	}

	// remove current label from map
	polyline.unbindLabel();

	// update on map
	if(hikeName.length == 0){
		polyline.bindLabel(defaultHikeName, { noHide: true });
	}
	else {
		polyline.bindLabel(hikeName, { noHide: true });
	}

	updateHikeFactBox();

} //END updateHikeName()

function updateHikeDescription(element){

	if(element != undefined){
		// get input from form
		hikeDescription = document.getElementById(element.id).value;
	}

	updateHikeFactBox();

} //END updateHikeDescription()

function updatePlaceNameA(element){

	if(element != undefined){
		// get input from form
		placeNameA = document.getElementById(element.id).value;
	}

	// remove current label from map
	leaflet_marker_place_a.unbindLabel();

	// update on map
	if(placeNameA.length == 0){
		leaflet_marker_place_a.bindLabel(defaultPlaceNameA, { noHide: true }).showLabel();
	}
	else {
		leaflet_marker_place_a.bindLabel(placeNameA, { noHide: true }).showLabel();
	}

	updateHikePathFactBox();

} //END updatePathNameA()

function updatePlaceNameB(element){

	if(element != undefined){
		// get input from form
		placeNameB = document.getElementById(element.id).value;
	}

	// remove current label from map
	leaflet_marker_place_b.unbindLabel();

	// update on map
	if(placeNameB.length == 0){
		leaflet_marker_place_b.bindLabel(defaultPlaceNameB, { noHide: true }).showLabel();
	}
	else {
		leaflet_marker_place_b.bindLabel(placeNameB, { noHide: true }).showLabel();
	}

	updateHikePathFactBox();

} //END updatePathNameB()

function setPlacePointForMySQL(path){

	placePointAForMySQL = "POINT("+ path[0][0] +", "+ path[0][1] +")";
	placePointBForMySQL = "POINT("+ path[path.length-1][0] +", "+ path[path.length-1][1] +")";

} //END setPlacePointForMySQL()

function setVarLeafletPath(jsonEncodedPath){

	for (var i = 0; i < jsonEncodedPath.length; i++) {
		leafletPath.push(new L.LatLng(jsonEncodedPath[i]['lat'], jsonEncodedPath[i]['lng']));
	}

} //END setVarLeafletPath(jsonEncodedPath)

function convertTime(dec){
	var seconds = dec * 3600;
	var hours = Math.floor(dec);
		seconds -= hours * 3600;
	var minutes = Math.floor(seconds / 60);
		seconds -= minutes * 60;
	return hours +"h "+ minutes +"m";
} //END convertTime()


text:
MAKE=make
GIT-PULL=git pull -q
GIT-CLONE=git clone -q
ZIP=zip -qr
CC=gmcs

ADL_GIT=http://git.thesoftwarefactory.be/pub/ADL.git
UTF_GIT=http://git.thesoftwarefactory.be/pub/UmlToolingFramework.git

SRCS=src/*.cs

DIST_LIBS=lib/ADL/src/cs/ADLSharp.dll \
     ../../UmlCanvasSharp/build/UmlCanvasSharp.dll \
     lib/UmlToolingFramework/build/UmlToolingFramework.dll \
     ../../UmlCanvasSharp/build/UmlCanvasSharp.UTF.dll \
     lib/UmlToolingFramework/build/UmlToolingFramework.EA.dll

LIBS=lib/Interop.EA.dll ${DIST_LIBS}

REFS=-r:System.Windows.Forms.dll \
     -r:System.Drawing.dll \
     -r:lib/Interop.EA.dll \
	 -r:lib/ADL/src/cs/ADLSharp.dll \
	 -r:../../UmlCanvasSharp/build/UmlCanvasSharp.dll \
     -r:lib/UmlToolingFramework/build/UmlToolingFramework.dll \
     -r:lib/UmlToolingFramework/build/UmlToolingFramework.EA.dll \
     -r:../../UmlCanvasSharp/build/UmlCanvasSharp.UTF.dll

all: build/UmlCanvas.EA.Addin.dll

build/UmlCanvas.EA.Addin.dll: ${SRCS} ${LIBS}
	@mkdir -p build
	@MONO_PATH=lib/UmlToolingFramework/build/ \
	  ${CC} -target:library ${REFS} -out:$@ ${SRCS}

lib/Interop.EA.dll:
	@echo "obtain a copy of Interop.EA.dll and put it in the lib/ dir"

lib/UmlToolingFramework/build/UmlToolingFramework.dll: UmlToolingFramework
	@(cd lib/UmlToolingFramework; ${MAKE} build/UmlToolingFramework.dll)

lib/UmlToolingFramework/build/UmlToolingFramework.EA.dll: UmlToolingFramework
	@(cd lib/UmlToolingFramework; ${MAKE} build/UmlToolingFramework.EA.dll)

UmlToolingFramework: lib/UmlToolingFramework
	@(cd lib/UmlToolingFramework; \
	  ${GIT-PULL}; \
	  mkdir -p lib; \
	  cd lib; \
	  rm -f Interop.EA.dll; \
	  ln -s ../../Interop.EA.dll . )

lib/UmlToolingFramework:
	@(cd lib; ${GIT-CLONE} ${UTF_GIT})

lib/ADL/src/cs/ADLSharp.dll: lib/ADL
	@(cd lib/ADL/src/cs; ${MAKE})

lib/ADL:
	@mkdir -p lib
	@(cd lib; ${GIT-CLONE} ${ADL_GIT})

../../UmlCanvasSharp/build/UmlCanvasSharp.dll:
	@(cd ../../UmlCanvasSharp; ${MAKE} build/UmlCanvasSharp.dll)

../../UmlCanvasSharp/build/UmlCanvasSharp.UTF.dll:
	@(cd ../../UmlCanvasSharp; ${MAKE} build/UmlCanvasSharp.UTF.dll)

dist: clean-dist build/UmlCanvas.EA.Addin.dll
	@mkdir -p dist/UmlCanvas.EA.Addin
	@cp ${DIST_LIBS} dist/UmlCanvas.EA.Addin
	@cp build/UmlCanvas.EA.Addin.dll dist/UmlCanvas.EA.Addin
	@cp reg.bat addin.reg dist/UmlCanvas.EA.Addin
	@(cd dist/; ZIP UmlCanvas.EA.Addin.zip UmlCanvas.EA.Addin/* )

.PHONY:
clean:
	@rm -rf build

clean-dist:
	@rm -rf dist

mrproper: clean
	@rm -rf dist
	@rm -rf lib/ADL lib/UmlToolingFramework


text:
namespace platform
{
	Thread* thread_create(ThreadEntry entry, void* data)
	{
		return posix_thread_create(entry, data);
	}

	void thread_destroy(Thread* thread)
	{
		posix_thread_destroy(thread);
	}

	int thread_join(Thread* thread, uint32_t)
	{
		return posix_thread_join(thread);
	}

	void thread_sleep(int milliseconds)
	{
		posix_thread_sleep(milliseconds);
	}

	pthread_t thread_id()
	{
		return posix_thread_id();
	}

	ThreadStatus thread_status(Thread* thread)
	{
		return posix_thread_status(thread);
	}

	bool thread_is_active(Thread* thread)
	{
		return posix_thread_is_active(thread);
	}

	Semaphore* semaphore_create(uint32_t initial_count, uint32_t max_count)
	{
		return posix_semaphore_create(initial_count, max_count);
	}

	void semaphore_wait(Semaphore* sem)
	{
		assert(sem);
		posix_semaphore_wait(sem);
	}

	void semaphore_signal(Semaphore* sem, uint32_t count)
	{
		assert(sem);
		posix_semaphore_signal(sem, count);
	}

	void semaphore_destroy(Semaphore* sem)
	{
		assert(sem);
		posix_semaphore_destroy(sem);
	}

} // namespace platform