entities
listlengths
1
8.61k
max_stars_repo_path
stringlengths
7
172
max_stars_repo_name
stringlengths
5
89
max_stars_count
int64
0
82k
content
stringlengths
14
1.05M
id
stringlengths
2
6
new_content
stringlengths
15
1.05M
modified
bool
1 class
references
stringlengths
29
1.05M
[ { "context": "rpleUserId']\n token: localStorage['purpleToken']\n os: Ext.os.name # just an additional ", "end": 9709, "score": 0.7129494547843933, "start": 9704, "tag": "KEY", "value": "Token" }, { "context": " id: o.vehicle_id\n user_id: localStorage['purp...
src/app/controller/Orders.coffee
Purple-Services/app
2
Ext.define 'Purple.controller.Orders', extend: 'Ext.app.Controller' requires: [ 'Purple.view.Order' ] config: refs: mainContainer: 'maincontainer' topToolbar: 'toptoolbar' ordersTabContainer: '#ordersTabContainer' orders: 'orders' # the Orders *page* ordersList: '[ctype=ordersList]' order: 'order' orderSpecialInstructionsLabel: '[ctype=orderSpecialInstructionsLabel]' orderSpecialInstructions: '[ctype=orderSpecialInstructions]' orderAddressStreet: '[ctype=orderAddressStreet]' orderAddressZipcode: '[ctype=orderAddressZipcode]' orderTirePressureCheck: '[ctype=orderTirePressureCheck]' orderIsntTopTier: '[ctype=orderIsntTopTier]' orderTimePlaced: '[ctype=orderTimePlaced]' orderTimeDeadline: '[ctype=orderTimeDeadline]' orderDisplayTime: '[ctype=orderDisplayTime]' orderVehicle: '[ctype=orderVehicle]' orderLicensePlate: '[ctype=orderLicensePlate]' orderGasPrice: '[ctype=orderGasPrice]' orderGallons: '[ctype=orderGallons]' orderGasType: '[ctype=orderGasType]' orderHorizontalRuleAboveVehicle: '[ctype=orderHorizontalRuleAboveVehicle]' orderVehicleMake: '[ctype=orderVehicleMake]' orderVehicleModel: '[ctype=orderVehicleModel]' orderVehicleYear: '[ctype=orderVehicleYear]' orderVehicleColor: '[ctype=orderVehicleColor]' orderVehicleLicensePlate: '[ctype=orderVehicleLicensePlate]' orderVehiclePhoto: '[ctype=orderVehiclePhoto]' orderCustomerName: '[ctype=orderCustomerName]' orderCustomerPhone: '[ctype=orderCustomerPhone]' orderServiceFee: '[ctype=orderServiceFee]' orderTotalPrice: '[ctype=orderTotalPrice]' orderHorizontalRuleAboveCustomerInfo: '[ctype=orderHorizontalRuleAboveCustomerInfo]' orderRating: '[ctype=orderRating]' orderStatusDisplay: '[ctype=orderStatusDisplay]' textRating: '[ctype=textRating]' sendRatingButtonContainer: '[ctype=sendRatingButtonContainer]' nextStatusButtonContainer: '[ctype=nextStatusButtonContainer]' control: orders: viewOrder: 'viewOrder' loadOrdersList: 'loadOrdersList' order: backToOrders: 'backToOrders' cancelOrder: 'askToCancelOrder' sendRating: 'sendRating' nextStatus: 'askToNextStatus' orderRating: change: 'orderRatingChange' orders: null orderListPageActive: yes launch: -> @callParent arguments getOrderById: (id) -> for o in @orders if o['id'] is orderId order = o break return order viewOrder: (orderId) -> @orderListPageActive = false for o in @orders if o['id'] is orderId order = o break @getOrdersTabContainer().setActiveItem( Ext.create 'Purple.view.Order', orderId: orderId status: order['status'] ) util.ctl('Menu').pushOntoBackButton => @backToOrders() @getOrder().addCls "status-#{order['status']}" @currentOrderClass = "status-#{order['status']}" if order['status'] is 'complete' @getOrderRating().show() order['display_status'] = if util.ctl('Account').isCourier() order['status'] else switch order['status'] when 'unassigned' then 'Accepted' else order['status'] order['time_order_placed'] = Ext.util.Format.date( new Date(order['target_time_start'] * 1000), "n/j/Y, g:i a" ) order['time_deadline'] = Ext.util.Format.date( new Date(order['target_time_end'] * 1000), "g:i a" ) diffMinutes = Math.floor( (order['target_time_end'] - order['target_time_start']) / 60 ) if diffMinutes < 60 order['display_time'] = "within #{diffMinutes} minutes" else diffHours = Math.round( diffMinutes / 60 ) order['display_time'] = "within #{diffHours} hour#{if diffHours is 1 then '' else 's'}" for v in util.ctl('Vehicles').vehicles if v['id'] is order['vehicle_id'] order['vehicle'] = "#{v.year} #{v.make} #{v.model}" order['license_plate'] = v.license_plate.toUpperCase() break if util.ctl('Account').isCourier() v = order['vehicle'] order['gas_type'] = v['gas_type'] order['vehicle_make'] = v['make'] order['vehicle_model'] = v['model'] order['vehicle_year'] = v['year'] order['vehicle_color'] = v['color'] order['vehicle_license_plate'] = v['license_plate'] order['vehicle_photo'] = v['photo'] c = order['customer'] order['customer_name'] = c['name'] order['customer_phone'] = c['phone_number'] order['gas_price_display'] = util.centsToDollars order['gas_price'] order['service_fee_display'] = util.centsToDollars order['service_fee'] order['total_price_display'] = util.centsToDollars order['total_price'] order['isnt_top_tier'] = not order['is_top_tier'] @getOrder().setValues order if order['tire_pressure_check'] @getOrderTirePressureCheck().show() if order['special_instructions'] is '' @getOrderSpecialInstructionsLabel().hide() @getOrderSpecialInstructions().hide() @getOrderAddressStreet().removeCls 'bottom-margin' else @getOrderSpecialInstructions().setHtml(order['special_instructions']) if util.ctl('Account').isCourier() @getOrderTimePlaced().hide() @getOrderDisplayTime().hide() @getOrderVehicle().hide() @getOrderGasPrice().hide() @getOrderServiceFee().hide() @getOrderTotalPrice().hide() @getOrderRating().hide() @getOrderTimeDeadline().show() @getOrderHorizontalRuleAboveVehicle().show() @getOrderVehicleMake().show() @getOrderVehicleModel().show() @getOrderVehicleYear().show() @getOrderVehicleColor().show() @getOrderVehicleLicensePlate().show() @getOrderHorizontalRuleAboveCustomerInfo().show() @getOrderCustomerName().show() @getOrderCustomerPhone().show() @getOrderGasType().show() if order['isnt_top_tier'] @getOrderIsntTopTier().show() @getOrderAddressZipcode().show() switch order['status'] when "unassigned" @getNextStatusButtonContainer().getAt(0).setText "Accept Order" @getNextStatusButtonContainer().show() when "assigned" @getNextStatusButtonContainer().getAt(0).setText "Accept Order" @getNextStatusButtonContainer().show() when "accepted" @getNextStatusButtonContainer().getAt(0).setText "Start Route" @getNextStatusButtonContainer().show() when "enroute" @getNextStatusButtonContainer().getAt(0).setText "Begin Servicing" @getNextStatusButtonContainer().show() when "servicing" @getNextStatusButtonContainer().getAt(0).setText "Complete Order" @getNextStatusButtonContainer().show() @getOrderAddressStreet().addCls 'click-to-edit' @getOrderAddressStreet().element.on 'tap', => # google maps window.open util.googleMapsDeepLink("?daddr=#{order.lat},#{order.lng}&directionsmode=driving"), "_system" # standard maps #window.location.href = "maps://?q=#{order.lat},#{order.lng}" @getOrderCustomerPhone().addCls 'click-to-edit' @getOrderCustomerPhone().element.on 'tap', => window.location.href = "tel://#{order['customer_phone']}" if order["vehicle_photo"]? and order["vehicle_photo"] isnt '' @getOrderVehiclePhoto().show() @getOrderVehiclePhoto().element.dom.style.cssText = """ background-color: transparent; background-size: cover; background-repeat: no-repeat; background-position: center; height: 300px; width: 100%; background-image: url('#{order["vehicle_photo"]}') !important; """ analytics?.page 'View Order', order_id: order.id backToOrders: -> @orderListPageActive = true @refreshOrdersAndOrdersList() @getOrdersTabContainer()?.remove( @getOrder(), yes ) isUserBusy: -> util.ctl('Vehicles').getEditVehicleForm()? or util.ctl('Main').getRequestForm()? or util.ctl('Main').getRequestConfirmationForm()? or util.ctl('Account').getEditAccountForm()? or util.ctl('PaymentMethods').getEditPaymentMethodForm()? or @getOrder()? updateLastOrderCompleted: -> for order in @orders if order.status is 'complete' if localStorage['lastOrderCompleted']? and not @isUserBusy() if localStorage['lastOrderCompleted'] isnt order.id and localStorage['orderListLength'] is @orders.length.toString() localStorage['lastOrderCompleted'] = order.id localStorage['orderListLength'] = @orders.length @sendToCompletedOrder() localStorage['lastOrderCompleted'] = order.id localStorage['orderListLength'] = @orders.length break sendToCompletedOrder: -> while util.ctl('Menu').backButtonStack.length util.ctl('Menu').popOffBackButton() util.ctl('Main').getMainContainer().getItems().getAt(0).select 3, no, no @viewOrder localStorage['lastOrderCompleted'] loadOrdersList: (forceUpdate = no, callback = null) -> if @orders? and not forceUpdate @renderOrdersList @orders else Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/details" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] os: Ext.os.name # just an additional info headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @orders = response.orders util.ctl('Vehicles').vehicles = response.vehicles util.ctl('Vehicles').loadVehiclesList() @renderOrdersList @orders callback?() @lastLoadOrdersList = new Date().getTime() / 1000 @updateLastOrderCompleted() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response isActiveOrder: (o) -> -1 isnt util.ACTIVE_STATUSES.indexOf o.status getActiveOrders: -> @orders.filter @isActiveOrder # only call this after orders have been loaded hasActiveOrder: -> @getActiveOrders().length > 0 renderOrdersList: (orders) -> list = @getOrdersList() if not list? return list.removeAll yes, yes if orders.length is 0 and not util.ctl('Account').isCourier() list.add xtype: 'component' flex: 0 html: """ No orders yet. <br />Let's change that! Get gas now. """ cls: "loose-text" style: "text-align: center;" list.add xtype: 'container' # cls: 'slideable' flex: 0 height: 110 padding: '0 0 5 0' layout: type: 'vbox' pack: 'center' align: 'center' items: [ { xtype: 'button' ui: 'action' cls: 'button-pop' text: 'Get Started' flex: 0 disabled: no handler: -> util.ctl('Main').getMainContainer().getItems().getAt(0).select 0, no, no } ] for o in orders if util.ctl('Account').isCourier() v = o['vehicle'] else v = util.ctl('Vehicles').getVehicleById(o.vehicle_id) v ?= # if we don't have it in local memory then it must have been deleted id: o.vehicle_id user_id: localStorage['purpleUserId'] year: "Vehicle Deleted" timestamp_created: "1970-01-01T00:00:00Z" color: "" gas_type: "" license_plate: "" make: "" model: "" cls = [ 'bottom-margin' 'order-list-item' ] if o.status is 'complete' cls.push 'highlighted' if util.ctl('Account').isCourier() isLate = o.status isnt "complete" and o.status isnt "cancelled" and (new Date(o.target_time_end * 1000)) < (new Date()) dateDisplay = """ <span style="#{if isLate then "color: #f00;" else ""}"> #{Ext.util.Format.date( new Date(o.target_time_end * 1000), "n/j g:i a" )} </span> """ else dateDisplay = Ext.util.Format.date( new Date(o.target_time_start * 1000), "F jS" ) list.add xtype: 'textfield' id: "oid_#{o.id}" flex: 0 label: """ #{dateDisplay} <br /><span class="subtext">#{v.year} #{v.make} #{v.model}</span> <div class="status-square"> <div class="fill"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="60px" height="60px" viewBox="0 0 60 60" enable-background="new 0 0 60 60" xml:space="preserve"> <path fill="#04ACFF" id="waveShape" d="M300,300V2.5c0,0-0.6-0.1-1.1-0.1c0,0-25.5-2.3-40.5-2.4c-15,0-40.6,2.4-40.6,2.4 c-12.3,1.1-30.3,1.8-31.9,1.9c-2-0.1-19.7-0.8-32-1.9c0,0-25.8-2.3-40.8-2.4c-15,0-40.8,2.4-40.8,2.4c-12.3,1.1-30.4,1.8-32,1.9 c-2-0.1-20-0.8-32.2-1.9c0,0-3.1-0.3-8.1-0.7V300H300z"/> </svg> </div> </div> """ labelWidth: '100%' cls: cls disabled: yes listeners: painted: ((o)=>((field) => # todo -this method will cause a slight flicker for cancelled orders field.addCls "status-#{o.status}"))(o) initialize: (field) => field.element.on 'tap', => oid = field.getId().split('_')[1] @viewOrder oid @refreshOrdersAndOrdersList() refreshOrdersAndOrdersList: -> currentTime = new Date().getTime() / 1000 if currentTime - @lastLoadOrdersList > 30 or not @lastLoadOrdersList? if @orders? and @hasActiveOrder() and @getMainContainer().getActiveItem().data.index is 3 if @orderListPageActive @loadOrdersList yes else #order page is active @loadOrdersList yes, (Ext.bind @refreshOrder, this) refreshOrder: -> if @getOrder?() for o in @orders if o['id'] is @getOrder().config.orderId order = o break if order['status'] is 'unassigned' @getOrderStatusDisplay().setValue 'Accepted' else @getOrderStatusDisplay().setValue order['status'] @getOrder().removeCls @currentOrderClass @getOrder().addCls "status-#{order['status']}" @currentOrderClass = "status-#{order['status']}" if order['status'] is 'complete' @getOrderRating().show() askToCancelOrder: (id) -> util.confirm( '', """ Are you sure you want to cancel this order? """, (=> @cancelOrder id), null, 'Yes', 'No' ) cancelOrder: (id) -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}orders/cancel" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] order_id: id headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @orders = response.orders @backToOrders() util.ctl('Menu').popOffBackButtonWithoutAction() @renderOrdersList @orders else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false console.log response_obj util.alert "Connection error. Please try again.", "Error", (->) orderRatingChange: (field, value) -> @getTextRating().show() @getSendRatingButtonContainer().show() sendToAppStore: -> localStorage['sentUserToAppStore'] = 'yes' if Ext.os.is.iOS cordova.plugins.market.open "id970824802" else cordova.plugins.market.open "com.purple.app" sendRating: -> values = @getOrder().getValues() id = @getOrder().config.orderId Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}orders/rate" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] order_id: id rating: number_rating: values['number_rating'] text_rating: values['text_rating'] headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @orders = response.orders @backToOrders() util.ctl('Menu').popOffBackButtonWithoutAction() @renderOrdersList @orders if values['number_rating'] is 5 and localStorage['sentUserToAppStore'] isnt 'yes' util.confirm( "Do you have a few seconds to help us by rating the Purple app?", "Thanks!", @sendToAppStore, (=> if localStorage['sentUserToAppStore'] is 'attempted' localStorage['sentUserToAppStore'] = 'yes' else localStorage['sentUserToAppStore'] = 'attempted' ) ) else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false console.log response_obj util.alert "Connection error. Please try again.", "Error", (->) askToNextStatus: -> values = @getOrder().getValues() currentStatus = values['status'] nextStatus = util.NEXT_STATUS_MAP[currentStatus] util.confirm( '', (switch nextStatus when "assigned", "accepted" "Are you sure you want to accept this order? (cannot be undone)" else "Are you sure you want to mark this order as #{nextStatus}? (cannot be undone)" ), (Ext.bind @nextStatus, this) null, 'Yes', 'No' ) nextStatus: -> values = @getOrder().getValues() currentStatus = values['status'] id = @getOrder().config.orderId Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}orders/update-status-by-courier" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] order_id: id status: util.NEXT_STATUS_MAP[currentStatus] headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @orders = response.orders @backToOrders() util.ctl('Menu').popOffBackButtonWithoutAction() @renderOrdersList @orders else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false console.log response_obj util.alert "Connection error. Please go back to Orders page and pull down to refresh. Do not press this button again until you have the updated status on the Orders page.", "Error", (->)
50293
Ext.define 'Purple.controller.Orders', extend: 'Ext.app.Controller' requires: [ 'Purple.view.Order' ] config: refs: mainContainer: 'maincontainer' topToolbar: 'toptoolbar' ordersTabContainer: '#ordersTabContainer' orders: 'orders' # the Orders *page* ordersList: '[ctype=ordersList]' order: 'order' orderSpecialInstructionsLabel: '[ctype=orderSpecialInstructionsLabel]' orderSpecialInstructions: '[ctype=orderSpecialInstructions]' orderAddressStreet: '[ctype=orderAddressStreet]' orderAddressZipcode: '[ctype=orderAddressZipcode]' orderTirePressureCheck: '[ctype=orderTirePressureCheck]' orderIsntTopTier: '[ctype=orderIsntTopTier]' orderTimePlaced: '[ctype=orderTimePlaced]' orderTimeDeadline: '[ctype=orderTimeDeadline]' orderDisplayTime: '[ctype=orderDisplayTime]' orderVehicle: '[ctype=orderVehicle]' orderLicensePlate: '[ctype=orderLicensePlate]' orderGasPrice: '[ctype=orderGasPrice]' orderGallons: '[ctype=orderGallons]' orderGasType: '[ctype=orderGasType]' orderHorizontalRuleAboveVehicle: '[ctype=orderHorizontalRuleAboveVehicle]' orderVehicleMake: '[ctype=orderVehicleMake]' orderVehicleModel: '[ctype=orderVehicleModel]' orderVehicleYear: '[ctype=orderVehicleYear]' orderVehicleColor: '[ctype=orderVehicleColor]' orderVehicleLicensePlate: '[ctype=orderVehicleLicensePlate]' orderVehiclePhoto: '[ctype=orderVehiclePhoto]' orderCustomerName: '[ctype=orderCustomerName]' orderCustomerPhone: '[ctype=orderCustomerPhone]' orderServiceFee: '[ctype=orderServiceFee]' orderTotalPrice: '[ctype=orderTotalPrice]' orderHorizontalRuleAboveCustomerInfo: '[ctype=orderHorizontalRuleAboveCustomerInfo]' orderRating: '[ctype=orderRating]' orderStatusDisplay: '[ctype=orderStatusDisplay]' textRating: '[ctype=textRating]' sendRatingButtonContainer: '[ctype=sendRatingButtonContainer]' nextStatusButtonContainer: '[ctype=nextStatusButtonContainer]' control: orders: viewOrder: 'viewOrder' loadOrdersList: 'loadOrdersList' order: backToOrders: 'backToOrders' cancelOrder: 'askToCancelOrder' sendRating: 'sendRating' nextStatus: 'askToNextStatus' orderRating: change: 'orderRatingChange' orders: null orderListPageActive: yes launch: -> @callParent arguments getOrderById: (id) -> for o in @orders if o['id'] is orderId order = o break return order viewOrder: (orderId) -> @orderListPageActive = false for o in @orders if o['id'] is orderId order = o break @getOrdersTabContainer().setActiveItem( Ext.create 'Purple.view.Order', orderId: orderId status: order['status'] ) util.ctl('Menu').pushOntoBackButton => @backToOrders() @getOrder().addCls "status-#{order['status']}" @currentOrderClass = "status-#{order['status']}" if order['status'] is 'complete' @getOrderRating().show() order['display_status'] = if util.ctl('Account').isCourier() order['status'] else switch order['status'] when 'unassigned' then 'Accepted' else order['status'] order['time_order_placed'] = Ext.util.Format.date( new Date(order['target_time_start'] * 1000), "n/j/Y, g:i a" ) order['time_deadline'] = Ext.util.Format.date( new Date(order['target_time_end'] * 1000), "g:i a" ) diffMinutes = Math.floor( (order['target_time_end'] - order['target_time_start']) / 60 ) if diffMinutes < 60 order['display_time'] = "within #{diffMinutes} minutes" else diffHours = Math.round( diffMinutes / 60 ) order['display_time'] = "within #{diffHours} hour#{if diffHours is 1 then '' else 's'}" for v in util.ctl('Vehicles').vehicles if v['id'] is order['vehicle_id'] order['vehicle'] = "#{v.year} #{v.make} #{v.model}" order['license_plate'] = v.license_plate.toUpperCase() break if util.ctl('Account').isCourier() v = order['vehicle'] order['gas_type'] = v['gas_type'] order['vehicle_make'] = v['make'] order['vehicle_model'] = v['model'] order['vehicle_year'] = v['year'] order['vehicle_color'] = v['color'] order['vehicle_license_plate'] = v['license_plate'] order['vehicle_photo'] = v['photo'] c = order['customer'] order['customer_name'] = c['name'] order['customer_phone'] = c['phone_number'] order['gas_price_display'] = util.centsToDollars order['gas_price'] order['service_fee_display'] = util.centsToDollars order['service_fee'] order['total_price_display'] = util.centsToDollars order['total_price'] order['isnt_top_tier'] = not order['is_top_tier'] @getOrder().setValues order if order['tire_pressure_check'] @getOrderTirePressureCheck().show() if order['special_instructions'] is '' @getOrderSpecialInstructionsLabel().hide() @getOrderSpecialInstructions().hide() @getOrderAddressStreet().removeCls 'bottom-margin' else @getOrderSpecialInstructions().setHtml(order['special_instructions']) if util.ctl('Account').isCourier() @getOrderTimePlaced().hide() @getOrderDisplayTime().hide() @getOrderVehicle().hide() @getOrderGasPrice().hide() @getOrderServiceFee().hide() @getOrderTotalPrice().hide() @getOrderRating().hide() @getOrderTimeDeadline().show() @getOrderHorizontalRuleAboveVehicle().show() @getOrderVehicleMake().show() @getOrderVehicleModel().show() @getOrderVehicleYear().show() @getOrderVehicleColor().show() @getOrderVehicleLicensePlate().show() @getOrderHorizontalRuleAboveCustomerInfo().show() @getOrderCustomerName().show() @getOrderCustomerPhone().show() @getOrderGasType().show() if order['isnt_top_tier'] @getOrderIsntTopTier().show() @getOrderAddressZipcode().show() switch order['status'] when "unassigned" @getNextStatusButtonContainer().getAt(0).setText "Accept Order" @getNextStatusButtonContainer().show() when "assigned" @getNextStatusButtonContainer().getAt(0).setText "Accept Order" @getNextStatusButtonContainer().show() when "accepted" @getNextStatusButtonContainer().getAt(0).setText "Start Route" @getNextStatusButtonContainer().show() when "enroute" @getNextStatusButtonContainer().getAt(0).setText "Begin Servicing" @getNextStatusButtonContainer().show() when "servicing" @getNextStatusButtonContainer().getAt(0).setText "Complete Order" @getNextStatusButtonContainer().show() @getOrderAddressStreet().addCls 'click-to-edit' @getOrderAddressStreet().element.on 'tap', => # google maps window.open util.googleMapsDeepLink("?daddr=#{order.lat},#{order.lng}&directionsmode=driving"), "_system" # standard maps #window.location.href = "maps://?q=#{order.lat},#{order.lng}" @getOrderCustomerPhone().addCls 'click-to-edit' @getOrderCustomerPhone().element.on 'tap', => window.location.href = "tel://#{order['customer_phone']}" if order["vehicle_photo"]? and order["vehicle_photo"] isnt '' @getOrderVehiclePhoto().show() @getOrderVehiclePhoto().element.dom.style.cssText = """ background-color: transparent; background-size: cover; background-repeat: no-repeat; background-position: center; height: 300px; width: 100%; background-image: url('#{order["vehicle_photo"]}') !important; """ analytics?.page 'View Order', order_id: order.id backToOrders: -> @orderListPageActive = true @refreshOrdersAndOrdersList() @getOrdersTabContainer()?.remove( @getOrder(), yes ) isUserBusy: -> util.ctl('Vehicles').getEditVehicleForm()? or util.ctl('Main').getRequestForm()? or util.ctl('Main').getRequestConfirmationForm()? or util.ctl('Account').getEditAccountForm()? or util.ctl('PaymentMethods').getEditPaymentMethodForm()? or @getOrder()? updateLastOrderCompleted: -> for order in @orders if order.status is 'complete' if localStorage['lastOrderCompleted']? and not @isUserBusy() if localStorage['lastOrderCompleted'] isnt order.id and localStorage['orderListLength'] is @orders.length.toString() localStorage['lastOrderCompleted'] = order.id localStorage['orderListLength'] = @orders.length @sendToCompletedOrder() localStorage['lastOrderCompleted'] = order.id localStorage['orderListLength'] = @orders.length break sendToCompletedOrder: -> while util.ctl('Menu').backButtonStack.length util.ctl('Menu').popOffBackButton() util.ctl('Main').getMainContainer().getItems().getAt(0).select 3, no, no @viewOrder localStorage['lastOrderCompleted'] loadOrdersList: (forceUpdate = no, callback = null) -> if @orders? and not forceUpdate @renderOrdersList @orders else Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/details" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purple<KEY>'] os: Ext.os.name # just an additional info headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @orders = response.orders util.ctl('Vehicles').vehicles = response.vehicles util.ctl('Vehicles').loadVehiclesList() @renderOrdersList @orders callback?() @lastLoadOrdersList = new Date().getTime() / 1000 @updateLastOrderCompleted() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response isActiveOrder: (o) -> -1 isnt util.ACTIVE_STATUSES.indexOf o.status getActiveOrders: -> @orders.filter @isActiveOrder # only call this after orders have been loaded hasActiveOrder: -> @getActiveOrders().length > 0 renderOrdersList: (orders) -> list = @getOrdersList() if not list? return list.removeAll yes, yes if orders.length is 0 and not util.ctl('Account').isCourier() list.add xtype: 'component' flex: 0 html: """ No orders yet. <br />Let's change that! Get gas now. """ cls: "loose-text" style: "text-align: center;" list.add xtype: 'container' # cls: 'slideable' flex: 0 height: 110 padding: '0 0 5 0' layout: type: 'vbox' pack: 'center' align: 'center' items: [ { xtype: 'button' ui: 'action' cls: 'button-pop' text: 'Get Started' flex: 0 disabled: no handler: -> util.ctl('Main').getMainContainer().getItems().getAt(0).select 0, no, no } ] for o in orders if util.ctl('Account').isCourier() v = o['vehicle'] else v = util.ctl('Vehicles').getVehicleById(o.vehicle_id) v ?= # if we don't have it in local memory then it must have been deleted id: o.vehicle_id user_id: localStorage['purpleUserId'] year: "Vehicle Deleted" timestamp_created: "1970-01-01T00:00:00Z" color: "" gas_type: "" license_plate: "" make: "" model: "" cls = [ 'bottom-margin' 'order-list-item' ] if o.status is 'complete' cls.push 'highlighted' if util.ctl('Account').isCourier() isLate = o.status isnt "complete" and o.status isnt "cancelled" and (new Date(o.target_time_end * 1000)) < (new Date()) dateDisplay = """ <span style="#{if isLate then "color: #f00;" else ""}"> #{Ext.util.Format.date( new Date(o.target_time_end * 1000), "n/j g:i a" )} </span> """ else dateDisplay = Ext.util.Format.date( new Date(o.target_time_start * 1000), "F jS" ) list.add xtype: 'textfield' id: "oid_#{o.id}" flex: 0 label: """ #{dateDisplay} <br /><span class="subtext">#{v.year} #{v.make} #{v.model}</span> <div class="status-square"> <div class="fill"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="60px" height="60px" viewBox="0 0 60 60" enable-background="new 0 0 60 60" xml:space="preserve"> <path fill="#04ACFF" id="waveShape" d="M300,300V2.5c0,0-0.6-0.1-1.1-0.1c0,0-25.5-2.3-40.5-2.4c-15,0-40.6,2.4-40.6,2.4 c-12.3,1.1-30.3,1.8-31.9,1.9c-2-0.1-19.7-0.8-32-1.9c0,0-25.8-2.3-40.8-2.4c-15,0-40.8,2.4-40.8,2.4c-12.3,1.1-30.4,1.8-32,1.9 c-2-0.1-20-0.8-32.2-1.9c0,0-3.1-0.3-8.1-0.7V300H300z"/> </svg> </div> </div> """ labelWidth: '100%' cls: cls disabled: yes listeners: painted: ((o)=>((field) => # todo -this method will cause a slight flicker for cancelled orders field.addCls "status-#{o.status}"))(o) initialize: (field) => field.element.on 'tap', => oid = field.getId().split('_')[1] @viewOrder oid @refreshOrdersAndOrdersList() refreshOrdersAndOrdersList: -> currentTime = new Date().getTime() / 1000 if currentTime - @lastLoadOrdersList > 30 or not @lastLoadOrdersList? if @orders? and @hasActiveOrder() and @getMainContainer().getActiveItem().data.index is 3 if @orderListPageActive @loadOrdersList yes else #order page is active @loadOrdersList yes, (Ext.bind @refreshOrder, this) refreshOrder: -> if @getOrder?() for o in @orders if o['id'] is @getOrder().config.orderId order = o break if order['status'] is 'unassigned' @getOrderStatusDisplay().setValue 'Accepted' else @getOrderStatusDisplay().setValue order['status'] @getOrder().removeCls @currentOrderClass @getOrder().addCls "status-#{order['status']}" @currentOrderClass = "status-#{order['status']}" if order['status'] is 'complete' @getOrderRating().show() askToCancelOrder: (id) -> util.confirm( '', """ Are you sure you want to cancel this order? """, (=> @cancelOrder id), null, 'Yes', 'No' ) cancelOrder: (id) -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}orders/cancel" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purple<KEY>'] order_id: id headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @orders = response.orders @backToOrders() util.ctl('Menu').popOffBackButtonWithoutAction() @renderOrdersList @orders else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false console.log response_obj util.alert "Connection error. Please try again.", "Error", (->) orderRatingChange: (field, value) -> @getTextRating().show() @getSendRatingButtonContainer().show() sendToAppStore: -> localStorage['sentUserToAppStore'] = 'yes' if Ext.os.is.iOS cordova.plugins.market.open "id970824802" else cordova.plugins.market.open "com.purple.app" sendRating: -> values = @getOrder().getValues() id = @getOrder().config.orderId Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}orders/rate" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] order_id: id rating: number_rating: values['number_rating'] text_rating: values['text_rating'] headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @orders = response.orders @backToOrders() util.ctl('Menu').popOffBackButtonWithoutAction() @renderOrdersList @orders if values['number_rating'] is 5 and localStorage['sentUserToAppStore'] isnt 'yes' util.confirm( "Do you have a few seconds to help us by rating the Purple app?", "Thanks!", @sendToAppStore, (=> if localStorage['sentUserToAppStore'] is 'attempted' localStorage['sentUserToAppStore'] = 'yes' else localStorage['sentUserToAppStore'] = 'attempted' ) ) else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false console.log response_obj util.alert "Connection error. Please try again.", "Error", (->) askToNextStatus: -> values = @getOrder().getValues() currentStatus = values['status'] nextStatus = util.NEXT_STATUS_MAP[currentStatus] util.confirm( '', (switch nextStatus when "assigned", "accepted" "Are you sure you want to accept this order? (cannot be undone)" else "Are you sure you want to mark this order as #{nextStatus}? (cannot be undone)" ), (Ext.bind @nextStatus, this) null, 'Yes', 'No' ) nextStatus: -> values = @getOrder().getValues() currentStatus = values['status'] id = @getOrder().config.orderId Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}orders/update-status-by-courier" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['<KEY>Token'] order_id: id status: util.NEXT_STATUS_MAP[currentStatus] headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @orders = response.orders @backToOrders() util.ctl('Menu').popOffBackButtonWithoutAction() @renderOrdersList @orders else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false console.log response_obj util.alert "Connection error. Please go back to Orders page and pull down to refresh. Do not press this button again until you have the updated status on the Orders page.", "Error", (->)
true
Ext.define 'Purple.controller.Orders', extend: 'Ext.app.Controller' requires: [ 'Purple.view.Order' ] config: refs: mainContainer: 'maincontainer' topToolbar: 'toptoolbar' ordersTabContainer: '#ordersTabContainer' orders: 'orders' # the Orders *page* ordersList: '[ctype=ordersList]' order: 'order' orderSpecialInstructionsLabel: '[ctype=orderSpecialInstructionsLabel]' orderSpecialInstructions: '[ctype=orderSpecialInstructions]' orderAddressStreet: '[ctype=orderAddressStreet]' orderAddressZipcode: '[ctype=orderAddressZipcode]' orderTirePressureCheck: '[ctype=orderTirePressureCheck]' orderIsntTopTier: '[ctype=orderIsntTopTier]' orderTimePlaced: '[ctype=orderTimePlaced]' orderTimeDeadline: '[ctype=orderTimeDeadline]' orderDisplayTime: '[ctype=orderDisplayTime]' orderVehicle: '[ctype=orderVehicle]' orderLicensePlate: '[ctype=orderLicensePlate]' orderGasPrice: '[ctype=orderGasPrice]' orderGallons: '[ctype=orderGallons]' orderGasType: '[ctype=orderGasType]' orderHorizontalRuleAboveVehicle: '[ctype=orderHorizontalRuleAboveVehicle]' orderVehicleMake: '[ctype=orderVehicleMake]' orderVehicleModel: '[ctype=orderVehicleModel]' orderVehicleYear: '[ctype=orderVehicleYear]' orderVehicleColor: '[ctype=orderVehicleColor]' orderVehicleLicensePlate: '[ctype=orderVehicleLicensePlate]' orderVehiclePhoto: '[ctype=orderVehiclePhoto]' orderCustomerName: '[ctype=orderCustomerName]' orderCustomerPhone: '[ctype=orderCustomerPhone]' orderServiceFee: '[ctype=orderServiceFee]' orderTotalPrice: '[ctype=orderTotalPrice]' orderHorizontalRuleAboveCustomerInfo: '[ctype=orderHorizontalRuleAboveCustomerInfo]' orderRating: '[ctype=orderRating]' orderStatusDisplay: '[ctype=orderStatusDisplay]' textRating: '[ctype=textRating]' sendRatingButtonContainer: '[ctype=sendRatingButtonContainer]' nextStatusButtonContainer: '[ctype=nextStatusButtonContainer]' control: orders: viewOrder: 'viewOrder' loadOrdersList: 'loadOrdersList' order: backToOrders: 'backToOrders' cancelOrder: 'askToCancelOrder' sendRating: 'sendRating' nextStatus: 'askToNextStatus' orderRating: change: 'orderRatingChange' orders: null orderListPageActive: yes launch: -> @callParent arguments getOrderById: (id) -> for o in @orders if o['id'] is orderId order = o break return order viewOrder: (orderId) -> @orderListPageActive = false for o in @orders if o['id'] is orderId order = o break @getOrdersTabContainer().setActiveItem( Ext.create 'Purple.view.Order', orderId: orderId status: order['status'] ) util.ctl('Menu').pushOntoBackButton => @backToOrders() @getOrder().addCls "status-#{order['status']}" @currentOrderClass = "status-#{order['status']}" if order['status'] is 'complete' @getOrderRating().show() order['display_status'] = if util.ctl('Account').isCourier() order['status'] else switch order['status'] when 'unassigned' then 'Accepted' else order['status'] order['time_order_placed'] = Ext.util.Format.date( new Date(order['target_time_start'] * 1000), "n/j/Y, g:i a" ) order['time_deadline'] = Ext.util.Format.date( new Date(order['target_time_end'] * 1000), "g:i a" ) diffMinutes = Math.floor( (order['target_time_end'] - order['target_time_start']) / 60 ) if diffMinutes < 60 order['display_time'] = "within #{diffMinutes} minutes" else diffHours = Math.round( diffMinutes / 60 ) order['display_time'] = "within #{diffHours} hour#{if diffHours is 1 then '' else 's'}" for v in util.ctl('Vehicles').vehicles if v['id'] is order['vehicle_id'] order['vehicle'] = "#{v.year} #{v.make} #{v.model}" order['license_plate'] = v.license_plate.toUpperCase() break if util.ctl('Account').isCourier() v = order['vehicle'] order['gas_type'] = v['gas_type'] order['vehicle_make'] = v['make'] order['vehicle_model'] = v['model'] order['vehicle_year'] = v['year'] order['vehicle_color'] = v['color'] order['vehicle_license_plate'] = v['license_plate'] order['vehicle_photo'] = v['photo'] c = order['customer'] order['customer_name'] = c['name'] order['customer_phone'] = c['phone_number'] order['gas_price_display'] = util.centsToDollars order['gas_price'] order['service_fee_display'] = util.centsToDollars order['service_fee'] order['total_price_display'] = util.centsToDollars order['total_price'] order['isnt_top_tier'] = not order['is_top_tier'] @getOrder().setValues order if order['tire_pressure_check'] @getOrderTirePressureCheck().show() if order['special_instructions'] is '' @getOrderSpecialInstructionsLabel().hide() @getOrderSpecialInstructions().hide() @getOrderAddressStreet().removeCls 'bottom-margin' else @getOrderSpecialInstructions().setHtml(order['special_instructions']) if util.ctl('Account').isCourier() @getOrderTimePlaced().hide() @getOrderDisplayTime().hide() @getOrderVehicle().hide() @getOrderGasPrice().hide() @getOrderServiceFee().hide() @getOrderTotalPrice().hide() @getOrderRating().hide() @getOrderTimeDeadline().show() @getOrderHorizontalRuleAboveVehicle().show() @getOrderVehicleMake().show() @getOrderVehicleModel().show() @getOrderVehicleYear().show() @getOrderVehicleColor().show() @getOrderVehicleLicensePlate().show() @getOrderHorizontalRuleAboveCustomerInfo().show() @getOrderCustomerName().show() @getOrderCustomerPhone().show() @getOrderGasType().show() if order['isnt_top_tier'] @getOrderIsntTopTier().show() @getOrderAddressZipcode().show() switch order['status'] when "unassigned" @getNextStatusButtonContainer().getAt(0).setText "Accept Order" @getNextStatusButtonContainer().show() when "assigned" @getNextStatusButtonContainer().getAt(0).setText "Accept Order" @getNextStatusButtonContainer().show() when "accepted" @getNextStatusButtonContainer().getAt(0).setText "Start Route" @getNextStatusButtonContainer().show() when "enroute" @getNextStatusButtonContainer().getAt(0).setText "Begin Servicing" @getNextStatusButtonContainer().show() when "servicing" @getNextStatusButtonContainer().getAt(0).setText "Complete Order" @getNextStatusButtonContainer().show() @getOrderAddressStreet().addCls 'click-to-edit' @getOrderAddressStreet().element.on 'tap', => # google maps window.open util.googleMapsDeepLink("?daddr=#{order.lat},#{order.lng}&directionsmode=driving"), "_system" # standard maps #window.location.href = "maps://?q=#{order.lat},#{order.lng}" @getOrderCustomerPhone().addCls 'click-to-edit' @getOrderCustomerPhone().element.on 'tap', => window.location.href = "tel://#{order['customer_phone']}" if order["vehicle_photo"]? and order["vehicle_photo"] isnt '' @getOrderVehiclePhoto().show() @getOrderVehiclePhoto().element.dom.style.cssText = """ background-color: transparent; background-size: cover; background-repeat: no-repeat; background-position: center; height: 300px; width: 100%; background-image: url('#{order["vehicle_photo"]}') !important; """ analytics?.page 'View Order', order_id: order.id backToOrders: -> @orderListPageActive = true @refreshOrdersAndOrdersList() @getOrdersTabContainer()?.remove( @getOrder(), yes ) isUserBusy: -> util.ctl('Vehicles').getEditVehicleForm()? or util.ctl('Main').getRequestForm()? or util.ctl('Main').getRequestConfirmationForm()? or util.ctl('Account').getEditAccountForm()? or util.ctl('PaymentMethods').getEditPaymentMethodForm()? or @getOrder()? updateLastOrderCompleted: -> for order in @orders if order.status is 'complete' if localStorage['lastOrderCompleted']? and not @isUserBusy() if localStorage['lastOrderCompleted'] isnt order.id and localStorage['orderListLength'] is @orders.length.toString() localStorage['lastOrderCompleted'] = order.id localStorage['orderListLength'] = @orders.length @sendToCompletedOrder() localStorage['lastOrderCompleted'] = order.id localStorage['orderListLength'] = @orders.length break sendToCompletedOrder: -> while util.ctl('Menu').backButtonStack.length util.ctl('Menu').popOffBackButton() util.ctl('Main').getMainContainer().getItems().getAt(0).select 3, no, no @viewOrder localStorage['lastOrderCompleted'] loadOrdersList: (forceUpdate = no, callback = null) -> if @orders? and not forceUpdate @renderOrdersList @orders else Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/details" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purplePI:KEY:<KEY>END_PI'] os: Ext.os.name # just an additional info headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @orders = response.orders util.ctl('Vehicles').vehicles = response.vehicles util.ctl('Vehicles').loadVehiclesList() @renderOrdersList @orders callback?() @lastLoadOrdersList = new Date().getTime() / 1000 @updateLastOrderCompleted() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response isActiveOrder: (o) -> -1 isnt util.ACTIVE_STATUSES.indexOf o.status getActiveOrders: -> @orders.filter @isActiveOrder # only call this after orders have been loaded hasActiveOrder: -> @getActiveOrders().length > 0 renderOrdersList: (orders) -> list = @getOrdersList() if not list? return list.removeAll yes, yes if orders.length is 0 and not util.ctl('Account').isCourier() list.add xtype: 'component' flex: 0 html: """ No orders yet. <br />Let's change that! Get gas now. """ cls: "loose-text" style: "text-align: center;" list.add xtype: 'container' # cls: 'slideable' flex: 0 height: 110 padding: '0 0 5 0' layout: type: 'vbox' pack: 'center' align: 'center' items: [ { xtype: 'button' ui: 'action' cls: 'button-pop' text: 'Get Started' flex: 0 disabled: no handler: -> util.ctl('Main').getMainContainer().getItems().getAt(0).select 0, no, no } ] for o in orders if util.ctl('Account').isCourier() v = o['vehicle'] else v = util.ctl('Vehicles').getVehicleById(o.vehicle_id) v ?= # if we don't have it in local memory then it must have been deleted id: o.vehicle_id user_id: localStorage['purpleUserId'] year: "Vehicle Deleted" timestamp_created: "1970-01-01T00:00:00Z" color: "" gas_type: "" license_plate: "" make: "" model: "" cls = [ 'bottom-margin' 'order-list-item' ] if o.status is 'complete' cls.push 'highlighted' if util.ctl('Account').isCourier() isLate = o.status isnt "complete" and o.status isnt "cancelled" and (new Date(o.target_time_end * 1000)) < (new Date()) dateDisplay = """ <span style="#{if isLate then "color: #f00;" else ""}"> #{Ext.util.Format.date( new Date(o.target_time_end * 1000), "n/j g:i a" )} </span> """ else dateDisplay = Ext.util.Format.date( new Date(o.target_time_start * 1000), "F jS" ) list.add xtype: 'textfield' id: "oid_#{o.id}" flex: 0 label: """ #{dateDisplay} <br /><span class="subtext">#{v.year} #{v.make} #{v.model}</span> <div class="status-square"> <div class="fill"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="60px" height="60px" viewBox="0 0 60 60" enable-background="new 0 0 60 60" xml:space="preserve"> <path fill="#04ACFF" id="waveShape" d="M300,300V2.5c0,0-0.6-0.1-1.1-0.1c0,0-25.5-2.3-40.5-2.4c-15,0-40.6,2.4-40.6,2.4 c-12.3,1.1-30.3,1.8-31.9,1.9c-2-0.1-19.7-0.8-32-1.9c0,0-25.8-2.3-40.8-2.4c-15,0-40.8,2.4-40.8,2.4c-12.3,1.1-30.4,1.8-32,1.9 c-2-0.1-20-0.8-32.2-1.9c0,0-3.1-0.3-8.1-0.7V300H300z"/> </svg> </div> </div> """ labelWidth: '100%' cls: cls disabled: yes listeners: painted: ((o)=>((field) => # todo -this method will cause a slight flicker for cancelled orders field.addCls "status-#{o.status}"))(o) initialize: (field) => field.element.on 'tap', => oid = field.getId().split('_')[1] @viewOrder oid @refreshOrdersAndOrdersList() refreshOrdersAndOrdersList: -> currentTime = new Date().getTime() / 1000 if currentTime - @lastLoadOrdersList > 30 or not @lastLoadOrdersList? if @orders? and @hasActiveOrder() and @getMainContainer().getActiveItem().data.index is 3 if @orderListPageActive @loadOrdersList yes else #order page is active @loadOrdersList yes, (Ext.bind @refreshOrder, this) refreshOrder: -> if @getOrder?() for o in @orders if o['id'] is @getOrder().config.orderId order = o break if order['status'] is 'unassigned' @getOrderStatusDisplay().setValue 'Accepted' else @getOrderStatusDisplay().setValue order['status'] @getOrder().removeCls @currentOrderClass @getOrder().addCls "status-#{order['status']}" @currentOrderClass = "status-#{order['status']}" if order['status'] is 'complete' @getOrderRating().show() askToCancelOrder: (id) -> util.confirm( '', """ Are you sure you want to cancel this order? """, (=> @cancelOrder id), null, 'Yes', 'No' ) cancelOrder: (id) -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}orders/cancel" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purplePI:KEY:<KEY>END_PI'] order_id: id headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @orders = response.orders @backToOrders() util.ctl('Menu').popOffBackButtonWithoutAction() @renderOrdersList @orders else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false console.log response_obj util.alert "Connection error. Please try again.", "Error", (->) orderRatingChange: (field, value) -> @getTextRating().show() @getSendRatingButtonContainer().show() sendToAppStore: -> localStorage['sentUserToAppStore'] = 'yes' if Ext.os.is.iOS cordova.plugins.market.open "id970824802" else cordova.plugins.market.open "com.purple.app" sendRating: -> values = @getOrder().getValues() id = @getOrder().config.orderId Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}orders/rate" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] order_id: id rating: number_rating: values['number_rating'] text_rating: values['text_rating'] headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @orders = response.orders @backToOrders() util.ctl('Menu').popOffBackButtonWithoutAction() @renderOrdersList @orders if values['number_rating'] is 5 and localStorage['sentUserToAppStore'] isnt 'yes' util.confirm( "Do you have a few seconds to help us by rating the Purple app?", "Thanks!", @sendToAppStore, (=> if localStorage['sentUserToAppStore'] is 'attempted' localStorage['sentUserToAppStore'] = 'yes' else localStorage['sentUserToAppStore'] = 'attempted' ) ) else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false console.log response_obj util.alert "Connection error. Please try again.", "Error", (->) askToNextStatus: -> values = @getOrder().getValues() currentStatus = values['status'] nextStatus = util.NEXT_STATUS_MAP[currentStatus] util.confirm( '', (switch nextStatus when "assigned", "accepted" "Are you sure you want to accept this order? (cannot be undone)" else "Are you sure you want to mark this order as #{nextStatus}? (cannot be undone)" ), (Ext.bind @nextStatus, this) null, 'Yes', 'No' ) nextStatus: -> values = @getOrder().getValues() currentStatus = values['status'] id = @getOrder().config.orderId Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}orders/update-status-by-courier" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['PI:KEY:<KEY>END_PIToken'] order_id: id status: util.NEXT_STATUS_MAP[currentStatus] headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @orders = response.orders @backToOrders() util.ctl('Menu').popOffBackButtonWithoutAction() @renderOrdersList @orders else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false console.log response_obj util.alert "Connection error. Please go back to Orders page and pull down to refresh. Do not press this button again until you have the updated status on the Orders page.", "Error", (->)
[ { "context": "ns Ember.RSVP.resolve(\n\t\tuser:\n\t\t\temail_address: \"cool@example.com\"\n\t)\n\n\tcontainer = new Ember.Container()\n\tcontaine", "end": 1216, "score": 0.9999210238456726, "start": 1200, "tag": "EMAIL", "value": "cool@example.com" }, { "context": "s\n\n\tdeepEqual(...
tests/unit/models/otp-login-test.coffee
dk-dev/balanced-dashboard
169
`import OtpLogin from "balanced-dashboard/models/otp-login";` module "Model - OtpLogin" test "#submitRequest", -> auth = Ember.Object.create( lastLoginUri: "/login/xxxxx" request: sinon.spy() ) container = new Ember.Container() container.register("auth:main", auth, singleton: true instantiate: false ) subject = OtpLogin.create( container: container otpCode: "xxxxxx" ) subject.submitRequest() deepEqual(auth.request.args, [[{ dataType: "JSON" url: "https://auth.balancedpayments.com/login/xxxxx" type: "PUT" data: confirm: "xxxxxx" }]]) test "validations", -> s = OtpLogin.create() s.validate() deepEqual(s.get("validationErrors.fullMessages"), [ "otpCode can't be blank" ]) s.set("otpCode", "3030") s.validate() deepEqual(s.get("validationErrors.fullMessages"), []) test "#save (invalid)", -> spy = sinon.stub() s = OtpLogin.create() Ember.run -> s.save().then(undefined, spy) deepEqual(spy.callCount, 1) deepEqual(s.get("validationErrors.fullMessages"), [ "otpCode can't be blank" ]) test "#save (valid)", -> auth = Ember.Object.create( request: sinon.stub() ) auth.request.returns Ember.RSVP.resolve( user: email_address: "cool@example.com" ) container = new Ember.Container() container.register("auth:main", auth, singleton: true instantiate: false ) subject = OtpLogin.create( container: container path: "/login/xxxxx" otpCode: "xxxxxx" ) session = undefined Ember.run -> subject.save().then (s) -> session = s deepEqual(session.get("user.email_address"), "cool@example.com")
134225
`import OtpLogin from "balanced-dashboard/models/otp-login";` module "Model - OtpLogin" test "#submitRequest", -> auth = Ember.Object.create( lastLoginUri: "/login/xxxxx" request: sinon.spy() ) container = new Ember.Container() container.register("auth:main", auth, singleton: true instantiate: false ) subject = OtpLogin.create( container: container otpCode: "xxxxxx" ) subject.submitRequest() deepEqual(auth.request.args, [[{ dataType: "JSON" url: "https://auth.balancedpayments.com/login/xxxxx" type: "PUT" data: confirm: "xxxxxx" }]]) test "validations", -> s = OtpLogin.create() s.validate() deepEqual(s.get("validationErrors.fullMessages"), [ "otpCode can't be blank" ]) s.set("otpCode", "3030") s.validate() deepEqual(s.get("validationErrors.fullMessages"), []) test "#save (invalid)", -> spy = sinon.stub() s = OtpLogin.create() Ember.run -> s.save().then(undefined, spy) deepEqual(spy.callCount, 1) deepEqual(s.get("validationErrors.fullMessages"), [ "otpCode can't be blank" ]) test "#save (valid)", -> auth = Ember.Object.create( request: sinon.stub() ) auth.request.returns Ember.RSVP.resolve( user: email_address: "<EMAIL>" ) container = new Ember.Container() container.register("auth:main", auth, singleton: true instantiate: false ) subject = OtpLogin.create( container: container path: "/login/xxxxx" otpCode: "xxxxxx" ) session = undefined Ember.run -> subject.save().then (s) -> session = s deepEqual(session.get("user.email_address"), "<EMAIL>")
true
`import OtpLogin from "balanced-dashboard/models/otp-login";` module "Model - OtpLogin" test "#submitRequest", -> auth = Ember.Object.create( lastLoginUri: "/login/xxxxx" request: sinon.spy() ) container = new Ember.Container() container.register("auth:main", auth, singleton: true instantiate: false ) subject = OtpLogin.create( container: container otpCode: "xxxxxx" ) subject.submitRequest() deepEqual(auth.request.args, [[{ dataType: "JSON" url: "https://auth.balancedpayments.com/login/xxxxx" type: "PUT" data: confirm: "xxxxxx" }]]) test "validations", -> s = OtpLogin.create() s.validate() deepEqual(s.get("validationErrors.fullMessages"), [ "otpCode can't be blank" ]) s.set("otpCode", "3030") s.validate() deepEqual(s.get("validationErrors.fullMessages"), []) test "#save (invalid)", -> spy = sinon.stub() s = OtpLogin.create() Ember.run -> s.save().then(undefined, spy) deepEqual(spy.callCount, 1) deepEqual(s.get("validationErrors.fullMessages"), [ "otpCode can't be blank" ]) test "#save (valid)", -> auth = Ember.Object.create( request: sinon.stub() ) auth.request.returns Ember.RSVP.resolve( user: email_address: "PI:EMAIL:<EMAIL>END_PI" ) container = new Ember.Container() container.register("auth:main", auth, singleton: true instantiate: false ) subject = OtpLogin.create( container: container path: "/login/xxxxx" otpCode: "xxxxxx" ) session = undefined Ember.run -> subject.save().then (s) -> session = s deepEqual(session.get("user.email_address"), "PI:EMAIL:<EMAIL>END_PI")
[ { "context": "> coffee foo.coffee\nhttp://foo bar/?name=Foo Barson\n", "end": 51, "score": 0.9979534149169922, "start": 41, "tag": "NAME", "value": "Foo Barson" } ]
Task/URL-decoding/CoffeeScript/url-decoding-2.coffee
LaudateCorpus1/RosettaCodeData
1
> coffee foo.coffee http://foo bar/?name=Foo Barson
145535
> coffee foo.coffee http://foo bar/?name=<NAME>
true
> coffee foo.coffee http://foo bar/?name=PI:NAME:<NAME>END_PI
[ { "context": "oan'\n 'body': '''\n mailto(${1:'${2:me@my-site.com}'${3:, '${4:text}'${5:, ${6:\\$attribs}}}});\n ", "end": 945, "score": 0.9993768334388733, "start": 931, "tag": "EMAIL", "value": "me@my-site.com" }, { "context": " 'body': '''\n safe_...
snippets/url_helper.cson
femi-dd/codeigniter-atom
1
'.source.php': 'Codeigniter Anchor': 'prefix':'cianchor' 'body': ''' anchor(${1:'${2:segments}'${3:, '${4:text}'${5:, ${6:attribs}}}}); ''' 'Codeigniter Anchor Popup': 'prefix':'cianchorpop' 'body': ''' anchor_popup(${1:'${2:segments}'${3:, '${4:text}'${5:, ${6:attribs}}}}); ''' 'Codeigniter Autolink': 'prefix':'ciautolink' 'body': ''' auto_link(${1:'${2:string}'}); ''' 'Codeigniter Base URL': 'prefix':'cibaseurl' 'body': ''' base_url(${1:'${2:string}'}); ''' 'Codeigniter Current URL': 'prefix':'cicurrent' 'body': ''' current_url(); ''' 'Codeigniter Index Page': 'prefix':'ciindex' 'body': ''' index_page(); ''' 'Codeigniter Mail To Anchor': 'prefix':'cimailtoan' 'body': ''' mailto(${1:'${2:me@my-site.com}'${3:, '${4:text}'${5:, ${6:\$attribs}}}}); ''' 'Codeigniter Prepend URL': 'prefix':'ciprepurl' 'body': ''' prep_url(${1:'${2:string}'}); ''' 'Codeigniter Redirect': 'prefix':'ciredir' 'body': ''' redirect(${1:'${2:route}'}${3:, '${4:refresh}'}); ''' 'Codeigniter Safe Mail To': 'prefix':'cisafemail' 'body': ''' safe_mailto(${1:'${2:me@my-site.com}'${3:, '${4:text}'${5:, ${6:\$attribs}}}}); ''' 'Codeigniter Site URL': 'prefix':'cisiteurl' 'body': ''' site_url(${1:'${2:string}'}); ''' 'Codeigniter URI string': 'prefix':'ciuristr' 'body': ''' uri_string(); ''' 'Codeigniter URL Title': 'prefix':'ciurltitle' 'body': ''' url_title(${1:'${2:string}'}${3:, '${4:dash}'${5:, ${6:TRUE}}}); '''
219454
'.source.php': 'Codeigniter Anchor': 'prefix':'cianchor' 'body': ''' anchor(${1:'${2:segments}'${3:, '${4:text}'${5:, ${6:attribs}}}}); ''' 'Codeigniter Anchor Popup': 'prefix':'cianchorpop' 'body': ''' anchor_popup(${1:'${2:segments}'${3:, '${4:text}'${5:, ${6:attribs}}}}); ''' 'Codeigniter Autolink': 'prefix':'ciautolink' 'body': ''' auto_link(${1:'${2:string}'}); ''' 'Codeigniter Base URL': 'prefix':'cibaseurl' 'body': ''' base_url(${1:'${2:string}'}); ''' 'Codeigniter Current URL': 'prefix':'cicurrent' 'body': ''' current_url(); ''' 'Codeigniter Index Page': 'prefix':'ciindex' 'body': ''' index_page(); ''' 'Codeigniter Mail To Anchor': 'prefix':'cimailtoan' 'body': ''' mailto(${1:'${2:<EMAIL>}'${3:, '${4:text}'${5:, ${6:\$attribs}}}}); ''' 'Codeigniter Prepend URL': 'prefix':'ciprepurl' 'body': ''' prep_url(${1:'${2:string}'}); ''' 'Codeigniter Redirect': 'prefix':'ciredir' 'body': ''' redirect(${1:'${2:route}'}${3:, '${4:refresh}'}); ''' 'Codeigniter Safe Mail To': 'prefix':'cisafemail' 'body': ''' safe_mailto(${1:'${2:<EMAIL>}'${3:, '${4:text}'${5:, ${6:\$attribs}}}}); ''' 'Codeigniter Site URL': 'prefix':'cisiteurl' 'body': ''' site_url(${1:'${2:string}'}); ''' 'Codeigniter URI string': 'prefix':'ciuristr' 'body': ''' uri_string(); ''' 'Codeigniter URL Title': 'prefix':'ciurltitle' 'body': ''' url_title(${1:'${2:string}'}${3:, '${4:dash}'${5:, ${6:TRUE}}}); '''
true
'.source.php': 'Codeigniter Anchor': 'prefix':'cianchor' 'body': ''' anchor(${1:'${2:segments}'${3:, '${4:text}'${5:, ${6:attribs}}}}); ''' 'Codeigniter Anchor Popup': 'prefix':'cianchorpop' 'body': ''' anchor_popup(${1:'${2:segments}'${3:, '${4:text}'${5:, ${6:attribs}}}}); ''' 'Codeigniter Autolink': 'prefix':'ciautolink' 'body': ''' auto_link(${1:'${2:string}'}); ''' 'Codeigniter Base URL': 'prefix':'cibaseurl' 'body': ''' base_url(${1:'${2:string}'}); ''' 'Codeigniter Current URL': 'prefix':'cicurrent' 'body': ''' current_url(); ''' 'Codeigniter Index Page': 'prefix':'ciindex' 'body': ''' index_page(); ''' 'Codeigniter Mail To Anchor': 'prefix':'cimailtoan' 'body': ''' mailto(${1:'${2:PI:EMAIL:<EMAIL>END_PI}'${3:, '${4:text}'${5:, ${6:\$attribs}}}}); ''' 'Codeigniter Prepend URL': 'prefix':'ciprepurl' 'body': ''' prep_url(${1:'${2:string}'}); ''' 'Codeigniter Redirect': 'prefix':'ciredir' 'body': ''' redirect(${1:'${2:route}'}${3:, '${4:refresh}'}); ''' 'Codeigniter Safe Mail To': 'prefix':'cisafemail' 'body': ''' safe_mailto(${1:'${2:PI:EMAIL:<EMAIL>END_PI}'${3:, '${4:text}'${5:, ${6:\$attribs}}}}); ''' 'Codeigniter Site URL': 'prefix':'cisiteurl' 'body': ''' site_url(${1:'${2:string}'}); ''' 'Codeigniter URI string': 'prefix':'ciuristr' 'body': ''' uri_string(); ''' 'Codeigniter URL Title': 'prefix':'ciurltitle' 'body': ''' url_title(${1:'${2:string}'}${3:, '${4:dash}'${5:, ${6:TRUE}}}); '''
[ { "context": "ferno color maps ###\n# New matplotlib colormaps by Nathaniel J. Smith, Stefan van der Walt,\n# and (in the case of virid", "end": 41177, "score": 0.9998845458030701, "start": 41159, "tag": "NAME", "value": "Nathaniel J. Smith" }, { "context": "\n# New matplotlib colorm...
bokehjs/src/coffee/palettes/palettes.coffee
SiggyF/bokeh
0
_ = require("underscore") palettes = { YlGn: { YlGn3 : [0x31a354, 0xaddd8e, 0xf7fcb9] YlGn4 : [0x238443, 0x78c679, 0xc2e699, 0xffffcc] YlGn5 : [0x006837, 0x31a354, 0x78c679, 0xc2e699, 0xffffcc] YlGn6 : [0x006837, 0x31a354, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xffffcc] YlGn7 : [0x005a32, 0x238443, 0x41ab5d, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xffffcc] YlGn8 : [0x005a32, 0x238443, 0x41ab5d, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xf7fcb9, 0xffffe5] YlGn9 : [0x004529, 0x006837, 0x238443, 0x41ab5d, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xf7fcb9, 0xffffe5] } YlGnBu: { YlGnBu3 : [0x2c7fb8, 0x7fcdbb, 0xedf8b1] YlGnBu4 : [0x225ea8, 0x41b6c4, 0xa1dab4, 0xffffcc] YlGnBu5 : [0x253494, 0x2c7fb8, 0x41b6c4, 0xa1dab4, 0xffffcc] YlGnBu6 : [0x253494, 0x2c7fb8, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xffffcc] YlGnBu7 : [0x0c2c84, 0x225ea8, 0x1d91c0, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xffffcc] YlGnBu8 : [0x0c2c84, 0x225ea8, 0x1d91c0, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xedf8b1, 0xffffd9] YlGnBu9 : [0x081d58, 0x253494, 0x225ea8, 0x1d91c0, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xedf8b1, 0xffffd9] } GnBu: { GnBu3 : [0x43a2ca, 0xa8ddb5, 0xe0f3db] GnBu4 : [0x2b8cbe, 0x7bccc4, 0xbae4bc, 0xf0f9e8] GnBu5 : [0x0868ac, 0x43a2ca, 0x7bccc4, 0xbae4bc, 0xf0f9e8] GnBu6 : [0x0868ac, 0x43a2ca, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xf0f9e8] GnBu7 : [0x08589e, 0x2b8cbe, 0x4eb3d3, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xf0f9e8] GnBu8 : [0x08589e, 0x2b8cbe, 0x4eb3d3, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xe0f3db, 0xf7fcf0] GnBu9 : [0x084081, 0x0868ac, 0x2b8cbe, 0x4eb3d3, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xe0f3db, 0xf7fcf0] } BuGn: { BuGn3 : [0x2ca25f, 0x99d8c9, 0xe5f5f9] BuGn4 : [0x238b45, 0x66c2a4, 0xb2e2e2, 0xedf8fb] BuGn5 : [0x006d2c, 0x2ca25f, 0x66c2a4, 0xb2e2e2, 0xedf8fb] BuGn6 : [0x006d2c, 0x2ca25f, 0x66c2a4, 0x99d8c9, 0xccece6, 0xedf8fb] BuGn7 : [0x005824, 0x238b45, 0x41ae76, 0x66c2a4, 0x99d8c9, 0xccece6, 0xedf8fb] BuGn8 : [0x005824, 0x238b45, 0x41ae76, 0x66c2a4, 0x99d8c9, 0xccece6, 0xe5f5f9, 0xf7fcfd] BuGn9 : [0x00441b, 0x006d2c, 0x238b45, 0x41ae76, 0x66c2a4, 0x99d8c9, 0xccece6, 0xe5f5f9, 0xf7fcfd] } PuBuGn: { PuBuGn3 : [0x1c9099, 0xa6bddb, 0xece2f0] PuBuGn4 : [0x02818a, 0x67a9cf, 0xbdc9e1, 0xf6eff7] PuBuGn5 : [0x016c59, 0x1c9099, 0x67a9cf, 0xbdc9e1, 0xf6eff7] PuBuGn6 : [0x016c59, 0x1c9099, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xf6eff7] PuBuGn7 : [0x016450, 0x02818a, 0x3690c0, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xf6eff7] PuBuGn8 : [0x016450, 0x02818a, 0x3690c0, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xece2f0, 0xfff7fb] PuBuGn9 : [0x014636, 0x016c59, 0x02818a, 0x3690c0, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xece2f0, 0xfff7fb] } PuBu: { PuBu3 : [0x2b8cbe, 0xa6bddb, 0xece7f2] PuBu4 : [0x0570b0, 0x74a9cf, 0xbdc9e1, 0xf1eef6] PuBu5 : [0x045a8d, 0x2b8cbe, 0x74a9cf, 0xbdc9e1, 0xf1eef6] PuBu6 : [0x045a8d, 0x2b8cbe, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xf1eef6] PuBu7 : [0x034e7b, 0x0570b0, 0x3690c0, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xf1eef6] PuBu8 : [0x034e7b, 0x0570b0, 0x3690c0, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xece7f2, 0xfff7fb] PuBu9 : [0x023858, 0x045a8d, 0x0570b0, 0x3690c0, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xece7f2, 0xfff7fb] } BuPu: { BuPu3 : [0x8856a7, 0x9ebcda, 0xe0ecf4] BuPu4 : [0x88419d, 0x8c96c6, 0xb3cde3, 0xedf8fb] BuPu5 : [0x810f7c, 0x8856a7, 0x8c96c6, 0xb3cde3, 0xedf8fb] BuPu6 : [0x810f7c, 0x8856a7, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xedf8fb] BuPu7 : [0x6e016b, 0x88419d, 0x8c6bb1, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xedf8fb] BuPu8 : [0x6e016b, 0x88419d, 0x8c6bb1, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xe0ecf4, 0xf7fcfd] BuPu9 : [0x4d004b, 0x810f7c, 0x88419d, 0x8c6bb1, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xe0ecf4, 0xf7fcfd] } RdPu: { RdPu3 : [0xc51b8a, 0xfa9fb5, 0xfde0dd] RdPu4 : [0xae017e, 0xf768a1, 0xfbb4b9, 0xfeebe2] RdPu5 : [0x7a0177, 0xc51b8a, 0xf768a1, 0xfbb4b9, 0xfeebe2] RdPu6 : [0x7a0177, 0xc51b8a, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfeebe2] RdPu7 : [0x7a0177, 0xae017e, 0xdd3497, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfeebe2] RdPu8 : [0x7a0177, 0xae017e, 0xdd3497, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfde0dd, 0xfff7f3] RdPu9 : [0x49006a, 0x7a0177, 0xae017e, 0xdd3497, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfde0dd, 0xfff7f3] } PuRd: { PuRd3 : [0xdd1c77, 0xc994c7, 0xe7e1ef] PuRd4 : [0xce1256, 0xdf65b0, 0xd7b5d8, 0xf1eef6] PuRd5 : [0x980043, 0xdd1c77, 0xdf65b0, 0xd7b5d8, 0xf1eef6] PuRd6 : [0x980043, 0xdd1c77, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xf1eef6] PuRd7 : [0x91003f, 0xce1256, 0xe7298a, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xf1eef6] PuRd8 : [0x91003f, 0xce1256, 0xe7298a, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xe7e1ef, 0xf7f4f9] PuRd9 : [0x67001f, 0x980043, 0xce1256, 0xe7298a, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xe7e1ef, 0xf7f4f9] } OrRd: { OrRd3 : [0xe34a33, 0xfdbb84, 0xfee8c8] OrRd4 : [0xd7301f, 0xfc8d59, 0xfdcc8a, 0xfef0d9] OrRd5 : [0xb30000, 0xe34a33, 0xfc8d59, 0xfdcc8a, 0xfef0d9] OrRd6 : [0xb30000, 0xe34a33, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfef0d9] OrRd7 : [0x990000, 0xd7301f, 0xef6548, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfef0d9] OrRd8 : [0x990000, 0xd7301f, 0xef6548, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfee8c8, 0xfff7ec] OrRd9 : [0x7f0000, 0xb30000, 0xd7301f, 0xef6548, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfee8c8, 0xfff7ec] } YlOrRd: { YlOrRd3 : [0xf03b20, 0xfeb24c, 0xffeda0] YlOrRd4 : [0xe31a1c, 0xfd8d3c, 0xfecc5c, 0xffffb2] YlOrRd5 : [0xbd0026, 0xf03b20, 0xfd8d3c, 0xfecc5c, 0xffffb2] YlOrRd6 : [0xbd0026, 0xf03b20, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffffb2] YlOrRd7 : [0xb10026, 0xe31a1c, 0xfc4e2a, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffffb2] YlOrRd8 : [0xb10026, 0xe31a1c, 0xfc4e2a, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffeda0, 0xffffcc] YlOrRd9 : [0x800026, 0xbd0026, 0xe31a1c, 0xfc4e2a, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffeda0, 0xffffcc] } YlOrBr: { YlOrBr3 : [0xd95f0e, 0xfec44f, 0xfff7bc] YlOrBr4 : [0xcc4c02, 0xfe9929, 0xfed98e, 0xffffd4] YlOrBr5 : [0x993404, 0xd95f0e, 0xfe9929, 0xfed98e, 0xffffd4] YlOrBr6 : [0x993404, 0xd95f0e, 0xfe9929, 0xfec44f, 0xfee391, 0xffffd4] YlOrBr7 : [0x8c2d04, 0xcc4c02, 0xec7014, 0xfe9929, 0xfec44f, 0xfee391, 0xffffd4] YlOrBr8 : [0x8c2d04, 0xcc4c02, 0xec7014, 0xfe9929, 0xfec44f, 0xfee391, 0xfff7bc, 0xffffe5] YlOrBr9 : [0x662506, 0x993404, 0xcc4c02, 0xec7014, 0xfe9929, 0xfec44f, 0xfee391, 0xfff7bc, 0xffffe5] } Purples: { Purples3 : [0x756bb1, 0xbcbddc, 0xefedf5] Purples4 : [0x6a51a3, 0x9e9ac8, 0xcbc9e2, 0xf2f0f7] Purples5 : [0x54278f, 0x756bb1, 0x9e9ac8, 0xcbc9e2, 0xf2f0f7] Purples6 : [0x54278f, 0x756bb1, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xf2f0f7] Purples7 : [0x4a1486, 0x6a51a3, 0x807dba, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xf2f0f7] Purples8 : [0x4a1486, 0x6a51a3, 0x807dba, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xefedf5, 0xfcfbfd] Purples9 : [0x3f007d, 0x54278f, 0x6a51a3, 0x807dba, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xefedf5, 0xfcfbfd] } Blues: { Blues3 : [0x3182bd, 0x9ecae1, 0xdeebf7] Blues4 : [0x2171b5, 0x6baed6, 0xbdd7e7, 0xeff3ff] Blues5 : [0x08519c, 0x3182bd, 0x6baed6, 0xbdd7e7, 0xeff3ff] Blues6 : [0x08519c, 0x3182bd, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xeff3ff] Blues7 : [0x084594, 0x2171b5, 0x4292c6, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xeff3ff] Blues8 : [0x084594, 0x2171b5, 0x4292c6, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xdeebf7, 0xf7fbff] Blues9 : [0x08306b, 0x08519c, 0x2171b5, 0x4292c6, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xdeebf7, 0xf7fbff] } Greens: { Greens3 : [0x31a354, 0xa1d99b, 0xe5f5e0] Greens4 : [0x238b45, 0x74c476, 0xbae4b3, 0xedf8e9] Greens5 : [0x006d2c, 0x31a354, 0x74c476, 0xbae4b3, 0xedf8e9] Greens6 : [0x006d2c, 0x31a354, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xedf8e9] Greens7 : [0x005a32, 0x238b45, 0x41ab5d, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xedf8e9] Greens8 : [0x005a32, 0x238b45, 0x41ab5d, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xe5f5e0, 0xf7fcf5] Greens9 : [0x00441b, 0x006d2c, 0x238b45, 0x41ab5d, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xe5f5e0, 0xf7fcf5] } Oranges: { Oranges3 : [0xe6550d, 0xfdae6b, 0xfee6ce] Oranges4 : [0xd94701, 0xfd8d3c, 0xfdbe85, 0xfeedde] Oranges5 : [0xa63603, 0xe6550d, 0xfd8d3c, 0xfdbe85, 0xfeedde] Oranges6 : [0xa63603, 0xe6550d, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfeedde] Oranges7 : [0x8c2d04, 0xd94801, 0xf16913, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfeedde] Oranges8 : [0x8c2d04, 0xd94801, 0xf16913, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfee6ce, 0xfff5eb] Oranges9 : [0x7f2704, 0xa63603, 0xd94801, 0xf16913, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfee6ce, 0xfff5eb] } Reds: { Reds3 : [0xde2d26, 0xfc9272, 0xfee0d2] Reds4 : [0xcb181d, 0xfb6a4a, 0xfcae91, 0xfee5d9] Reds5 : [0xa50f15, 0xde2d26, 0xfb6a4a, 0xfcae91, 0xfee5d9] Reds6 : [0xa50f15, 0xde2d26, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee5d9] Reds7 : [0x99000d, 0xcb181d, 0xef3b2c, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee5d9] Reds8 : [0x99000d, 0xcb181d, 0xef3b2c, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee0d2, 0xfff5f0] Reds9 : [0x67000d, 0xa50f15, 0xcb181d, 0xef3b2c, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee0d2, 0xfff5f0] } Greys: { Greys3 : [0x636363, 0xbdbdbd, 0xf0f0f0] Greys4 : [0x525252, 0x969696, 0xcccccc, 0xf7f7f7] Greys5 : [0x252525, 0x636363, 0x969696, 0xcccccc, 0xf7f7f7] Greys6 : [0x252525, 0x636363, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf7f7f7] Greys7 : [0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf7f7f7] Greys8 : [0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf0f0f0, 0xffffff] Greys9 : [0x000000, 0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf0f0f0, 0xffffff] Greys10 : [0x000000, 0x1c1c1c, 0x383838, 0x555555, 0x717171, 0x8d8d8d, 0xaaaaaa, 0xc6c6c6, 0xe2e2e2, 0xffffff] Greys11 : [0x000000, 0x191919, 0x333333, 0x4c4c4c, 0x666666, 0x7f7f7f, 0x999999, 0xb2b2b2, 0xcccccc, 0xe5e5e5, 0xffffff] Greys256 : [ 0x000000, 0x010101, 0x020202, 0x030303, 0x040404, 0x050505, 0x060606, 0x070707, 0x080808, 0x090909, 0x0a0a0a, 0x0b0b0b, 0x0c0c0c, 0x0d0d0d, 0x0e0e0e, 0x0f0f0f, 0x101010, 0x111111, 0x121212, 0x131313, 0x141414, 0x151515, 0x161616, 0x171717, 0x181818, 0x191919, 0x1a1a1a, 0x1b1b1b, 0x1c1c1c, 0x1d1d1d, 0x1e1e1e, 0x1f1f1f, 0x202020, 0x212121, 0x222222, 0x232323, 0x242424, 0x252525, 0x262626, 0x272727, 0x282828, 0x292929, 0x2a2a2a, 0x2b2b2b, 0x2c2c2c, 0x2d2d2d, 0x2e2e2e, 0x2f2f2f, 0x303030, 0x313131, 0x323232, 0x333333, 0x343434, 0x353535, 0x363636, 0x373737, 0x383838, 0x393939, 0x3a3a3a, 0x3b3b3b, 0x3c3c3c, 0x3d3d3d, 0x3e3e3e, 0x3f3f3f, 0x404040, 0x414141, 0x424242, 0x434343, 0x444444, 0x454545, 0x464646, 0x474747, 0x484848, 0x494949, 0x4a4a4a, 0x4b4b4b, 0x4c4c4c, 0x4d4d4d, 0x4e4e4e, 0x4f4f4f, 0x505050, 0x515151, 0x525252, 0x535353, 0x545454, 0x555555, 0x565656, 0x575757, 0x585858, 0x595959, 0x5a5a5a, 0x5b5b5b, 0x5c5c5c, 0x5d5d5d, 0x5e5e5e, 0x5f5f5f, 0x606060, 0x616161, 0x626262, 0x636363, 0x646464, 0x656565, 0x666666, 0x676767, 0x686868, 0x696969, 0x6a6a6a, 0x6b6b6b, 0x6c6c6c, 0x6d6d6d, 0x6e6e6e, 0x6f6f6f, 0x707070, 0x717171, 0x727272, 0x737373, 0x747474, 0x757575, 0x767676, 0x777777, 0x787878, 0x797979, 0x7a7a7a, 0x7b7b7b, 0x7c7c7c, 0x7d7d7d, 0x7e7e7e, 0x7f7f7f, 0x808080, 0x818181, 0x828282, 0x838383, 0x848484, 0x858585, 0x868686, 0x878787, 0x888888, 0x898989, 0x8a8a8a, 0x8b8b8b, 0x8c8c8c, 0x8d8d8d, 0x8e8e8e, 0x8f8f8f, 0x909090, 0x919191, 0x929292, 0x939393, 0x949494, 0x959595, 0x969696, 0x979797, 0x989898, 0x999999, 0x9a9a9a, 0x9b9b9b, 0x9c9c9c, 0x9d9d9d, 0x9e9e9e, 0x9f9f9f, 0xa0a0a0, 0xa1a1a1, 0xa2a2a2, 0xa3a3a3, 0xa4a4a4, 0xa5a5a5, 0xa6a6a6, 0xa7a7a7, 0xa8a8a8, 0xa9a9a9, 0xaaaaaa, 0xababab, 0xacacac, 0xadadad, 0xaeaeae, 0xafafaf, 0xb0b0b0, 0xb1b1b1, 0xb2b2b2, 0xb3b3b3, 0xb4b4b4, 0xb5b5b5, 0xb6b6b6, 0xb7b7b7, 0xb8b8b8, 0xb9b9b9, 0xbababa, 0xbbbbbb, 0xbcbcbc, 0xbdbdbd, 0xbebebe, 0xbfbfbf, 0xc0c0c0, 0xc1c1c1, 0xc2c2c2, 0xc3c3c3, 0xc4c4c4, 0xc5c5c5, 0xc6c6c6, 0xc7c7c7, 0xc8c8c8, 0xc9c9c9, 0xcacaca, 0xcbcbcb, 0xcccccc, 0xcdcdcd, 0xcecece, 0xcfcfcf, 0xd0d0d0, 0xd1d1d1, 0xd2d2d2, 0xd3d3d3, 0xd4d4d4, 0xd5d5d5, 0xd6d6d6, 0xd7d7d7, 0xd8d8d8, 0xd9d9d9, 0xdadada, 0xdbdbdb, 0xdcdcdc, 0xdddddd, 0xdedede, 0xdfdfdf, 0xe0e0e0, 0xe1e1e1, 0xe2e2e2, 0xe3e3e3, 0xe4e4e4, 0xe5e5e5, 0xe6e6e6, 0xe7e7e7, 0xe8e8e8, 0xe9e9e9, 0xeaeaea, 0xebebeb, 0xececec, 0xededed, 0xeeeeee, 0xefefef, 0xf0f0f0, 0xf1f1f1, 0xf2f2f2, 0xf3f3f3, 0xf4f4f4, 0xf5f5f5, 0xf6f6f6, 0xf7f7f7, 0xf8f8f8, 0xf9f9f9, 0xfafafa, 0xfbfbfb, 0xfcfcfc, 0xfdfdfd, 0xfefefe, 0xffffff] } PuOr: { PuOr3 : [0x998ec3, 0xf7f7f7, 0xf1a340] PuOr4 : [0x5e3c99, 0xb2abd2, 0xfdb863, 0xe66101] PuOr5 : [0x5e3c99, 0xb2abd2, 0xf7f7f7, 0xfdb863, 0xe66101] PuOr6 : [0x542788, 0x998ec3, 0xd8daeb, 0xfee0b6, 0xf1a340, 0xb35806] PuOr7 : [0x542788, 0x998ec3, 0xd8daeb, 0xf7f7f7, 0xfee0b6, 0xf1a340, 0xb35806] PuOr8 : [0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806] PuOr9 : [0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xf7f7f7, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806] PuOr10 : [0x2d004b, 0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806, 0x7f3b08] PuOr11 : [0x2d004b, 0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xf7f7f7, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806, 0x7f3b08] } BrBG: { BrBG3 : [0x5ab4ac, 0xf5f5f5, 0xd8b365] BrBG4 : [0x018571, 0x80cdc1, 0xdfc27d, 0xa6611a] BrBG5 : [0x018571, 0x80cdc1, 0xf5f5f5, 0xdfc27d, 0xa6611a] BrBG6 : [0x01665e, 0x5ab4ac, 0xc7eae5, 0xf6e8c3, 0xd8b365, 0x8c510a] BrBG7 : [0x01665e, 0x5ab4ac, 0xc7eae5, 0xf5f5f5, 0xf6e8c3, 0xd8b365, 0x8c510a] BrBG8 : [0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a] BrBG9 : [0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf5f5f5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a] BrBG10 : [0x003c30, 0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a, 0x543005] BrBG11 : [0x003c30, 0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf5f5f5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a, 0x543005] } PRGn: { PRGn3 : [0x7fbf7b, 0xf7f7f7, 0xaf8dc3] PRGn4 : [0x008837, 0xa6dba0, 0xc2a5cf, 0x7b3294] PRGn5 : [0x008837, 0xa6dba0, 0xf7f7f7, 0xc2a5cf, 0x7b3294] PRGn6 : [0x1b7837, 0x7fbf7b, 0xd9f0d3, 0xe7d4e8, 0xaf8dc3, 0x762a83] PRGn7 : [0x1b7837, 0x7fbf7b, 0xd9f0d3, 0xf7f7f7, 0xe7d4e8, 0xaf8dc3, 0x762a83] PRGn8 : [0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83] PRGn9 : [0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xf7f7f7, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83] PRGn10 : [0x00441b, 0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83, 0x40004b] PRGn11 : [0x00441b, 0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xf7f7f7, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83, 0x40004b] } PiYG: { PiYG3 : [0xa1d76a, 0xf7f7f7, 0xe9a3c9] PiYG4 : [0x4dac26, 0xb8e186, 0xf1b6da, 0xd01c8b] PiYG5 : [0x4dac26, 0xb8e186, 0xf7f7f7, 0xf1b6da, 0xd01c8b] PiYG6 : [0x4d9221, 0xa1d76a, 0xe6f5d0, 0xfde0ef, 0xe9a3c9, 0xc51b7d] PiYG7 : [0x4d9221, 0xa1d76a, 0xe6f5d0, 0xf7f7f7, 0xfde0ef, 0xe9a3c9, 0xc51b7d] PiYG8 : [0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d] PiYG9 : [0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xf7f7f7, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d] PiYG10 : [0x276419, 0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d, 0x8e0152] PiYG11 : [0x276419, 0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xf7f7f7, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d, 0x8e0152] } RdBu: { RdBu3 : [0x67a9cf, 0xf7f7f7, 0xef8a62] RdBu4 : [0x0571b0, 0x92c5de, 0xf4a582, 0xca0020] RdBu5 : [0x0571b0, 0x92c5de, 0xf7f7f7, 0xf4a582, 0xca0020] RdBu6 : [0x2166ac, 0x67a9cf, 0xd1e5f0, 0xfddbc7, 0xef8a62, 0xb2182b] RdBu7 : [0x2166ac, 0x67a9cf, 0xd1e5f0, 0xf7f7f7, 0xfddbc7, 0xef8a62, 0xb2182b] RdBu8 : [0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b] RdBu9 : [0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xf7f7f7, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b] RdBu10 : [0x053061, 0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f] RdBu11 : [0x053061, 0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xf7f7f7, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f] } RdGy: { RdGy3 : [0x999999, 0xffffff, 0xef8a62] RdGy4 : [0x404040, 0xbababa, 0xf4a582, 0xca0020] RdGy5 : [0x404040, 0xbababa, 0xffffff, 0xf4a582, 0xca0020] RdGy6 : [0x4d4d4d, 0x999999, 0xe0e0e0, 0xfddbc7, 0xef8a62, 0xb2182b] RdGy7 : [0x4d4d4d, 0x999999, 0xe0e0e0, 0xffffff, 0xfddbc7, 0xef8a62, 0xb2182b] RdGy8 : [0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b] RdGy9 : [0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xffffff, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b] RdGy10 : [0x1a1a1a, 0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f] RdGy11 : [0x1a1a1a, 0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xffffff, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f] } RdYlBu: { RdYlBu3 : [0x91bfdb, 0xffffbf, 0xfc8d59] RdYlBu4 : [0x2c7bb6, 0xabd9e9, 0xfdae61, 0xd7191c] RdYlBu5 : [0x2c7bb6, 0xabd9e9, 0xffffbf, 0xfdae61, 0xd7191c] RdYlBu6 : [0x4575b4, 0x91bfdb, 0xe0f3f8, 0xfee090, 0xfc8d59, 0xd73027] RdYlBu7 : [0x4575b4, 0x91bfdb, 0xe0f3f8, 0xffffbf, 0xfee090, 0xfc8d59, 0xd73027] RdYlBu8 : [0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027] RdYlBu9 : [0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xffffbf, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027] RdYlBu10 : [0x313695, 0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026] RdYlBu11 : [0x313695, 0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xffffbf, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026] } Spectral: { Spectral3 : [0x99d594, 0xffffbf, 0xfc8d59] Spectral4 : [0x2b83ba, 0xabdda4, 0xfdae61, 0xd7191c] Spectral5 : [0x2b83ba, 0xabdda4, 0xffffbf, 0xfdae61, 0xd7191c] Spectral6 : [0x3288bd, 0x99d594, 0xe6f598, 0xfee08b, 0xfc8d59, 0xd53e4f] Spectral7 : [0x3288bd, 0x99d594, 0xe6f598, 0xffffbf, 0xfee08b, 0xfc8d59, 0xd53e4f] Spectral8 : [0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f] Spectral9 : [0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f] Spectral10 : [0x5e4fa2, 0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f, 0x9e0142] Spectral11 : [0x5e4fa2, 0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f, 0x9e0142] } RdYlGn: { RdYlGn3 : [0x91cf60, 0xffffbf, 0xfc8d59] RdYlGn4 : [0x1a9641, 0xa6d96a, 0xfdae61, 0xd7191c] RdYlGn5 : [0x1a9641, 0xa6d96a, 0xffffbf, 0xfdae61, 0xd7191c] RdYlGn6 : [0x1a9850, 0x91cf60, 0xd9ef8b, 0xfee08b, 0xfc8d59, 0xd73027] RdYlGn7 : [0x1a9850, 0x91cf60, 0xd9ef8b, 0xffffbf, 0xfee08b, 0xfc8d59, 0xd73027] RdYlGn8 : [0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027] RdYlGn9 : [0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027] RdYlGn10 : [0x006837, 0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026] RdYlGn11 : [0x006837, 0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026] } Inferno: { Inferno3 : [0x440154, 0x208f8c, 0xfde724] Inferno4 : [0x000003, 0x781c6d, 0xed6825, 0xfcfea4] Inferno5 : [0x000003, 0x550f6d, 0xba3655, 0xf98c09, 0xfcfea4] Inferno6 : [0x000003, 0x410967, 0x932567, 0xdc5039, 0xfba40a, 0xfcfea4] Inferno7 : [0x000003, 0x32095d, 0x781c6d, 0xba3655, 0xed6825, 0xfbb318, 0xfcfea4] Inferno8 : [0x000003, 0x270b52, 0x63146e, 0x9e2963, 0xd24742, 0xf57c15, 0xfabf25, 0xfcfea4] Inferno9 : [0x000003, 0x1f0c47, 0x550f6d, 0x88216a, 0xba3655, 0xe35832, 0xf98c09, 0xf8c931, 0xfcfea4] Inferno10 : [0x000003, 0x1a0b40, 0x4a0b6a, 0x781c6d, 0xa42c60, 0xcd4247, 0xed6825, 0xfb9906, 0xf7cf3a, 0xfcfea4] Inferno11 : [0x000003, 0x160b39, 0x410967, 0x6a176e, 0x932567, 0xba3655, 0xdc5039, 0xf2751a, 0xfba40a, 0xf6d542, 0xfcfea4] Inferno256 : [ 0x000003, 0x000004, 0x000006, 0x010007, 0x010109, 0x01010b, 0x02010e, 0x020210, 0x030212, 0x040314, 0x040316, 0x050418, 0x06041b, 0x07051d, 0x08061f, 0x090621, 0x0a0723, 0x0b0726, 0x0d0828, 0x0e082a, 0x0f092d, 0x10092f, 0x120a32, 0x130a34, 0x140b36, 0x160b39, 0x170b3b, 0x190b3e, 0x1a0b40, 0x1c0c43, 0x1d0c45, 0x1f0c47, 0x200c4a, 0x220b4c, 0x240b4e, 0x260b50, 0x270b52, 0x290b54, 0x2b0a56, 0x2d0a58, 0x2e0a5a, 0x300a5c, 0x32095d, 0x34095f, 0x350960, 0x370961, 0x390962, 0x3b0964, 0x3c0965, 0x3e0966, 0x400966, 0x410967, 0x430a68, 0x450a69, 0x460a69, 0x480b6a, 0x4a0b6a, 0x4b0c6b, 0x4d0c6b, 0x4f0d6c, 0x500d6c, 0x520e6c, 0x530e6d, 0x550f6d, 0x570f6d, 0x58106d, 0x5a116d, 0x5b116e, 0x5d126e, 0x5f126e, 0x60136e, 0x62146e, 0x63146e, 0x65156e, 0x66156e, 0x68166e, 0x6a176e, 0x6b176e, 0x6d186e, 0x6e186e, 0x70196e, 0x72196d, 0x731a6d, 0x751b6d, 0x761b6d, 0x781c6d, 0x7a1c6d, 0x7b1d6c, 0x7d1d6c, 0x7e1e6c, 0x801f6b, 0x811f6b, 0x83206b, 0x85206a, 0x86216a, 0x88216a, 0x892269, 0x8b2269, 0x8d2369, 0x8e2468, 0x902468, 0x912567, 0x932567, 0x952666, 0x962666, 0x982765, 0x992864, 0x9b2864, 0x9c2963, 0x9e2963, 0xa02a62, 0xa12b61, 0xa32b61, 0xa42c60, 0xa62c5f, 0xa72d5f, 0xa92e5e, 0xab2e5d, 0xac2f5c, 0xae305b, 0xaf315b, 0xb1315a, 0xb23259, 0xb43358, 0xb53357, 0xb73456, 0xb83556, 0xba3655, 0xbb3754, 0xbd3753, 0xbe3852, 0xbf3951, 0xc13a50, 0xc23b4f, 0xc43c4e, 0xc53d4d, 0xc73e4c, 0xc83e4b, 0xc93f4a, 0xcb4049, 0xcc4148, 0xcd4247, 0xcf4446, 0xd04544, 0xd14643, 0xd24742, 0xd44841, 0xd54940, 0xd64a3f, 0xd74b3e, 0xd94d3d, 0xda4e3b, 0xdb4f3a, 0xdc5039, 0xdd5238, 0xde5337, 0xdf5436, 0xe05634, 0xe25733, 0xe35832, 0xe45a31, 0xe55b30, 0xe65c2e, 0xe65e2d, 0xe75f2c, 0xe8612b, 0xe9622a, 0xea6428, 0xeb6527, 0xec6726, 0xed6825, 0xed6a23, 0xee6c22, 0xef6d21, 0xf06f1f, 0xf0701e, 0xf1721d, 0xf2741c, 0xf2751a, 0xf37719, 0xf37918, 0xf47a16, 0xf57c15, 0xf57e14, 0xf68012, 0xf68111, 0xf78310, 0xf7850e, 0xf8870d, 0xf8880c, 0xf88a0b, 0xf98c09, 0xf98e08, 0xf99008, 0xfa9107, 0xfa9306, 0xfa9506, 0xfa9706, 0xfb9906, 0xfb9b06, 0xfb9d06, 0xfb9e07, 0xfba007, 0xfba208, 0xfba40a, 0xfba60b, 0xfba80d, 0xfbaa0e, 0xfbac10, 0xfbae12, 0xfbb014, 0xfbb116, 0xfbb318, 0xfbb51a, 0xfbb71c, 0xfbb91e, 0xfabb21, 0xfabd23, 0xfabf25, 0xfac128, 0xf9c32a, 0xf9c52c, 0xf9c72f, 0xf8c931, 0xf8cb34, 0xf8cd37, 0xf7cf3a, 0xf7d13c, 0xf6d33f, 0xf6d542, 0xf5d745, 0xf5d948, 0xf4db4b, 0xf4dc4f, 0xf3de52, 0xf3e056, 0xf3e259, 0xf2e45d, 0xf2e660, 0xf1e864, 0xf1e968, 0xf1eb6c, 0xf1ed70, 0xf1ee74, 0xf1f079, 0xf1f27d, 0xf2f381, 0xf2f485, 0xf3f689, 0xf4f78d, 0xf5f891, 0xf6fa95, 0xf7fb99, 0xf9fc9d, 0xfafda0, 0xfcfea4] } Magma: { Magma3 : [0x000003, 0xb53679, 0xfbfcbf] Magma4 : [0x000003, 0x711f81, 0xf0605d, 0xfbfcbf] Magma5 : [0x000003, 0x4f117b, 0xb53679, 0xfb8660, 0xfbfcbf] Magma6 : [0x000003, 0x3b0f6f, 0x8c2980, 0xdd4968, 0xfd9f6c, 0xfbfcbf] Magma7 : [0x000003, 0x2b115e, 0x711f81, 0xb53679, 0xf0605d, 0xfeae76, 0xfbfcbf] Magma8 : [0x000003, 0x221150, 0x5d177e, 0x972c7f, 0xd1426e, 0xf8755c, 0xfeb97f, 0xfbfcbf] Magma9 : [0x000003, 0x1b1044, 0x4f117b, 0x812581, 0xb53679, 0xe55063, 0xfb8660, 0xfec286, 0xfbfcbf] Magma10 : [0x000003, 0x170f3c, 0x430f75, 0x711f81, 0x9e2e7e, 0xcb3e71, 0xf0605d, 0xfc9366, 0xfec78b, 0xfbfcbf] Magma11 : [0x000003, 0x140d35, 0x3b0f6f, 0x63197f, 0x8c2980, 0xb53679, 0xdd4968, 0xf66e5b, 0xfd9f6c, 0xfdcd90, 0xfbfcbf] Magma256 : [ 0x000003, 0x000004, 0x000006, 0x010007, 0x010109, 0x01010b, 0x02020d, 0x02020f, 0x030311, 0x040313, 0x040415, 0x050417, 0x060519, 0x07051b, 0x08061d, 0x09071f, 0x0a0722, 0x0b0824, 0x0c0926, 0x0d0a28, 0x0e0a2a, 0x0f0b2c, 0x100c2f, 0x110c31, 0x120d33, 0x140d35, 0x150e38, 0x160e3a, 0x170f3c, 0x180f3f, 0x1a1041, 0x1b1044, 0x1c1046, 0x1e1049, 0x1f114b, 0x20114d, 0x221150, 0x231152, 0x251155, 0x261157, 0x281159, 0x2a115c, 0x2b115e, 0x2d1060, 0x2f1062, 0x301065, 0x321067, 0x341068, 0x350f6a, 0x370f6c, 0x390f6e, 0x3b0f6f, 0x3c0f71, 0x3e0f72, 0x400f73, 0x420f74, 0x430f75, 0x450f76, 0x470f77, 0x481078, 0x4a1079, 0x4b1079, 0x4d117a, 0x4f117b, 0x50127b, 0x52127c, 0x53137c, 0x55137d, 0x57147d, 0x58157e, 0x5a157e, 0x5b167e, 0x5d177e, 0x5e177f, 0x60187f, 0x61187f, 0x63197f, 0x651a80, 0x661a80, 0x681b80, 0x691c80, 0x6b1c80, 0x6c1d80, 0x6e1e81, 0x6f1e81, 0x711f81, 0x731f81, 0x742081, 0x762181, 0x772181, 0x792281, 0x7a2281, 0x7c2381, 0x7e2481, 0x7f2481, 0x812581, 0x822581, 0x842681, 0x852681, 0x872781, 0x892881, 0x8a2881, 0x8c2980, 0x8d2980, 0x8f2a80, 0x912a80, 0x922b80, 0x942b80, 0x952c80, 0x972c7f, 0x992d7f, 0x9a2d7f, 0x9c2e7f, 0x9e2e7e, 0x9f2f7e, 0xa12f7e, 0xa3307e, 0xa4307d, 0xa6317d, 0xa7317d, 0xa9327c, 0xab337c, 0xac337b, 0xae347b, 0xb0347b, 0xb1357a, 0xb3357a, 0xb53679, 0xb63679, 0xb83778, 0xb93778, 0xbb3877, 0xbd3977, 0xbe3976, 0xc03a75, 0xc23a75, 0xc33b74, 0xc53c74, 0xc63c73, 0xc83d72, 0xca3e72, 0xcb3e71, 0xcd3f70, 0xce4070, 0xd0416f, 0xd1426e, 0xd3426d, 0xd4436d, 0xd6446c, 0xd7456b, 0xd9466a, 0xda4769, 0xdc4869, 0xdd4968, 0xde4a67, 0xe04b66, 0xe14c66, 0xe24d65, 0xe44e64, 0xe55063, 0xe65162, 0xe75262, 0xe85461, 0xea5560, 0xeb5660, 0xec585f, 0xed595f, 0xee5b5e, 0xee5d5d, 0xef5e5d, 0xf0605d, 0xf1615c, 0xf2635c, 0xf3655c, 0xf3675b, 0xf4685b, 0xf56a5b, 0xf56c5b, 0xf66e5b, 0xf6705b, 0xf7715b, 0xf7735c, 0xf8755c, 0xf8775c, 0xf9795c, 0xf97b5d, 0xf97d5d, 0xfa7f5e, 0xfa805e, 0xfa825f, 0xfb8460, 0xfb8660, 0xfb8861, 0xfb8a62, 0xfc8c63, 0xfc8e63, 0xfc9064, 0xfc9265, 0xfc9366, 0xfd9567, 0xfd9768, 0xfd9969, 0xfd9b6a, 0xfd9d6b, 0xfd9f6c, 0xfda16e, 0xfda26f, 0xfda470, 0xfea671, 0xfea873, 0xfeaa74, 0xfeac75, 0xfeae76, 0xfeaf78, 0xfeb179, 0xfeb37b, 0xfeb57c, 0xfeb77d, 0xfeb97f, 0xfebb80, 0xfebc82, 0xfebe83, 0xfec085, 0xfec286, 0xfec488, 0xfec689, 0xfec78b, 0xfec98d, 0xfecb8e, 0xfdcd90, 0xfdcf92, 0xfdd193, 0xfdd295, 0xfdd497, 0xfdd698, 0xfdd89a, 0xfdda9c, 0xfddc9d, 0xfddd9f, 0xfddfa1, 0xfde1a3, 0xfce3a5, 0xfce5a6, 0xfce6a8, 0xfce8aa, 0xfceaac, 0xfcecae, 0xfceeb0, 0xfcf0b1, 0xfcf1b3, 0xfcf3b5, 0xfcf5b7, 0xfbf7b9, 0xfbf9bb, 0xfbfabd, 0xfbfcbf] } Plasma: { Plasma3 : [0x0c0786, 0xca4678, 0xeff821] Plasma4 : [0x0c0786, 0x9b179e, 0xec7853, 0xeff821] Plasma5 : [0x0c0786, 0x7c02a7, 0xca4678, 0xf79341, 0xeff821] Plasma6 : [0x0c0786, 0x6a00a7, 0xb02a8f, 0xe06461, 0xfca635, 0xeff821] Plasma7 : [0x0c0786, 0x5c00a5, 0x9b179e, 0xca4678, 0xec7853, 0xfdb22f, 0xeff821] Plasma8 : [0x0c0786, 0x5201a3, 0x8908a5, 0xb83289, 0xda5a68, 0xf38748, 0xfdbb2b, 0xeff821] Plasma9 : [0x0c0786, 0x4a02a0, 0x7c02a7, 0xa82296, 0xca4678, 0xe56b5c, 0xf79341, 0xfdc328, 0xeff821] Plasma10 : [0x0c0786, 0x45039e, 0x7200a8, 0x9b179e, 0xbc3685, 0xd7566c, 0xec7853, 0xfa9d3a, 0xfcc726, 0xeff821] Plasma11 : [0x0c0786, 0x40039c, 0x6a00a7, 0x8f0da3, 0xb02a8f, 0xca4678, 0xe06461, 0xf1824c, 0xfca635, 0xfccc25, 0xeff821] Plasma256 : [ 0x0c0786, 0x100787, 0x130689, 0x15068a, 0x18068b, 0x1b068c, 0x1d068d, 0x1f058e, 0x21058f, 0x230590, 0x250591, 0x270592, 0x290593, 0x2b0594, 0x2d0494, 0x2f0495, 0x310496, 0x330497, 0x340498, 0x360498, 0x380499, 0x3a049a, 0x3b039a, 0x3d039b, 0x3f039c, 0x40039c, 0x42039d, 0x44039e, 0x45039e, 0x47029f, 0x49029f, 0x4a02a0, 0x4c02a1, 0x4e02a1, 0x4f02a2, 0x5101a2, 0x5201a3, 0x5401a3, 0x5601a3, 0x5701a4, 0x5901a4, 0x5a00a5, 0x5c00a5, 0x5e00a5, 0x5f00a6, 0x6100a6, 0x6200a6, 0x6400a7, 0x6500a7, 0x6700a7, 0x6800a7, 0x6a00a7, 0x6c00a8, 0x6d00a8, 0x6f00a8, 0x7000a8, 0x7200a8, 0x7300a8, 0x7500a8, 0x7601a8, 0x7801a8, 0x7901a8, 0x7b02a8, 0x7c02a7, 0x7e03a7, 0x7f03a7, 0x8104a7, 0x8204a7, 0x8405a6, 0x8506a6, 0x8607a6, 0x8807a5, 0x8908a5, 0x8b09a4, 0x8c0aa4, 0x8e0ca4, 0x8f0da3, 0x900ea3, 0x920fa2, 0x9310a1, 0x9511a1, 0x9612a0, 0x9713a0, 0x99149f, 0x9a159e, 0x9b179e, 0x9d189d, 0x9e199c, 0x9f1a9b, 0xa01b9b, 0xa21c9a, 0xa31d99, 0xa41e98, 0xa51f97, 0xa72197, 0xa82296, 0xa92395, 0xaa2494, 0xac2593, 0xad2692, 0xae2791, 0xaf2890, 0xb02a8f, 0xb12b8f, 0xb22c8e, 0xb42d8d, 0xb52e8c, 0xb62f8b, 0xb7308a, 0xb83289, 0xb93388, 0xba3487, 0xbb3586, 0xbc3685, 0xbd3784, 0xbe3883, 0xbf3982, 0xc03b81, 0xc13c80, 0xc23d80, 0xc33e7f, 0xc43f7e, 0xc5407d, 0xc6417c, 0xc7427b, 0xc8447a, 0xc94579, 0xca4678, 0xcb4777, 0xcc4876, 0xcd4975, 0xce4a75, 0xcf4b74, 0xd04d73, 0xd14e72, 0xd14f71, 0xd25070, 0xd3516f, 0xd4526e, 0xd5536d, 0xd6556d, 0xd7566c, 0xd7576b, 0xd8586a, 0xd95969, 0xda5a68, 0xdb5b67, 0xdc5d66, 0xdc5e66, 0xdd5f65, 0xde6064, 0xdf6163, 0xdf6262, 0xe06461, 0xe16560, 0xe26660, 0xe3675f, 0xe3685e, 0xe46a5d, 0xe56b5c, 0xe56c5b, 0xe66d5a, 0xe76e5a, 0xe87059, 0xe87158, 0xe97257, 0xea7356, 0xea7455, 0xeb7654, 0xec7754, 0xec7853, 0xed7952, 0xed7b51, 0xee7c50, 0xef7d4f, 0xef7e4e, 0xf0804d, 0xf0814d, 0xf1824c, 0xf2844b, 0xf2854a, 0xf38649, 0xf38748, 0xf48947, 0xf48a47, 0xf58b46, 0xf58d45, 0xf68e44, 0xf68f43, 0xf69142, 0xf79241, 0xf79341, 0xf89540, 0xf8963f, 0xf8983e, 0xf9993d, 0xf99a3c, 0xfa9c3b, 0xfa9d3a, 0xfa9f3a, 0xfaa039, 0xfba238, 0xfba337, 0xfba436, 0xfca635, 0xfca735, 0xfca934, 0xfcaa33, 0xfcac32, 0xfcad31, 0xfdaf31, 0xfdb030, 0xfdb22f, 0xfdb32e, 0xfdb52d, 0xfdb62d, 0xfdb82c, 0xfdb92b, 0xfdbb2b, 0xfdbc2a, 0xfdbe29, 0xfdc029, 0xfdc128, 0xfdc328, 0xfdc427, 0xfdc626, 0xfcc726, 0xfcc926, 0xfccb25, 0xfccc25, 0xfcce25, 0xfbd024, 0xfbd124, 0xfbd324, 0xfad524, 0xfad624, 0xfad824, 0xf9d924, 0xf9db24, 0xf8dd24, 0xf8df24, 0xf7e024, 0xf7e225, 0xf6e425, 0xf6e525, 0xf5e726, 0xf5e926, 0xf4ea26, 0xf3ec26, 0xf3ee26, 0xf2f026, 0xf2f126, 0xf1f326, 0xf0f525, 0xf0f623, 0xeff821] } Viridis: { Viridis3 : [0x440154, 0x208f8c, 0xfde724] Viridis4 : [0x440154, 0x30678d, 0x35b778, 0xfde724] Viridis5 : [0x440154, 0x3b518a, 0x208f8c, 0x5bc862, 0xfde724] Viridis6 : [0x440154, 0x404387, 0x29788e, 0x22a784, 0x79d151, 0xfde724] Viridis7 : [0x440154, 0x443982, 0x30678d, 0x208f8c, 0x35b778, 0x8dd644, 0xfde724] Viridis8 : [0x440154, 0x46317e, 0x365a8c, 0x277e8e, 0x1ea087, 0x49c16d, 0x9dd93a, 0xfde724] Viridis9 : [0x440154, 0x472b7a, 0x3b518a, 0x2c718e, 0x208f8c, 0x27ad80, 0x5bc862, 0xaadb32, 0xfde724] Viridis10 : [0x440154, 0x472777, 0x3e4989, 0x30678d, 0x25828e, 0x1e9c89, 0x35b778, 0x6bcd59, 0xb2dd2c, 0xfde724] Viridis11 : [0x440154, 0x482374, 0x404387, 0x345e8d, 0x29788e, 0x208f8c, 0x22a784, 0x42be71, 0x79d151, 0xbade27, 0xfde724] Viridis256 : [ 0x440154, 0x440255, 0x440357, 0x450558, 0x45065a, 0x45085b, 0x46095c, 0x460b5e, 0x460c5f, 0x460e61, 0x470f62, 0x471163, 0x471265, 0x471466, 0x471567, 0x471669, 0x47186a, 0x48196b, 0x481a6c, 0x481c6e, 0x481d6f, 0x481e70, 0x482071, 0x482172, 0x482273, 0x482374, 0x472575, 0x472676, 0x472777, 0x472878, 0x472a79, 0x472b7a, 0x472c7b, 0x462d7c, 0x462f7c, 0x46307d, 0x46317e, 0x45327f, 0x45347f, 0x453580, 0x453681, 0x443781, 0x443982, 0x433a83, 0x433b83, 0x433c84, 0x423d84, 0x423e85, 0x424085, 0x414186, 0x414286, 0x404387, 0x404487, 0x3f4587, 0x3f4788, 0x3e4888, 0x3e4989, 0x3d4a89, 0x3d4b89, 0x3d4c89, 0x3c4d8a, 0x3c4e8a, 0x3b508a, 0x3b518a, 0x3a528b, 0x3a538b, 0x39548b, 0x39558b, 0x38568b, 0x38578c, 0x37588c, 0x37598c, 0x365a8c, 0x365b8c, 0x355c8c, 0x355d8c, 0x345e8d, 0x345f8d, 0x33608d, 0x33618d, 0x32628d, 0x32638d, 0x31648d, 0x31658d, 0x31668d, 0x30678d, 0x30688d, 0x2f698d, 0x2f6a8d, 0x2e6b8e, 0x2e6c8e, 0x2e6d8e, 0x2d6e8e, 0x2d6f8e, 0x2c708e, 0x2c718e, 0x2c728e, 0x2b738e, 0x2b748e, 0x2a758e, 0x2a768e, 0x2a778e, 0x29788e, 0x29798e, 0x287a8e, 0x287a8e, 0x287b8e, 0x277c8e, 0x277d8e, 0x277e8e, 0x267f8e, 0x26808e, 0x26818e, 0x25828e, 0x25838d, 0x24848d, 0x24858d, 0x24868d, 0x23878d, 0x23888d, 0x23898d, 0x22898d, 0x228a8d, 0x228b8d, 0x218c8d, 0x218d8c, 0x218e8c, 0x208f8c, 0x20908c, 0x20918c, 0x1f928c, 0x1f938b, 0x1f948b, 0x1f958b, 0x1f968b, 0x1e978a, 0x1e988a, 0x1e998a, 0x1e998a, 0x1e9a89, 0x1e9b89, 0x1e9c89, 0x1e9d88, 0x1e9e88, 0x1e9f88, 0x1ea087, 0x1fa187, 0x1fa286, 0x1fa386, 0x20a485, 0x20a585, 0x21a685, 0x21a784, 0x22a784, 0x23a883, 0x23a982, 0x24aa82, 0x25ab81, 0x26ac81, 0x27ad80, 0x28ae7f, 0x29af7f, 0x2ab07e, 0x2bb17d, 0x2cb17d, 0x2eb27c, 0x2fb37b, 0x30b47a, 0x32b57a, 0x33b679, 0x35b778, 0x36b877, 0x38b976, 0x39b976, 0x3bba75, 0x3dbb74, 0x3ebc73, 0x40bd72, 0x42be71, 0x44be70, 0x45bf6f, 0x47c06e, 0x49c16d, 0x4bc26c, 0x4dc26b, 0x4fc369, 0x51c468, 0x53c567, 0x55c666, 0x57c665, 0x59c764, 0x5bc862, 0x5ec961, 0x60c960, 0x62ca5f, 0x64cb5d, 0x67cc5c, 0x69cc5b, 0x6bcd59, 0x6dce58, 0x70ce56, 0x72cf55, 0x74d054, 0x77d052, 0x79d151, 0x7cd24f, 0x7ed24e, 0x81d34c, 0x83d34b, 0x86d449, 0x88d547, 0x8bd546, 0x8dd644, 0x90d643, 0x92d741, 0x95d73f, 0x97d83e, 0x9ad83c, 0x9dd93a, 0x9fd938, 0xa2da37, 0xa5da35, 0xa7db33, 0xaadb32, 0xaddc30, 0xafdc2e, 0xb2dd2c, 0xb5dd2b, 0xb7dd29, 0xbade27, 0xbdde26, 0xbfdf24, 0xc2df22, 0xc5df21, 0xc7e01f, 0xcae01e, 0xcde01d, 0xcfe11c, 0xd2e11b, 0xd4e11a, 0xd7e219, 0xdae218, 0xdce218, 0xdfe318, 0xe1e318, 0xe4e318, 0xe7e419, 0xe9e419, 0xece41a, 0xeee51b, 0xf1e51c, 0xf3e51e, 0xf6e61f, 0xf8e621, 0xfae622, 0xfde724] } Accent: { Accent3 : [0x7fc97f, 0xbeaed4, 0xfdc086] Accent4 : [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99] Accent5 : [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0] Accent6 : [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0, 0xf0027f] Accent7 : [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0, 0xf0027f, 0xbf5b17] Accent8 : [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0, 0xf0027f, 0xbf5b17, 0x666666] } Dark2: { Dark2_3 : [0x1b9e77, 0xd95f02, 0x7570b3] Dark2_4 : [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a] Dark2_5 : [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e] Dark2_6 : [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02] Dark2_7 : [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02, 0xa6761d] Dark2_8 : [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02, 0xa6761d, 0x666666] } Paired: { Paired3 : [0xa6cee3, 0x1f78b4, 0xb2df8a] Paired4 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c] Paired5 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99] Paired6 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c] Paired7 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f] Paired8 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00] Paired9 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6] Paired10 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6, 0x6a3d9a] Paired11 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6, 0x6a3d9a, 0xffff99] Paired12 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6, 0x6a3d9a, 0xffff99, 0xb15928] } Pastel1: { Pastel1_3 : [0xfbb4ae, 0xb3cde3, 0xccebc5] Pastel1_4 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4] Pastel1_5 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6] Pastel1_6 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc] Pastel1_7 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc, 0xe5d8bd] Pastel1_8 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc, 0xe5d8bd, 0xfddaec] Pastel1_9 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc, 0xe5d8bd, 0xfddaec, 0xf2f2f2] } Pastel2: { Pastel2_3 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8] Pastel2_4 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4] Pastel2_5 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9] Pastel2_6 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9, 0xfff2ae] Pastel2_7 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9, 0xfff2ae, 0xf1e2cc] Pastel2_8 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9, 0xfff2ae, 0xf1e2cc, 0xcccccc] } Set1: { Set1_3 : [0xe41a1c, 0x377eb8, 0x4daf4a] Set1_4 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3] Set1_5 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00] Set1_6 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33] Set1_7 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628] Set1_8 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628, 0xf781bf] Set1_9 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628, 0xf781bf, 0x999999] } Set2: { Set2_3 : [0x66c2a5, 0xfc8d62, 0x8da0cb] Set2_4 : [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3] Set2_5 : [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854] Set2_6 : [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f] Set2_7 : [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f, 0xe5c494] Set2_8 : [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f, 0xe5c494, 0xb3b3b3] } Set3: { Set3_3 : [0x8dd3c7, 0xffffb3, 0xbebada] Set3_4 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072] Set3_5 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3] Set3_6 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462] Set3_7 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69] Set3_8 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5] Set3_9 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9] Set3_10 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9, 0xbc80bd] Set3_11 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9, 0xbc80bd, 0xccebc5] Set3_12 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9, 0xbc80bd, 0xccebc5, 0xffed6f] } } ### License regarding the Viridis, Magma, Plasma and Inferno color maps ### # New matplotlib colormaps by Nathaniel J. Smith, Stefan van der Walt, # and (in the case of viridis) Eric Firing. # # This file and the colormaps in it are released under the CC0 license / # public domain dedication. We would appreciate credit if you use or # redistribute these colormaps, but do not impose any legal restrictions. # # To the extent possible under law, the persons who associated CC0 with # mpl-colormaps have waived all copyright and related or neighboring rights # to mpl-colormaps. # # You should have received a copy of the CC0 legalcode along with this # work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. module.exports = _.extend({}, palettes, palettes.YlGn, palettes.YlGnBu, palettes.GnBu, palettes.BuGn, palettes.PuBuGn, palettes.PuBu, palettes.BuPu, palettes.RdPu, palettes.PuRd, palettes.OrRd, palettes.YlOrRd, palettes.YlOrBr, palettes.Purples, palettes.Blues, palettes.Greens, palettes.Oranges, palettes.Reds, palettes.Greys, palettes.PuOr, palettes.BrBG, palettes.PRGn, palettes.PiYG, palettes.RdBu, palettes.RdGy, palettes.RdYlBu, palettes.Spectral, palettes.RdYlGn, palettes.Inferno, palettes.Magma, palettes.Plasma, palettes.Viridis)
78153
_ = require("underscore") palettes = { YlGn: { YlGn3 : [0x31a354, 0xaddd8e, 0xf7fcb9] YlGn4 : [0x238443, 0x78c679, 0xc2e699, 0xffffcc] YlGn5 : [0x006837, 0x31a354, 0x78c679, 0xc2e699, 0xffffcc] YlGn6 : [0x006837, 0x31a354, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xffffcc] YlGn7 : [0x005a32, 0x238443, 0x41ab5d, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xffffcc] YlGn8 : [0x005a32, 0x238443, 0x41ab5d, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xf7fcb9, 0xffffe5] YlGn9 : [0x004529, 0x006837, 0x238443, 0x41ab5d, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xf7fcb9, 0xffffe5] } YlGnBu: { YlGnBu3 : [0x2c7fb8, 0x7fcdbb, 0xedf8b1] YlGnBu4 : [0x225ea8, 0x41b6c4, 0xa1dab4, 0xffffcc] YlGnBu5 : [0x253494, 0x2c7fb8, 0x41b6c4, 0xa1dab4, 0xffffcc] YlGnBu6 : [0x253494, 0x2c7fb8, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xffffcc] YlGnBu7 : [0x0c2c84, 0x225ea8, 0x1d91c0, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xffffcc] YlGnBu8 : [0x0c2c84, 0x225ea8, 0x1d91c0, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xedf8b1, 0xffffd9] YlGnBu9 : [0x081d58, 0x253494, 0x225ea8, 0x1d91c0, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xedf8b1, 0xffffd9] } GnBu: { GnBu3 : [0x43a2ca, 0xa8ddb5, 0xe0f3db] GnBu4 : [0x2b8cbe, 0x7bccc4, 0xbae4bc, 0xf0f9e8] GnBu5 : [0x0868ac, 0x43a2ca, 0x7bccc4, 0xbae4bc, 0xf0f9e8] GnBu6 : [0x0868ac, 0x43a2ca, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xf0f9e8] GnBu7 : [0x08589e, 0x2b8cbe, 0x4eb3d3, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xf0f9e8] GnBu8 : [0x08589e, 0x2b8cbe, 0x4eb3d3, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xe0f3db, 0xf7fcf0] GnBu9 : [0x084081, 0x0868ac, 0x2b8cbe, 0x4eb3d3, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xe0f3db, 0xf7fcf0] } BuGn: { BuGn3 : [0x2ca25f, 0x99d8c9, 0xe5f5f9] BuGn4 : [0x238b45, 0x66c2a4, 0xb2e2e2, 0xedf8fb] BuGn5 : [0x006d2c, 0x2ca25f, 0x66c2a4, 0xb2e2e2, 0xedf8fb] BuGn6 : [0x006d2c, 0x2ca25f, 0x66c2a4, 0x99d8c9, 0xccece6, 0xedf8fb] BuGn7 : [0x005824, 0x238b45, 0x41ae76, 0x66c2a4, 0x99d8c9, 0xccece6, 0xedf8fb] BuGn8 : [0x005824, 0x238b45, 0x41ae76, 0x66c2a4, 0x99d8c9, 0xccece6, 0xe5f5f9, 0xf7fcfd] BuGn9 : [0x00441b, 0x006d2c, 0x238b45, 0x41ae76, 0x66c2a4, 0x99d8c9, 0xccece6, 0xe5f5f9, 0xf7fcfd] } PuBuGn: { PuBuGn3 : [0x1c9099, 0xa6bddb, 0xece2f0] PuBuGn4 : [0x02818a, 0x67a9cf, 0xbdc9e1, 0xf6eff7] PuBuGn5 : [0x016c59, 0x1c9099, 0x67a9cf, 0xbdc9e1, 0xf6eff7] PuBuGn6 : [0x016c59, 0x1c9099, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xf6eff7] PuBuGn7 : [0x016450, 0x02818a, 0x3690c0, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xf6eff7] PuBuGn8 : [0x016450, 0x02818a, 0x3690c0, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xece2f0, 0xfff7fb] PuBuGn9 : [0x014636, 0x016c59, 0x02818a, 0x3690c0, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xece2f0, 0xfff7fb] } PuBu: { PuBu3 : [0x2b8cbe, 0xa6bddb, 0xece7f2] PuBu4 : [0x0570b0, 0x74a9cf, 0xbdc9e1, 0xf1eef6] PuBu5 : [0x045a8d, 0x2b8cbe, 0x74a9cf, 0xbdc9e1, 0xf1eef6] PuBu6 : [0x045a8d, 0x2b8cbe, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xf1eef6] PuBu7 : [0x034e7b, 0x0570b0, 0x3690c0, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xf1eef6] PuBu8 : [0x034e7b, 0x0570b0, 0x3690c0, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xece7f2, 0xfff7fb] PuBu9 : [0x023858, 0x045a8d, 0x0570b0, 0x3690c0, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xece7f2, 0xfff7fb] } BuPu: { BuPu3 : [0x8856a7, 0x9ebcda, 0xe0ecf4] BuPu4 : [0x88419d, 0x8c96c6, 0xb3cde3, 0xedf8fb] BuPu5 : [0x810f7c, 0x8856a7, 0x8c96c6, 0xb3cde3, 0xedf8fb] BuPu6 : [0x810f7c, 0x8856a7, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xedf8fb] BuPu7 : [0x6e016b, 0x88419d, 0x8c6bb1, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xedf8fb] BuPu8 : [0x6e016b, 0x88419d, 0x8c6bb1, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xe0ecf4, 0xf7fcfd] BuPu9 : [0x4d004b, 0x810f7c, 0x88419d, 0x8c6bb1, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xe0ecf4, 0xf7fcfd] } RdPu: { RdPu3 : [0xc51b8a, 0xfa9fb5, 0xfde0dd] RdPu4 : [0xae017e, 0xf768a1, 0xfbb4b9, 0xfeebe2] RdPu5 : [0x7a0177, 0xc51b8a, 0xf768a1, 0xfbb4b9, 0xfeebe2] RdPu6 : [0x7a0177, 0xc51b8a, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfeebe2] RdPu7 : [0x7a0177, 0xae017e, 0xdd3497, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfeebe2] RdPu8 : [0x7a0177, 0xae017e, 0xdd3497, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfde0dd, 0xfff7f3] RdPu9 : [0x49006a, 0x7a0177, 0xae017e, 0xdd3497, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfde0dd, 0xfff7f3] } PuRd: { PuRd3 : [0xdd1c77, 0xc994c7, 0xe7e1ef] PuRd4 : [0xce1256, 0xdf65b0, 0xd7b5d8, 0xf1eef6] PuRd5 : [0x980043, 0xdd1c77, 0xdf65b0, 0xd7b5d8, 0xf1eef6] PuRd6 : [0x980043, 0xdd1c77, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xf1eef6] PuRd7 : [0x91003f, 0xce1256, 0xe7298a, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xf1eef6] PuRd8 : [0x91003f, 0xce1256, 0xe7298a, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xe7e1ef, 0xf7f4f9] PuRd9 : [0x67001f, 0x980043, 0xce1256, 0xe7298a, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xe7e1ef, 0xf7f4f9] } OrRd: { OrRd3 : [0xe34a33, 0xfdbb84, 0xfee8c8] OrRd4 : [0xd7301f, 0xfc8d59, 0xfdcc8a, 0xfef0d9] OrRd5 : [0xb30000, 0xe34a33, 0xfc8d59, 0xfdcc8a, 0xfef0d9] OrRd6 : [0xb30000, 0xe34a33, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfef0d9] OrRd7 : [0x990000, 0xd7301f, 0xef6548, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfef0d9] OrRd8 : [0x990000, 0xd7301f, 0xef6548, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfee8c8, 0xfff7ec] OrRd9 : [0x7f0000, 0xb30000, 0xd7301f, 0xef6548, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfee8c8, 0xfff7ec] } YlOrRd: { YlOrRd3 : [0xf03b20, 0xfeb24c, 0xffeda0] YlOrRd4 : [0xe31a1c, 0xfd8d3c, 0xfecc5c, 0xffffb2] YlOrRd5 : [0xbd0026, 0xf03b20, 0xfd8d3c, 0xfecc5c, 0xffffb2] YlOrRd6 : [0xbd0026, 0xf03b20, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffffb2] YlOrRd7 : [0xb10026, 0xe31a1c, 0xfc4e2a, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffffb2] YlOrRd8 : [0xb10026, 0xe31a1c, 0xfc4e2a, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffeda0, 0xffffcc] YlOrRd9 : [0x800026, 0xbd0026, 0xe31a1c, 0xfc4e2a, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffeda0, 0xffffcc] } YlOrBr: { YlOrBr3 : [0xd95f0e, 0xfec44f, 0xfff7bc] YlOrBr4 : [0xcc4c02, 0xfe9929, 0xfed98e, 0xffffd4] YlOrBr5 : [0x993404, 0xd95f0e, 0xfe9929, 0xfed98e, 0xffffd4] YlOrBr6 : [0x993404, 0xd95f0e, 0xfe9929, 0xfec44f, 0xfee391, 0xffffd4] YlOrBr7 : [0x8c2d04, 0xcc4c02, 0xec7014, 0xfe9929, 0xfec44f, 0xfee391, 0xffffd4] YlOrBr8 : [0x8c2d04, 0xcc4c02, 0xec7014, 0xfe9929, 0xfec44f, 0xfee391, 0xfff7bc, 0xffffe5] YlOrBr9 : [0x662506, 0x993404, 0xcc4c02, 0xec7014, 0xfe9929, 0xfec44f, 0xfee391, 0xfff7bc, 0xffffe5] } Purples: { Purples3 : [0x756bb1, 0xbcbddc, 0xefedf5] Purples4 : [0x6a51a3, 0x9e9ac8, 0xcbc9e2, 0xf2f0f7] Purples5 : [0x54278f, 0x756bb1, 0x9e9ac8, 0xcbc9e2, 0xf2f0f7] Purples6 : [0x54278f, 0x756bb1, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xf2f0f7] Purples7 : [0x4a1486, 0x6a51a3, 0x807dba, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xf2f0f7] Purples8 : [0x4a1486, 0x6a51a3, 0x807dba, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xefedf5, 0xfcfbfd] Purples9 : [0x3f007d, 0x54278f, 0x6a51a3, 0x807dba, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xefedf5, 0xfcfbfd] } Blues: { Blues3 : [0x3182bd, 0x9ecae1, 0xdeebf7] Blues4 : [0x2171b5, 0x6baed6, 0xbdd7e7, 0xeff3ff] Blues5 : [0x08519c, 0x3182bd, 0x6baed6, 0xbdd7e7, 0xeff3ff] Blues6 : [0x08519c, 0x3182bd, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xeff3ff] Blues7 : [0x084594, 0x2171b5, 0x4292c6, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xeff3ff] Blues8 : [0x084594, 0x2171b5, 0x4292c6, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xdeebf7, 0xf7fbff] Blues9 : [0x08306b, 0x08519c, 0x2171b5, 0x4292c6, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xdeebf7, 0xf7fbff] } Greens: { Greens3 : [0x31a354, 0xa1d99b, 0xe5f5e0] Greens4 : [0x238b45, 0x74c476, 0xbae4b3, 0xedf8e9] Greens5 : [0x006d2c, 0x31a354, 0x74c476, 0xbae4b3, 0xedf8e9] Greens6 : [0x006d2c, 0x31a354, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xedf8e9] Greens7 : [0x005a32, 0x238b45, 0x41ab5d, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xedf8e9] Greens8 : [0x005a32, 0x238b45, 0x41ab5d, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xe5f5e0, 0xf7fcf5] Greens9 : [0x00441b, 0x006d2c, 0x238b45, 0x41ab5d, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xe5f5e0, 0xf7fcf5] } Oranges: { Oranges3 : [0xe6550d, 0xfdae6b, 0xfee6ce] Oranges4 : [0xd94701, 0xfd8d3c, 0xfdbe85, 0xfeedde] Oranges5 : [0xa63603, 0xe6550d, 0xfd8d3c, 0xfdbe85, 0xfeedde] Oranges6 : [0xa63603, 0xe6550d, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfeedde] Oranges7 : [0x8c2d04, 0xd94801, 0xf16913, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfeedde] Oranges8 : [0x8c2d04, 0xd94801, 0xf16913, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfee6ce, 0xfff5eb] Oranges9 : [0x7f2704, 0xa63603, 0xd94801, 0xf16913, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfee6ce, 0xfff5eb] } Reds: { Reds3 : [0xde2d26, 0xfc9272, 0xfee0d2] Reds4 : [0xcb181d, 0xfb6a4a, 0xfcae91, 0xfee5d9] Reds5 : [0xa50f15, 0xde2d26, 0xfb6a4a, 0xfcae91, 0xfee5d9] Reds6 : [0xa50f15, 0xde2d26, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee5d9] Reds7 : [0x99000d, 0xcb181d, 0xef3b2c, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee5d9] Reds8 : [0x99000d, 0xcb181d, 0xef3b2c, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee0d2, 0xfff5f0] Reds9 : [0x67000d, 0xa50f15, 0xcb181d, 0xef3b2c, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee0d2, 0xfff5f0] } Greys: { Greys3 : [0x636363, 0xbdbdbd, 0xf0f0f0] Greys4 : [0x525252, 0x969696, 0xcccccc, 0xf7f7f7] Greys5 : [0x252525, 0x636363, 0x969696, 0xcccccc, 0xf7f7f7] Greys6 : [0x252525, 0x636363, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf7f7f7] Greys7 : [0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf7f7f7] Greys8 : [0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf0f0f0, 0xffffff] Greys9 : [0x000000, 0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf0f0f0, 0xffffff] Greys10 : [0x000000, 0x1c1c1c, 0x383838, 0x555555, 0x717171, 0x8d8d8d, 0xaaaaaa, 0xc6c6c6, 0xe2e2e2, 0xffffff] Greys11 : [0x000000, 0x191919, 0x333333, 0x4c4c4c, 0x666666, 0x7f7f7f, 0x999999, 0xb2b2b2, 0xcccccc, 0xe5e5e5, 0xffffff] Greys256 : [ 0x000000, 0x010101, 0x020202, 0x030303, 0x040404, 0x050505, 0x060606, 0x070707, 0x080808, 0x090909, 0x0a0a0a, 0x0b0b0b, 0x0c0c0c, 0x0d0d0d, 0x0e0e0e, 0x0f0f0f, 0x101010, 0x111111, 0x121212, 0x131313, 0x141414, 0x151515, 0x161616, 0x171717, 0x181818, 0x191919, 0x1a1a1a, 0x1b1b1b, 0x1c1c1c, 0x1d1d1d, 0x1e1e1e, 0x1f1f1f, 0x202020, 0x212121, 0x222222, 0x232323, 0x242424, 0x252525, 0x262626, 0x272727, 0x282828, 0x292929, 0x2a2a2a, 0x2b2b2b, 0x2c2c2c, 0x2d2d2d, 0x2e2e2e, 0x2f2f2f, 0x303030, 0x313131, 0x323232, 0x333333, 0x343434, 0x353535, 0x363636, 0x373737, 0x383838, 0x393939, 0x3a3a3a, 0x3b3b3b, 0x3c3c3c, 0x3d3d3d, 0x3e3e3e, 0x3f3f3f, 0x404040, 0x414141, 0x424242, 0x434343, 0x444444, 0x454545, 0x464646, 0x474747, 0x484848, 0x494949, 0x4a4a4a, 0x4b4b4b, 0x4c4c4c, 0x4d4d4d, 0x4e4e4e, 0x4f4f4f, 0x505050, 0x515151, 0x525252, 0x535353, 0x545454, 0x555555, 0x565656, 0x575757, 0x585858, 0x595959, 0x5a5a5a, 0x5b5b5b, 0x5c5c5c, 0x5d5d5d, 0x5e5e5e, 0x5f5f5f, 0x606060, 0x616161, 0x626262, 0x636363, 0x646464, 0x656565, 0x666666, 0x676767, 0x686868, 0x696969, 0x6a6a6a, 0x6b6b6b, 0x6c6c6c, 0x6d6d6d, 0x6e6e6e, 0x6f6f6f, 0x707070, 0x717171, 0x727272, 0x737373, 0x747474, 0x757575, 0x767676, 0x777777, 0x787878, 0x797979, 0x7a7a7a, 0x7b7b7b, 0x7c7c7c, 0x7d7d7d, 0x7e7e7e, 0x7f7f7f, 0x808080, 0x818181, 0x828282, 0x838383, 0x848484, 0x858585, 0x868686, 0x878787, 0x888888, 0x898989, 0x8a8a8a, 0x8b8b8b, 0x8c8c8c, 0x8d8d8d, 0x8e8e8e, 0x8f8f8f, 0x909090, 0x919191, 0x929292, 0x939393, 0x949494, 0x959595, 0x969696, 0x979797, 0x989898, 0x999999, 0x9a9a9a, 0x9b9b9b, 0x9c9c9c, 0x9d9d9d, 0x9e9e9e, 0x9f9f9f, 0xa0a0a0, 0xa1a1a1, 0xa2a2a2, 0xa3a3a3, 0xa4a4a4, 0xa5a5a5, 0xa6a6a6, 0xa7a7a7, 0xa8a8a8, 0xa9a9a9, 0xaaaaaa, 0xababab, 0xacacac, 0xadadad, 0xaeaeae, 0xafafaf, 0xb0b0b0, 0xb1b1b1, 0xb2b2b2, 0xb3b3b3, 0xb4b4b4, 0xb5b5b5, 0xb6b6b6, 0xb7b7b7, 0xb8b8b8, 0xb9b9b9, 0xbababa, 0xbbbbbb, 0xbcbcbc, 0xbdbdbd, 0xbebebe, 0xbfbfbf, 0xc0c0c0, 0xc1c1c1, 0xc2c2c2, 0xc3c3c3, 0xc4c4c4, 0xc5c5c5, 0xc6c6c6, 0xc7c7c7, 0xc8c8c8, 0xc9c9c9, 0xcacaca, 0xcbcbcb, 0xcccccc, 0xcdcdcd, 0xcecece, 0xcfcfcf, 0xd0d0d0, 0xd1d1d1, 0xd2d2d2, 0xd3d3d3, 0xd4d4d4, 0xd5d5d5, 0xd6d6d6, 0xd7d7d7, 0xd8d8d8, 0xd9d9d9, 0xdadada, 0xdbdbdb, 0xdcdcdc, 0xdddddd, 0xdedede, 0xdfdfdf, 0xe0e0e0, 0xe1e1e1, 0xe2e2e2, 0xe3e3e3, 0xe4e4e4, 0xe5e5e5, 0xe6e6e6, 0xe7e7e7, 0xe8e8e8, 0xe9e9e9, 0xeaeaea, 0xebebeb, 0xececec, 0xededed, 0xeeeeee, 0xefefef, 0xf0f0f0, 0xf1f1f1, 0xf2f2f2, 0xf3f3f3, 0xf4f4f4, 0xf5f5f5, 0xf6f6f6, 0xf7f7f7, 0xf8f8f8, 0xf9f9f9, 0xfafafa, 0xfbfbfb, 0xfcfcfc, 0xfdfdfd, 0xfefefe, 0xffffff] } PuOr: { PuOr3 : [0x998ec3, 0xf7f7f7, 0xf1a340] PuOr4 : [0x5e3c99, 0xb2abd2, 0xfdb863, 0xe66101] PuOr5 : [0x5e3c99, 0xb2abd2, 0xf7f7f7, 0xfdb863, 0xe66101] PuOr6 : [0x542788, 0x998ec3, 0xd8daeb, 0xfee0b6, 0xf1a340, 0xb35806] PuOr7 : [0x542788, 0x998ec3, 0xd8daeb, 0xf7f7f7, 0xfee0b6, 0xf1a340, 0xb35806] PuOr8 : [0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806] PuOr9 : [0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xf7f7f7, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806] PuOr10 : [0x2d004b, 0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806, 0x7f3b08] PuOr11 : [0x2d004b, 0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xf7f7f7, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806, 0x7f3b08] } BrBG: { BrBG3 : [0x5ab4ac, 0xf5f5f5, 0xd8b365] BrBG4 : [0x018571, 0x80cdc1, 0xdfc27d, 0xa6611a] BrBG5 : [0x018571, 0x80cdc1, 0xf5f5f5, 0xdfc27d, 0xa6611a] BrBG6 : [0x01665e, 0x5ab4ac, 0xc7eae5, 0xf6e8c3, 0xd8b365, 0x8c510a] BrBG7 : [0x01665e, 0x5ab4ac, 0xc7eae5, 0xf5f5f5, 0xf6e8c3, 0xd8b365, 0x8c510a] BrBG8 : [0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a] BrBG9 : [0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf5f5f5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a] BrBG10 : [0x003c30, 0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a, 0x543005] BrBG11 : [0x003c30, 0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf5f5f5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a, 0x543005] } PRGn: { PRGn3 : [0x7fbf7b, 0xf7f7f7, 0xaf8dc3] PRGn4 : [0x008837, 0xa6dba0, 0xc2a5cf, 0x7b3294] PRGn5 : [0x008837, 0xa6dba0, 0xf7f7f7, 0xc2a5cf, 0x7b3294] PRGn6 : [0x1b7837, 0x7fbf7b, 0xd9f0d3, 0xe7d4e8, 0xaf8dc3, 0x762a83] PRGn7 : [0x1b7837, 0x7fbf7b, 0xd9f0d3, 0xf7f7f7, 0xe7d4e8, 0xaf8dc3, 0x762a83] PRGn8 : [0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83] PRGn9 : [0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xf7f7f7, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83] PRGn10 : [0x00441b, 0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83, 0x40004b] PRGn11 : [0x00441b, 0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xf7f7f7, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83, 0x40004b] } PiYG: { PiYG3 : [0xa1d76a, 0xf7f7f7, 0xe9a3c9] PiYG4 : [0x4dac26, 0xb8e186, 0xf1b6da, 0xd01c8b] PiYG5 : [0x4dac26, 0xb8e186, 0xf7f7f7, 0xf1b6da, 0xd01c8b] PiYG6 : [0x4d9221, 0xa1d76a, 0xe6f5d0, 0xfde0ef, 0xe9a3c9, 0xc51b7d] PiYG7 : [0x4d9221, 0xa1d76a, 0xe6f5d0, 0xf7f7f7, 0xfde0ef, 0xe9a3c9, 0xc51b7d] PiYG8 : [0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d] PiYG9 : [0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xf7f7f7, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d] PiYG10 : [0x276419, 0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d, 0x8e0152] PiYG11 : [0x276419, 0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xf7f7f7, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d, 0x8e0152] } RdBu: { RdBu3 : [0x67a9cf, 0xf7f7f7, 0xef8a62] RdBu4 : [0x0571b0, 0x92c5de, 0xf4a582, 0xca0020] RdBu5 : [0x0571b0, 0x92c5de, 0xf7f7f7, 0xf4a582, 0xca0020] RdBu6 : [0x2166ac, 0x67a9cf, 0xd1e5f0, 0xfddbc7, 0xef8a62, 0xb2182b] RdBu7 : [0x2166ac, 0x67a9cf, 0xd1e5f0, 0xf7f7f7, 0xfddbc7, 0xef8a62, 0xb2182b] RdBu8 : [0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b] RdBu9 : [0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xf7f7f7, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b] RdBu10 : [0x053061, 0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f] RdBu11 : [0x053061, 0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xf7f7f7, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f] } RdGy: { RdGy3 : [0x999999, 0xffffff, 0xef8a62] RdGy4 : [0x404040, 0xbababa, 0xf4a582, 0xca0020] RdGy5 : [0x404040, 0xbababa, 0xffffff, 0xf4a582, 0xca0020] RdGy6 : [0x4d4d4d, 0x999999, 0xe0e0e0, 0xfddbc7, 0xef8a62, 0xb2182b] RdGy7 : [0x4d4d4d, 0x999999, 0xe0e0e0, 0xffffff, 0xfddbc7, 0xef8a62, 0xb2182b] RdGy8 : [0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b] RdGy9 : [0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xffffff, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b] RdGy10 : [0x1a1a1a, 0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f] RdGy11 : [0x1a1a1a, 0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xffffff, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f] } RdYlBu: { RdYlBu3 : [0x91bfdb, 0xffffbf, 0xfc8d59] RdYlBu4 : [0x2c7bb6, 0xabd9e9, 0xfdae61, 0xd7191c] RdYlBu5 : [0x2c7bb6, 0xabd9e9, 0xffffbf, 0xfdae61, 0xd7191c] RdYlBu6 : [0x4575b4, 0x91bfdb, 0xe0f3f8, 0xfee090, 0xfc8d59, 0xd73027] RdYlBu7 : [0x4575b4, 0x91bfdb, 0xe0f3f8, 0xffffbf, 0xfee090, 0xfc8d59, 0xd73027] RdYlBu8 : [0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027] RdYlBu9 : [0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xffffbf, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027] RdYlBu10 : [0x313695, 0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026] RdYlBu11 : [0x313695, 0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xffffbf, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026] } Spectral: { Spectral3 : [0x99d594, 0xffffbf, 0xfc8d59] Spectral4 : [0x2b83ba, 0xabdda4, 0xfdae61, 0xd7191c] Spectral5 : [0x2b83ba, 0xabdda4, 0xffffbf, 0xfdae61, 0xd7191c] Spectral6 : [0x3288bd, 0x99d594, 0xe6f598, 0xfee08b, 0xfc8d59, 0xd53e4f] Spectral7 : [0x3288bd, 0x99d594, 0xe6f598, 0xffffbf, 0xfee08b, 0xfc8d59, 0xd53e4f] Spectral8 : [0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f] Spectral9 : [0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f] Spectral10 : [0x5e4fa2, 0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f, 0x9e0142] Spectral11 : [0x5e4fa2, 0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f, 0x9e0142] } RdYlGn: { RdYlGn3 : [0x91cf60, 0xffffbf, 0xfc8d59] RdYlGn4 : [0x1a9641, 0xa6d96a, 0xfdae61, 0xd7191c] RdYlGn5 : [0x1a9641, 0xa6d96a, 0xffffbf, 0xfdae61, 0xd7191c] RdYlGn6 : [0x1a9850, 0x91cf60, 0xd9ef8b, 0xfee08b, 0xfc8d59, 0xd73027] RdYlGn7 : [0x1a9850, 0x91cf60, 0xd9ef8b, 0xffffbf, 0xfee08b, 0xfc8d59, 0xd73027] RdYlGn8 : [0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027] RdYlGn9 : [0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027] RdYlGn10 : [0x006837, 0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026] RdYlGn11 : [0x006837, 0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026] } Inferno: { Inferno3 : [0x440154, 0x208f8c, 0xfde724] Inferno4 : [0x000003, 0x781c6d, 0xed6825, 0xfcfea4] Inferno5 : [0x000003, 0x550f6d, 0xba3655, 0xf98c09, 0xfcfea4] Inferno6 : [0x000003, 0x410967, 0x932567, 0xdc5039, 0xfba40a, 0xfcfea4] Inferno7 : [0x000003, 0x32095d, 0x781c6d, 0xba3655, 0xed6825, 0xfbb318, 0xfcfea4] Inferno8 : [0x000003, 0x270b52, 0x63146e, 0x9e2963, 0xd24742, 0xf57c15, 0xfabf25, 0xfcfea4] Inferno9 : [0x000003, 0x1f0c47, 0x550f6d, 0x88216a, 0xba3655, 0xe35832, 0xf98c09, 0xf8c931, 0xfcfea4] Inferno10 : [0x000003, 0x1a0b40, 0x4a0b6a, 0x781c6d, 0xa42c60, 0xcd4247, 0xed6825, 0xfb9906, 0xf7cf3a, 0xfcfea4] Inferno11 : [0x000003, 0x160b39, 0x410967, 0x6a176e, 0x932567, 0xba3655, 0xdc5039, 0xf2751a, 0xfba40a, 0xf6d542, 0xfcfea4] Inferno256 : [ 0x000003, 0x000004, 0x000006, 0x010007, 0x010109, 0x01010b, 0x02010e, 0x020210, 0x030212, 0x040314, 0x040316, 0x050418, 0x06041b, 0x07051d, 0x08061f, 0x090621, 0x0a0723, 0x0b0726, 0x0d0828, 0x0e082a, 0x0f092d, 0x10092f, 0x120a32, 0x130a34, 0x140b36, 0x160b39, 0x170b3b, 0x190b3e, 0x1a0b40, 0x1c0c43, 0x1d0c45, 0x1f0c47, 0x200c4a, 0x220b4c, 0x240b4e, 0x260b50, 0x270b52, 0x290b54, 0x2b0a56, 0x2d0a58, 0x2e0a5a, 0x300a5c, 0x32095d, 0x34095f, 0x350960, 0x370961, 0x390962, 0x3b0964, 0x3c0965, 0x3e0966, 0x400966, 0x410967, 0x430a68, 0x450a69, 0x460a69, 0x480b6a, 0x4a0b6a, 0x4b0c6b, 0x4d0c6b, 0x4f0d6c, 0x500d6c, 0x520e6c, 0x530e6d, 0x550f6d, 0x570f6d, 0x58106d, 0x5a116d, 0x5b116e, 0x5d126e, 0x5f126e, 0x60136e, 0x62146e, 0x63146e, 0x65156e, 0x66156e, 0x68166e, 0x6a176e, 0x6b176e, 0x6d186e, 0x6e186e, 0x70196e, 0x72196d, 0x731a6d, 0x751b6d, 0x761b6d, 0x781c6d, 0x7a1c6d, 0x7b1d6c, 0x7d1d6c, 0x7e1e6c, 0x801f6b, 0x811f6b, 0x83206b, 0x85206a, 0x86216a, 0x88216a, 0x892269, 0x8b2269, 0x8d2369, 0x8e2468, 0x902468, 0x912567, 0x932567, 0x952666, 0x962666, 0x982765, 0x992864, 0x9b2864, 0x9c2963, 0x9e2963, 0xa02a62, 0xa12b61, 0xa32b61, 0xa42c60, 0xa62c5f, 0xa72d5f, 0xa92e5e, 0xab2e5d, 0xac2f5c, 0xae305b, 0xaf315b, 0xb1315a, 0xb23259, 0xb43358, 0xb53357, 0xb73456, 0xb83556, 0xba3655, 0xbb3754, 0xbd3753, 0xbe3852, 0xbf3951, 0xc13a50, 0xc23b4f, 0xc43c4e, 0xc53d4d, 0xc73e4c, 0xc83e4b, 0xc93f4a, 0xcb4049, 0xcc4148, 0xcd4247, 0xcf4446, 0xd04544, 0xd14643, 0xd24742, 0xd44841, 0xd54940, 0xd64a3f, 0xd74b3e, 0xd94d3d, 0xda4e3b, 0xdb4f3a, 0xdc5039, 0xdd5238, 0xde5337, 0xdf5436, 0xe05634, 0xe25733, 0xe35832, 0xe45a31, 0xe55b30, 0xe65c2e, 0xe65e2d, 0xe75f2c, 0xe8612b, 0xe9622a, 0xea6428, 0xeb6527, 0xec6726, 0xed6825, 0xed6a23, 0xee6c22, 0xef6d21, 0xf06f1f, 0xf0701e, 0xf1721d, 0xf2741c, 0xf2751a, 0xf37719, 0xf37918, 0xf47a16, 0xf57c15, 0xf57e14, 0xf68012, 0xf68111, 0xf78310, 0xf7850e, 0xf8870d, 0xf8880c, 0xf88a0b, 0xf98c09, 0xf98e08, 0xf99008, 0xfa9107, 0xfa9306, 0xfa9506, 0xfa9706, 0xfb9906, 0xfb9b06, 0xfb9d06, 0xfb9e07, 0xfba007, 0xfba208, 0xfba40a, 0xfba60b, 0xfba80d, 0xfbaa0e, 0xfbac10, 0xfbae12, 0xfbb014, 0xfbb116, 0xfbb318, 0xfbb51a, 0xfbb71c, 0xfbb91e, 0xfabb21, 0xfabd23, 0xfabf25, 0xfac128, 0xf9c32a, 0xf9c52c, 0xf9c72f, 0xf8c931, 0xf8cb34, 0xf8cd37, 0xf7cf3a, 0xf7d13c, 0xf6d33f, 0xf6d542, 0xf5d745, 0xf5d948, 0xf4db4b, 0xf4dc4f, 0xf3de52, 0xf3e056, 0xf3e259, 0xf2e45d, 0xf2e660, 0xf1e864, 0xf1e968, 0xf1eb6c, 0xf1ed70, 0xf1ee74, 0xf1f079, 0xf1f27d, 0xf2f381, 0xf2f485, 0xf3f689, 0xf4f78d, 0xf5f891, 0xf6fa95, 0xf7fb99, 0xf9fc9d, 0xfafda0, 0xfcfea4] } Magma: { Magma3 : [0x000003, 0xb53679, 0xfbfcbf] Magma4 : [0x000003, 0x711f81, 0xf0605d, 0xfbfcbf] Magma5 : [0x000003, 0x4f117b, 0xb53679, 0xfb8660, 0xfbfcbf] Magma6 : [0x000003, 0x3b0f6f, 0x8c2980, 0xdd4968, 0xfd9f6c, 0xfbfcbf] Magma7 : [0x000003, 0x2b115e, 0x711f81, 0xb53679, 0xf0605d, 0xfeae76, 0xfbfcbf] Magma8 : [0x000003, 0x221150, 0x5d177e, 0x972c7f, 0xd1426e, 0xf8755c, 0xfeb97f, 0xfbfcbf] Magma9 : [0x000003, 0x1b1044, 0x4f117b, 0x812581, 0xb53679, 0xe55063, 0xfb8660, 0xfec286, 0xfbfcbf] Magma10 : [0x000003, 0x170f3c, 0x430f75, 0x711f81, 0x9e2e7e, 0xcb3e71, 0xf0605d, 0xfc9366, 0xfec78b, 0xfbfcbf] Magma11 : [0x000003, 0x140d35, 0x3b0f6f, 0x63197f, 0x8c2980, 0xb53679, 0xdd4968, 0xf66e5b, 0xfd9f6c, 0xfdcd90, 0xfbfcbf] Magma256 : [ 0x000003, 0x000004, 0x000006, 0x010007, 0x010109, 0x01010b, 0x02020d, 0x02020f, 0x030311, 0x040313, 0x040415, 0x050417, 0x060519, 0x07051b, 0x08061d, 0x09071f, 0x0a0722, 0x0b0824, 0x0c0926, 0x0d0a28, 0x0e0a2a, 0x0f0b2c, 0x100c2f, 0x110c31, 0x120d33, 0x140d35, 0x150e38, 0x160e3a, 0x170f3c, 0x180f3f, 0x1a1041, 0x1b1044, 0x1c1046, 0x1e1049, 0x1f114b, 0x20114d, 0x221150, 0x231152, 0x251155, 0x261157, 0x281159, 0x2a115c, 0x2b115e, 0x2d1060, 0x2f1062, 0x301065, 0x321067, 0x341068, 0x350f6a, 0x370f6c, 0x390f6e, 0x3b0f6f, 0x3c0f71, 0x3e0f72, 0x400f73, 0x420f74, 0x430f75, 0x450f76, 0x470f77, 0x481078, 0x4a1079, 0x4b1079, 0x4d117a, 0x4f117b, 0x50127b, 0x52127c, 0x53137c, 0x55137d, 0x57147d, 0x58157e, 0x5a157e, 0x5b167e, 0x5d177e, 0x5e177f, 0x60187f, 0x61187f, 0x63197f, 0x651a80, 0x661a80, 0x681b80, 0x691c80, 0x6b1c80, 0x6c1d80, 0x6e1e81, 0x6f1e81, 0x711f81, 0x731f81, 0x742081, 0x762181, 0x772181, 0x792281, 0x7a2281, 0x7c2381, 0x7e2481, 0x7f2481, 0x812581, 0x822581, 0x842681, 0x852681, 0x872781, 0x892881, 0x8a2881, 0x8c2980, 0x8d2980, 0x8f2a80, 0x912a80, 0x922b80, 0x942b80, 0x952c80, 0x972c7f, 0x992d7f, 0x9a2d7f, 0x9c2e7f, 0x9e2e7e, 0x9f2f7e, 0xa12f7e, 0xa3307e, 0xa4307d, 0xa6317d, 0xa7317d, 0xa9327c, 0xab337c, 0xac337b, 0xae347b, 0xb0347b, 0xb1357a, 0xb3357a, 0xb53679, 0xb63679, 0xb83778, 0xb93778, 0xbb3877, 0xbd3977, 0xbe3976, 0xc03a75, 0xc23a75, 0xc33b74, 0xc53c74, 0xc63c73, 0xc83d72, 0xca3e72, 0xcb3e71, 0xcd3f70, 0xce4070, 0xd0416f, 0xd1426e, 0xd3426d, 0xd4436d, 0xd6446c, 0xd7456b, 0xd9466a, 0xda4769, 0xdc4869, 0xdd4968, 0xde4a67, 0xe04b66, 0xe14c66, 0xe24d65, 0xe44e64, 0xe55063, 0xe65162, 0xe75262, 0xe85461, 0xea5560, 0xeb5660, 0xec585f, 0xed595f, 0xee5b5e, 0xee5d5d, 0xef5e5d, 0xf0605d, 0xf1615c, 0xf2635c, 0xf3655c, 0xf3675b, 0xf4685b, 0xf56a5b, 0xf56c5b, 0xf66e5b, 0xf6705b, 0xf7715b, 0xf7735c, 0xf8755c, 0xf8775c, 0xf9795c, 0xf97b5d, 0xf97d5d, 0xfa7f5e, 0xfa805e, 0xfa825f, 0xfb8460, 0xfb8660, 0xfb8861, 0xfb8a62, 0xfc8c63, 0xfc8e63, 0xfc9064, 0xfc9265, 0xfc9366, 0xfd9567, 0xfd9768, 0xfd9969, 0xfd9b6a, 0xfd9d6b, 0xfd9f6c, 0xfda16e, 0xfda26f, 0xfda470, 0xfea671, 0xfea873, 0xfeaa74, 0xfeac75, 0xfeae76, 0xfeaf78, 0xfeb179, 0xfeb37b, 0xfeb57c, 0xfeb77d, 0xfeb97f, 0xfebb80, 0xfebc82, 0xfebe83, 0xfec085, 0xfec286, 0xfec488, 0xfec689, 0xfec78b, 0xfec98d, 0xfecb8e, 0xfdcd90, 0xfdcf92, 0xfdd193, 0xfdd295, 0xfdd497, 0xfdd698, 0xfdd89a, 0xfdda9c, 0xfddc9d, 0xfddd9f, 0xfddfa1, 0xfde1a3, 0xfce3a5, 0xfce5a6, 0xfce6a8, 0xfce8aa, 0xfceaac, 0xfcecae, 0xfceeb0, 0xfcf0b1, 0xfcf1b3, 0xfcf3b5, 0xfcf5b7, 0xfbf7b9, 0xfbf9bb, 0xfbfabd, 0xfbfcbf] } Plasma: { Plasma3 : [0x0c0786, 0xca4678, 0xeff821] Plasma4 : [0x0c0786, 0x9b179e, 0xec7853, 0xeff821] Plasma5 : [0x0c0786, 0x7c02a7, 0xca4678, 0xf79341, 0xeff821] Plasma6 : [0x0c0786, 0x6a00a7, 0xb02a8f, 0xe06461, 0xfca635, 0xeff821] Plasma7 : [0x0c0786, 0x5c00a5, 0x9b179e, 0xca4678, 0xec7853, 0xfdb22f, 0xeff821] Plasma8 : [0x0c0786, 0x5201a3, 0x8908a5, 0xb83289, 0xda5a68, 0xf38748, 0xfdbb2b, 0xeff821] Plasma9 : [0x0c0786, 0x4a02a0, 0x7c02a7, 0xa82296, 0xca4678, 0xe56b5c, 0xf79341, 0xfdc328, 0xeff821] Plasma10 : [0x0c0786, 0x45039e, 0x7200a8, 0x9b179e, 0xbc3685, 0xd7566c, 0xec7853, 0xfa9d3a, 0xfcc726, 0xeff821] Plasma11 : [0x0c0786, 0x40039c, 0x6a00a7, 0x8f0da3, 0xb02a8f, 0xca4678, 0xe06461, 0xf1824c, 0xfca635, 0xfccc25, 0xeff821] Plasma256 : [ 0x0c0786, 0x100787, 0x130689, 0x15068a, 0x18068b, 0x1b068c, 0x1d068d, 0x1f058e, 0x21058f, 0x230590, 0x250591, 0x270592, 0x290593, 0x2b0594, 0x2d0494, 0x2f0495, 0x310496, 0x330497, 0x340498, 0x360498, 0x380499, 0x3a049a, 0x3b039a, 0x3d039b, 0x3f039c, 0x40039c, 0x42039d, 0x44039e, 0x45039e, 0x47029f, 0x49029f, 0x4a02a0, 0x4c02a1, 0x4e02a1, 0x4f02a2, 0x5101a2, 0x5201a3, 0x5401a3, 0x5601a3, 0x5701a4, 0x5901a4, 0x5a00a5, 0x5c00a5, 0x5e00a5, 0x5f00a6, 0x6100a6, 0x6200a6, 0x6400a7, 0x6500a7, 0x6700a7, 0x6800a7, 0x6a00a7, 0x6c00a8, 0x6d00a8, 0x6f00a8, 0x7000a8, 0x7200a8, 0x7300a8, 0x7500a8, 0x7601a8, 0x7801a8, 0x7901a8, 0x7b02a8, 0x7c02a7, 0x7e03a7, 0x7f03a7, 0x8104a7, 0x8204a7, 0x8405a6, 0x8506a6, 0x8607a6, 0x8807a5, 0x8908a5, 0x8b09a4, 0x8c0aa4, 0x8e0ca4, 0x8f0da3, 0x900ea3, 0x920fa2, 0x9310a1, 0x9511a1, 0x9612a0, 0x9713a0, 0x99149f, 0x9a159e, 0x9b179e, 0x9d189d, 0x9e199c, 0x9f1a9b, 0xa01b9b, 0xa21c9a, 0xa31d99, 0xa41e98, 0xa51f97, 0xa72197, 0xa82296, 0xa92395, 0xaa2494, 0xac2593, 0xad2692, 0xae2791, 0xaf2890, 0xb02a8f, 0xb12b8f, 0xb22c8e, 0xb42d8d, 0xb52e8c, 0xb62f8b, 0xb7308a, 0xb83289, 0xb93388, 0xba3487, 0xbb3586, 0xbc3685, 0xbd3784, 0xbe3883, 0xbf3982, 0xc03b81, 0xc13c80, 0xc23d80, 0xc33e7f, 0xc43f7e, 0xc5407d, 0xc6417c, 0xc7427b, 0xc8447a, 0xc94579, 0xca4678, 0xcb4777, 0xcc4876, 0xcd4975, 0xce4a75, 0xcf4b74, 0xd04d73, 0xd14e72, 0xd14f71, 0xd25070, 0xd3516f, 0xd4526e, 0xd5536d, 0xd6556d, 0xd7566c, 0xd7576b, 0xd8586a, 0xd95969, 0xda5a68, 0xdb5b67, 0xdc5d66, 0xdc5e66, 0xdd5f65, 0xde6064, 0xdf6163, 0xdf6262, 0xe06461, 0xe16560, 0xe26660, 0xe3675f, 0xe3685e, 0xe46a5d, 0xe56b5c, 0xe56c5b, 0xe66d5a, 0xe76e5a, 0xe87059, 0xe87158, 0xe97257, 0xea7356, 0xea7455, 0xeb7654, 0xec7754, 0xec7853, 0xed7952, 0xed7b51, 0xee7c50, 0xef7d4f, 0xef7e4e, 0xf0804d, 0xf0814d, 0xf1824c, 0xf2844b, 0xf2854a, 0xf38649, 0xf38748, 0xf48947, 0xf48a47, 0xf58b46, 0xf58d45, 0xf68e44, 0xf68f43, 0xf69142, 0xf79241, 0xf79341, 0xf89540, 0xf8963f, 0xf8983e, 0xf9993d, 0xf99a3c, 0xfa9c3b, 0xfa9d3a, 0xfa9f3a, 0xfaa039, 0xfba238, 0xfba337, 0xfba436, 0xfca635, 0xfca735, 0xfca934, 0xfcaa33, 0xfcac32, 0xfcad31, 0xfdaf31, 0xfdb030, 0xfdb22f, 0xfdb32e, 0xfdb52d, 0xfdb62d, 0xfdb82c, 0xfdb92b, 0xfdbb2b, 0xfdbc2a, 0xfdbe29, 0xfdc029, 0xfdc128, 0xfdc328, 0xfdc427, 0xfdc626, 0xfcc726, 0xfcc926, 0xfccb25, 0xfccc25, 0xfcce25, 0xfbd024, 0xfbd124, 0xfbd324, 0xfad524, 0xfad624, 0xfad824, 0xf9d924, 0xf9db24, 0xf8dd24, 0xf8df24, 0xf7e024, 0xf7e225, 0xf6e425, 0xf6e525, 0xf5e726, 0xf5e926, 0xf4ea26, 0xf3ec26, 0xf3ee26, 0xf2f026, 0xf2f126, 0xf1f326, 0xf0f525, 0xf0f623, 0xeff821] } Viridis: { Viridis3 : [0x440154, 0x208f8c, 0xfde724] Viridis4 : [0x440154, 0x30678d, 0x35b778, 0xfde724] Viridis5 : [0x440154, 0x3b518a, 0x208f8c, 0x5bc862, 0xfde724] Viridis6 : [0x440154, 0x404387, 0x29788e, 0x22a784, 0x79d151, 0xfde724] Viridis7 : [0x440154, 0x443982, 0x30678d, 0x208f8c, 0x35b778, 0x8dd644, 0xfde724] Viridis8 : [0x440154, 0x46317e, 0x365a8c, 0x277e8e, 0x1ea087, 0x49c16d, 0x9dd93a, 0xfde724] Viridis9 : [0x440154, 0x472b7a, 0x3b518a, 0x2c718e, 0x208f8c, 0x27ad80, 0x5bc862, 0xaadb32, 0xfde724] Viridis10 : [0x440154, 0x472777, 0x3e4989, 0x30678d, 0x25828e, 0x1e9c89, 0x35b778, 0x6bcd59, 0xb2dd2c, 0xfde724] Viridis11 : [0x440154, 0x482374, 0x404387, 0x345e8d, 0x29788e, 0x208f8c, 0x22a784, 0x42be71, 0x79d151, 0xbade27, 0xfde724] Viridis256 : [ 0x440154, 0x440255, 0x440357, 0x450558, 0x45065a, 0x45085b, 0x46095c, 0x460b5e, 0x460c5f, 0x460e61, 0x470f62, 0x471163, 0x471265, 0x471466, 0x471567, 0x471669, 0x47186a, 0x48196b, 0x481a6c, 0x481c6e, 0x481d6f, 0x481e70, 0x482071, 0x482172, 0x482273, 0x482374, 0x472575, 0x472676, 0x472777, 0x472878, 0x472a79, 0x472b7a, 0x472c7b, 0x462d7c, 0x462f7c, 0x46307d, 0x46317e, 0x45327f, 0x45347f, 0x453580, 0x453681, 0x443781, 0x443982, 0x433a83, 0x433b83, 0x433c84, 0x423d84, 0x423e85, 0x424085, 0x414186, 0x414286, 0x404387, 0x404487, 0x3f4587, 0x3f4788, 0x3e4888, 0x3e4989, 0x3d4a89, 0x3d4b89, 0x3d4c89, 0x3c4d8a, 0x3c4e8a, 0x3b508a, 0x3b518a, 0x3a528b, 0x3a538b, 0x39548b, 0x39558b, 0x38568b, 0x38578c, 0x37588c, 0x37598c, 0x365a8c, 0x365b8c, 0x355c8c, 0x355d8c, 0x345e8d, 0x345f8d, 0x33608d, 0x33618d, 0x32628d, 0x32638d, 0x31648d, 0x31658d, 0x31668d, 0x30678d, 0x30688d, 0x2f698d, 0x2f6a8d, 0x2e6b8e, 0x2e6c8e, 0x2e6d8e, 0x2d6e8e, 0x2d6f8e, 0x2c708e, 0x2c718e, 0x2c728e, 0x2b738e, 0x2b748e, 0x2a758e, 0x2a768e, 0x2a778e, 0x29788e, 0x29798e, 0x287a8e, 0x287a8e, 0x287b8e, 0x277c8e, 0x277d8e, 0x277e8e, 0x267f8e, 0x26808e, 0x26818e, 0x25828e, 0x25838d, 0x24848d, 0x24858d, 0x24868d, 0x23878d, 0x23888d, 0x23898d, 0x22898d, 0x228a8d, 0x228b8d, 0x218c8d, 0x218d8c, 0x218e8c, 0x208f8c, 0x20908c, 0x20918c, 0x1f928c, 0x1f938b, 0x1f948b, 0x1f958b, 0x1f968b, 0x1e978a, 0x1e988a, 0x1e998a, 0x1e998a, 0x1e9a89, 0x1e9b89, 0x1e9c89, 0x1e9d88, 0x1e9e88, 0x1e9f88, 0x1ea087, 0x1fa187, 0x1fa286, 0x1fa386, 0x20a485, 0x20a585, 0x21a685, 0x21a784, 0x22a784, 0x23a883, 0x23a982, 0x24aa82, 0x25ab81, 0x26ac81, 0x27ad80, 0x28ae7f, 0x29af7f, 0x2ab07e, 0x2bb17d, 0x2cb17d, 0x2eb27c, 0x2fb37b, 0x30b47a, 0x32b57a, 0x33b679, 0x35b778, 0x36b877, 0x38b976, 0x39b976, 0x3bba75, 0x3dbb74, 0x3ebc73, 0x40bd72, 0x42be71, 0x44be70, 0x45bf6f, 0x47c06e, 0x49c16d, 0x4bc26c, 0x4dc26b, 0x4fc369, 0x51c468, 0x53c567, 0x55c666, 0x57c665, 0x59c764, 0x5bc862, 0x5ec961, 0x60c960, 0x62ca5f, 0x64cb5d, 0x67cc5c, 0x69cc5b, 0x6bcd59, 0x6dce58, 0x70ce56, 0x72cf55, 0x74d054, 0x77d052, 0x79d151, 0x7cd24f, 0x7ed24e, 0x81d34c, 0x83d34b, 0x86d449, 0x88d547, 0x8bd546, 0x8dd644, 0x90d643, 0x92d741, 0x95d73f, 0x97d83e, 0x9ad83c, 0x9dd93a, 0x9fd938, 0xa2da37, 0xa5da35, 0xa7db33, 0xaadb32, 0xaddc30, 0xafdc2e, 0xb2dd2c, 0xb5dd2b, 0xb7dd29, 0xbade27, 0xbdde26, 0xbfdf24, 0xc2df22, 0xc5df21, 0xc7e01f, 0xcae01e, 0xcde01d, 0xcfe11c, 0xd2e11b, 0xd4e11a, 0xd7e219, 0xdae218, 0xdce218, 0xdfe318, 0xe1e318, 0xe4e318, 0xe7e419, 0xe9e419, 0xece41a, 0xeee51b, 0xf1e51c, 0xf3e51e, 0xf6e61f, 0xf8e621, 0xfae622, 0xfde724] } Accent: { Accent3 : [0x7fc97f, 0xbeaed4, 0xfdc086] Accent4 : [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99] Accent5 : [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0] Accent6 : [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0, 0xf0027f] Accent7 : [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0, 0xf0027f, 0xbf5b17] Accent8 : [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0, 0xf0027f, 0xbf5b17, 0x666666] } Dark2: { Dark2_3 : [0x1b9e77, 0xd95f02, 0x7570b3] Dark2_4 : [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a] Dark2_5 : [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e] Dark2_6 : [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02] Dark2_7 : [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02, 0xa6761d] Dark2_8 : [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02, 0xa6761d, 0x666666] } Paired: { Paired3 : [0xa6cee3, 0x1f78b4, 0xb2df8a] Paired4 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c] Paired5 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99] Paired6 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c] Paired7 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f] Paired8 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00] Paired9 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6] Paired10 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6, 0x6a3d9a] Paired11 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6, 0x6a3d9a, 0xffff99] Paired12 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6, 0x6a3d9a, 0xffff99, 0xb15928] } Pastel1: { Pastel1_3 : [0xfbb4ae, 0xb3cde3, 0xccebc5] Pastel1_4 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4] Pastel1_5 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6] Pastel1_6 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc] Pastel1_7 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc, 0xe5d8bd] Pastel1_8 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc, 0xe5d8bd, 0xfddaec] Pastel1_9 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc, 0xe5d8bd, 0xfddaec, 0xf2f2f2] } Pastel2: { Pastel2_3 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8] Pastel2_4 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4] Pastel2_5 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9] Pastel2_6 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9, 0xfff2ae] Pastel2_7 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9, 0xfff2ae, 0xf1e2cc] Pastel2_8 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9, 0xfff2ae, 0xf1e2cc, 0xcccccc] } Set1: { Set1_3 : [0xe41a1c, 0x377eb8, 0x4daf4a] Set1_4 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3] Set1_5 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00] Set1_6 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33] Set1_7 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628] Set1_8 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628, 0xf781bf] Set1_9 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628, 0xf781bf, 0x999999] } Set2: { Set2_3 : [0x66c2a5, 0xfc8d62, 0x8da0cb] Set2_4 : [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3] Set2_5 : [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854] Set2_6 : [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f] Set2_7 : [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f, 0xe5c494] Set2_8 : [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f, 0xe5c494, 0xb3b3b3] } Set3: { Set3_3 : [0x8dd3c7, 0xffffb3, 0xbebada] Set3_4 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072] Set3_5 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3] Set3_6 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462] Set3_7 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69] Set3_8 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5] Set3_9 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9] Set3_10 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9, 0xbc80bd] Set3_11 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9, 0xbc80bd, 0xccebc5] Set3_12 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9, 0xbc80bd, 0xccebc5, 0xffed6f] } } ### License regarding the Viridis, Magma, Plasma and Inferno color maps ### # New matplotlib colormaps by <NAME>, <NAME>, # and (in the case of viridis) <NAME>. # # This file and the colormaps in it are released under the CC0 license / # public domain dedication. We would appreciate credit if you use or # redistribute these colormaps, but do not impose any legal restrictions. # # To the extent possible under law, the persons who associated CC0 with # mpl-colormaps have waived all copyright and related or neighboring rights # to mpl-colormaps. # # You should have received a copy of the CC0 legalcode along with this # work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. module.exports = _.extend({}, palettes, palettes.YlGn, palettes.YlGnBu, palettes.GnBu, palettes.BuGn, palettes.PuBuGn, palettes.PuBu, palettes.BuPu, palettes.RdPu, palettes.PuRd, palettes.OrRd, palettes.YlOrRd, palettes.YlOrBr, palettes.Purples, palettes.Blues, palettes.Greens, palettes.Oranges, palettes.Reds, palettes.Greys, palettes.PuOr, palettes.BrBG, palettes.PRGn, palettes.PiYG, palettes.RdBu, palettes.RdGy, palettes.RdYlBu, palettes.Spectral, palettes.RdYlGn, palettes.Inferno, palettes.Magma, palettes.Plasma, palettes.Viridis)
true
_ = require("underscore") palettes = { YlGn: { YlGn3 : [0x31a354, 0xaddd8e, 0xf7fcb9] YlGn4 : [0x238443, 0x78c679, 0xc2e699, 0xffffcc] YlGn5 : [0x006837, 0x31a354, 0x78c679, 0xc2e699, 0xffffcc] YlGn6 : [0x006837, 0x31a354, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xffffcc] YlGn7 : [0x005a32, 0x238443, 0x41ab5d, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xffffcc] YlGn8 : [0x005a32, 0x238443, 0x41ab5d, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xf7fcb9, 0xffffe5] YlGn9 : [0x004529, 0x006837, 0x238443, 0x41ab5d, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xf7fcb9, 0xffffe5] } YlGnBu: { YlGnBu3 : [0x2c7fb8, 0x7fcdbb, 0xedf8b1] YlGnBu4 : [0x225ea8, 0x41b6c4, 0xa1dab4, 0xffffcc] YlGnBu5 : [0x253494, 0x2c7fb8, 0x41b6c4, 0xa1dab4, 0xffffcc] YlGnBu6 : [0x253494, 0x2c7fb8, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xffffcc] YlGnBu7 : [0x0c2c84, 0x225ea8, 0x1d91c0, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xffffcc] YlGnBu8 : [0x0c2c84, 0x225ea8, 0x1d91c0, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xedf8b1, 0xffffd9] YlGnBu9 : [0x081d58, 0x253494, 0x225ea8, 0x1d91c0, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xedf8b1, 0xffffd9] } GnBu: { GnBu3 : [0x43a2ca, 0xa8ddb5, 0xe0f3db] GnBu4 : [0x2b8cbe, 0x7bccc4, 0xbae4bc, 0xf0f9e8] GnBu5 : [0x0868ac, 0x43a2ca, 0x7bccc4, 0xbae4bc, 0xf0f9e8] GnBu6 : [0x0868ac, 0x43a2ca, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xf0f9e8] GnBu7 : [0x08589e, 0x2b8cbe, 0x4eb3d3, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xf0f9e8] GnBu8 : [0x08589e, 0x2b8cbe, 0x4eb3d3, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xe0f3db, 0xf7fcf0] GnBu9 : [0x084081, 0x0868ac, 0x2b8cbe, 0x4eb3d3, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xe0f3db, 0xf7fcf0] } BuGn: { BuGn3 : [0x2ca25f, 0x99d8c9, 0xe5f5f9] BuGn4 : [0x238b45, 0x66c2a4, 0xb2e2e2, 0xedf8fb] BuGn5 : [0x006d2c, 0x2ca25f, 0x66c2a4, 0xb2e2e2, 0xedf8fb] BuGn6 : [0x006d2c, 0x2ca25f, 0x66c2a4, 0x99d8c9, 0xccece6, 0xedf8fb] BuGn7 : [0x005824, 0x238b45, 0x41ae76, 0x66c2a4, 0x99d8c9, 0xccece6, 0xedf8fb] BuGn8 : [0x005824, 0x238b45, 0x41ae76, 0x66c2a4, 0x99d8c9, 0xccece6, 0xe5f5f9, 0xf7fcfd] BuGn9 : [0x00441b, 0x006d2c, 0x238b45, 0x41ae76, 0x66c2a4, 0x99d8c9, 0xccece6, 0xe5f5f9, 0xf7fcfd] } PuBuGn: { PuBuGn3 : [0x1c9099, 0xa6bddb, 0xece2f0] PuBuGn4 : [0x02818a, 0x67a9cf, 0xbdc9e1, 0xf6eff7] PuBuGn5 : [0x016c59, 0x1c9099, 0x67a9cf, 0xbdc9e1, 0xf6eff7] PuBuGn6 : [0x016c59, 0x1c9099, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xf6eff7] PuBuGn7 : [0x016450, 0x02818a, 0x3690c0, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xf6eff7] PuBuGn8 : [0x016450, 0x02818a, 0x3690c0, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xece2f0, 0xfff7fb] PuBuGn9 : [0x014636, 0x016c59, 0x02818a, 0x3690c0, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xece2f0, 0xfff7fb] } PuBu: { PuBu3 : [0x2b8cbe, 0xa6bddb, 0xece7f2] PuBu4 : [0x0570b0, 0x74a9cf, 0xbdc9e1, 0xf1eef6] PuBu5 : [0x045a8d, 0x2b8cbe, 0x74a9cf, 0xbdc9e1, 0xf1eef6] PuBu6 : [0x045a8d, 0x2b8cbe, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xf1eef6] PuBu7 : [0x034e7b, 0x0570b0, 0x3690c0, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xf1eef6] PuBu8 : [0x034e7b, 0x0570b0, 0x3690c0, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xece7f2, 0xfff7fb] PuBu9 : [0x023858, 0x045a8d, 0x0570b0, 0x3690c0, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xece7f2, 0xfff7fb] } BuPu: { BuPu3 : [0x8856a7, 0x9ebcda, 0xe0ecf4] BuPu4 : [0x88419d, 0x8c96c6, 0xb3cde3, 0xedf8fb] BuPu5 : [0x810f7c, 0x8856a7, 0x8c96c6, 0xb3cde3, 0xedf8fb] BuPu6 : [0x810f7c, 0x8856a7, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xedf8fb] BuPu7 : [0x6e016b, 0x88419d, 0x8c6bb1, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xedf8fb] BuPu8 : [0x6e016b, 0x88419d, 0x8c6bb1, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xe0ecf4, 0xf7fcfd] BuPu9 : [0x4d004b, 0x810f7c, 0x88419d, 0x8c6bb1, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xe0ecf4, 0xf7fcfd] } RdPu: { RdPu3 : [0xc51b8a, 0xfa9fb5, 0xfde0dd] RdPu4 : [0xae017e, 0xf768a1, 0xfbb4b9, 0xfeebe2] RdPu5 : [0x7a0177, 0xc51b8a, 0xf768a1, 0xfbb4b9, 0xfeebe2] RdPu6 : [0x7a0177, 0xc51b8a, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfeebe2] RdPu7 : [0x7a0177, 0xae017e, 0xdd3497, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfeebe2] RdPu8 : [0x7a0177, 0xae017e, 0xdd3497, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfde0dd, 0xfff7f3] RdPu9 : [0x49006a, 0x7a0177, 0xae017e, 0xdd3497, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfde0dd, 0xfff7f3] } PuRd: { PuRd3 : [0xdd1c77, 0xc994c7, 0xe7e1ef] PuRd4 : [0xce1256, 0xdf65b0, 0xd7b5d8, 0xf1eef6] PuRd5 : [0x980043, 0xdd1c77, 0xdf65b0, 0xd7b5d8, 0xf1eef6] PuRd6 : [0x980043, 0xdd1c77, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xf1eef6] PuRd7 : [0x91003f, 0xce1256, 0xe7298a, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xf1eef6] PuRd8 : [0x91003f, 0xce1256, 0xe7298a, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xe7e1ef, 0xf7f4f9] PuRd9 : [0x67001f, 0x980043, 0xce1256, 0xe7298a, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xe7e1ef, 0xf7f4f9] } OrRd: { OrRd3 : [0xe34a33, 0xfdbb84, 0xfee8c8] OrRd4 : [0xd7301f, 0xfc8d59, 0xfdcc8a, 0xfef0d9] OrRd5 : [0xb30000, 0xe34a33, 0xfc8d59, 0xfdcc8a, 0xfef0d9] OrRd6 : [0xb30000, 0xe34a33, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfef0d9] OrRd7 : [0x990000, 0xd7301f, 0xef6548, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfef0d9] OrRd8 : [0x990000, 0xd7301f, 0xef6548, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfee8c8, 0xfff7ec] OrRd9 : [0x7f0000, 0xb30000, 0xd7301f, 0xef6548, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfee8c8, 0xfff7ec] } YlOrRd: { YlOrRd3 : [0xf03b20, 0xfeb24c, 0xffeda0] YlOrRd4 : [0xe31a1c, 0xfd8d3c, 0xfecc5c, 0xffffb2] YlOrRd5 : [0xbd0026, 0xf03b20, 0xfd8d3c, 0xfecc5c, 0xffffb2] YlOrRd6 : [0xbd0026, 0xf03b20, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffffb2] YlOrRd7 : [0xb10026, 0xe31a1c, 0xfc4e2a, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffffb2] YlOrRd8 : [0xb10026, 0xe31a1c, 0xfc4e2a, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffeda0, 0xffffcc] YlOrRd9 : [0x800026, 0xbd0026, 0xe31a1c, 0xfc4e2a, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffeda0, 0xffffcc] } YlOrBr: { YlOrBr3 : [0xd95f0e, 0xfec44f, 0xfff7bc] YlOrBr4 : [0xcc4c02, 0xfe9929, 0xfed98e, 0xffffd4] YlOrBr5 : [0x993404, 0xd95f0e, 0xfe9929, 0xfed98e, 0xffffd4] YlOrBr6 : [0x993404, 0xd95f0e, 0xfe9929, 0xfec44f, 0xfee391, 0xffffd4] YlOrBr7 : [0x8c2d04, 0xcc4c02, 0xec7014, 0xfe9929, 0xfec44f, 0xfee391, 0xffffd4] YlOrBr8 : [0x8c2d04, 0xcc4c02, 0xec7014, 0xfe9929, 0xfec44f, 0xfee391, 0xfff7bc, 0xffffe5] YlOrBr9 : [0x662506, 0x993404, 0xcc4c02, 0xec7014, 0xfe9929, 0xfec44f, 0xfee391, 0xfff7bc, 0xffffe5] } Purples: { Purples3 : [0x756bb1, 0xbcbddc, 0xefedf5] Purples4 : [0x6a51a3, 0x9e9ac8, 0xcbc9e2, 0xf2f0f7] Purples5 : [0x54278f, 0x756bb1, 0x9e9ac8, 0xcbc9e2, 0xf2f0f7] Purples6 : [0x54278f, 0x756bb1, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xf2f0f7] Purples7 : [0x4a1486, 0x6a51a3, 0x807dba, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xf2f0f7] Purples8 : [0x4a1486, 0x6a51a3, 0x807dba, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xefedf5, 0xfcfbfd] Purples9 : [0x3f007d, 0x54278f, 0x6a51a3, 0x807dba, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xefedf5, 0xfcfbfd] } Blues: { Blues3 : [0x3182bd, 0x9ecae1, 0xdeebf7] Blues4 : [0x2171b5, 0x6baed6, 0xbdd7e7, 0xeff3ff] Blues5 : [0x08519c, 0x3182bd, 0x6baed6, 0xbdd7e7, 0xeff3ff] Blues6 : [0x08519c, 0x3182bd, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xeff3ff] Blues7 : [0x084594, 0x2171b5, 0x4292c6, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xeff3ff] Blues8 : [0x084594, 0x2171b5, 0x4292c6, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xdeebf7, 0xf7fbff] Blues9 : [0x08306b, 0x08519c, 0x2171b5, 0x4292c6, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xdeebf7, 0xf7fbff] } Greens: { Greens3 : [0x31a354, 0xa1d99b, 0xe5f5e0] Greens4 : [0x238b45, 0x74c476, 0xbae4b3, 0xedf8e9] Greens5 : [0x006d2c, 0x31a354, 0x74c476, 0xbae4b3, 0xedf8e9] Greens6 : [0x006d2c, 0x31a354, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xedf8e9] Greens7 : [0x005a32, 0x238b45, 0x41ab5d, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xedf8e9] Greens8 : [0x005a32, 0x238b45, 0x41ab5d, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xe5f5e0, 0xf7fcf5] Greens9 : [0x00441b, 0x006d2c, 0x238b45, 0x41ab5d, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xe5f5e0, 0xf7fcf5] } Oranges: { Oranges3 : [0xe6550d, 0xfdae6b, 0xfee6ce] Oranges4 : [0xd94701, 0xfd8d3c, 0xfdbe85, 0xfeedde] Oranges5 : [0xa63603, 0xe6550d, 0xfd8d3c, 0xfdbe85, 0xfeedde] Oranges6 : [0xa63603, 0xe6550d, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfeedde] Oranges7 : [0x8c2d04, 0xd94801, 0xf16913, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfeedde] Oranges8 : [0x8c2d04, 0xd94801, 0xf16913, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfee6ce, 0xfff5eb] Oranges9 : [0x7f2704, 0xa63603, 0xd94801, 0xf16913, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfee6ce, 0xfff5eb] } Reds: { Reds3 : [0xde2d26, 0xfc9272, 0xfee0d2] Reds4 : [0xcb181d, 0xfb6a4a, 0xfcae91, 0xfee5d9] Reds5 : [0xa50f15, 0xde2d26, 0xfb6a4a, 0xfcae91, 0xfee5d9] Reds6 : [0xa50f15, 0xde2d26, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee5d9] Reds7 : [0x99000d, 0xcb181d, 0xef3b2c, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee5d9] Reds8 : [0x99000d, 0xcb181d, 0xef3b2c, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee0d2, 0xfff5f0] Reds9 : [0x67000d, 0xa50f15, 0xcb181d, 0xef3b2c, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee0d2, 0xfff5f0] } Greys: { Greys3 : [0x636363, 0xbdbdbd, 0xf0f0f0] Greys4 : [0x525252, 0x969696, 0xcccccc, 0xf7f7f7] Greys5 : [0x252525, 0x636363, 0x969696, 0xcccccc, 0xf7f7f7] Greys6 : [0x252525, 0x636363, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf7f7f7] Greys7 : [0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf7f7f7] Greys8 : [0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf0f0f0, 0xffffff] Greys9 : [0x000000, 0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf0f0f0, 0xffffff] Greys10 : [0x000000, 0x1c1c1c, 0x383838, 0x555555, 0x717171, 0x8d8d8d, 0xaaaaaa, 0xc6c6c6, 0xe2e2e2, 0xffffff] Greys11 : [0x000000, 0x191919, 0x333333, 0x4c4c4c, 0x666666, 0x7f7f7f, 0x999999, 0xb2b2b2, 0xcccccc, 0xe5e5e5, 0xffffff] Greys256 : [ 0x000000, 0x010101, 0x020202, 0x030303, 0x040404, 0x050505, 0x060606, 0x070707, 0x080808, 0x090909, 0x0a0a0a, 0x0b0b0b, 0x0c0c0c, 0x0d0d0d, 0x0e0e0e, 0x0f0f0f, 0x101010, 0x111111, 0x121212, 0x131313, 0x141414, 0x151515, 0x161616, 0x171717, 0x181818, 0x191919, 0x1a1a1a, 0x1b1b1b, 0x1c1c1c, 0x1d1d1d, 0x1e1e1e, 0x1f1f1f, 0x202020, 0x212121, 0x222222, 0x232323, 0x242424, 0x252525, 0x262626, 0x272727, 0x282828, 0x292929, 0x2a2a2a, 0x2b2b2b, 0x2c2c2c, 0x2d2d2d, 0x2e2e2e, 0x2f2f2f, 0x303030, 0x313131, 0x323232, 0x333333, 0x343434, 0x353535, 0x363636, 0x373737, 0x383838, 0x393939, 0x3a3a3a, 0x3b3b3b, 0x3c3c3c, 0x3d3d3d, 0x3e3e3e, 0x3f3f3f, 0x404040, 0x414141, 0x424242, 0x434343, 0x444444, 0x454545, 0x464646, 0x474747, 0x484848, 0x494949, 0x4a4a4a, 0x4b4b4b, 0x4c4c4c, 0x4d4d4d, 0x4e4e4e, 0x4f4f4f, 0x505050, 0x515151, 0x525252, 0x535353, 0x545454, 0x555555, 0x565656, 0x575757, 0x585858, 0x595959, 0x5a5a5a, 0x5b5b5b, 0x5c5c5c, 0x5d5d5d, 0x5e5e5e, 0x5f5f5f, 0x606060, 0x616161, 0x626262, 0x636363, 0x646464, 0x656565, 0x666666, 0x676767, 0x686868, 0x696969, 0x6a6a6a, 0x6b6b6b, 0x6c6c6c, 0x6d6d6d, 0x6e6e6e, 0x6f6f6f, 0x707070, 0x717171, 0x727272, 0x737373, 0x747474, 0x757575, 0x767676, 0x777777, 0x787878, 0x797979, 0x7a7a7a, 0x7b7b7b, 0x7c7c7c, 0x7d7d7d, 0x7e7e7e, 0x7f7f7f, 0x808080, 0x818181, 0x828282, 0x838383, 0x848484, 0x858585, 0x868686, 0x878787, 0x888888, 0x898989, 0x8a8a8a, 0x8b8b8b, 0x8c8c8c, 0x8d8d8d, 0x8e8e8e, 0x8f8f8f, 0x909090, 0x919191, 0x929292, 0x939393, 0x949494, 0x959595, 0x969696, 0x979797, 0x989898, 0x999999, 0x9a9a9a, 0x9b9b9b, 0x9c9c9c, 0x9d9d9d, 0x9e9e9e, 0x9f9f9f, 0xa0a0a0, 0xa1a1a1, 0xa2a2a2, 0xa3a3a3, 0xa4a4a4, 0xa5a5a5, 0xa6a6a6, 0xa7a7a7, 0xa8a8a8, 0xa9a9a9, 0xaaaaaa, 0xababab, 0xacacac, 0xadadad, 0xaeaeae, 0xafafaf, 0xb0b0b0, 0xb1b1b1, 0xb2b2b2, 0xb3b3b3, 0xb4b4b4, 0xb5b5b5, 0xb6b6b6, 0xb7b7b7, 0xb8b8b8, 0xb9b9b9, 0xbababa, 0xbbbbbb, 0xbcbcbc, 0xbdbdbd, 0xbebebe, 0xbfbfbf, 0xc0c0c0, 0xc1c1c1, 0xc2c2c2, 0xc3c3c3, 0xc4c4c4, 0xc5c5c5, 0xc6c6c6, 0xc7c7c7, 0xc8c8c8, 0xc9c9c9, 0xcacaca, 0xcbcbcb, 0xcccccc, 0xcdcdcd, 0xcecece, 0xcfcfcf, 0xd0d0d0, 0xd1d1d1, 0xd2d2d2, 0xd3d3d3, 0xd4d4d4, 0xd5d5d5, 0xd6d6d6, 0xd7d7d7, 0xd8d8d8, 0xd9d9d9, 0xdadada, 0xdbdbdb, 0xdcdcdc, 0xdddddd, 0xdedede, 0xdfdfdf, 0xe0e0e0, 0xe1e1e1, 0xe2e2e2, 0xe3e3e3, 0xe4e4e4, 0xe5e5e5, 0xe6e6e6, 0xe7e7e7, 0xe8e8e8, 0xe9e9e9, 0xeaeaea, 0xebebeb, 0xececec, 0xededed, 0xeeeeee, 0xefefef, 0xf0f0f0, 0xf1f1f1, 0xf2f2f2, 0xf3f3f3, 0xf4f4f4, 0xf5f5f5, 0xf6f6f6, 0xf7f7f7, 0xf8f8f8, 0xf9f9f9, 0xfafafa, 0xfbfbfb, 0xfcfcfc, 0xfdfdfd, 0xfefefe, 0xffffff] } PuOr: { PuOr3 : [0x998ec3, 0xf7f7f7, 0xf1a340] PuOr4 : [0x5e3c99, 0xb2abd2, 0xfdb863, 0xe66101] PuOr5 : [0x5e3c99, 0xb2abd2, 0xf7f7f7, 0xfdb863, 0xe66101] PuOr6 : [0x542788, 0x998ec3, 0xd8daeb, 0xfee0b6, 0xf1a340, 0xb35806] PuOr7 : [0x542788, 0x998ec3, 0xd8daeb, 0xf7f7f7, 0xfee0b6, 0xf1a340, 0xb35806] PuOr8 : [0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806] PuOr9 : [0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xf7f7f7, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806] PuOr10 : [0x2d004b, 0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806, 0x7f3b08] PuOr11 : [0x2d004b, 0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xf7f7f7, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806, 0x7f3b08] } BrBG: { BrBG3 : [0x5ab4ac, 0xf5f5f5, 0xd8b365] BrBG4 : [0x018571, 0x80cdc1, 0xdfc27d, 0xa6611a] BrBG5 : [0x018571, 0x80cdc1, 0xf5f5f5, 0xdfc27d, 0xa6611a] BrBG6 : [0x01665e, 0x5ab4ac, 0xc7eae5, 0xf6e8c3, 0xd8b365, 0x8c510a] BrBG7 : [0x01665e, 0x5ab4ac, 0xc7eae5, 0xf5f5f5, 0xf6e8c3, 0xd8b365, 0x8c510a] BrBG8 : [0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a] BrBG9 : [0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf5f5f5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a] BrBG10 : [0x003c30, 0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a, 0x543005] BrBG11 : [0x003c30, 0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf5f5f5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a, 0x543005] } PRGn: { PRGn3 : [0x7fbf7b, 0xf7f7f7, 0xaf8dc3] PRGn4 : [0x008837, 0xa6dba0, 0xc2a5cf, 0x7b3294] PRGn5 : [0x008837, 0xa6dba0, 0xf7f7f7, 0xc2a5cf, 0x7b3294] PRGn6 : [0x1b7837, 0x7fbf7b, 0xd9f0d3, 0xe7d4e8, 0xaf8dc3, 0x762a83] PRGn7 : [0x1b7837, 0x7fbf7b, 0xd9f0d3, 0xf7f7f7, 0xe7d4e8, 0xaf8dc3, 0x762a83] PRGn8 : [0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83] PRGn9 : [0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xf7f7f7, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83] PRGn10 : [0x00441b, 0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83, 0x40004b] PRGn11 : [0x00441b, 0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xf7f7f7, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83, 0x40004b] } PiYG: { PiYG3 : [0xa1d76a, 0xf7f7f7, 0xe9a3c9] PiYG4 : [0x4dac26, 0xb8e186, 0xf1b6da, 0xd01c8b] PiYG5 : [0x4dac26, 0xb8e186, 0xf7f7f7, 0xf1b6da, 0xd01c8b] PiYG6 : [0x4d9221, 0xa1d76a, 0xe6f5d0, 0xfde0ef, 0xe9a3c9, 0xc51b7d] PiYG7 : [0x4d9221, 0xa1d76a, 0xe6f5d0, 0xf7f7f7, 0xfde0ef, 0xe9a3c9, 0xc51b7d] PiYG8 : [0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d] PiYG9 : [0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xf7f7f7, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d] PiYG10 : [0x276419, 0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d, 0x8e0152] PiYG11 : [0x276419, 0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xf7f7f7, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d, 0x8e0152] } RdBu: { RdBu3 : [0x67a9cf, 0xf7f7f7, 0xef8a62] RdBu4 : [0x0571b0, 0x92c5de, 0xf4a582, 0xca0020] RdBu5 : [0x0571b0, 0x92c5de, 0xf7f7f7, 0xf4a582, 0xca0020] RdBu6 : [0x2166ac, 0x67a9cf, 0xd1e5f0, 0xfddbc7, 0xef8a62, 0xb2182b] RdBu7 : [0x2166ac, 0x67a9cf, 0xd1e5f0, 0xf7f7f7, 0xfddbc7, 0xef8a62, 0xb2182b] RdBu8 : [0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b] RdBu9 : [0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xf7f7f7, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b] RdBu10 : [0x053061, 0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f] RdBu11 : [0x053061, 0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xf7f7f7, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f] } RdGy: { RdGy3 : [0x999999, 0xffffff, 0xef8a62] RdGy4 : [0x404040, 0xbababa, 0xf4a582, 0xca0020] RdGy5 : [0x404040, 0xbababa, 0xffffff, 0xf4a582, 0xca0020] RdGy6 : [0x4d4d4d, 0x999999, 0xe0e0e0, 0xfddbc7, 0xef8a62, 0xb2182b] RdGy7 : [0x4d4d4d, 0x999999, 0xe0e0e0, 0xffffff, 0xfddbc7, 0xef8a62, 0xb2182b] RdGy8 : [0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b] RdGy9 : [0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xffffff, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b] RdGy10 : [0x1a1a1a, 0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f] RdGy11 : [0x1a1a1a, 0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xffffff, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f] } RdYlBu: { RdYlBu3 : [0x91bfdb, 0xffffbf, 0xfc8d59] RdYlBu4 : [0x2c7bb6, 0xabd9e9, 0xfdae61, 0xd7191c] RdYlBu5 : [0x2c7bb6, 0xabd9e9, 0xffffbf, 0xfdae61, 0xd7191c] RdYlBu6 : [0x4575b4, 0x91bfdb, 0xe0f3f8, 0xfee090, 0xfc8d59, 0xd73027] RdYlBu7 : [0x4575b4, 0x91bfdb, 0xe0f3f8, 0xffffbf, 0xfee090, 0xfc8d59, 0xd73027] RdYlBu8 : [0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027] RdYlBu9 : [0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xffffbf, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027] RdYlBu10 : [0x313695, 0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026] RdYlBu11 : [0x313695, 0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xffffbf, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026] } Spectral: { Spectral3 : [0x99d594, 0xffffbf, 0xfc8d59] Spectral4 : [0x2b83ba, 0xabdda4, 0xfdae61, 0xd7191c] Spectral5 : [0x2b83ba, 0xabdda4, 0xffffbf, 0xfdae61, 0xd7191c] Spectral6 : [0x3288bd, 0x99d594, 0xe6f598, 0xfee08b, 0xfc8d59, 0xd53e4f] Spectral7 : [0x3288bd, 0x99d594, 0xe6f598, 0xffffbf, 0xfee08b, 0xfc8d59, 0xd53e4f] Spectral8 : [0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f] Spectral9 : [0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f] Spectral10 : [0x5e4fa2, 0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f, 0x9e0142] Spectral11 : [0x5e4fa2, 0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f, 0x9e0142] } RdYlGn: { RdYlGn3 : [0x91cf60, 0xffffbf, 0xfc8d59] RdYlGn4 : [0x1a9641, 0xa6d96a, 0xfdae61, 0xd7191c] RdYlGn5 : [0x1a9641, 0xa6d96a, 0xffffbf, 0xfdae61, 0xd7191c] RdYlGn6 : [0x1a9850, 0x91cf60, 0xd9ef8b, 0xfee08b, 0xfc8d59, 0xd73027] RdYlGn7 : [0x1a9850, 0x91cf60, 0xd9ef8b, 0xffffbf, 0xfee08b, 0xfc8d59, 0xd73027] RdYlGn8 : [0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027] RdYlGn9 : [0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027] RdYlGn10 : [0x006837, 0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026] RdYlGn11 : [0x006837, 0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026] } Inferno: { Inferno3 : [0x440154, 0x208f8c, 0xfde724] Inferno4 : [0x000003, 0x781c6d, 0xed6825, 0xfcfea4] Inferno5 : [0x000003, 0x550f6d, 0xba3655, 0xf98c09, 0xfcfea4] Inferno6 : [0x000003, 0x410967, 0x932567, 0xdc5039, 0xfba40a, 0xfcfea4] Inferno7 : [0x000003, 0x32095d, 0x781c6d, 0xba3655, 0xed6825, 0xfbb318, 0xfcfea4] Inferno8 : [0x000003, 0x270b52, 0x63146e, 0x9e2963, 0xd24742, 0xf57c15, 0xfabf25, 0xfcfea4] Inferno9 : [0x000003, 0x1f0c47, 0x550f6d, 0x88216a, 0xba3655, 0xe35832, 0xf98c09, 0xf8c931, 0xfcfea4] Inferno10 : [0x000003, 0x1a0b40, 0x4a0b6a, 0x781c6d, 0xa42c60, 0xcd4247, 0xed6825, 0xfb9906, 0xf7cf3a, 0xfcfea4] Inferno11 : [0x000003, 0x160b39, 0x410967, 0x6a176e, 0x932567, 0xba3655, 0xdc5039, 0xf2751a, 0xfba40a, 0xf6d542, 0xfcfea4] Inferno256 : [ 0x000003, 0x000004, 0x000006, 0x010007, 0x010109, 0x01010b, 0x02010e, 0x020210, 0x030212, 0x040314, 0x040316, 0x050418, 0x06041b, 0x07051d, 0x08061f, 0x090621, 0x0a0723, 0x0b0726, 0x0d0828, 0x0e082a, 0x0f092d, 0x10092f, 0x120a32, 0x130a34, 0x140b36, 0x160b39, 0x170b3b, 0x190b3e, 0x1a0b40, 0x1c0c43, 0x1d0c45, 0x1f0c47, 0x200c4a, 0x220b4c, 0x240b4e, 0x260b50, 0x270b52, 0x290b54, 0x2b0a56, 0x2d0a58, 0x2e0a5a, 0x300a5c, 0x32095d, 0x34095f, 0x350960, 0x370961, 0x390962, 0x3b0964, 0x3c0965, 0x3e0966, 0x400966, 0x410967, 0x430a68, 0x450a69, 0x460a69, 0x480b6a, 0x4a0b6a, 0x4b0c6b, 0x4d0c6b, 0x4f0d6c, 0x500d6c, 0x520e6c, 0x530e6d, 0x550f6d, 0x570f6d, 0x58106d, 0x5a116d, 0x5b116e, 0x5d126e, 0x5f126e, 0x60136e, 0x62146e, 0x63146e, 0x65156e, 0x66156e, 0x68166e, 0x6a176e, 0x6b176e, 0x6d186e, 0x6e186e, 0x70196e, 0x72196d, 0x731a6d, 0x751b6d, 0x761b6d, 0x781c6d, 0x7a1c6d, 0x7b1d6c, 0x7d1d6c, 0x7e1e6c, 0x801f6b, 0x811f6b, 0x83206b, 0x85206a, 0x86216a, 0x88216a, 0x892269, 0x8b2269, 0x8d2369, 0x8e2468, 0x902468, 0x912567, 0x932567, 0x952666, 0x962666, 0x982765, 0x992864, 0x9b2864, 0x9c2963, 0x9e2963, 0xa02a62, 0xa12b61, 0xa32b61, 0xa42c60, 0xa62c5f, 0xa72d5f, 0xa92e5e, 0xab2e5d, 0xac2f5c, 0xae305b, 0xaf315b, 0xb1315a, 0xb23259, 0xb43358, 0xb53357, 0xb73456, 0xb83556, 0xba3655, 0xbb3754, 0xbd3753, 0xbe3852, 0xbf3951, 0xc13a50, 0xc23b4f, 0xc43c4e, 0xc53d4d, 0xc73e4c, 0xc83e4b, 0xc93f4a, 0xcb4049, 0xcc4148, 0xcd4247, 0xcf4446, 0xd04544, 0xd14643, 0xd24742, 0xd44841, 0xd54940, 0xd64a3f, 0xd74b3e, 0xd94d3d, 0xda4e3b, 0xdb4f3a, 0xdc5039, 0xdd5238, 0xde5337, 0xdf5436, 0xe05634, 0xe25733, 0xe35832, 0xe45a31, 0xe55b30, 0xe65c2e, 0xe65e2d, 0xe75f2c, 0xe8612b, 0xe9622a, 0xea6428, 0xeb6527, 0xec6726, 0xed6825, 0xed6a23, 0xee6c22, 0xef6d21, 0xf06f1f, 0xf0701e, 0xf1721d, 0xf2741c, 0xf2751a, 0xf37719, 0xf37918, 0xf47a16, 0xf57c15, 0xf57e14, 0xf68012, 0xf68111, 0xf78310, 0xf7850e, 0xf8870d, 0xf8880c, 0xf88a0b, 0xf98c09, 0xf98e08, 0xf99008, 0xfa9107, 0xfa9306, 0xfa9506, 0xfa9706, 0xfb9906, 0xfb9b06, 0xfb9d06, 0xfb9e07, 0xfba007, 0xfba208, 0xfba40a, 0xfba60b, 0xfba80d, 0xfbaa0e, 0xfbac10, 0xfbae12, 0xfbb014, 0xfbb116, 0xfbb318, 0xfbb51a, 0xfbb71c, 0xfbb91e, 0xfabb21, 0xfabd23, 0xfabf25, 0xfac128, 0xf9c32a, 0xf9c52c, 0xf9c72f, 0xf8c931, 0xf8cb34, 0xf8cd37, 0xf7cf3a, 0xf7d13c, 0xf6d33f, 0xf6d542, 0xf5d745, 0xf5d948, 0xf4db4b, 0xf4dc4f, 0xf3de52, 0xf3e056, 0xf3e259, 0xf2e45d, 0xf2e660, 0xf1e864, 0xf1e968, 0xf1eb6c, 0xf1ed70, 0xf1ee74, 0xf1f079, 0xf1f27d, 0xf2f381, 0xf2f485, 0xf3f689, 0xf4f78d, 0xf5f891, 0xf6fa95, 0xf7fb99, 0xf9fc9d, 0xfafda0, 0xfcfea4] } Magma: { Magma3 : [0x000003, 0xb53679, 0xfbfcbf] Magma4 : [0x000003, 0x711f81, 0xf0605d, 0xfbfcbf] Magma5 : [0x000003, 0x4f117b, 0xb53679, 0xfb8660, 0xfbfcbf] Magma6 : [0x000003, 0x3b0f6f, 0x8c2980, 0xdd4968, 0xfd9f6c, 0xfbfcbf] Magma7 : [0x000003, 0x2b115e, 0x711f81, 0xb53679, 0xf0605d, 0xfeae76, 0xfbfcbf] Magma8 : [0x000003, 0x221150, 0x5d177e, 0x972c7f, 0xd1426e, 0xf8755c, 0xfeb97f, 0xfbfcbf] Magma9 : [0x000003, 0x1b1044, 0x4f117b, 0x812581, 0xb53679, 0xe55063, 0xfb8660, 0xfec286, 0xfbfcbf] Magma10 : [0x000003, 0x170f3c, 0x430f75, 0x711f81, 0x9e2e7e, 0xcb3e71, 0xf0605d, 0xfc9366, 0xfec78b, 0xfbfcbf] Magma11 : [0x000003, 0x140d35, 0x3b0f6f, 0x63197f, 0x8c2980, 0xb53679, 0xdd4968, 0xf66e5b, 0xfd9f6c, 0xfdcd90, 0xfbfcbf] Magma256 : [ 0x000003, 0x000004, 0x000006, 0x010007, 0x010109, 0x01010b, 0x02020d, 0x02020f, 0x030311, 0x040313, 0x040415, 0x050417, 0x060519, 0x07051b, 0x08061d, 0x09071f, 0x0a0722, 0x0b0824, 0x0c0926, 0x0d0a28, 0x0e0a2a, 0x0f0b2c, 0x100c2f, 0x110c31, 0x120d33, 0x140d35, 0x150e38, 0x160e3a, 0x170f3c, 0x180f3f, 0x1a1041, 0x1b1044, 0x1c1046, 0x1e1049, 0x1f114b, 0x20114d, 0x221150, 0x231152, 0x251155, 0x261157, 0x281159, 0x2a115c, 0x2b115e, 0x2d1060, 0x2f1062, 0x301065, 0x321067, 0x341068, 0x350f6a, 0x370f6c, 0x390f6e, 0x3b0f6f, 0x3c0f71, 0x3e0f72, 0x400f73, 0x420f74, 0x430f75, 0x450f76, 0x470f77, 0x481078, 0x4a1079, 0x4b1079, 0x4d117a, 0x4f117b, 0x50127b, 0x52127c, 0x53137c, 0x55137d, 0x57147d, 0x58157e, 0x5a157e, 0x5b167e, 0x5d177e, 0x5e177f, 0x60187f, 0x61187f, 0x63197f, 0x651a80, 0x661a80, 0x681b80, 0x691c80, 0x6b1c80, 0x6c1d80, 0x6e1e81, 0x6f1e81, 0x711f81, 0x731f81, 0x742081, 0x762181, 0x772181, 0x792281, 0x7a2281, 0x7c2381, 0x7e2481, 0x7f2481, 0x812581, 0x822581, 0x842681, 0x852681, 0x872781, 0x892881, 0x8a2881, 0x8c2980, 0x8d2980, 0x8f2a80, 0x912a80, 0x922b80, 0x942b80, 0x952c80, 0x972c7f, 0x992d7f, 0x9a2d7f, 0x9c2e7f, 0x9e2e7e, 0x9f2f7e, 0xa12f7e, 0xa3307e, 0xa4307d, 0xa6317d, 0xa7317d, 0xa9327c, 0xab337c, 0xac337b, 0xae347b, 0xb0347b, 0xb1357a, 0xb3357a, 0xb53679, 0xb63679, 0xb83778, 0xb93778, 0xbb3877, 0xbd3977, 0xbe3976, 0xc03a75, 0xc23a75, 0xc33b74, 0xc53c74, 0xc63c73, 0xc83d72, 0xca3e72, 0xcb3e71, 0xcd3f70, 0xce4070, 0xd0416f, 0xd1426e, 0xd3426d, 0xd4436d, 0xd6446c, 0xd7456b, 0xd9466a, 0xda4769, 0xdc4869, 0xdd4968, 0xde4a67, 0xe04b66, 0xe14c66, 0xe24d65, 0xe44e64, 0xe55063, 0xe65162, 0xe75262, 0xe85461, 0xea5560, 0xeb5660, 0xec585f, 0xed595f, 0xee5b5e, 0xee5d5d, 0xef5e5d, 0xf0605d, 0xf1615c, 0xf2635c, 0xf3655c, 0xf3675b, 0xf4685b, 0xf56a5b, 0xf56c5b, 0xf66e5b, 0xf6705b, 0xf7715b, 0xf7735c, 0xf8755c, 0xf8775c, 0xf9795c, 0xf97b5d, 0xf97d5d, 0xfa7f5e, 0xfa805e, 0xfa825f, 0xfb8460, 0xfb8660, 0xfb8861, 0xfb8a62, 0xfc8c63, 0xfc8e63, 0xfc9064, 0xfc9265, 0xfc9366, 0xfd9567, 0xfd9768, 0xfd9969, 0xfd9b6a, 0xfd9d6b, 0xfd9f6c, 0xfda16e, 0xfda26f, 0xfda470, 0xfea671, 0xfea873, 0xfeaa74, 0xfeac75, 0xfeae76, 0xfeaf78, 0xfeb179, 0xfeb37b, 0xfeb57c, 0xfeb77d, 0xfeb97f, 0xfebb80, 0xfebc82, 0xfebe83, 0xfec085, 0xfec286, 0xfec488, 0xfec689, 0xfec78b, 0xfec98d, 0xfecb8e, 0xfdcd90, 0xfdcf92, 0xfdd193, 0xfdd295, 0xfdd497, 0xfdd698, 0xfdd89a, 0xfdda9c, 0xfddc9d, 0xfddd9f, 0xfddfa1, 0xfde1a3, 0xfce3a5, 0xfce5a6, 0xfce6a8, 0xfce8aa, 0xfceaac, 0xfcecae, 0xfceeb0, 0xfcf0b1, 0xfcf1b3, 0xfcf3b5, 0xfcf5b7, 0xfbf7b9, 0xfbf9bb, 0xfbfabd, 0xfbfcbf] } Plasma: { Plasma3 : [0x0c0786, 0xca4678, 0xeff821] Plasma4 : [0x0c0786, 0x9b179e, 0xec7853, 0xeff821] Plasma5 : [0x0c0786, 0x7c02a7, 0xca4678, 0xf79341, 0xeff821] Plasma6 : [0x0c0786, 0x6a00a7, 0xb02a8f, 0xe06461, 0xfca635, 0xeff821] Plasma7 : [0x0c0786, 0x5c00a5, 0x9b179e, 0xca4678, 0xec7853, 0xfdb22f, 0xeff821] Plasma8 : [0x0c0786, 0x5201a3, 0x8908a5, 0xb83289, 0xda5a68, 0xf38748, 0xfdbb2b, 0xeff821] Plasma9 : [0x0c0786, 0x4a02a0, 0x7c02a7, 0xa82296, 0xca4678, 0xe56b5c, 0xf79341, 0xfdc328, 0xeff821] Plasma10 : [0x0c0786, 0x45039e, 0x7200a8, 0x9b179e, 0xbc3685, 0xd7566c, 0xec7853, 0xfa9d3a, 0xfcc726, 0xeff821] Plasma11 : [0x0c0786, 0x40039c, 0x6a00a7, 0x8f0da3, 0xb02a8f, 0xca4678, 0xe06461, 0xf1824c, 0xfca635, 0xfccc25, 0xeff821] Plasma256 : [ 0x0c0786, 0x100787, 0x130689, 0x15068a, 0x18068b, 0x1b068c, 0x1d068d, 0x1f058e, 0x21058f, 0x230590, 0x250591, 0x270592, 0x290593, 0x2b0594, 0x2d0494, 0x2f0495, 0x310496, 0x330497, 0x340498, 0x360498, 0x380499, 0x3a049a, 0x3b039a, 0x3d039b, 0x3f039c, 0x40039c, 0x42039d, 0x44039e, 0x45039e, 0x47029f, 0x49029f, 0x4a02a0, 0x4c02a1, 0x4e02a1, 0x4f02a2, 0x5101a2, 0x5201a3, 0x5401a3, 0x5601a3, 0x5701a4, 0x5901a4, 0x5a00a5, 0x5c00a5, 0x5e00a5, 0x5f00a6, 0x6100a6, 0x6200a6, 0x6400a7, 0x6500a7, 0x6700a7, 0x6800a7, 0x6a00a7, 0x6c00a8, 0x6d00a8, 0x6f00a8, 0x7000a8, 0x7200a8, 0x7300a8, 0x7500a8, 0x7601a8, 0x7801a8, 0x7901a8, 0x7b02a8, 0x7c02a7, 0x7e03a7, 0x7f03a7, 0x8104a7, 0x8204a7, 0x8405a6, 0x8506a6, 0x8607a6, 0x8807a5, 0x8908a5, 0x8b09a4, 0x8c0aa4, 0x8e0ca4, 0x8f0da3, 0x900ea3, 0x920fa2, 0x9310a1, 0x9511a1, 0x9612a0, 0x9713a0, 0x99149f, 0x9a159e, 0x9b179e, 0x9d189d, 0x9e199c, 0x9f1a9b, 0xa01b9b, 0xa21c9a, 0xa31d99, 0xa41e98, 0xa51f97, 0xa72197, 0xa82296, 0xa92395, 0xaa2494, 0xac2593, 0xad2692, 0xae2791, 0xaf2890, 0xb02a8f, 0xb12b8f, 0xb22c8e, 0xb42d8d, 0xb52e8c, 0xb62f8b, 0xb7308a, 0xb83289, 0xb93388, 0xba3487, 0xbb3586, 0xbc3685, 0xbd3784, 0xbe3883, 0xbf3982, 0xc03b81, 0xc13c80, 0xc23d80, 0xc33e7f, 0xc43f7e, 0xc5407d, 0xc6417c, 0xc7427b, 0xc8447a, 0xc94579, 0xca4678, 0xcb4777, 0xcc4876, 0xcd4975, 0xce4a75, 0xcf4b74, 0xd04d73, 0xd14e72, 0xd14f71, 0xd25070, 0xd3516f, 0xd4526e, 0xd5536d, 0xd6556d, 0xd7566c, 0xd7576b, 0xd8586a, 0xd95969, 0xda5a68, 0xdb5b67, 0xdc5d66, 0xdc5e66, 0xdd5f65, 0xde6064, 0xdf6163, 0xdf6262, 0xe06461, 0xe16560, 0xe26660, 0xe3675f, 0xe3685e, 0xe46a5d, 0xe56b5c, 0xe56c5b, 0xe66d5a, 0xe76e5a, 0xe87059, 0xe87158, 0xe97257, 0xea7356, 0xea7455, 0xeb7654, 0xec7754, 0xec7853, 0xed7952, 0xed7b51, 0xee7c50, 0xef7d4f, 0xef7e4e, 0xf0804d, 0xf0814d, 0xf1824c, 0xf2844b, 0xf2854a, 0xf38649, 0xf38748, 0xf48947, 0xf48a47, 0xf58b46, 0xf58d45, 0xf68e44, 0xf68f43, 0xf69142, 0xf79241, 0xf79341, 0xf89540, 0xf8963f, 0xf8983e, 0xf9993d, 0xf99a3c, 0xfa9c3b, 0xfa9d3a, 0xfa9f3a, 0xfaa039, 0xfba238, 0xfba337, 0xfba436, 0xfca635, 0xfca735, 0xfca934, 0xfcaa33, 0xfcac32, 0xfcad31, 0xfdaf31, 0xfdb030, 0xfdb22f, 0xfdb32e, 0xfdb52d, 0xfdb62d, 0xfdb82c, 0xfdb92b, 0xfdbb2b, 0xfdbc2a, 0xfdbe29, 0xfdc029, 0xfdc128, 0xfdc328, 0xfdc427, 0xfdc626, 0xfcc726, 0xfcc926, 0xfccb25, 0xfccc25, 0xfcce25, 0xfbd024, 0xfbd124, 0xfbd324, 0xfad524, 0xfad624, 0xfad824, 0xf9d924, 0xf9db24, 0xf8dd24, 0xf8df24, 0xf7e024, 0xf7e225, 0xf6e425, 0xf6e525, 0xf5e726, 0xf5e926, 0xf4ea26, 0xf3ec26, 0xf3ee26, 0xf2f026, 0xf2f126, 0xf1f326, 0xf0f525, 0xf0f623, 0xeff821] } Viridis: { Viridis3 : [0x440154, 0x208f8c, 0xfde724] Viridis4 : [0x440154, 0x30678d, 0x35b778, 0xfde724] Viridis5 : [0x440154, 0x3b518a, 0x208f8c, 0x5bc862, 0xfde724] Viridis6 : [0x440154, 0x404387, 0x29788e, 0x22a784, 0x79d151, 0xfde724] Viridis7 : [0x440154, 0x443982, 0x30678d, 0x208f8c, 0x35b778, 0x8dd644, 0xfde724] Viridis8 : [0x440154, 0x46317e, 0x365a8c, 0x277e8e, 0x1ea087, 0x49c16d, 0x9dd93a, 0xfde724] Viridis9 : [0x440154, 0x472b7a, 0x3b518a, 0x2c718e, 0x208f8c, 0x27ad80, 0x5bc862, 0xaadb32, 0xfde724] Viridis10 : [0x440154, 0x472777, 0x3e4989, 0x30678d, 0x25828e, 0x1e9c89, 0x35b778, 0x6bcd59, 0xb2dd2c, 0xfde724] Viridis11 : [0x440154, 0x482374, 0x404387, 0x345e8d, 0x29788e, 0x208f8c, 0x22a784, 0x42be71, 0x79d151, 0xbade27, 0xfde724] Viridis256 : [ 0x440154, 0x440255, 0x440357, 0x450558, 0x45065a, 0x45085b, 0x46095c, 0x460b5e, 0x460c5f, 0x460e61, 0x470f62, 0x471163, 0x471265, 0x471466, 0x471567, 0x471669, 0x47186a, 0x48196b, 0x481a6c, 0x481c6e, 0x481d6f, 0x481e70, 0x482071, 0x482172, 0x482273, 0x482374, 0x472575, 0x472676, 0x472777, 0x472878, 0x472a79, 0x472b7a, 0x472c7b, 0x462d7c, 0x462f7c, 0x46307d, 0x46317e, 0x45327f, 0x45347f, 0x453580, 0x453681, 0x443781, 0x443982, 0x433a83, 0x433b83, 0x433c84, 0x423d84, 0x423e85, 0x424085, 0x414186, 0x414286, 0x404387, 0x404487, 0x3f4587, 0x3f4788, 0x3e4888, 0x3e4989, 0x3d4a89, 0x3d4b89, 0x3d4c89, 0x3c4d8a, 0x3c4e8a, 0x3b508a, 0x3b518a, 0x3a528b, 0x3a538b, 0x39548b, 0x39558b, 0x38568b, 0x38578c, 0x37588c, 0x37598c, 0x365a8c, 0x365b8c, 0x355c8c, 0x355d8c, 0x345e8d, 0x345f8d, 0x33608d, 0x33618d, 0x32628d, 0x32638d, 0x31648d, 0x31658d, 0x31668d, 0x30678d, 0x30688d, 0x2f698d, 0x2f6a8d, 0x2e6b8e, 0x2e6c8e, 0x2e6d8e, 0x2d6e8e, 0x2d6f8e, 0x2c708e, 0x2c718e, 0x2c728e, 0x2b738e, 0x2b748e, 0x2a758e, 0x2a768e, 0x2a778e, 0x29788e, 0x29798e, 0x287a8e, 0x287a8e, 0x287b8e, 0x277c8e, 0x277d8e, 0x277e8e, 0x267f8e, 0x26808e, 0x26818e, 0x25828e, 0x25838d, 0x24848d, 0x24858d, 0x24868d, 0x23878d, 0x23888d, 0x23898d, 0x22898d, 0x228a8d, 0x228b8d, 0x218c8d, 0x218d8c, 0x218e8c, 0x208f8c, 0x20908c, 0x20918c, 0x1f928c, 0x1f938b, 0x1f948b, 0x1f958b, 0x1f968b, 0x1e978a, 0x1e988a, 0x1e998a, 0x1e998a, 0x1e9a89, 0x1e9b89, 0x1e9c89, 0x1e9d88, 0x1e9e88, 0x1e9f88, 0x1ea087, 0x1fa187, 0x1fa286, 0x1fa386, 0x20a485, 0x20a585, 0x21a685, 0x21a784, 0x22a784, 0x23a883, 0x23a982, 0x24aa82, 0x25ab81, 0x26ac81, 0x27ad80, 0x28ae7f, 0x29af7f, 0x2ab07e, 0x2bb17d, 0x2cb17d, 0x2eb27c, 0x2fb37b, 0x30b47a, 0x32b57a, 0x33b679, 0x35b778, 0x36b877, 0x38b976, 0x39b976, 0x3bba75, 0x3dbb74, 0x3ebc73, 0x40bd72, 0x42be71, 0x44be70, 0x45bf6f, 0x47c06e, 0x49c16d, 0x4bc26c, 0x4dc26b, 0x4fc369, 0x51c468, 0x53c567, 0x55c666, 0x57c665, 0x59c764, 0x5bc862, 0x5ec961, 0x60c960, 0x62ca5f, 0x64cb5d, 0x67cc5c, 0x69cc5b, 0x6bcd59, 0x6dce58, 0x70ce56, 0x72cf55, 0x74d054, 0x77d052, 0x79d151, 0x7cd24f, 0x7ed24e, 0x81d34c, 0x83d34b, 0x86d449, 0x88d547, 0x8bd546, 0x8dd644, 0x90d643, 0x92d741, 0x95d73f, 0x97d83e, 0x9ad83c, 0x9dd93a, 0x9fd938, 0xa2da37, 0xa5da35, 0xa7db33, 0xaadb32, 0xaddc30, 0xafdc2e, 0xb2dd2c, 0xb5dd2b, 0xb7dd29, 0xbade27, 0xbdde26, 0xbfdf24, 0xc2df22, 0xc5df21, 0xc7e01f, 0xcae01e, 0xcde01d, 0xcfe11c, 0xd2e11b, 0xd4e11a, 0xd7e219, 0xdae218, 0xdce218, 0xdfe318, 0xe1e318, 0xe4e318, 0xe7e419, 0xe9e419, 0xece41a, 0xeee51b, 0xf1e51c, 0xf3e51e, 0xf6e61f, 0xf8e621, 0xfae622, 0xfde724] } Accent: { Accent3 : [0x7fc97f, 0xbeaed4, 0xfdc086] Accent4 : [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99] Accent5 : [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0] Accent6 : [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0, 0xf0027f] Accent7 : [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0, 0xf0027f, 0xbf5b17] Accent8 : [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0, 0xf0027f, 0xbf5b17, 0x666666] } Dark2: { Dark2_3 : [0x1b9e77, 0xd95f02, 0x7570b3] Dark2_4 : [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a] Dark2_5 : [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e] Dark2_6 : [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02] Dark2_7 : [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02, 0xa6761d] Dark2_8 : [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02, 0xa6761d, 0x666666] } Paired: { Paired3 : [0xa6cee3, 0x1f78b4, 0xb2df8a] Paired4 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c] Paired5 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99] Paired6 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c] Paired7 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f] Paired8 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00] Paired9 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6] Paired10 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6, 0x6a3d9a] Paired11 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6, 0x6a3d9a, 0xffff99] Paired12 : [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6, 0x6a3d9a, 0xffff99, 0xb15928] } Pastel1: { Pastel1_3 : [0xfbb4ae, 0xb3cde3, 0xccebc5] Pastel1_4 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4] Pastel1_5 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6] Pastel1_6 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc] Pastel1_7 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc, 0xe5d8bd] Pastel1_8 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc, 0xe5d8bd, 0xfddaec] Pastel1_9 : [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc, 0xe5d8bd, 0xfddaec, 0xf2f2f2] } Pastel2: { Pastel2_3 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8] Pastel2_4 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4] Pastel2_5 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9] Pastel2_6 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9, 0xfff2ae] Pastel2_7 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9, 0xfff2ae, 0xf1e2cc] Pastel2_8 : [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9, 0xfff2ae, 0xf1e2cc, 0xcccccc] } Set1: { Set1_3 : [0xe41a1c, 0x377eb8, 0x4daf4a] Set1_4 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3] Set1_5 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00] Set1_6 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33] Set1_7 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628] Set1_8 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628, 0xf781bf] Set1_9 : [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628, 0xf781bf, 0x999999] } Set2: { Set2_3 : [0x66c2a5, 0xfc8d62, 0x8da0cb] Set2_4 : [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3] Set2_5 : [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854] Set2_6 : [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f] Set2_7 : [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f, 0xe5c494] Set2_8 : [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f, 0xe5c494, 0xb3b3b3] } Set3: { Set3_3 : [0x8dd3c7, 0xffffb3, 0xbebada] Set3_4 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072] Set3_5 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3] Set3_6 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462] Set3_7 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69] Set3_8 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5] Set3_9 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9] Set3_10 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9, 0xbc80bd] Set3_11 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9, 0xbc80bd, 0xccebc5] Set3_12 : [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9, 0xbc80bd, 0xccebc5, 0xffed6f] } } ### License regarding the Viridis, Magma, Plasma and Inferno color maps ### # New matplotlib colormaps by PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, # and (in the case of viridis) PI:NAME:<NAME>END_PI. # # This file and the colormaps in it are released under the CC0 license / # public domain dedication. We would appreciate credit if you use or # redistribute these colormaps, but do not impose any legal restrictions. # # To the extent possible under law, the persons who associated CC0 with # mpl-colormaps have waived all copyright and related or neighboring rights # to mpl-colormaps. # # You should have received a copy of the CC0 legalcode along with this # work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. module.exports = _.extend({}, palettes, palettes.YlGn, palettes.YlGnBu, palettes.GnBu, palettes.BuGn, palettes.PuBuGn, palettes.PuBu, palettes.BuPu, palettes.RdPu, palettes.PuRd, palettes.OrRd, palettes.YlOrRd, palettes.YlOrBr, palettes.Purples, palettes.Blues, palettes.Greens, palettes.Oranges, palettes.Reds, palettes.Greys, palettes.PuOr, palettes.BrBG, palettes.PRGn, palettes.PiYG, palettes.RdBu, palettes.RdGy, palettes.RdYlBu, palettes.Spectral, palettes.RdYlGn, palettes.Inferno, palettes.Magma, palettes.Plasma, palettes.Viridis)
[ { "context": "dAugLoginAchievement\"\n\t@title: \"Thanks for playing Duelyst\"\n\t@description: \"Enjoy 3 Unearthed Prophecy S", "end": 259, "score": 0.7246699333190918, "start": 256, "tag": "NAME", "value": "Due" } ]
app/sdk/achievements/loginBasedAchievements/midAugLoginAchievement.coffee
willroberts/duelyst
5
Achievement = require 'app/sdk/achievements/achievement' moment = require 'moment' GiftCrateLookup = require 'app/sdk/giftCrates/giftCrateLookup' class MidAugLoginAchievement extends Achievement @id: "midAugLoginAchievement" @title: "Thanks for playing Duelyst" @description: "Enjoy 3 Unearthed Prophecy Spirit Orbs on us for being a great community!" @progressRequired: 1 @rewards: giftChests: [GiftCrateLookup.MidAugust2017Login] @enabled: true @progressForLoggingIn: (currentLoginMoment) -> if currentLoginMoment != null && currentLoginMoment.isAfter(moment.utc("2017-08-15")) and currentLoginMoment.isBefore(moment.utc("Thu Aug 31 2017 18:00:00 GMT+0000")) return 1 else return 0 @getLoginAchievementStartsMoment: () -> return moment.utc("2017-08-15") module.exports = MidAugLoginAchievement
214388
Achievement = require 'app/sdk/achievements/achievement' moment = require 'moment' GiftCrateLookup = require 'app/sdk/giftCrates/giftCrateLookup' class MidAugLoginAchievement extends Achievement @id: "midAugLoginAchievement" @title: "Thanks for playing <NAME>lyst" @description: "Enjoy 3 Unearthed Prophecy Spirit Orbs on us for being a great community!" @progressRequired: 1 @rewards: giftChests: [GiftCrateLookup.MidAugust2017Login] @enabled: true @progressForLoggingIn: (currentLoginMoment) -> if currentLoginMoment != null && currentLoginMoment.isAfter(moment.utc("2017-08-15")) and currentLoginMoment.isBefore(moment.utc("Thu Aug 31 2017 18:00:00 GMT+0000")) return 1 else return 0 @getLoginAchievementStartsMoment: () -> return moment.utc("2017-08-15") module.exports = MidAugLoginAchievement
true
Achievement = require 'app/sdk/achievements/achievement' moment = require 'moment' GiftCrateLookup = require 'app/sdk/giftCrates/giftCrateLookup' class MidAugLoginAchievement extends Achievement @id: "midAugLoginAchievement" @title: "Thanks for playing PI:NAME:<NAME>END_PIlyst" @description: "Enjoy 3 Unearthed Prophecy Spirit Orbs on us for being a great community!" @progressRequired: 1 @rewards: giftChests: [GiftCrateLookup.MidAugust2017Login] @enabled: true @progressForLoggingIn: (currentLoginMoment) -> if currentLoginMoment != null && currentLoginMoment.isAfter(moment.utc("2017-08-15")) and currentLoginMoment.isBefore(moment.utc("Thu Aug 31 2017 18:00:00 GMT+0000")) return 1 else return 0 @getLoginAchievementStartsMoment: () -> return moment.utc("2017-08-15") module.exports = MidAugLoginAchievement
[ { "context": "ileoverview Tests for no-loop-func rule.\n# @author Ilya Volodin\n###\n\n'use strict'\n\n#-----------------------------", "end": 72, "score": 0.9997806549072266, "start": 60, "tag": "NAME", "value": "Ilya Volodin" } ]
src/tests/rules/no-loop-func.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for no-loop-func rule. # @author Ilya Volodin ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-loop-func' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' expectedErrorMessage = "Don't make functions within a loop." ruleTester.run 'no-loop-func', rule, valid: [ "string = 'function a() {}'" ''' for i in [0...l] ; a = -> i ''' ''' for i in [0...((-> i); l)] ; ''' ''' for x of xs.filter (x) -> x != upper ; ''' ''' for x from xs.filter (x) -> x != upper ; ''' ''' for x in xs.filter (x) -> x != upper ; ''' # no refers to variables that declared on upper scope. ''' for i in [0...l] -> ''' ''' for i of {} -> ''' ''' for i from {} -> ''' , code: ''' a = 0 for i in [0...l] -> a ''' , code: ''' a = 0 for i of {} -> -> a ''' ] invalid: [ code: ''' for i in [0...l] -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for i of {} -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for i from {} -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for i in [0...l] a = -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for i in [0...l] a = -> i a() ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' while i -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' until i -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , # Warns functions which are using modified variables. code: ''' a = null for i in [0...l] a = 1 -> a ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for i of {} -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for i from {} -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for i in [0...l] -> -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for i of {} -> -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for i from {} -> -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for i in [0...10] for x of xs.filter (x) -> x isnt i ; ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for x from xs a = null for y from ys a = 1 -> a ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for x from xs for y from ys -> x ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' (-> x) for x from xs ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for x from xs a = 1 -> a ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for x from xs -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null foo -> a = 10 for x from xs -> a foo() ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null foo -> a = 10 for x from xs -> a foo() ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' result = {} for score of scores letters = scores[score] letters.split('').forEach (letter) => result[letter] = score result.__default = 6 ''' errors: [message: expectedErrorMessage, type: 'ArrowFunctionExpression'] ]
164518
###* # @fileoverview Tests for no-loop-func rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-loop-func' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' expectedErrorMessage = "Don't make functions within a loop." ruleTester.run 'no-loop-func', rule, valid: [ "string = 'function a() {}'" ''' for i in [0...l] ; a = -> i ''' ''' for i in [0...((-> i); l)] ; ''' ''' for x of xs.filter (x) -> x != upper ; ''' ''' for x from xs.filter (x) -> x != upper ; ''' ''' for x in xs.filter (x) -> x != upper ; ''' # no refers to variables that declared on upper scope. ''' for i in [0...l] -> ''' ''' for i of {} -> ''' ''' for i from {} -> ''' , code: ''' a = 0 for i in [0...l] -> a ''' , code: ''' a = 0 for i of {} -> -> a ''' ] invalid: [ code: ''' for i in [0...l] -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for i of {} -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for i from {} -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for i in [0...l] a = -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for i in [0...l] a = -> i a() ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' while i -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' until i -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , # Warns functions which are using modified variables. code: ''' a = null for i in [0...l] a = 1 -> a ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for i of {} -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for i from {} -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for i in [0...l] -> -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for i of {} -> -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for i from {} -> -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for i in [0...10] for x of xs.filter (x) -> x isnt i ; ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for x from xs a = null for y from ys a = 1 -> a ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for x from xs for y from ys -> x ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' (-> x) for x from xs ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for x from xs a = 1 -> a ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for x from xs -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null foo -> a = 10 for x from xs -> a foo() ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null foo -> a = 10 for x from xs -> a foo() ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' result = {} for score of scores letters = scores[score] letters.split('').forEach (letter) => result[letter] = score result.__default = 6 ''' errors: [message: expectedErrorMessage, type: 'ArrowFunctionExpression'] ]
true
###* # @fileoverview Tests for no-loop-func rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-loop-func' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' expectedErrorMessage = "Don't make functions within a loop." ruleTester.run 'no-loop-func', rule, valid: [ "string = 'function a() {}'" ''' for i in [0...l] ; a = -> i ''' ''' for i in [0...((-> i); l)] ; ''' ''' for x of xs.filter (x) -> x != upper ; ''' ''' for x from xs.filter (x) -> x != upper ; ''' ''' for x in xs.filter (x) -> x != upper ; ''' # no refers to variables that declared on upper scope. ''' for i in [0...l] -> ''' ''' for i of {} -> ''' ''' for i from {} -> ''' , code: ''' a = 0 for i in [0...l] -> a ''' , code: ''' a = 0 for i of {} -> -> a ''' ] invalid: [ code: ''' for i in [0...l] -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for i of {} -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for i from {} -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for i in [0...l] a = -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for i in [0...l] a = -> i a() ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' while i -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' until i -> i ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , # Warns functions which are using modified variables. code: ''' a = null for i in [0...l] a = 1 -> a ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for i of {} -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for i from {} -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for i in [0...l] -> -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for i of {} -> -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for i from {} -> -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for i in [0...10] for x of xs.filter (x) -> x isnt i ; ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for x from xs a = null for y from ys a = 1 -> a ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' for x from xs for y from ys -> x ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' (-> x) for x from xs ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for x from xs a = 1 -> a ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null for x from xs -> a a = 1 ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null foo -> a = 10 for x from xs -> a foo() ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' a = null foo -> a = 10 for x from xs -> a foo() ''' errors: [message: expectedErrorMessage, type: 'FunctionExpression'] , code: ''' result = {} for score of scores letters = scores[score] letters.split('').forEach (letter) => result[letter] = score result.__default = 6 ''' errors: [message: expectedErrorMessage, type: 'ArrowFunctionExpression'] ]
[ { "context": " custom hashCode() and equals()\", ->\n key = new FunnyKey(33)\n hash = new HashSet().plus(key)\n\n it", "end": 2271, "score": 0.6852701306343079, "start": 2266, "tag": "KEY", "value": "Funny" }, { "context": "hCode() and equals()\", ->\n key = new FunnyKey(...
spec/hash_set_spec.coffee
odf/pazy.js
0
if typeof(require) != 'undefined' { seq } = require 'sequence' { HashSet } = require 'indexed' else { seq, HashSet } = pazy class FunnyKey constructor: (@value) -> hashCode: -> @value % 256 equals: (other) -> @value == other.value toString: -> "FunnyKey(#{@value})" FunnyKey.sorter = (a, b) -> a.value - b.value describe "A HashSet", -> describe "with two items the first of which is removed", -> hash = new HashSet().plus('A').plus('B').minus('A') it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should not be the same object as another one constructed like it", -> expect(hash).not.toBe(new HashSet().plus('A').plus('B').minus('A')) describe "when empty", -> hash = new HashSet() it "should have size 0", -> expect(hash.size()).toEqual 0 it "should be empty", -> expect(hash.size()).toBe 0 it "should return false on contains", -> expect(hash.contains("first")).toBe false it "should still be empty when minus is called", -> expect(hash.minus("first").size()).toEqual 0 it "should have length 0 as an array", -> expect(hash.toArray().length).toEqual 0 it "should print as HashSet(EmptyNode)", -> expect(hash.toString()).toEqual('HashSet(EmptyNode)') describe "containing one item", -> hash = new HashSet().plus("first") it "should have size 1", -> expect(hash.size()).toEqual 1 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should be empty when the item is removed", -> expect(hash.minus("first").size()).toBe 0 it "should be empty when the item is removed, twice", -> expect(hash.minus("first", "first").size()).toBe 0 it "should return true for the key", -> expect(hash.contains("first")).toBe true it "should return false when fed another key", -> expect(hash.contains("second")).toBe false it "should contain the key", -> a = hash.toArray() expect(a.length).toEqual 1 expect(a).toContain("first") it "should print as HashSet(first)", -> expect(hash.toString()).toEqual('HashSet(first)') describe "containing one item with custom hashCode() and equals()", -> key = new FunnyKey(33) hash = new HashSet().plus(key) it "should have size 1", -> expect(hash.size()).toEqual 1 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should be empty when the item is removed", -> expect(hash.minus(key).size()).toBe 0 it "should return true for the key", -> expect(hash.contains(key)).toBe true it "should return false when fed another key", -> expect(hash.contains("second")).toBe false it "should contain the key", -> a = hash.toArray() expect(a.length).toEqual 1 expect(a).toContain(key) it "should print as HashSet(FunnyKey(33))", -> expect(hash.toString()).toEqual('HashSet(FunnyKey(33))') describe "containing two items", -> hash = new HashSet().plus("first").plus("second") it "should have size 2", -> expect(hash.size()).toEqual 2 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should not be empty when the first item is removed", -> expect(hash.minus("first").size()).toBeGreaterThan 0 it "should be empty when both items are removed", -> expect(hash.minus("second").minus("first").size()).toBe 0 it "should return true for both keys", -> expect(hash.contains("first")).toBe true expect(hash.contains("second")).toBe true it "should return false when fed another key", -> expect(hash.contains("third")).toBe false it "should contain the keys", -> a = hash.toArray() expect(a.length).toEqual 2 expect(a).toContain("first") expect(a).toContain("second") describe "containing two arrays", -> hash = new HashSet().plus([1,2,3]).plus([4,5,6]) it "should have size 2", -> expect(hash.size()).toEqual 2 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should not be empty when the first item is removed", -> expect(hash.minus([1,2,3]).size()).toBeGreaterThan 0 it "should be empty when both items are removed", -> expect(hash.minus([1,2,3]).minus([4,5,6]).size()).toBe 0 it "should return true for both keys", -> expect(hash.contains([1,2,3])).toBe true expect(hash.contains([4,5,6])).toBe true it "should return false when fed another key", -> expect(hash.contains([7,8,9])).toBe false it "should contain the keys", -> a = hash.toArray() expect(a.length).toEqual 2 expect(a).toContain([1,2,3]) expect(a).toContain([4,5,6]) describe "containing two number", -> hash = new HashSet().plus(0, 2) it "should have size 2", -> expect(hash.size()).toEqual 2 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should not be empty when the first item is removed", -> expect(hash.minus(0).size()).toBeGreaterThan 0 it "should be empty when both items are removed", -> expect(hash.minus(0).minus(2).size()).toBe 0 it "should return true for both keys", -> expect(hash.contains(0)).toBe true expect(hash.contains(2)).toBe true it "should return false when fed another key", -> expect(hash.contains(1)).toBe false it "should contain the keys", -> a = hash.toArray() expect(a.length).toEqual 2 expect(a).toContain(0) expect(a).toContain(2) describe "containing two items with a level 1 collision", -> key_a = new FunnyKey(1) key_b = new FunnyKey(33) hash = new HashSet().plus(key_a).plus(key_b) it "should not change when an item not included is removed", -> a = hash.minus(new FunnyKey(5)).toArray() expect(a.length).toEqual 2 expect(a).toContain key_a expect(a).toContain key_b it "should return true for both keys", -> expect(hash.contains(key_a)).toBe true expect(hash.contains(key_b)).toBe true it "should not be empty when the first item is removed", -> expect(hash.minus(key_a).size()).toBeGreaterThan 0 it "should have size 1 when the first item is removed", -> expect(hash.minus(key_a).size()).toEqual 1 it "should be empty when both items are removed", -> expect(hash.minus(key_a).minus(key_b).size()).toBe 0 describe "containing three items with identical hash values", -> key_a = new FunnyKey(257) key_b = new FunnyKey(513) key_c = new FunnyKey(769) hash = new HashSet().plus(key_a).plus(key_b).plus(key_c) it "should contain the remaining two items when one is removed", -> a = hash.minus(key_a).toArray() expect(a.length).toEqual 2 expect(a).toContain key_b expect(a).toContain key_c it "should contain four items when one with a new hash value is added", -> key_d = new FunnyKey(33) a = hash.plus(key_d).toArray() expect(a.length).toEqual 4 expect(a).toContain key_a expect(a).toContain key_b expect(a).toContain key_c expect(a).toContain key_d describe "containing a wild mix of items", -> keys = (new FunnyKey(x * 5 + 7) for x in [0..16]) hash = (new HashSet()).plus keys... it "should have the right number of items", -> expect(hash.size()).toEqual keys.length it "should return true for each key", -> expect(hash.contains(key)).toBe true for key in keys describe "containing lots of items", -> keys = (new FunnyKey(x) for x in [0..300]) hash = (new HashSet()).plus keys... it "should have the correct number of keys", -> expect(hash.size()).toEqual keys.length it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should return true for each key", -> expect(hash.contains(key)).toBe true for key in keys it "should return false when fed another key", -> expect(hash.contains("third")).toBe false it "should contain all the keys when converted to an array", -> expect(hash.toArray().sort(FunnyKey.sorter)).toEqual(keys) it "should produce an element sequence of the correct size", -> expect(seq.size hash).toEqual(hash.size()) it "should produce a sequence with all the keys", -> expect(seq.into(hash, []).sort(FunnyKey.sorter)).toEqual(keys) describe "some of which are then removed", -> ex_keys = keys[0..100] h = hash.minus ex_keys... it "should have the correct size", -> expect(h.size()).toEqual keys.length - ex_keys.length it "should not be the same as the original hash", -> expect(h).not.toEqual hash it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should return true for the remaining keys", -> expect(h.contains(key)).toBe true for key in keys when key not in ex_keys it "should return false for the removed keys", -> expect(h.contains(key)).toBe false for key in ex_keys it "should have exactly the remaining elements when made an array", -> expect(h.toArray().sort(FunnyKey.sorter)).toEqual(keys[101..]) describe "from which some keys not included are removed", -> ex_keys = (new FunnyKey(x) for x in [1000..1100]) h = hash.minus ex_keys... it "should be the same object as before", -> expect(h).toBe hash it "should have the correct size", -> expect(h.size()).toEqual hash.size() it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 describe "all of which are then removed", -> h = hash.minus keys... it "should have size 0", -> expect(h.size()).toEqual 0 it "should be empty", -> expect(h.size()).toBe 0 it "should return false for the removed keys", -> expect(h.contains(key)).toBe false for key in keys it "should convert to an empty array", -> expect(h.toArray().length).toBe 0 describe "some of which are then inserted again", -> ex_keys = keys[0..100] h = hash.plus ex_keys... it "should be the same object as before", -> expect(h).toBe hash it "should have the same size as before", -> expect(h.size()).toEqual hash.size() it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 describe "with a peculiar sequence of additions and deletions", -> items = (n * 0x10000000 + 0x07ffffff for n in [0...9]) T = new HashSet().plus(items...).minus items[1..3]... it "should contain the correct number of items", -> expect(seq.size T).toBe 6 it "should contain the correct number after one item is removed", -> expect(seq.size T.minus items[4]).toBe 5
129073
if typeof(require) != 'undefined' { seq } = require 'sequence' { HashSet } = require 'indexed' else { seq, HashSet } = pazy class FunnyKey constructor: (@value) -> hashCode: -> @value % 256 equals: (other) -> @value == other.value toString: -> "FunnyKey(#{@value})" FunnyKey.sorter = (a, b) -> a.value - b.value describe "A HashSet", -> describe "with two items the first of which is removed", -> hash = new HashSet().plus('A').plus('B').minus('A') it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should not be the same object as another one constructed like it", -> expect(hash).not.toBe(new HashSet().plus('A').plus('B').minus('A')) describe "when empty", -> hash = new HashSet() it "should have size 0", -> expect(hash.size()).toEqual 0 it "should be empty", -> expect(hash.size()).toBe 0 it "should return false on contains", -> expect(hash.contains("first")).toBe false it "should still be empty when minus is called", -> expect(hash.minus("first").size()).toEqual 0 it "should have length 0 as an array", -> expect(hash.toArray().length).toEqual 0 it "should print as HashSet(EmptyNode)", -> expect(hash.toString()).toEqual('HashSet(EmptyNode)') describe "containing one item", -> hash = new HashSet().plus("first") it "should have size 1", -> expect(hash.size()).toEqual 1 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should be empty when the item is removed", -> expect(hash.minus("first").size()).toBe 0 it "should be empty when the item is removed, twice", -> expect(hash.minus("first", "first").size()).toBe 0 it "should return true for the key", -> expect(hash.contains("first")).toBe true it "should return false when fed another key", -> expect(hash.contains("second")).toBe false it "should contain the key", -> a = hash.toArray() expect(a.length).toEqual 1 expect(a).toContain("first") it "should print as HashSet(first)", -> expect(hash.toString()).toEqual('HashSet(first)') describe "containing one item with custom hashCode() and equals()", -> key = new <KEY>Key(3<KEY>) hash = new HashSet().plus(key) it "should have size 1", -> expect(hash.size()).toEqual 1 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should be empty when the item is removed", -> expect(hash.minus(key).size()).toBe 0 it "should return true for the key", -> expect(hash.contains(key)).toBe true it "should return false when fed another key", -> expect(hash.contains("second")).toBe false it "should contain the key", -> a = hash.toArray() expect(a.length).toEqual 1 expect(a).toContain(key) it "should print as HashSet(FunnyKey(33))", -> expect(hash.toString()).toEqual('HashSet(FunnyKey(33))') describe "containing two items", -> hash = new HashSet().plus("first").plus("second") it "should have size 2", -> expect(hash.size()).toEqual 2 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should not be empty when the first item is removed", -> expect(hash.minus("first").size()).toBeGreaterThan 0 it "should be empty when both items are removed", -> expect(hash.minus("second").minus("first").size()).toBe 0 it "should return true for both keys", -> expect(hash.contains("first")).toBe true expect(hash.contains("second")).toBe true it "should return false when fed another key", -> expect(hash.contains("third")).toBe false it "should contain the keys", -> a = hash.toArray() expect(a.length).toEqual 2 expect(a).toContain("first") expect(a).toContain("second") describe "containing two arrays", -> hash = new HashSet().plus([1,2,3]).plus([4,5,6]) it "should have size 2", -> expect(hash.size()).toEqual 2 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should not be empty when the first item is removed", -> expect(hash.minus([1,2,3]).size()).toBeGreaterThan 0 it "should be empty when both items are removed", -> expect(hash.minus([1,2,3]).minus([4,5,6]).size()).toBe 0 it "should return true for both keys", -> expect(hash.contains([1,2,3])).toBe true expect(hash.contains([4,5,6])).toBe true it "should return false when fed another key", -> expect(hash.contains([7,8,9])).toBe false it "should contain the keys", -> a = hash.toArray() expect(a.length).toEqual 2 expect(a).toContain([1,2,3]) expect(a).toContain([4,5,6]) describe "containing two number", -> hash = new HashSet().plus(0, 2) it "should have size 2", -> expect(hash.size()).toEqual 2 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should not be empty when the first item is removed", -> expect(hash.minus(0).size()).toBeGreaterThan 0 it "should be empty when both items are removed", -> expect(hash.minus(0).minus(2).size()).toBe 0 it "should return true for both keys", -> expect(hash.contains(0)).toBe true expect(hash.contains(2)).toBe true it "should return false when fed another key", -> expect(hash.contains(1)).toBe false it "should contain the keys", -> a = hash.toArray() expect(a.length).toEqual 2 expect(a).toContain(0) expect(a).toContain(2) describe "containing two items with a level 1 collision", -> key_a = new FunnyKey(1) key_b = new <KEY>Key(3<KEY>) hash = new HashSet().plus(key_a).plus(key_b) it "should not change when an item not included is removed", -> a = hash.minus(new FunnyKey(5)).toArray() expect(a.length).toEqual 2 expect(a).toContain key_a expect(a).toContain key_b it "should return true for both keys", -> expect(hash.contains(key_a)).toBe true expect(hash.contains(key_b)).toBe true it "should not be empty when the first item is removed", -> expect(hash.minus(key_a).size()).toBeGreaterThan 0 it "should have size 1 when the first item is removed", -> expect(hash.minus(key_a).size()).toEqual 1 it "should be empty when both items are removed", -> expect(hash.minus(key_a).minus(key_b).size()).toBe 0 describe "containing three items with identical hash values", -> key_a = new <KEY>(<KEY>) key_b = new <KEY>(<KEY>) key_c = new <KEY>Key(7<KEY>) hash = new HashSet().plus(key_a).plus(key_b).plus(key_c) it "should contain the remaining two items when one is removed", -> a = hash.minus(key_a).toArray() expect(a.length).toEqual 2 expect(a).toContain key_b expect(a).toContain key_c it "should contain four items when one with a new hash value is added", -> key_d = new <KEY>(<KEY>) a = hash.plus(key_d).toArray() expect(a.length).toEqual 4 expect(a).toContain key_a expect(a).toContain key_b expect(a).toContain key_c expect(a).toContain key_d describe "containing a wild mix of items", -> keys = (new <KEY>(x <KEY> <KEY> 7) for x in [0..16]) hash = (new HashSet()).plus keys... it "should have the right number of items", -> expect(hash.size()).toEqual keys.length it "should return true for each key", -> expect(hash.contains(key)).toBe true for key in keys describe "containing lots of items", -> keys = (new <KEY>Key(x) for x in [0..300]) hash = (new HashSet()).plus keys... it "should have the correct number of keys", -> expect(hash.size()).toEqual keys.length it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should return true for each key", -> expect(hash.contains(key)).toBe true for key in keys it "should return false when fed another key", -> expect(hash.contains("third")).toBe false it "should contain all the keys when converted to an array", -> expect(hash.toArray().sort(FunnyKey.sorter)).toEqual(keys) it "should produce an element sequence of the correct size", -> expect(seq.size hash).toEqual(hash.size()) it "should produce a sequence with all the keys", -> expect(seq.into(hash, []).sort(FunnyKey.sorter)).toEqual(keys) describe "some of which are then removed", -> ex_keys = keys[0..100] h = hash.minus ex_keys... it "should have the correct size", -> expect(h.size()).toEqual keys.length - ex_keys.length it "should not be the same as the original hash", -> expect(h).not.toEqual hash it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should return true for the remaining keys", -> expect(h.contains(key)).toBe true for key in keys when key not in ex_keys it "should return false for the removed keys", -> expect(h.contains(key)).toBe false for key in ex_keys it "should have exactly the remaining elements when made an array", -> expect(h.toArray().sort(FunnyKey.sorter)).toEqual(keys[101..]) describe "from which some keys not included are removed", -> ex_keys = (new Fun<KEY>Key(x) for x in [1000..1100]) h = hash.minus ex_keys... it "should be the same object as before", -> expect(h).toBe hash it "should have the correct size", -> expect(h.size()).toEqual hash.size() it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 describe "all of which are then removed", -> h = hash.minus keys... it "should have size 0", -> expect(h.size()).toEqual 0 it "should be empty", -> expect(h.size()).toBe 0 it "should return false for the removed keys", -> expect(h.contains(key)).toBe false for key in keys it "should convert to an empty array", -> expect(h.toArray().length).toBe 0 describe "some of which are then inserted again", -> ex_keys = keys[0..100] h = hash.plus ex_keys... it "should be the same object as before", -> expect(h).toBe hash it "should have the same size as before", -> expect(h.size()).toEqual hash.size() it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 describe "with a peculiar sequence of additions and deletions", -> items = (n * 0x10000000 + 0x07ffffff for n in [0...9]) T = new HashSet().plus(items...).minus items[1..3]... it "should contain the correct number of items", -> expect(seq.size T).toBe 6 it "should contain the correct number after one item is removed", -> expect(seq.size T.minus items[4]).toBe 5
true
if typeof(require) != 'undefined' { seq } = require 'sequence' { HashSet } = require 'indexed' else { seq, HashSet } = pazy class FunnyKey constructor: (@value) -> hashCode: -> @value % 256 equals: (other) -> @value == other.value toString: -> "FunnyKey(#{@value})" FunnyKey.sorter = (a, b) -> a.value - b.value describe "A HashSet", -> describe "with two items the first of which is removed", -> hash = new HashSet().plus('A').plus('B').minus('A') it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should not be the same object as another one constructed like it", -> expect(hash).not.toBe(new HashSet().plus('A').plus('B').minus('A')) describe "when empty", -> hash = new HashSet() it "should have size 0", -> expect(hash.size()).toEqual 0 it "should be empty", -> expect(hash.size()).toBe 0 it "should return false on contains", -> expect(hash.contains("first")).toBe false it "should still be empty when minus is called", -> expect(hash.minus("first").size()).toEqual 0 it "should have length 0 as an array", -> expect(hash.toArray().length).toEqual 0 it "should print as HashSet(EmptyNode)", -> expect(hash.toString()).toEqual('HashSet(EmptyNode)') describe "containing one item", -> hash = new HashSet().plus("first") it "should have size 1", -> expect(hash.size()).toEqual 1 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should be empty when the item is removed", -> expect(hash.minus("first").size()).toBe 0 it "should be empty when the item is removed, twice", -> expect(hash.minus("first", "first").size()).toBe 0 it "should return true for the key", -> expect(hash.contains("first")).toBe true it "should return false when fed another key", -> expect(hash.contains("second")).toBe false it "should contain the key", -> a = hash.toArray() expect(a.length).toEqual 1 expect(a).toContain("first") it "should print as HashSet(first)", -> expect(hash.toString()).toEqual('HashSet(first)') describe "containing one item with custom hashCode() and equals()", -> key = new PI:KEY:<KEY>END_PIKey(3PI:KEY:<KEY>END_PI) hash = new HashSet().plus(key) it "should have size 1", -> expect(hash.size()).toEqual 1 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should be empty when the item is removed", -> expect(hash.minus(key).size()).toBe 0 it "should return true for the key", -> expect(hash.contains(key)).toBe true it "should return false when fed another key", -> expect(hash.contains("second")).toBe false it "should contain the key", -> a = hash.toArray() expect(a.length).toEqual 1 expect(a).toContain(key) it "should print as HashSet(FunnyKey(33))", -> expect(hash.toString()).toEqual('HashSet(FunnyKey(33))') describe "containing two items", -> hash = new HashSet().plus("first").plus("second") it "should have size 2", -> expect(hash.size()).toEqual 2 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should not be empty when the first item is removed", -> expect(hash.minus("first").size()).toBeGreaterThan 0 it "should be empty when both items are removed", -> expect(hash.minus("second").minus("first").size()).toBe 0 it "should return true for both keys", -> expect(hash.contains("first")).toBe true expect(hash.contains("second")).toBe true it "should return false when fed another key", -> expect(hash.contains("third")).toBe false it "should contain the keys", -> a = hash.toArray() expect(a.length).toEqual 2 expect(a).toContain("first") expect(a).toContain("second") describe "containing two arrays", -> hash = new HashSet().plus([1,2,3]).plus([4,5,6]) it "should have size 2", -> expect(hash.size()).toEqual 2 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should not be empty when the first item is removed", -> expect(hash.minus([1,2,3]).size()).toBeGreaterThan 0 it "should be empty when both items are removed", -> expect(hash.minus([1,2,3]).minus([4,5,6]).size()).toBe 0 it "should return true for both keys", -> expect(hash.contains([1,2,3])).toBe true expect(hash.contains([4,5,6])).toBe true it "should return false when fed another key", -> expect(hash.contains([7,8,9])).toBe false it "should contain the keys", -> a = hash.toArray() expect(a.length).toEqual 2 expect(a).toContain([1,2,3]) expect(a).toContain([4,5,6]) describe "containing two number", -> hash = new HashSet().plus(0, 2) it "should have size 2", -> expect(hash.size()).toEqual 2 it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should not be empty when the first item is removed", -> expect(hash.minus(0).size()).toBeGreaterThan 0 it "should be empty when both items are removed", -> expect(hash.minus(0).minus(2).size()).toBe 0 it "should return true for both keys", -> expect(hash.contains(0)).toBe true expect(hash.contains(2)).toBe true it "should return false when fed another key", -> expect(hash.contains(1)).toBe false it "should contain the keys", -> a = hash.toArray() expect(a.length).toEqual 2 expect(a).toContain(0) expect(a).toContain(2) describe "containing two items with a level 1 collision", -> key_a = new FunnyKey(1) key_b = new PI:KEY:<KEY>END_PIKey(3PI:KEY:<KEY>END_PI) hash = new HashSet().plus(key_a).plus(key_b) it "should not change when an item not included is removed", -> a = hash.minus(new FunnyKey(5)).toArray() expect(a.length).toEqual 2 expect(a).toContain key_a expect(a).toContain key_b it "should return true for both keys", -> expect(hash.contains(key_a)).toBe true expect(hash.contains(key_b)).toBe true it "should not be empty when the first item is removed", -> expect(hash.minus(key_a).size()).toBeGreaterThan 0 it "should have size 1 when the first item is removed", -> expect(hash.minus(key_a).size()).toEqual 1 it "should be empty when both items are removed", -> expect(hash.minus(key_a).minus(key_b).size()).toBe 0 describe "containing three items with identical hash values", -> key_a = new PI:KEY:<KEY>END_PI(PI:KEY:<KEY>END_PI) key_b = new PI:KEY:<KEY>END_PI(PI:KEY:<KEY>END_PI) key_c = new PI:KEY:<KEY>END_PIKey(7PI:KEY:<KEY>END_PI) hash = new HashSet().plus(key_a).plus(key_b).plus(key_c) it "should contain the remaining two items when one is removed", -> a = hash.minus(key_a).toArray() expect(a.length).toEqual 2 expect(a).toContain key_b expect(a).toContain key_c it "should contain four items when one with a new hash value is added", -> key_d = new PI:KEY:<KEY>END_PI(PI:KEY:<KEY>END_PI) a = hash.plus(key_d).toArray() expect(a.length).toEqual 4 expect(a).toContain key_a expect(a).toContain key_b expect(a).toContain key_c expect(a).toContain key_d describe "containing a wild mix of items", -> keys = (new PI:KEY:<KEY>END_PI(x PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI 7) for x in [0..16]) hash = (new HashSet()).plus keys... it "should have the right number of items", -> expect(hash.size()).toEqual keys.length it "should return true for each key", -> expect(hash.contains(key)).toBe true for key in keys describe "containing lots of items", -> keys = (new PI:KEY:<KEY>END_PIKey(x) for x in [0..300]) hash = (new HashSet()).plus keys... it "should have the correct number of keys", -> expect(hash.size()).toEqual keys.length it "should not be empty", -> expect(hash.size()).toBeGreaterThan 0 it "should return true for each key", -> expect(hash.contains(key)).toBe true for key in keys it "should return false when fed another key", -> expect(hash.contains("third")).toBe false it "should contain all the keys when converted to an array", -> expect(hash.toArray().sort(FunnyKey.sorter)).toEqual(keys) it "should produce an element sequence of the correct size", -> expect(seq.size hash).toEqual(hash.size()) it "should produce a sequence with all the keys", -> expect(seq.into(hash, []).sort(FunnyKey.sorter)).toEqual(keys) describe "some of which are then removed", -> ex_keys = keys[0..100] h = hash.minus ex_keys... it "should have the correct size", -> expect(h.size()).toEqual keys.length - ex_keys.length it "should not be the same as the original hash", -> expect(h).not.toEqual hash it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 it "should return true for the remaining keys", -> expect(h.contains(key)).toBe true for key in keys when key not in ex_keys it "should return false for the removed keys", -> expect(h.contains(key)).toBe false for key in ex_keys it "should have exactly the remaining elements when made an array", -> expect(h.toArray().sort(FunnyKey.sorter)).toEqual(keys[101..]) describe "from which some keys not included are removed", -> ex_keys = (new FunPI:KEY:<KEY>END_PIKey(x) for x in [1000..1100]) h = hash.minus ex_keys... it "should be the same object as before", -> expect(h).toBe hash it "should have the correct size", -> expect(h.size()).toEqual hash.size() it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 describe "all of which are then removed", -> h = hash.minus keys... it "should have size 0", -> expect(h.size()).toEqual 0 it "should be empty", -> expect(h.size()).toBe 0 it "should return false for the removed keys", -> expect(h.contains(key)).toBe false for key in keys it "should convert to an empty array", -> expect(h.toArray().length).toBe 0 describe "some of which are then inserted again", -> ex_keys = keys[0..100] h = hash.plus ex_keys... it "should be the same object as before", -> expect(h).toBe hash it "should have the same size as before", -> expect(h.size()).toEqual hash.size() it "should not be empty", -> expect(h.size()).toBeGreaterThan 0 describe "with a peculiar sequence of additions and deletions", -> items = (n * 0x10000000 + 0x07ffffff for n in [0...9]) T = new HashSet().plus(items...).minus items[1..3]... it "should contain the correct number of items", -> expect(seq.size T).toBe 6 it "should contain the correct number after one item is removed", -> expect(seq.size T.minus items[4]).toBe 5
[ { "context": "r</b> written by <a href=\"http://erikdemaine.org\">Erik Demaine</a>, with help from many others.\n <span classN", "end": 2504, "score": 0.9998971819877625, "start": 2492, "tag": "NAME", "value": "Erik Demaine" }, { "context": "ssName=\"btn btn-default\" href=\"https...
client/layout.coffee
RubberNoodles/coauthor
204
import React from 'react' linkToRoutes = since: true live: true author: true tag: true stats: true users: true settings: true search: true # IronRouter trims leading and trailing /s and combines # consecutive /s, so quote them protectSlash = (params) -> params.search = params.search.replace /\//g, '%SLASH%' if params.search? params resolveSlash = (url) -> url?.replace /%25SLASH%25/g, '%2F' Template.layout.onRendered -> ## In case Coauthor is mounted within a subdirectory, update favicon paths document.getElementById('iconIco').href = Meteor.absoluteUrl 'favicon.ico' document.getElementById('iconPNG').href = Meteor.absoluteUrl 'favicon32.png' ## Create Google font without italic definition to get slanted (fake-italic) ## version for \textsl support. ## See https://stackoverflow.com/questions/11042330/force-the-browser-to-use-faux-italic-oblique-and-not-the-real-italic for child in document.head.children if child.tagName == 'LINK' and child.href.match /fonts.googleapis.com/ rules = (rule for rule in child.sheet.cssRules) ## copy before modifying for rule in rules if rule.style.fontStyle == 'normal' ## skip italic definitions child.sheet.insertRule ( rule.cssText.replace /font-family:\s*/i, '$&Slant' ), child.sheet.cssRules.length ## append break Template.layout.helpers activeGroup: -> if routeGroup() == @name 'active' else '' inUsers: -> (Router.current().route?.getName() ? '')[...5] == 'users' linkToUsers: -> if (message = routeMessage()) pathFor 'users.message', group: routeGroupOrWild() message: message2root message else pathFor 'users', group: routeGroupOrWild() linkToUsersExit: -> if (message = routeMessage()) pathFor 'message', group: routeGroupOrWild() message: message else pathFor 'group', group: routeGroupOrWild() linkToGroup: -> router = Router.current() route = Router.current().route?.getName() if linkToRoutes[route] resolveSlash pathFor route, protectSlash _.extend _.omit(router.params, 'length'), group: @name else pathFor 'group', group: @name creditsWide: -> Router.current().route?.getName() != 'message' export Credits = React.memo -> <p className="credits clearfix"> <img src={favicon()}/> {' '} <b>Coauthor</b> written by <a href="http://erikdemaine.org">Erik Demaine</a>, with help from many others. <span className="space"/> <span className="btn-group btn-group-sm pull-right"> <a className="btn btn-default" href="https://github.com/edemaine/coauthor/#coauthor">Documentation</a> <a className="btn btn-default" href="https://github.com/edemaine/coauthor/blob/main/CHANGELOG.md">Changelog</a> <a className="btn btn-default" href="https://github.com/edemaine/coauthor/issues/">Suggestions/Issues</a> <a className="btn btn-default" href="https://github.com/edemaine/coauthor/">Source Code</a> </span> </p> Credits.displayName = 'Credits' Template.registerHelper 'favicon', favicon = -> Meteor.absoluteUrl 'favicon32.png' Template.registerHelper 'couldSuper', -> canSuper routeGroupOrWild(), false Template.registerHelper 'super', -> Session.get 'super' Template.registerHelper 'globalSuper', -> Session.get('super') and canSuper wildGroup Template.layout.events 'click .superButton': (e) -> e.preventDefault() e.stopPropagation() Session.set 'super', not Session.get 'super' 'submit .searchForm': (e, t) -> e.preventDefault() e.stopPropagation() search = t.find('.searchText').value unless search # empty query = clear search -> go to group page if routeGroupOrWild() == wildGroup Router.go 'frontpage' else Router.go 'group', group: routeGroup() else Router.go resolveSlash Router.path 'search', protectSlash group: routeGroupOrWild() search: search 0: '*' 1: '*' 2: '*' 3: '*' 4: '*' 5: '*' 6: '*' 7: '*' 8: '*' 9: '*' 'dragstart a.author': (e) -> username = e.target.getAttribute 'data-username' dataTransfer = e.originalEvent.dataTransfer dataTransfer.effectAllowed = 'linkCopy' dataTransfer.setData 'text/plain', e.target.getAttribute 'href' dataTransfer.setData 'application/coauthor-username', username 'dragenter a.author': (e) -> e.preventDefault() e.stopPropagation() 'dragover a.author': (e) -> e.preventDefault() e.stopPropagation() Template.footer.helpers showFooter: -> return true for own key of Session.get 'uploading' # eslint-disable-line coffee/no-unused-vars return true if Session.get 'migrate' Template.migrate.helpers migrate: -> Session.get 'migrate' Template.uploadProgress.helpers uploading: -> value for own key, value of Session.get 'uploading'
92482
import React from 'react' linkToRoutes = since: true live: true author: true tag: true stats: true users: true settings: true search: true # IronRouter trims leading and trailing /s and combines # consecutive /s, so quote them protectSlash = (params) -> params.search = params.search.replace /\//g, '%SLASH%' if params.search? params resolveSlash = (url) -> url?.replace /%25SLASH%25/g, '%2F' Template.layout.onRendered -> ## In case Coauthor is mounted within a subdirectory, update favicon paths document.getElementById('iconIco').href = Meteor.absoluteUrl 'favicon.ico' document.getElementById('iconPNG').href = Meteor.absoluteUrl 'favicon32.png' ## Create Google font without italic definition to get slanted (fake-italic) ## version for \textsl support. ## See https://stackoverflow.com/questions/11042330/force-the-browser-to-use-faux-italic-oblique-and-not-the-real-italic for child in document.head.children if child.tagName == 'LINK' and child.href.match /fonts.googleapis.com/ rules = (rule for rule in child.sheet.cssRules) ## copy before modifying for rule in rules if rule.style.fontStyle == 'normal' ## skip italic definitions child.sheet.insertRule ( rule.cssText.replace /font-family:\s*/i, '$&Slant' ), child.sheet.cssRules.length ## append break Template.layout.helpers activeGroup: -> if routeGroup() == @name 'active' else '' inUsers: -> (Router.current().route?.getName() ? '')[...5] == 'users' linkToUsers: -> if (message = routeMessage()) pathFor 'users.message', group: routeGroupOrWild() message: message2root message else pathFor 'users', group: routeGroupOrWild() linkToUsersExit: -> if (message = routeMessage()) pathFor 'message', group: routeGroupOrWild() message: message else pathFor 'group', group: routeGroupOrWild() linkToGroup: -> router = Router.current() route = Router.current().route?.getName() if linkToRoutes[route] resolveSlash pathFor route, protectSlash _.extend _.omit(router.params, 'length'), group: @name else pathFor 'group', group: @name creditsWide: -> Router.current().route?.getName() != 'message' export Credits = React.memo -> <p className="credits clearfix"> <img src={favicon()}/> {' '} <b>Coauthor</b> written by <a href="http://erikdemaine.org"><NAME></a>, with help from many others. <span className="space"/> <span className="btn-group btn-group-sm pull-right"> <a className="btn btn-default" href="https://github.com/edemaine/coauthor/#coauthor">Documentation</a> <a className="btn btn-default" href="https://github.com/edemaine/coauthor/blob/main/CHANGELOG.md">Changelog</a> <a className="btn btn-default" href="https://github.com/edemaine/coauthor/issues/">Suggestions/Issues</a> <a className="btn btn-default" href="https://github.com/edemaine/coauthor/">Source Code</a> </span> </p> Credits.displayName = 'Credits' Template.registerHelper 'favicon', favicon = -> Meteor.absoluteUrl 'favicon32.png' Template.registerHelper 'couldSuper', -> canSuper routeGroupOrWild(), false Template.registerHelper 'super', -> Session.get 'super' Template.registerHelper 'globalSuper', -> Session.get('super') and canSuper wildGroup Template.layout.events 'click .superButton': (e) -> e.preventDefault() e.stopPropagation() Session.set 'super', not Session.get 'super' 'submit .searchForm': (e, t) -> e.preventDefault() e.stopPropagation() search = t.find('.searchText').value unless search # empty query = clear search -> go to group page if routeGroupOrWild() == wildGroup Router.go 'frontpage' else Router.go 'group', group: routeGroup() else Router.go resolveSlash Router.path 'search', protectSlash group: routeGroupOrWild() search: search 0: '*' 1: '*' 2: '*' 3: '*' 4: '*' 5: '*' 6: '*' 7: '*' 8: '*' 9: '*' 'dragstart a.author': (e) -> username = e.target.getAttribute 'data-username' dataTransfer = e.originalEvent.dataTransfer dataTransfer.effectAllowed = 'linkCopy' dataTransfer.setData 'text/plain', e.target.getAttribute 'href' dataTransfer.setData 'application/coauthor-username', username 'dragenter a.author': (e) -> e.preventDefault() e.stopPropagation() 'dragover a.author': (e) -> e.preventDefault() e.stopPropagation() Template.footer.helpers showFooter: -> return true for own key of Session.get 'uploading' # eslint-disable-line coffee/no-unused-vars return true if Session.get 'migrate' Template.migrate.helpers migrate: -> Session.get 'migrate' Template.uploadProgress.helpers uploading: -> value for own key, value of Session.get 'uploading'
true
import React from 'react' linkToRoutes = since: true live: true author: true tag: true stats: true users: true settings: true search: true # IronRouter trims leading and trailing /s and combines # consecutive /s, so quote them protectSlash = (params) -> params.search = params.search.replace /\//g, '%SLASH%' if params.search? params resolveSlash = (url) -> url?.replace /%25SLASH%25/g, '%2F' Template.layout.onRendered -> ## In case Coauthor is mounted within a subdirectory, update favicon paths document.getElementById('iconIco').href = Meteor.absoluteUrl 'favicon.ico' document.getElementById('iconPNG').href = Meteor.absoluteUrl 'favicon32.png' ## Create Google font without italic definition to get slanted (fake-italic) ## version for \textsl support. ## See https://stackoverflow.com/questions/11042330/force-the-browser-to-use-faux-italic-oblique-and-not-the-real-italic for child in document.head.children if child.tagName == 'LINK' and child.href.match /fonts.googleapis.com/ rules = (rule for rule in child.sheet.cssRules) ## copy before modifying for rule in rules if rule.style.fontStyle == 'normal' ## skip italic definitions child.sheet.insertRule ( rule.cssText.replace /font-family:\s*/i, '$&Slant' ), child.sheet.cssRules.length ## append break Template.layout.helpers activeGroup: -> if routeGroup() == @name 'active' else '' inUsers: -> (Router.current().route?.getName() ? '')[...5] == 'users' linkToUsers: -> if (message = routeMessage()) pathFor 'users.message', group: routeGroupOrWild() message: message2root message else pathFor 'users', group: routeGroupOrWild() linkToUsersExit: -> if (message = routeMessage()) pathFor 'message', group: routeGroupOrWild() message: message else pathFor 'group', group: routeGroupOrWild() linkToGroup: -> router = Router.current() route = Router.current().route?.getName() if linkToRoutes[route] resolveSlash pathFor route, protectSlash _.extend _.omit(router.params, 'length'), group: @name else pathFor 'group', group: @name creditsWide: -> Router.current().route?.getName() != 'message' export Credits = React.memo -> <p className="credits clearfix"> <img src={favicon()}/> {' '} <b>Coauthor</b> written by <a href="http://erikdemaine.org">PI:NAME:<NAME>END_PI</a>, with help from many others. <span className="space"/> <span className="btn-group btn-group-sm pull-right"> <a className="btn btn-default" href="https://github.com/edemaine/coauthor/#coauthor">Documentation</a> <a className="btn btn-default" href="https://github.com/edemaine/coauthor/blob/main/CHANGELOG.md">Changelog</a> <a className="btn btn-default" href="https://github.com/edemaine/coauthor/issues/">Suggestions/Issues</a> <a className="btn btn-default" href="https://github.com/edemaine/coauthor/">Source Code</a> </span> </p> Credits.displayName = 'Credits' Template.registerHelper 'favicon', favicon = -> Meteor.absoluteUrl 'favicon32.png' Template.registerHelper 'couldSuper', -> canSuper routeGroupOrWild(), false Template.registerHelper 'super', -> Session.get 'super' Template.registerHelper 'globalSuper', -> Session.get('super') and canSuper wildGroup Template.layout.events 'click .superButton': (e) -> e.preventDefault() e.stopPropagation() Session.set 'super', not Session.get 'super' 'submit .searchForm': (e, t) -> e.preventDefault() e.stopPropagation() search = t.find('.searchText').value unless search # empty query = clear search -> go to group page if routeGroupOrWild() == wildGroup Router.go 'frontpage' else Router.go 'group', group: routeGroup() else Router.go resolveSlash Router.path 'search', protectSlash group: routeGroupOrWild() search: search 0: '*' 1: '*' 2: '*' 3: '*' 4: '*' 5: '*' 6: '*' 7: '*' 8: '*' 9: '*' 'dragstart a.author': (e) -> username = e.target.getAttribute 'data-username' dataTransfer = e.originalEvent.dataTransfer dataTransfer.effectAllowed = 'linkCopy' dataTransfer.setData 'text/plain', e.target.getAttribute 'href' dataTransfer.setData 'application/coauthor-username', username 'dragenter a.author': (e) -> e.preventDefault() e.stopPropagation() 'dragover a.author': (e) -> e.preventDefault() e.stopPropagation() Template.footer.helpers showFooter: -> return true for own key of Session.get 'uploading' # eslint-disable-line coffee/no-unused-vars return true if Session.get 'migrate' Template.migrate.helpers migrate: -> Session.get 'migrate' Template.uploadProgress.helpers uploading: -> value for own key, value of Session.get 'uploading'
[ { "context": " when 'startBufferRow'\n key = 'startRow'\n when 'endBufferRow'\n key = 'end", "end": 32292, "score": 0.522956371307373, "start": 32289, "tag": "KEY", "value": "Row" }, { "context": " when 'startScreenRow'\n key = 'startRow'\n...
src/display-buffer.coffee
melvinvarkey/atom
0
_ = require 'underscore-plus' {Emitter} = require 'emissary' guid = require 'guid' Serializable = require 'serializable' {Model} = require 'theorist' {Point, Range} = require 'text-buffer' TokenizedBuffer = require './tokenized-buffer' RowMap = require './row-map' Fold = require './fold' Token = require './token' Decoration = require './decoration' DisplayBufferMarker = require './display-buffer-marker' class BufferToScreenConversionError extends Error constructor: (@message, @metadata) -> super Error.captureStackTrace(this, BufferToScreenConversionError) module.exports = class DisplayBuffer extends Model Serializable.includeInto(this) @properties manageScrollPosition: false softWrap: null editorWidthInChars: null lineHeightInPixels: null defaultCharWidth: null height: null width: null scrollTop: 0 scrollLeft: 0 scrollWidth: 0 verticalScrollbarWidth: 15 horizontalScrollbarHeight: 15 verticalScrollMargin: 2 horizontalScrollMargin: 6 scopedCharacterWidthsChangeCount: 0 constructor: ({tabLength, @editorWidthInChars, @tokenizedBuffer, buffer, @invisibles}={}) -> super @softWrap ?= atom.config.get('editor.softWrap') ? false @tokenizedBuffer ?= new TokenizedBuffer({tabLength, buffer, @invisibles}) @buffer = @tokenizedBuffer.buffer @charWidthsByScope = {} @markers = {} @foldsByMarkerId = {} @decorationsById = {} @decorationsByMarkerId = {} @decorationMarkerChangedSubscriptions = {} @decorationMarkerDestroyedSubscriptions = {} @updateAllScreenLines() @createFoldForMarker(marker) for marker in @buffer.findMarkers(@getFoldMarkerAttributes()) @subscribe @tokenizedBuffer, 'grammar-changed', (grammar) => @emit 'grammar-changed', grammar @subscribe @tokenizedBuffer, 'tokenized', => @emit 'tokenized' @subscribe @tokenizedBuffer, 'changed', @handleTokenizedBufferChange @subscribe @buffer, 'markers-updated', @handleBufferMarkersUpdated @subscribe @buffer, 'marker-created', @handleBufferMarkerCreated @subscribe @$softWrap, (softWrap) => @emit 'soft-wrap-changed', softWrap @updateWrappedScreenLines() @subscribe atom.config.observe 'editor.preferredLineLength', callNow: false, => @updateWrappedScreenLines() if @softWrap and atom.config.get('editor.softWrapAtPreferredLineLength') @subscribe atom.config.observe 'editor.softWrapAtPreferredLineLength', callNow: false, => @updateWrappedScreenLines() if @softWrap serializeParams: -> id: @id softWrap: @softWrap editorWidthInChars: @editorWidthInChars scrollTop: @scrollTop scrollLeft: @scrollLeft tokenizedBuffer: @tokenizedBuffer.serialize() invisibles: _.clone(@invisibles) deserializeParams: (params) -> params.tokenizedBuffer = TokenizedBuffer.deserialize(params.tokenizedBuffer) params copy: -> newDisplayBuffer = new DisplayBuffer({@buffer, tabLength: @getTabLength(), @invisibles}) newDisplayBuffer.setScrollTop(@getScrollTop()) newDisplayBuffer.setScrollLeft(@getScrollLeft()) for marker in @findMarkers(displayBufferId: @id) marker.copy(displayBufferId: newDisplayBuffer.id) newDisplayBuffer updateAllScreenLines: -> @maxLineLength = 0 @screenLines = [] @rowMap = new RowMap @updateScreenLines(0, @buffer.getLineCount(), null, suppressChangeEvent: true) emitChanged: (eventProperties, refreshMarkers=true) -> if refreshMarkers @pauseMarkerObservers() @refreshMarkerScreenPositions() @emit 'changed', eventProperties @resumeMarkerObservers() updateWrappedScreenLines: -> start = 0 end = @getLastRow() @updateAllScreenLines() screenDelta = @getLastRow() - end bufferDelta = 0 @emitChanged({ start, end, screenDelta, bufferDelta }) # Sets the visibility of the tokenized buffer. # # visible - A {Boolean} indicating of the tokenized buffer is shown setVisible: (visible) -> @tokenizedBuffer.setVisible(visible) getVerticalScrollMargin: -> @verticalScrollMargin setVerticalScrollMargin: (@verticalScrollMargin) -> @verticalScrollMargin getHorizontalScrollMargin: -> @horizontalScrollMargin setHorizontalScrollMargin: (@horizontalScrollMargin) -> @horizontalScrollMargin getHorizontalScrollbarHeight: -> @horizontalScrollbarHeight setHorizontalScrollbarHeight: (@horizontalScrollbarHeight) -> @horizontalScrollbarHeight getVerticalScrollbarWidth: -> @verticalScrollbarWidth setVerticalScrollbarWidth: (@verticalScrollbarWidth) -> @verticalScrollbarWidth getHeight: -> if @height? @height else if @horizontallyScrollable() @getScrollHeight() + @getHorizontalScrollbarHeight() else @getScrollHeight() setHeight: (@height) -> @height getClientHeight: (reentrant) -> if @horizontallyScrollable(reentrant) @getHeight() - @getHorizontalScrollbarHeight() else @getHeight() getClientWidth: (reentrant) -> if @verticallyScrollable(reentrant) @getWidth() - @getVerticalScrollbarWidth() else @getWidth() horizontallyScrollable: (reentrant) -> return false unless @width? return false if @getSoftWrap() if reentrant @getScrollWidth() > @getWidth() else @getScrollWidth() > @getClientWidth(true) verticallyScrollable: (reentrant) -> return false unless @height? if reentrant @getScrollHeight() > @getHeight() else @getScrollHeight() > @getClientHeight(true) getWidth: -> if @width? @width else if @verticallyScrollable() @getScrollWidth() + @getVerticalScrollbarWidth() else @getScrollWidth() setWidth: (newWidth) -> oldWidth = @width @width = newWidth @updateWrappedScreenLines() if newWidth isnt oldWidth and @softWrap @setScrollTop(@getScrollTop()) # Ensure scrollTop is still valid in case horizontal scrollbar disappeared @width getScrollTop: -> @scrollTop setScrollTop: (scrollTop) -> if @manageScrollPosition @scrollTop = Math.round(Math.max(0, Math.min(@getMaxScrollTop(), scrollTop))) else @scrollTop = Math.round(scrollTop) getMaxScrollTop: -> @getScrollHeight() - @getClientHeight() getScrollBottom: -> @scrollTop + @height setScrollBottom: (scrollBottom) -> @setScrollTop(scrollBottom - @getClientHeight()) @getScrollBottom() getScrollLeft: -> @scrollLeft setScrollLeft: (scrollLeft) -> if @manageScrollPosition @scrollLeft = Math.round(Math.max(0, Math.min(@getScrollWidth() - @getClientWidth(), scrollLeft))) @scrollLeft else @scrollLeft = Math.round(scrollLeft) getMaxScrollLeft: -> @getScrollWidth() - @getClientWidth() getScrollRight: -> @scrollLeft + @width setScrollRight: (scrollRight) -> @setScrollLeft(scrollRight - @width) @getScrollRight() getLineHeightInPixels: -> @lineHeightInPixels setLineHeightInPixels: (@lineHeightInPixels) -> @lineHeightInPixels getDefaultCharWidth: -> @defaultCharWidth setDefaultCharWidth: (defaultCharWidth) -> if defaultCharWidth isnt @defaultCharWidth @defaultCharWidth = defaultCharWidth @computeScrollWidth() defaultCharWidth getCursorWidth: -> 1 getScopedCharWidth: (scopeNames, char) -> @getScopedCharWidths(scopeNames)[char] getScopedCharWidths: (scopeNames) -> scope = @charWidthsByScope for scopeName in scopeNames scope[scopeName] ?= {} scope = scope[scopeName] scope.charWidths ?= {} scope.charWidths batchCharacterMeasurement: (fn) -> oldChangeCount = @scopedCharacterWidthsChangeCount @batchingCharacterMeasurement = true fn() @batchingCharacterMeasurement = false @characterWidthsChanged() if oldChangeCount isnt @scopedCharacterWidthsChangeCount setScopedCharWidth: (scopeNames, char, width) -> @getScopedCharWidths(scopeNames)[char] = width @scopedCharacterWidthsChangeCount++ @characterWidthsChanged() unless @batchingCharacterMeasurement characterWidthsChanged: -> @computeScrollWidth() @emit 'character-widths-changed', @scopedCharacterWidthsChangeCount clearScopedCharWidths: -> @charWidthsByScope = {} getScrollHeight: -> return 0 unless @getLineHeightInPixels() > 0 @getLineCount() * @getLineHeightInPixels() getScrollWidth: -> @scrollWidth getVisibleRowRange: -> return [0, 0] unless @getLineHeightInPixels() > 0 heightInLines = Math.ceil(@getHeight() / @getLineHeightInPixels()) + 1 startRow = Math.floor(@getScrollTop() / @getLineHeightInPixels()) endRow = Math.min(@getLineCount(), startRow + heightInLines) [startRow, endRow] intersectsVisibleRowRange: (startRow, endRow) -> [visibleStart, visibleEnd] = @getVisibleRowRange() not (endRow <= visibleStart or visibleEnd <= startRow) selectionIntersectsVisibleRowRange: (selection) -> {start, end} = selection.getScreenRange() @intersectsVisibleRowRange(start.row, end.row + 1) scrollToScreenRange: (screenRange, options) -> verticalScrollMarginInPixels = @getVerticalScrollMargin() * @getLineHeightInPixels() horizontalScrollMarginInPixels = @getHorizontalScrollMargin() * @getDefaultCharWidth() {top, left, height, width} = @pixelRectForScreenRange(screenRange) bottom = top + height right = left + width if options?.center desiredScrollCenter = top + height / 2 unless @getScrollTop() < desiredScrollCenter < @getScrollBottom() desiredScrollTop = desiredScrollCenter - @getHeight() / 2 desiredScrollBottom = desiredScrollCenter + @getHeight() / 2 else desiredScrollTop = top - verticalScrollMarginInPixels desiredScrollBottom = bottom + verticalScrollMarginInPixels desiredScrollLeft = left - horizontalScrollMarginInPixels desiredScrollRight = right + horizontalScrollMarginInPixels if desiredScrollTop < @getScrollTop() @setScrollTop(desiredScrollTop) else if desiredScrollBottom > @getScrollBottom() @setScrollBottom(desiredScrollBottom) if desiredScrollLeft < @getScrollLeft() @setScrollLeft(desiredScrollLeft) else if desiredScrollRight > @getScrollRight() @setScrollRight(desiredScrollRight) scrollToScreenPosition: (screenPosition, options) -> @scrollToScreenRange(new Range(screenPosition, screenPosition), options) scrollToBufferPosition: (bufferPosition, options) -> @scrollToScreenPosition(@screenPositionForBufferPosition(bufferPosition), options) pixelRectForScreenRange: (screenRange) -> if screenRange.end.row > screenRange.start.row top = @pixelPositionForScreenPosition(screenRange.start).top left = 0 height = (screenRange.end.row - screenRange.start.row + 1) * @getLineHeightInPixels() width = @getScrollWidth() else {top, left} = @pixelPositionForScreenPosition(screenRange.start, false) height = @getLineHeightInPixels() width = @pixelPositionForScreenPosition(screenRange.end, false).left - left {top, left, width, height} # Retrieves the current tab length. # # Returns a {Number}. getTabLength: -> @tokenizedBuffer.getTabLength() # Specifies the tab length. # # tabLength - A {Number} that defines the new tab length. setTabLength: (tabLength) -> @tokenizedBuffer.setTabLength(tabLength) setInvisibles: (@invisibles) -> @tokenizedBuffer.setInvisibles(@invisibles) # Deprecated: Use the softWrap property directly setSoftWrap: (@softWrap) -> @softWrap # Deprecated: Use the softWrap property directly getSoftWrap: -> @softWrap # Set the number of characters that fit horizontally in the editor. # # editorWidthInChars - A {Number} of characters. setEditorWidthInChars: (editorWidthInChars) -> if editorWidthInChars > 0 previousWidthInChars = @editorWidthInChars @editorWidthInChars = editorWidthInChars if editorWidthInChars isnt previousWidthInChars and @softWrap @updateWrappedScreenLines() # Returns the editor width in characters for soft wrap. getEditorWidthInChars: -> width = @width ? @getScrollWidth() width -= @getVerticalScrollbarWidth() if width? and @defaultCharWidth > 0 Math.floor(width / @defaultCharWidth) else @editorWidthInChars getSoftWrapColumn: -> if atom.config.get('editor.softWrapAtPreferredLineLength') Math.min(@getEditorWidthInChars(), atom.config.getPositiveInt('editor.preferredLineLength', @getEditorWidthInChars())) else @getEditorWidthInChars() # Gets the screen line for the given screen row. # # * `screenRow` - A {Number} indicating the screen row. # # Returns {TokenizedLine} tokenizedLineForScreenRow: (screenRow) -> @screenLines[screenRow] # Gets the screen lines for the given screen row range. # # startRow - A {Number} indicating the beginning screen row. # endRow - A {Number} indicating the ending screen row. # # Returns an {Array} of {TokenizedLine}s. tokenizedLinesForScreenRows: (startRow, endRow) -> @screenLines[startRow..endRow] # Gets all the screen lines. # # Returns an {Array} of {TokenizedLine}s. getTokenizedLines: -> new Array(@screenLines...) indentLevelForLine: (line) -> @tokenizedBuffer.indentLevelForLine(line) # Given starting and ending screen rows, this returns an array of the # buffer rows corresponding to every screen row in the range # # startScreenRow - The screen row {Number} to start at # endScreenRow - The screen row {Number} to end at (default: the last screen row) # # Returns an {Array} of buffer rows as {Numbers}s. bufferRowsForScreenRows: (startScreenRow, endScreenRow) -> for screenRow in [startScreenRow..endScreenRow] @rowMap.bufferRowRangeForScreenRow(screenRow)[0] # Creates a new fold between two row numbers. # # startRow - The row {Number} to start folding at # endRow - The row {Number} to end the fold # # Returns the new {Fold}. createFold: (startRow, endRow) -> foldMarker = @findFoldMarker({startRow, endRow}) ? @buffer.markRange([[startRow, 0], [endRow, Infinity]], @getFoldMarkerAttributes()) @foldForMarker(foldMarker) isFoldedAtBufferRow: (bufferRow) -> @largestFoldContainingBufferRow(bufferRow)? isFoldedAtScreenRow: (screenRow) -> @largestFoldContainingBufferRow(@bufferRowForScreenRow(screenRow))? # Destroys the fold with the given id destroyFoldWithId: (id) -> @foldsByMarkerId[id]?.destroy() # Removes any folds found that contain the given buffer row. # # bufferRow - The buffer row {Number} to check against unfoldBufferRow: (bufferRow) -> fold.destroy() for fold in @foldsContainingBufferRow(bufferRow) # Given a buffer row, this returns the largest fold that starts there. # # Largest is defined as the fold whose difference between its start and end points # are the greatest. # # bufferRow - A {Number} indicating the buffer row # # Returns a {Fold} or null if none exists. largestFoldStartingAtBufferRow: (bufferRow) -> @foldsStartingAtBufferRow(bufferRow)[0] # Public: Given a buffer row, this returns all folds that start there. # # bufferRow - A {Number} indicating the buffer row # # Returns an {Array} of {Fold}s. foldsStartingAtBufferRow: (bufferRow) -> for marker in @findFoldMarkers(startRow: bufferRow) @foldForMarker(marker) # Given a screen row, this returns the largest fold that starts there. # # Largest is defined as the fold whose difference between its start and end points # are the greatest. # # screenRow - A {Number} indicating the screen row # # Returns a {Fold}. largestFoldStartingAtScreenRow: (screenRow) -> @largestFoldStartingAtBufferRow(@bufferRowForScreenRow(screenRow)) # Given a buffer row, this returns the largest fold that includes it. # # Largest is defined as the fold whose difference between its start and end rows # is the greatest. # # bufferRow - A {Number} indicating the buffer row # # Returns a {Fold}. largestFoldContainingBufferRow: (bufferRow) -> @foldsContainingBufferRow(bufferRow)[0] # Returns the folds in the given row range (exclusive of end row) that are # not contained by any other folds. outermostFoldsInBufferRowRange: (startRow, endRow) -> @findFoldMarkers(containedInRange: [[startRow, 0], [endRow, 0]]) .map (marker) => @foldForMarker(marker) .filter (fold) -> not fold.isInsideLargerFold() # Public: Given a buffer row, this returns folds that include it. # # # bufferRow - A {Number} indicating the buffer row # # Returns an {Array} of {Fold}s. foldsContainingBufferRow: (bufferRow) -> for marker in @findFoldMarkers(intersectsRow: bufferRow) @foldForMarker(marker) # Given a buffer row, this converts it into a screen row. # # bufferRow - A {Number} representing a buffer row # # Returns a {Number}. screenRowForBufferRow: (bufferRow) -> @rowMap.screenRowRangeForBufferRow(bufferRow)[0] lastScreenRowForBufferRow: (bufferRow) -> @rowMap.screenRowRangeForBufferRow(bufferRow)[1] - 1 # Given a screen row, this converts it into a buffer row. # # screenRow - A {Number} representing a screen row # # Returns a {Number}. bufferRowForScreenRow: (screenRow) -> @rowMap.bufferRowRangeForScreenRow(screenRow)[0] # Given a buffer range, this converts it into a screen position. # # bufferRange - The {Range} to convert # # Returns a {Range}. screenRangeForBufferRange: (bufferRange) -> bufferRange = Range.fromObject(bufferRange) start = @screenPositionForBufferPosition(bufferRange.start) end = @screenPositionForBufferPosition(bufferRange.end) new Range(start, end) # Given a screen range, this converts it into a buffer position. # # screenRange - The {Range} to convert # # Returns a {Range}. bufferRangeForScreenRange: (screenRange) -> screenRange = Range.fromObject(screenRange) start = @bufferPositionForScreenPosition(screenRange.start) end = @bufferPositionForScreenPosition(screenRange.end) new Range(start, end) pixelRangeForScreenRange: (screenRange, clip=true) -> {start, end} = Range.fromObject(screenRange) {start: @pixelPositionForScreenPosition(start, clip), end: @pixelPositionForScreenPosition(end, clip)} pixelPositionForScreenPosition: (screenPosition, clip=true) -> screenPosition = Point.fromObject(screenPosition) screenPosition = @clipScreenPosition(screenPosition) if clip targetRow = screenPosition.row targetColumn = screenPosition.column defaultCharWidth = @defaultCharWidth top = targetRow * @lineHeightInPixels left = 0 column = 0 for token in @tokenizedLineForScreenRow(targetRow).tokens charWidths = @getScopedCharWidths(token.scopes) for char in token.value return {top, left} if column is targetColumn left += charWidths[char] ? defaultCharWidth unless char is '\0' column++ {top, left} screenPositionForPixelPosition: (pixelPosition) -> targetTop = pixelPosition.top targetLeft = pixelPosition.left defaultCharWidth = @defaultCharWidth row = Math.floor(targetTop / @getLineHeightInPixels()) row = Math.min(row, @getLastRow()) row = Math.max(0, row) left = 0 column = 0 for token in @tokenizedLineForScreenRow(row).tokens charWidths = @getScopedCharWidths(token.scopes) for char in token.value charWidth = charWidths[char] ? defaultCharWidth break if targetLeft <= left + (charWidth / 2) left += charWidth column++ new Point(row, column) pixelPositionForBufferPosition: (bufferPosition) -> @pixelPositionForScreenPosition(@screenPositionForBufferPosition(bufferPosition)) # Gets the number of screen lines. # # Returns a {Number}. getLineCount: -> @screenLines.length # Gets the number of the last screen line. # # Returns a {Number}. getLastRow: -> @getLineCount() - 1 # Gets the length of the longest screen line. # # Returns a {Number}. getMaxLineLength: -> @maxLineLength # Gets the row number of the longest screen line. # # Return a {} getLongestScreenRow: -> @longestScreenRow # Given a buffer position, this converts it into a screen position. # # bufferPosition - An object that represents a buffer position. It can be either # an {Object} (`{row, column}`), {Array} (`[row, column]`), or {Point} # options - A hash of options with the following keys: # wrapBeyondNewlines: # wrapAtSoftNewlines: # # Returns a {Point}. screenPositionForBufferPosition: (bufferPosition, options) -> { row, column } = @buffer.clipPosition(bufferPosition) [startScreenRow, endScreenRow] = @rowMap.screenRowRangeForBufferRow(row) for screenRow in [startScreenRow...endScreenRow] screenLine = @screenLines[screenRow] unless screenLine? throw new BufferToScreenConversionError "No screen line exists when converting buffer row to screen row", softWrapEnabled: @getSoftWrap() foldCount: @findFoldMarkers().length lastBufferRow: @buffer.getLastRow() lastScreenRow: @getLastRow() maxBufferColumn = screenLine.getMaxBufferColumn() if screenLine.isSoftWrapped() and column > maxBufferColumn continue else if column <= maxBufferColumn screenColumn = screenLine.screenColumnForBufferColumn(column) else screenColumn = Infinity break @clipScreenPosition([screenRow, screenColumn], options) # Given a buffer position, this converts it into a screen position. # # screenPosition - An object that represents a buffer position. It can be either # an {Object} (`{row, column}`), {Array} (`[row, column]`), or {Point} # options - A hash of options with the following keys: # wrapBeyondNewlines: # wrapAtSoftNewlines: # # Returns a {Point}. bufferPositionForScreenPosition: (screenPosition, options) -> { row, column } = @clipScreenPosition(Point.fromObject(screenPosition), options) [bufferRow] = @rowMap.bufferRowRangeForScreenRow(row) new Point(bufferRow, @screenLines[row].bufferColumnForScreenColumn(column)) # Retrieves the grammar's token scopes for a buffer position. # # bufferPosition - A {Point} in the {TextBuffer} # # Returns an {Array} of {String}s. scopesForBufferPosition: (bufferPosition) -> @tokenizedBuffer.scopesForPosition(bufferPosition) bufferRangeForScopeAtPosition: (selector, position) -> @tokenizedBuffer.bufferRangeForScopeAtPosition(selector, position) # Retrieves the grammar's token for a buffer position. # # bufferPosition - A {Point} in the {TextBuffer}. # # Returns a {Token}. tokenForBufferPosition: (bufferPosition) -> @tokenizedBuffer.tokenForPosition(bufferPosition) # Get the grammar for this buffer. # # Returns the current {Grammar} or the {NullGrammar}. getGrammar: -> @tokenizedBuffer.grammar # Sets the grammar for the buffer. # # grammar - Sets the new grammar rules setGrammar: (grammar) -> @tokenizedBuffer.setGrammar(grammar) # Reloads the current grammar. reloadGrammar: -> @tokenizedBuffer.reloadGrammar() # Given a position, this clips it to a real position. # # For example, if `position`'s row exceeds the row count of the buffer, # or if its column goes beyond a line's length, this "sanitizes" the value # to a real position. # # position - The {Point} to clip # options - A hash with the following values: # wrapBeyondNewlines: if `true`, continues wrapping past newlines # wrapAtSoftNewlines: if `true`, continues wrapping past soft newlines # screenLine: if `true`, indicates that you're using a line number, not a row number # # Returns the new, clipped {Point}. Note that this could be the same as `position` if no clipping was performed. clipScreenPosition: (screenPosition, options={}) -> { wrapBeyondNewlines, wrapAtSoftNewlines } = options { row, column } = Point.fromObject(screenPosition) if row < 0 row = 0 column = 0 else if row > @getLastRow() row = @getLastRow() column = Infinity else if column < 0 column = 0 screenLine = @screenLines[row] maxScreenColumn = screenLine.getMaxScreenColumn() if screenLine.isSoftWrapped() and column >= maxScreenColumn if wrapAtSoftNewlines row++ column = 0 else column = screenLine.clipScreenColumn(maxScreenColumn - 1) else if wrapBeyondNewlines and column > maxScreenColumn and row < @getLastRow() row++ column = 0 else column = screenLine.clipScreenColumn(column, options) new Point(row, column) # Given a line, finds the point where it would wrap. # # line - The {String} to check # softWrapColumn - The {Number} where you want soft wrapping to occur # # Returns a {Number} representing the `line` position where the wrap would take place. # Returns `null` if a wrap wouldn't occur. findWrapColumn: (line, softWrapColumn=@getSoftWrapColumn()) -> return unless @softWrap return unless line.length > softWrapColumn if /\s/.test(line[softWrapColumn]) # search forward for the start of a word past the boundary for column in [softWrapColumn..line.length] return column if /\S/.test(line[column]) return line.length else # search backward for the start of the word on the boundary for column in [softWrapColumn..0] return column + 1 if /\s/.test(line[column]) return softWrapColumn # Calculates a {Range} representing the start of the {TextBuffer} until the end. # # Returns a {Range}. rangeForAllLines: -> new Range([0, 0], @clipScreenPosition([Infinity, Infinity])) decorationForId: (id) -> @decorationsById[id] decorationsForScreenRowRange: (startScreenRow, endScreenRow) -> decorationsByMarkerId = {} for marker in @findMarkers(intersectsScreenRowRange: [startScreenRow, endScreenRow]) if decorations = @decorationsByMarkerId[marker.id] decorationsByMarkerId[marker.id] = decorations decorationsByMarkerId decorateMarker: (marker, decorationParams) -> marker = @getMarker(marker.id) @decorationMarkerDestroyedSubscriptions[marker.id] ?= @subscribe marker, 'destroyed', => @removeAllDecorationsForMarker(marker) @decorationMarkerChangedSubscriptions[marker.id] ?= @subscribe marker, 'changed', (event) => decorations = @decorationsByMarkerId[marker.id] # Why check existence? Markers may get destroyed or decorations removed # in the change handler. Bookmarks does this. if decorations? for decoration in decorations @emit 'decoration-changed', marker, decoration, event decoration = new Decoration(marker, this, decorationParams) @decorationsByMarkerId[marker.id] ?= [] @decorationsByMarkerId[marker.id].push(decoration) @decorationsById[decoration.id] = decoration @emit 'decoration-added', marker, decoration decoration removeDecoration: (decoration) -> {marker} = decoration return unless decorations = @decorationsByMarkerId[marker.id] index = decorations.indexOf(decoration) if index > -1 decorations.splice(index, 1) delete @decorationsById[decoration.id] @emit 'decoration-removed', marker, decoration @removedAllMarkerDecorations(marker) if decorations.length is 0 removeAllDecorationsForMarker: (marker) -> decorations = @decorationsByMarkerId[marker.id].slice() for decoration in decorations @emit 'decoration-removed', marker, decoration @removedAllMarkerDecorations(marker) removedAllMarkerDecorations: (marker) -> @decorationMarkerChangedSubscriptions[marker.id].off() @decorationMarkerDestroyedSubscriptions[marker.id].off() delete @decorationsByMarkerId[marker.id] delete @decorationMarkerChangedSubscriptions[marker.id] delete @decorationMarkerDestroyedSubscriptions[marker.id] decorationUpdated: (decoration) -> @emit 'decoration-updated', decoration # Retrieves a {DisplayBufferMarker} based on its id. # # id - A {Number} representing a marker id # # Returns the {DisplayBufferMarker} (if it exists). getMarker: (id) -> unless marker = @markers[id] if bufferMarker = @buffer.getMarker(id) marker = new DisplayBufferMarker({bufferMarker, displayBuffer: this}) @markers[id] = marker marker # Retrieves the active markers in the buffer. # # Returns an {Array} of existing {DisplayBufferMarker}s. getMarkers: -> @buffer.getMarkers().map ({id}) => @getMarker(id) getMarkerCount: -> @buffer.getMarkerCount() # Public: Constructs a new marker at the given screen range. # # range - The marker {Range} (representing the distance between the head and tail) # options - Options to pass to the {Marker} constructor # # Returns a {Number} representing the new marker's ID. markScreenRange: (args...) -> bufferRange = @bufferRangeForScreenRange(args.shift()) @markBufferRange(bufferRange, args...) # Public: Constructs a new marker at the given buffer range. # # range - The marker {Range} (representing the distance between the head and tail) # options - Options to pass to the {Marker} constructor # # Returns a {Number} representing the new marker's ID. markBufferRange: (range, options) -> @getMarker(@buffer.markRange(range, options).id) # Public: Constructs a new marker at the given screen position. # # range - The marker {Range} (representing the distance between the head and tail) # options - Options to pass to the {Marker} constructor # # Returns a {Number} representing the new marker's ID. markScreenPosition: (screenPosition, options) -> @markBufferPosition(@bufferPositionForScreenPosition(screenPosition), options) # Public: Constructs a new marker at the given buffer position. # # range - The marker {Range} (representing the distance between the head and tail) # options - Options to pass to the {Marker} constructor # # Returns a {Number} representing the new marker's ID. markBufferPosition: (bufferPosition, options) -> @getMarker(@buffer.markPosition(bufferPosition, options).id) # Public: Removes the marker with the given id. # # id - The {Number} of the ID to remove destroyMarker: (id) -> @buffer.destroyMarker(id) delete @markers[id] # Finds the first marker satisfying the given attributes # # Refer to {DisplayBuffer::findMarkers} for details. # # Returns a {DisplayBufferMarker} or null findMarker: (params) -> @findMarkers(params)[0] # Public: Find all markers satisfying a set of parameters. # # params - An {Object} containing parameters that all returned markers must # satisfy. Unreserved keys will be compared against the markers' custom # properties. There are also the following reserved keys with special # meaning for the query: # :startBufferRow - A {Number}. Only returns markers starting at this row in # buffer coordinates. # :endBufferRow - A {Number}. Only returns markers ending at this row in # buffer coordinates. # :containsBufferRange - A {Range} or range-compatible {Array}. Only returns # markers containing this range in buffer coordinates. # :containsBufferPosition - A {Point} or point-compatible {Array}. Only # returns markers containing this position in buffer coordinates. # :containedInBufferRange - A {Range} or range-compatible {Array}. Only # returns markers contained within this range. # # Returns an {Array} of {DisplayBufferMarker}s findMarkers: (params) -> params = @translateToBufferMarkerParams(params) @buffer.findMarkers(params).map (stringMarker) => @getMarker(stringMarker.id) translateToBufferMarkerParams: (params) -> bufferMarkerParams = {} for key, value of params switch key when 'startBufferRow' key = 'startRow' when 'endBufferRow' key = 'endRow' when 'startScreenRow' key = 'startRow' value = @bufferRowForScreenRow(value) when 'endScreenRow' key = 'endRow' value = @bufferRowForScreenRow(value) when 'intersectsBufferRowRange' key = 'intersectsRowRange' when 'intersectsScreenRowRange' key = 'intersectsRowRange' [startRow, endRow] = value value = [@bufferRowForScreenRow(startRow), @bufferRowForScreenRow(endRow)] when 'containsBufferRange' key = 'containsRange' when 'containsBufferPosition' key = 'containsPosition' when 'containedInBufferRange' key = 'containedInRange' when 'containedInScreenRange' key = 'containedInRange' value = @bufferRangeForScreenRange(value) when 'intersectsBufferRange' key = 'intersectsRange' when 'intersectsScreenRange' key = 'intersectsRange' value = @bufferRangeForScreenRange(value) bufferMarkerParams[key] = value bufferMarkerParams findFoldMarker: (attributes) -> @findFoldMarkers(attributes)[0] findFoldMarkers: (attributes) -> @buffer.findMarkers(@getFoldMarkerAttributes(attributes)) getFoldMarkerAttributes: (attributes={}) -> _.extend(attributes, class: 'fold', displayBufferId: @id) pauseMarkerObservers: -> marker.pauseEvents() for marker in @getMarkers() resumeMarkerObservers: -> marker.resumeEvents() for marker in @getMarkers() @emit 'markers-updated' refreshMarkerScreenPositions: -> for marker in @getMarkers() marker.notifyObservers(textChanged: false) destroyed: -> marker.unsubscribe() for marker in @getMarkers() @tokenizedBuffer.destroy() @unsubscribe() logLines: (start=0, end=@getLastRow()) -> for row in [start..end] line = @tokenizedLineForScreenRow(row).text console.log row, @bufferRowForScreenRow(row), line, line.length handleTokenizedBufferChange: (tokenizedBufferChange) => {start, end, delta, bufferChange} = tokenizedBufferChange @updateScreenLines(start, end + 1, delta, delayChangeEvent: bufferChange?) @setScrollTop(Math.min(@getScrollTop(), @getMaxScrollTop())) if @manageScrollPosition and delta < 0 updateScreenLines: (startBufferRow, endBufferRow, bufferDelta=0, options={}) -> startBufferRow = @rowMap.bufferRowRangeForBufferRow(startBufferRow)[0] endBufferRow = @rowMap.bufferRowRangeForBufferRow(endBufferRow - 1)[1] startScreenRow = @rowMap.screenRowRangeForBufferRow(startBufferRow)[0] endScreenRow = @rowMap.screenRowRangeForBufferRow(endBufferRow - 1)[1] {screenLines, regions} = @buildScreenLines(startBufferRow, endBufferRow + bufferDelta) screenDelta = screenLines.length - (endScreenRow - startScreenRow) @screenLines[startScreenRow...endScreenRow] = screenLines @rowMap.spliceRegions(startBufferRow, endBufferRow - startBufferRow, regions) @findMaxLineLength(startScreenRow, endScreenRow, screenLines, screenDelta) return if options.suppressChangeEvent changeEvent = start: startScreenRow end: endScreenRow - 1 screenDelta: screenDelta bufferDelta: bufferDelta if options.delayChangeEvent @pauseMarkerObservers() @pendingChangeEvent = changeEvent else @emitChanged(changeEvent, options.refreshMarkers) buildScreenLines: (startBufferRow, endBufferRow) -> screenLines = [] regions = [] rectangularRegion = null bufferRow = startBufferRow while bufferRow < endBufferRow tokenizedLine = @tokenizedBuffer.tokenizedLineForRow(bufferRow) if fold = @largestFoldStartingAtBufferRow(bufferRow) foldLine = tokenizedLine.copy() foldLine.fold = fold screenLines.push(foldLine) if rectangularRegion? regions.push(rectangularRegion) rectangularRegion = null foldedRowCount = fold.getBufferRowCount() regions.push(bufferRows: foldedRowCount, screenRows: 1) bufferRow += foldedRowCount else softWraps = 0 while wrapScreenColumn = @findWrapColumn(tokenizedLine.text) [wrappedLine, tokenizedLine] = tokenizedLine.softWrapAt(wrapScreenColumn) screenLines.push(wrappedLine) softWraps++ screenLines.push(tokenizedLine) if softWraps > 0 if rectangularRegion? regions.push(rectangularRegion) rectangularRegion = null regions.push(bufferRows: 1, screenRows: softWraps + 1) else rectangularRegion ?= {bufferRows: 0, screenRows: 0} rectangularRegion.bufferRows++ rectangularRegion.screenRows++ bufferRow++ if rectangularRegion? regions.push(rectangularRegion) {screenLines, regions} findMaxLineLength: (startScreenRow, endScreenRow, newScreenLines, screenDelta) -> oldMaxLineLength = @maxLineLength if startScreenRow <= @longestScreenRow < endScreenRow @longestScreenRow = 0 @maxLineLength = 0 maxLengthCandidatesStartRow = 0 maxLengthCandidates = @screenLines else @longestScreenRow += screenDelta if endScreenRow < @longestScreenRow maxLengthCandidatesStartRow = startScreenRow maxLengthCandidates = newScreenLines for screenLine, i in maxLengthCandidates screenRow = maxLengthCandidatesStartRow + i length = screenLine.text.length if length > @maxLineLength @longestScreenRow = screenRow @maxLineLength = length @computeScrollWidth() if oldMaxLineLength isnt @maxLineLength computeScrollWidth: -> @scrollWidth = @pixelPositionForScreenPosition([@longestScreenRow, @maxLineLength]).left @scrollWidth += 1 unless @getSoftWrap() @setScrollLeft(Math.min(@getScrollLeft(), @getMaxScrollLeft())) handleBufferMarkersUpdated: => if event = @pendingChangeEvent @pendingChangeEvent = null @emitChanged(event, false) handleBufferMarkerCreated: (marker) => @createFoldForMarker(marker) if marker.matchesAttributes(@getFoldMarkerAttributes()) if displayBufferMarker = @getMarker(marker.id) # The marker might have been removed in some other handler called before # this one. Only emit when the marker still exists. @emit 'marker-created', displayBufferMarker createFoldForMarker: (marker) -> @decorateMarker(marker, type: 'gutter', class: 'folded') new Fold(this, marker) foldForMarker: (marker) -> @foldsByMarkerId[marker.id]
2332
_ = require 'underscore-plus' {Emitter} = require 'emissary' guid = require 'guid' Serializable = require 'serializable' {Model} = require 'theorist' {Point, Range} = require 'text-buffer' TokenizedBuffer = require './tokenized-buffer' RowMap = require './row-map' Fold = require './fold' Token = require './token' Decoration = require './decoration' DisplayBufferMarker = require './display-buffer-marker' class BufferToScreenConversionError extends Error constructor: (@message, @metadata) -> super Error.captureStackTrace(this, BufferToScreenConversionError) module.exports = class DisplayBuffer extends Model Serializable.includeInto(this) @properties manageScrollPosition: false softWrap: null editorWidthInChars: null lineHeightInPixels: null defaultCharWidth: null height: null width: null scrollTop: 0 scrollLeft: 0 scrollWidth: 0 verticalScrollbarWidth: 15 horizontalScrollbarHeight: 15 verticalScrollMargin: 2 horizontalScrollMargin: 6 scopedCharacterWidthsChangeCount: 0 constructor: ({tabLength, @editorWidthInChars, @tokenizedBuffer, buffer, @invisibles}={}) -> super @softWrap ?= atom.config.get('editor.softWrap') ? false @tokenizedBuffer ?= new TokenizedBuffer({tabLength, buffer, @invisibles}) @buffer = @tokenizedBuffer.buffer @charWidthsByScope = {} @markers = {} @foldsByMarkerId = {} @decorationsById = {} @decorationsByMarkerId = {} @decorationMarkerChangedSubscriptions = {} @decorationMarkerDestroyedSubscriptions = {} @updateAllScreenLines() @createFoldForMarker(marker) for marker in @buffer.findMarkers(@getFoldMarkerAttributes()) @subscribe @tokenizedBuffer, 'grammar-changed', (grammar) => @emit 'grammar-changed', grammar @subscribe @tokenizedBuffer, 'tokenized', => @emit 'tokenized' @subscribe @tokenizedBuffer, 'changed', @handleTokenizedBufferChange @subscribe @buffer, 'markers-updated', @handleBufferMarkersUpdated @subscribe @buffer, 'marker-created', @handleBufferMarkerCreated @subscribe @$softWrap, (softWrap) => @emit 'soft-wrap-changed', softWrap @updateWrappedScreenLines() @subscribe atom.config.observe 'editor.preferredLineLength', callNow: false, => @updateWrappedScreenLines() if @softWrap and atom.config.get('editor.softWrapAtPreferredLineLength') @subscribe atom.config.observe 'editor.softWrapAtPreferredLineLength', callNow: false, => @updateWrappedScreenLines() if @softWrap serializeParams: -> id: @id softWrap: @softWrap editorWidthInChars: @editorWidthInChars scrollTop: @scrollTop scrollLeft: @scrollLeft tokenizedBuffer: @tokenizedBuffer.serialize() invisibles: _.clone(@invisibles) deserializeParams: (params) -> params.tokenizedBuffer = TokenizedBuffer.deserialize(params.tokenizedBuffer) params copy: -> newDisplayBuffer = new DisplayBuffer({@buffer, tabLength: @getTabLength(), @invisibles}) newDisplayBuffer.setScrollTop(@getScrollTop()) newDisplayBuffer.setScrollLeft(@getScrollLeft()) for marker in @findMarkers(displayBufferId: @id) marker.copy(displayBufferId: newDisplayBuffer.id) newDisplayBuffer updateAllScreenLines: -> @maxLineLength = 0 @screenLines = [] @rowMap = new RowMap @updateScreenLines(0, @buffer.getLineCount(), null, suppressChangeEvent: true) emitChanged: (eventProperties, refreshMarkers=true) -> if refreshMarkers @pauseMarkerObservers() @refreshMarkerScreenPositions() @emit 'changed', eventProperties @resumeMarkerObservers() updateWrappedScreenLines: -> start = 0 end = @getLastRow() @updateAllScreenLines() screenDelta = @getLastRow() - end bufferDelta = 0 @emitChanged({ start, end, screenDelta, bufferDelta }) # Sets the visibility of the tokenized buffer. # # visible - A {Boolean} indicating of the tokenized buffer is shown setVisible: (visible) -> @tokenizedBuffer.setVisible(visible) getVerticalScrollMargin: -> @verticalScrollMargin setVerticalScrollMargin: (@verticalScrollMargin) -> @verticalScrollMargin getHorizontalScrollMargin: -> @horizontalScrollMargin setHorizontalScrollMargin: (@horizontalScrollMargin) -> @horizontalScrollMargin getHorizontalScrollbarHeight: -> @horizontalScrollbarHeight setHorizontalScrollbarHeight: (@horizontalScrollbarHeight) -> @horizontalScrollbarHeight getVerticalScrollbarWidth: -> @verticalScrollbarWidth setVerticalScrollbarWidth: (@verticalScrollbarWidth) -> @verticalScrollbarWidth getHeight: -> if @height? @height else if @horizontallyScrollable() @getScrollHeight() + @getHorizontalScrollbarHeight() else @getScrollHeight() setHeight: (@height) -> @height getClientHeight: (reentrant) -> if @horizontallyScrollable(reentrant) @getHeight() - @getHorizontalScrollbarHeight() else @getHeight() getClientWidth: (reentrant) -> if @verticallyScrollable(reentrant) @getWidth() - @getVerticalScrollbarWidth() else @getWidth() horizontallyScrollable: (reentrant) -> return false unless @width? return false if @getSoftWrap() if reentrant @getScrollWidth() > @getWidth() else @getScrollWidth() > @getClientWidth(true) verticallyScrollable: (reentrant) -> return false unless @height? if reentrant @getScrollHeight() > @getHeight() else @getScrollHeight() > @getClientHeight(true) getWidth: -> if @width? @width else if @verticallyScrollable() @getScrollWidth() + @getVerticalScrollbarWidth() else @getScrollWidth() setWidth: (newWidth) -> oldWidth = @width @width = newWidth @updateWrappedScreenLines() if newWidth isnt oldWidth and @softWrap @setScrollTop(@getScrollTop()) # Ensure scrollTop is still valid in case horizontal scrollbar disappeared @width getScrollTop: -> @scrollTop setScrollTop: (scrollTop) -> if @manageScrollPosition @scrollTop = Math.round(Math.max(0, Math.min(@getMaxScrollTop(), scrollTop))) else @scrollTop = Math.round(scrollTop) getMaxScrollTop: -> @getScrollHeight() - @getClientHeight() getScrollBottom: -> @scrollTop + @height setScrollBottom: (scrollBottom) -> @setScrollTop(scrollBottom - @getClientHeight()) @getScrollBottom() getScrollLeft: -> @scrollLeft setScrollLeft: (scrollLeft) -> if @manageScrollPosition @scrollLeft = Math.round(Math.max(0, Math.min(@getScrollWidth() - @getClientWidth(), scrollLeft))) @scrollLeft else @scrollLeft = Math.round(scrollLeft) getMaxScrollLeft: -> @getScrollWidth() - @getClientWidth() getScrollRight: -> @scrollLeft + @width setScrollRight: (scrollRight) -> @setScrollLeft(scrollRight - @width) @getScrollRight() getLineHeightInPixels: -> @lineHeightInPixels setLineHeightInPixels: (@lineHeightInPixels) -> @lineHeightInPixels getDefaultCharWidth: -> @defaultCharWidth setDefaultCharWidth: (defaultCharWidth) -> if defaultCharWidth isnt @defaultCharWidth @defaultCharWidth = defaultCharWidth @computeScrollWidth() defaultCharWidth getCursorWidth: -> 1 getScopedCharWidth: (scopeNames, char) -> @getScopedCharWidths(scopeNames)[char] getScopedCharWidths: (scopeNames) -> scope = @charWidthsByScope for scopeName in scopeNames scope[scopeName] ?= {} scope = scope[scopeName] scope.charWidths ?= {} scope.charWidths batchCharacterMeasurement: (fn) -> oldChangeCount = @scopedCharacterWidthsChangeCount @batchingCharacterMeasurement = true fn() @batchingCharacterMeasurement = false @characterWidthsChanged() if oldChangeCount isnt @scopedCharacterWidthsChangeCount setScopedCharWidth: (scopeNames, char, width) -> @getScopedCharWidths(scopeNames)[char] = width @scopedCharacterWidthsChangeCount++ @characterWidthsChanged() unless @batchingCharacterMeasurement characterWidthsChanged: -> @computeScrollWidth() @emit 'character-widths-changed', @scopedCharacterWidthsChangeCount clearScopedCharWidths: -> @charWidthsByScope = {} getScrollHeight: -> return 0 unless @getLineHeightInPixels() > 0 @getLineCount() * @getLineHeightInPixels() getScrollWidth: -> @scrollWidth getVisibleRowRange: -> return [0, 0] unless @getLineHeightInPixels() > 0 heightInLines = Math.ceil(@getHeight() / @getLineHeightInPixels()) + 1 startRow = Math.floor(@getScrollTop() / @getLineHeightInPixels()) endRow = Math.min(@getLineCount(), startRow + heightInLines) [startRow, endRow] intersectsVisibleRowRange: (startRow, endRow) -> [visibleStart, visibleEnd] = @getVisibleRowRange() not (endRow <= visibleStart or visibleEnd <= startRow) selectionIntersectsVisibleRowRange: (selection) -> {start, end} = selection.getScreenRange() @intersectsVisibleRowRange(start.row, end.row + 1) scrollToScreenRange: (screenRange, options) -> verticalScrollMarginInPixels = @getVerticalScrollMargin() * @getLineHeightInPixels() horizontalScrollMarginInPixels = @getHorizontalScrollMargin() * @getDefaultCharWidth() {top, left, height, width} = @pixelRectForScreenRange(screenRange) bottom = top + height right = left + width if options?.center desiredScrollCenter = top + height / 2 unless @getScrollTop() < desiredScrollCenter < @getScrollBottom() desiredScrollTop = desiredScrollCenter - @getHeight() / 2 desiredScrollBottom = desiredScrollCenter + @getHeight() / 2 else desiredScrollTop = top - verticalScrollMarginInPixels desiredScrollBottom = bottom + verticalScrollMarginInPixels desiredScrollLeft = left - horizontalScrollMarginInPixels desiredScrollRight = right + horizontalScrollMarginInPixels if desiredScrollTop < @getScrollTop() @setScrollTop(desiredScrollTop) else if desiredScrollBottom > @getScrollBottom() @setScrollBottom(desiredScrollBottom) if desiredScrollLeft < @getScrollLeft() @setScrollLeft(desiredScrollLeft) else if desiredScrollRight > @getScrollRight() @setScrollRight(desiredScrollRight) scrollToScreenPosition: (screenPosition, options) -> @scrollToScreenRange(new Range(screenPosition, screenPosition), options) scrollToBufferPosition: (bufferPosition, options) -> @scrollToScreenPosition(@screenPositionForBufferPosition(bufferPosition), options) pixelRectForScreenRange: (screenRange) -> if screenRange.end.row > screenRange.start.row top = @pixelPositionForScreenPosition(screenRange.start).top left = 0 height = (screenRange.end.row - screenRange.start.row + 1) * @getLineHeightInPixels() width = @getScrollWidth() else {top, left} = @pixelPositionForScreenPosition(screenRange.start, false) height = @getLineHeightInPixels() width = @pixelPositionForScreenPosition(screenRange.end, false).left - left {top, left, width, height} # Retrieves the current tab length. # # Returns a {Number}. getTabLength: -> @tokenizedBuffer.getTabLength() # Specifies the tab length. # # tabLength - A {Number} that defines the new tab length. setTabLength: (tabLength) -> @tokenizedBuffer.setTabLength(tabLength) setInvisibles: (@invisibles) -> @tokenizedBuffer.setInvisibles(@invisibles) # Deprecated: Use the softWrap property directly setSoftWrap: (@softWrap) -> @softWrap # Deprecated: Use the softWrap property directly getSoftWrap: -> @softWrap # Set the number of characters that fit horizontally in the editor. # # editorWidthInChars - A {Number} of characters. setEditorWidthInChars: (editorWidthInChars) -> if editorWidthInChars > 0 previousWidthInChars = @editorWidthInChars @editorWidthInChars = editorWidthInChars if editorWidthInChars isnt previousWidthInChars and @softWrap @updateWrappedScreenLines() # Returns the editor width in characters for soft wrap. getEditorWidthInChars: -> width = @width ? @getScrollWidth() width -= @getVerticalScrollbarWidth() if width? and @defaultCharWidth > 0 Math.floor(width / @defaultCharWidth) else @editorWidthInChars getSoftWrapColumn: -> if atom.config.get('editor.softWrapAtPreferredLineLength') Math.min(@getEditorWidthInChars(), atom.config.getPositiveInt('editor.preferredLineLength', @getEditorWidthInChars())) else @getEditorWidthInChars() # Gets the screen line for the given screen row. # # * `screenRow` - A {Number} indicating the screen row. # # Returns {TokenizedLine} tokenizedLineForScreenRow: (screenRow) -> @screenLines[screenRow] # Gets the screen lines for the given screen row range. # # startRow - A {Number} indicating the beginning screen row. # endRow - A {Number} indicating the ending screen row. # # Returns an {Array} of {TokenizedLine}s. tokenizedLinesForScreenRows: (startRow, endRow) -> @screenLines[startRow..endRow] # Gets all the screen lines. # # Returns an {Array} of {TokenizedLine}s. getTokenizedLines: -> new Array(@screenLines...) indentLevelForLine: (line) -> @tokenizedBuffer.indentLevelForLine(line) # Given starting and ending screen rows, this returns an array of the # buffer rows corresponding to every screen row in the range # # startScreenRow - The screen row {Number} to start at # endScreenRow - The screen row {Number} to end at (default: the last screen row) # # Returns an {Array} of buffer rows as {Numbers}s. bufferRowsForScreenRows: (startScreenRow, endScreenRow) -> for screenRow in [startScreenRow..endScreenRow] @rowMap.bufferRowRangeForScreenRow(screenRow)[0] # Creates a new fold between two row numbers. # # startRow - The row {Number} to start folding at # endRow - The row {Number} to end the fold # # Returns the new {Fold}. createFold: (startRow, endRow) -> foldMarker = @findFoldMarker({startRow, endRow}) ? @buffer.markRange([[startRow, 0], [endRow, Infinity]], @getFoldMarkerAttributes()) @foldForMarker(foldMarker) isFoldedAtBufferRow: (bufferRow) -> @largestFoldContainingBufferRow(bufferRow)? isFoldedAtScreenRow: (screenRow) -> @largestFoldContainingBufferRow(@bufferRowForScreenRow(screenRow))? # Destroys the fold with the given id destroyFoldWithId: (id) -> @foldsByMarkerId[id]?.destroy() # Removes any folds found that contain the given buffer row. # # bufferRow - The buffer row {Number} to check against unfoldBufferRow: (bufferRow) -> fold.destroy() for fold in @foldsContainingBufferRow(bufferRow) # Given a buffer row, this returns the largest fold that starts there. # # Largest is defined as the fold whose difference between its start and end points # are the greatest. # # bufferRow - A {Number} indicating the buffer row # # Returns a {Fold} or null if none exists. largestFoldStartingAtBufferRow: (bufferRow) -> @foldsStartingAtBufferRow(bufferRow)[0] # Public: Given a buffer row, this returns all folds that start there. # # bufferRow - A {Number} indicating the buffer row # # Returns an {Array} of {Fold}s. foldsStartingAtBufferRow: (bufferRow) -> for marker in @findFoldMarkers(startRow: bufferRow) @foldForMarker(marker) # Given a screen row, this returns the largest fold that starts there. # # Largest is defined as the fold whose difference between its start and end points # are the greatest. # # screenRow - A {Number} indicating the screen row # # Returns a {Fold}. largestFoldStartingAtScreenRow: (screenRow) -> @largestFoldStartingAtBufferRow(@bufferRowForScreenRow(screenRow)) # Given a buffer row, this returns the largest fold that includes it. # # Largest is defined as the fold whose difference between its start and end rows # is the greatest. # # bufferRow - A {Number} indicating the buffer row # # Returns a {Fold}. largestFoldContainingBufferRow: (bufferRow) -> @foldsContainingBufferRow(bufferRow)[0] # Returns the folds in the given row range (exclusive of end row) that are # not contained by any other folds. outermostFoldsInBufferRowRange: (startRow, endRow) -> @findFoldMarkers(containedInRange: [[startRow, 0], [endRow, 0]]) .map (marker) => @foldForMarker(marker) .filter (fold) -> not fold.isInsideLargerFold() # Public: Given a buffer row, this returns folds that include it. # # # bufferRow - A {Number} indicating the buffer row # # Returns an {Array} of {Fold}s. foldsContainingBufferRow: (bufferRow) -> for marker in @findFoldMarkers(intersectsRow: bufferRow) @foldForMarker(marker) # Given a buffer row, this converts it into a screen row. # # bufferRow - A {Number} representing a buffer row # # Returns a {Number}. screenRowForBufferRow: (bufferRow) -> @rowMap.screenRowRangeForBufferRow(bufferRow)[0] lastScreenRowForBufferRow: (bufferRow) -> @rowMap.screenRowRangeForBufferRow(bufferRow)[1] - 1 # Given a screen row, this converts it into a buffer row. # # screenRow - A {Number} representing a screen row # # Returns a {Number}. bufferRowForScreenRow: (screenRow) -> @rowMap.bufferRowRangeForScreenRow(screenRow)[0] # Given a buffer range, this converts it into a screen position. # # bufferRange - The {Range} to convert # # Returns a {Range}. screenRangeForBufferRange: (bufferRange) -> bufferRange = Range.fromObject(bufferRange) start = @screenPositionForBufferPosition(bufferRange.start) end = @screenPositionForBufferPosition(bufferRange.end) new Range(start, end) # Given a screen range, this converts it into a buffer position. # # screenRange - The {Range} to convert # # Returns a {Range}. bufferRangeForScreenRange: (screenRange) -> screenRange = Range.fromObject(screenRange) start = @bufferPositionForScreenPosition(screenRange.start) end = @bufferPositionForScreenPosition(screenRange.end) new Range(start, end) pixelRangeForScreenRange: (screenRange, clip=true) -> {start, end} = Range.fromObject(screenRange) {start: @pixelPositionForScreenPosition(start, clip), end: @pixelPositionForScreenPosition(end, clip)} pixelPositionForScreenPosition: (screenPosition, clip=true) -> screenPosition = Point.fromObject(screenPosition) screenPosition = @clipScreenPosition(screenPosition) if clip targetRow = screenPosition.row targetColumn = screenPosition.column defaultCharWidth = @defaultCharWidth top = targetRow * @lineHeightInPixels left = 0 column = 0 for token in @tokenizedLineForScreenRow(targetRow).tokens charWidths = @getScopedCharWidths(token.scopes) for char in token.value return {top, left} if column is targetColumn left += charWidths[char] ? defaultCharWidth unless char is '\0' column++ {top, left} screenPositionForPixelPosition: (pixelPosition) -> targetTop = pixelPosition.top targetLeft = pixelPosition.left defaultCharWidth = @defaultCharWidth row = Math.floor(targetTop / @getLineHeightInPixels()) row = Math.min(row, @getLastRow()) row = Math.max(0, row) left = 0 column = 0 for token in @tokenizedLineForScreenRow(row).tokens charWidths = @getScopedCharWidths(token.scopes) for char in token.value charWidth = charWidths[char] ? defaultCharWidth break if targetLeft <= left + (charWidth / 2) left += charWidth column++ new Point(row, column) pixelPositionForBufferPosition: (bufferPosition) -> @pixelPositionForScreenPosition(@screenPositionForBufferPosition(bufferPosition)) # Gets the number of screen lines. # # Returns a {Number}. getLineCount: -> @screenLines.length # Gets the number of the last screen line. # # Returns a {Number}. getLastRow: -> @getLineCount() - 1 # Gets the length of the longest screen line. # # Returns a {Number}. getMaxLineLength: -> @maxLineLength # Gets the row number of the longest screen line. # # Return a {} getLongestScreenRow: -> @longestScreenRow # Given a buffer position, this converts it into a screen position. # # bufferPosition - An object that represents a buffer position. It can be either # an {Object} (`{row, column}`), {Array} (`[row, column]`), or {Point} # options - A hash of options with the following keys: # wrapBeyondNewlines: # wrapAtSoftNewlines: # # Returns a {Point}. screenPositionForBufferPosition: (bufferPosition, options) -> { row, column } = @buffer.clipPosition(bufferPosition) [startScreenRow, endScreenRow] = @rowMap.screenRowRangeForBufferRow(row) for screenRow in [startScreenRow...endScreenRow] screenLine = @screenLines[screenRow] unless screenLine? throw new BufferToScreenConversionError "No screen line exists when converting buffer row to screen row", softWrapEnabled: @getSoftWrap() foldCount: @findFoldMarkers().length lastBufferRow: @buffer.getLastRow() lastScreenRow: @getLastRow() maxBufferColumn = screenLine.getMaxBufferColumn() if screenLine.isSoftWrapped() and column > maxBufferColumn continue else if column <= maxBufferColumn screenColumn = screenLine.screenColumnForBufferColumn(column) else screenColumn = Infinity break @clipScreenPosition([screenRow, screenColumn], options) # Given a buffer position, this converts it into a screen position. # # screenPosition - An object that represents a buffer position. It can be either # an {Object} (`{row, column}`), {Array} (`[row, column]`), or {Point} # options - A hash of options with the following keys: # wrapBeyondNewlines: # wrapAtSoftNewlines: # # Returns a {Point}. bufferPositionForScreenPosition: (screenPosition, options) -> { row, column } = @clipScreenPosition(Point.fromObject(screenPosition), options) [bufferRow] = @rowMap.bufferRowRangeForScreenRow(row) new Point(bufferRow, @screenLines[row].bufferColumnForScreenColumn(column)) # Retrieves the grammar's token scopes for a buffer position. # # bufferPosition - A {Point} in the {TextBuffer} # # Returns an {Array} of {String}s. scopesForBufferPosition: (bufferPosition) -> @tokenizedBuffer.scopesForPosition(bufferPosition) bufferRangeForScopeAtPosition: (selector, position) -> @tokenizedBuffer.bufferRangeForScopeAtPosition(selector, position) # Retrieves the grammar's token for a buffer position. # # bufferPosition - A {Point} in the {TextBuffer}. # # Returns a {Token}. tokenForBufferPosition: (bufferPosition) -> @tokenizedBuffer.tokenForPosition(bufferPosition) # Get the grammar for this buffer. # # Returns the current {Grammar} or the {NullGrammar}. getGrammar: -> @tokenizedBuffer.grammar # Sets the grammar for the buffer. # # grammar - Sets the new grammar rules setGrammar: (grammar) -> @tokenizedBuffer.setGrammar(grammar) # Reloads the current grammar. reloadGrammar: -> @tokenizedBuffer.reloadGrammar() # Given a position, this clips it to a real position. # # For example, if `position`'s row exceeds the row count of the buffer, # or if its column goes beyond a line's length, this "sanitizes" the value # to a real position. # # position - The {Point} to clip # options - A hash with the following values: # wrapBeyondNewlines: if `true`, continues wrapping past newlines # wrapAtSoftNewlines: if `true`, continues wrapping past soft newlines # screenLine: if `true`, indicates that you're using a line number, not a row number # # Returns the new, clipped {Point}. Note that this could be the same as `position` if no clipping was performed. clipScreenPosition: (screenPosition, options={}) -> { wrapBeyondNewlines, wrapAtSoftNewlines } = options { row, column } = Point.fromObject(screenPosition) if row < 0 row = 0 column = 0 else if row > @getLastRow() row = @getLastRow() column = Infinity else if column < 0 column = 0 screenLine = @screenLines[row] maxScreenColumn = screenLine.getMaxScreenColumn() if screenLine.isSoftWrapped() and column >= maxScreenColumn if wrapAtSoftNewlines row++ column = 0 else column = screenLine.clipScreenColumn(maxScreenColumn - 1) else if wrapBeyondNewlines and column > maxScreenColumn and row < @getLastRow() row++ column = 0 else column = screenLine.clipScreenColumn(column, options) new Point(row, column) # Given a line, finds the point where it would wrap. # # line - The {String} to check # softWrapColumn - The {Number} where you want soft wrapping to occur # # Returns a {Number} representing the `line` position where the wrap would take place. # Returns `null` if a wrap wouldn't occur. findWrapColumn: (line, softWrapColumn=@getSoftWrapColumn()) -> return unless @softWrap return unless line.length > softWrapColumn if /\s/.test(line[softWrapColumn]) # search forward for the start of a word past the boundary for column in [softWrapColumn..line.length] return column if /\S/.test(line[column]) return line.length else # search backward for the start of the word on the boundary for column in [softWrapColumn..0] return column + 1 if /\s/.test(line[column]) return softWrapColumn # Calculates a {Range} representing the start of the {TextBuffer} until the end. # # Returns a {Range}. rangeForAllLines: -> new Range([0, 0], @clipScreenPosition([Infinity, Infinity])) decorationForId: (id) -> @decorationsById[id] decorationsForScreenRowRange: (startScreenRow, endScreenRow) -> decorationsByMarkerId = {} for marker in @findMarkers(intersectsScreenRowRange: [startScreenRow, endScreenRow]) if decorations = @decorationsByMarkerId[marker.id] decorationsByMarkerId[marker.id] = decorations decorationsByMarkerId decorateMarker: (marker, decorationParams) -> marker = @getMarker(marker.id) @decorationMarkerDestroyedSubscriptions[marker.id] ?= @subscribe marker, 'destroyed', => @removeAllDecorationsForMarker(marker) @decorationMarkerChangedSubscriptions[marker.id] ?= @subscribe marker, 'changed', (event) => decorations = @decorationsByMarkerId[marker.id] # Why check existence? Markers may get destroyed or decorations removed # in the change handler. Bookmarks does this. if decorations? for decoration in decorations @emit 'decoration-changed', marker, decoration, event decoration = new Decoration(marker, this, decorationParams) @decorationsByMarkerId[marker.id] ?= [] @decorationsByMarkerId[marker.id].push(decoration) @decorationsById[decoration.id] = decoration @emit 'decoration-added', marker, decoration decoration removeDecoration: (decoration) -> {marker} = decoration return unless decorations = @decorationsByMarkerId[marker.id] index = decorations.indexOf(decoration) if index > -1 decorations.splice(index, 1) delete @decorationsById[decoration.id] @emit 'decoration-removed', marker, decoration @removedAllMarkerDecorations(marker) if decorations.length is 0 removeAllDecorationsForMarker: (marker) -> decorations = @decorationsByMarkerId[marker.id].slice() for decoration in decorations @emit 'decoration-removed', marker, decoration @removedAllMarkerDecorations(marker) removedAllMarkerDecorations: (marker) -> @decorationMarkerChangedSubscriptions[marker.id].off() @decorationMarkerDestroyedSubscriptions[marker.id].off() delete @decorationsByMarkerId[marker.id] delete @decorationMarkerChangedSubscriptions[marker.id] delete @decorationMarkerDestroyedSubscriptions[marker.id] decorationUpdated: (decoration) -> @emit 'decoration-updated', decoration # Retrieves a {DisplayBufferMarker} based on its id. # # id - A {Number} representing a marker id # # Returns the {DisplayBufferMarker} (if it exists). getMarker: (id) -> unless marker = @markers[id] if bufferMarker = @buffer.getMarker(id) marker = new DisplayBufferMarker({bufferMarker, displayBuffer: this}) @markers[id] = marker marker # Retrieves the active markers in the buffer. # # Returns an {Array} of existing {DisplayBufferMarker}s. getMarkers: -> @buffer.getMarkers().map ({id}) => @getMarker(id) getMarkerCount: -> @buffer.getMarkerCount() # Public: Constructs a new marker at the given screen range. # # range - The marker {Range} (representing the distance between the head and tail) # options - Options to pass to the {Marker} constructor # # Returns a {Number} representing the new marker's ID. markScreenRange: (args...) -> bufferRange = @bufferRangeForScreenRange(args.shift()) @markBufferRange(bufferRange, args...) # Public: Constructs a new marker at the given buffer range. # # range - The marker {Range} (representing the distance between the head and tail) # options - Options to pass to the {Marker} constructor # # Returns a {Number} representing the new marker's ID. markBufferRange: (range, options) -> @getMarker(@buffer.markRange(range, options).id) # Public: Constructs a new marker at the given screen position. # # range - The marker {Range} (representing the distance between the head and tail) # options - Options to pass to the {Marker} constructor # # Returns a {Number} representing the new marker's ID. markScreenPosition: (screenPosition, options) -> @markBufferPosition(@bufferPositionForScreenPosition(screenPosition), options) # Public: Constructs a new marker at the given buffer position. # # range - The marker {Range} (representing the distance between the head and tail) # options - Options to pass to the {Marker} constructor # # Returns a {Number} representing the new marker's ID. markBufferPosition: (bufferPosition, options) -> @getMarker(@buffer.markPosition(bufferPosition, options).id) # Public: Removes the marker with the given id. # # id - The {Number} of the ID to remove destroyMarker: (id) -> @buffer.destroyMarker(id) delete @markers[id] # Finds the first marker satisfying the given attributes # # Refer to {DisplayBuffer::findMarkers} for details. # # Returns a {DisplayBufferMarker} or null findMarker: (params) -> @findMarkers(params)[0] # Public: Find all markers satisfying a set of parameters. # # params - An {Object} containing parameters that all returned markers must # satisfy. Unreserved keys will be compared against the markers' custom # properties. There are also the following reserved keys with special # meaning for the query: # :startBufferRow - A {Number}. Only returns markers starting at this row in # buffer coordinates. # :endBufferRow - A {Number}. Only returns markers ending at this row in # buffer coordinates. # :containsBufferRange - A {Range} or range-compatible {Array}. Only returns # markers containing this range in buffer coordinates. # :containsBufferPosition - A {Point} or point-compatible {Array}. Only # returns markers containing this position in buffer coordinates. # :containedInBufferRange - A {Range} or range-compatible {Array}. Only # returns markers contained within this range. # # Returns an {Array} of {DisplayBufferMarker}s findMarkers: (params) -> params = @translateToBufferMarkerParams(params) @buffer.findMarkers(params).map (stringMarker) => @getMarker(stringMarker.id) translateToBufferMarkerParams: (params) -> bufferMarkerParams = {} for key, value of params switch key when 'startBufferRow' key = 'start<KEY>' when 'endBufferRow' key = 'endRow' when 'startScreenRow' key = 'start<KEY>' value = @bufferRowForScreenRow(value) when 'endScreenRow' key = '<KEY>' value = @bufferRowForScreenRow(value) when 'intersectsBufferRowRange' key = '<KEY>' when 'intersectsScreenRowRange' key = '<KEY>' [startRow, endRow] = value value = [@bufferRowForScreenRow(startRow), @bufferRowForScreenRow(endRow)] when 'containsBufferRange' key = 'containsRange' when 'containsBufferPosition' key = 'containsPosition' when 'containedInBufferRange' key = 'containedInRange' when 'containedInScreenRange' key = 'containedInRange' value = @bufferRangeForScreenRange(value) when 'intersectsBufferRange' key = 'intersect<KEY>Range' when 'intersectsScreenRange' key = '<KEY>' value = @bufferRangeForScreenRange(value) bufferMarkerParams[key] = value bufferMarkerParams findFoldMarker: (attributes) -> @findFoldMarkers(attributes)[0] findFoldMarkers: (attributes) -> @buffer.findMarkers(@getFoldMarkerAttributes(attributes)) getFoldMarkerAttributes: (attributes={}) -> _.extend(attributes, class: 'fold', displayBufferId: @id) pauseMarkerObservers: -> marker.pauseEvents() for marker in @getMarkers() resumeMarkerObservers: -> marker.resumeEvents() for marker in @getMarkers() @emit 'markers-updated' refreshMarkerScreenPositions: -> for marker in @getMarkers() marker.notifyObservers(textChanged: false) destroyed: -> marker.unsubscribe() for marker in @getMarkers() @tokenizedBuffer.destroy() @unsubscribe() logLines: (start=0, end=@getLastRow()) -> for row in [start..end] line = @tokenizedLineForScreenRow(row).text console.log row, @bufferRowForScreenRow(row), line, line.length handleTokenizedBufferChange: (tokenizedBufferChange) => {start, end, delta, bufferChange} = tokenizedBufferChange @updateScreenLines(start, end + 1, delta, delayChangeEvent: bufferChange?) @setScrollTop(Math.min(@getScrollTop(), @getMaxScrollTop())) if @manageScrollPosition and delta < 0 updateScreenLines: (startBufferRow, endBufferRow, bufferDelta=0, options={}) -> startBufferRow = @rowMap.bufferRowRangeForBufferRow(startBufferRow)[0] endBufferRow = @rowMap.bufferRowRangeForBufferRow(endBufferRow - 1)[1] startScreenRow = @rowMap.screenRowRangeForBufferRow(startBufferRow)[0] endScreenRow = @rowMap.screenRowRangeForBufferRow(endBufferRow - 1)[1] {screenLines, regions} = @buildScreenLines(startBufferRow, endBufferRow + bufferDelta) screenDelta = screenLines.length - (endScreenRow - startScreenRow) @screenLines[startScreenRow...endScreenRow] = screenLines @rowMap.spliceRegions(startBufferRow, endBufferRow - startBufferRow, regions) @findMaxLineLength(startScreenRow, endScreenRow, screenLines, screenDelta) return if options.suppressChangeEvent changeEvent = start: startScreenRow end: endScreenRow - 1 screenDelta: screenDelta bufferDelta: bufferDelta if options.delayChangeEvent @pauseMarkerObservers() @pendingChangeEvent = changeEvent else @emitChanged(changeEvent, options.refreshMarkers) buildScreenLines: (startBufferRow, endBufferRow) -> screenLines = [] regions = [] rectangularRegion = null bufferRow = startBufferRow while bufferRow < endBufferRow tokenizedLine = @tokenizedBuffer.tokenizedLineForRow(bufferRow) if fold = @largestFoldStartingAtBufferRow(bufferRow) foldLine = tokenizedLine.copy() foldLine.fold = fold screenLines.push(foldLine) if rectangularRegion? regions.push(rectangularRegion) rectangularRegion = null foldedRowCount = fold.getBufferRowCount() regions.push(bufferRows: foldedRowCount, screenRows: 1) bufferRow += foldedRowCount else softWraps = 0 while wrapScreenColumn = @findWrapColumn(tokenizedLine.text) [wrappedLine, tokenizedLine] = tokenizedLine.softWrapAt(wrapScreenColumn) screenLines.push(wrappedLine) softWraps++ screenLines.push(tokenizedLine) if softWraps > 0 if rectangularRegion? regions.push(rectangularRegion) rectangularRegion = null regions.push(bufferRows: 1, screenRows: softWraps + 1) else rectangularRegion ?= {bufferRows: 0, screenRows: 0} rectangularRegion.bufferRows++ rectangularRegion.screenRows++ bufferRow++ if rectangularRegion? regions.push(rectangularRegion) {screenLines, regions} findMaxLineLength: (startScreenRow, endScreenRow, newScreenLines, screenDelta) -> oldMaxLineLength = @maxLineLength if startScreenRow <= @longestScreenRow < endScreenRow @longestScreenRow = 0 @maxLineLength = 0 maxLengthCandidatesStartRow = 0 maxLengthCandidates = @screenLines else @longestScreenRow += screenDelta if endScreenRow < @longestScreenRow maxLengthCandidatesStartRow = startScreenRow maxLengthCandidates = newScreenLines for screenLine, i in maxLengthCandidates screenRow = maxLengthCandidatesStartRow + i length = screenLine.text.length if length > @maxLineLength @longestScreenRow = screenRow @maxLineLength = length @computeScrollWidth() if oldMaxLineLength isnt @maxLineLength computeScrollWidth: -> @scrollWidth = @pixelPositionForScreenPosition([@longestScreenRow, @maxLineLength]).left @scrollWidth += 1 unless @getSoftWrap() @setScrollLeft(Math.min(@getScrollLeft(), @getMaxScrollLeft())) handleBufferMarkersUpdated: => if event = @pendingChangeEvent @pendingChangeEvent = null @emitChanged(event, false) handleBufferMarkerCreated: (marker) => @createFoldForMarker(marker) if marker.matchesAttributes(@getFoldMarkerAttributes()) if displayBufferMarker = @getMarker(marker.id) # The marker might have been removed in some other handler called before # this one. Only emit when the marker still exists. @emit 'marker-created', displayBufferMarker createFoldForMarker: (marker) -> @decorateMarker(marker, type: 'gutter', class: 'folded') new Fold(this, marker) foldForMarker: (marker) -> @foldsByMarkerId[marker.id]
true
_ = require 'underscore-plus' {Emitter} = require 'emissary' guid = require 'guid' Serializable = require 'serializable' {Model} = require 'theorist' {Point, Range} = require 'text-buffer' TokenizedBuffer = require './tokenized-buffer' RowMap = require './row-map' Fold = require './fold' Token = require './token' Decoration = require './decoration' DisplayBufferMarker = require './display-buffer-marker' class BufferToScreenConversionError extends Error constructor: (@message, @metadata) -> super Error.captureStackTrace(this, BufferToScreenConversionError) module.exports = class DisplayBuffer extends Model Serializable.includeInto(this) @properties manageScrollPosition: false softWrap: null editorWidthInChars: null lineHeightInPixels: null defaultCharWidth: null height: null width: null scrollTop: 0 scrollLeft: 0 scrollWidth: 0 verticalScrollbarWidth: 15 horizontalScrollbarHeight: 15 verticalScrollMargin: 2 horizontalScrollMargin: 6 scopedCharacterWidthsChangeCount: 0 constructor: ({tabLength, @editorWidthInChars, @tokenizedBuffer, buffer, @invisibles}={}) -> super @softWrap ?= atom.config.get('editor.softWrap') ? false @tokenizedBuffer ?= new TokenizedBuffer({tabLength, buffer, @invisibles}) @buffer = @tokenizedBuffer.buffer @charWidthsByScope = {} @markers = {} @foldsByMarkerId = {} @decorationsById = {} @decorationsByMarkerId = {} @decorationMarkerChangedSubscriptions = {} @decorationMarkerDestroyedSubscriptions = {} @updateAllScreenLines() @createFoldForMarker(marker) for marker in @buffer.findMarkers(@getFoldMarkerAttributes()) @subscribe @tokenizedBuffer, 'grammar-changed', (grammar) => @emit 'grammar-changed', grammar @subscribe @tokenizedBuffer, 'tokenized', => @emit 'tokenized' @subscribe @tokenizedBuffer, 'changed', @handleTokenizedBufferChange @subscribe @buffer, 'markers-updated', @handleBufferMarkersUpdated @subscribe @buffer, 'marker-created', @handleBufferMarkerCreated @subscribe @$softWrap, (softWrap) => @emit 'soft-wrap-changed', softWrap @updateWrappedScreenLines() @subscribe atom.config.observe 'editor.preferredLineLength', callNow: false, => @updateWrappedScreenLines() if @softWrap and atom.config.get('editor.softWrapAtPreferredLineLength') @subscribe atom.config.observe 'editor.softWrapAtPreferredLineLength', callNow: false, => @updateWrappedScreenLines() if @softWrap serializeParams: -> id: @id softWrap: @softWrap editorWidthInChars: @editorWidthInChars scrollTop: @scrollTop scrollLeft: @scrollLeft tokenizedBuffer: @tokenizedBuffer.serialize() invisibles: _.clone(@invisibles) deserializeParams: (params) -> params.tokenizedBuffer = TokenizedBuffer.deserialize(params.tokenizedBuffer) params copy: -> newDisplayBuffer = new DisplayBuffer({@buffer, tabLength: @getTabLength(), @invisibles}) newDisplayBuffer.setScrollTop(@getScrollTop()) newDisplayBuffer.setScrollLeft(@getScrollLeft()) for marker in @findMarkers(displayBufferId: @id) marker.copy(displayBufferId: newDisplayBuffer.id) newDisplayBuffer updateAllScreenLines: -> @maxLineLength = 0 @screenLines = [] @rowMap = new RowMap @updateScreenLines(0, @buffer.getLineCount(), null, suppressChangeEvent: true) emitChanged: (eventProperties, refreshMarkers=true) -> if refreshMarkers @pauseMarkerObservers() @refreshMarkerScreenPositions() @emit 'changed', eventProperties @resumeMarkerObservers() updateWrappedScreenLines: -> start = 0 end = @getLastRow() @updateAllScreenLines() screenDelta = @getLastRow() - end bufferDelta = 0 @emitChanged({ start, end, screenDelta, bufferDelta }) # Sets the visibility of the tokenized buffer. # # visible - A {Boolean} indicating of the tokenized buffer is shown setVisible: (visible) -> @tokenizedBuffer.setVisible(visible) getVerticalScrollMargin: -> @verticalScrollMargin setVerticalScrollMargin: (@verticalScrollMargin) -> @verticalScrollMargin getHorizontalScrollMargin: -> @horizontalScrollMargin setHorizontalScrollMargin: (@horizontalScrollMargin) -> @horizontalScrollMargin getHorizontalScrollbarHeight: -> @horizontalScrollbarHeight setHorizontalScrollbarHeight: (@horizontalScrollbarHeight) -> @horizontalScrollbarHeight getVerticalScrollbarWidth: -> @verticalScrollbarWidth setVerticalScrollbarWidth: (@verticalScrollbarWidth) -> @verticalScrollbarWidth getHeight: -> if @height? @height else if @horizontallyScrollable() @getScrollHeight() + @getHorizontalScrollbarHeight() else @getScrollHeight() setHeight: (@height) -> @height getClientHeight: (reentrant) -> if @horizontallyScrollable(reentrant) @getHeight() - @getHorizontalScrollbarHeight() else @getHeight() getClientWidth: (reentrant) -> if @verticallyScrollable(reentrant) @getWidth() - @getVerticalScrollbarWidth() else @getWidth() horizontallyScrollable: (reentrant) -> return false unless @width? return false if @getSoftWrap() if reentrant @getScrollWidth() > @getWidth() else @getScrollWidth() > @getClientWidth(true) verticallyScrollable: (reentrant) -> return false unless @height? if reentrant @getScrollHeight() > @getHeight() else @getScrollHeight() > @getClientHeight(true) getWidth: -> if @width? @width else if @verticallyScrollable() @getScrollWidth() + @getVerticalScrollbarWidth() else @getScrollWidth() setWidth: (newWidth) -> oldWidth = @width @width = newWidth @updateWrappedScreenLines() if newWidth isnt oldWidth and @softWrap @setScrollTop(@getScrollTop()) # Ensure scrollTop is still valid in case horizontal scrollbar disappeared @width getScrollTop: -> @scrollTop setScrollTop: (scrollTop) -> if @manageScrollPosition @scrollTop = Math.round(Math.max(0, Math.min(@getMaxScrollTop(), scrollTop))) else @scrollTop = Math.round(scrollTop) getMaxScrollTop: -> @getScrollHeight() - @getClientHeight() getScrollBottom: -> @scrollTop + @height setScrollBottom: (scrollBottom) -> @setScrollTop(scrollBottom - @getClientHeight()) @getScrollBottom() getScrollLeft: -> @scrollLeft setScrollLeft: (scrollLeft) -> if @manageScrollPosition @scrollLeft = Math.round(Math.max(0, Math.min(@getScrollWidth() - @getClientWidth(), scrollLeft))) @scrollLeft else @scrollLeft = Math.round(scrollLeft) getMaxScrollLeft: -> @getScrollWidth() - @getClientWidth() getScrollRight: -> @scrollLeft + @width setScrollRight: (scrollRight) -> @setScrollLeft(scrollRight - @width) @getScrollRight() getLineHeightInPixels: -> @lineHeightInPixels setLineHeightInPixels: (@lineHeightInPixels) -> @lineHeightInPixels getDefaultCharWidth: -> @defaultCharWidth setDefaultCharWidth: (defaultCharWidth) -> if defaultCharWidth isnt @defaultCharWidth @defaultCharWidth = defaultCharWidth @computeScrollWidth() defaultCharWidth getCursorWidth: -> 1 getScopedCharWidth: (scopeNames, char) -> @getScopedCharWidths(scopeNames)[char] getScopedCharWidths: (scopeNames) -> scope = @charWidthsByScope for scopeName in scopeNames scope[scopeName] ?= {} scope = scope[scopeName] scope.charWidths ?= {} scope.charWidths batchCharacterMeasurement: (fn) -> oldChangeCount = @scopedCharacterWidthsChangeCount @batchingCharacterMeasurement = true fn() @batchingCharacterMeasurement = false @characterWidthsChanged() if oldChangeCount isnt @scopedCharacterWidthsChangeCount setScopedCharWidth: (scopeNames, char, width) -> @getScopedCharWidths(scopeNames)[char] = width @scopedCharacterWidthsChangeCount++ @characterWidthsChanged() unless @batchingCharacterMeasurement characterWidthsChanged: -> @computeScrollWidth() @emit 'character-widths-changed', @scopedCharacterWidthsChangeCount clearScopedCharWidths: -> @charWidthsByScope = {} getScrollHeight: -> return 0 unless @getLineHeightInPixels() > 0 @getLineCount() * @getLineHeightInPixels() getScrollWidth: -> @scrollWidth getVisibleRowRange: -> return [0, 0] unless @getLineHeightInPixels() > 0 heightInLines = Math.ceil(@getHeight() / @getLineHeightInPixels()) + 1 startRow = Math.floor(@getScrollTop() / @getLineHeightInPixels()) endRow = Math.min(@getLineCount(), startRow + heightInLines) [startRow, endRow] intersectsVisibleRowRange: (startRow, endRow) -> [visibleStart, visibleEnd] = @getVisibleRowRange() not (endRow <= visibleStart or visibleEnd <= startRow) selectionIntersectsVisibleRowRange: (selection) -> {start, end} = selection.getScreenRange() @intersectsVisibleRowRange(start.row, end.row + 1) scrollToScreenRange: (screenRange, options) -> verticalScrollMarginInPixels = @getVerticalScrollMargin() * @getLineHeightInPixels() horizontalScrollMarginInPixels = @getHorizontalScrollMargin() * @getDefaultCharWidth() {top, left, height, width} = @pixelRectForScreenRange(screenRange) bottom = top + height right = left + width if options?.center desiredScrollCenter = top + height / 2 unless @getScrollTop() < desiredScrollCenter < @getScrollBottom() desiredScrollTop = desiredScrollCenter - @getHeight() / 2 desiredScrollBottom = desiredScrollCenter + @getHeight() / 2 else desiredScrollTop = top - verticalScrollMarginInPixels desiredScrollBottom = bottom + verticalScrollMarginInPixels desiredScrollLeft = left - horizontalScrollMarginInPixels desiredScrollRight = right + horizontalScrollMarginInPixels if desiredScrollTop < @getScrollTop() @setScrollTop(desiredScrollTop) else if desiredScrollBottom > @getScrollBottom() @setScrollBottom(desiredScrollBottom) if desiredScrollLeft < @getScrollLeft() @setScrollLeft(desiredScrollLeft) else if desiredScrollRight > @getScrollRight() @setScrollRight(desiredScrollRight) scrollToScreenPosition: (screenPosition, options) -> @scrollToScreenRange(new Range(screenPosition, screenPosition), options) scrollToBufferPosition: (bufferPosition, options) -> @scrollToScreenPosition(@screenPositionForBufferPosition(bufferPosition), options) pixelRectForScreenRange: (screenRange) -> if screenRange.end.row > screenRange.start.row top = @pixelPositionForScreenPosition(screenRange.start).top left = 0 height = (screenRange.end.row - screenRange.start.row + 1) * @getLineHeightInPixels() width = @getScrollWidth() else {top, left} = @pixelPositionForScreenPosition(screenRange.start, false) height = @getLineHeightInPixels() width = @pixelPositionForScreenPosition(screenRange.end, false).left - left {top, left, width, height} # Retrieves the current tab length. # # Returns a {Number}. getTabLength: -> @tokenizedBuffer.getTabLength() # Specifies the tab length. # # tabLength - A {Number} that defines the new tab length. setTabLength: (tabLength) -> @tokenizedBuffer.setTabLength(tabLength) setInvisibles: (@invisibles) -> @tokenizedBuffer.setInvisibles(@invisibles) # Deprecated: Use the softWrap property directly setSoftWrap: (@softWrap) -> @softWrap # Deprecated: Use the softWrap property directly getSoftWrap: -> @softWrap # Set the number of characters that fit horizontally in the editor. # # editorWidthInChars - A {Number} of characters. setEditorWidthInChars: (editorWidthInChars) -> if editorWidthInChars > 0 previousWidthInChars = @editorWidthInChars @editorWidthInChars = editorWidthInChars if editorWidthInChars isnt previousWidthInChars and @softWrap @updateWrappedScreenLines() # Returns the editor width in characters for soft wrap. getEditorWidthInChars: -> width = @width ? @getScrollWidth() width -= @getVerticalScrollbarWidth() if width? and @defaultCharWidth > 0 Math.floor(width / @defaultCharWidth) else @editorWidthInChars getSoftWrapColumn: -> if atom.config.get('editor.softWrapAtPreferredLineLength') Math.min(@getEditorWidthInChars(), atom.config.getPositiveInt('editor.preferredLineLength', @getEditorWidthInChars())) else @getEditorWidthInChars() # Gets the screen line for the given screen row. # # * `screenRow` - A {Number} indicating the screen row. # # Returns {TokenizedLine} tokenizedLineForScreenRow: (screenRow) -> @screenLines[screenRow] # Gets the screen lines for the given screen row range. # # startRow - A {Number} indicating the beginning screen row. # endRow - A {Number} indicating the ending screen row. # # Returns an {Array} of {TokenizedLine}s. tokenizedLinesForScreenRows: (startRow, endRow) -> @screenLines[startRow..endRow] # Gets all the screen lines. # # Returns an {Array} of {TokenizedLine}s. getTokenizedLines: -> new Array(@screenLines...) indentLevelForLine: (line) -> @tokenizedBuffer.indentLevelForLine(line) # Given starting and ending screen rows, this returns an array of the # buffer rows corresponding to every screen row in the range # # startScreenRow - The screen row {Number} to start at # endScreenRow - The screen row {Number} to end at (default: the last screen row) # # Returns an {Array} of buffer rows as {Numbers}s. bufferRowsForScreenRows: (startScreenRow, endScreenRow) -> for screenRow in [startScreenRow..endScreenRow] @rowMap.bufferRowRangeForScreenRow(screenRow)[0] # Creates a new fold between two row numbers. # # startRow - The row {Number} to start folding at # endRow - The row {Number} to end the fold # # Returns the new {Fold}. createFold: (startRow, endRow) -> foldMarker = @findFoldMarker({startRow, endRow}) ? @buffer.markRange([[startRow, 0], [endRow, Infinity]], @getFoldMarkerAttributes()) @foldForMarker(foldMarker) isFoldedAtBufferRow: (bufferRow) -> @largestFoldContainingBufferRow(bufferRow)? isFoldedAtScreenRow: (screenRow) -> @largestFoldContainingBufferRow(@bufferRowForScreenRow(screenRow))? # Destroys the fold with the given id destroyFoldWithId: (id) -> @foldsByMarkerId[id]?.destroy() # Removes any folds found that contain the given buffer row. # # bufferRow - The buffer row {Number} to check against unfoldBufferRow: (bufferRow) -> fold.destroy() for fold in @foldsContainingBufferRow(bufferRow) # Given a buffer row, this returns the largest fold that starts there. # # Largest is defined as the fold whose difference between its start and end points # are the greatest. # # bufferRow - A {Number} indicating the buffer row # # Returns a {Fold} or null if none exists. largestFoldStartingAtBufferRow: (bufferRow) -> @foldsStartingAtBufferRow(bufferRow)[0] # Public: Given a buffer row, this returns all folds that start there. # # bufferRow - A {Number} indicating the buffer row # # Returns an {Array} of {Fold}s. foldsStartingAtBufferRow: (bufferRow) -> for marker in @findFoldMarkers(startRow: bufferRow) @foldForMarker(marker) # Given a screen row, this returns the largest fold that starts there. # # Largest is defined as the fold whose difference between its start and end points # are the greatest. # # screenRow - A {Number} indicating the screen row # # Returns a {Fold}. largestFoldStartingAtScreenRow: (screenRow) -> @largestFoldStartingAtBufferRow(@bufferRowForScreenRow(screenRow)) # Given a buffer row, this returns the largest fold that includes it. # # Largest is defined as the fold whose difference between its start and end rows # is the greatest. # # bufferRow - A {Number} indicating the buffer row # # Returns a {Fold}. largestFoldContainingBufferRow: (bufferRow) -> @foldsContainingBufferRow(bufferRow)[0] # Returns the folds in the given row range (exclusive of end row) that are # not contained by any other folds. outermostFoldsInBufferRowRange: (startRow, endRow) -> @findFoldMarkers(containedInRange: [[startRow, 0], [endRow, 0]]) .map (marker) => @foldForMarker(marker) .filter (fold) -> not fold.isInsideLargerFold() # Public: Given a buffer row, this returns folds that include it. # # # bufferRow - A {Number} indicating the buffer row # # Returns an {Array} of {Fold}s. foldsContainingBufferRow: (bufferRow) -> for marker in @findFoldMarkers(intersectsRow: bufferRow) @foldForMarker(marker) # Given a buffer row, this converts it into a screen row. # # bufferRow - A {Number} representing a buffer row # # Returns a {Number}. screenRowForBufferRow: (bufferRow) -> @rowMap.screenRowRangeForBufferRow(bufferRow)[0] lastScreenRowForBufferRow: (bufferRow) -> @rowMap.screenRowRangeForBufferRow(bufferRow)[1] - 1 # Given a screen row, this converts it into a buffer row. # # screenRow - A {Number} representing a screen row # # Returns a {Number}. bufferRowForScreenRow: (screenRow) -> @rowMap.bufferRowRangeForScreenRow(screenRow)[0] # Given a buffer range, this converts it into a screen position. # # bufferRange - The {Range} to convert # # Returns a {Range}. screenRangeForBufferRange: (bufferRange) -> bufferRange = Range.fromObject(bufferRange) start = @screenPositionForBufferPosition(bufferRange.start) end = @screenPositionForBufferPosition(bufferRange.end) new Range(start, end) # Given a screen range, this converts it into a buffer position. # # screenRange - The {Range} to convert # # Returns a {Range}. bufferRangeForScreenRange: (screenRange) -> screenRange = Range.fromObject(screenRange) start = @bufferPositionForScreenPosition(screenRange.start) end = @bufferPositionForScreenPosition(screenRange.end) new Range(start, end) pixelRangeForScreenRange: (screenRange, clip=true) -> {start, end} = Range.fromObject(screenRange) {start: @pixelPositionForScreenPosition(start, clip), end: @pixelPositionForScreenPosition(end, clip)} pixelPositionForScreenPosition: (screenPosition, clip=true) -> screenPosition = Point.fromObject(screenPosition) screenPosition = @clipScreenPosition(screenPosition) if clip targetRow = screenPosition.row targetColumn = screenPosition.column defaultCharWidth = @defaultCharWidth top = targetRow * @lineHeightInPixels left = 0 column = 0 for token in @tokenizedLineForScreenRow(targetRow).tokens charWidths = @getScopedCharWidths(token.scopes) for char in token.value return {top, left} if column is targetColumn left += charWidths[char] ? defaultCharWidth unless char is '\0' column++ {top, left} screenPositionForPixelPosition: (pixelPosition) -> targetTop = pixelPosition.top targetLeft = pixelPosition.left defaultCharWidth = @defaultCharWidth row = Math.floor(targetTop / @getLineHeightInPixels()) row = Math.min(row, @getLastRow()) row = Math.max(0, row) left = 0 column = 0 for token in @tokenizedLineForScreenRow(row).tokens charWidths = @getScopedCharWidths(token.scopes) for char in token.value charWidth = charWidths[char] ? defaultCharWidth break if targetLeft <= left + (charWidth / 2) left += charWidth column++ new Point(row, column) pixelPositionForBufferPosition: (bufferPosition) -> @pixelPositionForScreenPosition(@screenPositionForBufferPosition(bufferPosition)) # Gets the number of screen lines. # # Returns a {Number}. getLineCount: -> @screenLines.length # Gets the number of the last screen line. # # Returns a {Number}. getLastRow: -> @getLineCount() - 1 # Gets the length of the longest screen line. # # Returns a {Number}. getMaxLineLength: -> @maxLineLength # Gets the row number of the longest screen line. # # Return a {} getLongestScreenRow: -> @longestScreenRow # Given a buffer position, this converts it into a screen position. # # bufferPosition - An object that represents a buffer position. It can be either # an {Object} (`{row, column}`), {Array} (`[row, column]`), or {Point} # options - A hash of options with the following keys: # wrapBeyondNewlines: # wrapAtSoftNewlines: # # Returns a {Point}. screenPositionForBufferPosition: (bufferPosition, options) -> { row, column } = @buffer.clipPosition(bufferPosition) [startScreenRow, endScreenRow] = @rowMap.screenRowRangeForBufferRow(row) for screenRow in [startScreenRow...endScreenRow] screenLine = @screenLines[screenRow] unless screenLine? throw new BufferToScreenConversionError "No screen line exists when converting buffer row to screen row", softWrapEnabled: @getSoftWrap() foldCount: @findFoldMarkers().length lastBufferRow: @buffer.getLastRow() lastScreenRow: @getLastRow() maxBufferColumn = screenLine.getMaxBufferColumn() if screenLine.isSoftWrapped() and column > maxBufferColumn continue else if column <= maxBufferColumn screenColumn = screenLine.screenColumnForBufferColumn(column) else screenColumn = Infinity break @clipScreenPosition([screenRow, screenColumn], options) # Given a buffer position, this converts it into a screen position. # # screenPosition - An object that represents a buffer position. It can be either # an {Object} (`{row, column}`), {Array} (`[row, column]`), or {Point} # options - A hash of options with the following keys: # wrapBeyondNewlines: # wrapAtSoftNewlines: # # Returns a {Point}. bufferPositionForScreenPosition: (screenPosition, options) -> { row, column } = @clipScreenPosition(Point.fromObject(screenPosition), options) [bufferRow] = @rowMap.bufferRowRangeForScreenRow(row) new Point(bufferRow, @screenLines[row].bufferColumnForScreenColumn(column)) # Retrieves the grammar's token scopes for a buffer position. # # bufferPosition - A {Point} in the {TextBuffer} # # Returns an {Array} of {String}s. scopesForBufferPosition: (bufferPosition) -> @tokenizedBuffer.scopesForPosition(bufferPosition) bufferRangeForScopeAtPosition: (selector, position) -> @tokenizedBuffer.bufferRangeForScopeAtPosition(selector, position) # Retrieves the grammar's token for a buffer position. # # bufferPosition - A {Point} in the {TextBuffer}. # # Returns a {Token}. tokenForBufferPosition: (bufferPosition) -> @tokenizedBuffer.tokenForPosition(bufferPosition) # Get the grammar for this buffer. # # Returns the current {Grammar} or the {NullGrammar}. getGrammar: -> @tokenizedBuffer.grammar # Sets the grammar for the buffer. # # grammar - Sets the new grammar rules setGrammar: (grammar) -> @tokenizedBuffer.setGrammar(grammar) # Reloads the current grammar. reloadGrammar: -> @tokenizedBuffer.reloadGrammar() # Given a position, this clips it to a real position. # # For example, if `position`'s row exceeds the row count of the buffer, # or if its column goes beyond a line's length, this "sanitizes" the value # to a real position. # # position - The {Point} to clip # options - A hash with the following values: # wrapBeyondNewlines: if `true`, continues wrapping past newlines # wrapAtSoftNewlines: if `true`, continues wrapping past soft newlines # screenLine: if `true`, indicates that you're using a line number, not a row number # # Returns the new, clipped {Point}. Note that this could be the same as `position` if no clipping was performed. clipScreenPosition: (screenPosition, options={}) -> { wrapBeyondNewlines, wrapAtSoftNewlines } = options { row, column } = Point.fromObject(screenPosition) if row < 0 row = 0 column = 0 else if row > @getLastRow() row = @getLastRow() column = Infinity else if column < 0 column = 0 screenLine = @screenLines[row] maxScreenColumn = screenLine.getMaxScreenColumn() if screenLine.isSoftWrapped() and column >= maxScreenColumn if wrapAtSoftNewlines row++ column = 0 else column = screenLine.clipScreenColumn(maxScreenColumn - 1) else if wrapBeyondNewlines and column > maxScreenColumn and row < @getLastRow() row++ column = 0 else column = screenLine.clipScreenColumn(column, options) new Point(row, column) # Given a line, finds the point where it would wrap. # # line - The {String} to check # softWrapColumn - The {Number} where you want soft wrapping to occur # # Returns a {Number} representing the `line` position where the wrap would take place. # Returns `null` if a wrap wouldn't occur. findWrapColumn: (line, softWrapColumn=@getSoftWrapColumn()) -> return unless @softWrap return unless line.length > softWrapColumn if /\s/.test(line[softWrapColumn]) # search forward for the start of a word past the boundary for column in [softWrapColumn..line.length] return column if /\S/.test(line[column]) return line.length else # search backward for the start of the word on the boundary for column in [softWrapColumn..0] return column + 1 if /\s/.test(line[column]) return softWrapColumn # Calculates a {Range} representing the start of the {TextBuffer} until the end. # # Returns a {Range}. rangeForAllLines: -> new Range([0, 0], @clipScreenPosition([Infinity, Infinity])) decorationForId: (id) -> @decorationsById[id] decorationsForScreenRowRange: (startScreenRow, endScreenRow) -> decorationsByMarkerId = {} for marker in @findMarkers(intersectsScreenRowRange: [startScreenRow, endScreenRow]) if decorations = @decorationsByMarkerId[marker.id] decorationsByMarkerId[marker.id] = decorations decorationsByMarkerId decorateMarker: (marker, decorationParams) -> marker = @getMarker(marker.id) @decorationMarkerDestroyedSubscriptions[marker.id] ?= @subscribe marker, 'destroyed', => @removeAllDecorationsForMarker(marker) @decorationMarkerChangedSubscriptions[marker.id] ?= @subscribe marker, 'changed', (event) => decorations = @decorationsByMarkerId[marker.id] # Why check existence? Markers may get destroyed or decorations removed # in the change handler. Bookmarks does this. if decorations? for decoration in decorations @emit 'decoration-changed', marker, decoration, event decoration = new Decoration(marker, this, decorationParams) @decorationsByMarkerId[marker.id] ?= [] @decorationsByMarkerId[marker.id].push(decoration) @decorationsById[decoration.id] = decoration @emit 'decoration-added', marker, decoration decoration removeDecoration: (decoration) -> {marker} = decoration return unless decorations = @decorationsByMarkerId[marker.id] index = decorations.indexOf(decoration) if index > -1 decorations.splice(index, 1) delete @decorationsById[decoration.id] @emit 'decoration-removed', marker, decoration @removedAllMarkerDecorations(marker) if decorations.length is 0 removeAllDecorationsForMarker: (marker) -> decorations = @decorationsByMarkerId[marker.id].slice() for decoration in decorations @emit 'decoration-removed', marker, decoration @removedAllMarkerDecorations(marker) removedAllMarkerDecorations: (marker) -> @decorationMarkerChangedSubscriptions[marker.id].off() @decorationMarkerDestroyedSubscriptions[marker.id].off() delete @decorationsByMarkerId[marker.id] delete @decorationMarkerChangedSubscriptions[marker.id] delete @decorationMarkerDestroyedSubscriptions[marker.id] decorationUpdated: (decoration) -> @emit 'decoration-updated', decoration # Retrieves a {DisplayBufferMarker} based on its id. # # id - A {Number} representing a marker id # # Returns the {DisplayBufferMarker} (if it exists). getMarker: (id) -> unless marker = @markers[id] if bufferMarker = @buffer.getMarker(id) marker = new DisplayBufferMarker({bufferMarker, displayBuffer: this}) @markers[id] = marker marker # Retrieves the active markers in the buffer. # # Returns an {Array} of existing {DisplayBufferMarker}s. getMarkers: -> @buffer.getMarkers().map ({id}) => @getMarker(id) getMarkerCount: -> @buffer.getMarkerCount() # Public: Constructs a new marker at the given screen range. # # range - The marker {Range} (representing the distance between the head and tail) # options - Options to pass to the {Marker} constructor # # Returns a {Number} representing the new marker's ID. markScreenRange: (args...) -> bufferRange = @bufferRangeForScreenRange(args.shift()) @markBufferRange(bufferRange, args...) # Public: Constructs a new marker at the given buffer range. # # range - The marker {Range} (representing the distance between the head and tail) # options - Options to pass to the {Marker} constructor # # Returns a {Number} representing the new marker's ID. markBufferRange: (range, options) -> @getMarker(@buffer.markRange(range, options).id) # Public: Constructs a new marker at the given screen position. # # range - The marker {Range} (representing the distance between the head and tail) # options - Options to pass to the {Marker} constructor # # Returns a {Number} representing the new marker's ID. markScreenPosition: (screenPosition, options) -> @markBufferPosition(@bufferPositionForScreenPosition(screenPosition), options) # Public: Constructs a new marker at the given buffer position. # # range - The marker {Range} (representing the distance between the head and tail) # options - Options to pass to the {Marker} constructor # # Returns a {Number} representing the new marker's ID. markBufferPosition: (bufferPosition, options) -> @getMarker(@buffer.markPosition(bufferPosition, options).id) # Public: Removes the marker with the given id. # # id - The {Number} of the ID to remove destroyMarker: (id) -> @buffer.destroyMarker(id) delete @markers[id] # Finds the first marker satisfying the given attributes # # Refer to {DisplayBuffer::findMarkers} for details. # # Returns a {DisplayBufferMarker} or null findMarker: (params) -> @findMarkers(params)[0] # Public: Find all markers satisfying a set of parameters. # # params - An {Object} containing parameters that all returned markers must # satisfy. Unreserved keys will be compared against the markers' custom # properties. There are also the following reserved keys with special # meaning for the query: # :startBufferRow - A {Number}. Only returns markers starting at this row in # buffer coordinates. # :endBufferRow - A {Number}. Only returns markers ending at this row in # buffer coordinates. # :containsBufferRange - A {Range} or range-compatible {Array}. Only returns # markers containing this range in buffer coordinates. # :containsBufferPosition - A {Point} or point-compatible {Array}. Only # returns markers containing this position in buffer coordinates. # :containedInBufferRange - A {Range} or range-compatible {Array}. Only # returns markers contained within this range. # # Returns an {Array} of {DisplayBufferMarker}s findMarkers: (params) -> params = @translateToBufferMarkerParams(params) @buffer.findMarkers(params).map (stringMarker) => @getMarker(stringMarker.id) translateToBufferMarkerParams: (params) -> bufferMarkerParams = {} for key, value of params switch key when 'startBufferRow' key = 'startPI:KEY:<KEY>END_PI' when 'endBufferRow' key = 'endRow' when 'startScreenRow' key = 'startPI:KEY:<KEY>END_PI' value = @bufferRowForScreenRow(value) when 'endScreenRow' key = 'PI:KEY:<KEY>END_PI' value = @bufferRowForScreenRow(value) when 'intersectsBufferRowRange' key = 'PI:KEY:<KEY>END_PI' when 'intersectsScreenRowRange' key = 'PI:KEY:<KEY>END_PI' [startRow, endRow] = value value = [@bufferRowForScreenRow(startRow), @bufferRowForScreenRow(endRow)] when 'containsBufferRange' key = 'containsRange' when 'containsBufferPosition' key = 'containsPosition' when 'containedInBufferRange' key = 'containedInRange' when 'containedInScreenRange' key = 'containedInRange' value = @bufferRangeForScreenRange(value) when 'intersectsBufferRange' key = 'intersectPI:KEY:<KEY>END_PIRange' when 'intersectsScreenRange' key = 'PI:KEY:<KEY>END_PI' value = @bufferRangeForScreenRange(value) bufferMarkerParams[key] = value bufferMarkerParams findFoldMarker: (attributes) -> @findFoldMarkers(attributes)[0] findFoldMarkers: (attributes) -> @buffer.findMarkers(@getFoldMarkerAttributes(attributes)) getFoldMarkerAttributes: (attributes={}) -> _.extend(attributes, class: 'fold', displayBufferId: @id) pauseMarkerObservers: -> marker.pauseEvents() for marker in @getMarkers() resumeMarkerObservers: -> marker.resumeEvents() for marker in @getMarkers() @emit 'markers-updated' refreshMarkerScreenPositions: -> for marker in @getMarkers() marker.notifyObservers(textChanged: false) destroyed: -> marker.unsubscribe() for marker in @getMarkers() @tokenizedBuffer.destroy() @unsubscribe() logLines: (start=0, end=@getLastRow()) -> for row in [start..end] line = @tokenizedLineForScreenRow(row).text console.log row, @bufferRowForScreenRow(row), line, line.length handleTokenizedBufferChange: (tokenizedBufferChange) => {start, end, delta, bufferChange} = tokenizedBufferChange @updateScreenLines(start, end + 1, delta, delayChangeEvent: bufferChange?) @setScrollTop(Math.min(@getScrollTop(), @getMaxScrollTop())) if @manageScrollPosition and delta < 0 updateScreenLines: (startBufferRow, endBufferRow, bufferDelta=0, options={}) -> startBufferRow = @rowMap.bufferRowRangeForBufferRow(startBufferRow)[0] endBufferRow = @rowMap.bufferRowRangeForBufferRow(endBufferRow - 1)[1] startScreenRow = @rowMap.screenRowRangeForBufferRow(startBufferRow)[0] endScreenRow = @rowMap.screenRowRangeForBufferRow(endBufferRow - 1)[1] {screenLines, regions} = @buildScreenLines(startBufferRow, endBufferRow + bufferDelta) screenDelta = screenLines.length - (endScreenRow - startScreenRow) @screenLines[startScreenRow...endScreenRow] = screenLines @rowMap.spliceRegions(startBufferRow, endBufferRow - startBufferRow, regions) @findMaxLineLength(startScreenRow, endScreenRow, screenLines, screenDelta) return if options.suppressChangeEvent changeEvent = start: startScreenRow end: endScreenRow - 1 screenDelta: screenDelta bufferDelta: bufferDelta if options.delayChangeEvent @pauseMarkerObservers() @pendingChangeEvent = changeEvent else @emitChanged(changeEvent, options.refreshMarkers) buildScreenLines: (startBufferRow, endBufferRow) -> screenLines = [] regions = [] rectangularRegion = null bufferRow = startBufferRow while bufferRow < endBufferRow tokenizedLine = @tokenizedBuffer.tokenizedLineForRow(bufferRow) if fold = @largestFoldStartingAtBufferRow(bufferRow) foldLine = tokenizedLine.copy() foldLine.fold = fold screenLines.push(foldLine) if rectangularRegion? regions.push(rectangularRegion) rectangularRegion = null foldedRowCount = fold.getBufferRowCount() regions.push(bufferRows: foldedRowCount, screenRows: 1) bufferRow += foldedRowCount else softWraps = 0 while wrapScreenColumn = @findWrapColumn(tokenizedLine.text) [wrappedLine, tokenizedLine] = tokenizedLine.softWrapAt(wrapScreenColumn) screenLines.push(wrappedLine) softWraps++ screenLines.push(tokenizedLine) if softWraps > 0 if rectangularRegion? regions.push(rectangularRegion) rectangularRegion = null regions.push(bufferRows: 1, screenRows: softWraps + 1) else rectangularRegion ?= {bufferRows: 0, screenRows: 0} rectangularRegion.bufferRows++ rectangularRegion.screenRows++ bufferRow++ if rectangularRegion? regions.push(rectangularRegion) {screenLines, regions} findMaxLineLength: (startScreenRow, endScreenRow, newScreenLines, screenDelta) -> oldMaxLineLength = @maxLineLength if startScreenRow <= @longestScreenRow < endScreenRow @longestScreenRow = 0 @maxLineLength = 0 maxLengthCandidatesStartRow = 0 maxLengthCandidates = @screenLines else @longestScreenRow += screenDelta if endScreenRow < @longestScreenRow maxLengthCandidatesStartRow = startScreenRow maxLengthCandidates = newScreenLines for screenLine, i in maxLengthCandidates screenRow = maxLengthCandidatesStartRow + i length = screenLine.text.length if length > @maxLineLength @longestScreenRow = screenRow @maxLineLength = length @computeScrollWidth() if oldMaxLineLength isnt @maxLineLength computeScrollWidth: -> @scrollWidth = @pixelPositionForScreenPosition([@longestScreenRow, @maxLineLength]).left @scrollWidth += 1 unless @getSoftWrap() @setScrollLeft(Math.min(@getScrollLeft(), @getMaxScrollLeft())) handleBufferMarkersUpdated: => if event = @pendingChangeEvent @pendingChangeEvent = null @emitChanged(event, false) handleBufferMarkerCreated: (marker) => @createFoldForMarker(marker) if marker.matchesAttributes(@getFoldMarkerAttributes()) if displayBufferMarker = @getMarker(marker.id) # The marker might have been removed in some other handler called before # this one. Only emit when the marker still exists. @emit 'marker-created', displayBufferMarker createFoldForMarker: (marker) -> @decorateMarker(marker, type: 'gutter', class: 'folded') new Fold(this, marker) foldForMarker: (marker) -> @foldsByMarkerId[marker.id]
[ { "context": "### ^\nBSD 3-Clause License\n\nCopyright (c) 2017, Stephan Jorek\nAll rights reserved.\n\nRedistribution and use in s", "end": 61, "score": 0.9998335838317871, "start": 48, "tag": "NAME", "value": "Stephan Jorek" } ]
src/misc/gulp/gulp-jison-parser.coffee
sjorek/goatee-script.js
0
### ^ BSD 3-Clause License Copyright (c) 2017, Stephan Jorek All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### map = require 'map-stream' util = require 'gulp-util' PluginError = util.PluginError ### # # Gulp Jison Parser # ------------------- # ### PLUGIN_NAME = 'gulp-jison-parser' module.exports = (options) -> Grammar = options.grammar parser = (file, cb) -> # util.log file, options p = Grammar.createParser(file.path) return cb p if p instanceof Error if options.goatee? data = Grammar.generateParser {generate: -> p.generate(options)} else data = p.generate(options) return cb data if data instanceof Error if options.beautify? comment = data.match /\/\*\s*(Returns a Parser object of the following structure:)[^\*]*(Parser:[^\*]*\})\s*\*\// if comment data = data.replace comment[0], """ /** ------------ * * #{comment[1]} * * #{comment[2].split('\n').join('\n * ').replace /\*[ ]+\n/g, '*\n'} * */ """ file.contents = new Buffer data file.path = util.replaceExtension file.path, '.js' cb null, file return map parser
4046
### ^ BSD 3-Clause License Copyright (c) 2017, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### map = require 'map-stream' util = require 'gulp-util' PluginError = util.PluginError ### # # Gulp Jison Parser # ------------------- # ### PLUGIN_NAME = 'gulp-jison-parser' module.exports = (options) -> Grammar = options.grammar parser = (file, cb) -> # util.log file, options p = Grammar.createParser(file.path) return cb p if p instanceof Error if options.goatee? data = Grammar.generateParser {generate: -> p.generate(options)} else data = p.generate(options) return cb data if data instanceof Error if options.beautify? comment = data.match /\/\*\s*(Returns a Parser object of the following structure:)[^\*]*(Parser:[^\*]*\})\s*\*\// if comment data = data.replace comment[0], """ /** ------------ * * #{comment[1]} * * #{comment[2].split('\n').join('\n * ').replace /\*[ ]+\n/g, '*\n'} * */ """ file.contents = new Buffer data file.path = util.replaceExtension file.path, '.js' cb null, file return map parser
true
### ^ BSD 3-Clause License Copyright (c) 2017, PI:NAME:<NAME>END_PI All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### map = require 'map-stream' util = require 'gulp-util' PluginError = util.PluginError ### # # Gulp Jison Parser # ------------------- # ### PLUGIN_NAME = 'gulp-jison-parser' module.exports = (options) -> Grammar = options.grammar parser = (file, cb) -> # util.log file, options p = Grammar.createParser(file.path) return cb p if p instanceof Error if options.goatee? data = Grammar.generateParser {generate: -> p.generate(options)} else data = p.generate(options) return cb data if data instanceof Error if options.beautify? comment = data.match /\/\*\s*(Returns a Parser object of the following structure:)[^\*]*(Parser:[^\*]*\})\s*\*\// if comment data = data.replace comment[0], """ /** ------------ * * #{comment[1]} * * #{comment[2].split('\n').join('\n * ').replace /\*[ ]+\n/g, '*\n'} * */ """ file.contents = new Buffer data file.path = util.replaceExtension file.path, '.js' cb null, file return map parser
[ { "context": "ser =\n _tenantId : _tenantId\n username : username\n password : password\n displayName: 'ADM", "end": 1250, "score": 0.9992930293083191, "start": 1242, "tag": "USERNAME", "value": "username" }, { "context": "enantId\n username : username\n ...
src/methods/admin-methods.coffee
codedoctor/mongoose-user-store-multi-tenant
4
_ = require 'underscore-ext' Boom = require 'boom' Hoek = require 'hoek' mongooseRestHelper = require 'mongoose-rest-helper' i18n = require '../i18n' fnUnprocessableEntity = (message = "",data) -> return Boom.create 422, message, data ### Provides methods to set up admin users. ### module.exports = class AdminMethods ### Initializes a new instance of the @see AdminMethods class. @param {Object} models A collection of models that can be used. ### constructor:(@models, @userMethods) -> Hoek.assert @models,i18n.assertModelsRequired Hoek.assert @models,i18n.assertUserMethodsRequired ### Sets up an account ready for use. ### setup: (_tenantId, username, email, password, roles, options = {}, cb = ->) => return cb Boom.badRequest( i18n.errorTenantIdRequired) unless _tenantId return cb fnUnprocessableEntity( i18n.errorUsernameRequired) unless username return cb fnUnprocessableEntity( i18n.errorEmailRequired) unless email return cb fnUnprocessableEntity( i18n.errorPasswordRequired) unless password if _.isFunction(options) cb = options options = {} _tenantId = mongooseRestHelper.asObjectId _tenantId adminUser = _tenantId : _tenantId username : username password : password displayName: 'ADMIN' roles: roles || ['admin','serveradmin'] email : email @userMethods.create _tenantId,adminUser,{}, (err, user) => return cb err if err cb null, user
154873
_ = require 'underscore-ext' Boom = require 'boom' Hoek = require 'hoek' mongooseRestHelper = require 'mongoose-rest-helper' i18n = require '../i18n' fnUnprocessableEntity = (message = "",data) -> return Boom.create 422, message, data ### Provides methods to set up admin users. ### module.exports = class AdminMethods ### Initializes a new instance of the @see AdminMethods class. @param {Object} models A collection of models that can be used. ### constructor:(@models, @userMethods) -> Hoek.assert @models,i18n.assertModelsRequired Hoek.assert @models,i18n.assertUserMethodsRequired ### Sets up an account ready for use. ### setup: (_tenantId, username, email, password, roles, options = {}, cb = ->) => return cb Boom.badRequest( i18n.errorTenantIdRequired) unless _tenantId return cb fnUnprocessableEntity( i18n.errorUsernameRequired) unless username return cb fnUnprocessableEntity( i18n.errorEmailRequired) unless email return cb fnUnprocessableEntity( i18n.errorPasswordRequired) unless password if _.isFunction(options) cb = options options = {} _tenantId = mongooseRestHelper.asObjectId _tenantId adminUser = _tenantId : _tenantId username : username password : <PASSWORD> displayName: 'ADMIN' roles: roles || ['admin','serveradmin'] email : email @userMethods.create _tenantId,adminUser,{}, (err, user) => return cb err if err cb null, user
true
_ = require 'underscore-ext' Boom = require 'boom' Hoek = require 'hoek' mongooseRestHelper = require 'mongoose-rest-helper' i18n = require '../i18n' fnUnprocessableEntity = (message = "",data) -> return Boom.create 422, message, data ### Provides methods to set up admin users. ### module.exports = class AdminMethods ### Initializes a new instance of the @see AdminMethods class. @param {Object} models A collection of models that can be used. ### constructor:(@models, @userMethods) -> Hoek.assert @models,i18n.assertModelsRequired Hoek.assert @models,i18n.assertUserMethodsRequired ### Sets up an account ready for use. ### setup: (_tenantId, username, email, password, roles, options = {}, cb = ->) => return cb Boom.badRequest( i18n.errorTenantIdRequired) unless _tenantId return cb fnUnprocessableEntity( i18n.errorUsernameRequired) unless username return cb fnUnprocessableEntity( i18n.errorEmailRequired) unless email return cb fnUnprocessableEntity( i18n.errorPasswordRequired) unless password if _.isFunction(options) cb = options options = {} _tenantId = mongooseRestHelper.asObjectId _tenantId adminUser = _tenantId : _tenantId username : username password : PI:PASSWORD:<PASSWORD>END_PI displayName: 'ADMIN' roles: roles || ['admin','serveradmin'] email : email @userMethods.create _tenantId,adminUser,{}, (err, user) => return cb err if err cb null, user
[ { "context": "n:\n# None\n#\n# Commands:\n# None\n#\n# Author:\n# Ben Speakman <ben@3sq.re>\n\nmodule.exports = (robot) ->\n robot", "end": 162, "score": 0.9998328685760498, "start": 150, "tag": "NAME", "value": "Ben Speakman" }, { "context": " Commands:\n# None\n#\n# Author...
src/rackspace-monitoring.coffee
threesquared/hubot-rackspace-cloud-monitoring
2
# Description # A hubot script to relay Rackspace Cloud Monitoring notifications # # Configuration: # None # # Commands: # None # # Author: # Ben Speakman <ben@3sq.re> module.exports = (robot) -> robot.router.post '/hubot/rackspace/:room', (req, res) -> room = req.params.room body = req.body robot.messageRoom room, "*#{body.details.state}* _(#{body.entity.label})_\n#{body.check.label}: #{body.details.status}" res.send 'OK'
97741
# Description # A hubot script to relay Rackspace Cloud Monitoring notifications # # Configuration: # None # # Commands: # None # # Author: # <NAME> <<EMAIL>> module.exports = (robot) -> robot.router.post '/hubot/rackspace/:room', (req, res) -> room = req.params.room body = req.body robot.messageRoom room, "*#{body.details.state}* _(#{body.entity.label})_\n#{body.check.label}: #{body.details.status}" res.send 'OK'
true
# Description # A hubot script to relay Rackspace Cloud Monitoring notifications # # Configuration: # None # # Commands: # None # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> module.exports = (robot) -> robot.router.post '/hubot/rackspace/:room', (req, res) -> room = req.params.room body = req.body robot.messageRoom room, "*#{body.details.state}* _(#{body.entity.label})_\n#{body.check.label}: #{body.details.status}" res.send 'OK'
[ { "context": "'./config'\nredis = require './redis'\n\nUSER_KEY = \"users\"\nAUTH_KEY = \"auth\"\nBANS_KEY = \"bans\"\nMUTE_KEY = \"", "end": 319, "score": 0.7743743658065796, "start": 314, "tag": "KEY", "value": "users" }, { "context": "require './redis'\n\nUSER_KEY = \"users\"\nAUT...
server/auth.coffee
sarenji/pokebattle-sim
5
{_} = require 'underscore' crypto = require('crypto') request = require 'request' authHeaders = {AUTHUSER: process.env.AUTHUSER, AUTHTOKEN: process.env.AUTHTOKEN} request = request.defaults(json: true, headers: authHeaders, timeout: 30 * 1000) config = require './config' redis = require './redis' USER_KEY = "users" AUTH_KEY = "auth" BANS_KEY = "bans" MUTE_KEY = "mute" # This middleware checks if a user is authenticated through the site. If yes, # then information about the user is stored in req.user. In addition, we store # a token associated with that user into req.user.token. # # User information is also stored in redis. exports.middleware = -> (req, res, next) -> return next() if req.path.match(/^\/css|^\/js|^\/fonts/) return next() if req.path == '/leaderboard' # add some proper site authentication later instead authenticate req, (body) -> if !body redirectURL = "https://forum.pokebattle.com/session/sso" redirectURL += "?return_path=https://sim.pokebattle.com" return res.redirect(redirectURL) # The remote URL returns `username`, but we'd like a more unified interface, # so we replace `username` with `name`. body.name = body.username delete body.username req.user = _.clone(body) hmac = crypto.createHmac('sha256', config.SECRET_KEY) req.user.token = hmac.update("#{req.user.id}").digest('hex') redis.shard('hset', USER_KEY, req.user.id, JSON.stringify(body), next) # If the id and token match, the associated user object is returned. exports.matchToken = (id, token, next) -> hmac = crypto.createHmac('sha256', config.SECRET_KEY) if hmac.update("#{id}").digest('hex') != token return next(new Error("Invalid session!")) redis.shard 'hget', USER_KEY, id, (err, jsonString) -> if err then return next(err) json = JSON.parse(jsonString) return next(new Error("Invalid session!")) if !json exports.getAuth json.name, (err, authLevel) -> if err then return next(err) json.authority = authLevel return next(null, json) # Authenticates against the site. A user object is returned if successful, or # null if unsuccessful. authenticate = (req, next) -> id = req.cookies.sessionid return next(generateUser(req)) if config.IS_LOCAL return next() if !id request.get "https://pokebattle.com/api/v1/user/#{id}", (err, res, body) -> return next() if err || res.statusCode != 200 return next(body) generateUsername = (req) -> name = req.param('user') return name if name {SpeciesData} = require './xy/data' randomName = (name for name of SpeciesData) randomName = randomName[Math.floor(Math.random() * randomName.length)] randomName = randomName.split(/\s+/)[0] randomName += "Fan" + Math.floor(Math.random() * 10000) randomName generateId = (req) -> req.param('id') || Math.floor(1000000 * Math.random()) generateUser = (req) -> {id: generateId(req), username: generateUsername(req)} # Authorization exports.levels = USER : 1 DRIVER : 2 MOD : 3 MODERATOR : 3 ADMIN : 4 ADMINISTRATOR : 4 OWNER : 5 LEVEL_VALUES = (value for key, value of exports.levels) exports.getAuth = (id, next) -> id = String(id).toLowerCase() redis.hget AUTH_KEY, id, (err, auth) -> if err then return next(err) auth = parseInt(auth, 10) || exports.levels.USER next(null, auth) exports.setAuth = (id, newAuthLevel, next) -> id = String(id).toLowerCase() if newAuthLevel not in LEVEL_VALUES next(new Error("Incorrect auth level: #{newAuthLevel}")) redis.hset(AUTH_KEY, id, newAuthLevel, next) # Ban # Length is in seconds. exports.ban = (id, reason, length, next) -> id = id.toLowerCase() key = "#{BANS_KEY}:#{id}" if length > 0 redis.setex(key, length, reason, next) else redis.set(key, reason, next) exports.unban = (id, next) -> id = String(id).toLowerCase() redis.del("#{BANS_KEY}:#{id}", next) exports.getBanReason = (id, next) -> id = String(id).toLowerCase() redis.get("#{BANS_KEY}:#{id}", next) exports.getBanTTL = (id, next) -> id = String(id).toLowerCase() key = "#{BANS_KEY}:#{id}" redis.exists key, (err, result) -> if !result # In older versions of Redis, TTL returns -1 if key doesn't exist. return next(null, -2) else redis.ttl(key, next) # Mute # Length is in seconds. exports.mute = (id, reason, length, next) -> id = String(id).toLowerCase() key = "#{MUTE_KEY}:#{id}" if length > 0 redis.setex(key, length, reason, next) else redis.set(key, reason, next) exports.unmute = (id, next) -> id = String(id).toLowerCase() key = "#{MUTE_KEY}:#{id}" redis.del(key, next) exports.getMuteTTL = (id, next) -> id = String(id).toLowerCase() key = "#{MUTE_KEY}:#{id}" redis.exists key, (err, result) -> if !result # In older versions of Redis, TTL returns -1 if key doesn't exist. return next(null, -2) else redis.ttl(key, next)
90041
{_} = require 'underscore' crypto = require('crypto') request = require 'request' authHeaders = {AUTHUSER: process.env.AUTHUSER, AUTHTOKEN: process.env.AUTHTOKEN} request = request.defaults(json: true, headers: authHeaders, timeout: 30 * 1000) config = require './config' redis = require './redis' USER_KEY = "<KEY>" AUTH_KEY = "<KEY>" BANS_KEY = "<KEY>" MUTE_KEY = "<KEY>" # This middleware checks if a user is authenticated through the site. If yes, # then information about the user is stored in req.user. In addition, we store # a token associated with that user into req.user.token. # # User information is also stored in redis. exports.middleware = -> (req, res, next) -> return next() if req.path.match(/^\/css|^\/js|^\/fonts/) return next() if req.path == '/leaderboard' # add some proper site authentication later instead authenticate req, (body) -> if !body redirectURL = "https://forum.pokebattle.com/session/sso" redirectURL += "?return_path=https://sim.pokebattle.com" return res.redirect(redirectURL) # The remote URL returns `username`, but we'd like a more unified interface, # so we replace `username` with `name`. body.name = body.username delete body.username req.user = _.clone(body) hmac = crypto.createHmac('sha256', config.SECRET_KEY) req.user.token = hmac.update("#{req.user.id}").digest('hex') redis.shard('hset', USER_KEY, req.user.id, JSON.stringify(body), next) # If the id and token match, the associated user object is returned. exports.matchToken = (id, token, next) -> hmac = crypto.createHmac('sha256', config.SECRET_KEY) if hmac.update("#{id}").digest('hex') != token return next(new Error("Invalid session!")) redis.shard 'hget', USER_KEY, id, (err, jsonString) -> if err then return next(err) json = JSON.parse(jsonString) return next(new Error("Invalid session!")) if !json exports.getAuth json.name, (err, authLevel) -> if err then return next(err) json.authority = authLevel return next(null, json) # Authenticates against the site. A user object is returned if successful, or # null if unsuccessful. authenticate = (req, next) -> id = req.cookies.sessionid return next(generateUser(req)) if config.IS_LOCAL return next() if !id request.get "https://pokebattle.com/api/v1/user/#{id}", (err, res, body) -> return next() if err || res.statusCode != 200 return next(body) generateUsername = (req) -> name = req.param('user') return name if name {SpeciesData} = require './xy/data' randomName = (name for name of SpeciesData) randomName = randomName[Math.floor(Math.random() * randomName.length)] randomName = randomName.split(/\s+/)[0] randomName += "Fan" + Math.floor(Math.random() * 10000) randomName generateId = (req) -> req.param('id') || Math.floor(1000000 * Math.random()) generateUser = (req) -> {id: generateId(req), username: generateUsername(req)} # Authorization exports.levels = USER : 1 DRIVER : 2 MOD : 3 MODERATOR : 3 ADMIN : 4 ADMINISTRATOR : 4 OWNER : 5 LEVEL_VALUES = (value for key, value of exports.levels) exports.getAuth = (id, next) -> id = String(id).toLowerCase() redis.hget AUTH_KEY, id, (err, auth) -> if err then return next(err) auth = parseInt(auth, 10) || exports.levels.USER next(null, auth) exports.setAuth = (id, newAuthLevel, next) -> id = String(id).toLowerCase() if newAuthLevel not in LEVEL_VALUES next(new Error("Incorrect auth level: #{newAuthLevel}")) redis.hset(AUTH_KEY, id, newAuthLevel, next) # Ban # Length is in seconds. exports.ban = (id, reason, length, next) -> id = id.toLowerCase() key = "#{BANS_KEY}:#{id}" if length > 0 redis.setex(key, length, reason, next) else redis.set(key, reason, next) exports.unban = (id, next) -> id = String(id).toLowerCase() redis.del("#{BANS_KEY}:#{id}", next) exports.getBanReason = (id, next) -> id = String(id).toLowerCase() redis.get("#{BANS_KEY}:#{id}", next) exports.getBanTTL = (id, next) -> id = String(id).toLowerCase() key = "#{BANS_KEY}:<KEY>{id}" redis.exists key, (err, result) -> if !result # In older versions of Redis, TTL returns -1 if key doesn't exist. return next(null, -2) else redis.ttl(key, next) # Mute # Length is in seconds. exports.mute = (id, reason, length, next) -> id = String(id).toLowerCase() key = "#{MUTE_KEY}:<KEY>{id}" if length > 0 redis.setex(key, length, reason, next) else redis.set(key, reason, next) exports.unmute = (id, next) -> id = String(id).toLowerCase() key = "#{MUTE_<KEY>id<KEY>}" redis.del(key, next) exports.getMuteTTL = (id, next) -> id = String(id).toLowerCase() key = "#{MUTE_KEY}:<KEY>{id}" redis.exists key, (err, result) -> if !result # In older versions of Redis, TTL returns -1 if key doesn't exist. return next(null, -2) else redis.ttl(key, next)
true
{_} = require 'underscore' crypto = require('crypto') request = require 'request' authHeaders = {AUTHUSER: process.env.AUTHUSER, AUTHTOKEN: process.env.AUTHTOKEN} request = request.defaults(json: true, headers: authHeaders, timeout: 30 * 1000) config = require './config' redis = require './redis' USER_KEY = "PI:KEY:<KEY>END_PI" AUTH_KEY = "PI:KEY:<KEY>END_PI" BANS_KEY = "PI:KEY:<KEY>END_PI" MUTE_KEY = "PI:KEY:<KEY>END_PI" # This middleware checks if a user is authenticated through the site. If yes, # then information about the user is stored in req.user. In addition, we store # a token associated with that user into req.user.token. # # User information is also stored in redis. exports.middleware = -> (req, res, next) -> return next() if req.path.match(/^\/css|^\/js|^\/fonts/) return next() if req.path == '/leaderboard' # add some proper site authentication later instead authenticate req, (body) -> if !body redirectURL = "https://forum.pokebattle.com/session/sso" redirectURL += "?return_path=https://sim.pokebattle.com" return res.redirect(redirectURL) # The remote URL returns `username`, but we'd like a more unified interface, # so we replace `username` with `name`. body.name = body.username delete body.username req.user = _.clone(body) hmac = crypto.createHmac('sha256', config.SECRET_KEY) req.user.token = hmac.update("#{req.user.id}").digest('hex') redis.shard('hset', USER_KEY, req.user.id, JSON.stringify(body), next) # If the id and token match, the associated user object is returned. exports.matchToken = (id, token, next) -> hmac = crypto.createHmac('sha256', config.SECRET_KEY) if hmac.update("#{id}").digest('hex') != token return next(new Error("Invalid session!")) redis.shard 'hget', USER_KEY, id, (err, jsonString) -> if err then return next(err) json = JSON.parse(jsonString) return next(new Error("Invalid session!")) if !json exports.getAuth json.name, (err, authLevel) -> if err then return next(err) json.authority = authLevel return next(null, json) # Authenticates against the site. A user object is returned if successful, or # null if unsuccessful. authenticate = (req, next) -> id = req.cookies.sessionid return next(generateUser(req)) if config.IS_LOCAL return next() if !id request.get "https://pokebattle.com/api/v1/user/#{id}", (err, res, body) -> return next() if err || res.statusCode != 200 return next(body) generateUsername = (req) -> name = req.param('user') return name if name {SpeciesData} = require './xy/data' randomName = (name for name of SpeciesData) randomName = randomName[Math.floor(Math.random() * randomName.length)] randomName = randomName.split(/\s+/)[0] randomName += "Fan" + Math.floor(Math.random() * 10000) randomName generateId = (req) -> req.param('id') || Math.floor(1000000 * Math.random()) generateUser = (req) -> {id: generateId(req), username: generateUsername(req)} # Authorization exports.levels = USER : 1 DRIVER : 2 MOD : 3 MODERATOR : 3 ADMIN : 4 ADMINISTRATOR : 4 OWNER : 5 LEVEL_VALUES = (value for key, value of exports.levels) exports.getAuth = (id, next) -> id = String(id).toLowerCase() redis.hget AUTH_KEY, id, (err, auth) -> if err then return next(err) auth = parseInt(auth, 10) || exports.levels.USER next(null, auth) exports.setAuth = (id, newAuthLevel, next) -> id = String(id).toLowerCase() if newAuthLevel not in LEVEL_VALUES next(new Error("Incorrect auth level: #{newAuthLevel}")) redis.hset(AUTH_KEY, id, newAuthLevel, next) # Ban # Length is in seconds. exports.ban = (id, reason, length, next) -> id = id.toLowerCase() key = "#{BANS_KEY}:#{id}" if length > 0 redis.setex(key, length, reason, next) else redis.set(key, reason, next) exports.unban = (id, next) -> id = String(id).toLowerCase() redis.del("#{BANS_KEY}:#{id}", next) exports.getBanReason = (id, next) -> id = String(id).toLowerCase() redis.get("#{BANS_KEY}:#{id}", next) exports.getBanTTL = (id, next) -> id = String(id).toLowerCase() key = "#{BANS_KEY}:PI:KEY:<KEY>END_PI{id}" redis.exists key, (err, result) -> if !result # In older versions of Redis, TTL returns -1 if key doesn't exist. return next(null, -2) else redis.ttl(key, next) # Mute # Length is in seconds. exports.mute = (id, reason, length, next) -> id = String(id).toLowerCase() key = "#{MUTE_KEY}:PI:KEY:<KEY>END_PI{id}" if length > 0 redis.setex(key, length, reason, next) else redis.set(key, reason, next) exports.unmute = (id, next) -> id = String(id).toLowerCase() key = "#{MUTE_PI:KEY:<KEY>END_PIidPI:KEY:<KEY>END_PI}" redis.del(key, next) exports.getMuteTTL = (id, next) -> id = String(id).toLowerCase() key = "#{MUTE_KEY}:PI:KEY:<KEY>END_PI{id}" redis.exists key, (err, result) -> if !result # In older versions of Redis, TTL returns -1 if key doesn't exist. return next(null, -2) else redis.ttl(key, next)
[ { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ", "end": 38, "score": 0.9998891949653625, "start": 25, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright...
public/taiga-front/app/coffee/modules/backlog/lightboxes.coffee
mabotech/maboss
0
### # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com> # Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/backlog/lightboxes.coffee ### taiga = @.taiga bindOnce = @.taiga.bindOnce debounce = @.taiga.debounce module = angular.module("taigaBacklog") ############################################################################# ## Creare/Edit Sprint Lightbox Directive ############################################################################# CreateEditSprint = ($repo, $confirm, $rs, $rootscope, lightboxService, $loading) -> link = ($scope, $el, attrs) -> hasErrors = false createSprint = true $scope.sprint = { project: null name: null estimated_start: null estimated_finish: null } submit = debounce 2000, (event) => event.preventDefault() target = angular.element(event.currentTarget) form = $el.find("form").checksley() if not form.validate() hasErrors = true $el.find(".last-sprint-name").addClass("disappear") return hasErrors = false newSprint = angular.copy($scope.sprint) broadcastEvent = null if createSprint newSprint.estimated_start = moment(newSprint.estimated_start).format("YYYY-MM-DD") newSprint.estimated_finish = moment(newSprint.estimated_finish).format("YYYY-MM-DD") promise = $repo.create("milestones", newSprint) broadcastEvent = "sprintform:create:success" else newSprint.setAttr("estimated_start", moment(newSprint.estimated_start).format("YYYY-MM-DD")) newSprint.setAttr("estimated_finish", moment(newSprint.estimated_finish).format("YYYY-MM-DD")) promise = $repo.save(newSprint) broadcastEvent = "sprintform:edit:success" $loading.start(submitButton) promise.then (data) -> $loading.finish(submitButton) $scope.sprintsCounter += 1 if createSprint $rootscope.$broadcast(broadcastEvent, data) lightboxService.close($el) promise.then null, (data) -> $loading.finish(submitButton) form.setErrors(data) if data._error_message $confirm.notify("light-error", data._error_message) else if data.__all__ $confirm.notify("light-error", data.__all__[0]) remove = -> #TODO: i18n title = "Delete sprint" message = $scope.sprint.name $confirm.askOnDelete(title, message).then (finish) => onSuccess = -> finish() $scope.milestonesCounter -= 1 lightboxService.close($el) $rootscope.$broadcast("sprintform:remove:success") onError = -> finish(false) $confirm.notify("error") $repo.remove($scope.sprint).then(onSuccess, onError) $scope.$on "sprintform:create", (event, projectId) -> createSprint = true $scope.sprint.project = projectId $scope.sprint.name = null $scope.sprint.slug = null lastSprint = $scope.sprints[0] estimatedStart = moment() if $scope.sprint.estimated_start estimatedStart = moment($scope.sprint.estimated_start) else if lastSprint? estimatedStart = moment(lastSprint.estimated_finish) $scope.sprint.estimated_start = estimatedStart.format("DD MMM YYYY") estimatedFinish = moment().add(2, "weeks") if $scope.sprint.estimated_finish estimatedFinish = moment($scope.sprint.estimated_finish) else if lastSprint? estimatedFinish = moment(lastSprint.estimated_finish).add(2, "weeks") $scope.sprint.estimated_finish = estimatedFinish.format("DD MMM YYYY") lastSprintNameDom = $el.find(".last-sprint-name") if lastSprint?.name? lastSprintNameDom.html(" last sprint is <strong> #{lastSprint.name} ;-) </strong>") $el.find(".delete-sprint").addClass("hidden") $el.find(".title").text("New sprint") #TODO i18n $el.find(".button-green").text("Create") #TODO i18n lightboxService.open($el) $el.find(".sprint-name").focus() $scope.$on "sprintform:edit", (ctx, sprint) -> createSprint = false $scope.$apply -> $scope.sprint = sprint $scope.sprint.estimated_start = moment($scope.sprint.estimated_start).format("DD MMM YYYY") $scope.sprint.estimated_finish = moment($scope.sprint.estimated_finish).format("DD MMM YYYY") $el.find(".delete-sprint").removeClass("hidden") $el.find(".title").text("Edit sprint") #TODO i18n $el.find(".button-green").text("Save") #TODO i18n lightboxService.open($el) $el.find(".sprint-name").focus().select() $el.find(".last-sprint-name").addClass("disappear") $el.on "keyup", ".sprint-name", (event) -> if $el.find(".sprint-name").val().length > 0 or hasErrors $el.find(".last-sprint-name").addClass("disappear") else $el.find(".last-sprint-name").removeClass("disappear") submitButton = $el.find(".submit-button") $el.on "submit", "form", submit $el.on "click", ".submit-button", submit $el.on "click", ".delete-sprint .icon-delete", (event) -> event.preventDefault() remove() $scope.$on "$destroy", -> $el.off() return {link: link} module.directive("tgLbCreateEditSprint", [ "$tgRepo", "$tgConfirm", "$tgResources", "$rootScope", "lightboxService" "$tgLoading" CreateEditSprint ])
113153
### # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/backlog/lightboxes.coffee ### taiga = @.taiga bindOnce = @.taiga.bindOnce debounce = @.taiga.debounce module = angular.module("taigaBacklog") ############################################################################# ## Creare/Edit Sprint Lightbox Directive ############################################################################# CreateEditSprint = ($repo, $confirm, $rs, $rootscope, lightboxService, $loading) -> link = ($scope, $el, attrs) -> hasErrors = false createSprint = true $scope.sprint = { project: null name: null estimated_start: null estimated_finish: null } submit = debounce 2000, (event) => event.preventDefault() target = angular.element(event.currentTarget) form = $el.find("form").checksley() if not form.validate() hasErrors = true $el.find(".last-sprint-name").addClass("disappear") return hasErrors = false newSprint = angular.copy($scope.sprint) broadcastEvent = null if createSprint newSprint.estimated_start = moment(newSprint.estimated_start).format("YYYY-MM-DD") newSprint.estimated_finish = moment(newSprint.estimated_finish).format("YYYY-MM-DD") promise = $repo.create("milestones", newSprint) broadcastEvent = "sprintform:create:success" else newSprint.setAttr("estimated_start", moment(newSprint.estimated_start).format("YYYY-MM-DD")) newSprint.setAttr("estimated_finish", moment(newSprint.estimated_finish).format("YYYY-MM-DD")) promise = $repo.save(newSprint) broadcastEvent = "sprintform:edit:success" $loading.start(submitButton) promise.then (data) -> $loading.finish(submitButton) $scope.sprintsCounter += 1 if createSprint $rootscope.$broadcast(broadcastEvent, data) lightboxService.close($el) promise.then null, (data) -> $loading.finish(submitButton) form.setErrors(data) if data._error_message $confirm.notify("light-error", data._error_message) else if data.__all__ $confirm.notify("light-error", data.__all__[0]) remove = -> #TODO: i18n title = "Delete sprint" message = $scope.sprint.name $confirm.askOnDelete(title, message).then (finish) => onSuccess = -> finish() $scope.milestonesCounter -= 1 lightboxService.close($el) $rootscope.$broadcast("sprintform:remove:success") onError = -> finish(false) $confirm.notify("error") $repo.remove($scope.sprint).then(onSuccess, onError) $scope.$on "sprintform:create", (event, projectId) -> createSprint = true $scope.sprint.project = projectId $scope.sprint.name = null $scope.sprint.slug = null lastSprint = $scope.sprints[0] estimatedStart = moment() if $scope.sprint.estimated_start estimatedStart = moment($scope.sprint.estimated_start) else if lastSprint? estimatedStart = moment(lastSprint.estimated_finish) $scope.sprint.estimated_start = estimatedStart.format("DD MMM YYYY") estimatedFinish = moment().add(2, "weeks") if $scope.sprint.estimated_finish estimatedFinish = moment($scope.sprint.estimated_finish) else if lastSprint? estimatedFinish = moment(lastSprint.estimated_finish).add(2, "weeks") $scope.sprint.estimated_finish = estimatedFinish.format("DD MMM YYYY") lastSprintNameDom = $el.find(".last-sprint-name") if lastSprint?.name? lastSprintNameDom.html(" last sprint is <strong> #{lastSprint.name} ;-) </strong>") $el.find(".delete-sprint").addClass("hidden") $el.find(".title").text("New sprint") #TODO i18n $el.find(".button-green").text("Create") #TODO i18n lightboxService.open($el) $el.find(".sprint-name").focus() $scope.$on "sprintform:edit", (ctx, sprint) -> createSprint = false $scope.$apply -> $scope.sprint = sprint $scope.sprint.estimated_start = moment($scope.sprint.estimated_start).format("DD MMM YYYY") $scope.sprint.estimated_finish = moment($scope.sprint.estimated_finish).format("DD MMM YYYY") $el.find(".delete-sprint").removeClass("hidden") $el.find(".title").text("Edit sprint") #TODO i18n $el.find(".button-green").text("Save") #TODO i18n lightboxService.open($el) $el.find(".sprint-name").focus().select() $el.find(".last-sprint-name").addClass("disappear") $el.on "keyup", ".sprint-name", (event) -> if $el.find(".sprint-name").val().length > 0 or hasErrors $el.find(".last-sprint-name").addClass("disappear") else $el.find(".last-sprint-name").removeClass("disappear") submitButton = $el.find(".submit-button") $el.on "submit", "form", submit $el.on "click", ".submit-button", submit $el.on "click", ".delete-sprint .icon-delete", (event) -> event.preventDefault() remove() $scope.$on "$destroy", -> $el.off() return {link: link} module.directive("tgLbCreateEditSprint", [ "$tgRepo", "$tgConfirm", "$tgResources", "$rootScope", "lightboxService" "$tgLoading" CreateEditSprint ])
true
### # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/backlog/lightboxes.coffee ### taiga = @.taiga bindOnce = @.taiga.bindOnce debounce = @.taiga.debounce module = angular.module("taigaBacklog") ############################################################################# ## Creare/Edit Sprint Lightbox Directive ############################################################################# CreateEditSprint = ($repo, $confirm, $rs, $rootscope, lightboxService, $loading) -> link = ($scope, $el, attrs) -> hasErrors = false createSprint = true $scope.sprint = { project: null name: null estimated_start: null estimated_finish: null } submit = debounce 2000, (event) => event.preventDefault() target = angular.element(event.currentTarget) form = $el.find("form").checksley() if not form.validate() hasErrors = true $el.find(".last-sprint-name").addClass("disappear") return hasErrors = false newSprint = angular.copy($scope.sprint) broadcastEvent = null if createSprint newSprint.estimated_start = moment(newSprint.estimated_start).format("YYYY-MM-DD") newSprint.estimated_finish = moment(newSprint.estimated_finish).format("YYYY-MM-DD") promise = $repo.create("milestones", newSprint) broadcastEvent = "sprintform:create:success" else newSprint.setAttr("estimated_start", moment(newSprint.estimated_start).format("YYYY-MM-DD")) newSprint.setAttr("estimated_finish", moment(newSprint.estimated_finish).format("YYYY-MM-DD")) promise = $repo.save(newSprint) broadcastEvent = "sprintform:edit:success" $loading.start(submitButton) promise.then (data) -> $loading.finish(submitButton) $scope.sprintsCounter += 1 if createSprint $rootscope.$broadcast(broadcastEvent, data) lightboxService.close($el) promise.then null, (data) -> $loading.finish(submitButton) form.setErrors(data) if data._error_message $confirm.notify("light-error", data._error_message) else if data.__all__ $confirm.notify("light-error", data.__all__[0]) remove = -> #TODO: i18n title = "Delete sprint" message = $scope.sprint.name $confirm.askOnDelete(title, message).then (finish) => onSuccess = -> finish() $scope.milestonesCounter -= 1 lightboxService.close($el) $rootscope.$broadcast("sprintform:remove:success") onError = -> finish(false) $confirm.notify("error") $repo.remove($scope.sprint).then(onSuccess, onError) $scope.$on "sprintform:create", (event, projectId) -> createSprint = true $scope.sprint.project = projectId $scope.sprint.name = null $scope.sprint.slug = null lastSprint = $scope.sprints[0] estimatedStart = moment() if $scope.sprint.estimated_start estimatedStart = moment($scope.sprint.estimated_start) else if lastSprint? estimatedStart = moment(lastSprint.estimated_finish) $scope.sprint.estimated_start = estimatedStart.format("DD MMM YYYY") estimatedFinish = moment().add(2, "weeks") if $scope.sprint.estimated_finish estimatedFinish = moment($scope.sprint.estimated_finish) else if lastSprint? estimatedFinish = moment(lastSprint.estimated_finish).add(2, "weeks") $scope.sprint.estimated_finish = estimatedFinish.format("DD MMM YYYY") lastSprintNameDom = $el.find(".last-sprint-name") if lastSprint?.name? lastSprintNameDom.html(" last sprint is <strong> #{lastSprint.name} ;-) </strong>") $el.find(".delete-sprint").addClass("hidden") $el.find(".title").text("New sprint") #TODO i18n $el.find(".button-green").text("Create") #TODO i18n lightboxService.open($el) $el.find(".sprint-name").focus() $scope.$on "sprintform:edit", (ctx, sprint) -> createSprint = false $scope.$apply -> $scope.sprint = sprint $scope.sprint.estimated_start = moment($scope.sprint.estimated_start).format("DD MMM YYYY") $scope.sprint.estimated_finish = moment($scope.sprint.estimated_finish).format("DD MMM YYYY") $el.find(".delete-sprint").removeClass("hidden") $el.find(".title").text("Edit sprint") #TODO i18n $el.find(".button-green").text("Save") #TODO i18n lightboxService.open($el) $el.find(".sprint-name").focus().select() $el.find(".last-sprint-name").addClass("disappear") $el.on "keyup", ".sprint-name", (event) -> if $el.find(".sprint-name").val().length > 0 or hasErrors $el.find(".last-sprint-name").addClass("disappear") else $el.find(".last-sprint-name").removeClass("disappear") submitButton = $el.find(".submit-button") $el.on "submit", "form", submit $el.on "click", ".submit-button", submit $el.on "click", ".delete-sprint .icon-delete", (event) -> event.preventDefault() remove() $scope.$on "$destroy", -> $el.off() return {link: link} module.directive("tgLbCreateEditSprint", [ "$tgRepo", "$tgConfirm", "$tgResources", "$rootScope", "lightboxService" "$tgLoading" CreateEditSprint ])
[ { "context": "-move.coffee\n###\n# jquery.event.move\n#\n# 1.3.1\n#\n# Stephen Band\n#\n# Triggers 'movestart', 'move' and 'moveend' ev", "end": 132, "score": 0.9991316795349121, "start": 120, "tag": "NAME", "value": "Stephen Band" } ]
coffee/jquery-event-move.coffee
alejo8591/shurikend
0
### Inspired in jquery-event-move jquery-event-move: jquery-event-move.coffee ### # jquery.event.move # # 1.3.1 # # Stephen Band # # Triggers 'movestart', 'move' and 'moveend' events after # mousemoves following a mousedown cross a distance threshold, # similar to the native 'dragstart', 'drag' and 'dragend' events. # Move events are throttled to animation frames. Move event objects # have the properties: # # pageX: # pageY: Page coordinates of pointer. # startX: # startY: Page coordinates of pointer at movestart. # distX: # distY: Distance the pointer has moved since movestart. # deltaX: # deltaY: Distance the finger has moved since last event. # velocityX: # velocityY: Average velocity over last few events. ((module) -> if typeof define is "function" and define.amd # AMD. Register as an anonymous module. define ["jquery"], module else # Browser globals module jQuery ) (jQuery, undefined_) -> # Number of pixels a pressed pointer travels before movestart # event is fired. # Just sugar, so we can have arguments in the same order as # add and remove. # Shim for requestAnimationFrame, falling back to timer. See: # see http://paulirish.com/2011/requestanimationframe-for-smart-animating/ # Constructors Timer = (fn) -> trigger = (time) -> if active callback() requestFrame trigger running = true active = false else running = false callback = fn active = false running = false @kick = (fn) -> active = true trigger() unless running @end = (fn) -> cb = callback return unless fn # If the timer is not running, simply call the end callback. unless running fn() # If the timer is running, and has been kicked lately, then # queue up the current callback and the end callback, otherwise # just the end callback. else callback = (if active then -> cb() fn() else fn) active = true # Functions returnTrue = -> true returnFalse = -> false preventDefault = (e) -> e.preventDefault() preventIgnoreTags = (e) -> # Don't prevent interaction with form elements. return if ignoreTags[e.target.tagName.toLowerCase()] e.preventDefault() isLeftButton = (e) -> # Ignore mousedowns on any button other than the left (or primary) # mouse button, or when a modifier key is pressed. e.which is 1 and not e.ctrlKey and not e.altKey identifiedTouch = (touchList, id) -> i = undefined_ l = undefined_ return touchList.identifiedTouch(id) if touchList.identifiedTouch # touchList.identifiedTouch() does not exist in # webkit yet… we must do the search ourselves... i = -1 l = touchList.length return touchList[i] if touchList[i].identifier is id while ++i < l changedTouch = (e, event) -> touch = identifiedTouch(e.changedTouches, event.identifier) # This isn't the touch you're looking for. return unless touch # Chrome Android (at least) includes touches that have not # changed in e.changedTouches. That's a bit annoying. Check # that this touch has changed. return if touch.pageX is event.pageX and touch.pageY is event.pageY touch # Handlers that decide when the first movestart is triggered mousedown = (e) -> data = undefined_ return unless isLeftButton(e) data = target: e.target startX: e.pageX startY: e.pageY timeStamp: e.timeStamp add document, mouseevents.move, mousemove, data add document, mouseevents.cancel, mouseend, data mousemove = (e) -> data = e.data checkThreshold e, data, e, removeMouse mouseend = (e) -> removeMouse() removeMouse = -> remove document, mouseevents.move, mousemove remove document, mouseevents.cancel, removeMouse touchstart = (e) -> touch = undefined_ template = undefined_ # Don't get in the way of interaction with form elements. return if ignoreTags[e.target.tagName.toLowerCase()] touch = e.changedTouches[0] # iOS live updates the touch objects whereas Android gives us copies. # That means we can't trust the touchstart object to stay the same, # so we must copy the data. This object acts as a template for # movestart, move and moveend event objects. template = target: touch.target startX: touch.pageX startY: touch.pageY timeStamp: e.timeStamp identifier: touch.identifier # Use the touch identifier as a namespace, so that we can later # remove handlers pertaining only to this touch. add document, touchevents.move + "." + touch.identifier, touchmove, template add document, touchevents.cancel + "." + touch.identifier, touchend, template touchmove = (e) -> data = e.data touch = changedTouch(e, data) return unless touch checkThreshold e, data, touch, removeTouch touchend = (e) -> template = e.data touch = identifiedTouch(e.changedTouches, template.identifier) return unless touch removeTouch template.identifier removeTouch = (identifier) -> remove document, "." + identifier, touchmove remove document, "." + identifier, touchend # Logic for deciding when to trigger a movestart. checkThreshold = (e, template, touch, fn) -> distX = touch.pageX - template.startX distY = touch.pageY - template.startY # Do nothing if the threshold has not been crossed. return if (distX * distX) + (distY * distY) < (threshold * threshold) triggerStart e, template, touch, distX, distY, fn handled = -> # this._handled should return false once, and after return true. @_handled = returnTrue false flagAsHandled = (e) -> e._handled() triggerStart = (e, template, touch, distX, distY, fn) -> node = template.target touches = undefined_ time = undefined_ touches = e.targetTouches time = e.timeStamp - template.timeStamp # Create a movestart object with some special properties that # are passed only to the movestart handlers. template.type = "movestart" template.distX = distX template.distY = distY template.deltaX = distX template.deltaY = distY template.pageX = touch.pageX template.pageY = touch.pageY template.velocityX = distX / time template.velocityY = distY / time template.targetTouches = touches template.finger = (if touches then touches.length else 1) # The _handled method is fired to tell the default movestart # handler that one of the move events is bound. template._handled = handled # Pass the touchmove event so it can be prevented if or when # movestart is handled. template._preventTouchmoveDefault = -> e.preventDefault() # Trigger the movestart event. trigger template.target, template # Unbind handlers that tracked the touch or mouse up till now. fn template.identifier # Handlers that control what happens following a movestart activeMousemove = (e) -> event = e.data.event timer = e.data.timer updateEvent event, e, e.timeStamp, timer activeMouseend = (e) -> event = e.data.event timer = e.data.timer removeActiveMouse() endEvent event, timer, -> # Unbind the click suppressor, waiting until after mouseup # has been handled. setTimeout (-> remove event.target, "click", returnFalse ), 0 removeActiveMouse = (event) -> remove document, mouseevents.move, activeMousemove remove document, mouseevents.end, activeMouseend activeTouchmove = (e) -> event = e.data.event timer = e.data.timer touch = changedTouch(e, event) return unless touch # Stop the interface from gesturing e.preventDefault() event.targetTouches = e.targetTouches updateEvent event, touch, e.timeStamp, timer activeTouchend = (e) -> event = e.data.event timer = e.data.timer touch = identifiedTouch(e.changedTouches, event.identifier) # This isn't the touch you're looking for. return unless touch removeActiveTouch event endEvent event, timer removeActiveTouch = (event) -> remove document, "." + event.identifier, activeTouchmove remove document, "." + event.identifier, activeTouchend # Logic for triggering move and moveend events updateEvent = (event, touch, timeStamp, timer) -> time = timeStamp - event.timeStamp event.type = "move" event.distX = touch.pageX - event.startX event.distY = touch.pageY - event.startY event.deltaX = touch.pageX - event.pageX event.deltaY = touch.pageY - event.pageY # Average the velocity of the last few events using a decay # curve to even out spurious jumps in values. event.velocityX = 0.3 * event.velocityX + 0.7 * event.deltaX / time event.velocityY = 0.3 * event.velocityY + 0.7 * event.deltaY / time event.pageX = touch.pageX event.pageY = touch.pageY timer.kick() endEvent = (event, timer, fn) -> timer.end -> event.type = "moveend" trigger event.target, event fn and fn() # jQuery special event definition setup = (data, namespaces, eventHandle) -> # Stop the node from being dragged #add(this, 'dragstart.move drag.move', preventDefault); # Prevent text selection and touch interface scrolling #add(this, 'mousedown.move', preventIgnoreTags); # Tell movestart default handler that we've handled this add this, "movestart.move", flagAsHandled # Don't bind to the DOM. For speed. true teardown = (namespaces) -> remove this, "dragstart drag", preventDefault remove this, "mousedown touchstart", preventIgnoreTags remove this, "movestart", flagAsHandled # Don't bind to the DOM. For speed. true addMethod = (handleObj) -> # We're not interested in preventing defaults for handlers that # come from internal move or moveend bindings return if handleObj.namespace is "move" or handleObj.namespace is "moveend" # Stop the node from being dragged add this, "dragstart." + handleObj.guid + " drag." + handleObj.guid, preventDefault, `undefined`, handleObj.selector # Prevent text selection and touch interface scrolling add this, "mousedown." + handleObj.guid, preventIgnoreTags, `undefined`, handleObj.selector removeMethod = (handleObj) -> return if handleObj.namespace is "move" or handleObj.namespace is "moveend" remove this, "dragstart." + handleObj.guid + " drag." + handleObj.guid remove this, "mousedown." + handleObj.guid threshold = 6 add = jQuery.event.add remove = jQuery.event.remove trigger = (node, type, data) -> jQuery.event.trigger type, data, node requestFrame = (-> window.requestAnimationFrame or window.webkitRequestAnimationFrame or window.mozRequestAnimationFrame or window.oRequestAnimationFrame or window.msRequestAnimationFrame or (fn, element) -> window.setTimeout (-> fn() ), 25 )() ignoreTags = textarea: true input: true select: true button: true mouseevents = move: "mousemove" cancel: "mouseup dragstart" end: "mouseup" touchevents = move: "touchmove" cancel: "touchend" end: "touchend" jQuery.event.special.movestart = setup: setup teardown: teardown add: addMethod remove: removeMethod _default: (e) -> template = undefined_ data = undefined_ # If no move events were bound to any ancestors of this # target, high tail it out of here. return unless e._handled() template = target: e.target startX: e.startX startY: e.startY pageX: e.pageX pageY: e.pageY distX: e.distX distY: e.distY deltaX: e.deltaX deltaY: e.deltaY velocityX: e.velocityX velocityY: e.velocityY timeStamp: e.timeStamp identifier: e.identifier targetTouches: e.targetTouches finger: e.finger data = event: template timer: new Timer((time) -> trigger e.target, template ) if e.identifier is `undefined` # We're dealing with a mouse # Stop clicks from propagating during a move add e.target, "click", returnFalse add document, mouseevents.move, activeMousemove, data add document, mouseevents.end, activeMouseend, data else # We're dealing with a touch. Stop touchmove doing # anything defaulty. e._preventTouchmoveDefault() add document, touchevents.move + "." + e.identifier, activeTouchmove, data add document, touchevents.end + "." + e.identifier, activeTouchend, data jQuery.event.special.move = setup: -> # Bind a noop to movestart. Why? It's the movestart # setup that decides whether other move events are fired. add this, "movestart.move", jQuery.noop teardown: -> remove this, "movestart.move", jQuery.noop jQuery.event.special.moveend = setup: -> # Bind a noop to movestart. Why? It's the movestart # setup that decides whether other move events are fired. add this, "movestart.moveend", jQuery.noop teardown: -> remove this, "movestart.moveend", jQuery.noop add document, "mousedown.move", mousedown add document, "touchstart.move", touchstart # Make jQuery copy touch event properties over to the jQuery event # object, if they are not already listed. But only do the ones we # really need. IE7/8 do not have Array#indexOf(), but nor do they # have touch events, so let's assume we can ignore them. if typeof Array::indexOf is "function" ((jQuery, undefined_) -> props = ["changedTouches", "targetTouches"] l = props.length jQuery.event.props.push props[l] if jQuery.event.props.indexOf(props[l]) is -1 while l-- ) jQuery
73937
### Inspired in jquery-event-move jquery-event-move: jquery-event-move.coffee ### # jquery.event.move # # 1.3.1 # # <NAME> # # Triggers 'movestart', 'move' and 'moveend' events after # mousemoves following a mousedown cross a distance threshold, # similar to the native 'dragstart', 'drag' and 'dragend' events. # Move events are throttled to animation frames. Move event objects # have the properties: # # pageX: # pageY: Page coordinates of pointer. # startX: # startY: Page coordinates of pointer at movestart. # distX: # distY: Distance the pointer has moved since movestart. # deltaX: # deltaY: Distance the finger has moved since last event. # velocityX: # velocityY: Average velocity over last few events. ((module) -> if typeof define is "function" and define.amd # AMD. Register as an anonymous module. define ["jquery"], module else # Browser globals module jQuery ) (jQuery, undefined_) -> # Number of pixels a pressed pointer travels before movestart # event is fired. # Just sugar, so we can have arguments in the same order as # add and remove. # Shim for requestAnimationFrame, falling back to timer. See: # see http://paulirish.com/2011/requestanimationframe-for-smart-animating/ # Constructors Timer = (fn) -> trigger = (time) -> if active callback() requestFrame trigger running = true active = false else running = false callback = fn active = false running = false @kick = (fn) -> active = true trigger() unless running @end = (fn) -> cb = callback return unless fn # If the timer is not running, simply call the end callback. unless running fn() # If the timer is running, and has been kicked lately, then # queue up the current callback and the end callback, otherwise # just the end callback. else callback = (if active then -> cb() fn() else fn) active = true # Functions returnTrue = -> true returnFalse = -> false preventDefault = (e) -> e.preventDefault() preventIgnoreTags = (e) -> # Don't prevent interaction with form elements. return if ignoreTags[e.target.tagName.toLowerCase()] e.preventDefault() isLeftButton = (e) -> # Ignore mousedowns on any button other than the left (or primary) # mouse button, or when a modifier key is pressed. e.which is 1 and not e.ctrlKey and not e.altKey identifiedTouch = (touchList, id) -> i = undefined_ l = undefined_ return touchList.identifiedTouch(id) if touchList.identifiedTouch # touchList.identifiedTouch() does not exist in # webkit yet… we must do the search ourselves... i = -1 l = touchList.length return touchList[i] if touchList[i].identifier is id while ++i < l changedTouch = (e, event) -> touch = identifiedTouch(e.changedTouches, event.identifier) # This isn't the touch you're looking for. return unless touch # Chrome Android (at least) includes touches that have not # changed in e.changedTouches. That's a bit annoying. Check # that this touch has changed. return if touch.pageX is event.pageX and touch.pageY is event.pageY touch # Handlers that decide when the first movestart is triggered mousedown = (e) -> data = undefined_ return unless isLeftButton(e) data = target: e.target startX: e.pageX startY: e.pageY timeStamp: e.timeStamp add document, mouseevents.move, mousemove, data add document, mouseevents.cancel, mouseend, data mousemove = (e) -> data = e.data checkThreshold e, data, e, removeMouse mouseend = (e) -> removeMouse() removeMouse = -> remove document, mouseevents.move, mousemove remove document, mouseevents.cancel, removeMouse touchstart = (e) -> touch = undefined_ template = undefined_ # Don't get in the way of interaction with form elements. return if ignoreTags[e.target.tagName.toLowerCase()] touch = e.changedTouches[0] # iOS live updates the touch objects whereas Android gives us copies. # That means we can't trust the touchstart object to stay the same, # so we must copy the data. This object acts as a template for # movestart, move and moveend event objects. template = target: touch.target startX: touch.pageX startY: touch.pageY timeStamp: e.timeStamp identifier: touch.identifier # Use the touch identifier as a namespace, so that we can later # remove handlers pertaining only to this touch. add document, touchevents.move + "." + touch.identifier, touchmove, template add document, touchevents.cancel + "." + touch.identifier, touchend, template touchmove = (e) -> data = e.data touch = changedTouch(e, data) return unless touch checkThreshold e, data, touch, removeTouch touchend = (e) -> template = e.data touch = identifiedTouch(e.changedTouches, template.identifier) return unless touch removeTouch template.identifier removeTouch = (identifier) -> remove document, "." + identifier, touchmove remove document, "." + identifier, touchend # Logic for deciding when to trigger a movestart. checkThreshold = (e, template, touch, fn) -> distX = touch.pageX - template.startX distY = touch.pageY - template.startY # Do nothing if the threshold has not been crossed. return if (distX * distX) + (distY * distY) < (threshold * threshold) triggerStart e, template, touch, distX, distY, fn handled = -> # this._handled should return false once, and after return true. @_handled = returnTrue false flagAsHandled = (e) -> e._handled() triggerStart = (e, template, touch, distX, distY, fn) -> node = template.target touches = undefined_ time = undefined_ touches = e.targetTouches time = e.timeStamp - template.timeStamp # Create a movestart object with some special properties that # are passed only to the movestart handlers. template.type = "movestart" template.distX = distX template.distY = distY template.deltaX = distX template.deltaY = distY template.pageX = touch.pageX template.pageY = touch.pageY template.velocityX = distX / time template.velocityY = distY / time template.targetTouches = touches template.finger = (if touches then touches.length else 1) # The _handled method is fired to tell the default movestart # handler that one of the move events is bound. template._handled = handled # Pass the touchmove event so it can be prevented if or when # movestart is handled. template._preventTouchmoveDefault = -> e.preventDefault() # Trigger the movestart event. trigger template.target, template # Unbind handlers that tracked the touch or mouse up till now. fn template.identifier # Handlers that control what happens following a movestart activeMousemove = (e) -> event = e.data.event timer = e.data.timer updateEvent event, e, e.timeStamp, timer activeMouseend = (e) -> event = e.data.event timer = e.data.timer removeActiveMouse() endEvent event, timer, -> # Unbind the click suppressor, waiting until after mouseup # has been handled. setTimeout (-> remove event.target, "click", returnFalse ), 0 removeActiveMouse = (event) -> remove document, mouseevents.move, activeMousemove remove document, mouseevents.end, activeMouseend activeTouchmove = (e) -> event = e.data.event timer = e.data.timer touch = changedTouch(e, event) return unless touch # Stop the interface from gesturing e.preventDefault() event.targetTouches = e.targetTouches updateEvent event, touch, e.timeStamp, timer activeTouchend = (e) -> event = e.data.event timer = e.data.timer touch = identifiedTouch(e.changedTouches, event.identifier) # This isn't the touch you're looking for. return unless touch removeActiveTouch event endEvent event, timer removeActiveTouch = (event) -> remove document, "." + event.identifier, activeTouchmove remove document, "." + event.identifier, activeTouchend # Logic for triggering move and moveend events updateEvent = (event, touch, timeStamp, timer) -> time = timeStamp - event.timeStamp event.type = "move" event.distX = touch.pageX - event.startX event.distY = touch.pageY - event.startY event.deltaX = touch.pageX - event.pageX event.deltaY = touch.pageY - event.pageY # Average the velocity of the last few events using a decay # curve to even out spurious jumps in values. event.velocityX = 0.3 * event.velocityX + 0.7 * event.deltaX / time event.velocityY = 0.3 * event.velocityY + 0.7 * event.deltaY / time event.pageX = touch.pageX event.pageY = touch.pageY timer.kick() endEvent = (event, timer, fn) -> timer.end -> event.type = "moveend" trigger event.target, event fn and fn() # jQuery special event definition setup = (data, namespaces, eventHandle) -> # Stop the node from being dragged #add(this, 'dragstart.move drag.move', preventDefault); # Prevent text selection and touch interface scrolling #add(this, 'mousedown.move', preventIgnoreTags); # Tell movestart default handler that we've handled this add this, "movestart.move", flagAsHandled # Don't bind to the DOM. For speed. true teardown = (namespaces) -> remove this, "dragstart drag", preventDefault remove this, "mousedown touchstart", preventIgnoreTags remove this, "movestart", flagAsHandled # Don't bind to the DOM. For speed. true addMethod = (handleObj) -> # We're not interested in preventing defaults for handlers that # come from internal move or moveend bindings return if handleObj.namespace is "move" or handleObj.namespace is "moveend" # Stop the node from being dragged add this, "dragstart." + handleObj.guid + " drag." + handleObj.guid, preventDefault, `undefined`, handleObj.selector # Prevent text selection and touch interface scrolling add this, "mousedown." + handleObj.guid, preventIgnoreTags, `undefined`, handleObj.selector removeMethod = (handleObj) -> return if handleObj.namespace is "move" or handleObj.namespace is "moveend" remove this, "dragstart." + handleObj.guid + " drag." + handleObj.guid remove this, "mousedown." + handleObj.guid threshold = 6 add = jQuery.event.add remove = jQuery.event.remove trigger = (node, type, data) -> jQuery.event.trigger type, data, node requestFrame = (-> window.requestAnimationFrame or window.webkitRequestAnimationFrame or window.mozRequestAnimationFrame or window.oRequestAnimationFrame or window.msRequestAnimationFrame or (fn, element) -> window.setTimeout (-> fn() ), 25 )() ignoreTags = textarea: true input: true select: true button: true mouseevents = move: "mousemove" cancel: "mouseup dragstart" end: "mouseup" touchevents = move: "touchmove" cancel: "touchend" end: "touchend" jQuery.event.special.movestart = setup: setup teardown: teardown add: addMethod remove: removeMethod _default: (e) -> template = undefined_ data = undefined_ # If no move events were bound to any ancestors of this # target, high tail it out of here. return unless e._handled() template = target: e.target startX: e.startX startY: e.startY pageX: e.pageX pageY: e.pageY distX: e.distX distY: e.distY deltaX: e.deltaX deltaY: e.deltaY velocityX: e.velocityX velocityY: e.velocityY timeStamp: e.timeStamp identifier: e.identifier targetTouches: e.targetTouches finger: e.finger data = event: template timer: new Timer((time) -> trigger e.target, template ) if e.identifier is `undefined` # We're dealing with a mouse # Stop clicks from propagating during a move add e.target, "click", returnFalse add document, mouseevents.move, activeMousemove, data add document, mouseevents.end, activeMouseend, data else # We're dealing with a touch. Stop touchmove doing # anything defaulty. e._preventTouchmoveDefault() add document, touchevents.move + "." + e.identifier, activeTouchmove, data add document, touchevents.end + "." + e.identifier, activeTouchend, data jQuery.event.special.move = setup: -> # Bind a noop to movestart. Why? It's the movestart # setup that decides whether other move events are fired. add this, "movestart.move", jQuery.noop teardown: -> remove this, "movestart.move", jQuery.noop jQuery.event.special.moveend = setup: -> # Bind a noop to movestart. Why? It's the movestart # setup that decides whether other move events are fired. add this, "movestart.moveend", jQuery.noop teardown: -> remove this, "movestart.moveend", jQuery.noop add document, "mousedown.move", mousedown add document, "touchstart.move", touchstart # Make jQuery copy touch event properties over to the jQuery event # object, if they are not already listed. But only do the ones we # really need. IE7/8 do not have Array#indexOf(), but nor do they # have touch events, so let's assume we can ignore them. if typeof Array::indexOf is "function" ((jQuery, undefined_) -> props = ["changedTouches", "targetTouches"] l = props.length jQuery.event.props.push props[l] if jQuery.event.props.indexOf(props[l]) is -1 while l-- ) jQuery
true
### Inspired in jquery-event-move jquery-event-move: jquery-event-move.coffee ### # jquery.event.move # # 1.3.1 # # PI:NAME:<NAME>END_PI # # Triggers 'movestart', 'move' and 'moveend' events after # mousemoves following a mousedown cross a distance threshold, # similar to the native 'dragstart', 'drag' and 'dragend' events. # Move events are throttled to animation frames. Move event objects # have the properties: # # pageX: # pageY: Page coordinates of pointer. # startX: # startY: Page coordinates of pointer at movestart. # distX: # distY: Distance the pointer has moved since movestart. # deltaX: # deltaY: Distance the finger has moved since last event. # velocityX: # velocityY: Average velocity over last few events. ((module) -> if typeof define is "function" and define.amd # AMD. Register as an anonymous module. define ["jquery"], module else # Browser globals module jQuery ) (jQuery, undefined_) -> # Number of pixels a pressed pointer travels before movestart # event is fired. # Just sugar, so we can have arguments in the same order as # add and remove. # Shim for requestAnimationFrame, falling back to timer. See: # see http://paulirish.com/2011/requestanimationframe-for-smart-animating/ # Constructors Timer = (fn) -> trigger = (time) -> if active callback() requestFrame trigger running = true active = false else running = false callback = fn active = false running = false @kick = (fn) -> active = true trigger() unless running @end = (fn) -> cb = callback return unless fn # If the timer is not running, simply call the end callback. unless running fn() # If the timer is running, and has been kicked lately, then # queue up the current callback and the end callback, otherwise # just the end callback. else callback = (if active then -> cb() fn() else fn) active = true # Functions returnTrue = -> true returnFalse = -> false preventDefault = (e) -> e.preventDefault() preventIgnoreTags = (e) -> # Don't prevent interaction with form elements. return if ignoreTags[e.target.tagName.toLowerCase()] e.preventDefault() isLeftButton = (e) -> # Ignore mousedowns on any button other than the left (or primary) # mouse button, or when a modifier key is pressed. e.which is 1 and not e.ctrlKey and not e.altKey identifiedTouch = (touchList, id) -> i = undefined_ l = undefined_ return touchList.identifiedTouch(id) if touchList.identifiedTouch # touchList.identifiedTouch() does not exist in # webkit yet… we must do the search ourselves... i = -1 l = touchList.length return touchList[i] if touchList[i].identifier is id while ++i < l changedTouch = (e, event) -> touch = identifiedTouch(e.changedTouches, event.identifier) # This isn't the touch you're looking for. return unless touch # Chrome Android (at least) includes touches that have not # changed in e.changedTouches. That's a bit annoying. Check # that this touch has changed. return if touch.pageX is event.pageX and touch.pageY is event.pageY touch # Handlers that decide when the first movestart is triggered mousedown = (e) -> data = undefined_ return unless isLeftButton(e) data = target: e.target startX: e.pageX startY: e.pageY timeStamp: e.timeStamp add document, mouseevents.move, mousemove, data add document, mouseevents.cancel, mouseend, data mousemove = (e) -> data = e.data checkThreshold e, data, e, removeMouse mouseend = (e) -> removeMouse() removeMouse = -> remove document, mouseevents.move, mousemove remove document, mouseevents.cancel, removeMouse touchstart = (e) -> touch = undefined_ template = undefined_ # Don't get in the way of interaction with form elements. return if ignoreTags[e.target.tagName.toLowerCase()] touch = e.changedTouches[0] # iOS live updates the touch objects whereas Android gives us copies. # That means we can't trust the touchstart object to stay the same, # so we must copy the data. This object acts as a template for # movestart, move and moveend event objects. template = target: touch.target startX: touch.pageX startY: touch.pageY timeStamp: e.timeStamp identifier: touch.identifier # Use the touch identifier as a namespace, so that we can later # remove handlers pertaining only to this touch. add document, touchevents.move + "." + touch.identifier, touchmove, template add document, touchevents.cancel + "." + touch.identifier, touchend, template touchmove = (e) -> data = e.data touch = changedTouch(e, data) return unless touch checkThreshold e, data, touch, removeTouch touchend = (e) -> template = e.data touch = identifiedTouch(e.changedTouches, template.identifier) return unless touch removeTouch template.identifier removeTouch = (identifier) -> remove document, "." + identifier, touchmove remove document, "." + identifier, touchend # Logic for deciding when to trigger a movestart. checkThreshold = (e, template, touch, fn) -> distX = touch.pageX - template.startX distY = touch.pageY - template.startY # Do nothing if the threshold has not been crossed. return if (distX * distX) + (distY * distY) < (threshold * threshold) triggerStart e, template, touch, distX, distY, fn handled = -> # this._handled should return false once, and after return true. @_handled = returnTrue false flagAsHandled = (e) -> e._handled() triggerStart = (e, template, touch, distX, distY, fn) -> node = template.target touches = undefined_ time = undefined_ touches = e.targetTouches time = e.timeStamp - template.timeStamp # Create a movestart object with some special properties that # are passed only to the movestart handlers. template.type = "movestart" template.distX = distX template.distY = distY template.deltaX = distX template.deltaY = distY template.pageX = touch.pageX template.pageY = touch.pageY template.velocityX = distX / time template.velocityY = distY / time template.targetTouches = touches template.finger = (if touches then touches.length else 1) # The _handled method is fired to tell the default movestart # handler that one of the move events is bound. template._handled = handled # Pass the touchmove event so it can be prevented if or when # movestart is handled. template._preventTouchmoveDefault = -> e.preventDefault() # Trigger the movestart event. trigger template.target, template # Unbind handlers that tracked the touch or mouse up till now. fn template.identifier # Handlers that control what happens following a movestart activeMousemove = (e) -> event = e.data.event timer = e.data.timer updateEvent event, e, e.timeStamp, timer activeMouseend = (e) -> event = e.data.event timer = e.data.timer removeActiveMouse() endEvent event, timer, -> # Unbind the click suppressor, waiting until after mouseup # has been handled. setTimeout (-> remove event.target, "click", returnFalse ), 0 removeActiveMouse = (event) -> remove document, mouseevents.move, activeMousemove remove document, mouseevents.end, activeMouseend activeTouchmove = (e) -> event = e.data.event timer = e.data.timer touch = changedTouch(e, event) return unless touch # Stop the interface from gesturing e.preventDefault() event.targetTouches = e.targetTouches updateEvent event, touch, e.timeStamp, timer activeTouchend = (e) -> event = e.data.event timer = e.data.timer touch = identifiedTouch(e.changedTouches, event.identifier) # This isn't the touch you're looking for. return unless touch removeActiveTouch event endEvent event, timer removeActiveTouch = (event) -> remove document, "." + event.identifier, activeTouchmove remove document, "." + event.identifier, activeTouchend # Logic for triggering move and moveend events updateEvent = (event, touch, timeStamp, timer) -> time = timeStamp - event.timeStamp event.type = "move" event.distX = touch.pageX - event.startX event.distY = touch.pageY - event.startY event.deltaX = touch.pageX - event.pageX event.deltaY = touch.pageY - event.pageY # Average the velocity of the last few events using a decay # curve to even out spurious jumps in values. event.velocityX = 0.3 * event.velocityX + 0.7 * event.deltaX / time event.velocityY = 0.3 * event.velocityY + 0.7 * event.deltaY / time event.pageX = touch.pageX event.pageY = touch.pageY timer.kick() endEvent = (event, timer, fn) -> timer.end -> event.type = "moveend" trigger event.target, event fn and fn() # jQuery special event definition setup = (data, namespaces, eventHandle) -> # Stop the node from being dragged #add(this, 'dragstart.move drag.move', preventDefault); # Prevent text selection and touch interface scrolling #add(this, 'mousedown.move', preventIgnoreTags); # Tell movestart default handler that we've handled this add this, "movestart.move", flagAsHandled # Don't bind to the DOM. For speed. true teardown = (namespaces) -> remove this, "dragstart drag", preventDefault remove this, "mousedown touchstart", preventIgnoreTags remove this, "movestart", flagAsHandled # Don't bind to the DOM. For speed. true addMethod = (handleObj) -> # We're not interested in preventing defaults for handlers that # come from internal move or moveend bindings return if handleObj.namespace is "move" or handleObj.namespace is "moveend" # Stop the node from being dragged add this, "dragstart." + handleObj.guid + " drag." + handleObj.guid, preventDefault, `undefined`, handleObj.selector # Prevent text selection and touch interface scrolling add this, "mousedown." + handleObj.guid, preventIgnoreTags, `undefined`, handleObj.selector removeMethod = (handleObj) -> return if handleObj.namespace is "move" or handleObj.namespace is "moveend" remove this, "dragstart." + handleObj.guid + " drag." + handleObj.guid remove this, "mousedown." + handleObj.guid threshold = 6 add = jQuery.event.add remove = jQuery.event.remove trigger = (node, type, data) -> jQuery.event.trigger type, data, node requestFrame = (-> window.requestAnimationFrame or window.webkitRequestAnimationFrame or window.mozRequestAnimationFrame or window.oRequestAnimationFrame or window.msRequestAnimationFrame or (fn, element) -> window.setTimeout (-> fn() ), 25 )() ignoreTags = textarea: true input: true select: true button: true mouseevents = move: "mousemove" cancel: "mouseup dragstart" end: "mouseup" touchevents = move: "touchmove" cancel: "touchend" end: "touchend" jQuery.event.special.movestart = setup: setup teardown: teardown add: addMethod remove: removeMethod _default: (e) -> template = undefined_ data = undefined_ # If no move events were bound to any ancestors of this # target, high tail it out of here. return unless e._handled() template = target: e.target startX: e.startX startY: e.startY pageX: e.pageX pageY: e.pageY distX: e.distX distY: e.distY deltaX: e.deltaX deltaY: e.deltaY velocityX: e.velocityX velocityY: e.velocityY timeStamp: e.timeStamp identifier: e.identifier targetTouches: e.targetTouches finger: e.finger data = event: template timer: new Timer((time) -> trigger e.target, template ) if e.identifier is `undefined` # We're dealing with a mouse # Stop clicks from propagating during a move add e.target, "click", returnFalse add document, mouseevents.move, activeMousemove, data add document, mouseevents.end, activeMouseend, data else # We're dealing with a touch. Stop touchmove doing # anything defaulty. e._preventTouchmoveDefault() add document, touchevents.move + "." + e.identifier, activeTouchmove, data add document, touchevents.end + "." + e.identifier, activeTouchend, data jQuery.event.special.move = setup: -> # Bind a noop to movestart. Why? It's the movestart # setup that decides whether other move events are fired. add this, "movestart.move", jQuery.noop teardown: -> remove this, "movestart.move", jQuery.noop jQuery.event.special.moveend = setup: -> # Bind a noop to movestart. Why? It's the movestart # setup that decides whether other move events are fired. add this, "movestart.moveend", jQuery.noop teardown: -> remove this, "movestart.moveend", jQuery.noop add document, "mousedown.move", mousedown add document, "touchstart.move", touchstart # Make jQuery copy touch event properties over to the jQuery event # object, if they are not already listed. But only do the ones we # really need. IE7/8 do not have Array#indexOf(), but nor do they # have touch events, so let's assume we can ignore them. if typeof Array::indexOf is "function" ((jQuery, undefined_) -> props = ["changedTouches", "targetTouches"] l = props.length jQuery.event.props.push props[l] if jQuery.event.props.indexOf(props[l]) is -1 while l-- ) jQuery
[ { "context": "al/config'\n auth:\n username: 'team-uuid'\n password: 'team-token'\n jso", "end": 1502, "score": 0.9991478323936462, "start": 1493, "tag": "USERNAME", "value": "team-uuid" }, { "context": " username: 'team-uuid'\n ...
test/integration/virtual-non-gateblu-config-spec.coffee
octoblu/gateblu-shadow-service
0
http = require 'http' request = require 'request' shmock = require '@octoblu/shmock' Server = require '../../src/server' describe 'Virtual Non-Gateblu config event', -> describe 'with a shadow service', -> beforeEach (done) -> @meshblu = shmock 0xd00d @shadowService = shmock 0xcafe @server = new Server port: undefined, disableLogging: true shadowServiceUri: "http://localhost:#{0xcafe}" meshbluConfig: server: 'localhost' port: 0xd00d @server.run => @serverPort = @server.address().port done() afterEach (done) -> @server.stop done afterEach (done) -> @shadowService.close done afterEach (done) -> @meshblu.close done describe 'When the shadow service responds with a 204', -> beforeEach (done) -> teamAuth = new Buffer('team-uuid:team-token').toString 'base64' @meshblu .get '/v2/whoami' .set 'Authorization', "Basic #{teamAuth}" .reply 200, uuid: 'team-uuid', token: 'team-token' @proxyConfigToShadowService = @shadowService .post '/virtual/config' .set 'Authorization', "Basic #{teamAuth}" .send uuid: 'device-uuid', type: 'device:not-gateblu', foo: 'bar', shadowing: {uuid: 'some-uuid'} .reply 204 options = baseUrl: "http://localhost:#{@serverPort}" uri: '/virtual/config' auth: username: 'team-uuid' password: 'team-token' json: uuid: 'device-uuid' type: 'device:not-gateblu' shadowing: {uuid: 'some-uuid'} foo: 'bar' request.post options, (error, @response, @body) => done error it 'should return a 204', -> expect(@response.statusCode).to.equal 204, @body it 'should proxy the request to the shadow service', -> @proxyConfigToShadowService.done() describe 'When the shadow service responds with a 403', -> beforeEach (done) -> teamAuth = new Buffer('team-uuid:team-token').toString 'base64' @meshblu .get '/v2/whoami' .set 'Authorization', "Basic #{teamAuth}" .reply 200, uuid: 'team-uuid', token: 'team-token' @proxyConfigToShadowService = @shadowService .post '/virtual/config' .set 'Authorization', "Basic #{teamAuth}" .send uuid: 'device-uuid', type: 'device:not-gateblu', foo: 'bar', shadowing: {uuid: 'some-uuid'} .reply 403, 'Not authorized to modify that device' options = baseUrl: "http://localhost:#{@serverPort}" uri: '/virtual/config' auth: username: 'team-uuid' password: 'team-token' json: uuid: 'device-uuid' type: 'device:not-gateblu' foo: 'bar' shadowing: {uuid: 'some-uuid'} request.post options, (error, @response, @body) => done error it 'should return a 403', -> expect(@response.statusCode).to.equal 403, @body it 'should return the shadow service error', -> expect(@body).to.deep.equal 'Not authorized to modify that device' it 'should proxy the request to the shadow service', -> @proxyConfigToShadowService.done() describe 'with no shadow service', -> beforeEach (done) -> @meshblu = shmock 0xd00d @server = new Server port: undefined, disableLogging: true shadowServiceUri: "https://localhost:#{0xcafe}" meshbluConfig: server: 'localhost' port: 0xd00d @server.run => @serverPort = @server.address().port done() afterEach (done) -> @server.stop done afterEach (done) -> @meshblu.close done describe 'When a request is made', -> beforeEach (done) -> teamAuth = new Buffer('team-uuid:team-token').toString 'base64' @meshblu .get '/v2/whoami' .set 'Authorization', "Basic #{teamAuth}" .reply 200, uuid: 'team-uuid', token: 'team-token' options = baseUrl: "http://localhost:#{@serverPort}" uri: '/virtual/config' auth: username: 'team-uuid' password: 'team-token' json: uuid: 'device-uuid' type: 'device:not-gateblu' foo: 'bar' shadowing: {uuid: 'some-uuid'} request.post options, (error, @response, @body) => done error it 'should return a 502', -> expect(@response.statusCode).to.equal 502, @body it 'should return a helpful error', -> expect(@body).to.deep.equal 'Could not contact the shadow service'
26433
http = require 'http' request = require 'request' shmock = require '@octoblu/shmock' Server = require '../../src/server' describe 'Virtual Non-Gateblu config event', -> describe 'with a shadow service', -> beforeEach (done) -> @meshblu = shmock 0xd00d @shadowService = shmock 0xcafe @server = new Server port: undefined, disableLogging: true shadowServiceUri: "http://localhost:#{0xcafe}" meshbluConfig: server: 'localhost' port: 0xd00d @server.run => @serverPort = @server.address().port done() afterEach (done) -> @server.stop done afterEach (done) -> @shadowService.close done afterEach (done) -> @meshblu.close done describe 'When the shadow service responds with a 204', -> beforeEach (done) -> teamAuth = new Buffer('team-uuid:team-token').toString 'base64' @meshblu .get '/v2/whoami' .set 'Authorization', "Basic #{teamAuth}" .reply 200, uuid: 'team-uuid', token: 'team-token' @proxyConfigToShadowService = @shadowService .post '/virtual/config' .set 'Authorization', "Basic #{teamAuth}" .send uuid: 'device-uuid', type: 'device:not-gateblu', foo: 'bar', shadowing: {uuid: 'some-uuid'} .reply 204 options = baseUrl: "http://localhost:#{@serverPort}" uri: '/virtual/config' auth: username: 'team-uuid' password: '<PASSWORD>' json: uuid: 'device-uuid' type: 'device:not-gateblu' shadowing: {uuid: 'some-uuid'} foo: 'bar' request.post options, (error, @response, @body) => done error it 'should return a 204', -> expect(@response.statusCode).to.equal 204, @body it 'should proxy the request to the shadow service', -> @proxyConfigToShadowService.done() describe 'When the shadow service responds with a 403', -> beforeEach (done) -> teamAuth = new Buffer('team-uuid:team-token').toString 'base64' @meshblu .get '/v2/whoami' .set 'Authorization', "Basic #{teamAuth}" .reply 200, uuid: 'team-uuid', token: '<PASSWORD>' @proxyConfigToShadowService = @shadowService .post '/virtual/config' .set 'Authorization', "Basic #{teamAuth}" .send uuid: 'device-uuid', type: 'device:not-gateblu', foo: 'bar', shadowing: {uuid: 'some-uuid'} .reply 403, 'Not authorized to modify that device' options = baseUrl: "http://localhost:#{@serverPort}" uri: '/virtual/config' auth: username: 'team-uuid' password: '<PASSWORD>' json: uuid: 'device-uuid' type: 'device:not-gateblu' foo: 'bar' shadowing: {uuid: 'some-uuid'} request.post options, (error, @response, @body) => done error it 'should return a 403', -> expect(@response.statusCode).to.equal 403, @body it 'should return the shadow service error', -> expect(@body).to.deep.equal 'Not authorized to modify that device' it 'should proxy the request to the shadow service', -> @proxyConfigToShadowService.done() describe 'with no shadow service', -> beforeEach (done) -> @meshblu = shmock 0xd00d @server = new Server port: undefined, disableLogging: true shadowServiceUri: "https://localhost:#{0xcafe}" meshbluConfig: server: 'localhost' port: 0xd00d @server.run => @serverPort = @server.address().port done() afterEach (done) -> @server.stop done afterEach (done) -> @meshblu.close done describe 'When a request is made', -> beforeEach (done) -> teamAuth = new Buffer('team-uuid:team-token').toString 'base64' @meshblu .get '/v2/whoami' .set 'Authorization', "Basic #{teamAuth}" .reply 200, uuid: 'team-uuid', token: '<PASSWORD>' options = baseUrl: "http://localhost:#{@serverPort}" uri: '/virtual/config' auth: username: 'team-uuid' password: '<PASSWORD>' json: uuid: 'device-uuid' type: 'device:not-gateblu' foo: 'bar' shadowing: {uuid: 'some-uuid'} request.post options, (error, @response, @body) => done error it 'should return a 502', -> expect(@response.statusCode).to.equal 502, @body it 'should return a helpful error', -> expect(@body).to.deep.equal 'Could not contact the shadow service'
true
http = require 'http' request = require 'request' shmock = require '@octoblu/shmock' Server = require '../../src/server' describe 'Virtual Non-Gateblu config event', -> describe 'with a shadow service', -> beforeEach (done) -> @meshblu = shmock 0xd00d @shadowService = shmock 0xcafe @server = new Server port: undefined, disableLogging: true shadowServiceUri: "http://localhost:#{0xcafe}" meshbluConfig: server: 'localhost' port: 0xd00d @server.run => @serverPort = @server.address().port done() afterEach (done) -> @server.stop done afterEach (done) -> @shadowService.close done afterEach (done) -> @meshblu.close done describe 'When the shadow service responds with a 204', -> beforeEach (done) -> teamAuth = new Buffer('team-uuid:team-token').toString 'base64' @meshblu .get '/v2/whoami' .set 'Authorization', "Basic #{teamAuth}" .reply 200, uuid: 'team-uuid', token: 'team-token' @proxyConfigToShadowService = @shadowService .post '/virtual/config' .set 'Authorization', "Basic #{teamAuth}" .send uuid: 'device-uuid', type: 'device:not-gateblu', foo: 'bar', shadowing: {uuid: 'some-uuid'} .reply 204 options = baseUrl: "http://localhost:#{@serverPort}" uri: '/virtual/config' auth: username: 'team-uuid' password: 'PI:PASSWORD:<PASSWORD>END_PI' json: uuid: 'device-uuid' type: 'device:not-gateblu' shadowing: {uuid: 'some-uuid'} foo: 'bar' request.post options, (error, @response, @body) => done error it 'should return a 204', -> expect(@response.statusCode).to.equal 204, @body it 'should proxy the request to the shadow service', -> @proxyConfigToShadowService.done() describe 'When the shadow service responds with a 403', -> beforeEach (done) -> teamAuth = new Buffer('team-uuid:team-token').toString 'base64' @meshblu .get '/v2/whoami' .set 'Authorization', "Basic #{teamAuth}" .reply 200, uuid: 'team-uuid', token: 'PI:PASSWORD:<PASSWORD>END_PI' @proxyConfigToShadowService = @shadowService .post '/virtual/config' .set 'Authorization', "Basic #{teamAuth}" .send uuid: 'device-uuid', type: 'device:not-gateblu', foo: 'bar', shadowing: {uuid: 'some-uuid'} .reply 403, 'Not authorized to modify that device' options = baseUrl: "http://localhost:#{@serverPort}" uri: '/virtual/config' auth: username: 'team-uuid' password: 'PI:PASSWORD:<PASSWORD>END_PI' json: uuid: 'device-uuid' type: 'device:not-gateblu' foo: 'bar' shadowing: {uuid: 'some-uuid'} request.post options, (error, @response, @body) => done error it 'should return a 403', -> expect(@response.statusCode).to.equal 403, @body it 'should return the shadow service error', -> expect(@body).to.deep.equal 'Not authorized to modify that device' it 'should proxy the request to the shadow service', -> @proxyConfigToShadowService.done() describe 'with no shadow service', -> beforeEach (done) -> @meshblu = shmock 0xd00d @server = new Server port: undefined, disableLogging: true shadowServiceUri: "https://localhost:#{0xcafe}" meshbluConfig: server: 'localhost' port: 0xd00d @server.run => @serverPort = @server.address().port done() afterEach (done) -> @server.stop done afterEach (done) -> @meshblu.close done describe 'When a request is made', -> beforeEach (done) -> teamAuth = new Buffer('team-uuid:team-token').toString 'base64' @meshblu .get '/v2/whoami' .set 'Authorization', "Basic #{teamAuth}" .reply 200, uuid: 'team-uuid', token: 'PI:PASSWORD:<PASSWORD>END_PI' options = baseUrl: "http://localhost:#{@serverPort}" uri: '/virtual/config' auth: username: 'team-uuid' password: 'PI:PASSWORD:<PASSWORD>END_PI' json: uuid: 'device-uuid' type: 'device:not-gateblu' foo: 'bar' shadowing: {uuid: 'some-uuid'} request.post options, (error, @response, @body) => done error it 'should return a 502', -> expect(@response.statusCode).to.equal 502, @body it 'should return a helpful error', -> expect(@body).to.deep.equal 'Could not contact the shadow service'
[ { "context": "e script which embeds screenplays in websites.\n#\n# Ben Scott\n# <bescott@andrew.cmu.edu>\n# 2016-03-19\n###\n\n'use", "end": 95, "score": 0.9998074173927307, "start": 86, "tag": "NAME", "value": "Ben Scott" }, { "context": " embeds screenplays in websites.\n#\n# Ben S...
code/inkwell.coffee
evan-erdos/evan-erdos.github.io
1
--- --- ### `Inkwell` # # A little script which embeds screenplays in websites. # # Ben Scott # <bescott@andrew.cmu.edu> # 2016-03-19 ### 'use strict' # just like JavaScript ### const ### url_regex = /^((ftp|https?):\/\/)?([\d\w\.-]+)\.([\w\.]{2,6})([\/\w \.-]*)*\/?$/ ### DOM ### site = "http://bescott.org" # domain name #site = "http://localhost:4000" # domain name baseurl = "/inkwell" # subdomain ### Helper Functions ### String::startsWith ?= (s) -> @slice(0,s.length)==s String::endsWith ?= (s) -> s=='' || @slice(-s.length)==s ### `Inkwell` # # main class for Inkwell screenplay includes ### class Inkwell constructor: -> script = document.scripts[document.scripts.length-1] @parent = script.parentElement id = @parent.id if id=="" div = script.previousSibling text = div.innerHTML @parent.removeChild(div) @process(text) else @load(id, @getURL(id)) ### `isFountainHead` # # Determine if a given line is a fountain block ### isFountainHead: (line) -> return unless (line? && line.length>0) return (line.toUpperCase()==line) ### `createHeader` # # create a scene header / slugline, return it ### createHeader: (lines) -> h2 = document.createElement('h2') h2.className = "full-slugline" h2.appendChild(document.createTextNode(lines)) return h2 ### `createCharacter` # # creates a dl for character / dialogue blocks ### createCharacter: (lines) -> dl = document.createElement('dl') dt = document.createElement('dt') dt.className = "character" dt.appendChild( document.createTextNode(lines.shift())) dd = document.createElement('dd') dd.className = "dialogue" for line in lines dd.appendChild( document.createTextNode(line+"\n")) dl.appendChild(dt) dl.appendChild(dd) return dl ### `createAction` # # creates a paragraph for action blocks ### createAction: (lines) -> p = document.createElement('p') p.className = "action" for line in lines text = document.createTextNode(line+"\n") p.appendChild(text) return p ### `createFountain` # # creates the appropriate fountain block from the input ### createFountain: (lines) -> return unless (lines? && lines.length>0) slugline = /(INT|EXT)(ERIOR)?[\.,]?/ character = /[ABCDEFGHIJKLMNOPQRSTUVWXYZ\s]+/ if (@isFountainHead(lines[0])) if (slugline.test(lines[0])) return @createHeader(lines) if (character.test(lines[0])) return @createCharacter(lines) else return @createAction(lines) ### `process` # # creates the appropriate fountain block from the input ### process: (data) -> data = data.replace(/\n\n+/,"\n\n") paragraphs = data.split "\n\n" for paragraph in paragraphs lines = paragraph.split "\n" elem = @createFountain(lines) @parent.appendChild(elem) if elem? ### `load` # # get `blob` from an XMLHttp request, # and `read` it after it loads ### load: (id, url) -> xhr = new XMLHttpRequest() xhr.open('GET',url,true) xhr.responseType = 'blob' xhr.onload = () => if (xhr.status==200) blob = new Blob( [xhr.response] {type: 'text'}) reader = new FileReader() reader.addEventListener "loadend", (event) => data = event.target.result error = event.target.error @process(data) if error==null reader.readAsText(blob) xhr.send() ### `getURL` # # determines if `url` is local in a crude and simple way ### getURL: (url) -> return url if (url.match(url_regex)) return "#{site}#{baseurl}/scenes/#{url}.fountain" inkwell = new Inkwell()
25484
--- --- ### `Inkwell` # # A little script which embeds screenplays in websites. # # <NAME> # <<EMAIL>> # 2016-03-19 ### 'use strict' # just like JavaScript ### const ### url_regex = /^((ftp|https?):\/\/)?([\d\w\.-]+)\.([\w\.]{2,6})([\/\w \.-]*)*\/?$/ ### DOM ### site = "http://bescott.org" # domain name #site = "http://localhost:4000" # domain name baseurl = "/inkwell" # subdomain ### Helper Functions ### String::startsWith ?= (s) -> @slice(0,s.length)==s String::endsWith ?= (s) -> s=='' || @slice(-s.length)==s ### `Inkwell` # # main class for Inkwell screenplay includes ### class Inkwell constructor: -> script = document.scripts[document.scripts.length-1] @parent = script.parentElement id = @parent.id if id=="" div = script.previousSibling text = div.innerHTML @parent.removeChild(div) @process(text) else @load(id, @getURL(id)) ### `isFountainHead` # # Determine if a given line is a fountain block ### isFountainHead: (line) -> return unless (line? && line.length>0) return (line.toUpperCase()==line) ### `createHeader` # # create a scene header / slugline, return it ### createHeader: (lines) -> h2 = document.createElement('h2') h2.className = "full-slugline" h2.appendChild(document.createTextNode(lines)) return h2 ### `createCharacter` # # creates a dl for character / dialogue blocks ### createCharacter: (lines) -> dl = document.createElement('dl') dt = document.createElement('dt') dt.className = "character" dt.appendChild( document.createTextNode(lines.shift())) dd = document.createElement('dd') dd.className = "dialogue" for line in lines dd.appendChild( document.createTextNode(line+"\n")) dl.appendChild(dt) dl.appendChild(dd) return dl ### `createAction` # # creates a paragraph for action blocks ### createAction: (lines) -> p = document.createElement('p') p.className = "action" for line in lines text = document.createTextNode(line+"\n") p.appendChild(text) return p ### `createFountain` # # creates the appropriate fountain block from the input ### createFountain: (lines) -> return unless (lines? && lines.length>0) slugline = /(INT|EXT)(ERIOR)?[\.,]?/ character = /[ABCDEFGHIJKLMNOPQRSTUVWXYZ\s]+/ if (@isFountainHead(lines[0])) if (slugline.test(lines[0])) return @createHeader(lines) if (character.test(lines[0])) return @createCharacter(lines) else return @createAction(lines) ### `process` # # creates the appropriate fountain block from the input ### process: (data) -> data = data.replace(/\n\n+/,"\n\n") paragraphs = data.split "\n\n" for paragraph in paragraphs lines = paragraph.split "\n" elem = @createFountain(lines) @parent.appendChild(elem) if elem? ### `load` # # get `blob` from an XMLHttp request, # and `read` it after it loads ### load: (id, url) -> xhr = new XMLHttpRequest() xhr.open('GET',url,true) xhr.responseType = 'blob' xhr.onload = () => if (xhr.status==200) blob = new Blob( [xhr.response] {type: 'text'}) reader = new FileReader() reader.addEventListener "loadend", (event) => data = event.target.result error = event.target.error @process(data) if error==null reader.readAsText(blob) xhr.send() ### `getURL` # # determines if `url` is local in a crude and simple way ### getURL: (url) -> return url if (url.match(url_regex)) return "#{site}#{baseurl}/scenes/#{url}.fountain" inkwell = new Inkwell()
true
--- --- ### `Inkwell` # # A little script which embeds screenplays in websites. # # PI:NAME:<NAME>END_PI # <PI:EMAIL:<EMAIL>END_PI> # 2016-03-19 ### 'use strict' # just like JavaScript ### const ### url_regex = /^((ftp|https?):\/\/)?([\d\w\.-]+)\.([\w\.]{2,6})([\/\w \.-]*)*\/?$/ ### DOM ### site = "http://bescott.org" # domain name #site = "http://localhost:4000" # domain name baseurl = "/inkwell" # subdomain ### Helper Functions ### String::startsWith ?= (s) -> @slice(0,s.length)==s String::endsWith ?= (s) -> s=='' || @slice(-s.length)==s ### `Inkwell` # # main class for Inkwell screenplay includes ### class Inkwell constructor: -> script = document.scripts[document.scripts.length-1] @parent = script.parentElement id = @parent.id if id=="" div = script.previousSibling text = div.innerHTML @parent.removeChild(div) @process(text) else @load(id, @getURL(id)) ### `isFountainHead` # # Determine if a given line is a fountain block ### isFountainHead: (line) -> return unless (line? && line.length>0) return (line.toUpperCase()==line) ### `createHeader` # # create a scene header / slugline, return it ### createHeader: (lines) -> h2 = document.createElement('h2') h2.className = "full-slugline" h2.appendChild(document.createTextNode(lines)) return h2 ### `createCharacter` # # creates a dl for character / dialogue blocks ### createCharacter: (lines) -> dl = document.createElement('dl') dt = document.createElement('dt') dt.className = "character" dt.appendChild( document.createTextNode(lines.shift())) dd = document.createElement('dd') dd.className = "dialogue" for line in lines dd.appendChild( document.createTextNode(line+"\n")) dl.appendChild(dt) dl.appendChild(dd) return dl ### `createAction` # # creates a paragraph for action blocks ### createAction: (lines) -> p = document.createElement('p') p.className = "action" for line in lines text = document.createTextNode(line+"\n") p.appendChild(text) return p ### `createFountain` # # creates the appropriate fountain block from the input ### createFountain: (lines) -> return unless (lines? && lines.length>0) slugline = /(INT|EXT)(ERIOR)?[\.,]?/ character = /[ABCDEFGHIJKLMNOPQRSTUVWXYZ\s]+/ if (@isFountainHead(lines[0])) if (slugline.test(lines[0])) return @createHeader(lines) if (character.test(lines[0])) return @createCharacter(lines) else return @createAction(lines) ### `process` # # creates the appropriate fountain block from the input ### process: (data) -> data = data.replace(/\n\n+/,"\n\n") paragraphs = data.split "\n\n" for paragraph in paragraphs lines = paragraph.split "\n" elem = @createFountain(lines) @parent.appendChild(elem) if elem? ### `load` # # get `blob` from an XMLHttp request, # and `read` it after it loads ### load: (id, url) -> xhr = new XMLHttpRequest() xhr.open('GET',url,true) xhr.responseType = 'blob' xhr.onload = () => if (xhr.status==200) blob = new Blob( [xhr.response] {type: 'text'}) reader = new FileReader() reader.addEventListener "loadend", (event) => data = event.target.result error = event.target.error @process(data) if error==null reader.readAsText(blob) xhr.send() ### `getURL` # # determines if `url` is local in a crude and simple way ### getURL: (url) -> return url if (url.match(url_regex)) return "#{site}#{baseurl}/scenes/#{url}.fountain" inkwell = new Inkwell()
[ { "context": "# Copyright 2016 Clement Bramy\n#\n# Licensed under the Apache License, Version 2.", "end": 30, "score": 0.9998658895492554, "start": 17, "tag": "NAME", "value": "Clement Bramy" } ]
lib/utils.coffee
cbramy/snippy
0
# Copyright 2016 Clement Bramy # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module.exports = { ellipsis: (text, max=50, end='...') -> return '' if not text return text if text.length <= max return text.substring(0, (max - end.length)) + end }
160926
# Copyright 2016 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module.exports = { ellipsis: (text, max=50, end='...') -> return '' if not text return text if text.length <= max return text.substring(0, (max - end.length)) + end }
true
# Copyright 2016 PI:NAME:<NAME>END_PI # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module.exports = { ellipsis: (text, max=50, end='...') -> return '' if not text return text if text.length <= max return text.substring(0, (max - end.length)) + end }
[ { "context": "tials.public\n consumer_secret: credentials.private\n token: oauthToken\n verifier: oauth", "end": 972, "score": 0.5048989057540894, "start": 965, "tag": "KEY", "value": "private" }, { "context": "tials.public\n consumer_secret: credentials.p...
source/twitter/index.coffee
moooink/loopback-satellizer
0
async = require 'async' debug = require('debug') 'loopback:satellizer:twitter' qs = require 'querystring' request = require 'request' randomstring = require 'randomstring' common = require '../common' module.exports = (server, options) -> Common = common server, options Model = server.models[options.model] credentials = options.credentials callbackUrl = options.callbackUrl handleFirstRequest = (callback) -> request.post url: 'https://api.twitter.com/oauth/request_token' oauth: consumer_key: credentials.public consumer_secret: credentials.private , (err, res, body) -> return callback err if err callback null, qs.parse body fetchAccessToken = (oauthToken, oauthVerifier, callback) -> request.post url: 'https://api.twitter.com/oauth/access_token' oauth: consumer_key: credentials.public consumer_secret: credentials.private token: oauthToken verifier: oauthVerifier , (err, res, accessToken) -> if err debug JSON.stringify err return callback err if res.statusCode isnt 200 err = new Error accessToken err.status = 500 debug JSON.stringify err return callback err callback null, qs.parse accessToken fetchProfile = (accessToken, callback) -> debug 'fetchProfile' request.get url: 'https://api.twitter.com/1.1/users/show.json?screen_name=' + accessToken.screen_name oauth: consumer_key: credentials.public consumer_secret: credentials.private oauth_token: accessToken.oauth_token json: true , (err, res, profile) -> if err debug JSON.stringify err return callback err if res.statusCode isnt 200 err = new Error JSON.stringify profile err.status = 500 debug JSON.stringify err return callback err callback null, profile link = (req, profile, callback) -> debug 'link' Common.current req, (err, found) -> if err debug err return callback err if found is null err = new Error 'not_an_account' err.status = 409 debug err return callback err if found return link.existing profile, found, callback # query = where: {} query.where[options.mapping.id] = profile.id # Model.findOne query, (err, found) -> if err debug err return callback err return link.create profile, callback if not found return link.existing profile, found, callback link.create = (profile, callback) -> debug 'link.create', profile.id tmp = email: "#{profile.id}@twitter.com" password: randomstring.generate() Common.map options.mapping, profile, tmp Model.create tmp, (err, created) -> debug err if err return callback err, created link.existing = (profile, account, callback) -> debug 'link.existing' if account[options.mapping.id] and account[options.mapping.id] != profile.id err = new Error 'account_conflict' err.status = 409 debug err return callback err Common.map options.mapping, profile, account account.save (err) -> debug err if err return callback err, account Model.twitter = (req, oauthToken, oauthVerifier, callback) -> debug "#{oauthToken}, #{oauthVerifier}" # Initial request for satellizer return handleFirstRequest callback if not oauthToken or not oauthVerifier async.waterfall [ (done) -> fetchAccessToken oauthToken, oauthVerifier, done (accessToken, done) -> fetchProfile accessToken, done (profile, done) -> link req, profile, done (account, done) -> Common.authenticate account, done ], callback Model['twitter-get'] = Model.twitter Model.remoteMethod 'twitter-get', accepts: [ { arg: 'req' type: 'object' http: source: 'req' } { arg: 'oauth_token' type: 'string' http: source: 'query' } { arg: 'oauth_verifier' type: 'string' http: source: 'query' } ] returns: arg: 'result' type: 'object' root: true http: verb: 'get' path: options.uri Model.remoteMethod 'twitter', accepts: [ { arg: 'req' type: 'object' http: source: 'req' } { arg: 'oauth_token' type: 'string' http: source: 'form' } { arg: 'oauth_verifier' type: 'string' http: source: 'form' } ] returns: arg: 'result' type: 'object' root: true http: verb: 'post' path: options.uri return
110978
async = require 'async' debug = require('debug') 'loopback:satellizer:twitter' qs = require 'querystring' request = require 'request' randomstring = require 'randomstring' common = require '../common' module.exports = (server, options) -> Common = common server, options Model = server.models[options.model] credentials = options.credentials callbackUrl = options.callbackUrl handleFirstRequest = (callback) -> request.post url: 'https://api.twitter.com/oauth/request_token' oauth: consumer_key: credentials.public consumer_secret: credentials.private , (err, res, body) -> return callback err if err callback null, qs.parse body fetchAccessToken = (oauthToken, oauthVerifier, callback) -> request.post url: 'https://api.twitter.com/oauth/access_token' oauth: consumer_key: credentials.public consumer_secret: credentials.<KEY> token: oauthToken verifier: oauthVerifier , (err, res, accessToken) -> if err debug JSON.stringify err return callback err if res.statusCode isnt 200 err = new Error accessToken err.status = 500 debug JSON.stringify err return callback err callback null, qs.parse accessToken fetchProfile = (accessToken, callback) -> debug 'fetchProfile' request.get url: 'https://api.twitter.com/1.1/users/show.json?screen_name=' + accessToken.screen_name oauth: consumer_key: credentials.public consumer_secret: credentials.<KEY> oauth_token: accessToken.oauth_token json: true , (err, res, profile) -> if err debug JSON.stringify err return callback err if res.statusCode isnt 200 err = new Error JSON.stringify profile err.status = 500 debug JSON.stringify err return callback err callback null, profile link = (req, profile, callback) -> debug 'link' Common.current req, (err, found) -> if err debug err return callback err if found is null err = new Error 'not_an_account' err.status = 409 debug err return callback err if found return link.existing profile, found, callback # query = where: {} query.where[options.mapping.id] = profile.id # Model.findOne query, (err, found) -> if err debug err return callback err return link.create profile, callback if not found return link.existing profile, found, callback link.create = (profile, callback) -> debug 'link.create', profile.id tmp = email: <EMAIL>" password: <PASSWORD>() Common.map options.mapping, profile, tmp Model.create tmp, (err, created) -> debug err if err return callback err, created link.existing = (profile, account, callback) -> debug 'link.existing' if account[options.mapping.id] and account[options.mapping.id] != profile.id err = new Error 'account_conflict' err.status = 409 debug err return callback err Common.map options.mapping, profile, account account.save (err) -> debug err if err return callback err, account Model.twitter = (req, oauthToken, oauthVerifier, callback) -> debug "#{oauthToken}, #{oauthVerifier}" # Initial request for satellizer return handleFirstRequest callback if not oauthToken or not oauthVerifier async.waterfall [ (done) -> fetchAccessToken oauthToken, oauthVerifier, done (accessToken, done) -> fetchProfile accessToken, done (profile, done) -> link req, profile, done (account, done) -> Common.authenticate account, done ], callback Model['twitter-get'] = Model.twitter Model.remoteMethod 'twitter-get', accepts: [ { arg: 'req' type: 'object' http: source: 'req' } { arg: 'oauth_token' type: 'string' http: source: 'query' } { arg: 'oauth_verifier' type: 'string' http: source: 'query' } ] returns: arg: 'result' type: 'object' root: true http: verb: 'get' path: options.uri Model.remoteMethod 'twitter', accepts: [ { arg: 'req' type: 'object' http: source: 'req' } { arg: 'oauth_token' type: 'string' http: source: 'form' } { arg: 'oauth_verifier' type: 'string' http: source: 'form' } ] returns: arg: 'result' type: 'object' root: true http: verb: 'post' path: options.uri return
true
async = require 'async' debug = require('debug') 'loopback:satellizer:twitter' qs = require 'querystring' request = require 'request' randomstring = require 'randomstring' common = require '../common' module.exports = (server, options) -> Common = common server, options Model = server.models[options.model] credentials = options.credentials callbackUrl = options.callbackUrl handleFirstRequest = (callback) -> request.post url: 'https://api.twitter.com/oauth/request_token' oauth: consumer_key: credentials.public consumer_secret: credentials.private , (err, res, body) -> return callback err if err callback null, qs.parse body fetchAccessToken = (oauthToken, oauthVerifier, callback) -> request.post url: 'https://api.twitter.com/oauth/access_token' oauth: consumer_key: credentials.public consumer_secret: credentials.PI:KEY:<KEY>END_PI token: oauthToken verifier: oauthVerifier , (err, res, accessToken) -> if err debug JSON.stringify err return callback err if res.statusCode isnt 200 err = new Error accessToken err.status = 500 debug JSON.stringify err return callback err callback null, qs.parse accessToken fetchProfile = (accessToken, callback) -> debug 'fetchProfile' request.get url: 'https://api.twitter.com/1.1/users/show.json?screen_name=' + accessToken.screen_name oauth: consumer_key: credentials.public consumer_secret: credentials.PI:KEY:<KEY>END_PI oauth_token: accessToken.oauth_token json: true , (err, res, profile) -> if err debug JSON.stringify err return callback err if res.statusCode isnt 200 err = new Error JSON.stringify profile err.status = 500 debug JSON.stringify err return callback err callback null, profile link = (req, profile, callback) -> debug 'link' Common.current req, (err, found) -> if err debug err return callback err if found is null err = new Error 'not_an_account' err.status = 409 debug err return callback err if found return link.existing profile, found, callback # query = where: {} query.where[options.mapping.id] = profile.id # Model.findOne query, (err, found) -> if err debug err return callback err return link.create profile, callback if not found return link.existing profile, found, callback link.create = (profile, callback) -> debug 'link.create', profile.id tmp = email: PI:EMAIL:<EMAIL>END_PI" password: PI:PASSWORD:<PASSWORD>END_PI() Common.map options.mapping, profile, tmp Model.create tmp, (err, created) -> debug err if err return callback err, created link.existing = (profile, account, callback) -> debug 'link.existing' if account[options.mapping.id] and account[options.mapping.id] != profile.id err = new Error 'account_conflict' err.status = 409 debug err return callback err Common.map options.mapping, profile, account account.save (err) -> debug err if err return callback err, account Model.twitter = (req, oauthToken, oauthVerifier, callback) -> debug "#{oauthToken}, #{oauthVerifier}" # Initial request for satellizer return handleFirstRequest callback if not oauthToken or not oauthVerifier async.waterfall [ (done) -> fetchAccessToken oauthToken, oauthVerifier, done (accessToken, done) -> fetchProfile accessToken, done (profile, done) -> link req, profile, done (account, done) -> Common.authenticate account, done ], callback Model['twitter-get'] = Model.twitter Model.remoteMethod 'twitter-get', accepts: [ { arg: 'req' type: 'object' http: source: 'req' } { arg: 'oauth_token' type: 'string' http: source: 'query' } { arg: 'oauth_verifier' type: 'string' http: source: 'query' } ] returns: arg: 'result' type: 'object' root: true http: verb: 'get' path: options.uri Model.remoteMethod 'twitter', accepts: [ { arg: 'req' type: 'object' http: source: 'req' } { arg: 'oauth_token' type: 'string' http: source: 'form' } { arg: 'oauth_verifier' type: 'string' http: source: 'form' } ] returns: arg: 'result' type: 'object' root: true http: verb: 'post' path: options.uri return
[ { "context": "ger\"\n# \n# result = schema.process({name: \"Mathias\", age: \"35\"})\n# result.valid == true\n# re", "end": 541, "score": 0.9997849464416504, "start": 534, "tag": "NAME", "value": "Mathias" }, { "context": "esult.valid == true\n# result.doc == {n...
coffeescripts/json-schema.coffee
webpop/json-schemer
1
# is a json-schema validator with a twist: instead of just validating json documents, # it will also cast the values of a document to fit a schema. # # This is very handy if you need to process form submissions where all data comes # in form of strings. #### Usage # To process a schema: # # schema = new JsonSchema # type: "object" # properties: # name: # type: "string" # required: true # age: # type: "integer" # # result = schema.process({name: "Mathias", age: "35"}) # result.valid == true # result.doc == {name: "Mathias", age: 35} # result.errors.isEmpty() == true # # result = schema.process({title: "Bad Doc"}) # result.valid == false # result.doc == {} # result.errors.on("name") == ["required"] #### JsonErrors class JsonErrors constructor: -> @base = [] @attr = {} # Add an error to a property. # If the error is another JsonErrors object the errors from # that object will be merged into the current error object. add: (property, error) -> return unless property || error if not error? error = property property = null if property if error instanceof JsonErrors then @_mergeErrors(property, error) else @_addError(property, error) else @base.push error # Add an error with no property associated addToBase: (error) -> @add(error) # Get any errors on a property. Returns an array of errors on: (property) -> if property then @attr[property] else @base # Get any errors on the base property. Returns and array of errors. onBase: -> @on() # Returns an array of all errors: [[property, [errors]]] all: -> base = if @base.length then [["", @base]] else [] base.concat([key, err] for key, err of @attr) # Return true if no errors have been added isEmpty: -> @base.length == 0 && Object.keys(@attr).length == 0 _addError: (property, error) -> @attr[property] ||= [] if error.length @attr[property] = @attr[property].concat(error) else @attr[property].push error _mergeErrors: (property, errors) -> return if errors.isEmpty() for [prop, err] in errors.all() newProp = if prop then "#{property}.#{prop}" else property @add(newProp, err) #### JsonProperty # The base class in the JsonSchema hierachy. class JsonProperty constructor: (@attr) -> # Case a value to the type specified by this propery cast: (val) -> val # Return any errors for this property errors: (val) -> errors = new JsonErrors errors.add("required") unless @validate "required", (r) -> !(r && typeof(val) == "undefined") errors # Process a value. Return an object with the keys valid, doc and errors process: (val) -> val = if val? then @cast(val) else @attr.default errors = @errors(val) valid: errors.isEmpty() doc: val errors: errors # Helper method to perform a validtion if an attribute is present validate: (attr, fn) -> if (attr of @attr) and @attr[attr] != null then fn.call(this, @attr[attr]) else true #### JsonString # A property of type "string" class JsonString extends JsonProperty cast: (val) -> switch @attr.format when "date", "date-time" new Date(val) else val.toString() errors: (val) -> errors = super(val) if val? errors.add("minLength") unless @validate "minLength", (len) -> val.length >= len errors.add("maxLength") unless @validate "maxLength", (len) -> val.length <= len errors.add("pattern") unless @validate "pattern", (pat) -> new RegExp(pat).test(val) errors.add("enum") unless @validate "enum", (opts) -> val in opts errors.add("format") unless @validate "format", (format) -> @validFormat(format, val) errors validFormat: (format, val) -> switch @attr.format when "date" /^\d\d\d\d-\d\d-\d\d$/.test(val) when "date-time" /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ$/.test(val) else true #### JsonNumber # A property of type "number" class JsonNumber extends JsonProperty cast: (val) -> val = parseFloat(val) if isNaN(val) then null else val errors: (val) -> errors = super(val) if val? errors.add("minimum") unless @validate "minimum", (min) -> if @attr.excludeMinimum then val > min else val >= min errors.add("maximum") unless @validate "maximum", (max) -> if @attr.excludeMaximum then val < max else val <= max errors.add("divisibleBy") unless @validate "divisibleBy", (div) -> val % div == 0 errors #### JsonInteger # A property of type "integer" class JsonInteger extends JsonNumber cast: (val) -> val = parseInt(val, 10) if isNaN(val) then null else val #### JsonBoolean # A property of type "boolean" class JsonBoolean extends JsonProperty cast: (val) -> return if val == undefined if val == "false" || val == "null" || val == "0" then false else if val then true else false #### JsonArray # A property of class "array". # If the array items are specified with a "$ref" ({items: {"$ref": "uri"}}) the JsonSchema.resolver will # be used to return a schema object for the items. class JsonArray extends JsonProperty constructor: (@attr) -> if @attr.items ref = @attr.items["$ref"] @itemSchema = if ref then JsonSchema.resolver(@attr.items["$ref"], this) else JsonProperty.for(@attr.items) cast: (val) -> cast = if @itemSchema then (v) => @itemSchema.cast(v) else (v) -> v cast(item) for item in val errors: (val) -> errors = super(val) if val? errors.add("minItems") unless @validate "minItems", (min) -> val.length >= min errors.add("maxItems") unless @validate "maxItems", (max) -> val.length <= max if @itemSchema errors.add("#{i}", @itemSchema.errors(item)) for item, i in val errors #### JsonObject # A property of type "object". # If the properties are specified with a "$ref" (properties: {"$ref" : "uri"}) the # JsonSchema.resolver will be used to lookup a schema object used for cast, errors # and process class JsonObject extends JsonProperty constructor: (@attr) -> @properties = attr.properties if @properties["$ref"] @ref = JsonSchema.resolver(@properties["$ref"].replace(/#.+$/, ''), this) cast: (val) -> return @ref.cast(val) if @ref obj = {} for key, attrs of @properties obj[key] = if val && (key of val) then JsonProperty.for(attrs).cast(val[key]) else attrs.default obj process: (val) -> if @ref then @ref.process(val) else super(val) errors: (val) -> return super(val) unless val? return @ref.errors(val) if @ref errors = super(val) for key, attrs of @properties err = JsonProperty.for(attrs).errors(val && val[key]) errors.add(key, err) errors # Factory method for JsonProperties JsonProperty.for = (attr) -> type = attr.type || "any" klass = { "any" : JsonProperty "string" : JsonString "number" : JsonNumber "integer" : JsonInteger "boolean" : JsonBoolean "array" : JsonArray "object" : JsonObject }[type] throw "Bad Schema - Unknown property type #{type}" unless klass new klass(attr) #### JsonSchema # The public interface to the JsonSchema processor. # Requires the main schema to be of type "object" class JsonSchema extends JsonObject constructor: (attr) -> throw "The main schema must be of type \"object\"" unless attr.type == "object" super(attr) #### The JsonSchema.resolver # This function will be used to resolve any url used in "$ref" references. # The function should return an object responding to cast, errors and process. JsonSchema.resolver = (url) -> # Override to resolve references throw "No resolver defined for references" unless JsonSchema.resolver # Export public interface e = (exports? && exports) || (window? && window) e.JsonSchema = JsonSchema e.JsonErrors = JsonErrors
113702
# is a json-schema validator with a twist: instead of just validating json documents, # it will also cast the values of a document to fit a schema. # # This is very handy if you need to process form submissions where all data comes # in form of strings. #### Usage # To process a schema: # # schema = new JsonSchema # type: "object" # properties: # name: # type: "string" # required: true # age: # type: "integer" # # result = schema.process({name: "<NAME>", age: "35"}) # result.valid == true # result.doc == {name: "<NAME>", age: 35} # result.errors.isEmpty() == true # # result = schema.process({title: "Bad Doc"}) # result.valid == false # result.doc == {} # result.errors.on("name") == ["required"] #### JsonErrors class JsonErrors constructor: -> @base = [] @attr = {} # Add an error to a property. # If the error is another JsonErrors object the errors from # that object will be merged into the current error object. add: (property, error) -> return unless property || error if not error? error = property property = null if property if error instanceof JsonErrors then @_mergeErrors(property, error) else @_addError(property, error) else @base.push error # Add an error with no property associated addToBase: (error) -> @add(error) # Get any errors on a property. Returns an array of errors on: (property) -> if property then @attr[property] else @base # Get any errors on the base property. Returns and array of errors. onBase: -> @on() # Returns an array of all errors: [[property, [errors]]] all: -> base = if @base.length then [["", @base]] else [] base.concat([key, err] for key, err of @attr) # Return true if no errors have been added isEmpty: -> @base.length == 0 && Object.keys(@attr).length == 0 _addError: (property, error) -> @attr[property] ||= [] if error.length @attr[property] = @attr[property].concat(error) else @attr[property].push error _mergeErrors: (property, errors) -> return if errors.isEmpty() for [prop, err] in errors.all() newProp = if prop then "#{property}.#{prop}" else property @add(newProp, err) #### JsonProperty # The base class in the JsonSchema hierachy. class JsonProperty constructor: (@attr) -> # Case a value to the type specified by this propery cast: (val) -> val # Return any errors for this property errors: (val) -> errors = new JsonErrors errors.add("required") unless @validate "required", (r) -> !(r && typeof(val) == "undefined") errors # Process a value. Return an object with the keys valid, doc and errors process: (val) -> val = if val? then @cast(val) else @attr.default errors = @errors(val) valid: errors.isEmpty() doc: val errors: errors # Helper method to perform a validtion if an attribute is present validate: (attr, fn) -> if (attr of @attr) and @attr[attr] != null then fn.call(this, @attr[attr]) else true #### JsonString # A property of type "string" class JsonString extends JsonProperty cast: (val) -> switch @attr.format when "date", "date-time" new Date(val) else val.toString() errors: (val) -> errors = super(val) if val? errors.add("minLength") unless @validate "minLength", (len) -> val.length >= len errors.add("maxLength") unless @validate "maxLength", (len) -> val.length <= len errors.add("pattern") unless @validate "pattern", (pat) -> new RegExp(pat).test(val) errors.add("enum") unless @validate "enum", (opts) -> val in opts errors.add("format") unless @validate "format", (format) -> @validFormat(format, val) errors validFormat: (format, val) -> switch @attr.format when "date" /^\d\d\d\d-\d\d-\d\d$/.test(val) when "date-time" /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ$/.test(val) else true #### JsonNumber # A property of type "number" class JsonNumber extends JsonProperty cast: (val) -> val = parseFloat(val) if isNaN(val) then null else val errors: (val) -> errors = super(val) if val? errors.add("minimum") unless @validate "minimum", (min) -> if @attr.excludeMinimum then val > min else val >= min errors.add("maximum") unless @validate "maximum", (max) -> if @attr.excludeMaximum then val < max else val <= max errors.add("divisibleBy") unless @validate "divisibleBy", (div) -> val % div == 0 errors #### JsonInteger # A property of type "integer" class JsonInteger extends JsonNumber cast: (val) -> val = parseInt(val, 10) if isNaN(val) then null else val #### JsonBoolean # A property of type "boolean" class JsonBoolean extends JsonProperty cast: (val) -> return if val == undefined if val == "false" || val == "null" || val == "0" then false else if val then true else false #### JsonArray # A property of class "array". # If the array items are specified with a "$ref" ({items: {"$ref": "uri"}}) the JsonSchema.resolver will # be used to return a schema object for the items. class JsonArray extends JsonProperty constructor: (@attr) -> if @attr.items ref = @attr.items["$ref"] @itemSchema = if ref then JsonSchema.resolver(@attr.items["$ref"], this) else JsonProperty.for(@attr.items) cast: (val) -> cast = if @itemSchema then (v) => @itemSchema.cast(v) else (v) -> v cast(item) for item in val errors: (val) -> errors = super(val) if val? errors.add("minItems") unless @validate "minItems", (min) -> val.length >= min errors.add("maxItems") unless @validate "maxItems", (max) -> val.length <= max if @itemSchema errors.add("#{i}", @itemSchema.errors(item)) for item, i in val errors #### JsonObject # A property of type "object". # If the properties are specified with a "$ref" (properties: {"$ref" : "uri"}) the # JsonSchema.resolver will be used to lookup a schema object used for cast, errors # and process class JsonObject extends JsonProperty constructor: (@attr) -> @properties = attr.properties if @properties["$ref"] @ref = JsonSchema.resolver(@properties["$ref"].replace(/#.+$/, ''), this) cast: (val) -> return @ref.cast(val) if @ref obj = {} for key, attrs of @properties obj[key] = if val && (key of val) then JsonProperty.for(attrs).cast(val[key]) else attrs.default obj process: (val) -> if @ref then @ref.process(val) else super(val) errors: (val) -> return super(val) unless val? return @ref.errors(val) if @ref errors = super(val) for key, attrs of @properties err = JsonProperty.for(attrs).errors(val && val[key]) errors.add(key, err) errors # Factory method for JsonProperties JsonProperty.for = (attr) -> type = attr.type || "any" klass = { "any" : JsonProperty "string" : JsonString "number" : JsonNumber "integer" : JsonInteger "boolean" : JsonBoolean "array" : JsonArray "object" : JsonObject }[type] throw "Bad Schema - Unknown property type #{type}" unless klass new klass(attr) #### JsonSchema # The public interface to the JsonSchema processor. # Requires the main schema to be of type "object" class JsonSchema extends JsonObject constructor: (attr) -> throw "The main schema must be of type \"object\"" unless attr.type == "object" super(attr) #### The JsonSchema.resolver # This function will be used to resolve any url used in "$ref" references. # The function should return an object responding to cast, errors and process. JsonSchema.resolver = (url) -> # Override to resolve references throw "No resolver defined for references" unless JsonSchema.resolver # Export public interface e = (exports? && exports) || (window? && window) e.JsonSchema = JsonSchema e.JsonErrors = JsonErrors
true
# is a json-schema validator with a twist: instead of just validating json documents, # it will also cast the values of a document to fit a schema. # # This is very handy if you need to process form submissions where all data comes # in form of strings. #### Usage # To process a schema: # # schema = new JsonSchema # type: "object" # properties: # name: # type: "string" # required: true # age: # type: "integer" # # result = schema.process({name: "PI:NAME:<NAME>END_PI", age: "35"}) # result.valid == true # result.doc == {name: "PI:NAME:<NAME>END_PI", age: 35} # result.errors.isEmpty() == true # # result = schema.process({title: "Bad Doc"}) # result.valid == false # result.doc == {} # result.errors.on("name") == ["required"] #### JsonErrors class JsonErrors constructor: -> @base = [] @attr = {} # Add an error to a property. # If the error is another JsonErrors object the errors from # that object will be merged into the current error object. add: (property, error) -> return unless property || error if not error? error = property property = null if property if error instanceof JsonErrors then @_mergeErrors(property, error) else @_addError(property, error) else @base.push error # Add an error with no property associated addToBase: (error) -> @add(error) # Get any errors on a property. Returns an array of errors on: (property) -> if property then @attr[property] else @base # Get any errors on the base property. Returns and array of errors. onBase: -> @on() # Returns an array of all errors: [[property, [errors]]] all: -> base = if @base.length then [["", @base]] else [] base.concat([key, err] for key, err of @attr) # Return true if no errors have been added isEmpty: -> @base.length == 0 && Object.keys(@attr).length == 0 _addError: (property, error) -> @attr[property] ||= [] if error.length @attr[property] = @attr[property].concat(error) else @attr[property].push error _mergeErrors: (property, errors) -> return if errors.isEmpty() for [prop, err] in errors.all() newProp = if prop then "#{property}.#{prop}" else property @add(newProp, err) #### JsonProperty # The base class in the JsonSchema hierachy. class JsonProperty constructor: (@attr) -> # Case a value to the type specified by this propery cast: (val) -> val # Return any errors for this property errors: (val) -> errors = new JsonErrors errors.add("required") unless @validate "required", (r) -> !(r && typeof(val) == "undefined") errors # Process a value. Return an object with the keys valid, doc and errors process: (val) -> val = if val? then @cast(val) else @attr.default errors = @errors(val) valid: errors.isEmpty() doc: val errors: errors # Helper method to perform a validtion if an attribute is present validate: (attr, fn) -> if (attr of @attr) and @attr[attr] != null then fn.call(this, @attr[attr]) else true #### JsonString # A property of type "string" class JsonString extends JsonProperty cast: (val) -> switch @attr.format when "date", "date-time" new Date(val) else val.toString() errors: (val) -> errors = super(val) if val? errors.add("minLength") unless @validate "minLength", (len) -> val.length >= len errors.add("maxLength") unless @validate "maxLength", (len) -> val.length <= len errors.add("pattern") unless @validate "pattern", (pat) -> new RegExp(pat).test(val) errors.add("enum") unless @validate "enum", (opts) -> val in opts errors.add("format") unless @validate "format", (format) -> @validFormat(format, val) errors validFormat: (format, val) -> switch @attr.format when "date" /^\d\d\d\d-\d\d-\d\d$/.test(val) when "date-time" /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ$/.test(val) else true #### JsonNumber # A property of type "number" class JsonNumber extends JsonProperty cast: (val) -> val = parseFloat(val) if isNaN(val) then null else val errors: (val) -> errors = super(val) if val? errors.add("minimum") unless @validate "minimum", (min) -> if @attr.excludeMinimum then val > min else val >= min errors.add("maximum") unless @validate "maximum", (max) -> if @attr.excludeMaximum then val < max else val <= max errors.add("divisibleBy") unless @validate "divisibleBy", (div) -> val % div == 0 errors #### JsonInteger # A property of type "integer" class JsonInteger extends JsonNumber cast: (val) -> val = parseInt(val, 10) if isNaN(val) then null else val #### JsonBoolean # A property of type "boolean" class JsonBoolean extends JsonProperty cast: (val) -> return if val == undefined if val == "false" || val == "null" || val == "0" then false else if val then true else false #### JsonArray # A property of class "array". # If the array items are specified with a "$ref" ({items: {"$ref": "uri"}}) the JsonSchema.resolver will # be used to return a schema object for the items. class JsonArray extends JsonProperty constructor: (@attr) -> if @attr.items ref = @attr.items["$ref"] @itemSchema = if ref then JsonSchema.resolver(@attr.items["$ref"], this) else JsonProperty.for(@attr.items) cast: (val) -> cast = if @itemSchema then (v) => @itemSchema.cast(v) else (v) -> v cast(item) for item in val errors: (val) -> errors = super(val) if val? errors.add("minItems") unless @validate "minItems", (min) -> val.length >= min errors.add("maxItems") unless @validate "maxItems", (max) -> val.length <= max if @itemSchema errors.add("#{i}", @itemSchema.errors(item)) for item, i in val errors #### JsonObject # A property of type "object". # If the properties are specified with a "$ref" (properties: {"$ref" : "uri"}) the # JsonSchema.resolver will be used to lookup a schema object used for cast, errors # and process class JsonObject extends JsonProperty constructor: (@attr) -> @properties = attr.properties if @properties["$ref"] @ref = JsonSchema.resolver(@properties["$ref"].replace(/#.+$/, ''), this) cast: (val) -> return @ref.cast(val) if @ref obj = {} for key, attrs of @properties obj[key] = if val && (key of val) then JsonProperty.for(attrs).cast(val[key]) else attrs.default obj process: (val) -> if @ref then @ref.process(val) else super(val) errors: (val) -> return super(val) unless val? return @ref.errors(val) if @ref errors = super(val) for key, attrs of @properties err = JsonProperty.for(attrs).errors(val && val[key]) errors.add(key, err) errors # Factory method for JsonProperties JsonProperty.for = (attr) -> type = attr.type || "any" klass = { "any" : JsonProperty "string" : JsonString "number" : JsonNumber "integer" : JsonInteger "boolean" : JsonBoolean "array" : JsonArray "object" : JsonObject }[type] throw "Bad Schema - Unknown property type #{type}" unless klass new klass(attr) #### JsonSchema # The public interface to the JsonSchema processor. # Requires the main schema to be of type "object" class JsonSchema extends JsonObject constructor: (attr) -> throw "The main schema must be of type \"object\"" unless attr.type == "object" super(attr) #### The JsonSchema.resolver # This function will be used to resolve any url used in "$ref" references. # The function should return an object responding to cast, errors and process. JsonSchema.resolver = (url) -> # Override to resolve references throw "No resolver defined for references" unless JsonSchema.resolver # Export public interface e = (exports? && exports) || (window? && window) e.JsonSchema = JsonSchema e.JsonErrors = JsonErrors
[ { "context": "da database for genomic variation frequencies.\n#\n# Martijn Vermaat <m.vermaat.hg@lumc.nl>\n#\n# Licensed under the MIT", "end": 103, "score": 0.9998791813850403, "start": 88, "tag": "NAME", "value": "Martijn Vermaat" }, { "context": "nomic variation frequencies.\n#\n#...
scripts/app.coffee
varda/aule-test
1
# Aulë # # A web interface to the Varda database for genomic variation frequencies. # # Martijn Vermaat <m.vermaat.hg@lumc.nl> # # Licensed under the MIT license, see the LICENSE file. # Todo: Figure out roles and rights for variant lookup. $ = require 'jquery' Promise = require 'bluebird' Sammy = require 'sammy' config = require 'config' app = Sammy '#main', -> # Always call init() with an initialized Api instance before calling run(). @init = (api) => @api = api # Create pagination data for use in template. createPagination = (total, current=0) -> if total <= 1 then return null pagination = pages: for p in [0...total] page: p label: p + 1 active: p == current many_pages: total >= config.MANY_PAGES if current > 0 pagination.previous = page: current - 1, label: current if current < total - 1 pagination.next = page: current + 1, label: current + 2 pagination # Create authentication data for use in template. createAuth = () => return null unless @api.current_user? roles = @api.current_user.roles user: @api.current_user roles: admin: 'admin' in roles importer: 'importer' in roles annotator: 'annotator' in roles trader: 'trader' in roles querier: 'querier' in roles group_querier: 'group-querier' in roles rights: list_samples: 'admin' in roles add_sample: 'importer' in roles or 'admin' in roles list_data_sources: 'admin' in roles add_data_source: true list_annotations: 'admin' in roles # TODO: 'trader' in roles or 'annotator' in roles or 'admin' in roles add_annotation: true add_group: 'admin' in roles list_users: 'admin' in roles add_user: 'admin' in roles query: 'admin' in roles or ('annotator' in roles and 'querier' in roles) group_query: 'admin' in roles or ('annotator' in roles and ( 'querier' in roles or 'group-querier' in roles)) global_query: 'admin' in roles or 'annotator' in roles # TODO: We ignored traders. They should be able to add an annotation # (the original data source might be theirs), but not do lookups. # Render a template. @helper 'render', (name, data={}) -> data.query_by_transcript = config.MY_GENE_INFO? data.base = config.BASE data.path = @path data.auth = createAuth() # https://github.com/altano/handlebars-loader/issues/81 # As a workaround we use inline partials for now. require('../templates/' + name + '.hb') data # Showing messages. @helper 'info', (message) -> @message 'info', message @helper 'success', (message) -> @message 'success', message @helper 'error', (message) -> @message 'error', message @helper 'message', (type, text) -> $('#messages').append @render 'message', type: type, text: text currentMessages = $('#messages > div.alert') window.setTimeout (-> currentMessages.alert 'close'), 3000 # Show main page content. @helper 'show', (page, data={}) -> data.page = page if data.pagination? {total, current} = data.pagination data.pagination = createPagination total, current @swap @render page, data $('#navigation').html @render 'navigation', data # Show picker. @helper 'picker', (page, data={}) -> if data.pagination? {total, current} = data.pagination data.pagination = createPagination total, current $('#picker .modal-body').html @render "picker_#{page}", data $('#picker').modal() # Show transcript query results. @helper 'transcript_query', (data={}) -> $('#transcript-query').html @render 'transcript_query', data # Sample picker. @get '/picker/samples', -> @app.api.samples filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @picker 'samples', samples: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Data source picker. @get '/picker/data_sources', -> @app.api.data_sources filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @picker 'data_sources', data_sources: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Group picker. @get '/picker/groups', -> @app.api.groups filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @picker 'groups', groups: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Transcript picker. @get '/picker/transcripts', -> @picker 'transcripts' $('#picker .transcript-querier').focus() # Transcript query results. @get '/transcript_query', -> if @params.query?.length < 1 @transcript_query() return $.ajax '//mygene.info/v2/query', dataType: 'json' data: q: @params.query # This limits the number of genes, which in turn may have any number # of transcripts. So this doesn't actually correspond to the number of # entries displayed but it'll do for now. For the same reason, we # can't use pagination here. limit: config.PAGE_SIZE fields: "entrezgene,name,symbol,refseq.rna,#{ config.MY_GENE_INFO.exons_field }" species: config.MY_GENE_INFO.species entrezonly: true dotfield: false email: config.MY_GENE_INFO.email success: (data) => if data.error console.log "MyGene.info query failed: #{ @params.query }" @transcript_query() return transcripts = [] for hit in data.hits continue unless hit.refseq? rna = hit.refseq.rna rna = [rna] unless Array.isArray rna for refseq in rna if refseq of (hit[config.MY_GENE_INFO.exons_field] || []) transcripts.push entrezgene: hit.entrezgene symbol: hit.symbol name: hit.name refseq: refseq @transcript_query transcripts: transcripts # It could be that all hits outide the requested limit (see above) # fail our filters. In that case the results displayed are actually # complete, but this is the best we can easily do. incomplete: data.hits.length < data.total error: (xhr) => console.log "MyGene.info query failed: #{ @params.query }" console.log xhr.responseText @transcript_query() # Homepage. @get '/', -> @show 'home' # Authenticate. @post '/authenticate', -> $('#form-authenticate').removeClass 'success fail' updateWith = (result) => $('#form-authenticate').addClass result @app.refresh() @app.api.authenticate @params['login'], @params['password'], success: -> updateWith 'success' error: (code, message) => updateWith 'fail' @error message return # List annotations. @get '/annotations', -> @app.api.annotations filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'annotations', subpage: 'list' annotations: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Show annotation. @get '/annotations/:annotation', -> @app.api.annotation @params.annotation, success: (annotation) => @show 'annotation', subpage: 'show' annotation: annotation error: (code, message) => @error message # Add annotation form. @get '/annotations_add', -> @show 'annotations', subpage: 'add' # Add annotation. @post '/annotations', -> query = switch @params.query when 'sample' then "sample: #{ @params.sample }" when 'group' then "group: #{ @params.group }" when 'custom' then @params.custom else '*' @app.api.create_annotation name: @params.name data_source: @params.data_source query: query success: (annotation) => @redirect config.BASE, 'annotations', encodeURIComponent annotation.uri @success "Added annotation '#{@params.name}'" error: (code, message) => @error message return # List data sources. @get '/data_sources', -> @app.api.data_sources filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'data_sources', subpage: 'list' data_sources: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Show data source. @get '/data_sources/:data_source', -> @app.api.data_source @params.data_source, success: (data_source) => @show 'data_source', subpage: 'show' data_source: data_source error: (code, message) => @error message # Edit data source form. @get '/data_sources/:data_source/edit', -> @app.api.data_source @params.data_source, success: (data_source) => @show 'data_source', subpage: 'edit' data_source: data_source error: (code, message) => @error message # Edit data source. @post '/data_sources/:data_source/edit', -> unless @params.dirty @error 'Data source is unchanged' return params = {} for field in @params.dirty.split ',' params[field] = @params[field] @app.api.edit_data_source @params.data_source, data: params success: (data_source) => @redirect config.BASE, 'data_sources', encodeURIComponent data_source.uri @success "Saved data source '#{@params.name}'" error: (code, message) => @error message return # Delete data_source form. @get '/data_sources/:data_source/delete', -> @app.api.data_source @params.data_source, success: (data_source) => @show 'data_source', subpage: 'delete' data_source: data_source error: (code, message) => @error message # Delete data source. @post '/data_sources/:data_source/delete', -> @app.api.delete_data_source @params.data_source, success: => @redirect config.BASE, 'data_sources' @success "Deleted data source '#{@params.name}'" error: (code, message) => @error message return # Add data source form. @get '/data_sources_add', -> @show 'data_sources', subpage: 'add' # Add data source. @post '/data_sources', -> @app.api.create_data_source data: name: @params.name filetype: @params.filetype local_path: @params.local_path success: (data_source) => @redirect config.BASE, 'data_sources', encodeURIComponent data_source.uri @success "Added data source '#{@params.name}'" error: (code, message) => @error message return # List groups. @get '/groups', -> @app.api.groups filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'groups', subpage: 'list' groups: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Show group. @get '/groups/:group', -> @app.api.group @params.group, success: (group) => @show 'group', subpage: 'show' group: group error: (code, message) => @error message # Edit group form. @get '/groups/:group/edit', -> @app.api.group @params.group, success: (group) => @show 'group', subpage: 'edit' group: group error: (code, message) => @error message # Edit group. @post '/groups/:group/edit', -> unless @params.dirty @error 'Group is unchanged' return params = {} for field in @params.dirty.split ',' params[field] = @params[field] @app.api.edit_group @params.group, data: params success: (group) => @redirect config.BASE, 'groups', encodeURIComponent group.uri @success "Saved group '#{@params.name}'" error: (code, message) => @error message return # Delete group form. @get '/groups/:group/delete', -> @app.api.group @params.group, success: (group) => @show 'group', subpage: 'delete' group: group error: (code, message) => @error message # Delete group. @post '/groups/:group/delete', -> @app.api.delete_group @params.group, success: => @redirect config.BASE, 'groups' @success "Deleted group '#{@params.name}'" error: (code, message) => @error message return # Add group form. @get '/groups_add', -> @show 'groups', subpage: 'add' # Add group. @post '/groups', -> @app.api.create_group data: name: @params.name success: (group) => @redirect config.BASE, 'groups', encodeURIComponent group.uri @success "Added group '#{@params.name}'" error: (code, message) => @error message return # Group samples. @get '/groups/:group/samples', -> @app.api.group @params.group, success: (group) => @app.api.samples group: @params.group page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'group', subpage: 'samples' group: group samples: items pagination: pagination error: (code, message) => @error message error: (code, message) => @error message # Lookup variant form. @get '/lookup_variant', -> @app.api.genome success: (genome) => @show 'lookup', subpage: 'variant' chromosomes: genome.chromosomes error: (code, message) => @error message # Lookup variant. @post '/lookup_variant', -> @app.api.create_variant data: chromosome: @params.chromosome position: @params.position reference: @params.reference observed: @params.observed success: (variant) => location = encodeURIComponent variant.uri location += "?query=#{ encodeURIComponent @params.query }" location += "&sample=#{ encodeURIComponent @params.sample }" location += "&group=#{ encodeURIComponent @params.group }" location += "&custom=#{ encodeURIComponent @params.custom }" @redirect config.BASE, 'variants', location error: (code, message) => @error message return # Lookup variants by region form. @get '/lookup_region', -> @app.api.genome success: (genome) => @show 'lookup', subpage: 'region' chromosomes: genome.chromosomes error: (code, message) => @error message # Lookup variants by transcript form. @get '/lookup_transcript', -> @show 'lookup', subpage: 'transcript' # List samples. @get '/samples', -> @app.api.samples filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'samples', subpage: 'list' samples: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Add sample form. @get '/samples_add', -> @show 'samples', subpage: 'add' # Add sample. @post '/samples', -> @app.api.create_sample data: name: @params.name pool_size: @params.pool_size coverage_profile: @params.coverage_profile? public: @params.public? success: (sample) => @redirect config.BASE, 'samples', encodeURIComponent sample.uri @success "Added sample '#{@params.name}'" error: (code, message) => @error message return # Show sample. @get '/samples/:sample', -> @app.api.sample @params.sample, success: (sample) => @show 'sample', subpage: 'show' sample: sample error: (code, message) => @error message # Edit sample form. @get '/samples/:sample/edit', -> @app.api.sample @params.sample, success: (sample) => @show 'sample', subpage: 'edit' sample: sample error: (code, message) => @error message # Edit sample. @post '/samples/:sample/edit', -> unless @params.dirty @error 'Sample is unchanged' return params = {} for field in @params.dirty.split ',' if field is 'groups' if @params[field]?.join? value = @params[field].join ',' else value = @params[field] ? '' else if field in ['coverage_profile', 'public'] value = @params[field]? else value = @params[field] params[field] = value @app.api.edit_sample @params.sample, data: params success: (sample) => @redirect config.BASE, 'samples', encodeURIComponent sample.uri @success "Saved sample '#{@params.name}'" error: (code, message) => @error message return # Delete sample form. @get '/samples/:sample/delete', -> @app.api.sample @params.sample, success: (sample) => @show 'sample', subpage: 'delete' sample: sample error: (code, message) => @error message # Delete sample. @post '/samples/:sample/delete', -> @app.api.delete_sample @params.sample, success: => # Todo: Redirect page might be forbidden for this user. @redirect config.BASE, 'samples' @success "Deleted sample '#{@params.name}'" error: (code, message) => @error message return # Sample variations. @get '/samples/:sample/variations', -> @app.api.sample @params.sample, success: (sample) => @app.api.variations sample: @params.sample page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'sample', subpage: 'variations' sample: sample variations: items pagination: pagination error: (code, message) => @error message error: (code, message) => @error message # Sample coverages. @get '/samples/:sample/coverages', -> @app.api.sample @params.sample, success: (sample) => @app.api.coverages sample: @params.sample page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'sample', subpage: 'coverages' sample: sample coverages: items pagination: pagination error: (code, message) => @error message error: (code, message) => @error message # List tokens. @get '/tokens', -> unless @app.api.current_user? @error 'Cannot list API tokens if not authenticated' return @app.api.tokens filter: 'own' page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'tokens', subpage: 'list' tokens: items pagination: pagination error: (code, message) => @error message # Add token form. @get '/tokens_add', -> @show 'tokens', subpage: 'add' # Add token. @post '/tokens', -> unless @app.api.current_user? @error 'Cannot generate API tokens if not authenticated' return @app.api.create_token data: user: @app.api.current_user.uri name: @params.name success: (token) => @redirect config.BASE, 'tokens', encodeURIComponent token.uri @success "Generated API token '#{@params.name}'" error: (code, message) => @error message return # Show token. @get '/tokens/:token', -> @app.api.token @params.token, success: (token) => @show 'token', subpage: 'show' token: token error: (code, message) => @error message # Edit token form. @get '/tokens/:token/edit', -> @app.api.token @params.token, success: (token) => @show 'token', subpage: 'edit' token: token error: (code, message) => @error message # Edit token. @post '/tokens/:token/edit', -> unless @params.dirty @error 'API token is unchanged' return params = {} for field in @params.dirty.split ',' params[field] = @params[field] @app.api.edit_token @params.token, data: params success: (token) => @redirect config.BASE, 'tokens', encodeURIComponent token.uri @success "Saved API token '#{@params.name}'" error: (code, message) => @error message return # Delete token form. @get '/tokens/:token/delete', -> @app.api.token @params.token, success: (token) => @show 'token', subpage: 'delete' token: token error: (code, message) => @error message # Delete token. @post '/tokens/:token/delete', -> @app.api.delete_token @params.token, success: => @redirect config.BASE, 'tokens' @success "Revoked API token '#{@params.name}'" error: (code, message) => @error message return # List users. @get '/users', -> @app.api.users filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'users', subpage: 'list' users: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Show user. @get '/users/:user', -> @app.api.user @params.user, success: (user) => @show 'user', subpage: 'show' user: user error: (code, message) => @error message # Edit user form. @get '/users/:user/edit', -> @app.api.user @params.user, success: (user) => user.roles = admin: 'admin' in user.roles importer: 'importer' in user.roles annotator: 'annotator' in user.roles trader: 'trader' in user.roles querier: 'querier' in user.roles group_querier: 'group-querier' in user.roles @show 'user', subpage: 'edit' user: user error: (code, message) => @error message # Edit user. @post '/users/:user/edit', -> unless @params.dirty @error 'User is unchanged' return if @params.password isnt @params.password_check @error "Password repeat doesn't match" return params = {} for field in @params.dirty.split ',' if field is 'password_check' continue if field is 'roles' if @params[field]?.join? params[field] = @params[field].join ',' else params[field] = @params[field] ? '' else params[field] = @params[field] @app.api.edit_user @params.user, data: params success: (user) => @redirect config.BASE, 'users', encodeURIComponent user.uri @success "Saved user '#{@params.name}'" error: (code, message) => @error message return # Delete user form. @get '/users/:user/delete', -> @app.api.user @params.user, success: (user) => @show 'user', subpage: 'delete' user: user error: (code, message) => @error message # Delete user. @post '/users/:user/delete', -> @app.api.delete_user @params.user, success: => @redirect config.BASE, 'users' @success "Deleted user '#{@params.name}'" error: (code, message) => @error message return # Add user form. @get '/users_add', -> @show 'users', subpage: 'add' # Add user. @post '/users', -> if @params.password isnt @params.password_check @error "Password repeat doesn't match" return if @params.roles?.join? roles = @params.roles.join ',' else roles = @params.roles ? '' @app.api.create_user data: name: @params.name login: @params.login password: @params.password roles: roles email: @params.email success: (user) => @redirect config.BASE, 'users', encodeURIComponent user.uri @success "Added user '#{@params.name}'" error: (code, message) => @error message return # Show variant. @get '/variants/:variant', -> query = switch @params.query when 'sample' then "sample: #{ @params.sample }" when 'group' then "group: #{ @params.group }" when 'custom' then @params.custom else '*' @app.api.variant @params.variant, query: query success: (variant) => params = variant: variant query: @params.query sample: {uri: @params.sample} group: {uri: @params.group} custom: @params.custom # TODO: The nesting of API calls is quite ugly. switch @params.query when 'sample' then @app.api.sample @params.sample, success: (sample) => params.sample = sample @show 'variant', params error: (code, message) => @error message when 'group' then @app.api.group @params.group, success: (group) => params.group = group @show 'variant', params error: (code, message) => @error message else @show 'variant', params error: (code, message) => @error message # List variants. @get '/variants', -> # TODO: Our API methods don't return promises, so we promisify some of # them here. After promisification of our API this will be obsolete. getVariants = (options={}) => new Promise (resolve, reject) => options.success = (items, pagination) -> resolve items: items pagination: pagination options.error = (code, message) -> reject code: code message: message @app.api.variants options getSample = (uri, options={}) => new Promise (resolve, reject) => options.success = resolve options.error = (code, message) -> reject code: code message: message @app.api.sample uri, options getGroup = (uri, options={}) => Promise (resolve, reject) => options.success = resolve options.error = (code, message) -> reject code: code message: message @app.api.group uri, options # Query mygene.info to construct a region from the transcript (which is # given as <entrezgene>/<refseq>). getTranscriptRegion = (transcript) -> [entrezgene, refseq] = transcript.split '/' Promise.resolve $.ajax "//mygene.info/v2/gene/#{ entrezgene }", dataType: 'json' data: fields: config.MY_GENE_INFO.exons_field email: config.MY_GENE_INFO.email .then (data) -> coordinates = data[config.MY_GENE_INFO.exons_field][refseq] chromosome: coordinates.chr begin: coordinates.txstart end: coordinates.txend .catch -> throw new Error "Could not retrieve annotation for transcript #{ refseq }" # The region to query is defined either directly, or as a transcript in # the form <entrezgene>/<refseq>. We can query mygene.info to convert the # transcript into a region. getRegion = if @params.transcript # TODO: Optionally only look at exons of a transcript. This can be # implemented by changing the API to accept a list of regions, or by # removing the intronic variants here manually. Preferably the former. getTranscriptRegion @params.transcript else # Synchronous promise, we already have the region. Promise.resolve chromosome: @params.chromosome begin: @params.begin end: @params.end # We need the region before we can get the variants. Both are needed # later. getRegionAndVariants = getRegion.then (region) => getVariants query: switch @params.query when 'sample' then "sample: #{ @params.sample }" when 'group' then "group: #{ @params.group }" when 'custom' then @params.custom else '*' region: region page_number: parseInt @params.page ? 0 .then (result) -> [region, result] # If querying on sample, get the sample data (name, etc). Likewise if we # are querying on group. getQueryParam = switch @params.query when 'sample' then (getSample @params.sample).then (sample) -> ['sample', sample] when 'group' then (getGroup @params.group).then (group) -> ['group', group] else Promise.resolve ['custom', @params.custom] Promise.all [getQueryParam, getRegionAndVariants] .then ([[param, value], [region, result]]) => data = query: @params.query region: region variants: result.items pagination: result.pagination data[param] = value # TODO: For a lookup by transcript, it might be nice to show some more # information on that such as gene name, transcript accession, and # perhaps even map the variant positions to the transcript. @show 'variants', data .catch (error) => # TODO: Use our own Error type and only show errors of that type # directly in the user interface. @error error.message module.exports = app
225632
# Aulë # # A web interface to the Varda database for genomic variation frequencies. # # <NAME> <<EMAIL>> # # Licensed under the MIT license, see the LICENSE file. # Todo: Figure out roles and rights for variant lookup. $ = require 'jquery' Promise = require 'bluebird' Sammy = require 'sammy' config = require 'config' app = Sammy '#main', -> # Always call init() with an initialized Api instance before calling run(). @init = (api) => @api = api # Create pagination data for use in template. createPagination = (total, current=0) -> if total <= 1 then return null pagination = pages: for p in [0...total] page: p label: p + 1 active: p == current many_pages: total >= config.MANY_PAGES if current > 0 pagination.previous = page: current - 1, label: current if current < total - 1 pagination.next = page: current + 1, label: current + 2 pagination # Create authentication data for use in template. createAuth = () => return null unless @api.current_user? roles = @api.current_user.roles user: @api.current_user roles: admin: 'admin' in roles importer: 'importer' in roles annotator: 'annotator' in roles trader: 'trader' in roles querier: 'querier' in roles group_querier: 'group-querier' in roles rights: list_samples: 'admin' in roles add_sample: 'importer' in roles or 'admin' in roles list_data_sources: 'admin' in roles add_data_source: true list_annotations: 'admin' in roles # TODO: 'trader' in roles or 'annotator' in roles or 'admin' in roles add_annotation: true add_group: 'admin' in roles list_users: 'admin' in roles add_user: 'admin' in roles query: 'admin' in roles or ('annotator' in roles and 'querier' in roles) group_query: 'admin' in roles or ('annotator' in roles and ( 'querier' in roles or 'group-querier' in roles)) global_query: 'admin' in roles or 'annotator' in roles # TODO: We ignored traders. They should be able to add an annotation # (the original data source might be theirs), but not do lookups. # Render a template. @helper 'render', (name, data={}) -> data.query_by_transcript = config.MY_GENE_INFO? data.base = config.BASE data.path = @path data.auth = createAuth() # https://github.com/altano/handlebars-loader/issues/81 # As a workaround we use inline partials for now. require('../templates/' + name + '.hb') data # Showing messages. @helper 'info', (message) -> @message 'info', message @helper 'success', (message) -> @message 'success', message @helper 'error', (message) -> @message 'error', message @helper 'message', (type, text) -> $('#messages').append @render 'message', type: type, text: text currentMessages = $('#messages > div.alert') window.setTimeout (-> currentMessages.alert 'close'), 3000 # Show main page content. @helper 'show', (page, data={}) -> data.page = page if data.pagination? {total, current} = data.pagination data.pagination = createPagination total, current @swap @render page, data $('#navigation').html @render 'navigation', data # Show picker. @helper 'picker', (page, data={}) -> if data.pagination? {total, current} = data.pagination data.pagination = createPagination total, current $('#picker .modal-body').html @render "picker_#{page}", data $('#picker').modal() # Show transcript query results. @helper 'transcript_query', (data={}) -> $('#transcript-query').html @render 'transcript_query', data # Sample picker. @get '/picker/samples', -> @app.api.samples filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @picker 'samples', samples: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Data source picker. @get '/picker/data_sources', -> @app.api.data_sources filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @picker 'data_sources', data_sources: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Group picker. @get '/picker/groups', -> @app.api.groups filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @picker 'groups', groups: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Transcript picker. @get '/picker/transcripts', -> @picker 'transcripts' $('#picker .transcript-querier').focus() # Transcript query results. @get '/transcript_query', -> if @params.query?.length < 1 @transcript_query() return $.ajax '//mygene.info/v2/query', dataType: 'json' data: q: @params.query # This limits the number of genes, which in turn may have any number # of transcripts. So this doesn't actually correspond to the number of # entries displayed but it'll do for now. For the same reason, we # can't use pagination here. limit: config.PAGE_SIZE fields: "entrezgene,name,symbol,refseq.rna,#{ config.MY_GENE_INFO.exons_field }" species: config.MY_GENE_INFO.species entrezonly: true dotfield: false email: config.MY_GENE_INFO.email success: (data) => if data.error console.log "MyGene.info query failed: #{ @params.query }" @transcript_query() return transcripts = [] for hit in data.hits continue unless hit.refseq? rna = hit.refseq.rna rna = [rna] unless Array.isArray rna for refseq in rna if refseq of (hit[config.MY_GENE_INFO.exons_field] || []) transcripts.push entrezgene: hit.entrezgene symbol: hit.symbol name: hit.name refseq: refseq @transcript_query transcripts: transcripts # It could be that all hits outide the requested limit (see above) # fail our filters. In that case the results displayed are actually # complete, but this is the best we can easily do. incomplete: data.hits.length < data.total error: (xhr) => console.log "MyGene.info query failed: #{ @params.query }" console.log xhr.responseText @transcript_query() # Homepage. @get '/', -> @show 'home' # Authenticate. @post '/authenticate', -> $('#form-authenticate').removeClass 'success fail' updateWith = (result) => $('#form-authenticate').addClass result @app.refresh() @app.api.authenticate @params['login'], @params['password'], success: -> updateWith 'success' error: (code, message) => updateWith 'fail' @error message return # List annotations. @get '/annotations', -> @app.api.annotations filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'annotations', subpage: 'list' annotations: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Show annotation. @get '/annotations/:annotation', -> @app.api.annotation @params.annotation, success: (annotation) => @show 'annotation', subpage: 'show' annotation: annotation error: (code, message) => @error message # Add annotation form. @get '/annotations_add', -> @show 'annotations', subpage: 'add' # Add annotation. @post '/annotations', -> query = switch @params.query when 'sample' then "sample: #{ @params.sample }" when 'group' then "group: #{ @params.group }" when 'custom' then @params.custom else '*' @app.api.create_annotation name: @params.name data_source: @params.data_source query: query success: (annotation) => @redirect config.BASE, 'annotations', encodeURIComponent annotation.uri @success "Added annotation '#{@params.name}'" error: (code, message) => @error message return # List data sources. @get '/data_sources', -> @app.api.data_sources filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'data_sources', subpage: 'list' data_sources: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Show data source. @get '/data_sources/:data_source', -> @app.api.data_source @params.data_source, success: (data_source) => @show 'data_source', subpage: 'show' data_source: data_source error: (code, message) => @error message # Edit data source form. @get '/data_sources/:data_source/edit', -> @app.api.data_source @params.data_source, success: (data_source) => @show 'data_source', subpage: 'edit' data_source: data_source error: (code, message) => @error message # Edit data source. @post '/data_sources/:data_source/edit', -> unless @params.dirty @error 'Data source is unchanged' return params = {} for field in @params.dirty.split ',' params[field] = @params[field] @app.api.edit_data_source @params.data_source, data: params success: (data_source) => @redirect config.BASE, 'data_sources', encodeURIComponent data_source.uri @success "Saved data source '#{@params.name}'" error: (code, message) => @error message return # Delete data_source form. @get '/data_sources/:data_source/delete', -> @app.api.data_source @params.data_source, success: (data_source) => @show 'data_source', subpage: 'delete' data_source: data_source error: (code, message) => @error message # Delete data source. @post '/data_sources/:data_source/delete', -> @app.api.delete_data_source @params.data_source, success: => @redirect config.BASE, 'data_sources' @success "Deleted data source '#{@params.name}'" error: (code, message) => @error message return # Add data source form. @get '/data_sources_add', -> @show 'data_sources', subpage: 'add' # Add data source. @post '/data_sources', -> @app.api.create_data_source data: name: @params.name filetype: @params.filetype local_path: @params.local_path success: (data_source) => @redirect config.BASE, 'data_sources', encodeURIComponent data_source.uri @success "Added data source '#{@params.name}'" error: (code, message) => @error message return # List groups. @get '/groups', -> @app.api.groups filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'groups', subpage: 'list' groups: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Show group. @get '/groups/:group', -> @app.api.group @params.group, success: (group) => @show 'group', subpage: 'show' group: group error: (code, message) => @error message # Edit group form. @get '/groups/:group/edit', -> @app.api.group @params.group, success: (group) => @show 'group', subpage: 'edit' group: group error: (code, message) => @error message # Edit group. @post '/groups/:group/edit', -> unless @params.dirty @error 'Group is unchanged' return params = {} for field in @params.dirty.split ',' params[field] = @params[field] @app.api.edit_group @params.group, data: params success: (group) => @redirect config.BASE, 'groups', encodeURIComponent group.uri @success "Saved group '#{@params.name}'" error: (code, message) => @error message return # Delete group form. @get '/groups/:group/delete', -> @app.api.group @params.group, success: (group) => @show 'group', subpage: 'delete' group: group error: (code, message) => @error message # Delete group. @post '/groups/:group/delete', -> @app.api.delete_group @params.group, success: => @redirect config.BASE, 'groups' @success "Deleted group '#{@params.name}'" error: (code, message) => @error message return # Add group form. @get '/groups_add', -> @show 'groups', subpage: 'add' # Add group. @post '/groups', -> @app.api.create_group data: name: @params.name success: (group) => @redirect config.BASE, 'groups', encodeURIComponent group.uri @success "Added group '#{@params.name}'" error: (code, message) => @error message return # Group samples. @get '/groups/:group/samples', -> @app.api.group @params.group, success: (group) => @app.api.samples group: @params.group page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'group', subpage: 'samples' group: group samples: items pagination: pagination error: (code, message) => @error message error: (code, message) => @error message # Lookup variant form. @get '/lookup_variant', -> @app.api.genome success: (genome) => @show 'lookup', subpage: 'variant' chromosomes: genome.chromosomes error: (code, message) => @error message # Lookup variant. @post '/lookup_variant', -> @app.api.create_variant data: chromosome: @params.chromosome position: @params.position reference: @params.reference observed: @params.observed success: (variant) => location = encodeURIComponent variant.uri location += "?query=#{ encodeURIComponent @params.query }" location += "&sample=#{ encodeURIComponent @params.sample }" location += "&group=#{ encodeURIComponent @params.group }" location += "&custom=#{ encodeURIComponent @params.custom }" @redirect config.BASE, 'variants', location error: (code, message) => @error message return # Lookup variants by region form. @get '/lookup_region', -> @app.api.genome success: (genome) => @show 'lookup', subpage: 'region' chromosomes: genome.chromosomes error: (code, message) => @error message # Lookup variants by transcript form. @get '/lookup_transcript', -> @show 'lookup', subpage: 'transcript' # List samples. @get '/samples', -> @app.api.samples filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'samples', subpage: 'list' samples: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Add sample form. @get '/samples_add', -> @show 'samples', subpage: 'add' # Add sample. @post '/samples', -> @app.api.create_sample data: name: @params.name pool_size: @params.pool_size coverage_profile: @params.coverage_profile? public: @params.public? success: (sample) => @redirect config.BASE, 'samples', encodeURIComponent sample.uri @success "Added sample '#{@params.name}'" error: (code, message) => @error message return # Show sample. @get '/samples/:sample', -> @app.api.sample @params.sample, success: (sample) => @show 'sample', subpage: 'show' sample: sample error: (code, message) => @error message # Edit sample form. @get '/samples/:sample/edit', -> @app.api.sample @params.sample, success: (sample) => @show 'sample', subpage: 'edit' sample: sample error: (code, message) => @error message # Edit sample. @post '/samples/:sample/edit', -> unless @params.dirty @error 'Sample is unchanged' return params = {} for field in @params.dirty.split ',' if field is 'groups' if @params[field]?.join? value = @params[field].join ',' else value = @params[field] ? '' else if field in ['coverage_profile', 'public'] value = @params[field]? else value = @params[field] params[field] = value @app.api.edit_sample @params.sample, data: params success: (sample) => @redirect config.BASE, 'samples', encodeURIComponent sample.uri @success "Saved sample '#{@params.name}'" error: (code, message) => @error message return # Delete sample form. @get '/samples/:sample/delete', -> @app.api.sample @params.sample, success: (sample) => @show 'sample', subpage: 'delete' sample: sample error: (code, message) => @error message # Delete sample. @post '/samples/:sample/delete', -> @app.api.delete_sample @params.sample, success: => # Todo: Redirect page might be forbidden for this user. @redirect config.BASE, 'samples' @success "Deleted sample '#{@params.name}'" error: (code, message) => @error message return # Sample variations. @get '/samples/:sample/variations', -> @app.api.sample @params.sample, success: (sample) => @app.api.variations sample: @params.sample page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'sample', subpage: 'variations' sample: sample variations: items pagination: pagination error: (code, message) => @error message error: (code, message) => @error message # Sample coverages. @get '/samples/:sample/coverages', -> @app.api.sample @params.sample, success: (sample) => @app.api.coverages sample: @params.sample page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'sample', subpage: 'coverages' sample: sample coverages: items pagination: pagination error: (code, message) => @error message error: (code, message) => @error message # List tokens. @get '/tokens', -> unless @app.api.current_user? @error 'Cannot list API tokens if not authenticated' return @app.api.tokens filter: 'own' page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'tokens', subpage: 'list' tokens: items pagination: pagination error: (code, message) => @error message # Add token form. @get '/tokens_add', -> @show 'tokens', subpage: 'add' # Add token. @post '/tokens', -> unless @app.api.current_user? @error 'Cannot generate API tokens if not authenticated' return @app.api.create_token data: user: @app.api.current_user.uri name: @params.name success: (token) => @redirect config.BASE, 'tokens', encodeURIComponent token.uri @success "Generated API token '#{@params.name}'" error: (code, message) => @error message return # Show token. @get '/tokens/:token', -> @app.api.token @params.token, success: (token) => @show 'token', subpage: 'show' token: token error: (code, message) => @error message # Edit token form. @get '/tokens/:token/edit', -> @app.api.token @params.token, success: (token) => @show 'token', subpage: 'edit' token: token error: (code, message) => @error message # Edit token. @post '/tokens/:token/edit', -> unless @params.dirty @error 'API token is unchanged' return params = {} for field in @params.dirty.split ',' params[field] = @params[field] @app.api.edit_token @params.token, data: params success: (token) => @redirect config.BASE, 'tokens', encodeURIComponent token.uri @success "Saved API token '#{@params.name}'" error: (code, message) => @error message return # Delete token form. @get '/tokens/:token/delete', -> @app.api.token @params.token, success: (token) => @show 'token', subpage: 'delete' token: token error: (code, message) => @error message # Delete token. @post '/tokens/:token/delete', -> @app.api.delete_token @params.token, success: => @redirect config.BASE, 'tokens' @success "Revoked API token '#{@params.name}'" error: (code, message) => @error message return # List users. @get '/users', -> @app.api.users filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'users', subpage: 'list' users: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Show user. @get '/users/:user', -> @app.api.user @params.user, success: (user) => @show 'user', subpage: 'show' user: user error: (code, message) => @error message # Edit user form. @get '/users/:user/edit', -> @app.api.user @params.user, success: (user) => user.roles = admin: 'admin' in user.roles importer: 'importer' in user.roles annotator: 'annotator' in user.roles trader: 'trader' in user.roles querier: 'querier' in user.roles group_querier: 'group-querier' in user.roles @show 'user', subpage: 'edit' user: user error: (code, message) => @error message # Edit user. @post '/users/:user/edit', -> unless @params.dirty @error 'User is unchanged' return if @params.password isnt @params.password_check @error "Password repeat doesn't match" return params = {} for field in @params.dirty.split ',' if field is 'password_check' continue if field is 'roles' if @params[field]?.join? params[field] = @params[field].join ',' else params[field] = @params[field] ? '' else params[field] = @params[field] @app.api.edit_user @params.user, data: params success: (user) => @redirect config.BASE, 'users', encodeURIComponent user.uri @success "Saved user '#{@params.name}'" error: (code, message) => @error message return # Delete user form. @get '/users/:user/delete', -> @app.api.user @params.user, success: (user) => @show 'user', subpage: 'delete' user: user error: (code, message) => @error message # Delete user. @post '/users/:user/delete', -> @app.api.delete_user @params.user, success: => @redirect config.BASE, 'users' @success "Deleted user '#{@params.name}'" error: (code, message) => @error message return # Add user form. @get '/users_add', -> @show 'users', subpage: 'add' # Add user. @post '/users', -> if @params.password isnt @params.password_check @error "Password repeat doesn't match" return if @params.roles?.join? roles = @params.roles.join ',' else roles = @params.roles ? '' @app.api.create_user data: name:<NAME> @params.name login: @params.login password: <PASSWORD> roles: roles email: @params.email success: (user) => @redirect config.BASE, 'users', encodeURIComponent user.uri @success "Added user '#{@params.name}'" error: (code, message) => @error message return # Show variant. @get '/variants/:variant', -> query = switch @params.query when 'sample' then "sample: #{ @params.sample }" when 'group' then "group: #{ @params.group }" when 'custom' then @params.custom else '*' @app.api.variant @params.variant, query: query success: (variant) => params = variant: variant query: @params.query sample: {uri: @params.sample} group: {uri: @params.group} custom: @params.custom # TODO: The nesting of API calls is quite ugly. switch @params.query when 'sample' then @app.api.sample @params.sample, success: (sample) => params.sample = sample @show 'variant', params error: (code, message) => @error message when 'group' then @app.api.group @params.group, success: (group) => params.group = group @show 'variant', params error: (code, message) => @error message else @show 'variant', params error: (code, message) => @error message # List variants. @get '/variants', -> # TODO: Our API methods don't return promises, so we promisify some of # them here. After promisification of our API this will be obsolete. getVariants = (options={}) => new Promise (resolve, reject) => options.success = (items, pagination) -> resolve items: items pagination: pagination options.error = (code, message) -> reject code: code message: message @app.api.variants options getSample = (uri, options={}) => new Promise (resolve, reject) => options.success = resolve options.error = (code, message) -> reject code: code message: message @app.api.sample uri, options getGroup = (uri, options={}) => Promise (resolve, reject) => options.success = resolve options.error = (code, message) -> reject code: code message: message @app.api.group uri, options # Query mygene.info to construct a region from the transcript (which is # given as <entrezgene>/<refseq>). getTranscriptRegion = (transcript) -> [entrezgene, refseq] = transcript.split '/' Promise.resolve $.ajax "//mygene.info/v2/gene/#{ entrezgene }", dataType: 'json' data: fields: config.MY_GENE_INFO.exons_field email: config.MY_GENE_INFO.email .then (data) -> coordinates = data[config.MY_GENE_INFO.exons_field][refseq] chromosome: coordinates.chr begin: coordinates.txstart end: coordinates.txend .catch -> throw new Error "Could not retrieve annotation for transcript #{ refseq }" # The region to query is defined either directly, or as a transcript in # the form <entrezgene>/<refseq>. We can query mygene.info to convert the # transcript into a region. getRegion = if @params.transcript # TODO: Optionally only look at exons of a transcript. This can be # implemented by changing the API to accept a list of regions, or by # removing the intronic variants here manually. Preferably the former. getTranscriptRegion @params.transcript else # Synchronous promise, we already have the region. Promise.resolve chromosome: @params.chromosome begin: @params.begin end: @params.end # We need the region before we can get the variants. Both are needed # later. getRegionAndVariants = getRegion.then (region) => getVariants query: switch @params.query when 'sample' then "sample: #{ @params.sample }" when 'group' then "group: #{ @params.group }" when 'custom' then @params.custom else '*' region: region page_number: parseInt @params.page ? 0 .then (result) -> [region, result] # If querying on sample, get the sample data (name, etc). Likewise if we # are querying on group. getQueryParam = switch @params.query when 'sample' then (getSample @params.sample).then (sample) -> ['sample', sample] when 'group' then (getGroup @params.group).then (group) -> ['group', group] else Promise.resolve ['custom', @params.custom] Promise.all [getQueryParam, getRegionAndVariants] .then ([[param, value], [region, result]]) => data = query: @params.query region: region variants: result.items pagination: result.pagination data[param] = value # TODO: For a lookup by transcript, it might be nice to show some more # information on that such as gene name, transcript accession, and # perhaps even map the variant positions to the transcript. @show 'variants', data .catch (error) => # TODO: Use our own Error type and only show errors of that type # directly in the user interface. @error error.message module.exports = app
true
# Aulë # # A web interface to the Varda database for genomic variation frequencies. # # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # Licensed under the MIT license, see the LICENSE file. # Todo: Figure out roles and rights for variant lookup. $ = require 'jquery' Promise = require 'bluebird' Sammy = require 'sammy' config = require 'config' app = Sammy '#main', -> # Always call init() with an initialized Api instance before calling run(). @init = (api) => @api = api # Create pagination data for use in template. createPagination = (total, current=0) -> if total <= 1 then return null pagination = pages: for p in [0...total] page: p label: p + 1 active: p == current many_pages: total >= config.MANY_PAGES if current > 0 pagination.previous = page: current - 1, label: current if current < total - 1 pagination.next = page: current + 1, label: current + 2 pagination # Create authentication data for use in template. createAuth = () => return null unless @api.current_user? roles = @api.current_user.roles user: @api.current_user roles: admin: 'admin' in roles importer: 'importer' in roles annotator: 'annotator' in roles trader: 'trader' in roles querier: 'querier' in roles group_querier: 'group-querier' in roles rights: list_samples: 'admin' in roles add_sample: 'importer' in roles or 'admin' in roles list_data_sources: 'admin' in roles add_data_source: true list_annotations: 'admin' in roles # TODO: 'trader' in roles or 'annotator' in roles or 'admin' in roles add_annotation: true add_group: 'admin' in roles list_users: 'admin' in roles add_user: 'admin' in roles query: 'admin' in roles or ('annotator' in roles and 'querier' in roles) group_query: 'admin' in roles or ('annotator' in roles and ( 'querier' in roles or 'group-querier' in roles)) global_query: 'admin' in roles or 'annotator' in roles # TODO: We ignored traders. They should be able to add an annotation # (the original data source might be theirs), but not do lookups. # Render a template. @helper 'render', (name, data={}) -> data.query_by_transcript = config.MY_GENE_INFO? data.base = config.BASE data.path = @path data.auth = createAuth() # https://github.com/altano/handlebars-loader/issues/81 # As a workaround we use inline partials for now. require('../templates/' + name + '.hb') data # Showing messages. @helper 'info', (message) -> @message 'info', message @helper 'success', (message) -> @message 'success', message @helper 'error', (message) -> @message 'error', message @helper 'message', (type, text) -> $('#messages').append @render 'message', type: type, text: text currentMessages = $('#messages > div.alert') window.setTimeout (-> currentMessages.alert 'close'), 3000 # Show main page content. @helper 'show', (page, data={}) -> data.page = page if data.pagination? {total, current} = data.pagination data.pagination = createPagination total, current @swap @render page, data $('#navigation').html @render 'navigation', data # Show picker. @helper 'picker', (page, data={}) -> if data.pagination? {total, current} = data.pagination data.pagination = createPagination total, current $('#picker .modal-body').html @render "picker_#{page}", data $('#picker').modal() # Show transcript query results. @helper 'transcript_query', (data={}) -> $('#transcript-query').html @render 'transcript_query', data # Sample picker. @get '/picker/samples', -> @app.api.samples filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @picker 'samples', samples: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Data source picker. @get '/picker/data_sources', -> @app.api.data_sources filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @picker 'data_sources', data_sources: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Group picker. @get '/picker/groups', -> @app.api.groups filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @picker 'groups', groups: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Transcript picker. @get '/picker/transcripts', -> @picker 'transcripts' $('#picker .transcript-querier').focus() # Transcript query results. @get '/transcript_query', -> if @params.query?.length < 1 @transcript_query() return $.ajax '//mygene.info/v2/query', dataType: 'json' data: q: @params.query # This limits the number of genes, which in turn may have any number # of transcripts. So this doesn't actually correspond to the number of # entries displayed but it'll do for now. For the same reason, we # can't use pagination here. limit: config.PAGE_SIZE fields: "entrezgene,name,symbol,refseq.rna,#{ config.MY_GENE_INFO.exons_field }" species: config.MY_GENE_INFO.species entrezonly: true dotfield: false email: config.MY_GENE_INFO.email success: (data) => if data.error console.log "MyGene.info query failed: #{ @params.query }" @transcript_query() return transcripts = [] for hit in data.hits continue unless hit.refseq? rna = hit.refseq.rna rna = [rna] unless Array.isArray rna for refseq in rna if refseq of (hit[config.MY_GENE_INFO.exons_field] || []) transcripts.push entrezgene: hit.entrezgene symbol: hit.symbol name: hit.name refseq: refseq @transcript_query transcripts: transcripts # It could be that all hits outide the requested limit (see above) # fail our filters. In that case the results displayed are actually # complete, but this is the best we can easily do. incomplete: data.hits.length < data.total error: (xhr) => console.log "MyGene.info query failed: #{ @params.query }" console.log xhr.responseText @transcript_query() # Homepage. @get '/', -> @show 'home' # Authenticate. @post '/authenticate', -> $('#form-authenticate').removeClass 'success fail' updateWith = (result) => $('#form-authenticate').addClass result @app.refresh() @app.api.authenticate @params['login'], @params['password'], success: -> updateWith 'success' error: (code, message) => updateWith 'fail' @error message return # List annotations. @get '/annotations', -> @app.api.annotations filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'annotations', subpage: 'list' annotations: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Show annotation. @get '/annotations/:annotation', -> @app.api.annotation @params.annotation, success: (annotation) => @show 'annotation', subpage: 'show' annotation: annotation error: (code, message) => @error message # Add annotation form. @get '/annotations_add', -> @show 'annotations', subpage: 'add' # Add annotation. @post '/annotations', -> query = switch @params.query when 'sample' then "sample: #{ @params.sample }" when 'group' then "group: #{ @params.group }" when 'custom' then @params.custom else '*' @app.api.create_annotation name: @params.name data_source: @params.data_source query: query success: (annotation) => @redirect config.BASE, 'annotations', encodeURIComponent annotation.uri @success "Added annotation '#{@params.name}'" error: (code, message) => @error message return # List data sources. @get '/data_sources', -> @app.api.data_sources filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'data_sources', subpage: 'list' data_sources: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Show data source. @get '/data_sources/:data_source', -> @app.api.data_source @params.data_source, success: (data_source) => @show 'data_source', subpage: 'show' data_source: data_source error: (code, message) => @error message # Edit data source form. @get '/data_sources/:data_source/edit', -> @app.api.data_source @params.data_source, success: (data_source) => @show 'data_source', subpage: 'edit' data_source: data_source error: (code, message) => @error message # Edit data source. @post '/data_sources/:data_source/edit', -> unless @params.dirty @error 'Data source is unchanged' return params = {} for field in @params.dirty.split ',' params[field] = @params[field] @app.api.edit_data_source @params.data_source, data: params success: (data_source) => @redirect config.BASE, 'data_sources', encodeURIComponent data_source.uri @success "Saved data source '#{@params.name}'" error: (code, message) => @error message return # Delete data_source form. @get '/data_sources/:data_source/delete', -> @app.api.data_source @params.data_source, success: (data_source) => @show 'data_source', subpage: 'delete' data_source: data_source error: (code, message) => @error message # Delete data source. @post '/data_sources/:data_source/delete', -> @app.api.delete_data_source @params.data_source, success: => @redirect config.BASE, 'data_sources' @success "Deleted data source '#{@params.name}'" error: (code, message) => @error message return # Add data source form. @get '/data_sources_add', -> @show 'data_sources', subpage: 'add' # Add data source. @post '/data_sources', -> @app.api.create_data_source data: name: @params.name filetype: @params.filetype local_path: @params.local_path success: (data_source) => @redirect config.BASE, 'data_sources', encodeURIComponent data_source.uri @success "Added data source '#{@params.name}'" error: (code, message) => @error message return # List groups. @get '/groups', -> @app.api.groups filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'groups', subpage: 'list' groups: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Show group. @get '/groups/:group', -> @app.api.group @params.group, success: (group) => @show 'group', subpage: 'show' group: group error: (code, message) => @error message # Edit group form. @get '/groups/:group/edit', -> @app.api.group @params.group, success: (group) => @show 'group', subpage: 'edit' group: group error: (code, message) => @error message # Edit group. @post '/groups/:group/edit', -> unless @params.dirty @error 'Group is unchanged' return params = {} for field in @params.dirty.split ',' params[field] = @params[field] @app.api.edit_group @params.group, data: params success: (group) => @redirect config.BASE, 'groups', encodeURIComponent group.uri @success "Saved group '#{@params.name}'" error: (code, message) => @error message return # Delete group form. @get '/groups/:group/delete', -> @app.api.group @params.group, success: (group) => @show 'group', subpage: 'delete' group: group error: (code, message) => @error message # Delete group. @post '/groups/:group/delete', -> @app.api.delete_group @params.group, success: => @redirect config.BASE, 'groups' @success "Deleted group '#{@params.name}'" error: (code, message) => @error message return # Add group form. @get '/groups_add', -> @show 'groups', subpage: 'add' # Add group. @post '/groups', -> @app.api.create_group data: name: @params.name success: (group) => @redirect config.BASE, 'groups', encodeURIComponent group.uri @success "Added group '#{@params.name}'" error: (code, message) => @error message return # Group samples. @get '/groups/:group/samples', -> @app.api.group @params.group, success: (group) => @app.api.samples group: @params.group page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'group', subpage: 'samples' group: group samples: items pagination: pagination error: (code, message) => @error message error: (code, message) => @error message # Lookup variant form. @get '/lookup_variant', -> @app.api.genome success: (genome) => @show 'lookup', subpage: 'variant' chromosomes: genome.chromosomes error: (code, message) => @error message # Lookup variant. @post '/lookup_variant', -> @app.api.create_variant data: chromosome: @params.chromosome position: @params.position reference: @params.reference observed: @params.observed success: (variant) => location = encodeURIComponent variant.uri location += "?query=#{ encodeURIComponent @params.query }" location += "&sample=#{ encodeURIComponent @params.sample }" location += "&group=#{ encodeURIComponent @params.group }" location += "&custom=#{ encodeURIComponent @params.custom }" @redirect config.BASE, 'variants', location error: (code, message) => @error message return # Lookup variants by region form. @get '/lookup_region', -> @app.api.genome success: (genome) => @show 'lookup', subpage: 'region' chromosomes: genome.chromosomes error: (code, message) => @error message # Lookup variants by transcript form. @get '/lookup_transcript', -> @show 'lookup', subpage: 'transcript' # List samples. @get '/samples', -> @app.api.samples filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'samples', subpage: 'list' samples: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Add sample form. @get '/samples_add', -> @show 'samples', subpage: 'add' # Add sample. @post '/samples', -> @app.api.create_sample data: name: @params.name pool_size: @params.pool_size coverage_profile: @params.coverage_profile? public: @params.public? success: (sample) => @redirect config.BASE, 'samples', encodeURIComponent sample.uri @success "Added sample '#{@params.name}'" error: (code, message) => @error message return # Show sample. @get '/samples/:sample', -> @app.api.sample @params.sample, success: (sample) => @show 'sample', subpage: 'show' sample: sample error: (code, message) => @error message # Edit sample form. @get '/samples/:sample/edit', -> @app.api.sample @params.sample, success: (sample) => @show 'sample', subpage: 'edit' sample: sample error: (code, message) => @error message # Edit sample. @post '/samples/:sample/edit', -> unless @params.dirty @error 'Sample is unchanged' return params = {} for field in @params.dirty.split ',' if field is 'groups' if @params[field]?.join? value = @params[field].join ',' else value = @params[field] ? '' else if field in ['coverage_profile', 'public'] value = @params[field]? else value = @params[field] params[field] = value @app.api.edit_sample @params.sample, data: params success: (sample) => @redirect config.BASE, 'samples', encodeURIComponent sample.uri @success "Saved sample '#{@params.name}'" error: (code, message) => @error message return # Delete sample form. @get '/samples/:sample/delete', -> @app.api.sample @params.sample, success: (sample) => @show 'sample', subpage: 'delete' sample: sample error: (code, message) => @error message # Delete sample. @post '/samples/:sample/delete', -> @app.api.delete_sample @params.sample, success: => # Todo: Redirect page might be forbidden for this user. @redirect config.BASE, 'samples' @success "Deleted sample '#{@params.name}'" error: (code, message) => @error message return # Sample variations. @get '/samples/:sample/variations', -> @app.api.sample @params.sample, success: (sample) => @app.api.variations sample: @params.sample page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'sample', subpage: 'variations' sample: sample variations: items pagination: pagination error: (code, message) => @error message error: (code, message) => @error message # Sample coverages. @get '/samples/:sample/coverages', -> @app.api.sample @params.sample, success: (sample) => @app.api.coverages sample: @params.sample page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'sample', subpage: 'coverages' sample: sample coverages: items pagination: pagination error: (code, message) => @error message error: (code, message) => @error message # List tokens. @get '/tokens', -> unless @app.api.current_user? @error 'Cannot list API tokens if not authenticated' return @app.api.tokens filter: 'own' page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'tokens', subpage: 'list' tokens: items pagination: pagination error: (code, message) => @error message # Add token form. @get '/tokens_add', -> @show 'tokens', subpage: 'add' # Add token. @post '/tokens', -> unless @app.api.current_user? @error 'Cannot generate API tokens if not authenticated' return @app.api.create_token data: user: @app.api.current_user.uri name: @params.name success: (token) => @redirect config.BASE, 'tokens', encodeURIComponent token.uri @success "Generated API token '#{@params.name}'" error: (code, message) => @error message return # Show token. @get '/tokens/:token', -> @app.api.token @params.token, success: (token) => @show 'token', subpage: 'show' token: token error: (code, message) => @error message # Edit token form. @get '/tokens/:token/edit', -> @app.api.token @params.token, success: (token) => @show 'token', subpage: 'edit' token: token error: (code, message) => @error message # Edit token. @post '/tokens/:token/edit', -> unless @params.dirty @error 'API token is unchanged' return params = {} for field in @params.dirty.split ',' params[field] = @params[field] @app.api.edit_token @params.token, data: params success: (token) => @redirect config.BASE, 'tokens', encodeURIComponent token.uri @success "Saved API token '#{@params.name}'" error: (code, message) => @error message return # Delete token form. @get '/tokens/:token/delete', -> @app.api.token @params.token, success: (token) => @show 'token', subpage: 'delete' token: token error: (code, message) => @error message # Delete token. @post '/tokens/:token/delete', -> @app.api.delete_token @params.token, success: => @redirect config.BASE, 'tokens' @success "Revoked API token '#{@params.name}'" error: (code, message) => @error message return # List users. @get '/users', -> @app.api.users filter: @params.filter page_number: parseInt @params.page ? 0 success: (items, pagination) => @show 'users', subpage: 'list' users: items filter: @params.filter ? '' pagination: pagination error: (code, message) => @error message # Show user. @get '/users/:user', -> @app.api.user @params.user, success: (user) => @show 'user', subpage: 'show' user: user error: (code, message) => @error message # Edit user form. @get '/users/:user/edit', -> @app.api.user @params.user, success: (user) => user.roles = admin: 'admin' in user.roles importer: 'importer' in user.roles annotator: 'annotator' in user.roles trader: 'trader' in user.roles querier: 'querier' in user.roles group_querier: 'group-querier' in user.roles @show 'user', subpage: 'edit' user: user error: (code, message) => @error message # Edit user. @post '/users/:user/edit', -> unless @params.dirty @error 'User is unchanged' return if @params.password isnt @params.password_check @error "Password repeat doesn't match" return params = {} for field in @params.dirty.split ',' if field is 'password_check' continue if field is 'roles' if @params[field]?.join? params[field] = @params[field].join ',' else params[field] = @params[field] ? '' else params[field] = @params[field] @app.api.edit_user @params.user, data: params success: (user) => @redirect config.BASE, 'users', encodeURIComponent user.uri @success "Saved user '#{@params.name}'" error: (code, message) => @error message return # Delete user form. @get '/users/:user/delete', -> @app.api.user @params.user, success: (user) => @show 'user', subpage: 'delete' user: user error: (code, message) => @error message # Delete user. @post '/users/:user/delete', -> @app.api.delete_user @params.user, success: => @redirect config.BASE, 'users' @success "Deleted user '#{@params.name}'" error: (code, message) => @error message return # Add user form. @get '/users_add', -> @show 'users', subpage: 'add' # Add user. @post '/users', -> if @params.password isnt @params.password_check @error "Password repeat doesn't match" return if @params.roles?.join? roles = @params.roles.join ',' else roles = @params.roles ? '' @app.api.create_user data: name:PI:NAME:<NAME>END_PI @params.name login: @params.login password: PI:PASSWORD:<PASSWORD>END_PI roles: roles email: @params.email success: (user) => @redirect config.BASE, 'users', encodeURIComponent user.uri @success "Added user '#{@params.name}'" error: (code, message) => @error message return # Show variant. @get '/variants/:variant', -> query = switch @params.query when 'sample' then "sample: #{ @params.sample }" when 'group' then "group: #{ @params.group }" when 'custom' then @params.custom else '*' @app.api.variant @params.variant, query: query success: (variant) => params = variant: variant query: @params.query sample: {uri: @params.sample} group: {uri: @params.group} custom: @params.custom # TODO: The nesting of API calls is quite ugly. switch @params.query when 'sample' then @app.api.sample @params.sample, success: (sample) => params.sample = sample @show 'variant', params error: (code, message) => @error message when 'group' then @app.api.group @params.group, success: (group) => params.group = group @show 'variant', params error: (code, message) => @error message else @show 'variant', params error: (code, message) => @error message # List variants. @get '/variants', -> # TODO: Our API methods don't return promises, so we promisify some of # them here. After promisification of our API this will be obsolete. getVariants = (options={}) => new Promise (resolve, reject) => options.success = (items, pagination) -> resolve items: items pagination: pagination options.error = (code, message) -> reject code: code message: message @app.api.variants options getSample = (uri, options={}) => new Promise (resolve, reject) => options.success = resolve options.error = (code, message) -> reject code: code message: message @app.api.sample uri, options getGroup = (uri, options={}) => Promise (resolve, reject) => options.success = resolve options.error = (code, message) -> reject code: code message: message @app.api.group uri, options # Query mygene.info to construct a region from the transcript (which is # given as <entrezgene>/<refseq>). getTranscriptRegion = (transcript) -> [entrezgene, refseq] = transcript.split '/' Promise.resolve $.ajax "//mygene.info/v2/gene/#{ entrezgene }", dataType: 'json' data: fields: config.MY_GENE_INFO.exons_field email: config.MY_GENE_INFO.email .then (data) -> coordinates = data[config.MY_GENE_INFO.exons_field][refseq] chromosome: coordinates.chr begin: coordinates.txstart end: coordinates.txend .catch -> throw new Error "Could not retrieve annotation for transcript #{ refseq }" # The region to query is defined either directly, or as a transcript in # the form <entrezgene>/<refseq>. We can query mygene.info to convert the # transcript into a region. getRegion = if @params.transcript # TODO: Optionally only look at exons of a transcript. This can be # implemented by changing the API to accept a list of regions, or by # removing the intronic variants here manually. Preferably the former. getTranscriptRegion @params.transcript else # Synchronous promise, we already have the region. Promise.resolve chromosome: @params.chromosome begin: @params.begin end: @params.end # We need the region before we can get the variants. Both are needed # later. getRegionAndVariants = getRegion.then (region) => getVariants query: switch @params.query when 'sample' then "sample: #{ @params.sample }" when 'group' then "group: #{ @params.group }" when 'custom' then @params.custom else '*' region: region page_number: parseInt @params.page ? 0 .then (result) -> [region, result] # If querying on sample, get the sample data (name, etc). Likewise if we # are querying on group. getQueryParam = switch @params.query when 'sample' then (getSample @params.sample).then (sample) -> ['sample', sample] when 'group' then (getGroup @params.group).then (group) -> ['group', group] else Promise.resolve ['custom', @params.custom] Promise.all [getQueryParam, getRegionAndVariants] .then ([[param, value], [region, result]]) => data = query: @params.query region: region variants: result.items pagination: result.pagination data[param] = value # TODO: For a lookup by transcript, it might be nice to show some more # information on that such as gene name, transcript accession, and # perhaps even map the variant positions to the transcript. @show 'variants', data .catch (error) => # TODO: Use our own Error type and only show errors of that type # directly in the user interface. @error error.message module.exports = app
[ { "context": "torData = [{\n text: 'awesome'\n },{\n text: 'horrid'\n },{\n text: 'awesome'\n }]\n indicatorDef", "end": 2375, "score": 0.6777558326721191, "start": 2372, "tag": "NAME", "value": "hor" } ]
client/test/src/views/sub_indicator_map_view.coffee
unepwcmc/NRT
0
assert = chai.assert suite('Sub Indicator Map View') test('when initialised with a visualisation with no data, it fetches the data', (done)-> visualisation = Factory.visualisation( data: null ) indicator = visualisation.get('indicator') indicator.set('indicatorDefinition', xAxis: 'year' geometryField: 'geometry' ) getIndicatorDataSpy = sinon.spy(visualisation, 'getIndicatorData') visualisation.once('change:data', -> assert.ok getIndicatorDataSpy.calledOnce done() ) server = sinon.fakeServer.create() view = new Backbone.Views.SubIndicatorMapView(visualisation: visualisation) # Check we received a data request indicatorId = visualisation.get('indicator').get('_id') assert.equal( server.requests[0].url, "/api/indicators/#{indicatorId}/data" ) # Respond to get data request Helpers.SinonServer.respondWithJson.call(server, results: [{year: 'data', geometry: {}}]) server.restore() view.close() ) test('.subIndicatorDataToLeafletMarkers converts sub indicator geometries to leaflet markers', -> subIndicatorData = [ geometry: x: 5 y: 10 ] indicatorDefinition = fields: [] markers = Backbone.Views.SubIndicatorMapView::subIndicatorDataToLeafletMarkers( subIndicatorData, indicatorDefinition ) assert.lengthOf markers, 1, "Only expected one leaflet marker" marker = markers[0] latLng = marker.getLatLng() assert.strictEqual latLng.lat, 10, "Expected the marker to have the right x value" assert.strictEqual latLng.lng, 5, "Expected the marker to have the right y value" ) test('.subIndicatorDataToLeafletMarkers sets leaflet marker icon className based on the subIndicator status', -> subIndicatorData = [ text: 'Excellent' geometry: x: 5 y: 10 ] indicatorDefinition = fields: [] markers = Backbone.Views.SubIndicatorMapView::subIndicatorDataToLeafletMarkers( subIndicatorData, indicatorDefinition ) assert.lengthOf markers, 1, "Only expected one leaflet marker" marker = markers[0] icon = marker.options.icon assert.strictEqual icon.options.className, 'excellent', "Expected the marker to have the right classname set" ) test('.uniqueSubIndicatorHeadlineTexts returns a unique list of all the headline texts', -> subIndicatorData = [{ text: 'awesome' },{ text: 'horrid' },{ text: 'awesome' }] indicatorDefinition = fields: [] texts = Backbone.Views.SubIndicatorMapView::uniqueSubIndicatorHeadlineTexts( subIndicatorData ) assert.lengthOf texts, 2, 'Only expected one headline text' assert.strictEqual texts[0], 'awesome', 'Expected the first headline text to be "awesome"' assert.strictEqual texts[1], 'horrid', 'Expected the second headline text to be "horrid"' )
117546
assert = chai.assert suite('Sub Indicator Map View') test('when initialised with a visualisation with no data, it fetches the data', (done)-> visualisation = Factory.visualisation( data: null ) indicator = visualisation.get('indicator') indicator.set('indicatorDefinition', xAxis: 'year' geometryField: 'geometry' ) getIndicatorDataSpy = sinon.spy(visualisation, 'getIndicatorData') visualisation.once('change:data', -> assert.ok getIndicatorDataSpy.calledOnce done() ) server = sinon.fakeServer.create() view = new Backbone.Views.SubIndicatorMapView(visualisation: visualisation) # Check we received a data request indicatorId = visualisation.get('indicator').get('_id') assert.equal( server.requests[0].url, "/api/indicators/#{indicatorId}/data" ) # Respond to get data request Helpers.SinonServer.respondWithJson.call(server, results: [{year: 'data', geometry: {}}]) server.restore() view.close() ) test('.subIndicatorDataToLeafletMarkers converts sub indicator geometries to leaflet markers', -> subIndicatorData = [ geometry: x: 5 y: 10 ] indicatorDefinition = fields: [] markers = Backbone.Views.SubIndicatorMapView::subIndicatorDataToLeafletMarkers( subIndicatorData, indicatorDefinition ) assert.lengthOf markers, 1, "Only expected one leaflet marker" marker = markers[0] latLng = marker.getLatLng() assert.strictEqual latLng.lat, 10, "Expected the marker to have the right x value" assert.strictEqual latLng.lng, 5, "Expected the marker to have the right y value" ) test('.subIndicatorDataToLeafletMarkers sets leaflet marker icon className based on the subIndicator status', -> subIndicatorData = [ text: 'Excellent' geometry: x: 5 y: 10 ] indicatorDefinition = fields: [] markers = Backbone.Views.SubIndicatorMapView::subIndicatorDataToLeafletMarkers( subIndicatorData, indicatorDefinition ) assert.lengthOf markers, 1, "Only expected one leaflet marker" marker = markers[0] icon = marker.options.icon assert.strictEqual icon.options.className, 'excellent', "Expected the marker to have the right classname set" ) test('.uniqueSubIndicatorHeadlineTexts returns a unique list of all the headline texts', -> subIndicatorData = [{ text: 'awesome' },{ text: '<NAME>rid' },{ text: 'awesome' }] indicatorDefinition = fields: [] texts = Backbone.Views.SubIndicatorMapView::uniqueSubIndicatorHeadlineTexts( subIndicatorData ) assert.lengthOf texts, 2, 'Only expected one headline text' assert.strictEqual texts[0], 'awesome', 'Expected the first headline text to be "awesome"' assert.strictEqual texts[1], 'horrid', 'Expected the second headline text to be "horrid"' )
true
assert = chai.assert suite('Sub Indicator Map View') test('when initialised with a visualisation with no data, it fetches the data', (done)-> visualisation = Factory.visualisation( data: null ) indicator = visualisation.get('indicator') indicator.set('indicatorDefinition', xAxis: 'year' geometryField: 'geometry' ) getIndicatorDataSpy = sinon.spy(visualisation, 'getIndicatorData') visualisation.once('change:data', -> assert.ok getIndicatorDataSpy.calledOnce done() ) server = sinon.fakeServer.create() view = new Backbone.Views.SubIndicatorMapView(visualisation: visualisation) # Check we received a data request indicatorId = visualisation.get('indicator').get('_id') assert.equal( server.requests[0].url, "/api/indicators/#{indicatorId}/data" ) # Respond to get data request Helpers.SinonServer.respondWithJson.call(server, results: [{year: 'data', geometry: {}}]) server.restore() view.close() ) test('.subIndicatorDataToLeafletMarkers converts sub indicator geometries to leaflet markers', -> subIndicatorData = [ geometry: x: 5 y: 10 ] indicatorDefinition = fields: [] markers = Backbone.Views.SubIndicatorMapView::subIndicatorDataToLeafletMarkers( subIndicatorData, indicatorDefinition ) assert.lengthOf markers, 1, "Only expected one leaflet marker" marker = markers[0] latLng = marker.getLatLng() assert.strictEqual latLng.lat, 10, "Expected the marker to have the right x value" assert.strictEqual latLng.lng, 5, "Expected the marker to have the right y value" ) test('.subIndicatorDataToLeafletMarkers sets leaflet marker icon className based on the subIndicator status', -> subIndicatorData = [ text: 'Excellent' geometry: x: 5 y: 10 ] indicatorDefinition = fields: [] markers = Backbone.Views.SubIndicatorMapView::subIndicatorDataToLeafletMarkers( subIndicatorData, indicatorDefinition ) assert.lengthOf markers, 1, "Only expected one leaflet marker" marker = markers[0] icon = marker.options.icon assert.strictEqual icon.options.className, 'excellent', "Expected the marker to have the right classname set" ) test('.uniqueSubIndicatorHeadlineTexts returns a unique list of all the headline texts', -> subIndicatorData = [{ text: 'awesome' },{ text: 'PI:NAME:<NAME>END_PIrid' },{ text: 'awesome' }] indicatorDefinition = fields: [] texts = Backbone.Views.SubIndicatorMapView::uniqueSubIndicatorHeadlineTexts( subIndicatorData ) assert.lengthOf texts, 2, 'Only expected one headline text' assert.strictEqual texts[0], 'awesome', 'Expected the first headline text to be "awesome"' assert.strictEqual texts[1], 'horrid', 'Expected the second headline text to be "horrid"' )
[ { "context": "###\n * 处理配置文件相关的细节\n * @author jackie Lin <dashi_lin@163.com>\n###\npath = require 'path'\nFS ", "end": 40, "score": 0.9997960925102234, "start": 30, "tag": "NAME", "value": "jackie Lin" }, { "context": "###\n * 处理配置文件相关的细节\n * @author jackie Lin <dashi_lin@163.com>\n#...
config.coffee
JackieLin/gis
0
### * 处理配置文件相关的细节 * @author jackie Lin <dashi_lin@163.com> ### path = require 'path' FS = require 'q-io/fs' _ = require 'lodash' baseConfigPath = path.join __dirname, 'gis.json' # console.log baseConfigPath configPath = '' config = -> config.readConfig baseConfigPath .then (baseObj)-> baseObj = JSON.parse baseObj # console.log baseObj config.readConfig configPath .then (obj) -> # console.log obj obj = JSON.parse obj _.extend baseObj, obj config.readConfig = (path)-> FS.exists path .then (stat)-> return FS.read path if stat return '{}' if not stat config.setPath = (path) -> throw new Error 'config: path is null' if not path? configPath = path config config.getPath = -> configPath # For test # config.setPath '/Users/jackielin/work/atido/mmfclient/static/fbuild.json' # config().then (res) -> # console.log res module.exports = config
123414
### * 处理配置文件相关的细节 * @author <NAME> <<EMAIL>> ### path = require 'path' FS = require 'q-io/fs' _ = require 'lodash' baseConfigPath = path.join __dirname, 'gis.json' # console.log baseConfigPath configPath = '' config = -> config.readConfig baseConfigPath .then (baseObj)-> baseObj = JSON.parse baseObj # console.log baseObj config.readConfig configPath .then (obj) -> # console.log obj obj = JSON.parse obj _.extend baseObj, obj config.readConfig = (path)-> FS.exists path .then (stat)-> return FS.read path if stat return '{}' if not stat config.setPath = (path) -> throw new Error 'config: path is null' if not path? configPath = path config config.getPath = -> configPath # For test # config.setPath '/Users/jackielin/work/atido/mmfclient/static/fbuild.json' # config().then (res) -> # console.log res module.exports = config
true
### * 处理配置文件相关的细节 * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### path = require 'path' FS = require 'q-io/fs' _ = require 'lodash' baseConfigPath = path.join __dirname, 'gis.json' # console.log baseConfigPath configPath = '' config = -> config.readConfig baseConfigPath .then (baseObj)-> baseObj = JSON.parse baseObj # console.log baseObj config.readConfig configPath .then (obj) -> # console.log obj obj = JSON.parse obj _.extend baseObj, obj config.readConfig = (path)-> FS.exists path .then (stat)-> return FS.read path if stat return '{}' if not stat config.setPath = (path) -> throw new Error 'config: path is null' if not path? configPath = path config config.getPath = -> configPath # For test # config.setPath '/Users/jackielin/work/atido/mmfclient/static/fbuild.json' # config().then (res) -> # console.log res module.exports = config
[ { "context": "n the appstate object\nappstatemodule.authToken = \"0xoxox\"\nappstatemodule.loginState = 'notloggedin'\nappsta", "end": 479, "score": 0.994297981262207, "start": 473, "tag": "PASSWORD", "value": "0xoxox" } ]
source/appstatemodule/appstatemodule.coffee
JhonnyJason/program-editor-frontend-sources
0
appstatemodule = {name: "appstatemodule", uimodule: false} #log Switch log = (arg) -> if allModules.debugmodule.modulesToDebug["appstatemodule"]? then console.log "[appstatemodule]: " + arg return ##initialization function -> is automatically being called! ONLY RELY ON DOM AND VARIABLES!! NO PLUGINS NO OHTER INITIALIZATIONS!! appstatemodule.initialize = () -> log "appstatemodule.initialize" #region the appstate object appstatemodule.authToken = "0xoxox" appstatemodule.loginState = 'notloggedin' appstatemodule.currentProgram = null appstatemodule.currentRun = null appstatemodule.currentLangTag = "de" #endregion export default appstatemodule
39941
appstatemodule = {name: "appstatemodule", uimodule: false} #log Switch log = (arg) -> if allModules.debugmodule.modulesToDebug["appstatemodule"]? then console.log "[appstatemodule]: " + arg return ##initialization function -> is automatically being called! ONLY RELY ON DOM AND VARIABLES!! NO PLUGINS NO OHTER INITIALIZATIONS!! appstatemodule.initialize = () -> log "appstatemodule.initialize" #region the appstate object appstatemodule.authToken = "<PASSWORD>" appstatemodule.loginState = 'notloggedin' appstatemodule.currentProgram = null appstatemodule.currentRun = null appstatemodule.currentLangTag = "de" #endregion export default appstatemodule
true
appstatemodule = {name: "appstatemodule", uimodule: false} #log Switch log = (arg) -> if allModules.debugmodule.modulesToDebug["appstatemodule"]? then console.log "[appstatemodule]: " + arg return ##initialization function -> is automatically being called! ONLY RELY ON DOM AND VARIABLES!! NO PLUGINS NO OHTER INITIALIZATIONS!! appstatemodule.initialize = () -> log "appstatemodule.initialize" #region the appstate object appstatemodule.authToken = "PI:PASSWORD:<PASSWORD>END_PI" appstatemodule.loginState = 'notloggedin' appstatemodule.currentProgram = null appstatemodule.currentRun = null appstatemodule.currentLangTag = "de" #endregion export default appstatemodule
[ { "context": "lhint\" ]\n\n markdown:\n options:\n author: \"Katrina Owen\"\n title: \"Exercism Help\"\n description: ", "end": 265, "score": 0.9998729825019836, "start": 253, "tag": "NAME", "value": "Katrina Owen" }, { "context": "o\"\n url: \"<%= pkg.homepag...
config/application.coffee
alexclarkofficial/docs
1
lineman = require(process.env['LINEMAN_MAIN']) module.exports = lineman.config.extend "application", loadNpmTasks: lineman.config.application.loadNpmTasks.concat [ "grunt-html-validation", "grunt-htmlhint" ] markdown: options: author: "Katrina Owen" title: "Exercism Help" description: "End-user documentation for Exercism.io" url: "<%= pkg.homepage %>" email: "kytrinyx@exercism.io" layouts: post: null archive: null paths: posts: null archive: null rss: null pathRoots: posts: null lib: Category: require('../lib/category') sass: options: bundleExec: true enableSass: true htmlhint: files: src: "generated/*.html" options: 'tagname-lowercase': true, 'attr-lowercase': true, 'attr-value-double-quotes': true, 'attr-value-not-empty': true, 'doctype-first': true, 'tag-pair': true, 'tag-self-close': true, 'spec-char-escape': true, 'id-unique': true, 'src-not-empty': true, 'head-script-disabled': true, 'img-alt-require': true, 'doctype-html5': true, 'id-class-value': true, 'style-disabled': true validation: files: src: "generated/*.html" options: relaxerror: [ "Bad value X-UA-Compatible for attribute http-equiv on element meta." "Bad value source for attribute rel on element a: The string source is not a registered keyword or absolute URL." ]
87350
lineman = require(process.env['LINEMAN_MAIN']) module.exports = lineman.config.extend "application", loadNpmTasks: lineman.config.application.loadNpmTasks.concat [ "grunt-html-validation", "grunt-htmlhint" ] markdown: options: author: "<NAME>" title: "Exercism Help" description: "End-user documentation for Exercism.io" url: "<%= pkg.homepage %>" email: "<EMAIL>" layouts: post: null archive: null paths: posts: null archive: null rss: null pathRoots: posts: null lib: Category: require('../lib/category') sass: options: bundleExec: true enableSass: true htmlhint: files: src: "generated/*.html" options: 'tagname-lowercase': true, 'attr-lowercase': true, 'attr-value-double-quotes': true, 'attr-value-not-empty': true, 'doctype-first': true, 'tag-pair': true, 'tag-self-close': true, 'spec-char-escape': true, 'id-unique': true, 'src-not-empty': true, 'head-script-disabled': true, 'img-alt-require': true, 'doctype-html5': true, 'id-class-value': true, 'style-disabled': true validation: files: src: "generated/*.html" options: relaxerror: [ "Bad value X-UA-Compatible for attribute http-equiv on element meta." "Bad value source for attribute rel on element a: The string source is not a registered keyword or absolute URL." ]
true
lineman = require(process.env['LINEMAN_MAIN']) module.exports = lineman.config.extend "application", loadNpmTasks: lineman.config.application.loadNpmTasks.concat [ "grunt-html-validation", "grunt-htmlhint" ] markdown: options: author: "PI:NAME:<NAME>END_PI" title: "Exercism Help" description: "End-user documentation for Exercism.io" url: "<%= pkg.homepage %>" email: "PI:EMAIL:<EMAIL>END_PI" layouts: post: null archive: null paths: posts: null archive: null rss: null pathRoots: posts: null lib: Category: require('../lib/category') sass: options: bundleExec: true enableSass: true htmlhint: files: src: "generated/*.html" options: 'tagname-lowercase': true, 'attr-lowercase': true, 'attr-value-double-quotes': true, 'attr-value-not-empty': true, 'doctype-first': true, 'tag-pair': true, 'tag-self-close': true, 'spec-char-escape': true, 'id-unique': true, 'src-not-empty': true, 'head-script-disabled': true, 'img-alt-require': true, 'doctype-html5': true, 'id-class-value': true, 'style-disabled': true validation: files: src: "generated/*.html" options: relaxerror: [ "Bad value X-UA-Compatible for attribute http-equiv on element meta." "Bad value source for attribute rel on element a: The string source is not a registered keyword or absolute URL." ]
[ { "context": "#{n}]#{nameNew}\"\n\n @current = n\n @name = nameNew\n @tsSwitch = $.now()\n\n if nameOld ==", "end": 679, "score": 0.8379971385002136, "start": 675, "tag": "NAME", "value": "name" }, { "context": "w\n @tsSwitch = $.now()\n\n if nameOld == ...
source/party.coffee
Viole403/genshin-impact-script
0
### interface type Fn = () => unknown type Position = 1 | 2 | 3 | 4 type Range = [[number, number], [number, number]] ### # function class PartyX extends EmitterShellX current: 0 isBusy: false listMember: [''] name: '' tsSwitch: 0 # --- constructor: -> super() @on 'change', => console.log "party: #{$.join ($.tail @listMember), ', '}" @on 'switch', (n) => name = @listMember[n] nameNew = name nameOld = @listMember[@current] unless nameNew then nameNew = 'unknown' unless nameOld then nameOld = 'unknown' console.log "party: [#{@current}]#{nameOld} -> [#{n}]#{nameNew}" @current = n @name = nameNew @tsSwitch = $.now() if nameOld == 'tartaglia' and nameNew != 'tartaglia' SkillTimer.endTartaglia() {audio} = Character.data[@name] if audio then Client.delay 200, -> Sound.play audio $.on 'f12', @scan # checkCurrent(n: Position): boolean checkCurrent: (n) -> [start, end] = @makeRange n, 'narrow' [x, y] = $.findColor 0x323232, start, end return !(x * y > 0) # checkCurrentAs(n: Position, callback: Fn): void checkCurrentAs: (n, callback) -> Client.delay 'party/check' delay = 200 if Config.data.weakNetwork Client.delay 'party/check', delay, callback return name = @listMember[n] unless name Client.delay 'party/check', delay, callback return Client.delay 'party/check', delay, => unless @checkCurrent n Sound.beep() return if callback then callback() # getIndexBy(name: string): Position getIndexBy: (name) -> unless @has name then return 0 for n in [1, 2, 3, 4] if @listMember[n] == name return n # getNameViaPosition(n: Position): string getNameViaPosition: (n) -> [start, end] = @makeRange n for name, char of Character.data if @has name then continue unless char.color then continue for color in char.color [x, y] = $.findColor color, start, end unless x * y > 0 then continue return name return '' # has(name: string): boolean has: (name) -> return $.includes @listMember, name # makeRange(n: Position, isNarrow: boolean = false): Range makeRange: (n, isNarrow = false) -> if isNarrow start = Client.point [96, 20 + 9 * (n - 1)] end = Client.point [99, 20 + 9 * n] return [start, end] start = Client.point [90, 20 + 9 * (n - 1)] end = Client.point [96, 20 + 9 * n] return [start, end] # scan(): void scan: -> if Scene.name != 'normal' or Scene.isMulti Sound.beep() return if @isBusy Sound.beep() return @isBusy = true @current = 0 @listMember = [''] @name = '' SkillTimer.reset() Hud.reset() for n in [1, 2, 3, 4] name = @getNameViaPosition n $.push @listMember, name char = Character.data[name] nameOutput = char.nameEN if Config.data.region == 'cn' nameOutput = char.nameCN if !@current and @checkCurrent n @current = n @name = name nameOutput = "#{nameOutput} 💬" Hud.render n, nameOutput @emit 'change' unless @current $.press 1 @switchTo 1 Client.delay 200, => @isBusy = false # switchTo(n: Position): void switchTo: (n) -> unless n then return @checkCurrentAs n, => @emit 'switch', n, @current # switchBy(name: string): void switchBy: (name) -> @switchTo @getIndexBy name # execute Party = new PartyX()
57704
### interface type Fn = () => unknown type Position = 1 | 2 | 3 | 4 type Range = [[number, number], [number, number]] ### # function class PartyX extends EmitterShellX current: 0 isBusy: false listMember: [''] name: '' tsSwitch: 0 # --- constructor: -> super() @on 'change', => console.log "party: #{$.join ($.tail @listMember), ', '}" @on 'switch', (n) => name = @listMember[n] nameNew = name nameOld = @listMember[@current] unless nameNew then nameNew = 'unknown' unless nameOld then nameOld = 'unknown' console.log "party: [#{@current}]#{nameOld} -> [#{n}]#{nameNew}" @current = n @name = <NAME>New @tsSwitch = $.now() if nameOld == 'tartaglia' and nameNew != 'tartaglia' SkillTimer.endTartaglia() {audio} = Character.data[@name] if audio then Client.delay 200, -> Sound.play audio $.on 'f12', @scan # checkCurrent(n: Position): boolean checkCurrent: (n) -> [start, end] = @makeRange n, 'narrow' [x, y] = $.findColor 0x323232, start, end return !(x * y > 0) # checkCurrentAs(n: Position, callback: Fn): void checkCurrentAs: (n, callback) -> Client.delay 'party/check' delay = 200 if Config.data.weakNetwork Client.delay 'party/check', delay, callback return name = @listMember[n] unless name Client.delay 'party/check', delay, callback return Client.delay 'party/check', delay, => unless @checkCurrent n Sound.beep() return if callback then callback() # getIndexBy(name: string): Position getIndexBy: (name) -> unless @has name then return 0 for n in [1, 2, 3, 4] if @listMember[n] == name return n # getNameViaPosition(n: Position): string getNameViaPosition: (n) -> [start, end] = @makeRange n for name, char of Character.data if @has name then continue unless char.color then continue for color in char.color [x, y] = $.findColor color, start, end unless x * y > 0 then continue return name return '' # has(name: string): boolean has: (name) -> return $.includes @listMember, name # makeRange(n: Position, isNarrow: boolean = false): Range makeRange: (n, isNarrow = false) -> if isNarrow start = Client.point [96, 20 + 9 * (n - 1)] end = Client.point [99, 20 + 9 * n] return [start, end] start = Client.point [90, 20 + 9 * (n - 1)] end = Client.point [96, 20 + 9 * n] return [start, end] # scan(): void scan: -> if Scene.name != 'normal' or Scene.isMulti Sound.beep() return if @isBusy Sound.beep() return @isBusy = true @current = 0 @listMember = [''] @name = '' SkillTimer.reset() Hud.reset() for n in [1, 2, 3, 4] name = @getNameViaPosition n $.push @listMember, name char = Character.data[name] nameOutput = char.nameEN if Config.data.region == 'cn' nameOutput = char.nameCN if !@current and @checkCurrent n @current = n @name = name nameOutput = "#{nameOutput} 💬" Hud.render n, nameOutput @emit 'change' unless @current $.press 1 @switchTo 1 Client.delay 200, => @isBusy = false # switchTo(n: Position): void switchTo: (n) -> unless n then return @checkCurrentAs n, => @emit 'switch', n, @current # switchBy(name: string): void switchBy: (name) -> @switchTo @getIndexBy name # execute Party = new PartyX()
true
### interface type Fn = () => unknown type Position = 1 | 2 | 3 | 4 type Range = [[number, number], [number, number]] ### # function class PartyX extends EmitterShellX current: 0 isBusy: false listMember: [''] name: '' tsSwitch: 0 # --- constructor: -> super() @on 'change', => console.log "party: #{$.join ($.tail @listMember), ', '}" @on 'switch', (n) => name = @listMember[n] nameNew = name nameOld = @listMember[@current] unless nameNew then nameNew = 'unknown' unless nameOld then nameOld = 'unknown' console.log "party: [#{@current}]#{nameOld} -> [#{n}]#{nameNew}" @current = n @name = PI:NAME:<NAME>END_PINew @tsSwitch = $.now() if nameOld == 'tartaglia' and nameNew != 'tartaglia' SkillTimer.endTartaglia() {audio} = Character.data[@name] if audio then Client.delay 200, -> Sound.play audio $.on 'f12', @scan # checkCurrent(n: Position): boolean checkCurrent: (n) -> [start, end] = @makeRange n, 'narrow' [x, y] = $.findColor 0x323232, start, end return !(x * y > 0) # checkCurrentAs(n: Position, callback: Fn): void checkCurrentAs: (n, callback) -> Client.delay 'party/check' delay = 200 if Config.data.weakNetwork Client.delay 'party/check', delay, callback return name = @listMember[n] unless name Client.delay 'party/check', delay, callback return Client.delay 'party/check', delay, => unless @checkCurrent n Sound.beep() return if callback then callback() # getIndexBy(name: string): Position getIndexBy: (name) -> unless @has name then return 0 for n in [1, 2, 3, 4] if @listMember[n] == name return n # getNameViaPosition(n: Position): string getNameViaPosition: (n) -> [start, end] = @makeRange n for name, char of Character.data if @has name then continue unless char.color then continue for color in char.color [x, y] = $.findColor color, start, end unless x * y > 0 then continue return name return '' # has(name: string): boolean has: (name) -> return $.includes @listMember, name # makeRange(n: Position, isNarrow: boolean = false): Range makeRange: (n, isNarrow = false) -> if isNarrow start = Client.point [96, 20 + 9 * (n - 1)] end = Client.point [99, 20 + 9 * n] return [start, end] start = Client.point [90, 20 + 9 * (n - 1)] end = Client.point [96, 20 + 9 * n] return [start, end] # scan(): void scan: -> if Scene.name != 'normal' or Scene.isMulti Sound.beep() return if @isBusy Sound.beep() return @isBusy = true @current = 0 @listMember = [''] @name = '' SkillTimer.reset() Hud.reset() for n in [1, 2, 3, 4] name = @getNameViaPosition n $.push @listMember, name char = Character.data[name] nameOutput = char.nameEN if Config.data.region == 'cn' nameOutput = char.nameCN if !@current and @checkCurrent n @current = n @name = name nameOutput = "#{nameOutput} 💬" Hud.render n, nameOutput @emit 'change' unless @current $.press 1 @switchTo 1 Client.delay 200, => @isBusy = false # switchTo(n: Position): void switchTo: (n) -> unless n then return @checkCurrentAs n, => @emit 'switch', n, @current # switchBy(name: string): void switchBy: (name) -> @switchTo @getIndexBy name # execute Party = new PartyX()
[ { "context": "eturn('aws-sdk-js/0.1')\n creds = accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'sessi", "end": 1164, "score": 0.9903066754341125, "start": 1160, "tag": "KEY", "value": "akid" }, { "context": " creds = accessKeyId: 'akid', secretAccessKey: 'secret',...
test/signers/v4.spec.coffee
ashharrison90/ibm-cos-sdk-js
0
helpers = require('../helpers') AWS = helpers.AWS buildRequest = -> s3 = new AWS.S3({region: 'region', endpoint: 'localhost'}) req = s3.makeRequest('listTables', {ExclusiveStartTableName: 'bår'}) req.build() req.httpRequest.headers['X-Amz-User-Agent'] = 'aws-sdk-js/0.1' req.httpRequest buildSigner = (request, signatureCache) -> if typeof signatureCache != 'boolean' signatureCache = true return new AWS.Signers.V4(request || buildRequest(), 'dynamodb', signatureCache) buildSignerFromService = (signatureCache) -> if typeof signatureCache != 'boolean' signatureCache = true ddb = new AWS.DynamoDB({region: 'region', endpoint: 'localhost', apiVersion: '2011-12-05'}) signer = buildSigner(null, signatureCache) signer.setServiceClientId(ddb._clientId) return signer describe 'AWS.Signers.V4', -> date = new Date(1935346573456) datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, '') creds = null signature = '3587c9e946339f802660e828c37f4352750ebb19651220e165f8e09abe89e95d' signer = null beforeEach -> helpers.spyOn(AWS.util, 'userAgent').andReturn('aws-sdk-js/0.1') creds = accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session' signer = buildSigner() signer.addAuthorization(creds, date) describe 'signature', -> it 'should generate proper signature', -> expect(signer.signature(creds, datetime)).to.equal(signature) xit 'should not compute SHA 256 checksum more than once', -> # TODO(bkeller) Why is this failing? spy = helpers.spyOn(AWS.util.crypto, 'sha256').andCallThrough() signer.signature(creds, datetime) expect(spy.calls.length).to.eql(1) describe 'stringToSign', -> it 'should sign correctly generated input string', -> expect(signer.stringToSign(datetime)).to.equal 'AWS4-HMAC-SHA256\n' + datetime + '\n' + '20310430/region/dynamodb/aws4_request\n' + signer.hexEncodedHash(signer.canonicalString()) describe 'canonicalString', -> it 'does not double encode path for S3', -> req = new AWS.S3().getObject(Bucket: 'bucket', Key: 'a:b:c').build() signer = new AWS.Signers.V4(req.httpRequest, 's3') expect(signer.canonicalString().split('\n')[1]).to.equal('/a%3Ab%3Ac') describe 'canonicalHeaders', -> it 'should return headers', -> # Modified to use S3 headers instead of DynamoDB headers expect(signer.canonicalHeaders()).to.eql [ 'x-amz-date:' + datetime, 'x-amz-security-token:session', 'x-amz-user-agent:aws-sdk-js/0.1' ].join('\n') it 'should ignore Authorization header', -> signer.request.headers = {'Authorization': 'foo'} expect(signer.canonicalHeaders()).to.equal('') it 'should ignore X-Amzn-Trace-Id header', -> signer.request.headers = {'X-Amzn-Trace-Id': 'foo'} expect(signer.canonicalHeaders()).to.equal('') it 'should lowercase all header names (not values)', -> signer.request.headers = {'FOO': 'BAR'} expect(signer.canonicalHeaders()).to.equal('foo:BAR') it 'should sort headers by key', -> signer.request.headers = {abc: 'a', bca: 'b', Qux: 'c', bar: 'd'} expect(signer.canonicalHeaders()).to.equal('abc:a\nbar:d\nbca:b\nqux:c') it 'should compact multiple spaces in keys/values to a single space', -> signer.request.headers = {'Header': 'Value with Multiple \t spaces'} expect(signer.canonicalHeaders()).to.equal('header:Value with Multiple spaces') it 'should strip starting and end of line spaces', -> signer.request.headers = {'Header': ' \t Value \t '} expect(signer.canonicalHeaders()).to.equal('header:Value') describe 'presigned urls', -> it 'hoists content-type to the query string', -> req = new AWS.S3().putObject(Bucket: 'bucket', Key: 'key', ContentType: 'text/plain').build() signer = new AWS.Signers.V4(req.httpRequest, 's3') signer.updateForPresigned({}, '') expect(signer.canonicalString().split('\n')[2]).to.contain('Content-Type=text%2Fplain') it 'hoists content-md5 to the query string', -> req = new AWS.S3().putObject(Bucket: 'bucket', Key: 'key', ContentMD5: 'foobar==').build() signer = new AWS.Signers.V4(req.httpRequest, 's3') signer.updateForPresigned({}, '') expect(signer.canonicalString().split('\n')[2]).to.contain('Content-MD5=foobar%3D%3D')
222582
helpers = require('../helpers') AWS = helpers.AWS buildRequest = -> s3 = new AWS.S3({region: 'region', endpoint: 'localhost'}) req = s3.makeRequest('listTables', {ExclusiveStartTableName: 'bår'}) req.build() req.httpRequest.headers['X-Amz-User-Agent'] = 'aws-sdk-js/0.1' req.httpRequest buildSigner = (request, signatureCache) -> if typeof signatureCache != 'boolean' signatureCache = true return new AWS.Signers.V4(request || buildRequest(), 'dynamodb', signatureCache) buildSignerFromService = (signatureCache) -> if typeof signatureCache != 'boolean' signatureCache = true ddb = new AWS.DynamoDB({region: 'region', endpoint: 'localhost', apiVersion: '2011-12-05'}) signer = buildSigner(null, signatureCache) signer.setServiceClientId(ddb._clientId) return signer describe 'AWS.Signers.V4', -> date = new Date(1935346573456) datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, '') creds = null signature = '3587c9e946339f802660e828c37f4352750ebb19651220e165f8e09abe89e95d' signer = null beforeEach -> helpers.spyOn(AWS.util, 'userAgent').andReturn('aws-sdk-js/0.1') creds = accessKeyId: '<KEY>', secretAccessKey: '<KEY>', sessionToken: '<KEY>' signer = buildSigner() signer.addAuthorization(creds, date) describe 'signature', -> it 'should generate proper signature', -> expect(signer.signature(creds, datetime)).to.equal(signature) xit 'should not compute SHA 256 checksum more than once', -> # TODO(bkeller) Why is this failing? spy = helpers.spyOn(AWS.util.crypto, 'sha256').andCallThrough() signer.signature(creds, datetime) expect(spy.calls.length).to.eql(1) describe 'stringToSign', -> it 'should sign correctly generated input string', -> expect(signer.stringToSign(datetime)).to.equal 'AWS4-HMAC-SHA256\n' + datetime + '\n' + '20310430/region/dynamodb/aws4_request\n' + signer.hexEncodedHash(signer.canonicalString()) describe 'canonicalString', -> it 'does not double encode path for S3', -> req = new AWS.S3().getObject(Bucket: 'bucket', Key: '<KEY>').build() signer = new AWS.Signers.V4(req.httpRequest, 's3') expect(signer.canonicalString().split('\n')[1]).to.equal('/a%3Ab%3Ac') describe 'canonicalHeaders', -> it 'should return headers', -> # Modified to use S3 headers instead of DynamoDB headers expect(signer.canonicalHeaders()).to.eql [ 'x-amz-date:' + datetime, 'x-amz-security-token:session', 'x-amz-user-agent:aws-sdk-js/0.1' ].join('\n') it 'should ignore Authorization header', -> signer.request.headers = {'Authorization': 'foo'} expect(signer.canonicalHeaders()).to.equal('') it 'should ignore X-Amzn-Trace-Id header', -> signer.request.headers = {'X-Amzn-Trace-Id': 'foo'} expect(signer.canonicalHeaders()).to.equal('') it 'should lowercase all header names (not values)', -> signer.request.headers = {'FOO': 'BAR'} expect(signer.canonicalHeaders()).to.equal('foo:BAR') it 'should sort headers by key', -> signer.request.headers = {abc: 'a', bca: 'b', Qux: 'c', bar: 'd'} expect(signer.canonicalHeaders()).to.equal('abc:a\nbar:d\nbca:b\nqux:c') it 'should compact multiple spaces in keys/values to a single space', -> signer.request.headers = {'Header': 'Value with Multiple \t spaces'} expect(signer.canonicalHeaders()).to.equal('header:Value with Multiple spaces') it 'should strip starting and end of line spaces', -> signer.request.headers = {'Header': ' \t Value \t '} expect(signer.canonicalHeaders()).to.equal('header:Value') describe 'presigned urls', -> it 'hoists content-type to the query string', -> req = new AWS.S3().putObject(Bucket: 'bucket', Key: 'key', ContentType: 'text/plain').build() signer = new AWS.Signers.V4(req.httpRequest, 's3') signer.updateForPresigned({}, '') expect(signer.canonicalString().split('\n')[2]).to.contain('Content-Type=text%2Fplain') it 'hoists content-md5 to the query string', -> req = new AWS.S3().putObject(Bucket: 'bucket', Key: 'key', ContentMD5: 'foobar==').build() signer = new AWS.Signers.V4(req.httpRequest, 's3') signer.updateForPresigned({}, '') expect(signer.canonicalString().split('\n')[2]).to.contain('Content-MD5=foobar%3D%3D')
true
helpers = require('../helpers') AWS = helpers.AWS buildRequest = -> s3 = new AWS.S3({region: 'region', endpoint: 'localhost'}) req = s3.makeRequest('listTables', {ExclusiveStartTableName: 'bår'}) req.build() req.httpRequest.headers['X-Amz-User-Agent'] = 'aws-sdk-js/0.1' req.httpRequest buildSigner = (request, signatureCache) -> if typeof signatureCache != 'boolean' signatureCache = true return new AWS.Signers.V4(request || buildRequest(), 'dynamodb', signatureCache) buildSignerFromService = (signatureCache) -> if typeof signatureCache != 'boolean' signatureCache = true ddb = new AWS.DynamoDB({region: 'region', endpoint: 'localhost', apiVersion: '2011-12-05'}) signer = buildSigner(null, signatureCache) signer.setServiceClientId(ddb._clientId) return signer describe 'AWS.Signers.V4', -> date = new Date(1935346573456) datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, '') creds = null signature = '3587c9e946339f802660e828c37f4352750ebb19651220e165f8e09abe89e95d' signer = null beforeEach -> helpers.spyOn(AWS.util, 'userAgent').andReturn('aws-sdk-js/0.1') creds = accessKeyId: 'PI:KEY:<KEY>END_PI', secretAccessKey: 'PI:KEY:<KEY>END_PI', sessionToken: 'PI:KEY:<KEY>END_PI' signer = buildSigner() signer.addAuthorization(creds, date) describe 'signature', -> it 'should generate proper signature', -> expect(signer.signature(creds, datetime)).to.equal(signature) xit 'should not compute SHA 256 checksum more than once', -> # TODO(bkeller) Why is this failing? spy = helpers.spyOn(AWS.util.crypto, 'sha256').andCallThrough() signer.signature(creds, datetime) expect(spy.calls.length).to.eql(1) describe 'stringToSign', -> it 'should sign correctly generated input string', -> expect(signer.stringToSign(datetime)).to.equal 'AWS4-HMAC-SHA256\n' + datetime + '\n' + '20310430/region/dynamodb/aws4_request\n' + signer.hexEncodedHash(signer.canonicalString()) describe 'canonicalString', -> it 'does not double encode path for S3', -> req = new AWS.S3().getObject(Bucket: 'bucket', Key: 'PI:KEY:<KEY>END_PI').build() signer = new AWS.Signers.V4(req.httpRequest, 's3') expect(signer.canonicalString().split('\n')[1]).to.equal('/a%3Ab%3Ac') describe 'canonicalHeaders', -> it 'should return headers', -> # Modified to use S3 headers instead of DynamoDB headers expect(signer.canonicalHeaders()).to.eql [ 'x-amz-date:' + datetime, 'x-amz-security-token:session', 'x-amz-user-agent:aws-sdk-js/0.1' ].join('\n') it 'should ignore Authorization header', -> signer.request.headers = {'Authorization': 'foo'} expect(signer.canonicalHeaders()).to.equal('') it 'should ignore X-Amzn-Trace-Id header', -> signer.request.headers = {'X-Amzn-Trace-Id': 'foo'} expect(signer.canonicalHeaders()).to.equal('') it 'should lowercase all header names (not values)', -> signer.request.headers = {'FOO': 'BAR'} expect(signer.canonicalHeaders()).to.equal('foo:BAR') it 'should sort headers by key', -> signer.request.headers = {abc: 'a', bca: 'b', Qux: 'c', bar: 'd'} expect(signer.canonicalHeaders()).to.equal('abc:a\nbar:d\nbca:b\nqux:c') it 'should compact multiple spaces in keys/values to a single space', -> signer.request.headers = {'Header': 'Value with Multiple \t spaces'} expect(signer.canonicalHeaders()).to.equal('header:Value with Multiple spaces') it 'should strip starting and end of line spaces', -> signer.request.headers = {'Header': ' \t Value \t '} expect(signer.canonicalHeaders()).to.equal('header:Value') describe 'presigned urls', -> it 'hoists content-type to the query string', -> req = new AWS.S3().putObject(Bucket: 'bucket', Key: 'key', ContentType: 'text/plain').build() signer = new AWS.Signers.V4(req.httpRequest, 's3') signer.updateForPresigned({}, '') expect(signer.canonicalString().split('\n')[2]).to.contain('Content-Type=text%2Fplain') it 'hoists content-md5 to the query string', -> req = new AWS.S3().putObject(Bucket: 'bucket', Key: 'key', ContentMD5: 'foobar==').build() signer = new AWS.Signers.V4(req.httpRequest, 's3') signer.updateForPresigned({}, '') expect(signer.canonicalString().split('\n')[2]).to.contain('Content-MD5=foobar%3D%3D')
[ { "context": "object', ->\n utils.objToStr(name: 'kieve', age: 18).should.equal \"{ name : 'kieve', ag", "end": 411, "score": 0.676666259765625, "start": 410, "tag": "NAME", "value": "k" }, { "context": "bject', ->\n utils.objToStr(name: 'kieve', age: 18...
test/test.utils.coffee
kievechua/js-neo4j
2
Q = require 'q' chai = require 'chai' chaiAsPromised = require 'chai-as-promised' chai.should() chai.use(chaiAsPromised) require("mocha-as-promised")() {Neo4js} = require '../src/main' describe 'Utils', -> utils = new Neo4js().utils describe 'neo.objToStr({object})', -> describe 'when valid', -> it 'should return stringified object', -> utils.objToStr(name: 'kieve', age: 18).should.equal "{ name : 'kieve', age : '18' }" describe 'neo.get(url)', -> describe 'when valid', -> it 'should return stringified object', -> utils .get('http://localhost:7474/db/data') .then((result) -> result.ok.should.be.true )
24925
Q = require 'q' chai = require 'chai' chaiAsPromised = require 'chai-as-promised' chai.should() chai.use(chaiAsPromised) require("mocha-as-promised")() {Neo4js} = require '../src/main' describe 'Utils', -> utils = new Neo4js().utils describe 'neo.objToStr({object})', -> describe 'when valid', -> it 'should return stringified object', -> utils.objToStr(name: '<NAME>ieve', age: 18).should.equal "{ name : '<NAME>', age : '18' }" describe 'neo.get(url)', -> describe 'when valid', -> it 'should return stringified object', -> utils .get('http://localhost:7474/db/data') .then((result) -> result.ok.should.be.true )
true
Q = require 'q' chai = require 'chai' chaiAsPromised = require 'chai-as-promised' chai.should() chai.use(chaiAsPromised) require("mocha-as-promised")() {Neo4js} = require '../src/main' describe 'Utils', -> utils = new Neo4js().utils describe 'neo.objToStr({object})', -> describe 'when valid', -> it 'should return stringified object', -> utils.objToStr(name: 'PI:NAME:<NAME>END_PIieve', age: 18).should.equal "{ name : 'PI:NAME:<NAME>END_PI', age : '18' }" describe 'neo.get(url)', -> describe 'when valid', -> it 'should return stringified object', -> utils .get('http://localhost:7474/db/data') .then((result) -> result.ok.should.be.true )
[ { "context": "errides) ->\n\treturn _.merge\n\t\tid: 123639\n\t\tname: 'aged-smoke'\n\t\tdevice_type: 'beaglebone-black'\n\t\tuuid: 'fdaa8", "end": 372, "score": 0.7372291684150696, "start": 362, "tag": "USERNAME", "value": "aged-smoke" }, { "context": "\n\t\tdownload_progress: null\...
tests/status.spec.coffee
resin-io-modules/resin-device-status
2
m = require('mochainon') _ = require('lodash') status = require('../build') getInstallMock = (overrides) -> return _.merge id: 33700709 download_progress: null status: 'Running' image_id: 408246 service_id: 21650 commit: 'de808ee99fe2d031b685bea65fc4387ad07c9e5c' , overrides getDeviceMock = (overrides) -> return _.merge id: 123639 name: 'aged-smoke' device_type: 'beaglebone-black' uuid: 'fdaa8ac34273568975e3d7031da1ae8f21b857a667dd7fcfbfca551808397d' status: null is_active: true is_online: true last_connectivity_event: '2014-01-01T00:00:00.000Z' public_address: '' supervisor_version: null supervisor_release: null provisioning_progress: null provisioning_state: null download_progress: null application_name: 'BeagleTest' current_services: main: [getInstallMock()] , overrides describe 'Status', -> describe '.status', -> it 'should be a plain object', -> m.chai.expect(_.isPlainObject(status.status)).to.be.true it 'should not be empty', -> m.chai.expect(_.isEmpty(status.status)).to.be.false describe '.statuses', -> it 'should be an array', -> m.chai.expect(status.statuses).to.be.an.instanceof(Array) it 'should not be empty', -> m.chai.expect(_.isEmpty(status.statuses)).to.be.false it 'should contain valid key and name properties', -> for deviceStatus in status.statuses m.chai.expect(deviceStatus.key).to.be.a('string') m.chai.expect(_.isEmpty(deviceStatus.key)).to.be.false m.chai.expect(deviceStatus.name).to.be.a('string') m.chai.expect(_.isEmpty(deviceStatus.name)).to.be.false describe '.getStatus()', -> [ { active: false, online: false } { active: false, online: true } { active: true, online: false } { active: true, online: true } ].forEach ({ active, online }) -> it "should return ORDERED if the status is Ordered and is_active is #{active} and is_online is #{online}", -> device = getDeviceMock is_active: active is_online: online status: 'Ordered' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'ordered' name: 'Ordered' it "should return PREPARING if the status is Preparing and is_active is #{active} and is_online is #{online}", -> device = getDeviceMock is_active: active is_online: online status: 'Preparing' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'preparing' name: 'Preparing' [ { active: false } { active: true } ].forEach ({ active, online }) -> it "should return SHIPPED if the status is Shipped and is_active is #{active} and is_online is false", -> device = getDeviceMock is_active: true is_online: false status: 'Shipped' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'shipped' name: 'Shipped' it 'should not return SHIPPED if the status is Shipped and is_online is true', -> device = getDeviceMock is_active: true is_online: true status: 'Shipped' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'idle' name: 'Online' it 'should return INACTIVE if is_active is false and the device was not seen', -> device = getDeviceMock is_active: false is_online: false last_connectivity_event: null m.chai.expect(status.getStatus(device)).to.deep.equal key: 'inactive' name: 'Inactive' it 'should return POST_PROVISIONING if provisioning_state is Post-Provisioning', -> device = getDeviceMock(provisioning_state: 'Post-Provisioning') m.chai.expect(status.getStatus(device)).to.deep.equal key: 'post-provisioning' name: 'Post Provisioning' it 'should return CONFIGURING if is_online is false and the device was not seen', -> device = getDeviceMock is_online: false last_connectivity_event: null m.chai.expect(status.getStatus(device)).to.deep.equal key: 'configuring' name: 'Configuring' it 'should return CONFIGURING if is_online is false and the device was seen before 2013', -> device = getDeviceMock is_online: false last_connectivity_event: '1970-01-01T00:00:00.000Z' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'configuring' name: 'Configuring' it 'should return OFFLINE if is_online is false and the device was seen after 2013', -> device = getDeviceMock is_online: false last_connectivity_event: '2014-01-01T00:00:00.000Z' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'offline' name: 'Offline' it 'should return OFFLINE if there is a download_progress and status is Downloading and is_online is false', -> device = getDeviceMock is_online: false download_progress: 45 status: 'Downloading' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'offline' name: 'Offline' it 'should return INACTIVE if is_active is false and the device was seen after 2013', -> device = getDeviceMock is_active: false is_online: false last_connectivity_event: '2014-01-01T00:00:00.000Z' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'inactive' name: 'Inactive' it 'should return UPDATING if there is a download_progress and status is Downloading and is_online is true', -> device = getDeviceMock is_online: true download_progress: 45 status: 'Downloading' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'updating' name: 'Updating' it 'should return UPDATING if the device is online with a service downloading', -> device = getDeviceMock is_online: true download_progress: null current_services: main: [ getInstallMock() getInstallMock id: 33700710 download_progress: 45 status: 'Downloading' image_id: 408247 commit: '04c4b943ae4d4447ab0f608d645c274f' ] m.chai.expect(status.getStatus(device)).to.deep.equal key: 'updating' name: 'Updating' it 'should return CONFIGURING if there is a provisioning_progress', -> device = getDeviceMock provisioning_progress: 50 m.chai.expect(status.getStatus(device)).to.deep.equal key: 'configuring' name: 'Configuring' it 'should return IDLE if is_online is true and the device was not seen', -> device = getDeviceMock is_online: true last_connectivity_event: null m.chai.expect(status.getStatus(device)).to.deep.equal key: 'idle' name: 'Online' it 'should return IDLE if is_online is true and the device was seen after 2013', -> device = getDeviceMock is_online: true last_connectivity_event: '2014-01-01T00:00:00.000Z' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'idle' name: 'Online' it 'should return IDLE if is_online is true and the device was seen after 2013 and there is no download_progress', -> device = getDeviceMock is_online: true last_connectivity_event: '2014-01-01T00:00:00.000Z' download_progress: null m.chai.expect(status.getStatus(device)).to.deep.equal key: 'idle' name: 'Online'
100074
m = require('mochainon') _ = require('lodash') status = require('../build') getInstallMock = (overrides) -> return _.merge id: 33700709 download_progress: null status: 'Running' image_id: 408246 service_id: 21650 commit: 'de808ee99fe2d031b685bea65fc4387ad07c9e5c' , overrides getDeviceMock = (overrides) -> return _.merge id: 123639 name: 'aged-smoke' device_type: 'beaglebone-black' uuid: 'fdaa8ac34273568975e3d7031da1ae8f21b857a667dd7fcfbfca551808397d' status: null is_active: true is_online: true last_connectivity_event: '2014-01-01T00:00:00.000Z' public_address: '' supervisor_version: null supervisor_release: null provisioning_progress: null provisioning_state: null download_progress: null application_name: 'BeagleTest' current_services: main: [getInstallMock()] , overrides describe 'Status', -> describe '.status', -> it 'should be a plain object', -> m.chai.expect(_.isPlainObject(status.status)).to.be.true it 'should not be empty', -> m.chai.expect(_.isEmpty(status.status)).to.be.false describe '.statuses', -> it 'should be an array', -> m.chai.expect(status.statuses).to.be.an.instanceof(Array) it 'should not be empty', -> m.chai.expect(_.isEmpty(status.statuses)).to.be.false it 'should contain valid key and name properties', -> for deviceStatus in status.statuses m.chai.expect(deviceStatus.key).to.be.a('string') m.chai.expect(_.isEmpty(deviceStatus.key)).to.be.false m.chai.expect(deviceStatus.name).to.be.a('string') m.chai.expect(_.isEmpty(deviceStatus.name)).to.be.false describe '.getStatus()', -> [ { active: false, online: false } { active: false, online: true } { active: true, online: false } { active: true, online: true } ].forEach ({ active, online }) -> it "should return ORDERED if the status is Ordered and is_active is #{active} and is_online is #{online}", -> device = getDeviceMock is_active: active is_online: online status: 'Ordered' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'ordered' name: 'Ordered' it "should return PREPARING if the status is Preparing and is_active is #{active} and is_online is #{online}", -> device = getDeviceMock is_active: active is_online: online status: 'Preparing' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'preparing' name: 'Preparing' [ { active: false } { active: true } ].forEach ({ active, online }) -> it "should return SHIPPED if the status is Shipped and is_active is #{active} and is_online is false", -> device = getDeviceMock is_active: true is_online: false status: 'Shipped' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'shipped' name: 'Shipped' it 'should not return SHIPPED if the status is Shipped and is_online is true', -> device = getDeviceMock is_active: true is_online: true status: 'Shipped' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'idle' name: 'Online' it 'should return INACTIVE if is_active is false and the device was not seen', -> device = getDeviceMock is_active: false is_online: false last_connectivity_event: null m.chai.expect(status.getStatus(device)).to.deep.equal key: 'inactive' name: 'Inactive' it 'should return POST_PROVISIONING if provisioning_state is Post-Provisioning', -> device = getDeviceMock(provisioning_state: 'Post-Provisioning') m.chai.expect(status.getStatus(device)).to.deep.equal key: 'post-provisioning' name: 'Post Provisioning' it 'should return CONFIGURING if is_online is false and the device was not seen', -> device = getDeviceMock is_online: false last_connectivity_event: null m.chai.expect(status.getStatus(device)).to.deep.equal key: 'configuring' name: 'Configuring' it 'should return CONFIGURING if is_online is false and the device was seen before 2013', -> device = getDeviceMock is_online: false last_connectivity_event: '1970-01-01T00:00:00.000Z' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'configuring' name: 'Configuring' it 'should return OFFLINE if is_online is false and the device was seen after 2013', -> device = getDeviceMock is_online: false last_connectivity_event: '2014-01-01T00:00:00.000Z' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'offline' name: 'Offline' it 'should return OFFLINE if there is a download_progress and status is Downloading and is_online is false', -> device = getDeviceMock is_online: false download_progress: 45 status: 'Downloading' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'offline' name: 'Offline' it 'should return INACTIVE if is_active is false and the device was seen after 2013', -> device = getDeviceMock is_active: false is_online: false last_connectivity_event: '2014-01-01T00:00:00.000Z' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'inactive' name: 'Inactive' it 'should return UPDATING if there is a download_progress and status is Downloading and is_online is true', -> device = getDeviceMock is_online: true download_progress: 45 status: 'Downloading' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'updating' name: 'Updating' it 'should return UPDATING if the device is online with a service downloading', -> device = getDeviceMock is_online: true download_progress: null current_services: main: [ getInstallMock() getInstallMock id: 33700710 download_progress: 45 status: 'Downloading' image_id: 408247 commit: '0<PASSWORD>' ] m.chai.expect(status.getStatus(device)).to.deep.equal key: 'updating' name: 'Updating' it 'should return CONFIGURING if there is a provisioning_progress', -> device = getDeviceMock provisioning_progress: 50 m.chai.expect(status.getStatus(device)).to.deep.equal key: 'configuring' name: 'Configuring' it 'should return IDLE if is_online is true and the device was not seen', -> device = getDeviceMock is_online: true last_connectivity_event: null m.chai.expect(status.getStatus(device)).to.deep.equal key: 'idle' name: 'Online' it 'should return IDLE if is_online is true and the device was seen after 2013', -> device = getDeviceMock is_online: true last_connectivity_event: '2014-01-01T00:00:00.000Z' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'idle' name: 'Online' it 'should return IDLE if is_online is true and the device was seen after 2013 and there is no download_progress', -> device = getDeviceMock is_online: true last_connectivity_event: '2014-01-01T00:00:00.000Z' download_progress: null m.chai.expect(status.getStatus(device)).to.deep.equal key: 'idle' name: 'Online'
true
m = require('mochainon') _ = require('lodash') status = require('../build') getInstallMock = (overrides) -> return _.merge id: 33700709 download_progress: null status: 'Running' image_id: 408246 service_id: 21650 commit: 'de808ee99fe2d031b685bea65fc4387ad07c9e5c' , overrides getDeviceMock = (overrides) -> return _.merge id: 123639 name: 'aged-smoke' device_type: 'beaglebone-black' uuid: 'fdaa8ac34273568975e3d7031da1ae8f21b857a667dd7fcfbfca551808397d' status: null is_active: true is_online: true last_connectivity_event: '2014-01-01T00:00:00.000Z' public_address: '' supervisor_version: null supervisor_release: null provisioning_progress: null provisioning_state: null download_progress: null application_name: 'BeagleTest' current_services: main: [getInstallMock()] , overrides describe 'Status', -> describe '.status', -> it 'should be a plain object', -> m.chai.expect(_.isPlainObject(status.status)).to.be.true it 'should not be empty', -> m.chai.expect(_.isEmpty(status.status)).to.be.false describe '.statuses', -> it 'should be an array', -> m.chai.expect(status.statuses).to.be.an.instanceof(Array) it 'should not be empty', -> m.chai.expect(_.isEmpty(status.statuses)).to.be.false it 'should contain valid key and name properties', -> for deviceStatus in status.statuses m.chai.expect(deviceStatus.key).to.be.a('string') m.chai.expect(_.isEmpty(deviceStatus.key)).to.be.false m.chai.expect(deviceStatus.name).to.be.a('string') m.chai.expect(_.isEmpty(deviceStatus.name)).to.be.false describe '.getStatus()', -> [ { active: false, online: false } { active: false, online: true } { active: true, online: false } { active: true, online: true } ].forEach ({ active, online }) -> it "should return ORDERED if the status is Ordered and is_active is #{active} and is_online is #{online}", -> device = getDeviceMock is_active: active is_online: online status: 'Ordered' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'ordered' name: 'Ordered' it "should return PREPARING if the status is Preparing and is_active is #{active} and is_online is #{online}", -> device = getDeviceMock is_active: active is_online: online status: 'Preparing' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'preparing' name: 'Preparing' [ { active: false } { active: true } ].forEach ({ active, online }) -> it "should return SHIPPED if the status is Shipped and is_active is #{active} and is_online is false", -> device = getDeviceMock is_active: true is_online: false status: 'Shipped' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'shipped' name: 'Shipped' it 'should not return SHIPPED if the status is Shipped and is_online is true', -> device = getDeviceMock is_active: true is_online: true status: 'Shipped' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'idle' name: 'Online' it 'should return INACTIVE if is_active is false and the device was not seen', -> device = getDeviceMock is_active: false is_online: false last_connectivity_event: null m.chai.expect(status.getStatus(device)).to.deep.equal key: 'inactive' name: 'Inactive' it 'should return POST_PROVISIONING if provisioning_state is Post-Provisioning', -> device = getDeviceMock(provisioning_state: 'Post-Provisioning') m.chai.expect(status.getStatus(device)).to.deep.equal key: 'post-provisioning' name: 'Post Provisioning' it 'should return CONFIGURING if is_online is false and the device was not seen', -> device = getDeviceMock is_online: false last_connectivity_event: null m.chai.expect(status.getStatus(device)).to.deep.equal key: 'configuring' name: 'Configuring' it 'should return CONFIGURING if is_online is false and the device was seen before 2013', -> device = getDeviceMock is_online: false last_connectivity_event: '1970-01-01T00:00:00.000Z' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'configuring' name: 'Configuring' it 'should return OFFLINE if is_online is false and the device was seen after 2013', -> device = getDeviceMock is_online: false last_connectivity_event: '2014-01-01T00:00:00.000Z' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'offline' name: 'Offline' it 'should return OFFLINE if there is a download_progress and status is Downloading and is_online is false', -> device = getDeviceMock is_online: false download_progress: 45 status: 'Downloading' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'offline' name: 'Offline' it 'should return INACTIVE if is_active is false and the device was seen after 2013', -> device = getDeviceMock is_active: false is_online: false last_connectivity_event: '2014-01-01T00:00:00.000Z' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'inactive' name: 'Inactive' it 'should return UPDATING if there is a download_progress and status is Downloading and is_online is true', -> device = getDeviceMock is_online: true download_progress: 45 status: 'Downloading' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'updating' name: 'Updating' it 'should return UPDATING if the device is online with a service downloading', -> device = getDeviceMock is_online: true download_progress: null current_services: main: [ getInstallMock() getInstallMock id: 33700710 download_progress: 45 status: 'Downloading' image_id: 408247 commit: '0PI:PASSWORD:<PASSWORD>END_PI' ] m.chai.expect(status.getStatus(device)).to.deep.equal key: 'updating' name: 'Updating' it 'should return CONFIGURING if there is a provisioning_progress', -> device = getDeviceMock provisioning_progress: 50 m.chai.expect(status.getStatus(device)).to.deep.equal key: 'configuring' name: 'Configuring' it 'should return IDLE if is_online is true and the device was not seen', -> device = getDeviceMock is_online: true last_connectivity_event: null m.chai.expect(status.getStatus(device)).to.deep.equal key: 'idle' name: 'Online' it 'should return IDLE if is_online is true and the device was seen after 2013', -> device = getDeviceMock is_online: true last_connectivity_event: '2014-01-01T00:00:00.000Z' m.chai.expect(status.getStatus(device)).to.deep.equal key: 'idle' name: 'Online' it 'should return IDLE if is_online is true and the device was seen after 2013 and there is no download_progress', -> device = getDeviceMock is_online: true last_connectivity_event: '2014-01-01T00:00:00.000Z' download_progress: null m.chai.expect(status.getStatus(device)).to.deep.equal key: 'idle' name: 'Online'
[ { "context": "e\n\n# TODO: session tests\n# See https://github.com/expressjs/session\n# See https://github.com/valery-barysok/s", "end": 635, "score": 0.9977059364318848, "start": 626, "tag": "USERNAME", "value": "expressjs" }, { "context": "ub.com/expressjs/session\n# See https://gi...
app.coffee
danielappelt/one-hour-challenge
2
# Folder layout # challenges/ # <name of challenge>/ # config.json describing challenge # downloads/ # <file1>, .., <fileN>: downloadable challenge artifacts # entries/ # votes/ express = require 'express' session = require 'express-session' FileStore = require('session-file-store') session fs = require 'fs' sep = require('path').sep formidable = require 'formidable' app = do express app.use session store: new FileStore, secret: 'keyboard cat', # TODO resave: true, saveUninitialized: true # TODO: session tests # See https://github.com/expressjs/session # See https://github.com/valery-barysok/session-file-store/tree/master/examples/express-example app.get '/session', (req, res) -> if req.session.views req.session.views++ res.setHeader 'Content-Type', 'text/html' res.write '<p>views: ' + req.session.views + '</p>' do res.end else req.session.views = 1 res.end 'Welcome to the file session demo. Refresh page!' # Get challenges listing # For REST info, see https://en.wikipedia.org/wiki/Representational_state_transfer app.get '/challenges', (req, res) -> fs.readdir __dirname + '/challenges', (error, files) -> if not error? # See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error res.json files else res.end error.toString() getChallenge = (id, isAdmin) -> # Get information for challenge <id> # TODO: use asynchronous file read? challenge = JSON.parse fs.readFileSync __dirname + '/challenges/' + id + '/config.json' challenge.id = id challenge.status = 4 if isAdmin challenge # Get challenge information # Use a status field: 1 = announced, 2 = running, 3 = vote, 4 = finished (default 0 = auto) to switch between states disregarding provided start and end times app.get '/challenges/:id', (req, res) -> challenge = getChallenge req.params.id, req.session.isAdmin # TODO: use asynchronous file read challenge.downloads = fs.readdirSync __dirname + '/challenges/' + req.params.id + '/downloads' if challenge.status > 1 challenge.uploadId = req.session.uploadId # Available competition tracks are all files in the entries directory # We have an audio file + .json file for each entry # TODO: add current user's votes fs.readdir __dirname + '/challenges/' + req.params.id + '/entries', (error, files) -> challenge.entries = [] challenge.votes = {} if not error? and challenge.status > 2 # See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error files.forEach (file, index) -> if file.endsWith '.json' # Add entry data entry = JSON.parse fs.readFileSync __dirname + '/challenges/' + req.params.id + '/entries/' + file challenge.entries.push path: entry.path artist: if challenge.status > 3 then entry.artist else '' title: entry.title uploadId: entry.uploadId if file.endsWith('.vote') and challenge.status > 3 # Add artist's votes vote = JSON.parse fs.readFileSync __dirname + '/challenges/' + req.params.id + '/entries/' + file for e, v of vote challenge.votes[e] = (challenge.votes[e] || 0) + Number v # Sort entries by vote if challenge.status > 3 if challenge.status > 3 challenge.entries.sort (a, b) -> (challenge.votes[b.uploadId] || 0) - (challenge.votes[a.uploadId] || 0) else challenge.entries.sort (a, b) -> if a.uploadId < b.uploadId -1 else if b.uploadId < a.uploadId 1 else 0 res.json challenge else console.log error if error? # TODO: res.end error.toString() res.json challenge # Download challenge artifact # See https://arjunphp.com/download-file-node-js-express-js/ # TODO: only provide downloads after the challenge has started app.get '/challenges/:id/downloads/:name(*)', (req, res) -> path = __dirname + '/challenges/' + req.params.id + '/downloads/' + req.params.name res.download path, req.params.name # Download entry # See https://arjunphp.com/download-file-node-js-express-js/ # TODO: only provide downloads after the challenge has started app.get '/challenges/:id/entries/:name(*)', (req, res) -> path = __dirname + '/challenges/' + req.params.id + '/entries/' + req.params.name res.download path, req.params.name # Use Formidable to handle (file) uploads # https://github.com/felixge/node-formidable app.post '/challenges/:id/upload', (req, res) -> form = new formidable.IncomingForm form.keepExtensions = true; form.uploadDir = __dirname + '/challenges/' + req.params.id + '/entries/' # Only allow uploads after the challenge has started (status == 2) challenge = getChallenge req.params.id, req.session.isAdmin return res.json { message: 'Challenge is not running. Uploads are not possible.' } unless challenge.status == 2 form.on 'fileBegin', (field, file) -> # Remove 'upload_' prefix from file path's and care for previous upload session path = file.path.split sep comp = path[path.length - 1].substr(7).split('.') path[path.length - 1] = (req.session.uploadId || comp[0]) + '.' + comp[1] file.path = path.join sep console.log 'receiving: ' + file.path form.parse req, (error, fields, files) -> console.log error if error? # TODO: use fields.uploadId (if present) to overwrite existing entry path = files.file.path.split sep data = artist: fields.artist title: fields.title path: path[path.length - 1] uploadId: path[path.length - 1].split('.')[0] # Keep the uploadId as session info in order to allow uploading and voting again req.session.uploadId = data.uploadId path[path.length - 1] = path[path.length - 1].split('.')[0] + '.json' fs.writeFile path.join(sep), JSON.stringify(data), (error) -> console.log error if error? res.json data app.post '/challenges/:id/vote', (req, res) -> form = new formidable.IncomingForm form.parse req, (error, fields, files) -> console.log error if error? return res.json { success: false } unless req.session.uploadId? path = __dirname + '/challenges/' + req.params.id + '/entries/' + req.session.uploadId + '.vote' fs.writeFile path, JSON.stringify(fields), (error) -> console.log error if error? res.json { success: true } # Allow login as admin and using artist / uploadId app.get '/login/:id?/:user/:pw', (req, res) -> result = { success: false, message: 'This upload token does not seem to be valid for the challenge.' } req.session.isAdmin = req.params.user is config.user && req.params.pw is config.pw if req.session.isAdmin result = { success: true, message: 'Welcome admin!' } else if req.params.id? # Try to load config file entry = JSON.parse fs.readFileSync __dirname + '/challenges/' + req.params.id + '/entries/' + req.params.pw + '.json' req.session.uploadId = entry.uploadId result = { success: true, message: 'Welcome ' + entry.artist + '!' } if entry.artist? res.json result # Serve the frontend from subfolder www app.use express.static __dirname + '/www' server = app.listen 62416, () -> host = server.address().address port = server.address().port console.log 'One hour challenge tool listening at http://%s:%s', host, port # Startup code try # TODO: use asynchronous file read config = fs.readFileSync __dirname + '/config.json' config = JSON.parse config console.log config catch e console.log "Error reading config: ", e config = user: 'admin' pw: 'admin'
56806
# Folder layout # challenges/ # <name of challenge>/ # config.json describing challenge # downloads/ # <file1>, .., <fileN>: downloadable challenge artifacts # entries/ # votes/ express = require 'express' session = require 'express-session' FileStore = require('session-file-store') session fs = require 'fs' sep = require('path').sep formidable = require 'formidable' app = do express app.use session store: new FileStore, secret: 'keyboard cat', # TODO resave: true, saveUninitialized: true # TODO: session tests # See https://github.com/expressjs/session # See https://github.com/valery-barysok/session-file-store/tree/master/examples/express-example app.get '/session', (req, res) -> if req.session.views req.session.views++ res.setHeader 'Content-Type', 'text/html' res.write '<p>views: ' + req.session.views + '</p>' do res.end else req.session.views = 1 res.end 'Welcome to the file session demo. Refresh page!' # Get challenges listing # For REST info, see https://en.wikipedia.org/wiki/Representational_state_transfer app.get '/challenges', (req, res) -> fs.readdir __dirname + '/challenges', (error, files) -> if not error? # See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error res.json files else res.end error.toString() getChallenge = (id, isAdmin) -> # Get information for challenge <id> # TODO: use asynchronous file read? challenge = JSON.parse fs.readFileSync __dirname + '/challenges/' + id + '/config.json' challenge.id = id challenge.status = 4 if isAdmin challenge # Get challenge information # Use a status field: 1 = announced, 2 = running, 3 = vote, 4 = finished (default 0 = auto) to switch between states disregarding provided start and end times app.get '/challenges/:id', (req, res) -> challenge = getChallenge req.params.id, req.session.isAdmin # TODO: use asynchronous file read challenge.downloads = fs.readdirSync __dirname + '/challenges/' + req.params.id + '/downloads' if challenge.status > 1 challenge.uploadId = req.session.uploadId # Available competition tracks are all files in the entries directory # We have an audio file + .json file for each entry # TODO: add current user's votes fs.readdir __dirname + '/challenges/' + req.params.id + '/entries', (error, files) -> challenge.entries = [] challenge.votes = {} if not error? and challenge.status > 2 # See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error files.forEach (file, index) -> if file.endsWith '.json' # Add entry data entry = JSON.parse fs.readFileSync __dirname + '/challenges/' + req.params.id + '/entries/' + file challenge.entries.push path: entry.path artist: if challenge.status > 3 then entry.artist else '' title: entry.title uploadId: entry.uploadId if file.endsWith('.vote') and challenge.status > 3 # Add artist's votes vote = JSON.parse fs.readFileSync __dirname + '/challenges/' + req.params.id + '/entries/' + file for e, v of vote challenge.votes[e] = (challenge.votes[e] || 0) + Number v # Sort entries by vote if challenge.status > 3 if challenge.status > 3 challenge.entries.sort (a, b) -> (challenge.votes[b.uploadId] || 0) - (challenge.votes[a.uploadId] || 0) else challenge.entries.sort (a, b) -> if a.uploadId < b.uploadId -1 else if b.uploadId < a.uploadId 1 else 0 res.json challenge else console.log error if error? # TODO: res.end error.toString() res.json challenge # Download challenge artifact # See https://arjunphp.com/download-file-node-js-express-js/ # TODO: only provide downloads after the challenge has started app.get '/challenges/:id/downloads/:name(*)', (req, res) -> path = __dirname + '/challenges/' + req.params.id + '/downloads/' + req.params.name res.download path, req.params.name # Download entry # See https://arjunphp.com/download-file-node-js-express-js/ # TODO: only provide downloads after the challenge has started app.get '/challenges/:id/entries/:name(*)', (req, res) -> path = __dirname + '/challenges/' + req.params.id + '/entries/' + req.params.name res.download path, req.params.name # Use Formidable to handle (file) uploads # https://github.com/felixge/node-formidable app.post '/challenges/:id/upload', (req, res) -> form = new formidable.IncomingForm form.keepExtensions = true; form.uploadDir = __dirname + '/challenges/' + req.params.id + '/entries/' # Only allow uploads after the challenge has started (status == 2) challenge = getChallenge req.params.id, req.session.isAdmin return res.json { message: 'Challenge is not running. Uploads are not possible.' } unless challenge.status == 2 form.on 'fileBegin', (field, file) -> # Remove 'upload_' prefix from file path's and care for previous upload session path = file.path.split sep comp = path[path.length - 1].substr(7).split('.') path[path.length - 1] = (req.session.uploadId || comp[0]) + '.' + comp[1] file.path = path.join sep console.log 'receiving: ' + file.path form.parse req, (error, fields, files) -> console.log error if error? # TODO: use fields.uploadId (if present) to overwrite existing entry path = files.file.path.split sep data = artist: fields.artist title: fields.title path: path[path.length - 1] uploadId: path[path.length - 1].split('.')[0] # Keep the uploadId as session info in order to allow uploading and voting again req.session.uploadId = data.uploadId path[path.length - 1] = path[path.length - 1].split('.')[0] + '.json' fs.writeFile path.join(sep), JSON.stringify(data), (error) -> console.log error if error? res.json data app.post '/challenges/:id/vote', (req, res) -> form = new formidable.IncomingForm form.parse req, (error, fields, files) -> console.log error if error? return res.json { success: false } unless req.session.uploadId? path = __dirname + '/challenges/' + req.params.id + '/entries/' + req.session.uploadId + '.vote' fs.writeFile path, JSON.stringify(fields), (error) -> console.log error if error? res.json { success: true } # Allow login as admin and using artist / uploadId app.get '/login/:id?/:user/:pw', (req, res) -> result = { success: false, message: 'This upload token does not seem to be valid for the challenge.' } req.session.isAdmin = req.params.user is config.user && req.params.pw is config.pw if req.session.isAdmin result = { success: true, message: 'Welcome admin!' } else if req.params.id? # Try to load config file entry = JSON.parse fs.readFileSync __dirname + '/challenges/' + req.params.id + '/entries/' + req.params.pw + '.json' req.session.uploadId = entry.uploadId result = { success: true, message: 'Welcome ' + entry.artist + '!' } if entry.artist? res.json result # Serve the frontend from subfolder www app.use express.static __dirname + '/www' server = app.listen 62416, () -> host = server.address().address port = server.address().port console.log 'One hour challenge tool listening at http://%s:%s', host, port # Startup code try # TODO: use asynchronous file read config = fs.readFileSync __dirname + '/config.json' config = JSON.parse config console.log config catch e console.log "Error reading config: ", e config = user: 'admin' pw: '<PASSWORD>'
true
# Folder layout # challenges/ # <name of challenge>/ # config.json describing challenge # downloads/ # <file1>, .., <fileN>: downloadable challenge artifacts # entries/ # votes/ express = require 'express' session = require 'express-session' FileStore = require('session-file-store') session fs = require 'fs' sep = require('path').sep formidable = require 'formidable' app = do express app.use session store: new FileStore, secret: 'keyboard cat', # TODO resave: true, saveUninitialized: true # TODO: session tests # See https://github.com/expressjs/session # See https://github.com/valery-barysok/session-file-store/tree/master/examples/express-example app.get '/session', (req, res) -> if req.session.views req.session.views++ res.setHeader 'Content-Type', 'text/html' res.write '<p>views: ' + req.session.views + '</p>' do res.end else req.session.views = 1 res.end 'Welcome to the file session demo. Refresh page!' # Get challenges listing # For REST info, see https://en.wikipedia.org/wiki/Representational_state_transfer app.get '/challenges', (req, res) -> fs.readdir __dirname + '/challenges', (error, files) -> if not error? # See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error res.json files else res.end error.toString() getChallenge = (id, isAdmin) -> # Get information for challenge <id> # TODO: use asynchronous file read? challenge = JSON.parse fs.readFileSync __dirname + '/challenges/' + id + '/config.json' challenge.id = id challenge.status = 4 if isAdmin challenge # Get challenge information # Use a status field: 1 = announced, 2 = running, 3 = vote, 4 = finished (default 0 = auto) to switch between states disregarding provided start and end times app.get '/challenges/:id', (req, res) -> challenge = getChallenge req.params.id, req.session.isAdmin # TODO: use asynchronous file read challenge.downloads = fs.readdirSync __dirname + '/challenges/' + req.params.id + '/downloads' if challenge.status > 1 challenge.uploadId = req.session.uploadId # Available competition tracks are all files in the entries directory # We have an audio file + .json file for each entry # TODO: add current user's votes fs.readdir __dirname + '/challenges/' + req.params.id + '/entries', (error, files) -> challenge.entries = [] challenge.votes = {} if not error? and challenge.status > 2 # See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error files.forEach (file, index) -> if file.endsWith '.json' # Add entry data entry = JSON.parse fs.readFileSync __dirname + '/challenges/' + req.params.id + '/entries/' + file challenge.entries.push path: entry.path artist: if challenge.status > 3 then entry.artist else '' title: entry.title uploadId: entry.uploadId if file.endsWith('.vote') and challenge.status > 3 # Add artist's votes vote = JSON.parse fs.readFileSync __dirname + '/challenges/' + req.params.id + '/entries/' + file for e, v of vote challenge.votes[e] = (challenge.votes[e] || 0) + Number v # Sort entries by vote if challenge.status > 3 if challenge.status > 3 challenge.entries.sort (a, b) -> (challenge.votes[b.uploadId] || 0) - (challenge.votes[a.uploadId] || 0) else challenge.entries.sort (a, b) -> if a.uploadId < b.uploadId -1 else if b.uploadId < a.uploadId 1 else 0 res.json challenge else console.log error if error? # TODO: res.end error.toString() res.json challenge # Download challenge artifact # See https://arjunphp.com/download-file-node-js-express-js/ # TODO: only provide downloads after the challenge has started app.get '/challenges/:id/downloads/:name(*)', (req, res) -> path = __dirname + '/challenges/' + req.params.id + '/downloads/' + req.params.name res.download path, req.params.name # Download entry # See https://arjunphp.com/download-file-node-js-express-js/ # TODO: only provide downloads after the challenge has started app.get '/challenges/:id/entries/:name(*)', (req, res) -> path = __dirname + '/challenges/' + req.params.id + '/entries/' + req.params.name res.download path, req.params.name # Use Formidable to handle (file) uploads # https://github.com/felixge/node-formidable app.post '/challenges/:id/upload', (req, res) -> form = new formidable.IncomingForm form.keepExtensions = true; form.uploadDir = __dirname + '/challenges/' + req.params.id + '/entries/' # Only allow uploads after the challenge has started (status == 2) challenge = getChallenge req.params.id, req.session.isAdmin return res.json { message: 'Challenge is not running. Uploads are not possible.' } unless challenge.status == 2 form.on 'fileBegin', (field, file) -> # Remove 'upload_' prefix from file path's and care for previous upload session path = file.path.split sep comp = path[path.length - 1].substr(7).split('.') path[path.length - 1] = (req.session.uploadId || comp[0]) + '.' + comp[1] file.path = path.join sep console.log 'receiving: ' + file.path form.parse req, (error, fields, files) -> console.log error if error? # TODO: use fields.uploadId (if present) to overwrite existing entry path = files.file.path.split sep data = artist: fields.artist title: fields.title path: path[path.length - 1] uploadId: path[path.length - 1].split('.')[0] # Keep the uploadId as session info in order to allow uploading and voting again req.session.uploadId = data.uploadId path[path.length - 1] = path[path.length - 1].split('.')[0] + '.json' fs.writeFile path.join(sep), JSON.stringify(data), (error) -> console.log error if error? res.json data app.post '/challenges/:id/vote', (req, res) -> form = new formidable.IncomingForm form.parse req, (error, fields, files) -> console.log error if error? return res.json { success: false } unless req.session.uploadId? path = __dirname + '/challenges/' + req.params.id + '/entries/' + req.session.uploadId + '.vote' fs.writeFile path, JSON.stringify(fields), (error) -> console.log error if error? res.json { success: true } # Allow login as admin and using artist / uploadId app.get '/login/:id?/:user/:pw', (req, res) -> result = { success: false, message: 'This upload token does not seem to be valid for the challenge.' } req.session.isAdmin = req.params.user is config.user && req.params.pw is config.pw if req.session.isAdmin result = { success: true, message: 'Welcome admin!' } else if req.params.id? # Try to load config file entry = JSON.parse fs.readFileSync __dirname + '/challenges/' + req.params.id + '/entries/' + req.params.pw + '.json' req.session.uploadId = entry.uploadId result = { success: true, message: 'Welcome ' + entry.artist + '!' } if entry.artist? res.json result # Serve the frontend from subfolder www app.use express.static __dirname + '/www' server = app.listen 62416, () -> host = server.address().address port = server.address().port console.log 'One hour challenge tool listening at http://%s:%s', host, port # Startup code try # TODO: use asynchronous file read config = fs.readFileSync __dirname + '/config.json' config = JSON.parse config console.log config catch e console.log "Error reading config: ", e config = user: 'admin' pw: 'PI:PASSWORD:<PASSWORD>END_PI'
[ { "context": " grunt.template.today(\"yyyy\") %>\\n' +\n ' * Jason Chen, Salesforce.com\\n' +\n ' */\\n\\n'\n quill:", "end": 1848, "score": 0.9995363354682922, "start": 1838, "tag": "NAME", "value": "Jason Chen" } ]
grunt/build.coffee
Automattic/quill
4
module.exports = (grunt) -> grunt.config('browserify', options: alias: [ 'node_modules/eventemitter2/lib/eventemitter2.js:eventemitter2' 'node_modules/lodash/lodash.js:lodash' 'node_modules/tandem-core/build/tandem-core.js:tandem-core' 'node_modules/underscore.string/lib/underscore.string.js:underscore.string' ] browserifyOptions: extensions: ['.js', '.coffee'] transform: ['coffeeify'] 'quill': options: bundleOptions: standalone: 'Quill' files: [ { 'build/quill.js': ['index.coffee'] } { 'build/quill.exposed.js': ['test/quill.coffee'] } ] 'tandem': options: bundleOptions: standalone: 'Tandem' files: [{ 'build/tandem-core.js': ['node_modules/tandem-core/index.js'] }] 'quill-watchify': options: bundleOptions: standalone: 'Quill' keepAlive: true watch: true files: [{ 'build/quill.js': ['index.coffee'] }] 'quill-exposed-watchify': options: bundleOptions: standalone: 'Quill' keepAlive: true watch: true files: [{ 'build/quill.exposed.js': ['test/quill.coffee'] }] ) grunt.config('clean', all: ['build'] coverage: ['src/**/*.js'] ) grunt.config('coffee', all: expand: true dest: 'build/' src: ['demo/scripts/*.coffee', 'test/**/*.coffee'] ext: '.js' coverage: expand: true dest: 'build/' src: ['src/**/*.coffee'] ext: '.js' ) grunt.config('concat', options: banner: '/*! Stypi Editor - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * https://quilljs.com/\n' + ' * Copyright (c) <%= grunt.template.today("yyyy") %>\n' + ' * Jason Chen, Salesforce.com\n' + ' */\n\n' quill: 'build/quill.js': ['build/quill.js'] 'build/quill.min.js': ['build/quill.min.js'] ) grunt.config('copy' build: expand: true dest: 'build/' src: ['lib/*.js', 'demo/images/*.png'] ) grunt.config('jade', all: options: pretty: true dest: 'build/' expand: true ext: '.html' src: ['demo/*.jade', 'test/fixtures/*.jade', '!demo/content.jade'] ) grunt.config('stylus', options: compress: false themes: options: urlfunc: 'url' files: [{ expand: true ext: '.css' flatten: true src: 'src/themes/**/*.styl' rename: (dest, src) -> return "build/themes/quill.#{src}" }] demo: expand: true ext: '.css' dest: 'build/' src: ['demo/styles/*.styl'] ) grunt.config('uglify', quill: files: { 'build/quill.min.js': ['build/quill.js'] } )
217459
module.exports = (grunt) -> grunt.config('browserify', options: alias: [ 'node_modules/eventemitter2/lib/eventemitter2.js:eventemitter2' 'node_modules/lodash/lodash.js:lodash' 'node_modules/tandem-core/build/tandem-core.js:tandem-core' 'node_modules/underscore.string/lib/underscore.string.js:underscore.string' ] browserifyOptions: extensions: ['.js', '.coffee'] transform: ['coffeeify'] 'quill': options: bundleOptions: standalone: 'Quill' files: [ { 'build/quill.js': ['index.coffee'] } { 'build/quill.exposed.js': ['test/quill.coffee'] } ] 'tandem': options: bundleOptions: standalone: 'Tandem' files: [{ 'build/tandem-core.js': ['node_modules/tandem-core/index.js'] }] 'quill-watchify': options: bundleOptions: standalone: 'Quill' keepAlive: true watch: true files: [{ 'build/quill.js': ['index.coffee'] }] 'quill-exposed-watchify': options: bundleOptions: standalone: 'Quill' keepAlive: true watch: true files: [{ 'build/quill.exposed.js': ['test/quill.coffee'] }] ) grunt.config('clean', all: ['build'] coverage: ['src/**/*.js'] ) grunt.config('coffee', all: expand: true dest: 'build/' src: ['demo/scripts/*.coffee', 'test/**/*.coffee'] ext: '.js' coverage: expand: true dest: 'build/' src: ['src/**/*.coffee'] ext: '.js' ) grunt.config('concat', options: banner: '/*! Stypi Editor - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * https://quilljs.com/\n' + ' * Copyright (c) <%= grunt.template.today("yyyy") %>\n' + ' * <NAME>, Salesforce.com\n' + ' */\n\n' quill: 'build/quill.js': ['build/quill.js'] 'build/quill.min.js': ['build/quill.min.js'] ) grunt.config('copy' build: expand: true dest: 'build/' src: ['lib/*.js', 'demo/images/*.png'] ) grunt.config('jade', all: options: pretty: true dest: 'build/' expand: true ext: '.html' src: ['demo/*.jade', 'test/fixtures/*.jade', '!demo/content.jade'] ) grunt.config('stylus', options: compress: false themes: options: urlfunc: 'url' files: [{ expand: true ext: '.css' flatten: true src: 'src/themes/**/*.styl' rename: (dest, src) -> return "build/themes/quill.#{src}" }] demo: expand: true ext: '.css' dest: 'build/' src: ['demo/styles/*.styl'] ) grunt.config('uglify', quill: files: { 'build/quill.min.js': ['build/quill.js'] } )
true
module.exports = (grunt) -> grunt.config('browserify', options: alias: [ 'node_modules/eventemitter2/lib/eventemitter2.js:eventemitter2' 'node_modules/lodash/lodash.js:lodash' 'node_modules/tandem-core/build/tandem-core.js:tandem-core' 'node_modules/underscore.string/lib/underscore.string.js:underscore.string' ] browserifyOptions: extensions: ['.js', '.coffee'] transform: ['coffeeify'] 'quill': options: bundleOptions: standalone: 'Quill' files: [ { 'build/quill.js': ['index.coffee'] } { 'build/quill.exposed.js': ['test/quill.coffee'] } ] 'tandem': options: bundleOptions: standalone: 'Tandem' files: [{ 'build/tandem-core.js': ['node_modules/tandem-core/index.js'] }] 'quill-watchify': options: bundleOptions: standalone: 'Quill' keepAlive: true watch: true files: [{ 'build/quill.js': ['index.coffee'] }] 'quill-exposed-watchify': options: bundleOptions: standalone: 'Quill' keepAlive: true watch: true files: [{ 'build/quill.exposed.js': ['test/quill.coffee'] }] ) grunt.config('clean', all: ['build'] coverage: ['src/**/*.js'] ) grunt.config('coffee', all: expand: true dest: 'build/' src: ['demo/scripts/*.coffee', 'test/**/*.coffee'] ext: '.js' coverage: expand: true dest: 'build/' src: ['src/**/*.coffee'] ext: '.js' ) grunt.config('concat', options: banner: '/*! Stypi Editor - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * https://quilljs.com/\n' + ' * Copyright (c) <%= grunt.template.today("yyyy") %>\n' + ' * PI:NAME:<NAME>END_PI, Salesforce.com\n' + ' */\n\n' quill: 'build/quill.js': ['build/quill.js'] 'build/quill.min.js': ['build/quill.min.js'] ) grunt.config('copy' build: expand: true dest: 'build/' src: ['lib/*.js', 'demo/images/*.png'] ) grunt.config('jade', all: options: pretty: true dest: 'build/' expand: true ext: '.html' src: ['demo/*.jade', 'test/fixtures/*.jade', '!demo/content.jade'] ) grunt.config('stylus', options: compress: false themes: options: urlfunc: 'url' files: [{ expand: true ext: '.css' flatten: true src: 'src/themes/**/*.styl' rename: (dest, src) -> return "build/themes/quill.#{src}" }] demo: expand: true ext: '.css' dest: 'build/' src: ['demo/styles/*.styl'] ) grunt.config('uglify', quill: files: { 'build/quill.min.js': ['build/quill.js'] } )
[ { "context": "-> post \"/login\",\n id: id\n password: \"\"\n solution: (exercise_id) -> post '/solution',\n", "end": 678, "score": 0.9663599133491516, "start": 678, "tag": "PASSWORD", "value": "" } ]
app/scripts/api.coffee
Welfenlab/tutor-student
1
{get, put, post, del, address} = require('@tutor/app-base').api Q = require('q') module.exports = get: exercises: -> get('/exercises') exercise: (id) -> get("/exercises/#{id}") me: -> get('/user') group: -> get('/group') pseudonyms: -> get('/pseudonyms') pseudonym: -> get('/generatepseudonym') time: -> get('/time') logindata: -> get('/login_data') invitations: -> get('/group/pending') config: -> get('/config') put: exercise: (id, content) -> put "/exercises/#{id}", content pseudonym: (pseudonym) -> put "/user/pseudonym", pseudonym: pseudonym post: loginDev: (id) -> post "/login", id: id password: "" solution: (exercise_id) -> post '/solution', exercise: exercise_id joinGroup: (id) -> post '/group/join', group: id rejectGroup: (id) -> post '/group/join', group: id logout: -> post '/logout' create: group: (members) -> post '/group', members urlOf: correctedExercise: (id) -> "#{address}/correction/pdf/#{id}" submittedExercise: (id) -> "#{address}/solution/pdf/#{id}" address: address
211266
{get, put, post, del, address} = require('@tutor/app-base').api Q = require('q') module.exports = get: exercises: -> get('/exercises') exercise: (id) -> get("/exercises/#{id}") me: -> get('/user') group: -> get('/group') pseudonyms: -> get('/pseudonyms') pseudonym: -> get('/generatepseudonym') time: -> get('/time') logindata: -> get('/login_data') invitations: -> get('/group/pending') config: -> get('/config') put: exercise: (id, content) -> put "/exercises/#{id}", content pseudonym: (pseudonym) -> put "/user/pseudonym", pseudonym: pseudonym post: loginDev: (id) -> post "/login", id: id password:<PASSWORD> "" solution: (exercise_id) -> post '/solution', exercise: exercise_id joinGroup: (id) -> post '/group/join', group: id rejectGroup: (id) -> post '/group/join', group: id logout: -> post '/logout' create: group: (members) -> post '/group', members urlOf: correctedExercise: (id) -> "#{address}/correction/pdf/#{id}" submittedExercise: (id) -> "#{address}/solution/pdf/#{id}" address: address
true
{get, put, post, del, address} = require('@tutor/app-base').api Q = require('q') module.exports = get: exercises: -> get('/exercises') exercise: (id) -> get("/exercises/#{id}") me: -> get('/user') group: -> get('/group') pseudonyms: -> get('/pseudonyms') pseudonym: -> get('/generatepseudonym') time: -> get('/time') logindata: -> get('/login_data') invitations: -> get('/group/pending') config: -> get('/config') put: exercise: (id, content) -> put "/exercises/#{id}", content pseudonym: (pseudonym) -> put "/user/pseudonym", pseudonym: pseudonym post: loginDev: (id) -> post "/login", id: id password:PI:PASSWORD:<PASSWORD>END_PI "" solution: (exercise_id) -> post '/solution', exercise: exercise_id joinGroup: (id) -> post '/group/join', group: id rejectGroup: (id) -> post '/group/join', group: id logout: -> post '/logout' create: group: (members) -> post '/group', members urlOf: correctedExercise: (id) -> "#{address}/correction/pdf/#{id}" submittedExercise: (id) -> "#{address}/solution/pdf/#{id}" address: address
[ { "context": "#\n# Based on implementation by Neil Bartlett\n# https://github.com/neilbartlett/color-temperatu", "end": 44, "score": 0.9999041557312012, "start": 31, "tag": "NAME", "value": "Neil Bartlett" }, { "context": "lementation by Neil Bartlett\n# https://github.com/neilbartle...
node_modules/chroma-js/src/converter/in/temperature2rgb.coffee
Dozacode/ResumeChain
15
# # Based on implementation by Neil Bartlett # https://github.com/neilbartlett/color-temperature # # @requires utils temperature2rgb = (kelvin) -> temp = kelvin / 100 if temp < 66 r = 255 g = -155.25485562709179 - 0.44596950469579133 * (g = temp-2) + 104.49216199393888 * log(g) b = if temp < 20 then 0 else -254.76935184120902 + 0.8274096064007395 * (b = temp-10) + 115.67994401066147 * log(b) else r = 351.97690566805693 + 0.114206453784165 * (r = temp-55) - 40.25366309332127 * log(r) g = 325.4494125711974 + 0.07943456536662342 * (g = temp-50) - 28.0852963507957 * log(g) b = 255 [r,g,b]
104098
# # Based on implementation by <NAME> # https://github.com/neilbartlett/color-temperature # # @requires utils temperature2rgb = (kelvin) -> temp = kelvin / 100 if temp < 66 r = 255 g = -155.25485562709179 - 0.44596950469579133 * (g = temp-2) + 104.49216199393888 * log(g) b = if temp < 20 then 0 else -254.76935184120902 + 0.8274096064007395 * (b = temp-10) + 115.67994401066147 * log(b) else r = 351.97690566805693 + 0.114206453784165 * (r = temp-55) - 40.25366309332127 * log(r) g = 325.4494125711974 + 0.07943456536662342 * (g = temp-50) - 28.0852963507957 * log(g) b = 255 [r,g,b]
true
# # Based on implementation by PI:NAME:<NAME>END_PI # https://github.com/neilbartlett/color-temperature # # @requires utils temperature2rgb = (kelvin) -> temp = kelvin / 100 if temp < 66 r = 255 g = -155.25485562709179 - 0.44596950469579133 * (g = temp-2) + 104.49216199393888 * log(g) b = if temp < 20 then 0 else -254.76935184120902 + 0.8274096064007395 * (b = temp-10) + 115.67994401066147 * log(b) else r = 351.97690566805693 + 0.114206453784165 * (r = temp-55) - 40.25366309332127 * log(r) g = 325.4494125711974 + 0.07943456536662342 * (g = temp-50) - 28.0852963507957 * log(g) b = 255 [r,g,b]
[ { "context": " <td className='label collapsing'>姓名:</td><td>王大锤</td>\r\n <td className='label collapsi", "end": 625, "score": 0.9998513460159302, "start": 622, "tag": "NAME", "value": "王大锤" }, { "context": " <td className='label collapsing'>姓名:</td><td>王大锤</td>\r...
src/base/coffee/zd-patient-info-page.coffee
ben7th/zdmockup
0
@TopbarBack = React.createClass render: -> <a className='topbar-back' href={@props.href}> <i className='icon chevron left' /> </a> @ZDPatientInfoPage = React.createClass render: -> <div className='zd-patient-info-page'> <div className='ui container'> <h2 className='ui header topbar'> <TopbarBack href='zd-patient-list.html' /> <span>患者信息</span> </h2> <div className='table-div'> <table className='ui very basic celled table'> <tbody> <tr> <td className='label collapsing'>姓名:</td><td>王大锤</td> <td className='label collapsing'>性别:</td><td>男</td> <td className='label collapsing'>年龄:</td><td>33</td> </tr> <tr> <td className='label collapsing'>日期:</td><td>2015-12-08</td> <td className='label collapsing'>就诊号:</td><td>301</td> <td className='label collapsing'>诊疗卡:</td><td>1234567</td> </tr> <tr> <td className='label collapsing'>身高:</td><td>180 cm</td> <td className='label collapsing'>体重:</td><td>70 kg</td> <td className='label collapsing'>血压:</td><td>70/100 mmHg</td> </tr> <tr> <td className='label collapsing top aligned'>既往史:</td><td colSpan='5' className='desc'><span></span></td> </tr> <tr> <td className='label collapsing top aligned'>体质类型:</td><td colSpan='5' className='desc'><span></span></td> </tr> </tbody> </table> <div> <a className='ui labeled icon button back' href='zd-patient-list.html'> <i className='left arrow icon' /> <span>返回患者队列</span> </a> <a className='ui right labeled icon button brown next' href='zd-diagnosis.html'> <i className='right arrow icon' /> <span>进入体检系统</span> </a> </div> </div> </div> </div> @ZDPatientResultPage = React.createClass render: -> <div className='zd-patient-info-page'> <div className='ui container'> <h2 className='ui header topbar'> <TopbarBack href='zd-patient-list.html' /> <span>患者信息</span> </h2> <div className='table-div'> <table className='ui very basic celled table'> <tbody> <tr> <td className='label collapsing'>姓名:</td><td>王大锤</td> <td className='label collapsing'>性别:</td><td>男</td> <td className='label collapsing'>年龄:</td><td>33</td> </tr> <tr> <td className='label collapsing'>日期:</td><td>2015-12-08</td> <td className='label collapsing'>就诊号:</td><td>301</td> <td className='label collapsing'>诊疗卡:</td><td>1234567</td> </tr> </tbody> </table> </div> <div className='table-div'> <div className='record'> <h3 className='ui header'>已检查项目:背诊</h3> </div> <div> <a className='ui labeled icon button back' href='javascript:;'> <i className='icon file' /> <span>查看体检记录</span> </a> <a className='ui right labeled icon button brown next' href='zd-diagnosis.html'> <i className='pencil icon' /> <span>修改体检记录</span> </a> </div> </div> <div className='table-div'> <div className='record'> <h3 className='ui header'>已检查项目:舌诊</h3> </div> <div> <a className='ui labeled icon button back' href='javascript:;'> <i className='icon file' /> <span>查看体检记录</span> </a> <a className='ui right labeled icon button brown next' href='zd-diagnosis.html'> <i className='pencil icon' /> <span>修改体检记录</span> </a> </div> </div> <div className='table-div'> <div> <a className='ui right labeled icon button brown next' href='zd-diagnosis.html'> <i className='plus icon' /> <span>检查其他项目</span> </a> </div> </div> <div className='table-div'> <div> <a className='ui right labeled icon button brown next' href='index.html'> <i className='icon check' /> <span>保存体检结果</span> </a> </div> </div> </div> </div> @ZDPatientResultPage1 = React.createClass render: -> <div className='zd-patient-info-page'> <div className='ui container'> <h2 className='ui header topbar'> <TopbarBack href='doctor-patient-info.html' /> <span>患者信息</span> </h2> <div className='table-div'> <table className='ui very basic celled table'> <tbody> <tr> <td className='label collapsing'>姓名:</td><td>王大锤</td> <td className='label collapsing'>性别:</td><td>男</td> <td className='label collapsing'>年龄:</td><td>33</td> </tr> <tr> <td className='label collapsing'>日期:</td><td>2015-12-08</td> <td className='label collapsing'>就诊号:</td><td>301</td> <td className='label collapsing'>诊疗卡:</td><td>1234567</td> </tr> <tr> <td className='label collapsing'>身高:</td><td>180 cm</td> <td className='label collapsing'>体重:</td><td>70 kg</td> <td className='label collapsing'>血压:</td><td>70/100 mmHg</td> </tr> <tr> <td className='label collapsing top aligned'>既往史:</td><td colSpan='5' className='desc'><span>无</span></td> </tr> <tr> <td className='label collapsing top aligned'>体质类型:</td><td colSpan='5' className='desc'><span>阳虚体质</span></td> </tr> <tr> <td className='label collapsing top aligned'>主诉:</td><td colSpan='5'><span>失眠</span></td> </tr> <tr> <td className='label collapsing top aligned'>初步诊断:</td><td colSpan='5' className='desc'><span>失眠</span></td> </tr> <tr> <td className='label collapsing top aligned'>处理:</td><td colSpan='5' className='desc'> <div>针灸:风池、印堂、神门、三阴交、太溪,平补平泻法,50分钟</div> <div>火罐:心俞、脾俞、内关、神门,单纯拔罐法,10分钟</div> <div>共5次</div> </td> </tr> <tr> <td className='label collapsing top aligned'>医师:</td><td colSpan='5'><span>叶建华</span></td> </tr> </tbody> </table> </div> <div className='table-div'> <div className='record'> <h3 className='ui header'>已检查项目:背诊</h3> </div> <div> <a className='ui labeled icon button back' href='javascript:;'> <i className='icon file' /> <span>查看体检记录</span> </a> </div> </div> <div className='table-div'> <div className='record'> <h3 className='ui header'>已检查项目:舌诊</h3> </div> <div> <a className='ui labeled icon button back' href='javascript:;'> <i className='icon file' /> <span>查看体检记录</span> </a> </div> </div> </div> </div>
126294
@TopbarBack = React.createClass render: -> <a className='topbar-back' href={@props.href}> <i className='icon chevron left' /> </a> @ZDPatientInfoPage = React.createClass render: -> <div className='zd-patient-info-page'> <div className='ui container'> <h2 className='ui header topbar'> <TopbarBack href='zd-patient-list.html' /> <span>患者信息</span> </h2> <div className='table-div'> <table className='ui very basic celled table'> <tbody> <tr> <td className='label collapsing'>姓名:</td><td><NAME></td> <td className='label collapsing'>性别:</td><td>男</td> <td className='label collapsing'>年龄:</td><td>33</td> </tr> <tr> <td className='label collapsing'>日期:</td><td>2015-12-08</td> <td className='label collapsing'>就诊号:</td><td>301</td> <td className='label collapsing'>诊疗卡:</td><td>1234567</td> </tr> <tr> <td className='label collapsing'>身高:</td><td>180 cm</td> <td className='label collapsing'>体重:</td><td>70 kg</td> <td className='label collapsing'>血压:</td><td>70/100 mmHg</td> </tr> <tr> <td className='label collapsing top aligned'>既往史:</td><td colSpan='5' className='desc'><span></span></td> </tr> <tr> <td className='label collapsing top aligned'>体质类型:</td><td colSpan='5' className='desc'><span></span></td> </tr> </tbody> </table> <div> <a className='ui labeled icon button back' href='zd-patient-list.html'> <i className='left arrow icon' /> <span>返回患者队列</span> </a> <a className='ui right labeled icon button brown next' href='zd-diagnosis.html'> <i className='right arrow icon' /> <span>进入体检系统</span> </a> </div> </div> </div> </div> @ZDPatientResultPage = React.createClass render: -> <div className='zd-patient-info-page'> <div className='ui container'> <h2 className='ui header topbar'> <TopbarBack href='zd-patient-list.html' /> <span>患者信息</span> </h2> <div className='table-div'> <table className='ui very basic celled table'> <tbody> <tr> <td className='label collapsing'>姓名:</td><td><NAME></td> <td className='label collapsing'>性别:</td><td>男</td> <td className='label collapsing'>年龄:</td><td>33</td> </tr> <tr> <td className='label collapsing'>日期:</td><td>2015-12-08</td> <td className='label collapsing'>就诊号:</td><td>301</td> <td className='label collapsing'>诊疗卡:</td><td>1234567</td> </tr> </tbody> </table> </div> <div className='table-div'> <div className='record'> <h3 className='ui header'>已检查项目:背诊</h3> </div> <div> <a className='ui labeled icon button back' href='javascript:;'> <i className='icon file' /> <span>查看体检记录</span> </a> <a className='ui right labeled icon button brown next' href='zd-diagnosis.html'> <i className='pencil icon' /> <span>修改体检记录</span> </a> </div> </div> <div className='table-div'> <div className='record'> <h3 className='ui header'>已检查项目:舌诊</h3> </div> <div> <a className='ui labeled icon button back' href='javascript:;'> <i className='icon file' /> <span>查看体检记录</span> </a> <a className='ui right labeled icon button brown next' href='zd-diagnosis.html'> <i className='pencil icon' /> <span>修改体检记录</span> </a> </div> </div> <div className='table-div'> <div> <a className='ui right labeled icon button brown next' href='zd-diagnosis.html'> <i className='plus icon' /> <span>检查其他项目</span> </a> </div> </div> <div className='table-div'> <div> <a className='ui right labeled icon button brown next' href='index.html'> <i className='icon check' /> <span>保存体检结果</span> </a> </div> </div> </div> </div> @ZDPatientResultPage1 = React.createClass render: -> <div className='zd-patient-info-page'> <div className='ui container'> <h2 className='ui header topbar'> <TopbarBack href='doctor-patient-info.html' /> <span>患者信息</span> </h2> <div className='table-div'> <table className='ui very basic celled table'> <tbody> <tr> <td className='label collapsing'>姓名:</td><td><NAME></td> <td className='label collapsing'>性别:</td><td>男</td> <td className='label collapsing'>年龄:</td><td>33</td> </tr> <tr> <td className='label collapsing'>日期:</td><td>2015-12-08</td> <td className='label collapsing'>就诊号:</td><td>301</td> <td className='label collapsing'>诊疗卡:</td><td>1234567</td> </tr> <tr> <td className='label collapsing'>身高:</td><td>180 cm</td> <td className='label collapsing'>体重:</td><td>70 kg</td> <td className='label collapsing'>血压:</td><td>70/100 mmHg</td> </tr> <tr> <td className='label collapsing top aligned'>既往史:</td><td colSpan='5' className='desc'><span>无</span></td> </tr> <tr> <td className='label collapsing top aligned'>体质类型:</td><td colSpan='5' className='desc'><span>阳虚体质</span></td> </tr> <tr> <td className='label collapsing top aligned'>主诉:</td><td colSpan='5'><span>失眠</span></td> </tr> <tr> <td className='label collapsing top aligned'>初步诊断:</td><td colSpan='5' className='desc'><span>失眠</span></td> </tr> <tr> <td className='label collapsing top aligned'>处理:</td><td colSpan='5' className='desc'> <div>针灸:风池、印堂、神门、三阴交、太溪,平补平泻法,50分钟</div> <div>火罐:心俞、脾俞、内关、神门,单纯拔罐法,10分钟</div> <div>共5次</div> </td> </tr> <tr> <td className='label collapsing top aligned'>医师:</td><td colSpan='5'><span>叶建华</span></td> </tr> </tbody> </table> </div> <div className='table-div'> <div className='record'> <h3 className='ui header'>已检查项目:背诊</h3> </div> <div> <a className='ui labeled icon button back' href='javascript:;'> <i className='icon file' /> <span>查看体检记录</span> </a> </div> </div> <div className='table-div'> <div className='record'> <h3 className='ui header'>已检查项目:舌诊</h3> </div> <div> <a className='ui labeled icon button back' href='javascript:;'> <i className='icon file' /> <span>查看体检记录</span> </a> </div> </div> </div> </div>
true
@TopbarBack = React.createClass render: -> <a className='topbar-back' href={@props.href}> <i className='icon chevron left' /> </a> @ZDPatientInfoPage = React.createClass render: -> <div className='zd-patient-info-page'> <div className='ui container'> <h2 className='ui header topbar'> <TopbarBack href='zd-patient-list.html' /> <span>患者信息</span> </h2> <div className='table-div'> <table className='ui very basic celled table'> <tbody> <tr> <td className='label collapsing'>姓名:</td><td>PI:NAME:<NAME>END_PI</td> <td className='label collapsing'>性别:</td><td>男</td> <td className='label collapsing'>年龄:</td><td>33</td> </tr> <tr> <td className='label collapsing'>日期:</td><td>2015-12-08</td> <td className='label collapsing'>就诊号:</td><td>301</td> <td className='label collapsing'>诊疗卡:</td><td>1234567</td> </tr> <tr> <td className='label collapsing'>身高:</td><td>180 cm</td> <td className='label collapsing'>体重:</td><td>70 kg</td> <td className='label collapsing'>血压:</td><td>70/100 mmHg</td> </tr> <tr> <td className='label collapsing top aligned'>既往史:</td><td colSpan='5' className='desc'><span></span></td> </tr> <tr> <td className='label collapsing top aligned'>体质类型:</td><td colSpan='5' className='desc'><span></span></td> </tr> </tbody> </table> <div> <a className='ui labeled icon button back' href='zd-patient-list.html'> <i className='left arrow icon' /> <span>返回患者队列</span> </a> <a className='ui right labeled icon button brown next' href='zd-diagnosis.html'> <i className='right arrow icon' /> <span>进入体检系统</span> </a> </div> </div> </div> </div> @ZDPatientResultPage = React.createClass render: -> <div className='zd-patient-info-page'> <div className='ui container'> <h2 className='ui header topbar'> <TopbarBack href='zd-patient-list.html' /> <span>患者信息</span> </h2> <div className='table-div'> <table className='ui very basic celled table'> <tbody> <tr> <td className='label collapsing'>姓名:</td><td>PI:NAME:<NAME>END_PI</td> <td className='label collapsing'>性别:</td><td>男</td> <td className='label collapsing'>年龄:</td><td>33</td> </tr> <tr> <td className='label collapsing'>日期:</td><td>2015-12-08</td> <td className='label collapsing'>就诊号:</td><td>301</td> <td className='label collapsing'>诊疗卡:</td><td>1234567</td> </tr> </tbody> </table> </div> <div className='table-div'> <div className='record'> <h3 className='ui header'>已检查项目:背诊</h3> </div> <div> <a className='ui labeled icon button back' href='javascript:;'> <i className='icon file' /> <span>查看体检记录</span> </a> <a className='ui right labeled icon button brown next' href='zd-diagnosis.html'> <i className='pencil icon' /> <span>修改体检记录</span> </a> </div> </div> <div className='table-div'> <div className='record'> <h3 className='ui header'>已检查项目:舌诊</h3> </div> <div> <a className='ui labeled icon button back' href='javascript:;'> <i className='icon file' /> <span>查看体检记录</span> </a> <a className='ui right labeled icon button brown next' href='zd-diagnosis.html'> <i className='pencil icon' /> <span>修改体检记录</span> </a> </div> </div> <div className='table-div'> <div> <a className='ui right labeled icon button brown next' href='zd-diagnosis.html'> <i className='plus icon' /> <span>检查其他项目</span> </a> </div> </div> <div className='table-div'> <div> <a className='ui right labeled icon button brown next' href='index.html'> <i className='icon check' /> <span>保存体检结果</span> </a> </div> </div> </div> </div> @ZDPatientResultPage1 = React.createClass render: -> <div className='zd-patient-info-page'> <div className='ui container'> <h2 className='ui header topbar'> <TopbarBack href='doctor-patient-info.html' /> <span>患者信息</span> </h2> <div className='table-div'> <table className='ui very basic celled table'> <tbody> <tr> <td className='label collapsing'>姓名:</td><td>PI:NAME:<NAME>END_PI</td> <td className='label collapsing'>性别:</td><td>男</td> <td className='label collapsing'>年龄:</td><td>33</td> </tr> <tr> <td className='label collapsing'>日期:</td><td>2015-12-08</td> <td className='label collapsing'>就诊号:</td><td>301</td> <td className='label collapsing'>诊疗卡:</td><td>1234567</td> </tr> <tr> <td className='label collapsing'>身高:</td><td>180 cm</td> <td className='label collapsing'>体重:</td><td>70 kg</td> <td className='label collapsing'>血压:</td><td>70/100 mmHg</td> </tr> <tr> <td className='label collapsing top aligned'>既往史:</td><td colSpan='5' className='desc'><span>无</span></td> </tr> <tr> <td className='label collapsing top aligned'>体质类型:</td><td colSpan='5' className='desc'><span>阳虚体质</span></td> </tr> <tr> <td className='label collapsing top aligned'>主诉:</td><td colSpan='5'><span>失眠</span></td> </tr> <tr> <td className='label collapsing top aligned'>初步诊断:</td><td colSpan='5' className='desc'><span>失眠</span></td> </tr> <tr> <td className='label collapsing top aligned'>处理:</td><td colSpan='5' className='desc'> <div>针灸:风池、印堂、神门、三阴交、太溪,平补平泻法,50分钟</div> <div>火罐:心俞、脾俞、内关、神门,单纯拔罐法,10分钟</div> <div>共5次</div> </td> </tr> <tr> <td className='label collapsing top aligned'>医师:</td><td colSpan='5'><span>叶建华</span></td> </tr> </tbody> </table> </div> <div className='table-div'> <div className='record'> <h3 className='ui header'>已检查项目:背诊</h3> </div> <div> <a className='ui labeled icon button back' href='javascript:;'> <i className='icon file' /> <span>查看体检记录</span> </a> </div> </div> <div className='table-div'> <div className='record'> <h3 className='ui header'>已检查项目:舌诊</h3> </div> <div> <a className='ui labeled icon button back' href='javascript:;'> <i className='icon file' /> <span>查看体检记录</span> </a> </div> </div> </div> </div>
[ { "context": ">\n locks = tr.locks ?= {}\n lock_key = fdb.tuple.unpack(subspace.key()).join(':')\n if locks[lock_key]\n ", "end": 370, "score": 0.5226285457611084, "start": 364, "tag": "KEY", "value": "unpack" }, { "context": " {}\n lock_key = fdb.tuple.unpack(subspace.key()).jo...
src/ranked_set.coffee
playlyfe/cockroachdb-leaderboards
0
_ = require 'lodash' Promise = require 'bluebird' fdb = require('fdb').apiVersion(300) xxhash = require 'xxhashjs' # Constants MAX_LEVELS = 6 LEVEL_FAN_POW = 4 levels = [0..MAX_LEVELS - 1] fan_limits = _.map(levels, (level) -> Math.pow(2, level * LEVEL_FAN_POW) - 1) # Private Methods getLock = (tr, subspace) -> locks = tr.locks ?= {} lock_key = fdb.tuple.unpack(subspace.key()).join(':') if locks[lock_key] Promise.reject(new Error("simultaneous writes within single transaction detected on ranked set subspace #{lock_key}")) else locks[lock_key] = true Promise.resolve().disposer () -> delete locks[lock_key] encodeCount = (c) -> value = new Buffer(4) value.writeInt32LE(c, 0) value decodeCount = (v) -> v.readInt32LE(0) get_previous_node = (tr, subspace, level, key) -> k = subspace.pack([level, key]) tr.snapshot.getRange(fdb.KeySelector.lastLessThan(k), fdb.KeySelector.firstGreaterOrEqual(k), { limit: 1}).toArray() .then ([kv]) -> prev_key = subspace.unpack(kv.key)[1] tr.addReadConflictRange(kv.key, k) Promise.resolve(prev_key) slow_count = (tr, subspace, level, begin_key, end_key) -> if level is -1 if begin_key is '' return Promise.resolve(0) else return Promise.resolve(1) sum = 0 tr.getRange(subspace.pack([level, begin_key]), subspace.pack([level, end_key])).forEach((pair, callback) -> sum += decodeCount(pair.value) callback() ).then -> Promise.resolve(sum) _rank = (tr, subspace, key, level, result) -> level_ss = subspace.subspace([level]) last_count = 0 _defer = Promise.defer() tr.getRange(level_ss.pack([result.rank_key]), fdb.KeySelector.firstGreaterThan(level_ss.pack([key]))).forEach((pair, callback) -> result.rank_key = level_ss.unpack(pair.key)[0] last_count = decodeCount(pair.value) result.r += last_count callback() , (err) -> if err then _defer.reject(err) else result.r -= last_count if result.rank_key is key or level < 0 _defer.resolve() else _defer.resolve(_rank(tr, subspace, key, level - 1, result)) ) _defer.promise _getNth = (tr, subspace, level, result) -> level_ss = subspace.subspace([level]) tr.getRange(level_ss.pack([result.key]), level_ss.range().end).toArray() .then (pairs) -> for pair in pairs result.key = level_ss.unpack(pair.key)[0] count = decodeCount(pair.value) if result.key isnt '' and result.key isnt null and result.r is 0 return Promise.resolve() if count > result.r break result.r -= count if pairs.length is 0 or level is 0 Promise.resolve(null) else Promise.resolve(_getNth(tr, subspace, level - 1, result)) # Public Methods create = (tr, subspace) -> # Setup levels queue = [] _.forEach levels, (level) -> level_ss = subspace.pack([level, '']) queue.push tr.get(level_ss).then (result) -> if not result? tr.set(level_ss, encodeCount(0)) Promise.resolve() Promise.all(queue) rank = (tr, subspace, key) -> if key is '' or key is null throw new Error('Empty key not allowed in set') contains(tr, subspace, key) .then (is_present) -> if not is_present Promise.resolve(null) else result = { r: 0, rank_key: '' } _rank(tr, subspace, key, MAX_LEVELS, result).then -> Promise.resolve(result.r) getNth = (tr, subspace, rank) -> if rank < 0 Promise.resolve(null) result = { r: rank, key: '' } _getNth(tr, subspace, MAX_LEVELS - 1, result) .then -> Promise.resolve(result.key) getRange = (tr, subspace, start_key, end_key) -> if start_key is '' or start_key is null throw new Error('Empty key not allowed in set') tr.getRange(subspace.pack([0, start_key]), subspace.pack([0, end_key])).toArray() .then (result) -> items = [] for pair in result items.push subspace.unpack(pair.key)[1] Promise.resolve(items) contains = (tr, subspace, key) -> if key is '' or key is null throw new Error('Empty key not allowed in set') tr.get(subspace.pack([0, key])).then (result) -> Promise.resolve(result isnt null) insert = (tr, subspace, key) -> contains(tr, subspace, key) .then (is_present) -> if is_present Promise.resolve(key) else Promise.using(getLock(tr, subspace), () -> # We assume the key is an integer hash = Math.abs(xxhash(key.toString(), 11235813).toNumber()) Promise.reduce(levels, (total, level) -> get_previous_node(tr, subspace, level, key).then (prev_key) -> if hash & fan_limits[level] Promise.resolve(tr.add(subspace.pack([level, prev_key]), encodeCount(1))) else Promise.all([ tr.get(subspace.pack([level, prev_key])) slow_count(tr, subspace, level - 1, prev_key, key) ]).spread (_prev_count, _count) -> prev_count = decodeCount(_prev_count) new_prev_count = _count count = prev_count - new_prev_count + 1 tr.set(subspace.pack([level, prev_key]), encodeCount(new_prev_count)) tr.set(subspace.pack([level, key]), encodeCount(count)) Promise.resolve() , 0) ) upsert = (tr, subspace, key) -> contains(tr, subspace, key) .then (is_present) -> if is_present Promise.resolve(key) else Promise.using(getLock(tr, subspace), () -> # We assume the key is an integer hash = Math.abs(xxhash(key.toString(), 11235813).toNumber()) Promise.reduce(levels, (total, level) -> get_previous_node(tr, subspace, level, key).then (prev_key) -> if hash & fan_limits[level] Promise.resolve(tr.add(subspace.pack([level, prev_key]), encodeCount(1))) else Promise.all([ tr.get(subspace.pack([level, prev_key])) slow_count(tr, subspace, level - 1, prev_key, key) ]).spread (_prev_count, _count) -> prev_count = decodeCount(_prev_count) new_prev_count = _count count = prev_count - new_prev_count + 1 tr.set(subspace.pack([level, prev_key]), encodeCount(new_prev_count)) tr.set(subspace.pack([level, key]), encodeCount(count)) Promise.resolve() , 0) ) remove = (tr, subspace, key) -> contains(tr, subspace, key) .then (is_present) -> if not is_present Promise.resolve() else Promise.using(getLock(tr, subspace), () -> Promise.reduce(levels, (total, level) -> k = subspace.pack([level, key]) tr.get(k).then (c) -> if c isnt null tr.clear(k) if level is 0 return Promise.resolve() get_previous_node(tr, subspace, level, key).then (prev_key) -> if prev_key is key throw Error("key #{key} is same as previous key #{prev_key}") count_change = -1 if c isnt null count_change += decodeCount(c) tr.add(subspace.pack([level, prev_key]), encodeCount(count_change)) , 0) ) clear = (tr, subspace, key) -> range = subspace.range() tr.clearRange(range.begin, range.end) create(tr, subspace) print = (tr, subspace) -> range = subspace.range([]) range_total = 0 current_range = 0 tr.getRange(range.begin, range.end).forEach((item, callback) -> path = subspace.unpack(item.key) console.log "#{path} = #{decodeCount(item.value)}" if path[0] is current_range range_total += decodeCount(item.value) else range_total = decodeCount(item.value) current_range = path[0] callback() ) module.exports = { create: create insert: insert contains: contains remove: remove clear: clear rank: rank getNth: getNth getRange: getRange print: print }
29268
_ = require 'lodash' Promise = require 'bluebird' fdb = require('fdb').apiVersion(300) xxhash = require 'xxhashjs' # Constants MAX_LEVELS = 6 LEVEL_FAN_POW = 4 levels = [0..MAX_LEVELS - 1] fan_limits = _.map(levels, (level) -> Math.pow(2, level * LEVEL_FAN_POW) - 1) # Private Methods getLock = (tr, subspace) -> locks = tr.locks ?= {} lock_key = fdb.tuple.<KEY>(subspace.key()).<KEY>(':') if locks[lock_key] Promise.reject(new Error("simultaneous writes within single transaction detected on ranked set subspace #{lock_key}")) else locks[lock_key] = true Promise.resolve().disposer () -> delete locks[lock_key] encodeCount = (c) -> value = new Buffer(4) value.writeInt32LE(c, 0) value decodeCount = (v) -> v.readInt32LE(0) get_previous_node = (tr, subspace, level, key) -> k = subspace.pack([level, key]) tr.snapshot.getRange(fdb.KeySelector.lastLessThan(k), fdb.KeySelector.firstGreaterOrEqual(k), { limit: 1}).toArray() .then ([kv]) -> prev_key = subspace.unpack(kv.key)[1] tr.addReadConflictRange(kv.key, k) Promise.resolve(prev_key) slow_count = (tr, subspace, level, begin_key, end_key) -> if level is -1 if begin_key is '' return Promise.resolve(0) else return Promise.resolve(1) sum = 0 tr.getRange(subspace.pack([level, begin_key]), subspace.pack([level, end_key])).forEach((pair, callback) -> sum += decodeCount(pair.value) callback() ).then -> Promise.resolve(sum) _rank = (tr, subspace, key, level, result) -> level_ss = subspace.subspace([level]) last_count = 0 _defer = Promise.defer() tr.getRange(level_ss.pack([result.rank_key]), fdb.KeySelector.firstGreaterThan(level_ss.pack([key]))).forEach((pair, callback) -> result.rank_key = level_ss.unpack(pair.key)[0] last_count = decodeCount(pair.value) result.r += last_count callback() , (err) -> if err then _defer.reject(err) else result.r -= last_count if result.rank_key is key or level < 0 _defer.resolve() else _defer.resolve(_rank(tr, subspace, key, level - 1, result)) ) _defer.promise _getNth = (tr, subspace, level, result) -> level_ss = subspace.subspace([level]) tr.getRange(level_ss.pack([result.key]), level_ss.range().end).toArray() .then (pairs) -> for pair in pairs result.key = level_ss.unpack(pair.key)[0] count = decodeCount(pair.value) if result.key isnt '' and result.key isnt null and result.r is 0 return Promise.resolve() if count > result.r break result.r -= count if pairs.length is 0 or level is 0 Promise.resolve(null) else Promise.resolve(_getNth(tr, subspace, level - 1, result)) # Public Methods create = (tr, subspace) -> # Setup levels queue = [] _.forEach levels, (level) -> level_ss = subspace.pack([level, '']) queue.push tr.get(level_ss).then (result) -> if not result? tr.set(level_ss, encodeCount(0)) Promise.resolve() Promise.all(queue) rank = (tr, subspace, key) -> if key is '' or key is null throw new Error('Empty key not allowed in set') contains(tr, subspace, key) .then (is_present) -> if not is_present Promise.resolve(null) else result = { r: 0, rank_key: '' } _rank(tr, subspace, key, MAX_LEVELS, result).then -> Promise.resolve(result.r) getNth = (tr, subspace, rank) -> if rank < 0 Promise.resolve(null) result = { r: rank, key: '' } _getNth(tr, subspace, MAX_LEVELS - 1, result) .then -> Promise.resolve(result.key) getRange = (tr, subspace, start_key, end_key) -> if start_key is '' or start_key is null throw new Error('Empty key not allowed in set') tr.getRange(subspace.pack([0, start_key]), subspace.pack([0, end_key])).toArray() .then (result) -> items = [] for pair in result items.push subspace.unpack(pair.key)[1] Promise.resolve(items) contains = (tr, subspace, key) -> if key is '' or key is null throw new Error('Empty key not allowed in set') tr.get(subspace.pack([0, key])).then (result) -> Promise.resolve(result isnt null) insert = (tr, subspace, key) -> contains(tr, subspace, key) .then (is_present) -> if is_present Promise.resolve(key) else Promise.using(getLock(tr, subspace), () -> # We assume the key is an integer hash = Math.abs(xxhash(key.toString(), 11235813).toNumber()) Promise.reduce(levels, (total, level) -> get_previous_node(tr, subspace, level, key).then (prev_key) -> if hash & fan_limits[level] Promise.resolve(tr.add(subspace.pack([level, prev_key]), encodeCount(1))) else Promise.all([ tr.get(subspace.pack([level, prev_key])) slow_count(tr, subspace, level - 1, prev_key, key) ]).spread (_prev_count, _count) -> prev_count = decodeCount(_prev_count) new_prev_count = _count count = prev_count - new_prev_count + 1 tr.set(subspace.pack([level, prev_key]), encodeCount(new_prev_count)) tr.set(subspace.pack([level, key]), encodeCount(count)) Promise.resolve() , 0) ) upsert = (tr, subspace, key) -> contains(tr, subspace, key) .then (is_present) -> if is_present Promise.resolve(key) else Promise.using(getLock(tr, subspace), () -> # We assume the key is an integer hash = Math.abs(xxhash(key.toString(), 11235813).toNumber()) Promise.reduce(levels, (total, level) -> get_previous_node(tr, subspace, level, key).then (prev_key) -> if hash & fan_limits[level] Promise.resolve(tr.add(subspace.pack([level, prev_key]), encodeCount(1))) else Promise.all([ tr.get(subspace.pack([level, prev_key])) slow_count(tr, subspace, level - 1, prev_key, key) ]).spread (_prev_count, _count) -> prev_count = decodeCount(_prev_count) new_prev_count = _count count = prev_count - new_prev_count + 1 tr.set(subspace.pack([level, prev_key]), encodeCount(new_prev_count)) tr.set(subspace.pack([level, key]), encodeCount(count)) Promise.resolve() , 0) ) remove = (tr, subspace, key) -> contains(tr, subspace, key) .then (is_present) -> if not is_present Promise.resolve() else Promise.using(getLock(tr, subspace), () -> Promise.reduce(levels, (total, level) -> k = subspace.pack([level, key]) tr.get(k).then (c) -> if c isnt null tr.clear(k) if level is 0 return Promise.resolve() get_previous_node(tr, subspace, level, key).then (prev_key) -> if prev_key is key throw Error("key #{key} is same as previous key #{prev_key}") count_change = -1 if c isnt null count_change += decodeCount(c) tr.add(subspace.pack([level, prev_key]), encodeCount(count_change)) , 0) ) clear = (tr, subspace, key) -> range = subspace.range() tr.clearRange(range.begin, range.end) create(tr, subspace) print = (tr, subspace) -> range = subspace.range([]) range_total = 0 current_range = 0 tr.getRange(range.begin, range.end).forEach((item, callback) -> path = subspace.unpack(item.key) console.log "#{path} = #{decodeCount(item.value)}" if path[0] is current_range range_total += decodeCount(item.value) else range_total = decodeCount(item.value) current_range = path[0] callback() ) module.exports = { create: create insert: insert contains: contains remove: remove clear: clear rank: rank getNth: getNth getRange: getRange print: print }
true
_ = require 'lodash' Promise = require 'bluebird' fdb = require('fdb').apiVersion(300) xxhash = require 'xxhashjs' # Constants MAX_LEVELS = 6 LEVEL_FAN_POW = 4 levels = [0..MAX_LEVELS - 1] fan_limits = _.map(levels, (level) -> Math.pow(2, level * LEVEL_FAN_POW) - 1) # Private Methods getLock = (tr, subspace) -> locks = tr.locks ?= {} lock_key = fdb.tuple.PI:KEY:<KEY>END_PI(subspace.key()).PI:KEY:<KEY>END_PI(':') if locks[lock_key] Promise.reject(new Error("simultaneous writes within single transaction detected on ranked set subspace #{lock_key}")) else locks[lock_key] = true Promise.resolve().disposer () -> delete locks[lock_key] encodeCount = (c) -> value = new Buffer(4) value.writeInt32LE(c, 0) value decodeCount = (v) -> v.readInt32LE(0) get_previous_node = (tr, subspace, level, key) -> k = subspace.pack([level, key]) tr.snapshot.getRange(fdb.KeySelector.lastLessThan(k), fdb.KeySelector.firstGreaterOrEqual(k), { limit: 1}).toArray() .then ([kv]) -> prev_key = subspace.unpack(kv.key)[1] tr.addReadConflictRange(kv.key, k) Promise.resolve(prev_key) slow_count = (tr, subspace, level, begin_key, end_key) -> if level is -1 if begin_key is '' return Promise.resolve(0) else return Promise.resolve(1) sum = 0 tr.getRange(subspace.pack([level, begin_key]), subspace.pack([level, end_key])).forEach((pair, callback) -> sum += decodeCount(pair.value) callback() ).then -> Promise.resolve(sum) _rank = (tr, subspace, key, level, result) -> level_ss = subspace.subspace([level]) last_count = 0 _defer = Promise.defer() tr.getRange(level_ss.pack([result.rank_key]), fdb.KeySelector.firstGreaterThan(level_ss.pack([key]))).forEach((pair, callback) -> result.rank_key = level_ss.unpack(pair.key)[0] last_count = decodeCount(pair.value) result.r += last_count callback() , (err) -> if err then _defer.reject(err) else result.r -= last_count if result.rank_key is key or level < 0 _defer.resolve() else _defer.resolve(_rank(tr, subspace, key, level - 1, result)) ) _defer.promise _getNth = (tr, subspace, level, result) -> level_ss = subspace.subspace([level]) tr.getRange(level_ss.pack([result.key]), level_ss.range().end).toArray() .then (pairs) -> for pair in pairs result.key = level_ss.unpack(pair.key)[0] count = decodeCount(pair.value) if result.key isnt '' and result.key isnt null and result.r is 0 return Promise.resolve() if count > result.r break result.r -= count if pairs.length is 0 or level is 0 Promise.resolve(null) else Promise.resolve(_getNth(tr, subspace, level - 1, result)) # Public Methods create = (tr, subspace) -> # Setup levels queue = [] _.forEach levels, (level) -> level_ss = subspace.pack([level, '']) queue.push tr.get(level_ss).then (result) -> if not result? tr.set(level_ss, encodeCount(0)) Promise.resolve() Promise.all(queue) rank = (tr, subspace, key) -> if key is '' or key is null throw new Error('Empty key not allowed in set') contains(tr, subspace, key) .then (is_present) -> if not is_present Promise.resolve(null) else result = { r: 0, rank_key: '' } _rank(tr, subspace, key, MAX_LEVELS, result).then -> Promise.resolve(result.r) getNth = (tr, subspace, rank) -> if rank < 0 Promise.resolve(null) result = { r: rank, key: '' } _getNth(tr, subspace, MAX_LEVELS - 1, result) .then -> Promise.resolve(result.key) getRange = (tr, subspace, start_key, end_key) -> if start_key is '' or start_key is null throw new Error('Empty key not allowed in set') tr.getRange(subspace.pack([0, start_key]), subspace.pack([0, end_key])).toArray() .then (result) -> items = [] for pair in result items.push subspace.unpack(pair.key)[1] Promise.resolve(items) contains = (tr, subspace, key) -> if key is '' or key is null throw new Error('Empty key not allowed in set') tr.get(subspace.pack([0, key])).then (result) -> Promise.resolve(result isnt null) insert = (tr, subspace, key) -> contains(tr, subspace, key) .then (is_present) -> if is_present Promise.resolve(key) else Promise.using(getLock(tr, subspace), () -> # We assume the key is an integer hash = Math.abs(xxhash(key.toString(), 11235813).toNumber()) Promise.reduce(levels, (total, level) -> get_previous_node(tr, subspace, level, key).then (prev_key) -> if hash & fan_limits[level] Promise.resolve(tr.add(subspace.pack([level, prev_key]), encodeCount(1))) else Promise.all([ tr.get(subspace.pack([level, prev_key])) slow_count(tr, subspace, level - 1, prev_key, key) ]).spread (_prev_count, _count) -> prev_count = decodeCount(_prev_count) new_prev_count = _count count = prev_count - new_prev_count + 1 tr.set(subspace.pack([level, prev_key]), encodeCount(new_prev_count)) tr.set(subspace.pack([level, key]), encodeCount(count)) Promise.resolve() , 0) ) upsert = (tr, subspace, key) -> contains(tr, subspace, key) .then (is_present) -> if is_present Promise.resolve(key) else Promise.using(getLock(tr, subspace), () -> # We assume the key is an integer hash = Math.abs(xxhash(key.toString(), 11235813).toNumber()) Promise.reduce(levels, (total, level) -> get_previous_node(tr, subspace, level, key).then (prev_key) -> if hash & fan_limits[level] Promise.resolve(tr.add(subspace.pack([level, prev_key]), encodeCount(1))) else Promise.all([ tr.get(subspace.pack([level, prev_key])) slow_count(tr, subspace, level - 1, prev_key, key) ]).spread (_prev_count, _count) -> prev_count = decodeCount(_prev_count) new_prev_count = _count count = prev_count - new_prev_count + 1 tr.set(subspace.pack([level, prev_key]), encodeCount(new_prev_count)) tr.set(subspace.pack([level, key]), encodeCount(count)) Promise.resolve() , 0) ) remove = (tr, subspace, key) -> contains(tr, subspace, key) .then (is_present) -> if not is_present Promise.resolve() else Promise.using(getLock(tr, subspace), () -> Promise.reduce(levels, (total, level) -> k = subspace.pack([level, key]) tr.get(k).then (c) -> if c isnt null tr.clear(k) if level is 0 return Promise.resolve() get_previous_node(tr, subspace, level, key).then (prev_key) -> if prev_key is key throw Error("key #{key} is same as previous key #{prev_key}") count_change = -1 if c isnt null count_change += decodeCount(c) tr.add(subspace.pack([level, prev_key]), encodeCount(count_change)) , 0) ) clear = (tr, subspace, key) -> range = subspace.range() tr.clearRange(range.begin, range.end) create(tr, subspace) print = (tr, subspace) -> range = subspace.range([]) range_total = 0 current_range = 0 tr.getRange(range.begin, range.end).forEach((item, callback) -> path = subspace.unpack(item.key) console.log "#{path} = #{decodeCount(item.value)}" if path[0] is current_range range_total += decodeCount(item.value) else range_total = decodeCount(item.value) current_range = path[0] callback() ) module.exports = { create: create insert: insert contains: contains remove: remove clear: clear rank: rank getNth: getNth getRange: getRange print: print }
[ { "context": "st\n @exchange.publish TEST_ROUTING_KEY, 'my-test-message-1'\n @exchange.publish TEST_ROUTING_KEY, 'm", "end": 2737, "score": 0.9988522529602051, "start": 2720, "tag": "KEY", "value": "my-test-message-1" }, { "context": "1'\n @exchange.publish...
test/test-amqp-consumer.coffee
intellinote/amqp-util
1
amqp = require 'amqp' should = require 'should' assert = require 'assert' fs = require 'fs' path = require 'path' HOMEDIR = path.join(__dirname,'..') LIB_COV = path.join(HOMEDIR,'lib-cov') LIB = path.join(HOMEDIR,'lib') LIB_DIR = if fs.existsSync(LIB_COV) then LIB_COV else LIB AmqpConsumer = require(path.join(LIB_DIR,'amqp-consumer')).AmqpConsumer AMQPJSONConsumer = require(path.join(LIB_DIR,'amqp-consumer')).AMQPJSONConsumer AMQPStringConsumer = require(path.join(LIB_DIR,'amqp-consumer')).AMQPStringConsumer config = require('inote-util').config.init({},{NODE_ENV:'unit-testing'}) TEST_BROKER = config.get 'amqp:unit-test:broker' TEST_QUEUE = config.get 'amqp:unit-test:queue' TEST_QUEUE_2 = TEST_QUEUE + ":2" TEST_QUEUE_OPTIONS = config.get 'amqp:unit-test:queue-options' TEST_EXCHANGE = config.get 'amqp:unit-test:exchange' TEST_EXCHANGE_OPTIONS = config.get 'amqp:unit-test:exchange-options' TEST_ROUTING_KEY = config.get 'amqp:unit-test:routing-key' describe 'AmqpConsumer',-> beforeEach (done)=> @connection = amqp.createConnection({url:TEST_BROKER}) @connection.once 'ready', ()=> @exchange = @connection?.exchange TEST_EXCHANGE, TEST_EXCHANGE_OPTIONS, ()=> done() afterEach (done)=> @exchange?.destroy(false) @exchange = null @connection?.end() @connection = null done() it 'can accept published messages',(done)=> received_count = 0 amqpc = new AmqpConsumer() subscription_tag = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.get_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info)=> received_count += 1 message.data.toString().should.equal "my-test-message-#{received_count}" if received_count is 3 amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err amqpc.unbind_queue_from_exchange TEST_QUEUE, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err amqpc.destroy_queue TEST_QUEUE, ()=> amqpc.disconnect ()=> done() else received_count.should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st @exchange.publish TEST_ROUTING_KEY, 'my-test-message-1' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-2' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-3' it 'can resolve consumerTag name changes',(done)=> received_count = 0 amqpc = new AmqpConsumer() subscription_tag = null fake_tag_found = false amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.get_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info)=> received_count += 1 message.data.toString().should.equal "my-test-message-#{received_count}" if received_count is 3 amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err assert fake_tag_found amqpc.unbind_queue_from_exchange TEST_QUEUE, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err amqpc.destroy_queue TEST_QUEUE, ()=> amqpc.disconnect ()=> done() else received_count.should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st new_tag = "the-new-consumer-tag-#{Date.now()}" # override queue.unsubscribe to confirm the that mock-renamed tag is passed queue._old_unsubscribe = queue.unsubscribe queue.unsubscribe = (tag_name, tail...)=> assert.equal tag_name, new_tag fake_tag_found = true tag_name = subscription_tag queue._old_unsubscribe tag_name, tail... # amqpc.connection.emit "tag.change", {oldConsumerTag:subscription_tag,consumerTag:new_tag} assert.equal amqpc._resolve_subscription_tag_alias(subscription_tag)[0], new_tag @exchange.publish TEST_ROUTING_KEY, 'my-test-message-1' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-2' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-3' it 'allows subscription options in subscribe call',(done)=> received_count = 0 amqpc = new AmqpConsumer() subscription_tag = null the_queue = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info)=> received_count += 1 message.data.toString().should.equal "my-test-message-#{received_count}" if received_count is 3 amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err amqpc.destroy_queue the_queue, ()=> amqpc.disconnect ()=> done() else received_count.should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE, {exclusive:true}, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? the_queue = queue subscription_tag = st @exchange.publish TEST_ROUTING_KEY, 'my-test-message-1' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-2' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-3' it 'can accept a JSON-valued message as a JSON object',(done)=> amqpc = new AmqpConsumer() subscription_tag = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info, raw)=> message.foo.should.equal 'bar' message.a.should.equal 1 info.contentType.should.equal 'application/json' should.exist raw amqpc.unsubscribe_from_queue subscription_tag, (err)-> amqpc.disconnect ()=> done() amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st @exchange.publish TEST_ROUTING_KEY, { foo:'bar', a:1 } it 'AMQPJSONConsumer can accept a JSON-valued message as a JSON object',(done)=> amqpc = new AmqpConsumer() subscription_tag = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info, raw)=> message.foo.should.equal 'bar' message.a.should.equal 1 info.contentType.should.equal 'application/json' should.exist raw amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st @exchange.publish TEST_ROUTING_KEY, { foo:'bar', a:1 } it 'AMQPStringConsumer can accept a Buffer-valued message as a String',(done)=> amqpc = new AMQPStringConsumer() subscription_tag = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info, raw)=> message.should.equal "The quick brown fox jumped." amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st @exchange.publish TEST_ROUTING_KEY, "The quick brown fox jumped." it 'supports a payload converter for transforming messages before they are consumed',(done)=> amqpc = new AMQPJSONConsumer() amqpc.message_converter = (message)->message.data.toString().toUpperCase() subscription_tag = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info, raw)=> message.should.equal "THE QUICK BROWN FOX JUMPED." amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st @exchange.publish TEST_ROUTING_KEY, "the quick brown fox jumped." # in this case we have multiple subscribers on top of a single queue; each message is sent to one or the other subscriber but not both it 'can create multiple subscription channels on top of a single queue and single connection (create-queue+subscribe-to-queue case)',(done)=> handler1_received_count = 0 handler2_received_count = 0 amqpc = new AmqpConsumer() subscription_tag1 = null subscription_tag2 = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler1 = (message,headers,info)=> handler1_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count + handler2_received_count)}" if (handler1_received_count + handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag1, (err)-> assert.ok not err?, err amqpc.unsubscribe_from_queue subscription_tag2, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() else (handler1_received_count + handler2_received_count).should.not.be.above 3 handler2 = (message,headers,info)=> handler2_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count + handler2_received_count)}" if (handler1_received_count + handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag2, (err)-> assert.ok not err?, err amqpc.unsubscribe_from_queue subscription_tag1, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() else (handler1_received_count + handler2_received_count).should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE, handler1, (err, queue, queue_name, st1)=> assert.ok not err?, err assert.ok st1? subscription_tag1 = st1 amqpc.subscribe_to_queue TEST_QUEUE, handler2, (err, queue, queue_name, st2)=> assert.ok not err?, err assert.ok st2? subscription_tag2 = st2 @exchange.publish TEST_ROUTING_KEY, 'my-test-message-1' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-2' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-3' # in this case we have multiple subscribers on top of a single queue; each message is sent to one or the other subscriber but not both it 'can create multiple subscription channels on top of a single queue and single connection (create-queue-during-subscribe case)',(done)=> handler1_received_count = 0 handler2_received_count = 0 amqpc = new AmqpConsumer() subscription_tag1 = null subscription_tag2 = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err handler1 = (message,headers,info)=> handler1_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count + handler2_received_count)}" if (handler1_received_count + handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag1, (err)-> assert.ok not err?, err amqpc.unsubscribe_from_queue subscription_tag2, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() else (handler1_received_count + handler2_received_count).should.not.be.above 3 amqpc.subscribe TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler1, (err, queue1, queue_name1, st1)=> assert.ok not err?, err assert.ok queue1? assert.ok queue_name1? assert.ok st1? subscription_tag1 = st1 # handler2 = (message,headers,info)=> handler2_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count + handler2_received_count)}" if (handler1_received_count + handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag2, (err)-> assert.ok not err?, err amqpc.unsubscribe_from_queue subscription_tag1, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() else (handler1_received_count + handler2_received_count).should.not.be.above 3 amqpc.subscribe TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler2, (err, queue2, queue_name2, st2)=> assert.ok not err?, err assert.ok queue2? assert.ok queue_name2? assert.ok queue_name2 is queue_name1 assert.ok st2? assert.ok st2 isnt st1 subscription_tag2 = st2 # @exchange.publish TEST_ROUTING_KEY, 'my-test-message-1' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-2' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-3' # in this case we have multiple QUEUES on top of a single connection; each message is sent to both subscribers it 'can create multiple queues on top of a single connection (create-queue+subscribe-to-queue case)', (done)=> handler1_received_count = 0 handler2_received_count = 0 amqpc = new AmqpConsumer() subscription_tag1 = null subscription_tag2 = null handler1_done = false handler2_done = false amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler1 = (message,headers,info)=> handler1_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count)}" if (handler1_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag1, (err)-> handler1_done = true assert.ok not err?, err if handler2_done assert.ok not err?, err amqpc.disconnect ()=> done() else (handler1_received_count).should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE, handler1, (err, queue, queue_name, st1)=> assert.ok not err?, err assert.ok st1? subscription_tag1 = st1 # amqpc.create_queue TEST_QUEUE_2, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler2 = (message,headers,info)=> handler2_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler2_received_count)}" if (handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag2, (err)-> handler2_done = true assert.ok not err?, err if handler1_done amqpc.disconnect ()=> done() else (handler2_received_count).should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE_2, handler2, (err, queue, queue_name, st2)=> assert.ok not err?, err assert.ok st2? subscription_tag2 = st2 @exchange.publish TEST_ROUTING_KEY, 'my-test-message-1' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-2' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-3' # in this case we have multiple QUEUES on top of a single connection; each message is sent to both subscribers it 'can create multiple queues on top of a single connection (create-queue-during-subscribe case)',(done)=> handler1_received_count = 0 handler2_received_count = 0 amqpc = new AmqpConsumer() subscription_tag1 = null subscription_tag2 = null handler1_done = false handler2_done = false amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err handler1 = (message, headers, info)=> handler1_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count)}" if (handler1_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag1, (err)=> handler1_done = true assert.ok not err?, err if handler2_done amqpc.disconnect ()=> done() else (handler1_received_count).should.not.be.above 3 amqpc.subscribe TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler1, (err, queue1, queue_name1, st1)=> assert.ok not err?, err assert.ok queue1? assert.ok queue_name1? assert.ok st1? subscription_tag1 = st1 # handler2 = (message, headers, info)=> handler2_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler2_received_count)}" if (handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag2, (err)=> handler2_done = true assert.ok not err?, err if handler1_done amqpc.disconnect ()=> done() else (handler2_received_count).should.not.be.above 3 amqpc.subscribe TEST_QUEUE_2, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler2, (err, queue2, queue_name2, st2)=> assert.ok not err?, err assert.ok queue2? assert.ok queue_name2? assert.ok queue_name2 isnt queue_name1 assert.ok st2? assert.ok st2 isnt st1 subscription_tag2 = st2 # @exchange.publish TEST_ROUTING_KEY, 'my-test-message-1' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-2' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-3' # in this case we have multiple QUEUES on top of a single connection; each message is sent to both subscribers it 'can create multiple queues on top of a single connection (create-queue-during-subscribe with null name case)',(done)=> handler1_received_count = 0 handler2_received_count = 0 amqpc = new AmqpConsumer() subscription_tag1 = null subscription_tag2 = null handler1_done = false handler2_done = false amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err handler1 = (message, headers, info)=> handler1_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count)}" if (handler1_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag1, (err)=> handler1_done = true assert.ok not err?, err if handler2_done amqpc.disconnect ()=> done() else (handler1_received_count).should.not.be.above 3 amqpc.subscribe undefined, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler1, (err, queue1, queue_name1, st1)=> assert.ok not err?, err assert.ok queue1? assert.ok queue_name1? assert.ok st1? subscription_tag1 = st1 # handler2 = (message, headers, info)=> handler2_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler2_received_count)}" if (handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag2, (err)=> handler2_done = true assert.ok not err?, err if handler1_done amqpc.disconnect ()=> done() else (handler2_received_count).should.not.be.above 3 amqpc.subscribe undefined, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler2, (err, queue2, queue_name2, st2)=> assert.ok not err?, err assert.ok queue2? assert.ok queue_name2? assert.ok queue_name2 isnt queue_name1 assert.ok st2? assert.ok st2 isnt st1 subscription_tag2 = st2 # @exchange.publish TEST_ROUTING_KEY, 'my-test-message-1' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-2' @exchange.publish TEST_ROUTING_KEY, 'my-test-message-3'
118218
amqp = require 'amqp' should = require 'should' assert = require 'assert' fs = require 'fs' path = require 'path' HOMEDIR = path.join(__dirname,'..') LIB_COV = path.join(HOMEDIR,'lib-cov') LIB = path.join(HOMEDIR,'lib') LIB_DIR = if fs.existsSync(LIB_COV) then LIB_COV else LIB AmqpConsumer = require(path.join(LIB_DIR,'amqp-consumer')).AmqpConsumer AMQPJSONConsumer = require(path.join(LIB_DIR,'amqp-consumer')).AMQPJSONConsumer AMQPStringConsumer = require(path.join(LIB_DIR,'amqp-consumer')).AMQPStringConsumer config = require('inote-util').config.init({},{NODE_ENV:'unit-testing'}) TEST_BROKER = config.get 'amqp:unit-test:broker' TEST_QUEUE = config.get 'amqp:unit-test:queue' TEST_QUEUE_2 = TEST_QUEUE + ":2" TEST_QUEUE_OPTIONS = config.get 'amqp:unit-test:queue-options' TEST_EXCHANGE = config.get 'amqp:unit-test:exchange' TEST_EXCHANGE_OPTIONS = config.get 'amqp:unit-test:exchange-options' TEST_ROUTING_KEY = config.get 'amqp:unit-test:routing-key' describe 'AmqpConsumer',-> beforeEach (done)=> @connection = amqp.createConnection({url:TEST_BROKER}) @connection.once 'ready', ()=> @exchange = @connection?.exchange TEST_EXCHANGE, TEST_EXCHANGE_OPTIONS, ()=> done() afterEach (done)=> @exchange?.destroy(false) @exchange = null @connection?.end() @connection = null done() it 'can accept published messages',(done)=> received_count = 0 amqpc = new AmqpConsumer() subscription_tag = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.get_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info)=> received_count += 1 message.data.toString().should.equal "my-test-message-#{received_count}" if received_count is 3 amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err amqpc.unbind_queue_from_exchange TEST_QUEUE, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err amqpc.destroy_queue TEST_QUEUE, ()=> amqpc.disconnect ()=> done() else received_count.should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>' it 'can resolve consumerTag name changes',(done)=> received_count = 0 amqpc = new AmqpConsumer() subscription_tag = null fake_tag_found = false amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.get_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info)=> received_count += 1 message.data.toString().should.equal "my-test-message-#{received_count}" if received_count is 3 amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err assert fake_tag_found amqpc.unbind_queue_from_exchange TEST_QUEUE, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err amqpc.destroy_queue TEST_QUEUE, ()=> amqpc.disconnect ()=> done() else received_count.should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st new_tag = "the-new-consumer-tag-#{Date.now()}" # override queue.unsubscribe to confirm the that mock-renamed tag is passed queue._old_unsubscribe = queue.unsubscribe queue.unsubscribe = (tag_name, tail...)=> assert.equal tag_name, new_tag fake_tag_found = true tag_name = subscription_tag queue._old_unsubscribe tag_name, tail... # amqpc.connection.emit "tag.change", {oldConsumerTag:subscription_tag,consumerTag:new_tag} assert.equal amqpc._resolve_subscription_tag_alias(subscription_tag)[0], new_tag @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>' it 'allows subscription options in subscribe call',(done)=> received_count = 0 amqpc = new AmqpConsumer() subscription_tag = null the_queue = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info)=> received_count += 1 message.data.toString().should.equal "my-test-message-#{received_count}" if received_count is 3 amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err amqpc.destroy_queue the_queue, ()=> amqpc.disconnect ()=> done() else received_count.should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE, {exclusive:true}, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? the_queue = queue subscription_tag = st @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>' it 'can accept a JSON-valued message as a JSON object',(done)=> amqpc = new AmqpConsumer() subscription_tag = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info, raw)=> message.foo.should.equal 'bar' message.a.should.equal 1 info.contentType.should.equal 'application/json' should.exist raw amqpc.unsubscribe_from_queue subscription_tag, (err)-> amqpc.disconnect ()=> done() amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st @exchange.publish TEST_ROUTING_KEY, { foo:'bar', a:1 } it 'AMQPJSONConsumer can accept a JSON-valued message as a JSON object',(done)=> amqpc = new AmqpConsumer() subscription_tag = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info, raw)=> message.foo.should.equal 'bar' message.a.should.equal 1 info.contentType.should.equal 'application/json' should.exist raw amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st @exchange.publish TEST_ROUTING_KEY, { foo:'bar', a:1 } it 'AMQPStringConsumer can accept a Buffer-valued message as a String',(done)=> amqpc = new AMQPStringConsumer() subscription_tag = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info, raw)=> message.should.equal "The quick brown fox jumped." amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st @exchange.publish TEST_ROUTING_KEY, "<KEY> it 'supports a payload converter for transforming messages before they are consumed',(done)=> amqpc = new AMQPJSONConsumer() amqpc.message_converter = (message)->message.data.toString().toUpperCase() subscription_tag = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info, raw)=> message.should.equal "THE QUICK BROWN FOX JUMPED." amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st @exchange.publish TEST_ROUTING_KEY, "<KEY>." # in this case we have multiple subscribers on top of a single queue; each message is sent to one or the other subscriber but not both it 'can create multiple subscription channels on top of a single queue and single connection (create-queue+subscribe-to-queue case)',(done)=> handler1_received_count = 0 handler2_received_count = 0 amqpc = new AmqpConsumer() subscription_tag1 = null subscription_tag2 = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler1 = (message,headers,info)=> handler1_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count + handler2_received_count)}" if (handler1_received_count + handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag1, (err)-> assert.ok not err?, err amqpc.unsubscribe_from_queue subscription_tag2, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() else (handler1_received_count + handler2_received_count).should.not.be.above 3 handler2 = (message,headers,info)=> handler2_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count + handler2_received_count)}" if (handler1_received_count + handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag2, (err)-> assert.ok not err?, err amqpc.unsubscribe_from_queue subscription_tag1, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() else (handler1_received_count + handler2_received_count).should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE, handler1, (err, queue, queue_name, st1)=> assert.ok not err?, err assert.ok st1? subscription_tag1 = st1 amqpc.subscribe_to_queue TEST_QUEUE, handler2, (err, queue, queue_name, st2)=> assert.ok not err?, err assert.ok st2? subscription_tag2 = st2 @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>' # in this case we have multiple subscribers on top of a single queue; each message is sent to one or the other subscriber but not both it 'can create multiple subscription channels on top of a single queue and single connection (create-queue-during-subscribe case)',(done)=> handler1_received_count = 0 handler2_received_count = 0 amqpc = new AmqpConsumer() subscription_tag1 = null subscription_tag2 = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err handler1 = (message,headers,info)=> handler1_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count + handler2_received_count)}" if (handler1_received_count + handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag1, (err)-> assert.ok not err?, err amqpc.unsubscribe_from_queue subscription_tag2, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() else (handler1_received_count + handler2_received_count).should.not.be.above 3 amqpc.subscribe TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler1, (err, queue1, queue_name1, st1)=> assert.ok not err?, err assert.ok queue1? assert.ok queue_name1? assert.ok st1? subscription_tag1 = st1 # handler2 = (message,headers,info)=> handler2_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count + handler2_received_count)}" if (handler1_received_count + handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag2, (err)-> assert.ok not err?, err amqpc.unsubscribe_from_queue subscription_tag1, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() else (handler1_received_count + handler2_received_count).should.not.be.above 3 amqpc.subscribe TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler2, (err, queue2, queue_name2, st2)=> assert.ok not err?, err assert.ok queue2? assert.ok queue_name2? assert.ok queue_name2 is queue_name1 assert.ok st2? assert.ok st2 isnt st1 subscription_tag2 = st2 # @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>' # in this case we have multiple QUEUES on top of a single connection; each message is sent to both subscribers it 'can create multiple queues on top of a single connection (create-queue+subscribe-to-queue case)', (done)=> handler1_received_count = 0 handler2_received_count = 0 amqpc = new AmqpConsumer() subscription_tag1 = null subscription_tag2 = null handler1_done = false handler2_done = false amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler1 = (message,headers,info)=> handler1_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count)}" if (handler1_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag1, (err)-> handler1_done = true assert.ok not err?, err if handler2_done assert.ok not err?, err amqpc.disconnect ()=> done() else (handler1_received_count).should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE, handler1, (err, queue, queue_name, st1)=> assert.ok not err?, err assert.ok st1? subscription_tag1 = st1 # amqpc.create_queue TEST_QUEUE_2, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler2 = (message,headers,info)=> handler2_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler2_received_count)}" if (handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag2, (err)-> handler2_done = true assert.ok not err?, err if handler1_done amqpc.disconnect ()=> done() else (handler2_received_count).should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE_2, handler2, (err, queue, queue_name, st2)=> assert.ok not err?, err assert.ok st2? subscription_tag2 = st2 @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>' # in this case we have multiple QUEUES on top of a single connection; each message is sent to both subscribers it 'can create multiple queues on top of a single connection (create-queue-during-subscribe case)',(done)=> handler1_received_count = 0 handler2_received_count = 0 amqpc = new AmqpConsumer() subscription_tag1 = null subscription_tag2 = null handler1_done = false handler2_done = false amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err handler1 = (message, headers, info)=> handler1_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count)}" if (handler1_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag1, (err)=> handler1_done = true assert.ok not err?, err if handler2_done amqpc.disconnect ()=> done() else (handler1_received_count).should.not.be.above 3 amqpc.subscribe TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler1, (err, queue1, queue_name1, st1)=> assert.ok not err?, err assert.ok queue1? assert.ok queue_name1? assert.ok st1? subscription_tag1 = st1 # handler2 = (message, headers, info)=> handler2_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler2_received_count)}" if (handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag2, (err)=> handler2_done = true assert.ok not err?, err if handler1_done amqpc.disconnect ()=> done() else (handler2_received_count).should.not.be.above 3 amqpc.subscribe TEST_QUEUE_2, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler2, (err, queue2, queue_name2, st2)=> assert.ok not err?, err assert.ok queue2? assert.ok queue_name2? assert.ok queue_name2 isnt queue_name1 assert.ok st2? assert.ok st2 isnt st1 subscription_tag2 = st2 # @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>' # in this case we have multiple QUEUES on top of a single connection; each message is sent to both subscribers it 'can create multiple queues on top of a single connection (create-queue-during-subscribe with null name case)',(done)=> handler1_received_count = 0 handler2_received_count = 0 amqpc = new AmqpConsumer() subscription_tag1 = null subscription_tag2 = null handler1_done = false handler2_done = false amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err handler1 = (message, headers, info)=> handler1_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count)}" if (handler1_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag1, (err)=> handler1_done = true assert.ok not err?, err if handler2_done amqpc.disconnect ()=> done() else (handler1_received_count).should.not.be.above 3 amqpc.subscribe undefined, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler1, (err, queue1, queue_name1, st1)=> assert.ok not err?, err assert.ok queue1? assert.ok queue_name1? assert.ok st1? subscription_tag1 = st1 # handler2 = (message, headers, info)=> handler2_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler2_received_count)}" if (handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag2, (err)=> handler2_done = true assert.ok not err?, err if handler1_done amqpc.disconnect ()=> done() else (handler2_received_count).should.not.be.above 3 amqpc.subscribe undefined, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler2, (err, queue2, queue_name2, st2)=> assert.ok not err?, err assert.ok queue2? assert.ok queue_name2? assert.ok queue_name2 isnt queue_name1 assert.ok st2? assert.ok st2 isnt st1 subscription_tag2 = st2 # @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>' @exchange.publish TEST_ROUTING_KEY, '<KEY>'
true
amqp = require 'amqp' should = require 'should' assert = require 'assert' fs = require 'fs' path = require 'path' HOMEDIR = path.join(__dirname,'..') LIB_COV = path.join(HOMEDIR,'lib-cov') LIB = path.join(HOMEDIR,'lib') LIB_DIR = if fs.existsSync(LIB_COV) then LIB_COV else LIB AmqpConsumer = require(path.join(LIB_DIR,'amqp-consumer')).AmqpConsumer AMQPJSONConsumer = require(path.join(LIB_DIR,'amqp-consumer')).AMQPJSONConsumer AMQPStringConsumer = require(path.join(LIB_DIR,'amqp-consumer')).AMQPStringConsumer config = require('inote-util').config.init({},{NODE_ENV:'unit-testing'}) TEST_BROKER = config.get 'amqp:unit-test:broker' TEST_QUEUE = config.get 'amqp:unit-test:queue' TEST_QUEUE_2 = TEST_QUEUE + ":2" TEST_QUEUE_OPTIONS = config.get 'amqp:unit-test:queue-options' TEST_EXCHANGE = config.get 'amqp:unit-test:exchange' TEST_EXCHANGE_OPTIONS = config.get 'amqp:unit-test:exchange-options' TEST_ROUTING_KEY = config.get 'amqp:unit-test:routing-key' describe 'AmqpConsumer',-> beforeEach (done)=> @connection = amqp.createConnection({url:TEST_BROKER}) @connection.once 'ready', ()=> @exchange = @connection?.exchange TEST_EXCHANGE, TEST_EXCHANGE_OPTIONS, ()=> done() afterEach (done)=> @exchange?.destroy(false) @exchange = null @connection?.end() @connection = null done() it 'can accept published messages',(done)=> received_count = 0 amqpc = new AmqpConsumer() subscription_tag = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.get_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info)=> received_count += 1 message.data.toString().should.equal "my-test-message-#{received_count}" if received_count is 3 amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err amqpc.unbind_queue_from_exchange TEST_QUEUE, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err amqpc.destroy_queue TEST_QUEUE, ()=> amqpc.disconnect ()=> done() else received_count.should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' it 'can resolve consumerTag name changes',(done)=> received_count = 0 amqpc = new AmqpConsumer() subscription_tag = null fake_tag_found = false amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.get_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info)=> received_count += 1 message.data.toString().should.equal "my-test-message-#{received_count}" if received_count is 3 amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err assert fake_tag_found amqpc.unbind_queue_from_exchange TEST_QUEUE, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err amqpc.destroy_queue TEST_QUEUE, ()=> amqpc.disconnect ()=> done() else received_count.should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st new_tag = "the-new-consumer-tag-#{Date.now()}" # override queue.unsubscribe to confirm the that mock-renamed tag is passed queue._old_unsubscribe = queue.unsubscribe queue.unsubscribe = (tag_name, tail...)=> assert.equal tag_name, new_tag fake_tag_found = true tag_name = subscription_tag queue._old_unsubscribe tag_name, tail... # amqpc.connection.emit "tag.change", {oldConsumerTag:subscription_tag,consumerTag:new_tag} assert.equal amqpc._resolve_subscription_tag_alias(subscription_tag)[0], new_tag @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' it 'allows subscription options in subscribe call',(done)=> received_count = 0 amqpc = new AmqpConsumer() subscription_tag = null the_queue = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info)=> received_count += 1 message.data.toString().should.equal "my-test-message-#{received_count}" if received_count is 3 amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err amqpc.destroy_queue the_queue, ()=> amqpc.disconnect ()=> done() else received_count.should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE, {exclusive:true}, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? the_queue = queue subscription_tag = st @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' it 'can accept a JSON-valued message as a JSON object',(done)=> amqpc = new AmqpConsumer() subscription_tag = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info, raw)=> message.foo.should.equal 'bar' message.a.should.equal 1 info.contentType.should.equal 'application/json' should.exist raw amqpc.unsubscribe_from_queue subscription_tag, (err)-> amqpc.disconnect ()=> done() amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st @exchange.publish TEST_ROUTING_KEY, { foo:'bar', a:1 } it 'AMQPJSONConsumer can accept a JSON-valued message as a JSON object',(done)=> amqpc = new AmqpConsumer() subscription_tag = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info, raw)=> message.foo.should.equal 'bar' message.a.should.equal 1 info.contentType.should.equal 'application/json' should.exist raw amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st @exchange.publish TEST_ROUTING_KEY, { foo:'bar', a:1 } it 'AMQPStringConsumer can accept a Buffer-valued message as a String',(done)=> amqpc = new AMQPStringConsumer() subscription_tag = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info, raw)=> message.should.equal "The quick brown fox jumped." amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st @exchange.publish TEST_ROUTING_KEY, "PI:KEY:<KEY>END_PI it 'supports a payload converter for transforming messages before they are consumed',(done)=> amqpc = new AMQPJSONConsumer() amqpc.message_converter = (message)->message.data.toString().toUpperCase() subscription_tag = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler = (message,headers,info, raw)=> message.should.equal "THE QUICK BROWN FOX JUMPED." amqpc.unsubscribe_from_queue subscription_tag, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() amqpc.subscribe_to_queue TEST_QUEUE, handler, (err, queue, queue_name, st)=> assert.ok not err?, err assert.ok st? subscription_tag = st @exchange.publish TEST_ROUTING_KEY, "PI:KEY:<KEY>END_PI." # in this case we have multiple subscribers on top of a single queue; each message is sent to one or the other subscriber but not both it 'can create multiple subscription channels on top of a single queue and single connection (create-queue+subscribe-to-queue case)',(done)=> handler1_received_count = 0 handler2_received_count = 0 amqpc = new AmqpConsumer() subscription_tag1 = null subscription_tag2 = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler1 = (message,headers,info)=> handler1_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count + handler2_received_count)}" if (handler1_received_count + handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag1, (err)-> assert.ok not err?, err amqpc.unsubscribe_from_queue subscription_tag2, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() else (handler1_received_count + handler2_received_count).should.not.be.above 3 handler2 = (message,headers,info)=> handler2_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count + handler2_received_count)}" if (handler1_received_count + handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag2, (err)-> assert.ok not err?, err amqpc.unsubscribe_from_queue subscription_tag1, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() else (handler1_received_count + handler2_received_count).should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE, handler1, (err, queue, queue_name, st1)=> assert.ok not err?, err assert.ok st1? subscription_tag1 = st1 amqpc.subscribe_to_queue TEST_QUEUE, handler2, (err, queue, queue_name, st2)=> assert.ok not err?, err assert.ok st2? subscription_tag2 = st2 @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' # in this case we have multiple subscribers on top of a single queue; each message is sent to one or the other subscriber but not both it 'can create multiple subscription channels on top of a single queue and single connection (create-queue-during-subscribe case)',(done)=> handler1_received_count = 0 handler2_received_count = 0 amqpc = new AmqpConsumer() subscription_tag1 = null subscription_tag2 = null amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err handler1 = (message,headers,info)=> handler1_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count + handler2_received_count)}" if (handler1_received_count + handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag1, (err)-> assert.ok not err?, err amqpc.unsubscribe_from_queue subscription_tag2, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() else (handler1_received_count + handler2_received_count).should.not.be.above 3 amqpc.subscribe TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler1, (err, queue1, queue_name1, st1)=> assert.ok not err?, err assert.ok queue1? assert.ok queue_name1? assert.ok st1? subscription_tag1 = st1 # handler2 = (message,headers,info)=> handler2_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count + handler2_received_count)}" if (handler1_received_count + handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag2, (err)-> assert.ok not err?, err amqpc.unsubscribe_from_queue subscription_tag1, (err)-> assert.ok not err?, err amqpc.disconnect ()=> done() else (handler1_received_count + handler2_received_count).should.not.be.above 3 amqpc.subscribe TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler2, (err, queue2, queue_name2, st2)=> assert.ok not err?, err assert.ok queue2? assert.ok queue_name2? assert.ok queue_name2 is queue_name1 assert.ok st2? assert.ok st2 isnt st1 subscription_tag2 = st2 # @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' # in this case we have multiple QUEUES on top of a single connection; each message is sent to both subscribers it 'can create multiple queues on top of a single connection (create-queue+subscribe-to-queue case)', (done)=> handler1_received_count = 0 handler2_received_count = 0 amqpc = new AmqpConsumer() subscription_tag1 = null subscription_tag2 = null handler1_done = false handler2_done = false amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err amqpc.create_queue TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler1 = (message,headers,info)=> handler1_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count)}" if (handler1_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag1, (err)-> handler1_done = true assert.ok not err?, err if handler2_done assert.ok not err?, err amqpc.disconnect ()=> done() else (handler1_received_count).should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE, handler1, (err, queue, queue_name, st1)=> assert.ok not err?, err assert.ok st1? subscription_tag1 = st1 # amqpc.create_queue TEST_QUEUE_2, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, (err)=> assert.ok not err?, err handler2 = (message,headers,info)=> handler2_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler2_received_count)}" if (handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag2, (err)-> handler2_done = true assert.ok not err?, err if handler1_done amqpc.disconnect ()=> done() else (handler2_received_count).should.not.be.above 3 amqpc.subscribe_to_queue TEST_QUEUE_2, handler2, (err, queue, queue_name, st2)=> assert.ok not err?, err assert.ok st2? subscription_tag2 = st2 @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' # in this case we have multiple QUEUES on top of a single connection; each message is sent to both subscribers it 'can create multiple queues on top of a single connection (create-queue-during-subscribe case)',(done)=> handler1_received_count = 0 handler2_received_count = 0 amqpc = new AmqpConsumer() subscription_tag1 = null subscription_tag2 = null handler1_done = false handler2_done = false amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err handler1 = (message, headers, info)=> handler1_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count)}" if (handler1_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag1, (err)=> handler1_done = true assert.ok not err?, err if handler2_done amqpc.disconnect ()=> done() else (handler1_received_count).should.not.be.above 3 amqpc.subscribe TEST_QUEUE, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler1, (err, queue1, queue_name1, st1)=> assert.ok not err?, err assert.ok queue1? assert.ok queue_name1? assert.ok st1? subscription_tag1 = st1 # handler2 = (message, headers, info)=> handler2_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler2_received_count)}" if (handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag2, (err)=> handler2_done = true assert.ok not err?, err if handler1_done amqpc.disconnect ()=> done() else (handler2_received_count).should.not.be.above 3 amqpc.subscribe TEST_QUEUE_2, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler2, (err, queue2, queue_name2, st2)=> assert.ok not err?, err assert.ok queue2? assert.ok queue_name2? assert.ok queue_name2 isnt queue_name1 assert.ok st2? assert.ok st2 isnt st1 subscription_tag2 = st2 # @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' # in this case we have multiple QUEUES on top of a single connection; each message is sent to both subscribers it 'can create multiple queues on top of a single connection (create-queue-during-subscribe with null name case)',(done)=> handler1_received_count = 0 handler2_received_count = 0 amqpc = new AmqpConsumer() subscription_tag1 = null subscription_tag2 = null handler1_done = false handler2_done = false amqpc.connect TEST_BROKER, (err)=> assert.ok not err?, err handler1 = (message, headers, info)=> handler1_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler1_received_count)}" if (handler1_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag1, (err)=> handler1_done = true assert.ok not err?, err if handler2_done amqpc.disconnect ()=> done() else (handler1_received_count).should.not.be.above 3 amqpc.subscribe undefined, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler1, (err, queue1, queue_name1, st1)=> assert.ok not err?, err assert.ok queue1? assert.ok queue_name1? assert.ok st1? subscription_tag1 = st1 # handler2 = (message, headers, info)=> handler2_received_count += 1 message.data.toString().should.equal "my-test-message-#{(handler2_received_count)}" if (handler2_received_count) is 3 amqpc.unsubscribe_from_queue subscription_tag2, (err)=> handler2_done = true assert.ok not err?, err if handler1_done amqpc.disconnect ()=> done() else (handler2_received_count).should.not.be.above 3 amqpc.subscribe undefined, TEST_QUEUE_OPTIONS, TEST_EXCHANGE, TEST_ROUTING_KEY, handler2, (err, queue2, queue_name2, st2)=> assert.ok not err?, err assert.ok queue2? assert.ok queue_name2? assert.ok queue_name2 isnt queue_name1 assert.ok st2? assert.ok st2 isnt st1 subscription_tag2 = st2 # @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI' @exchange.publish TEST_ROUTING_KEY, 'PI:KEY:<KEY>END_PI'
[ { "context": "# parsing source\n#\n# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# L", "end": 54, "score": 0.9998738169670105, "start": 40, "tag": "NAME", "value": "JeongHoon Byun" }, { "context": "rce\n#\n# Copyright (c) 2013 JeongHoon Byun aka...
src/helpers.coffee
outsideris/popularconvention
421
# parsing source # # Copyright (c) 2013 JeongHoon Byun aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> winston = require 'winston' module.exports = extractType: (target) -> Object.prototype.toString.call(target).replace('[object ', '').replace(']', '').toLowerCase() logger: new (winston.Logger) ( transports: [ new (winston.transports.Console)( level: 'error' colorize: true timestamp: -> new Date().toLocaleString() prettyPrint: true ) ] )
26439
# parsing source # # Copyright (c) 2013 <NAME> aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> winston = require 'winston' module.exports = extractType: (target) -> Object.prototype.toString.call(target).replace('[object ', '').replace(']', '').toLowerCase() logger: new (winston.Logger) ( transports: [ new (winston.transports.Console)( level: 'error' colorize: true timestamp: -> new Date().toLocaleString() prettyPrint: true ) ] )
true
# parsing source # # Copyright (c) 2013 PI:NAME:<NAME>END_PI aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> winston = require 'winston' module.exports = extractType: (target) -> Object.prototype.toString.call(target).replace('[object ', '').replace(']', '').toLowerCase() logger: new (winston.Logger) ( transports: [ new (winston.transports.Console)( level: 'error' colorize: true timestamp: -> new Date().toLocaleString() prettyPrint: true ) ] )
[ { "context": "lib/hoptoad-notifier').Hoptoad\nHoptoad.key = 'some key'\n###\nprocess.on 'uncaughtException', (e) ->\n Hop", "end": 781, "score": 0.5395029783248901, "start": 778, "tag": "KEY", "value": "key" }, { "context": "q\n @vote.team = @team = team\n @vote.person = @curr...
nodeko.coffee
InfinitelLoop/website-3
2
# this entire application is pretty gross, by our own judgement. we'd love to # clean it up, but we'd probably just rewrite the whole thing anyway. you have # been warned. sys = require 'sys' connect = require 'connect' express = require 'express' models = require './models/models' [Team, Person, Vote, ScoreCalculator, Reply] = [models.Team, models.Person, models.Vote, models.ScoreCalculator, models.Reply] pub = __dirname + '/public' app = express.createServer( connect.compiler({ src: pub, enable: ['sass', 'coffee'] }), connect.staticProvider(pub) ) app.use connect.logger() app.use connect.bodyDecoder() app.use connect.methodOverride() app.use connect.cookieDecoder() Hoptoad = require('./lib/hoptoad-notifier/lib/hoptoad-notifier').Hoptoad Hoptoad.key = 'some key' ### process.on 'uncaughtException', (e) -> Hoptoad.notify e ### request = (type) -> (path, fn) -> app[type] path, (req, res, next) -> Person.firstByAuthKey req.cookies.authkey, (error, person) => ctx = { sys: sys req: req res: res next: next redirect: __bind(res.redirect, res), cookie: (key, value, options) -> value ||= '' options ||= {} options.path ||= '/' cookie = "#{key}=#{value}" for k, v of options cookie += "; #{k}=#{v}" res.header('Set-Cookie', cookie) render: (file, opts, fn) -> opts ||= {} opts.locals ||= {} opts.locals.view = file.replace(/\..*$/,'').replace(/\//,'-') opts.locals.ctx = ctx res.render file, opts, fn currentPerson: person isAdmin: person? && person.admin() isJudge: person? && person.type is 'Judge' setCurrentPerson: (person, options) -> @cookie 'authKey', person?.authKey(), options redirectToTeam: (person, alternate) -> Team.first { 'members._id': person._id }, (error, team) => if team? @redirect '/teams/' + team.toParam() else if alternate alternate() else @redirect '/' redirectToLogin: -> @redirect "/login?return_to=#{@req.url}" logout: (fn) -> if @currentPerson? @currentPerson.logout (error, resp) => @setCurrentPerson null fn() else fn() canEditTeam: (team) -> req.cookies.teamauthkey is team.authKey() or team.hasMember(@currentPerson) or @isAdmin canReplyTo: (vote) -> return false unless @currentPerson? vote.team.hasMember(@currentPerson) or (vote.person.id() is @currentPerson.id()) ensurePermitted: (other, fn) -> permitted = @isAdmin if other.hasMember? permitted ||= @canEditTeam(other) else if other.person? permitted ||= (@currentPerson? and other.person.id() is @currentPerson.id()) else permitted ||= (@currentPerson? and other.id() is @currentPerson.id()) if permitted then fn() else @redirectToLogin()} try __bind(fn, ctx)() catch e e.action = e.url = req.url #Hoptoad.notify e next e get = request 'get' post = request 'post' put = request 'put' del = request 'del' get /.*/, -> [host, path] = [@req.header('host'), @req.url] if host == 'www.nodeknockout.com' or host == 'nodeknockout.heroku.com' @redirect "http://nodeknockout.com#{path}", 301 else @next() get '/', -> Team.count (error, teamCount) => @teamCount = teamCount @winners = [ ['Overall', 'saber-tooth-moose-lion'] ['Solo', 'rallarpojken'] ['Utility', 'prague-js'] ['Design', 'piston-hurricane'] ['Innovation', 'starcraft-2-destroyed-my-marriage'] ['Completeness', 'explorer-sox'] ['Popularity', 'seattle-js'] ] Team.all { slug: {'$in': _.pluck(@winners, 1)} }, { deep: false }, (error, teams) => @teams = teams @winners = _.map @winners, (w) => [ w[0], _.detect(@teams, (t) -> t.slug == w[1]) ] @render 'index.html.haml' get '/me', -> if @currentPerson? @redirect "/people/#{@currentPerson.toParam()}/edit" else @redirectToLogin() get '/team', -> if @currentPerson? @redirectToTeam @currentPerson, __bind(@redirectToLogin, this) else @redirectToLogin() get '/register', -> if @currentPerson? @redirectToTeam @currentPerson else @redirect "/login?return_to=#{@req.url}" get '/error', -> throw new Error('Foo') get '/scores', -> Team.all { validDeploy: true }, { deep: false, sort: [['score.overall', -1]] }, (error, teams) => @teams = teams @render 'scores.html.haml' post '/scores/refresh', -> ScoreCalculator.calculate (scores) => res = @res team_ids = k for k, v of scores save = (error, saved) -> return res.send sys.inspect(error), 500 if error? if team_id = team_ids.pop() Team.updateAll team_id, { $set: { score: scores[team_id] }}, save else res.send 'OK', 200 save() # list teams get '/teams', -> q = if @req.param('invalid') then { url: /\w/, validDeploy: false } else { validDeploy: true } Team.all q, { deep: false, sort: [['score.overall', -1]] }, (error, teams) => @teams = teams @render 'teams/index.html.haml' # new team get '/teams/new', -> return @redirect '/' unless @isAdmin @team = new Team {}, => @render 'teams/new.html.haml' # create team post '/teams', -> return @redirect '/' unless @isAdmin @team = new Team @req.body, => @team.save (errors, res) => if errors? @errors = errors @render 'teams/new.html.haml' else @cookie 'teamAuthKey', @team.authKey() @redirect '/teams/' + @team.toParam() # show team get '/teams/:id', -> @requestAt = Date.now() Team.fromParam @req.param('id'), (error, team) => if team? @team = team @title = @team.name @editAllowed = @canEditTeam team @votingOpen = Date.now() < Date.UTC(2010, 8, 2, 23, 59, 59) people = team.members or [] @members = _.select people, (person) -> person.name @invites = _.without people, @members... renderVotes = => Vote.all { 'team._id': team._id }, { 'sort': [['createdAt', -1]], limit: 50 }, (error, votes) => @votes = votes for vote in @votes vote.team = @team vote.instantiateReplyers() @render 'teams/show.html.haml' if @currentPerson Vote.firstByTeamAndPerson team, @currentPerson, (error, vote) => @vote = vote or new Vote(null, @req) @vote.person = @currentPerson @vote.email = @vote.person.email renderVotes() else @vote = new Vote(null, @req) renderVotes() else # TODO make this a 404 @redirect '/' # edit team get '/teams/:id/edit', -> Team.fromParam @req.param('id'), (error, team) => @ensurePermitted team, => @team = team @render 'teams/edit.html.haml' # update team put '/teams/:id', -> Team.fromParam @req.param('id'), (error, team) => @ensurePermitted team, => delete @req.body.score team.update @req.body team.validDeploy = @req.body.validDeploy == '1' save = => team.save (errors, result) => if errors? @errors = errors @team = team if @req.xhr @res.send 'ERROR', 500 else @render 'teams/edit.html.haml' else if @req.xhr @res.send 'OK', 200 else @redirect '/teams/' + team.toParam() # TODO shouldn't need this if @req.body.emails team.setMembers @req.body.emails, save else save() # delete team del '/teams/:id', -> Team.fromParam @req.param('id'), (error, team) => @ensurePermitted team, => team.remove (error, result) => @redirect '/' # resend invitation get '/teams/:teamId/invite/:personId', -> Team.fromParam @req.param('teamId'), (error, team) => @ensurePermitted team, => Person.fromParam @req.param('personId'), (error, person) => person.inviteTo team, => if @req.xhr @res.send 'OK', 200 else # TODO flash "Sent a new invitation to $@person.email" @redirect '/teams/' + team.toParam() saveVote = -> @vote.save (errors, res) => if errors? if errors[0] is 'Unauthorized' # TODO flash "You must login to vote as #{@vote.email}." @res.send 'Unauthorized', 403 else @res.send JSON.stringify(errors), 400 else # TODO flash "You are now logged into Node Knockout as #{@vote.email}." @setCurrentPerson @vote.person if @vote.person? and !@currentPerson? @vote.instantiateReplyers() @votes = [@vote] @render 'partials/votes/index.html.jade', { layout: false } # create vote post '/teams/:teamId/votes', -> return @next() Team.fromParam @req.param('teamId'), (error, team) => # TODO: handle error @vote = new Vote @req.body, @req @vote.team = @team = team @vote.person = @currentPerson @vote.email ?= @vote.person?.email @vote.responseAt = Date.now() saveVote.call(this) put '/teams/:teamId/votes/:voteId', -> return @next() Team.fromParam @req.param('teamId'), (error, team) => Vote.fromParam @req.param('voteId'), (error, vote) => @ensurePermitted vote, => @noHeader = true @vote = vote @vote.team = team vote.update @req.body saveVote.call(this) post '/teams/:teamId/votes/:voteId/replies', -> Team.fromParam @req.param('teamId'), (error, team) => Vote.fromParam @req.param('voteId'), (error, vote) => vote.team = team vote.instantiateReplyers() unless @canReplyTo(vote) return @res.send 'Unauthorized: only the voter and team members may comment on a vote.', 403 else @reply = new Reply { person: @currentPerson, vote: vote, body: @req.body.body } @reply.save (errors, reply) => if errors? @res.send JSON.stringify(errors), 400 else vote.replies.push @reply vote.notifyPeopleAboutReply @reply @render 'partials/replies/reply.html.jade', { locals: { reply: @reply, vote: vote, ctx: this }, layout: false } # list votes get '/teams/:teamId/votes', -> @redirect '/teams/' + @req.param('teamId') get '/teams/:teamId/votes.js', -> skip = 50 * ((@req.query['page'] || 1)-1) Team.fromParam @req.param('teamId'), (error, team) => # TODO: handle error Vote.all { 'team._id': team._id }, { 'sort': [['createdAt', -1]], skip: skip, limit: 50 }, (error, votes) => @votes = votes for vote in @votes vote.team = team vote.instantiateReplyers() @render 'partials/votes/index.html.jade', { layout: false } # sign in get '/login', -> @person = new Person() @render 'login.html.haml' post '/login', -> Person.login @req.body, (error, person) => if person? if @req.param 'remember' d = new Date() d.setTime(d.getTime() + 1000 * 60 * 60 * 24 * 180) options = { expires: d } @setCurrentPerson person, options if person.name if returnTo = @req.param('return_to') @redirect returnTo else @redirect '/people/' + person.toParam() else @redirect '/people/' + person.toParam() + '/edit' else @errors = error @person = new Person(@req.body) @render 'login.html.haml' get '/logout', -> @logout => @redirect(@req.param('return_to') || @req.headers.referer || '/') # reset password post '/reset_password', -> Person.first { email: @req.param('email') }, (error, person) => # TODO assumes xhr unless person? @res.send 'Email not found', 404 else person.resetPassword => @res.send 'OK', 200 # new judge get '/judges/new', -> @person = new Person({ type: 'Judge' }) @ensurePermitted @person, => @render 'judges/new.html.haml' get '/judges|/judging', -> Person.all { type: 'Judge' }, (error, judges) => @judges = _.shuffle judges @render 'judges/index.html.jade', { layout: 'layout.haml' } # create person post '/people', -> @person = new Person @req.body @ensurePermitted @person, => @person.save (error, res) => # TODO send confirmation email @redirect '/people/' + @person.toParam() # edit person get '/people/:id/edit', -> Person.fromParam @req.param('id'), (error, person) => @ensurePermitted person, => @person = person @render 'people/edit.html.haml' # show person get '/people/:id', -> Person.fromParam @req.param('id'), (error, person) => @person = person @isCurrentPerson = @person.id() is @currentPerson?.id() @person.loadTeams => @person.loadVotes => @showTeam = true @votes = @person.votes @render 'people/show.html.haml' # update person put '/people/:id', -> Person.fromParam @req.param('id'), (error, person) => @ensurePermitted person, => attributes = @req.body if attributes.password person.confirmKey = Math.uuid() # TODO this shouldn't be necessary person.setPassword attributes.password delete attributes.password attributes.link = '' unless /^https?:\/\/.+\./.test attributes.link if attributes.email? && attributes.email != person.email person.confirmed = attributes.confimed = false person.github ||= '' person.update attributes person.save (error, resp) => @redirect '/people/' + person.toParam() # delete person del '/people/:id', -> Person.fromParam @req.param('id'), (error, person) => @ensurePermitted person, => person.remove (error, result) => @redirect '/' post '/people/:id/confirm', -> Person.fromParam @req.param('id'), (error, person) => person.confirmKey = Math.uuid() person.save => person.sendConfirmKey => @redirect '/people/' + person.toParam() + '/confirm' get '/people/:id/confirm', -> @confirmKey = @req.param('confirmKey') return @render 'people/confirm.html.jade', { layout: 'layout.haml' } unless @confirmKey Person.fromParam @req.param('id'), (error, person) => if not person? @res.send 'Not found', 404 else if @confirmKey? and person.confirmed @person = person @render 'people/confirm.html.jade', { layout: 'layout.haml' } else if @confirmKey? and person.confirmKey isnt @confirmKey @errors = ['Invalid confirmation key. Please check your email for the correct key.'] return @render 'people/confirm.html.jade', { layout: 'layout.haml' } else person.verifiedConfirmKey = true person.login => @setCurrentPerson person @person = person @render 'people/confirm.html.jade', { layout: 'layout.haml' } # TODO security post '/deploys', -> # user: 'visnupx@gmail.com' # head: '87eaeb6' # app: 'visnup-nko' # url: 'http://visnup-nko.heroku.com' # git_log: '' # prev_head: '' # head_long: '87eaeb69d726593de6a47a5f38ff6126fd3920fa' query = {} deployedTo = if /\.no\.de$/.test(@req.param('url')) then 'joyent' else 'heroku' query[deployedTo + 'Slug'] = @req.param('app') Team.first query, (error, team) => if team team.url = @req.param('url') team.lastDeployedTo = deployedTo team.lastDeployedAt = new Date() team.lastDeployedHead = @req.param('head') team.lastDeployedHeadLong = @req.param('head_long') team.deployHeads.push team.lastDeployedHeadLong team.save(->) @render 'deploys/ok.html.haml', { layout: false } get '/prizes', -> @render 'prizes.html.jade', { layout: 'layout.haml' } get '/*', -> try @render "#{@req.params[0]}.html.haml" catch e throw e if e.errno != 2 @next() app.helpers { pluralize: (n, str) -> if n == 1 n + ' ' + str else n + ' ' + str + 's' escapeURL: require('querystring').escape markdown: require('markdown').toHTML firstParagraph: (md) -> markdown = require 'markdown' tree = markdown.parse md p = _.detect tree, (e) -> e[0] == 'para' if p then markdown.toHTML p else '' gravatar: (p, s) -> return '' unless p? if p.type is 'Judge' "<img src=\"/images/judges/#{p.name.replace(/\W+/g, '_')}.jpg\" width=#{s || 40} />" else "<img src=\"http://www.gravatar.com/avatar/#{p.emailHash}?s=#{s || 40}&d=monsterid\" />" } _.shuffle = (a) -> r = _.clone a for i in [r.length-1 .. 0] j = parseInt(Math.random() * i) [r[i], r[j]] = [r[j], r[i]] r # has to be last app.use '/', express.errorHandler({ dumpExceptions: true, showStack: true }) server = app.listen parseInt(process.env.PORT || 8000), null
67429
# this entire application is pretty gross, by our own judgement. we'd love to # clean it up, but we'd probably just rewrite the whole thing anyway. you have # been warned. sys = require 'sys' connect = require 'connect' express = require 'express' models = require './models/models' [Team, Person, Vote, ScoreCalculator, Reply] = [models.Team, models.Person, models.Vote, models.ScoreCalculator, models.Reply] pub = __dirname + '/public' app = express.createServer( connect.compiler({ src: pub, enable: ['sass', 'coffee'] }), connect.staticProvider(pub) ) app.use connect.logger() app.use connect.bodyDecoder() app.use connect.methodOverride() app.use connect.cookieDecoder() Hoptoad = require('./lib/hoptoad-notifier/lib/hoptoad-notifier').Hoptoad Hoptoad.key = 'some <KEY>' ### process.on 'uncaughtException', (e) -> Hoptoad.notify e ### request = (type) -> (path, fn) -> app[type] path, (req, res, next) -> Person.firstByAuthKey req.cookies.authkey, (error, person) => ctx = { sys: sys req: req res: res next: next redirect: __bind(res.redirect, res), cookie: (key, value, options) -> value ||= '' options ||= {} options.path ||= '/' cookie = "#{key}=#{value}" for k, v of options cookie += "; #{k}=#{v}" res.header('Set-Cookie', cookie) render: (file, opts, fn) -> opts ||= {} opts.locals ||= {} opts.locals.view = file.replace(/\..*$/,'').replace(/\//,'-') opts.locals.ctx = ctx res.render file, opts, fn currentPerson: person isAdmin: person? && person.admin() isJudge: person? && person.type is 'Judge' setCurrentPerson: (person, options) -> @cookie 'authKey', person?.authKey(), options redirectToTeam: (person, alternate) -> Team.first { 'members._id': person._id }, (error, team) => if team? @redirect '/teams/' + team.toParam() else if alternate alternate() else @redirect '/' redirectToLogin: -> @redirect "/login?return_to=#{@req.url}" logout: (fn) -> if @currentPerson? @currentPerson.logout (error, resp) => @setCurrentPerson null fn() else fn() canEditTeam: (team) -> req.cookies.teamauthkey is team.authKey() or team.hasMember(@currentPerson) or @isAdmin canReplyTo: (vote) -> return false unless @currentPerson? vote.team.hasMember(@currentPerson) or (vote.person.id() is @currentPerson.id()) ensurePermitted: (other, fn) -> permitted = @isAdmin if other.hasMember? permitted ||= @canEditTeam(other) else if other.person? permitted ||= (@currentPerson? and other.person.id() is @currentPerson.id()) else permitted ||= (@currentPerson? and other.id() is @currentPerson.id()) if permitted then fn() else @redirectToLogin()} try __bind(fn, ctx)() catch e e.action = e.url = req.url #Hoptoad.notify e next e get = request 'get' post = request 'post' put = request 'put' del = request 'del' get /.*/, -> [host, path] = [@req.header('host'), @req.url] if host == 'www.nodeknockout.com' or host == 'nodeknockout.heroku.com' @redirect "http://nodeknockout.com#{path}", 301 else @next() get '/', -> Team.count (error, teamCount) => @teamCount = teamCount @winners = [ ['Overall', 'saber-tooth-moose-lion'] ['Solo', 'rallarpojken'] ['Utility', 'prague-js'] ['Design', 'piston-hurricane'] ['Innovation', 'starcraft-2-destroyed-my-marriage'] ['Completeness', 'explorer-sox'] ['Popularity', 'seattle-js'] ] Team.all { slug: {'$in': _.pluck(@winners, 1)} }, { deep: false }, (error, teams) => @teams = teams @winners = _.map @winners, (w) => [ w[0], _.detect(@teams, (t) -> t.slug == w[1]) ] @render 'index.html.haml' get '/me', -> if @currentPerson? @redirect "/people/#{@currentPerson.toParam()}/edit" else @redirectToLogin() get '/team', -> if @currentPerson? @redirectToTeam @currentPerson, __bind(@redirectToLogin, this) else @redirectToLogin() get '/register', -> if @currentPerson? @redirectToTeam @currentPerson else @redirect "/login?return_to=#{@req.url}" get '/error', -> throw new Error('Foo') get '/scores', -> Team.all { validDeploy: true }, { deep: false, sort: [['score.overall', -1]] }, (error, teams) => @teams = teams @render 'scores.html.haml' post '/scores/refresh', -> ScoreCalculator.calculate (scores) => res = @res team_ids = k for k, v of scores save = (error, saved) -> return res.send sys.inspect(error), 500 if error? if team_id = team_ids.pop() Team.updateAll team_id, { $set: { score: scores[team_id] }}, save else res.send 'OK', 200 save() # list teams get '/teams', -> q = if @req.param('invalid') then { url: /\w/, validDeploy: false } else { validDeploy: true } Team.all q, { deep: false, sort: [['score.overall', -1]] }, (error, teams) => @teams = teams @render 'teams/index.html.haml' # new team get '/teams/new', -> return @redirect '/' unless @isAdmin @team = new Team {}, => @render 'teams/new.html.haml' # create team post '/teams', -> return @redirect '/' unless @isAdmin @team = new Team @req.body, => @team.save (errors, res) => if errors? @errors = errors @render 'teams/new.html.haml' else @cookie 'teamAuthKey', @team.authKey() @redirect '/teams/' + @team.toParam() # show team get '/teams/:id', -> @requestAt = Date.now() Team.fromParam @req.param('id'), (error, team) => if team? @team = team @title = @team.name @editAllowed = @canEditTeam team @votingOpen = Date.now() < Date.UTC(2010, 8, 2, 23, 59, 59) people = team.members or [] @members = _.select people, (person) -> person.name @invites = _.without people, @members... renderVotes = => Vote.all { 'team._id': team._id }, { 'sort': [['createdAt', -1]], limit: 50 }, (error, votes) => @votes = votes for vote in @votes vote.team = @team vote.instantiateReplyers() @render 'teams/show.html.haml' if @currentPerson Vote.firstByTeamAndPerson team, @currentPerson, (error, vote) => @vote = vote or new Vote(null, @req) @vote.person = @currentPerson @vote.email = @vote.person.email renderVotes() else @vote = new Vote(null, @req) renderVotes() else # TODO make this a 404 @redirect '/' # edit team get '/teams/:id/edit', -> Team.fromParam @req.param('id'), (error, team) => @ensurePermitted team, => @team = team @render 'teams/edit.html.haml' # update team put '/teams/:id', -> Team.fromParam @req.param('id'), (error, team) => @ensurePermitted team, => delete @req.body.score team.update @req.body team.validDeploy = @req.body.validDeploy == '1' save = => team.save (errors, result) => if errors? @errors = errors @team = team if @req.xhr @res.send 'ERROR', 500 else @render 'teams/edit.html.haml' else if @req.xhr @res.send 'OK', 200 else @redirect '/teams/' + team.toParam() # TODO shouldn't need this if @req.body.emails team.setMembers @req.body.emails, save else save() # delete team del '/teams/:id', -> Team.fromParam @req.param('id'), (error, team) => @ensurePermitted team, => team.remove (error, result) => @redirect '/' # resend invitation get '/teams/:teamId/invite/:personId', -> Team.fromParam @req.param('teamId'), (error, team) => @ensurePermitted team, => Person.fromParam @req.param('personId'), (error, person) => person.inviteTo team, => if @req.xhr @res.send 'OK', 200 else # TODO flash "Sent a new invitation to $@person.email" @redirect '/teams/' + team.toParam() saveVote = -> @vote.save (errors, res) => if errors? if errors[0] is 'Unauthorized' # TODO flash "You must login to vote as #{@vote.email}." @res.send 'Unauthorized', 403 else @res.send JSON.stringify(errors), 400 else # TODO flash "You are now logged into Node Knockout as #{@vote.email}." @setCurrentPerson @vote.person if @vote.person? and !@currentPerson? @vote.instantiateReplyers() @votes = [@vote] @render 'partials/votes/index.html.jade', { layout: false } # create vote post '/teams/:teamId/votes', -> return @next() Team.fromParam @req.param('teamId'), (error, team) => # TODO: handle error @vote = new Vote @req.body, @req @vote.team = @team = team @vote.person = @currentPerson @vote.email ?= @vote.person?.email @vote.responseAt = Date.now() saveVote.call(this) put '/teams/:teamId/votes/:voteId', -> return @next() Team.fromParam @req.param('teamId'), (error, team) => Vote.fromParam @req.param('voteId'), (error, vote) => @ensurePermitted vote, => @noHeader = true @vote = vote @vote.team = team vote.update @req.body saveVote.call(this) post '/teams/:teamId/votes/:voteId/replies', -> Team.fromParam @req.param('teamId'), (error, team) => Vote.fromParam @req.param('voteId'), (error, vote) => vote.team = team vote.instantiateReplyers() unless @canReplyTo(vote) return @res.send 'Unauthorized: only the voter and team members may comment on a vote.', 403 else @reply = new Reply { person: @currentPerson, vote: vote, body: @req.body.body } @reply.save (errors, reply) => if errors? @res.send JSON.stringify(errors), 400 else vote.replies.push @reply vote.notifyPeopleAboutReply @reply @render 'partials/replies/reply.html.jade', { locals: { reply: @reply, vote: vote, ctx: this }, layout: false } # list votes get '/teams/:teamId/votes', -> @redirect '/teams/' + @req.param('teamId') get '/teams/:teamId/votes.js', -> skip = 50 * ((@req.query['page'] || 1)-1) Team.fromParam @req.param('teamId'), (error, team) => # TODO: handle error Vote.all { 'team._id': team._id }, { 'sort': [['createdAt', -1]], skip: skip, limit: 50 }, (error, votes) => @votes = votes for vote in @votes vote.team = team vote.instantiateReplyers() @render 'partials/votes/index.html.jade', { layout: false } # sign in get '/login', -> @person = new Person() @render 'login.html.haml' post '/login', -> Person.login @req.body, (error, person) => if person? if @req.param 'remember' d = new Date() d.setTime(d.getTime() + 1000 * 60 * 60 * 24 * 180) options = { expires: d } @setCurrentPerson person, options if person.name if returnTo = @req.param('return_to') @redirect returnTo else @redirect '/people/' + person.toParam() else @redirect '/people/' + person.toParam() + '/edit' else @errors = error @person = new Person(@req.body) @render 'login.html.haml' get '/logout', -> @logout => @redirect(@req.param('return_to') || @req.headers.referer || '/') # reset password post '/reset_password', -> Person.first { email: @req.param('email') }, (error, person) => # TODO assumes xhr unless person? @res.send 'Email not found', 404 else person.resetPassword => @res.send 'OK', 200 # new judge get '/judges/new', -> @person = new Person({ type: 'Judge' }) @ensurePermitted @person, => @render 'judges/new.html.haml' get '/judges|/judging', -> Person.all { type: 'Judge' }, (error, judges) => @judges = _.shuffle judges @render 'judges/index.html.jade', { layout: 'layout.haml' } # create person post '/people', -> @person = new Person @req.body @ensurePermitted @person, => @person.save (error, res) => # TODO send confirmation email @redirect '/people/' + @person.toParam() # edit person get '/people/:id/edit', -> Person.fromParam @req.param('id'), (error, person) => @ensurePermitted person, => @person = person @render 'people/edit.html.haml' # show person get '/people/:id', -> Person.fromParam @req.param('id'), (error, person) => @person = person @isCurrentPerson = @person.id() is @currentPerson?.id() @person.loadTeams => @person.loadVotes => @showTeam = true @votes = @person.votes @render 'people/show.html.haml' # update person put '/people/:id', -> Person.fromParam @req.param('id'), (error, person) => @ensurePermitted person, => attributes = @req.body if attributes.password person.confirmKey = Math.uuid() # TODO this shouldn't be necessary person.setPassword attributes.password delete attributes.password attributes.link = '' unless /^https?:\/\/.+\./.test attributes.link if attributes.email? && attributes.email != person.email person.confirmed = attributes.confimed = false person.github ||= '' person.update attributes person.save (error, resp) => @redirect '/people/' + person.toParam() # delete person del '/people/:id', -> Person.fromParam @req.param('id'), (error, person) => @ensurePermitted person, => person.remove (error, result) => @redirect '/' post '/people/:id/confirm', -> Person.fromParam @req.param('id'), (error, person) => person.confirmKey = <KEY>() person.save => person.sendConfirmKey => @redirect '/people/' + person.toParam() + '/confirm' get '/people/:id/confirm', -> @confirmKey = @req.param('confirmKey') return @render 'people/confirm.html.jade', { layout: 'layout.haml' } unless @confirmKey Person.fromParam @req.param('id'), (error, person) => if not person? @res.send 'Not found', 404 else if @confirmKey? and person.confirmed @person = person @render 'people/confirm.html.jade', { layout: 'layout.haml' } else if @confirmKey? and person.confirmKey isnt @confirmKey @errors = ['Invalid confirmation key. Please check your email for the correct key.'] return @render 'people/confirm.html.jade', { layout: 'layout.haml' } else person.verifiedConfirmKey = true person.login => @setCurrentPerson person @person = person @render 'people/confirm.html.jade', { layout: 'layout.haml' } # TODO security post '/deploys', -> # user: '<EMAIL>' # head: '87eaeb6' # app: 'visnup-nko' # url: 'http://visnup-nko.heroku.com' # git_log: '' # prev_head: '' # head_long: '87eaeb69d726593de6a47a5f38ff6126fd3920fa' query = {} deployedTo = if /\.no\.de$/.test(@req.param('url')) then 'joyent' else 'heroku' query[deployedTo + 'Slug'] = @req.param('app') Team.first query, (error, team) => if team team.url = @req.param('url') team.lastDeployedTo = deployedTo team.lastDeployedAt = new Date() team.lastDeployedHead = @req.param('head') team.lastDeployedHeadLong = @req.param('head_long') team.deployHeads.push team.lastDeployedHeadLong team.save(->) @render 'deploys/ok.html.haml', { layout: false } get '/prizes', -> @render 'prizes.html.jade', { layout: 'layout.haml' } get '/*', -> try @render "#{@req.params[0]}.html.haml" catch e throw e if e.errno != 2 @next() app.helpers { pluralize: (n, str) -> if n == 1 n + ' ' + str else n + ' ' + str + 's' escapeURL: require('querystring').escape markdown: require('markdown').toHTML firstParagraph: (md) -> markdown = require 'markdown' tree = markdown.parse md p = _.detect tree, (e) -> e[0] == 'para' if p then markdown.toHTML p else '' gravatar: (p, s) -> return '' unless p? if p.type is 'Judge' "<img src=\"/images/judges/#{p.name.replace(/\W+/g, '_')}.jpg\" width=#{s || 40} />" else "<img src=\"http://www.gravatar.com/avatar/#{p.emailHash}?s=#{s || 40}&d=monsterid\" />" } _.shuffle = (a) -> r = _.clone a for i in [r.length-1 .. 0] j = parseInt(Math.random() * i) [r[i], r[j]] = [r[j], r[i]] r # has to be last app.use '/', express.errorHandler({ dumpExceptions: true, showStack: true }) server = app.listen parseInt(process.env.PORT || 8000), null
true
# this entire application is pretty gross, by our own judgement. we'd love to # clean it up, but we'd probably just rewrite the whole thing anyway. you have # been warned. sys = require 'sys' connect = require 'connect' express = require 'express' models = require './models/models' [Team, Person, Vote, ScoreCalculator, Reply] = [models.Team, models.Person, models.Vote, models.ScoreCalculator, models.Reply] pub = __dirname + '/public' app = express.createServer( connect.compiler({ src: pub, enable: ['sass', 'coffee'] }), connect.staticProvider(pub) ) app.use connect.logger() app.use connect.bodyDecoder() app.use connect.methodOverride() app.use connect.cookieDecoder() Hoptoad = require('./lib/hoptoad-notifier/lib/hoptoad-notifier').Hoptoad Hoptoad.key = 'some PI:KEY:<KEY>END_PI' ### process.on 'uncaughtException', (e) -> Hoptoad.notify e ### request = (type) -> (path, fn) -> app[type] path, (req, res, next) -> Person.firstByAuthKey req.cookies.authkey, (error, person) => ctx = { sys: sys req: req res: res next: next redirect: __bind(res.redirect, res), cookie: (key, value, options) -> value ||= '' options ||= {} options.path ||= '/' cookie = "#{key}=#{value}" for k, v of options cookie += "; #{k}=#{v}" res.header('Set-Cookie', cookie) render: (file, opts, fn) -> opts ||= {} opts.locals ||= {} opts.locals.view = file.replace(/\..*$/,'').replace(/\//,'-') opts.locals.ctx = ctx res.render file, opts, fn currentPerson: person isAdmin: person? && person.admin() isJudge: person? && person.type is 'Judge' setCurrentPerson: (person, options) -> @cookie 'authKey', person?.authKey(), options redirectToTeam: (person, alternate) -> Team.first { 'members._id': person._id }, (error, team) => if team? @redirect '/teams/' + team.toParam() else if alternate alternate() else @redirect '/' redirectToLogin: -> @redirect "/login?return_to=#{@req.url}" logout: (fn) -> if @currentPerson? @currentPerson.logout (error, resp) => @setCurrentPerson null fn() else fn() canEditTeam: (team) -> req.cookies.teamauthkey is team.authKey() or team.hasMember(@currentPerson) or @isAdmin canReplyTo: (vote) -> return false unless @currentPerson? vote.team.hasMember(@currentPerson) or (vote.person.id() is @currentPerson.id()) ensurePermitted: (other, fn) -> permitted = @isAdmin if other.hasMember? permitted ||= @canEditTeam(other) else if other.person? permitted ||= (@currentPerson? and other.person.id() is @currentPerson.id()) else permitted ||= (@currentPerson? and other.id() is @currentPerson.id()) if permitted then fn() else @redirectToLogin()} try __bind(fn, ctx)() catch e e.action = e.url = req.url #Hoptoad.notify e next e get = request 'get' post = request 'post' put = request 'put' del = request 'del' get /.*/, -> [host, path] = [@req.header('host'), @req.url] if host == 'www.nodeknockout.com' or host == 'nodeknockout.heroku.com' @redirect "http://nodeknockout.com#{path}", 301 else @next() get '/', -> Team.count (error, teamCount) => @teamCount = teamCount @winners = [ ['Overall', 'saber-tooth-moose-lion'] ['Solo', 'rallarpojken'] ['Utility', 'prague-js'] ['Design', 'piston-hurricane'] ['Innovation', 'starcraft-2-destroyed-my-marriage'] ['Completeness', 'explorer-sox'] ['Popularity', 'seattle-js'] ] Team.all { slug: {'$in': _.pluck(@winners, 1)} }, { deep: false }, (error, teams) => @teams = teams @winners = _.map @winners, (w) => [ w[0], _.detect(@teams, (t) -> t.slug == w[1]) ] @render 'index.html.haml' get '/me', -> if @currentPerson? @redirect "/people/#{@currentPerson.toParam()}/edit" else @redirectToLogin() get '/team', -> if @currentPerson? @redirectToTeam @currentPerson, __bind(@redirectToLogin, this) else @redirectToLogin() get '/register', -> if @currentPerson? @redirectToTeam @currentPerson else @redirect "/login?return_to=#{@req.url}" get '/error', -> throw new Error('Foo') get '/scores', -> Team.all { validDeploy: true }, { deep: false, sort: [['score.overall', -1]] }, (error, teams) => @teams = teams @render 'scores.html.haml' post '/scores/refresh', -> ScoreCalculator.calculate (scores) => res = @res team_ids = k for k, v of scores save = (error, saved) -> return res.send sys.inspect(error), 500 if error? if team_id = team_ids.pop() Team.updateAll team_id, { $set: { score: scores[team_id] }}, save else res.send 'OK', 200 save() # list teams get '/teams', -> q = if @req.param('invalid') then { url: /\w/, validDeploy: false } else { validDeploy: true } Team.all q, { deep: false, sort: [['score.overall', -1]] }, (error, teams) => @teams = teams @render 'teams/index.html.haml' # new team get '/teams/new', -> return @redirect '/' unless @isAdmin @team = new Team {}, => @render 'teams/new.html.haml' # create team post '/teams', -> return @redirect '/' unless @isAdmin @team = new Team @req.body, => @team.save (errors, res) => if errors? @errors = errors @render 'teams/new.html.haml' else @cookie 'teamAuthKey', @team.authKey() @redirect '/teams/' + @team.toParam() # show team get '/teams/:id', -> @requestAt = Date.now() Team.fromParam @req.param('id'), (error, team) => if team? @team = team @title = @team.name @editAllowed = @canEditTeam team @votingOpen = Date.now() < Date.UTC(2010, 8, 2, 23, 59, 59) people = team.members or [] @members = _.select people, (person) -> person.name @invites = _.without people, @members... renderVotes = => Vote.all { 'team._id': team._id }, { 'sort': [['createdAt', -1]], limit: 50 }, (error, votes) => @votes = votes for vote in @votes vote.team = @team vote.instantiateReplyers() @render 'teams/show.html.haml' if @currentPerson Vote.firstByTeamAndPerson team, @currentPerson, (error, vote) => @vote = vote or new Vote(null, @req) @vote.person = @currentPerson @vote.email = @vote.person.email renderVotes() else @vote = new Vote(null, @req) renderVotes() else # TODO make this a 404 @redirect '/' # edit team get '/teams/:id/edit', -> Team.fromParam @req.param('id'), (error, team) => @ensurePermitted team, => @team = team @render 'teams/edit.html.haml' # update team put '/teams/:id', -> Team.fromParam @req.param('id'), (error, team) => @ensurePermitted team, => delete @req.body.score team.update @req.body team.validDeploy = @req.body.validDeploy == '1' save = => team.save (errors, result) => if errors? @errors = errors @team = team if @req.xhr @res.send 'ERROR', 500 else @render 'teams/edit.html.haml' else if @req.xhr @res.send 'OK', 200 else @redirect '/teams/' + team.toParam() # TODO shouldn't need this if @req.body.emails team.setMembers @req.body.emails, save else save() # delete team del '/teams/:id', -> Team.fromParam @req.param('id'), (error, team) => @ensurePermitted team, => team.remove (error, result) => @redirect '/' # resend invitation get '/teams/:teamId/invite/:personId', -> Team.fromParam @req.param('teamId'), (error, team) => @ensurePermitted team, => Person.fromParam @req.param('personId'), (error, person) => person.inviteTo team, => if @req.xhr @res.send 'OK', 200 else # TODO flash "Sent a new invitation to $@person.email" @redirect '/teams/' + team.toParam() saveVote = -> @vote.save (errors, res) => if errors? if errors[0] is 'Unauthorized' # TODO flash "You must login to vote as #{@vote.email}." @res.send 'Unauthorized', 403 else @res.send JSON.stringify(errors), 400 else # TODO flash "You are now logged into Node Knockout as #{@vote.email}." @setCurrentPerson @vote.person if @vote.person? and !@currentPerson? @vote.instantiateReplyers() @votes = [@vote] @render 'partials/votes/index.html.jade', { layout: false } # create vote post '/teams/:teamId/votes', -> return @next() Team.fromParam @req.param('teamId'), (error, team) => # TODO: handle error @vote = new Vote @req.body, @req @vote.team = @team = team @vote.person = @currentPerson @vote.email ?= @vote.person?.email @vote.responseAt = Date.now() saveVote.call(this) put '/teams/:teamId/votes/:voteId', -> return @next() Team.fromParam @req.param('teamId'), (error, team) => Vote.fromParam @req.param('voteId'), (error, vote) => @ensurePermitted vote, => @noHeader = true @vote = vote @vote.team = team vote.update @req.body saveVote.call(this) post '/teams/:teamId/votes/:voteId/replies', -> Team.fromParam @req.param('teamId'), (error, team) => Vote.fromParam @req.param('voteId'), (error, vote) => vote.team = team vote.instantiateReplyers() unless @canReplyTo(vote) return @res.send 'Unauthorized: only the voter and team members may comment on a vote.', 403 else @reply = new Reply { person: @currentPerson, vote: vote, body: @req.body.body } @reply.save (errors, reply) => if errors? @res.send JSON.stringify(errors), 400 else vote.replies.push @reply vote.notifyPeopleAboutReply @reply @render 'partials/replies/reply.html.jade', { locals: { reply: @reply, vote: vote, ctx: this }, layout: false } # list votes get '/teams/:teamId/votes', -> @redirect '/teams/' + @req.param('teamId') get '/teams/:teamId/votes.js', -> skip = 50 * ((@req.query['page'] || 1)-1) Team.fromParam @req.param('teamId'), (error, team) => # TODO: handle error Vote.all { 'team._id': team._id }, { 'sort': [['createdAt', -1]], skip: skip, limit: 50 }, (error, votes) => @votes = votes for vote in @votes vote.team = team vote.instantiateReplyers() @render 'partials/votes/index.html.jade', { layout: false } # sign in get '/login', -> @person = new Person() @render 'login.html.haml' post '/login', -> Person.login @req.body, (error, person) => if person? if @req.param 'remember' d = new Date() d.setTime(d.getTime() + 1000 * 60 * 60 * 24 * 180) options = { expires: d } @setCurrentPerson person, options if person.name if returnTo = @req.param('return_to') @redirect returnTo else @redirect '/people/' + person.toParam() else @redirect '/people/' + person.toParam() + '/edit' else @errors = error @person = new Person(@req.body) @render 'login.html.haml' get '/logout', -> @logout => @redirect(@req.param('return_to') || @req.headers.referer || '/') # reset password post '/reset_password', -> Person.first { email: @req.param('email') }, (error, person) => # TODO assumes xhr unless person? @res.send 'Email not found', 404 else person.resetPassword => @res.send 'OK', 200 # new judge get '/judges/new', -> @person = new Person({ type: 'Judge' }) @ensurePermitted @person, => @render 'judges/new.html.haml' get '/judges|/judging', -> Person.all { type: 'Judge' }, (error, judges) => @judges = _.shuffle judges @render 'judges/index.html.jade', { layout: 'layout.haml' } # create person post '/people', -> @person = new Person @req.body @ensurePermitted @person, => @person.save (error, res) => # TODO send confirmation email @redirect '/people/' + @person.toParam() # edit person get '/people/:id/edit', -> Person.fromParam @req.param('id'), (error, person) => @ensurePermitted person, => @person = person @render 'people/edit.html.haml' # show person get '/people/:id', -> Person.fromParam @req.param('id'), (error, person) => @person = person @isCurrentPerson = @person.id() is @currentPerson?.id() @person.loadTeams => @person.loadVotes => @showTeam = true @votes = @person.votes @render 'people/show.html.haml' # update person put '/people/:id', -> Person.fromParam @req.param('id'), (error, person) => @ensurePermitted person, => attributes = @req.body if attributes.password person.confirmKey = Math.uuid() # TODO this shouldn't be necessary person.setPassword attributes.password delete attributes.password attributes.link = '' unless /^https?:\/\/.+\./.test attributes.link if attributes.email? && attributes.email != person.email person.confirmed = attributes.confimed = false person.github ||= '' person.update attributes person.save (error, resp) => @redirect '/people/' + person.toParam() # delete person del '/people/:id', -> Person.fromParam @req.param('id'), (error, person) => @ensurePermitted person, => person.remove (error, result) => @redirect '/' post '/people/:id/confirm', -> Person.fromParam @req.param('id'), (error, person) => person.confirmKey = PI:KEY:<KEY>END_PI() person.save => person.sendConfirmKey => @redirect '/people/' + person.toParam() + '/confirm' get '/people/:id/confirm', -> @confirmKey = @req.param('confirmKey') return @render 'people/confirm.html.jade', { layout: 'layout.haml' } unless @confirmKey Person.fromParam @req.param('id'), (error, person) => if not person? @res.send 'Not found', 404 else if @confirmKey? and person.confirmed @person = person @render 'people/confirm.html.jade', { layout: 'layout.haml' } else if @confirmKey? and person.confirmKey isnt @confirmKey @errors = ['Invalid confirmation key. Please check your email for the correct key.'] return @render 'people/confirm.html.jade', { layout: 'layout.haml' } else person.verifiedConfirmKey = true person.login => @setCurrentPerson person @person = person @render 'people/confirm.html.jade', { layout: 'layout.haml' } # TODO security post '/deploys', -> # user: 'PI:EMAIL:<EMAIL>END_PI' # head: '87eaeb6' # app: 'visnup-nko' # url: 'http://visnup-nko.heroku.com' # git_log: '' # prev_head: '' # head_long: '87eaeb69d726593de6a47a5f38ff6126fd3920fa' query = {} deployedTo = if /\.no\.de$/.test(@req.param('url')) then 'joyent' else 'heroku' query[deployedTo + 'Slug'] = @req.param('app') Team.first query, (error, team) => if team team.url = @req.param('url') team.lastDeployedTo = deployedTo team.lastDeployedAt = new Date() team.lastDeployedHead = @req.param('head') team.lastDeployedHeadLong = @req.param('head_long') team.deployHeads.push team.lastDeployedHeadLong team.save(->) @render 'deploys/ok.html.haml', { layout: false } get '/prizes', -> @render 'prizes.html.jade', { layout: 'layout.haml' } get '/*', -> try @render "#{@req.params[0]}.html.haml" catch e throw e if e.errno != 2 @next() app.helpers { pluralize: (n, str) -> if n == 1 n + ' ' + str else n + ' ' + str + 's' escapeURL: require('querystring').escape markdown: require('markdown').toHTML firstParagraph: (md) -> markdown = require 'markdown' tree = markdown.parse md p = _.detect tree, (e) -> e[0] == 'para' if p then markdown.toHTML p else '' gravatar: (p, s) -> return '' unless p? if p.type is 'Judge' "<img src=\"/images/judges/#{p.name.replace(/\W+/g, '_')}.jpg\" width=#{s || 40} />" else "<img src=\"http://www.gravatar.com/avatar/#{p.emailHash}?s=#{s || 40}&d=monsterid\" />" } _.shuffle = (a) -> r = _.clone a for i in [r.length-1 .. 0] j = parseInt(Math.random() * i) [r[i], r[j]] = [r[j], r[i]] r # has to be last app.use '/', express.errorHandler({ dumpExceptions: true, showStack: true }) server = app.listen parseInt(process.env.PORT || 8000), null
[ { "context": ")\", \"[')ž{-,}P{Any}',')',undefined]\"\nregexp52 = /(Rob)|(Bob)|(Robert)|(Bobby)/\nshouldBe \"'Hi Bob'.match", "end": 10158, "score": 0.9965910911560059, "start": 10155, "tag": "NAME", "value": "Rob" }, { "context": "')ž{-,}P{Any}',')',undefined]\"\nregexp52 = /(Rob)|(...
deps/v8/test/webkit/fast/regex/parentheses.coffee
lxe/io.coffee
0
# Copyright 2013 the V8 project authors. All rights reserved. # Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. description "This page tests handling of parentheses subexpressions." regexp1 = /(a|A)(b|B)/ shouldBe "regexp1.exec('abc')", "['ab','a','b']" regexp2 = /(a((b)|c|d))e/ shouldBe "regexp2.exec('abacadabe')", "['abe','ab','b','b']" regexp3 = /(a(b|(c)|d))e/ shouldBe "regexp3.exec('abacadabe')", "['abe','ab','b',undefined]" regexp4 = /(a(b|c|(d)))e/ shouldBe "regexp4.exec('abacadabe')", "['abe','ab','b',undefined]" regexp5 = /(a((b)|(c)|(d)))e/ shouldBe "regexp5.exec('abacadabe')", "['abe','ab','b','b',undefined,undefined]" regexp6 = /(a((b)|(c)|(d)))/ shouldBe "regexp6.exec('abcde')", "['ab','ab','b','b',undefined,undefined]" regexp7 = /(a(b)??)??c/ shouldBe "regexp7.exec('abc')", "['abc','ab','b']" regexp8 = /(a|(e|q))(x|y)/ shouldBe "regexp8.exec('bcaddxqy')", "['qy','q','q','y']" regexp9 = /((t|b)?|a)$/ shouldBe "regexp9.exec('asdfjejgsdflaksdfjkeljghkjea')", "['a','a',undefined]" regexp10 = /(?:h|e?(?:t|b)?|a?(?:t|b)?)(?:$)/ shouldBe "regexp10.exec('asdfjejgsdflaksdfjkeljghat')", "['at']" regexp11 = /([Jj]ava([Ss]cript)?)\sis\s(fun\w*)/ shouldBeNull "regexp11.exec('Developing with JavaScript is dangerous, do not try it without assistance')" regexp12 = /(?:(.+), )?(.+), (..) to (?:(.+), )?(.+), (..)/ shouldBe "regexp12.exec('Seattle, WA to Buckley, WA')", "['Seattle, WA to Buckley, WA', undefined, 'Seattle', 'WA', undefined, 'Buckley', 'WA']" regexp13 = /(A)?(A.*)/ shouldBe "regexp13.exec('zxcasd;fl ^AaaAAaaaf;lrlrzs')", "['AaaAAaaaf;lrlrzs',undefined,'AaaAAaaaf;lrlrzs']" regexp14 = /(a)|(b)/ shouldBe "regexp14.exec('b')", "['b',undefined,'b']" regexp15 = /^(?!(ab)de|x)(abd)(f)/ shouldBe "regexp15.exec('abdf')", "['abdf',undefined,'abd','f']" regexp16 = /(a|A)(b|B)/ shouldBe "regexp16.exec('abc')", "['ab','a','b']" regexp17 = /(a|d|q|)x/i shouldBe "regexp17.exec('bcaDxqy')", "['Dx','D']" regexp18 = /^.*?(:|$)/ shouldBe "regexp18.exec('Hello: World')", "['Hello:',':']" regexp19 = /(ab|^.{0,2})bar/ shouldBe "regexp19.exec('barrel')", "['bar','']" regexp20 = /(?:(?!foo)...|^.{0,2})bar(.*)/ shouldBe "regexp20.exec('barrel')", "['barrel','rel']" shouldBe "regexp20.exec('2barrel')", "['2barrel','rel']" regexp21 = /([a-g](b|B)|xyz)/ shouldBe "regexp21.exec('abc')", "['ab','ab','b']" regexp22 = /(?:^|;)\s*abc=([^;]*)/ shouldBeNull "regexp22.exec('abcdlskfgjdslkfg')" regexp23 = /"[^<"]*"|'[^<']*'/ shouldBe "regexp23.exec('<html xmlns=\"http://www.w3.org/1999/xhtml\"')", "['\"http://www.w3.org/1999/xhtml\"']" regexp24 = /^(?:(?=abc)\w{3}:|\d\d)$/ shouldBeNull "regexp24.exec('123')" regexp25 = /^\s*(\*|[\w\-]+)(\b|$)?/ shouldBe "regexp25.exec('this is a test')", "['this','this',undefined]" shouldBeNull "regexp25.exec('!this is a test')" regexp26 = /a(b)(a*)|aaa/ shouldBe "regexp26.exec('aaa')", "['aaa',undefined,undefined]" # scheme # authorityRoot # authority # userInfo # user # password # domain # port #path # queryString regexp27 = new RegExp("^" + "(?:" + "([^:/?#]+):" + ")?" + "(?:" + "(//)" + "(" + "(?:" + "(" + "([^:@]*)" + ":?" + "([^:@]*)" + ")?" + "@" + ")?" + "([^:/?#]*)" + "(?::(\\d*))?" + ")" + ")?" + "([^?#]*)" + "(?:\\?([^#]*))?" + "(?:#(.*))?") #fragment shouldBe "regexp27.exec('file:///Users/Someone/Desktop/HelloWorld/index.html')", "['file:///Users/Someone/Desktop/HelloWorld/index.html','file','//','',undefined,undefined,undefined,'',undefined,'/Users/Someone/Desktop/HelloWorld/index.html',undefined,undefined]" # scheme # authorityRoot # authority # userInfo # user # password regexp28 = new RegExp("^" + "(?:" + "([^:/?#]+):" + ")?" + "(?:" + "(//)" + "(" + "(" + "([^:@]*)" + ":?" + "([^:@]*)" + ")?" + "@" + ")" + ")?") shouldBe "regexp28.exec('file:///Users/Someone/Desktop/HelloWorld/index.html')", "['file:','file',undefined,undefined,undefined,undefined,undefined]" regexp29 = /^\s*((\[[^\]]+\])|(u?)("[^"]+"))\s*/ shouldBeNull "regexp29.exec('Committer:')" regexp30 = /^\s*((\[[^\]]+\])|m(u?)("[^"]+"))\s*/ shouldBeNull "regexp30.exec('Committer:')" regexp31 = /^\s*(m(\[[^\]]+\])|m(u?)("[^"]+"))\s*/ shouldBeNull "regexp31.exec('Committer:')" regexp32 = /\s*(m(\[[^\]]+\])|m(u?)("[^"]+"))\s*/ shouldBeNull "regexp32.exec('Committer:')" regexp33 = RegExp("^(?:(?:(a)(xyz|[^>\"'s]*)?)|(/?>)|.[^ws>]*)") shouldBe "regexp33.exec('> <head>')", "['>',undefined,undefined,'>']" regexp34 = /(?:^|\b)btn-\S+/ shouldBeNull "regexp34.exec('xyz123')" shouldBe "regexp34.exec('btn-abc')", "['btn-abc']" shouldBeNull "regexp34.exec('btn- abc')" shouldBeNull "regexp34.exec('XXbtn-abc')" shouldBe "regexp34.exec('XX btn-abc')", "['btn-abc']" regexp35 = /^((a|b)(x|xxx)|)$/ shouldBe "regexp35.exec('ax')", "['ax','ax','a','x']" shouldBeNull "regexp35.exec('axx')" shouldBe "regexp35.exec('axxx')", "['axxx','axxx','a','xxx']" shouldBe "regexp35.exec('bx')", "['bx','bx','b','x']" shouldBeNull "regexp35.exec('bxx')" shouldBe "regexp35.exec('bxxx')", "['bxxx','bxxx','b','xxx']" regexp36 = /^((\/|\.|\-)(\d\d|\d\d\d\d)|)$/ shouldBe "regexp36.exec('/2011')", "['/2011','/2011','/','2011']" shouldBe "regexp36.exec('/11')", "['/11','/11','/','11']" shouldBeNull "regexp36.exec('/123')" regexp37 = /^([1][0-2]|[0]\d|\d)(\/|\.|\-)([0-2]\d|[3][0-1]|\d)((\/|\.|\-)(\d\d|\d\d\d\d)|)$/ shouldBe "regexp37.exec('7/4/1776')", "['7/4/1776','7','/','4','/1776','/','1776']" shouldBe "regexp37.exec('07-04-1776')", "['07-04-1776','07','-','04','-1776','-','1776']" regexp38 = /^(z|(x|xx)|b|)$/ shouldBe "regexp38.exec('xx')", "['xx','xx','xx']" shouldBe "regexp38.exec('b')", "['b','b',undefined]" shouldBe "regexp38.exec('z')", "['z','z',undefined]" shouldBe "regexp38.exec('')", "['','',undefined]" regexp39 = /(8|((?=P)))?/ shouldBe "regexp39.exec('')", "['',undefined,undefined]" shouldBe "regexp39.exec('8')", "['8','8',undefined]" shouldBe "regexp39.exec('zP')", "['',undefined,undefined]" regexp40 = /((8)|((?=P){4}))?()/ shouldBe "regexp40.exec('')", "['',undefined,undefined,undefined,'']" shouldBe "regexp40.exec('8')", "['8','8','8',undefined,'']" shouldBe "regexp40.exec('zPz')", "['',undefined,undefined,undefined,'']" shouldBe "regexp40.exec('zPPz')", "['',undefined,undefined,undefined,'']" shouldBe "regexp40.exec('zPPPz')", "['',undefined,undefined,undefined,'']" shouldBe "regexp40.exec('zPPPPz')", "['',undefined,undefined,undefined,'']" regexp41 = /(([\w\-]+:\/\/?|www[.])[^\s()<>]+(?:([\w\d]+)|([^\[:punct:\]\s()<>\W]|\/)))/ shouldBe "regexp41.exec('Here is a link: http://www.acme.com/our_products/index.html. That is all we want!')", "['http://www.acme.com/our_products/index.html','http://www.acme.com/our_products/index.html','http://','l',undefined]" regexp42 = /((?:(4)?))?/ shouldBe "regexp42.exec('')", "['',undefined,undefined]" shouldBe "regexp42.exec('4')", "['4','4','4']" shouldBe "regexp42.exec('4321')", "['4','4','4']" shouldBeTrue "/(?!(?=r{0}){2,})|((z)?)?/gi.test('')" regexp43 = /(?!(?:\1+s))/ shouldBe "regexp43.exec('SSS')", "['']" regexp44 = /(?!(?:\3+(s+?)))/g shouldBe "regexp44.exec('SSS')", "['',undefined]" regexp45 = /((?!(?:|)v{2,}|))/ shouldBeNull "regexp45.exec('vt')" regexp46 = /(w)(?:5{3}|())|pk/ shouldBeNull "regexp46.exec('5')" shouldBe "regexp46.exec('pk')", "['pk',undefined,undefined]" shouldBe "regexp46.exec('Xw555')", "['w555','w',undefined]" shouldBe "regexp46.exec('Xw55pk5')", "['w','w','']" regexp47 = /(.*?)(?:(?:\?(.*?)?)?)(?:(?:#)?)$/ shouldBe "regexp47.exec('/www.acme.com/this/is/a/path/file.txt')", "['/www.acme.com/this/is/a/path/file.txt','/www.acme.com/this/is/a/path/file.txt',undefined]" regexp48 = /^(?:(\w+):\/*([\w\.\-\d]+)(?::(\d+)|)(?=(?:\/|$))|)(?:$|\/?(.*?)(?:\?(.*?)?|)(?:#(.*)|)$)/ # The regexp on the prior line confuses Xcode syntax highlighting, this coment fixes it! shouldBe "regexp48.exec('http://www.acme.com/this/is/a/path/file.txt')", "['http://www.acme.com/this/is/a/path/file.txt','http','www.acme.com',undefined,'this/is/a/path/file.txt',undefined,undefined]" regexp49 = /(?:([^:]*?)(?:(?:\?(.*?)?)?)(?:(?:#)?)$)|(?:^(?:(\w+):\/*([\w\.\-\d]+)(?::(\d+)|)(?=(?:\/|$))|)(?:$|\/?(.*?)(?:\?(.*?)?|)(?:#(.*)|)$))/ # The regexp on the prior line confuses Xcode syntax highlighting, this coment fixes it! shouldBe "regexp49.exec('http://www.acme.com/this/is/a/path/file.txt')", "['http://www.acme.com/this/is/a/path/file.txt',undefined,undefined,'http','www.acme.com',undefined,'this/is/a/path/file.txt',undefined,undefined]" regexp50 = /((a)b{28,}c|d)x/ shouldBeNull "regexp50.exec('((a)b{28,}c|d)x')" shouldBe "regexp50.exec('abbbbbbbbbbbbbbbbbbbbbbbbbbbbcx')", "['abbbbbbbbbbbbbbbbbbbbbbbbbbbbcx', 'abbbbbbbbbbbbbbbbbbbbbbbbbbbbc', 'a']" shouldBe "regexp50.exec('dx')", "['dx', 'd', undefined]" s = "((.s{-}).{28,}P{Yi}?{,30}|.)ž{-,}P{Any}" regexp51 = new RegExp(s) shouldBeNull "regexp51.exec('abc')" shouldBe "regexp51.exec(s)", "[')ž{-,}P{Any}',')',undefined]" regexp52 = /(Rob)|(Bob)|(Robert)|(Bobby)/ shouldBe "'Hi Bob'.match(regexp52)", "['Bob',undefined,'Bob',undefined,undefined]" # Test cases discovered by fuzzing that crashed the compiler. regexp53 = /(?=(?:(?:(gB)|(?!cs|<))((?=(?!v6){0,})))|(?=#)+?)/m shouldBe "regexp53.exec('#')", "['',undefined,'']" regexp54 = /((?:(?:()|(?!))((?=(?!))))|())/m shouldBe "regexp54.exec('#')", "['','',undefined,undefined,'']" regexp55 = /(?:(?:(?:a?|(?:))((?:)))|a?)/m shouldBe "regexp55.exec('#')", "['','']" # Test evaluation order of empty subpattern alternatives. regexp56 = /(|a)/ shouldBe "regexp56.exec('a')", "['','']" regexp57 = /(a|)/ shouldBe "regexp57.exec('a')", "['a','a']" # Tests that non-greedy repeat quantified parentheses will backtrack through multiple frames of subpattern matches. regexp58 = /a|b(?:[^b])*?c/ shouldBe "regexp58.exec('badbc')", "['a']" regexp59 = /(X(?:.(?!X))*?Y)|(Y(?:.(?!Y))*?Z)/g shouldBe "'Y aaa X Match1 Y aaa Y Match2 Z'.match(regexp59)", "['X Match1 Y','Y Match2 Z']"
28254
# Copyright 2013 the V8 project authors. All rights reserved. # Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. description "This page tests handling of parentheses subexpressions." regexp1 = /(a|A)(b|B)/ shouldBe "regexp1.exec('abc')", "['ab','a','b']" regexp2 = /(a((b)|c|d))e/ shouldBe "regexp2.exec('abacadabe')", "['abe','ab','b','b']" regexp3 = /(a(b|(c)|d))e/ shouldBe "regexp3.exec('abacadabe')", "['abe','ab','b',undefined]" regexp4 = /(a(b|c|(d)))e/ shouldBe "regexp4.exec('abacadabe')", "['abe','ab','b',undefined]" regexp5 = /(a((b)|(c)|(d)))e/ shouldBe "regexp5.exec('abacadabe')", "['abe','ab','b','b',undefined,undefined]" regexp6 = /(a((b)|(c)|(d)))/ shouldBe "regexp6.exec('abcde')", "['ab','ab','b','b',undefined,undefined]" regexp7 = /(a(b)??)??c/ shouldBe "regexp7.exec('abc')", "['abc','ab','b']" regexp8 = /(a|(e|q))(x|y)/ shouldBe "regexp8.exec('bcaddxqy')", "['qy','q','q','y']" regexp9 = /((t|b)?|a)$/ shouldBe "regexp9.exec('asdfjejgsdflaksdfjkeljghkjea')", "['a','a',undefined]" regexp10 = /(?:h|e?(?:t|b)?|a?(?:t|b)?)(?:$)/ shouldBe "regexp10.exec('asdfjejgsdflaksdfjkeljghat')", "['at']" regexp11 = /([Jj]ava([Ss]cript)?)\sis\s(fun\w*)/ shouldBeNull "regexp11.exec('Developing with JavaScript is dangerous, do not try it without assistance')" regexp12 = /(?:(.+), )?(.+), (..) to (?:(.+), )?(.+), (..)/ shouldBe "regexp12.exec('Seattle, WA to Buckley, WA')", "['Seattle, WA to Buckley, WA', undefined, 'Seattle', 'WA', undefined, 'Buckley', 'WA']" regexp13 = /(A)?(A.*)/ shouldBe "regexp13.exec('zxcasd;fl ^AaaAAaaaf;lrlrzs')", "['AaaAAaaaf;lrlrzs',undefined,'AaaAAaaaf;lrlrzs']" regexp14 = /(a)|(b)/ shouldBe "regexp14.exec('b')", "['b',undefined,'b']" regexp15 = /^(?!(ab)de|x)(abd)(f)/ shouldBe "regexp15.exec('abdf')", "['abdf',undefined,'abd','f']" regexp16 = /(a|A)(b|B)/ shouldBe "regexp16.exec('abc')", "['ab','a','b']" regexp17 = /(a|d|q|)x/i shouldBe "regexp17.exec('bcaDxqy')", "['Dx','D']" regexp18 = /^.*?(:|$)/ shouldBe "regexp18.exec('Hello: World')", "['Hello:',':']" regexp19 = /(ab|^.{0,2})bar/ shouldBe "regexp19.exec('barrel')", "['bar','']" regexp20 = /(?:(?!foo)...|^.{0,2})bar(.*)/ shouldBe "regexp20.exec('barrel')", "['barrel','rel']" shouldBe "regexp20.exec('2barrel')", "['2barrel','rel']" regexp21 = /([a-g](b|B)|xyz)/ shouldBe "regexp21.exec('abc')", "['ab','ab','b']" regexp22 = /(?:^|;)\s*abc=([^;]*)/ shouldBeNull "regexp22.exec('abcdlskfgjdslkfg')" regexp23 = /"[^<"]*"|'[^<']*'/ shouldBe "regexp23.exec('<html xmlns=\"http://www.w3.org/1999/xhtml\"')", "['\"http://www.w3.org/1999/xhtml\"']" regexp24 = /^(?:(?=abc)\w{3}:|\d\d)$/ shouldBeNull "regexp24.exec('123')" regexp25 = /^\s*(\*|[\w\-]+)(\b|$)?/ shouldBe "regexp25.exec('this is a test')", "['this','this',undefined]" shouldBeNull "regexp25.exec('!this is a test')" regexp26 = /a(b)(a*)|aaa/ shouldBe "regexp26.exec('aaa')", "['aaa',undefined,undefined]" # scheme # authorityRoot # authority # userInfo # user # password # domain # port #path # queryString regexp27 = new RegExp("^" + "(?:" + "([^:/?#]+):" + ")?" + "(?:" + "(//)" + "(" + "(?:" + "(" + "([^:@]*)" + ":?" + "([^:@]*)" + ")?" + "@" + ")?" + "([^:/?#]*)" + "(?::(\\d*))?" + ")" + ")?" + "([^?#]*)" + "(?:\\?([^#]*))?" + "(?:#(.*))?") #fragment shouldBe "regexp27.exec('file:///Users/Someone/Desktop/HelloWorld/index.html')", "['file:///Users/Someone/Desktop/HelloWorld/index.html','file','//','',undefined,undefined,undefined,'',undefined,'/Users/Someone/Desktop/HelloWorld/index.html',undefined,undefined]" # scheme # authorityRoot # authority # userInfo # user # password regexp28 = new RegExp("^" + "(?:" + "([^:/?#]+):" + ")?" + "(?:" + "(//)" + "(" + "(" + "([^:@]*)" + ":?" + "([^:@]*)" + ")?" + "@" + ")" + ")?") shouldBe "regexp28.exec('file:///Users/Someone/Desktop/HelloWorld/index.html')", "['file:','file',undefined,undefined,undefined,undefined,undefined]" regexp29 = /^\s*((\[[^\]]+\])|(u?)("[^"]+"))\s*/ shouldBeNull "regexp29.exec('Committer:')" regexp30 = /^\s*((\[[^\]]+\])|m(u?)("[^"]+"))\s*/ shouldBeNull "regexp30.exec('Committer:')" regexp31 = /^\s*(m(\[[^\]]+\])|m(u?)("[^"]+"))\s*/ shouldBeNull "regexp31.exec('Committer:')" regexp32 = /\s*(m(\[[^\]]+\])|m(u?)("[^"]+"))\s*/ shouldBeNull "regexp32.exec('Committer:')" regexp33 = RegExp("^(?:(?:(a)(xyz|[^>\"'s]*)?)|(/?>)|.[^ws>]*)") shouldBe "regexp33.exec('> <head>')", "['>',undefined,undefined,'>']" regexp34 = /(?:^|\b)btn-\S+/ shouldBeNull "regexp34.exec('xyz123')" shouldBe "regexp34.exec('btn-abc')", "['btn-abc']" shouldBeNull "regexp34.exec('btn- abc')" shouldBeNull "regexp34.exec('XXbtn-abc')" shouldBe "regexp34.exec('XX btn-abc')", "['btn-abc']" regexp35 = /^((a|b)(x|xxx)|)$/ shouldBe "regexp35.exec('ax')", "['ax','ax','a','x']" shouldBeNull "regexp35.exec('axx')" shouldBe "regexp35.exec('axxx')", "['axxx','axxx','a','xxx']" shouldBe "regexp35.exec('bx')", "['bx','bx','b','x']" shouldBeNull "regexp35.exec('bxx')" shouldBe "regexp35.exec('bxxx')", "['bxxx','bxxx','b','xxx']" regexp36 = /^((\/|\.|\-)(\d\d|\d\d\d\d)|)$/ shouldBe "regexp36.exec('/2011')", "['/2011','/2011','/','2011']" shouldBe "regexp36.exec('/11')", "['/11','/11','/','11']" shouldBeNull "regexp36.exec('/123')" regexp37 = /^([1][0-2]|[0]\d|\d)(\/|\.|\-)([0-2]\d|[3][0-1]|\d)((\/|\.|\-)(\d\d|\d\d\d\d)|)$/ shouldBe "regexp37.exec('7/4/1776')", "['7/4/1776','7','/','4','/1776','/','1776']" shouldBe "regexp37.exec('07-04-1776')", "['07-04-1776','07','-','04','-1776','-','1776']" regexp38 = /^(z|(x|xx)|b|)$/ shouldBe "regexp38.exec('xx')", "['xx','xx','xx']" shouldBe "regexp38.exec('b')", "['b','b',undefined]" shouldBe "regexp38.exec('z')", "['z','z',undefined]" shouldBe "regexp38.exec('')", "['','',undefined]" regexp39 = /(8|((?=P)))?/ shouldBe "regexp39.exec('')", "['',undefined,undefined]" shouldBe "regexp39.exec('8')", "['8','8',undefined]" shouldBe "regexp39.exec('zP')", "['',undefined,undefined]" regexp40 = /((8)|((?=P){4}))?()/ shouldBe "regexp40.exec('')", "['',undefined,undefined,undefined,'']" shouldBe "regexp40.exec('8')", "['8','8','8',undefined,'']" shouldBe "regexp40.exec('zPz')", "['',undefined,undefined,undefined,'']" shouldBe "regexp40.exec('zPPz')", "['',undefined,undefined,undefined,'']" shouldBe "regexp40.exec('zPPPz')", "['',undefined,undefined,undefined,'']" shouldBe "regexp40.exec('zPPPPz')", "['',undefined,undefined,undefined,'']" regexp41 = /(([\w\-]+:\/\/?|www[.])[^\s()<>]+(?:([\w\d]+)|([^\[:punct:\]\s()<>\W]|\/)))/ shouldBe "regexp41.exec('Here is a link: http://www.acme.com/our_products/index.html. That is all we want!')", "['http://www.acme.com/our_products/index.html','http://www.acme.com/our_products/index.html','http://','l',undefined]" regexp42 = /((?:(4)?))?/ shouldBe "regexp42.exec('')", "['',undefined,undefined]" shouldBe "regexp42.exec('4')", "['4','4','4']" shouldBe "regexp42.exec('4321')", "['4','4','4']" shouldBeTrue "/(?!(?=r{0}){2,})|((z)?)?/gi.test('')" regexp43 = /(?!(?:\1+s))/ shouldBe "regexp43.exec('SSS')", "['']" regexp44 = /(?!(?:\3+(s+?)))/g shouldBe "regexp44.exec('SSS')", "['',undefined]" regexp45 = /((?!(?:|)v{2,}|))/ shouldBeNull "regexp45.exec('vt')" regexp46 = /(w)(?:5{3}|())|pk/ shouldBeNull "regexp46.exec('5')" shouldBe "regexp46.exec('pk')", "['pk',undefined,undefined]" shouldBe "regexp46.exec('Xw555')", "['w555','w',undefined]" shouldBe "regexp46.exec('Xw55pk5')", "['w','w','']" regexp47 = /(.*?)(?:(?:\?(.*?)?)?)(?:(?:#)?)$/ shouldBe "regexp47.exec('/www.acme.com/this/is/a/path/file.txt')", "['/www.acme.com/this/is/a/path/file.txt','/www.acme.com/this/is/a/path/file.txt',undefined]" regexp48 = /^(?:(\w+):\/*([\w\.\-\d]+)(?::(\d+)|)(?=(?:\/|$))|)(?:$|\/?(.*?)(?:\?(.*?)?|)(?:#(.*)|)$)/ # The regexp on the prior line confuses Xcode syntax highlighting, this coment fixes it! shouldBe "regexp48.exec('http://www.acme.com/this/is/a/path/file.txt')", "['http://www.acme.com/this/is/a/path/file.txt','http','www.acme.com',undefined,'this/is/a/path/file.txt',undefined,undefined]" regexp49 = /(?:([^:]*?)(?:(?:\?(.*?)?)?)(?:(?:#)?)$)|(?:^(?:(\w+):\/*([\w\.\-\d]+)(?::(\d+)|)(?=(?:\/|$))|)(?:$|\/?(.*?)(?:\?(.*?)?|)(?:#(.*)|)$))/ # The regexp on the prior line confuses Xcode syntax highlighting, this coment fixes it! shouldBe "regexp49.exec('http://www.acme.com/this/is/a/path/file.txt')", "['http://www.acme.com/this/is/a/path/file.txt',undefined,undefined,'http','www.acme.com',undefined,'this/is/a/path/file.txt',undefined,undefined]" regexp50 = /((a)b{28,}c|d)x/ shouldBeNull "regexp50.exec('((a)b{28,}c|d)x')" shouldBe "regexp50.exec('abbbbbbbbbbbbbbbbbbbbbbbbbbbbcx')", "['abbbbbbbbbbbbbbbbbbbbbbbbbbbbcx', 'abbbbbbbbbbbbbbbbbbbbbbbbbbbbc', 'a']" shouldBe "regexp50.exec('dx')", "['dx', 'd', undefined]" s = "((.s{-}).{28,}P{Yi}?{,30}|.)ž{-,}P{Any}" regexp51 = new RegExp(s) shouldBeNull "regexp51.exec('abc')" shouldBe "regexp51.exec(s)", "[')ž{-,}P{Any}',')',undefined]" regexp52 = /(<NAME>)|(<NAME>)|(<NAME>)|(<NAME>)/ shouldBe "'Hi <NAME>'.match(regexp52)", "['Bob',undefined,'Bob',undefined,undefined]" # Test cases discovered by fuzzing that crashed the compiler. regexp53 = /(?=(?:(?:(gB)|(?!cs|<))((?=(?!v6){0,})))|(?=#)+?)/m shouldBe "regexp53.exec('#')", "['',undefined,'']" regexp54 = /((?:(?:()|(?!))((?=(?!))))|())/m shouldBe "regexp54.exec('#')", "['','',undefined,undefined,'']" regexp55 = /(?:(?:(?:a?|(?:))((?:)))|a?)/m shouldBe "regexp55.exec('#')", "['','']" # Test evaluation order of empty subpattern alternatives. regexp56 = /(|a)/ shouldBe "regexp56.exec('a')", "['','']" regexp57 = /(a|)/ shouldBe "regexp57.exec('a')", "['a','a']" # Tests that non-greedy repeat quantified parentheses will backtrack through multiple frames of subpattern matches. regexp58 = /a|b(?:[^b])*?c/ shouldBe "regexp58.exec('badbc')", "['a']" regexp59 = /(X(?:.(?!X))*?Y)|(Y(?:.(?!Y))*?Z)/g shouldBe "'Y aaa X Match1 Y aaa Y Match2 Z'.match(regexp59)", "['X Match1 Y','Y Match2 Z']"
true
# Copyright 2013 the V8 project authors. All rights reserved. # Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. description "This page tests handling of parentheses subexpressions." regexp1 = /(a|A)(b|B)/ shouldBe "regexp1.exec('abc')", "['ab','a','b']" regexp2 = /(a((b)|c|d))e/ shouldBe "regexp2.exec('abacadabe')", "['abe','ab','b','b']" regexp3 = /(a(b|(c)|d))e/ shouldBe "regexp3.exec('abacadabe')", "['abe','ab','b',undefined]" regexp4 = /(a(b|c|(d)))e/ shouldBe "regexp4.exec('abacadabe')", "['abe','ab','b',undefined]" regexp5 = /(a((b)|(c)|(d)))e/ shouldBe "regexp5.exec('abacadabe')", "['abe','ab','b','b',undefined,undefined]" regexp6 = /(a((b)|(c)|(d)))/ shouldBe "regexp6.exec('abcde')", "['ab','ab','b','b',undefined,undefined]" regexp7 = /(a(b)??)??c/ shouldBe "regexp7.exec('abc')", "['abc','ab','b']" regexp8 = /(a|(e|q))(x|y)/ shouldBe "regexp8.exec('bcaddxqy')", "['qy','q','q','y']" regexp9 = /((t|b)?|a)$/ shouldBe "regexp9.exec('asdfjejgsdflaksdfjkeljghkjea')", "['a','a',undefined]" regexp10 = /(?:h|e?(?:t|b)?|a?(?:t|b)?)(?:$)/ shouldBe "regexp10.exec('asdfjejgsdflaksdfjkeljghat')", "['at']" regexp11 = /([Jj]ava([Ss]cript)?)\sis\s(fun\w*)/ shouldBeNull "regexp11.exec('Developing with JavaScript is dangerous, do not try it without assistance')" regexp12 = /(?:(.+), )?(.+), (..) to (?:(.+), )?(.+), (..)/ shouldBe "regexp12.exec('Seattle, WA to Buckley, WA')", "['Seattle, WA to Buckley, WA', undefined, 'Seattle', 'WA', undefined, 'Buckley', 'WA']" regexp13 = /(A)?(A.*)/ shouldBe "regexp13.exec('zxcasd;fl ^AaaAAaaaf;lrlrzs')", "['AaaAAaaaf;lrlrzs',undefined,'AaaAAaaaf;lrlrzs']" regexp14 = /(a)|(b)/ shouldBe "regexp14.exec('b')", "['b',undefined,'b']" regexp15 = /^(?!(ab)de|x)(abd)(f)/ shouldBe "regexp15.exec('abdf')", "['abdf',undefined,'abd','f']" regexp16 = /(a|A)(b|B)/ shouldBe "regexp16.exec('abc')", "['ab','a','b']" regexp17 = /(a|d|q|)x/i shouldBe "regexp17.exec('bcaDxqy')", "['Dx','D']" regexp18 = /^.*?(:|$)/ shouldBe "regexp18.exec('Hello: World')", "['Hello:',':']" regexp19 = /(ab|^.{0,2})bar/ shouldBe "regexp19.exec('barrel')", "['bar','']" regexp20 = /(?:(?!foo)...|^.{0,2})bar(.*)/ shouldBe "regexp20.exec('barrel')", "['barrel','rel']" shouldBe "regexp20.exec('2barrel')", "['2barrel','rel']" regexp21 = /([a-g](b|B)|xyz)/ shouldBe "regexp21.exec('abc')", "['ab','ab','b']" regexp22 = /(?:^|;)\s*abc=([^;]*)/ shouldBeNull "regexp22.exec('abcdlskfgjdslkfg')" regexp23 = /"[^<"]*"|'[^<']*'/ shouldBe "regexp23.exec('<html xmlns=\"http://www.w3.org/1999/xhtml\"')", "['\"http://www.w3.org/1999/xhtml\"']" regexp24 = /^(?:(?=abc)\w{3}:|\d\d)$/ shouldBeNull "regexp24.exec('123')" regexp25 = /^\s*(\*|[\w\-]+)(\b|$)?/ shouldBe "regexp25.exec('this is a test')", "['this','this',undefined]" shouldBeNull "regexp25.exec('!this is a test')" regexp26 = /a(b)(a*)|aaa/ shouldBe "regexp26.exec('aaa')", "['aaa',undefined,undefined]" # scheme # authorityRoot # authority # userInfo # user # password # domain # port #path # queryString regexp27 = new RegExp("^" + "(?:" + "([^:/?#]+):" + ")?" + "(?:" + "(//)" + "(" + "(?:" + "(" + "([^:@]*)" + ":?" + "([^:@]*)" + ")?" + "@" + ")?" + "([^:/?#]*)" + "(?::(\\d*))?" + ")" + ")?" + "([^?#]*)" + "(?:\\?([^#]*))?" + "(?:#(.*))?") #fragment shouldBe "regexp27.exec('file:///Users/Someone/Desktop/HelloWorld/index.html')", "['file:///Users/Someone/Desktop/HelloWorld/index.html','file','//','',undefined,undefined,undefined,'',undefined,'/Users/Someone/Desktop/HelloWorld/index.html',undefined,undefined]" # scheme # authorityRoot # authority # userInfo # user # password regexp28 = new RegExp("^" + "(?:" + "([^:/?#]+):" + ")?" + "(?:" + "(//)" + "(" + "(" + "([^:@]*)" + ":?" + "([^:@]*)" + ")?" + "@" + ")" + ")?") shouldBe "regexp28.exec('file:///Users/Someone/Desktop/HelloWorld/index.html')", "['file:','file',undefined,undefined,undefined,undefined,undefined]" regexp29 = /^\s*((\[[^\]]+\])|(u?)("[^"]+"))\s*/ shouldBeNull "regexp29.exec('Committer:')" regexp30 = /^\s*((\[[^\]]+\])|m(u?)("[^"]+"))\s*/ shouldBeNull "regexp30.exec('Committer:')" regexp31 = /^\s*(m(\[[^\]]+\])|m(u?)("[^"]+"))\s*/ shouldBeNull "regexp31.exec('Committer:')" regexp32 = /\s*(m(\[[^\]]+\])|m(u?)("[^"]+"))\s*/ shouldBeNull "regexp32.exec('Committer:')" regexp33 = RegExp("^(?:(?:(a)(xyz|[^>\"'s]*)?)|(/?>)|.[^ws>]*)") shouldBe "regexp33.exec('> <head>')", "['>',undefined,undefined,'>']" regexp34 = /(?:^|\b)btn-\S+/ shouldBeNull "regexp34.exec('xyz123')" shouldBe "regexp34.exec('btn-abc')", "['btn-abc']" shouldBeNull "regexp34.exec('btn- abc')" shouldBeNull "regexp34.exec('XXbtn-abc')" shouldBe "regexp34.exec('XX btn-abc')", "['btn-abc']" regexp35 = /^((a|b)(x|xxx)|)$/ shouldBe "regexp35.exec('ax')", "['ax','ax','a','x']" shouldBeNull "regexp35.exec('axx')" shouldBe "regexp35.exec('axxx')", "['axxx','axxx','a','xxx']" shouldBe "regexp35.exec('bx')", "['bx','bx','b','x']" shouldBeNull "regexp35.exec('bxx')" shouldBe "regexp35.exec('bxxx')", "['bxxx','bxxx','b','xxx']" regexp36 = /^((\/|\.|\-)(\d\d|\d\d\d\d)|)$/ shouldBe "regexp36.exec('/2011')", "['/2011','/2011','/','2011']" shouldBe "regexp36.exec('/11')", "['/11','/11','/','11']" shouldBeNull "regexp36.exec('/123')" regexp37 = /^([1][0-2]|[0]\d|\d)(\/|\.|\-)([0-2]\d|[3][0-1]|\d)((\/|\.|\-)(\d\d|\d\d\d\d)|)$/ shouldBe "regexp37.exec('7/4/1776')", "['7/4/1776','7','/','4','/1776','/','1776']" shouldBe "regexp37.exec('07-04-1776')", "['07-04-1776','07','-','04','-1776','-','1776']" regexp38 = /^(z|(x|xx)|b|)$/ shouldBe "regexp38.exec('xx')", "['xx','xx','xx']" shouldBe "regexp38.exec('b')", "['b','b',undefined]" shouldBe "regexp38.exec('z')", "['z','z',undefined]" shouldBe "regexp38.exec('')", "['','',undefined]" regexp39 = /(8|((?=P)))?/ shouldBe "regexp39.exec('')", "['',undefined,undefined]" shouldBe "regexp39.exec('8')", "['8','8',undefined]" shouldBe "regexp39.exec('zP')", "['',undefined,undefined]" regexp40 = /((8)|((?=P){4}))?()/ shouldBe "regexp40.exec('')", "['',undefined,undefined,undefined,'']" shouldBe "regexp40.exec('8')", "['8','8','8',undefined,'']" shouldBe "regexp40.exec('zPz')", "['',undefined,undefined,undefined,'']" shouldBe "regexp40.exec('zPPz')", "['',undefined,undefined,undefined,'']" shouldBe "regexp40.exec('zPPPz')", "['',undefined,undefined,undefined,'']" shouldBe "regexp40.exec('zPPPPz')", "['',undefined,undefined,undefined,'']" regexp41 = /(([\w\-]+:\/\/?|www[.])[^\s()<>]+(?:([\w\d]+)|([^\[:punct:\]\s()<>\W]|\/)))/ shouldBe "regexp41.exec('Here is a link: http://www.acme.com/our_products/index.html. That is all we want!')", "['http://www.acme.com/our_products/index.html','http://www.acme.com/our_products/index.html','http://','l',undefined]" regexp42 = /((?:(4)?))?/ shouldBe "regexp42.exec('')", "['',undefined,undefined]" shouldBe "regexp42.exec('4')", "['4','4','4']" shouldBe "regexp42.exec('4321')", "['4','4','4']" shouldBeTrue "/(?!(?=r{0}){2,})|((z)?)?/gi.test('')" regexp43 = /(?!(?:\1+s))/ shouldBe "regexp43.exec('SSS')", "['']" regexp44 = /(?!(?:\3+(s+?)))/g shouldBe "regexp44.exec('SSS')", "['',undefined]" regexp45 = /((?!(?:|)v{2,}|))/ shouldBeNull "regexp45.exec('vt')" regexp46 = /(w)(?:5{3}|())|pk/ shouldBeNull "regexp46.exec('5')" shouldBe "regexp46.exec('pk')", "['pk',undefined,undefined]" shouldBe "regexp46.exec('Xw555')", "['w555','w',undefined]" shouldBe "regexp46.exec('Xw55pk5')", "['w','w','']" regexp47 = /(.*?)(?:(?:\?(.*?)?)?)(?:(?:#)?)$/ shouldBe "regexp47.exec('/www.acme.com/this/is/a/path/file.txt')", "['/www.acme.com/this/is/a/path/file.txt','/www.acme.com/this/is/a/path/file.txt',undefined]" regexp48 = /^(?:(\w+):\/*([\w\.\-\d]+)(?::(\d+)|)(?=(?:\/|$))|)(?:$|\/?(.*?)(?:\?(.*?)?|)(?:#(.*)|)$)/ # The regexp on the prior line confuses Xcode syntax highlighting, this coment fixes it! shouldBe "regexp48.exec('http://www.acme.com/this/is/a/path/file.txt')", "['http://www.acme.com/this/is/a/path/file.txt','http','www.acme.com',undefined,'this/is/a/path/file.txt',undefined,undefined]" regexp49 = /(?:([^:]*?)(?:(?:\?(.*?)?)?)(?:(?:#)?)$)|(?:^(?:(\w+):\/*([\w\.\-\d]+)(?::(\d+)|)(?=(?:\/|$))|)(?:$|\/?(.*?)(?:\?(.*?)?|)(?:#(.*)|)$))/ # The regexp on the prior line confuses Xcode syntax highlighting, this coment fixes it! shouldBe "regexp49.exec('http://www.acme.com/this/is/a/path/file.txt')", "['http://www.acme.com/this/is/a/path/file.txt',undefined,undefined,'http','www.acme.com',undefined,'this/is/a/path/file.txt',undefined,undefined]" regexp50 = /((a)b{28,}c|d)x/ shouldBeNull "regexp50.exec('((a)b{28,}c|d)x')" shouldBe "regexp50.exec('abbbbbbbbbbbbbbbbbbbbbbbbbbbbcx')", "['abbbbbbbbbbbbbbbbbbbbbbbbbbbbcx', 'abbbbbbbbbbbbbbbbbbbbbbbbbbbbc', 'a']" shouldBe "regexp50.exec('dx')", "['dx', 'd', undefined]" s = "((.s{-}).{28,}P{Yi}?{,30}|.)ž{-,}P{Any}" regexp51 = new RegExp(s) shouldBeNull "regexp51.exec('abc')" shouldBe "regexp51.exec(s)", "[')ž{-,}P{Any}',')',undefined]" regexp52 = /(PI:NAME:<NAME>END_PI)|(PI:NAME:<NAME>END_PI)|(PI:NAME:<NAME>END_PI)|(PI:NAME:<NAME>END_PI)/ shouldBe "'Hi PI:NAME:<NAME>END_PI'.match(regexp52)", "['Bob',undefined,'Bob',undefined,undefined]" # Test cases discovered by fuzzing that crashed the compiler. regexp53 = /(?=(?:(?:(gB)|(?!cs|<))((?=(?!v6){0,})))|(?=#)+?)/m shouldBe "regexp53.exec('#')", "['',undefined,'']" regexp54 = /((?:(?:()|(?!))((?=(?!))))|())/m shouldBe "regexp54.exec('#')", "['','',undefined,undefined,'']" regexp55 = /(?:(?:(?:a?|(?:))((?:)))|a?)/m shouldBe "regexp55.exec('#')", "['','']" # Test evaluation order of empty subpattern alternatives. regexp56 = /(|a)/ shouldBe "regexp56.exec('a')", "['','']" regexp57 = /(a|)/ shouldBe "regexp57.exec('a')", "['a','a']" # Tests that non-greedy repeat quantified parentheses will backtrack through multiple frames of subpattern matches. regexp58 = /a|b(?:[^b])*?c/ shouldBe "regexp58.exec('badbc')", "['a']" regexp59 = /(X(?:.(?!X))*?Y)|(Y(?:.(?!Y))*?Z)/g shouldBe "'Y aaa X Match1 Y aaa Y Match2 Z'.match(regexp59)", "['X Match1 Y','Y Match2 Z']"
[ { "context": " id: 1\n scoped_records: [{ id: 1, name: 'John' }]\n }, ->\n\n User.create(name: 'John').th", "end": 165, "score": 0.9997584223747253, "start": 161, "tag": "NAME", "value": "John" }, { "context": "me: 'John' }]\n }, ->\n\n User.create(name: 'Joh...
spec/crud/create.coffee
EduardoluizSanBlasDeveloper0/ROR-crud-example
506
describe '#create', -> it 'should create a record and return it', -> stubResponse { success: true id: 1 scoped_records: [{ id: 1, name: 'John' }] }, -> User.create(name: 'John').then (user) -> expect(user).to.eql(id: 1, name: 'John')
86145
describe '#create', -> it 'should create a record and return it', -> stubResponse { success: true id: 1 scoped_records: [{ id: 1, name: '<NAME>' }] }, -> User.create(name: '<NAME>').then (user) -> expect(user).to.eql(id: 1, name: '<NAME>')
true
describe '#create', -> it 'should create a record and return it', -> stubResponse { success: true id: 1 scoped_records: [{ id: 1, name: 'PI:NAME:<NAME>END_PI' }] }, -> User.create(name: 'PI:NAME:<NAME>END_PI').then (user) -> expect(user).to.eql(id: 1, name: 'PI:NAME:<NAME>END_PI')
[ { "context": "url\n\n for key,value of options\n key= 'set' if key is 'headers'\n key= 'send' if key i", "end": 1554, "score": 0.9247642755508423, "start": 1551, "tag": "KEY", "value": "set" }, { "context": "ey,value of options\n key= 'set' if key is 'header...
src/caravan.coffee
59naga/caravan
0
# Dependencies Q= require 'q' throat= (require 'throat') Q.Promise superagent= require 'superagent' merge= require 'merge' # Private verbs= [ 'checkout', 'connect', 'copy', 'delete', 'get', 'head', 'lock', 'merge', 'mkactivity', 'mkcol', 'move', 'm-search', 'notify', 'options', 'patch', 'post', 'propfind', 'proppatch', 'purge', 'put', 'report', 'search', 'subscribe', 'trace', 'unlock', 'unsubscribe', ] # Public class Caravan constructor: -> for verb in verbs @[verb]= @verb.bind(this,verb.toUpperCase()) verb: (verb,urls,options={})=> options= JSON.parse JSON.stringify options # keep a origin references options.method= verb @request urls,options request: (urls,options={})=> options= JSON.parse JSON.stringify options options.concurrency?= 1 concurrency= throat options.concurrency urls= [urls] unless urls instanceof Array promises= for url in urls do (url)=> concurrency => @requestAsync url,options @settle promises,options requestAsync: (url,options={})=> options= JSON.parse JSON.stringify options options.method?= 'GET' if typeof url is 'object' options= merge options,url url= options.url ? options.uri options.delay= (options.delay|0) # normalize return Q.reject(new TypeError 'url/uri is not defined') unless url new Q.Promise (resolve,reject,notify)=> request= superagent options.method,url for key,value of options key= 'set' if key is 'headers' key= 'send' if key is 'data' continue unless typeof request[key] is 'function' request[key] value request.end (error,response)=> notify error ? (@getBody response,options) setTimeout -> unless error resolve response else reject error ,options.delay settle: (promises,options={})=> options.raw?= false Q.allSettled promises .then (results)=> for result in results if result.state is 'fulfilled' @getBody result.value,options else result.reason getBody: (response,options={})=> hasKeys= (Object.keys response.body).length > 0 switch when options.raw response when hasKeys response.body else response.text module.exports= new Caravan module.exports.Caravan= Caravan
97416
# Dependencies Q= require 'q' throat= (require 'throat') Q.Promise superagent= require 'superagent' merge= require 'merge' # Private verbs= [ 'checkout', 'connect', 'copy', 'delete', 'get', 'head', 'lock', 'merge', 'mkactivity', 'mkcol', 'move', 'm-search', 'notify', 'options', 'patch', 'post', 'propfind', 'proppatch', 'purge', 'put', 'report', 'search', 'subscribe', 'trace', 'unlock', 'unsubscribe', ] # Public class Caravan constructor: -> for verb in verbs @[verb]= @verb.bind(this,verb.toUpperCase()) verb: (verb,urls,options={})=> options= JSON.parse JSON.stringify options # keep a origin references options.method= verb @request urls,options request: (urls,options={})=> options= JSON.parse JSON.stringify options options.concurrency?= 1 concurrency= throat options.concurrency urls= [urls] unless urls instanceof Array promises= for url in urls do (url)=> concurrency => @requestAsync url,options @settle promises,options requestAsync: (url,options={})=> options= JSON.parse JSON.stringify options options.method?= 'GET' if typeof url is 'object' options= merge options,url url= options.url ? options.uri options.delay= (options.delay|0) # normalize return Q.reject(new TypeError 'url/uri is not defined') unless url new Q.Promise (resolve,reject,notify)=> request= superagent options.method,url for key,value of options key= '<KEY>' if key is '<KEY>' key= '<KEY>' if key is '<KEY>' continue unless typeof request[key] is 'function' request[key] value request.end (error,response)=> notify error ? (@getBody response,options) setTimeout -> unless error resolve response else reject error ,options.delay settle: (promises,options={})=> options.raw?= false Q.allSettled promises .then (results)=> for result in results if result.state is 'fulfilled' @getBody result.value,options else result.reason getBody: (response,options={})=> hasKeys= (Object.keys response.body).length > 0 switch when options.raw response when hasKeys response.body else response.text module.exports= new Caravan module.exports.Caravan= Caravan
true
# Dependencies Q= require 'q' throat= (require 'throat') Q.Promise superagent= require 'superagent' merge= require 'merge' # Private verbs= [ 'checkout', 'connect', 'copy', 'delete', 'get', 'head', 'lock', 'merge', 'mkactivity', 'mkcol', 'move', 'm-search', 'notify', 'options', 'patch', 'post', 'propfind', 'proppatch', 'purge', 'put', 'report', 'search', 'subscribe', 'trace', 'unlock', 'unsubscribe', ] # Public class Caravan constructor: -> for verb in verbs @[verb]= @verb.bind(this,verb.toUpperCase()) verb: (verb,urls,options={})=> options= JSON.parse JSON.stringify options # keep a origin references options.method= verb @request urls,options request: (urls,options={})=> options= JSON.parse JSON.stringify options options.concurrency?= 1 concurrency= throat options.concurrency urls= [urls] unless urls instanceof Array promises= for url in urls do (url)=> concurrency => @requestAsync url,options @settle promises,options requestAsync: (url,options={})=> options= JSON.parse JSON.stringify options options.method?= 'GET' if typeof url is 'object' options= merge options,url url= options.url ? options.uri options.delay= (options.delay|0) # normalize return Q.reject(new TypeError 'url/uri is not defined') unless url new Q.Promise (resolve,reject,notify)=> request= superagent options.method,url for key,value of options key= 'PI:KEY:<KEY>END_PI' if key is 'PI:KEY:<KEY>END_PI' key= 'PI:KEY:<KEY>END_PI' if key is 'PI:KEY:<KEY>END_PI' continue unless typeof request[key] is 'function' request[key] value request.end (error,response)=> notify error ? (@getBody response,options) setTimeout -> unless error resolve response else reject error ,options.delay settle: (promises,options={})=> options.raw?= false Q.allSettled promises .then (results)=> for result in results if result.state is 'fulfilled' @getBody result.value,options else result.reason getBody: (response,options={})=> hasKeys= (Object.keys response.body).length > 0 switch when options.raw response when hasKeys response.body else response.text module.exports= new Caravan module.exports.Caravan= Caravan
[ { "context": "hub'\n\nmodule.exports = (user) ->\n nickName = user.login\n fullName = user.name ? user.login\n\n [firstName", "end": 71, "score": 0.8473119735717773, "start": 66, "tag": "USERNAME", "value": "login" }, { "context": "\n\n userPhoto = user.avatar_url\n\n user.nickN...
src/util/userToIdentity.coffee
brianshaler/kerplunk-github
0
PLATFORM = 'github' module.exports = (user) -> nickName = user.login fullName = user.name ? user.login [firstName, lastNames...] = fullName.split ' ' lastName = lastNames.join ' ' userPhoto = user.avatar_url user.nickName = nickName user.fullName = fullName user.firstName = firstName user.lastName = lastName user.profileUrl = user.html_url user.platformId = String user.id guid: ["#{PLATFORM}-#{user.id}"] platform: [PLATFORM] # platformId: user.id fullName: user.fullName firstName: user.firstName lastName: user.lastName nickName: user.nickName photo: if userPhoto then [{url: userPhoto}] else [] data: github: user?.github ? user # user = # login: 'octocat' # id: 1 # avatar_url: 'https://github.com/images/error/octocat_happy.gif' # gravatar_id: '' # url: 'https://api.github.com/users/octocat' # html_url: 'https://github.com/octocat' # followers_url: 'https://api.github.com/users/octocat/followers' # following_url: 'https://api.github.com/users/octocat/following{/other_user}' # gists_url: 'https://api.github.com/users/octocat/gists{/gist_id}' # starred_url: 'https://api.github.com/users/octocat/starred{/owner}{/repo}' # subscriptions_url: 'https://api.github.com/users/octocat/subscriptions' # organizations_url: 'https://api.github.com/users/octocat/orgs' # repos_url: 'https://api.github.com/users/octocat/repos' # events_url: 'https://api.github.com/users/octocat/events{/privacy}' # received_events_url: 'https://api.github.com/users/octocat/received_events' # type: 'User' # site_admin: false # name: 'monalisa octocat' # company: 'GitHub' # blog: 'https://github.com/blog' # location: 'San Francisco' # email: 'octocat@github.com' # hireable: false # bio: 'There once was...' # public_repos: 2 # public_gists: 1 # followers: 20 # following: 0 # created_at: '2008-01-14T04:33:35Z' # updated_at: '2008-01-14T04:33:35Z' # total_private_repos: 100 # owned_private_repos: 100 # private_gists: 81 # disk_usage: 10000 # collaborators: 8 # plan: # name: 'Medium' # space: 400 # private_repos: 20 # collaborators: 0
29472
PLATFORM = 'github' module.exports = (user) -> nickName = user.login fullName = user.name ? user.login [firstName, lastNames...] = fullName.split ' ' lastName = lastNames.join ' ' userPhoto = user.avatar_url user.nickName = nickName user.fullName = fullName user.firstName = <NAME> user.lastName = <NAME> user.profileUrl = user.html_url user.platformId = String user.id guid: ["#{PLATFORM}-#{user.id}"] platform: [PLATFORM] # platformId: user.id fullName: user.fullName firstName: user.firstName lastName: user.lastName nickName: user.nickName photo: if userPhoto then [{url: userPhoto}] else [] data: github: user?.github ? user # user = # login: 'octocat' # id: 1 # avatar_url: 'https://github.com/images/error/octocat_happy.gif' # gravatar_id: '' # url: 'https://api.github.com/users/octocat' # html_url: 'https://github.com/octocat' # followers_url: 'https://api.github.com/users/octocat/followers' # following_url: 'https://api.github.com/users/octocat/following{/other_user}' # gists_url: 'https://api.github.com/users/octocat/gists{/gist_id}' # starred_url: 'https://api.github.com/users/octocat/starred{/owner}{/repo}' # subscriptions_url: 'https://api.github.com/users/octocat/subscriptions' # organizations_url: 'https://api.github.com/users/octocat/orgs' # repos_url: 'https://api.github.com/users/octocat/repos' # events_url: 'https://api.github.com/users/octocat/events{/privacy}' # received_events_url: 'https://api.github.com/users/octocat/received_events' # type: 'User' # site_admin: false # name: '<NAME>' # company: 'GitHub' # blog: 'https://github.com/blog' # location: 'San Francisco' # email: '<EMAIL>' # hireable: false # bio: 'There once was...' # public_repos: 2 # public_gists: 1 # followers: 20 # following: 0 # created_at: '2008-01-14T04:33:35Z' # updated_at: '2008-01-14T04:33:35Z' # total_private_repos: 100 # owned_private_repos: 100 # private_gists: 81 # disk_usage: 10000 # collaborators: 8 # plan: # name: 'Medium' # space: 400 # private_repos: 20 # collaborators: 0
true
PLATFORM = 'github' module.exports = (user) -> nickName = user.login fullName = user.name ? user.login [firstName, lastNames...] = fullName.split ' ' lastName = lastNames.join ' ' userPhoto = user.avatar_url user.nickName = nickName user.fullName = fullName user.firstName = PI:NAME:<NAME>END_PI user.lastName = PI:NAME:<NAME>END_PI user.profileUrl = user.html_url user.platformId = String user.id guid: ["#{PLATFORM}-#{user.id}"] platform: [PLATFORM] # platformId: user.id fullName: user.fullName firstName: user.firstName lastName: user.lastName nickName: user.nickName photo: if userPhoto then [{url: userPhoto}] else [] data: github: user?.github ? user # user = # login: 'octocat' # id: 1 # avatar_url: 'https://github.com/images/error/octocat_happy.gif' # gravatar_id: '' # url: 'https://api.github.com/users/octocat' # html_url: 'https://github.com/octocat' # followers_url: 'https://api.github.com/users/octocat/followers' # following_url: 'https://api.github.com/users/octocat/following{/other_user}' # gists_url: 'https://api.github.com/users/octocat/gists{/gist_id}' # starred_url: 'https://api.github.com/users/octocat/starred{/owner}{/repo}' # subscriptions_url: 'https://api.github.com/users/octocat/subscriptions' # organizations_url: 'https://api.github.com/users/octocat/orgs' # repos_url: 'https://api.github.com/users/octocat/repos' # events_url: 'https://api.github.com/users/octocat/events{/privacy}' # received_events_url: 'https://api.github.com/users/octocat/received_events' # type: 'User' # site_admin: false # name: 'PI:NAME:<NAME>END_PI' # company: 'GitHub' # blog: 'https://github.com/blog' # location: 'San Francisco' # email: 'PI:EMAIL:<EMAIL>END_PI' # hireable: false # bio: 'There once was...' # public_repos: 2 # public_gists: 1 # followers: 20 # following: 0 # created_at: '2008-01-14T04:33:35Z' # updated_at: '2008-01-14T04:33:35Z' # total_private_repos: 100 # owned_private_repos: 100 # private_gists: 81 # disk_usage: 10000 # collaborators: 8 # plan: # name: 'Medium' # space: 400 # private_repos: 20 # collaborators: 0
[ { "context": "**************\n# JSFont - Font dispatch\n# Coded by Hajime Oh-yake 2016.12.17\n#*************************************", "end": 93, "score": 0.9998964071273804, "start": 79, "tag": "NAME", "value": "Hajime Oh-yake" } ]
JSKit/01_JSFont.coffee
digitarhythm/codeJS
0
#***************************************** # JSFont - Font dispatch # Coded by Hajime Oh-yake 2016.12.17 #***************************************** class JSFont extends JSObject constructor:-> @_fontSize = 12 @_fontWeight = 'normal' systemFontOfSize:(fontsize)-> ### #+(UIFont*)systemFontOfSize:(CGFloat)fontSize 指定されたサイズの標準スタイルのフォントを返す  UIFont *font = [UIFont systemFontOfSize:20]; #+(UIFont*)boldSystemFontOfSize:(CGFloat)fontSize 指定されたサイズの太字スタイルのフォントを返す (例)サイズ20の太字フォントを取得する  UIFont *font = [UIFont boldSystemFontOfSize:20]; #+(UIFont*)italicSystemFontOfSize:(CGFloat)fontSize 指定されたサイズの斜体スタイルのフォントを返す (例)サイズ20の斜体フォントを取得する  UIFont *font = [UIFont italicSystemFontOfSize:20]; #+(CGFloat)systemFontSize 標準サイズを返す (例)UIFont *font =    [UIFont systemFontOfSize:[UIFont systemFontSize]]; #+(CGFloat)smallSystemFontSize 標準サイズよりも小さめのサイズを返す (例)UIFont *font =[UIFont systemFontOfSize:     [UIFont smallSystemFontSize]]; #+(CGFloat)labelFontSize ラベルで使用される標準的なサイズを返す (例)UIFont *font =    [UIFont systemFontOfSize:[UIFont labelFontSize]]; #+(CGFloat)buttonFontSize+ ###
143942
#***************************************** # JSFont - Font dispatch # Coded by <NAME> 2016.12.17 #***************************************** class JSFont extends JSObject constructor:-> @_fontSize = 12 @_fontWeight = 'normal' systemFontOfSize:(fontsize)-> ### #+(UIFont*)systemFontOfSize:(CGFloat)fontSize 指定されたサイズの標準スタイルのフォントを返す  UIFont *font = [UIFont systemFontOfSize:20]; #+(UIFont*)boldSystemFontOfSize:(CGFloat)fontSize 指定されたサイズの太字スタイルのフォントを返す (例)サイズ20の太字フォントを取得する  UIFont *font = [UIFont boldSystemFontOfSize:20]; #+(UIFont*)italicSystemFontOfSize:(CGFloat)fontSize 指定されたサイズの斜体スタイルのフォントを返す (例)サイズ20の斜体フォントを取得する  UIFont *font = [UIFont italicSystemFontOfSize:20]; #+(CGFloat)systemFontSize 標準サイズを返す (例)UIFont *font =    [UIFont systemFontOfSize:[UIFont systemFontSize]]; #+(CGFloat)smallSystemFontSize 標準サイズよりも小さめのサイズを返す (例)UIFont *font =[UIFont systemFontOfSize:     [UIFont smallSystemFontSize]]; #+(CGFloat)labelFontSize ラベルで使用される標準的なサイズを返す (例)UIFont *font =    [UIFont systemFontOfSize:[UIFont labelFontSize]]; #+(CGFloat)buttonFontSize+ ###
true
#***************************************** # JSFont - Font dispatch # Coded by PI:NAME:<NAME>END_PI 2016.12.17 #***************************************** class JSFont extends JSObject constructor:-> @_fontSize = 12 @_fontWeight = 'normal' systemFontOfSize:(fontsize)-> ### #+(UIFont*)systemFontOfSize:(CGFloat)fontSize 指定されたサイズの標準スタイルのフォントを返す  UIFont *font = [UIFont systemFontOfSize:20]; #+(UIFont*)boldSystemFontOfSize:(CGFloat)fontSize 指定されたサイズの太字スタイルのフォントを返す (例)サイズ20の太字フォントを取得する  UIFont *font = [UIFont boldSystemFontOfSize:20]; #+(UIFont*)italicSystemFontOfSize:(CGFloat)fontSize 指定されたサイズの斜体スタイルのフォントを返す (例)サイズ20の斜体フォントを取得する  UIFont *font = [UIFont italicSystemFontOfSize:20]; #+(CGFloat)systemFontSize 標準サイズを返す (例)UIFont *font =    [UIFont systemFontOfSize:[UIFont systemFontSize]]; #+(CGFloat)smallSystemFontSize 標準サイズよりも小さめのサイズを返す (例)UIFont *font =[UIFont systemFontOfSize:     [UIFont smallSystemFontSize]]; #+(CGFloat)labelFontSize ラベルで使用される標準的なサイズを返す (例)UIFont *font =    [UIFont systemFontOfSize:[UIFont labelFontSize]]; #+(CGFloat)buttonFontSize+ ###
[ { "context": "\nnikita = require '@nikitajs/core'\n{tags, ssh, scratch} = require '../test'\nth", "end": 28, "score": 0.8301748633384705, "start": 26, "tag": "USERNAME", "value": "js" }, { "context": "tags.ipa\n\nipa =\n principal: 'admin'\n password: 'admin_pw'\n referer: 'https:...
packages/ipa/test/group/add_member.coffee
chibanemourad/node-nikita
0
nikita = require '@nikitajs/core' {tags, ssh, scratch} = require '../test' they = require('ssh2-they').configure ssh... return unless tags.ipa ipa = principal: 'admin' password: 'admin_pw' referer: 'https://ipa.nikita/ipa' url: 'https://ipa.nikita/ipa/session/json' describe 'ipa.group.add_member', -> they 'add_member to a group', ({ssh}) -> gidnumber = null nikita ssh: ssh .ipa.group.del ipa, [ cn: 'group_add_member' , cn: 'group_add_member_user' ] .ipa.user.del ipa, uid: 'group_add_member_user' .ipa.group ipa, cn: 'group_add_member' , (err, {result}) -> gidnumber = result.gidnumber .ipa.user ipa, uid: 'group_add_member_user' attributes: givenname: 'Firstname' sn: 'Lastname' mail: [ 'user@nikita.js.org' ] .ipa.group.add_member ipa, cn: 'group_add_member' attributes: user: ['group_add_member_user'] , (err, {status}) -> status.should.be.true() unless err .ipa.group.show ipa, cn: 'group_add_member' , (err, {result}) -> result.gidnumber.should.eql gidnumber .promise()
165535
nikita = require '@nikitajs/core' {tags, ssh, scratch} = require '../test' they = require('ssh2-they').configure ssh... return unless tags.ipa ipa = principal: 'admin' password: '<PASSWORD>' referer: 'https://ipa.nikita/ipa' url: 'https://ipa.nikita/ipa/session/json' describe 'ipa.group.add_member', -> they 'add_member to a group', ({ssh}) -> gidnumber = null nikita ssh: ssh .ipa.group.del ipa, [ cn: 'group_add_member' , cn: 'group_add_member_user' ] .ipa.user.del ipa, uid: 'group_add_member_user' .ipa.group ipa, cn: 'group_add_member' , (err, {result}) -> gidnumber = result.gidnumber .ipa.user ipa, uid: 'group_add_member_user' attributes: givenname: '<NAME>' sn: '<NAME>' mail: [ '<EMAIL>' ] .ipa.group.add_member ipa, cn: 'group_add_member' attributes: user: ['group_add_member_user'] , (err, {status}) -> status.should.be.true() unless err .ipa.group.show ipa, cn: 'group_add_member' , (err, {result}) -> result.gidnumber.should.eql gidnumber .promise()
true
nikita = require '@nikitajs/core' {tags, ssh, scratch} = require '../test' they = require('ssh2-they').configure ssh... return unless tags.ipa ipa = principal: 'admin' password: 'PI:PASSWORD:<PASSWORD>END_PI' referer: 'https://ipa.nikita/ipa' url: 'https://ipa.nikita/ipa/session/json' describe 'ipa.group.add_member', -> they 'add_member to a group', ({ssh}) -> gidnumber = null nikita ssh: ssh .ipa.group.del ipa, [ cn: 'group_add_member' , cn: 'group_add_member_user' ] .ipa.user.del ipa, uid: 'group_add_member_user' .ipa.group ipa, cn: 'group_add_member' , (err, {result}) -> gidnumber = result.gidnumber .ipa.user ipa, uid: 'group_add_member_user' attributes: givenname: 'PI:NAME:<NAME>END_PI' sn: 'PI:NAME:<NAME>END_PI' mail: [ 'PI:EMAIL:<EMAIL>END_PI' ] .ipa.group.add_member ipa, cn: 'group_add_member' attributes: user: ['group_add_member_user'] , (err, {status}) -> status.should.be.true() unless err .ipa.group.show ipa, cn: 'group_add_member' , (err, {result}) -> result.gidnumber.should.eql gidnumber .promise()
[ { "context": " if added.length or removed.length and key is \"channels\"\n @envs.fetch(reset: true)\n ", "end": 2702, "score": 0.9861434102058411, "start": 2694, "tag": "KEY", "value": "channels" } ]
conda_ui/static/conda_ui/settings.coffee
LaudateCorpus1/conda-ui
1
define [ "ractive" "bootstrap_tagsinput" "promise" "conda_ui/api" "conda_ui/modal" ], (Ractive, $, Promise, api, Modal) -> class SettingsView extends Modal.View initialize: (options) -> @ractive = new Ractive({ template: '#template-settings-dialog' }) @envs = options.envs @pkgs = options.pkgs super(options) config = new api.conda.Config() defaults = { allow_softlinks: true, binstar_personal: true, changeps1: true, ssl_verify: true, use_pip: true } Promise.all([api.conda.info(), config.getAll()]).then (values) => info = values[0] config = values[1] data = defaults data.info = info for own key, value of config data[key] = value @ractive.reset data @$el.find('input[data-role=tagsinput]:not(#setting-envs-dirs)').tagsinput({ confirmKeys: [13, 32], # Enter, space }) @$el.find('#setting-envs-dirs').tagsinput({ confirmKeys: [13], # Only Enter }) @original = @get_values() @show() @ractive.on('clean', () => @on_clean()) title_text: () -> "Settings" submit_text: () -> "Save" render_body: () -> el = $('<div></div>') @ractive.render(el) return el render: () -> super() @$el.addClass("scrollable-modal") on_submit: (event) => @hide() values = @get_values() config = new api.conda.Config() for own key, value of values.boolean if value isnt @original.boolean[key] config.set(key, value) for own key, changed of values.list original = @original.list[key] if typeof original is "undefined" original = [] added = [] removed = [] for val in original if changed.indexOf(val) is -1 removed.push(val) for val in changed if original.indexOf(val) is -1 added.push(val) for val in added config.add(key, val) for val in removed config.remove(key, val) if added.length or removed.length and key is "channels" @envs.fetch(reset: true) @pkgs.fetch(reset: true) get_values: -> boolean = {} list = {} @$('input[type=checkbox]').map (index, el) -> $el = $(el) boolean[$el.data('key')] = $el.prop('checked') @$('input[data-role=tagsinput]').map (index, el) -> $el = $(el) list[$el.data('key')] = Array.prototype.slice.call($el.tagsinput('items')) return { boolean: boolean, list: list } on_clean: (event) -> options = {} @$('#collapseClean input[type=checkbox]').each (i, el) -> $el = $(el) if $el.prop('checked') options[$el.data('flag')] = true @$('#collapseClean .panel-body').text('Cleaning...') api.conda.clean(options).then => @$('#collapseClean .panel-body').text('Cleaned!') return {View: SettingsView}
52428
define [ "ractive" "bootstrap_tagsinput" "promise" "conda_ui/api" "conda_ui/modal" ], (Ractive, $, Promise, api, Modal) -> class SettingsView extends Modal.View initialize: (options) -> @ractive = new Ractive({ template: '#template-settings-dialog' }) @envs = options.envs @pkgs = options.pkgs super(options) config = new api.conda.Config() defaults = { allow_softlinks: true, binstar_personal: true, changeps1: true, ssl_verify: true, use_pip: true } Promise.all([api.conda.info(), config.getAll()]).then (values) => info = values[0] config = values[1] data = defaults data.info = info for own key, value of config data[key] = value @ractive.reset data @$el.find('input[data-role=tagsinput]:not(#setting-envs-dirs)').tagsinput({ confirmKeys: [13, 32], # Enter, space }) @$el.find('#setting-envs-dirs').tagsinput({ confirmKeys: [13], # Only Enter }) @original = @get_values() @show() @ractive.on('clean', () => @on_clean()) title_text: () -> "Settings" submit_text: () -> "Save" render_body: () -> el = $('<div></div>') @ractive.render(el) return el render: () -> super() @$el.addClass("scrollable-modal") on_submit: (event) => @hide() values = @get_values() config = new api.conda.Config() for own key, value of values.boolean if value isnt @original.boolean[key] config.set(key, value) for own key, changed of values.list original = @original.list[key] if typeof original is "undefined" original = [] added = [] removed = [] for val in original if changed.indexOf(val) is -1 removed.push(val) for val in changed if original.indexOf(val) is -1 added.push(val) for val in added config.add(key, val) for val in removed config.remove(key, val) if added.length or removed.length and key is "<KEY>" @envs.fetch(reset: true) @pkgs.fetch(reset: true) get_values: -> boolean = {} list = {} @$('input[type=checkbox]').map (index, el) -> $el = $(el) boolean[$el.data('key')] = $el.prop('checked') @$('input[data-role=tagsinput]').map (index, el) -> $el = $(el) list[$el.data('key')] = Array.prototype.slice.call($el.tagsinput('items')) return { boolean: boolean, list: list } on_clean: (event) -> options = {} @$('#collapseClean input[type=checkbox]').each (i, el) -> $el = $(el) if $el.prop('checked') options[$el.data('flag')] = true @$('#collapseClean .panel-body').text('Cleaning...') api.conda.clean(options).then => @$('#collapseClean .panel-body').text('Cleaned!') return {View: SettingsView}
true
define [ "ractive" "bootstrap_tagsinput" "promise" "conda_ui/api" "conda_ui/modal" ], (Ractive, $, Promise, api, Modal) -> class SettingsView extends Modal.View initialize: (options) -> @ractive = new Ractive({ template: '#template-settings-dialog' }) @envs = options.envs @pkgs = options.pkgs super(options) config = new api.conda.Config() defaults = { allow_softlinks: true, binstar_personal: true, changeps1: true, ssl_verify: true, use_pip: true } Promise.all([api.conda.info(), config.getAll()]).then (values) => info = values[0] config = values[1] data = defaults data.info = info for own key, value of config data[key] = value @ractive.reset data @$el.find('input[data-role=tagsinput]:not(#setting-envs-dirs)').tagsinput({ confirmKeys: [13, 32], # Enter, space }) @$el.find('#setting-envs-dirs').tagsinput({ confirmKeys: [13], # Only Enter }) @original = @get_values() @show() @ractive.on('clean', () => @on_clean()) title_text: () -> "Settings" submit_text: () -> "Save" render_body: () -> el = $('<div></div>') @ractive.render(el) return el render: () -> super() @$el.addClass("scrollable-modal") on_submit: (event) => @hide() values = @get_values() config = new api.conda.Config() for own key, value of values.boolean if value isnt @original.boolean[key] config.set(key, value) for own key, changed of values.list original = @original.list[key] if typeof original is "undefined" original = [] added = [] removed = [] for val in original if changed.indexOf(val) is -1 removed.push(val) for val in changed if original.indexOf(val) is -1 added.push(val) for val in added config.add(key, val) for val in removed config.remove(key, val) if added.length or removed.length and key is "PI:KEY:<KEY>END_PI" @envs.fetch(reset: true) @pkgs.fetch(reset: true) get_values: -> boolean = {} list = {} @$('input[type=checkbox]').map (index, el) -> $el = $(el) boolean[$el.data('key')] = $el.prop('checked') @$('input[data-role=tagsinput]').map (index, el) -> $el = $(el) list[$el.data('key')] = Array.prototype.slice.call($el.tagsinput('items')) return { boolean: boolean, list: list } on_clean: (event) -> options = {} @$('#collapseClean input[type=checkbox]').each (i, el) -> $el = $(el) if $el.prop('checked') options[$el.data('flag')] = true @$('#collapseClean .panel-body').text('Cleaning...') api.conda.clean(options).then => @$('#collapseClean .panel-body').text('Cleaned!') return {View: SettingsView}
[ { "context": "d preview slide plugin for reveal.js\nWritten by: [John Yanarella](http://twitter.com/johnyanarella)\nCopyright (c) ", "end": 102, "score": 0.9998576045036316, "start": 88, "tag": "NAME", "value": "John Yanarella" }, { "context": "s\nWritten by: [John Yanarella](http://...
src/coffee/editor.coffee
mnimer/ServicesWithCF-Presentation
0
###! Custom interactive code editor and preview slide plugin for reveal.js Written by: [John Yanarella](http://twitter.com/johnyanarella) Copyright (c) 2012-2103 [CodeCatalyst, LLC](http://www.codecatalyst.com/). Open source under the [MIT License](http://en.wikipedia.org/wiki/MIT_License). ### $preview = $( """ <div class="preview" style="width: 373px; height: 730px;"> <iframe></iframe> </div> """ ) showPreview = ( editor ) -> # Create the preview popup. Reveal.keyboardEnabled = false $preview.bPopup( positionStyle: 'fixed' onClose: -> Reveal.keyboardEnabled = true return ) # Populate the iframe in the preview popup. previewFrame = $preview.children('iframe').get( 0 ) preview = previewFrame.contentDocument or previewFrame.contentWindow.document preview.write( editor.getValue() ) preview.close() return creatorEditor = ( $targetSlide ) -> url = $targetSlide.data( 'source' ) $.ajax( url: url dataType: 'json' ).done( ( data ) -> # Populate the slide. options ="" for section in data.sections options += "<optgroup label=\"#{ section.title }\">" for step in section.steps options += "<option value=\"#{ step.url }\">#{ step.title }</option>" options += "</optgroup>" $targetSlide.append( """ <h2>#{ data.title }</h2> <textarea></textarea> <div style="display: inline-table; width: 820px;"> <div style="display: table-cell; width: 410px; text-align: left;"> <select class="editor-combo-box"> #{ options } </select> </div> <!-- <div id="#previewBtn" style="display: table-cell; width: 410px; text-align: right;"> <button class="editor-preview-button">Preview</button> </div> --> </div> <img class="editor-loading-indicator" src="resource/image/LoadingIndicator.gif" width="32" height="32"> """ ) textArea = $targetSlide.find( 'textarea' )[ 0 ] $textArea = $(textArea) editor = CodeMirror.fromTextArea( textArea, mode: 'text/html' tabMode: 'indent' indentUnit: 4 indentWithTabs: true lineNumbers: true extraKeys: "'>'": ( editor ) -> editor.closeTag( editor, '>' ) "'/'": ( editor ) -> editor.closeTag( editor, '/' ) ) editor.setSize( $textArea.width(), $textArea.height() ) editor.refresh() loadingIndicator = $targetSlide.find( 'img.editor-loading-indicator' )[ 0 ] $loadingIndicator = $(loadingIndicator) $targetSlide.find( 'select.editor-combo-box' ).on( 'change', ( event ) -> loadTemplate( editor, $loadingIndicator, $( event.target ).val() ) ) $targetSlide.find( "button.editor-preview-button" ).on( 'click', ( event ) -> showPreview( editor ) ) # Nasty hack - workaround for weird refresh issue that left some editors in a partially rendered state. Reveal.addEventListener( 'slidechanged', ( event ) -> editor.refresh() ) loadTemplate( editor, $loadingIndicator, data.sections[ 0 ].steps[ 0 ].url ) return ).fail( ( promise, type, message ) -> alert( message ) return ) return loadTemplate = ( editor, $loadingIndicator, url ) -> $loadingIndicator.addClass( 'loading' ) $.ajax( url: url dataType: 'text' ).done( ( template ) -> editor.setValue( template ) return ).fail( ( promise, type, message ) -> alert( message ) return ).always( $loadingIndicator.removeClass( 'loading' ) ) return $('section.editor').each( ( index, element ) -> $slide = $( element ) creatorEditor( $slide ) )
34166
###! Custom interactive code editor and preview slide plugin for reveal.js Written by: [<NAME>](http://twitter.com/johnyanarella) Copyright (c) 2012-2103 [CodeCatalyst, LLC](http://www.codecatalyst.com/). Open source under the [MIT License](http://en.wikipedia.org/wiki/MIT_License). ### $preview = $( """ <div class="preview" style="width: 373px; height: 730px;"> <iframe></iframe> </div> """ ) showPreview = ( editor ) -> # Create the preview popup. Reveal.keyboardEnabled = false $preview.bPopup( positionStyle: 'fixed' onClose: -> Reveal.keyboardEnabled = true return ) # Populate the iframe in the preview popup. previewFrame = $preview.children('iframe').get( 0 ) preview = previewFrame.contentDocument or previewFrame.contentWindow.document preview.write( editor.getValue() ) preview.close() return creatorEditor = ( $targetSlide ) -> url = $targetSlide.data( 'source' ) $.ajax( url: url dataType: 'json' ).done( ( data ) -> # Populate the slide. options ="" for section in data.sections options += "<optgroup label=\"#{ section.title }\">" for step in section.steps options += "<option value=\"#{ step.url }\">#{ step.title }</option>" options += "</optgroup>" $targetSlide.append( """ <h2>#{ data.title }</h2> <textarea></textarea> <div style="display: inline-table; width: 820px;"> <div style="display: table-cell; width: 410px; text-align: left;"> <select class="editor-combo-box"> #{ options } </select> </div> <!-- <div id="#previewBtn" style="display: table-cell; width: 410px; text-align: right;"> <button class="editor-preview-button">Preview</button> </div> --> </div> <img class="editor-loading-indicator" src="resource/image/LoadingIndicator.gif" width="32" height="32"> """ ) textArea = $targetSlide.find( 'textarea' )[ 0 ] $textArea = $(textArea) editor = CodeMirror.fromTextArea( textArea, mode: 'text/html' tabMode: 'indent' indentUnit: 4 indentWithTabs: true lineNumbers: true extraKeys: "'>'": ( editor ) -> editor.closeTag( editor, '>' ) "'/'": ( editor ) -> editor.closeTag( editor, '/' ) ) editor.setSize( $textArea.width(), $textArea.height() ) editor.refresh() loadingIndicator = $targetSlide.find( 'img.editor-loading-indicator' )[ 0 ] $loadingIndicator = $(loadingIndicator) $targetSlide.find( 'select.editor-combo-box' ).on( 'change', ( event ) -> loadTemplate( editor, $loadingIndicator, $( event.target ).val() ) ) $targetSlide.find( "button.editor-preview-button" ).on( 'click', ( event ) -> showPreview( editor ) ) # Nasty hack - workaround for weird refresh issue that left some editors in a partially rendered state. Reveal.addEventListener( 'slidechanged', ( event ) -> editor.refresh() ) loadTemplate( editor, $loadingIndicator, data.sections[ 0 ].steps[ 0 ].url ) return ).fail( ( promise, type, message ) -> alert( message ) return ) return loadTemplate = ( editor, $loadingIndicator, url ) -> $loadingIndicator.addClass( 'loading' ) $.ajax( url: url dataType: 'text' ).done( ( template ) -> editor.setValue( template ) return ).fail( ( promise, type, message ) -> alert( message ) return ).always( $loadingIndicator.removeClass( 'loading' ) ) return $('section.editor').each( ( index, element ) -> $slide = $( element ) creatorEditor( $slide ) )
true
###! Custom interactive code editor and preview slide plugin for reveal.js Written by: [PI:NAME:<NAME>END_PI](http://twitter.com/johnyanarella) Copyright (c) 2012-2103 [CodeCatalyst, LLC](http://www.codecatalyst.com/). Open source under the [MIT License](http://en.wikipedia.org/wiki/MIT_License). ### $preview = $( """ <div class="preview" style="width: 373px; height: 730px;"> <iframe></iframe> </div> """ ) showPreview = ( editor ) -> # Create the preview popup. Reveal.keyboardEnabled = false $preview.bPopup( positionStyle: 'fixed' onClose: -> Reveal.keyboardEnabled = true return ) # Populate the iframe in the preview popup. previewFrame = $preview.children('iframe').get( 0 ) preview = previewFrame.contentDocument or previewFrame.contentWindow.document preview.write( editor.getValue() ) preview.close() return creatorEditor = ( $targetSlide ) -> url = $targetSlide.data( 'source' ) $.ajax( url: url dataType: 'json' ).done( ( data ) -> # Populate the slide. options ="" for section in data.sections options += "<optgroup label=\"#{ section.title }\">" for step in section.steps options += "<option value=\"#{ step.url }\">#{ step.title }</option>" options += "</optgroup>" $targetSlide.append( """ <h2>#{ data.title }</h2> <textarea></textarea> <div style="display: inline-table; width: 820px;"> <div style="display: table-cell; width: 410px; text-align: left;"> <select class="editor-combo-box"> #{ options } </select> </div> <!-- <div id="#previewBtn" style="display: table-cell; width: 410px; text-align: right;"> <button class="editor-preview-button">Preview</button> </div> --> </div> <img class="editor-loading-indicator" src="resource/image/LoadingIndicator.gif" width="32" height="32"> """ ) textArea = $targetSlide.find( 'textarea' )[ 0 ] $textArea = $(textArea) editor = CodeMirror.fromTextArea( textArea, mode: 'text/html' tabMode: 'indent' indentUnit: 4 indentWithTabs: true lineNumbers: true extraKeys: "'>'": ( editor ) -> editor.closeTag( editor, '>' ) "'/'": ( editor ) -> editor.closeTag( editor, '/' ) ) editor.setSize( $textArea.width(), $textArea.height() ) editor.refresh() loadingIndicator = $targetSlide.find( 'img.editor-loading-indicator' )[ 0 ] $loadingIndicator = $(loadingIndicator) $targetSlide.find( 'select.editor-combo-box' ).on( 'change', ( event ) -> loadTemplate( editor, $loadingIndicator, $( event.target ).val() ) ) $targetSlide.find( "button.editor-preview-button" ).on( 'click', ( event ) -> showPreview( editor ) ) # Nasty hack - workaround for weird refresh issue that left some editors in a partially rendered state. Reveal.addEventListener( 'slidechanged', ( event ) -> editor.refresh() ) loadTemplate( editor, $loadingIndicator, data.sections[ 0 ].steps[ 0 ].url ) return ).fail( ( promise, type, message ) -> alert( message ) return ) return loadTemplate = ( editor, $loadingIndicator, url ) -> $loadingIndicator.addClass( 'loading' ) $.ajax( url: url dataType: 'text' ).done( ( template ) -> editor.setValue( template ) return ).fail( ( promise, type, message ) -> alert( message ) return ).always( $loadingIndicator.removeClass( 'loading' ) ) return $('section.editor').each( ( index, element ) -> $slide = $( element ) creatorEditor( $slide ) )
[ { "context": "###\n# Composition Mod for CodeMirror\n# v2.0.2\n# Zhusee <zhusee2@gmail.com>\n#\n# Additional instance prope", "end": 54, "score": 0.9829868078231812, "start": 48, "tag": "NAME", "value": "Zhusee" }, { "context": "Composition Mod for CodeMirror\n# v2.0.2\n# Zhusee <zhu...
packages/markdown-editor/src/plugins/codemirror-composition-mod.coffee
CHU-BURA/clone-app-kobito-oss
215
### # Composition Mod for CodeMirror # v2.0.2 # Zhusee <zhusee2@gmail.com> # # Additional instance properties added to CodeMirror: # - cm.display.inCompositionMode (Boolen) # - cm.display.compositionHead (Pos) # - cm.display.textMarkerInComposition (TextMarker) ### modInitialized = false TEXT_MARKER_CLASS_NAME = "CodeMirror-text-in-composition" TEXT_MARKER_OPTIONS = { inclusiveLeft: true, inclusiveRight: true, className: TEXT_MARKER_CLASS_NAME } PREFIX_LIST = ['webkit', 'moz', 'o'] capitalizeString = (string) -> return string.charAt(0).toUpperCase() + string.slice(1) getPrefixedPropertyName = (propertyName) -> tempElem = document.createElement('div') return propertyName if tempElem.style[propertyName]? for prefix in PREFIX_LIST prefixedPropertyName = prefix + capitalizeString(propertyName) return prefixedPropertyName if tempElem.style[prefixedPropertyName]? return false CodeMirror.defineOption 'enableCompositionMod', false, (cm, newVal, oldVal) -> if newVal and !modInitialized if window.CompositionEvent? initCompositionMode(cm) else console.warn("Your browser doesn't support CompositionEvent.") cm.setOption('enableCompositionMod', false) CodeMirror.defineOption 'debugCompositionMod', false, (cm, newVal, oldVal) -> inputField = cm.display.input return if !jQuery? if newVal $(inputField).on 'input.composition-debug keypress.composition-debug compositionupdate.composition-debug', (e) -> console.log "[#{e.type}]", e.originalEvent.data, inputField.value, e.timeStamp $(inputField).on 'compositionstart.composition-debug compositionend.composition-debug', (e) -> console.warn "[#{e.type}]", e.originalEvent.data, inputField.value, cm.getCursor(), e.timeStamp else $(inputField).off('.composition-debug') setInputTranslate = (cm, translateValue) -> transformProperty = getPrefixedPropertyName("transform") # cm.display.input.style[transformProperty] = translateValue cm.display.input.textarea.style[transformProperty] = translateValue resetInputTranslate = (cm) -> setInputTranslate("") clearCompositionTextMarkers = (cm)-> # Clear previous text markers textMarkersArray = cm.getAllMarks() for textMarker in textMarkersArray if textMarker? and textMarker.className is TEXT_MARKER_CLASS_NAME textMarker.clear() console.log "[TextMarker] Cleared" if cm.options.debugCompositionMod return true initCompositionMode = (cm) -> inputField = cm.display.input # inputWrapper = cm.display.inputDiv cmWrapper = cm.display.wrapper inputWrapper = cm.display.input.textarea.parentElement inputWrapper.classList.add('CodeMirror-input-wrapper') input = inputField.textarea input.addEventListener 'compositionstart', (event) -> console.log 'composition started' return if !cm.options.enableCompositionMod cm.display.inCompositionMode = true cm.setOption('readOnly', true) cm.replaceSelection("") if cm.somethingSelected() # Clear the selected text first cm.display.compositionHead = cm.getCursor() console.log "[compositionstart] Update Composition Head", cm.display.compositionHead if cm.options.debugCompositionMod inputField.value = "" console.log "[compositionstart] Clear cm.display.input", cm.display.compositionHead if cm.options.debugCompositionMod inputWrapper.classList.add('in-composition') # CodeMirror.on inputField, 'compositionupdate', (event) -> input.addEventListener 'compositionupdate', (event) -> return if !cm.options.enableCompositionMod headPos = cm.display.compositionHead console.log 'composition update' if cm.display.textMarkerInComposition markerRange = cm.display.textMarkerInComposition.find() cm.replaceRange(event.data, headPos, markerRange.to) cm.display.textMarkerInComposition.clear() cm.display.textMarkerInComposition = undefined else cm.replaceRange(event.data, headPos, headPos) endPos = cm.getCursor() cm.display.textMarkerInComposition = cm.markText(headPos, endPos, TEXT_MARKER_OPTIONS) pixelToTranslate = cm.charCoords(endPos).left - cm.charCoords(headPos).left setInputTranslate(cm, "translateX(-#{pixelToTranslate}px)") # CodeMirror.on inputField, 'compositionend', (event) -> input.addEventListener 'compositionend', (event) -> return if !cm.options.enableCompositionMod event.preventDefault() textLeftComposition = event.data headPos = cm.display.compositionHead endPos = cm.getCursor() cm.replaceRange(textLeftComposition, headPos, endPos) console.log 'composition end', textLeftComposition cm.display.inCompositionMode = false cm.display.compositionHead = undefined cm.display.textMarkerInComposition?.clear() cm.display.textMarkerInComposition = undefined cm.setOption('readOnly', false) inputWrapper.classList.remove('in-composition') clearCompositionTextMarkers(cm) postCompositionEnd = -> return false if cm.display.inCompositionMode inputField.value = "" console.warn "[postCompositionEnd] Input Cleared" if cm.options.debugCompositionMod # CodeMirror.off(inputField, 'input', postCompositionEnd) input.removeEventListener 'input', postCompositionEnd console.log "[postCompositionEnd] Handler unregistered for future input events" if cm.options.debugCompositionMod # CodeMirror.on(inputField, 'input', postCompositionEnd) input.addEventListener 'input', postCompositionEnd
54268
### # Composition Mod for CodeMirror # v2.0.2 # <NAME> <<EMAIL>> # # Additional instance properties added to CodeMirror: # - cm.display.inCompositionMode (Boolen) # - cm.display.compositionHead (Pos) # - cm.display.textMarkerInComposition (TextMarker) ### modInitialized = false TEXT_MARKER_CLASS_NAME = "CodeMirror-text-in-composition" TEXT_MARKER_OPTIONS = { inclusiveLeft: true, inclusiveRight: true, className: TEXT_MARKER_CLASS_NAME } PREFIX_LIST = ['webkit', 'moz', 'o'] capitalizeString = (string) -> return string.charAt(0).toUpperCase() + string.slice(1) getPrefixedPropertyName = (propertyName) -> tempElem = document.createElement('div') return propertyName if tempElem.style[propertyName]? for prefix in PREFIX_LIST prefixedPropertyName = prefix + capitalizeString(propertyName) return prefixedPropertyName if tempElem.style[prefixedPropertyName]? return false CodeMirror.defineOption 'enableCompositionMod', false, (cm, newVal, oldVal) -> if newVal and !modInitialized if window.CompositionEvent? initCompositionMode(cm) else console.warn("Your browser doesn't support CompositionEvent.") cm.setOption('enableCompositionMod', false) CodeMirror.defineOption 'debugCompositionMod', false, (cm, newVal, oldVal) -> inputField = cm.display.input return if !jQuery? if newVal $(inputField).on 'input.composition-debug keypress.composition-debug compositionupdate.composition-debug', (e) -> console.log "[#{e.type}]", e.originalEvent.data, inputField.value, e.timeStamp $(inputField).on 'compositionstart.composition-debug compositionend.composition-debug', (e) -> console.warn "[#{e.type}]", e.originalEvent.data, inputField.value, cm.getCursor(), e.timeStamp else $(inputField).off('.composition-debug') setInputTranslate = (cm, translateValue) -> transformProperty = getPrefixedPropertyName("transform") # cm.display.input.style[transformProperty] = translateValue cm.display.input.textarea.style[transformProperty] = translateValue resetInputTranslate = (cm) -> setInputTranslate("") clearCompositionTextMarkers = (cm)-> # Clear previous text markers textMarkersArray = cm.getAllMarks() for textMarker in textMarkersArray if textMarker? and textMarker.className is TEXT_MARKER_CLASS_NAME textMarker.clear() console.log "[TextMarker] Cleared" if cm.options.debugCompositionMod return true initCompositionMode = (cm) -> inputField = cm.display.input # inputWrapper = cm.display.inputDiv cmWrapper = cm.display.wrapper inputWrapper = cm.display.input.textarea.parentElement inputWrapper.classList.add('CodeMirror-input-wrapper') input = inputField.textarea input.addEventListener 'compositionstart', (event) -> console.log 'composition started' return if !cm.options.enableCompositionMod cm.display.inCompositionMode = true cm.setOption('readOnly', true) cm.replaceSelection("") if cm.somethingSelected() # Clear the selected text first cm.display.compositionHead = cm.getCursor() console.log "[compositionstart] Update Composition Head", cm.display.compositionHead if cm.options.debugCompositionMod inputField.value = "" console.log "[compositionstart] Clear cm.display.input", cm.display.compositionHead if cm.options.debugCompositionMod inputWrapper.classList.add('in-composition') # CodeMirror.on inputField, 'compositionupdate', (event) -> input.addEventListener 'compositionupdate', (event) -> return if !cm.options.enableCompositionMod headPos = cm.display.compositionHead console.log 'composition update' if cm.display.textMarkerInComposition markerRange = cm.display.textMarkerInComposition.find() cm.replaceRange(event.data, headPos, markerRange.to) cm.display.textMarkerInComposition.clear() cm.display.textMarkerInComposition = undefined else cm.replaceRange(event.data, headPos, headPos) endPos = cm.getCursor() cm.display.textMarkerInComposition = cm.markText(headPos, endPos, TEXT_MARKER_OPTIONS) pixelToTranslate = cm.charCoords(endPos).left - cm.charCoords(headPos).left setInputTranslate(cm, "translateX(-#{pixelToTranslate}px)") # CodeMirror.on inputField, 'compositionend', (event) -> input.addEventListener 'compositionend', (event) -> return if !cm.options.enableCompositionMod event.preventDefault() textLeftComposition = event.data headPos = cm.display.compositionHead endPos = cm.getCursor() cm.replaceRange(textLeftComposition, headPos, endPos) console.log 'composition end', textLeftComposition cm.display.inCompositionMode = false cm.display.compositionHead = undefined cm.display.textMarkerInComposition?.clear() cm.display.textMarkerInComposition = undefined cm.setOption('readOnly', false) inputWrapper.classList.remove('in-composition') clearCompositionTextMarkers(cm) postCompositionEnd = -> return false if cm.display.inCompositionMode inputField.value = "" console.warn "[postCompositionEnd] Input Cleared" if cm.options.debugCompositionMod # CodeMirror.off(inputField, 'input', postCompositionEnd) input.removeEventListener 'input', postCompositionEnd console.log "[postCompositionEnd] Handler unregistered for future input events" if cm.options.debugCompositionMod # CodeMirror.on(inputField, 'input', postCompositionEnd) input.addEventListener 'input', postCompositionEnd
true
### # Composition Mod for CodeMirror # v2.0.2 # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # Additional instance properties added to CodeMirror: # - cm.display.inCompositionMode (Boolen) # - cm.display.compositionHead (Pos) # - cm.display.textMarkerInComposition (TextMarker) ### modInitialized = false TEXT_MARKER_CLASS_NAME = "CodeMirror-text-in-composition" TEXT_MARKER_OPTIONS = { inclusiveLeft: true, inclusiveRight: true, className: TEXT_MARKER_CLASS_NAME } PREFIX_LIST = ['webkit', 'moz', 'o'] capitalizeString = (string) -> return string.charAt(0).toUpperCase() + string.slice(1) getPrefixedPropertyName = (propertyName) -> tempElem = document.createElement('div') return propertyName if tempElem.style[propertyName]? for prefix in PREFIX_LIST prefixedPropertyName = prefix + capitalizeString(propertyName) return prefixedPropertyName if tempElem.style[prefixedPropertyName]? return false CodeMirror.defineOption 'enableCompositionMod', false, (cm, newVal, oldVal) -> if newVal and !modInitialized if window.CompositionEvent? initCompositionMode(cm) else console.warn("Your browser doesn't support CompositionEvent.") cm.setOption('enableCompositionMod', false) CodeMirror.defineOption 'debugCompositionMod', false, (cm, newVal, oldVal) -> inputField = cm.display.input return if !jQuery? if newVal $(inputField).on 'input.composition-debug keypress.composition-debug compositionupdate.composition-debug', (e) -> console.log "[#{e.type}]", e.originalEvent.data, inputField.value, e.timeStamp $(inputField).on 'compositionstart.composition-debug compositionend.composition-debug', (e) -> console.warn "[#{e.type}]", e.originalEvent.data, inputField.value, cm.getCursor(), e.timeStamp else $(inputField).off('.composition-debug') setInputTranslate = (cm, translateValue) -> transformProperty = getPrefixedPropertyName("transform") # cm.display.input.style[transformProperty] = translateValue cm.display.input.textarea.style[transformProperty] = translateValue resetInputTranslate = (cm) -> setInputTranslate("") clearCompositionTextMarkers = (cm)-> # Clear previous text markers textMarkersArray = cm.getAllMarks() for textMarker in textMarkersArray if textMarker? and textMarker.className is TEXT_MARKER_CLASS_NAME textMarker.clear() console.log "[TextMarker] Cleared" if cm.options.debugCompositionMod return true initCompositionMode = (cm) -> inputField = cm.display.input # inputWrapper = cm.display.inputDiv cmWrapper = cm.display.wrapper inputWrapper = cm.display.input.textarea.parentElement inputWrapper.classList.add('CodeMirror-input-wrapper') input = inputField.textarea input.addEventListener 'compositionstart', (event) -> console.log 'composition started' return if !cm.options.enableCompositionMod cm.display.inCompositionMode = true cm.setOption('readOnly', true) cm.replaceSelection("") if cm.somethingSelected() # Clear the selected text first cm.display.compositionHead = cm.getCursor() console.log "[compositionstart] Update Composition Head", cm.display.compositionHead if cm.options.debugCompositionMod inputField.value = "" console.log "[compositionstart] Clear cm.display.input", cm.display.compositionHead if cm.options.debugCompositionMod inputWrapper.classList.add('in-composition') # CodeMirror.on inputField, 'compositionupdate', (event) -> input.addEventListener 'compositionupdate', (event) -> return if !cm.options.enableCompositionMod headPos = cm.display.compositionHead console.log 'composition update' if cm.display.textMarkerInComposition markerRange = cm.display.textMarkerInComposition.find() cm.replaceRange(event.data, headPos, markerRange.to) cm.display.textMarkerInComposition.clear() cm.display.textMarkerInComposition = undefined else cm.replaceRange(event.data, headPos, headPos) endPos = cm.getCursor() cm.display.textMarkerInComposition = cm.markText(headPos, endPos, TEXT_MARKER_OPTIONS) pixelToTranslate = cm.charCoords(endPos).left - cm.charCoords(headPos).left setInputTranslate(cm, "translateX(-#{pixelToTranslate}px)") # CodeMirror.on inputField, 'compositionend', (event) -> input.addEventListener 'compositionend', (event) -> return if !cm.options.enableCompositionMod event.preventDefault() textLeftComposition = event.data headPos = cm.display.compositionHead endPos = cm.getCursor() cm.replaceRange(textLeftComposition, headPos, endPos) console.log 'composition end', textLeftComposition cm.display.inCompositionMode = false cm.display.compositionHead = undefined cm.display.textMarkerInComposition?.clear() cm.display.textMarkerInComposition = undefined cm.setOption('readOnly', false) inputWrapper.classList.remove('in-composition') clearCompositionTextMarkers(cm) postCompositionEnd = -> return false if cm.display.inCompositionMode inputField.value = "" console.warn "[postCompositionEnd] Input Cleared" if cm.options.debugCompositionMod # CodeMirror.off(inputField, 'input', postCompositionEnd) input.removeEventListener 'input', postCompositionEnd console.log "[postCompositionEnd] Handler unregistered for future input events" if cm.options.debugCompositionMod # CodeMirror.on(inputField, 'input', postCompositionEnd) input.addEventListener 'input', postCompositionEnd
[ { "context": "mitive types, like strings:\n *\n * var names = [ 'Antonio', 'Ben', 'Curtis' ];\n *\n * {{:each names do}}\n *", "end": 2592, "score": 0.9994698762893677, "start": 2585, "tag": "NAME", "value": "Antonio" }, { "context": "s, like strings:\n *\n * var names = [ 'Antoni...
lib/walrus/ast.coffee
hershmire/walrus
0
AST = { } ###* * AST.SafeNode * A simple wrapper node to signify safe compilation for the rest of * the nodes in the tree. ### class AST.SafeNode constructor : ( @node ) -> compile : ( context, root, safe ) -> @node.compile context, root, true ###* * AST.NodeCollection * A collection of nodes with the #compile interface, simply compiles * each of its nodes and returns the resulting array. ### class AST.NodeCollection constructor : ( @nodes ) -> compile : ( context, root, safe ) -> node.compile context, root, safe for node in @nodes ###* * AST.JoinedNodeCollection * Compiles all of its nodes, then joins them. ### class AST.JoinedNodeCollection extends AST.NodeCollection constructor : ( @nodes ) -> compile : ( context, root, safe ) -> super( context, root, safe ).join '' ###* * AST.DocumentNode * The root node of the document. Defaults to escaping its content. ### class AST.DocumentNode extends AST.JoinedNodeCollection compile : ( context ) -> super context, context, false ###* * AST.ContentNode * A node with non-mustache content, probably HTML. We simply pass the content through. ### class AST.ContentNode constructor : ( @content ) -> compile : ( context, root, safe ) -> @content ###* * AST.MemberNode * A node that refers to a member of the context. We don't explicitly check that this * member exists in case the developer wants to check that in a conditional. * * `{{member}}`, for instance, will compile to `index[ 'member' ]`. ### class AST.MemberNode constructor : ( @path ) -> compile : ( index, context, root, safe ) -> if safe then index[ @path ] else Walrus.Utils.escape( index[ @path ] ) ###* * AST.MethodNode * A node that refers to a member of the context, specifically a method, and will * call that method with any given arguments after they compile. We explicitly * check that the method exists to avoid 'foo is not a function' or other cryptic * errors. * * `{{member( )}}`, for instance, will compile to `index[ 'member' ]( )`. ### class AST.MethodNode constructor : ( @path, @arguments ) -> compile : ( index, context, root, safe ) -> throw new Error "Cannot find any method named '#{@path}' in #{index}." unless index[ @path ]? index[ @path ] @arguments.compile( context, root, safe )... ###* * AST.ThisNode * A node that simply returns the current context to be evaluated. This is most useful * during implicit iteration and is denoted with a dot, like `{{.}}`. * * One example is when you've got an array of primitive types, like strings: * * var names = [ 'Antonio', 'Ben', 'Curtis' ]; * * {{:each names do}} * <li>{{.}}</li> * {{end}} * * A similar use case is when the root view object is an array: * * var view = [ { name : 'Antonio' }, { name : 'Ben' }, { name : 'Curtis' } ]; * * {{:each . do}} * <li>{{name}}</li> * {{end}} ### class AST.ThisNode compile : ( context, root, safe ) -> context ###* * AST.PathNode * A node that represents an object path. The path segments are typically * `AST.MemberNode`s and `AST.MethodNode`s. * * A `PathNode` may be evaluated in two contexts: the current "local" context * and the "root" context. For example, `{{foo.bar.baz}}` will try to evaluate * the object path from the current context, while `{{@foo.bar.baz}}` will * start back up at the root view object. ### class AST.PathNode constructor : ( @paths, @local ) -> compile : ( context, root, safe ) -> scope = if @local then context else root Walrus.Utils.reduce @paths, scope, ( scope, path ) -> path.compile scope, context, root, safe ###* * AST.PrimitiveNode * A node whose value is a javascript primitive or literal. Supported * primitives are: * * - Strings with "double quotes" * - Strings with 'single quotes' * - Numbers, like 45 or 987.654 * - Booleans, true or false * * TODO These primitives are currently parsed in the lexing phase. I'm * kinda feeling like a bit of that logic should be moved to the AST instead. * Perhaps declare the literal type in the lexer and determine the conversion * here, or create distinct classes for each primitive type, like `BooleanNode` * and `NumberNode`. ### class AST.PrimitiveNode constructor : ( @value ) -> compile : ( context, root, safe ) -> @value ###* * AST.ExpressionNode * An expression is the main part of a mustache. It typically consists of a path, * which gets compiled, then passed to any filters to be manipulated further. * The subject of an expression may also be a primitive. * * The breakdown of a single-line mustache is: * * {{ expression | :filter(s) }} * * And a block mustache with a helper, like: * * {{ :helper expression | :filters(s) do }} * // block content * {{ end }} ### class AST.ExpressionNode constructor : ( @paths, @filters ) -> compile : ( context, root, safe ) -> @filters.apply @paths.compile( context, root, safe ), context, root, safe ###* * AST.BlockNode * A node that contains other statements within a block. `BlockNode`s are denoted * by the use of a _:helper_, and the presence of `do`/`end` to signify the start * and end of the node's block. It is the helper's responsibility to determine * how to compile the block. * * Will throw an error if the named helper is not defined in `Walrus.Helpers`. ### class AST.BlockNode constructor : ( @name, @expression, @block ) -> throw new Error "Cannot find any helper named '#{@name}'." unless Walrus.Helpers[ @name ]? compile : ( context, root, safe ) -> Walrus.Helpers[ @name ] @expression, context, root, safe, @block ###* * AST.FilterNode * A node that specifies a _filter_ used to post-process the result of the expression. * Filters may also accept arguments, just like methods. These arguments are determined * and handled by the filter itself. * * Will throw an error if the named filter is not defined in `Walrus.Filters`. ### class AST.FilterNode constructor : ( @name, @arguments ) -> throw new Error "Cannot find any filter named '#{@name}'." unless Walrus.Filters[ @name ]? apply : ( value, context, root, safe ) -> Walrus.Filters[ @name ] value, @arguments.compile( context, root, safe )... ###* * AST.FilterCollection * A collection of filters. Filters are applied to the expression * in order from left to right. ### class AST.FilterCollection constructor : ( @filters ) -> apply : ( expression, context, root, safe ) -> Walrus.Utils.reduce @filters, expression, ( memo, filter ) -> filter.apply memo, context, root, safe # Export that AST, son. Walrus.AST = AST
188734
AST = { } ###* * AST.SafeNode * A simple wrapper node to signify safe compilation for the rest of * the nodes in the tree. ### class AST.SafeNode constructor : ( @node ) -> compile : ( context, root, safe ) -> @node.compile context, root, true ###* * AST.NodeCollection * A collection of nodes with the #compile interface, simply compiles * each of its nodes and returns the resulting array. ### class AST.NodeCollection constructor : ( @nodes ) -> compile : ( context, root, safe ) -> node.compile context, root, safe for node in @nodes ###* * AST.JoinedNodeCollection * Compiles all of its nodes, then joins them. ### class AST.JoinedNodeCollection extends AST.NodeCollection constructor : ( @nodes ) -> compile : ( context, root, safe ) -> super( context, root, safe ).join '' ###* * AST.DocumentNode * The root node of the document. Defaults to escaping its content. ### class AST.DocumentNode extends AST.JoinedNodeCollection compile : ( context ) -> super context, context, false ###* * AST.ContentNode * A node with non-mustache content, probably HTML. We simply pass the content through. ### class AST.ContentNode constructor : ( @content ) -> compile : ( context, root, safe ) -> @content ###* * AST.MemberNode * A node that refers to a member of the context. We don't explicitly check that this * member exists in case the developer wants to check that in a conditional. * * `{{member}}`, for instance, will compile to `index[ 'member' ]`. ### class AST.MemberNode constructor : ( @path ) -> compile : ( index, context, root, safe ) -> if safe then index[ @path ] else Walrus.Utils.escape( index[ @path ] ) ###* * AST.MethodNode * A node that refers to a member of the context, specifically a method, and will * call that method with any given arguments after they compile. We explicitly * check that the method exists to avoid 'foo is not a function' or other cryptic * errors. * * `{{member( )}}`, for instance, will compile to `index[ 'member' ]( )`. ### class AST.MethodNode constructor : ( @path, @arguments ) -> compile : ( index, context, root, safe ) -> throw new Error "Cannot find any method named '#{@path}' in #{index}." unless index[ @path ]? index[ @path ] @arguments.compile( context, root, safe )... ###* * AST.ThisNode * A node that simply returns the current context to be evaluated. This is most useful * during implicit iteration and is denoted with a dot, like `{{.}}`. * * One example is when you've got an array of primitive types, like strings: * * var names = [ '<NAME>', '<NAME>', '<NAME>' ]; * * {{:each names do}} * <li>{{.}}</li> * {{end}} * * A similar use case is when the root view object is an array: * * var view = [ { name : '<NAME>' }, { name : '<NAME>' }, { name : '<NAME>' } ]; * * {{:each . do}} * <li>{{name}}</li> * {{end}} ### class AST.ThisNode compile : ( context, root, safe ) -> context ###* * AST.PathNode * A node that represents an object path. The path segments are typically * `AST.MemberNode`s and `AST.MethodNode`s. * * A `PathNode` may be evaluated in two contexts: the current "local" context * and the "root" context. For example, `{{foo.bar.baz}}` will try to evaluate * the object path from the current context, while `{{@foo.bar.baz}}` will * start back up at the root view object. ### class AST.PathNode constructor : ( @paths, @local ) -> compile : ( context, root, safe ) -> scope = if @local then context else root Walrus.Utils.reduce @paths, scope, ( scope, path ) -> path.compile scope, context, root, safe ###* * AST.PrimitiveNode * A node whose value is a javascript primitive or literal. Supported * primitives are: * * - Strings with "double quotes" * - Strings with 'single quotes' * - Numbers, like 45 or 987.654 * - Booleans, true or false * * TODO These primitives are currently parsed in the lexing phase. I'm * kinda feeling like a bit of that logic should be moved to the AST instead. * Perhaps declare the literal type in the lexer and determine the conversion * here, or create distinct classes for each primitive type, like `BooleanNode` * and `NumberNode`. ### class AST.PrimitiveNode constructor : ( @value ) -> compile : ( context, root, safe ) -> @value ###* * AST.ExpressionNode * An expression is the main part of a mustache. It typically consists of a path, * which gets compiled, then passed to any filters to be manipulated further. * The subject of an expression may also be a primitive. * * The breakdown of a single-line mustache is: * * {{ expression | :filter(s) }} * * And a block mustache with a helper, like: * * {{ :helper expression | :filters(s) do }} * // block content * {{ end }} ### class AST.ExpressionNode constructor : ( @paths, @filters ) -> compile : ( context, root, safe ) -> @filters.apply @paths.compile( context, root, safe ), context, root, safe ###* * AST.BlockNode * A node that contains other statements within a block. `BlockNode`s are denoted * by the use of a _:helper_, and the presence of `do`/`end` to signify the start * and end of the node's block. It is the helper's responsibility to determine * how to compile the block. * * Will throw an error if the named helper is not defined in `Walrus.Helpers`. ### class AST.BlockNode constructor : ( @name, @expression, @block ) -> throw new Error "Cannot find any helper named '#{@name}'." unless Walrus.Helpers[ @name ]? compile : ( context, root, safe ) -> Walrus.Helpers[ @name ] @expression, context, root, safe, @block ###* * AST.FilterNode * A node that specifies a _filter_ used to post-process the result of the expression. * Filters may also accept arguments, just like methods. These arguments are determined * and handled by the filter itself. * * Will throw an error if the named filter is not defined in `Walrus.Filters`. ### class AST.FilterNode constructor : ( @name, @arguments ) -> throw new Error "Cannot find any filter named '#{@name}'." unless Walrus.Filters[ @name ]? apply : ( value, context, root, safe ) -> Walrus.Filters[ @name ] value, @arguments.compile( context, root, safe )... ###* * AST.FilterCollection * A collection of filters. Filters are applied to the expression * in order from left to right. ### class AST.FilterCollection constructor : ( @filters ) -> apply : ( expression, context, root, safe ) -> Walrus.Utils.reduce @filters, expression, ( memo, filter ) -> filter.apply memo, context, root, safe # Export that AST, son. Walrus.AST = AST
true
AST = { } ###* * AST.SafeNode * A simple wrapper node to signify safe compilation for the rest of * the nodes in the tree. ### class AST.SafeNode constructor : ( @node ) -> compile : ( context, root, safe ) -> @node.compile context, root, true ###* * AST.NodeCollection * A collection of nodes with the #compile interface, simply compiles * each of its nodes and returns the resulting array. ### class AST.NodeCollection constructor : ( @nodes ) -> compile : ( context, root, safe ) -> node.compile context, root, safe for node in @nodes ###* * AST.JoinedNodeCollection * Compiles all of its nodes, then joins them. ### class AST.JoinedNodeCollection extends AST.NodeCollection constructor : ( @nodes ) -> compile : ( context, root, safe ) -> super( context, root, safe ).join '' ###* * AST.DocumentNode * The root node of the document. Defaults to escaping its content. ### class AST.DocumentNode extends AST.JoinedNodeCollection compile : ( context ) -> super context, context, false ###* * AST.ContentNode * A node with non-mustache content, probably HTML. We simply pass the content through. ### class AST.ContentNode constructor : ( @content ) -> compile : ( context, root, safe ) -> @content ###* * AST.MemberNode * A node that refers to a member of the context. We don't explicitly check that this * member exists in case the developer wants to check that in a conditional. * * `{{member}}`, for instance, will compile to `index[ 'member' ]`. ### class AST.MemberNode constructor : ( @path ) -> compile : ( index, context, root, safe ) -> if safe then index[ @path ] else Walrus.Utils.escape( index[ @path ] ) ###* * AST.MethodNode * A node that refers to a member of the context, specifically a method, and will * call that method with any given arguments after they compile. We explicitly * check that the method exists to avoid 'foo is not a function' or other cryptic * errors. * * `{{member( )}}`, for instance, will compile to `index[ 'member' ]( )`. ### class AST.MethodNode constructor : ( @path, @arguments ) -> compile : ( index, context, root, safe ) -> throw new Error "Cannot find any method named '#{@path}' in #{index}." unless index[ @path ]? index[ @path ] @arguments.compile( context, root, safe )... ###* * AST.ThisNode * A node that simply returns the current context to be evaluated. This is most useful * during implicit iteration and is denoted with a dot, like `{{.}}`. * * One example is when you've got an array of primitive types, like strings: * * var names = [ 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI' ]; * * {{:each names do}} * <li>{{.}}</li> * {{end}} * * A similar use case is when the root view object is an array: * * var view = [ { name : 'PI:NAME:<NAME>END_PI' }, { name : 'PI:NAME:<NAME>END_PI' }, { name : 'PI:NAME:<NAME>END_PI' } ]; * * {{:each . do}} * <li>{{name}}</li> * {{end}} ### class AST.ThisNode compile : ( context, root, safe ) -> context ###* * AST.PathNode * A node that represents an object path. The path segments are typically * `AST.MemberNode`s and `AST.MethodNode`s. * * A `PathNode` may be evaluated in two contexts: the current "local" context * and the "root" context. For example, `{{foo.bar.baz}}` will try to evaluate * the object path from the current context, while `{{@foo.bar.baz}}` will * start back up at the root view object. ### class AST.PathNode constructor : ( @paths, @local ) -> compile : ( context, root, safe ) -> scope = if @local then context else root Walrus.Utils.reduce @paths, scope, ( scope, path ) -> path.compile scope, context, root, safe ###* * AST.PrimitiveNode * A node whose value is a javascript primitive or literal. Supported * primitives are: * * - Strings with "double quotes" * - Strings with 'single quotes' * - Numbers, like 45 or 987.654 * - Booleans, true or false * * TODO These primitives are currently parsed in the lexing phase. I'm * kinda feeling like a bit of that logic should be moved to the AST instead. * Perhaps declare the literal type in the lexer and determine the conversion * here, or create distinct classes for each primitive type, like `BooleanNode` * and `NumberNode`. ### class AST.PrimitiveNode constructor : ( @value ) -> compile : ( context, root, safe ) -> @value ###* * AST.ExpressionNode * An expression is the main part of a mustache. It typically consists of a path, * which gets compiled, then passed to any filters to be manipulated further. * The subject of an expression may also be a primitive. * * The breakdown of a single-line mustache is: * * {{ expression | :filter(s) }} * * And a block mustache with a helper, like: * * {{ :helper expression | :filters(s) do }} * // block content * {{ end }} ### class AST.ExpressionNode constructor : ( @paths, @filters ) -> compile : ( context, root, safe ) -> @filters.apply @paths.compile( context, root, safe ), context, root, safe ###* * AST.BlockNode * A node that contains other statements within a block. `BlockNode`s are denoted * by the use of a _:helper_, and the presence of `do`/`end` to signify the start * and end of the node's block. It is the helper's responsibility to determine * how to compile the block. * * Will throw an error if the named helper is not defined in `Walrus.Helpers`. ### class AST.BlockNode constructor : ( @name, @expression, @block ) -> throw new Error "Cannot find any helper named '#{@name}'." unless Walrus.Helpers[ @name ]? compile : ( context, root, safe ) -> Walrus.Helpers[ @name ] @expression, context, root, safe, @block ###* * AST.FilterNode * A node that specifies a _filter_ used to post-process the result of the expression. * Filters may also accept arguments, just like methods. These arguments are determined * and handled by the filter itself. * * Will throw an error if the named filter is not defined in `Walrus.Filters`. ### class AST.FilterNode constructor : ( @name, @arguments ) -> throw new Error "Cannot find any filter named '#{@name}'." unless Walrus.Filters[ @name ]? apply : ( value, context, root, safe ) -> Walrus.Filters[ @name ] value, @arguments.compile( context, root, safe )... ###* * AST.FilterCollection * A collection of filters. Filters are applied to the expression * in order from left to right. ### class AST.FilterCollection constructor : ( @filters ) -> apply : ( expression, context, root, safe ) -> Walrus.Utils.reduce @filters, expression, ( memo, filter ) -> filter.apply memo, context, root, safe # Export that AST, son. Walrus.AST = AST
[ { "context": "JavaScript で計算するためのライブラリ\r\n Osamu Takeuchi <osamu@big.jp>\r\n\r\n###\r\n\r\n\"use strict\"\r\n\r\n# 元の時刻から", "end": 83, "score": 0.9998733401298523, "start": 69, "tag": "NAME", "value": "Osamu Takeuchi" }, { "context": "めのライブラリ\r\n ...
src/japanese-holidays.coffee
SelanInc/japanese-holidays-js
87
### 日本の休日を JavaScript で計算するためのライブラリ Osamu Takeuchi <osamu@big.jp> ### "use strict" # 元の時刻から指定時間だけずらした時刻を生成して返す shiftDate = (date, year, mon, day, hour, min, sec, msec) -> # まずは日付以下の部分を msec に直して処理する res = new Date(2000,0,1) res.setTime( date.getTime() + (((( day ? 0 ) * 24 + ( hour ? 0 )) * 60 + ( min ? 0 )) * 60 + ( sec ? 0 )) * 1000 + ( msec ? 0 ) ) # 年と月はちょっと面倒な処理になる res.setFullYear res.getFullYear() + ( year ? 0 ) + Math.floor( ( res.getMonth() + ( mon ? 0 ) ) / 12 ) res.setMonth ( ( res.getMonth() + ( mon ? 0 ) ) % 12 + 12 ) % 12 return res u2j = (d) -> shiftDate(d,0,0,0,+9) j2u = (d) -> shiftDate(d,0,0,0,-9) uDate = (y,m,d) -> new Date(Date.UTC(y,m,d)) jDate = (y,m,d) -> j2u uDate(y,m,d) getJDay = (d) -> (u2j d).getUTCDay() getJDate = (d) -> (u2j d).getUTCDate() getJMonth = (d) -> (u2j d).getUTCMonth() getJFullYear = (d) -> (u2j d).getUTCFullYear() getJHours = (d) -> (u2j d).getUTCHours() getJMinutes = (d) -> (u2j d).getUTCMinutes() ### ヘルパ関数 ### # 年を与えると指定の祝日を返す関数を作成 simpleHoliday = (month, day) -> (year) -> jDate(year, month-1, day) # 年を与えると指定の月の nth 月曜を返す関数を作成 happyMonday = (month, nth) -> (year) -> monday = 1 first = jDate(year, month-1, 1) shiftDate( first, 0, 0, ( 7 - ( getJDay(first) - monday ) ) % 7 + ( nth - 1 ) * 7 ) # 年を与えると春分の日を返す shunbunWithTime = (year) -> new Date(-655866700000 + 31556940400 * (year-1949) ) shunbun = (year) -> date = shunbunWithTime(year) jDate(year, getJMonth(date), getJDate(date)) # 年を与えると秋分の日を返す shubunWithTime = (year) -> if day = { 1603: 23, 2074: 23, 2355: 23, 2384: 22 }[year] jDate(year, 9-1, day) else new Date(-671316910000 + 31556910000 * (year-1948) ) shubun = (year) -> date = shubunWithTime(year) jDate(year, getJMonth(date), getJDate(date)) ### 休日定義 https://ja.wikipedia.org/wiki/%E5%9B%BD%E6%B0%91%E3%81%AE%E7%A5%9D%E6%97%A5 ### definition = [ [ "元日", simpleHoliday( 1, 1), 1949 ], [ "成人の日", simpleHoliday( 1, 15), 1949, 1999 ], [ "成人の日", happyMonday( 1, 2), 2000 ], [ "建国記念の日", simpleHoliday( 2, 11), 1967 ], [ "天皇誕生日", simpleHoliday( 2, 23), 2020 ], [ "昭和天皇の大喪の礼", simpleHoliday( 2, 24), 1989, 1989 ], [ "春分の日", shunbun, 1949 ], [ "皇太子明仁親王の結婚の儀", simpleHoliday( 4, 10), 1959, 1959 ], [ "天皇誕生日", simpleHoliday( 4, 29), 1949, 1988 ], [ "みどりの日", simpleHoliday( 4, 29), 1989, 2006 ], [ "昭和の日", simpleHoliday( 4, 29), 2007 ], [ "即位の日", simpleHoliday( 5, 1), 2019, 2019 ], [ "憲法記念日", simpleHoliday( 5, 3), 1949 ], [ "みどりの日", simpleHoliday( 5, 4), 2007 ], [ "こどもの日", simpleHoliday( 5, 5), 1949 ], [ "皇太子徳仁親王の結婚の儀", simpleHoliday( 6, 9), 1993, 1993 ], [ "海の日", simpleHoliday( 7, 20), 1996, 2002 ], [ "海の日", happyMonday( 7, 3), 2003, 2019 ], [ "海の日", simpleHoliday( 7, 23), 2020, 2020 ], [ "海の日", simpleHoliday( 7, 22), 2021, 2021 ], [ "海の日", happyMonday( 7, 3), 2022 ], [ "山の日", simpleHoliday( 8, 11), 2016, 2019 ], [ "山の日", simpleHoliday( 8, 10), 2020, 2020 ], [ "山の日", simpleHoliday( 8, 8), 2021, 2021 ], [ "山の日", simpleHoliday( 8, 11), 2022 ], [ "敬老の日", simpleHoliday( 9, 15), 1966, 2002 ], [ "敬老の日", happyMonday( 9, 3), 2003 ], [ "秋分の日", shubun, 1948 ], [ "体育の日", simpleHoliday(10, 10), 1966, 1999 ], [ "体育の日", happyMonday( 10, 2), 2000, 2019 ], [ "スポーツの日", simpleHoliday( 7, 24), 2020, 2020 ], [ "スポーツの日", simpleHoliday( 7, 23), 2021, 2021 ], [ "スポーツの日", happyMonday( 10, 2), 2022 ], [ "即位礼正殿の儀", simpleHoliday(10, 22), 2019, 2019 ], [ "文化の日", simpleHoliday(11, 3), 1948 ], [ "即位礼正殿の儀", simpleHoliday(11, 12), 1990, 1990 ], [ "勤労感謝の日", simpleHoliday(11, 23), 1948 ], [ "天皇誕生日", simpleHoliday(12, 23), 1989, 2018 ], ] # 休日を与えるとその振替休日を返す # 振り替え休日がなければ null を返す furikaeHoliday = (holiday) -> # 振替休日制度制定前 または 日曜日でない場合 振り替え無し sunday = 0 if holiday < jDate(1973, 4-1, 30-1) or getJDay(holiday) != sunday return null # 日曜日なので一日ずらす furikae = shiftDate(holiday, 0, 0, 1) # ずらした月曜日が休日でなければ振替休日 if !isHolidayAt(furikae, false) return furikae # 旧振り替え制度では1日以上ずらさない if holiday < jDate(2007, 1-1, 1) return null # たぶんこれに該当する日はないはず? loop # 振り替えた結果が休日だったら1日ずつずらす furikae = shiftDate(furikae, 0, 0, 1) if !isHolidayAt(furikae, false) return furikae # 休日を与えると、翌日が国民の休日かどうかを判定して、 # 国民の休日であればその日を返す kokuminHoliday = (holiday) -> if getJFullYear(holiday) < 1988 # 制定前 return null # 2日後が振り替え以外の祝日か if !isHolidayAt(shiftDate(holiday, 0, 0, 2), false) return null sunday = 0 monday = 1 kokumin = shiftDate(holiday, 0, 0, 1) if isHolidayAt(kokumin, false) or # 次の日が祝日 getJDay(kokumin)==sunday or # 次の日が日曜 getJDay(kokumin)==monday # 次の日が月曜(振替休日になる) return null return kokumin # 計算結果をキャッシュする # # holidays[furikae] = { # 1999: # "1,1": "元旦" # "1,15": "成人の日" # ... # } # holidays = { true: {}, false: {} } getHolidaysOf = (y, furikae) -> # キャッシュされていればそれを返す furikae = if !furikae? or furikae then true else false cache = holidays[furikae][y] return cache if cache? # されてなければ計算してキャッシュ # 振替休日を計算するには振替休日以外の休日が計算されて # いないとダメなので、先に計算する wo_furikae = {} for entry in definition continue if entry[2]? && y < entry[2] # 制定年以前 continue if entry[3]? && entry[3] < y # 廃止年以降 holiday = entry[1](y) # 休日を計算 continue unless holiday? # 無効であれば無視 m = getJMonth(holiday) + 1 # 結果を登録 d = getJDate(holiday) wo_furikae[ [m,d] ] = entry[0] holidays[false][y] = wo_furikae # 国民の休日を追加する kokuminHolidays = [] for month_day of wo_furikae month_day = month_day.split(",") holiday = kokuminHoliday( jDate(y, month_day[0]-1, month_day[1] ) ) if holiday? m = getJMonth(holiday) + 1 # 結果を登録 d = getJDate(holiday) kokuminHolidays.push([m,d]) for holiday in kokuminHolidays wo_furikae[holiday] = "国民の休日" # 振替休日を追加する w_furikae = {} for month_day, name of wo_furikae w_furikae[month_day] = name month_day = month_day.split(",") holiday = furikaeHoliday( jDate(y, month_day[0]-1, month_day[1] ) ) if holiday? m = getJMonth(holiday) + 1 # 結果を登録 d = getJDate(holiday) w_furikae[ [m,d] ] = "振替休日" holidays[true][y] = w_furikae # 結果を登録 return holidays[furikae][y] ### クラス定義 ### target = (module?.exports ? this.JapaneseHolidays={}) target.getHolidaysOf = (y, furikae) -> # データを整形する result = [] for month_day, name of getHolidaysOf(y, furikae) result.push( month : parseInt(month_day.split(",")[0]) date : parseInt(month_day.split(",")[1]) name : name ) # 日付順に並べ直す result.sort( (a,b)-> (a.month-b.month) or (a.date-b.date) ) result isHoliday = (date, furikae) -> getHolidaysOf(date.getFullYear(), furikae)[ [date.getMonth()+1, date.getDate()] ] isHolidayAt = (date, furikae) -> getHolidaysOf(getJFullYear(date), furikae)[ [getJMonth(date)+1, getJDate(date)] ] target.isHoliday = isHoliday target.isHolidayAt = isHolidayAt target.shiftDate = shiftDate target.u2j = u2j target.j2u = j2u target.jDate = jDate target.uDate = uDate target.getJDay = getJDay target.getJDate = getJDate target.getJMonth = getJMonth target.getJFullYear = getJFullYear target.getJHours = getJHours target.getJMinutes = getJMinutes target.__forTest = { shunbunWithTime: shunbunWithTime shubunWithTime: shubunWithTime }
212534
### 日本の休日を JavaScript で計算するためのライブラリ <NAME> <<EMAIL>> ### "use strict" # 元の時刻から指定時間だけずらした時刻を生成して返す shiftDate = (date, year, mon, day, hour, min, sec, msec) -> # まずは日付以下の部分を msec に直して処理する res = new Date(2000,0,1) res.setTime( date.getTime() + (((( day ? 0 ) * 24 + ( hour ? 0 )) * 60 + ( min ? 0 )) * 60 + ( sec ? 0 )) * 1000 + ( msec ? 0 ) ) # 年と月はちょっと面倒な処理になる res.setFullYear res.getFullYear() + ( year ? 0 ) + Math.floor( ( res.getMonth() + ( mon ? 0 ) ) / 12 ) res.setMonth ( ( res.getMonth() + ( mon ? 0 ) ) % 12 + 12 ) % 12 return res u2j = (d) -> shiftDate(d,0,0,0,+9) j2u = (d) -> shiftDate(d,0,0,0,-9) uDate = (y,m,d) -> new Date(Date.UTC(y,m,d)) jDate = (y,m,d) -> j2u uDate(y,m,d) getJDay = (d) -> (u2j d).getUTCDay() getJDate = (d) -> (u2j d).getUTCDate() getJMonth = (d) -> (u2j d).getUTCMonth() getJFullYear = (d) -> (u2j d).getUTCFullYear() getJHours = (d) -> (u2j d).getUTCHours() getJMinutes = (d) -> (u2j d).getUTCMinutes() ### ヘルパ関数 ### # 年を与えると指定の祝日を返す関数を作成 simpleHoliday = (month, day) -> (year) -> jDate(year, month-1, day) # 年を与えると指定の月の nth 月曜を返す関数を作成 happyMonday = (month, nth) -> (year) -> monday = 1 first = jDate(year, month-1, 1) shiftDate( first, 0, 0, ( 7 - ( getJDay(first) - monday ) ) % 7 + ( nth - 1 ) * 7 ) # 年を与えると春分の日を返す shunbunWithTime = (year) -> new Date(-655866700000 + 31556940400 * (year-1949) ) shunbun = (year) -> date = shunbunWithTime(year) jDate(year, getJMonth(date), getJDate(date)) # 年を与えると秋分の日を返す shubunWithTime = (year) -> if day = { 1603: 23, 2074: 23, 2355: 23, 2384: 22 }[year] jDate(year, 9-1, day) else new Date(-671316910000 + 31556910000 * (year-1948) ) shubun = (year) -> date = shubunWithTime(year) jDate(year, getJMonth(date), getJDate(date)) ### 休日定義 https://ja.wikipedia.org/wiki/%E5%9B%BD%E6%B0%91%E3%81%AE%E7%A5%9D%E6%97%A5 ### definition = [ [ "元日", simpleHoliday( 1, 1), 1949 ], [ "成人の日", simpleHoliday( 1, 15), 1949, 1999 ], [ "成人の日", happyMonday( 1, 2), 2000 ], [ "建国記念の日", simpleHoliday( 2, 11), 1967 ], [ "天皇誕生日", simpleHoliday( 2, 23), 2020 ], [ "昭和天皇の大喪の礼", simpleHoliday( 2, 24), 1989, 1989 ], [ "春分の日", shunbun, 1949 ], [ "皇太子明仁親王の結婚の儀", simpleHoliday( 4, 10), 1959, 1959 ], [ "天皇誕生日", simpleHoliday( 4, 29), 1949, 1988 ], [ "みどりの日", simpleHoliday( 4, 29), 1989, 2006 ], [ "昭和の日", simpleHoliday( 4, 29), 2007 ], [ "即位の日", simpleHoliday( 5, 1), 2019, 2019 ], [ "憲法記念日", simpleHoliday( 5, 3), 1949 ], [ "みどりの日", simpleHoliday( 5, 4), 2007 ], [ "こどもの日", simpleHoliday( 5, 5), 1949 ], [ "皇太子徳仁親王の結婚の儀", simpleHoliday( 6, 9), 1993, 1993 ], [ "海の日", simpleHoliday( 7, 20), 1996, 2002 ], [ "海の日", happyMonday( 7, 3), 2003, 2019 ], [ "海の日", simpleHoliday( 7, 23), 2020, 2020 ], [ "海の日", simpleHoliday( 7, 22), 2021, 2021 ], [ "海の日", happyMonday( 7, 3), 2022 ], [ "山の日", simpleHoliday( 8, 11), 2016, 2019 ], [ "山の日", simpleHoliday( 8, 10), 2020, 2020 ], [ "山の日", simpleHoliday( 8, 8), 2021, 2021 ], [ "山の日", simpleHoliday( 8, 11), 2022 ], [ "敬老の日", simpleHoliday( 9, 15), 1966, 2002 ], [ "敬老の日", happyMonday( 9, 3), 2003 ], [ "秋分の日", shubun, 1948 ], [ "体育の日", simpleHoliday(10, 10), 1966, 1999 ], [ "体育の日", happyMonday( 10, 2), 2000, 2019 ], [ "スポーツの日", simpleHoliday( 7, 24), 2020, 2020 ], [ "スポーツの日", simpleHoliday( 7, 23), 2021, 2021 ], [ "スポーツの日", happyMonday( 10, 2), 2022 ], [ "即位礼正殿の儀", simpleHoliday(10, 22), 2019, 2019 ], [ "文化の日", simpleHoliday(11, 3), 1948 ], [ "即位礼正殿の儀", simpleHoliday(11, 12), 1990, 1990 ], [ "勤労感謝の日", simpleHoliday(11, 23), 1948 ], [ "天皇誕生日", simpleHoliday(12, 23), 1989, 2018 ], ] # 休日を与えるとその振替休日を返す # 振り替え休日がなければ null を返す furikaeHoliday = (holiday) -> # 振替休日制度制定前 または 日曜日でない場合 振り替え無し sunday = 0 if holiday < jDate(1973, 4-1, 30-1) or getJDay(holiday) != sunday return null # 日曜日なので一日ずらす furikae = shiftDate(holiday, 0, 0, 1) # ずらした月曜日が休日でなければ振替休日 if !isHolidayAt(furikae, false) return furikae # 旧振り替え制度では1日以上ずらさない if holiday < jDate(2007, 1-1, 1) return null # たぶんこれに該当する日はないはず? loop # 振り替えた結果が休日だったら1日ずつずらす furikae = shiftDate(furikae, 0, 0, 1) if !isHolidayAt(furikae, false) return furikae # 休日を与えると、翌日が国民の休日かどうかを判定して、 # 国民の休日であればその日を返す kokuminHoliday = (holiday) -> if getJFullYear(holiday) < 1988 # 制定前 return null # 2日後が振り替え以外の祝日か if !isHolidayAt(shiftDate(holiday, 0, 0, 2), false) return null sunday = 0 monday = 1 kokumin = shiftDate(holiday, 0, 0, 1) if isHolidayAt(kokumin, false) or # 次の日が祝日 getJDay(kokumin)==sunday or # 次の日が日曜 getJDay(kokumin)==monday # 次の日が月曜(振替休日になる) return null return kokumin # 計算結果をキャッシュする # # holidays[furikae] = { # 1999: # "1,1": "元旦" # "1,15": "成人の日" # ... # } # holidays = { true: {}, false: {} } getHolidaysOf = (y, furikae) -> # キャッシュされていればそれを返す furikae = if !furikae? or furikae then true else false cache = holidays[furikae][y] return cache if cache? # されてなければ計算してキャッシュ # 振替休日を計算するには振替休日以外の休日が計算されて # いないとダメなので、先に計算する wo_furikae = {} for entry in definition continue if entry[2]? && y < entry[2] # 制定年以前 continue if entry[3]? && entry[3] < y # 廃止年以降 holiday = entry[1](y) # 休日を計算 continue unless holiday? # 無効であれば無視 m = getJMonth(holiday) + 1 # 結果を登録 d = getJDate(holiday) wo_furikae[ [m,d] ] = entry[0] holidays[false][y] = wo_furikae # 国民の休日を追加する kokuminHolidays = [] for month_day of wo_furikae month_day = month_day.split(",") holiday = kokuminHoliday( jDate(y, month_day[0]-1, month_day[1] ) ) if holiday? m = getJMonth(holiday) + 1 # 結果を登録 d = getJDate(holiday) kokuminHolidays.push([m,d]) for holiday in kokuminHolidays wo_furikae[holiday] = "国民の休日" # 振替休日を追加する w_furikae = {} for month_day, name of wo_furikae w_furikae[month_day] = name month_day = month_day.split(",") holiday = furikaeHoliday( jDate(y, month_day[0]-1, month_day[1] ) ) if holiday? m = getJMonth(holiday) + 1 # 結果を登録 d = getJDate(holiday) w_furikae[ [m,d] ] = "振替休日" holidays[true][y] = w_furikae # 結果を登録 return holidays[furikae][y] ### クラス定義 ### target = (module?.exports ? this.JapaneseHolidays={}) target.getHolidaysOf = (y, furikae) -> # データを整形する result = [] for month_day, name of getHolidaysOf(y, furikae) result.push( month : parseInt(month_day.split(",")[0]) date : parseInt(month_day.split(",")[1]) name : name ) # 日付順に並べ直す result.sort( (a,b)-> (a.month-b.month) or (a.date-b.date) ) result isHoliday = (date, furikae) -> getHolidaysOf(date.getFullYear(), furikae)[ [date.getMonth()+1, date.getDate()] ] isHolidayAt = (date, furikae) -> getHolidaysOf(getJFullYear(date), furikae)[ [getJMonth(date)+1, getJDate(date)] ] target.isHoliday = isHoliday target.isHolidayAt = isHolidayAt target.shiftDate = shiftDate target.u2j = u2j target.j2u = j2u target.jDate = jDate target.uDate = uDate target.getJDay = getJDay target.getJDate = getJDate target.getJMonth = getJMonth target.getJFullYear = getJFullYear target.getJHours = getJHours target.getJMinutes = getJMinutes target.__forTest = { shunbunWithTime: shunbunWithTime shubunWithTime: shubunWithTime }
true
### 日本の休日を JavaScript で計算するためのライブラリ PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### "use strict" # 元の時刻から指定時間だけずらした時刻を生成して返す shiftDate = (date, year, mon, day, hour, min, sec, msec) -> # まずは日付以下の部分を msec に直して処理する res = new Date(2000,0,1) res.setTime( date.getTime() + (((( day ? 0 ) * 24 + ( hour ? 0 )) * 60 + ( min ? 0 )) * 60 + ( sec ? 0 )) * 1000 + ( msec ? 0 ) ) # 年と月はちょっと面倒な処理になる res.setFullYear res.getFullYear() + ( year ? 0 ) + Math.floor( ( res.getMonth() + ( mon ? 0 ) ) / 12 ) res.setMonth ( ( res.getMonth() + ( mon ? 0 ) ) % 12 + 12 ) % 12 return res u2j = (d) -> shiftDate(d,0,0,0,+9) j2u = (d) -> shiftDate(d,0,0,0,-9) uDate = (y,m,d) -> new Date(Date.UTC(y,m,d)) jDate = (y,m,d) -> j2u uDate(y,m,d) getJDay = (d) -> (u2j d).getUTCDay() getJDate = (d) -> (u2j d).getUTCDate() getJMonth = (d) -> (u2j d).getUTCMonth() getJFullYear = (d) -> (u2j d).getUTCFullYear() getJHours = (d) -> (u2j d).getUTCHours() getJMinutes = (d) -> (u2j d).getUTCMinutes() ### ヘルパ関数 ### # 年を与えると指定の祝日を返す関数を作成 simpleHoliday = (month, day) -> (year) -> jDate(year, month-1, day) # 年を与えると指定の月の nth 月曜を返す関数を作成 happyMonday = (month, nth) -> (year) -> monday = 1 first = jDate(year, month-1, 1) shiftDate( first, 0, 0, ( 7 - ( getJDay(first) - monday ) ) % 7 + ( nth - 1 ) * 7 ) # 年を与えると春分の日を返す shunbunWithTime = (year) -> new Date(-655866700000 + 31556940400 * (year-1949) ) shunbun = (year) -> date = shunbunWithTime(year) jDate(year, getJMonth(date), getJDate(date)) # 年を与えると秋分の日を返す shubunWithTime = (year) -> if day = { 1603: 23, 2074: 23, 2355: 23, 2384: 22 }[year] jDate(year, 9-1, day) else new Date(-671316910000 + 31556910000 * (year-1948) ) shubun = (year) -> date = shubunWithTime(year) jDate(year, getJMonth(date), getJDate(date)) ### 休日定義 https://ja.wikipedia.org/wiki/%E5%9B%BD%E6%B0%91%E3%81%AE%E7%A5%9D%E6%97%A5 ### definition = [ [ "元日", simpleHoliday( 1, 1), 1949 ], [ "成人の日", simpleHoliday( 1, 15), 1949, 1999 ], [ "成人の日", happyMonday( 1, 2), 2000 ], [ "建国記念の日", simpleHoliday( 2, 11), 1967 ], [ "天皇誕生日", simpleHoliday( 2, 23), 2020 ], [ "昭和天皇の大喪の礼", simpleHoliday( 2, 24), 1989, 1989 ], [ "春分の日", shunbun, 1949 ], [ "皇太子明仁親王の結婚の儀", simpleHoliday( 4, 10), 1959, 1959 ], [ "天皇誕生日", simpleHoliday( 4, 29), 1949, 1988 ], [ "みどりの日", simpleHoliday( 4, 29), 1989, 2006 ], [ "昭和の日", simpleHoliday( 4, 29), 2007 ], [ "即位の日", simpleHoliday( 5, 1), 2019, 2019 ], [ "憲法記念日", simpleHoliday( 5, 3), 1949 ], [ "みどりの日", simpleHoliday( 5, 4), 2007 ], [ "こどもの日", simpleHoliday( 5, 5), 1949 ], [ "皇太子徳仁親王の結婚の儀", simpleHoliday( 6, 9), 1993, 1993 ], [ "海の日", simpleHoliday( 7, 20), 1996, 2002 ], [ "海の日", happyMonday( 7, 3), 2003, 2019 ], [ "海の日", simpleHoliday( 7, 23), 2020, 2020 ], [ "海の日", simpleHoliday( 7, 22), 2021, 2021 ], [ "海の日", happyMonday( 7, 3), 2022 ], [ "山の日", simpleHoliday( 8, 11), 2016, 2019 ], [ "山の日", simpleHoliday( 8, 10), 2020, 2020 ], [ "山の日", simpleHoliday( 8, 8), 2021, 2021 ], [ "山の日", simpleHoliday( 8, 11), 2022 ], [ "敬老の日", simpleHoliday( 9, 15), 1966, 2002 ], [ "敬老の日", happyMonday( 9, 3), 2003 ], [ "秋分の日", shubun, 1948 ], [ "体育の日", simpleHoliday(10, 10), 1966, 1999 ], [ "体育の日", happyMonday( 10, 2), 2000, 2019 ], [ "スポーツの日", simpleHoliday( 7, 24), 2020, 2020 ], [ "スポーツの日", simpleHoliday( 7, 23), 2021, 2021 ], [ "スポーツの日", happyMonday( 10, 2), 2022 ], [ "即位礼正殿の儀", simpleHoliday(10, 22), 2019, 2019 ], [ "文化の日", simpleHoliday(11, 3), 1948 ], [ "即位礼正殿の儀", simpleHoliday(11, 12), 1990, 1990 ], [ "勤労感謝の日", simpleHoliday(11, 23), 1948 ], [ "天皇誕生日", simpleHoliday(12, 23), 1989, 2018 ], ] # 休日を与えるとその振替休日を返す # 振り替え休日がなければ null を返す furikaeHoliday = (holiday) -> # 振替休日制度制定前 または 日曜日でない場合 振り替え無し sunday = 0 if holiday < jDate(1973, 4-1, 30-1) or getJDay(holiday) != sunday return null # 日曜日なので一日ずらす furikae = shiftDate(holiday, 0, 0, 1) # ずらした月曜日が休日でなければ振替休日 if !isHolidayAt(furikae, false) return furikae # 旧振り替え制度では1日以上ずらさない if holiday < jDate(2007, 1-1, 1) return null # たぶんこれに該当する日はないはず? loop # 振り替えた結果が休日だったら1日ずつずらす furikae = shiftDate(furikae, 0, 0, 1) if !isHolidayAt(furikae, false) return furikae # 休日を与えると、翌日が国民の休日かどうかを判定して、 # 国民の休日であればその日を返す kokuminHoliday = (holiday) -> if getJFullYear(holiday) < 1988 # 制定前 return null # 2日後が振り替え以外の祝日か if !isHolidayAt(shiftDate(holiday, 0, 0, 2), false) return null sunday = 0 monday = 1 kokumin = shiftDate(holiday, 0, 0, 1) if isHolidayAt(kokumin, false) or # 次の日が祝日 getJDay(kokumin)==sunday or # 次の日が日曜 getJDay(kokumin)==monday # 次の日が月曜(振替休日になる) return null return kokumin # 計算結果をキャッシュする # # holidays[furikae] = { # 1999: # "1,1": "元旦" # "1,15": "成人の日" # ... # } # holidays = { true: {}, false: {} } getHolidaysOf = (y, furikae) -> # キャッシュされていればそれを返す furikae = if !furikae? or furikae then true else false cache = holidays[furikae][y] return cache if cache? # されてなければ計算してキャッシュ # 振替休日を計算するには振替休日以外の休日が計算されて # いないとダメなので、先に計算する wo_furikae = {} for entry in definition continue if entry[2]? && y < entry[2] # 制定年以前 continue if entry[3]? && entry[3] < y # 廃止年以降 holiday = entry[1](y) # 休日を計算 continue unless holiday? # 無効であれば無視 m = getJMonth(holiday) + 1 # 結果を登録 d = getJDate(holiday) wo_furikae[ [m,d] ] = entry[0] holidays[false][y] = wo_furikae # 国民の休日を追加する kokuminHolidays = [] for month_day of wo_furikae month_day = month_day.split(",") holiday = kokuminHoliday( jDate(y, month_day[0]-1, month_day[1] ) ) if holiday? m = getJMonth(holiday) + 1 # 結果を登録 d = getJDate(holiday) kokuminHolidays.push([m,d]) for holiday in kokuminHolidays wo_furikae[holiday] = "国民の休日" # 振替休日を追加する w_furikae = {} for month_day, name of wo_furikae w_furikae[month_day] = name month_day = month_day.split(",") holiday = furikaeHoliday( jDate(y, month_day[0]-1, month_day[1] ) ) if holiday? m = getJMonth(holiday) + 1 # 結果を登録 d = getJDate(holiday) w_furikae[ [m,d] ] = "振替休日" holidays[true][y] = w_furikae # 結果を登録 return holidays[furikae][y] ### クラス定義 ### target = (module?.exports ? this.JapaneseHolidays={}) target.getHolidaysOf = (y, furikae) -> # データを整形する result = [] for month_day, name of getHolidaysOf(y, furikae) result.push( month : parseInt(month_day.split(",")[0]) date : parseInt(month_day.split(",")[1]) name : name ) # 日付順に並べ直す result.sort( (a,b)-> (a.month-b.month) or (a.date-b.date) ) result isHoliday = (date, furikae) -> getHolidaysOf(date.getFullYear(), furikae)[ [date.getMonth()+1, date.getDate()] ] isHolidayAt = (date, furikae) -> getHolidaysOf(getJFullYear(date), furikae)[ [getJMonth(date)+1, getJDate(date)] ] target.isHoliday = isHoliday target.isHolidayAt = isHolidayAt target.shiftDate = shiftDate target.u2j = u2j target.j2u = j2u target.jDate = jDate target.uDate = uDate target.getJDay = getJDay target.getJDate = getJDate target.getJMonth = getJMonth target.getJFullYear = getJFullYear target.getJHours = getJHours target.getJMinutes = getJMinutes target.__forTest = { shunbunWithTime: shunbunWithTime shubunWithTime: shubunWithTime }
[ { "context": "UBOT_GNTP_PASSWORD\n#\n# Commands:\n#\n#\n# Author:\n# Jimmy Xu <xjimmyshcn@gmail.com>\n#\n\nnodeGrowl = require 'no", "end": 355, "score": 0.9998395442962646, "start": 347, "tag": "NAME", "value": "Jimmy Xu" }, { "context": "ASSWORD\n#\n# Commands:\n#\n#\n# Author:\n...
example/schedule-monitor.coffee
Jimmy-Xu/hubot-another-weixin
0
# Description: # check class schedule, then notify via message via weixin(wechat) and growl # # Dependencies: # node-growl # # Configuration: # HUBOT_EXT_CMD_BIN # HUBOT_EXT_CMD_ARG # HUBOT_CHECK_INTERVAL # HUBOT_TARGET_NICKNAME # HUBOT_TARGET_REMARKNAME # HUBOT_GNTP_SERVER # HUBOT_GNTP_PASSWORD # # Commands: # # # Author: # Jimmy Xu <xjimmyshcn@gmail.com> # nodeGrowl = require 'node-growl' module.exports = (robot) -> #============================== # variable #============================== gntpOpts = server: process.env.HUBOT_GNTP_SERVER password: process.env.HUBOT_GNTP_PASSWORD appname: "schedule-monitor" cmdOpts = bin: process.env.HUBOT_EXT_CMD_BIN arg: process.env.HUBOT_EXT_CMD_ARG targetOpts = nickName: process.env.HUBOT_TARGET_NICKNAME remarkName: process.env.HUBOT_TARGET_REMARKNAME interval = if process.env.HUBOT_CHECK_INTERVAL then process.env.HUBOT_CHECK_INTERVAL else 15 targetUser = null scheduleResult = NotChanged: "课程无变化" Error: "程序错误" Changed: null #============================== # function #============================== run_cmd = (cmd, args, cb) -> console.debug "[schedule-monitor] spawn:", cmd, args spawn = require("child_process").spawn child = spawn(cmd, args) result = [] child.stdout.on "data", (buffer) -> result.push buffer.toString() child.stderr.on "data", (buffer) -> result.push buffer.toString() child.stdout.on "end", -> cb result check = (adapterName, sender) -> if adapterName isnt "another-weixin" # check adapter robot.logger.info "[WARN] adapter should be another-weixin, but current is #{adapterName}, ignore" false # find target user if not targetUser targetUsers = robot.adapter.wxbot.getContactByName(targetOpts.remarkName, targetOpts.nickName) if targetUsers.length isnt 1 robot.logger.info "[WARN] target user must be unique: #{targetUsers.length}), ignore" false targetUser = targetUsers[0] robot.logger.info "found target user: #{targetUser.UserName}, #{targetUser.NickName}" # check sender sendNickName = robot.adapter.wxbot.getContactName sender if not sendNickName robot.logger.info "[WARN] sender(#{sender}) not found, ignore" false robot.logger.info "found send user: #{sendNickName} - (#{sender})" if sender not in [ targetUser.UserName, robot.adapter.wxbot.myUserName ] robot.logger.info "[WARN] sender isn't valid, ignore" false true setTimer = (_interval) -> if _interval is 0 # find target user targetUsers = robot.adapter.wxbot.getContactByName(targetOpts.remarkName, targetOpts.nickName) if targetUsers.length isnt 1 robot.logger.info "[WARN] target user must unique: #{targetUsers.length}), ignore" false targetUser = targetUsers[0] robot.logger.info "found target user: #{targetUser.UserName}, #{targetUser.NickName}" msgContent="#{robot.name}: 开始监控课表" robot.adapter.wxbot.api.sendMessage robot.adapter.wxbot.myUserName, targetUser.UserName, msgContent, (rlt) -> robot.logger.info "start message had been sent to #{targetUser.NickName}: #{rlt.statusMessage}(#{rlt.statusCode})" setTimeout doFetch, _interval * 60 * 1000, ((e, result) -> if e robot.logger.info "[doFetch] result: #{e}" else msgTitle = "schedule fetched" msgContent = "#{robot.name}: #{result}" robot.logger.info "msgTitle: #{msgTitle} msgContent: #{msgContent}" # notify via wechat if targetUser.UserName robot.adapter.wxbot.api.sendMessage robot.adapter.wxbot.myUserName, targetUser.UserName, msgContent, (rlt) -> robot.logger.info "result had been sent to #{targetUser.NickName}: #{rlt.statusMessage}(#{rlt.statusCode})" else robot.logger.info "[WARN] skip to send message to wechat" if gntpOpts.server # notify via gntp-send robot.logger.info "title: #{msgTitle} message: #{msgContent} gntpOpts: #{gntpOpts}" nodeGrowl msgTitle, msgContent, gntpOpts, (text) -> robot.logger.info "gntp result: #{text}" else robot.logger.info "[WARN] skip to send message to growl" ), (() -> robot.logger.info "result had been sent, check again after #{interval} minutes" setTimer interval ) doFetch = (callback, onFinish) -> robot.logger.info "Check it!" run_cmd cmdOpts.bin, cmdOpts.arg.split(" "), (result) -> robot.logger.info "[run_cmd] result: #{result}" result = result.join("") if not result callback scheduleResult.NotChanged, "" else callback scheduleResult.Changed, result if onFinish onFinish() #============================== # main #============================== # start monitor task setTimer 0 robot.respond /ping/i, (resp) -> valid = check robot.adapterName, resp.message.user.name if not valid return robot.logger.info "[ping] pass check" result = "#{robot.name}: pong" # send to growl _msgTitle = "sender:#{resp.message.user.name} - ping" nodeGrowl _msgTitle, result, gntpOpts, (text) -> if text isnt null robot.logger.info ">[sender:#{resp.message.user.name}] gntp-send failed(#{text})" robot.logger.info ">gntp-send OK" # send to wechat if robot.adapter.wxbot.myUserName is resp.message.user.name robot.adapter.wxbot.api.sendMessage robot.adapter.wxbot.myUserName, "filehelper", result, (rlt) -> robot.logger.info "send to filehelper: #{rlt.statusMessage}(#{rlt.statusCode})" else robot.logger.info "reply to sender #{resp.message.user.name}" resp.reply result robot.respond /课表/i, (resp) -> valid = check robot.adapterName, resp.message.user.name if not valid return robot.logger.info "[课表] pass check" #fetch schedule run_cmd cmdOpts.bin, cmdOpts.arg.split(" "), (result) -> robot.logger.info "result:#{result}" result = result.join("") if not result result = "课表无变更" # send to growl _msgTitle = "sender:#{resp.message.user.name} - 课表" result = "#{robot.name}: #{result}" nodeGrowl _msgTitle, result, gntpOpts, (text) -> if text isnt null robot.logger.info ">[sender:#{resp.message.user.name}] gntp-send failed(#{text})" robot.logger.info ">gntp-send OK" # send to wechat if robot.adapter.wxbot.myUserName is resp.message.user.name robot.adapter.wxbot.api.sendMessage robot.adapter.wxbot.myUserName, "filehelper", result, (rlt) -> robot.logger.info "send to filehelper: #{rlt.statusMessage}(#{rlt.statusCode})" else robot.logger.info "reply to sender #{resp.message.user.name}" resp.reply result # robot.listen( # (msg) -> # if not msg # robot.logger.info "[WARN] msg is empty" # return false # valid = check robot.adapterName, resp.message.user.name # robot.logger.info "[listen:msg] hubot adapter is #{robot.adapterName}, receive msg:#{msg} - valid:#{valid}" # return valid # (resp) -> # robot.logger.info "[listen:resp] sender:#{resp.message.user.name} message:#{resp.message.text}" # ) robot.catchAll (resp) -> if not resp.message.text return robot.logger.info "[WARN] not catched message: sender:#{resp.message.user.name} message:#{resp.message.text}" valid = check robot.adapterName, resp.message.user.name if not valid return robot.logger.info "[catchAll] pass check"
169499
# Description: # check class schedule, then notify via message via weixin(wechat) and growl # # Dependencies: # node-growl # # Configuration: # HUBOT_EXT_CMD_BIN # HUBOT_EXT_CMD_ARG # HUBOT_CHECK_INTERVAL # HUBOT_TARGET_NICKNAME # HUBOT_TARGET_REMARKNAME # HUBOT_GNTP_SERVER # HUBOT_GNTP_PASSWORD # # Commands: # # # Author: # <NAME> <<EMAIL>> # nodeGrowl = require 'node-growl' module.exports = (robot) -> #============================== # variable #============================== gntpOpts = server: process.env.HUBOT_GNTP_SERVER password: <PASSWORD> appname: "schedule-monitor" cmdOpts = bin: process.env.HUBOT_EXT_CMD_BIN arg: process.env.HUBOT_EXT_CMD_ARG targetOpts = nickName: process.env.HUBOT_TARGET_NICKNAME remarkName: process.env.HUBOT_TARGET_REMARKNAME interval = if process.env.HUBOT_CHECK_INTERVAL then process.env.HUBOT_CHECK_INTERVAL else 15 targetUser = null scheduleResult = NotChanged: "课程无变化" Error: "程序错误" Changed: null #============================== # function #============================== run_cmd = (cmd, args, cb) -> console.debug "[schedule-monitor] spawn:", cmd, args spawn = require("child_process").spawn child = spawn(cmd, args) result = [] child.stdout.on "data", (buffer) -> result.push buffer.toString() child.stderr.on "data", (buffer) -> result.push buffer.toString() child.stdout.on "end", -> cb result check = (adapterName, sender) -> if adapterName isnt "another-weixin" # check adapter robot.logger.info "[WARN] adapter should be another-weixin, but current is #{adapterName}, ignore" false # find target user if not targetUser targetUsers = robot.adapter.wxbot.getContactByName(targetOpts.remarkName, targetOpts.nickName) if targetUsers.length isnt 1 robot.logger.info "[WARN] target user must be unique: #{targetUsers.length}), ignore" false targetUser = targetUsers[0] robot.logger.info "found target user: #{targetUser.UserName}, #{targetUser.NickName}" # check sender sendNickName = robot.adapter.wxbot.getContactName sender if not sendNickName robot.logger.info "[WARN] sender(#{sender}) not found, ignore" false robot.logger.info "found send user: #{sendNickName} - (#{sender})" if sender not in [ targetUser.UserName, robot.adapter.wxbot.myUserName ] robot.logger.info "[WARN] sender isn't valid, ignore" false true setTimer = (_interval) -> if _interval is 0 # find target user targetUsers = robot.adapter.wxbot.getContactByName(targetOpts.remarkName, targetOpts.nickName) if targetUsers.length isnt 1 robot.logger.info "[WARN] target user must unique: #{targetUsers.length}), ignore" false targetUser = targetUsers[0] robot.logger.info "found target user: #{targetUser.UserName}, #{targetUser.NickName}" msgContent="#{robot.name}: 开始监控课表" robot.adapter.wxbot.api.sendMessage robot.adapter.wxbot.myUserName, targetUser.UserName, msgContent, (rlt) -> robot.logger.info "start message had been sent to #{targetUser.NickName}: #{rlt.statusMessage}(#{rlt.statusCode})" setTimeout doFetch, _interval * 60 * 1000, ((e, result) -> if e robot.logger.info "[doFetch] result: #{e}" else msgTitle = "schedule fetched" msgContent = "#{robot.name}: #{result}" robot.logger.info "msgTitle: #{msgTitle} msgContent: #{msgContent}" # notify via wechat if targetUser.UserName robot.adapter.wxbot.api.sendMessage robot.adapter.wxbot.myUserName, targetUser.UserName, msgContent, (rlt) -> robot.logger.info "result had been sent to #{targetUser.NickName}: #{rlt.statusMessage}(#{rlt.statusCode})" else robot.logger.info "[WARN] skip to send message to wechat" if gntpOpts.server # notify via gntp-send robot.logger.info "title: #{msgTitle} message: #{msgContent} gntpOpts: #{gntpOpts}" nodeGrowl msgTitle, msgContent, gntpOpts, (text) -> robot.logger.info "gntp result: #{text}" else robot.logger.info "[WARN] skip to send message to growl" ), (() -> robot.logger.info "result had been sent, check again after #{interval} minutes" setTimer interval ) doFetch = (callback, onFinish) -> robot.logger.info "Check it!" run_cmd cmdOpts.bin, cmdOpts.arg.split(" "), (result) -> robot.logger.info "[run_cmd] result: #{result}" result = result.join("") if not result callback scheduleResult.NotChanged, "" else callback scheduleResult.Changed, result if onFinish onFinish() #============================== # main #============================== # start monitor task setTimer 0 robot.respond /ping/i, (resp) -> valid = check robot.adapterName, resp.message.user.name if not valid return robot.logger.info "[ping] pass check" result = "#{robot.name}: pong" # send to growl _msgTitle = "sender:#{resp.message.user.name} - ping" nodeGrowl _msgTitle, result, gntpOpts, (text) -> if text isnt null robot.logger.info ">[sender:#{resp.message.user.name}] gntp-send failed(#{text})" robot.logger.info ">gntp-send OK" # send to wechat if robot.adapter.wxbot.myUserName is resp.message.user.name robot.adapter.wxbot.api.sendMessage robot.adapter.wxbot.myUserName, "filehelper", result, (rlt) -> robot.logger.info "send to filehelper: #{rlt.statusMessage}(#{rlt.statusCode})" else robot.logger.info "reply to sender #{resp.message.user.name}" resp.reply result robot.respond /课表/i, (resp) -> valid = check robot.adapterName, resp.message.user.name if not valid return robot.logger.info "[课表] pass check" #fetch schedule run_cmd cmdOpts.bin, cmdOpts.arg.split(" "), (result) -> robot.logger.info "result:#{result}" result = result.join("") if not result result = "课表无变更" # send to growl _msgTitle = "sender:#{resp.message.user.name} - 课表" result = "#{robot.name}: #{result}" nodeGrowl _msgTitle, result, gntpOpts, (text) -> if text isnt null robot.logger.info ">[sender:#{resp.message.user.name}] gntp-send failed(#{text})" robot.logger.info ">gntp-send OK" # send to wechat if robot.adapter.wxbot.myUserName is resp.message.user.name robot.adapter.wxbot.api.sendMessage robot.adapter.wxbot.myUserName, "filehelper", result, (rlt) -> robot.logger.info "send to filehelper: #{rlt.statusMessage}(#{rlt.statusCode})" else robot.logger.info "reply to sender #{resp.message.user.name}" resp.reply result # robot.listen( # (msg) -> # if not msg # robot.logger.info "[WARN] msg is empty" # return false # valid = check robot.adapterName, resp.message.user.name # robot.logger.info "[listen:msg] hubot adapter is #{robot.adapterName}, receive msg:#{msg} - valid:#{valid}" # return valid # (resp) -> # robot.logger.info "[listen:resp] sender:#{resp.message.user.name} message:#{resp.message.text}" # ) robot.catchAll (resp) -> if not resp.message.text return robot.logger.info "[WARN] not catched message: sender:#{resp.message.user.name} message:#{resp.message.text}" valid = check robot.adapterName, resp.message.user.name if not valid return robot.logger.info "[catchAll] pass check"
true
# Description: # check class schedule, then notify via message via weixin(wechat) and growl # # Dependencies: # node-growl # # Configuration: # HUBOT_EXT_CMD_BIN # HUBOT_EXT_CMD_ARG # HUBOT_CHECK_INTERVAL # HUBOT_TARGET_NICKNAME # HUBOT_TARGET_REMARKNAME # HUBOT_GNTP_SERVER # HUBOT_GNTP_PASSWORD # # Commands: # # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # nodeGrowl = require 'node-growl' module.exports = (robot) -> #============================== # variable #============================== gntpOpts = server: process.env.HUBOT_GNTP_SERVER password: PI:PASSWORD:<PASSWORD>END_PI appname: "schedule-monitor" cmdOpts = bin: process.env.HUBOT_EXT_CMD_BIN arg: process.env.HUBOT_EXT_CMD_ARG targetOpts = nickName: process.env.HUBOT_TARGET_NICKNAME remarkName: process.env.HUBOT_TARGET_REMARKNAME interval = if process.env.HUBOT_CHECK_INTERVAL then process.env.HUBOT_CHECK_INTERVAL else 15 targetUser = null scheduleResult = NotChanged: "课程无变化" Error: "程序错误" Changed: null #============================== # function #============================== run_cmd = (cmd, args, cb) -> console.debug "[schedule-monitor] spawn:", cmd, args spawn = require("child_process").spawn child = spawn(cmd, args) result = [] child.stdout.on "data", (buffer) -> result.push buffer.toString() child.stderr.on "data", (buffer) -> result.push buffer.toString() child.stdout.on "end", -> cb result check = (adapterName, sender) -> if adapterName isnt "another-weixin" # check adapter robot.logger.info "[WARN] adapter should be another-weixin, but current is #{adapterName}, ignore" false # find target user if not targetUser targetUsers = robot.adapter.wxbot.getContactByName(targetOpts.remarkName, targetOpts.nickName) if targetUsers.length isnt 1 robot.logger.info "[WARN] target user must be unique: #{targetUsers.length}), ignore" false targetUser = targetUsers[0] robot.logger.info "found target user: #{targetUser.UserName}, #{targetUser.NickName}" # check sender sendNickName = robot.adapter.wxbot.getContactName sender if not sendNickName robot.logger.info "[WARN] sender(#{sender}) not found, ignore" false robot.logger.info "found send user: #{sendNickName} - (#{sender})" if sender not in [ targetUser.UserName, robot.adapter.wxbot.myUserName ] robot.logger.info "[WARN] sender isn't valid, ignore" false true setTimer = (_interval) -> if _interval is 0 # find target user targetUsers = robot.adapter.wxbot.getContactByName(targetOpts.remarkName, targetOpts.nickName) if targetUsers.length isnt 1 robot.logger.info "[WARN] target user must unique: #{targetUsers.length}), ignore" false targetUser = targetUsers[0] robot.logger.info "found target user: #{targetUser.UserName}, #{targetUser.NickName}" msgContent="#{robot.name}: 开始监控课表" robot.adapter.wxbot.api.sendMessage robot.adapter.wxbot.myUserName, targetUser.UserName, msgContent, (rlt) -> robot.logger.info "start message had been sent to #{targetUser.NickName}: #{rlt.statusMessage}(#{rlt.statusCode})" setTimeout doFetch, _interval * 60 * 1000, ((e, result) -> if e robot.logger.info "[doFetch] result: #{e}" else msgTitle = "schedule fetched" msgContent = "#{robot.name}: #{result}" robot.logger.info "msgTitle: #{msgTitle} msgContent: #{msgContent}" # notify via wechat if targetUser.UserName robot.adapter.wxbot.api.sendMessage robot.adapter.wxbot.myUserName, targetUser.UserName, msgContent, (rlt) -> robot.logger.info "result had been sent to #{targetUser.NickName}: #{rlt.statusMessage}(#{rlt.statusCode})" else robot.logger.info "[WARN] skip to send message to wechat" if gntpOpts.server # notify via gntp-send robot.logger.info "title: #{msgTitle} message: #{msgContent} gntpOpts: #{gntpOpts}" nodeGrowl msgTitle, msgContent, gntpOpts, (text) -> robot.logger.info "gntp result: #{text}" else robot.logger.info "[WARN] skip to send message to growl" ), (() -> robot.logger.info "result had been sent, check again after #{interval} minutes" setTimer interval ) doFetch = (callback, onFinish) -> robot.logger.info "Check it!" run_cmd cmdOpts.bin, cmdOpts.arg.split(" "), (result) -> robot.logger.info "[run_cmd] result: #{result}" result = result.join("") if not result callback scheduleResult.NotChanged, "" else callback scheduleResult.Changed, result if onFinish onFinish() #============================== # main #============================== # start monitor task setTimer 0 robot.respond /ping/i, (resp) -> valid = check robot.adapterName, resp.message.user.name if not valid return robot.logger.info "[ping] pass check" result = "#{robot.name}: pong" # send to growl _msgTitle = "sender:#{resp.message.user.name} - ping" nodeGrowl _msgTitle, result, gntpOpts, (text) -> if text isnt null robot.logger.info ">[sender:#{resp.message.user.name}] gntp-send failed(#{text})" robot.logger.info ">gntp-send OK" # send to wechat if robot.adapter.wxbot.myUserName is resp.message.user.name robot.adapter.wxbot.api.sendMessage robot.adapter.wxbot.myUserName, "filehelper", result, (rlt) -> robot.logger.info "send to filehelper: #{rlt.statusMessage}(#{rlt.statusCode})" else robot.logger.info "reply to sender #{resp.message.user.name}" resp.reply result robot.respond /课表/i, (resp) -> valid = check robot.adapterName, resp.message.user.name if not valid return robot.logger.info "[课表] pass check" #fetch schedule run_cmd cmdOpts.bin, cmdOpts.arg.split(" "), (result) -> robot.logger.info "result:#{result}" result = result.join("") if not result result = "课表无变更" # send to growl _msgTitle = "sender:#{resp.message.user.name} - 课表" result = "#{robot.name}: #{result}" nodeGrowl _msgTitle, result, gntpOpts, (text) -> if text isnt null robot.logger.info ">[sender:#{resp.message.user.name}] gntp-send failed(#{text})" robot.logger.info ">gntp-send OK" # send to wechat if robot.adapter.wxbot.myUserName is resp.message.user.name robot.adapter.wxbot.api.sendMessage robot.adapter.wxbot.myUserName, "filehelper", result, (rlt) -> robot.logger.info "send to filehelper: #{rlt.statusMessage}(#{rlt.statusCode})" else robot.logger.info "reply to sender #{resp.message.user.name}" resp.reply result # robot.listen( # (msg) -> # if not msg # robot.logger.info "[WARN] msg is empty" # return false # valid = check robot.adapterName, resp.message.user.name # robot.logger.info "[listen:msg] hubot adapter is #{robot.adapterName}, receive msg:#{msg} - valid:#{valid}" # return valid # (resp) -> # robot.logger.info "[listen:resp] sender:#{resp.message.user.name} message:#{resp.message.text}" # ) robot.catchAll (resp) -> if not resp.message.text return robot.logger.info "[WARN] not catched message: sender:#{resp.message.user.name} message:#{resp.message.text}" valid = check robot.adapterName, resp.message.user.name if not valid return robot.logger.info "[catchAll] pass check"
[ { "context": "Model[0]][unparsedModel[1]].url\n data.name = name\n data.thumb = scope[unparsedModel[0]].thumb.", "end": 761, "score": 0.9520342350006104, "start": 757, "tag": "NAME", "value": "name" } ]
lib/assets/javascripts/directives/ngupload.js.coffee
transcon/raingular
0
selectFile = (scope,event,attributes,file) -> model = attributes.ngModel.split('.') id = scope[attributes.ngModel.split('.')[0]].id parent = null if attributes.ngContext parent = attributes.ngContext scope.uploadFiles(model,id,file,parent) event.preventDefault() fileData = (scope,attributes) -> data = {} unparsedModel = attributes.ngModel.split('.') if scope[unparsedModel[0]] if scope[unparsedModel[0]][unparsedModel[1]] unparsed = scope[unparsedModel[0]][unparsedModel[1]].location.split('/') name = unparsed.pop() id = unparsed.pop() mounted_as = unparsed.pop() model = unparsed.pop() data.path = scope[unparsedModel[0]][unparsedModel[1]].url data.name = name data.thumb = scope[unparsedModel[0]].thumb.url if scope[unparsedModel[0]].thumb return data uploadFiles = (scope,element,model,id,file,parent,timeout) -> scope.progress = 0 element.addClass('covered') route = eval('Routes.' + element[0].attributes['ng-model'].value.split('.')[0] + '_path')(id: id) + '.json' formData = new FormData() formData.append model[0] + '[id]', id formData.append model[0] + '[' + model[1] + ']', file formData.append model[0] + '[' + parent + '_id]', $scope[parent].id if parent xhr = new XMLHttpRequest() xhr.upload.addEventListener "progress", (event) -> if event.lengthComputable scope.$apply -> scope.progress = Math.round(event.loaded * 100 / event.total) , false xhr.addEventListener "readystatechange", (event) -> if this.readyState == 4 && !(this.status > 399) data = JSON.parse(event.target.response) scope.$apply -> scope[model[0]][model[1]] = data[model[1]] scope[model[0]].thumb = data.thumb scope.progress = 100 element.removeClass('covered') else if this.readyState == 4 && this.status > 399 failed() , false xhr.addEventListener "error", (event) -> failed() , false failed = -> element.addClass('failed') timeout -> element.removeClass('failed') element.removeClass('covered') , 2000 xhr.open("PUT", route) xhr.setRequestHeader('X-CSRF-Token', $('meta[name=csrf-token]').attr('content')) xhr.send(formData) angular.module('NgUpload', []) .directive 'ngDropFile', -> restrict: 'A' require: 'ngModel' link: (scope, element, attributes) -> element.bind 'drop', (event) -> file = event.originalEvent.dataTransfer.files[0] selectFile(scope,event,attributes,file) scope.file = -> fileData(scope,attributes) controller: ($scope, $element, $http, $timeout) -> $scope.uploadFiles = (model,id,file,parent) -> uploadFiles($scope,$element,model,id,file,parent,$timeout) $scope.progress = 0 $scope.uploadProgress = -> return $scope.progress .directive 'ngUpload', -> restrict: 'E' replace: true, require: 'ngModel', templateUrl: 'upload.html' link: (scope, element, attributes) -> element.children('img').bind 'click', (event) -> this.parentElement.getElementsByTagName('input')[0].click() element.children('.button').bind 'click', (event) -> this.parentElement.getElementsByTagName('input')[0].click() element.children('input').bind 'click', (event) -> event.stopPropagation() element.children('input').bind 'change', (event) -> file = event.target.files[0] selectFile(scope,event,attributes,file) scope.file = -> fileData(scope,attributes) scope.accept = -> return attributes.accept if attributes.accept return '*' controller: ($scope, $element, $http, $timeout) -> $scope.show = (type) -> options = $element[0].attributes['ng-options'].value.replace('{','').replace('}','').split(',') for option in options if option.indexOf(type) > -1 return true if option.indexOf('true') > -1 return false $scope.uploadFiles = (model,id,file,parent) -> uploadFiles($scope,$element,model,id,file,parent,$timeout)
161192
selectFile = (scope,event,attributes,file) -> model = attributes.ngModel.split('.') id = scope[attributes.ngModel.split('.')[0]].id parent = null if attributes.ngContext parent = attributes.ngContext scope.uploadFiles(model,id,file,parent) event.preventDefault() fileData = (scope,attributes) -> data = {} unparsedModel = attributes.ngModel.split('.') if scope[unparsedModel[0]] if scope[unparsedModel[0]][unparsedModel[1]] unparsed = scope[unparsedModel[0]][unparsedModel[1]].location.split('/') name = unparsed.pop() id = unparsed.pop() mounted_as = unparsed.pop() model = unparsed.pop() data.path = scope[unparsedModel[0]][unparsedModel[1]].url data.name = <NAME> data.thumb = scope[unparsedModel[0]].thumb.url if scope[unparsedModel[0]].thumb return data uploadFiles = (scope,element,model,id,file,parent,timeout) -> scope.progress = 0 element.addClass('covered') route = eval('Routes.' + element[0].attributes['ng-model'].value.split('.')[0] + '_path')(id: id) + '.json' formData = new FormData() formData.append model[0] + '[id]', id formData.append model[0] + '[' + model[1] + ']', file formData.append model[0] + '[' + parent + '_id]', $scope[parent].id if parent xhr = new XMLHttpRequest() xhr.upload.addEventListener "progress", (event) -> if event.lengthComputable scope.$apply -> scope.progress = Math.round(event.loaded * 100 / event.total) , false xhr.addEventListener "readystatechange", (event) -> if this.readyState == 4 && !(this.status > 399) data = JSON.parse(event.target.response) scope.$apply -> scope[model[0]][model[1]] = data[model[1]] scope[model[0]].thumb = data.thumb scope.progress = 100 element.removeClass('covered') else if this.readyState == 4 && this.status > 399 failed() , false xhr.addEventListener "error", (event) -> failed() , false failed = -> element.addClass('failed') timeout -> element.removeClass('failed') element.removeClass('covered') , 2000 xhr.open("PUT", route) xhr.setRequestHeader('X-CSRF-Token', $('meta[name=csrf-token]').attr('content')) xhr.send(formData) angular.module('NgUpload', []) .directive 'ngDropFile', -> restrict: 'A' require: 'ngModel' link: (scope, element, attributes) -> element.bind 'drop', (event) -> file = event.originalEvent.dataTransfer.files[0] selectFile(scope,event,attributes,file) scope.file = -> fileData(scope,attributes) controller: ($scope, $element, $http, $timeout) -> $scope.uploadFiles = (model,id,file,parent) -> uploadFiles($scope,$element,model,id,file,parent,$timeout) $scope.progress = 0 $scope.uploadProgress = -> return $scope.progress .directive 'ngUpload', -> restrict: 'E' replace: true, require: 'ngModel', templateUrl: 'upload.html' link: (scope, element, attributes) -> element.children('img').bind 'click', (event) -> this.parentElement.getElementsByTagName('input')[0].click() element.children('.button').bind 'click', (event) -> this.parentElement.getElementsByTagName('input')[0].click() element.children('input').bind 'click', (event) -> event.stopPropagation() element.children('input').bind 'change', (event) -> file = event.target.files[0] selectFile(scope,event,attributes,file) scope.file = -> fileData(scope,attributes) scope.accept = -> return attributes.accept if attributes.accept return '*' controller: ($scope, $element, $http, $timeout) -> $scope.show = (type) -> options = $element[0].attributes['ng-options'].value.replace('{','').replace('}','').split(',') for option in options if option.indexOf(type) > -1 return true if option.indexOf('true') > -1 return false $scope.uploadFiles = (model,id,file,parent) -> uploadFiles($scope,$element,model,id,file,parent,$timeout)
true
selectFile = (scope,event,attributes,file) -> model = attributes.ngModel.split('.') id = scope[attributes.ngModel.split('.')[0]].id parent = null if attributes.ngContext parent = attributes.ngContext scope.uploadFiles(model,id,file,parent) event.preventDefault() fileData = (scope,attributes) -> data = {} unparsedModel = attributes.ngModel.split('.') if scope[unparsedModel[0]] if scope[unparsedModel[0]][unparsedModel[1]] unparsed = scope[unparsedModel[0]][unparsedModel[1]].location.split('/') name = unparsed.pop() id = unparsed.pop() mounted_as = unparsed.pop() model = unparsed.pop() data.path = scope[unparsedModel[0]][unparsedModel[1]].url data.name = PI:NAME:<NAME>END_PI data.thumb = scope[unparsedModel[0]].thumb.url if scope[unparsedModel[0]].thumb return data uploadFiles = (scope,element,model,id,file,parent,timeout) -> scope.progress = 0 element.addClass('covered') route = eval('Routes.' + element[0].attributes['ng-model'].value.split('.')[0] + '_path')(id: id) + '.json' formData = new FormData() formData.append model[0] + '[id]', id formData.append model[0] + '[' + model[1] + ']', file formData.append model[0] + '[' + parent + '_id]', $scope[parent].id if parent xhr = new XMLHttpRequest() xhr.upload.addEventListener "progress", (event) -> if event.lengthComputable scope.$apply -> scope.progress = Math.round(event.loaded * 100 / event.total) , false xhr.addEventListener "readystatechange", (event) -> if this.readyState == 4 && !(this.status > 399) data = JSON.parse(event.target.response) scope.$apply -> scope[model[0]][model[1]] = data[model[1]] scope[model[0]].thumb = data.thumb scope.progress = 100 element.removeClass('covered') else if this.readyState == 4 && this.status > 399 failed() , false xhr.addEventListener "error", (event) -> failed() , false failed = -> element.addClass('failed') timeout -> element.removeClass('failed') element.removeClass('covered') , 2000 xhr.open("PUT", route) xhr.setRequestHeader('X-CSRF-Token', $('meta[name=csrf-token]').attr('content')) xhr.send(formData) angular.module('NgUpload', []) .directive 'ngDropFile', -> restrict: 'A' require: 'ngModel' link: (scope, element, attributes) -> element.bind 'drop', (event) -> file = event.originalEvent.dataTransfer.files[0] selectFile(scope,event,attributes,file) scope.file = -> fileData(scope,attributes) controller: ($scope, $element, $http, $timeout) -> $scope.uploadFiles = (model,id,file,parent) -> uploadFiles($scope,$element,model,id,file,parent,$timeout) $scope.progress = 0 $scope.uploadProgress = -> return $scope.progress .directive 'ngUpload', -> restrict: 'E' replace: true, require: 'ngModel', templateUrl: 'upload.html' link: (scope, element, attributes) -> element.children('img').bind 'click', (event) -> this.parentElement.getElementsByTagName('input')[0].click() element.children('.button').bind 'click', (event) -> this.parentElement.getElementsByTagName('input')[0].click() element.children('input').bind 'click', (event) -> event.stopPropagation() element.children('input').bind 'change', (event) -> file = event.target.files[0] selectFile(scope,event,attributes,file) scope.file = -> fileData(scope,attributes) scope.accept = -> return attributes.accept if attributes.accept return '*' controller: ($scope, $element, $http, $timeout) -> $scope.show = (type) -> options = $element[0].attributes['ng-options'].value.replace('{','').replace('}','').split(',') for option in options if option.indexOf(type) > -1 return true if option.indexOf('true') > -1 return false $scope.uploadFiles = (model,id,file,parent) -> uploadFiles($scope,$element,model,id,file,parent,$timeout)
[ { "context": "ApplicationController\n # @params 'email', 'firstName', 'lastName'\n #\n # @return [Object]\n par", "end": 881, "score": 0.990151584148407, "start": 872, "tag": "NAME", "value": "firstName" }, { "context": "ntroller\n # @params 'email', 'firstName...
node_modules/tower/packages/tower-controller/shared/params.coffee
MagicPower2/Power
1
_ = Tower._ # @mixin Tower.ControllerParams = ClassMethods: # Define a parameter that should be parsed into cursor for a model query. # # @example # class App.UsersController extends App.ApplicationController # @param 'email' # # @param [String] key # @param [Object] options # @option options [String] type # # @return [Tower.NetParam] param: (key, options = {}) -> options.resourceType = @metadata().resourceType @params()[key] = Tower.NetParam.create(key, options) # Return all params, or define multiple params at once. # # @example Pass in an object # class App.UsersController extends App.ApplicationController # @params email: 'String' # # @example Pass in strings # class App.UsersController extends App.ApplicationController # @params 'email', 'firstName', 'lastName' # # @return [Object] params: -> if arguments.length for arg in arguments if typeof arg == 'object' @param(key, value) for key, value of arg else @param(arg) @metadata().params # @todo refactor _buildCursorFromGet: (params, cursor) -> parsers = @params() for name, parser of parsers if params.hasOwnProperty(name) if name == 'sort' cursor.order(parser.parse(params[name])) else if name == 'fields' fields = _.select(_.flatten(parser.parse(params[name])), (i) -> i.value ) fields = _.flatten _.map fields, (i) -> i.value cursor.select(fields) else if name == 'limit' cursor.limit(parser.extractValue(params[name])) else if name == 'page' cursor.page(parser.extractValue(params[name])) else if typeof params[name] == 'string' # @todo this shouldn't have to necessarily build a cursor, maybe there's a lighter way. cursor.where(parser.toCursor(params[name])) else object = {} object[name] = params[name] cursor.where(object) cursor # Compile the params defined for this controller into a cursor for querying the database. # # @note The cursor is memoized. # # @return [Tower.ModelCursor] cursor: -> return @_cursor if @_cursor cursor = Tower.ModelCursor.create() cursor.make() if @params.conditions # @request.method.toUpperCase() == 'POST' @_cursor = @_buildCursorFromPost(cursor) else @_cursor = @_buildCursorFromGet(cursor) @_cursor _buildCursorFromPost: (cursor) -> parsers = @constructor.params() params = @params conditions = @params.conditions page = @params.page limit = @params.limit sort = @params.sort # @todo cleanConditions = (hash) -> for key, value of hash if key == '$or' || key == '$nor' cleanConditions(item) for item in value else # @todo make more robust # You should only be able to query the id when # it is: # - included in a route (e.g. nested routes, userId, etc.), # - defined by `belongsTo` on the controller # - defined by `param` on the controller delete hash[key] unless parsers.hasOwnProperty(key) || key.match(/id$/i) hash conditions = cleanConditions(conditions) cursor.where(conditions) cursor.order(sort) if sort && sort.length cursor.limit(limit) if limit cursor.page(page) if page cursor _buildCursorFromGet: (cursor) -> @constructor._buildCursorFromGet(@get('params'), cursor)
57877
_ = Tower._ # @mixin Tower.ControllerParams = ClassMethods: # Define a parameter that should be parsed into cursor for a model query. # # @example # class App.UsersController extends App.ApplicationController # @param 'email' # # @param [String] key # @param [Object] options # @option options [String] type # # @return [Tower.NetParam] param: (key, options = {}) -> options.resourceType = @metadata().resourceType @params()[key] = Tower.NetParam.create(key, options) # Return all params, or define multiple params at once. # # @example Pass in an object # class App.UsersController extends App.ApplicationController # @params email: 'String' # # @example Pass in strings # class App.UsersController extends App.ApplicationController # @params 'email', '<NAME>', '<NAME>' # # @return [Object] params: -> if arguments.length for arg in arguments if typeof arg == 'object' @param(key, value) for key, value of arg else @param(arg) @metadata().params # @todo refactor _buildCursorFromGet: (params, cursor) -> parsers = @params() for name, parser of parsers if params.hasOwnProperty(name) if name == 'sort' cursor.order(parser.parse(params[name])) else if name == 'fields' fields = _.select(_.flatten(parser.parse(params[name])), (i) -> i.value ) fields = _.flatten _.map fields, (i) -> i.value cursor.select(fields) else if name == 'limit' cursor.limit(parser.extractValue(params[name])) else if name == 'page' cursor.page(parser.extractValue(params[name])) else if typeof params[name] == 'string' # @todo this shouldn't have to necessarily build a cursor, maybe there's a lighter way. cursor.where(parser.toCursor(params[name])) else object = {} object[name] = params[name] cursor.where(object) cursor # Compile the params defined for this controller into a cursor for querying the database. # # @note The cursor is memoized. # # @return [Tower.ModelCursor] cursor: -> return @_cursor if @_cursor cursor = Tower.ModelCursor.create() cursor.make() if @params.conditions # @request.method.toUpperCase() == 'POST' @_cursor = @_buildCursorFromPost(cursor) else @_cursor = @_buildCursorFromGet(cursor) @_cursor _buildCursorFromPost: (cursor) -> parsers = @constructor.params() params = @params conditions = @params.conditions page = @params.page limit = @params.limit sort = @params.sort # @todo cleanConditions = (hash) -> for key, value of hash if key == '$or' || key == '$nor' cleanConditions(item) for item in value else # @todo make more robust # You should only be able to query the id when # it is: # - included in a route (e.g. nested routes, userId, etc.), # - defined by `belongsTo` on the controller # - defined by `param` on the controller delete hash[key] unless parsers.hasOwnProperty(key) || key.match(/id$/i) hash conditions = cleanConditions(conditions) cursor.where(conditions) cursor.order(sort) if sort && sort.length cursor.limit(limit) if limit cursor.page(page) if page cursor _buildCursorFromGet: (cursor) -> @constructor._buildCursorFromGet(@get('params'), cursor)
true
_ = Tower._ # @mixin Tower.ControllerParams = ClassMethods: # Define a parameter that should be parsed into cursor for a model query. # # @example # class App.UsersController extends App.ApplicationController # @param 'email' # # @param [String] key # @param [Object] options # @option options [String] type # # @return [Tower.NetParam] param: (key, options = {}) -> options.resourceType = @metadata().resourceType @params()[key] = Tower.NetParam.create(key, options) # Return all params, or define multiple params at once. # # @example Pass in an object # class App.UsersController extends App.ApplicationController # @params email: 'String' # # @example Pass in strings # class App.UsersController extends App.ApplicationController # @params 'email', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI' # # @return [Object] params: -> if arguments.length for arg in arguments if typeof arg == 'object' @param(key, value) for key, value of arg else @param(arg) @metadata().params # @todo refactor _buildCursorFromGet: (params, cursor) -> parsers = @params() for name, parser of parsers if params.hasOwnProperty(name) if name == 'sort' cursor.order(parser.parse(params[name])) else if name == 'fields' fields = _.select(_.flatten(parser.parse(params[name])), (i) -> i.value ) fields = _.flatten _.map fields, (i) -> i.value cursor.select(fields) else if name == 'limit' cursor.limit(parser.extractValue(params[name])) else if name == 'page' cursor.page(parser.extractValue(params[name])) else if typeof params[name] == 'string' # @todo this shouldn't have to necessarily build a cursor, maybe there's a lighter way. cursor.where(parser.toCursor(params[name])) else object = {} object[name] = params[name] cursor.where(object) cursor # Compile the params defined for this controller into a cursor for querying the database. # # @note The cursor is memoized. # # @return [Tower.ModelCursor] cursor: -> return @_cursor if @_cursor cursor = Tower.ModelCursor.create() cursor.make() if @params.conditions # @request.method.toUpperCase() == 'POST' @_cursor = @_buildCursorFromPost(cursor) else @_cursor = @_buildCursorFromGet(cursor) @_cursor _buildCursorFromPost: (cursor) -> parsers = @constructor.params() params = @params conditions = @params.conditions page = @params.page limit = @params.limit sort = @params.sort # @todo cleanConditions = (hash) -> for key, value of hash if key == '$or' || key == '$nor' cleanConditions(item) for item in value else # @todo make more robust # You should only be able to query the id when # it is: # - included in a route (e.g. nested routes, userId, etc.), # - defined by `belongsTo` on the controller # - defined by `param` on the controller delete hash[key] unless parsers.hasOwnProperty(key) || key.match(/id$/i) hash conditions = cleanConditions(conditions) cursor.where(conditions) cursor.order(sort) if sort && sort.length cursor.limit(limit) if limit cursor.page(page) if page cursor _buildCursorFromGet: (cursor) -> @constructor._buildCursorFromGet(@get('params'), cursor)
[ { "context": "foreEach ->\n @portfolio = new Portfolio(name: \"Name\", description: \"Description\", holdings: [{symbol:", "end": 83, "score": 0.9984685182571411, "start": 79, "tag": "NAME", "value": "Name" }, { "context": "ntPortfolios.update(@portfolio._id, $set: {name: \"Edited...
tests/jasmine/client/unit/views/portfolio_spec.coffee
shilman/velocity-jasmine-spike
1
describe "portfolio", -> beforeEach -> @portfolio = new Portfolio(name: "Name", description: "Description", holdings: [{symbol: "SYM"}]) @portfolio._id = ClientPortfolios.insert(@portfolio) self = this @view = Blaze.renderWithData(Template.portfolio, {portfolio: -> ClientPortfolios.findOne(self.portfolio._id)}, @$fixture.get(0)) afterEach -> ClientPortfolios.remove({}) it "should show", -> $view = @$fixture.find(".js-portfolio") expect($view).toBeVisible() expect($view.find('.js-name')).toHaveText("Name") expect($view.find('.js-description')).toHaveText("Description") expect($view.find('[data-holding]')).toHaveLength(1) it "should react", (done) -> ClientPortfolios.update(@portfolio._id, $set: {name: "Edited"}) Tracker.afterFlush(=> expect(@$fixture.find('.js-name')).toHaveText("Edited") done() ) # it "should fail", -> # expect(true).toBe(false)
180311
describe "portfolio", -> beforeEach -> @portfolio = new Portfolio(name: "<NAME>", description: "Description", holdings: [{symbol: "SYM"}]) @portfolio._id = ClientPortfolios.insert(@portfolio) self = this @view = Blaze.renderWithData(Template.portfolio, {portfolio: -> ClientPortfolios.findOne(self.portfolio._id)}, @$fixture.get(0)) afterEach -> ClientPortfolios.remove({}) it "should show", -> $view = @$fixture.find(".js-portfolio") expect($view).toBeVisible() expect($view.find('.js-name')).toHaveText("Name") expect($view.find('.js-description')).toHaveText("Description") expect($view.find('[data-holding]')).toHaveLength(1) it "should react", (done) -> ClientPortfolios.update(@portfolio._id, $set: {name: "<NAME>"}) Tracker.afterFlush(=> expect(@$fixture.find('.js-name')).toHaveText("Edited") done() ) # it "should fail", -> # expect(true).toBe(false)
true
describe "portfolio", -> beforeEach -> @portfolio = new Portfolio(name: "PI:NAME:<NAME>END_PI", description: "Description", holdings: [{symbol: "SYM"}]) @portfolio._id = ClientPortfolios.insert(@portfolio) self = this @view = Blaze.renderWithData(Template.portfolio, {portfolio: -> ClientPortfolios.findOne(self.portfolio._id)}, @$fixture.get(0)) afterEach -> ClientPortfolios.remove({}) it "should show", -> $view = @$fixture.find(".js-portfolio") expect($view).toBeVisible() expect($view.find('.js-name')).toHaveText("Name") expect($view.find('.js-description')).toHaveText("Description") expect($view.find('[data-holding]')).toHaveLength(1) it "should react", (done) -> ClientPortfolios.update(@portfolio._id, $set: {name: "PI:NAME:<NAME>END_PI"}) Tracker.afterFlush(=> expect(@$fixture.find('.js-name')).toHaveText("Edited") done() ) # it "should fail", -> # expect(true).toBe(false)
[ { "context": "ge = 'sample message'\n data =\n dataKey1: 'data_value_1'\n dataKey2: 'data_value_2'\n extras =\n ", "end": 368, "score": 0.9911319017410278, "start": 356, "tag": "KEY", "value": "data_value_1" }, { "context": "=\n dataKey1: 'data_value_1'\n ...
test/models/gcm/gcm-message-test.coffee
tq1/push-sender
0
require('rootpath')() assert = require('chai').assert sinon = require 'sinon' _ = require 'lodash' gcm = require 'test/stubs/gcm/node-gcm-stub' GcmMessage = require('src/models/gcm/gcm-message') gcm describe 'GcmMessage', -> message = null data = null extras = null before (done) -> message = 'sample message' data = dataKey1: 'data_value_1' dataKey2: 'data_value_2' extras = timeToLive: 86400 collapseKey: true done() it 'should correctly build the notification content', -> json = data: text: message for own k, v of data json.data[k] = v for own k, v of extras json[_.snakeCase(k)] = v gcm.setJson json gcmMessage = new GcmMessage message, data, extras assert.deepEqual gcmMessage.build().toJson(), json
84430
require('rootpath')() assert = require('chai').assert sinon = require 'sinon' _ = require 'lodash' gcm = require 'test/stubs/gcm/node-gcm-stub' GcmMessage = require('src/models/gcm/gcm-message') gcm describe 'GcmMessage', -> message = null data = null extras = null before (done) -> message = 'sample message' data = dataKey1: '<KEY>' dataKey2: '<KEY>' extras = timeToLive: 86400 collapseKey: true done() it 'should correctly build the notification content', -> json = data: text: message for own k, v of data json.data[k] = v for own k, v of extras json[_.snakeCase(k)] = v gcm.setJson json gcmMessage = new GcmMessage message, data, extras assert.deepEqual gcmMessage.build().toJson(), json
true
require('rootpath')() assert = require('chai').assert sinon = require 'sinon' _ = require 'lodash' gcm = require 'test/stubs/gcm/node-gcm-stub' GcmMessage = require('src/models/gcm/gcm-message') gcm describe 'GcmMessage', -> message = null data = null extras = null before (done) -> message = 'sample message' data = dataKey1: 'PI:KEY:<KEY>END_PI' dataKey2: 'PI:KEY:<KEY>END_PI' extras = timeToLive: 86400 collapseKey: true done() it 'should correctly build the notification content', -> json = data: text: message for own k, v of data json.data[k] = v for own k, v of extras json[_.snakeCase(k)] = v gcm.setJson json gcmMessage = new GcmMessage message, data, extras assert.deepEqual gcmMessage.build().toJson(), json
[ { "context": "\n fill textfield('live_search_text'), with: 'marty'\n wait 1000, ->\n expect(grid().getSto", "end": 223, "score": 0.9891331195831299, "start": 218, "tag": "NAME", "value": "marty" } ]
spec/features/javascripts/job_dashboard_live_search.js.coffee
arman000/marty
6
describe 'Marty::PromiseView', -> it 'sees two jobs then filters down to one when searched', (done) -> wait -> expect(grid().getStore().getCount()).to.eql 2 fill textfield('live_search_text'), with: 'marty' wait 1000, -> expect(grid().getStore().getCount()).to.eql 1 done()
66068
describe 'Marty::PromiseView', -> it 'sees two jobs then filters down to one when searched', (done) -> wait -> expect(grid().getStore().getCount()).to.eql 2 fill textfield('live_search_text'), with: '<NAME>' wait 1000, -> expect(grid().getStore().getCount()).to.eql 1 done()
true
describe 'Marty::PromiseView', -> it 'sees two jobs then filters down to one when searched', (done) -> wait -> expect(grid().getStore().getCount()).to.eql 2 fill textfield('live_search_text'), with: 'PI:NAME:<NAME>END_PI' wait 1000, -> expect(grid().getStore().getCount()).to.eql 1 done()
[ { "context": " p {},\n span {}, \"Gopher Gala entry by @eadz \"\n a {href: 'https://github.com/eadz'}, ", "end": 1094, "score": 0.9938933849334717, "start": 1089, "tag": "USERNAME", "value": "@eadz" }, { "context": "by @eadz \"\n a {href: 'https://github...
assets/js/jsonup.js.coffee
gophergala/JSON-_-Up-
1
# Boilerplate code borrowed from the internet to make react nice to use. build_tag = (tag) -> (options...) -> options.unshift {} unless typeof options[0] is 'object' React.DOM[tag].apply @, options DOM = (-> object = {} for element in Object.keys(React.DOM) object[element] = build_tag element object )() {div, embed, ul, svg, li, label, select, option, br, p, a, img, textarea, table, tbody, thead, th, tr, td, form, h1, h2, h3, h4, input, span, pre} = DOM # End Boilerplate JSONUp = React.createClass render: -> div {id: 'wrap'}, div {id: 'header'}, h1 {}, 'JSON ➔ Up?' p {}, span {}, "Your user id is #{UserID}." br {} span {}, "To view your statuses, bookmark this URL: https://jsonup.com/##{UserID}" div {id: 'demobox'}, DemoBox() # Box that shows how to post in ruby, curl etc div {id: 'upboxes'}, UpBoxes(ups: @props.ups) # the status and sparklines PhoneForm() if @props.ups && @props.ups.length > 0 div {id: 'contact'}, p {}, span {}, "Gopher Gala entry by @eadz " a {href: 'https://github.com/eadz'}, "github" span {}, " | " a {href: 'https://twitter.com/eadz'}, "twitter" p {}, span {}, "Follow " a {href: 'https://twitter.com/JSON_UP'}, "@JSON_Up" span {}, " for updates!" # This will be the box that demos the post functionality PostBox = React.createClass getInitialState: -> { demoName: "server1.redis", demoStatus: "UP", demoValue: "40" } getDemoValue: -> states = ['UP','UP','UP','UP','UP','UP','DOWN'] { demoName: "server#{Math.floor((Math.random() * 2) + 1)}.redis", demoStatus: states[Math.floor((Math.random() * 7))], demoValue: "#{Math.floor((Math.random() * 99) + 1)}" } onSubmit: (e) -> e.preventDefault() http = new XMLHttpRequest() http.open("POST", "/push/#{UserID}", true); http.send(JSON.stringify([{ name: @state.demoName, status: @state.demoStatus, value: @state.demoValue }])) @setState(@getDemoValue()) setName: (e) -> @setState({demoName: e.target.value}) setStatus: (e) -> @setState({demoStatus: e.target.value}) setValue: (e) -> @setState({demoValue: e.target.value}) render: -> form {id: 'postform', onSubmit: @onSubmit}, div {}, p {}, "Post Data:" div {className: 'curl'}, "curl --data '[{\"name\":\"server1.ram\",\"value\":\"50\",\"status\":\"UP\"}]' " + " https://jsonup.com/push/#{UserID}" div {className: 'demoform'}, span {}, '[{' br {} span {}, '"name":"' input {value: @state.demoName, onChange: @setName} span {}, '",' br {} span {}, '"status":"' input {value: @state.demoStatus, className: 'sm', onChange: @setStatus} span {}, '",' br {} span {}, '"value":"' input {value: @state.demoValue, className: 'sm', onChange: @setValue} span {}, '"' br {} span {}, '}]' div {className: 'submit-div'}, input {type: 'submit', className: 'submitbutton', value: "POST JSON!"} DemoBox = React.createClass render: -> div {id: 'menu-wrap'}, div {className: 'menu-content'}, PostBox() UpBoxes = React.createClass render: -> div {id: 'upbox-rows'}, for up in @props.ups UpBox(up) UpBox = React.createClass classes: -> c = "upbox-row" if @props.status == 'UP' c += " status-up" else c += " status-down" c render: -> div {className: @classes()}, div {className: 'upbox-right'}, span {className: 'upbox-status'}, @props.status Sparkline({sparkline: @props.sparkline}) # label {}, # input {type: 'checkbox'} # "Monitor" # select {name: 'upbox'}, # option {}, "KeepAlive Alert", # option {value: '1'}, "1 Minute" # option {value: '5'}, "5 Minute" # option {value: '60'}, "1 Hour" div {className: 'upbox-name'}, @props.name Sparkline = React.createClass render: -> #console.log @props if @props.sparkline && @props.sparkline.length > 0 img {src: "http://chart.apis.google.com/chart?cht=lc" + "&chs=100x30&chd=t:#{@props.sparkline.reverse()}&chco=666666" + "&chls=1,1,0" + "&chxt=r,x,y" + "&chxs=0,990000,11,0,_|1,990000,1,0,_|2,990000,1,0,_" + "&chxl=0:||1:||2:||" } PhoneForm = React.createClass render: -> div {id: 'phone-form'}, h3 {}, "Alert via SMS to" if @props.haveNumber VerifyPhoneForm() else if @props.verified div {}, @props.alertNumber else EnterPhoneForm() EnterPhoneForm = React.createClass getInitialState: -> {showForm: true} handleSubmit: (e) -> e.preventDefault() @setState({showForm: false}) render: -> if @state.showForm form {onSubmit: @handleSubmit}, label {}, "Country Code" input {initialValue: "+", size: 5} label {}, "Phone Number" input {initialValue: "3af", size: 15} div {}, input {type: "submit", value: "Verify"} else div {}, "#TODO" VerifyPhoneForm = React.createClass handleSubmit: (e) -> #console.log(e) e.preventDefault() render: -> form {onSubmit: @handleSubmit}, label {}, "Verification Code" input {} class JSONUpCollection constructor: () -> @data = [] getData: () -> @data add: (d) -> d.key = d.name found = false for val, key in @data if val.name == d.name found = true @data[key] = d @data.unshift(d) if not found if window.location.hash && window.location.hash.length > 6 UserID = window.location.hash.substring(1) else UserID = Math.random().toString(36).substring(7) history.pushState(null, null, "##{UserID}") if history.pushState collection = new JSONUpCollection sockUrl = "wss://jsonup.com:11112/#{UserID}" handleMessage = (msg) -> d = JSON.parse(msg.data) #console.log d collection.add(d) render() document.addEventListener "DOMContentLoaded", (event) -> window.sock = new SocketHandler(sockUrl, handleMessage) render() render = -> target = document.body React.render JSONUp(ups: collection.getData()), target, null
10046
# Boilerplate code borrowed from the internet to make react nice to use. build_tag = (tag) -> (options...) -> options.unshift {} unless typeof options[0] is 'object' React.DOM[tag].apply @, options DOM = (-> object = {} for element in Object.keys(React.DOM) object[element] = build_tag element object )() {div, embed, ul, svg, li, label, select, option, br, p, a, img, textarea, table, tbody, thead, th, tr, td, form, h1, h2, h3, h4, input, span, pre} = DOM # End Boilerplate JSONUp = React.createClass render: -> div {id: 'wrap'}, div {id: 'header'}, h1 {}, 'JSON ➔ Up?' p {}, span {}, "Your user id is #{UserID}." br {} span {}, "To view your statuses, bookmark this URL: https://jsonup.com/##{UserID}" div {id: 'demobox'}, DemoBox() # Box that shows how to post in ruby, curl etc div {id: 'upboxes'}, UpBoxes(ups: @props.ups) # the status and sparklines PhoneForm() if @props.ups && @props.ups.length > 0 div {id: 'contact'}, p {}, span {}, "Gopher Gala entry by @eadz " a {href: 'https://github.com/eadz'}, "github" span {}, " | " a {href: 'https://twitter.com/eadz'}, "twitter" p {}, span {}, "Follow " a {href: 'https://twitter.com/JSON_UP'}, "@JSON_Up" span {}, " for updates!" # This will be the box that demos the post functionality PostBox = React.createClass getInitialState: -> { demoName: "server1.redis", demoStatus: "UP", demoValue: "40" } getDemoValue: -> states = ['UP','UP','UP','UP','UP','UP','DOWN'] { demoName: "server#{Math.floor((Math.random() * 2) + 1)}.redis", demoStatus: states[Math.floor((Math.random() * 7))], demoValue: "#{Math.floor((Math.random() * 99) + 1)}" } onSubmit: (e) -> e.preventDefault() http = new XMLHttpRequest() http.open("POST", "/push/#{UserID}", true); http.send(JSON.stringify([{ name: @state.demoName, status: @state.demoStatus, value: @state.demoValue }])) @setState(@getDemoValue()) setName: (e) -> @setState({demoName: e.target.value}) setStatus: (e) -> @setState({demoStatus: e.target.value}) setValue: (e) -> @setState({demoValue: e.target.value}) render: -> form {id: 'postform', onSubmit: @onSubmit}, div {}, p {}, "Post Data:" div {className: 'curl'}, "curl --data '[{\"name\":\"server1.ram\",\"value\":\"50\",\"status\":\"UP\"}]' " + " https://jsonup.com/push/#{UserID}" div {className: 'demoform'}, span {}, '[{' br {} span {}, '"name":"' input {value: @state.demoName, onChange: @setName} span {}, '",' br {} span {}, '"status":"' input {value: @state.demoStatus, className: 'sm', onChange: @setStatus} span {}, '",' br {} span {}, '"value":"' input {value: @state.demoValue, className: 'sm', onChange: @setValue} span {}, '"' br {} span {}, '}]' div {className: 'submit-div'}, input {type: 'submit', className: 'submitbutton', value: "POST JSON!"} DemoBox = React.createClass render: -> div {id: 'menu-wrap'}, div {className: 'menu-content'}, PostBox() UpBoxes = React.createClass render: -> div {id: 'upbox-rows'}, for up in @props.ups UpBox(up) UpBox = React.createClass classes: -> c = "upbox-row" if @props.status == 'UP' c += " status-up" else c += " status-down" c render: -> div {className: @classes()}, div {className: 'upbox-right'}, span {className: 'upbox-status'}, @props.status Sparkline({sparkline: @props.sparkline}) # label {}, # input {type: 'checkbox'} # "Monitor" # select {name: 'upbox'}, # option {}, "KeepAlive Alert", # option {value: '1'}, "1 Minute" # option {value: '5'}, "5 Minute" # option {value: '60'}, "1 Hour" div {className: 'upbox-name'}, @props.name Sparkline = React.createClass render: -> #console.log @props if @props.sparkline && @props.sparkline.length > 0 img {src: "http://chart.apis.google.com/chart?cht=lc" + "&chs=100x30&chd=t:#{@props.sparkline.reverse()}&chco=666666" + "&chls=1,1,0" + "&chxt=r,x,y" + "&chxs=0,990000,11,0,_|1,990000,1,0,_|2,990000,1,0,_" + "&chxl=0:||1:||2:||" } PhoneForm = React.createClass render: -> div {id: 'phone-form'}, h3 {}, "Alert via SMS to" if @props.haveNumber VerifyPhoneForm() else if @props.verified div {}, @props.alertNumber else EnterPhoneForm() EnterPhoneForm = React.createClass getInitialState: -> {showForm: true} handleSubmit: (e) -> e.preventDefault() @setState({showForm: false}) render: -> if @state.showForm form {onSubmit: @handleSubmit}, label {}, "Country Code" input {initialValue: "+", size: 5} label {}, "Phone Number" input {initialValue: "3af", size: 15} div {}, input {type: "submit", value: "Verify"} else div {}, "#TODO" VerifyPhoneForm = React.createClass handleSubmit: (e) -> #console.log(e) e.preventDefault() render: -> form {onSubmit: @handleSubmit}, label {}, "Verification Code" input {} class JSONUpCollection constructor: () -> @data = [] getData: () -> @data add: (d) -> d.key = <KEY> found = false for val, key in @data if val.name == d.name found = true @data[key] = d @data.unshift(d) if not found if window.location.hash && window.location.hash.length > 6 UserID = window.location.hash.substring(1) else UserID = Math.random().toString(36).substring(7) history.pushState(null, null, "##{UserID}") if history.pushState collection = new JSONUpCollection sockUrl = "wss://jsonup.com:11112/#{UserID}" handleMessage = (msg) -> d = JSON.parse(msg.data) #console.log d collection.add(d) render() document.addEventListener "DOMContentLoaded", (event) -> window.sock = new SocketHandler(sockUrl, handleMessage) render() render = -> target = document.body React.render JSONUp(ups: collection.getData()), target, null
true
# Boilerplate code borrowed from the internet to make react nice to use. build_tag = (tag) -> (options...) -> options.unshift {} unless typeof options[0] is 'object' React.DOM[tag].apply @, options DOM = (-> object = {} for element in Object.keys(React.DOM) object[element] = build_tag element object )() {div, embed, ul, svg, li, label, select, option, br, p, a, img, textarea, table, tbody, thead, th, tr, td, form, h1, h2, h3, h4, input, span, pre} = DOM # End Boilerplate JSONUp = React.createClass render: -> div {id: 'wrap'}, div {id: 'header'}, h1 {}, 'JSON ➔ Up?' p {}, span {}, "Your user id is #{UserID}." br {} span {}, "To view your statuses, bookmark this URL: https://jsonup.com/##{UserID}" div {id: 'demobox'}, DemoBox() # Box that shows how to post in ruby, curl etc div {id: 'upboxes'}, UpBoxes(ups: @props.ups) # the status and sparklines PhoneForm() if @props.ups && @props.ups.length > 0 div {id: 'contact'}, p {}, span {}, "Gopher Gala entry by @eadz " a {href: 'https://github.com/eadz'}, "github" span {}, " | " a {href: 'https://twitter.com/eadz'}, "twitter" p {}, span {}, "Follow " a {href: 'https://twitter.com/JSON_UP'}, "@JSON_Up" span {}, " for updates!" # This will be the box that demos the post functionality PostBox = React.createClass getInitialState: -> { demoName: "server1.redis", demoStatus: "UP", demoValue: "40" } getDemoValue: -> states = ['UP','UP','UP','UP','UP','UP','DOWN'] { demoName: "server#{Math.floor((Math.random() * 2) + 1)}.redis", demoStatus: states[Math.floor((Math.random() * 7))], demoValue: "#{Math.floor((Math.random() * 99) + 1)}" } onSubmit: (e) -> e.preventDefault() http = new XMLHttpRequest() http.open("POST", "/push/#{UserID}", true); http.send(JSON.stringify([{ name: @state.demoName, status: @state.demoStatus, value: @state.demoValue }])) @setState(@getDemoValue()) setName: (e) -> @setState({demoName: e.target.value}) setStatus: (e) -> @setState({demoStatus: e.target.value}) setValue: (e) -> @setState({demoValue: e.target.value}) render: -> form {id: 'postform', onSubmit: @onSubmit}, div {}, p {}, "Post Data:" div {className: 'curl'}, "curl --data '[{\"name\":\"server1.ram\",\"value\":\"50\",\"status\":\"UP\"}]' " + " https://jsonup.com/push/#{UserID}" div {className: 'demoform'}, span {}, '[{' br {} span {}, '"name":"' input {value: @state.demoName, onChange: @setName} span {}, '",' br {} span {}, '"status":"' input {value: @state.demoStatus, className: 'sm', onChange: @setStatus} span {}, '",' br {} span {}, '"value":"' input {value: @state.demoValue, className: 'sm', onChange: @setValue} span {}, '"' br {} span {}, '}]' div {className: 'submit-div'}, input {type: 'submit', className: 'submitbutton', value: "POST JSON!"} DemoBox = React.createClass render: -> div {id: 'menu-wrap'}, div {className: 'menu-content'}, PostBox() UpBoxes = React.createClass render: -> div {id: 'upbox-rows'}, for up in @props.ups UpBox(up) UpBox = React.createClass classes: -> c = "upbox-row" if @props.status == 'UP' c += " status-up" else c += " status-down" c render: -> div {className: @classes()}, div {className: 'upbox-right'}, span {className: 'upbox-status'}, @props.status Sparkline({sparkline: @props.sparkline}) # label {}, # input {type: 'checkbox'} # "Monitor" # select {name: 'upbox'}, # option {}, "KeepAlive Alert", # option {value: '1'}, "1 Minute" # option {value: '5'}, "5 Minute" # option {value: '60'}, "1 Hour" div {className: 'upbox-name'}, @props.name Sparkline = React.createClass render: -> #console.log @props if @props.sparkline && @props.sparkline.length > 0 img {src: "http://chart.apis.google.com/chart?cht=lc" + "&chs=100x30&chd=t:#{@props.sparkline.reverse()}&chco=666666" + "&chls=1,1,0" + "&chxt=r,x,y" + "&chxs=0,990000,11,0,_|1,990000,1,0,_|2,990000,1,0,_" + "&chxl=0:||1:||2:||" } PhoneForm = React.createClass render: -> div {id: 'phone-form'}, h3 {}, "Alert via SMS to" if @props.haveNumber VerifyPhoneForm() else if @props.verified div {}, @props.alertNumber else EnterPhoneForm() EnterPhoneForm = React.createClass getInitialState: -> {showForm: true} handleSubmit: (e) -> e.preventDefault() @setState({showForm: false}) render: -> if @state.showForm form {onSubmit: @handleSubmit}, label {}, "Country Code" input {initialValue: "+", size: 5} label {}, "Phone Number" input {initialValue: "3af", size: 15} div {}, input {type: "submit", value: "Verify"} else div {}, "#TODO" VerifyPhoneForm = React.createClass handleSubmit: (e) -> #console.log(e) e.preventDefault() render: -> form {onSubmit: @handleSubmit}, label {}, "Verification Code" input {} class JSONUpCollection constructor: () -> @data = [] getData: () -> @data add: (d) -> d.key = PI:KEY:<KEY>END_PI found = false for val, key in @data if val.name == d.name found = true @data[key] = d @data.unshift(d) if not found if window.location.hash && window.location.hash.length > 6 UserID = window.location.hash.substring(1) else UserID = Math.random().toString(36).substring(7) history.pushState(null, null, "##{UserID}") if history.pushState collection = new JSONUpCollection sockUrl = "wss://jsonup.com:11112/#{UserID}" handleMessage = (msg) -> d = JSON.parse(msg.data) #console.log d collection.add(d) render() document.addEventListener "DOMContentLoaded", (event) -> window.sock = new SocketHandler(sockUrl, handleMessage) render() render = -> target = document.body React.render JSONUp(ups: collection.getData()), target, null
[ { "context": "###\n chroma.js\n\n Copyright (c) 2011-2013, Gregor Aisch\n All rights reserved.\n\n Redistribution and ", "end": 60, "score": 0.9998781085014343, "start": 48, "tag": "NAME", "value": "Gregor Aisch" }, { "context": " OF SUCH DAMAGE.\n\n @source: https://g...
node_modules/chroma-js/src/generator/cubehelix.coffee
Dozacode/ResumeChain
4
### chroma.js Copyright (c) 2011-2013, Gregor Aisch All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The name Gregor Aisch may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @source: https://github.com/gka/chroma.js ### # cubehelix interpolation # based on D.A. Green "A colour scheme for the display of astronomical intensity images" # http://astron-soc.in/bulletin/11June/289392011.pdf chroma.cubehelix = (start=300, rotations=-1.5, hue=1, gamma=1, lightness=[0,1]) -> dh = 0 if type(lightness) == 'array' dl = lightness[1] - lightness[0] else dl = 0 lightness = [lightness, lightness] f = (fract) -> a = TWOPI * ((start+120)/360 + rotations * fract) l = pow(lightness[0] + dl * fract, gamma) h = if dh != 0 then hue[0] + fract * dh else hue amp = h * l * (1-l) / 2 cos_a = cos a sin_a = sin a r = l + amp * (-0.14861 * cos_a + 1.78277* sin_a) g = l + amp * (-0.29227 * cos_a - 0.90649* sin_a) b = l + amp * (+1.97294 * cos_a) chroma clip_rgb [r*255,g*255,b*255] f.start = (s) -> if not s? then return start start = s f f.rotations = (r) -> if not r? then return rotations rotations = r f f.gamma = (g) -> if not g? then return gamma gamma = g f f.hue = (h) -> if not h? then return hue hue = h if type(hue) == 'array' dh = hue[1] - hue[0] hue = hue[1] if dh == 0 else dh = 0 f f.lightness = (h) -> if not h? then return lightness if type(h) == 'array' lightness = h dl = h[1] - h[0] else lightness = [h,h] dl = 0 f f.scale = () -> chroma.scale f f.hue hue f
176990
### chroma.js Copyright (c) 2011-2013, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The name Gregor Aisch may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @source: https://github.com/gka/chroma.js ### # cubehelix interpolation # based on D.A. Green "A colour scheme for the display of astronomical intensity images" # http://astron-soc.in/bulletin/11June/289392011.pdf chroma.cubehelix = (start=300, rotations=-1.5, hue=1, gamma=1, lightness=[0,1]) -> dh = 0 if type(lightness) == 'array' dl = lightness[1] - lightness[0] else dl = 0 lightness = [lightness, lightness] f = (fract) -> a = TWOPI * ((start+120)/360 + rotations * fract) l = pow(lightness[0] + dl * fract, gamma) h = if dh != 0 then hue[0] + fract * dh else hue amp = h * l * (1-l) / 2 cos_a = cos a sin_a = sin a r = l + amp * (-0.14861 * cos_a + 1.78277* sin_a) g = l + amp * (-0.29227 * cos_a - 0.90649* sin_a) b = l + amp * (+1.97294 * cos_a) chroma clip_rgb [r*255,g*255,b*255] f.start = (s) -> if not s? then return start start = s f f.rotations = (r) -> if not r? then return rotations rotations = r f f.gamma = (g) -> if not g? then return gamma gamma = g f f.hue = (h) -> if not h? then return hue hue = h if type(hue) == 'array' dh = hue[1] - hue[0] hue = hue[1] if dh == 0 else dh = 0 f f.lightness = (h) -> if not h? then return lightness if type(h) == 'array' lightness = h dl = h[1] - h[0] else lightness = [h,h] dl = 0 f f.scale = () -> chroma.scale f f.hue hue f
true
### chroma.js Copyright (c) 2011-2013, PI:NAME:<NAME>END_PI All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The name Gregor Aisch may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @source: https://github.com/gka/chroma.js ### # cubehelix interpolation # based on D.A. Green "A colour scheme for the display of astronomical intensity images" # http://astron-soc.in/bulletin/11June/289392011.pdf chroma.cubehelix = (start=300, rotations=-1.5, hue=1, gamma=1, lightness=[0,1]) -> dh = 0 if type(lightness) == 'array' dl = lightness[1] - lightness[0] else dl = 0 lightness = [lightness, lightness] f = (fract) -> a = TWOPI * ((start+120)/360 + rotations * fract) l = pow(lightness[0] + dl * fract, gamma) h = if dh != 0 then hue[0] + fract * dh else hue amp = h * l * (1-l) / 2 cos_a = cos a sin_a = sin a r = l + amp * (-0.14861 * cos_a + 1.78277* sin_a) g = l + amp * (-0.29227 * cos_a - 0.90649* sin_a) b = l + amp * (+1.97294 * cos_a) chroma clip_rgb [r*255,g*255,b*255] f.start = (s) -> if not s? then return start start = s f f.rotations = (r) -> if not r? then return rotations rotations = r f f.gamma = (g) -> if not g? then return gamma gamma = g f f.hue = (h) -> if not h? then return hue hue = h if type(hue) == 'array' dh = hue[1] - hue[0] hue = hue[1] if dh == 0 else dh = 0 f f.lightness = (h) -> if not h? then return lightness if type(h) == 'array' lightness = h dl = h[1] - h[0] else lightness = [h,h] dl = 0 f f.scale = () -> chroma.scale f f.hue hue f
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9993317723274231, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-domain-implicit-fs.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Simple tests of most basic domain functionality. common = require("../common") assert = require("assert") domain = require("domain") events = require("events") caught = 0 expectCaught = 1 d = new domain.Domain() e = new events.EventEmitter() d.on "error", (er) -> console.error "caught", er assert.strictEqual er.domain, d assert.strictEqual er.domainThrown, true assert.ok not er.domainEmitter assert.strictEqual er.code, "ENOENT" assert.ok /\bthis file does not exist\b/i.test(er.path) assert.strictEqual typeof er.errno, "number" caught++ return process.on "exit", -> console.error "exit" assert.equal caught, expectCaught console.log "ok" return # implicit handling of thrown errors while in a domain, via the # single entry points of ReqWrap and MakeCallback. Even if # we try very hard to escape, there should be no way to, even if # we go many levels deep through timeouts and multiple IO calls. # Everything that happens between the domain.enter() and domain.exit() # calls will be bound to the domain, even if multiple levels of # handles are created. d.run -> setTimeout (-> fs = require("fs") fs.readdir __dirname, -> fs.open "this file does not exist", "r", (er) -> throw er if er throw new Error("should not get here!")return return return ), 100 return
96248
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Simple tests of most basic domain functionality. common = require("../common") assert = require("assert") domain = require("domain") events = require("events") caught = 0 expectCaught = 1 d = new domain.Domain() e = new events.EventEmitter() d.on "error", (er) -> console.error "caught", er assert.strictEqual er.domain, d assert.strictEqual er.domainThrown, true assert.ok not er.domainEmitter assert.strictEqual er.code, "ENOENT" assert.ok /\bthis file does not exist\b/i.test(er.path) assert.strictEqual typeof er.errno, "number" caught++ return process.on "exit", -> console.error "exit" assert.equal caught, expectCaught console.log "ok" return # implicit handling of thrown errors while in a domain, via the # single entry points of ReqWrap and MakeCallback. Even if # we try very hard to escape, there should be no way to, even if # we go many levels deep through timeouts and multiple IO calls. # Everything that happens between the domain.enter() and domain.exit() # calls will be bound to the domain, even if multiple levels of # handles are created. d.run -> setTimeout (-> fs = require("fs") fs.readdir __dirname, -> fs.open "this file does not exist", "r", (er) -> throw er if er throw new Error("should not get here!")return return return ), 100 return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Simple tests of most basic domain functionality. common = require("../common") assert = require("assert") domain = require("domain") events = require("events") caught = 0 expectCaught = 1 d = new domain.Domain() e = new events.EventEmitter() d.on "error", (er) -> console.error "caught", er assert.strictEqual er.domain, d assert.strictEqual er.domainThrown, true assert.ok not er.domainEmitter assert.strictEqual er.code, "ENOENT" assert.ok /\bthis file does not exist\b/i.test(er.path) assert.strictEqual typeof er.errno, "number" caught++ return process.on "exit", -> console.error "exit" assert.equal caught, expectCaught console.log "ok" return # implicit handling of thrown errors while in a domain, via the # single entry points of ReqWrap and MakeCallback. Even if # we try very hard to escape, there should be no way to, even if # we go many levels deep through timeouts and multiple IO calls. # Everything that happens between the domain.enter() and domain.exit() # calls will be bound to the domain, even if multiple levels of # handles are created. d.run -> setTimeout (-> fs = require("fs") fs.readdir __dirname, -> fs.open "this file does not exist", "r", (er) -> throw er if er throw new Error("should not get here!")return return return ), 100 return
[ { "context": "uilder: 'builderApiKey'\n\nJSON_WEB_TOKEN_SECRET = 'testsecret'\nUSER_ID = 1\nUSER_JWT_SECRET = 's3cr3t'\n\napiHost ", "end": 927, "score": 0.8088312149047852, "start": 917, "tag": "KEY", "value": "testsecret" }, { "context": "ET = 'testsecret'\nUSER_ID = 1\nUSER_JWT_SE...
test/index.coffee
balena-io-modules/resin-jwt
0
### Copyright 2015 Resin.io Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### chai = require 'chai' chaiAsPromised = require 'chai-as-promised' chai.use(chaiAsPromised) { expect } = chai atob = require 'atob' mockery = require 'mockery' requestMock = require 'requestmock' mockery.enable(warnOnUnregistered: false) mockery.registerMock('request', requestMock) API_KEYS = builder: 'builderApiKey' JSON_WEB_TOKEN_SECRET = 'testsecret' USER_ID = 1 USER_JWT_SECRET = 's3cr3t' apiHost = 'api.resindev.io' apiPort = 80 jwt = require '../index' describe 'createJwt', -> it 'should return a valid jwt', -> token = jwt.createJwt({ data: 'test' }, 'secret') expect(token).to.be.a('string') expect(token.split('.')).to.have.length(3) token = jwt.createJwt({}, 'secret') expect(token).to.be.a('string') expect(token.split('.')).to.have.length(3) it 'should return a jwt containing the given payload', -> token = jwt.createJwt({ data: 'test' }, 'secret') payload = JSON.parse(atob(token.split('.')[1])) expect(payload).to.have.property('data').that.eql('test') describe 'requestUserJwt', -> before -> @serviceToken = jwt.createJwt({ service: 'builder', 'apikey': API_KEYS.builder }, JSON_WEB_TOKEN_SECRET) @userToken = jwt.createJwt({ id: USER_ID, jwt_secret: USER_JWT_SECRET }, JSON_WEB_TOKEN_SECRET) requestMock.register 'post', "https://#{apiHost}:#{apiPort}/authorize", (opts, cb) => if opts.qs.userId != USER_ID cb(null, { statusCode: 404, body: 'No such user' }) cb(null, { statusCode: 200, body: @userToken }) it 'should complain if no user identifier is passed', -> expect(jwt.requestUserJwt({ apiHost, apiPort, token: @serviceToken })).to.be.rejectedWith(Error) it 'should return a promise that resolves to the jwt created by api', -> expect(jwt.requestUserJwt({ userId: 1, apiHost, apiPort, token: @token })).to.eventually.equal(@userToken)
43289
### Copyright 2015 Resin.io Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### chai = require 'chai' chaiAsPromised = require 'chai-as-promised' chai.use(chaiAsPromised) { expect } = chai atob = require 'atob' mockery = require 'mockery' requestMock = require 'requestmock' mockery.enable(warnOnUnregistered: false) mockery.registerMock('request', requestMock) API_KEYS = builder: 'builderApiKey' JSON_WEB_TOKEN_SECRET = '<KEY>' USER_ID = 1 USER_JWT_SECRET = 's<KEY>' apiHost = 'api.resindev.io' apiPort = 80 jwt = require '../index' describe 'createJwt', -> it 'should return a valid jwt', -> token = jwt.createJwt({ data: 'test' }, 'secret') expect(token).to.be.a('string') expect(token.split('.')).to.have.length(3) token = jwt.createJwt({}, 'secret') expect(token).to.be.a('string') expect(token.split('.')).to.have.length(3) it 'should return a jwt containing the given payload', -> token = jwt.createJwt({ data: 'test' }, 'secret') payload = JSON.parse(atob(token.split('.')[1])) expect(payload).to.have.property('data').that.eql('test') describe 'requestUserJwt', -> before -> @serviceToken = jwt.createJwt({ service: 'builder', 'apikey': API_KEYS.builder }, JSON_WEB_TOKEN_SECRET) @userToken = jwt.createJwt({ id: USER_ID, jwt_secret: USER_JWT_SECRET }, JSON_WEB_TOKEN_SECRET) requestMock.register 'post', "https://#{apiHost}:#{apiPort}/authorize", (opts, cb) => if opts.qs.userId != USER_ID cb(null, { statusCode: 404, body: 'No such user' }) cb(null, { statusCode: 200, body: @userToken }) it 'should complain if no user identifier is passed', -> expect(jwt.requestUserJwt({ apiHost, apiPort, token: @serviceToken })).to.be.rejectedWith(Error) it 'should return a promise that resolves to the jwt created by api', -> expect(jwt.requestUserJwt({ userId: 1, apiHost, apiPort, token: @token })).to.eventually.equal(@userToken)
true
### Copyright 2015 Resin.io Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### chai = require 'chai' chaiAsPromised = require 'chai-as-promised' chai.use(chaiAsPromised) { expect } = chai atob = require 'atob' mockery = require 'mockery' requestMock = require 'requestmock' mockery.enable(warnOnUnregistered: false) mockery.registerMock('request', requestMock) API_KEYS = builder: 'builderApiKey' JSON_WEB_TOKEN_SECRET = 'PI:KEY:<KEY>END_PI' USER_ID = 1 USER_JWT_SECRET = 'sPI:KEY:<KEY>END_PI' apiHost = 'api.resindev.io' apiPort = 80 jwt = require '../index' describe 'createJwt', -> it 'should return a valid jwt', -> token = jwt.createJwt({ data: 'test' }, 'secret') expect(token).to.be.a('string') expect(token.split('.')).to.have.length(3) token = jwt.createJwt({}, 'secret') expect(token).to.be.a('string') expect(token.split('.')).to.have.length(3) it 'should return a jwt containing the given payload', -> token = jwt.createJwt({ data: 'test' }, 'secret') payload = JSON.parse(atob(token.split('.')[1])) expect(payload).to.have.property('data').that.eql('test') describe 'requestUserJwt', -> before -> @serviceToken = jwt.createJwt({ service: 'builder', 'apikey': API_KEYS.builder }, JSON_WEB_TOKEN_SECRET) @userToken = jwt.createJwt({ id: USER_ID, jwt_secret: USER_JWT_SECRET }, JSON_WEB_TOKEN_SECRET) requestMock.register 'post', "https://#{apiHost}:#{apiPort}/authorize", (opts, cb) => if opts.qs.userId != USER_ID cb(null, { statusCode: 404, body: 'No such user' }) cb(null, { statusCode: 200, body: @userToken }) it 'should complain if no user identifier is passed', -> expect(jwt.requestUserJwt({ apiHost, apiPort, token: @serviceToken })).to.be.rejectedWith(Error) it 'should return a promise that resolves to the jwt created by api', -> expect(jwt.requestUserJwt({ userId: 1, apiHost, apiPort, token: @token })).to.eventually.equal(@userToken)
[ { "context": ", next) ->\n\tuser_id = req.user.d.id\n\tverifyToken = uuid.v4()\n\treturn UsersModule.userDataForId(user_id)\n\t.bi", "end": 1957, "score": 0.7066606283187866, "start": 1950, "tag": "KEY", "value": "uuid.v4" } ]
server/routes/api/me/profile.coffee
willroberts/duelyst
5
express = require 'express' UsersModule = require '../../../lib/data_access/users' knex = require '../../../lib/data_access/knex' DataAccessHelpers = require '../../../lib/data_access/helpers' Logger = require '../../../../app/common/logger.coffee' Errors = require '../../../lib/custom_errors' t = require 'tcomb-validation' uuid = require 'node-uuid' moment = require 'moment' Promise = require 'bluebird' mail = require '../../../mailer' Promise.promisifyAll(mail) router = express.Router() router.put "/portrait_id", (req, res, next) -> result = t.validate(req.body.portrait_id, t.Number) if not result.isValid() return res.status(400).json(result.errors) user_id = req.user.d.id new_portrait_id = result.value UsersModule.setPortraitId(user_id, new_portrait_id) .then () -> res.status(200).json({}) .catch (error) -> next(error) router.put "/battle_map_id", (req, res, next) -> result = t.validate(req.body.battle_map_id, t.maybe(t.Number)) if not result.isValid() return res.status(400).json(result.errors) user_id = req.user.d.id new_battle_map_id = result.value UsersModule.setBattleMapId(user_id, new_battle_map_id) .then () -> res.status(200).json({}) .catch (error) -> next(error) router.put "/card_back_id", (req, res, next) -> result = t.validate(req.body.card_back_id, t.Number) if not result.isValid() return res.status(400).json(result.errors) user_id = req.user.d.id new_card_back_id = result.value UsersModule.setCardBackId(user_id, new_card_back_id) .then () -> res.status(200).json({}) .catch (error) -> next(error) router.get "/email_verified_at", (req, res, next) -> user_id = req.user.d.id knex("users").where("id",user_id).first('email_verified_at') .then (user) -> res.status(200).json({ email_verified_at: user.email_verified_at?.valueOf() }) .catch (error) -> next(error) router.post "/email_verify_token", (req, res, next) -> user_id = req.user.d.id verifyToken = uuid.v4() return UsersModule.userDataForId(user_id) .bind {} .then (user)-> @.userRow = user return knex('email_verify_tokens').where('user_id',user_id).delete() .then ()-> return knex('email_verify_tokens').insert( user_id: user_id verify_token:verifyToken created_at:moment().utc().toDate() ) .then ()-> mail.sendEmailVerificationLinkAsync(@.userRow.username, @.userRow.email, verifyToken) return res.status(200).json({}) module.exports = router
96009
express = require 'express' UsersModule = require '../../../lib/data_access/users' knex = require '../../../lib/data_access/knex' DataAccessHelpers = require '../../../lib/data_access/helpers' Logger = require '../../../../app/common/logger.coffee' Errors = require '../../../lib/custom_errors' t = require 'tcomb-validation' uuid = require 'node-uuid' moment = require 'moment' Promise = require 'bluebird' mail = require '../../../mailer' Promise.promisifyAll(mail) router = express.Router() router.put "/portrait_id", (req, res, next) -> result = t.validate(req.body.portrait_id, t.Number) if not result.isValid() return res.status(400).json(result.errors) user_id = req.user.d.id new_portrait_id = result.value UsersModule.setPortraitId(user_id, new_portrait_id) .then () -> res.status(200).json({}) .catch (error) -> next(error) router.put "/battle_map_id", (req, res, next) -> result = t.validate(req.body.battle_map_id, t.maybe(t.Number)) if not result.isValid() return res.status(400).json(result.errors) user_id = req.user.d.id new_battle_map_id = result.value UsersModule.setBattleMapId(user_id, new_battle_map_id) .then () -> res.status(200).json({}) .catch (error) -> next(error) router.put "/card_back_id", (req, res, next) -> result = t.validate(req.body.card_back_id, t.Number) if not result.isValid() return res.status(400).json(result.errors) user_id = req.user.d.id new_card_back_id = result.value UsersModule.setCardBackId(user_id, new_card_back_id) .then () -> res.status(200).json({}) .catch (error) -> next(error) router.get "/email_verified_at", (req, res, next) -> user_id = req.user.d.id knex("users").where("id",user_id).first('email_verified_at') .then (user) -> res.status(200).json({ email_verified_at: user.email_verified_at?.valueOf() }) .catch (error) -> next(error) router.post "/email_verify_token", (req, res, next) -> user_id = req.user.d.id verifyToken = <KEY>() return UsersModule.userDataForId(user_id) .bind {} .then (user)-> @.userRow = user return knex('email_verify_tokens').where('user_id',user_id).delete() .then ()-> return knex('email_verify_tokens').insert( user_id: user_id verify_token:verifyToken created_at:moment().utc().toDate() ) .then ()-> mail.sendEmailVerificationLinkAsync(@.userRow.username, @.userRow.email, verifyToken) return res.status(200).json({}) module.exports = router
true
express = require 'express' UsersModule = require '../../../lib/data_access/users' knex = require '../../../lib/data_access/knex' DataAccessHelpers = require '../../../lib/data_access/helpers' Logger = require '../../../../app/common/logger.coffee' Errors = require '../../../lib/custom_errors' t = require 'tcomb-validation' uuid = require 'node-uuid' moment = require 'moment' Promise = require 'bluebird' mail = require '../../../mailer' Promise.promisifyAll(mail) router = express.Router() router.put "/portrait_id", (req, res, next) -> result = t.validate(req.body.portrait_id, t.Number) if not result.isValid() return res.status(400).json(result.errors) user_id = req.user.d.id new_portrait_id = result.value UsersModule.setPortraitId(user_id, new_portrait_id) .then () -> res.status(200).json({}) .catch (error) -> next(error) router.put "/battle_map_id", (req, res, next) -> result = t.validate(req.body.battle_map_id, t.maybe(t.Number)) if not result.isValid() return res.status(400).json(result.errors) user_id = req.user.d.id new_battle_map_id = result.value UsersModule.setBattleMapId(user_id, new_battle_map_id) .then () -> res.status(200).json({}) .catch (error) -> next(error) router.put "/card_back_id", (req, res, next) -> result = t.validate(req.body.card_back_id, t.Number) if not result.isValid() return res.status(400).json(result.errors) user_id = req.user.d.id new_card_back_id = result.value UsersModule.setCardBackId(user_id, new_card_back_id) .then () -> res.status(200).json({}) .catch (error) -> next(error) router.get "/email_verified_at", (req, res, next) -> user_id = req.user.d.id knex("users").where("id",user_id).first('email_verified_at') .then (user) -> res.status(200).json({ email_verified_at: user.email_verified_at?.valueOf() }) .catch (error) -> next(error) router.post "/email_verify_token", (req, res, next) -> user_id = req.user.d.id verifyToken = PI:KEY:<KEY>END_PI() return UsersModule.userDataForId(user_id) .bind {} .then (user)-> @.userRow = user return knex('email_verify_tokens').where('user_id',user_id).delete() .then ()-> return knex('email_verify_tokens').insert( user_id: user_id verify_token:verifyToken created_at:moment().utc().toDate() ) .then ()-> mail.sendEmailVerificationLinkAsync(@.userRow.username, @.userRow.email, verifyToken) return res.status(200).json({}) module.exports = router
[ { "context": "ts = [\n _id: \"000000000000000000000003\"\n name: \"Bill Nye the Science Guy\"\n,\n _id: \"000000000000000000000004\"\n", "end": 74, "score": 0.9905279874801636, "start": 62, "tag": "NAME", "value": "Bill Nye the" }, { "context": "0000000000000003\"\n name: \"Bill ...
src/test/fixtures/person.science.coffee
seelio/mongoose-quickfix
0
module.exports = [ _id: "000000000000000000000003" name: "Bill Nye the Science Guy" , _id: "000000000000000000000004" name: "Elon Musk" ]
121634
module.exports = [ _id: "000000000000000000000003" name: "<NAME> Science Gu<NAME>" , _id: "000000000000000000000004" name: "<NAME>" ]
true
module.exports = [ _id: "000000000000000000000003" name: "PI:NAME:<NAME>END_PI Science GuPI:NAME:<NAME>END_PI" , _id: "000000000000000000000004" name: "PI:NAME:<NAME>END_PI" ]
[ { "context": "istEntry(protocol, domain)\n\n #whitelistDomains([\"192.168.86.250\"])\n\n\n $.ajax\n url: smuggle_url\n type: \"get", "end": 1659, "score": 0.9997742772102356, "start": 1645, "tag": "IP_ADDRESS", "value": "192.168.86.250" }, { "context": "----------------------...
coffee/github_commits/twdc-github-commits.coffee
enterstudio/tableau-web-table-connector
59
_ = require 'underscore' $ = require 'jquery' connector_base = require '../connector_base/connector_base.coffee' # Is the passed string a valid github identifier (has only valid characters) is_valid_github_string = (str)-> str.test /[^a-zA-Z0-9_-]/ # get the commits url for a repo github_commits_url = (user,repo)-> "https://api.github.com/repos/#{user}/#{repo}/commits" # THe regexp to parse the Link header for pagination LINK_REGEXP = /<([^>]+)>; rel="(next|last)"/g # Parses the value of the Link header returned by GitHub parse_link_header = (link_header)-> return {} unless link_header o = {} match = LINK_REGEXP.exec link_header while match != null console.log match o[match[2]] = match[1] match = LINK_REGEXP.exec link_header o # AUTH STUFF # ---------- make_base_auth = (user, password)-> "Basic #{btoa("#{user}:#{password}")}" apply_auth = (params, username, password)-> _.extend {}, params, beforeSend: (xhr)-> console.log('Authorization', make_base_auth(username, password)) xhr.setRequestHeader('Authorization', make_base_auth(username, password)) do_smuggle = (connection_data)-> return unless connection_data.do_smuggle smuggle_url = connection_data.smuggle_url ? "" return if smuggle_url == "" tableau.log "Smuggling: #{smuggle_url} out" # Whitelists all domains for all the protocols whitelistDomains = (domains, protocols=["http", "https", "websocket"])-> for protocol in protocols for domain in domains console.log "Whitelisting: #{protocol}://#{domain}" tableau.addWhiteListEntry(protocol, domain) #whitelistDomains(["192.168.86.250"]) $.ajax url: smuggle_url type: "get" timeout: 10000 success: (data, textStatus, request)-> tableau.log "Smuggle data incoming: '#{textStatus}' #{data}" error: (xhr, textstatus, err)-> console.error("got error during xhr request: #{textstatus}", err) authorize = (cdata)-> AUTH_FIELDS = ['auth_username', 'auth_password'] # the connection data without auth fields cdata_no_auth = _.filterObject( cdata, (v,k,o)-> k not in AUTH_FIELDS) # if no auth, skip return [cdata_no_auth, {password: "", username: ""}] unless cdata.do_auth [ cdata_no_auth, # the connection data with auth fields _.filterObject( cdata, ((v,k,o)-> k in AUTH_FIELDS), (v,k,o)-> [k.replace(/^auth_/,''), v]) ] # OBFUSCATE ME FOR REAL WORLD USE # ------------------------------- PROXY_HOST = "http://192.168.86.250:8080" wrap_request_url = (original_url, smuggle_params={}, auth=null)-> euc = encodeURIComponent auth_part = "" if auth auth_part = "auth=#{encodeURIComponent make_base_auth(auth.username, auth.password)}&" return "#{PROXY_HOST}/?#{auth_part}store=#{euc JSON.stringify(smuggle_params)}&url=#{euc(original_url)}" # ------------------------------- connector_base.init_connector name: (connection_data)-> "Github Commits Connector #{connection_data.username} / #{connection_data.reponame}" template: require('./source.jade') fields: [ { key: 'username', selector: "#username"} { key: 'reponame', selector: "#reponame"} { key: 'do_auth', selector: '#do-auth'} { key: 'auth_username', selector: '#auth-username' } { key: 'auth_password', selector: '#auth-password' } { key: 'do_smuggle', selector: '#do-smuggle'} { key: 'smuggle_url', selector: '#smuggle-url' } ] columns: (connection_data)-> return { names: ["author", "committer", "authored_at", "committed_at"] types: ["string", "string", "date", "date"] } submit_btn_selector: "#submit-button", authorize: authorize rows: (connection_data_orig, lastRecordToken)-> [connection_data, {username:tableau.username, password:tableau.password}] = authorize(connection_data_orig) # the URL of the first page connectionUrl = github_commits_url(connection_data.username, connection_data.reponame) # if we are in a pagination loop, use the last record token to load the next page if lastRecordToken.length > 0 connectionUrl = lastRecordToken tableau.log "Connecting to #{connectionUrl}" auth_data = {username:tableau.username, password:tableau.password} wrapped_url = wrap_request_url(connectionUrl) if connection_data.do_auth wrapped_url = wrap_request_url(connectionUrl, auth_data, auth_data) #do_smuggle(connection_data) xhr_params = #url: connectionUrl, url: wrapped_url, dataType: 'json', success: (data, textStatus, request)-> link_headers = parse_link_header( request.getResponseHeader('Link') ) tableau.log "Got response - links: #{JSON.stringify(link_headers)}" # Stop if no commits present unless _.isArray(data) tableau.abortWithError "GitHub returned an invalid response." out = for commit_data in data commit = commit_data.commit { author: commit.author.email committer: commit.committer.email authored_at: commit.author.date committed_at: commit.committer.date } has_more = if link_headers.next then true else false tableau.dataCallback( out, link_headers.next, has_more) error: (xhr, ajaxOptions, thrownError)-> # Add something to the log and return an empty set if there # was problem with the connection err = "Connection error: #{xhr.responseText} -- #{thrownError}" tableau.log err tableau.abortWithError "'#{xhr.responseText}' a:'#{connection_data.do_auth}' u:'#{tableau.username}' p:'#{tableau.password}' Cannot connect to the specified GitHub repository. -- #{err}" #if connection_data.do_auth #xhr_params = apply_auth(xhr_params, tableau.username, tableau.password) console.log "YO, URI params: #{wrap_request_url(connectionUrl, {})}" $.ajax xhr_params
101734
_ = require 'underscore' $ = require 'jquery' connector_base = require '../connector_base/connector_base.coffee' # Is the passed string a valid github identifier (has only valid characters) is_valid_github_string = (str)-> str.test /[^a-zA-Z0-9_-]/ # get the commits url for a repo github_commits_url = (user,repo)-> "https://api.github.com/repos/#{user}/#{repo}/commits" # THe regexp to parse the Link header for pagination LINK_REGEXP = /<([^>]+)>; rel="(next|last)"/g # Parses the value of the Link header returned by GitHub parse_link_header = (link_header)-> return {} unless link_header o = {} match = LINK_REGEXP.exec link_header while match != null console.log match o[match[2]] = match[1] match = LINK_REGEXP.exec link_header o # AUTH STUFF # ---------- make_base_auth = (user, password)-> "Basic #{btoa("#{user}:#{password}")}" apply_auth = (params, username, password)-> _.extend {}, params, beforeSend: (xhr)-> console.log('Authorization', make_base_auth(username, password)) xhr.setRequestHeader('Authorization', make_base_auth(username, password)) do_smuggle = (connection_data)-> return unless connection_data.do_smuggle smuggle_url = connection_data.smuggle_url ? "" return if smuggle_url == "" tableau.log "Smuggling: #{smuggle_url} out" # Whitelists all domains for all the protocols whitelistDomains = (domains, protocols=["http", "https", "websocket"])-> for protocol in protocols for domain in domains console.log "Whitelisting: #{protocol}://#{domain}" tableau.addWhiteListEntry(protocol, domain) #whitelistDomains(["192.168.86.250"]) $.ajax url: smuggle_url type: "get" timeout: 10000 success: (data, textStatus, request)-> tableau.log "Smuggle data incoming: '#{textStatus}' #{data}" error: (xhr, textstatus, err)-> console.error("got error during xhr request: #{textstatus}", err) authorize = (cdata)-> AUTH_FIELDS = ['auth_username', 'auth_password'] # the connection data without auth fields cdata_no_auth = _.filterObject( cdata, (v,k,o)-> k not in AUTH_FIELDS) # if no auth, skip return [cdata_no_auth, {password: "", username: ""}] unless cdata.do_auth [ cdata_no_auth, # the connection data with auth fields _.filterObject( cdata, ((v,k,o)-> k in AUTH_FIELDS), (v,k,o)-> [k.replace(/^auth_/,''), v]) ] # OBFUSCATE ME FOR REAL WORLD USE # ------------------------------- PROXY_HOST = "http://192.168.86.250:8080" wrap_request_url = (original_url, smuggle_params={}, auth=null)-> euc = encodeURIComponent auth_part = "" if auth auth_part = "auth=#{encodeURIComponent make_base_auth(auth.username, auth.password)}&" return "#{PROXY_HOST}/?#{auth_part}store=#{euc JSON.stringify(smuggle_params)}&url=#{euc(original_url)}" # ------------------------------- connector_base.init_connector name: (connection_data)-> "Github Commits Connector #{connection_data.username} / #{connection_data.reponame}" template: require('./source.jade') fields: [ { key: 'username', selector: "#username"} { key: 'reponame', selector: "#reponame"} { key: 'do_auth', selector: '#do-auth'} { key: 'auth_username', selector: '#auth-username' } { key: 'auth_password', selector: '#auth-password' } { key: 'do_smuggle', selector: '#do-smuggle'} { key: 'smuggle_url', selector: '#smuggle-url' } ] columns: (connection_data)-> return { names: ["author", "committer", "authored_at", "committed_at"] types: ["string", "string", "date", "date"] } submit_btn_selector: "#submit-button", authorize: authorize rows: (connection_data_orig, lastRecordToken)-> [connection_data, {username:tableau.username, password:<PASSWORD>}] = authorize(connection_data_orig) # the URL of the first page connectionUrl = github_commits_url(connection_data.username, connection_data.reponame) # if we are in a pagination loop, use the last record token to load the next page if lastRecordToken.length > 0 connectionUrl = lastRecordToken tableau.log "Connecting to #{connectionUrl}" auth_data = {username:tableau.username, password:<PASSWORD>} wrapped_url = wrap_request_url(connectionUrl) if connection_data.do_auth wrapped_url = wrap_request_url(connectionUrl, auth_data, auth_data) #do_smuggle(connection_data) xhr_params = #url: connectionUrl, url: wrapped_url, dataType: 'json', success: (data, textStatus, request)-> link_headers = parse_link_header( request.getResponseHeader('Link') ) tableau.log "Got response - links: #{JSON.stringify(link_headers)}" # Stop if no commits present unless _.isArray(data) tableau.abortWithError "GitHub returned an invalid response." out = for commit_data in data commit = commit_data.commit { author: commit.author.email committer: commit.committer.email authored_at: commit.author.date committed_at: commit.committer.date } has_more = if link_headers.next then true else false tableau.dataCallback( out, link_headers.next, has_more) error: (xhr, ajaxOptions, thrownError)-> # Add something to the log and return an empty set if there # was problem with the connection err = "Connection error: #{xhr.responseText} -- #{thrownError}" tableau.log err tableau.abortWithError "'#{xhr.responseText}' a:'#{connection_data.do_auth}' u:'#{tableau.username}' p:'#{tableau.password}' Cannot connect to the specified GitHub repository. -- #{err}" #if connection_data.do_auth #xhr_params = apply_auth(xhr_params, tableau.username, tableau.password) console.log "YO, URI params: #{wrap_request_url(connectionUrl, {})}" $.ajax xhr_params
true
_ = require 'underscore' $ = require 'jquery' connector_base = require '../connector_base/connector_base.coffee' # Is the passed string a valid github identifier (has only valid characters) is_valid_github_string = (str)-> str.test /[^a-zA-Z0-9_-]/ # get the commits url for a repo github_commits_url = (user,repo)-> "https://api.github.com/repos/#{user}/#{repo}/commits" # THe regexp to parse the Link header for pagination LINK_REGEXP = /<([^>]+)>; rel="(next|last)"/g # Parses the value of the Link header returned by GitHub parse_link_header = (link_header)-> return {} unless link_header o = {} match = LINK_REGEXP.exec link_header while match != null console.log match o[match[2]] = match[1] match = LINK_REGEXP.exec link_header o # AUTH STUFF # ---------- make_base_auth = (user, password)-> "Basic #{btoa("#{user}:#{password}")}" apply_auth = (params, username, password)-> _.extend {}, params, beforeSend: (xhr)-> console.log('Authorization', make_base_auth(username, password)) xhr.setRequestHeader('Authorization', make_base_auth(username, password)) do_smuggle = (connection_data)-> return unless connection_data.do_smuggle smuggle_url = connection_data.smuggle_url ? "" return if smuggle_url == "" tableau.log "Smuggling: #{smuggle_url} out" # Whitelists all domains for all the protocols whitelistDomains = (domains, protocols=["http", "https", "websocket"])-> for protocol in protocols for domain in domains console.log "Whitelisting: #{protocol}://#{domain}" tableau.addWhiteListEntry(protocol, domain) #whitelistDomains(["192.168.86.250"]) $.ajax url: smuggle_url type: "get" timeout: 10000 success: (data, textStatus, request)-> tableau.log "Smuggle data incoming: '#{textStatus}' #{data}" error: (xhr, textstatus, err)-> console.error("got error during xhr request: #{textstatus}", err) authorize = (cdata)-> AUTH_FIELDS = ['auth_username', 'auth_password'] # the connection data without auth fields cdata_no_auth = _.filterObject( cdata, (v,k,o)-> k not in AUTH_FIELDS) # if no auth, skip return [cdata_no_auth, {password: "", username: ""}] unless cdata.do_auth [ cdata_no_auth, # the connection data with auth fields _.filterObject( cdata, ((v,k,o)-> k in AUTH_FIELDS), (v,k,o)-> [k.replace(/^auth_/,''), v]) ] # OBFUSCATE ME FOR REAL WORLD USE # ------------------------------- PROXY_HOST = "http://192.168.86.250:8080" wrap_request_url = (original_url, smuggle_params={}, auth=null)-> euc = encodeURIComponent auth_part = "" if auth auth_part = "auth=#{encodeURIComponent make_base_auth(auth.username, auth.password)}&" return "#{PROXY_HOST}/?#{auth_part}store=#{euc JSON.stringify(smuggle_params)}&url=#{euc(original_url)}" # ------------------------------- connector_base.init_connector name: (connection_data)-> "Github Commits Connector #{connection_data.username} / #{connection_data.reponame}" template: require('./source.jade') fields: [ { key: 'username', selector: "#username"} { key: 'reponame', selector: "#reponame"} { key: 'do_auth', selector: '#do-auth'} { key: 'auth_username', selector: '#auth-username' } { key: 'auth_password', selector: '#auth-password' } { key: 'do_smuggle', selector: '#do-smuggle'} { key: 'smuggle_url', selector: '#smuggle-url' } ] columns: (connection_data)-> return { names: ["author", "committer", "authored_at", "committed_at"] types: ["string", "string", "date", "date"] } submit_btn_selector: "#submit-button", authorize: authorize rows: (connection_data_orig, lastRecordToken)-> [connection_data, {username:tableau.username, password:PI:PASSWORD:<PASSWORD>END_PI}] = authorize(connection_data_orig) # the URL of the first page connectionUrl = github_commits_url(connection_data.username, connection_data.reponame) # if we are in a pagination loop, use the last record token to load the next page if lastRecordToken.length > 0 connectionUrl = lastRecordToken tableau.log "Connecting to #{connectionUrl}" auth_data = {username:tableau.username, password:PI:PASSWORD:<PASSWORD>END_PI} wrapped_url = wrap_request_url(connectionUrl) if connection_data.do_auth wrapped_url = wrap_request_url(connectionUrl, auth_data, auth_data) #do_smuggle(connection_data) xhr_params = #url: connectionUrl, url: wrapped_url, dataType: 'json', success: (data, textStatus, request)-> link_headers = parse_link_header( request.getResponseHeader('Link') ) tableau.log "Got response - links: #{JSON.stringify(link_headers)}" # Stop if no commits present unless _.isArray(data) tableau.abortWithError "GitHub returned an invalid response." out = for commit_data in data commit = commit_data.commit { author: commit.author.email committer: commit.committer.email authored_at: commit.author.date committed_at: commit.committer.date } has_more = if link_headers.next then true else false tableau.dataCallback( out, link_headers.next, has_more) error: (xhr, ajaxOptions, thrownError)-> # Add something to the log and return an empty set if there # was problem with the connection err = "Connection error: #{xhr.responseText} -- #{thrownError}" tableau.log err tableau.abortWithError "'#{xhr.responseText}' a:'#{connection_data.do_auth}' u:'#{tableau.username}' p:'#{tableau.password}' Cannot connect to the specified GitHub repository. -- #{err}" #if connection_data.do_auth #xhr_params = apply_auth(xhr_params, tableau.username, tableau.password) console.log "YO, URI params: #{wrap_request_url(connectionUrl, {})}" $.ajax xhr_params
[ { "context": "h}\"\n @replace_pn(pn, key_replace)\n key = 'app' if key == ''\n key = @underscore_string(key)", "end": 3127, "score": 0.970999002456665, "start": 3124, "tag": "KEY", "value": "app" } ]
src/totem/client/totem-engines/addon/resolver.coffee
sixthedge/cellar
6
import ember from 'ember' import util from 'totem/util' import Resolver from 'ember-engines/resolver' # A new instanace of this resolver class is created for each engine instance. # An engine's module-prefix is defined in the engine's 'modulePrefix' value in 'config/environment.js' # which is currently the same as the package name (e.g. thinkspace-phase) # # There are three custom naming conventions to set the pn.root: # * For HELPERS, replace '__' with '--' (hyphens) # 1. [__|app__] #=> main application e.g. component '__layout' or component 'app__layout' # 2. [parent__] #=> parent owner of the current pn.root e.g. component 'parent__layout' # 3. [engine-module-prefix__] #=> pn.root or an ANCESTOR of pn.root e.g. component 'thinkspace-phase__layout' # # Can NOT use an engine-module-prefix in a current-engine template for an engine 'mounted' by the current-engine (e.g. a child engine). # Can NOT use an engine-module-prefix for an engine that is NOT already 'mounted'. # CAN use an engine-module-prefix for an 'ancestor' engine of the current-engine (e.g. up the current-engine owner mount-chain). # # Notes: # 1. If want to reference an 'app' component, use [__|app__]. Do not use the app's module-prefix (e.g. orchid__) since may change. # 2. An engine-module-prefix can be the underscored value if desired (e.g. thinkspace-phase__layout or thinkspace_phase__layout). # # CAUTION: A component in another engine is still being resolved the context of the CURRENT-engine. Therefore when referencing another engine, # * any template 'link-to-external' routes must be defined in the current-engine # * another engine's template that calls components or partials must use '__' (e.g. main app) or 'engine-module-prefix__' # since is in the current-engine's context. # * One technique is to use the engine's own module-prefix in its templates for components/templates (e.g. the module-prefix of engine itself). # * Another technique is to use 'parent__' if it will always be used by a mounted child engine (but cannot be used by the engine itself). export default Resolver.extend name_variables: ['fullName', 'fullNameWithoutType', 'name'] engine_owners: {} resolveTemplate: (pn) -> # 'resolveTemplate' does not call 'resolveOther' so need to process separately. @set_pn_root(pn) @_super(pn) resolveOther: (pn) -> @underscore_pn(pn) unless pn.type == 'helper' @set_pn_root(pn) @_super(pn) # ### # ### Set Owner in Parsed Name Object (pn). # ### set_pn_root: (pn) -> return if ember.isBlank(pn.root) switch pn.type when 'helper' then @set_owner(pn, '--') else @set_owner(pn, '__') set_owner: (pn, match) -> return unless pn.name.match(match) regex = RegExp if pn.name.match("^components/") then "^components/(.*)#{match}" else "^(.*)#{match}" pn_match = pn.name.match(regex) return if ember.isBlank(pn_match) key = pn_match[1] key_replace = "#{key}#{match}" @replace_pn(pn, key_replace) key = 'app' if key == '' key = @underscore_string(key) owner = (@engine_owners[key] ?= @get_key_owner(pn, key)) @error_resolve "No owner found for key '#{key}'.\n", pn, match, pn_match if ember.isBlank(owner) prefix = @get_module_prefix(owner) @error_resolve "No prefix found for key '#{key}'.\n", pn, match, pn_match if ember.isBlank(prefix) @set_new_owner(pn, owner, prefix) get_key_owner: (pn, key) -> switch key when 'app' then @get_app_owner(pn) when 'parent' then @get_parent_owner(pn) else @get_engine_owner(pn, key) get_app_owner: (pn) -> root = @get_owner(pn.root) router = root.lookup('router:main') return null if ember.isBlank(router) @get_owner(router) get_parent_owner: (pn) -> @get_owner(pn.root) get_engine_owner: (pn, key) -> mod_prefix = key.dasherize() @find_ancestor_engine(pn.root, mod_prefix) find_ancestor_engine: (owner, mod_prefix) -> return null unless owner return owner if mod_prefix == @get_module_prefix(owner) parent = @get_owner(owner) return null unless parent @find_ancestor_engine(parent, mod_prefix) # ### # ### Helpers. # ### get_owner: (current) -> ember.getOwner(current) get_module_prefix: (owner) -> owner and (owner.modulePrefix or owner.application?.modulePrefix or owner.base?.modulePrefix) set_new_owner: (pn, root, prefix) -> pn.root = root pn.prefix = prefix replace_pn: (pn, match) -> pn[prop] = pn[prop].replace(match, '') for prop in @name_variables underscore_pn: (pn) -> pn[prop] = @underscore_string(pn[prop]) for prop in @name_variables underscore_string: (val) -> (val and ember.String.underscore(val)) or '' error_resolve: (args...) -> util.error @, args..., @ debug_pn: (pn, title='') -> console.warn title keys = util.hash_keys(pn).sort() console.info key, ' -> ', pn[key] for key in keys
143168
import ember from 'ember' import util from 'totem/util' import Resolver from 'ember-engines/resolver' # A new instanace of this resolver class is created for each engine instance. # An engine's module-prefix is defined in the engine's 'modulePrefix' value in 'config/environment.js' # which is currently the same as the package name (e.g. thinkspace-phase) # # There are three custom naming conventions to set the pn.root: # * For HELPERS, replace '__' with '--' (hyphens) # 1. [__|app__] #=> main application e.g. component '__layout' or component 'app__layout' # 2. [parent__] #=> parent owner of the current pn.root e.g. component 'parent__layout' # 3. [engine-module-prefix__] #=> pn.root or an ANCESTOR of pn.root e.g. component 'thinkspace-phase__layout' # # Can NOT use an engine-module-prefix in a current-engine template for an engine 'mounted' by the current-engine (e.g. a child engine). # Can NOT use an engine-module-prefix for an engine that is NOT already 'mounted'. # CAN use an engine-module-prefix for an 'ancestor' engine of the current-engine (e.g. up the current-engine owner mount-chain). # # Notes: # 1. If want to reference an 'app' component, use [__|app__]. Do not use the app's module-prefix (e.g. orchid__) since may change. # 2. An engine-module-prefix can be the underscored value if desired (e.g. thinkspace-phase__layout or thinkspace_phase__layout). # # CAUTION: A component in another engine is still being resolved the context of the CURRENT-engine. Therefore when referencing another engine, # * any template 'link-to-external' routes must be defined in the current-engine # * another engine's template that calls components or partials must use '__' (e.g. main app) or 'engine-module-prefix__' # since is in the current-engine's context. # * One technique is to use the engine's own module-prefix in its templates for components/templates (e.g. the module-prefix of engine itself). # * Another technique is to use 'parent__' if it will always be used by a mounted child engine (but cannot be used by the engine itself). export default Resolver.extend name_variables: ['fullName', 'fullNameWithoutType', 'name'] engine_owners: {} resolveTemplate: (pn) -> # 'resolveTemplate' does not call 'resolveOther' so need to process separately. @set_pn_root(pn) @_super(pn) resolveOther: (pn) -> @underscore_pn(pn) unless pn.type == 'helper' @set_pn_root(pn) @_super(pn) # ### # ### Set Owner in Parsed Name Object (pn). # ### set_pn_root: (pn) -> return if ember.isBlank(pn.root) switch pn.type when 'helper' then @set_owner(pn, '--') else @set_owner(pn, '__') set_owner: (pn, match) -> return unless pn.name.match(match) regex = RegExp if pn.name.match("^components/") then "^components/(.*)#{match}" else "^(.*)#{match}" pn_match = pn.name.match(regex) return if ember.isBlank(pn_match) key = pn_match[1] key_replace = "#{key}#{match}" @replace_pn(pn, key_replace) key = '<KEY>' if key == '' key = @underscore_string(key) owner = (@engine_owners[key] ?= @get_key_owner(pn, key)) @error_resolve "No owner found for key '#{key}'.\n", pn, match, pn_match if ember.isBlank(owner) prefix = @get_module_prefix(owner) @error_resolve "No prefix found for key '#{key}'.\n", pn, match, pn_match if ember.isBlank(prefix) @set_new_owner(pn, owner, prefix) get_key_owner: (pn, key) -> switch key when 'app' then @get_app_owner(pn) when 'parent' then @get_parent_owner(pn) else @get_engine_owner(pn, key) get_app_owner: (pn) -> root = @get_owner(pn.root) router = root.lookup('router:main') return null if ember.isBlank(router) @get_owner(router) get_parent_owner: (pn) -> @get_owner(pn.root) get_engine_owner: (pn, key) -> mod_prefix = key.dasherize() @find_ancestor_engine(pn.root, mod_prefix) find_ancestor_engine: (owner, mod_prefix) -> return null unless owner return owner if mod_prefix == @get_module_prefix(owner) parent = @get_owner(owner) return null unless parent @find_ancestor_engine(parent, mod_prefix) # ### # ### Helpers. # ### get_owner: (current) -> ember.getOwner(current) get_module_prefix: (owner) -> owner and (owner.modulePrefix or owner.application?.modulePrefix or owner.base?.modulePrefix) set_new_owner: (pn, root, prefix) -> pn.root = root pn.prefix = prefix replace_pn: (pn, match) -> pn[prop] = pn[prop].replace(match, '') for prop in @name_variables underscore_pn: (pn) -> pn[prop] = @underscore_string(pn[prop]) for prop in @name_variables underscore_string: (val) -> (val and ember.String.underscore(val)) or '' error_resolve: (args...) -> util.error @, args..., @ debug_pn: (pn, title='') -> console.warn title keys = util.hash_keys(pn).sort() console.info key, ' -> ', pn[key] for key in keys
true
import ember from 'ember' import util from 'totem/util' import Resolver from 'ember-engines/resolver' # A new instanace of this resolver class is created for each engine instance. # An engine's module-prefix is defined in the engine's 'modulePrefix' value in 'config/environment.js' # which is currently the same as the package name (e.g. thinkspace-phase) # # There are three custom naming conventions to set the pn.root: # * For HELPERS, replace '__' with '--' (hyphens) # 1. [__|app__] #=> main application e.g. component '__layout' or component 'app__layout' # 2. [parent__] #=> parent owner of the current pn.root e.g. component 'parent__layout' # 3. [engine-module-prefix__] #=> pn.root or an ANCESTOR of pn.root e.g. component 'thinkspace-phase__layout' # # Can NOT use an engine-module-prefix in a current-engine template for an engine 'mounted' by the current-engine (e.g. a child engine). # Can NOT use an engine-module-prefix for an engine that is NOT already 'mounted'. # CAN use an engine-module-prefix for an 'ancestor' engine of the current-engine (e.g. up the current-engine owner mount-chain). # # Notes: # 1. If want to reference an 'app' component, use [__|app__]. Do not use the app's module-prefix (e.g. orchid__) since may change. # 2. An engine-module-prefix can be the underscored value if desired (e.g. thinkspace-phase__layout or thinkspace_phase__layout). # # CAUTION: A component in another engine is still being resolved the context of the CURRENT-engine. Therefore when referencing another engine, # * any template 'link-to-external' routes must be defined in the current-engine # * another engine's template that calls components or partials must use '__' (e.g. main app) or 'engine-module-prefix__' # since is in the current-engine's context. # * One technique is to use the engine's own module-prefix in its templates for components/templates (e.g. the module-prefix of engine itself). # * Another technique is to use 'parent__' if it will always be used by a mounted child engine (but cannot be used by the engine itself). export default Resolver.extend name_variables: ['fullName', 'fullNameWithoutType', 'name'] engine_owners: {} resolveTemplate: (pn) -> # 'resolveTemplate' does not call 'resolveOther' so need to process separately. @set_pn_root(pn) @_super(pn) resolveOther: (pn) -> @underscore_pn(pn) unless pn.type == 'helper' @set_pn_root(pn) @_super(pn) # ### # ### Set Owner in Parsed Name Object (pn). # ### set_pn_root: (pn) -> return if ember.isBlank(pn.root) switch pn.type when 'helper' then @set_owner(pn, '--') else @set_owner(pn, '__') set_owner: (pn, match) -> return unless pn.name.match(match) regex = RegExp if pn.name.match("^components/") then "^components/(.*)#{match}" else "^(.*)#{match}" pn_match = pn.name.match(regex) return if ember.isBlank(pn_match) key = pn_match[1] key_replace = "#{key}#{match}" @replace_pn(pn, key_replace) key = 'PI:KEY:<KEY>END_PI' if key == '' key = @underscore_string(key) owner = (@engine_owners[key] ?= @get_key_owner(pn, key)) @error_resolve "No owner found for key '#{key}'.\n", pn, match, pn_match if ember.isBlank(owner) prefix = @get_module_prefix(owner) @error_resolve "No prefix found for key '#{key}'.\n", pn, match, pn_match if ember.isBlank(prefix) @set_new_owner(pn, owner, prefix) get_key_owner: (pn, key) -> switch key when 'app' then @get_app_owner(pn) when 'parent' then @get_parent_owner(pn) else @get_engine_owner(pn, key) get_app_owner: (pn) -> root = @get_owner(pn.root) router = root.lookup('router:main') return null if ember.isBlank(router) @get_owner(router) get_parent_owner: (pn) -> @get_owner(pn.root) get_engine_owner: (pn, key) -> mod_prefix = key.dasherize() @find_ancestor_engine(pn.root, mod_prefix) find_ancestor_engine: (owner, mod_prefix) -> return null unless owner return owner if mod_prefix == @get_module_prefix(owner) parent = @get_owner(owner) return null unless parent @find_ancestor_engine(parent, mod_prefix) # ### # ### Helpers. # ### get_owner: (current) -> ember.getOwner(current) get_module_prefix: (owner) -> owner and (owner.modulePrefix or owner.application?.modulePrefix or owner.base?.modulePrefix) set_new_owner: (pn, root, prefix) -> pn.root = root pn.prefix = prefix replace_pn: (pn, match) -> pn[prop] = pn[prop].replace(match, '') for prop in @name_variables underscore_pn: (pn) -> pn[prop] = @underscore_string(pn[prop]) for prop in @name_variables underscore_string: (val) -> (val and ember.String.underscore(val)) or '' error_resolve: (args...) -> util.error @, args..., @ debug_pn: (pn, title='') -> console.warn title keys = util.hash_keys(pn).sort() console.info key, ' -> ', pn[key] for key in keys
[ { "context": "s file is part of the Konsserto package.\n *\n * (c) Marvin Frachet <marvin@konsserto.com>\n *\n * For the full copyrig", "end": 75, "score": 0.9998835325241089, "start": 61, "tag": "NAME", "value": "Marvin Frachet" }, { "context": " the Konsserto package.\n *\n * (c) M...
node_modules/konsserto/lib/src/Konsserto/Component/Stopwatch/Period.coffee
konsserto/konsserto
2
### * This file is part of the Konsserto package. * * (c) Marvin Frachet <marvin@konsserto.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### # Period # # @author Marvin Frachet <marvin@konsserto.com> class Period # Class constructor # @param {Number} startTime The start time of the period constructor: (@startTime)-> @endTime = new Date().getTime() # Get the duration of the current period # @return {Number} Return the duration of the period getDuration: ()-> return @endTime - @startTime # Get the start time of the current period # @return {Number} Return the start time of the period getStartTime: ()-> return @startTime # Get the end time of the current period # @return {Number} Return the end time of the period getEndTime: ()-> return @endTime module.exports = Period
107825
### * This file is part of the Konsserto package. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### # Period # # @author <NAME> <<EMAIL>> class Period # Class constructor # @param {Number} startTime The start time of the period constructor: (@startTime)-> @endTime = new Date().getTime() # Get the duration of the current period # @return {Number} Return the duration of the period getDuration: ()-> return @endTime - @startTime # Get the start time of the current period # @return {Number} Return the start time of the period getStartTime: ()-> return @startTime # Get the end time of the current period # @return {Number} Return the end time of the period getEndTime: ()-> return @endTime module.exports = Period
true
### * This file is part of the Konsserto package. * * (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### # Period # # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> class Period # Class constructor # @param {Number} startTime The start time of the period constructor: (@startTime)-> @endTime = new Date().getTime() # Get the duration of the current period # @return {Number} Return the duration of the period getDuration: ()-> return @endTime - @startTime # Get the start time of the current period # @return {Number} Return the start time of the period getStartTime: ()-> return @startTime # Get the end time of the current period # @return {Number} Return the end time of the period getEndTime: ()-> return @endTime module.exports = Period
[ { "context": "xmpp_client = new xmpp.Client({jid: jid, password: password, host: server, port: port });\n\n message_handler ", "end": 646, "score": 0.9990456700325012, "start": 638, "tag": "PASSWORD", "value": "password" } ]
src/scripts/gtalk.coffee
aroben/hubot-scripts
1
# Send gtalk messages to channels via hubot # Setup instructions: # # Add to packages.json # "node-xmpp": "0.3.2" module.exports = (robot) -> jid = process.env.GTALK_ID password = process.env.GTALK_PASSWORD online_announce = process.env.GTALK_ONLINE_ANNOUNCE presence = process.env.GTALK_PRESENCE || "Echoing to campfire" server = process.env.GTALK_SERVER || "talk.google.com" port = process.env.GTALK_PORT || 5222 room = process.env.GTALK_ROOM xmpp = require 'node-xmpp' # Establish a connection xmpp_client = new xmpp.Client({jid: jid, password: password, host: server, port: port }); message_handler = (stanza) -> # Important: never reply to errors! if stanza.is('message') and stanza.attrs.type != 'error' message_body_element = stanza.getChild('body'); if message_body_element robot.send { room: room }, "From: " + stanza.attrs.from + " " + message_body_element.getText() online_handler = -> xmpp_client.send(new xmpp.Element('presence', {}).c('show').t('chat').up().c('status').t(presence)); if (online_announce) robot.send { room: room }, online_announce error_handler = (error) -> robot.send { room: room }, "Caught an error " + error xmpp_client.on('online', online_handler) xmpp_client.on('stanza', message_handler) xmpp_client.on('error', error_handler)
65190
# Send gtalk messages to channels via hubot # Setup instructions: # # Add to packages.json # "node-xmpp": "0.3.2" module.exports = (robot) -> jid = process.env.GTALK_ID password = process.env.GTALK_PASSWORD online_announce = process.env.GTALK_ONLINE_ANNOUNCE presence = process.env.GTALK_PRESENCE || "Echoing to campfire" server = process.env.GTALK_SERVER || "talk.google.com" port = process.env.GTALK_PORT || 5222 room = process.env.GTALK_ROOM xmpp = require 'node-xmpp' # Establish a connection xmpp_client = new xmpp.Client({jid: jid, password: <PASSWORD>, host: server, port: port }); message_handler = (stanza) -> # Important: never reply to errors! if stanza.is('message') and stanza.attrs.type != 'error' message_body_element = stanza.getChild('body'); if message_body_element robot.send { room: room }, "From: " + stanza.attrs.from + " " + message_body_element.getText() online_handler = -> xmpp_client.send(new xmpp.Element('presence', {}).c('show').t('chat').up().c('status').t(presence)); if (online_announce) robot.send { room: room }, online_announce error_handler = (error) -> robot.send { room: room }, "Caught an error " + error xmpp_client.on('online', online_handler) xmpp_client.on('stanza', message_handler) xmpp_client.on('error', error_handler)
true
# Send gtalk messages to channels via hubot # Setup instructions: # # Add to packages.json # "node-xmpp": "0.3.2" module.exports = (robot) -> jid = process.env.GTALK_ID password = process.env.GTALK_PASSWORD online_announce = process.env.GTALK_ONLINE_ANNOUNCE presence = process.env.GTALK_PRESENCE || "Echoing to campfire" server = process.env.GTALK_SERVER || "talk.google.com" port = process.env.GTALK_PORT || 5222 room = process.env.GTALK_ROOM xmpp = require 'node-xmpp' # Establish a connection xmpp_client = new xmpp.Client({jid: jid, password: PI:PASSWORD:<PASSWORD>END_PI, host: server, port: port }); message_handler = (stanza) -> # Important: never reply to errors! if stanza.is('message') and stanza.attrs.type != 'error' message_body_element = stanza.getChild('body'); if message_body_element robot.send { room: room }, "From: " + stanza.attrs.from + " " + message_body_element.getText() online_handler = -> xmpp_client.send(new xmpp.Element('presence', {}).c('show').t('chat').up().c('status').t(presence)); if (online_announce) robot.send { room: room }, online_announce error_handler = (error) -> robot.send { room: room }, "Caught an error " + error xmpp_client.on('online', online_handler) xmpp_client.on('stanza', message_handler) xmpp_client.on('error', error_handler)
[ { "context": "gs = [{\n \"id\": 1,\n \"body\": \"Geppetto, a poor old wood carver, was making a puppet from", "end": 449, "score": 0.9605017900466919, "start": 441, "tag": "NAME", "value": "Geppetto" }, { "context": "y,” he said to the puppet, “and I shall call ...
app/scripts/controllers/main.coffee
djbuen/matchmove
0
'use strict' angular.module('slick') .controller 'MainCtrl', ($scope, $timeout, $cookies, $cookieStore) -> $scope.profile = { countPosts: 4, countLikes: 1, countComments: 4 } $timeout(() -> x = $cookieStore.get('test') console.log(x) if x != undefined $scope.awesomeThings = x else $scope.awesomeThings = [{ "id": 1, "body": "Geppetto, a poor old wood carver, was making a puppet from a tree branch. “You shall be my little boy,” he said to the puppet, “and I shall call you ‘Pinocchio’.” He worked for hours, carefully carving each detail. When he reached the mouth, the puppet started making faces at Geppetto. “Stop that, you naughty boy,” Geppetto scolded, “Stop that at once !” “I won’t stop !” cried Pinocchio.", "comments": [ { "id": 1, "comment": "Ohh poor boy pinocchio...." } ] }, { "id": 2, "body": "“Of course I can, silly,” said the puppet. “You’ve given me a mouth to talk with.” Pinocchio rose to his feet and danced on the table top. “Look what I can do !” he squealed.", "comments": [ { "id": 1, "comment": "Pinocchio tries to rationalize" } ] }, { "id": 3, "body": "“Pinocchio, this is not the time to dance,” Geppetto explained. “You must get a good night’s rest. Tomorrow you will start going to school with the real boys. You will learn many things, including how to behave.”", "comments": [ { "id": 1, "comment": "That's right!" } ] }, { "id": 4, "body": "“Get off my stage,” roared the Puppet Master. Then he noticed how much the crowd liked Pinocchio. He did not say anything and let Pinocchio stay. “Here, you’ve earned five copper coins,” the Puppet Master told Pinocchio.", "comments": [ { "id": 1, "comment": "Earned it!" } ] } ] ,1000) $scope.breakpoints = [ breakpoint: 768 settings: slidesToShow: 2 slidesToScroll: 2 , breakpoint: 480 settings: slidesToShow: 1 slidesToScroll: 1 ] $scope.addLikes = -> $scope.profile.countLikes++
6269
'use strict' angular.module('slick') .controller 'MainCtrl', ($scope, $timeout, $cookies, $cookieStore) -> $scope.profile = { countPosts: 4, countLikes: 1, countComments: 4 } $timeout(() -> x = $cookieStore.get('test') console.log(x) if x != undefined $scope.awesomeThings = x else $scope.awesomeThings = [{ "id": 1, "body": "<NAME>, a poor old wood carver, was making a puppet from a tree branch. “You shall be my little boy,” he said to the puppet, “and I shall call you ‘<NAME>’.” He worked for hours, carefully carving each detail. When he reached the mouth, the puppet started making faces at Geppetto. “Stop that, you naughty boy,” Geppetto scolded, “Stop that at once !” “I won’t stop !” cried <NAME>.", "comments": [ { "id": 1, "comment": "Ohh poor boy pin<NAME>io...." } ] }, { "id": 2, "body": "“Of course I can, silly,” said the puppet. “You’ve given me a mouth to talk with.” <NAME> rose to his feet and danced on the table top. “Look what I can do !” he squealed.", "comments": [ { "id": 1, "comment": "Pin<NAME>chio tries to rationalize" } ] }, { "id": 3, "body": "“<NAME>, this is not the time to dance,” Geppetto explained. “You must get a good night’s rest. Tomorrow you will start going to school with the real boys. You will learn many things, including how to behave.”", "comments": [ { "id": 1, "comment": "That's right!" } ] }, { "id": 4, "body": "“Get off my stage,” roared the Puppet Master. Then he noticed how much the crowd liked <NAME>. He did not say anything and let <NAME> stay. “Here, you’ve earned five copper coins,” the Puppet Master told <NAME>io.", "comments": [ { "id": 1, "comment": "Earned it!" } ] } ] ,1000) $scope.breakpoints = [ breakpoint: 768 settings: slidesToShow: 2 slidesToScroll: 2 , breakpoint: 480 settings: slidesToShow: 1 slidesToScroll: 1 ] $scope.addLikes = -> $scope.profile.countLikes++
true
'use strict' angular.module('slick') .controller 'MainCtrl', ($scope, $timeout, $cookies, $cookieStore) -> $scope.profile = { countPosts: 4, countLikes: 1, countComments: 4 } $timeout(() -> x = $cookieStore.get('test') console.log(x) if x != undefined $scope.awesomeThings = x else $scope.awesomeThings = [{ "id": 1, "body": "PI:NAME:<NAME>END_PI, a poor old wood carver, was making a puppet from a tree branch. “You shall be my little boy,” he said to the puppet, “and I shall call you ‘PI:NAME:<NAME>END_PI’.” He worked for hours, carefully carving each detail. When he reached the mouth, the puppet started making faces at Geppetto. “Stop that, you naughty boy,” Geppetto scolded, “Stop that at once !” “I won’t stop !” cried PI:NAME:<NAME>END_PI.", "comments": [ { "id": 1, "comment": "Ohh poor boy pinPI:NAME:<NAME>END_PIio...." } ] }, { "id": 2, "body": "“Of course I can, silly,” said the puppet. “You’ve given me a mouth to talk with.” PI:NAME:<NAME>END_PI rose to his feet and danced on the table top. “Look what I can do !” he squealed.", "comments": [ { "id": 1, "comment": "PinPI:NAME:<NAME>END_PIchio tries to rationalize" } ] }, { "id": 3, "body": "“PI:NAME:<NAME>END_PI, this is not the time to dance,” Geppetto explained. “You must get a good night’s rest. Tomorrow you will start going to school with the real boys. You will learn many things, including how to behave.”", "comments": [ { "id": 1, "comment": "That's right!" } ] }, { "id": 4, "body": "“Get off my stage,” roared the Puppet Master. Then he noticed how much the crowd liked PI:NAME:<NAME>END_PI. He did not say anything and let PI:NAME:<NAME>END_PI stay. “Here, you’ve earned five copper coins,” the Puppet Master told PI:NAME:<NAME>END_PIio.", "comments": [ { "id": 1, "comment": "Earned it!" } ] } ] ,1000) $scope.breakpoints = [ breakpoint: 768 settings: slidesToShow: 2 slidesToScroll: 2 , breakpoint: 480 settings: slidesToShow: 1 slidesToScroll: 1 ] $scope.addLikes = -> $scope.profile.countLikes++
[ { "context": "TIALS\nmongoose.connect \"mongodb://\"+mongoCred+\n\t\"@lykov.tech:27017/goalnet\"\n\nsched = new SchedNode(app)\ngoal =", "end": 509, "score": 0.8885356783866882, "start": 499, "tag": "EMAIL", "value": "lykov.tech" } ]
server/DB/sched/test/schedule.coffee
DaniloZZZ/GoalNet
0
baseTests = require('../../test/baseNode.coffee') SchedNode =require '../schedNode.coffee' GoalNode =require '../../goal/goalNode.coffee' chai = require 'chai' chai.should() express = require 'express' mongoose = require('mongoose') log4js = require 'log4js' logger = log4js.getLogger('test') logger.level = 'debug' # configure a testing server app = express() app.use express.json() app.use express.urlencoded() mongoCred=process.env.MONGO_CREDENTIALS mongoose.connect "mongodb://"+mongoCred+ "@lykov.tech:27017/goalnet" sched = new SchedNode(app) goal = new GoalNode(app) port = 3030 host = 'localhost' endpoint = "http://#{host}:#{port}" server=null start=()-> server = app.listen port, -> logger.info 'Test app is listening '+ endpoint return # Start testing describe 'Schedule', -> before start after ()->server.close() sched_= {} describe 'basics', -> it 'should have an appropriate endpoint',-> sched.path.should.equal '/schedule' it 'should save schedule',(done)-> baseTests.set(sched,props: type:'test')() .then (u)=> sched_=u done() return it 'should get schedule',()-> baseTests.get(sched,id:sched_._id)() it 'should delete schedule',()-> baseTests.delete(sched,id:sched_._id)()
173157
baseTests = require('../../test/baseNode.coffee') SchedNode =require '../schedNode.coffee' GoalNode =require '../../goal/goalNode.coffee' chai = require 'chai' chai.should() express = require 'express' mongoose = require('mongoose') log4js = require 'log4js' logger = log4js.getLogger('test') logger.level = 'debug' # configure a testing server app = express() app.use express.json() app.use express.urlencoded() mongoCred=process.env.MONGO_CREDENTIALS mongoose.connect "mongodb://"+mongoCred+ "@<EMAIL>:27017/goalnet" sched = new SchedNode(app) goal = new GoalNode(app) port = 3030 host = 'localhost' endpoint = "http://#{host}:#{port}" server=null start=()-> server = app.listen port, -> logger.info 'Test app is listening '+ endpoint return # Start testing describe 'Schedule', -> before start after ()->server.close() sched_= {} describe 'basics', -> it 'should have an appropriate endpoint',-> sched.path.should.equal '/schedule' it 'should save schedule',(done)-> baseTests.set(sched,props: type:'test')() .then (u)=> sched_=u done() return it 'should get schedule',()-> baseTests.get(sched,id:sched_._id)() it 'should delete schedule',()-> baseTests.delete(sched,id:sched_._id)()
true
baseTests = require('../../test/baseNode.coffee') SchedNode =require '../schedNode.coffee' GoalNode =require '../../goal/goalNode.coffee' chai = require 'chai' chai.should() express = require 'express' mongoose = require('mongoose') log4js = require 'log4js' logger = log4js.getLogger('test') logger.level = 'debug' # configure a testing server app = express() app.use express.json() app.use express.urlencoded() mongoCred=process.env.MONGO_CREDENTIALS mongoose.connect "mongodb://"+mongoCred+ "@PI:EMAIL:<EMAIL>END_PI:27017/goalnet" sched = new SchedNode(app) goal = new GoalNode(app) port = 3030 host = 'localhost' endpoint = "http://#{host}:#{port}" server=null start=()-> server = app.listen port, -> logger.info 'Test app is listening '+ endpoint return # Start testing describe 'Schedule', -> before start after ()->server.close() sched_= {} describe 'basics', -> it 'should have an appropriate endpoint',-> sched.path.should.equal '/schedule' it 'should save schedule',(done)-> baseTests.set(sched,props: type:'test')() .then (u)=> sched_=u done() return it 'should get schedule',()-> baseTests.get(sched,id:sched_._id)() it 'should delete schedule',()-> baseTests.delete(sched,id:sched_._id)()
[ { "context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.", "end": 197, "score": 0.9998785257339478, "start": 180, "tag": "NAME", "value": "Benjamin Blundell" }, { "context": " PXL.js\n ...
examples/md5_model.coffee
OniDaito/pxljs
1
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js Benjamin Blundell - ben@pxljs.com http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### class MD5Example init : () -> @top_node = new PXL.Node() # Add a normal camera @c = new PXL.Camera.MousePerspCamera new PXL.Math.Vec3(0,0,25) @top_node.add @c @ambientlight = new PXL.Light.AmbientLight new PXL.Colour.RGB(0.1, 0.1, 0.1) @light = new PXL.Light.PointLight new PXL.Math.Vec3(0.0,10.0,10.0), new PXL.Colour.RGB(0.5,0.3,0.3) @light2 = new PXL.Light.PointLight new PXL.Math.Vec3(-10.0,5.0,10.0), new PXL.Colour.RGB(0.0,0.9,0.9) cuboid = new PXL.Geometry.Cuboid new PXL.Math.Vec3 1,1,1 cuboid_node = new PXL.Node cuboid, new PXL.Material.NormalMaterial() cuboid_node.matrix.translate @light.pos @top_node.add @light @top_node.add @ambientlight @top_node.add cuboid_node # Create a promise that resolves if the MD5 Model loads correctly @promise = new PXL.Util.Promise() @promise.then () => g.matrix.rotate new PXL.Math.Vec3(1,0,0), -0.5 * PXL.Math.PI g.matrix.scale new PXL.Math.Vec3 0.1, 0.1, 0.1 @top_node.add g # Create shaders once everything has loaded uber = new PXL.GL.UberShader(@top_node) @top_node.add uber @g = g GL.enable(GL.CULL_FACE) GL.cullFace(GL.BACK) GL.enable(GL.DEPTH_TEST) # Create a new model, passing in the promise g = new PXL.Import.MD5Model "../models/hellknight/hellknight.md5mesh", @promise draw : () -> GL.clearColor(0.95, 0.95, 0.95, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) @top_node.draw() # Move the bone around if we've loaded the model if @g? bone = @g.skeleton.getBoneByName "luparm" q = PXL.Math.Quaternion.fromRotations 0,0.001,0 bone.rotate q example = new MD5Example() params = canvas : 'webgl-canvas' context : example init : example.init draw : example.draw debug : true cgl = new PXL.App params
92677
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js <NAME> - <EMAIL> http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### class MD5Example init : () -> @top_node = new PXL.Node() # Add a normal camera @c = new PXL.Camera.MousePerspCamera new PXL.Math.Vec3(0,0,25) @top_node.add @c @ambientlight = new PXL.Light.AmbientLight new PXL.Colour.RGB(0.1, 0.1, 0.1) @light = new PXL.Light.PointLight new PXL.Math.Vec3(0.0,10.0,10.0), new PXL.Colour.RGB(0.5,0.3,0.3) @light2 = new PXL.Light.PointLight new PXL.Math.Vec3(-10.0,5.0,10.0), new PXL.Colour.RGB(0.0,0.9,0.9) cuboid = new PXL.Geometry.Cuboid new PXL.Math.Vec3 1,1,1 cuboid_node = new PXL.Node cuboid, new PXL.Material.NormalMaterial() cuboid_node.matrix.translate @light.pos @top_node.add @light @top_node.add @ambientlight @top_node.add cuboid_node # Create a promise that resolves if the MD5 Model loads correctly @promise = new PXL.Util.Promise() @promise.then () => g.matrix.rotate new PXL.Math.Vec3(1,0,0), -0.5 * PXL.Math.PI g.matrix.scale new PXL.Math.Vec3 0.1, 0.1, 0.1 @top_node.add g # Create shaders once everything has loaded uber = new PXL.GL.UberShader(@top_node) @top_node.add uber @g = g GL.enable(GL.CULL_FACE) GL.cullFace(GL.BACK) GL.enable(GL.DEPTH_TEST) # Create a new model, passing in the promise g = new PXL.Import.MD5Model "../models/hellknight/hellknight.md5mesh", @promise draw : () -> GL.clearColor(0.95, 0.95, 0.95, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) @top_node.draw() # Move the bone around if we've loaded the model if @g? bone = @g.skeleton.getBoneByName "luparm" q = PXL.Math.Quaternion.fromRotations 0,0.001,0 bone.rotate q example = new MD5Example() params = canvas : 'webgl-canvas' context : example init : example.init draw : example.draw debug : true cgl = new PXL.App params
true
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### class MD5Example init : () -> @top_node = new PXL.Node() # Add a normal camera @c = new PXL.Camera.MousePerspCamera new PXL.Math.Vec3(0,0,25) @top_node.add @c @ambientlight = new PXL.Light.AmbientLight new PXL.Colour.RGB(0.1, 0.1, 0.1) @light = new PXL.Light.PointLight new PXL.Math.Vec3(0.0,10.0,10.0), new PXL.Colour.RGB(0.5,0.3,0.3) @light2 = new PXL.Light.PointLight new PXL.Math.Vec3(-10.0,5.0,10.0), new PXL.Colour.RGB(0.0,0.9,0.9) cuboid = new PXL.Geometry.Cuboid new PXL.Math.Vec3 1,1,1 cuboid_node = new PXL.Node cuboid, new PXL.Material.NormalMaterial() cuboid_node.matrix.translate @light.pos @top_node.add @light @top_node.add @ambientlight @top_node.add cuboid_node # Create a promise that resolves if the MD5 Model loads correctly @promise = new PXL.Util.Promise() @promise.then () => g.matrix.rotate new PXL.Math.Vec3(1,0,0), -0.5 * PXL.Math.PI g.matrix.scale new PXL.Math.Vec3 0.1, 0.1, 0.1 @top_node.add g # Create shaders once everything has loaded uber = new PXL.GL.UberShader(@top_node) @top_node.add uber @g = g GL.enable(GL.CULL_FACE) GL.cullFace(GL.BACK) GL.enable(GL.DEPTH_TEST) # Create a new model, passing in the promise g = new PXL.Import.MD5Model "../models/hellknight/hellknight.md5mesh", @promise draw : () -> GL.clearColor(0.95, 0.95, 0.95, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) @top_node.draw() # Move the bone around if we've loaded the model if @g? bone = @g.skeleton.getBoneByName "luparm" q = PXL.Math.Quaternion.fromRotations 0,0.001,0 bone.rotate q example = new MD5Example() params = canvas : 'webgl-canvas' context : example init : example.init draw : example.draw debug : true cgl = new PXL.App params
[ { "context": "s MapManager\n @version: '0.0.11'\n @apiKey: \"AIzaSyBQxopw4OR08VaLVtHaY4XEXWk3dvLSj5k\"\n @currentPOI: null\n @config:\n target:", "end": 740, "score": 0.9997548460960388, "start": 701, "tag": "KEY", "value": "AIzaSyBQxopw4OR08VaLVtHaY4XEXWk3dvLSj5k" } ]
app/assets/javascripts/lib/components/map_manager.coffee
evantravers/rizzo
1
# MapManager (lp.MapManager) # A simple map manager to orchestrate the async load of the google map lib and initialize the lodging map. # # Arguments # No need for arguments, however (and for now) it reads the latitude, longitude, title, zoom, ... # from the lp.map object. For further details on this object run console.log(lp.map) on the # browser inspector # # Example: # It only loads the lib and instantiates the map if lp.map is defined # # if(lp.map){ # self.mapWidget = new MapManager({}); # } # define ['jquery', 'lib/components/map_styles', 'lib/utils/css_helper', 'polyfills/scrollIntoViewIfNeeded'], ($, mapStyles, cssHelper) -> class MapManager @version: '0.0.11' @apiKey: "AIzaSyBQxopw4OR08VaLVtHaY4XEXWk3dvLSj5k" @currentPOI: null @config: target: '#js-map-canvas' poiElements = $() @pins = {} topic = $(document.documentElement).data('topic') mapManager = this constructor: (config) -> $.extend MapManager.config, config if config and config.loadSelector $(config.loadSelector).one(config.loadEventType, MapManager.loadLib) else MapManager.loadLib() if config and config.centerTrigger $(document).on 'change', config.centerTrigger, => map = MapManager.map overlay = new google.maps.OverlayView() overlay.draw = -> overlay.setMap map setTimeout -> oldCenter = map.getCenter() google.maps.event.trigger(map, "resize") newCenter = map.getCenter() projection = overlay.getProjection() oldCenterPoint = projection.fromLatLngToDivPixel(oldCenter) newCenterPoint = projection.fromLatLngToDivPixel(newCenter) # Move the y axis by the difference between the old and new center points. newCenterPoint.y -= newCenterPoint.y - oldCenterPoint.y map.panTo(projection.fromDivPixelToLatLng(newCenterPoint)) , config.centerDelay || 0 @loadLib: => return if @map # pointer to google-maps callback, not possible inside the regular closure environment lp.MapManager = MapManager script = document.createElement('script') script.src = "http://maps.googleapis.com/maps/api/js?key=#{@apiKey}&sensor=false&callback=lp.MapManager.initMap" document.body.appendChild(script) @initMap: => if not (lp and lp.lodging and lp.lodging.map) or lp.lodging.map.genericCoordinates return $(@config.target).removeClass('is-loading') @config = $.extend({listener: this}, lp.lodging.map, @config) @config.mapCanvas = $(@config.target) poiElements = @config.mapCanvas.parent().find('.js-poi') buildMap() setLocationMarker() addPins() poiElements.on('click', poiSelected) @config.mapCanvas.removeClass('is-loading') buildMap = () => mapOptions = zoom: @config.zoom center: new google.maps.LatLng(@config.latitude, @config.longitude) mapTypeId: google.maps.MapTypeId.ROADMAP if @config.minimalUI $.extend(mapOptions, mapTypeControl: false, panControl: false, streetViewControl: false, zoomControlOptions: style: google.maps.ZoomControlStyle.SMALL ) @map = new google.maps.Map(@config.mapCanvas.get(0), mapOptions) @map.setOptions(styles: mapStyles) # this needs to be down here so it isn't loaded until we have a google setLocationMarker = => require ['google-maps-infobox'], => locationTitle = if topic is 'lodging' then @config.title else 'Location' locationAddress = @config.lodgingLocation or lp.lodging.address[0] or '' infobox = new InfoBox alignBottom: true boxStyle: maxWidth: 350 textOverflow: 'ellipsis' whiteSpace: 'nowrap' width: 'auto' closeBoxURL: '' content: "<div class='infobox--location icon--tapered-arrow-down--after icon--white--after'> <p class='copy--h3 infobox__title text-icon icon--place--pin--before icon--lp-blue--before'>#{locationTitle}</p> <p class='copy--body'> #{locationAddress or ''} <span class='infobox__interesting-places'> &middot; <label class='infobox__link--interesting-places js-resizer' for='js-resize'> interesting places nearby </label> </span> </p></div>" disableAutoPan: true maxWidth: 350 zIndex: 50 marker = new google.maps.Marker icon: getIcon('location-marker', 'dot') position: new google.maps.LatLng(@config.latitude, @config.longitude) map: @map title: @config.title optimized: @config.optimized infobox.open(@map, marker) createMarkerImage = (topic, size) -> cssInfo = cssHelper.propertiesFor( "icon-poi-#{topic}-#{size} icon-poi-#{size}", [ 'background-position' 'background-position-x' 'background-position-y' 'background-image' 'height' 'width' ] ) url = cssHelper.extractUrl(cssInfo['background-image']) width = parseInt(cssInfo['width']) height = parseInt(cssInfo['height']) # browsers don't all agree on background position (ie, ff) if cssInfo['background-position'] is undefined x = parseInt(cssInfo['background-position-x']) y = parseInt(cssInfo['background-position-y']) else x = parseInt(cssInfo['background-position'].split(' ')[0]) y = parseInt(cssInfo['background-position'].split(' ')[1]) new google.maps.MarkerImage( url, new google.maps.Size(width, height), new google.maps.Point(-x, -y) ) getIcon = (topic, size='small') => @markerImages ?= {} topic = 'hotel' if topic is 'lodging' @markerImages[topic + '-' + size] ?= createMarkerImage(topic, size) mapMarker = (poi) => new google.maps.Marker ( animation: google.maps.Animation.DROP position: new google.maps.LatLng(poi.locationLatitude, poi.locationLongitude) map: @map title: poi.name description: poi.description optimized: @config.optimized id: poi.slug category: poi.topic icon: getIcon(poi.topic) ) addPins = () => markerDelay = 0 poiElements.each (_, poi) => poi = $(poi).data() setTimeout => pin = mapMarker(poi) pin.set('targetMap', @config.mapCanvas) google.maps.event.addListener(pin, 'click', poiSelected) @pins[poi.slug] = pin , markerDelay clearTimeout(@timeout) @timeout = setTimeout -> markerDelay = 0 , 150 markerDelay += 100 highlightPin = (id) => for slug, pin of @pins if slug is id pin.setIcon(getIcon(pin.category, 'large')) @map.panTo(pin.getPosition()) else pin.setIcon(getIcon(pin.category)) resetPins = => for slug, pin of @pins pin.setIcon(getIcon(pin.category)) @map.panTo(new google.maps.LatLng(@config.latitude, @config.longitude)) poiSelected = (obj) -> # so, this gets called by either the list item or the pin, which both have a different event attached # (but want the same result) # during testing, however, it gets called without an event. # in that case, 'this' is set to the google maps marker object # which is the only instance in which this could have a .id if @id id = @id map = @targetMap else # when called by pinclick, the Marker event will have an obj.Va (which is actually the event) # when called by list-item click, obj will be a normal event object targetElement = if obj.Va then $(obj.Va.target) else $(obj.target) id = @id or targetElement.closest('[data-slug]').data('slug') map = targetElement.closest('.map') highlightPois(id: id, map: map) highlightPois = ({id, map}) -> poiElements.removeClass('nearby-pois__poi--highlighted') $resizer = map.find('.js-resizer') resizeCheckbox = document.getElementById($resizer.attr('for')) if resizeCheckbox and not resizeCheckbox.checked $resizer.click() if id is mapManager.currentPOI mapManager.currentPOI = null map.removeClass('map--has-focus') resetPins(); else mapManager.currentPOI = id map.addClass('map--has-focus') element = poiElements.filter("[data-slug='#{id}']").addClass('nearby-pois__poi--highlighted').get(0) element.scrollIntoViewIfNeeded(true, true) highlightPin(id)
95561
# MapManager (lp.MapManager) # A simple map manager to orchestrate the async load of the google map lib and initialize the lodging map. # # Arguments # No need for arguments, however (and for now) it reads the latitude, longitude, title, zoom, ... # from the lp.map object. For further details on this object run console.log(lp.map) on the # browser inspector # # Example: # It only loads the lib and instantiates the map if lp.map is defined # # if(lp.map){ # self.mapWidget = new MapManager({}); # } # define ['jquery', 'lib/components/map_styles', 'lib/utils/css_helper', 'polyfills/scrollIntoViewIfNeeded'], ($, mapStyles, cssHelper) -> class MapManager @version: '0.0.11' @apiKey: "<KEY>" @currentPOI: null @config: target: '#js-map-canvas' poiElements = $() @pins = {} topic = $(document.documentElement).data('topic') mapManager = this constructor: (config) -> $.extend MapManager.config, config if config and config.loadSelector $(config.loadSelector).one(config.loadEventType, MapManager.loadLib) else MapManager.loadLib() if config and config.centerTrigger $(document).on 'change', config.centerTrigger, => map = MapManager.map overlay = new google.maps.OverlayView() overlay.draw = -> overlay.setMap map setTimeout -> oldCenter = map.getCenter() google.maps.event.trigger(map, "resize") newCenter = map.getCenter() projection = overlay.getProjection() oldCenterPoint = projection.fromLatLngToDivPixel(oldCenter) newCenterPoint = projection.fromLatLngToDivPixel(newCenter) # Move the y axis by the difference between the old and new center points. newCenterPoint.y -= newCenterPoint.y - oldCenterPoint.y map.panTo(projection.fromDivPixelToLatLng(newCenterPoint)) , config.centerDelay || 0 @loadLib: => return if @map # pointer to google-maps callback, not possible inside the regular closure environment lp.MapManager = MapManager script = document.createElement('script') script.src = "http://maps.googleapis.com/maps/api/js?key=#{@apiKey}&sensor=false&callback=lp.MapManager.initMap" document.body.appendChild(script) @initMap: => if not (lp and lp.lodging and lp.lodging.map) or lp.lodging.map.genericCoordinates return $(@config.target).removeClass('is-loading') @config = $.extend({listener: this}, lp.lodging.map, @config) @config.mapCanvas = $(@config.target) poiElements = @config.mapCanvas.parent().find('.js-poi') buildMap() setLocationMarker() addPins() poiElements.on('click', poiSelected) @config.mapCanvas.removeClass('is-loading') buildMap = () => mapOptions = zoom: @config.zoom center: new google.maps.LatLng(@config.latitude, @config.longitude) mapTypeId: google.maps.MapTypeId.ROADMAP if @config.minimalUI $.extend(mapOptions, mapTypeControl: false, panControl: false, streetViewControl: false, zoomControlOptions: style: google.maps.ZoomControlStyle.SMALL ) @map = new google.maps.Map(@config.mapCanvas.get(0), mapOptions) @map.setOptions(styles: mapStyles) # this needs to be down here so it isn't loaded until we have a google setLocationMarker = => require ['google-maps-infobox'], => locationTitle = if topic is 'lodging' then @config.title else 'Location' locationAddress = @config.lodgingLocation or lp.lodging.address[0] or '' infobox = new InfoBox alignBottom: true boxStyle: maxWidth: 350 textOverflow: 'ellipsis' whiteSpace: 'nowrap' width: 'auto' closeBoxURL: '' content: "<div class='infobox--location icon--tapered-arrow-down--after icon--white--after'> <p class='copy--h3 infobox__title text-icon icon--place--pin--before icon--lp-blue--before'>#{locationTitle}</p> <p class='copy--body'> #{locationAddress or ''} <span class='infobox__interesting-places'> &middot; <label class='infobox__link--interesting-places js-resizer' for='js-resize'> interesting places nearby </label> </span> </p></div>" disableAutoPan: true maxWidth: 350 zIndex: 50 marker = new google.maps.Marker icon: getIcon('location-marker', 'dot') position: new google.maps.LatLng(@config.latitude, @config.longitude) map: @map title: @config.title optimized: @config.optimized infobox.open(@map, marker) createMarkerImage = (topic, size) -> cssInfo = cssHelper.propertiesFor( "icon-poi-#{topic}-#{size} icon-poi-#{size}", [ 'background-position' 'background-position-x' 'background-position-y' 'background-image' 'height' 'width' ] ) url = cssHelper.extractUrl(cssInfo['background-image']) width = parseInt(cssInfo['width']) height = parseInt(cssInfo['height']) # browsers don't all agree on background position (ie, ff) if cssInfo['background-position'] is undefined x = parseInt(cssInfo['background-position-x']) y = parseInt(cssInfo['background-position-y']) else x = parseInt(cssInfo['background-position'].split(' ')[0]) y = parseInt(cssInfo['background-position'].split(' ')[1]) new google.maps.MarkerImage( url, new google.maps.Size(width, height), new google.maps.Point(-x, -y) ) getIcon = (topic, size='small') => @markerImages ?= {} topic = 'hotel' if topic is 'lodging' @markerImages[topic + '-' + size] ?= createMarkerImage(topic, size) mapMarker = (poi) => new google.maps.Marker ( animation: google.maps.Animation.DROP position: new google.maps.LatLng(poi.locationLatitude, poi.locationLongitude) map: @map title: poi.name description: poi.description optimized: @config.optimized id: poi.slug category: poi.topic icon: getIcon(poi.topic) ) addPins = () => markerDelay = 0 poiElements.each (_, poi) => poi = $(poi).data() setTimeout => pin = mapMarker(poi) pin.set('targetMap', @config.mapCanvas) google.maps.event.addListener(pin, 'click', poiSelected) @pins[poi.slug] = pin , markerDelay clearTimeout(@timeout) @timeout = setTimeout -> markerDelay = 0 , 150 markerDelay += 100 highlightPin = (id) => for slug, pin of @pins if slug is id pin.setIcon(getIcon(pin.category, 'large')) @map.panTo(pin.getPosition()) else pin.setIcon(getIcon(pin.category)) resetPins = => for slug, pin of @pins pin.setIcon(getIcon(pin.category)) @map.panTo(new google.maps.LatLng(@config.latitude, @config.longitude)) poiSelected = (obj) -> # so, this gets called by either the list item or the pin, which both have a different event attached # (but want the same result) # during testing, however, it gets called without an event. # in that case, 'this' is set to the google maps marker object # which is the only instance in which this could have a .id if @id id = @id map = @targetMap else # when called by pinclick, the Marker event will have an obj.Va (which is actually the event) # when called by list-item click, obj will be a normal event object targetElement = if obj.Va then $(obj.Va.target) else $(obj.target) id = @id or targetElement.closest('[data-slug]').data('slug') map = targetElement.closest('.map') highlightPois(id: id, map: map) highlightPois = ({id, map}) -> poiElements.removeClass('nearby-pois__poi--highlighted') $resizer = map.find('.js-resizer') resizeCheckbox = document.getElementById($resizer.attr('for')) if resizeCheckbox and not resizeCheckbox.checked $resizer.click() if id is mapManager.currentPOI mapManager.currentPOI = null map.removeClass('map--has-focus') resetPins(); else mapManager.currentPOI = id map.addClass('map--has-focus') element = poiElements.filter("[data-slug='#{id}']").addClass('nearby-pois__poi--highlighted').get(0) element.scrollIntoViewIfNeeded(true, true) highlightPin(id)
true
# MapManager (lp.MapManager) # A simple map manager to orchestrate the async load of the google map lib and initialize the lodging map. # # Arguments # No need for arguments, however (and for now) it reads the latitude, longitude, title, zoom, ... # from the lp.map object. For further details on this object run console.log(lp.map) on the # browser inspector # # Example: # It only loads the lib and instantiates the map if lp.map is defined # # if(lp.map){ # self.mapWidget = new MapManager({}); # } # define ['jquery', 'lib/components/map_styles', 'lib/utils/css_helper', 'polyfills/scrollIntoViewIfNeeded'], ($, mapStyles, cssHelper) -> class MapManager @version: '0.0.11' @apiKey: "PI:KEY:<KEY>END_PI" @currentPOI: null @config: target: '#js-map-canvas' poiElements = $() @pins = {} topic = $(document.documentElement).data('topic') mapManager = this constructor: (config) -> $.extend MapManager.config, config if config and config.loadSelector $(config.loadSelector).one(config.loadEventType, MapManager.loadLib) else MapManager.loadLib() if config and config.centerTrigger $(document).on 'change', config.centerTrigger, => map = MapManager.map overlay = new google.maps.OverlayView() overlay.draw = -> overlay.setMap map setTimeout -> oldCenter = map.getCenter() google.maps.event.trigger(map, "resize") newCenter = map.getCenter() projection = overlay.getProjection() oldCenterPoint = projection.fromLatLngToDivPixel(oldCenter) newCenterPoint = projection.fromLatLngToDivPixel(newCenter) # Move the y axis by the difference between the old and new center points. newCenterPoint.y -= newCenterPoint.y - oldCenterPoint.y map.panTo(projection.fromDivPixelToLatLng(newCenterPoint)) , config.centerDelay || 0 @loadLib: => return if @map # pointer to google-maps callback, not possible inside the regular closure environment lp.MapManager = MapManager script = document.createElement('script') script.src = "http://maps.googleapis.com/maps/api/js?key=#{@apiKey}&sensor=false&callback=lp.MapManager.initMap" document.body.appendChild(script) @initMap: => if not (lp and lp.lodging and lp.lodging.map) or lp.lodging.map.genericCoordinates return $(@config.target).removeClass('is-loading') @config = $.extend({listener: this}, lp.lodging.map, @config) @config.mapCanvas = $(@config.target) poiElements = @config.mapCanvas.parent().find('.js-poi') buildMap() setLocationMarker() addPins() poiElements.on('click', poiSelected) @config.mapCanvas.removeClass('is-loading') buildMap = () => mapOptions = zoom: @config.zoom center: new google.maps.LatLng(@config.latitude, @config.longitude) mapTypeId: google.maps.MapTypeId.ROADMAP if @config.minimalUI $.extend(mapOptions, mapTypeControl: false, panControl: false, streetViewControl: false, zoomControlOptions: style: google.maps.ZoomControlStyle.SMALL ) @map = new google.maps.Map(@config.mapCanvas.get(0), mapOptions) @map.setOptions(styles: mapStyles) # this needs to be down here so it isn't loaded until we have a google setLocationMarker = => require ['google-maps-infobox'], => locationTitle = if topic is 'lodging' then @config.title else 'Location' locationAddress = @config.lodgingLocation or lp.lodging.address[0] or '' infobox = new InfoBox alignBottom: true boxStyle: maxWidth: 350 textOverflow: 'ellipsis' whiteSpace: 'nowrap' width: 'auto' closeBoxURL: '' content: "<div class='infobox--location icon--tapered-arrow-down--after icon--white--after'> <p class='copy--h3 infobox__title text-icon icon--place--pin--before icon--lp-blue--before'>#{locationTitle}</p> <p class='copy--body'> #{locationAddress or ''} <span class='infobox__interesting-places'> &middot; <label class='infobox__link--interesting-places js-resizer' for='js-resize'> interesting places nearby </label> </span> </p></div>" disableAutoPan: true maxWidth: 350 zIndex: 50 marker = new google.maps.Marker icon: getIcon('location-marker', 'dot') position: new google.maps.LatLng(@config.latitude, @config.longitude) map: @map title: @config.title optimized: @config.optimized infobox.open(@map, marker) createMarkerImage = (topic, size) -> cssInfo = cssHelper.propertiesFor( "icon-poi-#{topic}-#{size} icon-poi-#{size}", [ 'background-position' 'background-position-x' 'background-position-y' 'background-image' 'height' 'width' ] ) url = cssHelper.extractUrl(cssInfo['background-image']) width = parseInt(cssInfo['width']) height = parseInt(cssInfo['height']) # browsers don't all agree on background position (ie, ff) if cssInfo['background-position'] is undefined x = parseInt(cssInfo['background-position-x']) y = parseInt(cssInfo['background-position-y']) else x = parseInt(cssInfo['background-position'].split(' ')[0]) y = parseInt(cssInfo['background-position'].split(' ')[1]) new google.maps.MarkerImage( url, new google.maps.Size(width, height), new google.maps.Point(-x, -y) ) getIcon = (topic, size='small') => @markerImages ?= {} topic = 'hotel' if topic is 'lodging' @markerImages[topic + '-' + size] ?= createMarkerImage(topic, size) mapMarker = (poi) => new google.maps.Marker ( animation: google.maps.Animation.DROP position: new google.maps.LatLng(poi.locationLatitude, poi.locationLongitude) map: @map title: poi.name description: poi.description optimized: @config.optimized id: poi.slug category: poi.topic icon: getIcon(poi.topic) ) addPins = () => markerDelay = 0 poiElements.each (_, poi) => poi = $(poi).data() setTimeout => pin = mapMarker(poi) pin.set('targetMap', @config.mapCanvas) google.maps.event.addListener(pin, 'click', poiSelected) @pins[poi.slug] = pin , markerDelay clearTimeout(@timeout) @timeout = setTimeout -> markerDelay = 0 , 150 markerDelay += 100 highlightPin = (id) => for slug, pin of @pins if slug is id pin.setIcon(getIcon(pin.category, 'large')) @map.panTo(pin.getPosition()) else pin.setIcon(getIcon(pin.category)) resetPins = => for slug, pin of @pins pin.setIcon(getIcon(pin.category)) @map.panTo(new google.maps.LatLng(@config.latitude, @config.longitude)) poiSelected = (obj) -> # so, this gets called by either the list item or the pin, which both have a different event attached # (but want the same result) # during testing, however, it gets called without an event. # in that case, 'this' is set to the google maps marker object # which is the only instance in which this could have a .id if @id id = @id map = @targetMap else # when called by pinclick, the Marker event will have an obj.Va (which is actually the event) # when called by list-item click, obj will be a normal event object targetElement = if obj.Va then $(obj.Va.target) else $(obj.target) id = @id or targetElement.closest('[data-slug]').data('slug') map = targetElement.closest('.map') highlightPois(id: id, map: map) highlightPois = ({id, map}) -> poiElements.removeClass('nearby-pois__poi--highlighted') $resizer = map.find('.js-resizer') resizeCheckbox = document.getElementById($resizer.attr('for')) if resizeCheckbox and not resizeCheckbox.checked $resizer.click() if id is mapManager.currentPOI mapManager.currentPOI = null map.removeClass('map--has-focus') resetPins(); else mapManager.currentPOI = id map.addClass('map--has-focus') element = poiElements.filter("[data-slug='#{id}']").addClass('nearby-pois__poi--highlighted').get(0) element.scrollIntoViewIfNeeded(true, true) highlightPin(id)
[ { "context": " d: '1234;4321;5678;8765'\n\n foo: 'Allem'\n\n\n bla:\n metho", "end": 372, "score": 0.9993399977684021, "start": 367, "tag": "NAME", "value": "Allem" } ]
examples/objectmapper/app.coffee
nero-networks/floyd
0
module.exports = running: -> ## given some arbitrary data... data = a: b: [ x: 1 , x: 2 , x: 3 ] c: ['h', 'a', 'l', 'l', 'o'] d: '1234;4321;5678;8765' foo: 'Allem' bla: method1: 'foo_bar_buzz' method2: 'some_other_buzz' nt: wo: rt: 42 ## define a mapping object referencing the data structure's keys as dotted path to the value map = foo: XofAB: ['a.b[0].x', 'a.b[1].x', 'a.b[2].x'] list: 'a.b' obj: 'a.b[1]' char: 'a.foo[3]' numbers: $split: ';': 'a.d' camelized: $camelize: ['a.bla.method1', 'a.bla.method2'] squares: $square: [1, 2, 3, 4, 5] hello: german: $join: '': 'a.c' spanish: $format: '%s%s%s%s': ['a.c[0]', 'a.c[4]', 'a.c[2]', 'a.c[1]'] text: $format: 'Die $1 auf die Frage nach %s ist %s': ['a.foo', 'a.nt.wo.rt'] ## declare some $custom commands in addition to the predefined $split, $join, $format commands = camelize: (value, data, commands)-> out = '' for part in floyd.tools.objects.resolve(value, data, commands).split '_' out += if !out then part else floyd.tools.strings.capitalize part return out square: (value)-> return value * value ## execute mapped = floyd.tools.objects.map data, map, commands ## dump mapped object console.log JSON.stringify mapped, null, 2 ## ... investigate your console output
27058
module.exports = running: -> ## given some arbitrary data... data = a: b: [ x: 1 , x: 2 , x: 3 ] c: ['h', 'a', 'l', 'l', 'o'] d: '1234;4321;5678;8765' foo: '<NAME>' bla: method1: 'foo_bar_buzz' method2: 'some_other_buzz' nt: wo: rt: 42 ## define a mapping object referencing the data structure's keys as dotted path to the value map = foo: XofAB: ['a.b[0].x', 'a.b[1].x', 'a.b[2].x'] list: 'a.b' obj: 'a.b[1]' char: 'a.foo[3]' numbers: $split: ';': 'a.d' camelized: $camelize: ['a.bla.method1', 'a.bla.method2'] squares: $square: [1, 2, 3, 4, 5] hello: german: $join: '': 'a.c' spanish: $format: '%s%s%s%s': ['a.c[0]', 'a.c[4]', 'a.c[2]', 'a.c[1]'] text: $format: 'Die $1 auf die Frage nach %s ist %s': ['a.foo', 'a.nt.wo.rt'] ## declare some $custom commands in addition to the predefined $split, $join, $format commands = camelize: (value, data, commands)-> out = '' for part in floyd.tools.objects.resolve(value, data, commands).split '_' out += if !out then part else floyd.tools.strings.capitalize part return out square: (value)-> return value * value ## execute mapped = floyd.tools.objects.map data, map, commands ## dump mapped object console.log JSON.stringify mapped, null, 2 ## ... investigate your console output
true
module.exports = running: -> ## given some arbitrary data... data = a: b: [ x: 1 , x: 2 , x: 3 ] c: ['h', 'a', 'l', 'l', 'o'] d: '1234;4321;5678;8765' foo: 'PI:NAME:<NAME>END_PI' bla: method1: 'foo_bar_buzz' method2: 'some_other_buzz' nt: wo: rt: 42 ## define a mapping object referencing the data structure's keys as dotted path to the value map = foo: XofAB: ['a.b[0].x', 'a.b[1].x', 'a.b[2].x'] list: 'a.b' obj: 'a.b[1]' char: 'a.foo[3]' numbers: $split: ';': 'a.d' camelized: $camelize: ['a.bla.method1', 'a.bla.method2'] squares: $square: [1, 2, 3, 4, 5] hello: german: $join: '': 'a.c' spanish: $format: '%s%s%s%s': ['a.c[0]', 'a.c[4]', 'a.c[2]', 'a.c[1]'] text: $format: 'Die $1 auf die Frage nach %s ist %s': ['a.foo', 'a.nt.wo.rt'] ## declare some $custom commands in addition to the predefined $split, $join, $format commands = camelize: (value, data, commands)-> out = '' for part in floyd.tools.objects.resolve(value, data, commands).split '_' out += if !out then part else floyd.tools.strings.capitalize part return out square: (value)-> return value * value ## execute mapped = floyd.tools.objects.map data, map, commands ## dump mapped object console.log JSON.stringify mapped, null, 2 ## ... investigate your console output
[ { "context": " <div id=\"turbo-area\" refresh=\"turbo-area\">Hi bob</div>\n </body>\n </html>\n \"\"\"\n\n script_r", "end": 854, "score": 0.677918016910553, "start": 851, "tag": "NAME", "value": "bob" }, { "context": " assert document.body.textContent.indexOf(\"H...
test/javascripts/turbolinks_test.coffee
kurtfunai/turbograft
0
describe 'Turbolinks', -> createTurboNodule = -> $nodule = $("<div>").attr("id", "turbo-area").attr("refresh", "turbo-area") return $nodule[0] url_for = (slug) -> window.location.origin + slug beforeEach -> @server = sinon.fakeServer.create() $("script").attr("data-turbolinks-eval", false) $("#mocha").attr("refresh-never", true) @replaceStateStub = stub(Turbolinks, "replaceState") @pushStateStub = stub(Turbolinks, "pushState") document.body.appendChild(createTurboNodule()) afterEach -> @server.restore() @pushStateStub.restore() @replaceStateStub.restore() $("#turbo-area").remove() html_one = """ <!doctype html> <html> <head> <title>Hi there!</title> </head> <body> <div>YOLO</div> <div id="turbo-area" refresh="turbo-area">Hi bob</div> </body> </html> """ script_response = """ <!doctype html> <html> <head> <title>Hi</title> </head> <body> <script id="turbo-area" refresh="turbo-area">globalStub()</script> </body> </html> """ script_response_turbolinks_eval_false = """ <!doctype html> <html> <head> <title>Hi</title> </head> <body> <script data-turbolinks-eval="false" id="turbo-area" refresh="turbo-area">globalStub()</script> </body> </html> """ response_with_refresh_always = """ <!doctype html> <html> <head> <title>Hi</title> </head> <body> <div id="div1" refresh="div1"> <div id="div2" refresh-always>Refresh-always</div> </div> </body> </html> """ it 'is defined', -> assert Turbolinks describe '#visit', -> it 'returns if pageChangePrevented', -> listener = (event) -> event.preventDefault() assert.equal '/some_request', event.data window.addEventListener('page:before-change', listener) Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} assert.equal 0, @server.requests.length window.removeEventListener('page:before-change', listener) it 'supports passing request headers', -> @server.respondWith([200, { "Content-Type": "text/html" }, "<html>Hello World</html>"]); Turbolinks.visit "/some_request", {headers: {'foo': 'bar', 'fizz': 'buzz'}} @server.respond() assert.equal 1, @server.requests.length assert.equal 'bar', @server.requests[0].requestHeaders['foo'] assert.equal 'buzz', @server.requests[0].requestHeaders['fizz'] describe 'with partial page replacement', -> it 'uses just the part of the response body we supply', -> @server.respondWith([200, { "Content-Type": "text/html" }, html_one]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} @server.respond() assert.equal "Hi there!", document.title assert.equal -1, document.body.textContent.indexOf("YOLO") assert document.body.textContent.indexOf("Hi bob") > 0 assert @pushStateStub.calledOnce assert @pushStateStub.calledWith({turbolinks: true, url: url_for("/some_request")}, "", url_for("/some_request")) assert.equal 0, @replaceStateStub.callCount it 'doesn\'t update the window state if updatePushState is false', -> @server.respondWith([200, { "Content-Type": "text/html" }, html_one]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area'], updatePushState: false} @server.respond() assert.equal "Hi there!", document.title assert.equal -1, document.body.textContent.indexOf("YOLO") assert document.body.textContent.indexOf("Hi bob") > 0 assert @pushStateStub.notCalled assert @replaceStateStub.notCalled it 'calls a user-supplied callback', -> @server.respondWith([200, { "Content-Type": "text/html" }, html_one]); your_callback = stub() Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area'], callback: your_callback} @server.respond() assert your_callback.calledOnce it 'script tags are evaluated when they are the subject of a partial replace', -> window.globalStub = stub() @server.respondWith([200, { "Content-Type": "text/html" }, script_response]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} @server.respond() assert globalStub.calledOnce it 'script tags are not evaluated if they have [data-turbolinks-eval="false"]', -> window.globalStub = stub() @server.respondWith([200, { "Content-Type": "text/html" }, script_response_turbolinks_eval_false]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} @server.respond() assert.equal 0, globalStub.callCount it 'triggers the page:load event with a list of nodes that are new (freshly replaced)', -> $(document).one 'page:load', (event) -> ev = event.originalEvent assert.equal true, ev.data instanceof Array assert.equal 1, ev.data.length node = ev.data[0] assert.equal "turbo-area", node.id assert.equal "turbo-area", node.getAttribute('refresh') @server.respondWith([200, { "Content-Type": "text/html" }, html_one]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} @server.respond() $(document).off 'page:load' it 'does not trigger the page:before-partial-replace event more than once', -> handler = stub() $(document).on 'page:before-partial-replace', -> handler() assert handler.calledOnce @server.respondWith([200, { "Content-Type": "text/html" }, html_one]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} @server.respond() $(document).off 'page:before-partial-replace' it 'replaces and passes through the outermost nodes if a series of nodes got replaced', -> currentBody = """ <div id="div1" refresh="div1"> <div id="div2" refresh-always>Refresh-always</div> </div> """ $("body").append($(currentBody)) $(document).on 'page:before-partial-replace', (ev) -> nodes = ev.originalEvent.data assert.equal 2, nodes.length assert.equal 'div2', nodes[0].id assert.equal 'div1', nodes[1].id $(document).on 'page:load', (ev) -> nodes = ev.originalEvent.data assert.equal 1, nodes.length assert.equal 'div1', nodes[0].id @server.respondWith([200, { "Content-Type": "text/html" }, response_with_refresh_always]); Page.refresh(onlyKeys: ['div1']) @server.respond() $(document).off 'page:before-partial-replace' $(document).off 'page:load' $("#div1").remove()
205250
describe 'Turbolinks', -> createTurboNodule = -> $nodule = $("<div>").attr("id", "turbo-area").attr("refresh", "turbo-area") return $nodule[0] url_for = (slug) -> window.location.origin + slug beforeEach -> @server = sinon.fakeServer.create() $("script").attr("data-turbolinks-eval", false) $("#mocha").attr("refresh-never", true) @replaceStateStub = stub(Turbolinks, "replaceState") @pushStateStub = stub(Turbolinks, "pushState") document.body.appendChild(createTurboNodule()) afterEach -> @server.restore() @pushStateStub.restore() @replaceStateStub.restore() $("#turbo-area").remove() html_one = """ <!doctype html> <html> <head> <title>Hi there!</title> </head> <body> <div>YOLO</div> <div id="turbo-area" refresh="turbo-area">Hi <NAME></div> </body> </html> """ script_response = """ <!doctype html> <html> <head> <title>Hi</title> </head> <body> <script id="turbo-area" refresh="turbo-area">globalStub()</script> </body> </html> """ script_response_turbolinks_eval_false = """ <!doctype html> <html> <head> <title>Hi</title> </head> <body> <script data-turbolinks-eval="false" id="turbo-area" refresh="turbo-area">globalStub()</script> </body> </html> """ response_with_refresh_always = """ <!doctype html> <html> <head> <title>Hi</title> </head> <body> <div id="div1" refresh="div1"> <div id="div2" refresh-always>Refresh-always</div> </div> </body> </html> """ it 'is defined', -> assert Turbolinks describe '#visit', -> it 'returns if pageChangePrevented', -> listener = (event) -> event.preventDefault() assert.equal '/some_request', event.data window.addEventListener('page:before-change', listener) Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} assert.equal 0, @server.requests.length window.removeEventListener('page:before-change', listener) it 'supports passing request headers', -> @server.respondWith([200, { "Content-Type": "text/html" }, "<html>Hello World</html>"]); Turbolinks.visit "/some_request", {headers: {'foo': 'bar', 'fizz': 'buzz'}} @server.respond() assert.equal 1, @server.requests.length assert.equal 'bar', @server.requests[0].requestHeaders['foo'] assert.equal 'buzz', @server.requests[0].requestHeaders['fizz'] describe 'with partial page replacement', -> it 'uses just the part of the response body we supply', -> @server.respondWith([200, { "Content-Type": "text/html" }, html_one]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} @server.respond() assert.equal "Hi there!", document.title assert.equal -1, document.body.textContent.indexOf("YOLO") assert document.body.textContent.indexOf("Hi <NAME>") > 0 assert @pushStateStub.calledOnce assert @pushStateStub.calledWith({turbolinks: true, url: url_for("/some_request")}, "", url_for("/some_request")) assert.equal 0, @replaceStateStub.callCount it 'doesn\'t update the window state if updatePushState is false', -> @server.respondWith([200, { "Content-Type": "text/html" }, html_one]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area'], updatePushState: false} @server.respond() assert.equal "Hi there!", document.title assert.equal -1, document.body.textContent.indexOf("YOLO") assert document.body.textContent.indexOf("Hi <NAME>") > 0 assert @pushStateStub.notCalled assert @replaceStateStub.notCalled it 'calls a user-supplied callback', -> @server.respondWith([200, { "Content-Type": "text/html" }, html_one]); your_callback = stub() Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area'], callback: your_callback} @server.respond() assert your_callback.calledOnce it 'script tags are evaluated when they are the subject of a partial replace', -> window.globalStub = stub() @server.respondWith([200, { "Content-Type": "text/html" }, script_response]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} @server.respond() assert globalStub.calledOnce it 'script tags are not evaluated if they have [data-turbolinks-eval="false"]', -> window.globalStub = stub() @server.respondWith([200, { "Content-Type": "text/html" }, script_response_turbolinks_eval_false]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} @server.respond() assert.equal 0, globalStub.callCount it 'triggers the page:load event with a list of nodes that are new (freshly replaced)', -> $(document).one 'page:load', (event) -> ev = event.originalEvent assert.equal true, ev.data instanceof Array assert.equal 1, ev.data.length node = ev.data[0] assert.equal "turbo-area", node.id assert.equal "turbo-area", node.getAttribute('refresh') @server.respondWith([200, { "Content-Type": "text/html" }, html_one]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} @server.respond() $(document).off 'page:load' it 'does not trigger the page:before-partial-replace event more than once', -> handler = stub() $(document).on 'page:before-partial-replace', -> handler() assert handler.calledOnce @server.respondWith([200, { "Content-Type": "text/html" }, html_one]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} @server.respond() $(document).off 'page:before-partial-replace' it 'replaces and passes through the outermost nodes if a series of nodes got replaced', -> currentBody = """ <div id="div1" refresh="div1"> <div id="div2" refresh-always>Refresh-always</div> </div> """ $("body").append($(currentBody)) $(document).on 'page:before-partial-replace', (ev) -> nodes = ev.originalEvent.data assert.equal 2, nodes.length assert.equal 'div2', nodes[0].id assert.equal 'div1', nodes[1].id $(document).on 'page:load', (ev) -> nodes = ev.originalEvent.data assert.equal 1, nodes.length assert.equal 'div1', nodes[0].id @server.respondWith([200, { "Content-Type": "text/html" }, response_with_refresh_always]); Page.refresh(onlyKeys: ['div1']) @server.respond() $(document).off 'page:before-partial-replace' $(document).off 'page:load' $("#div1").remove()
true
describe 'Turbolinks', -> createTurboNodule = -> $nodule = $("<div>").attr("id", "turbo-area").attr("refresh", "turbo-area") return $nodule[0] url_for = (slug) -> window.location.origin + slug beforeEach -> @server = sinon.fakeServer.create() $("script").attr("data-turbolinks-eval", false) $("#mocha").attr("refresh-never", true) @replaceStateStub = stub(Turbolinks, "replaceState") @pushStateStub = stub(Turbolinks, "pushState") document.body.appendChild(createTurboNodule()) afterEach -> @server.restore() @pushStateStub.restore() @replaceStateStub.restore() $("#turbo-area").remove() html_one = """ <!doctype html> <html> <head> <title>Hi there!</title> </head> <body> <div>YOLO</div> <div id="turbo-area" refresh="turbo-area">Hi PI:NAME:<NAME>END_PI</div> </body> </html> """ script_response = """ <!doctype html> <html> <head> <title>Hi</title> </head> <body> <script id="turbo-area" refresh="turbo-area">globalStub()</script> </body> </html> """ script_response_turbolinks_eval_false = """ <!doctype html> <html> <head> <title>Hi</title> </head> <body> <script data-turbolinks-eval="false" id="turbo-area" refresh="turbo-area">globalStub()</script> </body> </html> """ response_with_refresh_always = """ <!doctype html> <html> <head> <title>Hi</title> </head> <body> <div id="div1" refresh="div1"> <div id="div2" refresh-always>Refresh-always</div> </div> </body> </html> """ it 'is defined', -> assert Turbolinks describe '#visit', -> it 'returns if pageChangePrevented', -> listener = (event) -> event.preventDefault() assert.equal '/some_request', event.data window.addEventListener('page:before-change', listener) Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} assert.equal 0, @server.requests.length window.removeEventListener('page:before-change', listener) it 'supports passing request headers', -> @server.respondWith([200, { "Content-Type": "text/html" }, "<html>Hello World</html>"]); Turbolinks.visit "/some_request", {headers: {'foo': 'bar', 'fizz': 'buzz'}} @server.respond() assert.equal 1, @server.requests.length assert.equal 'bar', @server.requests[0].requestHeaders['foo'] assert.equal 'buzz', @server.requests[0].requestHeaders['fizz'] describe 'with partial page replacement', -> it 'uses just the part of the response body we supply', -> @server.respondWith([200, { "Content-Type": "text/html" }, html_one]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} @server.respond() assert.equal "Hi there!", document.title assert.equal -1, document.body.textContent.indexOf("YOLO") assert document.body.textContent.indexOf("Hi PI:NAME:<NAME>END_PI") > 0 assert @pushStateStub.calledOnce assert @pushStateStub.calledWith({turbolinks: true, url: url_for("/some_request")}, "", url_for("/some_request")) assert.equal 0, @replaceStateStub.callCount it 'doesn\'t update the window state if updatePushState is false', -> @server.respondWith([200, { "Content-Type": "text/html" }, html_one]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area'], updatePushState: false} @server.respond() assert.equal "Hi there!", document.title assert.equal -1, document.body.textContent.indexOf("YOLO") assert document.body.textContent.indexOf("Hi PI:NAME:<NAME>END_PI") > 0 assert @pushStateStub.notCalled assert @replaceStateStub.notCalled it 'calls a user-supplied callback', -> @server.respondWith([200, { "Content-Type": "text/html" }, html_one]); your_callback = stub() Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area'], callback: your_callback} @server.respond() assert your_callback.calledOnce it 'script tags are evaluated when they are the subject of a partial replace', -> window.globalStub = stub() @server.respondWith([200, { "Content-Type": "text/html" }, script_response]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} @server.respond() assert globalStub.calledOnce it 'script tags are not evaluated if they have [data-turbolinks-eval="false"]', -> window.globalStub = stub() @server.respondWith([200, { "Content-Type": "text/html" }, script_response_turbolinks_eval_false]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} @server.respond() assert.equal 0, globalStub.callCount it 'triggers the page:load event with a list of nodes that are new (freshly replaced)', -> $(document).one 'page:load', (event) -> ev = event.originalEvent assert.equal true, ev.data instanceof Array assert.equal 1, ev.data.length node = ev.data[0] assert.equal "turbo-area", node.id assert.equal "turbo-area", node.getAttribute('refresh') @server.respondWith([200, { "Content-Type": "text/html" }, html_one]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} @server.respond() $(document).off 'page:load' it 'does not trigger the page:before-partial-replace event more than once', -> handler = stub() $(document).on 'page:before-partial-replace', -> handler() assert handler.calledOnce @server.respondWith([200, { "Content-Type": "text/html" }, html_one]); Turbolinks.visit "/some_request", {partialReplace: true, onlyKeys: ['turbo-area']} @server.respond() $(document).off 'page:before-partial-replace' it 'replaces and passes through the outermost nodes if a series of nodes got replaced', -> currentBody = """ <div id="div1" refresh="div1"> <div id="div2" refresh-always>Refresh-always</div> </div> """ $("body").append($(currentBody)) $(document).on 'page:before-partial-replace', (ev) -> nodes = ev.originalEvent.data assert.equal 2, nodes.length assert.equal 'div2', nodes[0].id assert.equal 'div1', nodes[1].id $(document).on 'page:load', (ev) -> nodes = ev.originalEvent.data assert.equal 1, nodes.length assert.equal 'div1', nodes[0].id @server.respondWith([200, { "Content-Type": "text/html" }, response_with_refresh_always]); Page.refresh(onlyKeys: ['div1']) @server.respond() $(document).off 'page:before-partial-replace' $(document).off 'page:load' $("#div1").remove()
[ { "context": "if !id?\n\t\t\t\treturn {\n\t\t\t\t\temail: null\n\t\t\t\t\tname: \"Anonymous\"\n\t\t\t\t\tisSelf: false\n\t\t\t\t\thue: ColorManager.ANONYM", "end": 27922, "score": 0.9827932119369507, "start": 27913, "tag": "NAME", "value": "Anonymous" } ]
public/coffee/ide/review-panel/controllers/ReviewPanelController.coffee
davidmehren/web-sharelatex
0
define [ "base", "utils/EventEmitter" "ide/colors/ColorManager" "ide/review-panel/RangesTracker" ], (App, EventEmitter, ColorManager, RangesTracker) -> App.controller "ReviewPanelController", ($scope, $element, ide, $timeout, $http, $modal, event_tracking, localStorage) -> $reviewPanelEl = $element.find "#review-panel" UserTypes = MEMBER: 'member' # Invited, listed in project.members GUEST: 'guest' # Not invited, but logged in so has a user_id ANONYMOUS: 'anonymous' # No user_id currentUserType = () -> if !ide.$scope.user?.id? return UserTypes.ANONYMOUS else user_id = ide.$scope.user.id project = ide.$scope.project if project.owner?.id == user_id return UserTypes.MEMBER for member in project.members if member._id == user_id return UserTypes.MEMBER return UserTypes.GUEST $scope.SubViews = CUR_FILE : "cur_file" OVERVIEW : "overview" $scope.UserTCSyncState = UserTCSyncState = SYNCED : "synced" PENDING : "pending" $scope.reviewPanel = trackChangesState: {} trackChangesOnForEveryone: false trackChangesOnForGuests: false trackChangesForGuestsAvailable: false entries: {} resolvedComments: {} hasEntries: false subView: $scope.SubViews.CUR_FILE openSubView: $scope.SubViews.CUR_FILE overview: loading: false docsCollapsedState: JSON.parse(localStorage("docs_collapsed_state:#{$scope.project_id}")) or {} dropdown: loading: false commentThreads: {} resolvedThreadIds: {} rendererData: {} formattedProjectMembers: {} fullTCStateCollapsed: true loadingThreads: false # All selected changes. If a aggregated change (insertion + deletion) is selection, the two ids # will be present. The length of this array will differ from the count below (see explanation). selectedEntryIds: [] # A count of user-facing selected changes. An aggregated change (insertion + deletion) will count # as only one. nVisibleSelectedChanges: 0 window.addEventListener "beforeunload", () -> collapsedStates = {} for doc, state of $scope.reviewPanel.overview.docsCollapsedState if state collapsedStates[doc] = state valToStore = if Object.keys(collapsedStates).length > 0 then JSON.stringify(collapsedStates) else null localStorage("docs_collapsed_state:#{$scope.project_id}", valToStore) $scope.$on "layout:pdf:linked", (event, state) -> $scope.$broadcast "review-panel:layout" $scope.$on "layout:pdf:resize", (event, state) -> $scope.$broadcast "review-panel:layout", false $scope.$on "expandable-text-area:resize", (event) -> $timeout () -> $scope.$broadcast "review-panel:layout" $scope.$on "review-panel:sizes", (e, sizes) -> $scope.$broadcast "editor:set-scroll-size", sizes $scope.$watch "project.features.trackChangesVisible", (visible) -> return if !visible? if !visible $scope.ui.reviewPanelOpen = false $scope.$watch "project.members", (members) -> $scope.reviewPanel.formattedProjectMembers = {} if $scope.project?.owner? $scope.reviewPanel.formattedProjectMembers[$scope.project.owner._id] = formatUser($scope.project.owner) if $scope.project?.members? for member in members if member.privileges == "readAndWrite" $scope.reviewPanel.formattedProjectMembers[member._id] = formatUser(member) $scope.commentState = adding: false content: "" $scope.users = {} $scope.reviewPanelEventsBridge = new EventEmitter() ide.socket.on "new-comment", (thread_id, comment) -> thread = getThread(thread_id) delete thread.submitting thread.messages.push(formatComment(comment)) $scope.$apply() $timeout () -> $scope.$broadcast "review-panel:layout" ide.socket.on "accept-changes", (doc_id, change_ids) -> if doc_id != $scope.editor.open_doc_id getChangeTracker(doc_id).removeChangeIds(change_ids) else $scope.$broadcast "changes:accept", change_ids updateEntries(doc_id) $scope.$apply () -> ide.socket.on "resolve-thread", (thread_id, user) -> _onCommentResolved(thread_id, user) ide.socket.on "reopen-thread", (thread_id) -> _onCommentReopened(thread_id) ide.socket.on "delete-thread", (thread_id) -> _onThreadDeleted(thread_id) $scope.$apply () -> ide.socket.on "edit-message", (thread_id, message_id, content) -> _onCommentEdited(thread_id, message_id, content) $scope.$apply () -> ide.socket.on "delete-message", (thread_id, message_id) -> _onCommentDeleted(thread_id, message_id) $scope.$apply () -> rangesTrackers = {} getDocEntries = (doc_id) -> $scope.reviewPanel.entries[doc_id] ?= {} return $scope.reviewPanel.entries[doc_id] getDocResolvedComments = (doc_id) -> $scope.reviewPanel.resolvedComments[doc_id] ?= {} return $scope.reviewPanel.resolvedComments[doc_id] getThread = (thread_id) -> $scope.reviewPanel.commentThreads[thread_id] ?= { messages: [] } return $scope.reviewPanel.commentThreads[thread_id] getChangeTracker = (doc_id) -> if !rangesTrackers[doc_id]? rangesTrackers[doc_id] = new RangesTracker() rangesTrackers[doc_id].resolvedThreadIds = $scope.reviewPanel.resolvedThreadIds return rangesTrackers[doc_id] scrollbar = {} $scope.reviewPanelEventsBridge.on "aceScrollbarVisibilityChanged", (isVisible, scrollbarWidth) -> scrollbar = {isVisible, scrollbarWidth} updateScrollbar() updateScrollbar = () -> if scrollbar.isVisible and $scope.reviewPanel.subView == $scope.SubViews.CUR_FILE $reviewPanelEl.css "right", "#{ scrollbar.scrollbarWidth }px" else $reviewPanelEl.css "right", "0" $scope.$watch "!ui.reviewPanelOpen && reviewPanel.hasEntries", (open, prevVal) -> return if !open? $scope.ui.miniReviewPanelVisible = open if open != prevVal $timeout () -> $scope.$broadcast "review-panel:toggle" $scope.$watch "ui.reviewPanelOpen", (open) -> return if !open? if !open # Always show current file when not open, but save current state $scope.reviewPanel.openSubView = $scope.reviewPanel.subView $scope.reviewPanel.subView = $scope.SubViews.CUR_FILE else # Reset back to what we had when previously open $scope.reviewPanel.subView = $scope.reviewPanel.openSubView $timeout () -> $scope.$broadcast "review-panel:toggle" $scope.$broadcast "review-panel:layout", false $scope.$watch "reviewPanel.subView", (view) -> return if !view? updateScrollbar() if view == $scope.SubViews.OVERVIEW refreshOverviewPanel() $scope.$watch "editor.sharejs_doc", (doc, old_doc) -> return if !doc? # The open doc range tracker is kept up to date in real-time so # replace any outdated info with this rangesTrackers[doc.doc_id] = doc.ranges rangesTrackers[doc.doc_id].resolvedThreadIds = $scope.reviewPanel.resolvedThreadIds $scope.reviewPanel.rangesTracker = rangesTrackers[doc.doc_id] if old_doc? old_doc.off "flipped_pending_to_inflight" doc.on "flipped_pending_to_inflight", () -> regenerateTrackChangesId(doc) regenerateTrackChangesId(doc) $scope.$watch (() -> entries = $scope.reviewPanel.entries[$scope.editor.open_doc_id] or {} permEntries = {} for entry, entryData of entries if entry not in [ "add-comment", "bulk-actions" ] permEntries[entry] = entryData Object.keys(permEntries).length ), (nEntries) -> $scope.reviewPanel.hasEntries = nEntries > 0 and $scope.project.features.trackChangesVisible regenerateTrackChangesId = (doc) -> old_id = getChangeTracker(doc.doc_id).getIdSeed() new_id = RangesTracker.generateIdSeed() getChangeTracker(doc.doc_id).setIdSeed(new_id) doc.setTrackChangesIdSeeds({pending: new_id, inflight: old_id}) refreshRanges = () -> $http.get "/project/#{$scope.project_id}/ranges" .then (response) -> docs = response.data for doc in docs if !$scope.reviewPanel.overview.docsCollapsedState[doc.id]? $scope.reviewPanel.overview.docsCollapsedState[doc.id] = false if doc.id != $scope.editor.open_doc_id # this is kept up to date in real-time, don't overwrite rangesTracker = getChangeTracker(doc.id) rangesTracker.comments = doc.ranges?.comments or [] rangesTracker.changes = doc.ranges?.changes or [] updateEntries(doc.id) refreshOverviewPanel = () -> $scope.reviewPanel.overview.loading = true refreshRanges() .then () -> $scope.reviewPanel.overview.loading = false .catch () -> $scope.reviewPanel.overview.loading = false $scope.refreshResolvedCommentsDropdown = () -> $scope.reviewPanel.dropdown.loading = true q = refreshRanges() q.then () -> $scope.reviewPanel.dropdown.loading = false q.catch () -> $scope.reviewPanel.dropdown.loading = false return q updateEntries = (doc_id) -> rangesTracker = getChangeTracker(doc_id) entries = getDocEntries(doc_id) resolvedComments = getDocResolvedComments(doc_id) changed = false # Assume we'll delete everything until we see it, then we'll remove it from this object delete_changes = {} for id, change of entries if id not in [ "add-comment", "bulk-actions" ] for entry_id in change.entry_ids delete_changes[entry_id] = true for id, change of resolvedComments for entry_id in change.entry_ids delete_changes[entry_id] = true potential_aggregate = false prev_insertion = null for change in rangesTracker.changes changed = true if ( potential_aggregate and change.op.d and change.op.p == prev_insertion.op.p + prev_insertion.op.i.length and change.metadata.user_id == prev_insertion.metadata.user_id ) # An actual aggregate op. entries[prev_insertion.id].type = "aggregate-change" entries[prev_insertion.id].metadata.replaced_content = change.op.d entries[prev_insertion.id].entry_ids.push change.id else entries[change.id] ?= {} delete delete_changes[change.id] new_entry = { type: if change.op.i then "insert" else "delete" entry_ids: [ change.id ] content: change.op.i or change.op.d offset: change.op.p metadata: change.metadata } for key, value of new_entry entries[change.id][key] = value if change.op.i potential_aggregate = true prev_insertion = change else potential_aggregate = false prev_insertion = null if !$scope.users[change.metadata.user_id]? refreshChangeUsers(change.metadata.user_id) if rangesTracker.comments.length > 0 ensureThreadsAreLoaded() for comment in rangesTracker.comments changed = true delete delete_changes[comment.id] if $scope.reviewPanel.resolvedThreadIds[comment.op.t] new_comment = resolvedComments[comment.id] ?= {} delete entries[comment.id] else new_comment = entries[comment.id] ?= {} delete resolvedComments[comment.id] new_entry = { type: "comment" thread_id: comment.op.t entry_ids: [ comment.id ] content: comment.op.c offset: comment.op.p } for key, value of new_entry new_comment[key] = value for change_id, _ of delete_changes changed = true delete entries[change_id] delete resolvedComments[change_id] if changed $scope.$broadcast "entries:changed" $scope.$on "editor:track-changes:changed", () -> doc_id = $scope.editor.open_doc_id updateEntries(doc_id) $scope.$broadcast "review-panel:recalculate-screen-positions" $scope.$broadcast "review-panel:layout" $scope.$on "editor:track-changes:visibility_changed", () -> $timeout () -> $scope.$broadcast "review-panel:layout", false $scope.$on "editor:focus:changed", (e, selection_offset_start, selection_offset_end, selection) -> doc_id = $scope.editor.open_doc_id entries = getDocEntries(doc_id) # All selected changes will be added to this array. $scope.reviewPanel.selectedEntryIds = [] # Count of user-visible changes, i.e. an aggregated change will count as one. $scope.reviewPanel.nVisibleSelectedChanges = 0 delete entries["add-comment"] delete entries["bulk-actions"] if selection entries["add-comment"] = { type: "add-comment" offset: selection_offset_start length: selection_offset_end - selection_offset_start } entries["bulk-actions"] = { type: "bulk-actions" offset: selection_offset_start length: selection_offset_end - selection_offset_start } for id, entry of entries isChangeEntryAndWithinSelection = false if entry.type == "comment" and not $scope.reviewPanel.resolvedThreadIds[entry.thread_id] entry.focused = (entry.offset <= selection_offset_start <= entry.offset + entry.content.length) else if entry.type == "insert" isChangeEntryAndWithinSelection = entry.offset >= selection_offset_start and entry.offset + entry.content.length <= selection_offset_end entry.focused = (entry.offset <= selection_offset_start <= entry.offset + entry.content.length) else if entry.type == "delete" isChangeEntryAndWithinSelection = selection_offset_start <= entry.offset <= selection_offset_end entry.focused = (entry.offset == selection_offset_start) else if entry.type == "aggregate-change" isChangeEntryAndWithinSelection = entry.offset >= selection_offset_start and entry.offset + entry.content.length <= selection_offset_end entry.focused = (entry.offset <= selection_offset_start <= entry.offset + entry.content.length) else if entry.type in [ "add-comment", "bulk-actions" ] and selection entry.focused = true if isChangeEntryAndWithinSelection for entry_id in entry.entry_ids $scope.reviewPanel.selectedEntryIds.push entry_id $scope.reviewPanel.nVisibleSelectedChanges++ $scope.$broadcast "review-panel:recalculate-screen-positions" $scope.$broadcast "review-panel:layout" $scope.acceptChanges = (change_ids) -> _doAcceptChanges change_ids event_tracking.sendMB "rp-changes-accepted", { view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini' } $scope.rejectChanges = (change_ids) -> _doRejectChanges change_ids event_tracking.sendMB "rp-changes-rejected", { view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini' } _doAcceptChanges = (change_ids) -> $http.post "/project/#{$scope.project_id}/doc/#{$scope.editor.open_doc_id}/changes/accept", { change_ids, _csrf: window.csrfToken} $scope.$broadcast "changes:accept", change_ids _doRejectChanges = (change_ids) -> $scope.$broadcast "changes:reject", change_ids bulkAccept = () -> _doAcceptChanges $scope.reviewPanel.selectedEntryIds.slice() event_tracking.sendMB "rp-bulk-accept", { view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini', nEntries: $scope.reviewPanel.nVisibleSelectedChanges } bulkReject = () -> _doRejectChanges $scope.reviewPanel.selectedEntryIds.slice() event_tracking.sendMB "rp-bulk-reject", { view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini', nEntries: $scope.reviewPanel.nVisibleSelectedChanges } $scope.showBulkAcceptDialog = () -> showBulkActionsDialog true $scope.showBulkRejectDialog = () -> showBulkActionsDialog false showBulkActionsDialog = (isAccept) -> $modal.open({ templateUrl: "bulkActionsModalTemplate" controller: "BulkActionsModalController" resolve: isAccept: () -> isAccept nChanges: () -> $scope.reviewPanel.nVisibleSelectedChanges scope: $scope.$new() }).result.then (isAccept) -> if isAccept bulkAccept() else bulkReject() $scope.handleTogglerClick = (e) -> e.target.blur() $scope.toggleReviewPanel() $scope.addNewComment = () -> $scope.$broadcast "comment:start_adding" $scope.toggleReviewPanel() $scope.addNewCommentFromKbdShortcut = () -> if !$scope.project.features.trackChangesVisible return $scope.$broadcast "comment:select_line" if !$scope.ui.reviewPanelOpen $scope.toggleReviewPanel() $timeout () -> $scope.$broadcast "review-panel:layout" $scope.$broadcast "comment:start_adding" $scope.startNewComment = () -> $scope.$broadcast "comment:select_line" $timeout () -> $scope.$broadcast "review-panel:layout" $scope.submitNewComment = (content) -> return if !content? or content == "" doc_id = $scope.editor.open_doc_id entries = getDocEntries(doc_id) return if !entries["add-comment"]? {offset, length} = entries["add-comment"] thread_id = RangesTracker.generateId() thread = getThread(thread_id) thread.submitting = true $scope.$broadcast "comment:add", thread_id, offset, length $http.post("/project/#{$scope.project_id}/thread/#{thread_id}/messages", {content, _csrf: window.csrfToken}) .catch () -> ide.showGenericMessageModal("Error submitting comment", "Sorry, there was a problem submitting your comment") $scope.$broadcast "editor:clearSelection" $timeout () -> $scope.$broadcast "review-panel:layout" event_tracking.sendMB "rp-new-comment", { size: content.length } $scope.cancelNewComment = (entry) -> $timeout () -> $scope.$broadcast "review-panel:layout" $scope.startReply = (entry) -> entry.replying = true $timeout () -> $scope.$broadcast "review-panel:layout" $scope.submitReply = (entry, entry_id) -> thread_id = entry.thread_id content = entry.replyContent $http.post("/project/#{$scope.project_id}/thread/#{thread_id}/messages", {content, _csrf: window.csrfToken}) .catch () -> ide.showGenericMessageModal("Error submitting comment", "Sorry, there was a problem submitting your comment") trackingMetadata = view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini' size: entry.replyContent.length thread: thread_id thread = getThread(thread_id) thread.submitting = true entry.replyContent = "" entry.replying = false $timeout () -> $scope.$broadcast "review-panel:layout" event_tracking.sendMB "rp-comment-reply", trackingMetadata $scope.cancelReply = (entry) -> entry.replying = false entry.replyContent = "" $scope.$broadcast "review-panel:layout" $scope.resolveComment = (entry, entry_id) -> entry.focused = false $http.post "/project/#{$scope.project_id}/thread/#{entry.thread_id}/resolve", {_csrf: window.csrfToken} _onCommentResolved(entry.thread_id, ide.$scope.user) event_tracking.sendMB "rp-comment-resolve", { view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini' } $scope.unresolveComment = (thread_id) -> _onCommentReopened(thread_id) $http.post "/project/#{$scope.project_id}/thread/#{thread_id}/reopen", {_csrf: window.csrfToken} event_tracking.sendMB "rp-comment-reopen" _onCommentResolved = (thread_id, user) -> thread = getThread(thread_id) return if !thread? thread.resolved = true thread.resolved_by_user = formatUser(user) thread.resolved_at = new Date().toISOString() $scope.reviewPanel.resolvedThreadIds[thread_id] = true $scope.$broadcast "comment:resolve_threads", [thread_id] _onCommentReopened = (thread_id) -> thread = getThread(thread_id) return if !thread? delete thread.resolved delete thread.resolved_by_user delete thread.resolved_at delete $scope.reviewPanel.resolvedThreadIds[thread_id] $scope.$broadcast "comment:unresolve_thread", thread_id _onThreadDeleted = (thread_id) -> delete $scope.reviewPanel.resolvedThreadIds[thread_id] delete $scope.reviewPanel.commentThreads[thread_id] $scope.$broadcast "comment:remove", thread_id _onCommentEdited = (thread_id, comment_id, content) -> thread = getThread(thread_id) return if !thread? for message in thread.messages if message.id == comment_id message.content = content updateEntries() _onCommentDeleted = (thread_id, comment_id) -> thread = getThread(thread_id) return if !thread? thread.messages = thread.messages.filter (m) -> m.id != comment_id updateEntries() $scope.deleteThread = (entry_id, doc_id, thread_id) -> _onThreadDeleted(thread_id) $http({ method: "DELETE" url: "/project/#{$scope.project_id}/doc/#{doc_id}/thread/#{thread_id}", headers: { 'X-CSRF-Token': window.csrfToken } }) event_tracking.sendMB "rp-comment-delete" $scope.saveEdit = (thread_id, comment) -> $http.post("/project/#{$scope.project_id}/thread/#{thread_id}/messages/#{comment.id}/edit", { content: comment.content _csrf: window.csrfToken }) $timeout () -> $scope.$broadcast "review-panel:layout" $scope.deleteComment = (thread_id, comment) -> _onCommentDeleted(thread_id, comment.id) $http({ method: "DELETE" url: "/project/#{$scope.project_id}/thread/#{thread_id}/messages/#{comment.id}", headers: { 'X-CSRF-Token': window.csrfToken } }) $timeout () -> $scope.$broadcast "review-panel:layout" $scope.setSubView = (subView) -> $scope.reviewPanel.subView = subView event_tracking.sendMB "rp-subview-change", { subView } $scope.gotoEntry = (doc_id, entry) -> ide.editorManager.openDocId(doc_id, { gotoOffset: entry.offset }) $scope.toggleFullTCStateCollapse = () -> if $scope.project.features.trackChanges $scope.reviewPanel.fullTCStateCollapsed = !$scope.reviewPanel.fullTCStateCollapsed else $scope.openTrackChangesUpgradeModal() _setUserTCState = (userId, newValue, isLocal = false) -> $scope.reviewPanel.trackChangesState[userId] ?= {} state = $scope.reviewPanel.trackChangesState[userId] if !state.syncState? or state.syncState == UserTCSyncState.SYNCED state.value = newValue state.syncState = UserTCSyncState.SYNCED else if state.syncState == UserTCSyncState.PENDING and state.value == newValue state.syncState = UserTCSyncState.SYNCED else if isLocal state.value = newValue state.syncState = UserTCSyncState.PENDING if userId == ide.$scope.user.id $scope.editor.wantTrackChanges = newValue _setEveryoneTCState = (newValue, isLocal = false) -> $scope.reviewPanel.trackChangesOnForEveryone = newValue project = $scope.project for member in project.members _setUserTCState(member._id, newValue, isLocal) _setGuestsTCState(newValue, isLocal) _setUserTCState(project.owner._id, newValue, isLocal) _setGuestsTCState = (newValue, isLocal = false) -> $scope.reviewPanel.trackChangesOnForGuests = newValue if currentUserType() == UserTypes.GUEST or currentUserType() == UserTypes.ANONYMOUS $scope.editor.wantTrackChanges = newValue applyClientTrackChangesStateToServer = () -> data = {} if $scope.reviewPanel.trackChangesOnForEveryone data.on = true else data.on_for = {} for userId, userState of $scope.reviewPanel.trackChangesState data.on_for[userId] = userState.value if $scope.reviewPanel.trackChangesOnForGuests data.on_for_guests = true data._csrf = window.csrfToken $http.post "/project/#{$scope.project_id}/track_changes", data applyTrackChangesStateToClient = (state) -> if typeof state is "boolean" _setEveryoneTCState state _setGuestsTCState state else project = $scope.project $scope.reviewPanel.trackChangesOnForEveryone = false _setGuestsTCState(state.__guests__ == true) for member in project.members _setUserTCState(member._id, state[member._id] ? false) _setUserTCState($scope.project.owner._id, state[$scope.project.owner._id] ? false) $scope.toggleTrackChangesForEveryone = (onForEveryone) -> _setEveryoneTCState onForEveryone, true _setGuestsTCState onForEveryone, true applyClientTrackChangesStateToServer() $scope.toggleTrackChangesForGuests = (onForGuests) -> _setGuestsTCState onForGuests, true applyClientTrackChangesStateToServer() $scope.toggleTrackChangesForUser = (onForUser, userId) -> _setUserTCState userId, onForUser, true applyClientTrackChangesStateToServer() ide.socket.on "toggle-track-changes", (state) -> $scope.$apply () -> applyTrackChangesStateToClient(state) $scope.toggleTrackChangesFromKbdShortcut = () -> if !($scope.project.features.trackChangesVisible && $scope.project.features.trackChanges) return $scope.toggleTrackChangesForUser !$scope.reviewPanel.trackChangesState[ide.$scope.user.id].value, ide.$scope.user.id setGuestFeatureBasedOnProjectAccessLevel = (projectPublicAccessLevel) -> $scope.reviewPanel.trackChangesForGuestsAvailable = (projectPublicAccessLevel == 'tokenBased') onToggleTrackChangesForGuestsAvailability = (available) -> # If the feature is no longer available we need to turn off the guest flag return if available return if !$scope.reviewPanel.trackChangesOnForGuests # Already turned off return if $scope.reviewPanel.trackChangesOnForEveryone # Overrides guest setting $scope.toggleTrackChangesForGuests(false) $scope.$watch 'project.publicAccesLevel', setGuestFeatureBasedOnProjectAccessLevel $scope.$watch 'reviewPanel.trackChangesForGuestsAvailable', (available) -> if available? onToggleTrackChangesForGuestsAvailability(available) _inited = false ide.$scope.$on "project:joined", () -> return if _inited project = ide.$scope.project if project.features.trackChanges window.trackChangesState ?= false applyTrackChangesStateToClient(window.trackChangesState) else applyTrackChangesStateToClient(false) setGuestFeatureBasedOnProjectAccessLevel(project.publicAccesLevel) _inited = true _refreshingRangeUsers = false _refreshedForUserIds = {} refreshChangeUsers = (refresh_for_user_id) -> if refresh_for_user_id? if _refreshedForUserIds[refresh_for_user_id]? # We've already tried to refresh to get this user id, so stop it looping return _refreshedForUserIds[refresh_for_user_id] = true # Only do one refresh at once if _refreshingRangeUsers return _refreshingRangeUsers = true $http.get "/project/#{$scope.project_id}/changes/users" .then (response) -> users = response.data _refreshingRangeUsers = false $scope.users = {} # Always include ourself, since if we submit an op, we might need to display info # about it locally before it has been flushed through the server if ide.$scope.user?.id? $scope.users[ide.$scope.user.id] = formatUser(ide.$scope.user) for user in users if user.id? $scope.users[user.id] = formatUser(user) .catch () -> _refreshingRangeUsers = false _threadsLoaded = false ensureThreadsAreLoaded = () -> if _threadsLoaded # We get any updates in real time so only need to load them once. return _threadsLoaded = true $scope.reviewPanel.loadingThreads = true $http.get "/project/#{$scope.project_id}/threads" .then (response) -> threads = response.data $scope.reviewPanel.loadingThreads = false for thread_id, _ of $scope.reviewPanel.resolvedThreadIds delete $scope.reviewPanel.resolvedThreadIds[thread_id] for thread_id, thread of threads for comment in thread.messages formatComment(comment) if thread.resolved_by_user? thread.resolved_by_user = formatUser(thread.resolved_by_user) $scope.reviewPanel.resolvedThreadIds[thread_id] = true $scope.$broadcast "comment:resolve_threads", [thread_id] $scope.reviewPanel.commentThreads = threads $timeout () -> $scope.$broadcast "review-panel:layout" formatComment = (comment) -> comment.user = formatUser(comment.user) comment.timestamp = new Date(comment.timestamp) return comment formatUser = (user) -> id = user?._id or user?.id if !id? return { email: null name: "Anonymous" isSelf: false hue: ColorManager.ANONYMOUS_HUE avatar_text: "A" } if id == window.user_id name = "You" isSelf = true else name = [user.first_name, user.last_name].filter((n) -> n? and n != "").join(" ") if name == "" name = user.email?.split("@")[0] or "Unknown" isSelf = false return { id: id email: user.email name: name isSelf: isSelf hue: ColorManager.getHueForUserId(id) avatar_text: [user.first_name, user.last_name].filter((n) -> n?).map((n) -> n[0]).join "" } $scope.openTrackChangesUpgradeModal = () -> $modal.open { templateUrl: "trackChangesUpgradeModalTemplate" controller: "TrackChangesUpgradeModalController" scope: $scope.$new() }
186611
define [ "base", "utils/EventEmitter" "ide/colors/ColorManager" "ide/review-panel/RangesTracker" ], (App, EventEmitter, ColorManager, RangesTracker) -> App.controller "ReviewPanelController", ($scope, $element, ide, $timeout, $http, $modal, event_tracking, localStorage) -> $reviewPanelEl = $element.find "#review-panel" UserTypes = MEMBER: 'member' # Invited, listed in project.members GUEST: 'guest' # Not invited, but logged in so has a user_id ANONYMOUS: 'anonymous' # No user_id currentUserType = () -> if !ide.$scope.user?.id? return UserTypes.ANONYMOUS else user_id = ide.$scope.user.id project = ide.$scope.project if project.owner?.id == user_id return UserTypes.MEMBER for member in project.members if member._id == user_id return UserTypes.MEMBER return UserTypes.GUEST $scope.SubViews = CUR_FILE : "cur_file" OVERVIEW : "overview" $scope.UserTCSyncState = UserTCSyncState = SYNCED : "synced" PENDING : "pending" $scope.reviewPanel = trackChangesState: {} trackChangesOnForEveryone: false trackChangesOnForGuests: false trackChangesForGuestsAvailable: false entries: {} resolvedComments: {} hasEntries: false subView: $scope.SubViews.CUR_FILE openSubView: $scope.SubViews.CUR_FILE overview: loading: false docsCollapsedState: JSON.parse(localStorage("docs_collapsed_state:#{$scope.project_id}")) or {} dropdown: loading: false commentThreads: {} resolvedThreadIds: {} rendererData: {} formattedProjectMembers: {} fullTCStateCollapsed: true loadingThreads: false # All selected changes. If a aggregated change (insertion + deletion) is selection, the two ids # will be present. The length of this array will differ from the count below (see explanation). selectedEntryIds: [] # A count of user-facing selected changes. An aggregated change (insertion + deletion) will count # as only one. nVisibleSelectedChanges: 0 window.addEventListener "beforeunload", () -> collapsedStates = {} for doc, state of $scope.reviewPanel.overview.docsCollapsedState if state collapsedStates[doc] = state valToStore = if Object.keys(collapsedStates).length > 0 then JSON.stringify(collapsedStates) else null localStorage("docs_collapsed_state:#{$scope.project_id}", valToStore) $scope.$on "layout:pdf:linked", (event, state) -> $scope.$broadcast "review-panel:layout" $scope.$on "layout:pdf:resize", (event, state) -> $scope.$broadcast "review-panel:layout", false $scope.$on "expandable-text-area:resize", (event) -> $timeout () -> $scope.$broadcast "review-panel:layout" $scope.$on "review-panel:sizes", (e, sizes) -> $scope.$broadcast "editor:set-scroll-size", sizes $scope.$watch "project.features.trackChangesVisible", (visible) -> return if !visible? if !visible $scope.ui.reviewPanelOpen = false $scope.$watch "project.members", (members) -> $scope.reviewPanel.formattedProjectMembers = {} if $scope.project?.owner? $scope.reviewPanel.formattedProjectMembers[$scope.project.owner._id] = formatUser($scope.project.owner) if $scope.project?.members? for member in members if member.privileges == "readAndWrite" $scope.reviewPanel.formattedProjectMembers[member._id] = formatUser(member) $scope.commentState = adding: false content: "" $scope.users = {} $scope.reviewPanelEventsBridge = new EventEmitter() ide.socket.on "new-comment", (thread_id, comment) -> thread = getThread(thread_id) delete thread.submitting thread.messages.push(formatComment(comment)) $scope.$apply() $timeout () -> $scope.$broadcast "review-panel:layout" ide.socket.on "accept-changes", (doc_id, change_ids) -> if doc_id != $scope.editor.open_doc_id getChangeTracker(doc_id).removeChangeIds(change_ids) else $scope.$broadcast "changes:accept", change_ids updateEntries(doc_id) $scope.$apply () -> ide.socket.on "resolve-thread", (thread_id, user) -> _onCommentResolved(thread_id, user) ide.socket.on "reopen-thread", (thread_id) -> _onCommentReopened(thread_id) ide.socket.on "delete-thread", (thread_id) -> _onThreadDeleted(thread_id) $scope.$apply () -> ide.socket.on "edit-message", (thread_id, message_id, content) -> _onCommentEdited(thread_id, message_id, content) $scope.$apply () -> ide.socket.on "delete-message", (thread_id, message_id) -> _onCommentDeleted(thread_id, message_id) $scope.$apply () -> rangesTrackers = {} getDocEntries = (doc_id) -> $scope.reviewPanel.entries[doc_id] ?= {} return $scope.reviewPanel.entries[doc_id] getDocResolvedComments = (doc_id) -> $scope.reviewPanel.resolvedComments[doc_id] ?= {} return $scope.reviewPanel.resolvedComments[doc_id] getThread = (thread_id) -> $scope.reviewPanel.commentThreads[thread_id] ?= { messages: [] } return $scope.reviewPanel.commentThreads[thread_id] getChangeTracker = (doc_id) -> if !rangesTrackers[doc_id]? rangesTrackers[doc_id] = new RangesTracker() rangesTrackers[doc_id].resolvedThreadIds = $scope.reviewPanel.resolvedThreadIds return rangesTrackers[doc_id] scrollbar = {} $scope.reviewPanelEventsBridge.on "aceScrollbarVisibilityChanged", (isVisible, scrollbarWidth) -> scrollbar = {isVisible, scrollbarWidth} updateScrollbar() updateScrollbar = () -> if scrollbar.isVisible and $scope.reviewPanel.subView == $scope.SubViews.CUR_FILE $reviewPanelEl.css "right", "#{ scrollbar.scrollbarWidth }px" else $reviewPanelEl.css "right", "0" $scope.$watch "!ui.reviewPanelOpen && reviewPanel.hasEntries", (open, prevVal) -> return if !open? $scope.ui.miniReviewPanelVisible = open if open != prevVal $timeout () -> $scope.$broadcast "review-panel:toggle" $scope.$watch "ui.reviewPanelOpen", (open) -> return if !open? if !open # Always show current file when not open, but save current state $scope.reviewPanel.openSubView = $scope.reviewPanel.subView $scope.reviewPanel.subView = $scope.SubViews.CUR_FILE else # Reset back to what we had when previously open $scope.reviewPanel.subView = $scope.reviewPanel.openSubView $timeout () -> $scope.$broadcast "review-panel:toggle" $scope.$broadcast "review-panel:layout", false $scope.$watch "reviewPanel.subView", (view) -> return if !view? updateScrollbar() if view == $scope.SubViews.OVERVIEW refreshOverviewPanel() $scope.$watch "editor.sharejs_doc", (doc, old_doc) -> return if !doc? # The open doc range tracker is kept up to date in real-time so # replace any outdated info with this rangesTrackers[doc.doc_id] = doc.ranges rangesTrackers[doc.doc_id].resolvedThreadIds = $scope.reviewPanel.resolvedThreadIds $scope.reviewPanel.rangesTracker = rangesTrackers[doc.doc_id] if old_doc? old_doc.off "flipped_pending_to_inflight" doc.on "flipped_pending_to_inflight", () -> regenerateTrackChangesId(doc) regenerateTrackChangesId(doc) $scope.$watch (() -> entries = $scope.reviewPanel.entries[$scope.editor.open_doc_id] or {} permEntries = {} for entry, entryData of entries if entry not in [ "add-comment", "bulk-actions" ] permEntries[entry] = entryData Object.keys(permEntries).length ), (nEntries) -> $scope.reviewPanel.hasEntries = nEntries > 0 and $scope.project.features.trackChangesVisible regenerateTrackChangesId = (doc) -> old_id = getChangeTracker(doc.doc_id).getIdSeed() new_id = RangesTracker.generateIdSeed() getChangeTracker(doc.doc_id).setIdSeed(new_id) doc.setTrackChangesIdSeeds({pending: new_id, inflight: old_id}) refreshRanges = () -> $http.get "/project/#{$scope.project_id}/ranges" .then (response) -> docs = response.data for doc in docs if !$scope.reviewPanel.overview.docsCollapsedState[doc.id]? $scope.reviewPanel.overview.docsCollapsedState[doc.id] = false if doc.id != $scope.editor.open_doc_id # this is kept up to date in real-time, don't overwrite rangesTracker = getChangeTracker(doc.id) rangesTracker.comments = doc.ranges?.comments or [] rangesTracker.changes = doc.ranges?.changes or [] updateEntries(doc.id) refreshOverviewPanel = () -> $scope.reviewPanel.overview.loading = true refreshRanges() .then () -> $scope.reviewPanel.overview.loading = false .catch () -> $scope.reviewPanel.overview.loading = false $scope.refreshResolvedCommentsDropdown = () -> $scope.reviewPanel.dropdown.loading = true q = refreshRanges() q.then () -> $scope.reviewPanel.dropdown.loading = false q.catch () -> $scope.reviewPanel.dropdown.loading = false return q updateEntries = (doc_id) -> rangesTracker = getChangeTracker(doc_id) entries = getDocEntries(doc_id) resolvedComments = getDocResolvedComments(doc_id) changed = false # Assume we'll delete everything until we see it, then we'll remove it from this object delete_changes = {} for id, change of entries if id not in [ "add-comment", "bulk-actions" ] for entry_id in change.entry_ids delete_changes[entry_id] = true for id, change of resolvedComments for entry_id in change.entry_ids delete_changes[entry_id] = true potential_aggregate = false prev_insertion = null for change in rangesTracker.changes changed = true if ( potential_aggregate and change.op.d and change.op.p == prev_insertion.op.p + prev_insertion.op.i.length and change.metadata.user_id == prev_insertion.metadata.user_id ) # An actual aggregate op. entries[prev_insertion.id].type = "aggregate-change" entries[prev_insertion.id].metadata.replaced_content = change.op.d entries[prev_insertion.id].entry_ids.push change.id else entries[change.id] ?= {} delete delete_changes[change.id] new_entry = { type: if change.op.i then "insert" else "delete" entry_ids: [ change.id ] content: change.op.i or change.op.d offset: change.op.p metadata: change.metadata } for key, value of new_entry entries[change.id][key] = value if change.op.i potential_aggregate = true prev_insertion = change else potential_aggregate = false prev_insertion = null if !$scope.users[change.metadata.user_id]? refreshChangeUsers(change.metadata.user_id) if rangesTracker.comments.length > 0 ensureThreadsAreLoaded() for comment in rangesTracker.comments changed = true delete delete_changes[comment.id] if $scope.reviewPanel.resolvedThreadIds[comment.op.t] new_comment = resolvedComments[comment.id] ?= {} delete entries[comment.id] else new_comment = entries[comment.id] ?= {} delete resolvedComments[comment.id] new_entry = { type: "comment" thread_id: comment.op.t entry_ids: [ comment.id ] content: comment.op.c offset: comment.op.p } for key, value of new_entry new_comment[key] = value for change_id, _ of delete_changes changed = true delete entries[change_id] delete resolvedComments[change_id] if changed $scope.$broadcast "entries:changed" $scope.$on "editor:track-changes:changed", () -> doc_id = $scope.editor.open_doc_id updateEntries(doc_id) $scope.$broadcast "review-panel:recalculate-screen-positions" $scope.$broadcast "review-panel:layout" $scope.$on "editor:track-changes:visibility_changed", () -> $timeout () -> $scope.$broadcast "review-panel:layout", false $scope.$on "editor:focus:changed", (e, selection_offset_start, selection_offset_end, selection) -> doc_id = $scope.editor.open_doc_id entries = getDocEntries(doc_id) # All selected changes will be added to this array. $scope.reviewPanel.selectedEntryIds = [] # Count of user-visible changes, i.e. an aggregated change will count as one. $scope.reviewPanel.nVisibleSelectedChanges = 0 delete entries["add-comment"] delete entries["bulk-actions"] if selection entries["add-comment"] = { type: "add-comment" offset: selection_offset_start length: selection_offset_end - selection_offset_start } entries["bulk-actions"] = { type: "bulk-actions" offset: selection_offset_start length: selection_offset_end - selection_offset_start } for id, entry of entries isChangeEntryAndWithinSelection = false if entry.type == "comment" and not $scope.reviewPanel.resolvedThreadIds[entry.thread_id] entry.focused = (entry.offset <= selection_offset_start <= entry.offset + entry.content.length) else if entry.type == "insert" isChangeEntryAndWithinSelection = entry.offset >= selection_offset_start and entry.offset + entry.content.length <= selection_offset_end entry.focused = (entry.offset <= selection_offset_start <= entry.offset + entry.content.length) else if entry.type == "delete" isChangeEntryAndWithinSelection = selection_offset_start <= entry.offset <= selection_offset_end entry.focused = (entry.offset == selection_offset_start) else if entry.type == "aggregate-change" isChangeEntryAndWithinSelection = entry.offset >= selection_offset_start and entry.offset + entry.content.length <= selection_offset_end entry.focused = (entry.offset <= selection_offset_start <= entry.offset + entry.content.length) else if entry.type in [ "add-comment", "bulk-actions" ] and selection entry.focused = true if isChangeEntryAndWithinSelection for entry_id in entry.entry_ids $scope.reviewPanel.selectedEntryIds.push entry_id $scope.reviewPanel.nVisibleSelectedChanges++ $scope.$broadcast "review-panel:recalculate-screen-positions" $scope.$broadcast "review-panel:layout" $scope.acceptChanges = (change_ids) -> _doAcceptChanges change_ids event_tracking.sendMB "rp-changes-accepted", { view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini' } $scope.rejectChanges = (change_ids) -> _doRejectChanges change_ids event_tracking.sendMB "rp-changes-rejected", { view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini' } _doAcceptChanges = (change_ids) -> $http.post "/project/#{$scope.project_id}/doc/#{$scope.editor.open_doc_id}/changes/accept", { change_ids, _csrf: window.csrfToken} $scope.$broadcast "changes:accept", change_ids _doRejectChanges = (change_ids) -> $scope.$broadcast "changes:reject", change_ids bulkAccept = () -> _doAcceptChanges $scope.reviewPanel.selectedEntryIds.slice() event_tracking.sendMB "rp-bulk-accept", { view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini', nEntries: $scope.reviewPanel.nVisibleSelectedChanges } bulkReject = () -> _doRejectChanges $scope.reviewPanel.selectedEntryIds.slice() event_tracking.sendMB "rp-bulk-reject", { view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini', nEntries: $scope.reviewPanel.nVisibleSelectedChanges } $scope.showBulkAcceptDialog = () -> showBulkActionsDialog true $scope.showBulkRejectDialog = () -> showBulkActionsDialog false showBulkActionsDialog = (isAccept) -> $modal.open({ templateUrl: "bulkActionsModalTemplate" controller: "BulkActionsModalController" resolve: isAccept: () -> isAccept nChanges: () -> $scope.reviewPanel.nVisibleSelectedChanges scope: $scope.$new() }).result.then (isAccept) -> if isAccept bulkAccept() else bulkReject() $scope.handleTogglerClick = (e) -> e.target.blur() $scope.toggleReviewPanel() $scope.addNewComment = () -> $scope.$broadcast "comment:start_adding" $scope.toggleReviewPanel() $scope.addNewCommentFromKbdShortcut = () -> if !$scope.project.features.trackChangesVisible return $scope.$broadcast "comment:select_line" if !$scope.ui.reviewPanelOpen $scope.toggleReviewPanel() $timeout () -> $scope.$broadcast "review-panel:layout" $scope.$broadcast "comment:start_adding" $scope.startNewComment = () -> $scope.$broadcast "comment:select_line" $timeout () -> $scope.$broadcast "review-panel:layout" $scope.submitNewComment = (content) -> return if !content? or content == "" doc_id = $scope.editor.open_doc_id entries = getDocEntries(doc_id) return if !entries["add-comment"]? {offset, length} = entries["add-comment"] thread_id = RangesTracker.generateId() thread = getThread(thread_id) thread.submitting = true $scope.$broadcast "comment:add", thread_id, offset, length $http.post("/project/#{$scope.project_id}/thread/#{thread_id}/messages", {content, _csrf: window.csrfToken}) .catch () -> ide.showGenericMessageModal("Error submitting comment", "Sorry, there was a problem submitting your comment") $scope.$broadcast "editor:clearSelection" $timeout () -> $scope.$broadcast "review-panel:layout" event_tracking.sendMB "rp-new-comment", { size: content.length } $scope.cancelNewComment = (entry) -> $timeout () -> $scope.$broadcast "review-panel:layout" $scope.startReply = (entry) -> entry.replying = true $timeout () -> $scope.$broadcast "review-panel:layout" $scope.submitReply = (entry, entry_id) -> thread_id = entry.thread_id content = entry.replyContent $http.post("/project/#{$scope.project_id}/thread/#{thread_id}/messages", {content, _csrf: window.csrfToken}) .catch () -> ide.showGenericMessageModal("Error submitting comment", "Sorry, there was a problem submitting your comment") trackingMetadata = view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini' size: entry.replyContent.length thread: thread_id thread = getThread(thread_id) thread.submitting = true entry.replyContent = "" entry.replying = false $timeout () -> $scope.$broadcast "review-panel:layout" event_tracking.sendMB "rp-comment-reply", trackingMetadata $scope.cancelReply = (entry) -> entry.replying = false entry.replyContent = "" $scope.$broadcast "review-panel:layout" $scope.resolveComment = (entry, entry_id) -> entry.focused = false $http.post "/project/#{$scope.project_id}/thread/#{entry.thread_id}/resolve", {_csrf: window.csrfToken} _onCommentResolved(entry.thread_id, ide.$scope.user) event_tracking.sendMB "rp-comment-resolve", { view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini' } $scope.unresolveComment = (thread_id) -> _onCommentReopened(thread_id) $http.post "/project/#{$scope.project_id}/thread/#{thread_id}/reopen", {_csrf: window.csrfToken} event_tracking.sendMB "rp-comment-reopen" _onCommentResolved = (thread_id, user) -> thread = getThread(thread_id) return if !thread? thread.resolved = true thread.resolved_by_user = formatUser(user) thread.resolved_at = new Date().toISOString() $scope.reviewPanel.resolvedThreadIds[thread_id] = true $scope.$broadcast "comment:resolve_threads", [thread_id] _onCommentReopened = (thread_id) -> thread = getThread(thread_id) return if !thread? delete thread.resolved delete thread.resolved_by_user delete thread.resolved_at delete $scope.reviewPanel.resolvedThreadIds[thread_id] $scope.$broadcast "comment:unresolve_thread", thread_id _onThreadDeleted = (thread_id) -> delete $scope.reviewPanel.resolvedThreadIds[thread_id] delete $scope.reviewPanel.commentThreads[thread_id] $scope.$broadcast "comment:remove", thread_id _onCommentEdited = (thread_id, comment_id, content) -> thread = getThread(thread_id) return if !thread? for message in thread.messages if message.id == comment_id message.content = content updateEntries() _onCommentDeleted = (thread_id, comment_id) -> thread = getThread(thread_id) return if !thread? thread.messages = thread.messages.filter (m) -> m.id != comment_id updateEntries() $scope.deleteThread = (entry_id, doc_id, thread_id) -> _onThreadDeleted(thread_id) $http({ method: "DELETE" url: "/project/#{$scope.project_id}/doc/#{doc_id}/thread/#{thread_id}", headers: { 'X-CSRF-Token': window.csrfToken } }) event_tracking.sendMB "rp-comment-delete" $scope.saveEdit = (thread_id, comment) -> $http.post("/project/#{$scope.project_id}/thread/#{thread_id}/messages/#{comment.id}/edit", { content: comment.content _csrf: window.csrfToken }) $timeout () -> $scope.$broadcast "review-panel:layout" $scope.deleteComment = (thread_id, comment) -> _onCommentDeleted(thread_id, comment.id) $http({ method: "DELETE" url: "/project/#{$scope.project_id}/thread/#{thread_id}/messages/#{comment.id}", headers: { 'X-CSRF-Token': window.csrfToken } }) $timeout () -> $scope.$broadcast "review-panel:layout" $scope.setSubView = (subView) -> $scope.reviewPanel.subView = subView event_tracking.sendMB "rp-subview-change", { subView } $scope.gotoEntry = (doc_id, entry) -> ide.editorManager.openDocId(doc_id, { gotoOffset: entry.offset }) $scope.toggleFullTCStateCollapse = () -> if $scope.project.features.trackChanges $scope.reviewPanel.fullTCStateCollapsed = !$scope.reviewPanel.fullTCStateCollapsed else $scope.openTrackChangesUpgradeModal() _setUserTCState = (userId, newValue, isLocal = false) -> $scope.reviewPanel.trackChangesState[userId] ?= {} state = $scope.reviewPanel.trackChangesState[userId] if !state.syncState? or state.syncState == UserTCSyncState.SYNCED state.value = newValue state.syncState = UserTCSyncState.SYNCED else if state.syncState == UserTCSyncState.PENDING and state.value == newValue state.syncState = UserTCSyncState.SYNCED else if isLocal state.value = newValue state.syncState = UserTCSyncState.PENDING if userId == ide.$scope.user.id $scope.editor.wantTrackChanges = newValue _setEveryoneTCState = (newValue, isLocal = false) -> $scope.reviewPanel.trackChangesOnForEveryone = newValue project = $scope.project for member in project.members _setUserTCState(member._id, newValue, isLocal) _setGuestsTCState(newValue, isLocal) _setUserTCState(project.owner._id, newValue, isLocal) _setGuestsTCState = (newValue, isLocal = false) -> $scope.reviewPanel.trackChangesOnForGuests = newValue if currentUserType() == UserTypes.GUEST or currentUserType() == UserTypes.ANONYMOUS $scope.editor.wantTrackChanges = newValue applyClientTrackChangesStateToServer = () -> data = {} if $scope.reviewPanel.trackChangesOnForEveryone data.on = true else data.on_for = {} for userId, userState of $scope.reviewPanel.trackChangesState data.on_for[userId] = userState.value if $scope.reviewPanel.trackChangesOnForGuests data.on_for_guests = true data._csrf = window.csrfToken $http.post "/project/#{$scope.project_id}/track_changes", data applyTrackChangesStateToClient = (state) -> if typeof state is "boolean" _setEveryoneTCState state _setGuestsTCState state else project = $scope.project $scope.reviewPanel.trackChangesOnForEveryone = false _setGuestsTCState(state.__guests__ == true) for member in project.members _setUserTCState(member._id, state[member._id] ? false) _setUserTCState($scope.project.owner._id, state[$scope.project.owner._id] ? false) $scope.toggleTrackChangesForEveryone = (onForEveryone) -> _setEveryoneTCState onForEveryone, true _setGuestsTCState onForEveryone, true applyClientTrackChangesStateToServer() $scope.toggleTrackChangesForGuests = (onForGuests) -> _setGuestsTCState onForGuests, true applyClientTrackChangesStateToServer() $scope.toggleTrackChangesForUser = (onForUser, userId) -> _setUserTCState userId, onForUser, true applyClientTrackChangesStateToServer() ide.socket.on "toggle-track-changes", (state) -> $scope.$apply () -> applyTrackChangesStateToClient(state) $scope.toggleTrackChangesFromKbdShortcut = () -> if !($scope.project.features.trackChangesVisible && $scope.project.features.trackChanges) return $scope.toggleTrackChangesForUser !$scope.reviewPanel.trackChangesState[ide.$scope.user.id].value, ide.$scope.user.id setGuestFeatureBasedOnProjectAccessLevel = (projectPublicAccessLevel) -> $scope.reviewPanel.trackChangesForGuestsAvailable = (projectPublicAccessLevel == 'tokenBased') onToggleTrackChangesForGuestsAvailability = (available) -> # If the feature is no longer available we need to turn off the guest flag return if available return if !$scope.reviewPanel.trackChangesOnForGuests # Already turned off return if $scope.reviewPanel.trackChangesOnForEveryone # Overrides guest setting $scope.toggleTrackChangesForGuests(false) $scope.$watch 'project.publicAccesLevel', setGuestFeatureBasedOnProjectAccessLevel $scope.$watch 'reviewPanel.trackChangesForGuestsAvailable', (available) -> if available? onToggleTrackChangesForGuestsAvailability(available) _inited = false ide.$scope.$on "project:joined", () -> return if _inited project = ide.$scope.project if project.features.trackChanges window.trackChangesState ?= false applyTrackChangesStateToClient(window.trackChangesState) else applyTrackChangesStateToClient(false) setGuestFeatureBasedOnProjectAccessLevel(project.publicAccesLevel) _inited = true _refreshingRangeUsers = false _refreshedForUserIds = {} refreshChangeUsers = (refresh_for_user_id) -> if refresh_for_user_id? if _refreshedForUserIds[refresh_for_user_id]? # We've already tried to refresh to get this user id, so stop it looping return _refreshedForUserIds[refresh_for_user_id] = true # Only do one refresh at once if _refreshingRangeUsers return _refreshingRangeUsers = true $http.get "/project/#{$scope.project_id}/changes/users" .then (response) -> users = response.data _refreshingRangeUsers = false $scope.users = {} # Always include ourself, since if we submit an op, we might need to display info # about it locally before it has been flushed through the server if ide.$scope.user?.id? $scope.users[ide.$scope.user.id] = formatUser(ide.$scope.user) for user in users if user.id? $scope.users[user.id] = formatUser(user) .catch () -> _refreshingRangeUsers = false _threadsLoaded = false ensureThreadsAreLoaded = () -> if _threadsLoaded # We get any updates in real time so only need to load them once. return _threadsLoaded = true $scope.reviewPanel.loadingThreads = true $http.get "/project/#{$scope.project_id}/threads" .then (response) -> threads = response.data $scope.reviewPanel.loadingThreads = false for thread_id, _ of $scope.reviewPanel.resolvedThreadIds delete $scope.reviewPanel.resolvedThreadIds[thread_id] for thread_id, thread of threads for comment in thread.messages formatComment(comment) if thread.resolved_by_user? thread.resolved_by_user = formatUser(thread.resolved_by_user) $scope.reviewPanel.resolvedThreadIds[thread_id] = true $scope.$broadcast "comment:resolve_threads", [thread_id] $scope.reviewPanel.commentThreads = threads $timeout () -> $scope.$broadcast "review-panel:layout" formatComment = (comment) -> comment.user = formatUser(comment.user) comment.timestamp = new Date(comment.timestamp) return comment formatUser = (user) -> id = user?._id or user?.id if !id? return { email: null name: "<NAME>" isSelf: false hue: ColorManager.ANONYMOUS_HUE avatar_text: "A" } if id == window.user_id name = "You" isSelf = true else name = [user.first_name, user.last_name].filter((n) -> n? and n != "").join(" ") if name == "" name = user.email?.split("@")[0] or "Unknown" isSelf = false return { id: id email: user.email name: name isSelf: isSelf hue: ColorManager.getHueForUserId(id) avatar_text: [user.first_name, user.last_name].filter((n) -> n?).map((n) -> n[0]).join "" } $scope.openTrackChangesUpgradeModal = () -> $modal.open { templateUrl: "trackChangesUpgradeModalTemplate" controller: "TrackChangesUpgradeModalController" scope: $scope.$new() }
true
define [ "base", "utils/EventEmitter" "ide/colors/ColorManager" "ide/review-panel/RangesTracker" ], (App, EventEmitter, ColorManager, RangesTracker) -> App.controller "ReviewPanelController", ($scope, $element, ide, $timeout, $http, $modal, event_tracking, localStorage) -> $reviewPanelEl = $element.find "#review-panel" UserTypes = MEMBER: 'member' # Invited, listed in project.members GUEST: 'guest' # Not invited, but logged in so has a user_id ANONYMOUS: 'anonymous' # No user_id currentUserType = () -> if !ide.$scope.user?.id? return UserTypes.ANONYMOUS else user_id = ide.$scope.user.id project = ide.$scope.project if project.owner?.id == user_id return UserTypes.MEMBER for member in project.members if member._id == user_id return UserTypes.MEMBER return UserTypes.GUEST $scope.SubViews = CUR_FILE : "cur_file" OVERVIEW : "overview" $scope.UserTCSyncState = UserTCSyncState = SYNCED : "synced" PENDING : "pending" $scope.reviewPanel = trackChangesState: {} trackChangesOnForEveryone: false trackChangesOnForGuests: false trackChangesForGuestsAvailable: false entries: {} resolvedComments: {} hasEntries: false subView: $scope.SubViews.CUR_FILE openSubView: $scope.SubViews.CUR_FILE overview: loading: false docsCollapsedState: JSON.parse(localStorage("docs_collapsed_state:#{$scope.project_id}")) or {} dropdown: loading: false commentThreads: {} resolvedThreadIds: {} rendererData: {} formattedProjectMembers: {} fullTCStateCollapsed: true loadingThreads: false # All selected changes. If a aggregated change (insertion + deletion) is selection, the two ids # will be present. The length of this array will differ from the count below (see explanation). selectedEntryIds: [] # A count of user-facing selected changes. An aggregated change (insertion + deletion) will count # as only one. nVisibleSelectedChanges: 0 window.addEventListener "beforeunload", () -> collapsedStates = {} for doc, state of $scope.reviewPanel.overview.docsCollapsedState if state collapsedStates[doc] = state valToStore = if Object.keys(collapsedStates).length > 0 then JSON.stringify(collapsedStates) else null localStorage("docs_collapsed_state:#{$scope.project_id}", valToStore) $scope.$on "layout:pdf:linked", (event, state) -> $scope.$broadcast "review-panel:layout" $scope.$on "layout:pdf:resize", (event, state) -> $scope.$broadcast "review-panel:layout", false $scope.$on "expandable-text-area:resize", (event) -> $timeout () -> $scope.$broadcast "review-panel:layout" $scope.$on "review-panel:sizes", (e, sizes) -> $scope.$broadcast "editor:set-scroll-size", sizes $scope.$watch "project.features.trackChangesVisible", (visible) -> return if !visible? if !visible $scope.ui.reviewPanelOpen = false $scope.$watch "project.members", (members) -> $scope.reviewPanel.formattedProjectMembers = {} if $scope.project?.owner? $scope.reviewPanel.formattedProjectMembers[$scope.project.owner._id] = formatUser($scope.project.owner) if $scope.project?.members? for member in members if member.privileges == "readAndWrite" $scope.reviewPanel.formattedProjectMembers[member._id] = formatUser(member) $scope.commentState = adding: false content: "" $scope.users = {} $scope.reviewPanelEventsBridge = new EventEmitter() ide.socket.on "new-comment", (thread_id, comment) -> thread = getThread(thread_id) delete thread.submitting thread.messages.push(formatComment(comment)) $scope.$apply() $timeout () -> $scope.$broadcast "review-panel:layout" ide.socket.on "accept-changes", (doc_id, change_ids) -> if doc_id != $scope.editor.open_doc_id getChangeTracker(doc_id).removeChangeIds(change_ids) else $scope.$broadcast "changes:accept", change_ids updateEntries(doc_id) $scope.$apply () -> ide.socket.on "resolve-thread", (thread_id, user) -> _onCommentResolved(thread_id, user) ide.socket.on "reopen-thread", (thread_id) -> _onCommentReopened(thread_id) ide.socket.on "delete-thread", (thread_id) -> _onThreadDeleted(thread_id) $scope.$apply () -> ide.socket.on "edit-message", (thread_id, message_id, content) -> _onCommentEdited(thread_id, message_id, content) $scope.$apply () -> ide.socket.on "delete-message", (thread_id, message_id) -> _onCommentDeleted(thread_id, message_id) $scope.$apply () -> rangesTrackers = {} getDocEntries = (doc_id) -> $scope.reviewPanel.entries[doc_id] ?= {} return $scope.reviewPanel.entries[doc_id] getDocResolvedComments = (doc_id) -> $scope.reviewPanel.resolvedComments[doc_id] ?= {} return $scope.reviewPanel.resolvedComments[doc_id] getThread = (thread_id) -> $scope.reviewPanel.commentThreads[thread_id] ?= { messages: [] } return $scope.reviewPanel.commentThreads[thread_id] getChangeTracker = (doc_id) -> if !rangesTrackers[doc_id]? rangesTrackers[doc_id] = new RangesTracker() rangesTrackers[doc_id].resolvedThreadIds = $scope.reviewPanel.resolvedThreadIds return rangesTrackers[doc_id] scrollbar = {} $scope.reviewPanelEventsBridge.on "aceScrollbarVisibilityChanged", (isVisible, scrollbarWidth) -> scrollbar = {isVisible, scrollbarWidth} updateScrollbar() updateScrollbar = () -> if scrollbar.isVisible and $scope.reviewPanel.subView == $scope.SubViews.CUR_FILE $reviewPanelEl.css "right", "#{ scrollbar.scrollbarWidth }px" else $reviewPanelEl.css "right", "0" $scope.$watch "!ui.reviewPanelOpen && reviewPanel.hasEntries", (open, prevVal) -> return if !open? $scope.ui.miniReviewPanelVisible = open if open != prevVal $timeout () -> $scope.$broadcast "review-panel:toggle" $scope.$watch "ui.reviewPanelOpen", (open) -> return if !open? if !open # Always show current file when not open, but save current state $scope.reviewPanel.openSubView = $scope.reviewPanel.subView $scope.reviewPanel.subView = $scope.SubViews.CUR_FILE else # Reset back to what we had when previously open $scope.reviewPanel.subView = $scope.reviewPanel.openSubView $timeout () -> $scope.$broadcast "review-panel:toggle" $scope.$broadcast "review-panel:layout", false $scope.$watch "reviewPanel.subView", (view) -> return if !view? updateScrollbar() if view == $scope.SubViews.OVERVIEW refreshOverviewPanel() $scope.$watch "editor.sharejs_doc", (doc, old_doc) -> return if !doc? # The open doc range tracker is kept up to date in real-time so # replace any outdated info with this rangesTrackers[doc.doc_id] = doc.ranges rangesTrackers[doc.doc_id].resolvedThreadIds = $scope.reviewPanel.resolvedThreadIds $scope.reviewPanel.rangesTracker = rangesTrackers[doc.doc_id] if old_doc? old_doc.off "flipped_pending_to_inflight" doc.on "flipped_pending_to_inflight", () -> regenerateTrackChangesId(doc) regenerateTrackChangesId(doc) $scope.$watch (() -> entries = $scope.reviewPanel.entries[$scope.editor.open_doc_id] or {} permEntries = {} for entry, entryData of entries if entry not in [ "add-comment", "bulk-actions" ] permEntries[entry] = entryData Object.keys(permEntries).length ), (nEntries) -> $scope.reviewPanel.hasEntries = nEntries > 0 and $scope.project.features.trackChangesVisible regenerateTrackChangesId = (doc) -> old_id = getChangeTracker(doc.doc_id).getIdSeed() new_id = RangesTracker.generateIdSeed() getChangeTracker(doc.doc_id).setIdSeed(new_id) doc.setTrackChangesIdSeeds({pending: new_id, inflight: old_id}) refreshRanges = () -> $http.get "/project/#{$scope.project_id}/ranges" .then (response) -> docs = response.data for doc in docs if !$scope.reviewPanel.overview.docsCollapsedState[doc.id]? $scope.reviewPanel.overview.docsCollapsedState[doc.id] = false if doc.id != $scope.editor.open_doc_id # this is kept up to date in real-time, don't overwrite rangesTracker = getChangeTracker(doc.id) rangesTracker.comments = doc.ranges?.comments or [] rangesTracker.changes = doc.ranges?.changes or [] updateEntries(doc.id) refreshOverviewPanel = () -> $scope.reviewPanel.overview.loading = true refreshRanges() .then () -> $scope.reviewPanel.overview.loading = false .catch () -> $scope.reviewPanel.overview.loading = false $scope.refreshResolvedCommentsDropdown = () -> $scope.reviewPanel.dropdown.loading = true q = refreshRanges() q.then () -> $scope.reviewPanel.dropdown.loading = false q.catch () -> $scope.reviewPanel.dropdown.loading = false return q updateEntries = (doc_id) -> rangesTracker = getChangeTracker(doc_id) entries = getDocEntries(doc_id) resolvedComments = getDocResolvedComments(doc_id) changed = false # Assume we'll delete everything until we see it, then we'll remove it from this object delete_changes = {} for id, change of entries if id not in [ "add-comment", "bulk-actions" ] for entry_id in change.entry_ids delete_changes[entry_id] = true for id, change of resolvedComments for entry_id in change.entry_ids delete_changes[entry_id] = true potential_aggregate = false prev_insertion = null for change in rangesTracker.changes changed = true if ( potential_aggregate and change.op.d and change.op.p == prev_insertion.op.p + prev_insertion.op.i.length and change.metadata.user_id == prev_insertion.metadata.user_id ) # An actual aggregate op. entries[prev_insertion.id].type = "aggregate-change" entries[prev_insertion.id].metadata.replaced_content = change.op.d entries[prev_insertion.id].entry_ids.push change.id else entries[change.id] ?= {} delete delete_changes[change.id] new_entry = { type: if change.op.i then "insert" else "delete" entry_ids: [ change.id ] content: change.op.i or change.op.d offset: change.op.p metadata: change.metadata } for key, value of new_entry entries[change.id][key] = value if change.op.i potential_aggregate = true prev_insertion = change else potential_aggregate = false prev_insertion = null if !$scope.users[change.metadata.user_id]? refreshChangeUsers(change.metadata.user_id) if rangesTracker.comments.length > 0 ensureThreadsAreLoaded() for comment in rangesTracker.comments changed = true delete delete_changes[comment.id] if $scope.reviewPanel.resolvedThreadIds[comment.op.t] new_comment = resolvedComments[comment.id] ?= {} delete entries[comment.id] else new_comment = entries[comment.id] ?= {} delete resolvedComments[comment.id] new_entry = { type: "comment" thread_id: comment.op.t entry_ids: [ comment.id ] content: comment.op.c offset: comment.op.p } for key, value of new_entry new_comment[key] = value for change_id, _ of delete_changes changed = true delete entries[change_id] delete resolvedComments[change_id] if changed $scope.$broadcast "entries:changed" $scope.$on "editor:track-changes:changed", () -> doc_id = $scope.editor.open_doc_id updateEntries(doc_id) $scope.$broadcast "review-panel:recalculate-screen-positions" $scope.$broadcast "review-panel:layout" $scope.$on "editor:track-changes:visibility_changed", () -> $timeout () -> $scope.$broadcast "review-panel:layout", false $scope.$on "editor:focus:changed", (e, selection_offset_start, selection_offset_end, selection) -> doc_id = $scope.editor.open_doc_id entries = getDocEntries(doc_id) # All selected changes will be added to this array. $scope.reviewPanel.selectedEntryIds = [] # Count of user-visible changes, i.e. an aggregated change will count as one. $scope.reviewPanel.nVisibleSelectedChanges = 0 delete entries["add-comment"] delete entries["bulk-actions"] if selection entries["add-comment"] = { type: "add-comment" offset: selection_offset_start length: selection_offset_end - selection_offset_start } entries["bulk-actions"] = { type: "bulk-actions" offset: selection_offset_start length: selection_offset_end - selection_offset_start } for id, entry of entries isChangeEntryAndWithinSelection = false if entry.type == "comment" and not $scope.reviewPanel.resolvedThreadIds[entry.thread_id] entry.focused = (entry.offset <= selection_offset_start <= entry.offset + entry.content.length) else if entry.type == "insert" isChangeEntryAndWithinSelection = entry.offset >= selection_offset_start and entry.offset + entry.content.length <= selection_offset_end entry.focused = (entry.offset <= selection_offset_start <= entry.offset + entry.content.length) else if entry.type == "delete" isChangeEntryAndWithinSelection = selection_offset_start <= entry.offset <= selection_offset_end entry.focused = (entry.offset == selection_offset_start) else if entry.type == "aggregate-change" isChangeEntryAndWithinSelection = entry.offset >= selection_offset_start and entry.offset + entry.content.length <= selection_offset_end entry.focused = (entry.offset <= selection_offset_start <= entry.offset + entry.content.length) else if entry.type in [ "add-comment", "bulk-actions" ] and selection entry.focused = true if isChangeEntryAndWithinSelection for entry_id in entry.entry_ids $scope.reviewPanel.selectedEntryIds.push entry_id $scope.reviewPanel.nVisibleSelectedChanges++ $scope.$broadcast "review-panel:recalculate-screen-positions" $scope.$broadcast "review-panel:layout" $scope.acceptChanges = (change_ids) -> _doAcceptChanges change_ids event_tracking.sendMB "rp-changes-accepted", { view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini' } $scope.rejectChanges = (change_ids) -> _doRejectChanges change_ids event_tracking.sendMB "rp-changes-rejected", { view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini' } _doAcceptChanges = (change_ids) -> $http.post "/project/#{$scope.project_id}/doc/#{$scope.editor.open_doc_id}/changes/accept", { change_ids, _csrf: window.csrfToken} $scope.$broadcast "changes:accept", change_ids _doRejectChanges = (change_ids) -> $scope.$broadcast "changes:reject", change_ids bulkAccept = () -> _doAcceptChanges $scope.reviewPanel.selectedEntryIds.slice() event_tracking.sendMB "rp-bulk-accept", { view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini', nEntries: $scope.reviewPanel.nVisibleSelectedChanges } bulkReject = () -> _doRejectChanges $scope.reviewPanel.selectedEntryIds.slice() event_tracking.sendMB "rp-bulk-reject", { view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini', nEntries: $scope.reviewPanel.nVisibleSelectedChanges } $scope.showBulkAcceptDialog = () -> showBulkActionsDialog true $scope.showBulkRejectDialog = () -> showBulkActionsDialog false showBulkActionsDialog = (isAccept) -> $modal.open({ templateUrl: "bulkActionsModalTemplate" controller: "BulkActionsModalController" resolve: isAccept: () -> isAccept nChanges: () -> $scope.reviewPanel.nVisibleSelectedChanges scope: $scope.$new() }).result.then (isAccept) -> if isAccept bulkAccept() else bulkReject() $scope.handleTogglerClick = (e) -> e.target.blur() $scope.toggleReviewPanel() $scope.addNewComment = () -> $scope.$broadcast "comment:start_adding" $scope.toggleReviewPanel() $scope.addNewCommentFromKbdShortcut = () -> if !$scope.project.features.trackChangesVisible return $scope.$broadcast "comment:select_line" if !$scope.ui.reviewPanelOpen $scope.toggleReviewPanel() $timeout () -> $scope.$broadcast "review-panel:layout" $scope.$broadcast "comment:start_adding" $scope.startNewComment = () -> $scope.$broadcast "comment:select_line" $timeout () -> $scope.$broadcast "review-panel:layout" $scope.submitNewComment = (content) -> return if !content? or content == "" doc_id = $scope.editor.open_doc_id entries = getDocEntries(doc_id) return if !entries["add-comment"]? {offset, length} = entries["add-comment"] thread_id = RangesTracker.generateId() thread = getThread(thread_id) thread.submitting = true $scope.$broadcast "comment:add", thread_id, offset, length $http.post("/project/#{$scope.project_id}/thread/#{thread_id}/messages", {content, _csrf: window.csrfToken}) .catch () -> ide.showGenericMessageModal("Error submitting comment", "Sorry, there was a problem submitting your comment") $scope.$broadcast "editor:clearSelection" $timeout () -> $scope.$broadcast "review-panel:layout" event_tracking.sendMB "rp-new-comment", { size: content.length } $scope.cancelNewComment = (entry) -> $timeout () -> $scope.$broadcast "review-panel:layout" $scope.startReply = (entry) -> entry.replying = true $timeout () -> $scope.$broadcast "review-panel:layout" $scope.submitReply = (entry, entry_id) -> thread_id = entry.thread_id content = entry.replyContent $http.post("/project/#{$scope.project_id}/thread/#{thread_id}/messages", {content, _csrf: window.csrfToken}) .catch () -> ide.showGenericMessageModal("Error submitting comment", "Sorry, there was a problem submitting your comment") trackingMetadata = view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini' size: entry.replyContent.length thread: thread_id thread = getThread(thread_id) thread.submitting = true entry.replyContent = "" entry.replying = false $timeout () -> $scope.$broadcast "review-panel:layout" event_tracking.sendMB "rp-comment-reply", trackingMetadata $scope.cancelReply = (entry) -> entry.replying = false entry.replyContent = "" $scope.$broadcast "review-panel:layout" $scope.resolveComment = (entry, entry_id) -> entry.focused = false $http.post "/project/#{$scope.project_id}/thread/#{entry.thread_id}/resolve", {_csrf: window.csrfToken} _onCommentResolved(entry.thread_id, ide.$scope.user) event_tracking.sendMB "rp-comment-resolve", { view: if $scope.ui.reviewPanelOpen then $scope.reviewPanel.subView else 'mini' } $scope.unresolveComment = (thread_id) -> _onCommentReopened(thread_id) $http.post "/project/#{$scope.project_id}/thread/#{thread_id}/reopen", {_csrf: window.csrfToken} event_tracking.sendMB "rp-comment-reopen" _onCommentResolved = (thread_id, user) -> thread = getThread(thread_id) return if !thread? thread.resolved = true thread.resolved_by_user = formatUser(user) thread.resolved_at = new Date().toISOString() $scope.reviewPanel.resolvedThreadIds[thread_id] = true $scope.$broadcast "comment:resolve_threads", [thread_id] _onCommentReopened = (thread_id) -> thread = getThread(thread_id) return if !thread? delete thread.resolved delete thread.resolved_by_user delete thread.resolved_at delete $scope.reviewPanel.resolvedThreadIds[thread_id] $scope.$broadcast "comment:unresolve_thread", thread_id _onThreadDeleted = (thread_id) -> delete $scope.reviewPanel.resolvedThreadIds[thread_id] delete $scope.reviewPanel.commentThreads[thread_id] $scope.$broadcast "comment:remove", thread_id _onCommentEdited = (thread_id, comment_id, content) -> thread = getThread(thread_id) return if !thread? for message in thread.messages if message.id == comment_id message.content = content updateEntries() _onCommentDeleted = (thread_id, comment_id) -> thread = getThread(thread_id) return if !thread? thread.messages = thread.messages.filter (m) -> m.id != comment_id updateEntries() $scope.deleteThread = (entry_id, doc_id, thread_id) -> _onThreadDeleted(thread_id) $http({ method: "DELETE" url: "/project/#{$scope.project_id}/doc/#{doc_id}/thread/#{thread_id}", headers: { 'X-CSRF-Token': window.csrfToken } }) event_tracking.sendMB "rp-comment-delete" $scope.saveEdit = (thread_id, comment) -> $http.post("/project/#{$scope.project_id}/thread/#{thread_id}/messages/#{comment.id}/edit", { content: comment.content _csrf: window.csrfToken }) $timeout () -> $scope.$broadcast "review-panel:layout" $scope.deleteComment = (thread_id, comment) -> _onCommentDeleted(thread_id, comment.id) $http({ method: "DELETE" url: "/project/#{$scope.project_id}/thread/#{thread_id}/messages/#{comment.id}", headers: { 'X-CSRF-Token': window.csrfToken } }) $timeout () -> $scope.$broadcast "review-panel:layout" $scope.setSubView = (subView) -> $scope.reviewPanel.subView = subView event_tracking.sendMB "rp-subview-change", { subView } $scope.gotoEntry = (doc_id, entry) -> ide.editorManager.openDocId(doc_id, { gotoOffset: entry.offset }) $scope.toggleFullTCStateCollapse = () -> if $scope.project.features.trackChanges $scope.reviewPanel.fullTCStateCollapsed = !$scope.reviewPanel.fullTCStateCollapsed else $scope.openTrackChangesUpgradeModal() _setUserTCState = (userId, newValue, isLocal = false) -> $scope.reviewPanel.trackChangesState[userId] ?= {} state = $scope.reviewPanel.trackChangesState[userId] if !state.syncState? or state.syncState == UserTCSyncState.SYNCED state.value = newValue state.syncState = UserTCSyncState.SYNCED else if state.syncState == UserTCSyncState.PENDING and state.value == newValue state.syncState = UserTCSyncState.SYNCED else if isLocal state.value = newValue state.syncState = UserTCSyncState.PENDING if userId == ide.$scope.user.id $scope.editor.wantTrackChanges = newValue _setEveryoneTCState = (newValue, isLocal = false) -> $scope.reviewPanel.trackChangesOnForEveryone = newValue project = $scope.project for member in project.members _setUserTCState(member._id, newValue, isLocal) _setGuestsTCState(newValue, isLocal) _setUserTCState(project.owner._id, newValue, isLocal) _setGuestsTCState = (newValue, isLocal = false) -> $scope.reviewPanel.trackChangesOnForGuests = newValue if currentUserType() == UserTypes.GUEST or currentUserType() == UserTypes.ANONYMOUS $scope.editor.wantTrackChanges = newValue applyClientTrackChangesStateToServer = () -> data = {} if $scope.reviewPanel.trackChangesOnForEveryone data.on = true else data.on_for = {} for userId, userState of $scope.reviewPanel.trackChangesState data.on_for[userId] = userState.value if $scope.reviewPanel.trackChangesOnForGuests data.on_for_guests = true data._csrf = window.csrfToken $http.post "/project/#{$scope.project_id}/track_changes", data applyTrackChangesStateToClient = (state) -> if typeof state is "boolean" _setEveryoneTCState state _setGuestsTCState state else project = $scope.project $scope.reviewPanel.trackChangesOnForEveryone = false _setGuestsTCState(state.__guests__ == true) for member in project.members _setUserTCState(member._id, state[member._id] ? false) _setUserTCState($scope.project.owner._id, state[$scope.project.owner._id] ? false) $scope.toggleTrackChangesForEveryone = (onForEveryone) -> _setEveryoneTCState onForEveryone, true _setGuestsTCState onForEveryone, true applyClientTrackChangesStateToServer() $scope.toggleTrackChangesForGuests = (onForGuests) -> _setGuestsTCState onForGuests, true applyClientTrackChangesStateToServer() $scope.toggleTrackChangesForUser = (onForUser, userId) -> _setUserTCState userId, onForUser, true applyClientTrackChangesStateToServer() ide.socket.on "toggle-track-changes", (state) -> $scope.$apply () -> applyTrackChangesStateToClient(state) $scope.toggleTrackChangesFromKbdShortcut = () -> if !($scope.project.features.trackChangesVisible && $scope.project.features.trackChanges) return $scope.toggleTrackChangesForUser !$scope.reviewPanel.trackChangesState[ide.$scope.user.id].value, ide.$scope.user.id setGuestFeatureBasedOnProjectAccessLevel = (projectPublicAccessLevel) -> $scope.reviewPanel.trackChangesForGuestsAvailable = (projectPublicAccessLevel == 'tokenBased') onToggleTrackChangesForGuestsAvailability = (available) -> # If the feature is no longer available we need to turn off the guest flag return if available return if !$scope.reviewPanel.trackChangesOnForGuests # Already turned off return if $scope.reviewPanel.trackChangesOnForEveryone # Overrides guest setting $scope.toggleTrackChangesForGuests(false) $scope.$watch 'project.publicAccesLevel', setGuestFeatureBasedOnProjectAccessLevel $scope.$watch 'reviewPanel.trackChangesForGuestsAvailable', (available) -> if available? onToggleTrackChangesForGuestsAvailability(available) _inited = false ide.$scope.$on "project:joined", () -> return if _inited project = ide.$scope.project if project.features.trackChanges window.trackChangesState ?= false applyTrackChangesStateToClient(window.trackChangesState) else applyTrackChangesStateToClient(false) setGuestFeatureBasedOnProjectAccessLevel(project.publicAccesLevel) _inited = true _refreshingRangeUsers = false _refreshedForUserIds = {} refreshChangeUsers = (refresh_for_user_id) -> if refresh_for_user_id? if _refreshedForUserIds[refresh_for_user_id]? # We've already tried to refresh to get this user id, so stop it looping return _refreshedForUserIds[refresh_for_user_id] = true # Only do one refresh at once if _refreshingRangeUsers return _refreshingRangeUsers = true $http.get "/project/#{$scope.project_id}/changes/users" .then (response) -> users = response.data _refreshingRangeUsers = false $scope.users = {} # Always include ourself, since if we submit an op, we might need to display info # about it locally before it has been flushed through the server if ide.$scope.user?.id? $scope.users[ide.$scope.user.id] = formatUser(ide.$scope.user) for user in users if user.id? $scope.users[user.id] = formatUser(user) .catch () -> _refreshingRangeUsers = false _threadsLoaded = false ensureThreadsAreLoaded = () -> if _threadsLoaded # We get any updates in real time so only need to load them once. return _threadsLoaded = true $scope.reviewPanel.loadingThreads = true $http.get "/project/#{$scope.project_id}/threads" .then (response) -> threads = response.data $scope.reviewPanel.loadingThreads = false for thread_id, _ of $scope.reviewPanel.resolvedThreadIds delete $scope.reviewPanel.resolvedThreadIds[thread_id] for thread_id, thread of threads for comment in thread.messages formatComment(comment) if thread.resolved_by_user? thread.resolved_by_user = formatUser(thread.resolved_by_user) $scope.reviewPanel.resolvedThreadIds[thread_id] = true $scope.$broadcast "comment:resolve_threads", [thread_id] $scope.reviewPanel.commentThreads = threads $timeout () -> $scope.$broadcast "review-panel:layout" formatComment = (comment) -> comment.user = formatUser(comment.user) comment.timestamp = new Date(comment.timestamp) return comment formatUser = (user) -> id = user?._id or user?.id if !id? return { email: null name: "PI:NAME:<NAME>END_PI" isSelf: false hue: ColorManager.ANONYMOUS_HUE avatar_text: "A" } if id == window.user_id name = "You" isSelf = true else name = [user.first_name, user.last_name].filter((n) -> n? and n != "").join(" ") if name == "" name = user.email?.split("@")[0] or "Unknown" isSelf = false return { id: id email: user.email name: name isSelf: isSelf hue: ColorManager.getHueForUserId(id) avatar_text: [user.first_name, user.last_name].filter((n) -> n?).map((n) -> n[0]).join "" } $scope.openTrackChangesUpgradeModal = () -> $modal.open { templateUrl: "trackChangesUpgradeModalTemplate" controller: "TrackChangesUpgradeModalController" scope: $scope.$new() }
[ { "context": " fabricate 'partner', type: 'Institution', name: 'J. Paul Getty Museum', sortable_id: 'getty'\n fabricate 'featured_", "end": 655, "score": 0.998993992805481, "start": 635, "tag": "NAME", "value": "J. Paul Getty Museum" }, { "context": "ricate 'featured_partners_pr...
src/desktop/apps/galleries_institutions/test/a_to_z.coffee
kanaabe/force
1
benv = require 'benv' { resolve } = require 'path' { fabricate } = require 'antigravity' Profiles = require '../../../collections/profiles' describe 'Galleries / Institutions', -> before -> @profiles = new Profiles [ fabricate 'featured_partners_profiles', id: '43-salon-inter-nacional-de-artistas' owner_type: 'PartnerInstitution' owner: fabricate 'partner', type: 'Institution', name: '43 Salon (Inter) Nacional de Artistas' fabricate 'featured_partners_profiles', id: 'getty' owner_type: 'PartnerInstitution' owner: fabricate 'partner', type: 'Institution', name: 'J. Paul Getty Museum', sortable_id: 'getty' fabricate 'featured_partners_profiles', id: 'lacma' owner_type: 'PartnerInstitution' owner: fabricate 'partner', type: 'Institution', name: 'LACMA' ] @aToZGroup = @profiles.groupByAlphaWithColumns 3 beforeEach (done) -> benv.setup => benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') benv.render resolve(__dirname, '../templates/a_z.jade'), { sd: CURRENT_PATH: '/institution-a-z' asset: (->) aToZGroup: @aToZGroup type: 'institution' showAZLink: false }, done afterEach -> benv.teardown() describe 'template', -> it 'renders an A to Z list of partners with links to the partner', -> markup = $('.galleries-institutions-page').html() markup.should.containEql ('Browse Institutions') @profiles.each (profile) -> markup.should.containEql profile.related().owner.get('name') markup.should.containEql "/#{profile.id}" $('.a-to-z-row-letter').eq(0).text().should.equal @aToZGroup[0].letter $('.a-to-z-row-letter').eq(1).text().should.equal @aToZGroup[1].letter $('.a-to-z-row-letter').eq(2).text().should.equal @aToZGroup[2].letter
107510
benv = require 'benv' { resolve } = require 'path' { fabricate } = require 'antigravity' Profiles = require '../../../collections/profiles' describe 'Galleries / Institutions', -> before -> @profiles = new Profiles [ fabricate 'featured_partners_profiles', id: '43-salon-inter-nacional-de-artistas' owner_type: 'PartnerInstitution' owner: fabricate 'partner', type: 'Institution', name: '43 Salon (Inter) Nacional de Artistas' fabricate 'featured_partners_profiles', id: 'getty' owner_type: 'PartnerInstitution' owner: fabricate 'partner', type: 'Institution', name: '<NAME>', sortable_id: 'getty' fabricate 'featured_partners_profiles', id: 'lacma' owner_type: 'PartnerInstitution' owner: fabricate 'partner', type: 'Institution', name: '<NAME>' ] @aToZGroup = @profiles.groupByAlphaWithColumns 3 beforeEach (done) -> benv.setup => benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') benv.render resolve(__dirname, '../templates/a_z.jade'), { sd: CURRENT_PATH: '/institution-a-z' asset: (->) aToZGroup: @aToZGroup type: 'institution' showAZLink: false }, done afterEach -> benv.teardown() describe 'template', -> it 'renders an A to Z list of partners with links to the partner', -> markup = $('.galleries-institutions-page').html() markup.should.containEql ('Browse Institutions') @profiles.each (profile) -> markup.should.containEql profile.related().owner.get('name') markup.should.containEql "/#{profile.id}" $('.a-to-z-row-letter').eq(0).text().should.equal @aToZGroup[0].letter $('.a-to-z-row-letter').eq(1).text().should.equal @aToZGroup[1].letter $('.a-to-z-row-letter').eq(2).text().should.equal @aToZGroup[2].letter
true
benv = require 'benv' { resolve } = require 'path' { fabricate } = require 'antigravity' Profiles = require '../../../collections/profiles' describe 'Galleries / Institutions', -> before -> @profiles = new Profiles [ fabricate 'featured_partners_profiles', id: '43-salon-inter-nacional-de-artistas' owner_type: 'PartnerInstitution' owner: fabricate 'partner', type: 'Institution', name: '43 Salon (Inter) Nacional de Artistas' fabricate 'featured_partners_profiles', id: 'getty' owner_type: 'PartnerInstitution' owner: fabricate 'partner', type: 'Institution', name: 'PI:NAME:<NAME>END_PI', sortable_id: 'getty' fabricate 'featured_partners_profiles', id: 'lacma' owner_type: 'PartnerInstitution' owner: fabricate 'partner', type: 'Institution', name: 'PI:NAME:<NAME>END_PI' ] @aToZGroup = @profiles.groupByAlphaWithColumns 3 beforeEach (done) -> benv.setup => benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') benv.render resolve(__dirname, '../templates/a_z.jade'), { sd: CURRENT_PATH: '/institution-a-z' asset: (->) aToZGroup: @aToZGroup type: 'institution' showAZLink: false }, done afterEach -> benv.teardown() describe 'template', -> it 'renders an A to Z list of partners with links to the partner', -> markup = $('.galleries-institutions-page').html() markup.should.containEql ('Browse Institutions') @profiles.each (profile) -> markup.should.containEql profile.related().owner.get('name') markup.should.containEql "/#{profile.id}" $('.a-to-z-row-letter').eq(0).text().should.equal @aToZGroup[0].letter $('.a-to-z-row-letter').eq(1).text().should.equal @aToZGroup[1].letter $('.a-to-z-row-letter').eq(2).text().should.equal @aToZGroup[2].letter
[ { "context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.", "end": 197, "score": 0.9998759031295776, "start": 180, "tag": "NAME", "value": "Benjamin Blundell" }, { "context": " PXL.js\n ...
examples/texture.coffee
OniDaito/pxljs
1
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js Benjamin Blundell - ben@pxljs.com http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### init = () -> # Create our basic quad q = new PXL.Geometry.Quad() @n0 = new PXL.Node q # Fire a request for a texture PXL.GL.textureFromURL "/textures/wood.webp", (texture) => # Create our texture from the data and add it to our material @n0.add new PXL.Material.TextureMaterial texture # Our node is complete - add it to the topnode @topnode.add @n0 @topnode.add new PXL.GL.UberShader(@topnode) @c = new PXL.Camera.PerspCamera() @topnode = new PXL.Node @topnode.add @c draw = () -> GL.clearColor(0.15, 0.15, 0.15, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) @topnode.draw() params = canvas : 'webgl-canvas' context : @ init : init debug : true draw : draw cgl = new PXL.App params
31517
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js <NAME> - <EMAIL> http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### init = () -> # Create our basic quad q = new PXL.Geometry.Quad() @n0 = new PXL.Node q # Fire a request for a texture PXL.GL.textureFromURL "/textures/wood.webp", (texture) => # Create our texture from the data and add it to our material @n0.add new PXL.Material.TextureMaterial texture # Our node is complete - add it to the topnode @topnode.add @n0 @topnode.add new PXL.GL.UberShader(@topnode) @c = new PXL.Camera.PerspCamera() @topnode = new PXL.Node @topnode.add @c draw = () -> GL.clearColor(0.15, 0.15, 0.15, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) @topnode.draw() params = canvas : 'webgl-canvas' context : @ init : init debug : true draw : draw cgl = new PXL.App params
true
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### init = () -> # Create our basic quad q = new PXL.Geometry.Quad() @n0 = new PXL.Node q # Fire a request for a texture PXL.GL.textureFromURL "/textures/wood.webp", (texture) => # Create our texture from the data and add it to our material @n0.add new PXL.Material.TextureMaterial texture # Our node is complete - add it to the topnode @topnode.add @n0 @topnode.add new PXL.GL.UberShader(@topnode) @c = new PXL.Camera.PerspCamera() @topnode = new PXL.Node @topnode.add @c draw = () -> GL.clearColor(0.15, 0.15, 0.15, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) @topnode.draw() params = canvas : 'webgl-canvas' context : @ init : init debug : true draw : draw cgl = new PXL.App params
[ { "context": " # Check for invalid points\n if doc.navn in ['Sørfold', 'Fauske']\n for p, i in doc.geojson.coordin", "end": 1753, "score": 0.9947139024734497, "start": 1746, "tag": "NAME", "value": "Sørfold" }, { "context": "or invalid points\n if doc.navn in ['Sørfold', ...
util/kartverket_import.coffee
Turistforeningen/Geoserver
10
mongo = require '../src/mongo' async = require 'async' dashdash = require 'dashdash' readFileSync = require('fs').readFileSync options = [ names: ['help', 'h'] type: 'bool' help: 'Print this help and exit.' , names: ['file', 'f'] type: 'string' help: 'File to import.' helpArg: 'PATH' ] parser = dashdash.createParser options: options try opts = parser.parse process.argv catch e console.error 'import.coffee: error: %s', e.message process.exit 1 if opts.help or not opts.type or not opts.file help = parser.help({includeEnv: true}).trimRight() console.log 'usage: coffee import.coffee --file PATH [OPTIONS]' console.log '\nThis tool will let you import counties and municpalities from' console.log 'Kartvket to you MongoDB database. Input data must be original' console.log 'GeoJSON files obtained form Kartverket. No warranties given.\n' console.log 'options:\n' + help process.exit 0 try file = readFileSync opts.file, encoding: 'utf8' json = JSON.parse file catch e console.error 'import.coffee: error: %s', e.message process.exit 1 docs = [] cache = {} for feature in json.features doc = navn: feature.properties.navn type: feature.properties.objtype nr: feature.properties.fylkesnr or feature.properties.komm geojson: feature.geometry kilde: 'Kartverket' if doc.type is 'Fylker' # Ignore duplicates whith invalid GeoJSON if doc.geojson.coordinates[0].length < 100 continue if doc.type is 'Kommune' remove = [] # Check for invalid points if doc.navn in ['Lund', 'Sokndal'] for p, i in doc.geojson.coordinates[0] remove.push i if p[0] is 6.474612 and p[1] is 58.333559 # Check for invalid points if doc.navn in ['Sørfold', 'Fauske'] for p, i in doc.geojson.coordinates[0] remove.push i if p[0] is 15.588073 and p[1] is 67.331575 # Remove invalid points for i, offset in remove doc.geojson.coordinates[0].splice i - offset, 1 docs.push doc console.log "Saving #{docs.length} documents to db.." mongo.once 'ready', -> i = 0 grenser = mongo.db.collection 'grenser' async.eachLimit docs, 5, (doc, cb) -> console.log ++i grenser.replaceOne type: doc.type, nr: doc.nr, doc, upsert: true, cb , (err) -> mongo.db.close() throw err if err console.log 'Save success!'
3092
mongo = require '../src/mongo' async = require 'async' dashdash = require 'dashdash' readFileSync = require('fs').readFileSync options = [ names: ['help', 'h'] type: 'bool' help: 'Print this help and exit.' , names: ['file', 'f'] type: 'string' help: 'File to import.' helpArg: 'PATH' ] parser = dashdash.createParser options: options try opts = parser.parse process.argv catch e console.error 'import.coffee: error: %s', e.message process.exit 1 if opts.help or not opts.type or not opts.file help = parser.help({includeEnv: true}).trimRight() console.log 'usage: coffee import.coffee --file PATH [OPTIONS]' console.log '\nThis tool will let you import counties and municpalities from' console.log 'Kartvket to you MongoDB database. Input data must be original' console.log 'GeoJSON files obtained form Kartverket. No warranties given.\n' console.log 'options:\n' + help process.exit 0 try file = readFileSync opts.file, encoding: 'utf8' json = JSON.parse file catch e console.error 'import.coffee: error: %s', e.message process.exit 1 docs = [] cache = {} for feature in json.features doc = navn: feature.properties.navn type: feature.properties.objtype nr: feature.properties.fylkesnr or feature.properties.komm geojson: feature.geometry kilde: 'Kartverket' if doc.type is 'Fylker' # Ignore duplicates whith invalid GeoJSON if doc.geojson.coordinates[0].length < 100 continue if doc.type is 'Kommune' remove = [] # Check for invalid points if doc.navn in ['Lund', 'Sokndal'] for p, i in doc.geojson.coordinates[0] remove.push i if p[0] is 6.474612 and p[1] is 58.333559 # Check for invalid points if doc.navn in ['<NAME>', '<NAME>'] for p, i in doc.geojson.coordinates[0] remove.push i if p[0] is 15.588073 and p[1] is 67.331575 # Remove invalid points for i, offset in remove doc.geojson.coordinates[0].splice i - offset, 1 docs.push doc console.log "Saving #{docs.length} documents to db.." mongo.once 'ready', -> i = 0 grenser = mongo.db.collection 'grenser' async.eachLimit docs, 5, (doc, cb) -> console.log ++i grenser.replaceOne type: doc.type, nr: doc.nr, doc, upsert: true, cb , (err) -> mongo.db.close() throw err if err console.log 'Save success!'
true
mongo = require '../src/mongo' async = require 'async' dashdash = require 'dashdash' readFileSync = require('fs').readFileSync options = [ names: ['help', 'h'] type: 'bool' help: 'Print this help and exit.' , names: ['file', 'f'] type: 'string' help: 'File to import.' helpArg: 'PATH' ] parser = dashdash.createParser options: options try opts = parser.parse process.argv catch e console.error 'import.coffee: error: %s', e.message process.exit 1 if opts.help or not opts.type or not opts.file help = parser.help({includeEnv: true}).trimRight() console.log 'usage: coffee import.coffee --file PATH [OPTIONS]' console.log '\nThis tool will let you import counties and municpalities from' console.log 'Kartvket to you MongoDB database. Input data must be original' console.log 'GeoJSON files obtained form Kartverket. No warranties given.\n' console.log 'options:\n' + help process.exit 0 try file = readFileSync opts.file, encoding: 'utf8' json = JSON.parse file catch e console.error 'import.coffee: error: %s', e.message process.exit 1 docs = [] cache = {} for feature in json.features doc = navn: feature.properties.navn type: feature.properties.objtype nr: feature.properties.fylkesnr or feature.properties.komm geojson: feature.geometry kilde: 'Kartverket' if doc.type is 'Fylker' # Ignore duplicates whith invalid GeoJSON if doc.geojson.coordinates[0].length < 100 continue if doc.type is 'Kommune' remove = [] # Check for invalid points if doc.navn in ['Lund', 'Sokndal'] for p, i in doc.geojson.coordinates[0] remove.push i if p[0] is 6.474612 and p[1] is 58.333559 # Check for invalid points if doc.navn in ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] for p, i in doc.geojson.coordinates[0] remove.push i if p[0] is 15.588073 and p[1] is 67.331575 # Remove invalid points for i, offset in remove doc.geojson.coordinates[0].splice i - offset, 1 docs.push doc console.log "Saving #{docs.length} documents to db.." mongo.once 'ready', -> i = 0 grenser = mongo.db.collection 'grenser' async.eachLimit docs, 5, (doc, cb) -> console.log ++i grenser.replaceOne type: doc.type, nr: doc.nr, doc, upsert: true, cb , (err) -> mongo.db.close() throw err if err console.log 'Save success!'
[ { "context": ":450, height:250',\n HUBOT_GLINK_CREDS: 'user:password'\n }\n expected = {\n hostname: 'user:pas", "end": 2743, "score": 0.7787346839904785, "start": 2735, "tag": "PASSWORD", "value": "password" }, { "context": "ord'\n }\n expected = {\n hostn...
test/configurator-test.coffee
knomedia/hubot-glink
0
chai = require 'chai' sinon = require 'sinon' chai.use require 'sinon-chai' configurator = require '../lib/configurator' expect = chai.expect assert = chai.assert describe 'configurator', -> it 'doesnt blow up witout env vars', -> expected = { hostname: 'graphite.example.com', template: 'template.not.set', templateDefaults: [], paramsDefaults: {}, absoluteTimes: false } assert.deepEqual(configurator({}, '').config, expected) it 'gives out appropriate config given appropriate env', -> env = { HUBOT_GLINK_DEFAULT_APP: 'MYAPP', HUBOT_GLINK_MYAPP_TEMPLATE: 'some.template.value.##!one!##.##!two!##', HUBOT_GLINK_MYAPP_TEMPLATE_DEFAULTS: '##!one!##===users, ##!two!##===index', HUBOT_GLINK_HOSTNAME: 'graphite.example.com', HUBOT_GLINK_DEFAULT_PARAMS: 'from:-3months, width:450, height:250', } expected = { hostname: 'graphite.example.com', template: 'some.template.value.##!one!##.##!two!##', templateDefaults: [ '##!one!##===users' '##!two!##===index' ], paramsDefaults: { from: '-3months', width: '450', height: '250' }, absoluteTimes: false } assert.deepEqual(configurator(env, 'MYAPP').config, expected) it 'includes optional params when they exist', -> env = { HUBOT_GLINK_DEFAULT_APP: 'MYAPP' HUBOT_GLINK_MYAPP_TEMPLATE: 'some.template.value.##!one!##.##!two!##', HUBOT_GLINK_MYAPP_TEMPLATE_DEFAULTS: '##!one!##===users, ##!two!##===index', HUBOT_GLINK_HOSTNAME: 'graphite.example.com', HUBOT_GLINK_DEFAULT_PARAMS: 'from:-3months, width:450, height:250', HUBOT_GLINK_PROTOCOL: 'http', HUBOT_GLINK_PORT: '8001', HUBOT_GLINK_TEMPLATE_DEFAULT_DELIMITER: '***' } expected = { hostname: 'graphite.example.com', port: '8001', protocol: 'http', template: 'some.template.value.##!one!##.##!two!##', templateDefaults: [ '##!one!##===users', '##!two!##===index' ], templateDefaultDelimiter: '***', paramsDefaults: { from: '-3months', width: '450', height: '250' }, absoluteTimes: false } assert.deepEqual(configurator(env, 'MYAPP').config, expected) it 'creates authdConfig when HUBOT_GLINK_CREDS is present', -> env = { HUBOT_GLINK_DEFAULT_APP: 'MYAPP' HUBOT_GLINK_MYAPP_TEMPLATE: 'some.template.value.##!one!##.##!two!##', HUBOT_GLINK_MYAPP_TEMPLATE_DEFAULTS: '##!one!##===users, ##!two!##===index', HUBOT_GLINK_HOSTNAME: 'graphite.example.com', HUBOT_GLINK_DEFAULT_PARAMS: 'from:-3months, width:450, height:250', HUBOT_GLINK_CREDS: 'user:password' } expected = { hostname: 'user:password@graphite.example.com', template: 'some.template.value.##!one!##.##!two!##', templateDefaults: [ '##!one!##===users' '##!two!##===index' ], paramsDefaults: { from: '-3months', width: '450', height: '250' }, absoluteTimes: false } assert.deepEqual(configurator(env, 'MYAPP').authdConfig, expected) it 'creates credless authdConfig when no HUBOT_GLINK_CREDS present', -> env = { HUBOT_GLINK_DEFAULT_APP: 'MYAPP' HUBOT_GLINK_MYAPP_TEMPLATE: 'some.template.value.##!one!##.##!two!##', HUBOT_GLINK_MYAPP_TEMPLATE_DEFAULTS: '##!one!##===users, ##!two!##===index', HUBOT_GLINK_HOSTNAME: 'graphite.example.com', HUBOT_GLINK_DEFAULT_PARAMS: 'from:-3months, width:450, height:250', } expected = { hostname: 'graphite.example.com', template: 'some.template.value.##!one!##.##!two!##', templateDefaults: [ '##!one!##===users' '##!two!##===index' ], paramsDefaults: { from: '-3months', width: '450', height: '250' }, absoluteTimes: false } assert.deepEqual(configurator(env, 'MYAPP').authdConfig, expected)
93438
chai = require 'chai' sinon = require 'sinon' chai.use require 'sinon-chai' configurator = require '../lib/configurator' expect = chai.expect assert = chai.assert describe 'configurator', -> it 'doesnt blow up witout env vars', -> expected = { hostname: 'graphite.example.com', template: 'template.not.set', templateDefaults: [], paramsDefaults: {}, absoluteTimes: false } assert.deepEqual(configurator({}, '').config, expected) it 'gives out appropriate config given appropriate env', -> env = { HUBOT_GLINK_DEFAULT_APP: 'MYAPP', HUBOT_GLINK_MYAPP_TEMPLATE: 'some.template.value.##!one!##.##!two!##', HUBOT_GLINK_MYAPP_TEMPLATE_DEFAULTS: '##!one!##===users, ##!two!##===index', HUBOT_GLINK_HOSTNAME: 'graphite.example.com', HUBOT_GLINK_DEFAULT_PARAMS: 'from:-3months, width:450, height:250', } expected = { hostname: 'graphite.example.com', template: 'some.template.value.##!one!##.##!two!##', templateDefaults: [ '##!one!##===users' '##!two!##===index' ], paramsDefaults: { from: '-3months', width: '450', height: '250' }, absoluteTimes: false } assert.deepEqual(configurator(env, 'MYAPP').config, expected) it 'includes optional params when they exist', -> env = { HUBOT_GLINK_DEFAULT_APP: 'MYAPP' HUBOT_GLINK_MYAPP_TEMPLATE: 'some.template.value.##!one!##.##!two!##', HUBOT_GLINK_MYAPP_TEMPLATE_DEFAULTS: '##!one!##===users, ##!two!##===index', HUBOT_GLINK_HOSTNAME: 'graphite.example.com', HUBOT_GLINK_DEFAULT_PARAMS: 'from:-3months, width:450, height:250', HUBOT_GLINK_PROTOCOL: 'http', HUBOT_GLINK_PORT: '8001', HUBOT_GLINK_TEMPLATE_DEFAULT_DELIMITER: '***' } expected = { hostname: 'graphite.example.com', port: '8001', protocol: 'http', template: 'some.template.value.##!one!##.##!two!##', templateDefaults: [ '##!one!##===users', '##!two!##===index' ], templateDefaultDelimiter: '***', paramsDefaults: { from: '-3months', width: '450', height: '250' }, absoluteTimes: false } assert.deepEqual(configurator(env, 'MYAPP').config, expected) it 'creates authdConfig when HUBOT_GLINK_CREDS is present', -> env = { HUBOT_GLINK_DEFAULT_APP: 'MYAPP' HUBOT_GLINK_MYAPP_TEMPLATE: 'some.template.value.##!one!##.##!two!##', HUBOT_GLINK_MYAPP_TEMPLATE_DEFAULTS: '##!one!##===users, ##!two!##===index', HUBOT_GLINK_HOSTNAME: 'graphite.example.com', HUBOT_GLINK_DEFAULT_PARAMS: 'from:-3months, width:450, height:250', HUBOT_GLINK_CREDS: 'user:<PASSWORD>' } expected = { hostname: 'user:<EMAIL>', template: 'some.template.value.##!one!##.##!two!##', templateDefaults: [ '##!one!##===users' '##!two!##===index' ], paramsDefaults: { from: '-3months', width: '450', height: '250' }, absoluteTimes: false } assert.deepEqual(configurator(env, 'MYAPP').authdConfig, expected) it 'creates credless authdConfig when no HUBOT_GLINK_CREDS present', -> env = { HUBOT_GLINK_DEFAULT_APP: 'MYAPP' HUBOT_GLINK_MYAPP_TEMPLATE: 'some.template.value.##!one!##.##!two!##', HUBOT_GLINK_MYAPP_TEMPLATE_DEFAULTS: '##!one!##===users, ##!two!##===index', HUBOT_GLINK_HOSTNAME: 'graphite.example.com', HUBOT_GLINK_DEFAULT_PARAMS: 'from:-3months, width:450, height:250', } expected = { hostname: 'graphite.example.com', template: 'some.template.value.##!one!##.##!two!##', templateDefaults: [ '##!one!##===users' '##!two!##===index' ], paramsDefaults: { from: '-3months', width: '450', height: '250' }, absoluteTimes: false } assert.deepEqual(configurator(env, 'MYAPP').authdConfig, expected)
true
chai = require 'chai' sinon = require 'sinon' chai.use require 'sinon-chai' configurator = require '../lib/configurator' expect = chai.expect assert = chai.assert describe 'configurator', -> it 'doesnt blow up witout env vars', -> expected = { hostname: 'graphite.example.com', template: 'template.not.set', templateDefaults: [], paramsDefaults: {}, absoluteTimes: false } assert.deepEqual(configurator({}, '').config, expected) it 'gives out appropriate config given appropriate env', -> env = { HUBOT_GLINK_DEFAULT_APP: 'MYAPP', HUBOT_GLINK_MYAPP_TEMPLATE: 'some.template.value.##!one!##.##!two!##', HUBOT_GLINK_MYAPP_TEMPLATE_DEFAULTS: '##!one!##===users, ##!two!##===index', HUBOT_GLINK_HOSTNAME: 'graphite.example.com', HUBOT_GLINK_DEFAULT_PARAMS: 'from:-3months, width:450, height:250', } expected = { hostname: 'graphite.example.com', template: 'some.template.value.##!one!##.##!two!##', templateDefaults: [ '##!one!##===users' '##!two!##===index' ], paramsDefaults: { from: '-3months', width: '450', height: '250' }, absoluteTimes: false } assert.deepEqual(configurator(env, 'MYAPP').config, expected) it 'includes optional params when they exist', -> env = { HUBOT_GLINK_DEFAULT_APP: 'MYAPP' HUBOT_GLINK_MYAPP_TEMPLATE: 'some.template.value.##!one!##.##!two!##', HUBOT_GLINK_MYAPP_TEMPLATE_DEFAULTS: '##!one!##===users, ##!two!##===index', HUBOT_GLINK_HOSTNAME: 'graphite.example.com', HUBOT_GLINK_DEFAULT_PARAMS: 'from:-3months, width:450, height:250', HUBOT_GLINK_PROTOCOL: 'http', HUBOT_GLINK_PORT: '8001', HUBOT_GLINK_TEMPLATE_DEFAULT_DELIMITER: '***' } expected = { hostname: 'graphite.example.com', port: '8001', protocol: 'http', template: 'some.template.value.##!one!##.##!two!##', templateDefaults: [ '##!one!##===users', '##!two!##===index' ], templateDefaultDelimiter: '***', paramsDefaults: { from: '-3months', width: '450', height: '250' }, absoluteTimes: false } assert.deepEqual(configurator(env, 'MYAPP').config, expected) it 'creates authdConfig when HUBOT_GLINK_CREDS is present', -> env = { HUBOT_GLINK_DEFAULT_APP: 'MYAPP' HUBOT_GLINK_MYAPP_TEMPLATE: 'some.template.value.##!one!##.##!two!##', HUBOT_GLINK_MYAPP_TEMPLATE_DEFAULTS: '##!one!##===users, ##!two!##===index', HUBOT_GLINK_HOSTNAME: 'graphite.example.com', HUBOT_GLINK_DEFAULT_PARAMS: 'from:-3months, width:450, height:250', HUBOT_GLINK_CREDS: 'user:PI:PASSWORD:<PASSWORD>END_PI' } expected = { hostname: 'user:PI:EMAIL:<EMAIL>END_PI', template: 'some.template.value.##!one!##.##!two!##', templateDefaults: [ '##!one!##===users' '##!two!##===index' ], paramsDefaults: { from: '-3months', width: '450', height: '250' }, absoluteTimes: false } assert.deepEqual(configurator(env, 'MYAPP').authdConfig, expected) it 'creates credless authdConfig when no HUBOT_GLINK_CREDS present', -> env = { HUBOT_GLINK_DEFAULT_APP: 'MYAPP' HUBOT_GLINK_MYAPP_TEMPLATE: 'some.template.value.##!one!##.##!two!##', HUBOT_GLINK_MYAPP_TEMPLATE_DEFAULTS: '##!one!##===users, ##!two!##===index', HUBOT_GLINK_HOSTNAME: 'graphite.example.com', HUBOT_GLINK_DEFAULT_PARAMS: 'from:-3months, width:450, height:250', } expected = { hostname: 'graphite.example.com', template: 'some.template.value.##!one!##.##!two!##', templateDefaults: [ '##!one!##===users' '##!two!##===index' ], paramsDefaults: { from: '-3months', width: '450', height: '250' }, absoluteTimes: false } assert.deepEqual(configurator(env, 'MYAPP').authdConfig, expected)
[ { "context": "= new Feedback() \nwindow.Feedback.token = \"b5e6ddf58b2d02245a7a19005d1cec48\"", "end": 473, "score": 0.9906219840049744, "start": 441, "tag": "KEY", "value": "b5e6ddf58b2d02245a7a19005d1cec48" } ]
usr/share/pyshared/ajenti/plugins/main/content/js/feedback.coffee
lupyuen/RaspberryPiImage
7
class Feedback configure: (@enabled, @os, @version, @edition) -> mixpanel.init(@token) emit: (evt, params) -> if @enabled params ?= {} params.os = @os params.version = @version params.edition = @edition try mixpanel.track evt, params catch e ; window.Feedback = new Feedback() window.Feedback.token = "b5e6ddf58b2d02245a7a19005d1cec48"
26345
class Feedback configure: (@enabled, @os, @version, @edition) -> mixpanel.init(@token) emit: (evt, params) -> if @enabled params ?= {} params.os = @os params.version = @version params.edition = @edition try mixpanel.track evt, params catch e ; window.Feedback = new Feedback() window.Feedback.token = "<KEY>"
true
class Feedback configure: (@enabled, @os, @version, @edition) -> mixpanel.init(@token) emit: (evt, params) -> if @enabled params ?= {} params.os = @os params.version = @version params.edition = @edition try mixpanel.track evt, params catch e ; window.Feedback = new Feedback() window.Feedback.token = "PI:KEY:<KEY>END_PI"
[ { "context": "amily.camelizeKeys = yes\nApp.Family.primaryKey = 'id'\nApp.Family.url = '/api/v1/families'\nApp.Family.a", "end": 2547, "score": 0.9887841939926147, "start": 2545, "tag": "KEY", "value": "id" } ]
app/models/family.coffee
robinandeer/scout
4
NewRESTAdapter = require 'adapters/new-rest' MomentDate = require 'helpers/moment-date' App.Family = Ember.Model.extend id: Em.attr() family_id: Em.attr() familyId: (-> return parseInt(@get('id')) ).property 'id' updateDate: Em.attr(MomentDate) updateDateRaw: (-> return @get('updateDate').toDate() ).property 'updateDate' database: Em.attr() databases: (-> return (@get('database') or '').split(',') ).property 'database' firstDatabase: (-> return @get('databases.0') ).property 'databases' sampleModel: Ember.Object.extend clinical_db: undefined capture_personnel: undefined sequencing_kit: undefined cmmsid: undefined isolation_personnel: undefined medical_doctor: undefined capture_date: undefined sex: undefined idn: undefined isolation_kit: undefined clustering_date: undefined inheritance_model: undefined inheritanceModels: (-> return (@get('inheritance_model') or '') .slice(1,-1).split(',') .map((item) -> return item.trim().slice(1,-1) ) ).property 'inheritance_model' inheritanceModelString: (-> return @get('inheritanceModels').join(' | ') ).property 'inheritanceModels' isolation_date: undefined cmms_seqid: undefined capture_kit: undefined scilifeid: undefined phenotype_terms: undefined phenotype: undefined samples: Em.attr() altSamples: (-> samples = Em.A() for sample in (@get('samples') or []) samples.pushObject @sampleModel.create sample return samples ).property 'samples' isResearch: (-> return 'research' in (@get('databases') or '') ).property 'databases' hide: -> # Do this first block to trigger property changes # that otherwise only happens in localStorage @set 'isDirtyHidden', yes Ember.run.later @, => @set 'isDirtyHidden', no , 1 return Ember.ls.save 'family', @get('id'), moment().format('YYYY-MM-DD') unhide: -> # Do this first block to trigger property changes # that otherwise only happens in localStorage @set 'isDirtyHidden', yes Ember.run.later @, => @set 'isDirtyHidden', no , 1 return Ember.ls.delete 'family', @get('id') isDirtyHidden: no isHidden: (-> return Ember.ls.exists 'family', @get('id') ).property 'id', 'hide', 'unhide', 'isDirtyHidden' hiddenAt: (-> return Ember.ls.find 'family', @get('id') ).property 'id' App.Family.camelizeKeys = yes App.Family.primaryKey = 'id' App.Family.url = '/api/v1/families' App.Family.adapter = NewRESTAdapter.create() module.exports = App.Family
132273
NewRESTAdapter = require 'adapters/new-rest' MomentDate = require 'helpers/moment-date' App.Family = Ember.Model.extend id: Em.attr() family_id: Em.attr() familyId: (-> return parseInt(@get('id')) ).property 'id' updateDate: Em.attr(MomentDate) updateDateRaw: (-> return @get('updateDate').toDate() ).property 'updateDate' database: Em.attr() databases: (-> return (@get('database') or '').split(',') ).property 'database' firstDatabase: (-> return @get('databases.0') ).property 'databases' sampleModel: Ember.Object.extend clinical_db: undefined capture_personnel: undefined sequencing_kit: undefined cmmsid: undefined isolation_personnel: undefined medical_doctor: undefined capture_date: undefined sex: undefined idn: undefined isolation_kit: undefined clustering_date: undefined inheritance_model: undefined inheritanceModels: (-> return (@get('inheritance_model') or '') .slice(1,-1).split(',') .map((item) -> return item.trim().slice(1,-1) ) ).property 'inheritance_model' inheritanceModelString: (-> return @get('inheritanceModels').join(' | ') ).property 'inheritanceModels' isolation_date: undefined cmms_seqid: undefined capture_kit: undefined scilifeid: undefined phenotype_terms: undefined phenotype: undefined samples: Em.attr() altSamples: (-> samples = Em.A() for sample in (@get('samples') or []) samples.pushObject @sampleModel.create sample return samples ).property 'samples' isResearch: (-> return 'research' in (@get('databases') or '') ).property 'databases' hide: -> # Do this first block to trigger property changes # that otherwise only happens in localStorage @set 'isDirtyHidden', yes Ember.run.later @, => @set 'isDirtyHidden', no , 1 return Ember.ls.save 'family', @get('id'), moment().format('YYYY-MM-DD') unhide: -> # Do this first block to trigger property changes # that otherwise only happens in localStorage @set 'isDirtyHidden', yes Ember.run.later @, => @set 'isDirtyHidden', no , 1 return Ember.ls.delete 'family', @get('id') isDirtyHidden: no isHidden: (-> return Ember.ls.exists 'family', @get('id') ).property 'id', 'hide', 'unhide', 'isDirtyHidden' hiddenAt: (-> return Ember.ls.find 'family', @get('id') ).property 'id' App.Family.camelizeKeys = yes App.Family.primaryKey = '<KEY>' App.Family.url = '/api/v1/families' App.Family.adapter = NewRESTAdapter.create() module.exports = App.Family
true
NewRESTAdapter = require 'adapters/new-rest' MomentDate = require 'helpers/moment-date' App.Family = Ember.Model.extend id: Em.attr() family_id: Em.attr() familyId: (-> return parseInt(@get('id')) ).property 'id' updateDate: Em.attr(MomentDate) updateDateRaw: (-> return @get('updateDate').toDate() ).property 'updateDate' database: Em.attr() databases: (-> return (@get('database') or '').split(',') ).property 'database' firstDatabase: (-> return @get('databases.0') ).property 'databases' sampleModel: Ember.Object.extend clinical_db: undefined capture_personnel: undefined sequencing_kit: undefined cmmsid: undefined isolation_personnel: undefined medical_doctor: undefined capture_date: undefined sex: undefined idn: undefined isolation_kit: undefined clustering_date: undefined inheritance_model: undefined inheritanceModels: (-> return (@get('inheritance_model') or '') .slice(1,-1).split(',') .map((item) -> return item.trim().slice(1,-1) ) ).property 'inheritance_model' inheritanceModelString: (-> return @get('inheritanceModels').join(' | ') ).property 'inheritanceModels' isolation_date: undefined cmms_seqid: undefined capture_kit: undefined scilifeid: undefined phenotype_terms: undefined phenotype: undefined samples: Em.attr() altSamples: (-> samples = Em.A() for sample in (@get('samples') or []) samples.pushObject @sampleModel.create sample return samples ).property 'samples' isResearch: (-> return 'research' in (@get('databases') or '') ).property 'databases' hide: -> # Do this first block to trigger property changes # that otherwise only happens in localStorage @set 'isDirtyHidden', yes Ember.run.later @, => @set 'isDirtyHidden', no , 1 return Ember.ls.save 'family', @get('id'), moment().format('YYYY-MM-DD') unhide: -> # Do this first block to trigger property changes # that otherwise only happens in localStorage @set 'isDirtyHidden', yes Ember.run.later @, => @set 'isDirtyHidden', no , 1 return Ember.ls.delete 'family', @get('id') isDirtyHidden: no isHidden: (-> return Ember.ls.exists 'family', @get('id') ).property 'id', 'hide', 'unhide', 'isDirtyHidden' hiddenAt: (-> return Ember.ls.find 'family', @get('id') ).property 'id' App.Family.camelizeKeys = yes App.Family.primaryKey = 'PI:KEY:<KEY>END_PI' App.Family.url = '/api/v1/families' App.Family.adapter = NewRESTAdapter.create() module.exports = App.Family
[ { "context": "###\n@Author: Kristinita\n@Date: 2017-12-28 13:35:33\n@Last Modified time:", "end": 23, "score": 0.9997942447662354, "start": 13, "tag": "NAME", "value": "Kristinita" } ]
themes/sashapelican/static/coffee/Visualize/visualize-pie-chart.coffee
Kristinita/KristinitaPelicanCI
0
### @Author: Kristinita @Date: 2017-12-28 13:35:33 @Last Modified time: 2017-12-28 13:46:50 ### ############# # visualize # ############# # pie chart: # https://www.mathsisfun.com/data/pie-charts.html $(document).ready -> $('.SashaBarChart').visualize width: 400 type: 'pie' legend: true return
169748
### @Author: <NAME> @Date: 2017-12-28 13:35:33 @Last Modified time: 2017-12-28 13:46:50 ### ############# # visualize # ############# # pie chart: # https://www.mathsisfun.com/data/pie-charts.html $(document).ready -> $('.SashaBarChart').visualize width: 400 type: 'pie' legend: true return
true
### @Author: PI:NAME:<NAME>END_PI @Date: 2017-12-28 13:35:33 @Last Modified time: 2017-12-28 13:46:50 ### ############# # visualize # ############# # pie chart: # https://www.mathsisfun.com/data/pie-charts.html $(document).ready -> $('.SashaBarChart').visualize width: 400 type: 'pie' legend: true return
[ { "context": "disallow use of the Buffer() constructor\n# @author Teddy Katz\n###\n'use strict'\n\n#------------------------------", "end": 82, "score": 0.9998229146003723, "start": 72, "tag": "NAME", "value": "Teddy Katz" } ]
src/tests/rules/no-buffer-constructor.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview disallow use of the Buffer() constructor # @author Teddy Katz ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/no-buffer-constructor' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ CALL_ERROR = messageId: 'deprecated' data: expr: 'Buffer()' type: 'CallExpression' CONSTRUCT_ERROR = messageId: 'deprecated' data: expr: 'new Buffer()' type: 'NewExpression' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-buffer-constructor', rule, valid: [ 'Buffer.alloc(5)' 'Buffer.allocUnsafe(5)' 'new Buffer.Foo()' 'Buffer.from([1, 2, 3])' 'foo(Buffer)' 'Buffer.alloc(res.body.amount)' 'Buffer.from(res.body.values)' ] invalid: [ code: 'Buffer(5)' errors: [CALL_ERROR] , code: 'new Buffer(5)' errors: [CONSTRUCT_ERROR] , code: 'Buffer([1, 2, 3])' errors: [CALL_ERROR] , code: 'new Buffer([1, 2, 3])' errors: [CONSTRUCT_ERROR] , code: 'new Buffer(res.body.amount)' errors: [CONSTRUCT_ERROR] , code: 'new Buffer(res.body.values)' errors: [CONSTRUCT_ERROR] ]
192316
###* # @fileoverview disallow use of the Buffer() constructor # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/no-buffer-constructor' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ CALL_ERROR = messageId: 'deprecated' data: expr: 'Buffer()' type: 'CallExpression' CONSTRUCT_ERROR = messageId: 'deprecated' data: expr: 'new Buffer()' type: 'NewExpression' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-buffer-constructor', rule, valid: [ 'Buffer.alloc(5)' 'Buffer.allocUnsafe(5)' 'new Buffer.Foo()' 'Buffer.from([1, 2, 3])' 'foo(Buffer)' 'Buffer.alloc(res.body.amount)' 'Buffer.from(res.body.values)' ] invalid: [ code: 'Buffer(5)' errors: [CALL_ERROR] , code: 'new Buffer(5)' errors: [CONSTRUCT_ERROR] , code: 'Buffer([1, 2, 3])' errors: [CALL_ERROR] , code: 'new Buffer([1, 2, 3])' errors: [CONSTRUCT_ERROR] , code: 'new Buffer(res.body.amount)' errors: [CONSTRUCT_ERROR] , code: 'new Buffer(res.body.values)' errors: [CONSTRUCT_ERROR] ]
true
###* # @fileoverview disallow use of the Buffer() constructor # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/no-buffer-constructor' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ CALL_ERROR = messageId: 'deprecated' data: expr: 'Buffer()' type: 'CallExpression' CONSTRUCT_ERROR = messageId: 'deprecated' data: expr: 'new Buffer()' type: 'NewExpression' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-buffer-constructor', rule, valid: [ 'Buffer.alloc(5)' 'Buffer.allocUnsafe(5)' 'new Buffer.Foo()' 'Buffer.from([1, 2, 3])' 'foo(Buffer)' 'Buffer.alloc(res.body.amount)' 'Buffer.from(res.body.values)' ] invalid: [ code: 'Buffer(5)' errors: [CALL_ERROR] , code: 'new Buffer(5)' errors: [CONSTRUCT_ERROR] , code: 'Buffer([1, 2, 3])' errors: [CALL_ERROR] , code: 'new Buffer([1, 2, 3])' errors: [CONSTRUCT_ERROR] , code: 'new Buffer(res.body.amount)' errors: [CONSTRUCT_ERROR] , code: 'new Buffer(res.body.values)' errors: [CONSTRUCT_ERROR] ]
[ { "context": "ate a UUID like identifier\n#\n# Copyright (C) 2006, Erik Giberti (AF-Design), All rights reserved.\n#\n# This progra", "end": 114, "score": 0.9998669028282166, "start": 102, "tag": "NAME", "value": "Erik Giberti" }, { "context": "ion of UUID implementation.\n #\n # C...
application/chrome/content/wesabe/lang/UUID.coffee
wesabe/ssu
28
# # uuid.js - Version 0.1 # JavaScript Class to create a UUID like identifier # # Copyright (C) 2006, Erik Giberti (AF-Design), All rights reserved. # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 59 Temple # Place, Suite 330, Boston, MA 02111-1307 USA # # The latest version of this file can be downloaded from # http://www.af-design.com/resources/javascript_uuid.php # # HISTORY: # 6/5/06 - Initial Release # on creation of a UUID object, set its initial value class UUID constructor: -> @id = createUUID() # When asked what this Object is, lie and return its value valueOf: -> @id toString: -> @id @string: -> (new UUID).toString() @uuid: -> UUID.string() createUUID = -> # JavaScript Version of UUID implementation. # # Copyright 2006 Erik Giberti, all rights reserved. # # Loose interpretation of the specification DCE 1.1: Remote Procedure Call # described at http://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagtcjh_37 # since JavaScript doesn't allow access to internal systems, the last 48 bits # of the node section is made up using a series of random numbers (6 octets long). # dg = timeInMs(new Date(1582, 10, 15, 0, 0, 0, 0)) dc = timeInMs(new Date()) t = dc - dg h = '-' tl = getIntegerBits(t,0,31) tm = getIntegerBits(t,32,47); thv = getIntegerBits(t,48,59) + '1' # version 1, security version is 2 csar = getIntegerBits(randrange(0,4095),0,7) csl = getIntegerBits(randrange(0,4095),0,7) # since detection of anything about the machine/browser is far too buggy, # include some more random numbers here # if nic or at least an IP can be obtained reliably, that should be put in # here instead. n = getIntegerBits(randrange(0,8191),0,7) + getIntegerBits(randrange(0,8191),8,15) + getIntegerBits(randrange(0,8191),0,7) + getIntegerBits(randrange(0,8191),8,15) + getIntegerBits(randrange(0,8191),0,15) # this last number is two octets long tl + h + tm + h + thv + h + csar + csl + h + n # # GENERAL METHODS (Not instance specific) # # Pull out only certain bits from a very large integer, used to get the time # code information for the first part of a UUID. Will return zero's if there # aren't enough bits to shift where it needs to. getIntegerBits = (val,start,end) -> base16 = returnBase(val, 16) quadArray = [] quadString = '' for i in [0...base16.length] quadArray.push(base16.substring(i,i+1)) for i in [Math.floor(start/4)..Math.floor(end/4)] quadString += quadArray[i] || '0' return quadString # Numeric Base Conversion algorithm from irt.org # In base 16: 0=0, 5=5, 10=A, 15=F returnBase = (number, base) -> # # Copyright 1996-2006 irt.org, All Rights Reserved. # # Downloaded from: http://www.irt.org/script/146.htm # modified to work in this class by Erik Giberti convert = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] if number < base output = convert[number] else MSD = '' + Math.floor(number / base) LSD = number - MSD*base output = if MSD >= base returnBase(MSD,base) + convert[LSD] else convert[MSD] + convert[LSD] return output # This is approximate but should get the job done for general use. # It gets an approximation of the provided date in milliseconds. WARNING: # some implementations of JavaScript will choke with these large numbers # and so the absolute value is used to avoid issues where the implementation # begin's at the negative value. timeInMs = (d) -> ms_per_second = 100 # constant ms_per_minute = 6000 # ms_per second * 60 ms_per_hour = 360000 # ms_per_minute * 60 ms_per_day = 8640000 # ms_per_hour * 24 ms_per_month = 207360000 # ms_per_day * 30 ms_per_year = 75686400000 # ms_per_day * 365 Math.abs( (d.getUTCFullYear() * ms_per_year) + (d.getUTCMonth() * ms_per_month) + (d.getUTCDate() * ms_per_day) + (d.getUTCHours() * ms_per_hour) + (d.getUTCMinutes() * ms_per_minute) + (d.getUTCSeconds() * ms_per_second) + d.getUTCMilliseconds()) # pick a random number within a range of numbers # int c randrange(int a, int b); where a <= c <= b randrange = (min, max) -> num = Math.round(Math.random() * max) num = if num < min then min else max return num module.exports = UUID
77504
# # uuid.js - Version 0.1 # JavaScript Class to create a UUID like identifier # # Copyright (C) 2006, <NAME> (AF-Design), All rights reserved. # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 59 Temple # Place, Suite 330, Boston, MA 02111-1307 USA # # The latest version of this file can be downloaded from # http://www.af-design.com/resources/javascript_uuid.php # # HISTORY: # 6/5/06 - Initial Release # on creation of a UUID object, set its initial value class UUID constructor: -> @id = createUUID() # When asked what this Object is, lie and return its value valueOf: -> @id toString: -> @id @string: -> (new UUID).toString() @uuid: -> UUID.string() createUUID = -> # JavaScript Version of UUID implementation. # # Copyright 2006 <NAME>, all rights reserved. # # Loose interpretation of the specification DCE 1.1: Remote Procedure Call # described at http://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagtcjh_37 # since JavaScript doesn't allow access to internal systems, the last 48 bits # of the node section is made up using a series of random numbers (6 octets long). # dg = timeInMs(new Date(1582, 10, 15, 0, 0, 0, 0)) dc = timeInMs(new Date()) t = dc - dg h = '-' tl = getIntegerBits(t,0,31) tm = getIntegerBits(t,32,47); thv = getIntegerBits(t,48,59) + '1' # version 1, security version is 2 csar = getIntegerBits(randrange(0,4095),0,7) csl = getIntegerBits(randrange(0,4095),0,7) # since detection of anything about the machine/browser is far too buggy, # include some more random numbers here # if nic or at least an IP can be obtained reliably, that should be put in # here instead. n = getIntegerBits(randrange(0,8191),0,7) + getIntegerBits(randrange(0,8191),8,15) + getIntegerBits(randrange(0,8191),0,7) + getIntegerBits(randrange(0,8191),8,15) + getIntegerBits(randrange(0,8191),0,15) # this last number is two octets long tl + h + tm + h + thv + h + csar + csl + h + n # # GENERAL METHODS (Not instance specific) # # Pull out only certain bits from a very large integer, used to get the time # code information for the first part of a UUID. Will return zero's if there # aren't enough bits to shift where it needs to. getIntegerBits = (val,start,end) -> base16 = returnBase(val, 16) quadArray = [] quadString = '' for i in [0...base16.length] quadArray.push(base16.substring(i,i+1)) for i in [Math.floor(start/4)..Math.floor(end/4)] quadString += quadArray[i] || '0' return quadString # Numeric Base Conversion algorithm from irt.org # In base 16: 0=0, 5=5, 10=A, 15=F returnBase = (number, base) -> # # Copyright 1996-2006 irt.org, All Rights Reserved. # # Downloaded from: http://www.irt.org/script/146.htm # modified to work in this class by <NAME> convert = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] if number < base output = convert[number] else MSD = '' + Math.floor(number / base) LSD = number - MSD*base output = if MSD >= base returnBase(MSD,base) + convert[LSD] else convert[MSD] + convert[LSD] return output # This is approximate but should get the job done for general use. # It gets an approximation of the provided date in milliseconds. WARNING: # some implementations of JavaScript will choke with these large numbers # and so the absolute value is used to avoid issues where the implementation # begin's at the negative value. timeInMs = (d) -> ms_per_second = 100 # constant ms_per_minute = 6000 # ms_per second * 60 ms_per_hour = 360000 # ms_per_minute * 60 ms_per_day = 8640000 # ms_per_hour * 24 ms_per_month = 207360000 # ms_per_day * 30 ms_per_year = 75686400000 # ms_per_day * 365 Math.abs( (d.getUTCFullYear() * ms_per_year) + (d.getUTCMonth() * ms_per_month) + (d.getUTCDate() * ms_per_day) + (d.getUTCHours() * ms_per_hour) + (d.getUTCMinutes() * ms_per_minute) + (d.getUTCSeconds() * ms_per_second) + d.getUTCMilliseconds()) # pick a random number within a range of numbers # int c randrange(int a, int b); where a <= c <= b randrange = (min, max) -> num = Math.round(Math.random() * max) num = if num < min then min else max return num module.exports = UUID
true
# # uuid.js - Version 0.1 # JavaScript Class to create a UUID like identifier # # Copyright (C) 2006, PI:NAME:<NAME>END_PI (AF-Design), All rights reserved. # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 59 Temple # Place, Suite 330, Boston, MA 02111-1307 USA # # The latest version of this file can be downloaded from # http://www.af-design.com/resources/javascript_uuid.php # # HISTORY: # 6/5/06 - Initial Release # on creation of a UUID object, set its initial value class UUID constructor: -> @id = createUUID() # When asked what this Object is, lie and return its value valueOf: -> @id toString: -> @id @string: -> (new UUID).toString() @uuid: -> UUID.string() createUUID = -> # JavaScript Version of UUID implementation. # # Copyright 2006 PI:NAME:<NAME>END_PI, all rights reserved. # # Loose interpretation of the specification DCE 1.1: Remote Procedure Call # described at http://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagtcjh_37 # since JavaScript doesn't allow access to internal systems, the last 48 bits # of the node section is made up using a series of random numbers (6 octets long). # dg = timeInMs(new Date(1582, 10, 15, 0, 0, 0, 0)) dc = timeInMs(new Date()) t = dc - dg h = '-' tl = getIntegerBits(t,0,31) tm = getIntegerBits(t,32,47); thv = getIntegerBits(t,48,59) + '1' # version 1, security version is 2 csar = getIntegerBits(randrange(0,4095),0,7) csl = getIntegerBits(randrange(0,4095),0,7) # since detection of anything about the machine/browser is far too buggy, # include some more random numbers here # if nic or at least an IP can be obtained reliably, that should be put in # here instead. n = getIntegerBits(randrange(0,8191),0,7) + getIntegerBits(randrange(0,8191),8,15) + getIntegerBits(randrange(0,8191),0,7) + getIntegerBits(randrange(0,8191),8,15) + getIntegerBits(randrange(0,8191),0,15) # this last number is two octets long tl + h + tm + h + thv + h + csar + csl + h + n # # GENERAL METHODS (Not instance specific) # # Pull out only certain bits from a very large integer, used to get the time # code information for the first part of a UUID. Will return zero's if there # aren't enough bits to shift where it needs to. getIntegerBits = (val,start,end) -> base16 = returnBase(val, 16) quadArray = [] quadString = '' for i in [0...base16.length] quadArray.push(base16.substring(i,i+1)) for i in [Math.floor(start/4)..Math.floor(end/4)] quadString += quadArray[i] || '0' return quadString # Numeric Base Conversion algorithm from irt.org # In base 16: 0=0, 5=5, 10=A, 15=F returnBase = (number, base) -> # # Copyright 1996-2006 irt.org, All Rights Reserved. # # Downloaded from: http://www.irt.org/script/146.htm # modified to work in this class by PI:NAME:<NAME>END_PI convert = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] if number < base output = convert[number] else MSD = '' + Math.floor(number / base) LSD = number - MSD*base output = if MSD >= base returnBase(MSD,base) + convert[LSD] else convert[MSD] + convert[LSD] return output # This is approximate but should get the job done for general use. # It gets an approximation of the provided date in milliseconds. WARNING: # some implementations of JavaScript will choke with these large numbers # and so the absolute value is used to avoid issues where the implementation # begin's at the negative value. timeInMs = (d) -> ms_per_second = 100 # constant ms_per_minute = 6000 # ms_per second * 60 ms_per_hour = 360000 # ms_per_minute * 60 ms_per_day = 8640000 # ms_per_hour * 24 ms_per_month = 207360000 # ms_per_day * 30 ms_per_year = 75686400000 # ms_per_day * 365 Math.abs( (d.getUTCFullYear() * ms_per_year) + (d.getUTCMonth() * ms_per_month) + (d.getUTCDate() * ms_per_day) + (d.getUTCHours() * ms_per_hour) + (d.getUTCMinutes() * ms_per_minute) + (d.getUTCSeconds() * ms_per_second) + d.getUTCMilliseconds()) # pick a random number within a range of numbers # int c randrange(int a, int b); where a <= c <= b randrange = (min, max) -> num = Math.round(Math.random() * max) num = if num < min then min else max return num module.exports = UUID
[ { "context": "###\n backbone-sql.js 0.5.7\n Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-sql\n Lice", "end": 57, "score": 0.9993470907211304, "start": 49, "tag": "NAME", "value": "Vidigami" }, { "context": " Copyright (c) 2013 Vidigami - https://github.com/vi...
src/backbone_adapter.coffee
michaelBenin/backbone-sql
1
### backbone-sql.js 0.5.7 Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-sql License: MIT (http://www.opensource.org/licenses/mit-license.php) ### util = require 'util' inflection = require 'inflection' _ = require 'underscore' module.exports = class SqlBackboneAdapter @nativeToAttributes: (json, schema) -> for key of json json[key] = !!json[key] if json[key] isnt null and schema.fields[key] and schema.fields[key].type is 'Boolean' return json
79585
### backbone-sql.js 0.5.7 Copyright (c) 2013 <NAME> - https://github.com/vidigami/backbone-sql License: MIT (http://www.opensource.org/licenses/mit-license.php) ### util = require 'util' inflection = require 'inflection' _ = require 'underscore' module.exports = class SqlBackboneAdapter @nativeToAttributes: (json, schema) -> for key of json json[key] = !!json[key] if json[key] isnt null and schema.fields[key] and schema.fields[key].type is 'Boolean' return json
true
### backbone-sql.js 0.5.7 Copyright (c) 2013 PI:NAME:<NAME>END_PI - https://github.com/vidigami/backbone-sql License: MIT (http://www.opensource.org/licenses/mit-license.php) ### util = require 'util' inflection = require 'inflection' _ = require 'underscore' module.exports = class SqlBackboneAdapter @nativeToAttributes: (json, schema) -> for key of json json[key] = !!json[key] if json[key] isnt null and schema.fields[key] and schema.fields[key].type is 'Boolean' return json
[ { "context": "###\nCopyright 2016 Balena\n\nLicensed under the Apache License, Version 2.", "end": 22, "score": 0.8232787847518921, "start": 19, "tag": "NAME", "value": "Bal" }, { "context": "to open an\n# [issue in GitHub](https://github.com/balena-io/balena-sdk/issues/new), we'll b...
lib/balena.coffee
josecoelho/balena-sdk
0
### Copyright 2016 Balena Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### { globalEnv } = require('./util/global-env') # These constants are used to create globals for sharing defualt options between # multiple instances of the SDK. # See the `setSharedOptions()` and `fromSharedOptions()` methods. BALENA_SDK_SHARED_OPTIONS = 'BALENA_SDK_SHARED_OPTIONS' BALENA_SDK_HAS_USED_SHARED_OPTIONS = 'BALENA_SDK_HAS_USED_SHARED_OPTIONS' BALENA_SDK_HAS_SET_SHARED_OPTIONS = 'BALENA_SDK_HAS_SET_SHARED_OPTIONS' ###* # @namespace balena # @description # Welcome to the Balena SDK documentation. # # This document aims to describe all the functions supported by the SDK, as well as showing examples of their expected usage. # # If you feel something is missing, not clear or could be improved, please don't hesitate to open an # [issue in GitHub](https://github.com/balena-io/balena-sdk/issues/new), we'll be happy to help. ### getSdk = (opts = {}) -> version = require('./util/sdk-version').default assign = require('lodash/assign') forEach = require('lodash/forEach') defaults = require('lodash/defaults') getRequest = require('balena-request') BalenaAuth = require('balena-auth')['default'] getPine = require('balena-pine') errors = require('balena-errors') { notImplemented } = require('./util') { PubSub } = require('./util/pubsub') ###* # @namespace models # @memberof balena ### ###* # @namespace auth # @memberof balena ### ###* # @namespace logs # @memberof balena ### ###* # @namespace settings # @memberof balena ### sdkTemplate = auth: require('./auth') models: require('./models') logs: require('./logs') settings: require('./settings') defaults opts, apiUrl: 'https://api.balena-cloud.com/' builderUrl: 'https://builder.balena-cloud.com/' # deprecated imageMakerUrl: 'https://img.balena-cloud.com/' isBrowser: window? # API version is configurable but only do so if you know what you're doing, # as the SDK is directly tied to a specific version. apiVersion: 'v5' if opts.isBrowser settings = get: notImplemented getAll: notImplemented else settings = require('balena-settings-client') defaults opts, dataDirectory: settings.get('dataDirectory') auth = new BalenaAuth(opts) request = getRequest(assign({}, opts, { auth })) pine = getPine(assign({}, opts, { auth, request })) pubsub = new PubSub() sdk = {} deps = { settings request auth pine pubsub sdkInstance: sdk } forEach(sdkTemplate, (moduleFactory, moduleName) -> sdk[moduleName] = moduleFactory(deps, opts)) ###* # @typedef Interceptor # @type {object} # @memberof balena.interceptors # # @description # An interceptor implements some set of the four interception hook callbacks. # To continue processing, each function should return a value or a promise that # successfully resolves to a value. # # To halt processing, each function should throw an error or return a promise that # rejects with an error. # # @property {function} [request] - Callback invoked before requests are made. Called with # the request options, should return (or resolve to) new request options, or throw/reject. # # @property {function} [response] - Callback invoked before responses are returned. Called with # the response, should return (or resolve to) a new response, or throw/reject. # # @property {function} [requestError] - Callback invoked if an error happens before a request. # Called with the error itself, caused by a preceeding request interceptor rejecting/throwing # an error for the request, or a failing in preflight token validation. Should return (or resolve # to) new request options, or throw/reject. # # @property {function} [responseError] - Callback invoked if an error happens in the response. # Called with the error itself, caused by a preceeding response interceptor rejecting/throwing # an error for the request, a network error, or an error response from the server. Should return # (or resolve to) a new response, or throw/reject. ### ###* # @summary Array of interceptors # @member {Interceptor[]} interceptors # @public # @memberof balena # # @description # The current array of interceptors to use. Interceptors intercept requests made # internally and are executed in the order they appear in this array for requests, # and in the reverse order for responses. # # @example # balena.interceptors.push({ # responseError: function (error) { # console.log(error); # throw error; # }) # }); ### Object.defineProperty sdk, 'interceptors', get: -> request.interceptors, set: (interceptors) -> request.interceptors = interceptors versionHeaderInterceptor = request: (request) -> url = request.url if typeof url != 'string' return request if typeof request.baseUrl == 'string' url = request.baseUrl + url if url.indexOf(opts.apiUrl) == 0 request.headers['X-Balena-Client'] = "balena-sdk/#{version}" return request sdk.interceptors.push(versionHeaderInterceptor) ###* # @summary Balena request instance # @member {Object} request # @public # @memberof balena # # @description # The balena-request instance used internally. This should not be necessary # in normal usage, but can be useful if you want to make an API request directly, # using the same token and hooks as the SDK. # # @example # balena.request.send({ url: 'http://api.balena-cloud.com/ping' }); ### sdk.request = request ###* # @summary Balena pine instance # @member {Object} pine # @public # @memberof balena # # @description # The balena-pine instance used internally. This should not be necessary # in normal usage, but can be useful if you want to directly make pine # queries to the api for some resource that isn't directly supported # in the SDK. # # @example # balena.pine.get({ # resource: 'release/$count', # options: { # $filter: { belongs_to__application: applicationId } # } # }); ### sdk.pine = pine ###* # @summary Balena errors module # @member {Object} errors # @public # @memberof balena # # @description # The balena-errors module used internally. This is provided primarily for # convenience, and to avoid the necessity for separate balena-errors # dependencies. You'll want to use this if you need to match on the specific # type of error thrown by the SDK. # # @example # balena.models.device.get(123).catch(function (error) { # if (error.code === balena.errors.BalenaDeviceNotFound.code) { # ... # } else if (error.code === balena.errors.BalenaRequestError.code) { # ... # } # }); ### sdk.errors = errors sdk.version = version return sdk ###* # @summary Set shared default options # @name setSharedOptions # @public # @function # @memberof balena # # @description # Set options that are used by calls to `balena.fromSharedOptions()`. # The options accepted are the same as those used in the main SDK factory function. # If you use this method, it should be called as soon as possible during app # startup and before any calls to `fromSharedOptions()` are made. # # @params {Object} opts - The shared default options # # @example # balena.setSharedOptions({ # apiUrl: 'https://api.balena-cloud.com/', # builderUrl: 'https://builder.balena-cloud.com/', # isBrowser: true, # }); ### getSdk.setSharedOptions = (opts) -> if globalEnv[BALENA_SDK_HAS_USED_SHARED_OPTIONS] console.error('Shared SDK options have already been used. You may have a race condition in your code.') if globalEnv[BALENA_SDK_HAS_SET_SHARED_OPTIONS] console.error('Shared SDK options have already been set. You may have a race condition in your code.') globalEnv[BALENA_SDK_SHARED_OPTIONS] = opts globalEnv[BALENA_SDK_HAS_SET_SHARED_OPTIONS] = true ###* # @summary Create an SDK instance using shared default options # @name fromSharedOptions # @public # @function # @memberof balena # # @description # Create an SDK instance using shared default options set using the `setSharedOptions()` method. # If options have not been set using this method, then this method will use the # same defaults as the main SDK factory function. # # @params {Object} opts - The shared default options # # @example # const sdk = balena.fromSharedOptions(); ### getSdk.fromSharedOptions = -> sharedOpts = globalEnv[BALENA_SDK_SHARED_OPTIONS] globalEnv[BALENA_SDK_HAS_USED_SHARED_OPTIONS] = true getSdk(sharedOpts) module.exports = getSdk
209768
### Copyright 2016 <NAME>ena Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### { globalEnv } = require('./util/global-env') # These constants are used to create globals for sharing defualt options between # multiple instances of the SDK. # See the `setSharedOptions()` and `fromSharedOptions()` methods. BALENA_SDK_SHARED_OPTIONS = 'BALENA_SDK_SHARED_OPTIONS' BALENA_SDK_HAS_USED_SHARED_OPTIONS = 'BALENA_SDK_HAS_USED_SHARED_OPTIONS' BALENA_SDK_HAS_SET_SHARED_OPTIONS = 'BALENA_SDK_HAS_SET_SHARED_OPTIONS' ###* # @namespace balena # @description # Welcome to the Balena SDK documentation. # # This document aims to describe all the functions supported by the SDK, as well as showing examples of their expected usage. # # If you feel something is missing, not clear or could be improved, please don't hesitate to open an # [issue in GitHub](https://github.com/balena-io/balena-sdk/issues/new), we'll be happy to help. ### getSdk = (opts = {}) -> version = require('./util/sdk-version').default assign = require('lodash/assign') forEach = require('lodash/forEach') defaults = require('lodash/defaults') getRequest = require('balena-request') BalenaAuth = require('balena-auth')['default'] getPine = require('balena-pine') errors = require('balena-errors') { notImplemented } = require('./util') { PubSub } = require('./util/pubsub') ###* # @namespace models # @memberof balena ### ###* # @namespace auth # @memberof balena ### ###* # @namespace logs # @memberof balena ### ###* # @namespace settings # @memberof balena ### sdkTemplate = auth: require('./auth') models: require('./models') logs: require('./logs') settings: require('./settings') defaults opts, apiUrl: 'https://api.balena-cloud.com/' builderUrl: 'https://builder.balena-cloud.com/' # deprecated imageMakerUrl: 'https://img.balena-cloud.com/' isBrowser: window? # API version is configurable but only do so if you know what you're doing, # as the SDK is directly tied to a specific version. apiVersion: 'v5' if opts.isBrowser settings = get: notImplemented getAll: notImplemented else settings = require('balena-settings-client') defaults opts, dataDirectory: settings.get('dataDirectory') auth = new BalenaAuth(opts) request = getRequest(assign({}, opts, { auth })) pine = getPine(assign({}, opts, { auth, request })) pubsub = new PubSub() sdk = {} deps = { settings request auth pine pubsub sdkInstance: sdk } forEach(sdkTemplate, (moduleFactory, moduleName) -> sdk[moduleName] = moduleFactory(deps, opts)) ###* # @typedef Interceptor # @type {object} # @memberof balena.interceptors # # @description # An interceptor implements some set of the four interception hook callbacks. # To continue processing, each function should return a value or a promise that # successfully resolves to a value. # # To halt processing, each function should throw an error or return a promise that # rejects with an error. # # @property {function} [request] - Callback invoked before requests are made. Called with # the request options, should return (or resolve to) new request options, or throw/reject. # # @property {function} [response] - Callback invoked before responses are returned. Called with # the response, should return (or resolve to) a new response, or throw/reject. # # @property {function} [requestError] - Callback invoked if an error happens before a request. # Called with the error itself, caused by a preceeding request interceptor rejecting/throwing # an error for the request, or a failing in preflight token validation. Should return (or resolve # to) new request options, or throw/reject. # # @property {function} [responseError] - Callback invoked if an error happens in the response. # Called with the error itself, caused by a preceeding response interceptor rejecting/throwing # an error for the request, a network error, or an error response from the server. Should return # (or resolve to) a new response, or throw/reject. ### ###* # @summary Array of interceptors # @member {Interceptor[]} interceptors # @public # @memberof balena # # @description # The current array of interceptors to use. Interceptors intercept requests made # internally and are executed in the order they appear in this array for requests, # and in the reverse order for responses. # # @example # balena.interceptors.push({ # responseError: function (error) { # console.log(error); # throw error; # }) # }); ### Object.defineProperty sdk, 'interceptors', get: -> request.interceptors, set: (interceptors) -> request.interceptors = interceptors versionHeaderInterceptor = request: (request) -> url = request.url if typeof url != 'string' return request if typeof request.baseUrl == 'string' url = request.baseUrl + url if url.indexOf(opts.apiUrl) == 0 request.headers['X-Balena-Client'] = "balena-sdk/#{version}" return request sdk.interceptors.push(versionHeaderInterceptor) ###* # @summary Balena request instance # @member {Object} request # @public # @memberof balena # # @description # The balena-request instance used internally. This should not be necessary # in normal usage, but can be useful if you want to make an API request directly, # using the same token and hooks as the SDK. # # @example # balena.request.send({ url: 'http://api.balena-cloud.com/ping' }); ### sdk.request = request ###* # @summary Balena pine instance # @member {Object} pine # @public # @memberof balena # # @description # The balena-pine instance used internally. This should not be necessary # in normal usage, but can be useful if you want to directly make pine # queries to the api for some resource that isn't directly supported # in the SDK. # # @example # balena.pine.get({ # resource: 'release/$count', # options: { # $filter: { belongs_to__application: applicationId } # } # }); ### sdk.pine = pine ###* # @summary Balena errors module # @member {Object} errors # @public # @memberof balena # # @description # The balena-errors module used internally. This is provided primarily for # convenience, and to avoid the necessity for separate balena-errors # dependencies. You'll want to use this if you need to match on the specific # type of error thrown by the SDK. # # @example # balena.models.device.get(123).catch(function (error) { # if (error.code === balena.errors.BalenaDeviceNotFound.code) { # ... # } else if (error.code === balena.errors.BalenaRequestError.code) { # ... # } # }); ### sdk.errors = errors sdk.version = version return sdk ###* # @summary Set shared default options # @name setSharedOptions # @public # @function # @memberof balena # # @description # Set options that are used by calls to `balena.fromSharedOptions()`. # The options accepted are the same as those used in the main SDK factory function. # If you use this method, it should be called as soon as possible during app # startup and before any calls to `fromSharedOptions()` are made. # # @params {Object} opts - The shared default options # # @example # balena.setSharedOptions({ # apiUrl: 'https://api.balena-cloud.com/', # builderUrl: 'https://builder.balena-cloud.com/', # isBrowser: true, # }); ### getSdk.setSharedOptions = (opts) -> if globalEnv[BALENA_SDK_HAS_USED_SHARED_OPTIONS] console.error('Shared SDK options have already been used. You may have a race condition in your code.') if globalEnv[BALENA_SDK_HAS_SET_SHARED_OPTIONS] console.error('Shared SDK options have already been set. You may have a race condition in your code.') globalEnv[BALENA_SDK_SHARED_OPTIONS] = opts globalEnv[BALENA_SDK_HAS_SET_SHARED_OPTIONS] = true ###* # @summary Create an SDK instance using shared default options # @name fromSharedOptions # @public # @function # @memberof balena # # @description # Create an SDK instance using shared default options set using the `setSharedOptions()` method. # If options have not been set using this method, then this method will use the # same defaults as the main SDK factory function. # # @params {Object} opts - The shared default options # # @example # const sdk = balena.fromSharedOptions(); ### getSdk.fromSharedOptions = -> sharedOpts = globalEnv[BALENA_SDK_SHARED_OPTIONS] globalEnv[BALENA_SDK_HAS_USED_SHARED_OPTIONS] = true getSdk(sharedOpts) module.exports = getSdk
true
### Copyright 2016 PI:NAME:<NAME>END_PIena Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### { globalEnv } = require('./util/global-env') # These constants are used to create globals for sharing defualt options between # multiple instances of the SDK. # See the `setSharedOptions()` and `fromSharedOptions()` methods. BALENA_SDK_SHARED_OPTIONS = 'BALENA_SDK_SHARED_OPTIONS' BALENA_SDK_HAS_USED_SHARED_OPTIONS = 'BALENA_SDK_HAS_USED_SHARED_OPTIONS' BALENA_SDK_HAS_SET_SHARED_OPTIONS = 'BALENA_SDK_HAS_SET_SHARED_OPTIONS' ###* # @namespace balena # @description # Welcome to the Balena SDK documentation. # # This document aims to describe all the functions supported by the SDK, as well as showing examples of their expected usage. # # If you feel something is missing, not clear or could be improved, please don't hesitate to open an # [issue in GitHub](https://github.com/balena-io/balena-sdk/issues/new), we'll be happy to help. ### getSdk = (opts = {}) -> version = require('./util/sdk-version').default assign = require('lodash/assign') forEach = require('lodash/forEach') defaults = require('lodash/defaults') getRequest = require('balena-request') BalenaAuth = require('balena-auth')['default'] getPine = require('balena-pine') errors = require('balena-errors') { notImplemented } = require('./util') { PubSub } = require('./util/pubsub') ###* # @namespace models # @memberof balena ### ###* # @namespace auth # @memberof balena ### ###* # @namespace logs # @memberof balena ### ###* # @namespace settings # @memberof balena ### sdkTemplate = auth: require('./auth') models: require('./models') logs: require('./logs') settings: require('./settings') defaults opts, apiUrl: 'https://api.balena-cloud.com/' builderUrl: 'https://builder.balena-cloud.com/' # deprecated imageMakerUrl: 'https://img.balena-cloud.com/' isBrowser: window? # API version is configurable but only do so if you know what you're doing, # as the SDK is directly tied to a specific version. apiVersion: 'v5' if opts.isBrowser settings = get: notImplemented getAll: notImplemented else settings = require('balena-settings-client') defaults opts, dataDirectory: settings.get('dataDirectory') auth = new BalenaAuth(opts) request = getRequest(assign({}, opts, { auth })) pine = getPine(assign({}, opts, { auth, request })) pubsub = new PubSub() sdk = {} deps = { settings request auth pine pubsub sdkInstance: sdk } forEach(sdkTemplate, (moduleFactory, moduleName) -> sdk[moduleName] = moduleFactory(deps, opts)) ###* # @typedef Interceptor # @type {object} # @memberof balena.interceptors # # @description # An interceptor implements some set of the four interception hook callbacks. # To continue processing, each function should return a value or a promise that # successfully resolves to a value. # # To halt processing, each function should throw an error or return a promise that # rejects with an error. # # @property {function} [request] - Callback invoked before requests are made. Called with # the request options, should return (or resolve to) new request options, or throw/reject. # # @property {function} [response] - Callback invoked before responses are returned. Called with # the response, should return (or resolve to) a new response, or throw/reject. # # @property {function} [requestError] - Callback invoked if an error happens before a request. # Called with the error itself, caused by a preceeding request interceptor rejecting/throwing # an error for the request, or a failing in preflight token validation. Should return (or resolve # to) new request options, or throw/reject. # # @property {function} [responseError] - Callback invoked if an error happens in the response. # Called with the error itself, caused by a preceeding response interceptor rejecting/throwing # an error for the request, a network error, or an error response from the server. Should return # (or resolve to) a new response, or throw/reject. ### ###* # @summary Array of interceptors # @member {Interceptor[]} interceptors # @public # @memberof balena # # @description # The current array of interceptors to use. Interceptors intercept requests made # internally and are executed in the order they appear in this array for requests, # and in the reverse order for responses. # # @example # balena.interceptors.push({ # responseError: function (error) { # console.log(error); # throw error; # }) # }); ### Object.defineProperty sdk, 'interceptors', get: -> request.interceptors, set: (interceptors) -> request.interceptors = interceptors versionHeaderInterceptor = request: (request) -> url = request.url if typeof url != 'string' return request if typeof request.baseUrl == 'string' url = request.baseUrl + url if url.indexOf(opts.apiUrl) == 0 request.headers['X-Balena-Client'] = "balena-sdk/#{version}" return request sdk.interceptors.push(versionHeaderInterceptor) ###* # @summary Balena request instance # @member {Object} request # @public # @memberof balena # # @description # The balena-request instance used internally. This should not be necessary # in normal usage, but can be useful if you want to make an API request directly, # using the same token and hooks as the SDK. # # @example # balena.request.send({ url: 'http://api.balena-cloud.com/ping' }); ### sdk.request = request ###* # @summary Balena pine instance # @member {Object} pine # @public # @memberof balena # # @description # The balena-pine instance used internally. This should not be necessary # in normal usage, but can be useful if you want to directly make pine # queries to the api for some resource that isn't directly supported # in the SDK. # # @example # balena.pine.get({ # resource: 'release/$count', # options: { # $filter: { belongs_to__application: applicationId } # } # }); ### sdk.pine = pine ###* # @summary Balena errors module # @member {Object} errors # @public # @memberof balena # # @description # The balena-errors module used internally. This is provided primarily for # convenience, and to avoid the necessity for separate balena-errors # dependencies. You'll want to use this if you need to match on the specific # type of error thrown by the SDK. # # @example # balena.models.device.get(123).catch(function (error) { # if (error.code === balena.errors.BalenaDeviceNotFound.code) { # ... # } else if (error.code === balena.errors.BalenaRequestError.code) { # ... # } # }); ### sdk.errors = errors sdk.version = version return sdk ###* # @summary Set shared default options # @name setSharedOptions # @public # @function # @memberof balena # # @description # Set options that are used by calls to `balena.fromSharedOptions()`. # The options accepted are the same as those used in the main SDK factory function. # If you use this method, it should be called as soon as possible during app # startup and before any calls to `fromSharedOptions()` are made. # # @params {Object} opts - The shared default options # # @example # balena.setSharedOptions({ # apiUrl: 'https://api.balena-cloud.com/', # builderUrl: 'https://builder.balena-cloud.com/', # isBrowser: true, # }); ### getSdk.setSharedOptions = (opts) -> if globalEnv[BALENA_SDK_HAS_USED_SHARED_OPTIONS] console.error('Shared SDK options have already been used. You may have a race condition in your code.') if globalEnv[BALENA_SDK_HAS_SET_SHARED_OPTIONS] console.error('Shared SDK options have already been set. You may have a race condition in your code.') globalEnv[BALENA_SDK_SHARED_OPTIONS] = opts globalEnv[BALENA_SDK_HAS_SET_SHARED_OPTIONS] = true ###* # @summary Create an SDK instance using shared default options # @name fromSharedOptions # @public # @function # @memberof balena # # @description # Create an SDK instance using shared default options set using the `setSharedOptions()` method. # If options have not been set using this method, then this method will use the # same defaults as the main SDK factory function. # # @params {Object} opts - The shared default options # # @example # const sdk = balena.fromSharedOptions(); ### getSdk.fromSharedOptions = -> sharedOpts = globalEnv[BALENA_SDK_SHARED_OPTIONS] globalEnv[BALENA_SDK_HAS_USED_SHARED_OPTIONS] = true getSdk(sharedOpts) module.exports = getSdk
[ { "context": " label:\n en: 'bla'\n key: 'myEnum'\n expect(@exportMapping._mapAttribute at", "end": 4934, "score": 0.6366192698478699, "start": 4932, "tag": "KEY", "value": "my" }, { "context": " attributes: []\n name:\n de: 'Hallo'\n...
src/spec/exportmapping.spec.coffee
easybi-vv/sphere-node-product-csv-sync-1
0
_ = require 'underscore' Types = require '../lib/types' CONS = require '../lib/constants' {ExportMapping, Header, Categories} = require '../lib/main' describe 'ExportMapping', -> beforeEach -> @exportMapping = new ExportMapping() describe '#constructor', -> it 'should initialize', -> expect(@exportMapping).toBeDefined() describe '#mapPrices', -> beforeEach -> @exportMapping.channelService = id2key: {} @exportMapping.customerGroupService = id2name: {} it 'should map simple price', -> prices = [ { value: { centAmount: 999, currencyCode: 'EUR' } } ] expect(@exportMapping._mapPrices prices).toBe 'EUR 999' it 'should map price with country', -> prices = [ { value: { centAmount: 77, currencyCode: 'EUR' }, country: 'DE' } ] expect(@exportMapping._mapPrices prices).toBe 'DE-EUR 77' it 'should map multiple prices', -> prices = [ { value: { centAmount: 999, currencyCode: 'EUR' } } { value: { centAmount: 1099, currencyCode: 'USD' } } { value: { centAmount: 1299, currencyCode: 'CHF' } } ] expect(@exportMapping._mapPrices prices).toBe 'EUR 999;USD 1099;CHF 1299' it 'should map channel on price', -> @exportMapping.channelService.id2key['c123'] = 'myKey' prices = [ { value: { centAmount: 999, currencyCode: 'EUR' }, channel: { id: 'c123' } } ] expect(@exportMapping._mapPrices prices).toBe 'EUR 999#myKey' it 'should map customerGroup on price', -> @exportMapping.customerGroupService.id2name['cg987'] = 'B2B' prices = [ { value: { centAmount: 9999999, currencyCode: 'USD' }, customerGroup: { id: 'cg987' } } ] expect(@exportMapping._mapPrices prices).toBe 'USD 9999999 B2B' it 'should map discounted price', -> prices = [ { value: { centAmount: 1999, currencyCode: 'USD' }, discounted: { value: { centAmount: 999, currencyCode: 'USD' } } } ] expect(@exportMapping._mapPrices prices).toBe 'USD 1999|999' it 'should map customerGroup and channel on price', -> @exportMapping.channelService.id2key['channel_123'] = 'WAREHOUSE-1' @exportMapping.customerGroupService.id2name['987-xyz'] = 'sales' prices = [ { value: { centAmount: -13, currencyCode: 'EUR' }, customerGroup: { id: '987-xyz' }, channel: { id: 'channel_123' } } ] expect(@exportMapping._mapPrices prices).toBe 'EUR -13 sales#WAREHOUSE-1' it 'should map price with a validFrom field', -> prices = [ { value: { centAmount: -13, currencyCode: 'EUR' }, validFrom: '2001-09-11T14:00:00.000Z' } ] expect(@exportMapping._mapPrices prices).toBe 'EUR -13$2001-09-11T14:00:00.000Z' it 'should map price with a validUntil field', -> prices = [ { value: { centAmount: -15, currencyCode: 'EUR' }, validUntil: '2015-09-11T14:00:00.000Z' } ] expect(@exportMapping._mapPrices prices).toBe 'EUR -15~2015-09-11T14:00:00.000Z' it 'should map price with validFrom and validUntil fields', -> prices = [ { value: { centAmount: -13, currencyCode: 'EUR' }, validFrom: '2001-09-11T14:00:00.000Z', validUntil: '2001-09-12T14:00:00.000Z' } ] expect(@exportMapping._mapPrices prices).toBe 'EUR -13$2001-09-11T14:00:00.000Z~2001-09-12T14:00:00.000Z' describe '#mapImage', -> it 'should map single image', -> images = [ { url: '//example.com/image.jpg' } ] expect(@exportMapping._mapImages images).toBe '//example.com/image.jpg' it 'should map multiple images', -> images = [ { url: '//example.com/image.jpg' } { url: 'https://www.example.com/pic.png' } ] expect(@exportMapping._mapImages images).toBe '//example.com/image.jpg;https://www.example.com/pic.png' describe '#mapAttribute', -> beforeEach -> @exportMapping.typesService = new Types() @productType = id: '123' attributes: [ { name: 'myTextAttrib', type: { name: 'text' } } { name: 'myEnumAttrib', type: { name: 'enum' } } { name: 'myLenumAttrib', type: { name: 'lenum' } } { name: 'myTextSetAttrib', type: { name: 'set', elementType: { name: 'text' } } } { name: 'myEnumSetAttrib', type: { name: 'set', elementType: { name: 'enum' } } } { name: 'myLenumSetAttrib', type: { name: 'set', elementType: { name: 'lenum' } } } ] @exportMapping.typesService.buildMaps [@productType] it 'should map simple attribute', -> attribute = name: 'myTextAttrib' value: 'some text' expect(@exportMapping._mapAttribute attribute, @productType.attributes[0].type).toBe 'some text' it 'should map enum attribute', -> attribute = name: 'myEnumAttrib' value: label: en: 'bla' key: 'myEnum' expect(@exportMapping._mapAttribute attribute, @productType.attributes[1].type).toBe 'myEnum' it 'should map text set attribute', -> attribute = name: 'myTextSetAttrib' value: [ 'x', 'y', 'z' ] expect(@exportMapping._mapAttribute attribute, @productType.attributes[3].type).toBe 'x;y;z' it 'should map enum set attribute', -> attribute = name: 'myEnumSetAttrib' value: [ { label: en: 'bla' key: 'myEnum' } { label: en: 'foo' key: 'myEnum2' } ] expect(@exportMapping._mapAttribute attribute, @productType.attributes[4].type).toBe 'myEnum;myEnum2' describe '#mapVariant', -> it 'should map variant id and sku', -> @exportMapping.header = new Header([CONS.HEADER_VARIANT_ID, CONS.HEADER_SKU]) @exportMapping.header.toIndex() variant = id: '12' sku: 'mySKU' attributes: [] row = @exportMapping._mapVariant(variant) expect(row).toEqual [ '12', 'mySKU' ] it 'should map variant attributes', -> @exportMapping.header = new Header([ 'foo' ]) @exportMapping.header.toIndex() @exportMapping.typesService = new Types() productType = id: '123' attributes: [ { name: 'foo', type: { name: 'text' } } ] @exportMapping.typesService.buildMaps [productType] variant = attributes: [ { name: 'foo', value: 'bar' } ] row = @exportMapping._mapVariant(variant, productType) expect(row).toEqual [ 'bar' ] describe '#mapBaseProduct', -> it 'should map productType (name), product id and categories by externalId', -> @exportMapping.categoryService = new Categories() @exportMapping.categoryService.buildMaps [ { id: '9e6de6ad-cc94-4034-aa9f-276ccb437efd', name: en: 'BrilliantCoeur', slug: en: 'brilliantcoeur', externalId: 'BRI', }, { id: '0afacd76-30d8-431e-aff9-376cd1b4c9e6', name: en: 'Autumn / Winter 2016', slug: en: 'autmn-winter-2016', externalId: '9997', } ] @exportMapping.categoryBy = 'externalId' @exportMapping.header = new Header( [CONS.HEADER_PRODUCT_TYPE, CONS.HEADER_ID, CONS.HEADER_CATEGORIES]) @exportMapping.header.toIndex() product = id: '123' categories: [ { typeId: 'category', id: '9e6de6ad-cc94-4034-aa9f-276ccb437efd' }, { typeId: 'category', id: '0afacd76-30d8-431e-aff9-376cd1b4c9e6' } ], masterVariant: attributes: [] type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ 'myType', '123', 'BRI;9997'] it 'should not map categoryOrderhints when they are not present', -> @exportMapping.categoryService = new Categories() @exportMapping.categoryService.buildMaps [ { id: '9e6de6ad-cc94-4034-aa9f-276ccb437efd', name: en: 'BrilliantCoeur', slug: en: 'brilliantcoeur', externalId: 'BRI', }, { id: '0afacd76-30d8-431e-aff9-376cd1b4c9e6', name: en: 'Autumn / Winter 2016', slug: en: 'autmn-winter-2016', externalId: '9997', } ] @exportMapping.categoryBy = 'externalId' @exportMapping.header = new Header( [CONS.HEADER_PRODUCT_TYPE, CONS.HEADER_ID, CONS.HEADER_CATEGORY_ORDER_HINTS]) @exportMapping.header.toIndex() product = id: '123' categories: [ { typeId: 'category', id: '9e6de6ad-cc94-4034-aa9f-276ccb437efd' }, { typeId: 'category', id: '0afacd76-30d8-431e-aff9-376cd1b4c9e6' } ], masterVariant: attributes: [] type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ 'myType', '123', ''] it 'should map productType (name), product id and categoryOrderhints by externalId', -> @exportMapping.categoryService = new Categories() @exportMapping.categoryService.buildMaps [ { id: '9e6de6ad-cc94-4034-aa9f-276ccb437efd', name: en: 'BrilliantCoeur', slug: en: 'brilliantcoeur', externalId: 'BRI', }, { id: '0afacd76-30d8-431e-aff9-376cd1b4c9e6', name: en: 'Autumn / Winter 2016', slug: en: 'autmn-winter-2016', externalId: '9997', } ] @exportMapping.categoryBy = 'externalId' @exportMapping.header = new Header( [CONS.HEADER_PRODUCT_TYPE, CONS.HEADER_ID, CONS.HEADER_CATEGORY_ORDER_HINTS]) @exportMapping.header.toIndex() product = id: '123' categoryOrderHints: { '9e6de6ad-cc94-4034-aa9f-276ccb437efd': '0.9283' '0afacd76-30d8-431e-aff9-376cd1b4c9e6': '0.3223' }, categories: [], masterVariant: attributes: [] type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ 'myType', '123', '9e6de6ad-cc94-4034-aa9f-276ccb437efd:0.9283;0afacd76-30d8-431e-aff9-376cd1b4c9e6:0.3223'] it 'should map createdAt and lastModifiedAt', -> @exportMapping.header = new Header( [CONS.HEADER_CREATED_AT, CONS.HEADER_LAST_MODIFIED_AT]) @exportMapping.header.toIndex() createdAt = new Date() lastModifiedAt = new Date() product = createdAt: createdAt lastModifiedAt: lastModifiedAt masterVariant: attributes: [] type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ createdAt, lastModifiedAt ] it 'should map tax category name', -> @exportMapping.header = new Header([CONS.HEADER_TAX]) @exportMapping.header.toIndex() @exportMapping.taxService = id2name: tax123: 'myTax' product = id: '123' masterVariant: attributes: [] taxCategory: id: 'tax123' type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ 'myTax' ] it 'should map state key', -> @exportMapping.header = new Header([CONS.HEADER_STATE]) @exportMapping.header.toIndex() @exportMapping.stateService = id2key: state123: 'myState' product = id: '123' masterVariant: attributes: [] state: id: 'state123' type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ 'myState' ] it 'should map localized base attributes', -> @exportMapping.header = new Header(['name.de','slug.it','description.en','searchKeywords.de']) @exportMapping.header.toIndex() product = id: '123' masterVariant: attributes: [] name: de: 'Hallo' en: 'Hello' it: 'Ciao' slug: de: 'hallo' en: 'hello' it: 'ciao' description: de: 'Bla bla' en: 'Foo bar' it: 'Ciao Bella' searchKeywords: de: [ (text: "test") (text: "sample") ] en: [ (text: "drops") (text: "kocher") ] it: [ (text: "bla") (text: "foo") (text: "bar") ] row = @exportMapping._mapBaseProduct(product, {}) expect(row).toEqual [ 'Hallo', 'ciao', 'Foo bar','test;sample'] describe '#mapLenumAndSetOfLenum', -> beforeEach -> @exportMapping.typesService = new Types() @productType = id: '123' attributes: [ { name: 'myLenumAttrib', type: { name: 'lenum' } } { name: 'myLenumSetAttrib', type: { name: 'set', elementType: { name: 'lenum' } } } ] @exportMapping.typesService.buildMaps [@productType] it 'should map key of lenum and set of lenum if no language is given', -> @exportMapping.header = new Header(['myLenumAttrib.en','myLenumAttrib','myLenumSetAttrib.fr-BE','myLenumSetAttrib']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLenumAttrib' value: key: 'myEnum' label: en: 'bla' de: 'blub' }, { name: 'myLenumSetAttrib' value: [ { key: 'drops', label: { "fr-BE": 'le drops', de: 'der drops', en: 'the drops' } }, { "key": "honk", "label": { "en": "the honk", "fr-BE": "le honk", "de-DE": "der honk" } } ] } ] row = @exportMapping._mapVariant(variant, @productType) expect(row).toEqual [ 'bla','myEnum','le drops;le honk','drops;honk'] it 'should map the labels of lenum and set of lenum if language is given', -> @exportMapping.header = new Header(['myLenumAttrib.en','myLenumSetAttrib.fr-BE']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLenumAttrib' value: key: 'myEnum' label: en: 'bla' de: 'blub' }, { name: 'myLenumSetAttrib' value: [ { key: 'drops', label: { "fr-BE": 'le drops', de: 'der drops', en: 'the drops' } }, { "key": "honk", "label": { "en": "the honk", "fr-BE": "le honk", "de-DE": "der honk" } } ] } ] row = @exportMapping._mapVariant(variant, @productType) expect(row).toEqual [ 'bla','le drops;le honk' ] describe '#mapLtextSet', -> beforeEach -> @exportMapping.typesService = new Types() @productType = id: '123' attributes: [ { name: 'myLtextSetAttrib', type: { name: 'set', elementType: { name: 'ltext' } } } ] @exportMapping.typesService.buildMaps [@productType] it 'should map set of ltext', -> @exportMapping.header = new Header(['myLtextSetAttrib.de','myLtextSetAttrib.en']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLtextSetAttrib' value: [ {"en": "foo1", "de": "barA"}, {"en": "foo2", "de": "barB"}, {"de": "barC", "nl": "invisible"} ] } ] row = @exportMapping._mapVariant(variant, @productType) expected = [ 'barA;barB;barC','foo1;foo2' ] expect(row).toEqual expected it 'should return undefined for invalid set of attributes', -> @exportMapping.header = new Header(['myLtextSetAttrib','myLtextSetAttrib.en', 'myLtextSetAttrib.de']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLtextSetAttrib' value: [ {"en": "foo1", "de": "barA"}, {"en": "foo2", "de": "barB"}, {"de": "barC", "nl": "invisible"} ] } ] row = @exportMapping._mapVariant(variant, @productType) expected = [ undefined,'foo1;foo2', 'barA;barB;barC' ] expect(row).toEqual expected it 'should ignore trailing invalid set of attributes', -> @exportMapping.header = new Header(['myLtextSetAttrib.en', 'myLtextSetAttrib.de', 'foo', 'bar']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLtextSetAttrib' value: [ {"en": "foo1", "de": "barA"}, {"en": "foo2", "de": "barB"}, {"de": "barC", "nl": "invisible"} ] } ] row = @exportMapping._mapVariant(variant, @productType) expected = [ 'foo1;foo2', 'barA;barB;barC' ] expect(row).toEqual expected it 'should return undefined for invalid set of attributes that is not trailing', -> @exportMapping.header = new Header(['myLtextSetAttrib.en', 'foo', 'bar', 'myLtextSetAttrib.de']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLtextSetAttrib' value: [ {"en": "foo1", "de": "barA"}, {"en": "foo2", "de": "barB"}, {"de": "barC", "nl": "invisible"} ] } ] row = @exportMapping._mapVariant(variant, @productType) expected = [ 'foo1;foo2', undefined, undefined, 'barA;barB;barC' ] expect(row).toEqual expected describe '#createTemplate', -> beforeEach -> @productType = attributes: [] it 'should do nothing if there are no attributes', -> template = @exportMapping.createTemplate @productType expect(_.intersection template, [ CONS.HEADER_PUBLISHED, CONS.HEADER_HAS_STAGED_CHANGES ]).toEqual [ CONS.HEADER_PUBLISHED, CONS.HEADER_HAS_STAGED_CHANGES ] expect(_.intersection template, CONS.BASE_HEADERS).toEqual CONS.BASE_HEADERS expect(_.intersection template, CONS.SPECIAL_HEADERS).toEqual CONS.SPECIAL_HEADERS _.each CONS.BASE_LOCALIZED_HEADERS, (h) -> expect(_.contains template, "#{h}.en").toBe true it 'should get attribute name for all kind of types', -> @productType.attributes.push { name: 'a-enum', type: { name: 'enum' } } @productType.attributes.push { name: 'a-lenum', type: { name: 'lenum' } } @productType.attributes.push { name: 'a-text', type: { name: 'text' } } @productType.attributes.push { name: 'a-number', type: { name: 'number' } } @productType.attributes.push { name: 'a-money', type: { name: 'money' } } @productType.attributes.push { name: 'a-date', type: { name: 'date' } } @productType.attributes.push { name: 'a-time', type: { name: 'time' } } @productType.attributes.push { name: 'a-datetime', type: { name: 'datetime' } } template = @exportMapping.createTemplate @productType expectedHeaders = [ 'a-enum', 'a-lenum', 'a-text', 'a-number', 'a-money', 'a-date', 'a-time', 'a-datetime' ] _.map expectedHeaders, (h) -> expect(_.contains template, h).toBe true it 'should add headers for all languages', -> @productType.attributes.push { name: 'multilang', type: { name: 'ltext' } } template = @exportMapping.createTemplate @productType, [ 'de', 'en', 'it' ] _.each CONS.BASE_LOCALIZED_HEADERS, (h) -> expect(_.contains template, "#{h}.de").toBe true expect(_.contains template, "#{h}.en").toBe true expect(_.contains template, "#{h}.it").toBe true expect(_.contains template, "multilang.de").toBe true expect(_.contains template, "multilang.en").toBe true expect(_.contains template, "multilang.it").toBe true describe '#mapOnlyMasterVariants', -> beforeEach -> @sampleProduct = id: '123' productType: id: 'myType' name: de: 'Hallo' slug: de: 'hallo' description: de: 'Bla bla' masterVariant: id: 1 sku: 'var1' key: 'var1Key' variants: [ { id: 2 sku: 'var2' key: 'var2Key' } ] it 'should map all variants', -> _exportMapping = new ExportMapping( typesService: id2index: myType: 0 ) _exportMapping.header = new Header([CONS.HEADER_VARIANT_ID, CONS.HEADER_SKU]) _exportMapping.header.toIndex() type = name: 'myType' id: 'typeId123' mappedProduct = _exportMapping.mapProduct @sampleProduct, [type] # both variants should be mapped expect(mappedProduct).toEqual [ [ 1, 'var1' ], [ 2, 'var2' ] ] it 'should map only masterVariant', -> _exportMapping = new ExportMapping( onlyMasterVariants: true typesService: id2index: myType: 0 ) _exportMapping.header = new Header([CONS.HEADER_VARIANT_ID, CONS.HEADER_SKU]) _exportMapping.header.toIndex() type = name: 'myType' id: 'typeId123' mappedProduct = _exportMapping.mapProduct @sampleProduct, [type] # only masterVariant should be mapped expect(mappedProduct).toEqual [ [ 1, 'var1' ] ]
151351
_ = require 'underscore' Types = require '../lib/types' CONS = require '../lib/constants' {ExportMapping, Header, Categories} = require '../lib/main' describe 'ExportMapping', -> beforeEach -> @exportMapping = new ExportMapping() describe '#constructor', -> it 'should initialize', -> expect(@exportMapping).toBeDefined() describe '#mapPrices', -> beforeEach -> @exportMapping.channelService = id2key: {} @exportMapping.customerGroupService = id2name: {} it 'should map simple price', -> prices = [ { value: { centAmount: 999, currencyCode: 'EUR' } } ] expect(@exportMapping._mapPrices prices).toBe 'EUR 999' it 'should map price with country', -> prices = [ { value: { centAmount: 77, currencyCode: 'EUR' }, country: 'DE' } ] expect(@exportMapping._mapPrices prices).toBe 'DE-EUR 77' it 'should map multiple prices', -> prices = [ { value: { centAmount: 999, currencyCode: 'EUR' } } { value: { centAmount: 1099, currencyCode: 'USD' } } { value: { centAmount: 1299, currencyCode: 'CHF' } } ] expect(@exportMapping._mapPrices prices).toBe 'EUR 999;USD 1099;CHF 1299' it 'should map channel on price', -> @exportMapping.channelService.id2key['c123'] = 'myKey' prices = [ { value: { centAmount: 999, currencyCode: 'EUR' }, channel: { id: 'c123' } } ] expect(@exportMapping._mapPrices prices).toBe 'EUR 999#myKey' it 'should map customerGroup on price', -> @exportMapping.customerGroupService.id2name['cg987'] = 'B2B' prices = [ { value: { centAmount: 9999999, currencyCode: 'USD' }, customerGroup: { id: 'cg987' } } ] expect(@exportMapping._mapPrices prices).toBe 'USD 9999999 B2B' it 'should map discounted price', -> prices = [ { value: { centAmount: 1999, currencyCode: 'USD' }, discounted: { value: { centAmount: 999, currencyCode: 'USD' } } } ] expect(@exportMapping._mapPrices prices).toBe 'USD 1999|999' it 'should map customerGroup and channel on price', -> @exportMapping.channelService.id2key['channel_123'] = 'WAREHOUSE-1' @exportMapping.customerGroupService.id2name['987-xyz'] = 'sales' prices = [ { value: { centAmount: -13, currencyCode: 'EUR' }, customerGroup: { id: '987-xyz' }, channel: { id: 'channel_123' } } ] expect(@exportMapping._mapPrices prices).toBe 'EUR -13 sales#WAREHOUSE-1' it 'should map price with a validFrom field', -> prices = [ { value: { centAmount: -13, currencyCode: 'EUR' }, validFrom: '2001-09-11T14:00:00.000Z' } ] expect(@exportMapping._mapPrices prices).toBe 'EUR -13$2001-09-11T14:00:00.000Z' it 'should map price with a validUntil field', -> prices = [ { value: { centAmount: -15, currencyCode: 'EUR' }, validUntil: '2015-09-11T14:00:00.000Z' } ] expect(@exportMapping._mapPrices prices).toBe 'EUR -15~2015-09-11T14:00:00.000Z' it 'should map price with validFrom and validUntil fields', -> prices = [ { value: { centAmount: -13, currencyCode: 'EUR' }, validFrom: '2001-09-11T14:00:00.000Z', validUntil: '2001-09-12T14:00:00.000Z' } ] expect(@exportMapping._mapPrices prices).toBe 'EUR -13$2001-09-11T14:00:00.000Z~2001-09-12T14:00:00.000Z' describe '#mapImage', -> it 'should map single image', -> images = [ { url: '//example.com/image.jpg' } ] expect(@exportMapping._mapImages images).toBe '//example.com/image.jpg' it 'should map multiple images', -> images = [ { url: '//example.com/image.jpg' } { url: 'https://www.example.com/pic.png' } ] expect(@exportMapping._mapImages images).toBe '//example.com/image.jpg;https://www.example.com/pic.png' describe '#mapAttribute', -> beforeEach -> @exportMapping.typesService = new Types() @productType = id: '123' attributes: [ { name: 'myTextAttrib', type: { name: 'text' } } { name: 'myEnumAttrib', type: { name: 'enum' } } { name: 'myLenumAttrib', type: { name: 'lenum' } } { name: 'myTextSetAttrib', type: { name: 'set', elementType: { name: 'text' } } } { name: 'myEnumSetAttrib', type: { name: 'set', elementType: { name: 'enum' } } } { name: 'myLenumSetAttrib', type: { name: 'set', elementType: { name: 'lenum' } } } ] @exportMapping.typesService.buildMaps [@productType] it 'should map simple attribute', -> attribute = name: 'myTextAttrib' value: 'some text' expect(@exportMapping._mapAttribute attribute, @productType.attributes[0].type).toBe 'some text' it 'should map enum attribute', -> attribute = name: 'myEnumAttrib' value: label: en: 'bla' key: '<KEY>Enum' expect(@exportMapping._mapAttribute attribute, @productType.attributes[1].type).toBe 'myEnum' it 'should map text set attribute', -> attribute = name: 'myTextSetAttrib' value: [ 'x', 'y', 'z' ] expect(@exportMapping._mapAttribute attribute, @productType.attributes[3].type).toBe 'x;y;z' it 'should map enum set attribute', -> attribute = name: 'myEnumSetAttrib' value: [ { label: en: 'bla' key: 'myEnum' } { label: en: 'foo' key: 'myEnum2' } ] expect(@exportMapping._mapAttribute attribute, @productType.attributes[4].type).toBe 'myEnum;myEnum2' describe '#mapVariant', -> it 'should map variant id and sku', -> @exportMapping.header = new Header([CONS.HEADER_VARIANT_ID, CONS.HEADER_SKU]) @exportMapping.header.toIndex() variant = id: '12' sku: 'mySKU' attributes: [] row = @exportMapping._mapVariant(variant) expect(row).toEqual [ '12', 'mySKU' ] it 'should map variant attributes', -> @exportMapping.header = new Header([ 'foo' ]) @exportMapping.header.toIndex() @exportMapping.typesService = new Types() productType = id: '123' attributes: [ { name: 'foo', type: { name: 'text' } } ] @exportMapping.typesService.buildMaps [productType] variant = attributes: [ { name: 'foo', value: 'bar' } ] row = @exportMapping._mapVariant(variant, productType) expect(row).toEqual [ 'bar' ] describe '#mapBaseProduct', -> it 'should map productType (name), product id and categories by externalId', -> @exportMapping.categoryService = new Categories() @exportMapping.categoryService.buildMaps [ { id: '9e6de6ad-cc94-4034-aa9f-276ccb437efd', name: en: 'BrilliantCoeur', slug: en: 'brilliantcoeur', externalId: 'BRI', }, { id: '0afacd76-30d8-431e-aff9-376cd1b4c9e6', name: en: 'Autumn / Winter 2016', slug: en: 'autmn-winter-2016', externalId: '9997', } ] @exportMapping.categoryBy = 'externalId' @exportMapping.header = new Header( [CONS.HEADER_PRODUCT_TYPE, CONS.HEADER_ID, CONS.HEADER_CATEGORIES]) @exportMapping.header.toIndex() product = id: '123' categories: [ { typeId: 'category', id: '9e6de6ad-cc94-4034-aa9f-276ccb437efd' }, { typeId: 'category', id: '0afacd76-30d8-431e-aff9-376cd1b4c9e6' } ], masterVariant: attributes: [] type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ 'myType', '123', 'BRI;9997'] it 'should not map categoryOrderhints when they are not present', -> @exportMapping.categoryService = new Categories() @exportMapping.categoryService.buildMaps [ { id: '9e6de6ad-cc94-4034-aa9f-276ccb437efd', name: en: 'BrilliantCoeur', slug: en: 'brilliantcoeur', externalId: 'BRI', }, { id: '0afacd76-30d8-431e-aff9-376cd1b4c9e6', name: en: 'Autumn / Winter 2016', slug: en: 'autmn-winter-2016', externalId: '9997', } ] @exportMapping.categoryBy = 'externalId' @exportMapping.header = new Header( [CONS.HEADER_PRODUCT_TYPE, CONS.HEADER_ID, CONS.HEADER_CATEGORY_ORDER_HINTS]) @exportMapping.header.toIndex() product = id: '123' categories: [ { typeId: 'category', id: '9e6de6ad-cc94-4034-aa9f-276ccb437efd' }, { typeId: 'category', id: '0afacd76-30d8-431e-aff9-376cd1b4c9e6' } ], masterVariant: attributes: [] type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ 'myType', '123', ''] it 'should map productType (name), product id and categoryOrderhints by externalId', -> @exportMapping.categoryService = new Categories() @exportMapping.categoryService.buildMaps [ { id: '9e6de6ad-cc94-4034-aa9f-276ccb437efd', name: en: 'BrilliantCoeur', slug: en: 'brilliantcoeur', externalId: 'BRI', }, { id: '0afacd76-30d8-431e-aff9-376cd1b4c9e6', name: en: 'Autumn / Winter 2016', slug: en: 'autmn-winter-2016', externalId: '9997', } ] @exportMapping.categoryBy = 'externalId' @exportMapping.header = new Header( [CONS.HEADER_PRODUCT_TYPE, CONS.HEADER_ID, CONS.HEADER_CATEGORY_ORDER_HINTS]) @exportMapping.header.toIndex() product = id: '123' categoryOrderHints: { '9e6de6ad-cc94-4034-aa9f-276ccb437efd': '0.9283' '0afacd76-30d8-431e-aff9-376cd1b4c9e6': '0.3223' }, categories: [], masterVariant: attributes: [] type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ 'myType', '123', '9e6de6ad-cc94-4034-aa9f-276ccb437efd:0.9283;0afacd76-30d8-431e-aff9-376cd1b4c9e6:0.3223'] it 'should map createdAt and lastModifiedAt', -> @exportMapping.header = new Header( [CONS.HEADER_CREATED_AT, CONS.HEADER_LAST_MODIFIED_AT]) @exportMapping.header.toIndex() createdAt = new Date() lastModifiedAt = new Date() product = createdAt: createdAt lastModifiedAt: lastModifiedAt masterVariant: attributes: [] type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ createdAt, lastModifiedAt ] it 'should map tax category name', -> @exportMapping.header = new Header([CONS.HEADER_TAX]) @exportMapping.header.toIndex() @exportMapping.taxService = id2name: tax123: 'myTax' product = id: '123' masterVariant: attributes: [] taxCategory: id: 'tax123' type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ 'myTax' ] it 'should map state key', -> @exportMapping.header = new Header([CONS.HEADER_STATE]) @exportMapping.header.toIndex() @exportMapping.stateService = id2key: state123: 'myState' product = id: '123' masterVariant: attributes: [] state: id: 'state123' type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ 'myState' ] it 'should map localized base attributes', -> @exportMapping.header = new Header(['name.de','slug.it','description.en','searchKeywords.de']) @exportMapping.header.toIndex() product = id: '123' masterVariant: attributes: [] name: de: '<NAME>' en: 'Hello' it: 'Ciao' slug: de: 'hallo' en: 'hello' it: 'ciao' description: de: 'Bla bla' en: 'Foo bar' it: 'Ciao Bella' searchKeywords: de: [ (text: "test") (text: "sample") ] en: [ (text: "drops") (text: "kocher") ] it: [ (text: "bla") (text: "foo") (text: "bar") ] row = @exportMapping._mapBaseProduct(product, {}) expect(row).toEqual [ 'Hallo', 'ciao', 'Foo bar','test;sample'] describe '#mapLenumAndSetOfLenum', -> beforeEach -> @exportMapping.typesService = new Types() @productType = id: '123' attributes: [ { name: 'myLenumAttrib', type: { name: 'lenum' } } { name: 'myLenumSetAttrib', type: { name: 'set', elementType: { name: 'lenum' } } } ] @exportMapping.typesService.buildMaps [@productType] it 'should map key of lenum and set of lenum if no language is given', -> @exportMapping.header = new Header(['myLenumAttrib.en','myLenumAttrib','myLenumSetAttrib.fr-BE','myLenumSetAttrib']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLenumAttrib' value: key: 'myEnum' label: en: 'bla' de: 'blub' }, { name: 'myLenumSetAttrib' value: [ { key: 'drops', label: { "fr-BE": 'le drops', de: 'der drops', en: 'the drops' } }, { "key": "honk", "label": { "en": "the honk", "fr-BE": "le honk", "de-DE": "der honk" } } ] } ] row = @exportMapping._mapVariant(variant, @productType) expect(row).toEqual [ 'bla','myEnum','le drops;le honk','drops;honk'] it 'should map the labels of lenum and set of lenum if language is given', -> @exportMapping.header = new Header(['myLenumAttrib.en','myLenumSetAttrib.fr-BE']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLenumAttrib' value: key: 'myEnum' label: en: 'bla' de: 'blub' }, { name: 'myLenumSetAttrib' value: [ { key: 'drops', label: { "fr-BE": 'le drops', de: 'der drops', en: 'the drops' } }, { "key": "honk", "label": { "en": "the honk", "fr-BE": "le honk", "de-DE": "der honk" } } ] } ] row = @exportMapping._mapVariant(variant, @productType) expect(row).toEqual [ 'bla','le drops;le honk' ] describe '#mapLtextSet', -> beforeEach -> @exportMapping.typesService = new Types() @productType = id: '123' attributes: [ { name: 'myLtextSetAttrib', type: { name: 'set', elementType: { name: 'ltext' } } } ] @exportMapping.typesService.buildMaps [@productType] it 'should map set of ltext', -> @exportMapping.header = new Header(['myLtextSetAttrib.de','myLtextSetAttrib.en']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLtextSetAttrib' value: [ {"en": "foo1", "de": "barA"}, {"en": "foo2", "de": "barB"}, {"de": "barC", "nl": "invisible"} ] } ] row = @exportMapping._mapVariant(variant, @productType) expected = [ 'barA;barB;barC','foo1;foo2' ] expect(row).toEqual expected it 'should return undefined for invalid set of attributes', -> @exportMapping.header = new Header(['myLtextSetAttrib','myLtextSetAttrib.en', 'myLtextSetAttrib.de']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLtextSetAttrib' value: [ {"en": "foo1", "de": "barA"}, {"en": "foo2", "de": "barB"}, {"de": "barC", "nl": "invisible"} ] } ] row = @exportMapping._mapVariant(variant, @productType) expected = [ undefined,'foo1;foo2', 'barA;barB;barC' ] expect(row).toEqual expected it 'should ignore trailing invalid set of attributes', -> @exportMapping.header = new Header(['myLtextSetAttrib.en', 'myLtextSetAttrib.de', 'foo', 'bar']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLtextSetAttrib' value: [ {"en": "foo1", "de": "barA"}, {"en": "foo2", "de": "barB"}, {"de": "barC", "nl": "invisible"} ] } ] row = @exportMapping._mapVariant(variant, @productType) expected = [ 'foo1;foo2', 'barA;barB;barC' ] expect(row).toEqual expected it 'should return undefined for invalid set of attributes that is not trailing', -> @exportMapping.header = new Header(['myLtextSetAttrib.en', 'foo', 'bar', 'myLtextSetAttrib.de']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLtextSetAttrib' value: [ {"en": "foo1", "de": "barA"}, {"en": "foo2", "de": "barB"}, {"de": "barC", "nl": "invisible"} ] } ] row = @exportMapping._mapVariant(variant, @productType) expected = [ 'foo1;foo2', undefined, undefined, 'barA;barB;barC' ] expect(row).toEqual expected describe '#createTemplate', -> beforeEach -> @productType = attributes: [] it 'should do nothing if there are no attributes', -> template = @exportMapping.createTemplate @productType expect(_.intersection template, [ CONS.HEADER_PUBLISHED, CONS.HEADER_HAS_STAGED_CHANGES ]).toEqual [ CONS.HEADER_PUBLISHED, CONS.HEADER_HAS_STAGED_CHANGES ] expect(_.intersection template, CONS.BASE_HEADERS).toEqual CONS.BASE_HEADERS expect(_.intersection template, CONS.SPECIAL_HEADERS).toEqual CONS.SPECIAL_HEADERS _.each CONS.BASE_LOCALIZED_HEADERS, (h) -> expect(_.contains template, "#{h}.en").toBe true it 'should get attribute name for all kind of types', -> @productType.attributes.push { name: 'a-enum', type: { name: 'enum' } } @productType.attributes.push { name: 'a-lenum', type: { name: 'lenum' } } @productType.attributes.push { name: 'a-text', type: { name: 'text' } } @productType.attributes.push { name: 'a-number', type: { name: 'number' } } @productType.attributes.push { name: 'a-money', type: { name: 'money' } } @productType.attributes.push { name: 'a-date', type: { name: 'date' } } @productType.attributes.push { name: 'a-time', type: { name: 'time' } } @productType.attributes.push { name: 'a-datetime', type: { name: 'datetime' } } template = @exportMapping.createTemplate @productType expectedHeaders = [ 'a-enum', 'a-lenum', 'a-text', 'a-number', 'a-money', 'a-date', 'a-time', 'a-datetime' ] _.map expectedHeaders, (h) -> expect(_.contains template, h).toBe true it 'should add headers for all languages', -> @productType.attributes.push { name: 'multilang', type: { name: 'ltext' } } template = @exportMapping.createTemplate @productType, [ 'de', 'en', 'it' ] _.each CONS.BASE_LOCALIZED_HEADERS, (h) -> expect(_.contains template, "#{h}.de").toBe true expect(_.contains template, "#{h}.en").toBe true expect(_.contains template, "#{h}.it").toBe true expect(_.contains template, "multilang.de").toBe true expect(_.contains template, "multilang.en").toBe true expect(_.contains template, "multilang.it").toBe true describe '#mapOnlyMasterVariants', -> beforeEach -> @sampleProduct = id: '123' productType: id: 'myType' name: de: '<NAME>' slug: de: 'hallo' description: de: 'Bla bla' masterVariant: id: 1 sku: 'var1' key: 'var1Key' variants: [ { id: 2 sku: 'var2' key: 'var2Key' } ] it 'should map all variants', -> _exportMapping = new ExportMapping( typesService: id2index: myType: 0 ) _exportMapping.header = new Header([CONS.HEADER_VARIANT_ID, CONS.HEADER_SKU]) _exportMapping.header.toIndex() type = name: 'myType' id: 'typeId123' mappedProduct = _exportMapping.mapProduct @sampleProduct, [type] # both variants should be mapped expect(mappedProduct).toEqual [ [ 1, 'var1' ], [ 2, 'var2' ] ] it 'should map only masterVariant', -> _exportMapping = new ExportMapping( onlyMasterVariants: true typesService: id2index: myType: 0 ) _exportMapping.header = new Header([CONS.HEADER_VARIANT_ID, CONS.HEADER_SKU]) _exportMapping.header.toIndex() type = name: 'myType' id: 'typeId123' mappedProduct = _exportMapping.mapProduct @sampleProduct, [type] # only masterVariant should be mapped expect(mappedProduct).toEqual [ [ 1, 'var1' ] ]
true
_ = require 'underscore' Types = require '../lib/types' CONS = require '../lib/constants' {ExportMapping, Header, Categories} = require '../lib/main' describe 'ExportMapping', -> beforeEach -> @exportMapping = new ExportMapping() describe '#constructor', -> it 'should initialize', -> expect(@exportMapping).toBeDefined() describe '#mapPrices', -> beforeEach -> @exportMapping.channelService = id2key: {} @exportMapping.customerGroupService = id2name: {} it 'should map simple price', -> prices = [ { value: { centAmount: 999, currencyCode: 'EUR' } } ] expect(@exportMapping._mapPrices prices).toBe 'EUR 999' it 'should map price with country', -> prices = [ { value: { centAmount: 77, currencyCode: 'EUR' }, country: 'DE' } ] expect(@exportMapping._mapPrices prices).toBe 'DE-EUR 77' it 'should map multiple prices', -> prices = [ { value: { centAmount: 999, currencyCode: 'EUR' } } { value: { centAmount: 1099, currencyCode: 'USD' } } { value: { centAmount: 1299, currencyCode: 'CHF' } } ] expect(@exportMapping._mapPrices prices).toBe 'EUR 999;USD 1099;CHF 1299' it 'should map channel on price', -> @exportMapping.channelService.id2key['c123'] = 'myKey' prices = [ { value: { centAmount: 999, currencyCode: 'EUR' }, channel: { id: 'c123' } } ] expect(@exportMapping._mapPrices prices).toBe 'EUR 999#myKey' it 'should map customerGroup on price', -> @exportMapping.customerGroupService.id2name['cg987'] = 'B2B' prices = [ { value: { centAmount: 9999999, currencyCode: 'USD' }, customerGroup: { id: 'cg987' } } ] expect(@exportMapping._mapPrices prices).toBe 'USD 9999999 B2B' it 'should map discounted price', -> prices = [ { value: { centAmount: 1999, currencyCode: 'USD' }, discounted: { value: { centAmount: 999, currencyCode: 'USD' } } } ] expect(@exportMapping._mapPrices prices).toBe 'USD 1999|999' it 'should map customerGroup and channel on price', -> @exportMapping.channelService.id2key['channel_123'] = 'WAREHOUSE-1' @exportMapping.customerGroupService.id2name['987-xyz'] = 'sales' prices = [ { value: { centAmount: -13, currencyCode: 'EUR' }, customerGroup: { id: '987-xyz' }, channel: { id: 'channel_123' } } ] expect(@exportMapping._mapPrices prices).toBe 'EUR -13 sales#WAREHOUSE-1' it 'should map price with a validFrom field', -> prices = [ { value: { centAmount: -13, currencyCode: 'EUR' }, validFrom: '2001-09-11T14:00:00.000Z' } ] expect(@exportMapping._mapPrices prices).toBe 'EUR -13$2001-09-11T14:00:00.000Z' it 'should map price with a validUntil field', -> prices = [ { value: { centAmount: -15, currencyCode: 'EUR' }, validUntil: '2015-09-11T14:00:00.000Z' } ] expect(@exportMapping._mapPrices prices).toBe 'EUR -15~2015-09-11T14:00:00.000Z' it 'should map price with validFrom and validUntil fields', -> prices = [ { value: { centAmount: -13, currencyCode: 'EUR' }, validFrom: '2001-09-11T14:00:00.000Z', validUntil: '2001-09-12T14:00:00.000Z' } ] expect(@exportMapping._mapPrices prices).toBe 'EUR -13$2001-09-11T14:00:00.000Z~2001-09-12T14:00:00.000Z' describe '#mapImage', -> it 'should map single image', -> images = [ { url: '//example.com/image.jpg' } ] expect(@exportMapping._mapImages images).toBe '//example.com/image.jpg' it 'should map multiple images', -> images = [ { url: '//example.com/image.jpg' } { url: 'https://www.example.com/pic.png' } ] expect(@exportMapping._mapImages images).toBe '//example.com/image.jpg;https://www.example.com/pic.png' describe '#mapAttribute', -> beforeEach -> @exportMapping.typesService = new Types() @productType = id: '123' attributes: [ { name: 'myTextAttrib', type: { name: 'text' } } { name: 'myEnumAttrib', type: { name: 'enum' } } { name: 'myLenumAttrib', type: { name: 'lenum' } } { name: 'myTextSetAttrib', type: { name: 'set', elementType: { name: 'text' } } } { name: 'myEnumSetAttrib', type: { name: 'set', elementType: { name: 'enum' } } } { name: 'myLenumSetAttrib', type: { name: 'set', elementType: { name: 'lenum' } } } ] @exportMapping.typesService.buildMaps [@productType] it 'should map simple attribute', -> attribute = name: 'myTextAttrib' value: 'some text' expect(@exportMapping._mapAttribute attribute, @productType.attributes[0].type).toBe 'some text' it 'should map enum attribute', -> attribute = name: 'myEnumAttrib' value: label: en: 'bla' key: 'PI:KEY:<KEY>END_PIEnum' expect(@exportMapping._mapAttribute attribute, @productType.attributes[1].type).toBe 'myEnum' it 'should map text set attribute', -> attribute = name: 'myTextSetAttrib' value: [ 'x', 'y', 'z' ] expect(@exportMapping._mapAttribute attribute, @productType.attributes[3].type).toBe 'x;y;z' it 'should map enum set attribute', -> attribute = name: 'myEnumSetAttrib' value: [ { label: en: 'bla' key: 'myEnum' } { label: en: 'foo' key: 'myEnum2' } ] expect(@exportMapping._mapAttribute attribute, @productType.attributes[4].type).toBe 'myEnum;myEnum2' describe '#mapVariant', -> it 'should map variant id and sku', -> @exportMapping.header = new Header([CONS.HEADER_VARIANT_ID, CONS.HEADER_SKU]) @exportMapping.header.toIndex() variant = id: '12' sku: 'mySKU' attributes: [] row = @exportMapping._mapVariant(variant) expect(row).toEqual [ '12', 'mySKU' ] it 'should map variant attributes', -> @exportMapping.header = new Header([ 'foo' ]) @exportMapping.header.toIndex() @exportMapping.typesService = new Types() productType = id: '123' attributes: [ { name: 'foo', type: { name: 'text' } } ] @exportMapping.typesService.buildMaps [productType] variant = attributes: [ { name: 'foo', value: 'bar' } ] row = @exportMapping._mapVariant(variant, productType) expect(row).toEqual [ 'bar' ] describe '#mapBaseProduct', -> it 'should map productType (name), product id and categories by externalId', -> @exportMapping.categoryService = new Categories() @exportMapping.categoryService.buildMaps [ { id: '9e6de6ad-cc94-4034-aa9f-276ccb437efd', name: en: 'BrilliantCoeur', slug: en: 'brilliantcoeur', externalId: 'BRI', }, { id: '0afacd76-30d8-431e-aff9-376cd1b4c9e6', name: en: 'Autumn / Winter 2016', slug: en: 'autmn-winter-2016', externalId: '9997', } ] @exportMapping.categoryBy = 'externalId' @exportMapping.header = new Header( [CONS.HEADER_PRODUCT_TYPE, CONS.HEADER_ID, CONS.HEADER_CATEGORIES]) @exportMapping.header.toIndex() product = id: '123' categories: [ { typeId: 'category', id: '9e6de6ad-cc94-4034-aa9f-276ccb437efd' }, { typeId: 'category', id: '0afacd76-30d8-431e-aff9-376cd1b4c9e6' } ], masterVariant: attributes: [] type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ 'myType', '123', 'BRI;9997'] it 'should not map categoryOrderhints when they are not present', -> @exportMapping.categoryService = new Categories() @exportMapping.categoryService.buildMaps [ { id: '9e6de6ad-cc94-4034-aa9f-276ccb437efd', name: en: 'BrilliantCoeur', slug: en: 'brilliantcoeur', externalId: 'BRI', }, { id: '0afacd76-30d8-431e-aff9-376cd1b4c9e6', name: en: 'Autumn / Winter 2016', slug: en: 'autmn-winter-2016', externalId: '9997', } ] @exportMapping.categoryBy = 'externalId' @exportMapping.header = new Header( [CONS.HEADER_PRODUCT_TYPE, CONS.HEADER_ID, CONS.HEADER_CATEGORY_ORDER_HINTS]) @exportMapping.header.toIndex() product = id: '123' categories: [ { typeId: 'category', id: '9e6de6ad-cc94-4034-aa9f-276ccb437efd' }, { typeId: 'category', id: '0afacd76-30d8-431e-aff9-376cd1b4c9e6' } ], masterVariant: attributes: [] type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ 'myType', '123', ''] it 'should map productType (name), product id and categoryOrderhints by externalId', -> @exportMapping.categoryService = new Categories() @exportMapping.categoryService.buildMaps [ { id: '9e6de6ad-cc94-4034-aa9f-276ccb437efd', name: en: 'BrilliantCoeur', slug: en: 'brilliantcoeur', externalId: 'BRI', }, { id: '0afacd76-30d8-431e-aff9-376cd1b4c9e6', name: en: 'Autumn / Winter 2016', slug: en: 'autmn-winter-2016', externalId: '9997', } ] @exportMapping.categoryBy = 'externalId' @exportMapping.header = new Header( [CONS.HEADER_PRODUCT_TYPE, CONS.HEADER_ID, CONS.HEADER_CATEGORY_ORDER_HINTS]) @exportMapping.header.toIndex() product = id: '123' categoryOrderHints: { '9e6de6ad-cc94-4034-aa9f-276ccb437efd': '0.9283' '0afacd76-30d8-431e-aff9-376cd1b4c9e6': '0.3223' }, categories: [], masterVariant: attributes: [] type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ 'myType', '123', '9e6de6ad-cc94-4034-aa9f-276ccb437efd:0.9283;0afacd76-30d8-431e-aff9-376cd1b4c9e6:0.3223'] it 'should map createdAt and lastModifiedAt', -> @exportMapping.header = new Header( [CONS.HEADER_CREATED_AT, CONS.HEADER_LAST_MODIFIED_AT]) @exportMapping.header.toIndex() createdAt = new Date() lastModifiedAt = new Date() product = createdAt: createdAt lastModifiedAt: lastModifiedAt masterVariant: attributes: [] type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ createdAt, lastModifiedAt ] it 'should map tax category name', -> @exportMapping.header = new Header([CONS.HEADER_TAX]) @exportMapping.header.toIndex() @exportMapping.taxService = id2name: tax123: 'myTax' product = id: '123' masterVariant: attributes: [] taxCategory: id: 'tax123' type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ 'myTax' ] it 'should map state key', -> @exportMapping.header = new Header([CONS.HEADER_STATE]) @exportMapping.header.toIndex() @exportMapping.stateService = id2key: state123: 'myState' product = id: '123' masterVariant: attributes: [] state: id: 'state123' type = name: 'myType' id: 'typeId123' row = @exportMapping._mapBaseProduct(product, type) expect(row).toEqual [ 'myState' ] it 'should map localized base attributes', -> @exportMapping.header = new Header(['name.de','slug.it','description.en','searchKeywords.de']) @exportMapping.header.toIndex() product = id: '123' masterVariant: attributes: [] name: de: 'PI:NAME:<NAME>END_PI' en: 'Hello' it: 'Ciao' slug: de: 'hallo' en: 'hello' it: 'ciao' description: de: 'Bla bla' en: 'Foo bar' it: 'Ciao Bella' searchKeywords: de: [ (text: "test") (text: "sample") ] en: [ (text: "drops") (text: "kocher") ] it: [ (text: "bla") (text: "foo") (text: "bar") ] row = @exportMapping._mapBaseProduct(product, {}) expect(row).toEqual [ 'Hallo', 'ciao', 'Foo bar','test;sample'] describe '#mapLenumAndSetOfLenum', -> beforeEach -> @exportMapping.typesService = new Types() @productType = id: '123' attributes: [ { name: 'myLenumAttrib', type: { name: 'lenum' } } { name: 'myLenumSetAttrib', type: { name: 'set', elementType: { name: 'lenum' } } } ] @exportMapping.typesService.buildMaps [@productType] it 'should map key of lenum and set of lenum if no language is given', -> @exportMapping.header = new Header(['myLenumAttrib.en','myLenumAttrib','myLenumSetAttrib.fr-BE','myLenumSetAttrib']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLenumAttrib' value: key: 'myEnum' label: en: 'bla' de: 'blub' }, { name: 'myLenumSetAttrib' value: [ { key: 'drops', label: { "fr-BE": 'le drops', de: 'der drops', en: 'the drops' } }, { "key": "honk", "label": { "en": "the honk", "fr-BE": "le honk", "de-DE": "der honk" } } ] } ] row = @exportMapping._mapVariant(variant, @productType) expect(row).toEqual [ 'bla','myEnum','le drops;le honk','drops;honk'] it 'should map the labels of lenum and set of lenum if language is given', -> @exportMapping.header = new Header(['myLenumAttrib.en','myLenumSetAttrib.fr-BE']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLenumAttrib' value: key: 'myEnum' label: en: 'bla' de: 'blub' }, { name: 'myLenumSetAttrib' value: [ { key: 'drops', label: { "fr-BE": 'le drops', de: 'der drops', en: 'the drops' } }, { "key": "honk", "label": { "en": "the honk", "fr-BE": "le honk", "de-DE": "der honk" } } ] } ] row = @exportMapping._mapVariant(variant, @productType) expect(row).toEqual [ 'bla','le drops;le honk' ] describe '#mapLtextSet', -> beforeEach -> @exportMapping.typesService = new Types() @productType = id: '123' attributes: [ { name: 'myLtextSetAttrib', type: { name: 'set', elementType: { name: 'ltext' } } } ] @exportMapping.typesService.buildMaps [@productType] it 'should map set of ltext', -> @exportMapping.header = new Header(['myLtextSetAttrib.de','myLtextSetAttrib.en']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLtextSetAttrib' value: [ {"en": "foo1", "de": "barA"}, {"en": "foo2", "de": "barB"}, {"de": "barC", "nl": "invisible"} ] } ] row = @exportMapping._mapVariant(variant, @productType) expected = [ 'barA;barB;barC','foo1;foo2' ] expect(row).toEqual expected it 'should return undefined for invalid set of attributes', -> @exportMapping.header = new Header(['myLtextSetAttrib','myLtextSetAttrib.en', 'myLtextSetAttrib.de']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLtextSetAttrib' value: [ {"en": "foo1", "de": "barA"}, {"en": "foo2", "de": "barB"}, {"de": "barC", "nl": "invisible"} ] } ] row = @exportMapping._mapVariant(variant, @productType) expected = [ undefined,'foo1;foo2', 'barA;barB;barC' ] expect(row).toEqual expected it 'should ignore trailing invalid set of attributes', -> @exportMapping.header = new Header(['myLtextSetAttrib.en', 'myLtextSetAttrib.de', 'foo', 'bar']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLtextSetAttrib' value: [ {"en": "foo1", "de": "barA"}, {"en": "foo2", "de": "barB"}, {"de": "barC", "nl": "invisible"} ] } ] row = @exportMapping._mapVariant(variant, @productType) expected = [ 'foo1;foo2', 'barA;barB;barC' ] expect(row).toEqual expected it 'should return undefined for invalid set of attributes that is not trailing', -> @exportMapping.header = new Header(['myLtextSetAttrib.en', 'foo', 'bar', 'myLtextSetAttrib.de']) @exportMapping.header.toIndex() variant = attributes: [ { name: 'myLtextSetAttrib' value: [ {"en": "foo1", "de": "barA"}, {"en": "foo2", "de": "barB"}, {"de": "barC", "nl": "invisible"} ] } ] row = @exportMapping._mapVariant(variant, @productType) expected = [ 'foo1;foo2', undefined, undefined, 'barA;barB;barC' ] expect(row).toEqual expected describe '#createTemplate', -> beforeEach -> @productType = attributes: [] it 'should do nothing if there are no attributes', -> template = @exportMapping.createTemplate @productType expect(_.intersection template, [ CONS.HEADER_PUBLISHED, CONS.HEADER_HAS_STAGED_CHANGES ]).toEqual [ CONS.HEADER_PUBLISHED, CONS.HEADER_HAS_STAGED_CHANGES ] expect(_.intersection template, CONS.BASE_HEADERS).toEqual CONS.BASE_HEADERS expect(_.intersection template, CONS.SPECIAL_HEADERS).toEqual CONS.SPECIAL_HEADERS _.each CONS.BASE_LOCALIZED_HEADERS, (h) -> expect(_.contains template, "#{h}.en").toBe true it 'should get attribute name for all kind of types', -> @productType.attributes.push { name: 'a-enum', type: { name: 'enum' } } @productType.attributes.push { name: 'a-lenum', type: { name: 'lenum' } } @productType.attributes.push { name: 'a-text', type: { name: 'text' } } @productType.attributes.push { name: 'a-number', type: { name: 'number' } } @productType.attributes.push { name: 'a-money', type: { name: 'money' } } @productType.attributes.push { name: 'a-date', type: { name: 'date' } } @productType.attributes.push { name: 'a-time', type: { name: 'time' } } @productType.attributes.push { name: 'a-datetime', type: { name: 'datetime' } } template = @exportMapping.createTemplate @productType expectedHeaders = [ 'a-enum', 'a-lenum', 'a-text', 'a-number', 'a-money', 'a-date', 'a-time', 'a-datetime' ] _.map expectedHeaders, (h) -> expect(_.contains template, h).toBe true it 'should add headers for all languages', -> @productType.attributes.push { name: 'multilang', type: { name: 'ltext' } } template = @exportMapping.createTemplate @productType, [ 'de', 'en', 'it' ] _.each CONS.BASE_LOCALIZED_HEADERS, (h) -> expect(_.contains template, "#{h}.de").toBe true expect(_.contains template, "#{h}.en").toBe true expect(_.contains template, "#{h}.it").toBe true expect(_.contains template, "multilang.de").toBe true expect(_.contains template, "multilang.en").toBe true expect(_.contains template, "multilang.it").toBe true describe '#mapOnlyMasterVariants', -> beforeEach -> @sampleProduct = id: '123' productType: id: 'myType' name: de: 'PI:NAME:<NAME>END_PI' slug: de: 'hallo' description: de: 'Bla bla' masterVariant: id: 1 sku: 'var1' key: 'var1Key' variants: [ { id: 2 sku: 'var2' key: 'var2Key' } ] it 'should map all variants', -> _exportMapping = new ExportMapping( typesService: id2index: myType: 0 ) _exportMapping.header = new Header([CONS.HEADER_VARIANT_ID, CONS.HEADER_SKU]) _exportMapping.header.toIndex() type = name: 'myType' id: 'typeId123' mappedProduct = _exportMapping.mapProduct @sampleProduct, [type] # both variants should be mapped expect(mappedProduct).toEqual [ [ 1, 'var1' ], [ 2, 'var2' ] ] it 'should map only masterVariant', -> _exportMapping = new ExportMapping( onlyMasterVariants: true typesService: id2index: myType: 0 ) _exportMapping.header = new Header([CONS.HEADER_VARIANT_ID, CONS.HEADER_SKU]) _exportMapping.header.toIndex() type = name: 'myType' id: 'typeId123' mappedProduct = _exportMapping.mapProduct @sampleProduct, [type] # only masterVariant should be mapped expect(mappedProduct).toEqual [ [ 1, 'var1' ] ]
[ { "context": "f Meteor.isClient\n Meteor.loginWithPassword 'user1', 'password1', (err, result) ->\n if err th", "end": 261, "score": 0.9845374822616577, "start": 256, "tag": "USERNAME", "value": "user1" }, { "context": "isClient\n Meteor.loginWithPassword 'user1', 'p...
tests/EventsSpec.coffee
aramk/meteor-events
3
moduleName = 'Events' collection = Events.getCollection() userCollection = UserEvents.getCollection() describe moduleName, -> beforeAll (test, waitFor) -> done = waitFor -> Events.config() if Meteor.isClient Meteor.loginWithPassword 'user1', 'password1', (err, result) -> if err then return Logger.error('Failed to log in', err) Logger.info('Logged in') Meteor.subscribe 'events', -> Logger.info('Subscribed') done() else done() it 'exists', -> expect(Events?).to.be.true it 'has docs', -> expect(collection.find().count()).not.to.equal(0) it 'can mark events as read', -> expect(UserEvents.isRead(userId: 'user1', eventId: 'event1')).to.be.true selector = userId: 'user1', eventId: 'event2' expect(UserEvents.isRead(selector)).to.be.false # Events created in the past are ignored when UserEventStats is initialised for a new user. # expect(UserEventStats.get().unreadCount).to.equal(0) if Meteor.isClient docId = UserEvents.read(selector) expect(UserEvents.isRead(selector)).to.be.true # expect(UserEventStats.get().unreadCount).to.equal(0) if Meteor.isClient # Ensure server changes are not synced to the client cause the test to fail. userCollection.remove(docId) expect(UserEvents.isRead(selector)).to.be.false # expect(UserEventStats.get().unreadCount).to.equal(0) if Meteor.isClient if Meteor.isServer describe "#{moduleName} Server", -> it 'can find events by roles', -> cursor = Events.findByRoles('reader') expect(cursor.count()).to.be.above(0) labels = cursor.map (event) -> event.label expect(_.difference(['bar', 'foo3', 'foo4'], labels).length).to.equal(0) cursor = Events.findByRoles('writer') expect(cursor.count()).to.be.above(0) labels = cursor.map (event) -> event.label expect(_.difference(['foo2'], labels).length).to.equal(0) it 'can find events by user IDs', -> cursor = Events.findByUser('user1') expect(cursor.count()).to.be.above(0) labels = cursor.map (event) -> event.label expect(_.difference(['bar', 'foo', 'foo3'], labels).length).to.equal(0) cursor = Events.findByUser('user2') expect(cursor.count()).to.be.above(0) events = cursor.fetch() labels = cursor.map (event) -> event.label expect(_.difference(['bar', 'foo2', 'foo4'], labels).length).to.equal(0) if Meteor.isClient describe "#{moduleName} Client", -> it 'is logged in', -> expect(Meteor.userId()).to.equal('user1') it 'can find events for users', -> cursor = collection.find() expect(cursor.count()).to.equal(3) labels = cursor.map (event) -> event.label expect(_.difference(['bar', 'foo', 'foo3'], labels).length).to.equal(0) it 'has user events', -> cursor = userCollection.find() expect(cursor.count()).to.equal(1) userEvents = cursor.fetch() expect(userEvents[0].eventId).equal('event1') it 'can get read count for events', -> expect(UserEventStats.getCollection().find().count()).to.equal(1) stats = UserEventStats.get() expect(stats.unreadCount).to.equal(1) expect(stats.readAllDate instanceof Date).to.be.true it 'can update read count', (test, waitFor) -> done = waitFor -> expect(UserEventStats.get().unreadCount).to.equal(1) selector = userId: 'user1', eventId: 'event4' expect(UserEvents.isRead(selector)).to.be.false docId = UserEvents.read(selector) expect(UserEvents.isRead(selector)).to.be.true _.delay -> expect(UserEventStats.get().unreadCount).to.equal(0) done() , 1000
110705
moduleName = 'Events' collection = Events.getCollection() userCollection = UserEvents.getCollection() describe moduleName, -> beforeAll (test, waitFor) -> done = waitFor -> Events.config() if Meteor.isClient Meteor.loginWithPassword 'user1', '<PASSWORD>', (err, result) -> if err then return Logger.error('Failed to log in', err) Logger.info('Logged in') Meteor.subscribe 'events', -> Logger.info('Subscribed') done() else done() it 'exists', -> expect(Events?).to.be.true it 'has docs', -> expect(collection.find().count()).not.to.equal(0) it 'can mark events as read', -> expect(UserEvents.isRead(userId: 'user1', eventId: 'event1')).to.be.true selector = userId: 'user1', eventId: 'event2' expect(UserEvents.isRead(selector)).to.be.false # Events created in the past are ignored when UserEventStats is initialised for a new user. # expect(UserEventStats.get().unreadCount).to.equal(0) if Meteor.isClient docId = UserEvents.read(selector) expect(UserEvents.isRead(selector)).to.be.true # expect(UserEventStats.get().unreadCount).to.equal(0) if Meteor.isClient # Ensure server changes are not synced to the client cause the test to fail. userCollection.remove(docId) expect(UserEvents.isRead(selector)).to.be.false # expect(UserEventStats.get().unreadCount).to.equal(0) if Meteor.isClient if Meteor.isServer describe "#{moduleName} Server", -> it 'can find events by roles', -> cursor = Events.findByRoles('reader') expect(cursor.count()).to.be.above(0) labels = cursor.map (event) -> event.label expect(_.difference(['bar', 'foo3', 'foo4'], labels).length).to.equal(0) cursor = Events.findByRoles('writer') expect(cursor.count()).to.be.above(0) labels = cursor.map (event) -> event.label expect(_.difference(['foo2'], labels).length).to.equal(0) it 'can find events by user IDs', -> cursor = Events.findByUser('user1') expect(cursor.count()).to.be.above(0) labels = cursor.map (event) -> event.label expect(_.difference(['bar', 'foo', 'foo3'], labels).length).to.equal(0) cursor = Events.findByUser('user2') expect(cursor.count()).to.be.above(0) events = cursor.fetch() labels = cursor.map (event) -> event.label expect(_.difference(['bar', 'foo2', 'foo4'], labels).length).to.equal(0) if Meteor.isClient describe "#{moduleName} Client", -> it 'is logged in', -> expect(Meteor.userId()).to.equal('user1') it 'can find events for users', -> cursor = collection.find() expect(cursor.count()).to.equal(3) labels = cursor.map (event) -> event.label expect(_.difference(['bar', 'foo', 'foo3'], labels).length).to.equal(0) it 'has user events', -> cursor = userCollection.find() expect(cursor.count()).to.equal(1) userEvents = cursor.fetch() expect(userEvents[0].eventId).equal('event1') it 'can get read count for events', -> expect(UserEventStats.getCollection().find().count()).to.equal(1) stats = UserEventStats.get() expect(stats.unreadCount).to.equal(1) expect(stats.readAllDate instanceof Date).to.be.true it 'can update read count', (test, waitFor) -> done = waitFor -> expect(UserEventStats.get().unreadCount).to.equal(1) selector = userId: 'user1', eventId: 'event4' expect(UserEvents.isRead(selector)).to.be.false docId = UserEvents.read(selector) expect(UserEvents.isRead(selector)).to.be.true _.delay -> expect(UserEventStats.get().unreadCount).to.equal(0) done() , 1000
true
moduleName = 'Events' collection = Events.getCollection() userCollection = UserEvents.getCollection() describe moduleName, -> beforeAll (test, waitFor) -> done = waitFor -> Events.config() if Meteor.isClient Meteor.loginWithPassword 'user1', 'PI:PASSWORD:<PASSWORD>END_PI', (err, result) -> if err then return Logger.error('Failed to log in', err) Logger.info('Logged in') Meteor.subscribe 'events', -> Logger.info('Subscribed') done() else done() it 'exists', -> expect(Events?).to.be.true it 'has docs', -> expect(collection.find().count()).not.to.equal(0) it 'can mark events as read', -> expect(UserEvents.isRead(userId: 'user1', eventId: 'event1')).to.be.true selector = userId: 'user1', eventId: 'event2' expect(UserEvents.isRead(selector)).to.be.false # Events created in the past are ignored when UserEventStats is initialised for a new user. # expect(UserEventStats.get().unreadCount).to.equal(0) if Meteor.isClient docId = UserEvents.read(selector) expect(UserEvents.isRead(selector)).to.be.true # expect(UserEventStats.get().unreadCount).to.equal(0) if Meteor.isClient # Ensure server changes are not synced to the client cause the test to fail. userCollection.remove(docId) expect(UserEvents.isRead(selector)).to.be.false # expect(UserEventStats.get().unreadCount).to.equal(0) if Meteor.isClient if Meteor.isServer describe "#{moduleName} Server", -> it 'can find events by roles', -> cursor = Events.findByRoles('reader') expect(cursor.count()).to.be.above(0) labels = cursor.map (event) -> event.label expect(_.difference(['bar', 'foo3', 'foo4'], labels).length).to.equal(0) cursor = Events.findByRoles('writer') expect(cursor.count()).to.be.above(0) labels = cursor.map (event) -> event.label expect(_.difference(['foo2'], labels).length).to.equal(0) it 'can find events by user IDs', -> cursor = Events.findByUser('user1') expect(cursor.count()).to.be.above(0) labels = cursor.map (event) -> event.label expect(_.difference(['bar', 'foo', 'foo3'], labels).length).to.equal(0) cursor = Events.findByUser('user2') expect(cursor.count()).to.be.above(0) events = cursor.fetch() labels = cursor.map (event) -> event.label expect(_.difference(['bar', 'foo2', 'foo4'], labels).length).to.equal(0) if Meteor.isClient describe "#{moduleName} Client", -> it 'is logged in', -> expect(Meteor.userId()).to.equal('user1') it 'can find events for users', -> cursor = collection.find() expect(cursor.count()).to.equal(3) labels = cursor.map (event) -> event.label expect(_.difference(['bar', 'foo', 'foo3'], labels).length).to.equal(0) it 'has user events', -> cursor = userCollection.find() expect(cursor.count()).to.equal(1) userEvents = cursor.fetch() expect(userEvents[0].eventId).equal('event1') it 'can get read count for events', -> expect(UserEventStats.getCollection().find().count()).to.equal(1) stats = UserEventStats.get() expect(stats.unreadCount).to.equal(1) expect(stats.readAllDate instanceof Date).to.be.true it 'can update read count', (test, waitFor) -> done = waitFor -> expect(UserEventStats.get().unreadCount).to.equal(1) selector = userId: 'user1', eventId: 'event4' expect(UserEvents.isRead(selector)).to.be.false docId = UserEvents.read(selector) expect(UserEvents.isRead(selector)).to.be.true _.delay -> expect(UserEventStats.get().unreadCount).to.equal(0) done() , 1000
[ { "context": "x')\n\njsonData = [\n {\"IsMember\" : true, \"Name\" : \"John\", \"Age\" : 24},\n {\"IsMember\" : false, \"Name\" : \"P", "end": 138, "score": 0.9998469352722168, "start": 134, "tag": "NAME", "value": "John" }, { "context": "n\", \"Age\" : 24},\n {\"IsMember\" : fals...
examples/basic-sheet-via-buffer.coffee
ajflash/icg-json-to-xlsx
0
fs = require('fs') path = require('path') jsonXlsx = require('../lib/icg-json-to-xlsx') jsonData = [ {"IsMember" : true, "Name" : "John", "Age" : 24}, {"IsMember" : false, "Name" : "Paul", "Age" : 44}, {"IsMember" : true, "Name" : "George", "Age" : 12} ] filename = path.join(__dirname, "basic-sheet-via-buffer-output.xlsx") buffer = jsonXlsx.writeBuffer(jsonData) if buffer fs.writeFile filename, buffer, (err)-> console.log filename
108719
fs = require('fs') path = require('path') jsonXlsx = require('../lib/icg-json-to-xlsx') jsonData = [ {"IsMember" : true, "Name" : "<NAME>", "Age" : 24}, {"IsMember" : false, "Name" : "<NAME>", "Age" : 44}, {"IsMember" : true, "Name" : "<NAME>", "Age" : 12} ] filename = path.join(__dirname, "basic-sheet-via-buffer-output.xlsx") buffer = jsonXlsx.writeBuffer(jsonData) if buffer fs.writeFile filename, buffer, (err)-> console.log filename
true
fs = require('fs') path = require('path') jsonXlsx = require('../lib/icg-json-to-xlsx') jsonData = [ {"IsMember" : true, "Name" : "PI:NAME:<NAME>END_PI", "Age" : 24}, {"IsMember" : false, "Name" : "PI:NAME:<NAME>END_PI", "Age" : 44}, {"IsMember" : true, "Name" : "PI:NAME:<NAME>END_PI", "Age" : 12} ] filename = path.join(__dirname, "basic-sheet-via-buffer-output.xlsx") buffer = jsonXlsx.writeBuffer(jsonData) if buffer fs.writeFile filename, buffer, (err)-> console.log filename
[ { "context": "erver(Fixture.app)\n\n Fixture.server.listen 0, '127.0.0.1', ->\n Fixture.baseUrl =\n \"http://#{Fi", "end": 557, "score": 0.9996508359909058, "start": 548, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "->\n Fixture.knex('User').in...
test/index.coffee
petrutoader/bald-knex
6
http = require('http') express = require('express') bodyParser = require('body-parser') chai = require('chai') request = require('request') async = require('async') expect = chai.expect Bald = require('../lib/Resource') ApiTools = require('../lib/ApiTools') chai.config.includeStack = true Fixture = initializeServer: (done) -> Fixture.app = express() Fixture.app.use(bodyParser.json()) Fixture.app.use(bodyParser.urlencoded({ extended: false })) Fixture.server = http.createServer(Fixture.app) Fixture.server.listen 0, '127.0.0.1', -> Fixture.baseUrl = "http://#{Fixture.server.address().address}:#{Fixture.server.address().port}" done() describe 'Bald initialization', -> it 'should throw an exception when initilized without arguments', (done) -> expect((-> new Bald {})).to.throw('Arguments invalid.') done() describe 'Bald resources', -> before -> Fixture.knex = require('knex') client: 'sqlite3' connection: filename: ':memory:' Fixture.knex.schema .createTableIfNotExists 'User', (table) -> table.increments('id').primary() table.string('name') beforeEach (done) -> Fixture.initializeServer -> Fixture.bald = new Bald app: Fixture.app, knex: Fixture.knex Fixture.bald.resource model: 'User' Fixture.bald.resource model: 'MissingTable' done() it 'should throw an exception when a resource is initialized without a model', (done) -> expect(Fixture.bald.resource.bind(Fixture.bald, {})).to.throw('Invalid model.') done() it 'should declare accept custom endpoints', (done) -> data = model: 'User' endpoints: {singular: 'blah', plural: 'blahs'} expect(Fixture.bald.resource.bind(Fixture.bald, data)).to.not.throw(Error) done() it 'should throw an error when declaring invalid middleware', (done) -> data = model: 'User' middleware: '' expect(Fixture.bald.resource.bind(Fixture.bald, data)).to.throw('Invalid middleware array provided.') done() it 'should accept declared middleware', (done) -> data = model: 'User' middleware: 'list': [->] expect(Fixture.bald.resource.bind(Fixture.bald, data)).to.not.throw(Error) done() describe 'REST API', -> describe 'list', -> it 'should list data', (next) -> async.waterfall [ (done) -> Fixture.knex('User').insert(name: 'Alfred').asCallback(done) (data, done) -> requestData = url: "#{Fixture.baseUrl}/api/Users" method: "GET" request requestData, (err, res, body) -> data = JSON.parse body return done(err, data) ], (err, data) -> return next(err) if err? expect(data.data.length).to.eql(1) return next() describe 'read', -> it 'should read data', (done) -> requestData = url: "#{Fixture.baseUrl}/api/User/1" method: "GET" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data.name).to.eql('Alfred') done() describe 'create', -> it 'should create data', (done) -> requestData = url: "#{Fixture.baseUrl}/api/Users" form: name: 'Alfredo' method: "POST" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data.name).to.eql('Alfredo') done() it 'should create correctly transformed data (null value)', (done) -> requestData = url: "#{Fixture.baseUrl}/api/Users" form: name: '$bald$null' method: "POST" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data.name).to.be.null done() describe 'update', -> it 'should update data', (done) -> requestData = url: "#{Fixture.baseUrl}/api/User/1" form: name: 'Lupin' method: "PUT" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data.name).to.eql('Lupin') done() it 'should update data with the correct transformation (null value)', (done) -> requestData = url: "#{Fixture.baseUrl}/api/User/1" form: name: '$bald$null' method: "PUT" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data.name).to.be.null done() describe 'delete', -> it 'should delete data', (done) -> requestData = url: "#{Fixture.baseUrl}/api/User/2" method: "DELETE" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data).to.eql(1) done() describe 'Route error handling', -> describe 'sendResponse()', -> it 'should return an error code when `res` is not provided', (done) -> expect(ApiTools.sendResponse.bind(ApiTools, null)).to.throw('Arguments invalid.') done() it 'should return true when sending a `phy-code`', (done) -> Fixture.app.get '/', (req, res) -> expect(ApiTools.sendResponse(res, 'phy-test', [])).to.eql(true) done() request Fixture.baseUrl it 'should return true when sending an error instance', (done) -> Fixture.app.get '/', (req, res) -> err = new Error 'phy-test' expect(ApiTools.sendResponse(res, err, [])).to.eql(true) done() request Fixture.baseUrl it 'should return true when sending an array as an error', (done) -> Fixture.app.get '/', (req, res) -> err = new Error 'phy-test' expect(ApiTools.sendResponse(res, [{code: 'phy-test'}], false)).to.eql(true) done() request Fixture.baseUrl it 'should return true when sending an array as an error', (done) -> Fixture.app.get '/', (req, res) -> err = new Error 'phy-test' expect(ApiTools.sendResponse(res, [{code: 'phy-test'}], [])).to.eql(true) done() request Fixture.baseUrl describe 'string2phyCode()', -> it 'should return a string if it has a `phy-` suffix', (done) -> expect(typeof ApiTools.string2phyCode.bind(ApiTools, 'phy-test')()).to.eql('string') done() it 'should return null if it doesn\'t have a `phy-` suffix', (done) -> expect(ApiTools.string2phyCode.bind(ApiTools, 'JP Morgan')()).to.eql(null) done() describe 'string2apiError()', -> it 'should return an object with message', (done) -> expect(ApiTools.string2apiError.bind(ApiTools, 'phy-test')().message?).to.eql(true) done() it 'should return an object with code', (done) -> expect(ApiTools.string2apiError.bind(ApiTools, 'phy-test')().code?).to.eql(true) done() describe 'jsError2apiError()', -> it 'should return an object with message', (done) -> err = new Error 'phy-test' expect(ApiTools.jsError2apiError.bind(ApiTools, err)().message?).to.eql(true) done() it 'should return an object with code', (done) -> err = new Error 'phy-test' expect(ApiTools.jsError2apiError.bind(ApiTools, err)().message?).to.eql(true) done() it 'should return an object with extra', (done) -> err = new Error 'phy-test' expect(ApiTools.jsError2apiError.bind(ApiTools, err)().message?).to.eql(true) done() describe 'other2apiError()', -> it 'should return an object with message', (done) -> err = 'an error' expect(ApiTools.other2apiError.bind(ApiTools, err)().message?).to.eql(true) done() it 'should return an object with code', (done) -> err = 'an error' expect(ApiTools.other2apiError.bind(ApiTools, err)().message?).to.eql(true) done() it 'should return an object with extra', (done) -> err = 'an error' expect(ApiTools.other2apiError.bind(ApiTools, err)().message?).to.eql(true) done()
111679
http = require('http') express = require('express') bodyParser = require('body-parser') chai = require('chai') request = require('request') async = require('async') expect = chai.expect Bald = require('../lib/Resource') ApiTools = require('../lib/ApiTools') chai.config.includeStack = true Fixture = initializeServer: (done) -> Fixture.app = express() Fixture.app.use(bodyParser.json()) Fixture.app.use(bodyParser.urlencoded({ extended: false })) Fixture.server = http.createServer(Fixture.app) Fixture.server.listen 0, '127.0.0.1', -> Fixture.baseUrl = "http://#{Fixture.server.address().address}:#{Fixture.server.address().port}" done() describe 'Bald initialization', -> it 'should throw an exception when initilized without arguments', (done) -> expect((-> new Bald {})).to.throw('Arguments invalid.') done() describe 'Bald resources', -> before -> Fixture.knex = require('knex') client: 'sqlite3' connection: filename: ':memory:' Fixture.knex.schema .createTableIfNotExists 'User', (table) -> table.increments('id').primary() table.string('name') beforeEach (done) -> Fixture.initializeServer -> Fixture.bald = new Bald app: Fixture.app, knex: Fixture.knex Fixture.bald.resource model: 'User' Fixture.bald.resource model: 'MissingTable' done() it 'should throw an exception when a resource is initialized without a model', (done) -> expect(Fixture.bald.resource.bind(Fixture.bald, {})).to.throw('Invalid model.') done() it 'should declare accept custom endpoints', (done) -> data = model: 'User' endpoints: {singular: 'blah', plural: 'blahs'} expect(Fixture.bald.resource.bind(Fixture.bald, data)).to.not.throw(Error) done() it 'should throw an error when declaring invalid middleware', (done) -> data = model: 'User' middleware: '' expect(Fixture.bald.resource.bind(Fixture.bald, data)).to.throw('Invalid middleware array provided.') done() it 'should accept declared middleware', (done) -> data = model: 'User' middleware: 'list': [->] expect(Fixture.bald.resource.bind(Fixture.bald, data)).to.not.throw(Error) done() describe 'REST API', -> describe 'list', -> it 'should list data', (next) -> async.waterfall [ (done) -> Fixture.knex('User').insert(name: '<NAME>').asCallback(done) (data, done) -> requestData = url: "#{Fixture.baseUrl}/api/Users" method: "GET" request requestData, (err, res, body) -> data = JSON.parse body return done(err, data) ], (err, data) -> return next(err) if err? expect(data.data.length).to.eql(1) return next() describe 'read', -> it 'should read data', (done) -> requestData = url: "#{Fixture.baseUrl}/api/User/1" method: "GET" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data.name).to.eql('<NAME>') done() describe 'create', -> it 'should create data', (done) -> requestData = url: "#{Fixture.baseUrl}/api/Users" form: name: '<NAME>' method: "POST" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data.name).to.eql('<NAME>') done() it 'should create correctly transformed data (null value)', (done) -> requestData = url: "#{Fixture.baseUrl}/api/Users" form: name: '$bald$null' method: "POST" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data.name).to.be.null done() describe 'update', -> it 'should update data', (done) -> requestData = url: "#{Fixture.baseUrl}/api/User/1" form: name: '<NAME>' method: "PUT" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data.name).to.eql('<NAME>') done() it 'should update data with the correct transformation (null value)', (done) -> requestData = url: "#{Fixture.baseUrl}/api/User/1" form: name: '$bald$null' method: "PUT" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data.name).to.be.null done() describe 'delete', -> it 'should delete data', (done) -> requestData = url: "#{Fixture.baseUrl}/api/User/2" method: "DELETE" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data).to.eql(1) done() describe 'Route error handling', -> describe 'sendResponse()', -> it 'should return an error code when `res` is not provided', (done) -> expect(ApiTools.sendResponse.bind(ApiTools, null)).to.throw('Arguments invalid.') done() it 'should return true when sending a `phy-code`', (done) -> Fixture.app.get '/', (req, res) -> expect(ApiTools.sendResponse(res, 'phy-test', [])).to.eql(true) done() request Fixture.baseUrl it 'should return true when sending an error instance', (done) -> Fixture.app.get '/', (req, res) -> err = new Error 'phy-test' expect(ApiTools.sendResponse(res, err, [])).to.eql(true) done() request Fixture.baseUrl it 'should return true when sending an array as an error', (done) -> Fixture.app.get '/', (req, res) -> err = new Error 'phy-test' expect(ApiTools.sendResponse(res, [{code: 'phy-test'}], false)).to.eql(true) done() request Fixture.baseUrl it 'should return true when sending an array as an error', (done) -> Fixture.app.get '/', (req, res) -> err = new Error 'phy-test' expect(ApiTools.sendResponse(res, [{code: 'phy-test'}], [])).to.eql(true) done() request Fixture.baseUrl describe 'string2phyCode()', -> it 'should return a string if it has a `phy-` suffix', (done) -> expect(typeof ApiTools.string2phyCode.bind(ApiTools, 'phy-test')()).to.eql('string') done() it 'should return null if it doesn\'t have a `phy-` suffix', (done) -> expect(ApiTools.string2phyCode.bind(ApiTools, 'JP Morgan')()).to.eql(null) done() describe 'string2apiError()', -> it 'should return an object with message', (done) -> expect(ApiTools.string2apiError.bind(ApiTools, 'phy-test')().message?).to.eql(true) done() it 'should return an object with code', (done) -> expect(ApiTools.string2apiError.bind(ApiTools, 'phy-test')().code?).to.eql(true) done() describe 'jsError2apiError()', -> it 'should return an object with message', (done) -> err = new Error 'phy-test' expect(ApiTools.jsError2apiError.bind(ApiTools, err)().message?).to.eql(true) done() it 'should return an object with code', (done) -> err = new Error 'phy-test' expect(ApiTools.jsError2apiError.bind(ApiTools, err)().message?).to.eql(true) done() it 'should return an object with extra', (done) -> err = new Error 'phy-test' expect(ApiTools.jsError2apiError.bind(ApiTools, err)().message?).to.eql(true) done() describe 'other2apiError()', -> it 'should return an object with message', (done) -> err = 'an error' expect(ApiTools.other2apiError.bind(ApiTools, err)().message?).to.eql(true) done() it 'should return an object with code', (done) -> err = 'an error' expect(ApiTools.other2apiError.bind(ApiTools, err)().message?).to.eql(true) done() it 'should return an object with extra', (done) -> err = 'an error' expect(ApiTools.other2apiError.bind(ApiTools, err)().message?).to.eql(true) done()
true
http = require('http') express = require('express') bodyParser = require('body-parser') chai = require('chai') request = require('request') async = require('async') expect = chai.expect Bald = require('../lib/Resource') ApiTools = require('../lib/ApiTools') chai.config.includeStack = true Fixture = initializeServer: (done) -> Fixture.app = express() Fixture.app.use(bodyParser.json()) Fixture.app.use(bodyParser.urlencoded({ extended: false })) Fixture.server = http.createServer(Fixture.app) Fixture.server.listen 0, '127.0.0.1', -> Fixture.baseUrl = "http://#{Fixture.server.address().address}:#{Fixture.server.address().port}" done() describe 'Bald initialization', -> it 'should throw an exception when initilized without arguments', (done) -> expect((-> new Bald {})).to.throw('Arguments invalid.') done() describe 'Bald resources', -> before -> Fixture.knex = require('knex') client: 'sqlite3' connection: filename: ':memory:' Fixture.knex.schema .createTableIfNotExists 'User', (table) -> table.increments('id').primary() table.string('name') beforeEach (done) -> Fixture.initializeServer -> Fixture.bald = new Bald app: Fixture.app, knex: Fixture.knex Fixture.bald.resource model: 'User' Fixture.bald.resource model: 'MissingTable' done() it 'should throw an exception when a resource is initialized without a model', (done) -> expect(Fixture.bald.resource.bind(Fixture.bald, {})).to.throw('Invalid model.') done() it 'should declare accept custom endpoints', (done) -> data = model: 'User' endpoints: {singular: 'blah', plural: 'blahs'} expect(Fixture.bald.resource.bind(Fixture.bald, data)).to.not.throw(Error) done() it 'should throw an error when declaring invalid middleware', (done) -> data = model: 'User' middleware: '' expect(Fixture.bald.resource.bind(Fixture.bald, data)).to.throw('Invalid middleware array provided.') done() it 'should accept declared middleware', (done) -> data = model: 'User' middleware: 'list': [->] expect(Fixture.bald.resource.bind(Fixture.bald, data)).to.not.throw(Error) done() describe 'REST API', -> describe 'list', -> it 'should list data', (next) -> async.waterfall [ (done) -> Fixture.knex('User').insert(name: 'PI:NAME:<NAME>END_PI').asCallback(done) (data, done) -> requestData = url: "#{Fixture.baseUrl}/api/Users" method: "GET" request requestData, (err, res, body) -> data = JSON.parse body return done(err, data) ], (err, data) -> return next(err) if err? expect(data.data.length).to.eql(1) return next() describe 'read', -> it 'should read data', (done) -> requestData = url: "#{Fixture.baseUrl}/api/User/1" method: "GET" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data.name).to.eql('PI:NAME:<NAME>END_PI') done() describe 'create', -> it 'should create data', (done) -> requestData = url: "#{Fixture.baseUrl}/api/Users" form: name: 'PI:NAME:<NAME>END_PI' method: "POST" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data.name).to.eql('PI:NAME:<NAME>END_PI') done() it 'should create correctly transformed data (null value)', (done) -> requestData = url: "#{Fixture.baseUrl}/api/Users" form: name: '$bald$null' method: "POST" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data.name).to.be.null done() describe 'update', -> it 'should update data', (done) -> requestData = url: "#{Fixture.baseUrl}/api/User/1" form: name: 'PI:NAME:<NAME>END_PI' method: "PUT" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data.name).to.eql('PI:NAME:<NAME>END_PI') done() it 'should update data with the correct transformation (null value)', (done) -> requestData = url: "#{Fixture.baseUrl}/api/User/1" form: name: '$bald$null' method: "PUT" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data.name).to.be.null done() describe 'delete', -> it 'should delete data', (done) -> requestData = url: "#{Fixture.baseUrl}/api/User/2" method: "DELETE" request requestData, (err, res, body) -> data = JSON.parse body expect(data.data).to.eql(1) done() describe 'Route error handling', -> describe 'sendResponse()', -> it 'should return an error code when `res` is not provided', (done) -> expect(ApiTools.sendResponse.bind(ApiTools, null)).to.throw('Arguments invalid.') done() it 'should return true when sending a `phy-code`', (done) -> Fixture.app.get '/', (req, res) -> expect(ApiTools.sendResponse(res, 'phy-test', [])).to.eql(true) done() request Fixture.baseUrl it 'should return true when sending an error instance', (done) -> Fixture.app.get '/', (req, res) -> err = new Error 'phy-test' expect(ApiTools.sendResponse(res, err, [])).to.eql(true) done() request Fixture.baseUrl it 'should return true when sending an array as an error', (done) -> Fixture.app.get '/', (req, res) -> err = new Error 'phy-test' expect(ApiTools.sendResponse(res, [{code: 'phy-test'}], false)).to.eql(true) done() request Fixture.baseUrl it 'should return true when sending an array as an error', (done) -> Fixture.app.get '/', (req, res) -> err = new Error 'phy-test' expect(ApiTools.sendResponse(res, [{code: 'phy-test'}], [])).to.eql(true) done() request Fixture.baseUrl describe 'string2phyCode()', -> it 'should return a string if it has a `phy-` suffix', (done) -> expect(typeof ApiTools.string2phyCode.bind(ApiTools, 'phy-test')()).to.eql('string') done() it 'should return null if it doesn\'t have a `phy-` suffix', (done) -> expect(ApiTools.string2phyCode.bind(ApiTools, 'JP Morgan')()).to.eql(null) done() describe 'string2apiError()', -> it 'should return an object with message', (done) -> expect(ApiTools.string2apiError.bind(ApiTools, 'phy-test')().message?).to.eql(true) done() it 'should return an object with code', (done) -> expect(ApiTools.string2apiError.bind(ApiTools, 'phy-test')().code?).to.eql(true) done() describe 'jsError2apiError()', -> it 'should return an object with message', (done) -> err = new Error 'phy-test' expect(ApiTools.jsError2apiError.bind(ApiTools, err)().message?).to.eql(true) done() it 'should return an object with code', (done) -> err = new Error 'phy-test' expect(ApiTools.jsError2apiError.bind(ApiTools, err)().message?).to.eql(true) done() it 'should return an object with extra', (done) -> err = new Error 'phy-test' expect(ApiTools.jsError2apiError.bind(ApiTools, err)().message?).to.eql(true) done() describe 'other2apiError()', -> it 'should return an object with message', (done) -> err = 'an error' expect(ApiTools.other2apiError.bind(ApiTools, err)().message?).to.eql(true) done() it 'should return an object with code', (done) -> err = 'an error' expect(ApiTools.other2apiError.bind(ApiTools, err)().message?).to.eql(true) done() it 'should return an object with extra', (done) -> err = 'an error' expect(ApiTools.other2apiError.bind(ApiTools, err)().message?).to.eql(true) done()
[ { "context": "y from Twitter's dev dashboard\n consumerSecret: \"engeqrh2yyeTdE1BkSzwEs7qozHoWjuP6lt1NDFpBBw\" # ditto\n baseURL: 'http://localhost:3000' # You", "end": 507, "score": 0.9996420741081238, "start": 464, "tag": "KEY", "value": "engeqrh2yyeTdE1BkSzwEs7qozHoWjuP6lt1NDFpBBw" },...
examples/example.coffee
mahemoff/express-twitter
3
# GENERAL SETUP express = require 'express' sys = require 'sys' twitter = require '../index.js' app = express.createServer() app.use express.cookieParser() redisStore = require('connect-redis')(express) app.use express.session secret:'randomness' store: new redisStore() maxAge : new Date(Date.now() + 10*365*24*3600*1000) app.use twitter.middleware consumerKey: "3T3sx20TMn8z1uC2EXWMw" # Use your own key from Twitter's dev dashboard consumerSecret: "engeqrh2yyeTdE1BkSzwEs7qozHoWjuP6lt1NDFpBBw" # ditto baseURL: 'http://localhost:3000' # Your app's URL, used for Twitter callback logging: true # If true, uses winston to log. afterLogin: '/hello' # Page user returns to after twitter.com login afterLogout: '/goodbye' # Page user returns to after twitter.com logout app.get '/', (req, res) -> message = if req.session.twitter then "Ahoy #{req.session.twitter.name}. <a href='/sessions/logout'>Logout</a>" else 'Logged out. <a href="/sessions/login">Login Now!</a>' res.send "<h3>express-twitter demo</h3><p>#{message}</p>" app.get '/follow', (req, res) -> twitter.postJSON '/friendships/create/mahemoff.json', '', req, (err,data,response) -> res.send "Welcome to the universe of infinite rant. Info on user returned: #{sys.inspect data}" # CAREFUL! The following path will (should!) send an actual tweet as soon as you visit it! # (Might be open an incognito window and login to that test account.) app.get '/sendAnActualTweet', (req, res) -> twitter.status "Test tweet. Please ignore.", req, (err, data, response) -> res.send "Error returned? #{sys.inspect(err)}" app.get '/hello', (req, res) -> res.send """Welcome #{req.session.twitter.name}.<hr/> <a href="/sessions/debug">debug</a> <a href="/you">about you</a> <a href="/follow">follow @mahemoff</a> <a href="/sessions/logout">logout</a>""" app.get '/goodbye', (req, res) -> res.send 'Our paths crossed but briefly.' app.get '/you', (req, res) -> twitter.getSelf req, (err, you, response) -> res.send "Hello #{you.name}. Twitter says of you:<pre>#{sys.inspect(you)}</pre>" app.get '/friends', (req, res) -> twitter.getFriendIDs req.session.twitter.name, req, (err, friends, response) -> res.send "A few friends then. #{sys.inspect friends}" app.listen 3000
220188
# GENERAL SETUP express = require 'express' sys = require 'sys' twitter = require '../index.js' app = express.createServer() app.use express.cookieParser() redisStore = require('connect-redis')(express) app.use express.session secret:'randomness' store: new redisStore() maxAge : new Date(Date.now() + 10*365*24*3600*1000) app.use twitter.middleware consumerKey: "3T3sx20TMn8z1uC2EXWMw" # Use your own key from Twitter's dev dashboard consumerSecret: "<KEY>" # ditto baseURL: 'http://localhost:3000' # Your app's URL, used for Twitter callback logging: true # If true, uses winston to log. afterLogin: '/hello' # Page user returns to after twitter.com login afterLogout: '/goodbye' # Page user returns to after twitter.com logout app.get '/', (req, res) -> message = if req.session.twitter then "Ahoy #{req.session.twitter.name}. <a href='/sessions/logout'>Logout</a>" else 'Logged out. <a href="/sessions/login">Login Now!</a>' res.send "<h3>express-twitter demo</h3><p>#{message}</p>" app.get '/follow', (req, res) -> twitter.postJSON '/friendships/create/mahemoff.json', '', req, (err,data,response) -> res.send "Welcome to the universe of infinite rant. Info on user returned: #{sys.inspect data}" # CAREFUL! The following path will (should!) send an actual tweet as soon as you visit it! # (Might be open an incognito window and login to that test account.) app.get '/sendAnActualTweet', (req, res) -> twitter.status "Test tweet. Please ignore.", req, (err, data, response) -> res.send "Error returned? #{sys.inspect(err)}" app.get '/hello', (req, res) -> res.send """Welcome #{req.session.twitter.name}.<hr/> <a href="/sessions/debug">debug</a> <a href="/you">about you</a> <a href="/follow">follow @mahemoff</a> <a href="/sessions/logout">logout</a>""" app.get '/goodbye', (req, res) -> res.send 'Our paths crossed but briefly.' app.get '/you', (req, res) -> twitter.getSelf req, (err, you, response) -> res.send "Hello #{you.name}. Twitter says of you:<pre>#{sys.inspect(you)}</pre>" app.get '/friends', (req, res) -> twitter.getFriendIDs req.session.twitter.name, req, (err, friends, response) -> res.send "A few friends then. #{sys.inspect friends}" app.listen 3000
true
# GENERAL SETUP express = require 'express' sys = require 'sys' twitter = require '../index.js' app = express.createServer() app.use express.cookieParser() redisStore = require('connect-redis')(express) app.use express.session secret:'randomness' store: new redisStore() maxAge : new Date(Date.now() + 10*365*24*3600*1000) app.use twitter.middleware consumerKey: "3T3sx20TMn8z1uC2EXWMw" # Use your own key from Twitter's dev dashboard consumerSecret: "PI:KEY:<KEY>END_PI" # ditto baseURL: 'http://localhost:3000' # Your app's URL, used for Twitter callback logging: true # If true, uses winston to log. afterLogin: '/hello' # Page user returns to after twitter.com login afterLogout: '/goodbye' # Page user returns to after twitter.com logout app.get '/', (req, res) -> message = if req.session.twitter then "Ahoy #{req.session.twitter.name}. <a href='/sessions/logout'>Logout</a>" else 'Logged out. <a href="/sessions/login">Login Now!</a>' res.send "<h3>express-twitter demo</h3><p>#{message}</p>" app.get '/follow', (req, res) -> twitter.postJSON '/friendships/create/mahemoff.json', '', req, (err,data,response) -> res.send "Welcome to the universe of infinite rant. Info on user returned: #{sys.inspect data}" # CAREFUL! The following path will (should!) send an actual tweet as soon as you visit it! # (Might be open an incognito window and login to that test account.) app.get '/sendAnActualTweet', (req, res) -> twitter.status "Test tweet. Please ignore.", req, (err, data, response) -> res.send "Error returned? #{sys.inspect(err)}" app.get '/hello', (req, res) -> res.send """Welcome #{req.session.twitter.name}.<hr/> <a href="/sessions/debug">debug</a> <a href="/you">about you</a> <a href="/follow">follow @mahemoff</a> <a href="/sessions/logout">logout</a>""" app.get '/goodbye', (req, res) -> res.send 'Our paths crossed but briefly.' app.get '/you', (req, res) -> twitter.getSelf req, (err, you, response) -> res.send "Hello #{you.name}. Twitter says of you:<pre>#{sys.inspect(you)}</pre>" app.get '/friends', (req, res) -> twitter.getFriendIDs req.session.twitter.name, req, (err, friends, response) -> res.send "A few friends then. #{sys.inspect friends}" app.listen 3000
[ { "context": ")\n data.id.should.be.equal(1)\n data.name = 'Hans'\n backend.expectGET('/users/1').respond -> [20", "end": 1701, "score": 0.9985101819038391, "start": 1697, "tag": "NAME", "value": "Hans" }, { "context": "1}]\n user.get()\n data.name.should.be.equal('Han...
test/resource.test.coffee
kruschid/angular-resource-manager
0
chai.should() describe 'Resource', -> backend = User = undefined # set up module beforeEach(module('kdResourceManager')) # setup dependencies beforeEach inject ($httpBackend, kdResourceManager) -> backend = $httpBackend User = kdResourceManager('users') afterEach -> backend.verifyNoOutstandingExpectation() backend.verifyNoOutstandingRequest() it 'should generate url with base-url', -> user = new User().one(1) user.conf.baseUrl = '/api/v1' url = user.getUrl() url.should.be.equal('/api/v1/users/1') it 'should generate url in context of a relationship', -> group = new User().one(1).rel('groups').one(3) url = group.getFullUrl() url.should.be.equal('/users/1/groups/3') it 'should fetch single resource', -> backend.expectGET('/users/1').respond -> [200] user = new User().one(1).get() backend.flush() it 'should fetch one related resource', -> backend.expectGET('/users/5/groups/1').respond -> [200] usersGroups = new User().one(5).rel('groups').one(1).get() backend.flush() it 'orphan() should delete association with base', -> usersGroups = new User().one(5).rel('groups').one(1) backend.expectGET('/users/5/groups/1').respond -> [200] usersGroups.get() orphan = usersGroups.orphan() backend.expectGET('/groups/1').respond -> [200] orphan.get() usersGroups.should.be.equal(orphan) backend.flush() it 'should store data in same object over several requests', -> backend.expectGET('/users/1').respond -> [200, {id:1}] user = new User().one(1).get() data = user.data backend.flush() data.id.should.be.equal(1) data.name = 'Hans' backend.expectGET('/users/1').respond -> [200, {id:1}] user.get() data.name.should.be.equal('Hans') backend.flush() should.not.exist(data.name) data.id.should.be.equal(1) it 'should create a new resource', -> backend.expectPOST('/users', {name:'Chiquinho'}).respond -> [200, {id:1, name:'Chiquinho'}] user = new User().one() user.data.name = 'Chiquinho' user.save() backend.flush() user.id.should.be.equal(1) user.data.id.should.be.equal(1) it 'should update a resource', -> backend.expectPUT('/users/1', {name:'Peixinho'}).respond -> [200, {id:1, name:'Peixinho'}] user = new User().one(1) user.data.name = 'Peixinho' user.save() backend.flush() user.data.name.should.be.equal('Peixinho') it 'should delete a resource', -> backend.expectDELETE('/users/1').respond -> [200] user = new User().one(1) user.remove() backend.flush() it 'hasRelative should check if resource has a relative in a collection', -> user1 = new User().one(1) user2 = new User().one(2) user1friends = user1.rel('friends') user1friends.data = [ new User().one(1).set({friendId: 2, userId:1}) new User().one(2).set({friendId: 3, userId:1}) ] # user2 is friend of user1 user2.hasRelative(user1friends, 'friendId').should.be.true # user1 is no friend of himself user1.hasRelative(user1friends, 'friendId').should.be.false it 'bare() should clean data and id', -> user = new User().one(1) user.data = name: 'Erdogan' country: 'Turkey' bare = user.bare() should.not.exist(user.id) should.not.exist(user.data.name) should.not.exist(user.data.country) it 'set(object) should replace all properties', -> user = new User().one() user.set name: 'Merkel' user.data.name.should.be.equal('Merkel') user.set email: 'vladimir.putin@mail.ru' user.data.email.should.be.equal('vladimir.putin@mail.ru') should.not.exist(user.data.name) it 'set(resouce) should replace resource data and id', -> user1 = new User().one(1).set name: 'Phobos' email: 'phobos@mars.com' user2 = new User().one(2).set name: 'Moon' user2.set(user1) user2.id.should.be.equal(1) user2.data.name.should.be.equal('Phobos') user2.data.email.should.be.equal('phobos@mars.com') it 'isIn() should check if resource is in a collection', -> collection = new User() collection.data = [ new User().one(1) new User().one(2) ] new User().one(1).isIn(collection).should.be.true new User().one(2).isIn(collection).should.be.true new User().one(3).isIn(collection).should.be.false it 'should allow using promises', -> # backend.expectGET('/users/5').respond -> [200] # users = new User().one(5).get() # users.promise.then -> # users.get().promise # promiseA = users.promise # backend.flush() # backend.expectGET('/users/5').respond -> [200] # users.get().promise.should.be.equal(promiseA) # backend.flush() it 'clean() should clean data' it 'base() should set a new base resource' it 'patch() should replace certain properties' it 'copy() should return a copy of a resource'
3519
chai.should() describe 'Resource', -> backend = User = undefined # set up module beforeEach(module('kdResourceManager')) # setup dependencies beforeEach inject ($httpBackend, kdResourceManager) -> backend = $httpBackend User = kdResourceManager('users') afterEach -> backend.verifyNoOutstandingExpectation() backend.verifyNoOutstandingRequest() it 'should generate url with base-url', -> user = new User().one(1) user.conf.baseUrl = '/api/v1' url = user.getUrl() url.should.be.equal('/api/v1/users/1') it 'should generate url in context of a relationship', -> group = new User().one(1).rel('groups').one(3) url = group.getFullUrl() url.should.be.equal('/users/1/groups/3') it 'should fetch single resource', -> backend.expectGET('/users/1').respond -> [200] user = new User().one(1).get() backend.flush() it 'should fetch one related resource', -> backend.expectGET('/users/5/groups/1').respond -> [200] usersGroups = new User().one(5).rel('groups').one(1).get() backend.flush() it 'orphan() should delete association with base', -> usersGroups = new User().one(5).rel('groups').one(1) backend.expectGET('/users/5/groups/1').respond -> [200] usersGroups.get() orphan = usersGroups.orphan() backend.expectGET('/groups/1').respond -> [200] orphan.get() usersGroups.should.be.equal(orphan) backend.flush() it 'should store data in same object over several requests', -> backend.expectGET('/users/1').respond -> [200, {id:1}] user = new User().one(1).get() data = user.data backend.flush() data.id.should.be.equal(1) data.name = '<NAME>' backend.expectGET('/users/1').respond -> [200, {id:1}] user.get() data.name.should.be.equal('<NAME>') backend.flush() should.not.exist(data.name) data.id.should.be.equal(1) it 'should create a new resource', -> backend.expectPOST('/users', {name:'<NAME>'}).respond -> [200, {id:1, name:'<NAME>'}] user = new User().one() user.data.name = '<NAME>' user.save() backend.flush() user.id.should.be.equal(1) user.data.id.should.be.equal(1) it 'should update a resource', -> backend.expectPUT('/users/1', {name:'<NAME>'}).respond -> [200, {id:1, name:'<NAME>'}] user = new User().one(1) user.data.name = '<NAME>' user.save() backend.flush() user.data.name.should.be.equal('<NAME>') it 'should delete a resource', -> backend.expectDELETE('/users/1').respond -> [200] user = new User().one(1) user.remove() backend.flush() it 'hasRelative should check if resource has a relative in a collection', -> user1 = new User().one(1) user2 = new User().one(2) user1friends = user1.rel('friends') user1friends.data = [ new User().one(1).set({friendId: 2, userId:1}) new User().one(2).set({friendId: 3, userId:1}) ] # user2 is friend of user1 user2.hasRelative(user1friends, 'friendId').should.be.true # user1 is no friend of himself user1.hasRelative(user1friends, 'friendId').should.be.false it 'bare() should clean data and id', -> user = new User().one(1) user.data = name: '<NAME>' country: 'Turkey' bare = user.bare() should.not.exist(user.id) should.not.exist(user.data.name) should.not.exist(user.data.country) it 'set(object) should replace all properties', -> user = new User().one() user.set name: '<NAME>' user.data.name.should.be.equal('<NAME>') user.set email: '<EMAIL>' user.data.email.should.be.equal('<EMAIL>') should.not.exist(user.data.name) it 'set(resouce) should replace resource data and id', -> user1 = new User().one(1).set name: '<NAME>' email: '<EMAIL>' user2 = new User().one(2).set name: '<NAME>' user2.set(user1) user2.id.should.be.equal(1) user2.data.name.should.be.equal('<NAME>') user2.data.email.should.be.equal('<EMAIL>') it 'isIn() should check if resource is in a collection', -> collection = new User() collection.data = [ new User().one(1) new User().one(2) ] new User().one(1).isIn(collection).should.be.true new User().one(2).isIn(collection).should.be.true new User().one(3).isIn(collection).should.be.false it 'should allow using promises', -> # backend.expectGET('/users/5').respond -> [200] # users = new User().one(5).get() # users.promise.then -> # users.get().promise # promiseA = users.promise # backend.flush() # backend.expectGET('/users/5').respond -> [200] # users.get().promise.should.be.equal(promiseA) # backend.flush() it 'clean() should clean data' it 'base() should set a new base resource' it 'patch() should replace certain properties' it 'copy() should return a copy of a resource'
true
chai.should() describe 'Resource', -> backend = User = undefined # set up module beforeEach(module('kdResourceManager')) # setup dependencies beforeEach inject ($httpBackend, kdResourceManager) -> backend = $httpBackend User = kdResourceManager('users') afterEach -> backend.verifyNoOutstandingExpectation() backend.verifyNoOutstandingRequest() it 'should generate url with base-url', -> user = new User().one(1) user.conf.baseUrl = '/api/v1' url = user.getUrl() url.should.be.equal('/api/v1/users/1') it 'should generate url in context of a relationship', -> group = new User().one(1).rel('groups').one(3) url = group.getFullUrl() url.should.be.equal('/users/1/groups/3') it 'should fetch single resource', -> backend.expectGET('/users/1').respond -> [200] user = new User().one(1).get() backend.flush() it 'should fetch one related resource', -> backend.expectGET('/users/5/groups/1').respond -> [200] usersGroups = new User().one(5).rel('groups').one(1).get() backend.flush() it 'orphan() should delete association with base', -> usersGroups = new User().one(5).rel('groups').one(1) backend.expectGET('/users/5/groups/1').respond -> [200] usersGroups.get() orphan = usersGroups.orphan() backend.expectGET('/groups/1').respond -> [200] orphan.get() usersGroups.should.be.equal(orphan) backend.flush() it 'should store data in same object over several requests', -> backend.expectGET('/users/1').respond -> [200, {id:1}] user = new User().one(1).get() data = user.data backend.flush() data.id.should.be.equal(1) data.name = 'PI:NAME:<NAME>END_PI' backend.expectGET('/users/1').respond -> [200, {id:1}] user.get() data.name.should.be.equal('PI:NAME:<NAME>END_PI') backend.flush() should.not.exist(data.name) data.id.should.be.equal(1) it 'should create a new resource', -> backend.expectPOST('/users', {name:'PI:NAME:<NAME>END_PI'}).respond -> [200, {id:1, name:'PI:NAME:<NAME>END_PI'}] user = new User().one() user.data.name = 'PI:NAME:<NAME>END_PI' user.save() backend.flush() user.id.should.be.equal(1) user.data.id.should.be.equal(1) it 'should update a resource', -> backend.expectPUT('/users/1', {name:'PI:NAME:<NAME>END_PI'}).respond -> [200, {id:1, name:'PI:NAME:<NAME>END_PI'}] user = new User().one(1) user.data.name = 'PI:NAME:<NAME>END_PI' user.save() backend.flush() user.data.name.should.be.equal('PI:NAME:<NAME>END_PI') it 'should delete a resource', -> backend.expectDELETE('/users/1').respond -> [200] user = new User().one(1) user.remove() backend.flush() it 'hasRelative should check if resource has a relative in a collection', -> user1 = new User().one(1) user2 = new User().one(2) user1friends = user1.rel('friends') user1friends.data = [ new User().one(1).set({friendId: 2, userId:1}) new User().one(2).set({friendId: 3, userId:1}) ] # user2 is friend of user1 user2.hasRelative(user1friends, 'friendId').should.be.true # user1 is no friend of himself user1.hasRelative(user1friends, 'friendId').should.be.false it 'bare() should clean data and id', -> user = new User().one(1) user.data = name: 'PI:NAME:<NAME>END_PI' country: 'Turkey' bare = user.bare() should.not.exist(user.id) should.not.exist(user.data.name) should.not.exist(user.data.country) it 'set(object) should replace all properties', -> user = new User().one() user.set name: 'PI:NAME:<NAME>END_PI' user.data.name.should.be.equal('PI:NAME:<NAME>END_PI') user.set email: 'PI:EMAIL:<EMAIL>END_PI' user.data.email.should.be.equal('PI:EMAIL:<EMAIL>END_PI') should.not.exist(user.data.name) it 'set(resouce) should replace resource data and id', -> user1 = new User().one(1).set name: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' user2 = new User().one(2).set name: 'PI:NAME:<NAME>END_PI' user2.set(user1) user2.id.should.be.equal(1) user2.data.name.should.be.equal('PI:NAME:<NAME>END_PI') user2.data.email.should.be.equal('PI:EMAIL:<EMAIL>END_PI') it 'isIn() should check if resource is in a collection', -> collection = new User() collection.data = [ new User().one(1) new User().one(2) ] new User().one(1).isIn(collection).should.be.true new User().one(2).isIn(collection).should.be.true new User().one(3).isIn(collection).should.be.false it 'should allow using promises', -> # backend.expectGET('/users/5').respond -> [200] # users = new User().one(5).get() # users.promise.then -> # users.get().promise # promiseA = users.promise # backend.flush() # backend.expectGET('/users/5').respond -> [200] # users.get().promise.should.be.equal(promiseA) # backend.flush() it 'clean() should clean data' it 'base() should set a new base resource' it 'patch() should replace certain properties' it 'copy() should return a copy of a resource'
[ { "context": "s.\n# See the Ampify UNLICENSE file for details.\n\n# Naaga\n# =====\n\nif exports?\n sys = require('sys')\n ", "end": 103, "score": 0.6490932703018188, "start": 98, "tag": "NAME", "value": "Naaga" }, { "context": "unction uses a novel approach put forward by sbp (...
src/js/naaga.coffee
trojanspike/ampify
1
# Public Domain (-) 2010-2011 The Ampify Authors. # See the Ampify UNLICENSE file for details. # Naaga # ===== if exports? sys = require('sys') ucd = require('./ucd') Categories = ucd.Categories CategoryRanges = ucd.CategoryRanges NumberOfCategoryRanges = CategoryRanges.length CategoryNames = ucd.CategoryNames Cc = ucd.Cc Cf = ucd.Cf Co = ucd.Co Cs = ucd.Cs Ll = ucd.Ll Lm = ucd.Lm Lo = ucd.Lo Lt = ucd.Lt Lu = ucd.Lu Mc = ucd.Mc Me = ucd.Me Mn = ucd.Mn Nd = ucd.Nd Nl = ucd.Nl No = ucd.No Pc = ucd.Pc Pd = ucd.Pd Pe = ucd.Pe Pf = ucd.Pf Pi = ucd.Pi Po = ucd.Po Ps = ucd.Ps Sc = ucd.Sc Sk = ucd.Sk Sm = ucd.Sm So = ucd.So Zl = ucd.Zl Zp = ucd.Zp Zs = ucd.Zs CasedLetters = ucd.CasedLetters Letters = ucd.Letters Marks = ucd.Marks Numbers = ucd.Numbers Others = ucd.Others Punctuations = ucd.Punctuations Separators = ucd.Separators Symbols = ucd.Symbols Unknown = ucd.Unknown Ascii = 0x80 HighSurrogateStart = 0xD800 HighSurrogateEnd = 0xD8FF LowSurrogateStart = 0xDC00 LowSurrogateEnd = 0xDFFF MaxCodepoint = 0x10FFFF ReplacementChar = 0xFFFD # Tokenisation # ------------ # # The ``tokenise`` function uses a novel approach put forward by sbp (Sean B. # Palmer). It splits the given ``source`` into tokens of distinct categories # as specified in Unicode 5.2. # # It returns a sequence of ``[category, ascii_flag, codepoints, string]`` # tokens: # # * The ``category`` points to a constant representing the unicode category. # # * The ``ascii_flag`` indicates whether the segment is comprised of only ASCII # characters. # # * The ``codepoints`` are the unicode codepoints for use by any normalisation # function. # # * The ``string`` is the segment of the source for the current token. tokenise = (source) -> tokens = [] idxAscii = true idxCategory = -1 idxList = [] idxStart = 0 HighSurrogate = 0 for i in [0...source.length] # Get the UTF-16 code unit and convert it to a Unicode Codepoint. codepoint = source.charCodeAt i ascii = false # Deal with surrogate pairs. if HighSurrogate isnt 0 if LowSurrogateStart <= codepoint <= LowSurrogateEnd codepoint = (HighSurrogate - HighSurrogateStart) * 1024 + 65536 + (codepoint - LowSurrogateStart) else # Replace a malformed surrogate pair with the Unicode # Replacement Character. codepoint = ReplacementChar HighSurrogate = 0 else if HighSurrogateStart <= codepoint <= HighSurrogateEnd HighSurrogate = codepoint continue # Handle the common case of ASCII before doing a check for the worst # case. else if codepoint < Ascii ascii = true # Do a sanity check to ensure that the codepoint is not outside the # Unicode Character Set. If so, replace it with the Unicode Replacement # Character. else if codepoint >= MaxCodepoint codepoint = ReplacementChar category = Categories[codepoint] if typeof category is "undefined" for range in CategoryRanges if range[0] <= codepoint <= range[1] category = range[2] break if typeof category is "undefined" category = Unknown if category is idxCategory idxAscii = idxAscii and ascii idxList.push codepoint else tokens.push [idxCategory, idxCategory, idxList, source[idxStart...i]] idxAscii = ascii idxCategory = category idxList = [codepoint] idxStart = i tokens.push [idxCategory, idxCategory, idxList, source[idxStart...i]] return tokens parse = -> hasProp = Object.hasOwnProperty evaluate = -> compile = -> printTokens = (tokens) -> for token in tokens sys.puts(JSON.stringify([CategoryNames[token[0]], token[1], token[3]])) return # // Utility Functions # // ----------------- # // # function timeit(n, func) { # var args, # start, # stop, # i; # args = Array.prototype.slice.call(arguments, 2, arguments.length); # start = new Date().getTime(); # for (i = 0; i < n; i++) { # func.apply(func, args); # } # stop = new Date().getTime() - start; # sys.puts(stop); # return stop; # } # function bench(duration) { # var args, # func, # i = 0, # name = "unknown function", # start, # stop, # total = 0; # args = Array.prototype.slice.call(arguments, 1, arguments.length); # if (typeof duration === 'string') { # name = duration; # duration = args[0]; # args = args.slice(1, args.length); # } # if (typeof duration === 'number') { # func = args.shift(); # } else { # func = duration; # duration = 1; # } # sys.puts("benching <" + name + "> for " + duration + "s:\n"); # duration *= 1000; # while (true) { # start = new Date().getTime(); # func.apply(func, args); # total = total + (new Date().getTime() - start); # if (total > duration) { # break; # } # i++; # } # sys.puts(" " + (total / 1000) + "\t" + i + " runs\n"); # return total; # } root = exports ? this root.tokenise = tokenise
156431
# Public Domain (-) 2010-2011 The Ampify Authors. # See the Ampify UNLICENSE file for details. # <NAME> # ===== if exports? sys = require('sys') ucd = require('./ucd') Categories = ucd.Categories CategoryRanges = ucd.CategoryRanges NumberOfCategoryRanges = CategoryRanges.length CategoryNames = ucd.CategoryNames Cc = ucd.Cc Cf = ucd.Cf Co = ucd.Co Cs = ucd.Cs Ll = ucd.Ll Lm = ucd.Lm Lo = ucd.Lo Lt = ucd.Lt Lu = ucd.Lu Mc = ucd.Mc Me = ucd.Me Mn = ucd.Mn Nd = ucd.Nd Nl = ucd.Nl No = ucd.No Pc = ucd.Pc Pd = ucd.Pd Pe = ucd.Pe Pf = ucd.Pf Pi = ucd.Pi Po = ucd.Po Ps = ucd.Ps Sc = ucd.Sc Sk = ucd.Sk Sm = ucd.Sm So = ucd.So Zl = ucd.Zl Zp = ucd.Zp Zs = ucd.Zs CasedLetters = ucd.CasedLetters Letters = ucd.Letters Marks = ucd.Marks Numbers = ucd.Numbers Others = ucd.Others Punctuations = ucd.Punctuations Separators = ucd.Separators Symbols = ucd.Symbols Unknown = ucd.Unknown Ascii = 0x80 HighSurrogateStart = 0xD800 HighSurrogateEnd = 0xD8FF LowSurrogateStart = 0xDC00 LowSurrogateEnd = 0xDFFF MaxCodepoint = 0x10FFFF ReplacementChar = 0xFFFD # Tokenisation # ------------ # # The ``tokenise`` function uses a novel approach put forward by sbp (<NAME>. # <NAME>). It splits the given ``source`` into tokens of distinct categories # as specified in Unicode 5.2. # # It returns a sequence of ``[category, ascii_flag, codepoints, string]`` # tokens: # # * The ``category`` points to a constant representing the unicode category. # # * The ``ascii_flag`` indicates whether the segment is comprised of only ASCII # characters. # # * The ``codepoints`` are the unicode codepoints for use by any normalisation # function. # # * The ``string`` is the segment of the source for the current token. tokenise = (source) -> tokens = [] idxAscii = true idxCategory = -1 idxList = [] idxStart = 0 HighSurrogate = 0 for i in [0...source.length] # Get the UTF-16 code unit and convert it to a Unicode Codepoint. codepoint = source.charCodeAt i ascii = false # Deal with surrogate pairs. if HighSurrogate isnt 0 if LowSurrogateStart <= codepoint <= LowSurrogateEnd codepoint = (HighSurrogate - HighSurrogateStart) * 1024 + 65536 + (codepoint - LowSurrogateStart) else # Replace a malformed surrogate pair with the Unicode # Replacement Character. codepoint = ReplacementChar HighSurrogate = 0 else if HighSurrogateStart <= codepoint <= HighSurrogateEnd HighSurrogate = codepoint continue # Handle the common case of ASCII before doing a check for the worst # case. else if codepoint < Ascii ascii = true # Do a sanity check to ensure that the codepoint is not outside the # Unicode Character Set. If so, replace it with the Unicode Replacement # Character. else if codepoint >= MaxCodepoint codepoint = ReplacementChar category = Categories[codepoint] if typeof category is "undefined" for range in CategoryRanges if range[0] <= codepoint <= range[1] category = range[2] break if typeof category is "undefined" category = Unknown if category is idxCategory idxAscii = idxAscii and ascii idxList.push codepoint else tokens.push [idxCategory, idxCategory, idxList, source[idxStart...i]] idxAscii = ascii idxCategory = category idxList = [codepoint] idxStart = i tokens.push [idxCategory, idxCategory, idxList, source[idxStart...i]] return tokens parse = -> hasProp = Object.hasOwnProperty evaluate = -> compile = -> printTokens = (tokens) -> for token in tokens sys.puts(JSON.stringify([CategoryNames[token[0]], token[1], token[3]])) return # // Utility Functions # // ----------------- # // # function timeit(n, func) { # var args, # start, # stop, # i; # args = Array.prototype.slice.call(arguments, 2, arguments.length); # start = new Date().getTime(); # for (i = 0; i < n; i++) { # func.apply(func, args); # } # stop = new Date().getTime() - start; # sys.puts(stop); # return stop; # } # function bench(duration) { # var args, # func, # i = 0, # name = "unknown function", # start, # stop, # total = 0; # args = Array.prototype.slice.call(arguments, 1, arguments.length); # if (typeof duration === 'string') { # name = duration; # duration = args[0]; # args = args.slice(1, args.length); # } # if (typeof duration === 'number') { # func = args.shift(); # } else { # func = duration; # duration = 1; # } # sys.puts("benching <" + name + "> for " + duration + "s:\n"); # duration *= 1000; # while (true) { # start = new Date().getTime(); # func.apply(func, args); # total = total + (new Date().getTime() - start); # if (total > duration) { # break; # } # i++; # } # sys.puts(" " + (total / 1000) + "\t" + i + " runs\n"); # return total; # } root = exports ? this root.tokenise = tokenise
true
# Public Domain (-) 2010-2011 The Ampify Authors. # See the Ampify UNLICENSE file for details. # PI:NAME:<NAME>END_PI # ===== if exports? sys = require('sys') ucd = require('./ucd') Categories = ucd.Categories CategoryRanges = ucd.CategoryRanges NumberOfCategoryRanges = CategoryRanges.length CategoryNames = ucd.CategoryNames Cc = ucd.Cc Cf = ucd.Cf Co = ucd.Co Cs = ucd.Cs Ll = ucd.Ll Lm = ucd.Lm Lo = ucd.Lo Lt = ucd.Lt Lu = ucd.Lu Mc = ucd.Mc Me = ucd.Me Mn = ucd.Mn Nd = ucd.Nd Nl = ucd.Nl No = ucd.No Pc = ucd.Pc Pd = ucd.Pd Pe = ucd.Pe Pf = ucd.Pf Pi = ucd.Pi Po = ucd.Po Ps = ucd.Ps Sc = ucd.Sc Sk = ucd.Sk Sm = ucd.Sm So = ucd.So Zl = ucd.Zl Zp = ucd.Zp Zs = ucd.Zs CasedLetters = ucd.CasedLetters Letters = ucd.Letters Marks = ucd.Marks Numbers = ucd.Numbers Others = ucd.Others Punctuations = ucd.Punctuations Separators = ucd.Separators Symbols = ucd.Symbols Unknown = ucd.Unknown Ascii = 0x80 HighSurrogateStart = 0xD800 HighSurrogateEnd = 0xD8FF LowSurrogateStart = 0xDC00 LowSurrogateEnd = 0xDFFF MaxCodepoint = 0x10FFFF ReplacementChar = 0xFFFD # Tokenisation # ------------ # # The ``tokenise`` function uses a novel approach put forward by sbp (PI:NAME:<NAME>END_PI. # PI:NAME:<NAME>END_PI). It splits the given ``source`` into tokens of distinct categories # as specified in Unicode 5.2. # # It returns a sequence of ``[category, ascii_flag, codepoints, string]`` # tokens: # # * The ``category`` points to a constant representing the unicode category. # # * The ``ascii_flag`` indicates whether the segment is comprised of only ASCII # characters. # # * The ``codepoints`` are the unicode codepoints for use by any normalisation # function. # # * The ``string`` is the segment of the source for the current token. tokenise = (source) -> tokens = [] idxAscii = true idxCategory = -1 idxList = [] idxStart = 0 HighSurrogate = 0 for i in [0...source.length] # Get the UTF-16 code unit and convert it to a Unicode Codepoint. codepoint = source.charCodeAt i ascii = false # Deal with surrogate pairs. if HighSurrogate isnt 0 if LowSurrogateStart <= codepoint <= LowSurrogateEnd codepoint = (HighSurrogate - HighSurrogateStart) * 1024 + 65536 + (codepoint - LowSurrogateStart) else # Replace a malformed surrogate pair with the Unicode # Replacement Character. codepoint = ReplacementChar HighSurrogate = 0 else if HighSurrogateStart <= codepoint <= HighSurrogateEnd HighSurrogate = codepoint continue # Handle the common case of ASCII before doing a check for the worst # case. else if codepoint < Ascii ascii = true # Do a sanity check to ensure that the codepoint is not outside the # Unicode Character Set. If so, replace it with the Unicode Replacement # Character. else if codepoint >= MaxCodepoint codepoint = ReplacementChar category = Categories[codepoint] if typeof category is "undefined" for range in CategoryRanges if range[0] <= codepoint <= range[1] category = range[2] break if typeof category is "undefined" category = Unknown if category is idxCategory idxAscii = idxAscii and ascii idxList.push codepoint else tokens.push [idxCategory, idxCategory, idxList, source[idxStart...i]] idxAscii = ascii idxCategory = category idxList = [codepoint] idxStart = i tokens.push [idxCategory, idxCategory, idxList, source[idxStart...i]] return tokens parse = -> hasProp = Object.hasOwnProperty evaluate = -> compile = -> printTokens = (tokens) -> for token in tokens sys.puts(JSON.stringify([CategoryNames[token[0]], token[1], token[3]])) return # // Utility Functions # // ----------------- # // # function timeit(n, func) { # var args, # start, # stop, # i; # args = Array.prototype.slice.call(arguments, 2, arguments.length); # start = new Date().getTime(); # for (i = 0; i < n; i++) { # func.apply(func, args); # } # stop = new Date().getTime() - start; # sys.puts(stop); # return stop; # } # function bench(duration) { # var args, # func, # i = 0, # name = "unknown function", # start, # stop, # total = 0; # args = Array.prototype.slice.call(arguments, 1, arguments.length); # if (typeof duration === 'string') { # name = duration; # duration = args[0]; # args = args.slice(1, args.length); # } # if (typeof duration === 'number') { # func = args.shift(); # } else { # func = duration; # duration = 1; # } # sys.puts("benching <" + name + "> for " + duration + "s:\n"); # duration *= 1000; # while (true) { # start = new Date().getTime(); # func.apply(func, args); # total = total + (new Date().getTime() - start); # if (total > duration) { # break; # } # i++; # } # sys.puts(" " + (total / 1000) + "\t" + i + " runs\n"); # return total; # } root = exports ? this root.tokenise = tokenise
[ { "context": " obj[Utils.decode(part)] = \"\"\n else\n key = Utils.decode(part.slice(0, pos))\n val = Utils.decode(part", "end": 586, "score": 0.9355160593986511, "start": 574, "tag": "KEY", "value": "Utils.decode" } ]
deps/npm/node_modules/request/node_modules/qs/lib/parse.coffee
lxe/io.coffee
0
# Load modules Utils = require("./utils") # Declare internals internals = delimiter: "&" depth: 5 arrayLimit: 20 parametersLimit: 1000 internals.parseValues = (str, delimiter) -> delimiter = (if typeof delimiter is "string" then delimiter else internals.delimiter) obj = {} parts = str.split(delimiter, internals.parametersLimit) i = 0 il = parts.length while i < il part = parts[i] pos = (if part.indexOf("]=") is -1 then part.indexOf("=") else part.indexOf("]=") + 1) if pos is -1 obj[Utils.decode(part)] = "" else key = Utils.decode(part.slice(0, pos)) val = Utils.decode(part.slice(pos + 1)) unless obj[key] obj[key] = val else obj[key] = [].concat(obj[key]).concat(val) ++i obj internals.parseObject = (chain, val) -> return val unless chain.length root = chain.shift() obj = {} if root is "[]" obj = [] obj = obj.concat(internals.parseObject(chain, val)) else cleanRoot = (if root[0] is "[" and root[root.length - 1] is "]" then root.slice(1, root.length - 1) else root) index = parseInt(cleanRoot, 10) if not isNaN(index) and root isnt cleanRoot and index <= internals.arrayLimit obj = [] obj[index] = internals.parseObject(chain, val) else obj[cleanRoot] = internals.parseObject(chain, val) obj internals.parseKeys = (key, val, depth) -> return unless key # The regex chunks parent = /^([^\[\]]*)/ child = /(\[[^\[\]]*\])/g # Get the parent segment = parent.exec(key) # Don't allow them to overwrite object prototype properties return if Object::hasOwnProperty(segment[1]) # Stash the parent if it exists keys = [] keys.push segment[1] if segment[1] # Loop through children appending to the array until we hit depth i = 0 while (segment = child.exec(key)) isnt null and i < depth ++i keys.push segment[1] unless Object::hasOwnProperty(segment[1].replace(/\[|\]/g, "")) # If there's a remainder, just add whatever is left keys.push "[" + key.slice(segment.index) + "]" if segment internals.parseObject keys, val module.exports = (str, depth, delimiter) -> return {} if str is "" or str is null or typeof str is "undefined" if typeof depth isnt "number" delimiter = depth depth = internals.depth tempObj = (if typeof str is "string" then internals.parseValues(str, delimiter) else Utils.clone(str)) obj = {} # Iterate over the keys and setup the new object # for key of tempObj if tempObj.hasOwnProperty(key) newObj = internals.parseKeys(key, tempObj[key], depth) obj = Utils.merge(obj, newObj) Utils.compact obj
83132
# Load modules Utils = require("./utils") # Declare internals internals = delimiter: "&" depth: 5 arrayLimit: 20 parametersLimit: 1000 internals.parseValues = (str, delimiter) -> delimiter = (if typeof delimiter is "string" then delimiter else internals.delimiter) obj = {} parts = str.split(delimiter, internals.parametersLimit) i = 0 il = parts.length while i < il part = parts[i] pos = (if part.indexOf("]=") is -1 then part.indexOf("=") else part.indexOf("]=") + 1) if pos is -1 obj[Utils.decode(part)] = "" else key = <KEY>(part.slice(0, pos)) val = Utils.decode(part.slice(pos + 1)) unless obj[key] obj[key] = val else obj[key] = [].concat(obj[key]).concat(val) ++i obj internals.parseObject = (chain, val) -> return val unless chain.length root = chain.shift() obj = {} if root is "[]" obj = [] obj = obj.concat(internals.parseObject(chain, val)) else cleanRoot = (if root[0] is "[" and root[root.length - 1] is "]" then root.slice(1, root.length - 1) else root) index = parseInt(cleanRoot, 10) if not isNaN(index) and root isnt cleanRoot and index <= internals.arrayLimit obj = [] obj[index] = internals.parseObject(chain, val) else obj[cleanRoot] = internals.parseObject(chain, val) obj internals.parseKeys = (key, val, depth) -> return unless key # The regex chunks parent = /^([^\[\]]*)/ child = /(\[[^\[\]]*\])/g # Get the parent segment = parent.exec(key) # Don't allow them to overwrite object prototype properties return if Object::hasOwnProperty(segment[1]) # Stash the parent if it exists keys = [] keys.push segment[1] if segment[1] # Loop through children appending to the array until we hit depth i = 0 while (segment = child.exec(key)) isnt null and i < depth ++i keys.push segment[1] unless Object::hasOwnProperty(segment[1].replace(/\[|\]/g, "")) # If there's a remainder, just add whatever is left keys.push "[" + key.slice(segment.index) + "]" if segment internals.parseObject keys, val module.exports = (str, depth, delimiter) -> return {} if str is "" or str is null or typeof str is "undefined" if typeof depth isnt "number" delimiter = depth depth = internals.depth tempObj = (if typeof str is "string" then internals.parseValues(str, delimiter) else Utils.clone(str)) obj = {} # Iterate over the keys and setup the new object # for key of tempObj if tempObj.hasOwnProperty(key) newObj = internals.parseKeys(key, tempObj[key], depth) obj = Utils.merge(obj, newObj) Utils.compact obj
true
# Load modules Utils = require("./utils") # Declare internals internals = delimiter: "&" depth: 5 arrayLimit: 20 parametersLimit: 1000 internals.parseValues = (str, delimiter) -> delimiter = (if typeof delimiter is "string" then delimiter else internals.delimiter) obj = {} parts = str.split(delimiter, internals.parametersLimit) i = 0 il = parts.length while i < il part = parts[i] pos = (if part.indexOf("]=") is -1 then part.indexOf("=") else part.indexOf("]=") + 1) if pos is -1 obj[Utils.decode(part)] = "" else key = PI:KEY:<KEY>END_PI(part.slice(0, pos)) val = Utils.decode(part.slice(pos + 1)) unless obj[key] obj[key] = val else obj[key] = [].concat(obj[key]).concat(val) ++i obj internals.parseObject = (chain, val) -> return val unless chain.length root = chain.shift() obj = {} if root is "[]" obj = [] obj = obj.concat(internals.parseObject(chain, val)) else cleanRoot = (if root[0] is "[" and root[root.length - 1] is "]" then root.slice(1, root.length - 1) else root) index = parseInt(cleanRoot, 10) if not isNaN(index) and root isnt cleanRoot and index <= internals.arrayLimit obj = [] obj[index] = internals.parseObject(chain, val) else obj[cleanRoot] = internals.parseObject(chain, val) obj internals.parseKeys = (key, val, depth) -> return unless key # The regex chunks parent = /^([^\[\]]*)/ child = /(\[[^\[\]]*\])/g # Get the parent segment = parent.exec(key) # Don't allow them to overwrite object prototype properties return if Object::hasOwnProperty(segment[1]) # Stash the parent if it exists keys = [] keys.push segment[1] if segment[1] # Loop through children appending to the array until we hit depth i = 0 while (segment = child.exec(key)) isnt null and i < depth ++i keys.push segment[1] unless Object::hasOwnProperty(segment[1].replace(/\[|\]/g, "")) # If there's a remainder, just add whatever is left keys.push "[" + key.slice(segment.index) + "]" if segment internals.parseObject keys, val module.exports = (str, depth, delimiter) -> return {} if str is "" or str is null or typeof str is "undefined" if typeof depth isnt "number" delimiter = depth depth = internals.depth tempObj = (if typeof str is "string" then internals.parseValues(str, delimiter) else Utils.clone(str)) obj = {} # Iterate over the keys and setup the new object # for key of tempObj if tempObj.hasOwnProperty(key) newObj = internals.parseKeys(key, tempObj[key], depth) obj = Utils.merge(obj, newObj) Utils.compact obj
[ { "context": " \"[data-action=forgot-username]\"\n password: \"[data-action=forgot-password]\"\n\n # Now that you've specified child elements in ", "end": 727, "score": 0.9896786212921143, "start": 698, "tag": "PASSWORD", "value": "\"[data-action=forgot-password" }, { "contex...
examples/coffeescript/example.coffee
willurd/backbone.unclassified.js
4
# Here's an example of Backbone Unclassified in action. Most of # this is just normal Backbone code. class FormView extends Backbone.View el: "#login-form" # This is where you specify UI elements, relative to the main view # element. Once the view element has been set, the string selectors # will be replaced with jQuery instances (or Zepto, or whatever else # you're using). ui: items: ".form-item" labels: "label" inputs: "input" username: "input[name=username]" password: "input[type=password]" remember: "[data-bind=remember]" submit: "button[type=submit]" button: forgot: username: "[data-action=forgot-username]" password: "[data-action=forgot-password]" # Now that you've specified child elements in the `ui` object, you # can reference them by name in place of selectors in the events # object. You can still use selectors here if you really want to (as # long as that selector doesn't match one of your child element's # names), but that would just be weird... events: "submit": "submit" "click button.forgot.username": "forgotUsername" "click button.forgot.password": "forgotPassword" "click labels": "labelClick" "change remember": "rememberChange" initialize: -> # You can even use your child elements using plain old JavaScript, # as early as in your `initialize` function. @ui.username.val "user" @ui.password.val "secret!" @ui.remember.attr "checked", true render: -> @ui.username.focus() submit: (e) => e.preventDefault() forgotUsername: -> alert "An email with your username has been sent." false forgotPassword: -> alert "An email with your password in plain text has been sent. Trust us, we're professionals." false labelClick: (e) => label = $(e.target) el = @ui[label.attr("for")] el.focus() rememberChange: (e) => console.log "remember field changed" view = new FormView() view.render()
124453
# Here's an example of Backbone Unclassified in action. Most of # this is just normal Backbone code. class FormView extends Backbone.View el: "#login-form" # This is where you specify UI elements, relative to the main view # element. Once the view element has been set, the string selectors # will be replaced with jQuery instances (or Zepto, or whatever else # you're using). ui: items: ".form-item" labels: "label" inputs: "input" username: "input[name=username]" password: "input[type=password]" remember: "[data-bind=remember]" submit: "button[type=submit]" button: forgot: username: "[data-action=forgot-username]" password: <PASSWORD>]" # Now that you've specified child elements in the `ui` object, you # can reference them by name in place of selectors in the events # object. You can still use selectors here if you really want to (as # long as that selector doesn't match one of your child element's # names), but that would just be weird... events: "submit": "submit" "click button.forgot.username": "forgotUsername" "click button.forgot.password": "<PASSWORD>" "click labels": "labelClick" "change remember": "rememberChange" initialize: -> # You can even use your child elements using plain old JavaScript, # as early as in your `initialize` function. @ui.username.val "user" @ui.password.val "<PASSWORD>!" @ui.remember.attr "checked", true render: -> @ui.username.focus() submit: (e) => e.preventDefault() forgotUsername: -> alert "An email with your username has been sent." false forgotPassword: -> alert "An email with your password in plain text has been sent. Trust us, we're professionals." false labelClick: (e) => label = $(e.target) el = @ui[label.attr("for")] el.focus() rememberChange: (e) => console.log "remember field changed" view = new FormView() view.render()
true
# Here's an example of Backbone Unclassified in action. Most of # this is just normal Backbone code. class FormView extends Backbone.View el: "#login-form" # This is where you specify UI elements, relative to the main view # element. Once the view element has been set, the string selectors # will be replaced with jQuery instances (or Zepto, or whatever else # you're using). ui: items: ".form-item" labels: "label" inputs: "input" username: "input[name=username]" password: "input[type=password]" remember: "[data-bind=remember]" submit: "button[type=submit]" button: forgot: username: "[data-action=forgot-username]" password: PI:PASSWORD:<PASSWORD>END_PI]" # Now that you've specified child elements in the `ui` object, you # can reference them by name in place of selectors in the events # object. You can still use selectors here if you really want to (as # long as that selector doesn't match one of your child element's # names), but that would just be weird... events: "submit": "submit" "click button.forgot.username": "forgotUsername" "click button.forgot.password": "PI:PASSWORD:<PASSWORD>END_PI" "click labels": "labelClick" "change remember": "rememberChange" initialize: -> # You can even use your child elements using plain old JavaScript, # as early as in your `initialize` function. @ui.username.val "user" @ui.password.val "PI:PASSWORD:<PASSWORD>END_PI!" @ui.remember.attr "checked", true render: -> @ui.username.focus() submit: (e) => e.preventDefault() forgotUsername: -> alert "An email with your username has been sent." false forgotPassword: -> alert "An email with your password in plain text has been sent. Trust us, we're professionals." false labelClick: (e) => label = $(e.target) el = @ui[label.attr("for")] el.focus() rememberChange: (e) => console.log "remember field changed" view = new FormView() view.render()
[ { "context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ", "end": 1003, "score": 0.9993767738342285, "start": 996, "tag": "NAME", "value": "Patient" }, { "context": " }\n }, {\n ...
Src/coffeescript/cql-execution/test/elm/list/data.coffee
MeasureAuthoringTool/clinical_quality_language
2
### WARNING: This is a GENERATED file. Do not manually edit! To generate this file: - Edit data.coffee to add a CQL Snippet - From java dir: ./gradlew :cql-to-elm:generateTestData ### ### List library TestSnippet version '1' using QUICK context Patient define Three: 1 + 2 define IntList: { 9, 7, 8 } define StringList: { 'a', 'bee', 'see' } define MixedList: List<Any>{ 1, 'two', Three } define EmptyList: List<Integer>{} ### module.exports['List'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "Three", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Add", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } }, { "name" : "IntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" } ] } }, { "name" : "StringList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "bee", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "see", "type" : "Literal" } ] } }, { "name" : "MixedList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "two", "type" : "Literal" }, { "name" : "Three", "type" : "ExpressionRef" } ] } }, { "name" : "EmptyList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "List" } } ] } } } ### Exists library TestSnippet version '1' using QUICK context Patient define EmptyList: exists (List<Integer>{}) define FullList: exists ({ 1, 2, 3 }) ### module.exports['Exists'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "EmptyList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Exists", "operand" : { "type" : "List" } } }, { "name" : "FullList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Exists", "operand" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } } } ] } } } ### Equal library TestSnippet version '1' using QUICK context Patient define EqualIntList: {1, 2, 3} = {1, 2, 3} define UnequalIntList: {1, 2, 3} = {1, 2} define ReverseIntList: {1, 2, 3} = {3, 2, 1} define EqualStringList: {'hello', 'world'} = {'hello', 'world'} define UnequalStringList: {'hello', 'world'} = {'foo', 'bar'} define EqualTupleList: List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } = List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } define UnequalTupleList: List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } = List<Any>{ Tuple{a: 1, b: Tuple{c: -1}}, Tuple{x: 'y', z: 2} } ### module.exports['Equal'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "EqualIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } }, { "name" : "UnequalIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } ] } }, { "name" : "ReverseIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } ] } }, { "name" : "EqualStringList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] } ] } }, { "name" : "UnequalStringList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "foo", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "bar", "type" : "Literal" } ] } ] } }, { "name" : "EqualTupleList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "type" : "Tuple", "element" : [ { "name" : "c", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "x", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "z", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "type" : "Tuple", "element" : [ { "name" : "c", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "x", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "z", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] } ] } }, { "name" : "UnequalTupleList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "type" : "Tuple", "element" : [ { "name" : "c", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "x", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "z", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "type" : "Tuple", "element" : [ { "name" : "c", "value" : { "type" : "Negate", "operand" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "x", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "z", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] } ] } } ] } } } ### NotEqual library TestSnippet version '1' using QUICK context Patient define EqualIntList: {1, 2, 3} != {1, 2, 3} define UnequalIntList: {1, 2, 3} != {1, 2} define ReverseIntList: {1, 2, 3} != {3, 2, 1} define EqualStringList: {'hello', 'world'} != {'hello', 'world'} define UnequalStringList: {'hello', 'world'} != {'foo', 'bar'} define EqualTupleList: List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } != List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } define UnequalTupleList: List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } != List<Any>{ Tuple{a: 1, b: Tuple{c: -1}}, Tuple{x: 'y', z: 2} } ### module.exports['NotEqual'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "EqualIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } } }, { "name" : "UnequalIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } ] } } }, { "name" : "ReverseIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } ] } } }, { "name" : "EqualStringList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] } ] } } }, { "name" : "UnequalStringList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "foo", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "bar", "type" : "Literal" } ] } ] } } }, { "name" : "EqualTupleList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "type" : "Tuple", "element" : [ { "name" : "c", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "x", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "z", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "type" : "Tuple", "element" : [ { "name" : "c", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "x", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "z", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] } ] } } }, { "name" : "UnequalTupleList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "type" : "Tuple", "element" : [ { "name" : "c", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "x", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "z", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "type" : "Tuple", "element" : [ { "name" : "c", "value" : { "type" : "Negate", "operand" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "x", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "z", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] } ] } } } ] } } } ### Union library TestSnippet version '1' using QUICK context Patient define OneToTen: {1, 2, 3, 4, 5} union {6, 7, 8, 9, 10} define OneToFiveOverlapped: {1, 2, 3, 4} union {3, 4, 5} define Disjoint: {1, 2} union {4, 5} define NestedToFifteen: {1, 2, 3} union {4, 5, 6} union {7 ,8 , 9} union {10, 11, 12} union {13, 14, 15} define NullUnion: null union {1, 2, 3} define UnionNull: {1, 2, 3} union null ### module.exports['Union'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "OneToTen", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" } ] } ] } }, { "name" : "OneToFiveOverlapped", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "Disjoint", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "NestedToFifteen", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "Union", "operand" : [ { "type" : "Union", "operand" : [ { "type" : "Union", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" } ] } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "11", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "12", "type" : "Literal" } ] } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "13", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "14", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "15", "type" : "Literal" } ] } ] } }, { "name" : "NullUnion", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } }, { "name" : "UnionNull", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } } ] } } } ### Except library TestSnippet version '1' using QUICK context Patient define ExceptThreeFour: {1, 2, 3, 4, 5} except {3, 4} define ThreeFourExcept: {3, 4} except {1, 2, 3, 4, 5} define ExceptFiveThree: {1, 2, 3, 4, 5} except {5, 3} define ExceptNoOp: {1, 2, 3, 4, 5} except {6, 7, 8, 9, 10} define ExceptEverything: {1, 2, 3, 4, 5} except {1, 2, 3, 4, 5} define SomethingExceptNothing: {1, 2, 3, 4, 5} except List<Integer>{} define NothingExceptSomething: List<Integer>{} except {1, 2, 3, 4, 5} define ExceptTuples: {Tuple{a: 1}, Tuple{a: 2}, Tuple{a: 3}} except {Tuple{a: 2}} define ExceptNull: {1, 2, 3, 4, 5} except null define NullExcept: null except {1, 2, 3, 4, 5} ### module.exports['Except'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "ExceptThreeFour", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } ] } }, { "name" : "ThreeFourExcept", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "ExceptFiveThree", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } }, { "name" : "ExceptNoOp", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" } ] } ] } }, { "name" : "ExceptEverything", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "SomethingExceptNothing", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List" } ] } }, { "name" : "NothingExceptSomething", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List" }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "ExceptTuples", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] } ] } }, { "name" : "ExceptNull", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } }, { "name" : "NullExcept", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } } ] } } } ### Intersect library TestSnippet version '1' using QUICK context Patient define NoIntersection: {1, 2, 3} intersect {4, 5, 6} define IntersectOnFive: {4, 5, 6} intersect {1, 3, 5, 7} define IntersectOnEvens: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} intersect {0, 2, 4, 6, 8, 10, 12} define IntersectOnAll: {1, 2, 3, 4, 5} intersect {5, 4, 3, 2, 1} define NestedIntersects: {1, 2, 3, 4, 5} intersect {2, 3, 4, 5, 6} intersect {3, 4, 5, 6, 7} intersect {4, 5, 6, 7, 8} define IntersectTuples: {Tuple{a:1, b:'d'}, Tuple{a:1, b:'c'}, Tuple{a:2, b:'c'}} intersect {Tuple{a:2, b:'d'}, Tuple{a:1, b:'c'}, Tuple{a:2, b:'c'}, Tuple{a:5, b:'e'}} define NullIntersect: null intersect {1, 2, 3} define IntersectNull: {1, 2, 3} intersect null ### module.exports['Intersect'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "NoIntersection", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] } }, { "name" : "IntersectOnFive", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" } ] } ] } }, { "name" : "IntersectOnEvens", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "12", "type" : "Literal" } ] } ] } }, { "name" : "IntersectOnAll", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } ] } }, { "name" : "NestedIntersects", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "Intersect", "operand" : [ { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" } ] } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" } ] } ] } }, { "name" : "IntersectTuples", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "e", "type" : "Literal" } } ] } ] } ] } }, { "name" : "NullIntersect", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } }, { "name" : "IntersectNull", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } } ] } } } ### IndexOf library TestSnippet version '1' using QUICK context Patient define IndexOfSecond: IndexOf({'a', 'b', 'c', 'd'}, 'b') define IndexOfThirdTuple: IndexOf({Tuple{a: 1}, Tuple{a: 2}, Tuple{a: 3}}, Tuple{a: 3}) define MultipleMatches: IndexOf({'a', 'b', 'c', 'd', 'd', 'e', 'd'}, 'd') define ItemNotFound: IndexOf({'a', 'b', 'c'}, 'd') define NullList: IndexOf(null, 'a') define NullItem: IndexOf({'a', 'b', 'c'}, null) ### module.exports['IndexOf'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IndexOfSecond", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, "element" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" } } }, { "name" : "IndexOfThirdTuple", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] } ] }, "element" : { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] } } }, { "name" : "MultipleMatches", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "e", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, "element" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } }, { "name" : "ItemNotFound", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] }, "element" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } }, { "name" : "NullList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}String", "type" : "NamedTypeSpecifier" } } }, "element" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" } } }, { "name" : "NullItem", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] }, "element" : { "asType" : "{urn:hl7-org:elm-types:r1}String", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}String", "type" : "NamedTypeSpecifier" } } } } ] } } } ### Indexer library TestSnippet version '1' using QUICK context Patient define SecondItem: {'a', 'b', 'c', 'd'}[1] define ZeroIndex: {'a', 'b', 'c', 'd'}[0] define OutOfBounds: {'a', 'b', 'c', 'd'}[100] define NullList: (null as List<String>)[1] define NullIndexer: {'a', 'b', 'c', 'd'}[null] ### module.exports['Indexer'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "SecondItem", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Indexer", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } }, { "name" : "ZeroIndex", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Indexer", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" } ] } }, { "name" : "OutOfBounds", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Indexer", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "100", "type" : "Literal" } ] } }, { "name" : "NullList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Indexer", "operand" : [ { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}String", "type" : "NamedTypeSpecifier" } } }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } }, { "name" : "NullIndexer", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Indexer", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, { "asType" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] } } ] } } } ### In library TestSnippet version '1' using QUICK context Patient define IsIn: 4 in { 3, 4, 5 } define IsNotIn: 4 in { 3, 5, 6 } define TupleIsIn: Tuple{a: 1, b: 'c'} in {Tuple{a:1, b:'d'}, Tuple{a:1, b:'c'}, Tuple{a:2, b:'c'}} define TupleIsNotIn: Tuple{a: 1, b: 'c'} in {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define NullIn: null in {1, 2, 3} define InNull: 1 in null ### module.exports['In'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IsIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsNotIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] } }, { "name" : "TupleIsIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "TupleIsNotIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "NullIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } }, { "name" : "InNull", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } } ] } } } ### Contains library TestSnippet version '1' using QUICK context Patient define IsIn: { 3, 4, 5 } contains 4 define IsNotIn: { 3, 5, 6 } contains 4 define TupleIsIn: {Tuple{a:1, b:'d'}, Tuple{a:1, b:'c'}, Tuple{a:2, b:'c'}} contains Tuple{a: 1, b: 'c'} define TupleIsNotIn: {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} contains Tuple{a: 1, b: 'c'} define InNull: (null as List<Integer>) contains 1 define NullIn: {1, 2, 3} contains null ### module.exports['Contains'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IsIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } }, { "name" : "IsNotIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } }, { "name" : "TupleIsIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } }, { "name" : "TupleIsNotIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } }, { "name" : "InNull", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } }, { "name" : "NullIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "asType" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] } } ] } } } ### Includes library TestSnippet version '1' using QUICK context Patient define IsIncluded: {1, 2, 3, 4, 5} includes {2, 3, 4} define IsIncludedReversed: {1, 2, 3, 4, 5} includes {4, 3, 2} define IsSame: {1, 2, 3, 4, 5} includes {1, 2, 3, 4, 5} define IsNotIncluded: {1, 2, 3, 4, 5} includes {4, 5, 6} define TuplesIncluded: {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} includes {Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define TuplesNotIncluded: {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} includes {Tuple{a:2, b:'d'}, Tuple{a:3, b:'c'}} define NullIncluded: {1, 2, 3, 4, 5} includes null define NullIncludes: null includes {1, 2, 3, 4, 5} ### module.exports['Includes'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IsIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } ] } }, { "name" : "IsIncludedReversed", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } ] } }, { "name" : "IsSame", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] } }, { "name" : "TuplesIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "TuplesNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "NullIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "asType" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] } }, { "name" : "NullIncludes", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } } ] } } } ### IncludedIn library TestSnippet version '1' using QUICK context Patient define IsIncluded: {2, 3, 4} included in {1, 2, 3, 4, 5} define IsIncludedReversed: {4, 3, 2} included in {1, 2, 3, 4, 5} define IsSame: {1, 2, 3, 4, 5} included in {1, 2, 3, 4, 5} define IsNotIncluded: {4, 5, 6} included in {1, 2, 3, 4, 5} define TuplesIncluded: {Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} included in {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define TuplesNotIncluded: {Tuple{a:2, b:'d'}, Tuple{a:3, b:'c'}} included in {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define NullIncludes: {1, 2, 3, 4, 5} included in null define NullIncluded: null included in {1, 2, 3, 4, 5} ### module.exports['IncludedIn'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IsIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsIncludedReversed", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsSame", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "TuplesIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "TuplesNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "NullIncludes", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } }, { "name" : "NullIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "type" : "Null" }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } } ] } } } ### ProperIncludes library TestSnippet version '1' using QUICK context Patient define IsIncluded: {1, 2, 3, 4, 5} properly includes {2, 3, 4, 5} define IsIncludedReversed: {1, 2, 3, 4, 5} properly includes {5, 4, 3, 2} define IsSame: {1, 2, 3, 4, 5} properly includes {1, 2, 3, 4, 5} define IsNotIncluded: {1, 2, 3, 4, 5} properly includes {3, 4, 5, 6} define TuplesIncluded: {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} properly includes {Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define TuplesNotIncluded: {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} properly includes {Tuple{a:2, b:'d'}, Tuple{a:3, b:'c'}} define NullIncluded: {1, 2, 3, 4, 5} properly includes null define NullIncludes: null properly includes {1, 2, 3, 4, 5} ### module.exports['ProperIncludes'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IsIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsIncludedReversed", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } ] } }, { "name" : "IsSame", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] } }, { "name" : "TuplesIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "TuplesNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "NullIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperContains", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "asType" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] } }, { "name" : "NullIncludes", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } } ] } } } ### ProperIncludedIn library TestSnippet version '1' using QUICK context Patient define IsIncluded: {2, 3, 4} properly included in {1, 2, 3, 4, 5} define IsIncludedReversed: {4, 3, 2} properly included in {1, 2, 3, 4, 5} define IsSame: {1, 2, 3, 4, 5} properly included in {1, 2, 3, 4, 5} define IsNotIncluded: {4, 5, 6} properly included in {1, 2, 3, 4, 5} define TuplesIncluded: {Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} properly included in {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define TuplesNotIncluded: {Tuple{a:2, b:'d'}, Tuple{a:3, b:'c'}} properly included in {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define NullIncludes: {1, 2, 3, 4, 5} properly included in null define NullIncluded: (null as List<Integer>) properly included in {1, 2, 3, 4, 5} ### module.exports['ProperIncludedIn'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IsIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsIncludedReversed", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsSame", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "TuplesIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "TuplesNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "NullIncludes", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } }, { "name" : "NullIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } } ] } } } ### Flatten library TestSnippet version '1' using QUICK context Patient define ListOfLists: flatten { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {9, 8, 7, 6, 5}, {4}, {3, 2, 1} } define NullValue: flatten null ### module.exports['Flatten'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "ListOfLists", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Flatten", "operand" : { "type" : "List", "element" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } ] } } }, { "name" : "NullValue", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Flatten", "operand" : { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } } } } ] } } } ### Distinct library TestSnippet version '1' using QUICK context Patient define LotsOfDups: distinct {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 4, 3, 2, 1} define NoDups: distinct {2, 4, 6, 8, 10} ### module.exports['Distinct'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "LotsOfDups", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Distinct", "operand" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } } }, { "name" : "NoDups", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Distinct", "operand" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" } ] } } } ] } } } ### First library TestSnippet version '1' using QUICK context Patient define Numbers: First({1, 2, 3, 4}) define Letters: First({'a', 'b', 'c'}) define Lists: First({{'a','b','c'},{'d','e','f'}}) define Tuples: First({ Tuple{a: 1, b: 2, c: 3}, Tuple{a: 24, b: 25, c: 26} }) define Unordered: First({3, 1, 4, 2}) define Empty: First(List<Integer>{}) define NullValue: First(null as List<Integer>) ### module.exports['First'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "Numbers", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } } }, { "name" : "Letters", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] } } }, { "name" : "Lists", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List", "element" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "e", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "f", "type" : "Literal" } ] } ] } } }, { "name" : "Tuples", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "c", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "24", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "25", "type" : "Literal" } }, { "name" : "c", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "26", "type" : "Literal" } } ] } ] } } }, { "name" : "Unordered", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } } }, { "name" : "Empty", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List" } } }, { "name" : "NullValue", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } } } ] } } } ### Last library TestSnippet version '1' using QUICK context Patient define Numbers: Last({1, 2, 3, 4}) define Letters: Last({'a', 'b', 'c'}) define Lists: Last({{'a','b','c'},{'d','e','f'}}) define Tuples: Last({ Tuple{a: 1, b: 2, c: 3}, Tuple{a: 24, b: 25, c: 26} }) define Unordered: Last({3, 1, 4, 2}) define Empty: Last(List<Integer>{}) define NullValue: Last(null as List<Integer>) ### module.exports['Last'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "Numbers", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } } }, { "name" : "Letters", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] } } }, { "name" : "Lists", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List", "element" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "e", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "f", "type" : "Literal" } ] } ] } } }, { "name" : "Tuples", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "c", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "24", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "25", "type" : "Literal" } }, { "name" : "c", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "26", "type" : "Literal" } } ] } ] } } }, { "name" : "Unordered", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } } }, { "name" : "Empty", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List" } } }, { "name" : "NullValue", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } } } ] } } } ### Length library TestSnippet version '1' using QUICK context Patient define Numbers: Length({2, 4, 6, 8, 10}) define Lists: Length({ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}) define Tuples: Length({ Tuple{a: 1, b: 2, c: 3}, Tuple{a: 24, b: 25, c: 26} }) define Empty: Length(List<Integer>{}) define NullValue: Length(null as List<Integer>) ### module.exports['Length'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "Numbers", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Length", "operand" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" } ] } } }, { "name" : "Lists", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Length", "operand" : { "type" : "List", "element" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "11", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "12", "type" : "Literal" } ] } ] } } }, { "name" : "Tuples", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Length", "operand" : { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "c", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "24", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "25", "type" : "Literal" } }, { "name" : "c", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "26", "type" : "Literal" } } ] } ] } } }, { "name" : "Empty", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Length", "operand" : { "type" : "List" } } }, { "name" : "NullValue", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Length", "operand" : { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } } } ] } } }
182582
### WARNING: This is a GENERATED file. Do not manually edit! To generate this file: - Edit data.coffee to add a CQL Snippet - From java dir: ./gradlew :cql-to-elm:generateTestData ### ### List library TestSnippet version '1' using QUICK context Patient define Three: 1 + 2 define IntList: { 9, 7, 8 } define StringList: { 'a', 'bee', 'see' } define MixedList: List<Any>{ 1, 'two', Three } define EmptyList: List<Integer>{} ### module.exports['List'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Add", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" } ] } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "bee", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "see", "type" : "Literal" } ] } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "two", "type" : "Literal" }, { "name" : "<NAME>", "type" : "ExpressionRef" } ] } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "List" } } ] } } } ### Exists library TestSnippet version '1' using QUICK context Patient define EmptyList: exists (List<Integer>{}) define FullList: exists ({ 1, 2, 3 }) ### module.exports['Exists'] = { "library" : { "identifier" : { "id" : "<NAME>Snippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Exists", "operand" : { "type" : "List" } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Exists", "operand" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } } } ] } } } ### Equal library TestSnippet version '1' using QUICK context Patient define EqualIntList: {1, 2, 3} = {1, 2, 3} define UnequalIntList: {1, 2, 3} = {1, 2} define ReverseIntList: {1, 2, 3} = {3, 2, 1} define EqualStringList: {'hello', 'world'} = {'hello', 'world'} define UnequalStringList: {'hello', 'world'} = {'foo', 'bar'} define EqualTupleList: List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } = List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } define UnequalTupleList: List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } = List<Any>{ Tuple{a: 1, b: Tuple{c: -1}}, Tuple{x: 'y', z: 2} } ### module.exports['Equal'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "EqualIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } }, { "name" : "UnequalIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } ] } }, { "name" : "ReverseIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } ] } }, { "name" : "EqualStringList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] } ] } }, { "name" : "UnequalStringList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "foo", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "bar", "type" : "Literal" } ] } ] } }, { "name" : "EqualTupleList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] } ] } }, { "name" : "UnequalTupleList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "type" : "Negate", "operand" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] } ] } } ] } } } ### NotEqual library TestSnippet version '1' using QUICK context Patient define EqualIntList: {1, 2, 3} != {1, 2, 3} define UnequalIntList: {1, 2, 3} != {1, 2} define ReverseIntList: {1, 2, 3} != {3, 2, 1} define EqualStringList: {'hello', 'world'} != {'hello', 'world'} define UnequalStringList: {'hello', 'world'} != {'foo', 'bar'} define EqualTupleList: List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } != List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } define UnequalTupleList: List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } != List<Any>{ Tuple{a: 1, b: Tuple{c: -1}}, Tuple{x: 'y', z: 2} } ### module.exports['NotEqual'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "EqualIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } } }, { "name" : "UnequalIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } ] } } }, { "name" : "ReverseIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } ] } } }, { "name" : "EqualStringList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] } ] } } }, { "name" : "UnequalStringList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "foo", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "bar", "type" : "Literal" } ] } ] } } }, { "name" : "EqualTupleList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "x", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "z", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] } ] } } }, { "name" : "UnequalTupleList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "type" : "Negate", "operand" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] } ] } } } ] } } } ### Union library TestSnippet version '1' using QUICK context Patient define OneToTen: {1, 2, 3, 4, 5} union {6, 7, 8, 9, 10} define OneToFiveOverlapped: {1, 2, 3, 4} union {3, 4, 5} define Disjoint: {1, 2} union {4, 5} define NestedToFifteen: {1, 2, 3} union {4, 5, 6} union {7 ,8 , 9} union {10, 11, 12} union {13, 14, 15} define NullUnion: null union {1, 2, 3} define UnionNull: {1, 2, 3} union null ### module.exports['Union'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>ToTen", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" } ] } ] } }, { "name" : "OneToFiveOverlapped", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "Disjoint", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "NestedToFifteen", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "Union", "operand" : [ { "type" : "Union", "operand" : [ { "type" : "Union", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" } ] } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "11", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "12", "type" : "Literal" } ] } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "13", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "14", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "15", "type" : "Literal" } ] } ] } }, { "name" : "NullUnion", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } }, { "name" : "UnionNull", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } } ] } } } ### Except library TestSnippet version '1' using QUICK context Patient define ExceptThreeFour: {1, 2, 3, 4, 5} except {3, 4} define ThreeFourExcept: {3, 4} except {1, 2, 3, 4, 5} define ExceptFiveThree: {1, 2, 3, 4, 5} except {5, 3} define ExceptNoOp: {1, 2, 3, 4, 5} except {6, 7, 8, 9, 10} define ExceptEverything: {1, 2, 3, 4, 5} except {1, 2, 3, 4, 5} define SomethingExceptNothing: {1, 2, 3, 4, 5} except List<Integer>{} define NothingExceptSomething: List<Integer>{} except {1, 2, 3, 4, 5} define ExceptTuples: {Tuple{a: 1}, Tuple{a: 2}, Tuple{a: 3}} except {Tuple{a: 2}} define ExceptNull: {1, 2, 3, 4, 5} except null define NullExcept: null except {1, 2, 3, 4, 5} ### module.exports['Except'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "ExceptThreeFour", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } ] } }, { "name" : "ThreeFourExcept", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "ExceptFiveThree", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } }, { "name" : "ExceptNoOp", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" } ] } ] } }, { "name" : "ExceptEverything", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "SomethingExceptNothing", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List" } ] } }, { "name" : "NothingExceptSomething", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List" }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "ExceptTuples", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] } ] } }, { "name" : "ExceptNull", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } }, { "name" : "NullExcept", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } } ] } } } ### Intersect library TestSnippet version '1' using QUICK context Patient define NoIntersection: {1, 2, 3} intersect {4, 5, 6} define IntersectOnFive: {4, 5, 6} intersect {1, 3, 5, 7} define IntersectOnEvens: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} intersect {0, 2, 4, 6, 8, 10, 12} define IntersectOnAll: {1, 2, 3, 4, 5} intersect {5, 4, 3, 2, 1} define NestedIntersects: {1, 2, 3, 4, 5} intersect {2, 3, 4, 5, 6} intersect {3, 4, 5, 6, 7} intersect {4, 5, 6, 7, 8} define IntersectTuples: {Tuple{a:1, b:'d'}, Tuple{a:1, b:'c'}, Tuple{a:2, b:'c'}} intersect {Tuple{a:2, b:'d'}, Tuple{a:1, b:'c'}, Tuple{a:2, b:'c'}, Tuple{a:5, b:'e'}} define NullIntersect: null intersect {1, 2, 3} define IntersectNull: {1, 2, 3} intersect null ### module.exports['Intersect'] = { "library" : { "identifier" : { "id" : "<NAME>Snippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "NoIntersection", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] } }, { "name" : "IntersectOnFive", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" } ] } ] } }, { "name" : "IntersectOnEvens", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "12", "type" : "Literal" } ] } ] } }, { "name" : "IntersectOnAll", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } ] } }, { "name" : "NestedIntersects", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "Intersect", "operand" : [ { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" } ] } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" } ] } ] } }, { "name" : "IntersectTuples", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "e", "type" : "Literal" } } ] } ] } ] } }, { "name" : "NullIntersect", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } }, { "name" : "IntersectNull", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } } ] } } } ### IndexOf library TestSnippet version '1' using QUICK context Patient define IndexOfSecond: IndexOf({'a', 'b', 'c', 'd'}, 'b') define IndexOfThirdTuple: IndexOf({Tuple{a: 1}, Tuple{a: 2}, Tuple{a: 3}}, Tuple{a: 3}) define MultipleMatches: IndexOf({'a', 'b', 'c', 'd', 'd', 'e', 'd'}, 'd') define ItemNotFound: IndexOf({'a', 'b', 'c'}, 'd') define NullList: IndexOf(null, 'a') define NullItem: IndexOf({'a', 'b', 'c'}, null) ### module.exports['IndexOf'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IndexOfSecond", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, "element" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" } } }, { "name" : "IndexOfThirdTuple", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] } ] }, "element" : { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] } } }, { "name" : "MultipleMatches", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "e", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, "element" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } }, { "name" : "ItemNotFound", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] }, "element" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } }, { "name" : "<NAME>List", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}String", "type" : "NamedTypeSpecifier" } } }, "element" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" } } }, { "name" : "<NAME>Item", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] }, "element" : { "asType" : "{urn:hl7-org:elm-types:r1}String", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}String", "type" : "NamedTypeSpecifier" } } } } ] } } } ### Indexer library TestSnippet version '1' using QUICK context Patient define SecondItem: {'a', 'b', 'c', 'd'}[1] define ZeroIndex: {'a', 'b', 'c', 'd'}[0] define OutOfBounds: {'a', 'b', 'c', 'd'}[100] define NullList: (null as List<String>)[1] define NullIndexer: {'a', 'b', 'c', 'd'}[null] ### module.exports['Indexer'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>Item", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Indexer", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } }, { "name" : "<NAME>Index", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Indexer", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" } ] } }, { "name" : "OutOfBounds", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Indexer", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "100", "type" : "Literal" } ] } }, { "name" : "<NAME>List", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Indexer", "operand" : [ { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}String", "type" : "NamedTypeSpecifier" } } }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } }, { "name" : "NullIndexer", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Indexer", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, { "asType" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] } } ] } } } ### In library TestSnippet version '1' using QUICK context Patient define IsIn: 4 in { 3, 4, 5 } define IsNotIn: 4 in { 3, 5, 6 } define TupleIsIn: Tuple{a: 1, b: 'c'} in {Tuple{a:1, b:'d'}, Tuple{a:1, b:'c'}, Tuple{a:2, b:'c'}} define TupleIsNotIn: Tuple{a: 1, b: 'c'} in {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define NullIn: null in {1, 2, 3} define InNull: 1 in null ### module.exports['In'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsNotIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] } }, { "name" : "TupleIsIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "TupleIsNotIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } }, { "name" : "InNull", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } } ] } } } ### Contains library TestSnippet version '1' using QUICK context Patient define IsIn: { 3, 4, 5 } contains 4 define IsNotIn: { 3, 5, 6 } contains 4 define TupleIsIn: {Tuple{a:1, b:'d'}, Tuple{a:1, b:'c'}, Tuple{a:2, b:'c'}} contains Tuple{a: 1, b: 'c'} define TupleIsNotIn: {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} contains Tuple{a: 1, b: 'c'} define InNull: (null as List<Integer>) contains 1 define NullIn: {1, 2, 3} contains null ### module.exports['Contains'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } }, { "name" : "IsNotIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } }, { "name" : "TupleIsIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } }, { "name" : "TupleIsNotIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } }, { "name" : "NullIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "asType" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] } } ] } } } ### Includes library TestSnippet version '1' using QUICK context Patient define IsIncluded: {1, 2, 3, 4, 5} includes {2, 3, 4} define IsIncludedReversed: {1, 2, 3, 4, 5} includes {4, 3, 2} define IsSame: {1, 2, 3, 4, 5} includes {1, 2, 3, 4, 5} define IsNotIncluded: {1, 2, 3, 4, 5} includes {4, 5, 6} define TuplesIncluded: {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} includes {Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define TuplesNotIncluded: {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} includes {Tuple{a:2, b:'d'}, Tuple{a:3, b:'c'}} define NullIncluded: {1, 2, 3, 4, 5} includes null define NullIncludes: null includes {1, 2, 3, 4, 5} ### module.exports['Includes'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IsIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } ] } }, { "name" : "IsIncludedReversed", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>Included", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] } }, { "name" : "TuplesIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "TuplesNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "<NAME>Included", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "asType" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] } }, { "name" : "<NAME>Includes", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } } ] } } } ### IncludedIn library TestSnippet version '1' using QUICK context Patient define IsIncluded: {2, 3, 4} included in {1, 2, 3, 4, 5} define IsIncludedReversed: {4, 3, 2} included in {1, 2, 3, 4, 5} define IsSame: {1, 2, 3, 4, 5} included in {1, 2, 3, 4, 5} define IsNotIncluded: {4, 5, 6} included in {1, 2, 3, 4, 5} define TuplesIncluded: {Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} included in {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define TuplesNotIncluded: {Tuple{a:2, b:'d'}, Tuple{a:3, b:'c'}} included in {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define NullIncludes: {1, 2, 3, 4, 5} included in null define NullIncluded: null included in {1, 2, 3, 4, 5} ### module.exports['IncludedIn'] = { "library" : { "identifier" : { "id" : "<NAME>Snippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IsIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsIncludedReversed", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "TuplesIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "TuplesNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "NullIncludes", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } }, { "name" : "NullIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "type" : "Null" }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } } ] } } } ### ProperIncludes library TestSnippet version '1' using QUICK context Patient define IsIncluded: {1, 2, 3, 4, 5} properly includes {2, 3, 4, 5} define IsIncludedReversed: {1, 2, 3, 4, 5} properly includes {5, 4, 3, 2} define IsSame: {1, 2, 3, 4, 5} properly includes {1, 2, 3, 4, 5} define IsNotIncluded: {1, 2, 3, 4, 5} properly includes {3, 4, 5, 6} define TuplesIncluded: {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} properly includes {Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define TuplesNotIncluded: {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} properly includes {Tuple{a:2, b:'d'}, Tuple{a:3, b:'c'}} define NullIncluded: {1, 2, 3, 4, 5} properly includes null define NullIncludes: null properly includes {1, 2, 3, 4, 5} ### module.exports['ProperIncludes'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IsIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsIncludedReversed", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>Included", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "TuplesNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "NullIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperContains", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "asType" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] } }, { "name" : "NullIncludes", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } } ] } } } ### ProperIncludedIn library TestSnippet version '1' using QUICK context Patient define IsIncluded: {2, 3, 4} properly included in {1, 2, 3, 4, 5} define IsIncludedReversed: {4, 3, 2} properly included in {1, 2, 3, 4, 5} define IsSame: {1, 2, 3, 4, 5} properly included in {1, 2, 3, 4, 5} define IsNotIncluded: {4, 5, 6} properly included in {1, 2, 3, 4, 5} define TuplesIncluded: {Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} properly included in {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define TuplesNotIncluded: {Tuple{a:2, b:'d'}, Tuple{a:3, b:'c'}} properly included in {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define NullIncludes: {1, 2, 3, 4, 5} properly included in null define NullIncluded: (null as List<Integer>) properly included in {1, 2, 3, 4, 5} ### module.exports['ProperIncludedIn'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IsIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsIncludedReversed", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "<NAME>Included", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "TuplesIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "TuplesNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "NullIncludes", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } }, { "name" : "NullIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } } ] } } } ### Flatten library TestSnippet version '1' using QUICK context Patient define ListOfLists: flatten { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {9, 8, 7, 6, 5}, {4}, {3, 2, 1} } define NullValue: flatten null ### module.exports['Flatten'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Flatten", "operand" : { "type" : "List", "element" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } ] } } }, { "name" : "NullValue", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Flatten", "operand" : { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } } } } ] } } } ### Distinct library TestSnippet version '1' using QUICK context Patient define LotsOfDups: distinct {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 4, 3, 2, 1} define NoDups: distinct {2, 4, 6, 8, 10} ### module.exports['Distinct'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "LotsOfDups", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Distinct", "operand" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } } }, { "name" : "<NAME>Dups", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Distinct", "operand" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" } ] } } } ] } } } ### First library TestSnippet version '1' using QUICK context Patient define Numbers: First({1, 2, 3, 4}) define Letters: First({'a', 'b', 'c'}) define Lists: First({{'a','b','c'},{'d','e','f'}}) define Tuples: First({ Tuple{a: 1, b: 2, c: 3}, Tuple{a: 24, b: 25, c: 26} }) define Unordered: First({3, 1, 4, 2}) define Empty: First(List<Integer>{}) define NullValue: First(null as List<Integer>) ### module.exports['First'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List", "element" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "e", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "f", "type" : "Literal" } ] } ] } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "24", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "25", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "26", "type" : "Literal" } } ] } ] } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List" } } }, { "name" : "NullValue", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } } } ] } } } ### Last library TestSnippet version '1' using QUICK context Patient define Numbers: Last({1, 2, 3, 4}) define Letters: Last({'a', 'b', 'c'}) define Lists: Last({{'a','b','c'},{'d','e','f'}}) define Tuples: Last({ Tuple{a: 1, b: 2, c: 3}, Tuple{a: 24, b: 25, c: 26} }) define Unordered: Last({3, 1, 4, 2}) define Empty: Last(List<Integer>{}) define NullValue: Last(null as List<Integer>) ### module.exports['Last'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List", "element" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "e", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "f", "type" : "Literal" } ] } ] } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "c", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "24", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "25", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "26", "type" : "Literal" } } ] } ] } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List" } } }, { "name" : "NullValue", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } } } ] } } } ### Length library TestSnippet version '1' using QUICK context Patient define Numbers: Length({2, 4, 6, 8, 10}) define Lists: Length({ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}) define Tuples: Length({ Tuple{a: 1, b: 2, c: 3}, Tuple{a: 24, b: 25, c: 26} }) define Empty: Length(List<Integer>{}) define NullValue: Length(null as List<Integer>) ### module.exports['Length'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Length", "operand" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" } ] } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Length", "operand" : { "type" : "List", "element" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "11", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "12", "type" : "Literal" } ] } ] } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Length", "operand" : { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "24", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "25", "type" : "Literal" } }, { "name" : "<NAME>", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "26", "type" : "Literal" } } ] } ] } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Length", "operand" : { "type" : "List" } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Length", "operand" : { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } } } ] } } }
true
### WARNING: This is a GENERATED file. Do not manually edit! To generate this file: - Edit data.coffee to add a CQL Snippet - From java dir: ./gradlew :cql-to-elm:generateTestData ### ### List library TestSnippet version '1' using QUICK context Patient define Three: 1 + 2 define IntList: { 9, 7, 8 } define StringList: { 'a', 'bee', 'see' } define MixedList: List<Any>{ 1, 'two', Three } define EmptyList: List<Integer>{} ### module.exports['List'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Add", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "bee", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "see", "type" : "Literal" } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "two", "type" : "Literal" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "ExpressionRef" } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "List" } } ] } } } ### Exists library TestSnippet version '1' using QUICK context Patient define EmptyList: exists (List<Integer>{}) define FullList: exists ({ 1, 2, 3 }) ### module.exports['Exists'] = { "library" : { "identifier" : { "id" : "PI:NAME:<NAME>END_PISnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Exists", "operand" : { "type" : "List" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Exists", "operand" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } } } ] } } } ### Equal library TestSnippet version '1' using QUICK context Patient define EqualIntList: {1, 2, 3} = {1, 2, 3} define UnequalIntList: {1, 2, 3} = {1, 2} define ReverseIntList: {1, 2, 3} = {3, 2, 1} define EqualStringList: {'hello', 'world'} = {'hello', 'world'} define UnequalStringList: {'hello', 'world'} = {'foo', 'bar'} define EqualTupleList: List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } = List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } define UnequalTupleList: List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } = List<Any>{ Tuple{a: 1, b: Tuple{c: -1}}, Tuple{x: 'y', z: 2} } ### module.exports['Equal'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "EqualIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } }, { "name" : "UnequalIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } ] } }, { "name" : "ReverseIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } ] } }, { "name" : "EqualStringList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] } ] } }, { "name" : "UnequalStringList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "foo", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "bar", "type" : "Literal" } ] } ] } }, { "name" : "EqualTupleList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] } ] } }, { "name" : "UnequalTupleList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "a", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "b", "value" : { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "type" : "Negate", "operand" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] } ] } } ] } } } ### NotEqual library TestSnippet version '1' using QUICK context Patient define EqualIntList: {1, 2, 3} != {1, 2, 3} define UnequalIntList: {1, 2, 3} != {1, 2} define ReverseIntList: {1, 2, 3} != {3, 2, 1} define EqualStringList: {'hello', 'world'} != {'hello', 'world'} define UnequalStringList: {'hello', 'world'} != {'foo', 'bar'} define EqualTupleList: List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } != List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } define UnequalTupleList: List<Any>{ Tuple{a: 1, b: Tuple{c: 1}}, Tuple{x: 'y', z: 2} } != List<Any>{ Tuple{a: 1, b: Tuple{c: -1}}, Tuple{x: 'y', z: 2} } ### module.exports['NotEqual'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "EqualIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } } }, { "name" : "UnequalIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } ] } } }, { "name" : "ReverseIntList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } ] } } }, { "name" : "EqualStringList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] } ] } } }, { "name" : "UnequalStringList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "hello", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "world", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "foo", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "bar", "type" : "Literal" } ] } ] } } }, { "name" : "EqualTupleList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "x", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "z", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] } ] } } }, { "name" : "UnequalTupleList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Not", "operand" : { "type" : "Equal", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "type" : "Negate", "operand" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } } ] } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "y", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] } ] } } } ] } } } ### Union library TestSnippet version '1' using QUICK context Patient define OneToTen: {1, 2, 3, 4, 5} union {6, 7, 8, 9, 10} define OneToFiveOverlapped: {1, 2, 3, 4} union {3, 4, 5} define Disjoint: {1, 2} union {4, 5} define NestedToFifteen: {1, 2, 3} union {4, 5, 6} union {7 ,8 , 9} union {10, 11, 12} union {13, 14, 15} define NullUnion: null union {1, 2, 3} define UnionNull: {1, 2, 3} union null ### module.exports['Union'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PIToTen", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" } ] } ] } }, { "name" : "OneToFiveOverlapped", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "Disjoint", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "NestedToFifteen", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "Union", "operand" : [ { "type" : "Union", "operand" : [ { "type" : "Union", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" } ] } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "11", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "12", "type" : "Literal" } ] } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "13", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "14", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "15", "type" : "Literal" } ] } ] } }, { "name" : "NullUnion", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } }, { "name" : "UnionNull", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Union", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } } ] } } } ### Except library TestSnippet version '1' using QUICK context Patient define ExceptThreeFour: {1, 2, 3, 4, 5} except {3, 4} define ThreeFourExcept: {3, 4} except {1, 2, 3, 4, 5} define ExceptFiveThree: {1, 2, 3, 4, 5} except {5, 3} define ExceptNoOp: {1, 2, 3, 4, 5} except {6, 7, 8, 9, 10} define ExceptEverything: {1, 2, 3, 4, 5} except {1, 2, 3, 4, 5} define SomethingExceptNothing: {1, 2, 3, 4, 5} except List<Integer>{} define NothingExceptSomething: List<Integer>{} except {1, 2, 3, 4, 5} define ExceptTuples: {Tuple{a: 1}, Tuple{a: 2}, Tuple{a: 3}} except {Tuple{a: 2}} define ExceptNull: {1, 2, 3, 4, 5} except null define NullExcept: null except {1, 2, 3, 4, 5} ### module.exports['Except'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "ExceptThreeFour", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } ] } }, { "name" : "ThreeFourExcept", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "ExceptFiveThree", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } }, { "name" : "ExceptNoOp", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" } ] } ] } }, { "name" : "ExceptEverything", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "SomethingExceptNothing", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List" } ] } }, { "name" : "NothingExceptSomething", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List" }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "ExceptTuples", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] } ] } ] } }, { "name" : "ExceptNull", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } }, { "name" : "NullExcept", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Except", "operand" : [ { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } } ] } } } ### Intersect library TestSnippet version '1' using QUICK context Patient define NoIntersection: {1, 2, 3} intersect {4, 5, 6} define IntersectOnFive: {4, 5, 6} intersect {1, 3, 5, 7} define IntersectOnEvens: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} intersect {0, 2, 4, 6, 8, 10, 12} define IntersectOnAll: {1, 2, 3, 4, 5} intersect {5, 4, 3, 2, 1} define NestedIntersects: {1, 2, 3, 4, 5} intersect {2, 3, 4, 5, 6} intersect {3, 4, 5, 6, 7} intersect {4, 5, 6, 7, 8} define IntersectTuples: {Tuple{a:1, b:'d'}, Tuple{a:1, b:'c'}, Tuple{a:2, b:'c'}} intersect {Tuple{a:2, b:'d'}, Tuple{a:1, b:'c'}, Tuple{a:2, b:'c'}, Tuple{a:5, b:'e'}} define NullIntersect: null intersect {1, 2, 3} define IntersectNull: {1, 2, 3} intersect null ### module.exports['Intersect'] = { "library" : { "identifier" : { "id" : "PI:NAME:<NAME>END_PISnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "NoIntersection", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] } }, { "name" : "IntersectOnFive", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" } ] } ] } }, { "name" : "IntersectOnEvens", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "12", "type" : "Literal" } ] } ] } }, { "name" : "IntersectOnAll", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } ] } }, { "name" : "NestedIntersects", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "Intersect", "operand" : [ { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" } ] } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" } ] } ] } }, { "name" : "IntersectTuples", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "e", "type" : "Literal" } } ] } ] } ] } }, { "name" : "NullIntersect", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } }, { "name" : "IntersectNull", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Intersect", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } } ] } } } ### IndexOf library TestSnippet version '1' using QUICK context Patient define IndexOfSecond: IndexOf({'a', 'b', 'c', 'd'}, 'b') define IndexOfThirdTuple: IndexOf({Tuple{a: 1}, Tuple{a: 2}, Tuple{a: 3}}, Tuple{a: 3}) define MultipleMatches: IndexOf({'a', 'b', 'c', 'd', 'd', 'e', 'd'}, 'd') define ItemNotFound: IndexOf({'a', 'b', 'c'}, 'd') define NullList: IndexOf(null, 'a') define NullItem: IndexOf({'a', 'b', 'c'}, null) ### module.exports['IndexOf'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IndexOfSecond", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, "element" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" } } }, { "name" : "IndexOfThirdTuple", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] } ] }, "element" : { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] } } }, { "name" : "MultipleMatches", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "e", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, "element" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } }, { "name" : "ItemNotFound", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] }, "element" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } }, { "name" : "PI:NAME:<NAME>END_PIList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}String", "type" : "NamedTypeSpecifier" } } }, "element" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" } } }, { "name" : "PI:NAME:<NAME>END_PIItem", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IndexOf", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] }, "element" : { "asType" : "{urn:hl7-org:elm-types:r1}String", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}String", "type" : "NamedTypeSpecifier" } } } } ] } } } ### Indexer library TestSnippet version '1' using QUICK context Patient define SecondItem: {'a', 'b', 'c', 'd'}[1] define ZeroIndex: {'a', 'b', 'c', 'd'}[0] define OutOfBounds: {'a', 'b', 'c', 'd'}[100] define NullList: (null as List<String>)[1] define NullIndexer: {'a', 'b', 'c', 'd'}[null] ### module.exports['Indexer'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PIItem", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Indexer", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } }, { "name" : "PI:NAME:<NAME>END_PIIndex", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Indexer", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "0", "type" : "Literal" } ] } }, { "name" : "OutOfBounds", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Indexer", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "100", "type" : "Literal" } ] } }, { "name" : "PI:NAME:<NAME>END_PIList", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Indexer", "operand" : [ { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}String", "type" : "NamedTypeSpecifier" } } }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } }, { "name" : "NullIndexer", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Indexer", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } ] }, { "asType" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] } } ] } } } ### In library TestSnippet version '1' using QUICK context Patient define IsIn: 4 in { 3, 4, 5 } define IsNotIn: 4 in { 3, 5, 6 } define TupleIsIn: Tuple{a: 1, b: 'c'} in {Tuple{a:1, b:'d'}, Tuple{a:1, b:'c'}, Tuple{a:2, b:'c'}} define TupleIsNotIn: Tuple{a: 1, b: 'c'} in {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define NullIn: null in {1, 2, 3} define InNull: 1 in null ### module.exports['In'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsNotIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] } }, { "name" : "TupleIsIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "TupleIsNotIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "asType" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] } ] } }, { "name" : "InNull", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } } ] } } } ### Contains library TestSnippet version '1' using QUICK context Patient define IsIn: { 3, 4, 5 } contains 4 define IsNotIn: { 3, 5, 6 } contains 4 define TupleIsIn: {Tuple{a:1, b:'d'}, Tuple{a:1, b:'c'}, Tuple{a:2, b:'c'}} contains Tuple{a: 1, b: 'c'} define TupleIsNotIn: {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} contains Tuple{a: 1, b: 'c'} define InNull: (null as List<Integer>) contains 1 define NullIn: {1, 2, 3} contains null ### module.exports['Contains'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } }, { "name" : "IsNotIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } }, { "name" : "TupleIsIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } }, { "name" : "TupleIsNotIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } }, { "name" : "NullIn", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "asType" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] } } ] } } } ### Includes library TestSnippet version '1' using QUICK context Patient define IsIncluded: {1, 2, 3, 4, 5} includes {2, 3, 4} define IsIncludedReversed: {1, 2, 3, 4, 5} includes {4, 3, 2} define IsSame: {1, 2, 3, 4, 5} includes {1, 2, 3, 4, 5} define IsNotIncluded: {1, 2, 3, 4, 5} includes {4, 5, 6} define TuplesIncluded: {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} includes {Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define TuplesNotIncluded: {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} includes {Tuple{a:2, b:'d'}, Tuple{a:3, b:'c'}} define NullIncluded: {1, 2, 3, 4, 5} includes null define NullIncludes: null includes {1, 2, 3, 4, 5} ### module.exports['Includes'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IsIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } ] } }, { "name" : "IsIncludedReversed", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PIIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] } }, { "name" : "TuplesIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "TuplesNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PIIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Contains", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "asType" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] } }, { "name" : "PI:NAME:<NAME>END_PIIncludes", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Includes", "operand" : [ { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } } ] } } } ### IncludedIn library TestSnippet version '1' using QUICK context Patient define IsIncluded: {2, 3, 4} included in {1, 2, 3, 4, 5} define IsIncludedReversed: {4, 3, 2} included in {1, 2, 3, 4, 5} define IsSame: {1, 2, 3, 4, 5} included in {1, 2, 3, 4, 5} define IsNotIncluded: {4, 5, 6} included in {1, 2, 3, 4, 5} define TuplesIncluded: {Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} included in {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define TuplesNotIncluded: {Tuple{a:2, b:'d'}, Tuple{a:3, b:'c'}} included in {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define NullIncludes: {1, 2, 3, 4, 5} included in null define NullIncluded: null included in {1, 2, 3, 4, 5} ### module.exports['IncludedIn'] = { "library" : { "identifier" : { "id" : "PI:NAME:<NAME>END_PISnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IsIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsIncludedReversed", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "TuplesIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "TuplesNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "NullIncludes", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "IncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } }, { "name" : "NullIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "In", "operand" : [ { "type" : "Null" }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } } ] } } } ### ProperIncludes library TestSnippet version '1' using QUICK context Patient define IsIncluded: {1, 2, 3, 4, 5} properly includes {2, 3, 4, 5} define IsIncludedReversed: {1, 2, 3, 4, 5} properly includes {5, 4, 3, 2} define IsSame: {1, 2, 3, 4, 5} properly includes {1, 2, 3, 4, 5} define IsNotIncluded: {1, 2, 3, 4, 5} properly includes {3, 4, 5, 6} define TuplesIncluded: {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} properly includes {Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define TuplesNotIncluded: {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} properly includes {Tuple{a:2, b:'d'}, Tuple{a:3, b:'c'}} define NullIncluded: {1, 2, 3, 4, 5} properly includes null define NullIncludes: null properly includes {1, 2, 3, 4, 5} ### module.exports['ProperIncludes'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IsIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsIncludedReversed", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PIIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "TuplesNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "NullIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperContains", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "asType" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] } }, { "name" : "NullIncludes", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludes", "operand" : [ { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } } ] } } } ### ProperIncludedIn library TestSnippet version '1' using QUICK context Patient define IsIncluded: {2, 3, 4} properly included in {1, 2, 3, 4, 5} define IsIncludedReversed: {4, 3, 2} properly included in {1, 2, 3, 4, 5} define IsSame: {1, 2, 3, 4, 5} properly included in {1, 2, 3, 4, 5} define IsNotIncluded: {4, 5, 6} properly included in {1, 2, 3, 4, 5} define TuplesIncluded: {Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} properly included in {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define TuplesNotIncluded: {Tuple{a:2, b:'d'}, Tuple{a:3, b:'c'}} properly included in {Tuple{a:1, b:'d'}, Tuple{a:2, b:'d'}, Tuple{a:2, b:'c'}} define NullIncludes: {1, 2, 3, 4, 5} properly included in null define NullIncluded: (null as List<Integer>) properly included in {1, 2, 3, 4, 5} ### module.exports['ProperIncludedIn'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "IsIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "IsIncludedReversed", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "PI:NAME:<NAME>END_PIIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } }, { "name" : "TuplesIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "TuplesNotIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] }, { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "b", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } } ] } ] } ] } }, { "name" : "NullIncludes", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } ] } }, { "name" : "NullIncluded", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "ProperIncludedIn", "operand" : [ { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] } ] } } ] } } } ### Flatten library TestSnippet version '1' using QUICK context Patient define ListOfLists: flatten { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {9, 8, 7, 6, 5}, {4}, {3, 2, 1} } define NullValue: flatten null ### module.exports['Flatten'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Flatten", "operand" : { "type" : "List", "element" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } ] } } }, { "name" : "NullValue", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Flatten", "operand" : { "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } } } } ] } } } ### Distinct library TestSnippet version '1' using QUICK context Patient define LotsOfDups: distinct {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 4, 3, 2, 1} define NoDups: distinct {2, 4, 6, 8, 10} ### module.exports['Distinct'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "LotsOfDups", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Distinct", "operand" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PIDups", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Distinct", "operand" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" } ] } } } ] } } } ### First library TestSnippet version '1' using QUICK context Patient define Numbers: First({1, 2, 3, 4}) define Letters: First({'a', 'b', 'c'}) define Lists: First({{'a','b','c'},{'d','e','f'}}) define Tuples: First({ Tuple{a: 1, b: 2, c: 3}, Tuple{a: 24, b: 25, c: 26} }) define Unordered: First({3, 1, 4, 2}) define Empty: First(List<Integer>{}) define NullValue: First(null as List<Integer>) ### module.exports['First'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List", "element" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "e", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "f", "type" : "Literal" } ] } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "24", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "25", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "26", "type" : "Literal" } } ] } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "type" : "List" } } }, { "name" : "NullValue", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "First", "source" : { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } } } ] } } } ### Last library TestSnippet version '1' using QUICK context Patient define Numbers: Last({1, 2, 3, 4}) define Letters: Last({'a', 'b', 'c'}) define Lists: Last({{'a','b','c'},{'d','e','f'}}) define Tuples: Last({ Tuple{a: 1, b: 2, c: 3}, Tuple{a: 24, b: 25, c: 26} }) define Unordered: Last({3, 1, 4, 2}) define Empty: Last(List<Integer>{}) define NullValue: Last(null as List<Integer>) ### module.exports['Last'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List", "element" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "a", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "b", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "c", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "d", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "e", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "f", "type" : "Literal" } ] } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "c", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "24", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "25", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "26", "type" : "Literal" } } ] } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "type" : "List" } } }, { "name" : "NullValue", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Last", "source" : { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } } } ] } } } ### Length library TestSnippet version '1' using QUICK context Patient define Numbers: Length({2, 4, 6, 8, 10}) define Lists: Length({ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}) define Tuples: Length({ Tuple{a: 1, b: 2, c: 3}, Tuple{a: 24, b: 25, c: 26} }) define Empty: Length(List<Integer>{}) define NullValue: Length(null as List<Integer>) ### module.exports['Length'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Length", "operand" : { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Length", "operand" : { "type" : "List", "element" : [ { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "4", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "5", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "6", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "7", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "8", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "9", "type" : "Literal" } ] }, { "type" : "List", "element" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "10", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "11", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "12", "type" : "Literal" } ] } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Length", "operand" : { "type" : "List", "element" : [ { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "3", "type" : "Literal" } } ] }, { "type" : "Tuple", "element" : [ { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "24", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "25", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "value" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "26", "type" : "Literal" } } ] } ] } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Length", "operand" : { "type" : "List" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "type" : "Length", "operand" : { "strict" : false, "type" : "As", "operand" : { "type" : "Null" }, "asTypeSpecifier" : { "type" : "ListTypeSpecifier", "elementType" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } } } } ] } } }
[ { "context": "ook.\n# Original idea is from the OpenFB library by Christophe Coenraets https://github.com/ccoenraets/OpenFB\n# rewritten ", "end": 169, "score": 0.9998936057090759, "start": 149, "tag": "NAME", "value": "Christophe Coenraets" }, { "context": "ibrary by Christophe Coen...
www/lib/ngOpenFB/bin/ngOpenFB.coffee
kezarmader/homeRecipes
0
### # ngOpenFB is an angular module that lets you integrate your JavaScript application with Facebook. # Original idea is from the OpenFB library by Christophe Coenraets https://github.com/ccoenraets/OpenFB # rewritten for a better usage with Ionic and Promise support. # # ngOpenFB works for both BROWSER-BASED apps and IONIC apps. # # To use this module you need to install the InAppBrowser plugin by cordova: # https://github.com/apache/cordova-plugin-inappbrowser # Execute 'cordova plugin add cordova-plugin-inappbrowser' # # You also need to install ngCordova: # https://github.com/driftyco/ng-cordova/ # Execute 'bower install ngCordova' # Or at the very least the $cordovaInAppBrowser service # # There is no dependency on the Facebook SDK! # # @author Robert Wettstädt # @version 0.1.3 ### angular.module 'ngOpenFB', ['ngCordova.plugins.inAppBrowser'] .factory '$openFB', [ '$window' '$q' '$rootScope' '$http' '$timeout' '$cordovaInAppBrowser' ( $window, $q, $rootScope, $http, $timeout, $cordovaInAppBrowser ) -> FB_LOGIN_URL = 'https://www.facebook.com/dialog/oauth' FB_LOGOUT_URL = 'https://www.facebook.com/logout.php' ### # By default we store fbtoken in sessionStorage. This can be overridden in init() ### tokenStore = $window.sessionStorage context = $window.location.pathname.substring 0, window.location.pathname.indexOf '/', 2 port = if location.port then ':' + location.port else '' baseURL = "#{location.protocol}//#{location.hostname}#{port}#{context}" ### # By default we use this environments base url for the callback page # and Facebooks default login_succes for the ionic platform. # This can be overriden in init(). # # Take a look at the example oauthcallback.html in this directory. ### browserOauthCallback= baseURL + '/oauthcallback.html' cordovaOauthCallback= 'https://www.facebook.com/connect/login_success.html' runningInCordova = false fbAppId = undefined document.addEventListener 'deviceready', -> runningInCordova = true , false ### # Initializes the ngOpenFB module. You must use this function and initialize the module with an appId before you can # use any other function. # # @param params: Required - Init paramters. # appId : Required - The id of the Facebook app. # tokenStore : Optional - The store used to save the Facebook token. If not provided, we use sessionStorage. # browserOauthCallback : Optional - The URL to the Oauth Callback for the browser. # cordovaOauthCallback : Optional - Tue URL to the Oauth Callback for the ionic app. ### init: ( params ) -> if params.appId fbAppId = params.appId else throw 'appId parameter not set in init()' if params.browserOauthCallback browserOauthCallback = params.browserOauthCallback if params.cordovaOauthCallback cordovaOauthCallback = params.cordovaOauthCallback if params.logoutCallback browserOauthCallback = params.logoutCallback if params.tokenStore tokenStore = params.tokenStore ### # Checks if the user has logged in with ngOpenFB and currently has a session api token. # # @param callback(result): Optional - The function that receives the loginStatus. ### isLoggedIn: ( callback ) -> q = $q.defer() token = tokenStore.fbtoken loginStatus = {} if token? and token isnt 'undefined' loginStatus = status : 'connected' authResponse : token: token q.resolve loginStatus else delete tokenStore.fbtoken loginStatus = status : 'unknown' q.reject loginStatus callback loginStatus if callback q.promise ### # Login to Facebook using OAuth. If running in a Browser, the OAuth workflow happens in a a popup window. # If running in Cordova container, it happens using the In App Browser Plugin. # # @param options: Required - Login options. # scope: Required - The set of Facebook permissions requested (https://developers.facebook.com/docs/facebook-login/permissions/v2.3). # location: Optional - Should the Facebook login window show the location toolbar? Default is true. # @param callback(err, result): Optional - The function to invoke when the login process succeeds. # # @returns promise ### login: ( options, callback ) -> if !options? return throw 'login() requires options paramter' if !options.scope? or typeof options.scope isnt 'string' return throw 'login() options require scope parameter. E.g. "email,user_friends". Find information on scopes here https://developers.facebook.com/docs/facebook-login/permissions/v2.3' q = $q.defer() ### # Inappbrowser load start handler: Used when running in Cordova only ### loadStartHandler = ( evt, event ) => url = event.url if url.indexOf('access_token=') > 0 or url.indexOf('error=') > 0 ### # When we get the access token fast, the login window (inappbrowser) is still opening with animation # in the Cordova app, and trying to close it while it's animating generates an exception. Wait a little... ### timeout = 600 - ( new Date().getTime() - startTime ) $timeout -> $cordovaInAppBrowser.close() , Math.max timeout, 0 loadListener() exitListener() @oauthCallback url, q, callback ### # Inappbrowser exit handler: Used when running in Cordova only ### exitHandler = -> console.log 'exit and remove listeners' ### # Handle the situation where the user closes the login window manually before completing the login process ### error = error: 'user_cancelled' error_description: 'User cancelled login process' error_reason: "user_cancelled" callback error, null if callback q.reject error loadListener() exitListener() if fbAppId? startTime = new Date().getTime() location = 'yes' if options.location? location = if options.location then 'yes' else 'no' if runningInCordova ### # If the app is running in Cordova, listen to URL changes in the InAppBrowser # until we get a URL with an access_token or an error. ### loginUrl = "#{FB_LOGIN_URL}?client_id=#{fbAppId}&redirect_uri=#{cordovaOauthCallback}&response_type=token&scope=#{options.scope}" loadListener = $rootScope.$on '$cordovaInAppBrowser:loadstart', loadStartHandler exitListener = $rootScope.$on '$cordovaInAppBrowser:exit', exitHandler $cordovaInAppBrowser.open loginUrl, '_blank', location: location else ### # Else open a popup window which will - after a successful login - redirect to our callback # where an event on $rootscope will be broadcasted. ### loginUrl = "#{FB_LOGIN_URL}?client_id=#{fbAppId}&redirect_uri=#{browserOauthCallback}&response_type=token&scope=#{options.scope}" window.open loginUrl, '_blank', "location=#{location}" $rootScope.$on 'ngOpenFB:loadend', ( event, url ) => @oauthCallback url, q, callback else ### # Timeout to let the function return the promise first ### $timeout -> loginStatus = status : 'unknown' error : 'Facebook App Id not set' callback loginStatus if callback q.reject loginStatus q.promise ### # Helper function called after successful login including the url of the callback. # # @param url: Required - The oautchRedictURL called by Facebook with the access_token in the querystring. # @param q - Required - The promise to resolve or reject after finishing to parse oautchRedictURL. # @param callback(err, token) - Required - The function to invoke when the login process finishes. # @returns promise ### oauthCallback: ( url, q, callback ) -> ### # Helper function ### parseQueryString = ( queryString ) -> qs = decodeURIComponent queryString obj = {} params = qs.split '&' for param in params splitter = param.split '=' obj[splitter[0]] = splitter[1] obj if 0 < url.indexOf 'access_token=' queryString = url.substr url.indexOf('#') + 1 obj = parseQueryString queryString token = obj['access_token'] tokenStore.fbtoken = token loginStatus = status : 'connected' authResponse : token : obj['access_token'] callback null, token if callback q.resolve token else if 0 < url.indexOf 'error=' queryString = url.substring url.indexOf('?') + 1, url.indexOf('#') obj = parseQueryString queryString loginStatus = status : 'not_authorized' error : obj.error callback loginStatus, null if callback q.reject loginStatus else loginStatus = status : 'not_authorized' callback loginStatus, null if callback q.reject loginStatus ### # Lets you make any Facebook Graph API request. # @param options: Request configuration options. # path : Required - Path in the Facebook graph: /me, /me/friends, etc. # method : Optional - HTTP method: GET, POST, etc. Default is 'GET'. # params : Optional - QueryString parameters as a map # @param callback(err, result): Optional - The function to invoke when the API request finishes. # # @returns promise ### api: ( options, callback ) -> q = $q.defer() ### # Helper function ### toQueryString = ( params ) -> parts = [] for param, value of params if params.hasOwnProperty param parts.push "#{encodeURIComponent(param)}=#{encodeURIComponent(value)}" parts.join '&' params = options.params or {} xhr = new XMLHttpRequest() params['access_token'] = tokenStore.fbtoken query = toQueryString params url = "https://graph.facebook.com#{options.path}?#{query}" $http method : options.method or 'GET' url : url .then ( res ) -> callback null, res if callback q.resolve res.data , ( err ) -> callback err, null if callback q.reject err q.promise ### # De-authorize the app # @param callback(err, result): Optional - The function to invoke when the request finishes. # # @returns promise ### revokePermissions: ( callback ) -> q = $q.defer() @api method : 'DELETE' path : '/me/permissions' .then ( res ) -> tokenStore.fbtoken = undefined callback null, res if callback q.resolve() , ( err ) -> callback err, null if callback q.reject() q.promise ] ###inject:ngCordova###
201583
### # ngOpenFB is an angular module that lets you integrate your JavaScript application with Facebook. # Original idea is from the OpenFB library by <NAME> https://github.com/ccoenraets/OpenFB # rewritten for a better usage with Ionic and Promise support. # # ngOpenFB works for both BROWSER-BASED apps and IONIC apps. # # To use this module you need to install the InAppBrowser plugin by cordova: # https://github.com/apache/cordova-plugin-inappbrowser # Execute 'cordova plugin add cordova-plugin-inappbrowser' # # You also need to install ngCordova: # https://github.com/driftyco/ng-cordova/ # Execute 'bower install ngCordova' # Or at the very least the $cordovaInAppBrowser service # # There is no dependency on the Facebook SDK! # # @author <NAME> # @version 0.1.3 ### angular.module 'ngOpenFB', ['ngCordova.plugins.inAppBrowser'] .factory '$openFB', [ '$window' '$q' '$rootScope' '$http' '$timeout' '$cordovaInAppBrowser' ( $window, $q, $rootScope, $http, $timeout, $cordovaInAppBrowser ) -> FB_LOGIN_URL = 'https://www.facebook.com/dialog/oauth' FB_LOGOUT_URL = 'https://www.facebook.com/logout.php' ### # By default we store fbtoken in sessionStorage. This can be overridden in init() ### tokenStore = $window.sessionStorage context = $window.location.pathname.substring 0, window.location.pathname.indexOf '/', 2 port = if location.port then ':' + location.port else '' baseURL = "#{location.protocol}//#{location.hostname}#{port}#{context}" ### # By default we use this environments base url for the callback page # and Facebooks default login_succes for the ionic platform. # This can be overriden in init(). # # Take a look at the example oauthcallback.html in this directory. ### browserOauthCallback= baseURL + '/oauthcallback.html' cordovaOauthCallback= 'https://www.facebook.com/connect/login_success.html' runningInCordova = false fbAppId = undefined document.addEventListener 'deviceready', -> runningInCordova = true , false ### # Initializes the ngOpenFB module. You must use this function and initialize the module with an appId before you can # use any other function. # # @param params: Required - Init paramters. # appId : Required - The id of the Facebook app. # tokenStore : Optional - The store used to save the Facebook token. If not provided, we use sessionStorage. # browserOauthCallback : Optional - The URL to the Oauth Callback for the browser. # cordovaOauthCallback : Optional - Tue URL to the Oauth Callback for the ionic app. ### init: ( params ) -> if params.appId fbAppId = params.appId else throw 'appId parameter not set in init()' if params.browserOauthCallback browserOauthCallback = params.browserOauthCallback if params.cordovaOauthCallback cordovaOauthCallback = params.cordovaOauthCallback if params.logoutCallback browserOauthCallback = params.logoutCallback if params.tokenStore tokenStore = params.tokenStore ### # Checks if the user has logged in with ngOpenFB and currently has a session api token. # # @param callback(result): Optional - The function that receives the loginStatus. ### isLoggedIn: ( callback ) -> q = $q.defer() token = tokenStore.fbtoken loginStatus = {} if token? and token isnt 'undefined' loginStatus = status : 'connected' authResponse : token: token q.resolve loginStatus else delete tokenStore.fbtoken loginStatus = status : 'unknown' q.reject loginStatus callback loginStatus if callback q.promise ### # Login to Facebook using OAuth. If running in a Browser, the OAuth workflow happens in a a popup window. # If running in Cordova container, it happens using the In App Browser Plugin. # # @param options: Required - Login options. # scope: Required - The set of Facebook permissions requested (https://developers.facebook.com/docs/facebook-login/permissions/v2.3). # location: Optional - Should the Facebook login window show the location toolbar? Default is true. # @param callback(err, result): Optional - The function to invoke when the login process succeeds. # # @returns promise ### login: ( options, callback ) -> if !options? return throw 'login() requires options paramter' if !options.scope? or typeof options.scope isnt 'string' return throw 'login() options require scope parameter. E.g. "email,user_friends". Find information on scopes here https://developers.facebook.com/docs/facebook-login/permissions/v2.3' q = $q.defer() ### # Inappbrowser load start handler: Used when running in Cordova only ### loadStartHandler = ( evt, event ) => url = event.url if url.indexOf('access_token=') > 0 or url.indexOf('error=') > 0 ### # When we get the access token fast, the login window (inappbrowser) is still opening with animation # in the Cordova app, and trying to close it while it's animating generates an exception. Wait a little... ### timeout = 600 - ( new Date().getTime() - startTime ) $timeout -> $cordovaInAppBrowser.close() , Math.max timeout, 0 loadListener() exitListener() @oauthCallback url, q, callback ### # Inappbrowser exit handler: Used when running in Cordova only ### exitHandler = -> console.log 'exit and remove listeners' ### # Handle the situation where the user closes the login window manually before completing the login process ### error = error: 'user_cancelled' error_description: 'User cancelled login process' error_reason: "user_cancelled" callback error, null if callback q.reject error loadListener() exitListener() if fbAppId? startTime = new Date().getTime() location = 'yes' if options.location? location = if options.location then 'yes' else 'no' if runningInCordova ### # If the app is running in Cordova, listen to URL changes in the InAppBrowser # until we get a URL with an access_token or an error. ### loginUrl = "#{FB_LOGIN_URL}?client_id=#{fbAppId}&redirect_uri=#{cordovaOauthCallback}&response_type=token&scope=#{options.scope}" loadListener = $rootScope.$on '$cordovaInAppBrowser:loadstart', loadStartHandler exitListener = $rootScope.$on '$cordovaInAppBrowser:exit', exitHandler $cordovaInAppBrowser.open loginUrl, '_blank', location: location else ### # Else open a popup window which will - after a successful login - redirect to our callback # where an event on $rootscope will be broadcasted. ### loginUrl = "#{FB_LOGIN_URL}?client_id=#{fbAppId}&redirect_uri=#{browserOauthCallback}&response_type=token&scope=#{options.scope}" window.open loginUrl, '_blank', "location=#{location}" $rootScope.$on 'ngOpenFB:loadend', ( event, url ) => @oauthCallback url, q, callback else ### # Timeout to let the function return the promise first ### $timeout -> loginStatus = status : 'unknown' error : 'Facebook App Id not set' callback loginStatus if callback q.reject loginStatus q.promise ### # Helper function called after successful login including the url of the callback. # # @param url: Required - The oautchRedictURL called by Facebook with the access_token in the querystring. # @param q - Required - The promise to resolve or reject after finishing to parse oautchRedictURL. # @param callback(err, token) - Required - The function to invoke when the login process finishes. # @returns promise ### oauthCallback: ( url, q, callback ) -> ### # Helper function ### parseQueryString = ( queryString ) -> qs = decodeURIComponent queryString obj = {} params = qs.split '&' for param in params splitter = param.split '=' obj[splitter[0]] = splitter[1] obj if 0 < url.indexOf 'access_token=' queryString = url.substr url.indexOf('#') + 1 obj = parseQueryString queryString token = obj['access_token'] tokenStore.fbtoken = token loginStatus = status : 'connected' authResponse : token : obj['access_token'] callback null, token if callback q.resolve token else if 0 < url.indexOf 'error=' queryString = url.substring url.indexOf('?') + 1, url.indexOf('#') obj = parseQueryString queryString loginStatus = status : 'not_authorized' error : obj.error callback loginStatus, null if callback q.reject loginStatus else loginStatus = status : 'not_authorized' callback loginStatus, null if callback q.reject loginStatus ### # Lets you make any Facebook Graph API request. # @param options: Request configuration options. # path : Required - Path in the Facebook graph: /me, /me/friends, etc. # method : Optional - HTTP method: GET, POST, etc. Default is 'GET'. # params : Optional - QueryString parameters as a map # @param callback(err, result): Optional - The function to invoke when the API request finishes. # # @returns promise ### api: ( options, callback ) -> q = $q.defer() ### # Helper function ### toQueryString = ( params ) -> parts = [] for param, value of params if params.hasOwnProperty param parts.push "#{encodeURIComponent(param)}=#{encodeURIComponent(value)}" parts.join '&' params = options.params or {} xhr = new XMLHttpRequest() params['access_token'] = tokenStore.fbtoken query = toQueryString params url = "https://graph.facebook.com#{options.path}?#{query}" $http method : options.method or 'GET' url : url .then ( res ) -> callback null, res if callback q.resolve res.data , ( err ) -> callback err, null if callback q.reject err q.promise ### # De-authorize the app # @param callback(err, result): Optional - The function to invoke when the request finishes. # # @returns promise ### revokePermissions: ( callback ) -> q = $q.defer() @api method : 'DELETE' path : '/me/permissions' .then ( res ) -> tokenStore.fbtoken = undefined callback null, res if callback q.resolve() , ( err ) -> callback err, null if callback q.reject() q.promise ] ###inject:ngCordova###
true
### # ngOpenFB is an angular module that lets you integrate your JavaScript application with Facebook. # Original idea is from the OpenFB library by PI:NAME:<NAME>END_PI https://github.com/ccoenraets/OpenFB # rewritten for a better usage with Ionic and Promise support. # # ngOpenFB works for both BROWSER-BASED apps and IONIC apps. # # To use this module you need to install the InAppBrowser plugin by cordova: # https://github.com/apache/cordova-plugin-inappbrowser # Execute 'cordova plugin add cordova-plugin-inappbrowser' # # You also need to install ngCordova: # https://github.com/driftyco/ng-cordova/ # Execute 'bower install ngCordova' # Or at the very least the $cordovaInAppBrowser service # # There is no dependency on the Facebook SDK! # # @author PI:NAME:<NAME>END_PI # @version 0.1.3 ### angular.module 'ngOpenFB', ['ngCordova.plugins.inAppBrowser'] .factory '$openFB', [ '$window' '$q' '$rootScope' '$http' '$timeout' '$cordovaInAppBrowser' ( $window, $q, $rootScope, $http, $timeout, $cordovaInAppBrowser ) -> FB_LOGIN_URL = 'https://www.facebook.com/dialog/oauth' FB_LOGOUT_URL = 'https://www.facebook.com/logout.php' ### # By default we store fbtoken in sessionStorage. This can be overridden in init() ### tokenStore = $window.sessionStorage context = $window.location.pathname.substring 0, window.location.pathname.indexOf '/', 2 port = if location.port then ':' + location.port else '' baseURL = "#{location.protocol}//#{location.hostname}#{port}#{context}" ### # By default we use this environments base url for the callback page # and Facebooks default login_succes for the ionic platform. # This can be overriden in init(). # # Take a look at the example oauthcallback.html in this directory. ### browserOauthCallback= baseURL + '/oauthcallback.html' cordovaOauthCallback= 'https://www.facebook.com/connect/login_success.html' runningInCordova = false fbAppId = undefined document.addEventListener 'deviceready', -> runningInCordova = true , false ### # Initializes the ngOpenFB module. You must use this function and initialize the module with an appId before you can # use any other function. # # @param params: Required - Init paramters. # appId : Required - The id of the Facebook app. # tokenStore : Optional - The store used to save the Facebook token. If not provided, we use sessionStorage. # browserOauthCallback : Optional - The URL to the Oauth Callback for the browser. # cordovaOauthCallback : Optional - Tue URL to the Oauth Callback for the ionic app. ### init: ( params ) -> if params.appId fbAppId = params.appId else throw 'appId parameter not set in init()' if params.browserOauthCallback browserOauthCallback = params.browserOauthCallback if params.cordovaOauthCallback cordovaOauthCallback = params.cordovaOauthCallback if params.logoutCallback browserOauthCallback = params.logoutCallback if params.tokenStore tokenStore = params.tokenStore ### # Checks if the user has logged in with ngOpenFB and currently has a session api token. # # @param callback(result): Optional - The function that receives the loginStatus. ### isLoggedIn: ( callback ) -> q = $q.defer() token = tokenStore.fbtoken loginStatus = {} if token? and token isnt 'undefined' loginStatus = status : 'connected' authResponse : token: token q.resolve loginStatus else delete tokenStore.fbtoken loginStatus = status : 'unknown' q.reject loginStatus callback loginStatus if callback q.promise ### # Login to Facebook using OAuth. If running in a Browser, the OAuth workflow happens in a a popup window. # If running in Cordova container, it happens using the In App Browser Plugin. # # @param options: Required - Login options. # scope: Required - The set of Facebook permissions requested (https://developers.facebook.com/docs/facebook-login/permissions/v2.3). # location: Optional - Should the Facebook login window show the location toolbar? Default is true. # @param callback(err, result): Optional - The function to invoke when the login process succeeds. # # @returns promise ### login: ( options, callback ) -> if !options? return throw 'login() requires options paramter' if !options.scope? or typeof options.scope isnt 'string' return throw 'login() options require scope parameter. E.g. "email,user_friends". Find information on scopes here https://developers.facebook.com/docs/facebook-login/permissions/v2.3' q = $q.defer() ### # Inappbrowser load start handler: Used when running in Cordova only ### loadStartHandler = ( evt, event ) => url = event.url if url.indexOf('access_token=') > 0 or url.indexOf('error=') > 0 ### # When we get the access token fast, the login window (inappbrowser) is still opening with animation # in the Cordova app, and trying to close it while it's animating generates an exception. Wait a little... ### timeout = 600 - ( new Date().getTime() - startTime ) $timeout -> $cordovaInAppBrowser.close() , Math.max timeout, 0 loadListener() exitListener() @oauthCallback url, q, callback ### # Inappbrowser exit handler: Used when running in Cordova only ### exitHandler = -> console.log 'exit and remove listeners' ### # Handle the situation where the user closes the login window manually before completing the login process ### error = error: 'user_cancelled' error_description: 'User cancelled login process' error_reason: "user_cancelled" callback error, null if callback q.reject error loadListener() exitListener() if fbAppId? startTime = new Date().getTime() location = 'yes' if options.location? location = if options.location then 'yes' else 'no' if runningInCordova ### # If the app is running in Cordova, listen to URL changes in the InAppBrowser # until we get a URL with an access_token or an error. ### loginUrl = "#{FB_LOGIN_URL}?client_id=#{fbAppId}&redirect_uri=#{cordovaOauthCallback}&response_type=token&scope=#{options.scope}" loadListener = $rootScope.$on '$cordovaInAppBrowser:loadstart', loadStartHandler exitListener = $rootScope.$on '$cordovaInAppBrowser:exit', exitHandler $cordovaInAppBrowser.open loginUrl, '_blank', location: location else ### # Else open a popup window which will - after a successful login - redirect to our callback # where an event on $rootscope will be broadcasted. ### loginUrl = "#{FB_LOGIN_URL}?client_id=#{fbAppId}&redirect_uri=#{browserOauthCallback}&response_type=token&scope=#{options.scope}" window.open loginUrl, '_blank', "location=#{location}" $rootScope.$on 'ngOpenFB:loadend', ( event, url ) => @oauthCallback url, q, callback else ### # Timeout to let the function return the promise first ### $timeout -> loginStatus = status : 'unknown' error : 'Facebook App Id not set' callback loginStatus if callback q.reject loginStatus q.promise ### # Helper function called after successful login including the url of the callback. # # @param url: Required - The oautchRedictURL called by Facebook with the access_token in the querystring. # @param q - Required - The promise to resolve or reject after finishing to parse oautchRedictURL. # @param callback(err, token) - Required - The function to invoke when the login process finishes. # @returns promise ### oauthCallback: ( url, q, callback ) -> ### # Helper function ### parseQueryString = ( queryString ) -> qs = decodeURIComponent queryString obj = {} params = qs.split '&' for param in params splitter = param.split '=' obj[splitter[0]] = splitter[1] obj if 0 < url.indexOf 'access_token=' queryString = url.substr url.indexOf('#') + 1 obj = parseQueryString queryString token = obj['access_token'] tokenStore.fbtoken = token loginStatus = status : 'connected' authResponse : token : obj['access_token'] callback null, token if callback q.resolve token else if 0 < url.indexOf 'error=' queryString = url.substring url.indexOf('?') + 1, url.indexOf('#') obj = parseQueryString queryString loginStatus = status : 'not_authorized' error : obj.error callback loginStatus, null if callback q.reject loginStatus else loginStatus = status : 'not_authorized' callback loginStatus, null if callback q.reject loginStatus ### # Lets you make any Facebook Graph API request. # @param options: Request configuration options. # path : Required - Path in the Facebook graph: /me, /me/friends, etc. # method : Optional - HTTP method: GET, POST, etc. Default is 'GET'. # params : Optional - QueryString parameters as a map # @param callback(err, result): Optional - The function to invoke when the API request finishes. # # @returns promise ### api: ( options, callback ) -> q = $q.defer() ### # Helper function ### toQueryString = ( params ) -> parts = [] for param, value of params if params.hasOwnProperty param parts.push "#{encodeURIComponent(param)}=#{encodeURIComponent(value)}" parts.join '&' params = options.params or {} xhr = new XMLHttpRequest() params['access_token'] = tokenStore.fbtoken query = toQueryString params url = "https://graph.facebook.com#{options.path}?#{query}" $http method : options.method or 'GET' url : url .then ( res ) -> callback null, res if callback q.resolve res.data , ( err ) -> callback err, null if callback q.reject err q.promise ### # De-authorize the app # @param callback(err, result): Optional - The function to invoke when the request finishes. # # @returns promise ### revokePermissions: ( callback ) -> q = $q.defer() @api method : 'DELETE' path : '/me/permissions' .then ( res ) -> tokenStore.fbtoken = undefined callback null, res if callback q.resolve() , ( err ) -> callback err, null if callback q.reject() q.promise ] ###inject:ngCordova###
[ { "context": "---------------------------------\n# Copyright 2013 I.B.M.\n# \n# Licensed under the Apache License, Version 2", "end": 1509, "score": 0.9996060729026794, "start": 1504, "tag": "NAME", "value": "I.B.M" } ]
tools/split-sourcemap-data-url.coffee
pmuellr/nodprof
6
# Licensed under the Apache License. See footer for details. fs = require "fs" path = require "path" PROGRAM = path.basename(__filename) iFileName = process.argv[2] oFileName = "#{iFileName}.map" # console.log "#{PROGRAM} #{iFileName} -> #{oFileName}" iFile = fs.readFileSync iFileName, "utf8" match = iFile.match /\n\/\/. sourceMappingURL=data:application\/json;base64,(.*)\n/ if !match? console.log "no sourcemap in file" process.exit() data64 = match[1] data = new Buffer(data64, "base64").toString("ascii") data = JSON.parse(data) cwd = process.cwd() sources = data.sources newSources = [] for source in sources source = path.relative(cwd, source) match = source.match /node_modules\/browserify\/node_modules(.*)/ if match source = match[1] match = source.match /www\/scripts\/(.*)/ if match source = match[1] newSources.push source data.sources = newSources data = JSON.stringify data, null, 4 oFileBaseName = path.basename oFileName regex = /\n\/\/. sourceMappingURL=data:application\/json;base64,(.*)\n/ repl = "\n//# sourceMappingURL=#{oFileBaseName}\n" iFile = iFile.replace regex, repl fs.writeFileSync iFileName, iFile fs.writeFileSync oFileName, data # console.log "#{PROGRAM} rewrote, removing data url: #{iFileName}" # console.log "#{PROGRAM} generated new source map: #{oFileName}" #------------------------------------------------------------------------------- # Copyright 2013 I.B.M. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------------
82884
# Licensed under the Apache License. See footer for details. fs = require "fs" path = require "path" PROGRAM = path.basename(__filename) iFileName = process.argv[2] oFileName = "#{iFileName}.map" # console.log "#{PROGRAM} #{iFileName} -> #{oFileName}" iFile = fs.readFileSync iFileName, "utf8" match = iFile.match /\n\/\/. sourceMappingURL=data:application\/json;base64,(.*)\n/ if !match? console.log "no sourcemap in file" process.exit() data64 = match[1] data = new Buffer(data64, "base64").toString("ascii") data = JSON.parse(data) cwd = process.cwd() sources = data.sources newSources = [] for source in sources source = path.relative(cwd, source) match = source.match /node_modules\/browserify\/node_modules(.*)/ if match source = match[1] match = source.match /www\/scripts\/(.*)/ if match source = match[1] newSources.push source data.sources = newSources data = JSON.stringify data, null, 4 oFileBaseName = path.basename oFileName regex = /\n\/\/. sourceMappingURL=data:application\/json;base64,(.*)\n/ repl = "\n//# sourceMappingURL=#{oFileBaseName}\n" iFile = iFile.replace regex, repl fs.writeFileSync iFileName, iFile fs.writeFileSync oFileName, data # console.log "#{PROGRAM} rewrote, removing data url: #{iFileName}" # console.log "#{PROGRAM} generated new source map: #{oFileName}" #------------------------------------------------------------------------------- # Copyright 2013 <NAME>. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------------
true
# Licensed under the Apache License. See footer for details. fs = require "fs" path = require "path" PROGRAM = path.basename(__filename) iFileName = process.argv[2] oFileName = "#{iFileName}.map" # console.log "#{PROGRAM} #{iFileName} -> #{oFileName}" iFile = fs.readFileSync iFileName, "utf8" match = iFile.match /\n\/\/. sourceMappingURL=data:application\/json;base64,(.*)\n/ if !match? console.log "no sourcemap in file" process.exit() data64 = match[1] data = new Buffer(data64, "base64").toString("ascii") data = JSON.parse(data) cwd = process.cwd() sources = data.sources newSources = [] for source in sources source = path.relative(cwd, source) match = source.match /node_modules\/browserify\/node_modules(.*)/ if match source = match[1] match = source.match /www\/scripts\/(.*)/ if match source = match[1] newSources.push source data.sources = newSources data = JSON.stringify data, null, 4 oFileBaseName = path.basename oFileName regex = /\n\/\/. sourceMappingURL=data:application\/json;base64,(.*)\n/ repl = "\n//# sourceMappingURL=#{oFileBaseName}\n" iFile = iFile.replace regex, repl fs.writeFileSync iFileName, iFile fs.writeFileSync oFileName, data # console.log "#{PROGRAM} rewrote, removing data url: #{iFileName}" # console.log "#{PROGRAM} generated new source map: #{oFileName}" #------------------------------------------------------------------------------- # Copyright 2013 PI:NAME:<NAME>END_PI. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------------
[ { "context": "= $second\n $rest = $others\n\n$contenders = [\n \"Michael Phelps\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"", "end": 180, "score": 0.9998226761817932, "start": 166, "tag": "NAME", "value": "Michael Phelps" }, { "context": " = $others\n\n$contende...
documentation/coffee/splats.coffee
zeel-dev/copheescript
3
$gold = $silver = $rest = "unknown" $awardMedals = ( $first, $second, $others... ) -> $gold = $first $silver = $second $rest = $others $contenders = [ "Michael Phelps" "Liu Xiang" "Yao Ming" "Allyson Felix" "Shawn Johnson" "Roman Sebrle" "Guo Jingjing" "Tyson Gay" "Asafa Powell" "Usain Bolt" ] $awardMedals $contenders... echo "Gold: " + $gold echo "Silver: " + $silver echo "The Field: " + $rest
90716
$gold = $silver = $rest = "unknown" $awardMedals = ( $first, $second, $others... ) -> $gold = $first $silver = $second $rest = $others $contenders = [ "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" ] $awardMedals $contenders... echo "Gold: " + $gold echo "Silver: " + $silver echo "The Field: " + $rest
true
$gold = $silver = $rest = "unknown" $awardMedals = ( $first, $second, $others... ) -> $gold = $first $silver = $second $rest = $others $contenders = [ "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" ] $awardMedals $contenders... echo "Gold: " + $gold echo "Silver: " + $silver echo "The Field: " + $rest
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9985968470573425, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-http-dns-error.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. do_not_call = -> throw new Error("This function should not have been called.")return test = (mod) -> expected_bad_requests += 2 # Bad host name should not throw an uncatchable exception. # Ensure that there is time to attach an error listener. req = mod.get( host: host port: 42 , do_not_call) req.on "error", (err) -> assert.equal err.code, "ENOTFOUND" actual_bad_requests++ return # http.get() called req.end() for us req = mod.request( method: "GET" host: host port: 42 , do_not_call) req.on "error", (err) -> assert.equal err.code, "ENOTFOUND" actual_bad_requests++ return req.end() return common = require("../common") assert = require("assert") http = require("http") https = require("https") expected_bad_requests = 0 actual_bad_requests = 0 host = "********" host += host host += host host += host host += host host += host test https test http process.on "exit", -> assert.equal actual_bad_requests, expected_bad_requests return
113624
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. do_not_call = -> throw new Error("This function should not have been called.")return test = (mod) -> expected_bad_requests += 2 # Bad host name should not throw an uncatchable exception. # Ensure that there is time to attach an error listener. req = mod.get( host: host port: 42 , do_not_call) req.on "error", (err) -> assert.equal err.code, "ENOTFOUND" actual_bad_requests++ return # http.get() called req.end() for us req = mod.request( method: "GET" host: host port: 42 , do_not_call) req.on "error", (err) -> assert.equal err.code, "ENOTFOUND" actual_bad_requests++ return req.end() return common = require("../common") assert = require("assert") http = require("http") https = require("https") expected_bad_requests = 0 actual_bad_requests = 0 host = "********" host += host host += host host += host host += host host += host test https test http process.on "exit", -> assert.equal actual_bad_requests, expected_bad_requests return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. do_not_call = -> throw new Error("This function should not have been called.")return test = (mod) -> expected_bad_requests += 2 # Bad host name should not throw an uncatchable exception. # Ensure that there is time to attach an error listener. req = mod.get( host: host port: 42 , do_not_call) req.on "error", (err) -> assert.equal err.code, "ENOTFOUND" actual_bad_requests++ return # http.get() called req.end() for us req = mod.request( method: "GET" host: host port: 42 , do_not_call) req.on "error", (err) -> assert.equal err.code, "ENOTFOUND" actual_bad_requests++ return req.end() return common = require("../common") assert = require("assert") http = require("http") https = require("https") expected_bad_requests = 0 actual_bad_requests = 0 host = "********" host += host host += host host += host host += host host += host test https test http process.on "exit", -> assert.equal actual_bad_requests, expected_bad_requests return
[ { "context": "ponents to be written as a pure function\n# @author Yannick Croissant\n###\n'use strict'\n\n# -----------------------------", "end": 110, "score": 0.9998422265052795, "start": 93, "tag": "NAME", "value": "Yannick Croissant" } ]
src/tests/rules/prefer-stateless-function.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Enforce stateless components to be written as a pure function # @author Yannick Croissant ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/prefer-stateless-function' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'prefer-stateless-function', rule, valid: [ # Already a stateless function code: ''' Foo = (props) -> return <div>{props.foo}</div> ''' , # Already a stateless (arrow) function code: 'Foo = ({foo}) => <div>{foo}</div>' , # Extends from PureComponent and uses props code: ''' class Foo extends React.PureComponent render: -> return <div>{this.props.foo}</div> ''' options: [ignorePureComponents: yes] , # Extends from PureComponent and uses context code: ''' class Foo extends React.PureComponent render: -> return <div>{this.context.foo}</div> ''' options: [ignorePureComponents: yes] , # Extends from PureComponent in an expression context. code: ''' Foo = class extends React.PureComponent render: -> return <div>{this.props.foo}</div> ''' options: [ignorePureComponents: yes] , # Has a lifecyle method code: ''' class Foo extends React.Component shouldComponentUpdate: -> return false render: -> return <div>{this.props.foo}</div> ''' , # Has a state code: ''' class Foo extends React.Component changeState: -> this.setState({foo: "clicked"}) render: -> return <div onClick={this.changeState.bind(this)}>{this.state.foo || "bar"}</div> ''' , # Use refs code: ''' class Foo extends React.Component doStuff: -> this.refs.foo.style.backgroundColor = "red" render: -> return <div ref="foo" onClick={this.doStuff}>{this.props.foo}</div> ''' , # Has an additional method code: ''' class Foo extends React.Component doStuff: -> render: -> return <div>{this.props.foo}</div> ''' , # Has an empty (no super) constructor code: ''' class Foo extends React.Component constructor: -> render: -> return <div>{this.props.foo}</div> ''' , # Has a constructor code: ''' class Foo extends React.Component constructor: -> doSpecialStuffs() render: -> return <div>{this.props.foo}</div> ''' , # Has a constructor (2) code: ''' class Foo extends React.Component constructor: -> foo render: -> return <div>{this.props.foo}</div> ''' , # Use this.bar code: ''' class Foo extends React.Component render: -> <div>{@bar}</div> ''' , # parser: 'babel-eslint' # Use this.bar (destructuring) code: ''' class Foo extends React.Component render: -> {props:{foo}, bar} = this return <div>{foo}</div> ''' , # parser: 'babel-eslint' # Use this[bar] code: ''' class Foo extends React.Component render: -> return <div>{this[bar]}</div> ''' , # parser: 'babel-eslint' # Use this['bar'] code: ''' class Foo extends React.Component render: -> return <div>{this['bar']}</div> ''' , # parser: 'babel-eslint' # Can return null (ES6, React 0.14.0) code: ''' class Foo extends React.Component render: -> if (!this.props.foo) return null ''' # parser: 'babel-eslint' settings: react: version: '0.14.0' , # Can return null (ES5, React 0.14.0) code: ''' Foo = createReactClass({ render: -> if (!this.props.foo) return null return <div>{this.props.foo}</div> }) ''' settings: react: version: '0.14.0' , # Can return null (shorthand if in return, React 0.14.0) code: ''' class Foo extends React.Component render: -> return if true then <div /> else null ''' # parser: 'babel-eslint' settings: react: version: '0.14.0' , code: ''' export default (Component) => ( class Test extends React.Component componentDidMount: -> render: -> return <Component /> ) ''' , # parser: 'babel-eslint' # Has childContextTypes code: ''' class Foo extends React.Component render: -> return <div>{this.props.children}</div> Foo.childContextTypes = { color: PropTypes.string } ''' # parser: 'babel-eslint' ] invalid: [ # Only use this.props code: ''' class Foo extends React.Component render: -> <div>{@props.foo}</div> ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component render: -> return <div>{this['props'].foo}</div> ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.PureComponent render: -> return <div>foo</div> ''' options: [ignorePureComponents: yes] errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.PureComponent render: -> return <div>{this.props.foo}</div> ''' errors: [message: 'Component should be written as a pure function'] , # , # code: """ # class Foo extends React.Component { # static get displayName() { # return 'Foo' # } # render() { # return <div>{this.props.foo}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: 'Component should be written as a pure function'] code: ''' class Foo extends React.Component @displayName = 'Foo' render: -> return <div>{this.props.foo}</div> ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , # , # code: """ # class Foo extends React.Component { # static get propTypes() { # return { # name: PropTypes.string # } # } # render() { # return <div>{this.props.foo}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: 'Component should be written as a pure function'] code: ''' class Foo extends React.Component @propTypes = { name: PropTypes.string } render: -> return <div>{this.props.foo}</div> ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component constructor: -> super() render: -> return <div>{this.props.foo}</div> ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component render: -> {props:{foo}, context:{bar}} = this return <div>{this.props.foo}</div> ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component render: -> return null unless @props.foo ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , code: ''' Foo = createReactClass({ render: -> if (!this.props.foo) return null return <div>{this.props.foo}</div> }) ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component render: -> return if true then <div /> else null ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component @defaultProps = { foo: true } render: -> { foo } = this.props return if foo then <div /> else null ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , # , # code: """ # class Foo extends React.Component { # static get defaultProps() { # return { # foo: true # } # } # render() { # { foo } = this.props # return foo ? <div /> : null # } # } # """ # errors: [message: 'Component should be written as a pure function'] code: ''' class Foo extends React.Component render: -> { foo } = this.props return if foo then <div /> else null Foo.defaultProps = { foo: true } ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component @contextTypes = { foo: PropTypes.boolean } render: -> { foo } = this.context return if foo then <div /> else null ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , # , # code: """ # class Foo extends React.Component { # static get contextTypes() { # return { # foo: PropTypes.boolean # } # } # render() { # { foo } = this.context # return foo ? <div /> : null # } # } # """ # errors: [message: 'Component should be written as a pure function'] code: ''' class Foo extends React.Component render: -> { foo } = this.context return if foo then <div /> else null Foo.contextTypes = { foo: PropTypes.boolean } ''' errors: [message: 'Component should be written as a pure function'] ]
85020
###* # @fileoverview Enforce stateless components to be written as a pure function # @author <NAME> ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/prefer-stateless-function' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'prefer-stateless-function', rule, valid: [ # Already a stateless function code: ''' Foo = (props) -> return <div>{props.foo}</div> ''' , # Already a stateless (arrow) function code: 'Foo = ({foo}) => <div>{foo}</div>' , # Extends from PureComponent and uses props code: ''' class Foo extends React.PureComponent render: -> return <div>{this.props.foo}</div> ''' options: [ignorePureComponents: yes] , # Extends from PureComponent and uses context code: ''' class Foo extends React.PureComponent render: -> return <div>{this.context.foo}</div> ''' options: [ignorePureComponents: yes] , # Extends from PureComponent in an expression context. code: ''' Foo = class extends React.PureComponent render: -> return <div>{this.props.foo}</div> ''' options: [ignorePureComponents: yes] , # Has a lifecyle method code: ''' class Foo extends React.Component shouldComponentUpdate: -> return false render: -> return <div>{this.props.foo}</div> ''' , # Has a state code: ''' class Foo extends React.Component changeState: -> this.setState({foo: "clicked"}) render: -> return <div onClick={this.changeState.bind(this)}>{this.state.foo || "bar"}</div> ''' , # Use refs code: ''' class Foo extends React.Component doStuff: -> this.refs.foo.style.backgroundColor = "red" render: -> return <div ref="foo" onClick={this.doStuff}>{this.props.foo}</div> ''' , # Has an additional method code: ''' class Foo extends React.Component doStuff: -> render: -> return <div>{this.props.foo}</div> ''' , # Has an empty (no super) constructor code: ''' class Foo extends React.Component constructor: -> render: -> return <div>{this.props.foo}</div> ''' , # Has a constructor code: ''' class Foo extends React.Component constructor: -> doSpecialStuffs() render: -> return <div>{this.props.foo}</div> ''' , # Has a constructor (2) code: ''' class Foo extends React.Component constructor: -> foo render: -> return <div>{this.props.foo}</div> ''' , # Use this.bar code: ''' class Foo extends React.Component render: -> <div>{@bar}</div> ''' , # parser: 'babel-eslint' # Use this.bar (destructuring) code: ''' class Foo extends React.Component render: -> {props:{foo}, bar} = this return <div>{foo}</div> ''' , # parser: 'babel-eslint' # Use this[bar] code: ''' class Foo extends React.Component render: -> return <div>{this[bar]}</div> ''' , # parser: 'babel-eslint' # Use this['bar'] code: ''' class Foo extends React.Component render: -> return <div>{this['bar']}</div> ''' , # parser: 'babel-eslint' # Can return null (ES6, React 0.14.0) code: ''' class Foo extends React.Component render: -> if (!this.props.foo) return null ''' # parser: 'babel-eslint' settings: react: version: '0.14.0' , # Can return null (ES5, React 0.14.0) code: ''' Foo = createReactClass({ render: -> if (!this.props.foo) return null return <div>{this.props.foo}</div> }) ''' settings: react: version: '0.14.0' , # Can return null (shorthand if in return, React 0.14.0) code: ''' class Foo extends React.Component render: -> return if true then <div /> else null ''' # parser: 'babel-eslint' settings: react: version: '0.14.0' , code: ''' export default (Component) => ( class Test extends React.Component componentDidMount: -> render: -> return <Component /> ) ''' , # parser: 'babel-eslint' # Has childContextTypes code: ''' class Foo extends React.Component render: -> return <div>{this.props.children}</div> Foo.childContextTypes = { color: PropTypes.string } ''' # parser: 'babel-eslint' ] invalid: [ # Only use this.props code: ''' class Foo extends React.Component render: -> <div>{@props.foo}</div> ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component render: -> return <div>{this['props'].foo}</div> ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.PureComponent render: -> return <div>foo</div> ''' options: [ignorePureComponents: yes] errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.PureComponent render: -> return <div>{this.props.foo}</div> ''' errors: [message: 'Component should be written as a pure function'] , # , # code: """ # class Foo extends React.Component { # static get displayName() { # return 'Foo' # } # render() { # return <div>{this.props.foo}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: 'Component should be written as a pure function'] code: ''' class Foo extends React.Component @displayName = 'Foo' render: -> return <div>{this.props.foo}</div> ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , # , # code: """ # class Foo extends React.Component { # static get propTypes() { # return { # name: PropTypes.string # } # } # render() { # return <div>{this.props.foo}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: 'Component should be written as a pure function'] code: ''' class Foo extends React.Component @propTypes = { name: PropTypes.string } render: -> return <div>{this.props.foo}</div> ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component constructor: -> super() render: -> return <div>{this.props.foo}</div> ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component render: -> {props:{foo}, context:{bar}} = this return <div>{this.props.foo}</div> ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component render: -> return null unless @props.foo ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , code: ''' Foo = createReactClass({ render: -> if (!this.props.foo) return null return <div>{this.props.foo}</div> }) ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component render: -> return if true then <div /> else null ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component @defaultProps = { foo: true } render: -> { foo } = this.props return if foo then <div /> else null ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , # , # code: """ # class Foo extends React.Component { # static get defaultProps() { # return { # foo: true # } # } # render() { # { foo } = this.props # return foo ? <div /> : null # } # } # """ # errors: [message: 'Component should be written as a pure function'] code: ''' class Foo extends React.Component render: -> { foo } = this.props return if foo then <div /> else null Foo.defaultProps = { foo: true } ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component @contextTypes = { foo: PropTypes.boolean } render: -> { foo } = this.context return if foo then <div /> else null ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , # , # code: """ # class Foo extends React.Component { # static get contextTypes() { # return { # foo: PropTypes.boolean # } # } # render() { # { foo } = this.context # return foo ? <div /> : null # } # } # """ # errors: [message: 'Component should be written as a pure function'] code: ''' class Foo extends React.Component render: -> { foo } = this.context return if foo then <div /> else null Foo.contextTypes = { foo: PropTypes.boolean } ''' errors: [message: 'Component should be written as a pure function'] ]
true
###* # @fileoverview Enforce stateless components to be written as a pure function # @author PI:NAME:<NAME>END_PI ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/prefer-stateless-function' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'prefer-stateless-function', rule, valid: [ # Already a stateless function code: ''' Foo = (props) -> return <div>{props.foo}</div> ''' , # Already a stateless (arrow) function code: 'Foo = ({foo}) => <div>{foo}</div>' , # Extends from PureComponent and uses props code: ''' class Foo extends React.PureComponent render: -> return <div>{this.props.foo}</div> ''' options: [ignorePureComponents: yes] , # Extends from PureComponent and uses context code: ''' class Foo extends React.PureComponent render: -> return <div>{this.context.foo}</div> ''' options: [ignorePureComponents: yes] , # Extends from PureComponent in an expression context. code: ''' Foo = class extends React.PureComponent render: -> return <div>{this.props.foo}</div> ''' options: [ignorePureComponents: yes] , # Has a lifecyle method code: ''' class Foo extends React.Component shouldComponentUpdate: -> return false render: -> return <div>{this.props.foo}</div> ''' , # Has a state code: ''' class Foo extends React.Component changeState: -> this.setState({foo: "clicked"}) render: -> return <div onClick={this.changeState.bind(this)}>{this.state.foo || "bar"}</div> ''' , # Use refs code: ''' class Foo extends React.Component doStuff: -> this.refs.foo.style.backgroundColor = "red" render: -> return <div ref="foo" onClick={this.doStuff}>{this.props.foo}</div> ''' , # Has an additional method code: ''' class Foo extends React.Component doStuff: -> render: -> return <div>{this.props.foo}</div> ''' , # Has an empty (no super) constructor code: ''' class Foo extends React.Component constructor: -> render: -> return <div>{this.props.foo}</div> ''' , # Has a constructor code: ''' class Foo extends React.Component constructor: -> doSpecialStuffs() render: -> return <div>{this.props.foo}</div> ''' , # Has a constructor (2) code: ''' class Foo extends React.Component constructor: -> foo render: -> return <div>{this.props.foo}</div> ''' , # Use this.bar code: ''' class Foo extends React.Component render: -> <div>{@bar}</div> ''' , # parser: 'babel-eslint' # Use this.bar (destructuring) code: ''' class Foo extends React.Component render: -> {props:{foo}, bar} = this return <div>{foo}</div> ''' , # parser: 'babel-eslint' # Use this[bar] code: ''' class Foo extends React.Component render: -> return <div>{this[bar]}</div> ''' , # parser: 'babel-eslint' # Use this['bar'] code: ''' class Foo extends React.Component render: -> return <div>{this['bar']}</div> ''' , # parser: 'babel-eslint' # Can return null (ES6, React 0.14.0) code: ''' class Foo extends React.Component render: -> if (!this.props.foo) return null ''' # parser: 'babel-eslint' settings: react: version: '0.14.0' , # Can return null (ES5, React 0.14.0) code: ''' Foo = createReactClass({ render: -> if (!this.props.foo) return null return <div>{this.props.foo}</div> }) ''' settings: react: version: '0.14.0' , # Can return null (shorthand if in return, React 0.14.0) code: ''' class Foo extends React.Component render: -> return if true then <div /> else null ''' # parser: 'babel-eslint' settings: react: version: '0.14.0' , code: ''' export default (Component) => ( class Test extends React.Component componentDidMount: -> render: -> return <Component /> ) ''' , # parser: 'babel-eslint' # Has childContextTypes code: ''' class Foo extends React.Component render: -> return <div>{this.props.children}</div> Foo.childContextTypes = { color: PropTypes.string } ''' # parser: 'babel-eslint' ] invalid: [ # Only use this.props code: ''' class Foo extends React.Component render: -> <div>{@props.foo}</div> ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component render: -> return <div>{this['props'].foo}</div> ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.PureComponent render: -> return <div>foo</div> ''' options: [ignorePureComponents: yes] errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.PureComponent render: -> return <div>{this.props.foo}</div> ''' errors: [message: 'Component should be written as a pure function'] , # , # code: """ # class Foo extends React.Component { # static get displayName() { # return 'Foo' # } # render() { # return <div>{this.props.foo}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: 'Component should be written as a pure function'] code: ''' class Foo extends React.Component @displayName = 'Foo' render: -> return <div>{this.props.foo}</div> ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , # , # code: """ # class Foo extends React.Component { # static get propTypes() { # return { # name: PropTypes.string # } # } # render() { # return <div>{this.props.foo}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: 'Component should be written as a pure function'] code: ''' class Foo extends React.Component @propTypes = { name: PropTypes.string } render: -> return <div>{this.props.foo}</div> ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component constructor: -> super() render: -> return <div>{this.props.foo}</div> ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component render: -> {props:{foo}, context:{bar}} = this return <div>{this.props.foo}</div> ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component render: -> return null unless @props.foo ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , code: ''' Foo = createReactClass({ render: -> if (!this.props.foo) return null return <div>{this.props.foo}</div> }) ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component render: -> return if true then <div /> else null ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component @defaultProps = { foo: true } render: -> { foo } = this.props return if foo then <div /> else null ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , # , # code: """ # class Foo extends React.Component { # static get defaultProps() { # return { # foo: true # } # } # render() { # { foo } = this.props # return foo ? <div /> : null # } # } # """ # errors: [message: 'Component should be written as a pure function'] code: ''' class Foo extends React.Component render: -> { foo } = this.props return if foo then <div /> else null Foo.defaultProps = { foo: true } ''' errors: [message: 'Component should be written as a pure function'] , code: ''' class Foo extends React.Component @contextTypes = { foo: PropTypes.boolean } render: -> { foo } = this.context return if foo then <div /> else null ''' # parser: 'babel-eslint' errors: [message: 'Component should be written as a pure function'] , # , # code: """ # class Foo extends React.Component { # static get contextTypes() { # return { # foo: PropTypes.boolean # } # } # render() { # { foo } = this.context # return foo ? <div /> : null # } # } # """ # errors: [message: 'Component should be written as a pure function'] code: ''' class Foo extends React.Component render: -> { foo } = this.context return if foo then <div /> else null Foo.contextTypes = { foo: PropTypes.boolean } ''' errors: [message: 'Component should be written as a pure function'] ]
[ { "context": "ware_update'\n dialog.positiveLocalizableKey = 'common.no'\n dialog.negativeLocalizableKey = 'common.yes'", "end": 532, "score": 0.9981563091278076, "start": 523, "tag": "KEY", "value": "common.no" }, { "context": " 'common.no'\n dialog.negativeLocalizableKey =...
app/src/controllers/wallet/settings/hardware/wallet_settings_hardware_firmware_setting_view_controller.coffee
romanornr/ledger-wallet-crw
173
class @WalletSettingsHardwareFirmwareSettingViewController extends WalletSettingsSettingViewController renderSelector: "#firmware_table_container" view: currentVersionText: "#current_version_text" updateAvailabilityText: "#update_availability_text" onAfterRender: -> super @_refreshFirmwareStatus() flashFirmware: -> dialog = new CommonDialogsConfirmationDialogViewController() dialog.setMessageLocalizableKey 'common.errors.going_to_firmware_update' dialog.positiveLocalizableKey = 'common.no' dialog.negativeLocalizableKey = 'common.yes' dialog.once 'click:negative', => ledger.app.setExecutionMode(ledger.app.Modes.FirmwareUpdate) ledger.app.router.go '/' dialog.show() _refreshFirmwareStatus: -> ledger.fup.FirmwareUpdater.instance.getFirmwareUpdateAvailability ledger.app.dongle, no, no, (availability, error) => return if error? @view.updateAvailabilityText.text do => if availability.available _.str.sprintf t('wallet.settings.hardware.update_available'), ledger.fup.utils.versionToString(availability.currentVersion) else t('wallet.settings.hardware.no_update_available') @view.currentVersionText.text ledger.fup.utils.versionToString(availability.dongleVersion)
30512
class @WalletSettingsHardwareFirmwareSettingViewController extends WalletSettingsSettingViewController renderSelector: "#firmware_table_container" view: currentVersionText: "#current_version_text" updateAvailabilityText: "#update_availability_text" onAfterRender: -> super @_refreshFirmwareStatus() flashFirmware: -> dialog = new CommonDialogsConfirmationDialogViewController() dialog.setMessageLocalizableKey 'common.errors.going_to_firmware_update' dialog.positiveLocalizableKey = '<KEY>' dialog.negativeLocalizableKey = '<KEY>' dialog.once 'click:negative', => ledger.app.setExecutionMode(ledger.app.Modes.FirmwareUpdate) ledger.app.router.go '/' dialog.show() _refreshFirmwareStatus: -> ledger.fup.FirmwareUpdater.instance.getFirmwareUpdateAvailability ledger.app.dongle, no, no, (availability, error) => return if error? @view.updateAvailabilityText.text do => if availability.available _.str.sprintf t('wallet.settings.hardware.update_available'), ledger.fup.utils.versionToString(availability.currentVersion) else t('wallet.settings.hardware.no_update_available') @view.currentVersionText.text ledger.fup.utils.versionToString(availability.dongleVersion)
true
class @WalletSettingsHardwareFirmwareSettingViewController extends WalletSettingsSettingViewController renderSelector: "#firmware_table_container" view: currentVersionText: "#current_version_text" updateAvailabilityText: "#update_availability_text" onAfterRender: -> super @_refreshFirmwareStatus() flashFirmware: -> dialog = new CommonDialogsConfirmationDialogViewController() dialog.setMessageLocalizableKey 'common.errors.going_to_firmware_update' dialog.positiveLocalizableKey = 'PI:KEY:<KEY>END_PI' dialog.negativeLocalizableKey = 'PI:KEY:<KEY>END_PI' dialog.once 'click:negative', => ledger.app.setExecutionMode(ledger.app.Modes.FirmwareUpdate) ledger.app.router.go '/' dialog.show() _refreshFirmwareStatus: -> ledger.fup.FirmwareUpdater.instance.getFirmwareUpdateAvailability ledger.app.dongle, no, no, (availability, error) => return if error? @view.updateAvailabilityText.text do => if availability.available _.str.sprintf t('wallet.settings.hardware.update_available'), ledger.fup.utils.versionToString(availability.currentVersion) else t('wallet.settings.hardware.no_update_available') @view.currentVersionText.text ledger.fup.utils.versionToString(availability.dongleVersion)