code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
body,td,pre{font-family:Verdana,Arial,Helvetica,sans-serif;font-size:10px}body{background:#FFF}.mceVisualAid{border:1px dashed #BBB}* html body{scrollbar-3dlight-color:#F0F0EE;scrollbar-arrow-color:#676662;scrollbar-base-color:#F0F0EE;scrollbar-darkshadow-color:#DDD;scrollbar-face-color:#E0E0DD;scrollbar-highlight-color:#F0F0EE;scrollbar-shadow-color:#F0F0EE;scrollbar-track-color:#F5F5F5} | Dervisevic/cdnjs | ajax/libs/tinymce/3.5.8/themes/simple/skins/o2k7/content.min.css | CSS | mit | 391 |
<!--
setTimeout(function() { postMessage(1) }, 10);
/*
-->
<!doctype html>
<title>setTimeout</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<div id=log></div>
<script>
async_test(function() {
var worker = new Worker('#');
worker.onmessage = this.step_func(function(e) {
assert_equals(e.data, 1);
this.done();
});
});
</script>
<!--
*/
//-->
| cr/fxos-certsuite | web-platform-tests/tests/workers/interfaces/WorkerUtils/WindowTimers/001.html | HTML | mpl-2.0 | 424 |
var gulp = require('gulp');
var paths = require('../paths');
var del = require('del');
var vinylPaths = require('vinyl-paths');
// deletes all files in the output path
gulp.task('clean', function() {
return gulp.src([paths.output])
.pipe(vinylPaths(del));
});
| victorzki/doclify | workspace/build/tasks/clean.js | JavaScript | mit | 267 |
var test = require('tap').test
var server = require('./lib/server.js')
var common = require('./lib/common.js')
var client = common.freshClient()
function nop () {}
var URI = 'http://localhost:1337/rewrite'
var TOKEN = 'b00b00feed'
var PARAMS = {
auth: {
token: TOKEN
}
}
test('logout call contract', function (t) {
t.throws(function () {
client.logout(undefined, PARAMS, nop)
}, 'requires a URI')
t.throws(function () {
client.logout([], PARAMS, nop)
}, 'requires URI to be a string')
t.throws(function () {
client.logout(URI, undefined, nop)
}, 'requires params object')
t.throws(function () {
client.logout(URI, '', nop)
}, 'params must be object')
t.throws(function () {
client.logout(URI, PARAMS, undefined)
}, 'requires callback')
t.throws(function () {
client.logout(URI, PARAMS, 'callback')
}, 'callback must be function')
t.throws(
function () {
var params = {
auth: {}
}
client.logout(URI, params, nop)
},
{ name: 'AssertionError', message: 'can only log out for token auth' },
'auth must include token'
)
t.end()
})
test('log out from a token-based registry', function (t) {
server.expect('DELETE', '/-/user/token/' + TOKEN, function (req, res) {
t.equal(req.method, 'DELETE')
t.equal(req.headers.authorization, 'Bearer ' + TOKEN, 'request is authed')
res.json({message: 'ok'})
})
client.logout(URI, PARAMS, function (er) {
t.ifError(er, 'no errors')
t.end()
})
})
test('cleanup', function (t) {
server.close()
t.end()
})
| markredballoon/clivemizen | wp-content/themes/redballoon/bootstrap/npm/node_modules/npm-registry-client/test/logout.js | JavaScript | gpl-2.0 | 1,584 |
/*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
//>>built
define("dojo/store/JsonRest",["../_base/xhr","../_base/lang","../json","../_base/declare","./util/QueryResults"],function(_1,_2,_3,_4,_5){
var _6=null;
return _4("dojo.store.JsonRest",_6,{constructor:function(_7){
this.headers={};
_4.safeMixin(this,_7);
},headers:{},target:"",idProperty:"id",ascendingPrefix:"+",descendingPrefix:"-",_getTarget:function(id){
var _8=this.target;
if(typeof id!="undefined"){
if(_8.charAt(_8.length-1)=="/"){
_8+=id;
}else{
_8+="/"+id;
}
}
return _8;
},get:function(id,_9){
_9=_9||{};
var _a=_2.mixin({Accept:this.accepts},this.headers,_9.headers||_9);
return _1("GET",{url:this._getTarget(id),handleAs:"json",headers:_a});
},accepts:"application/javascript, application/json",getIdentity:function(_b){
return _b[this.idProperty];
},put:function(_c,_d){
_d=_d||{};
var id=("id" in _d)?_d.id:this.getIdentity(_c);
var _e=typeof id!="undefined";
return _1(_e&&!_d.incremental?"PUT":"POST",{url:this._getTarget(id),postData:_3.stringify(_c),handleAs:"json",headers:_2.mixin({"Content-Type":"application/json",Accept:this.accepts,"If-Match":_d.overwrite===true?"*":null,"If-None-Match":_d.overwrite===false?"*":null},this.headers,_d.headers)});
},add:function(_f,_10){
_10=_10||{};
_10.overwrite=false;
return this.put(_f,_10);
},remove:function(id,_11){
_11=_11||{};
return _1("DELETE",{url:this._getTarget(id),headers:_2.mixin({},this.headers,_11.headers)});
},query:function(_12,_13){
_13=_13||{};
var _14=_2.mixin({Accept:this.accepts},this.headers,_13.headers);
var _15=this.target.indexOf("?")>-1;
if(_12&&typeof _12=="object"){
_12=_1.objectToQuery(_12);
_12=_12?(_15?"&":"?")+_12:"";
}
if(_13.start>=0||_13.count>=0){
_14["X-Range"]="items="+(_13.start||"0")+"-"+(("count" in _13&&_13.count!=Infinity)?(_13.count+(_13.start||0)-1):"");
if(this.rangeParam){
_12+=(_12||_15?"&":"?")+this.rangeParam+"="+_14["X-Range"];
_15=true;
}else{
_14.Range=_14["X-Range"];
}
}
if(_13&&_13.sort){
var _16=this.sortParam;
_12+=(_12||_15?"&":"?")+(_16?_16+"=":"sort(");
for(var i=0;i<_13.sort.length;i++){
var _17=_13.sort[i];
_12+=(i>0?",":"")+(_17.descending?this.descendingPrefix:this.ascendingPrefix)+encodeURIComponent(_17.attribute);
}
if(!_16){
_12+=")";
}
}
var _18=_1("GET",{url:this.target+(_12||""),handleAs:"json",headers:_14});
_18.total=_18.then(function(){
var _19=_18.ioArgs.xhr.getResponseHeader("Content-Range");
if(!_19){
_19=_18.ioArgs.xhr.getResponseHeader("X-Content-Range");
}
return _19&&(_19=_19.match(/\/(.*)/))&&+_19[1];
});
return _5(_18);
}});
});
| mbouami/pme | web/js/dojo/store/JsonRest.js | JavaScript | mit | 2,702 |
/*
* This file is part of wl1271
*
* Copyright (C) 1998-2009 Texas Instruments. All rights reserved.
* Copyright (C) 2008-2009 Nokia Corporation
*
* Contact: Luciano Coelho <luciano.coelho@nokia.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#ifndef __WLCORE_I_H__
#define __WLCORE_I_H__
#include <linux/mutex.h>
#include <linux/completion.h>
#include <linux/spinlock.h>
#include <linux/list.h>
#include <linux/bitops.h>
#include <net/mac80211.h>
#include "conf.h"
#include "ini.h"
/*
* wl127x and wl128x are using the same NVS file name. However, the
* ini parameters between them are different. The driver validates
* the correct NVS size in wl1271_boot_upload_nvs().
*/
#define WL12XX_NVS_NAME "ti-connectivity/wl1271-nvs.bin"
#define WL1271_TX_SECURITY_LO16(s) ((u16)((s) & 0xffff))
#define WL1271_TX_SECURITY_HI32(s) ((u32)(((s) >> 16) & 0xffffffff))
#define WL1271_TX_SQN_POST_RECOVERY_PADDING 0xff
/* Use smaller padding for GEM, as some APs have issues when it's too big */
#define WL1271_TX_SQN_POST_RECOVERY_PADDING_GEM 0x20
#define WL1271_CIPHER_SUITE_GEM 0x00147201
#define WL1271_BUSY_WORD_CNT 1
#define WL1271_BUSY_WORD_LEN (WL1271_BUSY_WORD_CNT * sizeof(u32))
#define WL1271_ELP_HW_STATE_ASLEEP 0
#define WL1271_ELP_HW_STATE_IRQ 1
#define WL1271_DEFAULT_BEACON_INT 100
#define WL1271_DEFAULT_DTIM_PERIOD 1
#define WL12XX_MAX_ROLES 4
#define WL12XX_INVALID_ROLE_ID 0xff
#define WL12XX_INVALID_LINK_ID 0xff
/*
* max number of links allowed by all HWs.
* this is NOT the actual max links supported by the current hw.
*/
#define WLCORE_MAX_LINKS 16
/* the driver supports the 2.4Ghz and 5Ghz bands */
#define WLCORE_NUM_BANDS 2
#define WL12XX_MAX_RATE_POLICIES 16
#define WLCORE_MAX_KLV_TEMPLATES 4
/* Defined by FW as 0. Will not be freed or allocated. */
#define WL12XX_SYSTEM_HLID 0
/*
* When in AP-mode, we allow (at least) this number of packets
* to be transmitted to FW for a STA in PS-mode. Only when packets are
* present in the FW buffers it will wake the sleeping STA. We want to put
* enough packets for the driver to transmit all of its buffered data before
* the STA goes to sleep again. But we don't want to take too much memory
* as it might hurt the throughput of active STAs.
*/
#define WL1271_PS_STA_MAX_PACKETS 2
#define WL1271_AP_BSS_INDEX 0
#define WL1271_AP_DEF_BEACON_EXP 20
enum wlcore_state {
WLCORE_STATE_OFF,
WLCORE_STATE_RESTARTING,
WLCORE_STATE_ON,
};
enum wl12xx_fw_type {
WL12XX_FW_TYPE_NONE,
WL12XX_FW_TYPE_NORMAL,
WL12XX_FW_TYPE_MULTI,
WL12XX_FW_TYPE_PLT,
};
struct wl1271;
enum {
FW_VER_CHIP,
FW_VER_IF_TYPE,
FW_VER_MAJOR,
FW_VER_SUBTYPE,
FW_VER_MINOR,
NUM_FW_VER
};
struct wl1271_chip {
u32 id;
char fw_ver_str[ETHTOOL_FWVERS_LEN];
unsigned int fw_ver[NUM_FW_VER];
char phy_fw_ver_str[ETHTOOL_FWVERS_LEN];
};
#define NUM_TX_QUEUES 4
struct wl_fw_status {
u32 intr;
u8 fw_rx_counter;
u8 drv_rx_counter;
u8 tx_results_counter;
__le32 *rx_pkt_descs;
u32 fw_localtime;
/*
* A bitmap (where each bit represents a single HLID)
* to indicate if the station is in PS mode.
*/
u32 link_ps_bitmap;
/*
* A bitmap (where each bit represents a single HLID) to indicate
* if the station is in Fast mode
*/
u32 link_fast_bitmap;
/* Cumulative counter of total released mem blocks since FW-reset */
u32 total_released_blks;
/* Size (in Memory Blocks) of TX pool */
u32 tx_total;
struct {
/*
* Cumulative counter of released packets per AC
* (length of the array is NUM_TX_QUEUES)
*/
u8 *tx_released_pkts;
/*
* Cumulative counter of freed packets per HLID
* (length of the array is wl->num_links)
*/
u8 *tx_lnk_free_pkts;
/* Cumulative counter of released Voice memory blocks */
u8 tx_voice_released_blks;
/* Tx rate of the last transmitted packet */
u8 tx_last_rate;
} counters;
u32 log_start_addr;
/* Private status to be used by the lower drivers */
void *priv;
};
#define WL1271_MAX_CHANNELS 64
struct wl1271_scan {
struct cfg80211_scan_request *req;
unsigned long scanned_ch[BITS_TO_LONGS(WL1271_MAX_CHANNELS)];
bool failed;
u8 state;
u8 ssid[IEEE80211_MAX_SSID_LEN+1];
size_t ssid_len;
};
struct wl1271_if_operations {
int __must_check (*read)(struct device *child, int addr, void *buf,
size_t len, bool fixed);
int __must_check (*write)(struct device *child, int addr, void *buf,
size_t len, bool fixed);
void (*reset)(struct device *child);
void (*init)(struct device *child);
int (*power)(struct device *child, bool enable);
void (*set_block_size) (struct device *child, unsigned int blksz);
};
struct wlcore_platdev_data {
struct wl12xx_platform_data *pdata;
struct wl1271_if_operations *if_ops;
};
#define MAX_NUM_KEYS 14
#define MAX_KEY_SIZE 32
struct wl1271_ap_key {
u8 id;
u8 key_type;
u8 key_size;
u8 key[MAX_KEY_SIZE];
u8 hlid;
u32 tx_seq_32;
u16 tx_seq_16;
};
enum wl12xx_flags {
WL1271_FLAG_GPIO_POWER,
WL1271_FLAG_TX_QUEUE_STOPPED,
WL1271_FLAG_TX_PENDING,
WL1271_FLAG_IN_ELP,
WL1271_FLAG_ELP_REQUESTED,
WL1271_FLAG_IRQ_RUNNING,
WL1271_FLAG_FW_TX_BUSY,
WL1271_FLAG_DUMMY_PACKET_PENDING,
WL1271_FLAG_SUSPENDED,
WL1271_FLAG_PENDING_WORK,
WL1271_FLAG_SOFT_GEMINI,
WL1271_FLAG_RECOVERY_IN_PROGRESS,
WL1271_FLAG_VIF_CHANGE_IN_PROGRESS,
WL1271_FLAG_INTENDED_FW_RECOVERY,
WL1271_FLAG_IO_FAILED,
WL1271_FLAG_REINIT_TX_WDOG,
};
enum wl12xx_vif_flags {
WLVIF_FLAG_INITIALIZED,
WLVIF_FLAG_STA_ASSOCIATED,
WLVIF_FLAG_STA_AUTHORIZED,
WLVIF_FLAG_IBSS_JOINED,
WLVIF_FLAG_AP_STARTED,
WLVIF_FLAG_IN_PS,
WLVIF_FLAG_STA_STATE_SENT,
WLVIF_FLAG_RX_STREAMING_STARTED,
WLVIF_FLAG_PSPOLL_FAILURE,
WLVIF_FLAG_CS_PROGRESS,
WLVIF_FLAG_AP_PROBE_RESP_SET,
WLVIF_FLAG_IN_USE,
WLVIF_FLAG_ACTIVE,
};
struct wl12xx_vif;
struct wl1271_link {
/* AP-mode - TX queue per AC in link */
struct sk_buff_head tx_queue[NUM_TX_QUEUES];
/* accounting for allocated / freed packets in FW */
u8 allocated_pkts;
u8 prev_freed_pkts;
u8 addr[ETH_ALEN];
/* bitmap of TIDs where RX BA sessions are active for this link */
u8 ba_bitmap;
/* The wlvif this link belongs to. Might be null for global links */
struct wl12xx_vif *wlvif;
/*
* total freed FW packets on the link - used for tracking the
* AES/TKIP PN across recoveries. Re-initialized each time
* from the wl1271_station structure.
*/
u64 total_freed_pkts;
};
#define WL1271_MAX_RX_FILTERS 5
#define WL1271_RX_FILTER_MAX_FIELDS 8
#define WL1271_RX_FILTER_ETH_HEADER_SIZE 14
#define WL1271_RX_FILTER_MAX_FIELDS_SIZE 95
#define RX_FILTER_FIELD_OVERHEAD \
(sizeof(struct wl12xx_rx_filter_field) - sizeof(u8 *))
#define WL1271_RX_FILTER_MAX_PATTERN_SIZE \
(WL1271_RX_FILTER_MAX_FIELDS_SIZE - RX_FILTER_FIELD_OVERHEAD)
#define WL1271_RX_FILTER_FLAG_MASK BIT(0)
#define WL1271_RX_FILTER_FLAG_IP_HEADER 0
#define WL1271_RX_FILTER_FLAG_ETHERNET_HEADER BIT(1)
enum rx_filter_action {
FILTER_DROP = 0,
FILTER_SIGNAL = 1,
FILTER_FW_HANDLE = 2
};
enum plt_mode {
PLT_OFF = 0,
PLT_ON = 1,
PLT_FEM_DETECT = 2,
PLT_CHIP_AWAKE = 3
};
struct wl12xx_rx_filter_field {
__le16 offset;
u8 len;
u8 flags;
u8 *pattern;
} __packed;
struct wl12xx_rx_filter {
u8 action;
int num_fields;
struct wl12xx_rx_filter_field fields[WL1271_RX_FILTER_MAX_FIELDS];
};
struct wl1271_station {
u8 hlid;
bool in_connection;
/*
* total freed FW packets on the link to the STA - used for tracking the
* AES/TKIP PN across recoveries. Re-initialized each time from the
* wl1271_station structure.
* Used in both AP and STA mode.
*/
u64 total_freed_pkts;
};
struct wl12xx_vif {
struct wl1271 *wl;
struct list_head list;
unsigned long flags;
u8 bss_type;
u8 p2p; /* we are using p2p role */
u8 role_id;
/* sta/ibss specific */
u8 dev_role_id;
u8 dev_hlid;
union {
struct {
u8 hlid;
u8 basic_rate_idx;
u8 ap_rate_idx;
u8 p2p_rate_idx;
u8 klv_template_id;
bool qos;
/* channel type we started the STA role with */
enum nl80211_channel_type role_chan_type;
} sta;
struct {
u8 global_hlid;
u8 bcast_hlid;
/* HLIDs bitmap of associated stations */
unsigned long sta_hlid_map[BITS_TO_LONGS(
WLCORE_MAX_LINKS)];
/* recoreded keys - set here before AP startup */
struct wl1271_ap_key *recorded_keys[MAX_NUM_KEYS];
u8 mgmt_rate_idx;
u8 bcast_rate_idx;
u8 ucast_rate_idx[CONF_TX_MAX_AC_COUNT];
} ap;
};
/* the hlid of the last transmitted skb */
int last_tx_hlid;
/* counters of packets per AC, across all links in the vif */
int tx_queue_count[NUM_TX_QUEUES];
unsigned long links_map[BITS_TO_LONGS(WLCORE_MAX_LINKS)];
u8 ssid[IEEE80211_MAX_SSID_LEN + 1];
u8 ssid_len;
/* The current band */
enum ieee80211_band band;
int channel;
enum nl80211_channel_type channel_type;
u32 bitrate_masks[WLCORE_NUM_BANDS];
u32 basic_rate_set;
/*
* currently configured rate set:
* bits 0-15 - 802.11abg rates
* bits 16-23 - 802.11n MCS index mask
* support only 1 stream, thus only 8 bits for the MCS rates (0-7).
*/
u32 basic_rate;
u32 rate_set;
/* probe-req template for the current AP */
struct sk_buff *probereq;
/* Beaconing interval (needed for ad-hoc) */
u32 beacon_int;
/* Default key (for WEP) */
u32 default_key;
/* Our association ID */
u16 aid;
/* retry counter for PSM entries */
u8 psm_entry_retry;
/* in dBm */
int power_level;
int rssi_thold;
int last_rssi_event;
/* save the current encryption type for auto-arp config */
u8 encryption_type;
__be32 ip_addr;
/* RX BA constraint value */
bool ba_support;
bool ba_allowed;
bool wmm_enabled;
/* Rx Streaming */
struct work_struct rx_streaming_enable_work;
struct work_struct rx_streaming_disable_work;
struct timer_list rx_streaming_timer;
struct delayed_work channel_switch_work;
struct delayed_work connection_loss_work;
/* number of in connection stations */
int inconn_count;
/*
* This vif's queues are mapped to mac80211 HW queues as:
* VO - hw_queue_base
* VI - hw_queue_base + 1
* BE - hw_queue_base + 2
* BK - hw_queue_base + 3
*/
int hw_queue_base;
/* do we have a pending auth reply? (and ROC) */
bool ap_pending_auth_reply;
/* time when we sent the pending auth reply */
unsigned long pending_auth_reply_time;
/* work for canceling ROC after pending auth reply */
struct delayed_work pending_auth_complete_work;
/*
* total freed FW packets on the link.
* For STA this holds the PN of the link to the AP.
* For AP this holds the PN of the broadcast link.
*/
u64 total_freed_pkts;
/*
* This struct must be last!
* data that has to be saved acrossed reconfigs (e.g. recovery)
* should be declared in this struct.
*/
struct {
u8 persistent[0];
};
};
static inline struct wl12xx_vif *wl12xx_vif_to_data(struct ieee80211_vif *vif)
{
WARN_ON(!vif);
return (struct wl12xx_vif *)vif->drv_priv;
}
static inline
struct ieee80211_vif *wl12xx_wlvif_to_vif(struct wl12xx_vif *wlvif)
{
return container_of((void *)wlvif, struct ieee80211_vif, drv_priv);
}
#define wl12xx_for_each_wlvif(wl, wlvif) \
list_for_each_entry(wlvif, &wl->wlvif_list, list)
#define wl12xx_for_each_wlvif_continue(wl, wlvif) \
list_for_each_entry_continue(wlvif, &wl->wlvif_list, list)
#define wl12xx_for_each_wlvif_bss_type(wl, wlvif, _bss_type) \
wl12xx_for_each_wlvif(wl, wlvif) \
if (wlvif->bss_type == _bss_type)
#define wl12xx_for_each_wlvif_sta(wl, wlvif) \
wl12xx_for_each_wlvif_bss_type(wl, wlvif, BSS_TYPE_STA_BSS)
#define wl12xx_for_each_wlvif_ap(wl, wlvif) \
wl12xx_for_each_wlvif_bss_type(wl, wlvif, BSS_TYPE_AP_BSS)
int wl1271_plt_start(struct wl1271 *wl, const enum plt_mode plt_mode);
int wl1271_plt_stop(struct wl1271 *wl);
int wl1271_recalc_rx_streaming(struct wl1271 *wl, struct wl12xx_vif *wlvif);
void wl12xx_queue_recovery_work(struct wl1271 *wl);
size_t wl12xx_copy_fwlog(struct wl1271 *wl, u8 *memblock, size_t maxlen);
int wl1271_rx_filter_alloc_field(struct wl12xx_rx_filter *filter,
u16 offset, u8 flags,
const u8 *pattern, u8 len);
void wl1271_rx_filter_free(struct wl12xx_rx_filter *filter);
struct wl12xx_rx_filter *wl1271_rx_filter_alloc(void);
int wl1271_rx_filter_get_fields_size(struct wl12xx_rx_filter *filter);
void wl1271_rx_filter_flatten_fields(struct wl12xx_rx_filter *filter,
u8 *buf);
#define JOIN_TIMEOUT 5000 /* 5000 milliseconds to join */
#define SESSION_COUNTER_MAX 6 /* maximum value for the session counter */
#define SESSION_COUNTER_INVALID 7 /* used with dummy_packet */
#define WL1271_DEFAULT_POWER_LEVEL 0
#define WL1271_TX_QUEUE_LOW_WATERMARK 32
#define WL1271_TX_QUEUE_HIGH_WATERMARK 256
#define WL1271_DEFERRED_QUEUE_LIMIT 64
/* WL1271 needs a 200ms sleep after power on, and a 20ms sleep before power
on in case is has been shut down shortly before */
#define WL1271_PRE_POWER_ON_SLEEP 20 /* in milliseconds */
#define WL1271_POWER_ON_SLEEP 200 /* in milliseconds */
/* Macros to handle wl1271.sta_rate_set */
#define HW_BG_RATES_MASK 0xffff
#define HW_HT_RATES_OFFSET 16
#define HW_MIMO_RATES_OFFSET 24
#endif /* __WLCORE_I_H__ */
| mericon/Xp_Kernel_LGH850 | virt/drivers/net/wireless/ti/wlcore/wlcore_i.h | C | gpl-2.0 | 13,772 |
/* Copyright (c) 2008-2009, Code Aurora Forum. 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 Code Aurora Forum, Inc. 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 "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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.
*
*/
/*
* Touchpad driver for QSD platform.
*/
struct msm_touchpad_platform_data {
int gpioirq;
int gpiosuspend;
int (*gpio_setup) (void);
void (*gpio_shutdown)(void);
};
| arkas/Samsung-GT-I5510-Kernel | kernel/arch/arm/mach-msm/include/mach/msm_touchpad.h | C | gpl-2.0 | 1,771 |
require File.expand_path('../helper', __FILE__)
require 'open3'
class TestRakeReduceCompat < Rake::TestCase
include RubyRunner
def invoke_normal(task_name)
rake task_name.to_s
@out
end
def test_no_deprecated_dsl
rakefile %q{
task :check_task do
Module.new { p defined?(task) }
end
task :check_file do
Module.new { p defined?(file) }
end
}
assert_equal "nil", invoke_normal(:check_task).chomp
assert_equal "nil", invoke_normal(:check_file).chomp
end
end
| emineKoc/WiseWit | wisewitapi/vendor/bundle/gems/rake-11.1.2/test/test_rake_reduce_compat.rb | Ruby | gpl-3.0 | 532 |
/*
* Copyright (C) 2005 Sigmatel Inc
*
* Copyright 2008 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved.
*/
/*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*/
#ifndef __ASM_ARM_ARCH_IO_H
#define __ASM_ARM_ARCH_IO_H
#define IO_SPACE_LIMIT 0xffffffff
#define __io(a) __typesafe_io(a)
#define __mem_pci(a) (a)
#define __mem_isa(a) (a)
#endif
| wkritzinger/asuswrt-merlin | release/src-rt-7.x.main/src/linux/linux-2.6.36/arch/arm/plat-stmp3xxx/include/mach/io.h | C | gpl-2.0 | 661 |
#!/usr/bin/env python
import os
import re
import subprocess
import sys
import tempfile
CC = "gcc"
CFLAGS = "-fmax-errors=4 -std=c99 -pipe -D_POSIX_C_SOURCE=200809L -W -Wall -Wno-unused-variable -Wno-unused-parameter -Wno-unused-label -Wno-unused-value -Wno-unused-but-set-variable -Wno-unused-function -Wno-main".split(" ")
class Table():
pass
class TestMode():
pass_ = 0
fail_compile_parse = 1
fail_compile_sem = 2
fail_compile_ice = 3
fail_c = 4
fail_run = 5
fail_output = 6
fail_other = 7
disable = 8
test_modes = [TestMode.pass_, TestMode.fail_compile_parse,
TestMode.fail_compile_sem, TestMode.fail_compile_ice,
TestMode.fail_c, TestMode.fail_run, TestMode.fail_output,
TestMode.fail_other, TestMode.disable]
test_mode_names = {
TestMode.pass_: ("pass", "Passed"),
TestMode.fail_compile_parse: ("fail_compile_parse", "Compilation failed (parsing)"),
TestMode.fail_compile_sem: ("fail_compile_sem", "Compilation failed (semantics)"),
TestMode.fail_compile_ice: ("fail_compile_ice", "Compilation failed (ICE)"),
TestMode.fail_c: ("fail_c", "C compilation/linking failed"),
TestMode.fail_run: ("fail_run", "Run failed"),
TestMode.fail_output: ("fail_output", "Output mismatched"),
TestMode.fail_other: ("fail_other", "Expected failure didn't happen"),
TestMode.disable: ("disable", "Disabled"),
}
test_stats = dict([(m, 0) for m in test_modes])
test_mode_values = {}
for m, (s, _) in test_mode_names.iteritems():
test_mode_values[s] = m
def pick(v, m):
if v not in m:
raise Exception("Unknown value '%s'" % v)
return m[v]
def run_test(filename):
testname = os.path.basename(filename)
print("Test '%s'..." % testname)
workdir = tempfile.mkdtemp(prefix="boringtest")
tempfiles = []
src = open(filename)
headers = Table()
headers.mode = TestMode.pass_
headers.is_expr = False
headers.stdout = None
while True:
hline = src.readline()
if not hline:
break
m = re.match("(?://|/\*) ([A-Z]+):(.*)", hline)
if not m:
break
name, value = m.group(1), m.group(2)
value = value.strip()
if name == "TEST":
headers.mode = pick(value, test_mode_values)
elif name == "TYPE":
headers.is_expr = pick(value, {"normal": False, "expr": True})
elif name == "STDOUT":
term = value + "*/"
stdout = ""
while True:
line = src.readline()
if not line:
raise Exception("unterminated STDOUT header")
if line.strip() == term:
break
stdout += line
headers.stdout = stdout
else:
raise Exception("Unknown header '%s'" % name)
src.close()
def do_run():
if headers.mode == TestMode.disable:
return TestMode.disable
# make is for fags
tc = os.path.join(workdir, "t.c")
tcf = open(tc, "w")
tempfiles.append(tc)
res = subprocess.call(["./main", "cg_c", filename], stdout=tcf)
tcf.close()
if res != 0:
if res == 1:
return TestMode.fail_compile_parse
if res == 2:
return TestMode.fail_compile_sem
return TestMode.fail_compile_ice
t = os.path.join(workdir, "t")
tempfiles.append(t)
res = subprocess.call([CC] + CFLAGS + [tc, "-o", t])
if res != 0:
return TestMode.fail_c
p = subprocess.Popen([t], stdout=subprocess.PIPE)
output, _ = p.communicate()
res = p.wait()
if res != 0:
return TestMode.fail_run
if headers.stdout is not None and headers.stdout != output:
print("Program output: >\n%s<\nExpected: >\n%s<" % (output,
headers.stdout))
return TestMode.fail_output
return TestMode.pass_
actual_res = do_run()
for f in tempfiles:
try:
os.unlink(f)
except OSError:
pass
os.rmdir(workdir)
res = actual_res
if res == TestMode.disable:
pass
elif res == headers.mode:
res = TestMode.pass_
else:
if headers.mode != TestMode.pass_:
res = TestMode.fail_other
test_stats[res] += 1
print("Test '%s': %s (expected %s, got %s)" % (testname,
test_mode_names[res][0], test_mode_names[headers.mode][0],
test_mode_names[actual_res][0]))
def run_tests(list_file_name):
base = os.path.dirname(list_file_name)
for f in [x.strip() for x in open(argv[1])]:
run_test(os.path.join(base, f))
print("SUMMARY:")
test_sum = 0
for m in test_modes:
print(" %s: %d" % (test_mode_names[m][1], test_stats[m]))
test_sum += test_stats[m]
passed_tests = test_stats[TestMode.pass_]
failed_tests = test_sum - passed_tests - test_stats[TestMode.disable]
print("Passed/failed: %s/%d" % (passed_tests, failed_tests))
if failed_tests:
print("OMG OMG OMG ------- Some tests have failed ------- OMG OMG OMG")
sys.exit(1)
if __name__ == "__main__":
argv = sys.argv
if len(argv) != 2:
print("Usage: %s tests.lst" % argv[0])
sys.exit(1)
#subprocess.check_call(["make", "main"])
run_tests(argv[1])
| wm4/boringlang | run_tests.py | Python | isc | 5,430 |
var cx = require('classnames');
var blacklist = require('blacklist');
var React = require('react');
module.exports = React.createClass({
displayName: 'Field',
getDefaultProps() {
return {
d: null,
t: null,
m: null,
label: ''
}
},
renderError() {
if(!this.props.error) return null;
return <span className="error">{this.props.error}</span>;
},
renderLabel() {
var cn = cx('label', this.props.d ? `g-${this.props.d}` : null);
if(!this.props.label) {
return (
<label className={cn}> </label>
);
}
return (
<label className={cn}>
{this.props.label}
</label>
);
},
render() {
var props = blacklist(this.props, 'label', 'error', 'children', 'd', 't', 'm');
props.className = cx('u-field', {
'g-row': this.props.d,
'u-field-row': this.props.d,
'u-field-err': this.props.error
});
return (
<div {... props}>
{this.renderLabel()}
{this.props.d ? (
<div className={`g-${24 - this.props.d}`}>
{this.props.children}
</div>
) : this.props.children}
{this.renderError()}
</div>
);
}
});
| wangzuo/feng-ui | react/field.js | JavaScript | isc | 1,218 |
/* $OpenBSD: intr.h,v 1.45 2015/09/13 20:38:45 kettenis Exp $ */
/*
* Copyright (c) 2001-2004 Opsycon AB (www.opsycon.se / www.opsycon.com)
*
* 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 THE AUTHOR ``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 AUTHOR 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.
*
*/
#ifndef _MACHINE_INTR_H_
#define _MACHINE_INTR_H_
/*
* The interrupt level ipl is a logical level; per-platform interrupt
* code will turn it into the appropriate hardware interrupt masks
* values.
*
* Interrupt sources on the CPU are kept enabled regardless of the
* current ipl value; individual hardware sources interrupting while
* logically masked are masked on the fly, remembered as pending, and
* unmasked at the first splx() opportunity.
*
* An exception to this rule is the clock interrupt. Clock interrupts
* are always allowed to happen, but will (of course!) not be serviced
* if logically masked. The reason for this is that clocks usually sit on
* INT5 and cannot be easily masked if external hardware masking is used.
*/
/* Interrupt priority `levels'; not mutually exclusive. */
#define IPL_NONE 0 /* nothing */
#define IPL_SOFTINT 1 /* soft interrupts */
#define IPL_BIO 2 /* block I/O */
#define IPL_AUDIO IPL_BIO
#define IPL_NET 3 /* network */
#define IPL_TTY 4 /* terminal */
#define IPL_VM 5 /* memory allocation */
#define IPL_CLOCK 6 /* clock */
#define IPL_SCHED IPL_CLOCK
#define IPL_HIGH 7 /* everything */
#define IPL_IPI 8 /* interprocessor interrupt */
#define NIPLS 9 /* Number of levels */
#define IPL_MPFLOOR IPL_TTY
/* Interrupt priority 'flags'. */
#define IPL_MPSAFE 0 /* no "mpsafe" interrupts */
/* Interrupt sharing types. */
#define IST_NONE 0 /* none */
#define IST_PULSE 1 /* pulsed */
#define IST_EDGE 2 /* edge-triggered */
#define IST_LEVEL 3 /* level-triggered */
#define SINTBIT(q) (q)
#define SINTMASK(q) (1 << SINTBIT(q))
/* Soft interrupt masks. */
#define IPL_SOFT 0
#define IPL_SOFTCLOCK 1
#define IPL_SOFTNET 2
#define IPL_SOFTTTY 3
#define SI_SOFT 0 /* for IPL_SOFT */
#define SI_SOFTCLOCK 1 /* for IPL_SOFTCLOCK */
#define SI_SOFTNET 2 /* for IPL_SOFTNET */
#define SI_SOFTTTY 3 /* for IPL_SOFTTTY */
#define SI_NQUEUES 4
#ifndef _LOCORE
#include <machine/mutex.h>
#include <sys/queue.h>
struct soft_intrhand {
TAILQ_ENTRY(soft_intrhand) sih_list;
void (*sih_func)(void *);
void *sih_arg;
struct soft_intrq *sih_siq;
int sih_pending;
};
struct soft_intrq {
TAILQ_HEAD(, soft_intrhand) siq_list;
int siq_si;
struct mutex siq_mtx;
};
void softintr_disestablish(void *);
void softintr_dispatch(int);
void *softintr_establish(int, void (*)(void *), void *);
void softintr_init(void);
void softintr_schedule(void *);
#define splsoft() splraise(IPL_SOFTINT)
#define splbio() splraise(IPL_BIO)
#define splnet() splraise(IPL_NET)
#define spltty() splraise(IPL_TTY)
#define splaudio() splraise(IPL_AUDIO)
#define splvm() splraise(IPL_VM)
#define splclock() splraise(IPL_CLOCK)
#define splsched() splraise(IPL_SCHED)
#define splhigh() splraise(IPL_HIGH)
#define splsoftclock() splsoft()
#define splsoftnet() splsoft()
#define splstatclock() splhigh()
#define spllock() splhigh()
#define spl0() spllower(0)
void splinit(void);
#define splassert(X)
#define splsoftassert(X)
/* Inlines */
static __inline void register_splx_handler(void (*)(int));
typedef void (int_f)(int);
extern int_f *splx_hand;
static __inline void
register_splx_handler(void(*handler)(int))
{
splx_hand = handler;
}
int splraise(int);
void splx(int);
int spllower(int);
/*
* Interrupt control struct used by interrupt dispatchers
* to hold interrupt handler info.
*/
#include <sys/evcount.h>
struct intrhand {
struct intrhand *ih_next;
int (*ih_fun)(void *);
void *ih_arg;
int ih_level;
int ih_irq;
struct evcount ih_count;
int ih_flags;
#define IH_ALLOCATED 0x01
};
void intr_barrier(void *);
/*
* Low level interrupt dispatcher registration data.
*/
/* Schedule priorities for base interrupts (CPU) */
#define INTPRI_IPI 0
#define INTPRI_CLOCK 1
/* other values are system-specific */
#define NLOWINT 16 /* Number of low level registrations possible */
extern uint32_t idle_mask;
struct trap_frame;
void set_intr(int, uint32_t, uint32_t(*)(uint32_t, struct trap_frame *));
uint32_t updateimask(uint32_t);
void dosoftint(void);
#ifdef MULTIPROCESSOR
#if defined (TGT_OCTANE)
#define ENABLEIPI() updateimask(~CR_INT_2) /* enable IPI interrupt level */
#else
#error MULTIPROCESSOR kernel not supported on this configuration
#endif
#endif
#endif /* _LOCORE */
#endif /* _MACHINE_INTR_H_ */
| orumin/openbsd-efivars | arch/sgi/include/intr.h | C | isc | 5,725 |
// Copyright (c) 2014 The btcsuite developers
// Copyright (c) 2015-2020 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package dcrjson
import (
"errors"
"reflect"
"sort"
"testing"
)
// Register methods for testing purposes. This does not conflict with
// registration performed by external packages as they are done in separate
// builds.
func init() {
MustRegister("getblock", (*testGetBlockCmd)(nil), 0)
MustRegister("getblockcount", (*testGetBlockCountCmd)(nil), 0)
MustRegister("session", (*testSessionCmd)(nil), UFWebsocketOnly)
MustRegister("help", (*testHelpCmd)(nil), 0)
}
type testGetBlockCmd struct {
Hash string
Verbose *bool `jsonrpcdefault:"true"`
VerboseTx *bool `jsonrpcdefault:"false"`
}
type testGetBlockCountCmd struct{}
type testSessionCmd struct{}
type testHelpCmd struct {
Command *string
}
// TestUsageFlagStringer tests the stringized output for the UsageFlag type.
func TestUsageFlagStringer(t *testing.T) {
t.Parallel()
tests := []struct {
in UsageFlag
want string
}{
{0, "0x0"},
{1, "0x0"}, // was UFWalletOnly
{UFWebsocketOnly, "UFWebsocketOnly"},
{UFNotification, "UFNotification"},
{UFWebsocketOnly | UFNotification, "UFWebsocketOnly|UFNotification"},
{1 | UFWebsocketOnly | UFNotification | (1 << 31),
"UFWebsocketOnly|UFNotification|0x80000000"},
}
// Detect additional usage flags that don't have the stringer added.
numUsageFlags := 0
highestUsageFlagBit := highestUsageFlagBit
for highestUsageFlagBit > 1 {
numUsageFlags++
highestUsageFlagBit >>= 1
}
if len(tests)-3 != numUsageFlags {
t.Errorf("It appears a usage flag was added without adding " +
"an associated stringer test")
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
result := test.in.String()
if result != test.want {
t.Errorf("String #%d\n got: %s want: %s", i, result,
test.want)
continue
}
}
}
// TestRegisterCmdErrors ensures the RegisterCmd function returns the expected
// error when provided with invalid types.
func TestRegisterCmdErrors(t *testing.T) {
t.Parallel()
tests := []struct {
name string
method string
cmdFunc func() interface{}
flags UsageFlag
err error
}{
{
name: "duplicate method",
method: "getblock",
cmdFunc: func() interface{} {
return struct{}{}
},
err: ErrDuplicateMethod,
},
{
name: "invalid usage flags",
method: "registertestcmd",
cmdFunc: func() interface{} {
return 0
},
flags: highestUsageFlagBit,
err: ErrInvalidUsageFlags,
},
{
name: "invalid type",
method: "registertestcmd",
cmdFunc: func() interface{} {
return 0
},
err: ErrInvalidType,
},
{
name: "invalid type 2",
method: "registertestcmd",
cmdFunc: func() interface{} {
return &[]string{}
},
err: ErrInvalidType,
},
{
name: "embedded field",
method: "registertestcmd",
cmdFunc: func() interface{} {
type test struct{ int }
return (*test)(nil)
},
err: ErrEmbeddedType,
},
{
name: "unexported field",
method: "registertestcmd",
cmdFunc: func() interface{} {
type test struct{ a int }
return (*test)(nil)
},
err: ErrUnexportedField,
},
{
name: "unsupported field type 1",
method: "registertestcmd",
cmdFunc: func() interface{} {
type test struct{ A **int }
return (*test)(nil)
},
err: ErrUnsupportedFieldType,
},
{
name: "unsupported field type 2",
method: "registertestcmd",
cmdFunc: func() interface{} {
type test struct{ A chan int }
return (*test)(nil)
},
err: ErrUnsupportedFieldType,
},
{
name: "unsupported field type 3",
method: "registertestcmd",
cmdFunc: func() interface{} {
type test struct{ A complex64 }
return (*test)(nil)
},
err: ErrUnsupportedFieldType,
},
{
name: "unsupported field type 4",
method: "registertestcmd",
cmdFunc: func() interface{} {
type test struct{ A complex128 }
return (*test)(nil)
},
err: ErrUnsupportedFieldType,
},
{
name: "unsupported field type 5",
method: "registertestcmd",
cmdFunc: func() interface{} {
type test struct{ A func() }
return (*test)(nil)
},
err: ErrUnsupportedFieldType,
},
{
name: "unsupported field type 6",
method: "registertestcmd",
cmdFunc: func() interface{} {
type test struct{ A interface{} }
return (*test)(nil)
},
err: ErrUnsupportedFieldType,
},
{
name: "required after optional",
method: "registertestcmd",
cmdFunc: func() interface{} {
type test struct {
A *int
B int
}
return (*test)(nil)
},
err: ErrNonOptionalField,
},
{
name: "non-optional with default",
method: "registertestcmd",
cmdFunc: func() interface{} {
type test struct {
A int `jsonrpcdefault:"1"`
}
return (*test)(nil)
},
err: ErrNonOptionalDefault,
},
{
name: "mismatched default",
method: "registertestcmd",
cmdFunc: func() interface{} {
type test struct {
A *int `jsonrpcdefault:"1.7"`
}
return (*test)(nil)
},
err: ErrMismatchedDefault,
},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
err := Register(test.method, test.cmdFunc(), test.flags)
if !errors.Is(err, test.err) {
t.Errorf("Test #%d (%s): mismatched error - got %v, "+
"want %v", i, test.name, err, test.err)
continue
}
}
}
// TestMustRegisterCmdPanic ensures the MustRegisterCmd function panics when
// used to register an invalid type.
func TestMustRegisterCmdPanic(t *testing.T) {
t.Parallel()
// Setup a defer to catch the expected panic to ensure it actually
// paniced.
defer func() {
if err := recover(); err == nil {
t.Error("MustRegisterCmd did not panic as expected")
}
}()
// Intentionally try to register an invalid type to force a panic.
MustRegister("panicme", 0, 0)
}
// TestRegisteredCmdMethods tests the RegisteredCmdMethods function ensure it
// works as expected.
func TestRegisteredCmdMethods(t *testing.T) {
t.Parallel()
// Ensure the registered methods for plain string methods are returned.
methods := RegisteredMethods("")
if len(methods) == 0 {
t.Fatal("RegisteredCmdMethods: no methods")
}
// Ensure the returned methods are sorted.
sortedMethods := make([]string, len(methods))
copy(sortedMethods, methods)
sort.Strings(sortedMethods)
if !reflect.DeepEqual(sortedMethods, methods) {
t.Fatal("RegisteredCmdMethods: methods are not sorted")
}
}
| decred/dcrd | dcrjson/register_test.go | GO | isc | 6,603 |
/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef KERNEL_PROCESSOR_X86_VIRTUALADDRESSSPACE_H
#define KERNEL_PROCESSOR_X86_VIRTUALADDRESSSPACE_H
#include <processor/types.h>
#include <Spinlock.h>
#include <processor/VirtualAddressSpace.h>
//
// Virtual address space layout
//
#define KERNEL_SPACE_START reinterpret_cast<void*>(0xC0000000)
#define USERSPACE_DYNAMIC_LINKER_LOCATION reinterpret_cast<void*>(0x4FA00000)
#define USERSPACE_VIRTUAL_START reinterpret_cast<void*>(0x400000)
#define USERSPACE_VIRTUAL_HEAP reinterpret_cast<void*>(0x50000000)
#define USERSPACE_VIRTUAL_STACK reinterpret_cast<void*>(0xB0000000)
#define USERSPACE_RESERVED_START USERSPACE_VIRTUAL_HEAP
#define USERSPACE_VIRTUAL_MAX_STACK_SIZE 0x100000
#define USERSPACE_VIRTUAL_LOWEST_STACK reinterpret_cast<void*>(0x70000000)
#define VIRTUAL_PAGE_DIRECTORY reinterpret_cast<void*>(0xFFBFF000)
#define VIRTUAL_PAGE_TABLES reinterpret_cast<void*>(0xFFC00000)
#define KERNEL_VIRTUAL_TEMP1 reinterpret_cast<void*>(0xFFBFC000)
#define KERNEL_VIRTUAL_TEMP2 reinterpret_cast<void*>(0xFFBFD000)
#define KERNEL_VIRTUAL_TEMP3 reinterpret_cast<void*>(0xFFBFE000)
#define KERNEL_VIRTUAL_HEAP reinterpret_cast<void*>(0xC0000000)
#define KERNEL_VIRTUAL_HEAP_SIZE 0x10000000
#define KERNEL_VIRUTAL_PAGE_DIRECTORY reinterpret_cast<void*>(0xFF7FF000)
#define KERNEL_VIRTUAL_ADDRESS reinterpret_cast<void*>(0xFF400000 - 0x100000)
#define KERNEL_VIRTUAL_MEMORYREGION_ADDRESS reinterpret_cast<void*>(0xD0000000)
#define KERNEL_VIRTUAL_PAGESTACK_4GB reinterpret_cast<void*>(0xF0000000)
#define KERNEL_VIRTUAL_STACK reinterpret_cast<void*>(0xFF3F6000)
#define KERNEL_VIRTUAL_MEMORYREGION_SIZE 0x10000000
#define KERNEL_STACK_SIZE 0x8000
/** @addtogroup kernelprocessorx86
* @{ */
/** The X86VirtualAddressSpace implements the VirtualAddressSpace class for the x86 processor
* architecture, that means it wraps around the processor's paging functionality. */
class X86VirtualAddressSpace : public VirtualAddressSpace
{
/** Processor::switchAddressSpace() needs access to m_PhysicalPageDirectory */
friend class Processor;
/** Multiprocessor::initialise() needs access to m_PhysicalPageDirectory */
friend class Multiprocessor;
/** VirtualAddressSpace::create needs access to the constructor */
friend VirtualAddressSpace *VirtualAddressSpace::create();
public:
//
// VirtualAddressSpace Interface
//
virtual bool isAddressValid(void *virtualAddress);
virtual bool isMapped(void *virtualAddress);
virtual bool map(physical_uintptr_t physicalAddress,
void *virtualAddress,
size_t flags);
virtual void getMapping(void *virtualAddress,
physical_uintptr_t &physicalAddress,
size_t &flags);
virtual void setFlags(void *virtualAddress, size_t newFlags);
virtual void unmap(void *virtualAddress);
virtual void *allocateStack();
virtual void *allocateStack(size_t stackSz);
virtual void freeStack(void *pStack);
virtual bool memIsInHeap(void *pMem);
virtual void *getEndOfHeap();
virtual VirtualAddressSpace *clone();
virtual void revertToKernelAddressSpace();
//
// Needed for the PhysicalMemoryManager
//
/** Map the page table or the page frame if none is currently present
*\note This should only be used from the PhysicalMemoryManager and you have to
* switch to the VirtualAddressSpace you want to change first.
*\param[in] physicalAddress the physical page that should be used as page table or
* page frame
*\param[in] virtualAddress the virtual address that should be checked for the existance
* of a page table and page frame
*\param[in] flags the flags used for the mapping
*\return true, if a page table/frame is already mapped for that address, false if the
* physicalAddress has been used as a page table or as a page frame. */
bool mapPageStructures(physical_uintptr_t physicalAddress,
void *virtualAddress,
size_t flags);
/** Initialise the static members of VirtualAddressSpace */
static void initialise() INITIALISATION_ONLY;
/** The destructor cleans up the address space */
virtual ~X86VirtualAddressSpace();
/** Gets start address of the kernel in the address space. */
virtual uintptr_t getKernelStart() const
{
return reinterpret_cast<uintptr_t>(KERNEL_SPACE_START);
}
/** Gets start address of the region usable and cloneable for userspace. */
virtual uintptr_t getUserStart() const
{
return reinterpret_cast<uintptr_t>(USERSPACE_VIRTUAL_START);
}
/** Gets start address of reserved areas of the userpace address space. */
virtual uintptr_t getUserReservedStart() const
{
return reinterpret_cast<uintptr_t>(USERSPACE_RESERVED_START);
}
/** Gets address of the dynamic linker in the address space. */
virtual uintptr_t getDynamicLinkerAddress() const
{
return reinterpret_cast<uintptr_t>(USERSPACE_DYNAMIC_LINKER_LOCATION);
}
protected:
/** The constructor for already present paging structures
*\param[in] Heap virtual address of the beginning of the heap
*\param[in] PhysicalPageDirectory physical address of the page directory
*\param[in] VirtualPageDirectory virtual address of the page directory
*\param[in] VirtualPageTables virtual address of the page tables
*\param[in] VirtualStack virtual address of the next stacks
*\note This constructor is only used to construct the kernel VirtualAddressSpace */
X86VirtualAddressSpace(void *Heap,
physical_uintptr_t PhysicalPageDirectory,
void *VirtualPageDirectory,
void *VirtualPageTables,
void *VirtualStack) INITIALISATION_ONLY;
bool doIsMapped(void *virtualAddress);
bool doMap(physical_uintptr_t physicalAddress,
void *virtualAddress,
size_t flags);
void doGetMapping(void *virtualAddress,
physical_uintptr_t &physicalAddress,
size_t &flags);
void doSetFlags(void *virtualAddress, size_t newFlags);
void doUnmap(void *virtualAddress);
void *doAllocateStack(size_t sSize);
private:
/** The default constructor */
X86VirtualAddressSpace();
/** The copy-constructor
*\note NOT implemented */
X86VirtualAddressSpace(const X86VirtualAddressSpace &);
/** The copy-constructor
*\note Not implemented */
X86VirtualAddressSpace &operator = (const X86VirtualAddressSpace &);
/** Get the page table entry, if it exists and check whether a page is mapped or marked as
* swapped out.
*\param[in] virtualAddress the virtual address
*\param[out] pageTableEntry pointer to the page table entry
*\return true, if the page table is present and the page mapped or marked swapped out, false
* otherwise */
bool getPageTableEntry(void *virtualAddress,
uint32_t *&pageTableEntry);
/** Convert the processor independant flags to the processor's representation of the flags
*\param[in] flags the processor independant flag representation
*\return the proessor specific flag representation */
uint32_t toFlags(size_t flags);
/** Convert processor's representation of the flags to the processor independant representation
*\param[in] Flags the processor specific flag representation
*\return the proessor independant flag representation */
size_t fromFlags(uint32_t Flags);
/** Begins a "cross-address-space" transaction; maps this address space's
page directory and a page table in temporarily to the current address
space, to be used with mapCrossSpace.
This uses the pages "KERNEL_VIRTUAL_TEMP2" and "KERNEL_VIRTUAL_TEMP3".
\return A value to pass to mapCrossSpace. This value contains the
current page table mapped into KERNEL_VIRTUAL_TEMP3. */
uintptr_t beginCrossSpace(X86VirtualAddressSpace *pOther);
/** The mapping function for cross-space mappings. beginCrossSpace must be
called first.
\param v Value given by "beginCrossSpace". */
bool mapCrossSpace(uintptr_t &v,
physical_uintptr_t physicalAddress,
void *virtualAddress,
size_t flags);
/** Called to end a cross-space transaction. */
void endCrossSpace();
/** Physical address of the page directory */
physical_uintptr_t m_PhysicalPageDirectory;
/** Virtual address of the page directory */
void *m_VirtualPageDirectory;
/** Virtual address of the page tables */
void *m_VirtualPageTables;
/** Current top of the stacks */
void *m_pStackTop;
/** List of free stacks */
Vector<void*> m_freeStacks;
/** Lock to guard against multiprocessor reentrancy. */
Spinlock m_Lock;
};
/** The kernel's VirtualAddressSpace on x86 */
class X86KernelVirtualAddressSpace : public X86VirtualAddressSpace
{
/** X86VirtualAddressSpace needs access to m_Instance */
friend class X86VirtualAddressSpace;
/** VirtualAddressSpace::getKernelAddressSpace() needs access to m_Instance */
friend VirtualAddressSpace &VirtualAddressSpace::getKernelAddressSpace();
public:
//
// VirtualAddressSpace Interface
//
virtual bool isMapped(void *virtualAddress);
virtual bool map(physical_uintptr_t physicalAddress,
void *virtualAddress,
size_t flags);
virtual void getMapping(void *virtualAddress,
physical_uintptr_t &physicalAddress,
size_t &flags);
virtual void setFlags(void *virtualAddress, size_t newFlags);
virtual void unmap(void *virtualAddress);
virtual void *allocateStack();
private:
/** The constructor */
X86KernelVirtualAddressSpace();
/** The destructor */
~X86KernelVirtualAddressSpace();
/** The copy-constructor
*\note NOT implemented (Singleton) */
X86KernelVirtualAddressSpace(const X86KernelVirtualAddressSpace &);
/** The assignment operator
*\note NOT implemented (Singleton) */
X86KernelVirtualAddressSpace &operator = (const X86KernelVirtualAddressSpace &);
/** The kernel virtual address space */
static X86KernelVirtualAddressSpace m_Instance;
};
/** @} */
#endif
| jmolloy/pedigree | src/system/kernel/core/processor/x86/VirtualAddressSpace.h | C | isc | 11,604 |
<!DOCTYPE html>
<html lang="en-GB">
<head>
<base href="/">
<meta name="fragment" content="!" />
<title>Movies Search App</title>
</head>
<body>
<div data-ng-view></div>
<script src="/static/bundle.js"></script>
</body>
</html> | hyphenbash/movies-search | app/index.html | HTML | isc | 282 |
/*
* Copyright (c) 2015-2016, Fred Morcos <fred.morcos@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software
* for any purpose with or without fee is hereby granted, provided
* that the above copyright notice and this permission notice appear
* in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <assert.h>
#include <err.h>
#include "str.h"
#include "print.h"
char *humansize(long double size) {
assert(size > 0);
static const char units[] = "BKMGTPE";
static const size_t units_len = sizeof(units);
char *res = NULL;
size_t i = 0;
while (size >= 1024 && i < units_len) {
size /= 1024;
i++;
}
return xasprintf(NULL, &res, "%.2Lf%c", size, units[i])
< 0 ? NULL : res;
}
void print_bufstats(const size_t nent,
const size_t size,
const struct time_info *const ti) {
assert(ti != NULL);
assert(ti->cpu >= 0);
assert(ti->rt >= 0);
assert(ti->wc >= 0);
char *bufsize = NULL;
if (nent == 0) {
assert(size == 1);
warnx("OK: Loaded %zu entries", nent);
} else if ((bufsize = humansize(size))) {
warnx("OK: Loaded %zu entries into a %s buffer "
"in %.2Lfs cpu, %.2Lfs rt, %.2Lfs wc",
nent, bufsize, ti->cpu, ti->rt, ti->wc);
free(bufsize);
} else {
warnx("OK: Loaded %zu entries into a %zu bytes buffer "
"in %.2Lfs cpu, %.2Lfs rt, %.2Lfs wc",
nent, size, ti->cpu, ti->rt, ti->wc);
}
}
| fredmorcos/attic | projects/backy/libcore/print.c | C | isc | 2,009 |
# Picnic CSS
> Note: If your site breaks please read the [deprecation notice](https://github.com/picnicss/picnic/issues/42) (and I apologize for it).
Unpack your meal and get coding. An invasive CSS library to get your style started.
## Getting started
There are many ways of using Picnic CSS in your projects. Here a brief introduction of the recommended two methods:
### CDN - just give me the file
Use [Picnic CSS in the CDN jsDelivr](http://www.jsdelivr.com/#!picnicss) for linking to the static file.
### Bower - to personalize Picnic
To install Picnic with bower just write this in your terminal (you'll need bower installed):
bower install picnic
Then, to use it within your scss development cycle, just do:
// Here go any variables you want to overwrite
$picnic-primary: #faa;
// Now import picnic and a couple of plugins
@import 'BOWER_PATH/picnic/src/picnic';
@import 'BOWER_PATH/picnic/plugins/nav/plugin';
@import 'BOWER_PATH/picnic/plugins/modal/plugin';
### NPM
Just do
```bash
npm i -D picnic
```
To add it to your repository. Then you can include it straight from your css like:
```css
@import "../node_modules/picnic/releases/picnic.css";
```
Thanks to [chadoh](https://github.com/chadoh) for helping me in publishing it in NPM and for the instructions.
### Other ways
You can always download the latest minimized version from github, clone the repository or download it.
You can also [try it live in Codepen](http://codepen.io/FranciscoP/pen/ZGpzbL?editors=110).
Clone it: `git clone https://github.com/picnicss/picnic.git`
## Wait, *invasive*?
Many libraries rely upon adding classes to your already existing html elements, resulting in bloated code like `<button class="btn btn-primary">Hey</button>`. It would be easier if the buttons knew they are, well, *buttons*. Crazy eh?
This setup works neatly for newly created projects or for pages that you have to build quick from scratch. It also allows for a much more intuitive extension of base elements.
## Browser support IE9+
Bug reports and fixes only for IE9+. With IE8 usage [dropping *fast*](http://ux.stackexchange.com/a/643.61) and with IE9 and IE10 usage even below their older mate, it is time to start thinking about not supporting them anymore. However, bug fixes for IE9 will be accepted and everything is expected to run smooth down to it. For Chrome, Firefox, Opera and Safari up to 2 previous versions are expected to be working, and everything that is not is definitely a bug.
## Example usage
After including the stylesheet as indicated in the `Getting started`:
```html
<form>
What's your favourite Picnic CSS feature?
<label class="select">
<select name="feature">
<option value="semantic"> Semantic HTML5 </option>
<option value="lightweight"> Lightweight </option>
<option value="css3"> Only CSS3 </option>
<option value="responsive"> Responsive </option>
</select>
</label>
<input type="email" placeholder="Email to receive updates">
<button class="primary"> Subscribe! </button>
</form>
```
If you don't see anything that seems *picnic.css exclusive*, that's because there's nothing, that's the main purpose of Picnic CSS. However, try it out and you'll see a decent example in your browser.
## Advantages
- **Only CSS3** is needed and your **HTML5** stays highly semantic*.
- **Under 3kb** when minimized and gzipped and under 5kb with all plugins.
- **Normalize.css** is used as a base, achieving a solid foundation.
- **Support**: IE 9+ and others. No fancy CSS3 on IE 8.
- **Responsive**: The nav and the grids are responsive.
\* Except for the grids :(
## Disadvantages
- `select`, `radiobutton` and `checkbox` support is not great, however it's better than most of the similar solutions listed below. This is solved by making them optional. To make them work they require the use of a wrapper with a class. These are: `.select` for `<select>`, `.radio` for `<input type="radio">` and `.checkbox` for `<input type="checkbox">`. Pretty simple (:
- Difficult to drop in an already created project. This is what I meant by *invasive*. This is not within the new scope of the project.
- The grids introduce an unsemantic component to your HTML5 if you decide to use them. Not really a way to solve it, however the unsemantic bit is only a class called `.row`
## Alternatives and why I still created Picnic CSS
[PureCSS](http://purecss.io/): Lightweight, nice package. The thing I would be using if I didn't build Picnic CSS and where I took the inspiration. However, no nice `<select>` out of the box and the non-responsive grid from the CDN feels like a stab on the back.
[Bootstrap](http://getbootstrap.com/): Really comprehensive, but too many files and too heavy for most of the websites. It also relies too much on javascript. Still cannot get the `<select>` right out of the box.
[Min](http://minfwk.com/): a tiny, basic css framework. It has great browser support. No `<select>` right, and it's too inexpressive.
## Contributing
You are encouraged to contribute to Picnic CSS. To write a new plugin, just copy one of the existing ones (specially recommend "button") and modify the files. The code must be linted with scss-lint, except the `PropertySortOrder` which is ignored for a better code structure.
## Authors
Created by [Francisco Presencia](https://github.com/FranciscoP). SASS from [Jordan Wallwork](https://github.com/jordanwallwork). Significant fixes from [Alex Galushka](https://github.com/galulex). Tons of help in several parts of the project from [Emilio Coppola](https://github.com/Coppolaemilio).
## Some love
- [Clrs](http://clrs.cc/) the new nice web palette (from HN) used for Picnic CSS.
- [Fontello](http://fontello.com/) an icon library that plays really nice with others.
- [Tympanus buttons](http://tympanus.net/Development/CreativeButtons/) so many hours exploring its amazing CSS designs.
- [Normalize](http://necolas.github.io/normalize.css/) the foundation of Picnic CSS
| joerx/flux-do | public/vendor/picnic/README.md | Markdown | isc | 6,092 |
package info.faceland.loot.data;
public class PriceData {
private int price;
private boolean rare;
public PriceData (int price, boolean rare) {
this.price = price;
this.rare = rare;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public boolean isRare() {
return rare;
}
public void setRare(boolean rare) {
this.rare = rare;
}
}
| TealCube/loot | src/main/java/info/faceland/loot/data/PriceData.java | Java | isc | 435 |
#include "kvazaarfilter.h"
#include "statisticsinterface.h"
#include "common.h"
#include "settingskeys.h"
#include "logger.h"
#include <kvazaar.h>
#include <QtDebug>
#include <QTime>
#include <QSize>
enum RETURN_STATUS {C_SUCCESS = 0, C_FAILURE = -1};
KvazaarFilter::KvazaarFilter(QString id, StatisticsInterface *stats,
std::shared_ptr<HWResourceManager> hwResources):
Filter(id, "Kvazaar", stats, hwResources, DT_YUV420VIDEO, DT_HEVCVIDEO),
api_(nullptr),
config_(nullptr),
enc_(nullptr),
pts_(0),
input_pic_(nullptr),
framerate_num_(30),
framerate_denom_(1),
encodingFrames_()
{
maxBufferSize_ = 3;
}
void KvazaarFilter::updateSettings()
{
Logger::getLogger()->printNormal(this, "Updating kvazaar settings");
stop();
while(isRunning())
{
sleep(1);
}
close();
encodingFrames_.clear();
if(init())
{
Logger::getLogger()->printNormal(this, "Resolution change successful");
}
else
{
Logger::getLogger()->printNormal(this, "Failed to change resolution");
}
start();
Filter::updateSettings();
}
bool KvazaarFilter::init()
{
Logger::getLogger()->printNormal(this, "Iniating Kvazaar");
// input picture should not exist at this point
if(!input_pic_ && !api_)
{
api_ = kvz_api_get(8);
if(!api_)
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Failed to retrieve Kvazaar API.");
return false;
}
config_ = api_->config_alloc();
enc_ = nullptr;
if(!config_)
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Failed to allocate Kvazaar config.");
return false;
}
QSettings settings(settingsFile, settingsFileFormat);
api_->config_init(config_);
api_->config_parse(config_, "preset", settings.value(SettingsKey::videoPreset).toString().toUtf8());
// input
#ifdef __linux__
if (settingEnabled(SettingsKey::screenShareStatus))
{
config_->width = settings.value(SettingsKey::videoResultionWidth).toInt();
config_->height = settings.value(SettingsKey::videoResultionHeight).toInt();
framerate_num_ = settings.value(SettingsKey::videoFramerate).toFloat();
config_->framerate_num = framerate_num_;
}
else
{
// On Linux the Camerafilter seems to have a Qt bug that causes not being able to set resolution
config_->width = 640;
config_->height = 480;
config_->framerate_num = 30;
}
#else
config_->width = settings.value(SettingsKey::videoResultionWidth).toInt();
config_->height = settings.value(SettingsKey::videoResultionHeight).toInt();
convertFramerate(settings.value(SettingsKey::videoFramerate).toReal());
config_->framerate_num = framerate_num_;
#endif
config_->framerate_denom = framerate_denom_;
// parallelization
if (settings.value(SettingsKey::videoKvzThreads) == "auto")
{
config_->threads = QThread::idealThreadCount();
}
else if (settings.value(SettingsKey::videoKvzThreads) == "Main")
{
config_->threads = 0;
}
else
{
config_->threads = settings.value(SettingsKey::videoKvzThreads).toInt();
}
config_->owf = settings.value(SettingsKey::videoOWF).toInt();
config_->wpp = settings.value(SettingsKey::videoWPP).toInt();
bool tiles = false;
if (tiles)
{
std::string dimensions = settings.value(SettingsKey::videoTileDimensions).toString().toStdString();
api_->config_parse(config_, "tiles", dimensions.c_str());
}
// this does not work with uvgRTP at the moment. Avoid using slices.
if(settings.value(SettingsKey::videoSlices).toInt() == 1)
{
if(config_->wpp)
{
config_->slices = KVZ_SLICES_WPP;
}
else if (tiles)
{
config_->slices = KVZ_SLICES_TILES;
}
}
// Structure
config_->qp = settings.value(SettingsKey::videoQP).toInt();
config_->intra_period = settings.value(SettingsKey::videoIntra).toInt();
config_->vps_period = settings.value(SettingsKey::videoVPS).toInt();
config_->target_bitrate = settings.value(SettingsKey::videoBitrate).toInt();
if (config_->target_bitrate != 0)
{
QString rcAlgo = settings.value(SettingsKey::videoRCAlgorithm).toString();
if (rcAlgo == "lambda")
{
config_->rc_algorithm = KVZ_LAMBDA;
}
else if (rcAlgo == "oba")
{
config_->rc_algorithm = KVZ_OBA;
config_->clip_neighbour = settings.value(SettingsKey::videoOBAClipNeighbours).toInt();
}
else
{
Logger::getLogger()->printWarning(this, "Some carbage in rc algorithm setting");
config_->rc_algorithm = KVZ_NO_RC;
}
}
else
{
config_->rc_algorithm = KVZ_NO_RC;
}
config_->gop_lowdelay = 1;
if (settings.value(SettingsKey::videoScalingList).toInt() == 0)
{
config_->scaling_list = KVZ_SCALING_LIST_OFF;
}
else
{
config_->scaling_list = KVZ_SCALING_LIST_DEFAULT;
}
config_->lossless = settings.value(SettingsKey::videoLossless).toInt();
QString constraint = settings.value(SettingsKey::videoMVConstraint).toString();
if (constraint == "frame")
{
config_->mv_constraint = KVZ_MV_CONSTRAIN_FRAME;
}
else if (constraint == "tile")
{
config_->mv_constraint = KVZ_MV_CONSTRAIN_TILE;
}
else if (constraint == "frametile")
{
config_->mv_constraint = KVZ_MV_CONSTRAIN_FRAME_AND_TILE;
}
else if (constraint == "frametilemargin")
{
config_->mv_constraint = KVZ_MV_CONSTRAIN_FRAME_AND_TILE_MARGIN;
}
else
{
config_->mv_constraint = KVZ_MV_CONSTRAIN_NONE;
}
config_->set_qp_in_cu = settings.value(SettingsKey::videoQPInCU).toInt();
config_->vaq = settings.value(SettingsKey::videoVAQ).toInt();
// compression-tab
customParameters(settings);
config_->hash = KVZ_HASH_NONE;
enc_ = api_->encoder_open(config_);
if(!enc_)
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Failed to open Kvazaar encoder.");
return false;
}
input_pic_ = api_->picture_alloc(config_->width, config_->height);
if(!input_pic_)
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Could not allocate input picture.");
return false;
}
Logger::getLogger()->printNormal(this, "Kvazaar iniation succeeded");
}
return true;
}
void KvazaarFilter::close()
{
if(api_)
{
api_->encoder_close(enc_);
api_->config_destroy(config_);
enc_ = nullptr;
config_ = nullptr;
api_->picture_free(input_pic_);
input_pic_ = nullptr;
api_ = nullptr;
}
pts_ = 0;
Logger::getLogger()->printNormal(this, "Closed Kvazaar");
}
void KvazaarFilter::process()
{
Q_ASSERT(enc_);
Q_ASSERT(config_);
std::unique_ptr<Data> input = getInput();
while(input)
{
if(!input_pic_)
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this,
"Input picture was not allocated correctly.");
break;
}
feedInput(std::move(input));
input = getInput();
}
}
void KvazaarFilter::customParameters(QSettings& settings)
{
int size = settings.beginReadArray(SettingsKey::videoCustomParameters);
Logger::getLogger()->printNormal(this, "Getting custom Kvazaar parameters",
"Amount", QString::number(size));
for(int i = 0; i < size; ++i)
{
settings.setArrayIndex(i);
QString name = settings.value("Name").toString();
QString value = settings.value("Value").toString();
if (api_->config_parse(config_, name.toStdString().c_str(),
value.toStdString().c_str()) != 1)
{
Logger::getLogger()->printWarning(this, "Invalid custom parameter for kvazaar",
"Amount", QString::number(size));
}
}
settings.endArray();
}
void KvazaarFilter::feedInput(std::unique_ptr<Data> input)
{
kvz_picture *recon_pic = nullptr;
kvz_frame_info frame_info;
kvz_data_chunk *data_out = nullptr;
uint32_t len_out = 0;
if (config_->width != input->vInfo->width
|| config_->height != input->vInfo->height
|| (double)(config_->framerate_num/config_->framerate_denom) != input->vInfo->framerate)
{
// This should not happen.
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this,
"Input resolution or framerate differs from settings",
{"Settings", "Input"},
{QString::number(config_->width) + "x" +
QString::number(config_->height) + "p" +
QString::number(config_->framerate_num),
QString::number(input->vInfo->width) + "x" +
QString::number(input->vInfo->height) + "p" +
QString::number(input->vInfo->framerate)});
return;
}
// copy input to kvazaar picture
memcpy(input_pic_->y,
input->data.get(),
input->vInfo->width*input->vInfo->height);
memcpy(input_pic_->u,
&(input->data.get()[input->vInfo->width*input->vInfo->height]),
input->vInfo->width*input->vInfo->height/4);
memcpy(input_pic_->v,
&(input->data.get()[input->vInfo->width*input->vInfo->height + input->vInfo->width*input->vInfo->height/4]),
input->vInfo->width*input->vInfo->height/4);
input_pic_->pts = pts_;
++pts_;
encodingFrames_.push_front(std::move(input));
api_->encoder_encode(enc_, input_pic_,
&data_out, &len_out,
&recon_pic, nullptr,
&frame_info );
while(data_out != nullptr)
{
parseEncodedFrame(data_out, len_out, recon_pic);
// see if there is more output ready
api_->encoder_encode(enc_, nullptr,
&data_out, &len_out,
&recon_pic, nullptr,
&frame_info );
}
}
void KvazaarFilter::parseEncodedFrame(kvz_data_chunk *data_out,
uint32_t len_out, kvz_picture *recon_pic)
{
std::unique_ptr<Data> encodedFrame = std::move(encodingFrames_.back());
encodingFrames_.pop_back();
std::unique_ptr<uchar[]> hevc_frame(new uchar[len_out]);
uint8_t* writer = hevc_frame.get();
uint32_t dataWritten = 0;
for (kvz_data_chunk *chunk = data_out; chunk != nullptr; chunk = chunk->next)
{
if(chunk->len > 3 && chunk->data[0] == 0 && chunk->data[1] == 0
&& ( chunk->data[2] == 1 || (chunk->data[2] == 0 && chunk->data[3] == 1 ))
&& dataWritten != 0 && config_->slices != KVZ_SLICES_NONE)
{
// send previous packet if this is not the first
std::unique_ptr<Data> slice(shallowDataCopy(encodedFrame.get()));
sendEncodedFrame(std::move(slice), std::move(hevc_frame), dataWritten);
hevc_frame = std::unique_ptr<uchar[]>(new uchar[len_out - dataWritten]);
writer = hevc_frame.get();
dataWritten = 0;
}
memcpy(writer, chunk->data, chunk->len);
writer += chunk->len;
dataWritten += chunk->len;
}
api_->chunk_free(data_out);
api_->picture_free(recon_pic);
uint32_t delay = QDateTime::currentMSecsSinceEpoch() - encodedFrame->presentationTime;
getStats()->sendDelay("video", delay);
getStats()->addEncodedPacket("video", len_out);
// send last packet reusing input structure
sendEncodedFrame(std::move(encodedFrame), std::move(hevc_frame), dataWritten);
}
void KvazaarFilter::sendEncodedFrame(std::unique_ptr<Data> input,
std::unique_ptr<uchar[]> hevc_frame,
uint32_t dataWritten)
{
input->type = DT_HEVCVIDEO;
input->data_size = dataWritten;
input->data = std::move(hevc_frame);
sendOutput(std::move(input));
}
void KvazaarFilter::convertFramerate(double framerate)
{
uint32_t wholeNumber = (uint32_t)framerate;
double remainder = framerate - wholeNumber;
if (remainder > 0.0)
{
uint32_t multiplier = 1.0 /remainder;
framerate_num_ = framerate*multiplier;
framerate_denom_ = multiplier;
}
else
{
framerate_num_ = wholeNumber;
framerate_denom_ = 1;
}
Logger::getLogger()->printNormal(this, "Got framerate num and denum", "Framerate",
{QString::number(framerate_num_) + "/" +
QString::number(framerate_denom_) });
}
| ultravideo/kvazzup | src/media/processing/kvazaarfilter.cpp | C++ | isc | 12,600 |
/* @flow */
import { PropTypes } from 'react'
export default PropTypes.oneOfType([
// [Number, Number]
PropTypes.arrayOf(PropTypes.number),
// {lat: Number, lng: Number}
PropTypes.shape({
lat: PropTypes.number,
lng: PropTypes.number,
}),
// {lat: Number, lon: Number}
PropTypes.shape({
lat: PropTypes.number,
lon: PropTypes.number,
}),
])
| wxtiles/wxtiles-map | node_modules/react-leaflet/src/types/latlng.js | JavaScript | isc | 373 |
# straycats
Straycats is a silly demo application that I use to explore various technologies and architectures.
The idea is an application where anyone can report the sighting of a cat, and users can signup and search for reported cats, and choose to be notified when a critter matching their criteria is reported.
# Ideas to explore
* Deploy to AWS using Elastic Beanstalk
* AWS DynamoDB and SQS
* Frontend using bower, grunt/gulp and good test coverage
* Possible a mobile (android) application
* Using geolocation when reporting a sighting or searching
# Technologies
More to come...
| RuneMolin/straycats | README.md | Markdown | isc | 590 |
/* $OpenBSD: cread.c,v 1.13 2009/01/18 21:46:50 miod Exp $ */
/* $NetBSD: cread.c,v 1.2 1997/02/04 18:38:20 thorpej Exp $ */
/*
* Copyright (c) 1996
* Matthias Drochner. 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 THE AUTHOR ``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 AUTHOR 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.
*
*/
/* support for compressed bootfiles
(only read)
replaces open(), close(), read(), lseek().
original libsa open(), close(), read(), lseek() are called
as oopen(), oclose(), oread() resp. olseek().
compression parts stripped from zlib:gzio.c
*/
/* gzio.c -- IO on .gz files
* Copyright (C) 1995-1996 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#include "stand.h"
#include "../libz/zlib.h"
#define EOF (-1) /* needed by compression code */
#define zmemcpy memcpy
#ifdef SAVE_MEMORY
#define Z_BUFSIZE 1024
#else
#define Z_BUFSIZE 4096
#endif
static int gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
/* gzip flag byte */
#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */
#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
#define ORIG_NAME 0x08 /* bit 3 set: original file name present */
#define COMMENT 0x10 /* bit 4 set: file comment present */
#define RESERVED 0xE0 /* bits 5..7: reserved */
static struct sd {
z_stream stream;
int z_err; /* error code for last stream operation */
int z_eof; /* set if end of input file */
int fd;
unsigned char *inbuf; /* input buffer */
unsigned long crc; /* crc32 of uncompressed data */
int transparent; /* 1 if input file is not a .gz file */
} *ss[SOPEN_MAX];
#ifdef DEBUG
int z_verbose = 0;
#endif
/*
* compression utilities
*/
void *zcalloc(void *, unsigned int, unsigned int);
void zcfree(void *, void *);
void *
zcalloc(void *opaque, unsigned int items, unsigned int size)
{
return(alloc(items * size));
}
void
zcfree(void *opaque, void *ptr)
{
free(ptr, 0); /* XXX works only with modified allocator */
}
static int
get_byte(struct sd *s)
{
if (s->z_eof)
return EOF;
if (s->stream.avail_in == 0) {
errno = 0;
s->stream.avail_in = oread(s->fd, s->inbuf, Z_BUFSIZE);
if (s->stream.avail_in <= 0) {
s->z_eof = 1;
if (errno)
s->z_err = Z_ERRNO;
return EOF;
}
s->stream.next_in = s->inbuf;
}
s->stream.avail_in--;
return *(s->stream.next_in)++;
}
static unsigned long
getLong(struct sd *s)
{
unsigned long x = (unsigned long)get_byte(s);
int c;
x += ((unsigned long)get_byte(s))<<8;
x += ((unsigned long)get_byte(s))<<16;
c = get_byte(s);
if (c == EOF)
s->z_err = Z_DATA_ERROR;
x += ((unsigned long)c)<<24;
return x;
}
static void
check_header(struct sd *s)
{
int method; /* method byte */
int flags; /* flags byte */
unsigned int len;
int c;
/* Check the gzip magic header */
for (len = 0; len < 2; len++) {
c = get_byte(s);
if (c != gz_magic[len]) {
if (len != 0) {
s->stream.avail_in++;
s->stream.next_in--;
}
if (c != EOF) {
s->stream.avail_in++;
s->stream.next_in--;
s->transparent = 1;
}
s->z_err = s->stream.avail_in != 0 ? Z_OK :
Z_STREAM_END;
return;
}
}
method = get_byte(s);
flags = get_byte(s);
if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
s->z_err = Z_DATA_ERROR;
return;
}
/* Discard time, xflags and OS code: */
for (len = 0; len < 6; len++)
(void)get_byte(s);
if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
len = (unsigned int)get_byte(s);
len += ((unsigned int)get_byte(s))<<8;
/* len is garbage if EOF but the loop below will quit anyway */
while (len-- != 0 && get_byte(s) != EOF)
;
}
if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
while ((c = get_byte(s)) != 0 && c != EOF)
;
}
if ((flags & COMMENT) != 0) { /* skip the .gz file comment */
while ((c = get_byte(s)) != 0 && c != EOF)
;
}
if ((flags & HEAD_CRC) != 0) { /* skip the header crc */
for (len = 0; len < 2; len++)
(void)get_byte(s);
}
s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK;
}
/*
* new open(), close(), read(), lseek()
*/
int
open(const char *fname, int mode)
{
int fd;
struct sd *s = 0;
if (((fd = oopen(fname, mode)) == -1) ||
(mode != 0)) /* compression only for read */
return(fd);
ss[fd] = s = alloc(sizeof(struct sd));
if (!s)
goto errout;
bzero(s, sizeof(struct sd));
#ifdef SAVE_MEMORY
if (inflateInit2(&(s->stream), -11) != Z_OK)
#else
if (inflateInit2(&(s->stream), -15) != Z_OK)
#endif
goto errout;
s->stream.next_in = s->inbuf = (unsigned char *)alloc(Z_BUFSIZE);
if (!s->inbuf) {
inflateEnd(&(s->stream));
goto errout;
}
s->fd = fd;
check_header(s); /* skip the .gz header */
return(fd);
errout:
if (s)
free(s, sizeof(struct sd));
oclose(fd);
return(-1);
}
int
close(int fd)
{
struct open_file *f;
struct sd *s;
if ((unsigned)fd >= SOPEN_MAX) {
errno = EBADF;
return (-1);
}
f = &files[fd];
if (!(f->f_flags & F_READ))
return(oclose(fd));
s = ss[fd];
if (s != NULL) {
inflateEnd(&(s->stream));
free(s->inbuf, Z_BUFSIZE);
free(s, sizeof(struct sd));
}
return(oclose(fd));
}
ssize_t
read(int fd, void *buf, size_t len)
{
struct sd *s;
unsigned char *start = buf; /* starting point for crc computation */
s = ss[fd];
if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO)
return -1;
if (s->z_err == Z_STREAM_END)
return 0; /* EOF */
s->stream.next_out = buf;
s->stream.avail_out = len;
while (s->stream.avail_out != 0) {
if (s->transparent) {
/* Copy first the lookahead bytes: */
unsigned int n = s->stream.avail_in;
if (n > s->stream.avail_out)
n = s->stream.avail_out;
if (n > 0) {
zmemcpy(s->stream.next_out, s->stream.next_in, n);
s->stream.next_out += n;
s->stream.next_in += n;
s->stream.avail_out -= n;
s->stream.avail_in -= n;
}
if (s->stream.avail_out > 0) {
int n;
n = oread(fd, s->stream.next_out,
s->stream.avail_out);
if (n <= 0) {
s->z_eof = 1;
if (errno) {
s->z_err = Z_ERRNO;
break;
}
}
s->stream.avail_out -= n;
}
len -= s->stream.avail_out;
s->stream.total_in += (unsigned long)len;
s->stream.total_out += (unsigned long)len;
if (len == 0)
s->z_eof = 1;
return (int)len;
}
if (s->stream.avail_in == 0 && !s->z_eof) {
errno = 0;
s->stream.avail_in = oread(fd, s->inbuf, Z_BUFSIZE);
if (s->stream.avail_in <= 0) {
s->z_eof = 1;
if (errno) {
s->z_err = Z_ERRNO;
break;
}
}
s->stream.next_in = s->inbuf;
}
s->z_err = inflate(&(s->stream), Z_NO_FLUSH);
if (s->z_err == Z_STREAM_END) {
/* Check CRC and original size */
s->crc = crc32(s->crc, start,
(unsigned int)(s->stream.next_out - start));
start = s->stream.next_out;
if (getLong(s) != s->crc) {
s->z_err = Z_DATA_ERROR;
} else {
(void)getLong(s);
/* The uncompressed length returned by
* above getlong() may be different from
* s->stream.total_out in case of concatenated
* .gz files. Check for such files:
*/
check_header(s);
if (s->z_err == Z_OK) {
unsigned long total_in = s->stream.total_in;
unsigned long total_out = s->stream.total_out;
inflateReset(&(s->stream));
s->stream.total_in = total_in;
s->stream.total_out = total_out;
s->crc = crc32(0L, Z_NULL, 0);
}
}
}
if (s->z_err != Z_OK || s->z_eof)
break;
}
s->crc = crc32(s->crc, start, (unsigned int)(s->stream.next_out - start));
return (int)(len - s->stream.avail_out);
}
off_t
lseek(int fd, off_t offset, int where)
{
struct open_file *f;
struct sd *s;
if ((unsigned)fd >= SOPEN_MAX) {
errno = EBADF;
return (-1);
}
f = &files[fd];
if (!(f->f_flags & F_READ))
return(olseek(fd, offset, where));
s = ss[fd];
if (s->transparent) {
off_t res = olseek(fd, offset, where);
if (res != (off_t)-1) {
/* make sure the lookahead buffer is invalid */
s->stream.avail_in = 0;
}
return(res);
}
switch(where) {
case SEEK_CUR:
offset += s->stream.total_out;
case SEEK_SET:
/* if seek backwards, simply start from
the beginning */
if (offset < s->stream.total_out) {
off_t res;
void *sav_inbuf;
res = olseek(fd, 0, SEEK_SET);
if (res == (off_t)-1)
return(res);
/* ??? perhaps fallback to close / open */
inflateEnd(&(s->stream));
sav_inbuf = s->inbuf; /* don't allocate again */
bzero(s, sizeof(struct sd)); /* this resets total_out to 0! */
inflateInit2(&(s->stream), -15);
s->stream.next_in = s->inbuf = sav_inbuf;
s->fd = fd;
check_header(s); /* skip the .gz header */
}
/* to seek forwards, throw away data */
if (offset > s->stream.total_out) {
off_t toskip = offset - s->stream.total_out;
while(toskip > 0) {
#define DUMMYBUFSIZE 256
char dummybuf[DUMMYBUFSIZE];
off_t len = toskip;
if (len > DUMMYBUFSIZE)
len = DUMMYBUFSIZE;
if (read(fd, dummybuf, len) != len) {
errno = EOFFSET;
return((off_t)-1);
}
toskip -= len;
}
}
#ifdef DEBUG
if (offset != s->stream.total_out)
panic("lseek compressed");
#endif
return(offset);
case SEEK_END:
errno = EOFFSET;
break;
default:
errno = EINVAL;
}
return((off_t)-1);
}
| orumin/openbsd-efivars | lib/libsa/cread.c | C | isc | 10,442 |
//
// 2015.10.28 -- world-zones
//
// simple nimble elements example
//
#compile
> nimble
#run
open _build/index.html in browser
| q9design/nimble-elements | templates/bootstrap/world-zones/README.md | Markdown | isc | 138 |
// Arguments: Doubles, Doubles, Doubles
#include <stan/math/prim/scal.hpp>
using std::vector;
using std::numeric_limits;
using stan::math::var;
class AgradCdfGumbel : public AgradCdfTest {
public:
void valid_values(vector<vector<double> >& parameters,
vector<double>& cdf) {
vector<double> param(3);
param[0] = 0.0; // y
param[1] = 0.0; // mu
param[2] = 1.0; // beta
parameters.push_back(param);
cdf.push_back(0.3678794411714423215955237701614608674458111310317678); // expected cdf
param[0] = 1.0; // y
param[1] = 0.0; // mu
param[2] = 1.0; // beta
parameters.push_back(param);
cdf.push_back(0.6922006275553463538654219971827897614906780292975447); // expected cdf
param[0] = -2.0; // y
param[1] = 0.0; // mu
param[2] = 1.0; // beta
parameters.push_back(param);
cdf.push_back(0.0006179789893310934986195216040530260548886143651007); // expected cdf
param[0] = -3.5; // y
param[1] = 1.9; // mu
param[2] = 7.2; // beta
parameters.push_back(param);
cdf.push_back(0.1203922620798295861862650786832089422663975274508450); // expected cdf
}
void invalid_values(vector<size_t>& index,
vector<double>& value) {
// y
// mu
index.push_back(1U);
value.push_back(numeric_limits<double>::infinity());
index.push_back(1U);
value.push_back(-numeric_limits<double>::infinity());
// beta
index.push_back(2U);
value.push_back(0.0);
index.push_back(2U);
value.push_back(-1.0);
index.push_back(2U);
value.push_back(-numeric_limits<double>::infinity());
}
bool has_lower_bound() {
return false;
}
bool has_upper_bound() {
return false;
}
template <typename T_y, typename T_loc, typename T_scale,
typename T3, typename T4, typename T5>
typename stan::return_type<T_y, T_loc, T_scale>::type
cdf(const T_y& y, const T_loc& mu, const T_scale& beta,
const T3&, const T4&, const T5&) {
return stan::math::gumbel_cdf(y, mu, beta);
}
template <typename T_y, typename T_loc, typename T_scale,
typename T3, typename T4, typename T5>
typename stan::return_type<T_y, T_loc, T_scale>::type
cdf_function(const T_y& y, const T_loc& mu, const T_scale& beta,
const T3&, const T4&, const T5&) {
return exp(-exp(-(y - mu) / beta));
}
};
| ariddell/httpstan | httpstan/lib/stan/lib/stan_math/test/prob/gumbel/gumbel_cdf_test.hpp | C++ | isc | 2,497 |
module Users::FollowHelper
end
| smlsml/snappitt | app/helpers/users/follow_helper.rb | Ruby | isc | 31 |
import { modulo } from './Math.js'
export function random(x) {
return modulo(Math.sin(x) * 43758.5453123, 1)
}
| damienmortini/dlib | packages/core/math/PRNG.js | JavaScript | isc | 114 |
const test = require('tape')
const sinon = require('sinon')
const helpers = require('../test/helpers')
const MockCrock = require('../test/MockCrock')
const bindFunc = helpers.bindFunc
const curry = require('./curry')
const _compose = curry(require('./compose'))
const isFunction = require('./isFunction')
const isObject = require('./isObject')
const isSameType = require('./isSameType')
const isString = require('./isString')
const unit = require('./_unit')
const fl = require('./flNames')
const Maybe = require('./Maybe')
const Pred = require('./Pred')
const constant = x => () => x
const identity = x => x
const applyTo =
x => fn => fn(x)
const List = require('./List')
test('List', t => {
const f = x => List(x).toArray()
t.ok(isFunction(List), 'is a function')
t.ok(isObject(List([])), 'returns an object')
t.equals(List([]).constructor, List, 'provides TypeRep on constructor')
t.ok(isFunction(List.of), 'provides an of function')
t.ok(isFunction(List.fromArray), 'provides a fromArray function')
t.ok(isFunction(List.type), 'provides a type function')
t.ok(isString(List['@@type']), 'provides a @@type string')
const err = /List: List must wrap something/
t.throws(List, err, 'throws with no parameters')
t.same(f(undefined), [ undefined ], 'wraps value in array when called with undefined')
t.same(f(null), [ null ], 'wraps value in array when called with null')
t.same(f(0), [ 0 ], 'wraps value in array when called with falsey number')
t.same(f(1), [ 1 ], 'wraps value in array when called with truthy number')
t.same(f(''), [ '' ], 'wraps value in array when called with falsey string')
t.same(f('string'), [ 'string' ], 'wraps value in array when called with truthy string')
t.same(f(false), [ false ], 'wraps value in array when called with false')
t.same(f(true), [ true ], 'wraps value in array when called with true')
t.same(f({}), [ {} ], 'wraps value in array when called with an Object')
t.same(f([ 1, 2, 3 ]), [ 1, 2, 3 ], 'Does not wrap an array, just uses it as the list')
t.end()
})
test('List fantasy-land api', t => {
const m = List('value')
t.ok(isFunction(List[fl.empty]), 'provides empty function on constructor')
t.ok(isFunction(List[fl.of]), 'provides of function on constructor')
t.ok(isFunction(m[fl.of]), 'provides of method on instance')
t.ok(isFunction(m[fl.empty]), 'provides empty method on instance')
t.ok(isFunction(m[fl.equals]), 'provides equals method on instance')
t.ok(isFunction(m[fl.concat]), 'provides concat method on instance')
t.ok(isFunction(m[fl.map]), 'provides map method on instance')
t.ok(isFunction(m[fl.chain]), 'provides chain method on instance')
t.ok(isFunction(m[fl.reduce]), 'provides reduce method on instance')
t.ok(isFunction(m[fl.filter]), 'provides filter method on instance')
t.end()
})
test('List @@implements', t => {
const f = List['@@implements']
t.equal(f('ap'), true, 'implements ap func')
t.equal(f('chain'), true, 'implements chain func')
t.equal(f('concat'), true, 'implements concat func')
t.equal(f('empty'), true, 'implements empty func')
t.equal(f('equals'), true, 'implements equals func')
t.equal(f('map'), true, 'implements map func')
t.equal(f('of'), true, 'implements of func')
t.equal(f('reduce'), true, 'implements reduce func')
t.equal(f('traverse'), true, 'implements traverse func')
t.end()
})
test('List fromArray', t => {
const fromArray = bindFunc(List.fromArray)
const err = /List.fromArray: Array required/
t.throws(fromArray(undefined), err, 'throws with undefined')
t.throws(fromArray(null), err, 'throws with null')
t.throws(fromArray(0), err, 'throws with falsey number')
t.throws(fromArray(1), err, 'throws with truthy number')
t.throws(fromArray(''), err, 'throws with falsey string')
t.throws(fromArray('string'), err, 'throws with truthy string')
t.throws(fromArray(false), err, 'throws with false')
t.throws(fromArray(true), err, 'throws with true')
t.throws(fromArray({}), err, 'throws with an object')
const data = [ [ 2, 1 ], 'a' ]
t.ok(isSameType(List, List.fromArray([ 0 ])), 'returns a List')
t.same(List.fromArray(data).valueOf(), data, 'wraps the value passed into List in an array')
t.end()
})
test('List inspect', t => {
const m = List([ 1, true, 'string' ])
t.ok(isFunction(m.inspect), 'provides an inpsect function')
t.equal(m.inspect, m.toString, 'toString is the same function as inspect')
t.equal(m.inspect(), 'List [ 1, true, "string" ]', 'returns inspect string')
t.end()
})
test('List type', t => {
const m = List([])
t.ok(isFunction(m.type), 'is a function')
t.equal(m.type, List.type, 'static and instance versions are the same')
t.equal(m.type(), 'List', 'returns List')
t.end()
})
test('List @@type', t => {
const m = List([])
t.equal(m['@@type'], List['@@type'], 'static and instance versions are the same')
t.equal(m['@@type'], 'crocks/List@4', 'returns crocks/List@4')
t.end()
})
test('List head', t => {
const empty = List.empty()
const one = List.of(1)
const two = List([ 2, 3 ])
t.ok(isFunction(two.head), 'Provides a head Function')
t.ok(isSameType(Maybe, empty.head()), 'empty List returns a Maybe')
t.ok(isSameType(Maybe, one.head()), 'one element List returns a Maybe')
t.ok(isSameType(Maybe, two.head()), 'two element List returns a Maybe')
t.equal(empty.head().option('Nothing'), 'Nothing', 'empty List returns a Nothing')
t.equal(one.head().option('Nothing'), 1, 'one element List returns a `Just 1`')
t.equal(two.head().option('Nothing'), 2, 'two element List returns a `Just 2`')
t.end()
})
test('List tail', t => {
const empty = List.empty()
const one = List.of(1)
const two = List([ 2, 3 ])
const three = List([ 4, 5, 6 ])
t.ok(isFunction(two.tail), 'Provides a tail Function')
t.equal(empty.tail().type(), Maybe.type(), 'empty List returns a Maybe')
t.equal(one.tail().type(), Maybe.type(), 'one element List returns a Maybe')
t.equal(two.tail().type(), Maybe.type(), 'two element List returns a Maybe')
t.equal(three.tail().type(), Maybe.type(), 'three element List returns a Maybe')
t.equal(empty.tail().option('Nothing'), 'Nothing', 'empty List returns a Nothing')
t.equal(one.tail().option('Nothing'), 'Nothing', 'one element List returns a `Just 1`')
t.equal(two.tail().option('Nothing').type(), 'List', 'two element List returns a `Just List`')
t.same(two.tail().option('Nothing').valueOf(), [ 3 ], 'two element Maybe List contains `[ 3 ]`')
t.equal(three.tail().option('Nothing').type(), 'List', 'three element List returns a `Just List`')
t.same(three.tail().option('Nothing').valueOf(), [ 5, 6 ], 'three element Maybe List contains `[ 5, 6 ]`')
t.end()
})
test('List cons', t => {
const list = List.of('guy')
const consed = list.cons('hello')
t.ok(isFunction(list.cons), 'provides a cons function')
t.notSame(list.valueOf(), consed.valueOf(), 'keeps old list intact')
t.same(consed.valueOf(), [ 'hello', 'guy' ], 'returns a list with the element pushed to front')
t.end()
})
test('List valueOf', t => {
const x = List([ 'some-thing', 34 ]).valueOf()
t.same(x, [ 'some-thing', 34 ], 'provides the wrapped array')
t.end()
})
test('List toArray', t => {
const data = [ 'some-thing', [ 'else', 43 ], 34 ]
const a = List(data).toArray()
t.same(a, data, 'provides the wrapped array')
t.end()
})
test('List equals functionality', t => {
const a = List([ 'a', 'b' ])
const b = List([ 'a', 'b' ])
const c = List([ '1', 'b' ])
const value = 'yep'
const nonList = { type: 'List...Not' }
t.equal(a.equals(c), false, 'returns false when 2 Lists are not equal')
t.equal(a.equals(b), true, 'returns true when 2 Lists are equal')
t.equal(a.equals(value), false, 'returns false when passed a simple value')
t.equal(a.equals(nonList), false, 'returns false when passed a non-List')
t.end()
})
test('List equals properties (Setoid)', t => {
const a = List([ 0, 'like' ])
const b = List([ 0, 'like' ])
const c = List([ 1, 'rainbow' ])
const d = List([ 'like', 0 ])
t.ok(isFunction(List([]).equals), 'provides an equals function')
t.equal(a.equals(a), true, 'reflexivity')
t.equal(a.equals(b), b.equals(a), 'symmetry (equal)')
t.equal(a.equals(c), c.equals(a), 'symmetry (!equal)')
t.equal(a.equals(b) && b.equals(d), a.equals(d), 'transitivity')
t.end()
})
test('List concat properties (Semigroup)', t => {
const a = List([ 1, '' ])
const b = List([ 0, null ])
const c = List([ true, 'string' ])
const left = a.concat(b).concat(c)
const right = a.concat(b.concat(c))
t.ok(isFunction(a.concat), 'provides a concat function')
t.same(left.valueOf(), right.valueOf(), 'associativity')
t.equal(a.concat(b).type(), a.type(), 'returns a List')
t.end()
})
test('List concat errors', t => {
const a = List([ 1, 2 ])
const notList = { type: constant('List...Not') }
const cat = bindFunc(a.concat)
const err = /List.concat: List required/
t.throws(cat(undefined), err, 'throws with undefined')
t.throws(cat(null), err, 'throws with null')
t.throws(cat(0), err, 'throws with falsey number')
t.throws(cat(1), err, 'throws with truthy number')
t.throws(cat(''), err, 'throws with falsey string')
t.throws(cat('string'), err, 'throws with truthy string')
t.throws(cat(false), err, 'throws with false')
t.throws(cat(true), err, 'throws with true')
t.throws(cat([]), err, 'throws with an array')
t.throws(cat({}), err, 'throws with an object')
t.throws(cat(notList), err, 'throws when passed non-List')
t.end()
})
test('List concat fantasy-land errors', t => {
const a = List([ 1, 2 ])
const notList = { type: constant('List...Not') }
const cat = bindFunc(a[fl.concat])
const err = /List.fantasy-land\/concat: List required/
t.throws(cat(undefined), err, 'throws with undefined')
t.throws(cat(null), err, 'throws with null')
t.throws(cat(0), err, 'throws with falsey number')
t.throws(cat(1), err, 'throws with truthy number')
t.throws(cat(''), err, 'throws with falsey string')
t.throws(cat('string'), err, 'throws with truthy string')
t.throws(cat(false), err, 'throws with false')
t.throws(cat(true), err, 'throws with true')
t.throws(cat([]), err, 'throws with an array')
t.throws(cat({}), err, 'throws with an object')
t.throws(cat(notList), err, 'throws when passed non-List')
t.end()
})
test('List concat functionality', t => {
const a = List([ 1, 2 ])
const b = List([ 3, 4 ])
t.same(a.concat(b).valueOf(), [ 1, 2, 3, 4 ], 'concats second to first')
t.same(b.concat(a).valueOf(), [ 3, 4, 1, 2 ], 'concats first to second')
t.end()
})
test('List empty properties (Monoid)', t => {
const m = List([ 1, 2 ])
t.ok(isFunction(m.concat), 'provides a concat function')
t.ok(isFunction(m.empty), 'provides an empty function')
const right = m.concat(m.empty())
const left = m.empty().concat(m)
t.same(right.valueOf(), m.valueOf(), 'right identity')
t.same(left.valueOf(), m.valueOf(), 'left identity')
t.end()
})
test('List empty functionality', t => {
const x = List([ 0, 1, true ]).empty()
t.equal(x.type(), 'List', 'provides a List')
t.same(x.valueOf(), [], 'provides an empty array')
t.end()
})
test('List reduce errors', t => {
const reduce = bindFunc(List([ 1, 2 ]).reduce)
const err = /List.reduce: Function required for first argument/
t.throws(reduce(undefined, 0), err, 'throws with undefined in the first argument')
t.throws(reduce(null, 0), err, 'throws with null in the first argument')
t.throws(reduce(0, 0), err, 'throws with falsey number in the first argument')
t.throws(reduce(1, 0), err, 'throws with truthy number in the first argument')
t.throws(reduce('', 0), err, 'throws with falsey string in the first argument')
t.throws(reduce('string', 0), err, 'throws with truthy string in the first argument')
t.throws(reduce(false, 0), err, 'throws with false in the first argument')
t.throws(reduce(true, 0), err, 'throws with true in the first argument')
t.throws(reduce({}, 0), err, 'throws with an object in the first argument')
t.throws(reduce([], 0), err, 'throws with an array in the first argument')
t.end()
})
test('List reduce fantasy-land errors', t => {
const reduce = bindFunc(List([ 1, 2 ])[fl.reduce])
const err = /List.fantasy-land\/reduce: Function required for first argument/
t.throws(reduce(undefined, 0), err, 'throws with undefined in the first argument')
t.throws(reduce(null, 0), err, 'throws with null in the first argument')
t.throws(reduce(0, 0), err, 'throws with falsey number in the first argument')
t.throws(reduce(1, 0), err, 'throws with truthy number in the first argument')
t.throws(reduce('', 0), err, 'throws with falsey string in the first argument')
t.throws(reduce('string', 0), err, 'throws with truthy string in the first argument')
t.throws(reduce(false, 0), err, 'throws with false in the first argument')
t.throws(reduce(true, 0), err, 'throws with true in the first argument')
t.throws(reduce({}, 0), err, 'throws with an object in the first argument')
t.throws(reduce([], 0), err, 'throws with an array in the first argument')
t.end()
})
test('List reduce functionality', t => {
const f = (y, x) => y + x
const m = List([ 1, 2, 3 ])
t.equal(m.reduce(f, 0), 6, 'reduces as expected with a neutral initial value')
t.equal(m.reduce(f, 10), 16, 'reduces as expected with a non-neutral initial value')
t.end()
})
test('List reduceRight errors', t => {
const reduce = bindFunc(List([ 1, 2 ]).reduceRight)
const err = /List.reduceRight: Function required for first argument/
t.throws(reduce(undefined, 0), err, 'throws with undefined in the first argument')
t.throws(reduce(null, 0), err, 'throws with null in the first argument')
t.throws(reduce(0, 0), err, 'throws with falsey number in the first argument')
t.throws(reduce(1, 0), err, 'throws with truthy number in the first argument')
t.throws(reduce('', 0), err, 'throws with falsey string in the first argument')
t.throws(reduce('string', 0), err, 'throws with truthy string in the first argument')
t.throws(reduce(false, 0), err, 'throws with false in the first argument')
t.throws(reduce(true, 0), err, 'throws with true in the first argument')
t.throws(reduce({}, 0), err, 'throws with an object in the first argument')
t.throws(reduce([], 0), err, 'throws with an array in the first argument')
t.end()
})
test('List reduceRight functionality', t => {
const f = (y, x) => y.concat(x)
const m = List([ '1', '2', '3' ])
t.equal(m.reduceRight(f, '4'), '4321', 'reduces as expected')
t.end()
})
test('List fold errors', t => {
const f = bindFunc(x => List(x).fold())
const noSemi = /^TypeError: List.fold: List must contain Semigroups of the same type/
t.throws(f(undefined), noSemi, 'throws when contains single undefined')
t.throws(f(null), noSemi, 'throws when contains single null')
t.throws(f(0), noSemi, 'throws when contains single falsey number')
t.throws(f(1), noSemi, 'throws when contains single truthy number')
t.throws(f(false), noSemi, 'throws when contains single false')
t.throws(f(true), noSemi, 'throws when contains single true')
t.throws(f({}), noSemi, 'throws when contains a single object')
t.throws(f(unit), noSemi, 'throws when contains a single function')
const empty = /^TypeError: List.fold: List must contain at least one Semigroup/
t.throws(f([]), empty, 'throws when empty')
const diff = /^TypeError: List.fold: List must contain Semigroups of the same type/
t.throws(f([ [], '' ]), diff, 'throws when empty')
t.end()
})
test('List fold functionality', t => {
const f = x => List(x).fold()
t.same(f([ [ 1 ], [ 2 ] ]), [ 1, 2 ], 'combines and extracts semigroups')
t.equals(f('lucky'), 'lucky', 'extracts a single semigroup')
t.end()
})
test('List foldMap errors', t => {
const noFunc = bindFunc(fn => List([ 1 ]).foldMap(fn))
const funcErr = /^TypeError: List.foldMap: Semigroup returning function required/
t.throws(noFunc(undefined), funcErr, 'throws with undefined')
t.throws(noFunc(null), funcErr, 'throws with null')
t.throws(noFunc(0), funcErr, 'throws with falsey number')
t.throws(noFunc(1), funcErr, 'throws with truthy number')
t.throws(noFunc(false), funcErr, 'throws with false')
t.throws(noFunc(true), funcErr, 'throws with true')
t.throws(noFunc(''), funcErr, 'throws with falsey string')
t.throws(noFunc('string'), funcErr, 'throws with truthy string')
t.throws(noFunc({}), funcErr, 'throws with an object')
t.throws(noFunc([]), funcErr, 'throws with an array')
const fn = bindFunc(x => List(x).foldMap(identity))
const emptyErr = /^TypeError: List.foldMap: List must not be empty/
t.throws(fn([]), emptyErr, 'throws when passed an empty List')
const notSameSemi = /^TypeError: List.foldMap: Provided function must return Semigroups of the same type/
t.throws(fn([ 0 ]), notSameSemi, 'throws when function does not return a Semigroup')
t.throws(fn([ '', 0 ]), notSameSemi, 'throws when not all returned values are Semigroups')
t.throws(fn([ '', [] ]), notSameSemi, 'throws when different semigroups are returned')
t.end()
})
test('List foldMap functionality', t => {
const fold = xs =>
List(xs).foldMap(x => x.toString())
t.same(fold([ 1, 2 ]), '12', 'combines and extracts semigroups')
t.same(fold([ 3 ]), '3', 'extracts a single semigroup')
t.end()
})
test('List filter fantasy-land errors', t => {
const filter = bindFunc(List([ 0 ])[fl.filter])
const err = /List.fantasy-land\/filter: Pred or predicate function required/
t.throws(filter(undefined), err, 'throws with undefined')
t.throws(filter(null), err, 'throws with null')
t.throws(filter(0), err, 'throws with falsey number')
t.throws(filter(1), err, 'throws with truthy number')
t.throws(filter(''), err, 'throws with falsey string')
t.throws(filter('string'), err, 'throws with truthy string')
t.throws(filter(false), err, 'throws with false')
t.throws(filter(true), err, 'throws with true')
t.throws(filter([]), err, 'throws with an array')
t.throws(filter({}), err, 'throws with an object')
t.end()
})
test('List filter errors', t => {
const filter = bindFunc(List([ 0 ]).filter)
const err = /List.filter: Pred or predicate function required/
t.throws(filter(undefined), err, 'throws with undefined')
t.throws(filter(null), err, 'throws with null')
t.throws(filter(0), err, 'throws with falsey number')
t.throws(filter(1), err, 'throws with truthy number')
t.throws(filter(''), err, 'throws with falsey string')
t.throws(filter('string'), err, 'throws with truthy string')
t.throws(filter(false), err, 'throws with false')
t.throws(filter(true), err, 'throws with true')
t.throws(filter([]), err, 'throws with an array')
t.throws(filter({}), err, 'throws with an object')
t.end()
})
test('List filter functionality', t => {
const m = List([ 4, 5, 10, 34, 'string' ])
const bigNum = x => typeof x === 'number' && x > 10
const justStrings = x => typeof x === 'string'
const bigNumPred = Pred(bigNum)
const justStringsPred = Pred(justStrings)
t.same(m.filter(bigNum).valueOf(), [ 34 ], 'filters for bigNums with function')
t.same(m.filter(justStrings).valueOf(), [ 'string' ], 'filters for strings with function')
t.same(m.filter(bigNumPred).valueOf(), [ 34 ], 'filters for bigNums with Pred')
t.same(m.filter(justStringsPred).valueOf(), [ 'string' ], 'filters for strings with Pred')
t.end()
})
test('List filter properties (Filterable)', t => {
const m = List([ 2, 6, 10, 25, 9, 28 ])
const n = List([ 'string', 'party' ])
const isEven = x => x % 2 === 0
const isBig = x => x >= 10
const left = m.filter(x => isBig(x) && isEven(x)).valueOf()
const right = m.filter(isBig).filter(isEven).valueOf()
t.same(left, right , 'distributivity')
t.same(m.filter(() => true).valueOf(), m.valueOf(), 'identity')
t.same(m.filter(() => false).valueOf(), n.filter(() => false).valueOf(), 'annihilation')
t.end()
})
test('List reject errors', t => {
const reject = bindFunc(List([ 0 ]).reject)
const err = /List.reject: Pred or predicate function required/
t.throws(reject(undefined), err, 'throws with undefined')
t.throws(reject(null), err, 'throws with null')
t.throws(reject(0), err, 'throws with falsey number')
t.throws(reject(1), err, 'throws with truthy number')
t.throws(reject(''), err, 'throws with falsey string')
t.throws(reject('string'), err, 'throws with truthy string')
t.throws(reject(false), err, 'throws with false')
t.throws(reject(true), err, 'throws with true')
t.throws(reject([]), err, 'throws with an array')
t.throws(reject({}), err, 'throws with an object')
t.end()
})
test('List reject functionality', t => {
const m = List([ 4, 5, 10, 34, 'string' ])
const bigNum = x => typeof x === 'number' && x > 10
const justStrings = x => typeof x === 'string'
const bigNumPred = Pred(bigNum)
const justStringsPred = Pred(justStrings)
t.same(m.reject(bigNum).valueOf(), [ 4, 5, 10, 'string' ], 'rejects bigNums with function')
t.same(m.reject(justStrings).valueOf(), [ 4, 5, 10, 34 ], 'rejects strings with function')
t.same(m.reject(bigNumPred).valueOf(), [ 4, 5, 10, 'string' ], 'rejects bigNums with Pred')
t.same(m.reject(justStringsPred).valueOf(), [ 4, 5, 10, 34 ], 'rejects strings with Pred')
t.end()
})
test('List map errors', t => {
const map = bindFunc(List([]).map)
const err = /List.map: Function required/
t.throws(map(undefined), err, 'throws with undefined')
t.throws(map(null), err, 'throws with null')
t.throws(map(0), err, 'throws with falsey number')
t.throws(map(1), err, 'throws with truthy number')
t.throws(map(''), err, 'throws with falsey string')
t.throws(map('string'), err, 'throws with truthy string')
t.throws(map(false), err, 'throws with false')
t.throws(map(true), err, 'throws with true')
t.throws(map([]), err, 'throws with an array')
t.throws(map({}), err, 'throws with an object')
t.doesNotThrow(map(unit), 'allows a function')
t.end()
})
test('List map fantasy-land errors', t => {
const map = bindFunc(List([])[fl.map])
const err = /List.fantasy-land\/map: Function required/
t.throws(map(undefined), err, 'throws with undefined')
t.throws(map(null), err, 'throws with null')
t.throws(map(0), err, 'throws with falsey number')
t.throws(map(1), err, 'throws with truthy number')
t.throws(map(''), err, 'throws with falsey string')
t.throws(map('string'), err, 'throws with truthy string')
t.throws(map(false), err, 'throws with false')
t.throws(map(true), err, 'throws with true')
t.throws(map([]), err, 'throws with an array')
t.throws(map({}), err, 'throws with an object')
t.doesNotThrow(map(unit), 'allows a function')
t.end()
})
test('List map functionality', t => {
const spy = sinon.spy(identity)
const xs = [ 42 ]
const m = List(xs).map(spy)
t.equal(m.type(), 'List', 'returns a List')
t.equal(spy.called, true, 'calls mapping function')
t.same(m.valueOf(), xs, 'returns the result of the map inside of new List')
t.end()
})
test('List map properties (Functor)', t => {
const m = List([ 49 ])
const f = x => x + 54
const g = x => x * 4
t.ok(isFunction(m.map), 'provides a map function')
t.same(m.map(identity).valueOf(), m.valueOf(), 'identity')
t.same(m.map(_compose(f, g)).valueOf(), m.map(g).map(f).valueOf(), 'composition')
t.end()
})
test('List ap errors', t => {
const left = bindFunc(x => List([ x ]).ap(List([ 0 ])))
const noFunc = /List.ap: Wrapped values must all be functions/
t.throws(left([ undefined ]), noFunc, 'throws when wrapped value is undefined')
t.throws(left([ null ]), noFunc, 'throws when wrapped value is null')
t.throws(left([ 0 ]), noFunc, 'throws when wrapped value is a falsey number')
t.throws(left([ 1 ]), noFunc, 'throws when wrapped value is a truthy number')
t.throws(left([ '' ]), noFunc, 'throws when wrapped value is a falsey string')
t.throws(left([ 'string' ]), noFunc, 'throws when wrapped value is a truthy string')
t.throws(left([ false ]), noFunc, 'throws when wrapped value is false')
t.throws(left([ true ]), noFunc, 'throws when wrapped value is true')
t.throws(left([ [] ]), noFunc, 'throws when wrapped value is an array')
t.throws(left([ {} ]), noFunc, 'throws when wrapped value is an object')
t.throws(left([ unit, 'string' ]), noFunc, 'throws when wrapped values are not all functions')
const ap = bindFunc(x => List([ unit ]).ap(x))
const noList = /List.ap: List required/
t.throws(ap(undefined), noList, 'throws with undefined')
t.throws(ap(null), noList, 'throws with null')
t.throws(ap(0), noList, 'throws with falsey number')
t.throws(ap(1), noList, 'throws with truthy number')
t.throws(ap(''), noList, 'throws with falsey string')
t.throws(ap('string'), noList, 'throws with truthy string')
t.throws(ap(false), noList, 'throws with false')
t.throws(ap(true), noList, 'throws with true')
t.throws(ap([]), noList, 'throws with an array')
t.throws(ap({}), noList, 'throws with an object')
t.end()
})
test('List ap properties (Apply)', t => {
const m = List([ identity ])
const a = m.map(_compose).ap(m).ap(m)
const b = m.ap(m.ap(m))
t.ok(isFunction(List([]).ap), 'provides an ap function')
t.ok(isFunction(List([]).map), 'implements the Functor spec')
t.same(a.ap(List([ 3 ])).valueOf(), b.ap(List([ 3 ])).valueOf(), 'composition')
t.end()
})
test('List of', t => {
t.equal(List.of, List([]).of, 'List.of is the same as the instance version')
t.equal(List.of(0).type(), 'List', 'returns a List')
t.same(List.of(0).valueOf(), [ 0 ], 'wraps the value passed into List in an array')
t.end()
})
test('List of properties (Applicative)', t => {
const m = List([ identity ])
t.ok(isFunction(List([]).of), 'provides an of function')
t.ok(isFunction(List([]).ap), 'implements the Apply spec')
t.same(m.ap(List([ 3 ])).valueOf(), [ 3 ], 'identity')
t.same(m.ap(List.of(3)).valueOf(), List.of(identity(3)).valueOf(), 'homomorphism')
const a = x => m.ap(List.of(x))
const b = x => List.of(applyTo(x)).ap(m)
t.same(a(3).valueOf(), b(3).valueOf(), 'interchange')
t.end()
})
test('List chain errors', t => {
const chain = bindFunc(List([ 0 ]).chain)
const bad = bindFunc(x => List.of(x).chain(identity))
const noFunc = /List.chain: Function required/
t.throws(chain(undefined), noFunc, 'throws with undefined')
t.throws(chain(null), noFunc, 'throws with null')
t.throws(chain(0), noFunc, 'throw with falsey number')
t.throws(chain(1), noFunc, 'throws with truthy number')
t.throws(chain(''), noFunc, 'throws with falsey string')
t.throws(chain('string'), noFunc, 'throws with truthy string')
t.throws(chain(false), noFunc, 'throws with false')
t.throws(chain(true), noFunc, 'throws with true')
t.throws(chain([]), noFunc, 'throws with an array')
t.throws(chain({}), noFunc, 'throws with an object')
const noList = /List.chain: Function must return a List/
t.throws(bad(undefined), noList, 'throws when function returns undefined')
t.throws(bad(null), noList, 'throws when function returns null')
t.throws(bad(0), noList, 'throws when function returns falsey number')
t.throws(bad(1), noList, 'throws when function returns truthy number')
t.throws(bad(''), noList, 'throws when function returns falsey string')
t.throws(bad('string'), noList, 'throws when function returns truthy string')
t.throws(bad(false), noList, 'throws when function returns false')
t.throws(bad(true), noList, 'throws when function returns true')
t.throws(bad([]), noList, 'throws when function returns an array')
t.throws(bad({}), noList, 'throws when function returns an object')
t.throws(bad(unit), noList, 'throws when function returns a function')
t.throws(bad(MockCrock), noList, 'throws when function a non-List ADT')
t.end()
})
test('List chain fantasy-land errors', t => {
const chain = bindFunc(List([ 0 ])[fl.chain])
const bad = bindFunc(x => List.of(x)[fl.chain](identity))
const noFunc = /List.fantasy-land\/chain: Function required/
t.throws(chain(undefined), noFunc, 'throws with undefined')
t.throws(chain(null), noFunc, 'throws with null')
t.throws(chain(0), noFunc, 'throw with falsey number')
t.throws(chain(1), noFunc, 'throws with truthy number')
t.throws(chain(''), noFunc, 'throws with falsey string')
t.throws(chain('string'), noFunc, 'throws with truthy string')
t.throws(chain(false), noFunc, 'throws with false')
t.throws(chain(true), noFunc, 'throws with true')
t.throws(chain([]), noFunc, 'throws with an array')
t.throws(chain({}), noFunc, 'throws with an object')
const noList = /List.fantasy-land\/chain: Function must return a List/
t.throws(bad(undefined), noList, 'throws when function returns undefined')
t.throws(bad(null), noList, 'throws when function returns null')
t.throws(bad(0), noList, 'throws when function returns falsey number')
t.throws(bad(1), noList, 'throws when function returns truthy number')
t.throws(bad(''), noList, 'throws when function returns falsey string')
t.throws(bad('string'), noList, 'throws when function returns truthy string')
t.throws(bad(false), noList, 'throws when function returns false')
t.throws(bad(true), noList, 'throws when function returns true')
t.throws(bad([]), noList, 'throws when function returns an array')
t.throws(bad({}), noList, 'throws when function returns an object')
t.throws(bad(unit), noList, 'throws when function returns a function')
t.throws(bad(MockCrock), noList, 'throws when function a non-List ADT')
t.end()
})
test('List chain properties (Chain)', t => {
t.ok(isFunction(List([]).chain), 'provides a chain function')
t.ok(isFunction(List([]).ap), 'implements the Apply spec')
const f = x => List.of(x + 2)
const g = x => List.of(x + 10)
const a = x => List.of(x).chain(f).chain(g)
const b = x => List.of(x).chain(y => f(y).chain(g))
t.same(a(10).valueOf(), b(10).valueOf(), 'assosiativity')
t.end()
})
test('List chain properties (Monad)', t => {
t.ok(isFunction(List([]).chain), 'implements the Chain spec')
t.ok(isFunction(List([]).of), 'implements the Applicative spec')
const f = x => List([ x ])
t.same(List.of(3).chain(f).valueOf(), f(3).valueOf(), 'left identity')
t.same(f(3).chain(List.of).valueOf(), f(3).valueOf(), 'right identity')
t.end()
})
test('List sequence errors', t => {
const seq = bindFunc(List.of(MockCrock(2)).sequence)
const seqBad = bindFunc(List.of(0).sequence)
const err = /List.sequence: Applicative TypeRep or Apply returning function required/
t.throws(seq(undefined), err, 'throws with undefined')
t.throws(seq(null), err, 'throws with null')
t.throws(seq(0), err, 'throws falsey with number')
t.throws(seq(1), err, 'throws truthy with number')
t.throws(seq(''), err, 'throws falsey with string')
t.throws(seq('string'), err, 'throws with truthy string')
t.throws(seq(false), err, 'throws with false')
t.throws(seq(true), err, 'throws with true')
t.throws(seq([]), err, 'throws with an array')
t.throws(seq({}), err, 'throws with an object')
const noAppl = /List.sequence: Must wrap Applys of the same type/
t.throws(seqBad(unit), noAppl, 'wrapping non-Apply throws')
t.end()
})
test('List sequence with Apply function', t => {
const x = 'string'
const fn = x => MockCrock(x)
const m = List.of(MockCrock(x)).sequence(fn)
t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock')
t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List')
t.same(m.valueOf().valueOf(), [ x ], 'inner List contains original inner value')
const ar = x => [ x ]
const arM = List.of([ x ]).sequence(ar)
t.ok(isSameType(Array, arM), 'Provides an outer type of Array')
t.ok(isSameType(List, arM[0]), 'Provides an inner type of List')
t.same(arM[0].valueOf(), [ x ], 'inner List contains original inner value')
t.end()
})
test('List sequence with Applicative TypeRep', t => {
const x = 'string'
const m = List.of(MockCrock(x)).sequence(MockCrock)
t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock')
t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List')
t.same(m.valueOf().valueOf(), [ x ], 'inner List contains original inner value')
const ar = List.of([ x ]).sequence(Array)
t.ok(isSameType(Array, ar), 'Provides an outer type of Array')
t.ok(isSameType(List, ar[0]), 'Provides an inner type of List')
t.same(ar[0].valueOf(), [ x ], 'inner List contains original inner value')
t.end()
})
test('List traverse errors', t => {
const trav = bindFunc(List.of(2).traverse)
const first = /List.traverse: Applicative TypeRep or Apply returning function required for first argument/
t.throws(trav(undefined, MockCrock), first, 'throws with undefined in first argument')
t.throws(trav(null, MockCrock), first, 'throws with null in first argument')
t.throws(trav(0, MockCrock), first, 'throws falsey with number in first argument')
t.throws(trav(1, MockCrock), first, 'throws truthy with number in first argument')
t.throws(trav('', MockCrock), first, 'throws falsey with string in first argument')
t.throws(trav('string', MockCrock), first, 'throws with truthy string in first argument')
t.throws(trav(false, MockCrock), first, 'throws with false in first argument')
t.throws(trav(true, MockCrock), first, 'throws with true in first argument')
t.throws(trav([], MockCrock), first, 'throws with an array in first argument')
t.throws(trav({}, MockCrock), first, 'throws with an object in first argument')
const second = /List.traverse: Apply returning functions required for second argument/
t.throws(trav(MockCrock, undefined), second, 'throws with undefined in second argument')
t.throws(trav(MockCrock, null), second, 'throws with null in second argument')
t.throws(trav(MockCrock, 0), second, 'throws falsey with number in second argument')
t.throws(trav(MockCrock, 1), second, 'throws truthy with number in second argument')
t.throws(trav(MockCrock, ''), second, 'throws falsey with string in second argument')
t.throws(trav(MockCrock, 'string'), second, 'throws with truthy string in second argument')
t.throws(trav(MockCrock, false), second, 'throws with false in second argument')
t.throws(trav(MockCrock, true), second, 'throws with true in second argument')
t.throws(trav(MockCrock, []), second, 'throws with an array in second argument')
t.throws(trav(MockCrock, {}), second, 'throws with an object in second argument')
const noAppl = /List.traverse: Both functions must return an Apply of the same type/
t.throws(trav(unit, MockCrock), noAppl, 'throws with non-Appicative returning function in first argument')
t.throws(trav(MockCrock, unit), noAppl, 'throws with non-Appicative returning function in second argument')
t.end()
})
test('List traverse with Apply function', t => {
const x = 'string'
const res = 'result'
const f = x => MockCrock(x)
const fn = m => constant(m(res))
const m = List.of(x).traverse(f, fn(MockCrock))
t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock')
t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List')
t.same(m.valueOf().valueOf(), [ res ], 'inner List contains transformed value')
const ar = x => [ x ]
const arM = List.of(x).traverse(ar, fn(ar))
t.ok(isSameType(Array, arM), 'Provides an outer type of Array')
t.ok(isSameType(List, arM[0]), 'Provides an inner type of List')
t.same(arM[0].valueOf(), [ res ], 'inner List contains transformed value')
t.end()
})
test('List traverse with Applicative TypeRep', t => {
const x = 'string'
const res = 'result'
const fn = m => constant(m(res))
const m = List.of(x).traverse(MockCrock, fn(MockCrock))
t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock')
t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List')
t.same(m.valueOf().valueOf(), [ res ], 'inner List contains transformed value')
const ar = x => [ x ]
const arM = List.of(x).traverse(Array, fn(ar))
t.ok(isSameType(Array, arM), 'Provides an outer type of Array')
t.ok(isSameType(List, arM[0]), 'Provides an inner type of List')
t.same(arM[0].valueOf(), [ res ], 'inner List contains transformed value')
t.end()
})
| evilsoft/crocks | src/core/List.spec.js | JavaScript | isc | 36,528 |
'use strict';
var main = {
expand:true,
cwd: './build/styles/',
src:['*.css'],
dest: './build/styles/'
};
module.exports = {
main:main
};
| ariosejs/bui | grunt/config/cssmin.js | JavaScript | isc | 161 |
# hard
[![experimental][stability-image]][stability-url]
## Why?
## Installation
```sh
$ npm install akileez\hard
```
## Usage
```js
```
## API
```js
```
## See Also
## License [![ISC license][license-img]][license-url]
[ISC](https://tldrlegal.com/license/-isc-license)
[stability-image]: https://img.shields.io/badge/stability-experimental-orange.svg?style=flat-square
[stability-url]: https://github.com/akileez/hard
[license-img]: https://img.shields.io/badge/license-ISC-blue.svg?style=flat-square
[license-url]: https://github.com/akileez/npinit/blob/master/license.md | akileez/hard | README.md | Markdown | isc | 584 |
package de.klimek.spacecurl.activities;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelSlideListener;
import java.util.ArrayList;
import java.util.List;
import de.klimek.spacecurl.Database;
import de.klimek.spacecurl.R;
import de.klimek.spacecurl.game.GameCallBackListener;
import de.klimek.spacecurl.game.GameDescription;
import de.klimek.spacecurl.game.GameFragment;
import de.klimek.spacecurl.util.ColorGradient;
import de.klimek.spacecurl.util.cards.StatusCard;
import de.klimek.spacecurl.util.collection.GameStatus;
import de.klimek.spacecurl.util.collection.Training;
import de.klimek.spacecurl.util.collection.TrainingStatus;
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.view.CardListView;
import it.gmariotti.cardslib.library.view.CardView;
/**
* This abstract class loads a training and provides functionality to
* subclasses, e. g. usage of the status panel, switching games, and showing a
* pause screen. <br/>
* A Training must be loaded with {@link #loadTraining(Training)}. In order to
* use the status-panel {@link #useStatusPanel()} has to be called.
*
* @author Mike Klimek
* @see <a href="http://developer.android.com/reference/packages.html">Android
* API</a>
*/
public abstract class BasicTrainingActivity extends FragmentActivity implements OnClickListener,
GameCallBackListener {
public static final String TAG = BasicTrainingActivity.class.getName();
// Status panel
private boolean mUsesStatus = false;
private TrainingStatus mTrainingStatus;
private GameStatus mCurGameStatus;
private int mStatusColor;
private ColorGradient mStatusGradient = new ColorGradient(Color.RED, Color.YELLOW, Color.GREEN);
private FrameLayout mStatusIndicator;
private ImageButton mSlidingToggleButton;
private boolean mButtonImageIsExpand = true;
private SlidingUpPanelLayout mSlidingUpPanel;
private CardListView mCardListView;
private CardArrayAdapter mCardArrayAdapter;
private List<Card> mCards = new ArrayList<Card>();
private GameFragment mGameFragment;
private FrameLayout mGameFrame;
private Training mTraining;
private Database mDatabase;
// Pause Frame
private FrameLayout mPauseFrame;
private LinearLayout mInstructionLayout;
private ImageView mResumeButton;
private TextView mInstructionsTextView;
private String mInstructions = "";
private int mShortAnimationDuration;
private State mState = State.Paused;
public static enum State {
Paused, Pausing, Running
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDatabase = Database.getInstance(this);
setContentView(R.layout.activity_base);
setupPauseView();
}
/**
* Dialog with instructions for the current game or pause/play icon. Shows
* when the user interacts with the App.
*/
private void setupPauseView() {
mGameFrame = (FrameLayout) findViewById(R.id.game_frame);
mGameFrame.setOnClickListener(this);
// hide initially
mPauseFrame = (FrameLayout) findViewById(R.id.pause_layout);
mPauseFrame.setAlpha(0.0f);
mPauseFrame.setVisibility(View.GONE);
mInstructionLayout = (LinearLayout) findViewById(R.id.instruction_layout);
mResumeButton = (ImageView) findViewById(R.id.resume_button);
mInstructionsTextView = (TextView) findViewById(R.id.instructions_textview);
mShortAnimationDuration = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
@Override
protected void onResume() {
super.onResume();
if (mDatabase.isOrientationLandscape()) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
/**
* Subclasses must load a Training with this method.
*
* @param training
*/
protected final void loadTraining(Training training) {
mTraining = training;
}
/**
* Subclasses can use this method to enable the status-panel.
*/
protected final void useStatusPanel() {
mTrainingStatus = mTraining.createTrainingStatus();
mUsesStatus = true;
mStatusIndicator = (FrameLayout) findViewById(R.id.status_indicator);
mSlidingToggleButton = (ImageButton) findViewById(R.id.panel_button);
mSlidingUpPanel = (SlidingUpPanelLayout) findViewById(R.id.content_frame);
mSlidingUpPanel.setPanelSlideListener(new PanelSlideListener() {
@Override
public void onPanelSlide(View panel, float slideOffset) {
if (slideOffset > 0.5f && mButtonImageIsExpand) {
mSlidingToggleButton.setImageResource(R.drawable.ic_collapse);
mButtonImageIsExpand = false;
} else if (slideOffset < 0.5f && !mButtonImageIsExpand) {
mSlidingToggleButton.setImageResource(R.drawable.ic_expand);
mButtonImageIsExpand = true;
}
}
@Override
public void onPanelCollapsed(View panel) {
}
@Override
public void onPanelExpanded(View panel) {
}
@Override
public void onPanelAnchored(View panel) {
}
@Override
public void onPanelHidden(View panel) {
}
});
int statusIndicatorHeight = (int) (getResources()
.getDimension(R.dimen.status_indicator_height));
mSlidingUpPanel.setPanelHeight(statusIndicatorHeight);
// delegate clicks to underlying panel
mSlidingToggleButton.setClickable(false);
mSlidingUpPanel.setEnabled(true);
// setup cardlist
mCardArrayAdapter = new FixedCardArrayAdapter(this, mCards);
mCardListView = (CardListView) findViewById(R.id.card_list);
mCardListView.setAdapter(mCardArrayAdapter);
}
protected final void updateCurGameStatus(final float status) {
// graph
mCurGameStatus.addStatus(status);
// indicator color
mStatusColor = mStatusGradient.getColorForFraction(status);
mStatusIndicator.setBackgroundColor(mStatusColor);
}
protected final void expandSlidingPane() {
if (mState == State.Running) {
pause();
mState = State.Paused;
}
mSlidingUpPanel.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
}
protected final void collapseSlidingPane() {
mSlidingUpPanel.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
}
protected final void showStatusIndicator() {
mStatusIndicator.setVisibility(View.VISIBLE);
}
protected final void hideStatusIndicator() {
mStatusIndicator.setVisibility(View.GONE);
}
protected final void lockSlidingPane() {
mSlidingToggleButton.setVisibility(View.GONE);
}
protected final void unlockSlidingPane() {
mSlidingToggleButton.setVisibility(View.VISIBLE);
}
/**
* Creates a new GameFragment from a gameDescriptionIndex and displays it.
* Switches to the associated gameStatus from a previous game (overwriting
* it) or creates a new one.
*
* @param gameDescriptionIndex the game to start
* @param enterAnimation how the fragment should enter
* @param exitAnimation how the previous fragment should be removed
*/
protected final void switchToGame(int gameDescriptionIndex, int enterAnimation,
int exitAnimation) {
mState = State.Paused;
pause();
// get Fragment
GameDescription newGameDescription = mTraining.get(gameDescriptionIndex);
mGameFragment = newGameDescription.createFragment();
// Transaction
getSupportFragmentManager().beginTransaction()
.setCustomAnimations(enterAnimation, exitAnimation)
.replace(R.id.game_frame, mGameFragment)
.commit();
// enable callback
mGameFragment.registerGameCallBackListener(this);
// update pause view
mInstructions = newGameDescription.getInstructions();
if (mInstructions == null || mInstructions.isEmpty()) {
// only show pause/play icon
mInstructionLayout.setVisibility(View.GONE);
mResumeButton.setVisibility(View.VISIBLE);
} else {
// only show instructions
mResumeButton.setVisibility(View.GONE);
mInstructionLayout.setVisibility(View.VISIBLE);
mInstructionsTextView.setText(mInstructions);
}
if (mUsesStatus) {
// switch to status associated with current game
mCurGameStatus = mTrainingStatus.get(gameDescriptionIndex);
if (mCurGameStatus == null) {
// create new
mCurGameStatus = new GameStatus(newGameDescription.getTitle());
mTrainingStatus.append(gameDescriptionIndex, mCurGameStatus);
mCards.add(gameDescriptionIndex, new StatusCard(this, mCurGameStatus));
mCardArrayAdapter.notifyDataSetChanged();
} else {
// reset existing
mCurGameStatus.reset();
mCardArrayAdapter.notifyDataSetChanged();
}
}
}
/**
* Convenience method. Same as
* {@link #switchToGame(int gameDescriptionIndex, int enterAnimation, int exitAnimation)}
* but uses standard fade_in/fade_out animations.
*
* @param gameDescriptionIndex the game to start
*/
protected final void switchToGame(int gameDescriptionIndex) {
switchToGame(gameDescriptionIndex, android.R.anim.fade_in, android.R.anim.fade_out);
}
@Override
protected void onPause() {
super.onPause();
if (mState == State.Running) {
pause();
}
mState = State.Paused;
}
@Override
public void onUserInteraction() {
// Pause on every user interaction
if (mState == State.Running) {
mState = State.Pausing;
pause();
} else if (mState == State.Pausing) {
// Previously clicked outside of gameframe and now possibly on
// gameframe again to resume
mState = State.Paused;
}
super.onUserInteraction();
}
/**
* Called when clicking inside the game frame (after onUserInteraction)
*/
@Override
public void onClick(View v) {
if (mState == State.Paused) {
// Resume when paused
resume();
mState = State.Running;
} else if (mState == State.Pausing) {
// We have just paused in onUserInteraction -> don't resume
mState = State.Paused;
}
}
private void pause() {
Log.v(TAG, "Paused");
// pause game
if (mGameFragment != null) {
mGameFragment.onPauseGame();
}
// Show pause view and grey out screen
mPauseFrame.setVisibility(View.VISIBLE);
mPauseFrame.animate()
.alpha(1f)
.setDuration(mShortAnimationDuration)
.setListener(null);
// Show navigation bar
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
private void resume() {
Log.v(TAG, "Resumed");
// hide pause view
mPauseFrame.animate()
.alpha(0f)
.setDuration(mShortAnimationDuration)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mPauseFrame.setVisibility(View.GONE);
}
});
// resume game
if (mGameFragment != null) {
mGameFragment.onResumeGame();
}
// Grey out navigation bar
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
/**
* Fixes bug in {@link CardArrayAdapter CardArrayAdapter's} Viewholder
* pattern. Otherwise the cards innerViewElements would not be replaced
* (Title and Graph from previous Graph is shown).
*
* @author Mike Klimek
*/
private class FixedCardArrayAdapter extends CardArrayAdapter {
public FixedCardArrayAdapter(Context context, List<Card> cards) {
super(context, cards);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Card card = (Card) getItem(position);
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
convertView = layoutInflater.inflate(R.layout.list_card_layout, parent, false);
}
CardView view = (CardView) convertView.findViewById(R.id.list_cardId);
view.setForceReplaceInnerLayout(true);
view.setCard(card);
return convertView;
}
}
}
| Tetr4/Spacecurl | app/src/main/java/de/klimek/spacecurl/activities/BasicTrainingActivity.java | Java | isc | 14,055 |
// C++ entry point
#include "Elf32.h"
// autogen.h contains the full kernel binary in a char array
#include "autogen.h"
extern "C" {
volatile unsigned char *uart1 = (volatile unsigned char*) 0x4806A000;
volatile unsigned char *uart2 = (volatile unsigned char*) 0x4806C000;
volatile unsigned char *uart3 = (volatile unsigned char*) 0x49020000;
extern int memset(void *buf, int c, size_t len);
};
// http://www.simtec.co.uk/products/SWLINUX/files/booting_article.html
// http://www.arm.linux.org.uk/developer/booting.php
#define ATAG_NONE 0
#define ATAG_CORE 0x54410001
#define ATAG_MEM 0x54410002
#define ATAG_VIDEOTEXT 0x54410003
#define ATAG_RAMDISK 0x54410004
#define ATAG_INITRD2 0x54410005
#define ATAG_SERIAL 0x54410006
#define ATAG_REVISION 0x54410007
#define ATAG_VIDEOLFB 0x54410008
#define ATAG_CMDLINE 0x54410009
struct atag_header {
uint32_t size;
uint32_t tag;
};
struct atag_core {
uint32_t flags;
uint32_t pagesize;
uint32_t rootdev;
};
struct atag_mem {
uint32_t size;
uint32_t start;
};
struct atag_videotext {
unsigned char x;
unsigned char y;
unsigned short video_page;
unsigned char video_mode;
unsigned char video_cols;
unsigned short video_ega_bx;
unsigned char video_lines;
unsigned char video_isvga;
unsigned short video_points;
};
struct atag_ramdisk {
uint32_t flags;
uint32_t size;
uint32_t start;
};
struct atag_initrd2 {
uint32_t start;
uint32_t size;
};
struct atag_serialnr {
uint32_t low;
uint32_t high;
};
struct atag_revision {
uint32_t rev;
};
struct atag_videolfb {
unsigned short lfb_width;
unsigned short lfb_height;
unsigned short lfb_depth;
unsigned short lfb_linelength;
uint32_t lfb_base;
uint32_t lfb_size;
unsigned char red_size;
unsigned char red_pos;
unsigned char green_size;
unsigned char green_pos;
unsigned char blue_size;
unsigned char blue_pos;
unsigned char rsvd_size;
unsigned char rsvd_pos;
};
struct atag_cmdline {
char cmdline[1]; // Minimum size.
};
struct atag {
struct atag_header hdr;
union {
struct atag_core core;
struct atag_mem mem;
struct atag_videotext videotext;
struct atag_ramdisk ramdisk;
struct atag_initrd2 initrd2;
struct atag_serialnr serialnr;
struct atag_revision revision;
struct atag_videolfb videolfb;
struct atag_cmdline cmdline;
} u;
};
/// Bootstrap structure passed to the kernel entry point.
struct BootstrapStruct_t
{
uint32_t flags;
uint32_t mem_lower;
uint32_t mem_upper;
uint32_t boot_device;
uint32_t cmdline;
uint32_t mods_count;
uint32_t mods_addr;
/* ELF information */
uint32_t num;
uint32_t size;
uint32_t addr;
uint32_t shndx;
uint32_t mmap_length;
uint32_t mmap_addr;
uint32_t drives_length;
uint32_t drives_addr;
uint32_t config_table;
uint32_t boot_loader_name;
uint32_t apm_table;
uint32_t vbe_control_info;
uint32_t vbe_mode_info;
uint32_t vbe_mode;
uint32_t vbe_interface_seg;
uint32_t vbe_interface_off;
uint32_t vbe_interface_len;
} __attribute__((packed));
/// \note Page/section references are from the OMAP35xx Technical Reference Manual
/** UART/IrDA/CIR Registers */
#define DLL_REG 0x00 // R/W
#define RHR_REG 0x00 // R
#define THR_REG 0x00 // W
#define DLH_REG 0x04 // R/W
#define IER_REG 0x04 // R/W
#define IIR_REG 0x08 // R
#define FCR_REG 0x08 // W
#define EFR_REG 0x08 // RW
#define LCR_REG 0x0C // RW
#define MCR_REG 0x10 // RW
#define XON1_ADDR1_REG 0x10 // RW
#define LSR_REG 0x14 // R
#define XON2_ADDR2_REG 0x14 // RW
#define MSR_REG 0x18 // R
#define TCR_REG 0x18 // RW
#define XOFF1_REG 0x18 // RW
#define SPR_REG 0x1C // RW
#define TLR_REG 0x1C // RW
#define XOFF2_REG 0x1C // RW
#define MDR1_REG 0x20 // RW
#define MDR2_REG 0x24 // RW
#define USAR_REG 0x38 // R
#define SCR_REG 0x40 // RW
#define SSR_REG 0x44 // R
#define MVR_REG 0x50 // R
#define SYSC_REG 0x54 // RW
#define SYSS_REG 0x58 // R
#define WER_REG 0x5C // RW
/// Gets a uart MMIO block given a number
extern "C" volatile unsigned char *uart_get(int n)
{
if(n == 1)
return uart1;
else if(n == 2)
return uart2;
else if(n == 3)
return uart3;
else
return 0;
}
/// Perform a software reset of a given UART
extern "C" bool uart_softreset(int n)
{
volatile unsigned char *uart = uart_get(n);
if(!uart)
return false;
/** Reset the UART. Page 2677, section 17.5.1.1.1 **/
// 1. Initiate a software reset
uart[SYSC_REG] |= 0x2;
// 2. Wait for the end of the reset operation
while(!(uart[SYSS_REG] & 0x1));
return true;
}
/// Configure FIFOs and DMA to default values
extern "C" bool uart_fifodefaults(int n)
{
volatile unsigned char *uart = uart_get(n);
if(!uart)
return false;
/** Configure FIFOs and DMA **/
// 1. Switch to configuration mode B to access the EFR_REG register
unsigned char old_lcr_reg = uart[LCR_REG];
uart[LCR_REG] = 0xBF;
// 2. Enable submode TCR_TLR to access TLR_REG (part 1 of 2)
unsigned char efr_reg = uart[EFR_REG];
unsigned char old_enhanced_en = efr_reg & 0x8;
if(!(efr_reg & 0x8)) // Set ENHANCED_EN (bit 4) if not set
efr_reg |= 0x8;
uart[EFR_REG] = efr_reg; // Write back to the register
// 3. Switch to configuration mode A
uart[LCR_REG] = 0x80;
// 4. Enable submode TCL_TLR to access TLR_REG (part 2 of 2)
unsigned char mcr_reg = uart[MCR_REG];
unsigned char old_tcl_tlr = mcr_reg & 0x20;
if(!(mcr_reg & 0x20))
mcr_reg |= 0x20;
uart[MCR_REG] = mcr_reg;
// 5. Enable FIFO, load new FIFO triggers (part 1 of 3), and the new DMA mode (part 1 of 2)
uart[FCR_REG] = 1; // TX and RX FIFO triggers at 8 characters, no DMA mode
// 6. Switch to configuration mode B to access EFR_REG
uart[LCR_REG] = 0xBF;
// 7. Load new FIFO triggers (part 2 of 3)
uart[TLR_REG] = 0;
// 8. Load new FIFO triggers (part 3 of 3) and the new DMA mode (part 2 of 2)
uart[SCR_REG] = 0;
// 9. Restore the ENHANCED_EN value saved in step 2
if(!old_enhanced_en)
uart[EFR_REG] = uart[EFR_REG] ^ 0x8;
// 10. Switch to configuration mode A to access the MCR_REG register
uart[LCR_REG] = 0x80;
// 11. Restore the MCR_REG TCR_TLR value saved in step 4
if(!old_tcl_tlr)
uart[MCR_REG] = uart[MCR_REG] ^ 0x20;
// 12. Restore the LCR_REG value stored in step 1
uart[LCR_REG] = old_lcr_reg;
return true;
}
/// Configure the UART protocol (to defaults - 115200 baud, 8 character bits,
/// no paruart_protoconfigity, 1 stop bit). Will also enable the UART for output as a side
/// effect.
extern "C" bool uart_protoconfig(int n)
{
volatile unsigned char *uart = uart_get(n);
if(!uart)
return false;
/** Configure protocol, baud and interrupts **/
// 1. Disable UART to access DLL_REG and DLH_REG
uart[MDR1_REG] = (uart[MDR1_REG] & ~0x7) | 0x7;
// 2. Switch to configuration mode B to access the EFR_REG register
uart[LCR_REG] = 0xBF;
// 3. Enable access to IER_REG
unsigned char efr_reg = uart[EFR_REG];
unsigned char old_enhanced_en = efr_reg & 0x8;
if(!(efr_reg & 0x8)) // Set ENHANCED_EN (bit 4) if not set
efr_reg |= 0x8;
uart[EFR_REG] = efr_reg; // Write back to the register
// 4. Switch to operational mode to access the IER_REG register
uart[LCR_REG] = 0;
// 5. Clear IER_REG
uart[IER_REG] = 0;
// 6. Switch to configuration mode B to access DLL_REG and DLH_REG
uart[LCR_REG] = 0xBF;
// 7. Load the new divisor value (looking for 115200 baud)
uart[0x0] = 0x1A; // divisor low byte
uart[0x4] = 0; // divisor high byte
// 8. Switch to operational mode to access the IER_REG register
uart[LCR_REG] = 0;
// 9. Load new interrupt configuration
uart[IER_REG] = 0; // No interrupts wanted at this stage
// 10. Switch to configuration mode B to access the EFR_REG register
uart[LCR_REG] = 0xBF;
// 11. Restore the ENHANCED_EN value saved in step 3
if(old_enhanced_en)
uart[EFR_REG] = uart[EFR_REG] ^ 0x8;
// 12. Load the new protocol formatting (parity, stop bit, character length)
// and enter operational mode
uart[LCR_REG] = 0x3; // 8 bit characters, no parity, one stop bit
// 13. Load the new UART mode
uart[MDR1_REG] = 0;
return true;
}
/// Completely disable flow control on the UART
extern "C" bool uart_disableflowctl(int n)
{
volatile unsigned char *uart = uart_get(n);
if(!uart)
return false;
/** Configure hardware flow control */
// 1. Switch to configuration mode A to access the MCR_REG register
unsigned char old_lcr_reg = uart[LCR_REG];
uart[LCR_REG] = 0x80;
// 2. Enable submode TCR_TLR to access TCR_REG (part 1 of 2)
unsigned char mcr_reg = uart[MCR_REG];
unsigned char old_tcl_tlr = mcr_reg & 0x20;
if(!(mcr_reg & 0x20))
mcr_reg |= 0x20;
uart[MCR_REG] = mcr_reg;
// 3. Switch to configuration mode B to access the EFR_REG register
uart[LCR_REG] = 0xBF;
// 4. Enable submode TCR_TLR to access the TCR_REG register (part 2 of 2)
unsigned char efr_reg = uart[EFR_REG];
unsigned char old_enhanced_en = efr_reg & 0x8;
if(!(efr_reg & 0x8)) // Set ENHANCED_EN (bit 4) if not set
efr_reg |= 0x8;
uart[EFR_REG] = efr_reg; // Write back to the register
// 5. Load new start and halt trigger values
uart[TCR_REG] = 0;
// 6. Disable RX/TX hardware flow control mode, and restore the ENHANCED_EN
// values stored in step 4
uart[EFR_REG] = 0;
// 7. Switch to configuration mode A to access MCR_REG
uart[LCR_REG] = 0x80;
// 8. Restore the MCR_REG TCR_TLR value stored in step 2
if(!old_tcl_tlr)
uart[MCR_REG] = uart[MCR_REG] ^ 0x20;
// 9. Restore the LCR_REG value saved in step 1
uart[LCR_REG] = old_lcr_reg;
return true;
}
extern "C" void uart_write(int n, char c)
{
volatile unsigned char *uart = uart_get(n);
if(!uart)
return;
// Wait until the hold register is empty
while(!(uart[LSR_REG] & 0x20));
uart[THR_REG] = c;
}
extern "C" char uart_read(int n)
{
volatile unsigned char *uart = uart_get(n);
if(!uart)
return 0;
// Wait for data in the receive FIFO
while(!(uart[LSR_REG] & 0x1));
return uart[RHR_REG];
}
extern "C" inline void writeStr(int n, const char *str)
{
char c;
while ((c = *str++))
uart_write(n, c);
}
extern "C" void writeHex(int uart, unsigned int n)
{
bool noZeroes = true;
int i;
unsigned int tmp;
for (i = 28; i > 0; i -= 4)
{
tmp = (n >> i) & 0xF;
if (tmp == 0 && noZeroes)
continue;
if (tmp >= 0xA)
{
noZeroes = false;
uart_write(uart, tmp-0xA+'a');
}
else
{
noZeroes = false;
uart_write(uart, tmp+'0');
}
}
tmp = n & 0xF;
if (tmp >= 0xA)
uart_write(uart, tmp-0xA+'a');
else
uart_write(uart, tmp+'0');
}
/** GPIO implementation for the BeagleBoard */
class BeagleGpio
{
public:
BeagleGpio()
{}
~BeagleGpio()
{}
void initialise()
{
m_gpio1 = (volatile unsigned int *) 0x48310000;
initspecific(1, m_gpio1);
m_gpio2 = (volatile unsigned int *) 0x49050000;
initspecific(2, m_gpio2);
m_gpio3 = (volatile unsigned int *) 0x49052000;
initspecific(3, m_gpio3);
m_gpio4 = (volatile unsigned int *) 0x49054000;
initspecific(4, m_gpio4);
m_gpio5 = (volatile unsigned int *) 0x49056000;
initspecific(5, m_gpio5);
m_gpio6 = (volatile unsigned int *) 0x49058000;
initspecific(6, m_gpio6);
}
void clearpin(int pin)
{
// Grab the GPIO MMIO range for the pin
int base = 0;
volatile unsigned int *gpio = getGpioForPin(pin, &base);
if(!gpio)
{
writeStr(3, "BeagleGpio::drivepin : No GPIO found for pin ");
writeHex(3, pin);
writeStr(3, "!\r\n");
return;
}
// Write to the CLEARDATAOUT register
gpio[0x24] = (1 << base);
}
void drivepin(int pin)
{
// Grab the GPIO MMIO range for the pin
int base = 0;
volatile unsigned int *gpio = getGpioForPin(pin, &base);
if(!gpio)
{
writeStr(3, "BeagleGpio::drivepin : No GPIO found for pin ");
writeHex(3, pin);
writeStr(3, "!\r\n");
return;
}
// Write to the SETDATAOUT register. We can set a specific bit in
// this register without needing to maintain the state of a full
// 32-bit register (zeroes have no effect).
gpio[0x25] = (1 << base);
}
bool pinstate(int pin)
{
// Grab the GPIO MMIO range for the pin
int base = 0;
volatile unsigned int *gpio = getGpioForPin(pin, &base);
if(!gpio)
{
writeStr(3, "BeagleGpio::pinstate : No GPIO found for pin ");
writeHex(3, pin);
writeStr(3, "!\r\n");
return false;
}
return (gpio[0x25] & (1 << base));
}
int capturepin(int pin)
{
// Grab the GPIO MMIO range for the pin
int base = 0;
volatile unsigned int *gpio = getGpioForPin(pin, &base);
if(!gpio)
{
writeStr(3, "BeagleGpio::capturepin :No GPIO found for pin ");
writeHex(3, pin);
writeStr(3, "!\r\n");
return 0;
}
// Read the data from the pin
return (gpio[0xE] & (1 << base)) >> (base ? base - 1 : 0);
}
void enableoutput(int pin)
{
// Grab the GPIO MMIO range for the pin
int base = 0;
volatile unsigned int *gpio = getGpioForPin(pin, &base);
if(!gpio)
{
writeStr(3, "BeagleGpio::enableoutput :No GPIO found for pin ");
writeHex(3, pin);
writeStr(3, "!\r\n");
return;
}
// Set the pin as an output (if it's an input, the bit is set)
if(gpio[0xD] & (1 << base))
gpio[0xD] ^= (1 << base);
}
private:
/// Initialises a specific GPIO to a given set of defaults
void initspecific(int n, volatile unsigned int *gpio)
{
if(!gpio)
return;
// Write information about it
/// \todo When implementing within Pedigree, we'll have a much nicer
/// interface for string manipulation and writing stuff to the
/// UART.
unsigned int rev = gpio[0];
writeStr(3, "GPIO");
writeHex(3, n);
writeStr(3, ": revision ");
writeHex(3, (rev & 0xF0) >> 4);
writeStr(3, ".");
writeHex(3, rev & 0x0F);
writeStr(3, " - initialising: ");
// 1. Perform a software reset of the GPIO.
gpio[0x4] = 2;
while(!(gpio[0x5] & 1)); // Poll GPIO_SYSSTATUS, bit 0
// 2. Disable all IRQs
gpio[0x7] = 0; // GPIO_IRQENABLE1
gpio[0xB] = 0; // GPIO_IRQENABLE2
// 3. Enable the module
gpio[0xC] = 0;
// Completed the reset and initialisation.
writeStr(3, "Done.\r\n");
}
/// Gets the correct GPIO MMIO range for a given GPIO pin. The base
/// indicates which bit represents this pin in registers, where relevant
volatile unsigned int *getGpioForPin(int pin, int *bit)
{
volatile unsigned int *gpio = 0;
if(pin < 32)
{
*bit = pin;
gpio = m_gpio1;
}
else if((pin >= 34) && (pin < 64))
{
*bit = pin - 34;
gpio = m_gpio2;
}
else if((pin >= 64) && (pin < 96))
{
*bit = pin - 64;
gpio = m_gpio3;
}
else if((pin >= 96) && (pin < 128))
{
*bit = pin - 96;
gpio = m_gpio4;
}
else if((pin >= 128) && (pin < 160))
{
*bit = pin - 128;
gpio = m_gpio5;
}
else if((pin >= 160) && (pin < 192))
{
*bit = pin - 160;
gpio = m_gpio6;
}
else
gpio = 0;
return gpio;
}
volatile unsigned int *m_gpio1;
volatile unsigned int *m_gpio2;
volatile unsigned int *m_gpio3;
volatile unsigned int *m_gpio4;
volatile unsigned int *m_gpio5;
volatile unsigned int *m_gpio6;
};
/// First level descriptor - roughly equivalent to a page directory entry
/// on x86
struct FirstLevelDescriptor
{
/// Type field for descriptors
/// 0 = fault
/// 1 = page table
/// 2 = section or supersection
/// 3 = reserved
union {
struct {
uint32_t type : 2;
uint32_t ignore : 30;
} PACKED fault;
struct {
uint32_t type : 2;
uint32_t sbz1 : 1;
uint32_t ns : 1;
uint32_t sbz2 : 1;
uint32_t domain : 4;
uint32_t imp : 1;
uint32_t baseaddr : 22;
} PACKED pageTable;
struct {
uint32_t type : 2;
uint32_t b : 1;
uint32_t c : 1;
uint32_t xn : 1;
uint32_t domain : 4; /// extended base address for supersection
uint32_t imp : 1;
uint32_t ap1 : 2;
uint32_t tex : 3;
uint32_t ap2 : 1;
uint32_t s : 1;
uint32_t nG : 1;
uint32_t sectiontype : 1; /// = 0 for section, 1 for supersection
uint32_t ns : 1;
uint32_t base : 12;
} PACKED section;
uint32_t entry;
} descriptor;
} PACKED;
/// Second level descriptor - roughly equivalent to a page table entry
/// on x86
struct SecondLevelDescriptor
{
/// Type field for descriptors
/// 0 = fault
/// 1 = large page
/// >2 = small page (NX at bit 0)
union
{
struct {
uint32_t type : 2;
uint32_t ignore : 30;
} PACKED fault;
struct {
uint32_t type : 2;
uint32_t b : 1;
uint32_t c : 1;
uint32_t ap1 : 2;
uint32_t sbz : 3;
uint32_t ap2 : 1;
uint32_t s : 1;
uint32_t nG : 1;
uint32_t tex : 3;
uint32_t xn : 1;
uint32_t base : 16;
} PACKED largepage;
struct {
uint32_t type : 2;
uint32_t b : 1;
uint32_t c : 1;
uint32_t ap1 : 2;
uint32_t sbz : 3;
uint32_t ap2 : 1;
uint32_t s : 1;
uint32_t nG : 1;
uint32_t base : 20;
} PACKED smallpage;
uint32_t entry;
} descriptor;
} PACKED;
extern "C" void __start(uint32_t r0, uint32_t machineType, struct atag *tagList)
{
BeagleGpio gpio;
bool b = uart_softreset(3);
if(!b)
while(1);
b = uart_fifodefaults(3);
if(!b)
while(1);
b = uart_protoconfig(3);
if(!b)
while(1);
b = uart_disableflowctl(3);
if(!b)
while(1);
writeStr(3, "Pedigree for the BeagleBoard\r\n\r\n");
gpio.initialise();
gpio.enableoutput(149);
gpio.enableoutput(150);
gpio.drivepin(149); // Switch on the USR1 LED to show we're active and thinking
gpio.clearpin(150);
writeStr(3, "\r\nPlease press the USER button on the board to continue.\r\n");
while(!gpio.capturepin(7));
writeStr(3, "USER button pressed, continuing...\r\n\r\n");
writeStr(3, "Press 1 to toggle the USR0 LED, and 2 to toggle the USR1 LED.\r\nPress 0 to clear both LEDs. Hit ENTER to boot the kernel.\r\n");
while(1)
{
char c = uart_read(3);
if(c == '1')
{
writeStr(3, "Toggling USR0 LED\r\n");
if(gpio.pinstate(150))
gpio.clearpin(150);
else
gpio.drivepin(150);
}
else if(c == '2')
{
writeStr(3, "Toggling USR1 LED\r\n");
if(gpio.pinstate(149))
gpio.clearpin(149);
else
gpio.drivepin(149);
}
else if(c == '0')
{
writeStr(3, "Clearing both USR0 and USR1 LEDs\r\n");
gpio.clearpin(149);
gpio.clearpin(150);
}
else if((c == 13) || (c == 10))
break;
}
#if 0 // Set to 1 to enable the MMU test instead of loading the kernel.
writeStr(3, "\r\n\r\nVirtual memory test starting...\r\n");
FirstLevelDescriptor *pdir = (FirstLevelDescriptor*) 0x80100000;
memset(pdir, 0, 0x4000);
uint32_t base1 = 0x80000000; // Currently running code
uint32_t base2 = 0x49000000; // UART3
// First section covers the current code, identity mapped.
uint32_t pdir_offset = base1 >> 20;
pdir[pdir_offset].descriptor.entry = base1;
pdir[pdir_offset].descriptor.section.type = 2;
pdir[pdir_offset].descriptor.section.b = 0;
pdir[pdir_offset].descriptor.section.c = 0;
pdir[pdir_offset].descriptor.section.xn = 0;
pdir[pdir_offset].descriptor.section.domain = 0;
pdir[pdir_offset].descriptor.section.imp = 0;
pdir[pdir_offset].descriptor.section.ap1 = 3;
pdir[pdir_offset].descriptor.section.ap2 = 0;
pdir[pdir_offset].descriptor.section.tex = 0;
pdir[pdir_offset].descriptor.section.s = 1;
pdir[pdir_offset].descriptor.section.nG = 0;
pdir[pdir_offset].descriptor.section.sectiontype = 0;
pdir[pdir_offset].descriptor.section.ns = 0;
// Second section covers the UART, identity mapped.
pdir_offset = base2 >> 20;
pdir[pdir_offset].descriptor.entry = base2;
pdir[pdir_offset].descriptor.section.type = 2;
pdir[pdir_offset].descriptor.section.b = 0;
pdir[pdir_offset].descriptor.section.c = 0;
pdir[pdir_offset].descriptor.section.xn = 0;
pdir[pdir_offset].descriptor.section.domain = 0;
pdir[pdir_offset].descriptor.section.imp = 0;
pdir[pdir_offset].descriptor.section.ap1 = 3;
pdir[pdir_offset].descriptor.section.ap2 = 0;
pdir[pdir_offset].descriptor.section.tex = 0;
pdir[pdir_offset].descriptor.section.s = 1;
pdir[pdir_offset].descriptor.section.nG = 0;
pdir[pdir_offset].descriptor.section.sectiontype = 0;
pdir[pdir_offset].descriptor.section.ns = 0;
writeStr(3, "Writing to TTBR0 and enabling access to domain 0...\r\n");
asm volatile("MCR p15,0,%0,c2,c0,0" : : "r" (0x80100000));
asm volatile("MCR p15,0,%0,c3,c0,0" : : "r" (0xFFFFFFFF)); // Manager access to all domains for now
// Enable the MMU
uint32_t sctlr = 0;
asm volatile("MRC p15,0,%0,c1,c0,0" : "=r" (sctlr));
if(!(sctlr & 1))
sctlr |= 1;
else
writeStr(3, "It seems the MMU is already enabled?\r\n");
writeStr(3, "Enabling the MMU...\r\n");
asm volatile("MCR p15,0,%0,c1,c0,0" : : "r" (sctlr));
// If you can see the string, the identity map is complete and working.
writeStr(3, "\r\n\r\nTest completed without errors.\r\n");
while(1)
{
asm volatile("wfi");
}
#else
writeStr(3, "\r\n\r\nPlease wait while the kernel is loaded...\r\n");
Elf32 elf("kernel");
writeStr(3, "Preparing file... ");
elf.load((uint8_t*)file, 0);
writeStr(3, "Done!\r\n");
writeStr(3, "Loading file into memory (please wait) ");
elf.writeSections();
writeStr(3, " Done!\r\n");
int (*main)(struct BootstrapStruct_t*) = (int (*)(struct BootstrapStruct_t*)) elf.getEntryPoint();
struct BootstrapStruct_t *bs = reinterpret_cast<struct BootstrapStruct_t *>(0x80008000);
writeStr(3, "Creating bootstrap information structure... ");
memset(bs, 0, sizeof(bs));
bs->shndx = elf.m_pHeader->shstrndx;
bs->num = elf.m_pHeader->shnum;
bs->size = elf.m_pHeader->shentsize;
bs->addr = (unsigned int)elf.m_pSectionHeaders;
// Repurpose these variables a little....
bs->mods_addr = reinterpret_cast<uint32_t>(elf.m_pBuffer);
bs->mods_count = (sizeof file) + 0x1000;
// For every section header, set .addr = .offset + m_pBuffer.
for (int i = 0; i < elf.m_pHeader->shnum; i++)
{
elf.m_pSectionHeaders[i].addr = elf.m_pSectionHeaders[i].offset + (uint32_t)elf.m_pBuffer;
}
writeStr(3, "Done!\r\n");
// Just before running the kernel proper, turn off both LEDs so we can use
// their states for debugging the kernel.
gpio.clearpin(149);
gpio.clearpin(150);
// Run the kernel, finally
writeStr(3, "Now starting the Pedigree kernel (can take a while, please wait).\r\n\r\n");
main(bs);
#endif
while (1)
{
asm volatile("wfi");
}
}
| jmolloy/pedigree | src/system/boot/arm/main_beagle.cc | C++ | isc | 26,018 |
/**
* QUnit v1.3.0pre - A JavaScript Unit Testing Framework
*
* http://docs.jquery.com/QUnit
*
* Copyright (c) 2011 John Resig, Jörn Zaefferer
* Dual licensed under the MIT (MIT-LICENSE.txt)
* or GPL (GPL-LICENSE.txt) licenses.
* Pulled Live from Git Sat Jan 14 01:10:01 UTC 2012
* Last Commit: 0712230bb203c262211649b32bd712ec7df5f857
*/
(function(window) {
var defined = {
setTimeout: typeof window.setTimeout !== "undefined",
sessionStorage: (function() {
try {
return !!sessionStorage.getItem;
} catch(e) {
return false;
}
})()
};
var testId = 0,
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty;
var Test = function(name, testName, expected, testEnvironmentArg, async, callback) {
this.name = name;
this.testName = testName;
this.expected = expected;
this.testEnvironmentArg = testEnvironmentArg;
this.async = async;
this.callback = callback;
this.assertions = [];
};
Test.prototype = {
init: function() {
var tests = id("qunit-tests");
if (tests) {
var b = document.createElement("strong");
b.innerHTML = "Running " + this.name;
var li = document.createElement("li");
li.appendChild( b );
li.className = "running";
li.id = this.id = "test-output" + testId++;
tests.appendChild( li );
}
},
setup: function() {
if (this.module != config.previousModule) {
if ( config.previousModule ) {
runLoggingCallbacks('moduleDone', QUnit, {
name: config.previousModule,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all
} );
}
config.previousModule = this.module;
config.moduleStats = { all: 0, bad: 0 };
runLoggingCallbacks( 'moduleStart', QUnit, {
name: this.module
} );
}
config.current = this;
this.testEnvironment = extend({
setup: function() {},
teardown: function() {}
}, this.moduleTestEnvironment);
if (this.testEnvironmentArg) {
extend(this.testEnvironment, this.testEnvironmentArg);
}
runLoggingCallbacks( 'testStart', QUnit, {
name: this.testName,
module: this.module
});
// allow utility functions to access the current test environment
// TODO why??
QUnit.current_testEnvironment = this.testEnvironment;
try {
if ( !config.pollution ) {
saveGlobal();
}
this.testEnvironment.setup.call(this.testEnvironment);
} catch(e) {
QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message );
}
},
run: function() {
config.current = this;
if ( this.async ) {
QUnit.stop();
}
if ( config.notrycatch ) {
this.callback.call(this.testEnvironment);
return;
}
try {
this.callback.call(this.testEnvironment);
} catch(e) {
fail("Test " + this.testName + " died, exception and test follows", e, this.callback);
QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) );
// else next test will carry the responsibility
saveGlobal();
// Restart the tests if they're blocking
if ( config.blocking ) {
QUnit.start();
}
}
},
teardown: function() {
config.current = this;
try {
this.testEnvironment.teardown.call(this.testEnvironment);
checkPollution();
} catch(e) {
QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message );
}
},
finish: function() {
config.current = this;
if ( this.expected != null && this.expected != this.assertions.length ) {
QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" );
}
var good = 0, bad = 0,
tests = id("qunit-tests");
config.stats.all += this.assertions.length;
config.moduleStats.all += this.assertions.length;
if ( tests ) {
var ol = document.createElement("ol");
for ( var i = 0; i < this.assertions.length; i++ ) {
var assertion = this.assertions[i];
var li = document.createElement("li");
li.className = assertion.result ? "pass" : "fail";
li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed");
ol.appendChild( li );
if ( assertion.result ) {
good++;
} else {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
// store result when possible
if ( QUnit.config.reorder && defined.sessionStorage ) {
if (bad) {
sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad);
} else {
sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName);
}
}
if (bad == 0) {
ol.style.display = "none";
}
var b = document.createElement("strong");
b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>";
var a = document.createElement("a");
a.innerHTML = "Rerun";
a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
addEvent(b, "click", function() {
var next = b.nextSibling.nextSibling,
display = next.style.display;
next.style.display = display === "none" ? "block" : "none";
});
addEvent(b, "dblclick", function(e) {
var target = e && e.target ? e.target : window.event.srcElement;
if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) {
target = target.parentNode;
}
if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
}
});
var li = id(this.id);
li.className = bad ? "fail" : "pass";
li.removeChild( li.firstChild );
li.appendChild( b );
li.appendChild( a );
li.appendChild( ol );
} else {
for ( var i = 0; i < this.assertions.length; i++ ) {
if ( !this.assertions[i].result ) {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
}
try {
QUnit.reset();
} catch(e) {
fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset);
}
runLoggingCallbacks( 'testDone', QUnit, {
name: this.testName,
module: this.module,
failed: bad,
passed: this.assertions.length - bad,
total: this.assertions.length
} );
},
queue: function() {
var test = this;
synchronize(function() {
test.init();
});
function run() {
// each of these can by async
synchronize(function() {
test.setup();
});
synchronize(function() {
test.run();
});
synchronize(function() {
test.teardown();
});
synchronize(function() {
test.finish();
});
}
// defer when previous test run passed, if storage is available
var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName);
if (bad) {
run();
} else {
synchronize(run, true);
};
}
};
var QUnit = {
// call on start of module test to prepend name to all tests
module: function(name, testEnvironment) {
config.currentModule = name;
config.currentModuleTestEnviroment = testEnvironment;
},
asyncTest: function(testName, expected, callback) {
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
QUnit.test(testName, expected, callback, true);
},
test: function(testName, expected, callback, async) {
var name = '<span class="test-name">' + escapeInnerText(testName) + '</span>', testEnvironmentArg;
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
// is 2nd argument a testEnvironment?
if ( expected && typeof expected === 'object') {
testEnvironmentArg = expected;
expected = null;
}
if ( config.currentModule ) {
name = '<span class="module-name">' + config.currentModule + "</span>: " + name;
}
if ( !validTest(config.currentModule + ": " + testName) ) {
return;
}
var test = new Test(name, testName, expected, testEnvironmentArg, async, callback);
test.module = config.currentModule;
test.moduleTestEnvironment = config.currentModuleTestEnviroment;
test.queue();
},
/**
* Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
*/
expect: function(asserts) {
config.current.expected = asserts;
},
/**
* Asserts true.
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
*/
ok: function(a, msg) {
a = !!a;
var details = {
result: a,
message: msg
};
msg = escapeInnerText(msg);
runLoggingCallbacks( 'log', QUnit, details );
config.current.assertions.push({
result: a,
message: msg
});
},
/**
* Checks that the first two arguments are equal, with an optional message.
* Prints out both actual and expected values.
*
* Prefered to ok( actual == expected, message )
*
* @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
*
* @param Object actual
* @param Object expected
* @param String message (optional)
*/
equal: function(actual, expected, message) {
QUnit.push(expected == actual, actual, expected, message);
},
notEqual: function(actual, expected, message) {
QUnit.push(expected != actual, actual, expected, message);
},
deepEqual: function(actual, expected, message) {
QUnit.push(QUnit.equiv(actual, expected), actual, expected, message);
},
notDeepEqual: function(actual, expected, message) {
QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message);
},
strictEqual: function(actual, expected, message) {
QUnit.push(expected === actual, actual, expected, message);
},
notStrictEqual: function(actual, expected, message) {
QUnit.push(expected !== actual, actual, expected, message);
},
raises: function(block, expected, message) {
var actual, ok = false;
if (typeof expected === 'string') {
message = expected;
expected = null;
}
try {
block();
} catch (e) {
actual = e;
}
if (actual) {
// we don't want to validate thrown error
if (!expected) {
ok = true;
// expected is a regexp
} else if (QUnit.objectType(expected) === "regexp") {
ok = expected.test(actual);
// expected is a constructor
} else if (actual instanceof expected) {
ok = true;
// expected is a validation function which returns true is validation passed
} else if (expected.call({}, actual) === true) {
ok = true;
}
}
QUnit.ok(ok, message);
},
start: function(count) {
config.semaphore -= count || 1;
if (config.semaphore > 0) {
// don't start until equal number of stop-calls
return;
}
if (config.semaphore < 0) {
// ignore if start is called more often then stop
config.semaphore = 0;
}
// A slight delay, to avoid any current callbacks
if ( defined.setTimeout ) {
window.setTimeout(function() {
if (config.semaphore > 0) {
return;
}
if ( config.timeout ) {
clearTimeout(config.timeout);
}
config.blocking = false;
process(true);
}, 13);
} else {
config.blocking = false;
process(true);
}
},
stop: function(count) {
config.semaphore += count || 1;
config.blocking = true;
if ( config.testTimeout && defined.setTimeout ) {
clearTimeout(config.timeout);
config.timeout = window.setTimeout(function() {
QUnit.ok( false, "Test timed out" );
config.semaphore = 1;
QUnit.start();
}, config.testTimeout);
}
}
};
//We want access to the constructor's prototype
(function() {
function F(){};
F.prototype = QUnit;
QUnit = new F();
//Make F QUnit's constructor so that we can add to the prototype later
QUnit.constructor = F;
})();
// Backwards compatibility, deprecated
QUnit.equals = QUnit.equal;
QUnit.same = QUnit.deepEqual;
// Maintain internal state
var config = {
// The queue of tests to run
queue: [],
// block until document ready
blocking: true,
// when enabled, show only failing tests
// gets persisted through sessionStorage and can be changed in UI via checkbox
hidepassed: false,
// by default, run previously failed tests first
// very useful in combination with "Hide passed tests" checked
reorder: true,
// by default, modify document.title when suite is done
altertitle: true,
urlConfig: ['noglobals', 'notrycatch'],
//logging callback queues
begin: [],
done: [],
log: [],
testStart: [],
testDone: [],
moduleStart: [],
moduleDone: []
};
// Load paramaters
(function() {
var location = window.location || { search: "", protocol: "file:" },
params = location.search.slice( 1 ).split( "&" ),
length = params.length,
urlParams = {},
current;
if ( params[ 0 ] ) {
for ( var i = 0; i < length; i++ ) {
current = params[ i ].split( "=" );
current[ 0 ] = decodeURIComponent( current[ 0 ] );
// allow just a key to turn on a flag, e.g., test.html?noglobals
current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
urlParams[ current[ 0 ] ] = current[ 1 ];
}
}
QUnit.urlParams = urlParams;
config.filter = urlParams.filter;
// Figure out if we're running the tests from a server or not
QUnit.isLocal = !!(location.protocol === 'file:');
})();
// Expose the API as global variables, unless an 'exports'
// object exists, in that case we assume we're in CommonJS
if ( typeof exports === "undefined" || typeof require === "undefined" ) {
extend(window, QUnit);
window.QUnit = QUnit;
} else {
extend(exports, QUnit);
exports.QUnit = QUnit;
}
// define these after exposing globals to keep them in these QUnit namespace only
extend(QUnit, {
config: config,
// Initialize the configuration options
init: function() {
extend(config, {
stats: { all: 0, bad: 0 },
moduleStats: { all: 0, bad: 0 },
started: +new Date,
updateRate: 1000,
blocking: false,
autostart: true,
autorun: false,
filter: "",
queue: [],
semaphore: 0
});
var tests = id( "qunit-tests" ),
banner = id( "qunit-banner" ),
result = id( "qunit-testresult" );
if ( tests ) {
tests.innerHTML = "";
}
if ( banner ) {
banner.className = "";
}
if ( result ) {
result.parentNode.removeChild( result );
}
if ( tests ) {
result = document.createElement( "p" );
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore( result, tests );
result.innerHTML = 'Running...<br/> ';
}
},
/**
* Resets the test setup. Useful for tests that modify the DOM.
*
* If jQuery is available, uses jQuery's html(), otherwise just innerHTML.
*/
reset: function() {
if ( window.jQuery ) {
jQuery( "#qunit-fixture" ).html( config.fixture );
} else {
var main = id( 'qunit-fixture' );
if ( main ) {
main.innerHTML = config.fixture;
}
}
},
/**
* Trigger an event on an element.
*
* @example triggerEvent( document.body, "click" );
*
* @param DOMElement elem
* @param String type
*/
triggerEvent: function( elem, type, event ) {
if ( document.createEvent ) {
event = document.createEvent("MouseEvents");
event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent( event );
} else if ( elem.fireEvent ) {
elem.fireEvent("on"+type);
}
},
// Safe object type checking
is: function( type, obj ) {
return QUnit.objectType( obj ) == type;
},
objectType: function( obj ) {
if (typeof obj === "undefined") {
return "undefined";
// consider: typeof null === object
}
if (obj === null) {
return "null";
}
var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || '';
switch (type) {
case 'Number':
if (isNaN(obj)) {
return "nan";
} else {
return "number";
}
case 'String':
case 'Boolean':
case 'Array':
case 'Date':
case 'RegExp':
case 'Function':
return type.toLowerCase();
}
if (typeof obj === "object") {
return "object";
}
return undefined;
},
push: function(result, actual, expected, message) {
var details = {
result: result,
message: message,
actual: actual,
expected: expected
};
message = escapeInnerText(message) || (result ? "okay" : "failed");
message = '<span class="test-message">' + message + "</span>";
expected = escapeInnerText(QUnit.jsDump.parse(expected));
actual = escapeInnerText(QUnit.jsDump.parse(actual));
var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>';
if (actual != expected) {
output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>';
output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>';
}
if (!result) {
var source = sourceFromStacktrace();
if (source) {
details.source = source;
output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr>';
}
}
output += "</table>";
runLoggingCallbacks( 'log', QUnit, details );
config.current.assertions.push({
result: !!result,
message: output
});
},
url: function( params ) {
params = extend( extend( {}, QUnit.urlParams ), params );
var querystring = "?",
key;
for ( key in params ) {
if ( !hasOwn.call( params, key ) ) {
continue;
}
querystring += encodeURIComponent( key ) + "=" +
encodeURIComponent( params[ key ] ) + "&";
}
return window.location.pathname + querystring.slice( 0, -1 );
},
extend: extend,
id: id,
addEvent: addEvent
});
//QUnit.constructor is set to the empty F() above so that we can add to it's prototype later
//Doing this allows us to tell if the following methods have been overwritten on the actual
//QUnit object, which is a deprecated way of using the callbacks.
extend(QUnit.constructor.prototype, {
// Logging callbacks; all receive a single argument with the listed properties
// run test/logs.html for any related changes
begin: registerLoggingCallback('begin'),
// done: { failed, passed, total, runtime }
done: registerLoggingCallback('done'),
// log: { result, actual, expected, message }
log: registerLoggingCallback('log'),
// testStart: { name }
testStart: registerLoggingCallback('testStart'),
// testDone: { name, failed, passed, total }
testDone: registerLoggingCallback('testDone'),
// moduleStart: { name }
moduleStart: registerLoggingCallback('moduleStart'),
// moduleDone: { name, failed, passed, total }
moduleDone: registerLoggingCallback('moduleDone')
});
if ( typeof document === "undefined" || document.readyState === "complete" ) {
config.autorun = true;
}
QUnit.load = function() {
runLoggingCallbacks( 'begin', QUnit, {} );
// Initialize the config, saving the execution queue
var oldconfig = extend({}, config);
QUnit.init();
extend(config, oldconfig);
config.blocking = false;
var urlConfigHtml = '', len = config.urlConfig.length;
for ( var i = 0, val; i < len, val = config.urlConfig[i]; i++ ) {
config[val] = QUnit.urlParams[val];
urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>';
}
var userAgent = id("qunit-userAgent");
if ( userAgent ) {
userAgent.innerHTML = navigator.userAgent;
}
var banner = id("qunit-header");
if ( banner ) {
banner.innerHTML = '<a href="' + QUnit.url({ filter: undefined }) + '"> ' + banner.innerHTML + '</a> ' + urlConfigHtml;
addEvent( banner, "change", function( event ) {
var params = {};
params[ event.target.name ] = event.target.checked ? true : undefined;
window.location = QUnit.url( params );
});
}
var toolbar = id("qunit-testrunner-toolbar");
if ( toolbar ) {
var filter = document.createElement("input");
filter.type = "checkbox";
filter.id = "qunit-filter-pass";
addEvent( filter, "click", function() {
var ol = document.getElementById("qunit-tests");
if ( filter.checked ) {
ol.className = ol.className + " hidepass";
} else {
var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " ";
ol.className = tmp.replace(/ hidepass /, " ");
}
if ( defined.sessionStorage ) {
if (filter.checked) {
sessionStorage.setItem("qunit-filter-passed-tests", "true");
} else {
sessionStorage.removeItem("qunit-filter-passed-tests");
}
}
});
if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) {
filter.checked = true;
var ol = document.getElementById("qunit-tests");
ol.className = ol.className + " hidepass";
}
toolbar.appendChild( filter );
var label = document.createElement("label");
label.setAttribute("for", "qunit-filter-pass");
label.innerHTML = "Hide passed tests";
toolbar.appendChild( label );
}
var main = id('qunit-fixture');
if ( main ) {
config.fixture = main.innerHTML;
}
if (config.autostart) {
QUnit.start();
}
};
addEvent(window, "load", QUnit.load);
// addEvent(window, "error") gives us a useless event object
window.onerror = function( message, file, line ) {
if ( QUnit.config.current ) {
ok( false, message + ", " + file + ":" + line );
} else {
test( "global failure", function() {
ok( false, message + ", " + file + ":" + line );
});
}
};
function done() {
config.autorun = true;
// Log the last module results
if ( config.currentModule ) {
runLoggingCallbacks( 'moduleDone', QUnit, {
name: config.currentModule,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all
} );
}
var banner = id("qunit-banner"),
tests = id("qunit-tests"),
runtime = +new Date - config.started,
passed = config.stats.all - config.stats.bad,
html = [
'Tests completed in ',
runtime,
' milliseconds.<br/>',
'<span class="passed">',
passed,
'</span> tests of <span class="total">',
config.stats.all,
'</span> passed, <span class="failed">',
config.stats.bad,
'</span> failed.'
].join('');
if ( banner ) {
banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass");
}
if ( tests ) {
id( "qunit-testresult" ).innerHTML = html;
}
if ( config.altertitle && typeof document !== "undefined" && document.title ) {
// show ✖ for good, ✔ for bad suite result in title
// use escape sequences in case file gets loaded with non-utf-8-charset
document.title = [
(config.stats.bad ? "\u2716" : "\u2714"),
document.title.replace(/^[\u2714\u2716] /i, "")
].join(" ");
}
runLoggingCallbacks( 'done', QUnit, {
failed: config.stats.bad,
passed: passed,
total: config.stats.all,
runtime: runtime
} );
}
function validTest( name ) {
var filter = config.filter,
run = false;
if ( !filter ) {
return true;
}
var not = filter.charAt( 0 ) === "!";
if ( not ) {
filter = filter.slice( 1 );
}
if ( name.indexOf( filter ) !== -1 ) {
return !not;
}
if ( not ) {
run = true;
}
return run;
}
// so far supports only Firefox, Chrome and Opera (buggy)
// could be extended in the future to use something like https://github.com/csnover/TraceKit
function sourceFromStacktrace() {
try {
throw new Error();
} catch ( e ) {
if (e.stacktrace) {
// Opera
return e.stacktrace.split("\n")[6];
} else if (e.stack) {
// Firefox, Chrome
return e.stack.split("\n")[4];
} else if (e.sourceURL) {
// Safari, PhantomJS
// TODO sourceURL points at the 'throw new Error' line above, useless
//return e.sourceURL + ":" + e.line;
}
}
}
function escapeInnerText(s) {
if (!s) {
return "";
}
s = s + "";
return s.replace(/[\&<>]/g, function(s) {
switch(s) {
case "&": return "&";
case "<": return "<";
case ">": return ">";
default: return s;
}
});
}
function synchronize( callback, last ) {
config.queue.push( callback );
if ( config.autorun && !config.blocking ) {
process(last);
}
}
function process( last ) {
var start = new Date().getTime();
config.depth = config.depth ? config.depth + 1 : 1;
while ( config.queue.length && !config.blocking ) {
if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) {
config.queue.shift()();
} else {
window.setTimeout( function(){
process( last );
}, 13 );
break;
}
}
config.depth--;
if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
done();
}
}
function saveGlobal() {
config.pollution = [];
if ( config.noglobals ) {
for ( var key in window ) {
if ( !hasOwn.call( window, key ) ) {
continue;
}
config.pollution.push( key );
}
}
}
function checkPollution( name ) {
var old = config.pollution;
saveGlobal();
var newGlobals = diff( config.pollution, old );
if ( newGlobals.length > 0 ) {
ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
}
var deletedGlobals = diff( old, config.pollution );
if ( deletedGlobals.length > 0 ) {
ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
}
}
// returns a new Array with the elements that are in a but not in b
function diff( a, b ) {
var result = a.slice();
for ( var i = 0; i < result.length; i++ ) {
for ( var j = 0; j < b.length; j++ ) {
if ( result[i] === b[j] ) {
result.splice(i, 1);
i--;
break;
}
}
}
return result;
}
function fail(message, exception, callback) {
if ( typeof console !== "undefined" && console.error && console.warn ) {
console.error(message);
console.error(exception);
console.error(exception.stack);
console.warn(callback.toString());
} else if ( window.opera && opera.postError ) {
opera.postError(message, exception, callback.toString);
}
}
function extend(a, b) {
for ( var prop in b ) {
if ( b[prop] === undefined ) {
delete a[prop];
// Avoid "Member not found" error in IE8 caused by setting window.constructor
} else if ( prop !== "constructor" || a !== window ) {
a[prop] = b[prop];
}
}
return a;
}
function addEvent(elem, type, fn) {
if ( elem.addEventListener ) {
elem.addEventListener( type, fn, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, fn );
} else {
fn();
}
}
function id(name) {
return !!(typeof document !== "undefined" && document && document.getElementById) &&
document.getElementById( name );
}
function registerLoggingCallback(key){
return function(callback){
config[key].push( callback );
};
}
// Supports deprecated method of completely overwriting logging callbacks
function runLoggingCallbacks(key, scope, args) {
//debugger;
var callbacks;
if ( QUnit.hasOwnProperty(key) ) {
QUnit[key].call(scope, args);
} else {
callbacks = config[key];
for( var i = 0; i < callbacks.length; i++ ) {
callbacks[i].call( scope, args );
}
}
}
// Test for equality any JavaScript type.
// Author: Philippe Rathé <prathe@gmail.com>
QUnit.equiv = function () {
var innerEquiv; // the real equiv function
var callers = []; // stack to decide between skip/abort functions
var parents = []; // stack to avoiding loops from circular referencing
// Call the o related callback with the given arguments.
function bindCallbacks(o, callbacks, args) {
var prop = QUnit.objectType(o);
if (prop) {
if (QUnit.objectType(callbacks[prop]) === "function") {
return callbacks[prop].apply(callbacks, args);
} else {
return callbacks[prop]; // or undefined
}
}
}
var getProto = Object.getPrototypeOf || function (obj) {
return obj.__proto__;
};
var callbacks = function () {
// for string, boolean, number and null
function useStrictEquality(b, a) {
if (b instanceof a.constructor || a instanceof b.constructor) {
// to catch short annotaion VS 'new' annotation of a
// declaration
// e.g. var i = 1;
// var j = new Number(1);
return a == b;
} else {
return a === b;
}
}
return {
"string" : useStrictEquality,
"boolean" : useStrictEquality,
"number" : useStrictEquality,
"null" : useStrictEquality,
"undefined" : useStrictEquality,
"nan" : function(b) {
return isNaN(b);
},
"date" : function(b, a) {
return QUnit.objectType(b) === "date"
&& a.valueOf() === b.valueOf();
},
"regexp" : function(b, a) {
return QUnit.objectType(b) === "regexp"
&& a.source === b.source && // the regex itself
a.global === b.global && // and its modifers
// (gmi) ...
a.ignoreCase === b.ignoreCase
&& a.multiline === b.multiline;
},
// - skip when the property is a method of an instance (OOP)
// - abort otherwise,
// initial === would have catch identical references anyway
"function" : function() {
var caller = callers[callers.length - 1];
return caller !== Object && typeof caller !== "undefined";
},
"array" : function(b, a) {
var i, j, loop;
var len;
// b could be an object literal here
if (!(QUnit.objectType(b) === "array")) {
return false;
}
len = a.length;
if (len !== b.length) { // safe and faster
return false;
}
// track reference to avoid circular references
parents.push(a);
for (i = 0; i < len; i++) {
loop = false;
for (j = 0; j < parents.length; j++) {
if (parents[j] === a[i]) {
loop = true;// dont rewalk array
}
}
if (!loop && !innerEquiv(a[i], b[i])) {
parents.pop();
return false;
}
}
parents.pop();
return true;
},
"object" : function(b, a) {
var i, j, loop;
var eq = true; // unless we can proove it
var aProperties = [], bProperties = []; // collection of
// strings
// comparing constructors is more strict than using
// instanceof
if (a.constructor !== b.constructor) {
// Allow objects with no prototype to be equivalent to
// objects with Object as their constructor.
if (!((getProto(a) === null && getProto(b) === Object.prototype) ||
(getProto(b) === null && getProto(a) === Object.prototype)))
{
return false;
}
}
// stack constructor before traversing properties
callers.push(a.constructor);
// track reference to avoid circular references
parents.push(a);
for (i in a) { // be strict: don't ensures hasOwnProperty
// and go deep
loop = false;
for (j = 0; j < parents.length; j++) {
if (parents[j] === a[i])
loop = true; // don't go down the same path
// twice
}
aProperties.push(i); // collect a's properties
if (!loop && !innerEquiv(a[i], b[i])) {
eq = false;
break;
}
}
callers.pop(); // unstack, we are done
parents.pop();
for (i in b) {
bProperties.push(i); // collect b's properties
}
// Ensures identical properties name
return eq
&& innerEquiv(aProperties.sort(), bProperties
.sort());
}
};
}();
innerEquiv = function() { // can take multiple arguments
var args = Array.prototype.slice.apply(arguments);
if (args.length < 2) {
return true; // end transition
}
return (function(a, b) {
if (a === b) {
return true; // catch the most you can
} else if (a === null || b === null || typeof a === "undefined"
|| typeof b === "undefined"
|| QUnit.objectType(a) !== QUnit.objectType(b)) {
return false; // don't lose time with error prone cases
} else {
return bindCallbacks(a, callbacks, [ b, a ]);
}
// apply transition with (1..n) arguments
})(args[0], args[1])
&& arguments.callee.apply(this, args.splice(1,
args.length - 1));
};
return innerEquiv;
}();
/**
* jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com |
* http://flesler.blogspot.com Licensed under BSD
* (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008
*
* @projectDescription Advanced and extensible data dumping for Javascript.
* @version 1.0.0
* @author Ariel Flesler
* @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
*/
QUnit.jsDump = (function() {
function quote( str ) {
return '"' + str.toString().replace(/"/g, '\\"') + '"';
};
function literal( o ) {
return o + '';
};
function join( pre, arr, post ) {
var s = jsDump.separator(),
base = jsDump.indent(),
inner = jsDump.indent(1);
if ( arr.join )
arr = arr.join( ',' + s + inner );
if ( !arr )
return pre + post;
return [ pre, inner + arr, base + post ].join(s);
};
function array( arr, stack ) {
var i = arr.length, ret = Array(i);
this.up();
while ( i-- )
ret[i] = this.parse( arr[i] , undefined , stack);
this.down();
return join( '[', ret, ']' );
};
var reName = /^function (\w+)/;
var jsDump = {
parse:function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance
stack = stack || [ ];
var parser = this.parsers[ type || this.typeOf(obj) ];
type = typeof parser;
var inStack = inArray(obj, stack);
if (inStack != -1) {
return 'recursion('+(inStack - stack.length)+')';
}
//else
if (type == 'function') {
stack.push(obj);
var res = parser.call( this, obj, stack );
stack.pop();
return res;
}
// else
return (type == 'string') ? parser : this.parsers.error;
},
typeOf:function( obj ) {
var type;
if ( obj === null ) {
type = "null";
} else if (typeof obj === "undefined") {
type = "undefined";
} else if (QUnit.is("RegExp", obj)) {
type = "regexp";
} else if (QUnit.is("Date", obj)) {
type = "date";
} else if (QUnit.is("Function", obj)) {
type = "function";
} else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") {
type = "window";
} else if (obj.nodeType === 9) {
type = "document";
} else if (obj.nodeType) {
type = "node";
} else if (
// native arrays
toString.call( obj ) === "[object Array]" ||
// NodeList objects
( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) )
) {
type = "array";
} else {
type = typeof obj;
}
return type;
},
separator:function() {
return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' ';
},
indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
if ( !this.multiline )
return '';
var chr = this.indentChar;
if ( this.HTML )
chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
return Array( this._depth_ + (extra||0) ).join(chr);
},
up:function( a ) {
this._depth_ += a || 1;
},
down:function( a ) {
this._depth_ -= a || 1;
},
setParser:function( name, parser ) {
this.parsers[name] = parser;
},
// The next 3 are exposed so you can use them
quote:quote,
literal:literal,
join:join,
//
_depth_: 1,
// This is the list of parsers, to modify them, use jsDump.setParser
parsers:{
window: '[Window]',
document: '[Document]',
error:'[ERROR]', //when no parser is found, shouldn't happen
unknown: '[Unknown]',
'null':'null',
'undefined':'undefined',
'function':function( fn ) {
var ret = 'function',
name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
if ( name )
ret += ' ' + name;
ret += '(';
ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join('');
return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' );
},
array: array,
nodelist: array,
arguments: array,
object:function( map, stack ) {
var ret = [ ];
QUnit.jsDump.up();
for ( var key in map ) {
var val = map[key];
ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(val, undefined, stack));
}
QUnit.jsDump.down();
return join( '{', ret, '}' );
},
node:function( node ) {
var open = QUnit.jsDump.HTML ? '<' : '<',
close = QUnit.jsDump.HTML ? '>' : '>';
var tag = node.nodeName.toLowerCase(),
ret = open + tag;
for ( var a in QUnit.jsDump.DOMAttrs ) {
var val = node[QUnit.jsDump.DOMAttrs[a]];
if ( val )
ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' );
}
return ret + close + open + '/' + tag + close;
},
functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
var l = fn.length;
if ( !l ) return '';
var args = Array(l);
while ( l-- )
args[l] = String.fromCharCode(97+l);//97 is 'a'
return ' ' + args.join(', ') + ' ';
},
key:quote, //object calls it internally, the key part of an item in a map
functionCode:'[code]', //function calls it internally, it's the content of the function
attribute:quote, //node calls it internally, it's an html attribute value
string:quote,
date:quote,
regexp:literal, //regex
number:literal,
'boolean':literal
},
DOMAttrs:{//attributes to dump from nodes, name=>realName
id:'id',
name:'name',
'class':'className'
},
HTML:false,//if true, entities are escaped ( <, >, \t, space and \n )
indentChar:' ',//indentation unit
multiline:true //if true, items in a collection, are separated by a \n, else just a space.
};
return jsDump;
})();
// from Sizzle.js
function getText( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += getText( elem.childNodes );
}
}
return ret;
};
//from jquery.js
function inArray( elem, array ) {
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
}
/*
* Javascript Diff Algorithm
* By John Resig (http://ejohn.org/)
* Modified by Chu Alan "sprite"
*
* Released under the MIT license.
*
* More Info:
* http://ejohn.org/projects/javascript-diff-algorithm/
*
* Usage: QUnit.diff(expected, actual)
*
* QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over"
*/
QUnit.diff = (function() {
function diff(o, n) {
var ns = {};
var os = {};
for (var i = 0; i < n.length; i++) {
if (ns[n[i]] == null)
ns[n[i]] = {
rows: [],
o: null
};
ns[n[i]].rows.push(i);
}
for (var i = 0; i < o.length; i++) {
if (os[o[i]] == null)
os[o[i]] = {
rows: [],
n: null
};
os[o[i]].rows.push(i);
}
for (var i in ns) {
if ( !hasOwn.call( ns, i ) ) {
continue;
}
if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) {
n[ns[i].rows[0]] = {
text: n[ns[i].rows[0]],
row: os[i].rows[0]
};
o[os[i].rows[0]] = {
text: o[os[i].rows[0]],
row: ns[i].rows[0]
};
}
}
for (var i = 0; i < n.length - 1; i++) {
if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null &&
n[i + 1] == o[n[i].row + 1]) {
n[i + 1] = {
text: n[i + 1],
row: n[i].row + 1
};
o[n[i].row + 1] = {
text: o[n[i].row + 1],
row: i + 1
};
}
}
for (var i = n.length - 1; i > 0; i--) {
if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null &&
n[i - 1] == o[n[i].row - 1]) {
n[i - 1] = {
text: n[i - 1],
row: n[i].row - 1
};
o[n[i].row - 1] = {
text: o[n[i].row - 1],
row: i - 1
};
}
}
return {
o: o,
n: n
};
}
return function(o, n) {
o = o.replace(/\s+$/, '');
n = n.replace(/\s+$/, '');
var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/));
var str = "";
var oSpace = o.match(/\s+/g);
if (oSpace == null) {
oSpace = [" "];
}
else {
oSpace.push(" ");
}
var nSpace = n.match(/\s+/g);
if (nSpace == null) {
nSpace = [" "];
}
else {
nSpace.push(" ");
}
if (out.n.length == 0) {
for (var i = 0; i < out.o.length; i++) {
str += '<del>' + out.o[i] + oSpace[i] + "</del>";
}
}
else {
if (out.n[0].text == null) {
for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
str += '<del>' + out.o[n] + oSpace[n] + "</del>";
}
}
for (var i = 0; i < out.n.length; i++) {
if (out.n[i].text == null) {
str += '<ins>' + out.n[i] + nSpace[i] + "</ins>";
}
else {
var pre = "";
for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) {
pre += '<del>' + out.o[n] + oSpace[n] + "</del>";
}
str += " " + out.n[i].text + nSpace[i] + pre;
}
}
}
return str;
};
})();
})(this);
| crgwbr/flakeyjs | tests/qunit.js | JavaScript | isc | 41,188 |
import AddLearningToStoryDescription from '../../../../src/content_scripts/pivotal_tracker/use_cases/add_learning_to_story_description'
import WWLTWRepository from '../../../../src/content_scripts/repositories/wwltw_repository';
import StoryTitleProvider from '../../../../src/content_scripts/utilities/story_title_provider';
import ProjectIdProvider from '../../../../src/content_scripts/utilities/project_id_provider';
describe('AddLearningToStoryDescription', function () {
let wwltwRepositorySpy;
let foundStory;
let execute;
const projectId = 'some project id';
const storyTitle = 'some story title';
beforeEach(function () {
wwltwRepositorySpy = new WWLTWRepository();
foundStory = {id: '1234'};
spyOn(chrome.runtime, 'sendMessage');
spyOn(wwltwRepositorySpy, 'findByTitle').and.returnValue(Promise.resolve([foundStory]));
spyOn(wwltwRepositorySpy, 'update').and.returnValue(Promise.resolve());
spyOn(StoryTitleProvider, 'currentStoryTitle').and.returnValue(storyTitle);
spyOn(ProjectIdProvider, 'getProjectId').and.returnValue(projectId);
const useCase = new AddLearningToStoryDescription(wwltwRepositorySpy);
execute = useCase.execute;
});
describe('execute', function () {
describe('when called outside of AddLearningToStoryDescription instance', function () {
it('finds the story', function () {
execute('some tag, some other tag', 'some body');
expect(wwltwRepositorySpy.findByTitle).toHaveBeenCalledWith(
projectId,
storyTitle
);
});
it('sends analytics data', function () {
execute();
expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ eventType: 'submit' });
});
it('updates the found story', function (done) {
const body = 'some body';
const tags = 'some tag, some other tag';
execute(tags, body).then(function () {
expect(wwltwRepositorySpy.update).toHaveBeenCalledWith(
projectId, foundStory, tags, body
);
done();
});
});
});
});
}); | oliverswitzer/wwltw-for-pivotal-tracker | test/content_scripts/pivotal_tracker/use_cases/add_learning_to_story_description_spec.js | JavaScript | isc | 2,332 |
package gobular
import (
"testing"
)
func testFit(t *testing.T, s string, must string, len uint32, align Alignment) {
got := ansiEsc.ReplaceAllLiteralString(fitPad(len, align, s), "")
if got != must {
t.Errorf("Must:|%s| Got:|%s|\n", must, got)
}
}
// TODO: test multibyte and/or double-width utf8 characters
func TestFitPad(t *testing.T) {
testFit(t, "123456", "123456", 6, HAlignLeft)
testFit(t, "123456", "123456", 6, HAlignCenter)
testFit(t, "123456", "123456", 6, HAlignRight)
testFit(t, "123456", "123456 ", 10, HAlignLeft)
testFit(t, "123456", " 123456 ", 10, HAlignCenter)
testFit(t, "123456", " 123456", 10, HAlignRight)
testFit(t, "123456", "123456 ", 11, HAlignLeft)
testFit(t, "123456", " 123456 ", 11, HAlignCenter)
testFit(t, "123456", " 123456", 11, HAlignRight)
testFit(t, "123456", "12", 2, HAlignLeft)
testFit(t, "123456", "34", 2, HAlignCenter)
testFit(t, "123456", "56", 2, HAlignRight)
testFit(t, "123456", "123", 3, HAlignLeft)
testFit(t, "123456", "345", 3, HAlignCenter)
testFit(t, "123456", "456", 3, HAlignRight)
testFit(t, "123\033[38;5;226m456", "123456", 6, HAlignLeft)
testFit(t, "123\033[38;5;226m456", "123456", 6, HAlignCenter)
testFit(t, "123\033[38;5;226m456", "123456", 6, HAlignRight)
testFit(t, "123\033[38;5;226m456", "123456 ", 10, HAlignLeft)
testFit(t, "123\033[38;5;226m456", " 123456 ", 10, HAlignCenter)
testFit(t, "123\033[38;5;226m456", " 123456", 10, HAlignRight)
testFit(t, "123\033[38;5;226m456", "123456 ", 11, HAlignLeft)
testFit(t, "123\033[38;5;226m456", " 123456 ", 11, HAlignCenter)
testFit(t, "123\033[38;5;226m456", " 123456", 11, HAlignRight)
testFit(t, "123\033[38;5;226m456", "12", 2, HAlignLeft)
testFit(t, "123\033[38;5;226m456", "34", 2, HAlignCenter)
testFit(t, "123\033[38;5;226m456", "56", 2, HAlignRight)
testFit(t, "123\033[38;5;226m456", "123", 3, HAlignLeft)
testFit(t, "123\033[38;5;226m456", "345", 3, HAlignCenter)
testFit(t, "123\033[38;5;226m456", "456", 3, HAlignRight)
}
| schachmat/gobular | gobular_test.go | GO | isc | 2,027 |
# ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
| kaniini/ignore-together | ignoretogether.py | Python | isc | 3,250 |
"use strict";
var Template = function (options) {
this._pageTitle = '';
this._titleSeparator = options.title_separator;
this._siteTitle = options.site_title;
this._req = null;
this._res = null;
};
Template.prototype.bindMiddleware = function(req, res) {
this._req = req;
this._res = res;
};
Template.prototype.setPageTitle = function(pageTitle) {
this._pageTitle = pageTitle;
};
Template.prototype.setSiteTitle = function(siteTitle) {
this._siteTitle = siteTitle;
};
Template.prototype.setTitleSeparator = function(separator) {
this._titleSeparator = separator;
};
Template.prototype.getTitle = function() {
if (this._pageTitle !== '') {
return this._pageTitle + ' ' + this._titleSeparator + ' ' + this._siteTitle;
} else {
return this._siteTitle;
}
};
Template.prototype.getPageTitle = function() {
return this._pageTitle;
};
Template.prototype.getSiteTitle = function() {
return this._siteTitle;
};
Template.prototype.render = function(path, params) {
this._res.render('partials/' + path, params);
};
module.exports = Template; | mythos-framework/mythos-lib-template | Template.js | JavaScript | isc | 1,091 |
/* eslint-env mocha */
const mockBot = require('../mockBot')
const assert = require('assert')
const mockery = require('mockery')
const sinon = require('sinon')
const json = JSON.stringify({
state: 'normal',
nowTitle: 'Midnight News',
nowInfo: '20/03/2019',
nextStart: '2019-03-20T00:30:00Z',
nextTitle: 'Book of the Week'
})
describe('radio module', function () {
let sandbox
before(function () {
// mockery mocks the entire require()
mockery.enable()
mockery.registerMock('request-promise', {
get: () => Promise.resolve(json)
})
// sinon stubs individual functions
sandbox = sinon.sandbox.create()
mockBot.loadModule('radio')
})
it('should parse the API correctly', async function () {
sandbox.useFakeTimers({ now: 1553040900000 }) // 2019-03-20T00:15:00Z
const promise = await mockBot.runCommand('!r4')
assert.strictEqual(promise, 'Now: \u000300Midnight News\u000f \u000315(20/03/2019)\u000f followed by Book of the Week in 15 minutes (12:30 am)')
})
after(function (done) {
mockery.disable()
mockery.deregisterAll()
done()
})
})
| zuzakistan/civilservant | test/modules/radio.js | JavaScript | isc | 1,122 |
/*
* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdint.h>
#include <set>
#include <string>
#include <iostream>
#include <oriutil/debug.h>
#include <ori/localrepo.h>
using namespace std;
extern LocalRepo repository;
int
cmd_listobj(int argc, char * const argv[])
{
set<ObjectInfo> objects = repository.listObjects();
set<ObjectInfo>::iterator it;
for (it = objects.begin(); it != objects.end(); it++)
{
const char *type;
switch ((*it).type)
{
case ObjectInfo::Commit:
type = "Commit";
break;
case ObjectInfo::Tree:
type = "Tree";
break;
case ObjectInfo::Blob:
type = "Blob";
break;
case ObjectInfo::LargeBlob:
type = "LargeBlob";
break;
case ObjectInfo::Purged:
type = "Purged";
break;
default:
cout << "Unknown object type (id " << (*it).hash.hex() << ")!" << endl;
PANIC();
}
cout << (*it).hash.hex() << " # " << type << endl;
}
return 0;
}
| BBBSnowball/ori | oridbg/cmd_listobj.cc | C++ | isc | 1,918 |
package com.evanbyrne.vending_machine_kata.ui;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.SortedMap;
import org.jooq.lambda.tuple.Tuple2;
import com.evanbyrne.vending_machine_kata.coin.Cents;
import com.evanbyrne.vending_machine_kata.coin.Coin;
import com.evanbyrne.vending_machine_kata.coin.CoinCollection;
import com.evanbyrne.vending_machine_kata.coin.CoinFactory;
import com.evanbyrne.vending_machine_kata.inventory.IInventoryService;
import com.evanbyrne.vending_machine_kata.inventory.InventoryProduct;
/**
* Manages console input and output.
*/
public class Console {
/**
* Get change display for terminal output.
*
* @param Change.
* @return Formatted message.
*/
public String getChangeDisplay(final CoinCollection change) {
final ArrayList<String> display = new ArrayList<String>();
final LinkedHashMap<Coin, Integer> coinMap = new LinkedHashMap<Coin, Integer>();
display.add("THANK YOU");
for(final Coin coin : change.getList()) {
if(coinMap.containsKey(coin)) {
coinMap.put(coin, coinMap.get(coin) + 1);
} else {
coinMap.put(coin, 1);
}
}
if(!coinMap.isEmpty()) {
final ArrayList<String> displayReturn = new ArrayList<String>();
for(final Map.Entry<Coin, Integer> entry : coinMap.entrySet()) {
final String name = entry.getKey().name().toLowerCase();
final int count = entry.getValue();
displayReturn.add(String.format("%s (x%d)", name, count));
}
display.add("RETURN: " + String.join(", ", displayReturn));
}
return String.join("\n", display);
}
/**
* Get product listing display for terminal output.
*
* @param Sorted map of all inventory.
* @return Formatted message.
*/
public String getProductDisplay(final SortedMap<String, InventoryProduct> inventory) {
if(!inventory.isEmpty()) {
final ArrayList<String> display = new ArrayList<String>();
for(final Map.Entry<String, InventoryProduct> entry : inventory.entrySet()) {
final String centsString = Cents.toString(entry.getValue().getCents());
final String name = entry.getValue().getName();
final String key = entry.getKey();
display.add(String.format("%s\t%s\t%s", key, centsString, name));
}
return String.join("\n", display);
}
return "No items in vending machine.";
}
/**
* Prompt user for payment.
*
* Loops until payment >= selected product cost.
*
* @param Scanner.
* @param A product representing their selection.
* @return Payment.
*/
public CoinCollection promptForPayment(final Scanner scanner, final InventoryProduct selection) {
final CoinCollection paid = new CoinCollection();
Coin insert;
String input;
do {
System.out.println("PRICE: " + Cents.toString(selection.getCents()));
do {
System.out.print(String.format("INSERT COIN (%s): ", Cents.toString(paid.getTotal())));
input = scanner.nextLine();
insert = CoinFactory.getByName(input);
if(insert == null) {
System.out.println("Invalid coin. This machine accepts: quarter, dime, nickel.");
}
} while(insert == null);
paid.addCoin(insert);
} while(paid.getTotal() < selection.getCents());
return paid;
}
/**
* Prompt for product selection.
*
* Loops until a valid product has been selected.
*
* @param Scanner
* @param An implementation of IInventoryService.
* @return A tuple with the product key and product.
*/
public Tuple2<String, InventoryProduct> promptForSelection(final Scanner scanner, final IInventoryService inventoryService) {
InventoryProduct selection;
String input;
do {
System.out.print("SELECT: ");
input = scanner.nextLine();
selection = inventoryService.getProduct(input);
if( selection == null ) {
System.out.println("Invalid selection.");
}
} while(selection == null);
return new Tuple2<String, InventoryProduct>(input, selection);
}
}
| evantbyrne/vending-machine-kata | src/main/java/com/evanbyrne/vending_machine_kata/ui/Console.java | Java | isc | 4,553 |
import { Accessor, AnimationSampler, Document, Root, Transform, TransformContext } from '@gltf-transform/core';
import { createTransform, isTransformPending } from './utils';
const NAME = 'resample';
export interface ResampleOptions {tolerance?: number}
const RESAMPLE_DEFAULTS: Required<ResampleOptions> = {tolerance: 1e-4};
/**
* Resample {@link Animation}s, losslessly deduplicating keyframes to reduce file size. Duplicate
* keyframes are commonly present in animation 'baked' by the authoring software to apply IK
* constraints or other software-specific features. Based on THREE.KeyframeTrack.optimize().
*
* Example: (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
*/
export const resample = (_options: ResampleOptions = RESAMPLE_DEFAULTS): Transform => {
const options = {...RESAMPLE_DEFAULTS, ..._options} as Required<ResampleOptions>;
return createTransform(NAME, (doc: Document, context?: TransformContext): void => {
const accessorsVisited = new Set<Accessor>();
const accessorsCountPrev = doc.getRoot().listAccessors().length;
const logger = doc.getLogger();
let didSkipMorphTargets = false;
for (const animation of doc.getRoot().listAnimations()) {
// Skip morph targets, see https://github.com/donmccurdy/glTF-Transform/issues/290.
const morphTargetSamplers = new Set<AnimationSampler>();
for (const channel of animation.listChannels()) {
if (channel.getSampler() && channel.getTargetPath() === 'weights') {
morphTargetSamplers.add(channel.getSampler()!);
}
}
for (const sampler of animation.listSamplers()) {
if (morphTargetSamplers.has(sampler)) {
didSkipMorphTargets = true;
continue;
}
if (sampler.getInterpolation() === 'STEP'
|| sampler.getInterpolation() === 'LINEAR') {
accessorsVisited.add(sampler.getInput()!);
accessorsVisited.add(sampler.getOutput()!);
optimize(sampler, options);
}
}
}
for (const accessor of Array.from(accessorsVisited.values())) {
const used = accessor.listParents().some((p) => !(p instanceof Root));
if (!used) accessor.dispose();
}
if (doc.getRoot().listAccessors().length > accessorsCountPrev && !isTransformPending(context, NAME, 'dedup')) {
logger.warn(
`${NAME}: Resampling required copying accessors, some of which may be duplicates.`
+ ' Consider using "dedup" to consolidate any duplicates.'
);
}
if (didSkipMorphTargets) {
logger.warn(`${NAME}: Skipped optimizing morph target keyframes, not yet supported.`);
}
logger.debug(`${NAME}: Complete.`);
});
};
function optimize (sampler: AnimationSampler, options: ResampleOptions): void {
const input = sampler.getInput()!.clone();
const output = sampler.getOutput()!.clone();
const tolerance = options.tolerance as number;
const lastIndex = input.getCount() - 1;
const tmp: number[] = [];
let writeIndex = 1;
for (let i = 1; i < lastIndex; ++ i) {
const time = input.getScalar(i);
const timePrev = input.getScalar(i - 1);
const timeNext = input.getScalar(i + 1);
const timeMix = (time - timePrev) / (timeNext - timePrev);
let keep = false;
// Remove unnecessary adjacent keyframes.
if (time !== timeNext && (i !== 1 || time !== input.getScalar(0))) {
for (let j = 0; j < output.getElementSize(); j++) {
const value = output.getElement(i, tmp)[j];
const valuePrev = output.getElement(i - 1, tmp)[j];
const valueNext = output.getElement(i + 1, tmp)[j];
if (sampler.getInterpolation() === 'LINEAR') {
// Prune keyframes that are colinear with prev/next keyframes.
if (Math.abs(value - lerp(valuePrev, valueNext, timeMix)) > tolerance) {
keep = true;
break;
}
} else if (sampler.getInterpolation() === 'STEP') {
// Prune keyframes that are identical to prev/next keyframes.
if (value !== valuePrev || value !== valueNext) {
keep = true;
break;
}
}
}
}
// In-place compaction.
if (keep) {
if (i !== writeIndex) {
input.setScalar(writeIndex, input.getScalar(i));
output.setElement(writeIndex, output.getElement(i, tmp));
}
writeIndex++;
}
}
// Flush last keyframe (compaction looks ahead).
if (lastIndex > 0) {
input.setScalar(writeIndex, input.getScalar(lastIndex));
output.setElement(writeIndex, output.getElement(lastIndex, tmp));
writeIndex++;
}
// If the sampler was optimized, truncate and save the results. If not, clean up.
if (writeIndex !== input.getCount()) {
input.setArray(input.getArray()!.slice(0, writeIndex));
output.setArray(output.getArray()!.slice(0, writeIndex * output.getElementSize()));
sampler.setInput(input);
sampler.setOutput(output);
} else {
input.dispose();
output.dispose();
}
}
function lerp (v0: number, v1: number, t: number): number {
return v0 * (1 - t) + v1 * t;
}
| damienmortini/dlib | node_modules/@gltf-transform/functions/src/resample.ts | TypeScript | isc | 4,825 |
describe("Membrane Panel Operations with flat files:", function() {
"use strict";
var window;
beforeEach(async function() {
await getDocumentLoadPromise("base/gui/index.html");
window = testFrame.contentWindow;
window.LoadPanel.testMode = {fakeFiles: true};
let p1 = MessageEventPromise(window, "MembranePanel initialized");
let p2 = MessageEventPromise(
window, "MembranePanel cached configuration reset"
);
window.OuterGridManager.membranePanelRadio.click();
await Promise.all([p1, p2]);
});
function getErrorMessage() {
let output = window.OuterGridManager.currentErrorOutput;
if (!output.firstChild)
return null;
return output.firstChild.nodeValue;
}
it("starts with no graph names and two rows", function() {
// two delete buttons and one add button
{
let buttons = window.HandlerNames.grid.getElementsByTagName("button");
expect(buttons.length).toBe(3);
for (let i = 0; i < buttons.length; i++) {
expect(buttons[i].disabled).toBe(i < buttons.length - 1);
}
}
const [graphNames, graphSymbolLists] =
window.HandlerNames.serializableNames();
expect(Array.isArray(graphNames)).toBe(true);
expect(Array.isArray(graphSymbolLists)).toBe(true);
expect(graphNames.length).toBe(0);
expect(graphSymbolLists.length).toBe(0);
expect(getErrorMessage()).toBe(null);
});
it("supports the pass-through function for the membrane", function() {
const editor = window.MembranePanel.passThroughEditor;
{
expect(window.MembranePanel.passThroughCheckbox.checked).toBe(false);
expect(window.MembranePanel.primordialsCheckbox.checked).toBe(false);
expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(true);
expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(false);
}
{
window.MembranePanel.passThroughCheckbox.click();
expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true);
expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(false);
expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(true);
}
{
window.MembranePanel.primordialsCheckbox.click();
expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true);
expect(window.MembranePanel.primordialsCheckbox.checked).toBe(true);
expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(false);
expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(true);
const prelim = "(function() {\n const items = Membrane.Primordials.slice(0);\n\n";
const value = window.MembranePanel.getPassThrough(true);
expect(value.startsWith(prelim)).toBe(true);
}
{
window.MembranePanel.primordialsCheckbox.click();
expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true);
expect(window.MembranePanel.primordialsCheckbox.checked).toBe(false);
expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(false);
expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(true);
}
{
window.MembranePanel.passThroughCheckbox.click();
expect(window.MembranePanel.passThroughCheckbox.checked).toBe(false);
expect(window.MembranePanel.primordialsCheckbox.checked).toBe(false);
expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(true);
expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(false);
}
});
describe(
"The graph handler names API requires at least two distinct names (either symbols or strings)",
function() {
function validateControls() {
window.HandlerNames.update();
const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name");
const rv = [];
const length = inputs.length;
for (let i = 0; i < length; i++) {
rv.push(inputs[i].checkValidity());
expect(inputs[i].nextElementSibling.disabled).toBe(length == 2);
}
return rv;
}
it("initial state is disallowed for two inputs", function() {
const states = validateControls();
expect(states.length).toBe(2);
expect(states[0]).toBe(false);
expect(states[1]).toBe(false);
});
it("allows a name to be an unique string", function() {
const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name");
inputs[0].value = "foo";
inputs[1].value = "bar";
const states = validateControls();
expect(states.length).toBe(2);
expect(states[0]).toBe(true);
expect(states[1]).toBe(true);
});
it("clicking on the addRow button really does add a new row", function() {
window.HandlerNames.addRow();
const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name");
inputs[0].value = "foo";
inputs[1].value = "bar";
const states = validateControls();
expect(states.length).toBe(3);
expect(states[0]).toBe(true);
expect(states[1]).toBe(true);
expect(states[2]).toBe(false);
});
it("disallows non-unique strings", function() {
window.HandlerNames.addRow();
const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name");
inputs[0].value = "foo";
inputs[1].value = "bar";
inputs[2].value = "foo";
const states = validateControls();
expect(states.length).toBe(3);
expect(states[0]).toBe(true);
expect(states[1]).toBe(true);
expect(states[2]).toBe(false);
});
it("allows removing a row", function() {
window.HandlerNames.addRow();
const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name");
inputs[0].value = "foo";
inputs[1].value = "bar";
inputs[2].value = "baz";
inputs[0].nextElementSibling.click();
expect(inputs.length).toBe(2);
expect(inputs[0].value).toBe("bar");
expect(inputs[1].value).toBe("baz");
const states = validateControls();
expect(states.length).toBe(2);
expect(states[0]).toBe(true);
expect(states[1]).toBe(true);
});
it("allows a symbol to share a name with a string", function() {
window.HandlerNames.addRow();
const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name");
inputs[0].value = "foo";
inputs[1].value = "bar";
inputs[2].value = "foo";
inputs[2].previousElementSibling.firstElementChild.checked = true; // symbol
const states = validateControls();
expect(states.length).toBe(3);
expect(states[0]).toBe(true);
expect(states[1]).toBe(true);
expect(states[2]).toBe(true);
});
it("allows two symbols to share a name", function() {
window.HandlerNames.addRow();
const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name");
inputs[0].value = "foo";
inputs[1].value = "bar";
inputs[2].value = "foo";
inputs[0].previousElementSibling.firstElementChild.checked = true; // symbol
inputs[2].previousElementSibling.firstElementChild.checked = true; // symbol
const states = validateControls();
expect(states.length).toBe(3);
expect(states[0]).toBe(true);
expect(states[1]).toBe(true);
expect(states[2]).toBe(true);
});
}
);
});
it("Membrane Panel supports pass-through function", async function() {
await getDocumentLoadPromise("base/gui/index.html");
const window = testFrame.contentWindow;
window.LoadPanel.testMode = {
fakeFiles: true,
configSource: `{
"configurationSetup": {
"useZip": false,
"commonFiles": [],
"formatVersion": 1,
"lastUpdated": "Mon, 19 Feb 2018 20:56:56 GMT"
},
"membrane": {
"passThroughSource": " // hello world",
"passThroughEnabled": true,
"primordialsPass": true
},
"graphs": [
{
"name": "wet",
"isSymbol": false,
"passThroughSource": "",
"passThroughEnabled": false,
"primordialsPass": false,
"distortions": []
},
{
"name": "dry",
"isSymbol": false,
"passThroughSource": "",
"passThroughEnabled": false,
"primordialsPass": false,
"distortions": []
}
]
}`
};
let p1 = MessageEventPromise(window, "MembranePanel initialized");
let p2 = MessageEventPromise(
window,
"MembranePanel cached configuration reset",
"MembranePanel exception thrown in reset"
);
window.OuterGridManager.membranePanelRadio.click();
await Promise.all([p1, p2]);
expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true);
expect(window.MembranePanel.primordialsCheckbox.checked).toBe(true);
expect(window.MembranePanel.getPassThrough()).toContain("// hello world");
});
| ajvincent/es7-membrane | docs/gui/tests/membranePanel.js | JavaScript | isc | 9,110 |
.POSIX:
all: tests
tests:
CFLAGS='' SCCPREFIX=../../rootdir/ PATH=../../rootdir/bin:$$PATH ./chktest.sh scc-tests.lst
clean:
rm -f *.as *.o *.ir *.qbe *core test.log
distclean: clean
dep:
| k0gaMSX/scc | tests/execute/Makefile | Makefile | isc | 194 |
/*
TEXT DECORATION
*/
.strike { text-decoration: line-through; }
.underline { text-decoration: underline; }
.no-underline { text-decoration: none; }
@media screen and (min-width: 30em) {
.strike-ns { text-decoration: line-through; }
.underline-ns { text-decoration: underline; }
.no-underline-ns { text-decoration: none; }
}
@media screen and (min-width: 30em) and (max-width: 60em) {
.strike-m { text-decoration: line-through; }
.underline-m { text-decoration: underline; }
.no-underline-m { text-decoration: none; }
}
@media screen and (min-width: 60em) {
.strike-l { text-decoration: line-through; }
.underline-l { text-decoration: underline; }
.no-underline-l { text-decoration: none; }
}
| tachyons-css/tachyons-text-decoration | css/tachyons-text-decoration.css | CSS | isc | 708 |
tressa.title('HyperHTML');
tressa.assert(typeof hyperHTML === 'function', 'hyperHTML is a function');
try { tressa.log(''); } catch(e) { tressa.log = console.log.bind(console); }
tressa.async(function (done) {
tressa.log('## injecting text and attributes');
var i = 0;
var div = document.body.appendChild(document.createElement('div'));
var render = hyperHTML.bind(div);
function update(i) {
return render`
<p data-counter="${i}">
Time: ${
// IE Edge mobile did something funny here
// as template string returned xxx.xxxx
// but as innerHTML returned xxx.xx
(Math.random() * new Date).toFixed(2)
}
</p>
`;
}
function compare(html) {
return /^\s*<p data-counter="\d">\s*Time: \d+\.\d+<[^>]+?>\s*<\/p>\s*$/i.test(html);
}
var html = update(i++).innerHTML;
var p = div.querySelector('p');
var attr = p.attributes[0];
tressa.assert(compare(html), 'correct HTML');
tressa.assert(html === div.innerHTML, 'correctly returned');
setTimeout(function () {
tressa.log('## updating same nodes');
var html = update(i++).innerHTML;
tressa.assert(compare(html), 'correct HTML update');
tressa.assert(html === div.innerHTML, 'update applied');
tressa.assert(p === div.querySelector('p'), 'no node was changed');
tressa.assert(attr === p.attributes[0], 'no attribute was changed');
done();
});
})
.then(function () {
return tressa.async(function (done) {
tressa.log('## perf: same virtual text twice');
var div = document.body.appendChild(document.createElement('div'));
var render = hyperHTML.bind(div);
var html = (update('hello').innerHTML, update('hello').innerHTML);
function update(text) {
return render`<p>${text} world</p>`;
}
tressa.assert(
update('hello').innerHTML ===
update('hello').innerHTML,
'same text'
);
done(div);
});
})
.then(function () {
return tressa.async(function (done) {
tressa.log('## injecting HTML');
var div = document.body.appendChild(document.createElement('div'));
var render = hyperHTML.bind(div);
var html = update('hello').innerHTML;
function update(text) {
return render`<p>${['<strong>' + text + '</strong>']}</p>`;
}
function compare(html) {
return /^<p><strong>\w+<\/strong><!--.+?--><\/p>$/i.test(html);
}
tressa.assert(compare(html), 'HTML injected');
tressa.assert(html === div.innerHTML, 'HTML returned');
done(div);
});
})
.then(function (div) {
return tressa.async(function (done) {
tressa.log('## function attributes');
var render = hyperHTML.bind(div);
var times = 0;
update(function (e) {
console.log(e.type);
if (++times > 1) {
return tressa.assert(false, 'events are broken');
}
if (e) {
e.preventDefault();
e.stopPropagation();
}
tressa.assert(true, 'onclick invoked');
tressa.assert(!a.hasAttribute('onclick'), 'no attribute');
update(null);
e = document.createEvent('Event');
e.initEvent('click', false, false);
a.dispatchEvent(e);
done(div);
});
function update(click) {
// also test case-insensitive builtin events
return render`<a href="#" onClick="${click}">click</a>`;
}
var a = div.querySelector('a');
var e = document.createEvent('Event');
e.initEvent('click', false, false);
a.dispatchEvent(e);
});
})
.then(function (div) {
return tressa.async(function (done) {
tressa.log('## changing template');
var render = hyperHTML.bind(div);
var html = update('hello').innerHTML;
function update(text) {
return render`<p>${{any: ['<em>' + text + '</em>']}}</p>`;
}
function compare(html) {
return /^<p><em>\w+<\/em><!--.+?--><\/p>$/i.test(html);
}
tressa.assert(compare(html), 'new HTML injected');
tressa.assert(html === div.innerHTML, 'new HTML returned');
done(div);
});
})
.then(function () {
return tressa.async(function (done) {
tressa.log('## custom events');
var render = hyperHTML.bind(document.createElement('p'));
var e = document.createEvent('Event');
e.initEvent('Custom-EVENT', true, true);
(render`<span onCustom-EVENT="${function (e) {
tressa.assert(e.type === 'Custom-EVENT', 'event triggered');
done();
}}">how cool</span>`
).firstElementChild.dispatchEvent(e);
});
})
.then(function () {
tressa.log('## multi wire removal');
var render = hyperHTML.wire();
var update = function () {
return render`
<p>1</p>
<p>2</p>
`;
};
update().remove();
update = function () {
return render`
<p>1</p>
<p>2</p>
<p>3</p>
`;
};
update().remove();
tressa.assert(true, 'OK');
})
.then(function () {
tressa.log('## the attribute id');
var div = document.createElement('div');
hyperHTML.bind(div)`<p id=${'id'} class='class'>OK</p>`;
tressa.assert(div.firstChild.id === 'id', 'the id is preserved');
tressa.assert(div.firstChild.className === 'class', 'the class is preserved');
})
.then(function () {
return tressa.async(function (done) {
tressa.log('## hyperHTML.wire()');
var render = hyperHTML.wire();
var update = function () {
return render`
<p>1</p>
`;
};
var node = update();
tressa.assert(node.nodeName.toLowerCase() === 'p', 'correct node');
var same = update();
tressa.assert(node === same, 'same node returned');
render = hyperHTML.wire(null);
update = function () {
return render`
0
<p>1</p>
`;
};
node = update().childNodes;
tressa.assert(Array.isArray(node), 'list of nodes');
same = update().childNodes;
tressa.assert(
node.length === same.length &&
node[0] &&
node.every(function (n, i) { return same[i] === n; }),
'same list returned'
);
var div = document.createElement('div');
render = hyperHTML.bind(div);
render`${node}`;
same = div.childNodes;
tressa.assert(
node[0] &&
node.every(function (n, i) { return same[i] === n; }),
'same list applied'
);
function returnSame() {
return render`a`;
}
render = hyperHTML.wire();
tressa.assert(
returnSame() === returnSame(),
'template sensible wire'
);
done();
});
})
.then(function () {
return tressa.async(function (done) {
tressa.log('## hyperHTML.wire(object)');
var point = {x: 1, y: 2};
function update() {
return hyperHTML.wire(point)`
<span style="${`
position: absolute;
left: ${point.x}px;
top: ${point.y}px;
`}">O</span>`;
}
try { update(); } catch(e) { console.error(e) }
tressa.assert(update() === update(), 'same output');
tressa.assert(hyperHTML.wire(point) === hyperHTML.wire(point), 'same wire');
done();
});
})
.then(function () {
if (typeof MutationObserver === 'undefined') return;
return tressa.async(function (done) {
tressa.log('## preserve first child where first child is the same as incoming');
var div = document.body.appendChild(document.createElement('div'));
var render = hyperHTML.bind(div);
var observer = new MutationObserver(function (mutations) {
for (var i = 0, len = mutations.length; i < len; i++) {
trackMutations(mutations[i].addedNodes, 'added');
trackMutations(mutations[i].removedNodes, 'removed');
}
});
observer.observe(div, {
childList: true,
subtree: true,
});
var counters = [];
function trackMutations (nodes, countKey) {
for (var i = 0, len = nodes.length, counter, key; i < len; i++) {
if (nodes[i] && nodes[i].getAttribute && nodes[i].getAttribute('data-test')) {
key = nodes[i].getAttribute('data-test');
counter = counters[key] || (counters[key] = { added: 0, removed: 0 });
counter[countKey]++;
}
if (nodes[i].childNodes.length > 0) {
trackMutations(nodes[i].childNodes, countKey);
}
}
}
var listItems = [];
function update(items) {
render`
<section>
<ul>${
items.map(function (item, i) {
return hyperHTML.wire((listItems[i] || (listItems[i] = {})))`
<li data-test="${i}">${() => item.text}</li>
`;
})
}</ul>
</section>`;
}
update([]);
setTimeout(function () {
update([{ text: 'test1' }]);
}, 10);
setTimeout(function () {
update([{ text: 'test1' }, { text: 'test2' }]);
}, 20);
setTimeout(function () {
update([{ text: 'test1' }]);
}, 30);
setTimeout(function () {
if (counters.length) {
tressa.assert(counters[0].added === 1, 'first item added only once');
tressa.assert(counters[0].removed === 0, 'first item never removed');
}
done();
}, 100);
});
})
.then(function () {
tressa.log('## rendering one node');
var div = document.createElement('div');
var br = document.createElement('br');
var hr = document.createElement('hr');
hyperHTML.bind(div)`<div>${br}</div>`;
tressa.assert(div.firstChild.firstChild === br, 'one child is added');
hyperHTML.bind(div)`<div>${hr}</div>`;
tressa.assert(div.firstChild.firstChild === hr, 'one child is changed');
hyperHTML.bind(div)`<div>${[hr, br]}</div>`;
tressa.assert(
div.firstChild.childNodes[0] === hr &&
div.firstChild.childNodes[1] === br,
'more children are added'
);
hyperHTML.bind(div)`<div>${[br, hr]}</div>`;
tressa.assert(
div.firstChild.childNodes[0] === br &&
div.firstChild.childNodes[1] === hr,
'children can be swapped'
);
hyperHTML.bind(div)`<div>${br}</div>`;
tressa.assert(div.firstChild.firstChild === br, 'one child is kept');
hyperHTML.bind(div)`<div>${[]}</div>`;
tressa.assert(/<div><!--.+?--><\/div>/.test(div.innerHTML), 'dropped all children');
})
.then(function () {
tressa.log('## wire by id');
let ref = {};
let wires = {
a: function () {
return hyperHTML.wire(ref, ':a')`<a></a>`;
},
p: function () {
return hyperHTML.wire(ref, ':p')`<p></p>`;
}
};
tressa.assert(wires.a().nodeName.toLowerCase() === 'a', '<a> is correct');
tressa.assert(wires.p().nodeName.toLowerCase() === 'p', '<p> is correct');
tressa.assert(wires.a() === wires.a(), 'same wire for <a>');
tressa.assert(wires.p() === wires.p(), 'same wire for <p>');
})
.then(function () {
return tressa.async(function (done) {
tressa.log('## Promises instead of nodes');
let wrap = document.createElement('div');
let render = hyperHTML.bind(wrap);
render`<p>${
new Promise(function (r) { setTimeout(r, 50, 'any'); })
}</p>${
new Promise(function (r) { setTimeout(r, 10, 'virtual'); })
}<hr><div>${[
new Promise(function (r) { setTimeout(r, 20, 1); }),
new Promise(function (r) { setTimeout(r, 10, 2); }),
]}</div>${[
new Promise(function (r) { setTimeout(r, 20, 3); }),
new Promise(function (r) { setTimeout(r, 10, 4); }),
]}`;
let result = wrap.innerHTML;
setTimeout(function () {
tressa.assert(result !== wrap.innerHTML, 'promises fullfilled');
tressa.assert(
/^<p>any<!--.+?--><\/p>virtual<!--.+?--><hr(?: ?\/)?><div>12<!--.+?--><\/div>34<!--.+?-->$/.test(wrap.innerHTML),
'both any and virtual content correct'
);
done();
}, 100);
});
})
.then(function () {
hyperHTML.engine = hyperHTML.engine;
tressa.log('## for code coverage sake');
let wrap = document.createElement('div');
let text = [document.createTextNode('a'), document.createTextNode('b'), document.createTextNode('c')];
let testingMajinBuu = hyperHTML.bind(wrap);
testingMajinBuu`${[text]}`;
tressa.assert(wrap.textContent === 'abc');
text[0] = document.createTextNode('c');
text[2] = document.createTextNode('a');
testingMajinBuu`${[text]}`;
tressa.assert(wrap.textContent === 'cba');
let result = hyperHTML.wire()`<!--not hyperHTML-->`;
tressa.assert(result.nodeType === 8, 'it is a comment');
tressa.assert(result.textContent === 'not hyperHTML', 'correct content');
hyperHTML.bind(wrap)`<br/>${'node before'}`;
tressa.assert(/^<br(?: ?\/)?>node before<!--.+?-->$/i.test(wrap.innerHTML), 'node before');
hyperHTML.bind(wrap)`${'node after'}<br/>`;
tressa.assert(/^node after<!--.+?--><br(?: ?\/)?>$/i.test(wrap.innerHTML), 'node after');
hyperHTML.bind(wrap)`<style> ${'hyper-html{}'} </style>`;
tressa.assert('<style>hyper-html{}</style>' === wrap.innerHTML.toLowerCase(), 'node style');
var empty = function (value) {
return hyperHTML.bind(wrap)`${value}`;
};
empty(document.createTextNode('a'));
empty(document.createDocumentFragment());
empty(document.createDocumentFragment());
let fragment = document.createDocumentFragment();
fragment.appendChild(document.createTextNode('b'));
empty(fragment);
empty(123);
tressa.assert(wrap.textContent === '123', 'text as number');
empty(true);
tressa.assert(wrap.textContent === 'true', 'text as boolean');
empty([1]);
tressa.assert(wrap.textContent === '1', 'text as one entry array');
empty(['1', '2']);
tressa.assert(wrap.textContent === '12', 'text as multi entry array of strings');
let arr = [document.createTextNode('a'), document.createTextNode('b')];
empty([arr]);
tressa.assert(wrap.textContent === 'ab', 'text as multi entry array of nodes');
empty([arr]);
tressa.assert(wrap.textContent === 'ab', 'same array of nodes');
empty(wrap.childNodes);
tressa.assert(wrap.textContent === 'ab', 'childNodes as list');
hyperHTML.bind(wrap)`a=${{length:1, '0':'b'}}`;
tressa.assert(wrap.textContent === 'a=b', 'childNodes as virtual list');
empty = function () {
return hyperHTML.bind(wrap)`[${'text'}]`;
};
empty();
empty();
let onclick = (e) => {};
let handler = {handleEvent: onclick};
empty = function () {
return hyperHTML.bind(wrap)`<p onclick="${onclick}" onmouseover="${handler}" align="${'left'}"></p>`;
};
empty();
handler = {handleEvent: onclick};
empty();
empty();
empty = function (value) {
return hyperHTML.bind(wrap)`<br/>${value}<br/>`;
};
empty(arr[0]);
empty(arr);
empty(arr);
empty([]);
empty(['1', '2']);
empty(document.createDocumentFragment());
tressa.assert(true, 'passed various virtual content scenarios');
let svgContainer = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
if (!('ownerSVGElement' in svgContainer)) svgContainer.ownerSVGElement = null;
hyperHTML.bind(svgContainer)`<rect x="1" y="2" />`;
result = hyperHTML.wire(null, 'svg')`<svg></svg>`;
tressa.assert(result.nodeName.toLowerCase() === 'svg', 'svg content is allowed too');
result = hyperHTML.wire()``;
tressa.assert(!result.innerHTML, 'empty content');
let tr = hyperHTML.wire()`<tr><td>ok</td></tr>`;
tressa.assert(true, 'even TR as template');
hyperHTML.bind(wrap)`${' 1 '}`;
tressa.assert(wrap.textContent === ' 1 ', 'text in between');
hyperHTML.bind(wrap)` <br/>${1}<br/> `;
tressa.assert(/^\s*<br(?: ?\/)?>1<!--.+?--><br(?: ?\/)?>\s*$/.test(wrap.innerHTML), 'virtual content in between');
let last = hyperHTML.wire();
empty = function (style) {
return last`<textarea style=${style}>${() => 'same text'}</textarea>`;
};
empty('border:0');
empty({border: 0});
empty({vh: 100});
empty({vh: 10, vw: 1});
empty(null);
empty('');
const sameStyle = {ord: 0};
empty(sameStyle);
empty(sameStyle);
empty = function () {
return last`<p data=${last}></p>`;
};
empty();
empty();
let p = last`<p data=${last}>${0}</p>`;
const UID = p.childNodes[1].data;
last`<textarea new>${`<!--${UID}-->`}</textarea>`;
hyperHTML.wire()`<p><!--ok--></p>`;
})
.then(function () {
tressa.log('## <script> shenanigans');
return tressa.async(function (done) {
var div = document.createElement('div');
document.body.appendChild(div);
hyperHTML.bind(div)`<script
src="../index.js?_=asd"
onreadystatechange="${event => {
if (/loaded|complete/.test(event.readyState))
setTimeout(() => {
tressa.assert(true, 'executed');
done();
});
}}"
onload="${() => {
tressa.assert(true, 'executed');
done();
}}"
onerror="${() => {
tressa.assert(true, 'executed');
done();
}}"
></script>`;
// in nodejs case
if (!('onload' in document.defaultView)) {
var evt = document.createEvent('Event');
evt.initEvent('load', false, false);
div.firstChild.dispatchEvent(evt);
}
});
})
.then(function () {
tressa.log('## SVG and style');
var render = hyperHTML.wire(null, 'svg');
Object.prototype.ownerSVGElement = null;
function rect(style) {
return render`<rect style=${style} />`;
}
var node = rect({});
delete Object.prototype.ownerSVGElement;
rect({width: 100});
console.log(node.getAttribute('style'));
tressa.assert(/width:\s*100px;/.test(node.getAttribute('style')), 'correct style object');
rect('height:10px;');
tressa.assert(/height:\s*10px;/.test(node.getAttribute('style')), 'correct style string');
rect(null);
tressa.assert(/^(?:|null)$/.test(node.getAttribute('style')), 'correct style reset');
})
.then(function () {
var a = document.createTextNode('a');
var b = document.createTextNode('b');
var c = document.createTextNode('c');
var d = document.createTextNode('d');
var e = document.createTextNode('e');
var f = document.createTextNode('f');
var g = document.createTextNode('g');
var h = document.createTextNode('h');
var i = document.createTextNode('i');
var div = document.createElement('div');
var render = hyperHTML.bind(div);
render`${[]}`;
tressa.assert(div.textContent === '', 'div is empty');
render`${[c, d, e, f]}`;
// all tests know that a comment node is inside the div
tressa.assert(div.textContent === 'cdef' && div.childNodes.length === 5, 'div has 4 nodes');
render`${[c, d, e, f]}`;
tressa.assert(div.textContent === 'cdef', 'div has same 4 nodes');
render`${[a, b, c, d, e, f]}`;
tressa.assert(div.textContent === 'abcdef' && div.childNodes.length === 7, 'div has same 4 nodes + 2 prepends');
render`${[a, b, c, d, e, f, g, h, i]}`;
tressa.assert(div.textContent === 'abcdefghi' && div.childNodes.length === 10, 'div has 6 nodes + 3 appends');
render`${[b, c, d, e, f, g, h, i]}`;
tressa.assert(div.textContent === 'bcdefghi' && div.childNodes.length === 9, 'div has dropped first node');
render`${[b, c, d, e, f, g, h]}`;
tressa.assert(div.textContent === 'bcdefgh' && div.childNodes.length === 8, 'div has dropped last node');
render`${[b, c, d, f, e, g, h]}`;
tressa.assert(div.textContent === 'bcdfegh', 'div has changed 2 nodes');
render`${[b, d, c, f, g, e, h]}`;
tressa.assert(div.textContent === 'bdcfgeh', 'div has changed 4 nodes');
render`${[b, d, c, g, e, h]}`;
tressa.assert(div.textContent === 'bdcgeh' && div.childNodes.length === 7, 'div has removed central node');
})
.then(function () {
tressa.log('## no WebKit backfire');
var div = document.createElement('div');
function update(value, attr) {
return hyperHTML.bind(div)`
<input value="${value}" shaka="${attr}">`;
}
var input = update('', '').firstElementChild;
input.value = '456';
input.setAttribute('shaka', 'laka');
update('123', 'laka');
tressa.assert(input.value === '123', 'correct input');
tressa.assert(input.value === '123', 'correct attribute');
update('', '');
input.value = '123';
input.attributes.shaka.value = 'laka';
update('123', 'laka');
tressa.assert(input.value === '123', 'input.value was not reassigned');
})
.then(function () {
tressa.log('## wired arrays are rendered properly');
var div = document.createElement('div');
var employees = [
{first: 'Bob', last: 'Li'},
{first: 'Ayesha', last: 'Johnson'}
];
var getEmployee = employee => hyperHTML.wire(employee)`
<div>First name: ${employee.first}</div>
<p></p>`;
hyperHTML.bind(div)`${employees.map(getEmployee)}`;
tressa.assert(div.childElementCount === 4, 'correct elements as setAny');
hyperHTML.bind(div)`
<p></p>${employees.map(getEmployee)}`;
tressa.assert(div.childElementCount === 5, 'correct elements as setVirtual');
hyperHTML.bind(div)`
<p></p>${[]}`;
tressa.assert(div.childElementCount === 1, 'only one element left');
})
.then(function () {return tressa.async(function (done) {
function textarea(value) {
return hyperHTML.bind(div)`<textarea>${value}</textarea>`;
}
tressa.log('## textarea text');
var div = document.createElement('div');
textarea(1);
var ta = div.firstElementChild;
tressa.assert(ta.textContent === '1', 'primitives are fine');
textarea(null);
tressa.assert(ta.textContent === '', 'null/undefined is fine');
var p = Promise.resolve('OK');
textarea(p);
p.then(function () {
console.log(div.innerHTML);
tressa.assert(ta.textContent === 'OK', 'promises are fine');
textarea({text: 'text'});
tressa.assert(ta.textContent === 'text', 'text is fine');
textarea({html: 'html'});
tressa.assert(ta.textContent === 'html', 'html is fine');
textarea({any: 'any'});
tressa.assert(ta.textContent === 'any', 'any is fine');
textarea(['ar', 'ray']);
tressa.assert(ta.textContent === 'array', 'array is fine');
textarea({placeholder: 'placeholder'});
tressa.assert(ta.textContent === 'placeholder', 'placeholder is fine');
textarea({unknown: 'unknown'});
tressa.assert(ta.textContent === '', 'intents are fine');
done();
});
})})
.then(function () {
tressa.log('## attributes with weird chars');
var div = document.createElement('div');
hyperHTML.bind(div)`<p _foo=${'bar'}></p>`;
tressa.assert(div.firstChild.getAttribute('_foo') === 'bar', 'OK');
})
.then(function () {
tressa.log('## attributes without quotes');
var div = document.createElement('div');
hyperHTML.bind(div)`<p test=${'a"b'}></p>`;
tressa.assert(div.firstChild.getAttribute('test') === 'a"b', 'OK');
})
.then(function () {
tressa.log('## any content extras');
var div = document.createElement('div');
var html = hyperHTML.bind(div);
setContent(undefined);
tressa.assert(/<p><!--.+?--><\/p>/.test(div.innerHTML), 'expected layout');
setContent({text: '<img/>'});
tressa.assert(/<p><img(?: ?\/)?><!--.+?--><\/p>/.test(div.innerHTML), 'expected text');
function setContent(which) {
return html`<p>${which}</p>`;
}
})
.then(function () {
tressa.log('## any different content extras');
var div = document.createElement('div');
hyperHTML.bind(div)`<p>${undefined}</p>`;
tressa.assert(/<p><!--.+?--><\/p>/.test(div.innerHTML), 'expected layout');
hyperHTML.bind(div)`<p>${{text: '<img/>'}}</p>`;
tressa.assert(/<p><img(?: ?\/)?><!--.+?--><\/p>/.test(div.innerHTML), 'expected text');
})
.then(function () {
tressa.log('## virtual content extras');
var div = document.createElement('div');
hyperHTML.bind(div)`a ${null}`;
tressa.assert(/a <[^>]+?>/.test(div.innerHTML), 'expected layout');
hyperHTML.bind(div)`a ${{text: '<img/>'}}`;
tressa.assert(/a <img(?: ?\/)?><[^>]+?>/.test(div.innerHTML), 'expected text');
hyperHTML.bind(div)`a ${{any: 123}}`;
tressa.assert(/a 123<[^>]+?>/.test(div.innerHTML), 'expected any');
hyperHTML.bind(div)`a ${{html: '<b>ok</b>'}}`;
tressa.assert(/a <b>ok<\/b><[^>]+?>/.test(div.innerHTML), 'expected html');
hyperHTML.bind(div)`a ${{}}`;
tressa.assert(/a <[^>]+?>/.test(div.innerHTML), 'expected nothing');
})
.then(function () {
tressa.log('## defined transformer');
hyperHTML.define('eUC', encodeURIComponent);
var div = document.createElement('div');
hyperHTML.bind(div)`a=${{eUC: 'b c'}}`;
tressa.assert(/a=b%20c<[^>]+?>/.test(div.innerHTML), 'expected virtual layout');
hyperHTML.bind(div)`<p>${{eUC: 'b c'}}</p>`;
tressa.assert(/<p>b%20c<!--.+?--><\/p>/.test(div.innerHTML), 'expected layout');
// TODO: for coverage sake
// defined transformer ... so what?
hyperHTML.define('eUC', encodeURIComponent);
// non existent one ... so what?
hyperHTML.bind(div)`a=${{nOPE: 'b c'}}`;
})
.then(function () {
tressa.log('## attributes with null values');
var div = document.createElement('div');
var anyAttr = function (value) {
hyperHTML.bind(div)`<p any-attr=${value}>any content</p>`;
};
anyAttr('1');
tressa.assert(
div.firstChild.hasAttribute('any-attr') &&
div.firstChild.getAttribute('any-attr') === '1',
'regular attribute'
);
anyAttr(null);
tressa.assert(
!div.firstChild.hasAttribute('any-attr') &&
div.firstChild.getAttribute('any-attr') == null,
'can be removed'
);
anyAttr(undefined);
tressa.assert(
!div.firstChild.hasAttribute('any-attr') &&
div.firstChild.getAttribute('any-attr') == null,
'multiple times'
);
anyAttr('2');
tressa.assert(
div.firstChild.hasAttribute('any-attr') &&
div.firstChild.getAttribute('any-attr') === '2',
'but can be also reassigned'
);
anyAttr('3');
tressa.assert(
div.firstChild.hasAttribute('any-attr') &&
div.firstChild.getAttribute('any-attr') === '3',
'many other times'
);
var inputName = function (value) {
hyperHTML.bind(div)`<input name=${value}>`;
};
inputName('test');
tressa.assert(
div.firstChild.hasAttribute('name') &&
div.firstChild.name === 'test',
'special attributes are set too'
);
inputName(null);
tressa.assert(
!div.firstChild.hasAttribute('name') &&
!div.firstChild.name,
'but can also be removed'
);
inputName(undefined);
tressa.assert(
!div.firstChild.hasAttribute('name') &&
!div.firstChild.name,
'with either null or undefined'
);
inputName('back');
tressa.assert(
div.firstChild.hasAttribute('name') &&
div.firstChild.name === 'back',
'and can be put back'
);
})
.then(function () {return tressa.async(function (done) {
tressa.log('## placeholder');
var div = document.createElement('div');
var vdiv = document.createElement('div');
hyperHTML.bind(div)`<p>${{eUC: 'b c', placeholder: 'z'}}</p>`;
hyperHTML.bind(vdiv)`a=${{eUC: 'b c', placeholder: 'z'}}`;
tressa.assert(/<p>z<!--.+?--><\/p>/.test(div.innerHTML), 'expected inner placeholder layout');
tressa.assert(/a=z<[^>]+?>/.test(vdiv.innerHTML), 'expected virtual placeholder layout');
setTimeout(function () {
tressa.assert(/<p>b%20c<!--.+?--><\/p>/.test(div.innerHTML), 'expected inner resolved layout');
tressa.assert(/a=b%20c<[^>]+?>/.test(vdiv.innerHTML), 'expected virtual resolved layout');
hyperHTML.bind(div)`<p>${{text: 1, placeholder: '9'}}</p>`;
setTimeout(function () {
tressa.assert(/<p>1<!--.+?--><\/p>/.test(div.innerHTML), 'placeholder with text');
hyperHTML.bind(div)`<p>${{any: [1, 2], placeholder: '9'}}</p>`;
setTimeout(function () {
tressa.assert(/<p>12<!--.+?--><\/p>/.test(div.innerHTML), 'placeholder with any');
hyperHTML.bind(div)`<p>${{html: '<b>3</b>', placeholder: '9'}}</p>`;
setTimeout(function () {
tressa.assert(/<p><b>3<\/b><!--.+?--><\/p>/.test(div.innerHTML), 'placeholder with html');
done();
}, 10);
}, 10);
}, 10);
}, 10);
});})
.then(function () {
tressa.log('## hyper(...)');
var hyper = hyperHTML.hyper;
tressa.assert(typeof hyper() === 'function', 'empty hyper() is a wire tag');
tressa.assert((hyper`abc`).textContent === 'abc', 'hyper`abc`');
tressa.assert((hyper`<p>a${2}c</p>`).textContent === 'a2c', 'hyper`<p>a${2}c</p>`');
tressa.assert((hyper(document.createElement('div'))`abc`).textContent === 'abc', 'hyper(div)`abc`');
tressa.assert((hyper(document.createElement('div'))`a${'b'}c`).textContent === 'abc', 'hyper(div)`a${"b"}c`');
// WFT jsdom ?!
delete Object.prototype.nodeType;
tressa.assert((hyper({})`abc`).textContent === 'abc', 'hyper({})`abc`');
tressa.assert((hyper({})`<p>a${'b'}c</p>`).textContent === 'abc', 'hyper({})`<p>a${\'b\'}c</p>`');
tressa.assert((hyper({}, ':id')`abc`).textContent === 'abc', 'hyper({}, \':id\')`abc`');
tressa.assert((hyper({}, ':id')`<p>a${'b'}c</p>`).textContent === 'abc', 'hyper({}, \':id\')`<p>a${\'b\'}c</p>`');
tressa.assert((hyper('svg')`<rect />`), 'hyper("svg")`<rect />`');
})
.then(function () {
tressa.log('## data=${anyContent}');
var obj = {rand: Math.random()};
var div = hyperHTML.wire()`<div data=${obj}>abc</div>`;
tressa.assert(div.data === obj, 'data available without serialization');
tressa.assert(div.outerHTML === '<div>abc</div>', 'attribute not there');
})
.then(function () {
tressa.log('## hyper.Component');
class Button extends hyperHTML.Component {
render() { return this.html`
<button>hello</button>`;
}
}
class Rect extends hyperHTML.Component {
constructor(state) {
super();
this.setState(state, false);
}
render() { return this.svg`
<rect x=${this.state.x} y=${this.state.y} />`;
}
}
class Paragraph extends hyperHTML.Component {
constructor(state) {
super();
this.setState(state);
}
onclick() { this.clicked = true; }
render() { return this.html`
<p attr=${this.state.attr} onclick=${this}>hello</p>`;
}
}
var div = document.createElement('div');
var render = hyperHTML.bind(div);
render`${[
new Button,
new Rect({x: 123, y: 456})
]}`;
tressa.assert(div.querySelector('button'), 'the <button> exists');
tressa.assert(div.querySelector('rect'), 'the <rect /> exists');
tressa.assert(div.querySelector('rect').getAttribute('x') == '123', 'attributes are OK');
var p = new Paragraph(() => ({attr: 'test'}));
render`${p}`;
tressa.assert(div.querySelector('p').getAttribute('attr') === 'test', 'the <p attr=test> is defined');
p.render().click();
tressa.assert(p.clicked, 'the event worked');
render`${[
hyperHTML.Component.for.call(Rect, {x: 789, y: 123})
]}`;
tressa.assert(div.querySelector('rect').getAttribute('x') == '789', 'the for(state) worked');
})
.then(function () {
return tressa.async(function (done) {
tressa.log('## Component method via data-call');
class Paragraph extends hyperHTML.Component {
globally(e) {
tressa.assert(e.type === 'click', 'data-call invoked globall');
done();
}
test(e) {
tressa.assert(e.type === 'click', 'data-call invoked locally');
}
render() { return this.html`
<p data-call="test" onclick=${this}>hello</p>`;
}
}
class GlobalEvent extends hyperHTML.Component {
onclick(e) {
tressa.assert(e.type === 'click', 'click invoked globally');
document.removeEventListener('click', this);
done();
}
render() {
document.addEventListener('click', this);
return document;
}
}
var p = new Paragraph();
p.render().click();
var e = document.createEvent('Event');
e.initEvent('click', true, true);
(new GlobalEvent).render().dispatchEvent(e);
});
})
.then(function () { return tressa.async(function (done) {
tressa.log('## Custom Element attributes');
var global = document.defaultView;
var registry = global.customElements;
var customElements = {
_: Object.create(null),
define: function (name, Class) {
this._[name.toLowerCase()] = Class;
},
get: function (name) {
return this._[name.toLowerCase()];
}
};
Object.defineProperty(global, 'customElements', {
configurable: true,
value: customElements
});
function DumbElement() {}
DumbElement.prototype.dumb = null;
DumbElement.prototype.asd = null;
customElements.define('dumb-element', DumbElement);
function update(wire) {
return wire`<div>
<dumb-element dumb=${true} asd=${'qwe'}></dumb-element><dumber-element dumb=${true}></dumber-element>
</div>`;
}
var div = update(hyperHTML.wire());
if (!(div.firstElementChild instanceof DumbElement)) {
tressa.assert(div.firstElementChild.dumb !== true, 'not upgraded elements does not have special attributes');
tressa.assert(div.lastElementChild.dumb !== true, 'unknown elements never have special attributes');
// simulate an upgrade
div.firstElementChild.constructor.prototype.dumb = null;
}
div = update(hyperHTML.wire());
delete div.firstElementChild.constructor.prototype.dumb;
tressa.assert(div.firstElementChild.dumb === true, 'upgraded elements have special attributes');
Object.defineProperty(global, 'customElements', {
configurable: true,
value: registry
});
done();
}); })
.then(function () {
tressa.log('## hyper.Component state');
class DefaultState extends hyperHTML.Component {
get defaultState() { return {a: 'a'}; }
render() {}
}
class State extends hyperHTML.Component {}
var ds = new DefaultState;
var o = ds.state;
tressa.assert(!ds.propertyIsEnumerable('state'), 'states are not enumerable');
tressa.assert(!ds.propertyIsEnumerable('_state$'), 'neither their secret');
tressa.assert(o.a === 'a', 'default state retrieved');
var s = new State;
s.state = o;
tressa.assert(s.state === o, 'state can be set too');
ds.setState({b: 'b'});
tressa.assert(o.a === 'a' && o.b === 'b', 'state was updated');
s.state = {z: 123};
tressa.assert(s.state.z === 123 && !s.state.a, 'state can be re-set too');
})
.then(function () {
tressa.log('## splice and sort');
var todo = [
{id: 0, text: 'write documentation'},
{id: 1, text: 'publish online'},
{id: 2, text: 'create Code Pen'}
];
var div = document.createElement('div');
update();
todo.sort(function(a, b) { return a.text < b.text ? -1 : 1; });
update();
tressa.assert(/^\s+create Code Pen\s*publish online\s*write documentation\s+$/.test(div.textContent), 'correct order');
function update() {
hyperHTML.bind(div)`<ul>
${todo.map(function (item) {
return hyperHTML.wire(item)
`<li data-id=${item.id}>${item.text}</li>`;
})}
</ul>`;
}
})
.then(function () {
return tressa.async(function (done) {
tressa.log('## Component connected/disconnected');
var calls = 0;
class Paragraph extends hyperHTML.Component {
onconnected(e) {
calls++;
tressa.assert(e.type === 'connected', 'component connected');
e.currentTarget.parentNode.removeChild(e.currentTarget);
}
ondisconnected(e) {
calls++;
tressa.assert(e.type === 'disconnected', 'component disconnected');
}
render() { return this.html`
<p onconnected=${this} ondisconnected=${this}>hello</p>`;
}
}
var p = new Paragraph().render();
document.body.appendChild(p);
if (p.parentNode) {
setTimeout(function () {
var e = document.createEvent('Event');
e.initEvent('DOMNodeInserted', false, false);
Object.defineProperty(e, 'target', {value: document.body});
document.dispatchEvent(e);
setTimeout(function () {
e = document.createEvent('Event');
e.initEvent('DOMNodeInserted', false, false);
Object.defineProperty(e, 'target', {value: document.createTextNode('')});
document.dispatchEvent(e);
setTimeout(function () {
e = document.createEvent('Event');
e.initEvent('DOMNodeRemoved', false, false);
Object.defineProperty(e, 'target', {value: p});
document.dispatchEvent(e);
setTimeout(function () {
tressa.assert(calls === 2, 'correct amount of calls');
done();
}, 100);
}, 100);
}, 100);
}, 100);
}
});
})
.then(function () {
tressa.log('## style=${fun}');
var render = hyperHTML.wire();
function p(style) {
return render`<p style=${style}></p>`;
}
var node = p({fontSize:24});
tressa.assert(node.style.fontSize, node.style.fontSize);
p({});
tressa.assert(!node.style.fontSize, 'object cleaned');
p('font-size: 18px');
tressa.assert(node.style.fontSize, node.style.fontSize);
p({'--custom-color': 'red'});
if (node.style.cssText !== '')
tressa.assert(node.style.getPropertyValue('--custom-color') === 'red', 'custom style');
else
console.log('skipping CSS properties for IE');
})
.then(function () {
tressa.log('## <self-closing />');
var div = hyperHTML.wire()`<div><self-closing test=${1} /><input /><self-closing test="2" /></div>`;
tressa.assert(div.childNodes.length === 3, 'nodes did self close');
tressa.assert(div.childNodes[0].getAttribute('test') == "1", 'first node ok');
tressa.assert(/input/i.test(div.childNodes[1].nodeName), 'second node ok');
tressa.assert(div.childNodes[2].getAttribute('test') == "2", 'third node ok');
div = hyperHTML.wire()`<div>
<self-closing
test=1
/><input
/><self-closing test="2"
/>
</div>`;
tressa.assert(div.children.length === 3, 'nodes did self close');
tressa.assert(div.children[0].getAttribute('test') == "1", 'first node ok');
tressa.assert(/input/i.test(div.children[1].nodeName), 'second node ok');
tressa.assert(div.children[2].getAttribute('test') == "2", 'third node ok');
div = hyperHTML.wire()`
<div style="width: 200px;">
<svg viewBox="0 0 30 30" fill="currentColor">
<path d="M 0,27 L 27,0 L 30,3 L 3,30 Z" />
<path d="M 0,3 L 3,0 L 30,27 L 27,30 Z" />
</svg>
</div>
`;
tressa.assert(div.children.length === 1, 'one svg');
tressa.assert(div.querySelectorAll('path').length === 2, 'two paths');
})
.then(function () {
tressa.log('## <with><self-closing /></with>');
function check(form) {
return form.children.length === 3 &&
/label/i.test(form.children[0].nodeName) &&
/input/i.test(form.children[1].nodeName) &&
/button/i.test(form.children[2].nodeName)
}
tressa.assert(
check(hyperHTML.wire()`
<form onsubmit=${check}>
<label/>
<input type="email" placeholder="email">
<button>Button</button>
</form>`),
'no quotes is OK'
);
tressa.assert(
check(hyperHTML.wire()`
<form onsubmit=${check}>
<label />
<input type="email" placeholder="email"/>
<button>Button</button>
</form>`),
'self closing is OK'
);
tressa.assert(
check(hyperHTML.wire()`
<form onsubmit="${check}">
<label/>
<input type="email" placeholder="email">
<button>Button</button>
</form>`),
'quotes are OK'
);
tressa.assert(
check(hyperHTML.wire()`
<form onsubmit="${check}">
<label/>
<input type="email" placeholder="email" />
<button>Button</button>
</form>`),
'quotes and self-closing too OK'
);
})
.then(function () {
return tressa.async(function (done) {
tressa.log('## Nested Component connected/disconnected');
class GrandChild extends hyperHTML.Component {
onconnected(e) {
tressa.assert(e.type === 'connected', 'grand child component connected');
}
ondisconnected(e) {
tressa.assert(e.type === 'disconnected', 'grand child component disconnected');
}
render() {
return this.html`
<p class="grandchild" onconnected=${this} ondisconnected=${this}>I'm grand child</p>`;
}
}
class Child extends hyperHTML.Component {
onconnected(e) {
tressa.assert(e.type === 'connected', 'child component connected');
}
ondisconnected(e) {
tressa.assert(e.type === 'disconnected', 'child component disconnected');
}
render() {
return this.html`
<div class="child" onconnected=${this} ondisconnected=${this}>I'm child
${new GrandChild()}
</div>
`;
}
}
let connectedTimes = 0, disconnectedTimes = 0;
class Parent extends hyperHTML.Component {
onconnected(e) {
connectedTimes ++;
tressa.assert(e.type === 'connected', 'parent component connected');
tressa.assert(connectedTimes === 1, 'connected callback should only be triggered once');
}
ondisconnected(e) {
disconnectedTimes ++;
tressa.assert(e.type === 'disconnected', 'parent component disconnected');
tressa.assert(disconnectedTimes === 1, 'disconnected callback should only be triggered once');
done();
}
render() {
return this.html`
<div class="parent" onconnected=${this} ondisconnected=${this}>I'm parent
${new Child()}
</div>
`;
}
}
var p = new Parent().render();
document.body.appendChild(p);
setTimeout(function () {
if (p.parentNode) {
var e = document.createEvent('Event');
e.initEvent('DOMNodeInserted', false, false);
Object.defineProperty(e, 'target', {value: document.body});
document.dispatchEvent(e);
setTimeout(function () {
e = document.createEvent('Event');
e.initEvent('DOMNodeRemoved', false, false);
Object.defineProperty(e, 'target', {value: p});
document.dispatchEvent(e);
if (p.parentNode)
p.parentNode.removeChild(p);
}, 100);
}
}, 100);
});
})
.then(function () {
tressa.log('## Declarative Components');
class MenuSimple extends hyperHTML.Component {
render(props) {
return this.setState(props, false).html`
<div>A simple menu</div>
<ul>
${props.items.map(
(item, i) => MenuItem.for(this, i).render(item)
)}
</ul>
`;
}
}
class MenuWeakMap extends hyperHTML.Component {
render(props) {
return this.setState(props, false).html`
<div>A simple menu</div>
<ul>
${props.items.map(
item => MenuItem.for(this, item).render(item)
)}
</ul>
`;
}
}
class MenuItem extends hyperHTML.Component {
render(props) {
return this.setState(props, false).html`
<li>${props.name}</li>
`;
}
}
var a = document.createElement('div');
var b = document.createElement('div');
var method = hyperHTML.Component.for;
if (!MenuSimple.for) {
MenuSimple.for = method;
MenuWeakMap.for = method;
MenuItem.for = method;
}
hyperHTML.bind(a)`${MenuSimple.for(a).render({
items: [{name: 'item 1'}, {name: 'item 2'}, {name: 'item 3'}]
})}`;
tressa.assert(MenuSimple.for(a) === MenuSimple.for(a), 'same simple menu');
hyperHTML.bind(b)`${MenuWeakMap.for(b).render({
items: [{name: 'item 1'}, {name: 'item 2'}, {name: 'item 3'}]
})}`;
tressa.assert(MenuWeakMap.for(a) === MenuWeakMap.for(a), 'same weakmap menu');
tressa.assert(MenuSimple.for(a) !== MenuWeakMap.for(a), 'different from simple');
tressa.assert(MenuSimple.for(a) === MenuSimple.for(a), 'same as simple');
tressa.assert(a.outerHTML === b.outerHTML, 'same layout');
})
.then(function () {
tressa.log('## Component.dispatch');
class Pomponent extends hyperHTML.Component {
trigger() {
this.dispatch('event', 123);
}
render() {
return this.html`<p>a</p><p>b</p>`;
}
}
class Solonent extends hyperHTML.Component {
render() {
return this.html`<p>c</p>`;
}
}
var a = document.createElement('div');
var p = new Pomponent;
p.trigger();
var s = new Solonent;
var dispatched = false;
hyperHTML.bind(a)`${[p, s]}`;
a.addEventListener('event', event => {
tressa.assert(event.detail === 123, 'expected details');
tressa.assert(event.component === p, 'expected component');
dispatched = true;
});
p.trigger();
s.dispatch('test');
if (!dispatched) throw new Error('broken dispatch');
})
.then(function () {
tressa.log('## slotted callback');
var div = document.createElement('div');
var result = [];
function A() {
result.push(arguments);
return {html: '<b>a</b>'};
}
function B() {
result.push(arguments);
return {html: '<b>b</b>'};
}
function update() {
hyperHTML.bind(div)`${A} - ${B}`;
}
update();
tressa.assert(result[0][0].parentNode === div, 'expected parent node for A');
tressa.assert(result[1][0].parentNode === div, 'expected parent node for B');
})
.then(function () {
tressa.log('## define(hyper-attribute, callback)');
var a = document.createElement('div');
var random = Math.random().toPrecision(6); // IE < 11
var result = [];
hyperHTML.define('hyper-attribute', function (target, value) {
result.push(target, value);
return random;
});
hyperHTML.bind(a)`<p hyper-attribute=${random}/>`;
if (!result.length)
throw new Error('attributes intents failed');
else {
tressa.assert(result[0] === a.firstElementChild, 'expected target');
tressa.assert(result[1] === random, 'expected value');
tressa.assert(
a.firstElementChild.getAttribute('hyper-attribute') == random,
'expected attribute'
);
}
result.splice(0);
hyperHTML.define('other-attribute', function (target, value) {
result.push(target, value);
return '';
});
hyperHTML.define('disappeared-attribute', function (target, value) {
});
hyperHTML.define('whatever-attribute', function (target, value) {
return value;
});
hyperHTML.define('null-attribute', function (target, value) {
return null;
});
hyperHTML.bind(a)`<p
other-attribute=${random}
disappeared-attribute=${random}
whatever-attribute=${random}
null-attribute=${random}
/>`;
if (!result.length)
throw new Error('attributes intents failed');
else {
tressa.assert(result[0] === a.firstElementChild, 'expected other target');
tressa.assert(result[1] === random, 'expected other value');
tressa.assert(
a.firstElementChild.getAttribute('other-attribute') === '',
'expected other attribute'
);
tressa.assert(
!a.firstElementChild.hasAttribute('disappeared-attribute'),
'disappeared-attribute removed'
);
tressa.assert(
a.firstElementChild.getAttribute('whatever-attribute') == random,
'whatever-attribute set'
);
tressa.assert(
!a.firstElementChild.hasAttribute('null-attribute'),
'null-attribute removed'
);
}
})
// WARNING THESE TEST MUST BE AT THE VERY END
// WARNING THESE TEST MUST BE AT THE VERY END
// WARNING THESE TEST MUST BE AT THE VERY END
.then(function () {
// WARNING THESE TEST MUST BE AT THE VERY END
tressa.log('## IE9 double viewBox 🌈 🌈');
var output = document.createElement('div');
try {
hyperHTML.bind(output)`<svg viewBox=${'0 0 50 50'}></svg>`;
tressa.assert(output.firstChild.getAttribute('viewBox') == '0 0 50 50', 'correct camelCase attribute');
} catch(o_O) {
tressa.assert(true, 'code coverage caveat');
}
})
.then(function () {
tressa.log('## A-Frame compatibility');
var output = hyperHTML.wire()`<a-scene></a-scene>`;
tressa.assert(output.nodeName.toLowerCase() === 'a-scene', 'correct element');
})
// */
.then(function () {
if (!tressa.exitCode) {
document.body.style.backgroundColor = '#0FA';
}
tressa.end();
});
| WebReflection/hyperHTML | test/test.js | JavaScript | isc | 47,230 |
// License: The Unlicense (https://unlicense.org)
#include "EventHandler.hpp"
#include <SDL2/SDL.h>
int EventFilter(void *userData, SDL_Event *event);
void SetUpEvents(void) {
SDL_EventState(SDL_APP_TERMINATING, SDL_IGNORE);
SDL_EventState(SDL_APP_LOWMEMORY, SDL_IGNORE);
SDL_EventState(SDL_APP_WILLENTERBACKGROUND, SDL_IGNORE);
SDL_EventState(SDL_APP_DIDENTERBACKGROUND, SDL_IGNORE);
SDL_EventState(SDL_APP_WILLENTERFOREGROUND, SDL_IGNORE);
SDL_EventState(SDL_APP_DIDENTERFOREGROUND, SDL_IGNORE);
SDL_EventState(SDL_AUDIODEVICEADDED, SDL_IGNORE);
SDL_EventState(SDL_AUDIODEVICEREMOVED, SDL_IGNORE);
SDL_EventState(SDL_CLIPBOARDUPDATE, SDL_IGNORE);
SDL_EventState(SDL_CONTROLLERAXISMOTION, SDL_IGNORE);
SDL_EventState(SDL_CONTROLLERBUTTONDOWN, SDL_IGNORE);
SDL_EventState(SDL_CONTROLLERBUTTONUP, SDL_IGNORE);
SDL_EventState(SDL_CONTROLLERDEVICEADDED, SDL_IGNORE);
SDL_EventState(SDL_CONTROLLERDEVICEREMAPPED, SDL_IGNORE);
SDL_EventState(SDL_CONTROLLERDEVICEREMOVED, SDL_IGNORE);
SDL_EventState(SDL_DOLLARGESTURE, SDL_IGNORE);
SDL_EventState(SDL_DOLLARRECORD, SDL_IGNORE);
SDL_EventState(SDL_DROPFILE, SDL_IGNORE);
SDL_EventState(SDL_FINGERDOWN, SDL_IGNORE);
SDL_EventState(SDL_FINGERMOTION, SDL_IGNORE);
SDL_EventState(SDL_FINGERUP, SDL_IGNORE);
SDL_EventState(SDL_JOYAXISMOTION, SDL_IGNORE);
SDL_EventState(SDL_JOYBALLMOTION, SDL_IGNORE);
SDL_EventState(SDL_JOYBUTTONDOWN, SDL_IGNORE);
SDL_EventState(SDL_JOYBUTTONUP, SDL_IGNORE);
SDL_EventState(SDL_JOYDEVICEADDED, SDL_IGNORE);
SDL_EventState(SDL_JOYDEVICEREMOVED, SDL_IGNORE);
SDL_EventState(SDL_JOYHATMOTION, SDL_IGNORE);
SDL_EventState(SDL_KEYMAPCHANGED, SDL_IGNORE);
SDL_EventState(SDL_KEYUP, SDL_IGNORE);
SDL_EventState(SDL_LASTEVENT, SDL_IGNORE);
SDL_EventState(SDL_MOUSEBUTTONDOWN, SDL_IGNORE);
SDL_EventState(SDL_MOUSEBUTTONUP, SDL_IGNORE);
SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
SDL_EventState(SDL_MOUSEWHEEL, SDL_IGNORE);
SDL_EventState(SDL_MULTIGESTURE, SDL_IGNORE);
SDL_EventState(SDL_RENDER_TARGETS_RESET, SDL_IGNORE);
SDL_EventState(SDL_RENDER_DEVICE_RESET, SDL_IGNORE);
SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE);
SDL_EventState(SDL_TEXTEDITING, SDL_IGNORE);
SDL_EventState(SDL_TEXTINPUT, SDL_IGNORE);
SDL_EventState(SDL_USEREVENT, SDL_IGNORE);
SDL_SetEventFilter(EventFilter, nullptr);
}
int EventFilter(void *, SDL_Event *event) {
int result = 0;
switch (event->type) {
case SDL_QUIT:
case SDL_WINDOWEVENT:
result = 1;
break;
case SDL_KEYDOWN:
switch (event->key.keysym.sym) {
case SDLK_DOWN:
case SDLK_UP:
case SDLK_LEFT:
case SDLK_RIGHT:
result = 1;
break;
default:
// Ignore all other keys
break;
}
break;
default:
printf("Something happened!\n");
break;
}
return result;
}
| tblyons/goon | src/EventHandler.cpp | C++ | isc | 3,005 |
# node-aurora
Node.js client library for interacting with Aurora Dreamband.
Official documentation coming soon. Until then, consider this package a work in progress, subject to breaking changes.
| iwinks/node-aurora | README.md | Markdown | isc | 196 |
MAIN= sosplice-slides
LATEX?= latex </dev/null
XDVI?= xdvi -paper a4
DVIPS?= dvips
GV?= gv
PSPDF?= ps2pdf
DVIPDF?= dvipdf
XPDF?= xpdf
ISPELL?= ispell -t
.PHONY: all clean dvi ps pdf xdvi gv xpdf
all: dvi ps pdf
dvi: ${MAIN}.dvi
ps: ${MAIN}.ps
pdf: ${MAIN}.pdf
${MAIN}.dvi: *.tex
xdvi: ${MAIN}.dvi
${XDVI} ${MAIN} &
gv: ${MAIN}.ps
${GV} ${MAIN} &
xpdf: ${MAIN}.pdf
${XPDF} ${MAIN}.pdf &
ispell: ${MAIN}.tex
${ISPELL} ${MAIN}.tex
clean:
rm -f *.dvi *.log *.toc *.lof *.lot *.aux *.idx *.ind *.ilg *.ps *.pdf
.SUFFIXES: .tex .dvi .ps .pdf
.tex.dvi:
${LATEX} $*
.dvi.ps:
${DVIPS} -o $@ $*
.ps.pdf:
${PSPDF} $< $@
.dvi.pdf:
${DVIPDF} $< $@
| bluhm/talk-sosplice | Makefile | Makefile | isc | 659 |
var DND_START_EVENT = 'dnd-start',
DND_END_EVENT = 'dnd-end',
DND_DRAG_EVENT = 'dnd-drag';
angular
.module( 'app' )
.config( [ 'iScrollServiceProvider', function(iScrollServiceProvider){
iScrollServiceProvider.configureDefaults({
iScroll: {
momentum: false,
mouseWheel: true,
disableMouse: false,
useTransform: true,
scrollbars: true,
interactiveScrollbars: true,
resizeScrollbars: false,
probeType: 2,
preventDefault: false
// preventDefaultException: {
// tagName: /^.*$/
// }
},
directive: {
asyncRefreshDelay: 0,
refreshInterval: false
}
});
} ] )
.controller( 'main', function( $scope, draggingIndicator, iScrollService ){
'use strict';
this.iScrollState = iScrollService.state;
var DND_SCROLL_IGNORED_HEIGHT = 20, // ignoring 20px touch-scroll,
// TODO: this might be stored somewhere in browser env
DND_ACTIVATION_TIMEOUT = 500, // milliseconds needed to touch-activate d-n-d
MOUSE_OVER_EVENT = 'mousemove';
var self = this,
items = [],
touchTimerId;
$scope.dragging = draggingIndicator;
for( var i = 0; i< 25; i++ ){
items.push( i );
}
$scope.items = items;
this.disable = function ( ){
$scope.iScrollInstance.disable();
};
this.log = function ( msg ){
console.log( 'got msg', msg );
};
} );
| kosich/ng-hammer-iscroll-drag | main.js | JavaScript | isc | 1,547 |
/*
* Copyright © 2016 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jcanephora.tests.lwjgl3;
import com.io7m.jcanephora.core.api.JCGLContextType;
import com.io7m.jcanephora.core.api.JCGLInterfaceGL33Type;
import com.io7m.jcanephora.tests.contracts.JCGLFramebuffersContract;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class LWJGL3FramebuffersTestGL33 extends JCGLFramebuffersContract
{
private static final Logger LOG;
static {
LOG = LoggerFactory.getLogger(LWJGL3FramebuffersTestGL33.class);
}
@Override
public void onTestCompleted()
{
LWJGL3TestContexts.closeAllContexts();
}
@Override
protected Interfaces getInterfaces(final String name)
{
final JCGLContextType c = LWJGL3TestContexts.newGL33Context(name, 24, 8);
final JCGLInterfaceGL33Type cg = c.contextGetGL33();
return new Interfaces(c, cg.framebuffers(), cg.textures());
}
@Override
protected boolean hasRealBlitting()
{
return true;
}
}
| io7m/jcanephora | com.io7m.jcanephora.tests.lwjgl3/src/test/java/com/io7m/jcanephora/tests/lwjgl3/LWJGL3FramebuffersTestGL33.java | Java | isc | 1,726 |
'use strict'
let _ = require('lodash')
let HttpClient = require('./http-client')
/**
* Server configuration and environment information
* @extends {HttpClient}
*/
class Config extends HttpClient {
/**
* @constructs Config
* @param {Object} options General configuration options
* @param {Object} options.http configurations for HttpClient
*/
constructor (options) {
super(options.http)
}
/**
* Return the whole server information
* @return {Promise} A promise that resolves to the server information
*/
server () {
return this._httpRequest('GET')
.then((response) => response.metadata)
}
/**
* Retrieve the server configuration
* @return {Promise} A promise that resolves to the server configuration
*/
get () {
return this.server()
.then((server) => server.config)
}
/**
* Unset parameters from server configuration
* @param {...String} arguments A list parameters that you want to unset
* @return {Promise} A promise that resolves when the config has been unset
*/
unset () {
return this.get()
.then((config) => _.omit(config, _.flatten(Array.from(arguments))))
.then((config) => this.update(config))
}
/**
* Set one or more configurations in the server
* @param {Object} data A plain object containing the configuration you want
* to insert or update in the server
* @return {Pomise} A promise that resolves when the config has been set
*/
set (data) {
return this.get()
.then((config) => _.merge(config, data))
.then((config) => this.update(config))
}
/**
* Replaces the whole server configuration for the one provided
* @param {Object} data The new server configuration
* @return {Promise} A promise that resolves when the configuration has been
* replaces
*/
update (data) {
return this._httpRequest('PUT', { config: data })
}
}
module.exports = Config
| alanhoff/node-lxd | lib/config.js | JavaScript | isc | 1,927 |
# atm
前端构建工具
| atm-team/atm | README.md | Markdown | isc | 26 |
import $ from 'jquery';
import { router } from 'src/router';
import './header.scss';
export default class Header {
static selectors = {
button: '.header__enter',
search: '.header__search'
};
constructor($root) {
this.elements = {
$root,
$window: $(window)
};
this.attachEvents();
}
attachEvents() {
this.elements.$root.on('click', Header.selectors.button, this.handleClick)
}
handleClick = () => {
const search = $(Header.selectors.search).val();
if (search) {
router.navigate(`/search?query=${search}`);
}
}
}
| ksukhova/Auction | src/components/header/header.js | JavaScript | isc | 658 |
import re
from exchange.constants import (
CURRENCIES,
CURRENCY_NAMES,
DEFAULT_CURRENCY,
CURRENCY_EUR,
CURRENCY_UAH,
CURRENCY_USD,
CURRENCY_SESSION_KEY)
def round_number(value, decimal_places=2, down=False):
assert decimal_places > 0
factor = 1.0 ** decimal_places
sign = -1 if value < 0 else 1
return int(value * factor + sign * (0 if down else 0.5)) / factor
def format_number(value):
append_comma = lambda match_object: "%s," % match_object.group(0)
value = "%.2f" % float(value)
value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value)
return value
def format_price(price, round_price=False):
price = float(price)
return format_number(round_number(price) if round_price else price)
def format_printable_price(price, currency=DEFAULT_CURRENCY):
return '%s %s' % (format_price(price), dict(CURRENCIES)[currency])
def get_currency_from_session(session):
currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY
return int(currency)
def get_price_factory(rates, src, dst):
if src == dst:
return lambda p: p
name = lambda c: CURRENCY_NAMES[c]
if src == CURRENCY_UAH:
return lambda p: p / getattr(rates, name(dst))
if dst == CURRENCY_UAH:
return lambda p: p * getattr(rates, name(src))
if src == CURRENCY_USD and dst == CURRENCY_EUR:
return lambda p: p * rates.usd_eur
if src == CURRENCY_EUR and dst == CURRENCY_USD:
return lambda p: p / rates.usd_eur
raise ValueError('Unknown currencies')
| pmaigutyak/mp-shop | exchange/utils.py | Python | isc | 1,571 |
package org.apollo.game.event.handler.impl;
import org.apollo.game.event.handler.EventHandler;
import org.apollo.game.event.handler.EventHandlerContext;
import org.apollo.game.event.impl.ItemOnItemEvent;
import org.apollo.game.model.Inventory;
import org.apollo.game.model.Item;
import org.apollo.game.model.Player;
/**
* An {@link EventHandler} which verifies the target item in {@link ItemOnItemEvent}s.
*
* @author Chris Fletcher
*/
public final class ItemOnItemVerificationHandler extends EventHandler<ItemOnItemEvent> {
@Override
public void handle(EventHandlerContext ctx, Player player, ItemOnItemEvent event) {
Inventory inventory = ItemVerificationHandler.interfaceToInventory(player, event.getTargetInterfaceId());
int slot = event.getTargetSlot();
if (slot < 0 || slot >= inventory.capacity()) {
ctx.breakHandlerChain();
return;
}
Item item = inventory.get(slot);
if (item == null || item.getId() != event.getTargetId()) {
ctx.breakHandlerChain();
}
}
} | DealerNextDoor/ApolloDev | src/org/apollo/game/event/handler/impl/ItemOnItemVerificationHandler.java | Java | isc | 1,001 |
"use strict";
describe("This package", function(){
it("rubs the lotion on its skin, or else", function(){
2..should.equal(2); // In this universe, it'd damn well better
});
it("gets the hose again", function(){
this.should.be.extensible.and.ok; // Eventually
});
it("should not fail", function(){
NaN.should.not.equal(NaN); // NaH
global.foo = "Foo";
});
it("might be written later"); // Nah
it("should fail", function(){
const A = {
alpha: "A",
beta: "B",
gamma: "E",
delta: "D",
};
const B = {
Alpha: "A",
beta: "B",
gamma: "E",
delta: "d",
};
A.should.equal(B);
});
describe("Suite nesting", function(){
it("does something useful eventually", function(done){
setTimeout(() => done(), 40);
});
it("cleans anonymous async functions", async function(){
if(true){
true.should.be.true;
}
});
it("cleans anonymous generators", function * (){
if(true){
true.should.be.true;
}
});
it("cleans named async functions", async function foo() {
if(true){
true.should.be.true;
}
});
it("cleans named generators", function * foo (){
if(true){
true.should.be.true;
}
});
it("cleans async arrow functions", async () => {
if(true){
true.should.be.true;
}
});
});
});
describe("Second suite at top-level", function(){
it("shows another block", function(){
Chai.expect(Date).to.be.an.instanceOf(Function);
});
it("breaks something", function(){
something();
});
it("loads locally-required files", () => {
expect(global.someGlobalThing).to.equal("fooXYZ");
});
unlessOnWindows.it("enjoys real symbolic links", () => {
"Any Unix-like system".should.be.ok;
});
});
describe("Aborted tests", () => {
before(() => {throw new Error("Nah, not really")});
it("won't reach this", () => true.should.not.be.false);
it.skip("won't reach this either", () => true.should.be.true);
});
| Alhadis/Atom-Mocha | spec/basic-spec.js | JavaScript | isc | 1,958 |
/* $OpenBSD: ptrace.h,v 1.4 2011/11/10 22:48:13 deraadt Exp $ */
/*
* Copyright (c) 2005 Michael Shalayeff
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* MD ptrace definitions
*/
#define PT_STEP (PT_FIRSTMACH + 0)
#define PT_GETREGS (PT_FIRSTMACH + 1)
#define PT_SETREGS (PT_FIRSTMACH + 2)
#define PT_GETFPREGS (PT_FIRSTMACH + 3)
#define PT_SETFPREGS (PT_FIRSTMACH + 4)
| orumin/openbsd-efivars | arch/hppa/include/ptrace.h | C | isc | 1,097 |
'use strict';
var yeoman = require('yeoman-generator'),
chalk = require('chalk'),
yosay = require('yosay'),
bakery = require('../../lib/bakery'),
feedback = require('../../lib/feedback'),
debug = require('debug')('bakery:generators:cm-bash:index'),
glob = require('glob'),
path = require('path'),
_ = require('lodash');
// placeholder for CM implementaiton delivering a BASH-based project.
var BakeryCM = yeoman.Base.extend({
constructor: function () {
yeoman.Base.apply(this, arguments);
this._options.help.desc = 'Show this help';
this.argument('projectname', {
type: String,
required: this.config.get('projectname') == undefined
});
},
// generators are invalid without at least one method to run during lifecycle
default: function () {
/*
TAKE NOTE: these next two lines are fallout of having to include ALL
sub-generators in .composeWith(...) at the top level. Essentially
ALL SUBGENERATORS RUN ALL THE TIME. So we have to escape from
generators we don't want running within EVERY lifecycle method.
(ugh)
*/
let cmInfo = this.config.get('cm');
if (cmInfo.generatorName != 'cm-bash') {
return;
}
}
});
module.exports = BakeryCM;
| datapipe/generator-bakery | generators/cm-bash/index.js | JavaScript | isc | 1,256 |
package com.leychina.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebChromeClient;
import android.widget.ImageView;
import android.widget.TextView;
import com.leychina.R;
import com.leychina.model.Artist;
import com.leychina.value.Constant;
import com.leychina.widget.tabindicator.TouchyWebView;
import com.squareup.picasso.Picasso;
/**
* Created by yuandunlong on 11/21/15.
*/
public class ArtistDetailActivity extends AppCompatActivity {
TouchyWebView webview;
Artist artist;
ImageView imageView;
TextView weight, height, name, birthday;
public static void start(Context from, Artist artist) {
Intent intent = new Intent(from, ArtistDetailActivity.class);
intent.putExtra("artist", artist);
from.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
this.artist = (Artist) intent.getSerializableExtra("artist");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_artist_detail);
webview = (TouchyWebView) findViewById(R.id.artist_webview);
imageView = (ImageView) findViewById(R.id.image_view_artist_cover);
Picasso.with(this).load(Constant.DOMAIN+"/static/upload/"+artist.getPhoto()).into(imageView);
name = (TextView) findViewById(R.id.text_view_name);
height = (TextView) findViewById(R.id.text_view_height);
weight = (TextView) findViewById(R.id.text_view_weight);
birthday= (TextView) findViewById(R.id.text_view_birthday);
// name.setText(artist.get);
weight.setText(artist.getWeight() + "");
height.setText(artist.getHeight() + "");
birthday.setText(artist.getBlood());
webview.setWebChromeClient(new WebChromeClient());
webview.getSettings().setDefaultTextEncodingName("utf-8");
webview.loadDataWithBaseURL(Constant.DOMAIN, artist.getDescription(), "text/html", "utf-8","");
}
}
| yuandunlong/leychina-android | app/src/main/java/com/leychina/activity/ArtistDetailActivity.java | Java | isc | 2,114 |
/*\
|*|
|*| :: cookies.js ::
|*|
|*| A complete cookies reader/writer framework with full unicode support.
|*|
|*| Revision #1 - September 4, 2014
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*| https://developer.mozilla.org/User:fusionchess
|*|
|*| This framework is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*| Syntaxes:
|*|
|*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*| * docCookies.getItem(name)
|*| * docCookies.removeItem(name[, path[, domain]])
|*| * docCookies.hasItem(name)
|*| * docCookies.keys()
|*|
\*/
export default {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
| thinhhung610/my-blog | js/vendor/cookie.js | JavaScript | isc | 2,508 |
// SPDX-License-Identifier: ISC
// Copyright (c) 2014-2020 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package transactionrecord_test
import (
"bytes"
"encoding/json"
"reflect"
"testing"
"golang.org/x/crypto/ed25519"
"github.com/bitmark-inc/bitmarkd/currency"
"github.com/bitmark-inc/bitmarkd/fault"
"github.com/bitmark-inc/bitmarkd/merkle"
"github.com/bitmark-inc/bitmarkd/transactionrecord"
"github.com/bitmark-inc/bitmarkd/util"
)
// test the packing/unpacking of base record
//
// ensures that pack->unpack returns the same original value
func TestPackBaseData(t *testing.T) {
proofedByAccount := makeAccount(proofedBy.publicKey)
r := transactionrecord.OldBaseData{
Currency: currency.Bitcoin,
PaymentAddress: "mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn",
Owner: proofedByAccount,
Nonce: 0x12345678,
}
expected := []byte{
0x01, 0x01, 0x22, 0x6d, 0x69, 0x70, 0x63, 0x42,
0x62, 0x46, 0x67, 0x39, 0x67, 0x4d, 0x69, 0x43,
0x68, 0x38, 0x31, 0x4b, 0x6a, 0x38, 0x74, 0x71,
0x71, 0x64, 0x67, 0x6f, 0x5a, 0x75, 0x62, 0x31,
0x5a, 0x4a, 0x52, 0x66, 0x6e, 0x21, 0x13, 0x55,
0xb2, 0x98, 0x88, 0x17, 0xf7, 0xea, 0xec, 0x37,
0x74, 0x1b, 0x82, 0x44, 0x71, 0x63, 0xca, 0xaa,
0x5a, 0x9d, 0xb2, 0xb6, 0xf0, 0xce, 0x72, 0x26,
0x26, 0x33, 0x8e, 0x5e, 0x3f, 0xd7, 0xf7, 0xf8,
0xac, 0xd1, 0x91, 0x01,
}
expectedTxId := merkle.Digest{
0x9e, 0x93, 0x2b, 0x8e, 0xa1, 0xa3, 0xd4, 0x30,
0xc5, 0x9a, 0x23, 0xfd, 0x56, 0x75, 0xe8, 0xba,
0x64, 0x0e, 0xe8, 0x1c, 0xf3, 0x0e, 0x68, 0xca,
0x14, 0x8e, 0xe1, 0x1f, 0x13, 0xdb, 0xd4, 0x27,
}
// manually sign the record and attach signature to "expected"
signature := ed25519.Sign(proofedBy.privateKey, expected)
r.Signature = signature
//t.Logf("signature: %#v", r.Signature)
l := util.ToVarint64(uint64(len(signature)))
expected = append(expected, l...)
expected = append(expected, signature...)
// test the packer
packed, err := r.Pack(proofedByAccount)
if nil != err {
t.Fatalf("pack error: %s", err)
}
// if either of above fail we will have the message _without_ a signature
if !bytes.Equal(packed, expected) {
t.Errorf("pack record: %x expected: %x", packed, expected)
t.Errorf("*** GENERATED Packed:\n%s", util.FormatBytes("expected", packed))
t.Fatal("fatal error")
}
// check the record type
if transactionrecord.BaseDataTag != packed.Type() {
t.Fatalf("pack record type: %x expected: %x", packed.Type(), transactionrecord.BaseDataTag)
}
t.Logf("Packed length: %d bytes", len(packed))
// check txIds
txId := packed.MakeLink()
if txId != expectedTxId {
t.Errorf("pack tx id: %#v expected: %#v", txId, expectedTxId)
t.Errorf("*** GENERATED tx id:\n%s", util.FormatBytes("expectedTxId", txId[:]))
}
// test the unpacker
unpacked, n, err := packed.Unpack(true)
if nil != err {
t.Fatalf("unpack error: %s", err)
}
if len(packed) != n {
t.Errorf("did not unpack all data: only used: %d of: %d bytes", n, len(packed))
}
baseData, ok := unpacked.(*transactionrecord.OldBaseData)
if !ok {
t.Fatalf("did not unpack to BaseData")
}
// display a JSON version for information
item := struct {
TxId merkle.Digest
BaseData *transactionrecord.OldBaseData
}{
TxId: txId,
BaseData: baseData,
}
b, err := json.MarshalIndent(item, "", " ")
if nil != err {
t.Fatalf("json error: %s", err)
}
t.Logf("BaseData: JSON: %s", b)
// check that structure is preserved through Pack/Unpack
// note reg is a pointer here
if !reflect.DeepEqual(r, *baseData) {
t.Errorf("different, original: %v recovered: %v", r, *baseData)
}
checkPackedData(t, "base data", packed)
}
// test the pack failure on trying to use the zero public key
func TestPackBaseDataWithZeroAccount(t *testing.T) {
proofedByAccount := makeAccount(theZeroKey.publicKey)
r := transactionrecord.OldBaseData{
Currency: currency.Bitcoin,
PaymentAddress: "mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn",
Owner: proofedByAccount,
Nonce: 0x12345678,
Signature: []byte{1, 2, 3, 4},
}
// test the packer
_, err := r.Pack(proofedByAccount)
if nil == err {
t.Fatalf("pack should have failed")
}
if fault.InvalidOwnerOrRegistrant != err {
t.Fatalf("unexpected pack error: %s", err)
}
}
| bitmark-inc/bitmarkd | transactionrecord/base_test.go | GO | isc | 4,328 |
FitApp
======
Fitness app for the web. Runs as a [Chrome Extension](https://chrome.google.com/webstore/detail/ccbhmeejgcplbakhfhbmppbgpfbmjghd) or stand alone app.
| qbit/FitApp | README.md | Markdown | isc | 167 |
<!---
THIS IS AN AUTOGENERATED FILE. EDIT PACKAGES/BOUNDLESS-INPUT/INDEX.JS INSTEAD.
-->
# Input
Input abstracts away the cross-platform differences of placeholder styling and behaviors, for example: Internet Explorer dismisses native placeholders on input focus and other platforms do not. This component ensures that text input controls will feel and behave similarly on more devices.
## Component Instance Methods
When using `Input` in your project, you may call the following methods on a rendered instance of the component. Use [`refs`](https://facebook.github.io/react/docs/refs-and-the-dom.html) to get the instance.
- __getValue()__
returns the current value of the input field
- __setValue(string)__
programmatically set the input value; useful for clearing out the input in "uncontrolled" mode -- note that digging into the internals and setting the `refs.field.value = ''` directly will not trigger events and messes up the internal state of the component
## Installation
```bash
npm i boundless-input --save
```
Then use it like:
```jsx
/** @jsx createElement */
import { createElement, PureComponent } from 'react';
import Input from 'boundless-input';
export default class InputDemo extends PureComponent {
state = {
input: '',
}
handleChange = (e) => this.setState({ input: e.target.value })
render() {
return (
<div className='spread'>
<div>
<h5>hidePlaceholderOnFocus="false"</h5>
<Input
hidePlaceholderOnFocus={false}
inputProps={{
placeholder: 'Start typing and I disappear!',
}} />
</div>
<div style={{ marginLeft: '1em' }}>
<h5>hidePlaceholderOnFocus="true"</h5>
<Input
hidePlaceholderOnFocus={true}
inputProps={{
placeholder: 'Focus on me and I disappear!',
}} />
</div>
<div style={{ marginLeft: '1em' }}>
<h5>"controlled" input</h5>
<Input
hidePlaceholderOnFocus={true}
inputProps={{
placeholder: 'Focus on me and I disappear!',
onChange: this.handleChange,
value: this.state.input,
}} />
</div>
</div>
);
}
}
```
Input can also just be directly used from the main [Boundless library](https://www.npmjs.com/package/boundless). This is recommended when you're getting started to avoid maintaining the package versions of several components:
```bash
npm i boundless --save
```
the ES6 `import` statement then becomes like:
```js
import { Input } from 'boundless';
```
## Props
> Note: only top-level props are in the README, for the full list check out the [website](https://boundless.js.org/Input).
### Required Props
There are no required props.
### Optional Props
- __`*`__ · any [React-supported attribute](https://facebook.github.io/react/docs/tags-and-attributes.html#html-attributes)
Expects | Default Value
--- | ---
`any` | `n/a`
- __`component`__ · overrides the HTML container tag
Expects | Default Value
--- | ---
`string` | `'div'`
- __`hidePlaceholderOnFocus`__ · triggers the placeholder to disappear when the input field is focused, reappears when the user has tabbed away or focus is moved
Expects | Default Value
--- | ---
`bool` | `true`
- __`inputProps`__
Expects | Default Value
--- | ---
`object` | `{ type: 'text' }`
## Reference Styles
### Stylus
You can see what variables are available to override in [variables.styl](https://github.com/enigma-io/boundless/blob/master/variables.styl).
```stylus
// Redefine any variables as desired, e.g:
color-accent = royalblue
// Bring in the component styles; they will be autoconfigured based on the above
@require "node_modules/boundless-input/style"
```
### CSS
If desired, a precompiled plain CSS stylesheet is available for customization at `/build/style.css`, based on Boundless's [default variables](https://github.com/enigma-io/boundless/blob/master/variables.styl).
| enigma-io/boundless | packages/boundless-input/README.md | Markdown | mit | 4,410 |
module Scubaru
VERSION = "0.0.1"
end
| JoshAshby/scubaru | lib/scubaru/version.rb | Ruby | mit | 39 |
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/devtools/containeranalysis/v1alpha1/bill_of_materials.proto
package containeranalysis // import "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1alpha1"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "google.golang.org/genproto/googleapis/api/annotations"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// Instruction set architectures supported by various package managers.
type PackageManager_Architecture int32
const (
// Unknown architecture
PackageManager_ARCHITECTURE_UNSPECIFIED PackageManager_Architecture = 0
// X86 architecture
PackageManager_X86 PackageManager_Architecture = 1
// X64 architecture
PackageManager_X64 PackageManager_Architecture = 2
)
var PackageManager_Architecture_name = map[int32]string{
0: "ARCHITECTURE_UNSPECIFIED",
1: "X86",
2: "X64",
}
var PackageManager_Architecture_value = map[string]int32{
"ARCHITECTURE_UNSPECIFIED": 0,
"X86": 1,
"X64": 2,
}
func (x PackageManager_Architecture) String() string {
return proto.EnumName(PackageManager_Architecture_name, int32(x))
}
func (PackageManager_Architecture) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_bill_of_materials_ffdc7b89323081b5, []int{0, 0}
}
// PackageManager provides metadata about available / installed packages.
type PackageManager struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *PackageManager) Reset() { *m = PackageManager{} }
func (m *PackageManager) String() string { return proto.CompactTextString(m) }
func (*PackageManager) ProtoMessage() {}
func (*PackageManager) Descriptor() ([]byte, []int) {
return fileDescriptor_bill_of_materials_ffdc7b89323081b5, []int{0}
}
func (m *PackageManager) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_PackageManager.Unmarshal(m, b)
}
func (m *PackageManager) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_PackageManager.Marshal(b, m, deterministic)
}
func (dst *PackageManager) XXX_Merge(src proto.Message) {
xxx_messageInfo_PackageManager.Merge(dst, src)
}
func (m *PackageManager) XXX_Size() int {
return xxx_messageInfo_PackageManager.Size(m)
}
func (m *PackageManager) XXX_DiscardUnknown() {
xxx_messageInfo_PackageManager.DiscardUnknown(m)
}
var xxx_messageInfo_PackageManager proto.InternalMessageInfo
// This represents a particular channel of distribution for a given package.
// e.g. Debian's jessie-backports dpkg mirror
type PackageManager_Distribution struct {
// The cpe_uri in [cpe format](https://cpe.mitre.org/specification/)
// denoting the package manager version distributing a package.
CpeUri string `protobuf:"bytes,1,opt,name=cpe_uri,json=cpeUri,proto3" json:"cpe_uri,omitempty"`
// The CPU architecture for which packages in this distribution
// channel were built
Architecture PackageManager_Architecture `protobuf:"varint,2,opt,name=architecture,proto3,enum=google.devtools.containeranalysis.v1alpha1.PackageManager_Architecture" json:"architecture,omitempty"`
// The latest available version of this package in
// this distribution channel.
LatestVersion *VulnerabilityType_Version `protobuf:"bytes,3,opt,name=latest_version,json=latestVersion,proto3" json:"latest_version,omitempty"`
// A freeform string denoting the maintainer of this package.
Maintainer string `protobuf:"bytes,4,opt,name=maintainer,proto3" json:"maintainer,omitempty"`
// The distribution channel-specific homepage for this package.
Url string `protobuf:"bytes,6,opt,name=url,proto3" json:"url,omitempty"`
// The distribution channel-specific description of this package.
Description string `protobuf:"bytes,7,opt,name=description,proto3" json:"description,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *PackageManager_Distribution) Reset() { *m = PackageManager_Distribution{} }
func (m *PackageManager_Distribution) String() string { return proto.CompactTextString(m) }
func (*PackageManager_Distribution) ProtoMessage() {}
func (*PackageManager_Distribution) Descriptor() ([]byte, []int) {
return fileDescriptor_bill_of_materials_ffdc7b89323081b5, []int{0, 0}
}
func (m *PackageManager_Distribution) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_PackageManager_Distribution.Unmarshal(m, b)
}
func (m *PackageManager_Distribution) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_PackageManager_Distribution.Marshal(b, m, deterministic)
}
func (dst *PackageManager_Distribution) XXX_Merge(src proto.Message) {
xxx_messageInfo_PackageManager_Distribution.Merge(dst, src)
}
func (m *PackageManager_Distribution) XXX_Size() int {
return xxx_messageInfo_PackageManager_Distribution.Size(m)
}
func (m *PackageManager_Distribution) XXX_DiscardUnknown() {
xxx_messageInfo_PackageManager_Distribution.DiscardUnknown(m)
}
var xxx_messageInfo_PackageManager_Distribution proto.InternalMessageInfo
func (m *PackageManager_Distribution) GetCpeUri() string {
if m != nil {
return m.CpeUri
}
return ""
}
func (m *PackageManager_Distribution) GetArchitecture() PackageManager_Architecture {
if m != nil {
return m.Architecture
}
return PackageManager_ARCHITECTURE_UNSPECIFIED
}
func (m *PackageManager_Distribution) GetLatestVersion() *VulnerabilityType_Version {
if m != nil {
return m.LatestVersion
}
return nil
}
func (m *PackageManager_Distribution) GetMaintainer() string {
if m != nil {
return m.Maintainer
}
return ""
}
func (m *PackageManager_Distribution) GetUrl() string {
if m != nil {
return m.Url
}
return ""
}
func (m *PackageManager_Distribution) GetDescription() string {
if m != nil {
return m.Description
}
return ""
}
// An occurrence of a particular package installation found within a
// system's filesystem.
// e.g. glibc was found in /var/lib/dpkg/status
type PackageManager_Location struct {
// The cpe_uri in [cpe format](https://cpe.mitre.org/specification/)
// denoting the package manager version distributing a package.
CpeUri string `protobuf:"bytes,1,opt,name=cpe_uri,json=cpeUri,proto3" json:"cpe_uri,omitempty"`
// The version installed at this location.
Version *VulnerabilityType_Version `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"`
// The path from which we gathered that this package/version is installed.
Path string `protobuf:"bytes,3,opt,name=path,proto3" json:"path,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *PackageManager_Location) Reset() { *m = PackageManager_Location{} }
func (m *PackageManager_Location) String() string { return proto.CompactTextString(m) }
func (*PackageManager_Location) ProtoMessage() {}
func (*PackageManager_Location) Descriptor() ([]byte, []int) {
return fileDescriptor_bill_of_materials_ffdc7b89323081b5, []int{0, 1}
}
func (m *PackageManager_Location) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_PackageManager_Location.Unmarshal(m, b)
}
func (m *PackageManager_Location) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_PackageManager_Location.Marshal(b, m, deterministic)
}
func (dst *PackageManager_Location) XXX_Merge(src proto.Message) {
xxx_messageInfo_PackageManager_Location.Merge(dst, src)
}
func (m *PackageManager_Location) XXX_Size() int {
return xxx_messageInfo_PackageManager_Location.Size(m)
}
func (m *PackageManager_Location) XXX_DiscardUnknown() {
xxx_messageInfo_PackageManager_Location.DiscardUnknown(m)
}
var xxx_messageInfo_PackageManager_Location proto.InternalMessageInfo
func (m *PackageManager_Location) GetCpeUri() string {
if m != nil {
return m.CpeUri
}
return ""
}
func (m *PackageManager_Location) GetVersion() *VulnerabilityType_Version {
if m != nil {
return m.Version
}
return nil
}
func (m *PackageManager_Location) GetPath() string {
if m != nil {
return m.Path
}
return ""
}
// This represents a particular package that is distributed over
// various channels.
// e.g. glibc (aka libc6) is distributed by many, at various versions.
type PackageManager_Package struct {
// The name of the package.
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
// The various channels by which a package is distributed.
Distribution []*PackageManager_Distribution `protobuf:"bytes,10,rep,name=distribution,proto3" json:"distribution,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *PackageManager_Package) Reset() { *m = PackageManager_Package{} }
func (m *PackageManager_Package) String() string { return proto.CompactTextString(m) }
func (*PackageManager_Package) ProtoMessage() {}
func (*PackageManager_Package) Descriptor() ([]byte, []int) {
return fileDescriptor_bill_of_materials_ffdc7b89323081b5, []int{0, 2}
}
func (m *PackageManager_Package) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_PackageManager_Package.Unmarshal(m, b)
}
func (m *PackageManager_Package) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_PackageManager_Package.Marshal(b, m, deterministic)
}
func (dst *PackageManager_Package) XXX_Merge(src proto.Message) {
xxx_messageInfo_PackageManager_Package.Merge(dst, src)
}
func (m *PackageManager_Package) XXX_Size() int {
return xxx_messageInfo_PackageManager_Package.Size(m)
}
func (m *PackageManager_Package) XXX_DiscardUnknown() {
xxx_messageInfo_PackageManager_Package.DiscardUnknown(m)
}
var xxx_messageInfo_PackageManager_Package proto.InternalMessageInfo
func (m *PackageManager_Package) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *PackageManager_Package) GetDistribution() []*PackageManager_Distribution {
if m != nil {
return m.Distribution
}
return nil
}
// This represents how a particular software package may be installed on
// a system.
type PackageManager_Installation struct {
// Output only. The name of the installed package.
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
// All of the places within the filesystem versions of this package
// have been found.
Location []*PackageManager_Location `protobuf:"bytes,2,rep,name=location,proto3" json:"location,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *PackageManager_Installation) Reset() { *m = PackageManager_Installation{} }
func (m *PackageManager_Installation) String() string { return proto.CompactTextString(m) }
func (*PackageManager_Installation) ProtoMessage() {}
func (*PackageManager_Installation) Descriptor() ([]byte, []int) {
return fileDescriptor_bill_of_materials_ffdc7b89323081b5, []int{0, 3}
}
func (m *PackageManager_Installation) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_PackageManager_Installation.Unmarshal(m, b)
}
func (m *PackageManager_Installation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_PackageManager_Installation.Marshal(b, m, deterministic)
}
func (dst *PackageManager_Installation) XXX_Merge(src proto.Message) {
xxx_messageInfo_PackageManager_Installation.Merge(dst, src)
}
func (m *PackageManager_Installation) XXX_Size() int {
return xxx_messageInfo_PackageManager_Installation.Size(m)
}
func (m *PackageManager_Installation) XXX_DiscardUnknown() {
xxx_messageInfo_PackageManager_Installation.DiscardUnknown(m)
}
var xxx_messageInfo_PackageManager_Installation proto.InternalMessageInfo
func (m *PackageManager_Installation) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *PackageManager_Installation) GetLocation() []*PackageManager_Location {
if m != nil {
return m.Location
}
return nil
}
func init() {
proto.RegisterType((*PackageManager)(nil), "google.devtools.containeranalysis.v1alpha1.PackageManager")
proto.RegisterType((*PackageManager_Distribution)(nil), "google.devtools.containeranalysis.v1alpha1.PackageManager.Distribution")
proto.RegisterType((*PackageManager_Location)(nil), "google.devtools.containeranalysis.v1alpha1.PackageManager.Location")
proto.RegisterType((*PackageManager_Package)(nil), "google.devtools.containeranalysis.v1alpha1.PackageManager.Package")
proto.RegisterType((*PackageManager_Installation)(nil), "google.devtools.containeranalysis.v1alpha1.PackageManager.Installation")
proto.RegisterEnum("google.devtools.containeranalysis.v1alpha1.PackageManager_Architecture", PackageManager_Architecture_name, PackageManager_Architecture_value)
}
func init() {
proto.RegisterFile("google/devtools/containeranalysis/v1alpha1/bill_of_materials.proto", fileDescriptor_bill_of_materials_ffdc7b89323081b5)
}
var fileDescriptor_bill_of_materials_ffdc7b89323081b5 = []byte{
// 522 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x93, 0xd1, 0x8a, 0xd3, 0x4e,
0x14, 0xc6, 0xff, 0x49, 0x97, 0x76, 0xf7, 0xb4, 0xff, 0x52, 0xe6, 0xc6, 0x10, 0x16, 0x29, 0x0b,
0x42, 0xf1, 0x22, 0x61, 0x57, 0x59, 0x04, 0x41, 0xe8, 0x76, 0xbb, 0x6b, 0x41, 0xa5, 0xc4, 0x76,
0x11, 0xbd, 0x08, 0xa7, 0xe9, 0x98, 0x0e, 0x3b, 0x9d, 0x09, 0x93, 0x49, 0xa1, 0xd7, 0xde, 0x89,
0x0f, 0xe0, 0xb5, 0x0f, 0xa5, 0xaf, 0x23, 0x99, 0x24, 0x92, 0xb2, 0x2a, 0xbb, 0xac, 0x77, 0x27,
0xf3, 0x85, 0xdf, 0xf9, 0xce, 0x77, 0x66, 0xe0, 0x2c, 0x96, 0x32, 0xe6, 0xd4, 0x5f, 0xd2, 0x8d,
0x96, 0x92, 0xa7, 0x7e, 0x24, 0x85, 0x46, 0x26, 0xa8, 0x42, 0x81, 0x7c, 0x9b, 0xb2, 0xd4, 0xdf,
0x1c, 0x23, 0x4f, 0x56, 0x78, 0xec, 0x2f, 0x18, 0xe7, 0xa1, 0xfc, 0x18, 0xae, 0x51, 0x53, 0xc5,
0x90, 0xa7, 0x5e, 0xa2, 0xa4, 0x96, 0xe4, 0x71, 0xc1, 0xf0, 0x2a, 0x86, 0x77, 0x83, 0xe1, 0x55,
0x0c, 0xf7, 0xb0, 0xec, 0x87, 0x09, 0xf3, 0x51, 0x08, 0xa9, 0x51, 0x33, 0x29, 0x4a, 0x92, 0x7b,
0x71, 0x07, 0x37, 0x09, 0x46, 0xd7, 0x18, 0xd3, 0x70, 0x93, 0xf1, 0x5c, 0x5f, 0x30, 0xce, 0xf4,
0xb6, 0xe0, 0x1c, 0xfd, 0x68, 0x42, 0x77, 0x5a, 0xe8, 0xaf, 0x51, 0x60, 0x4c, 0x95, 0xfb, 0xdd,
0x86, 0xce, 0x39, 0x4b, 0xb5, 0x62, 0x8b, 0x2c, 0x6f, 0x49, 0x1e, 0x40, 0x2b, 0x4a, 0x68, 0x98,
0x29, 0xe6, 0x58, 0x7d, 0x6b, 0x70, 0x10, 0x34, 0xa3, 0x84, 0xce, 0x15, 0x23, 0xd7, 0xd0, 0x41,
0x15, 0xad, 0x98, 0xa6, 0x91, 0xce, 0x14, 0x75, 0xec, 0xbe, 0x35, 0xe8, 0x9e, 0x5c, 0x7a, 0xb7,
0x9f, 0xd2, 0xdb, 0xed, 0xed, 0x0d, 0x6b, 0xb8, 0x60, 0x07, 0x4e, 0x38, 0x74, 0x39, 0x6a, 0x9a,
0xea, 0x70, 0x43, 0x55, 0xca, 0xa4, 0x70, 0x1a, 0x7d, 0x6b, 0xd0, 0x3e, 0x19, 0xdf, 0xa5, 0xdd,
0x55, 0x3d, 0x82, 0xd9, 0x36, 0xa1, 0xde, 0x55, 0x01, 0x0b, 0xfe, 0x2f, 0xe0, 0xe5, 0x27, 0x79,
0x08, 0xb0, 0x46, 0x56, 0x72, 0x9c, 0x3d, 0x33, 0x76, 0xed, 0x84, 0xf4, 0xa0, 0x91, 0x29, 0xee,
0x34, 0x8d, 0x90, 0x97, 0xa4, 0x0f, 0xed, 0x25, 0x4d, 0x23, 0xc5, 0x92, 0x3c, 0x34, 0xa7, 0x65,
0x94, 0xfa, 0x91, 0xfb, 0xd5, 0x82, 0xfd, 0x57, 0x32, 0xc2, 0xbf, 0x87, 0x1a, 0x42, 0xab, 0x1a,
0xd0, 0xfe, 0x97, 0x03, 0x56, 0x54, 0x42, 0x60, 0x2f, 0x41, 0xbd, 0x32, 0xf1, 0x1d, 0x04, 0xa6,
0x76, 0x3f, 0x5b, 0xd0, 0x2a, 0x57, 0x91, 0xeb, 0x02, 0xd7, 0xb4, 0xb4, 0x65, 0xea, 0x7c, 0xd3,
0xcb, 0xda, 0x95, 0x70, 0xa0, 0xdf, 0x18, 0xb4, 0xef, 0xb5, 0xe9, 0xfa, 0x0d, 0x0b, 0x76, 0xe0,
0xee, 0x27, 0x0b, 0x3a, 0x13, 0x91, 0x6a, 0xe4, 0xbc, 0xc8, 0xea, 0x77, 0x8e, 0x42, 0xd8, 0xe7,
0x65, 0x96, 0x8e, 0x6d, 0xdc, 0x8c, 0xee, 0xe1, 0xa6, 0x5a, 0x4b, 0xf0, 0x0b, 0x7a, 0xf4, 0x02,
0x3a, 0xf5, 0xdb, 0x48, 0x0e, 0xc1, 0x19, 0x06, 0xa3, 0x97, 0x93, 0xd9, 0x78, 0x34, 0x9b, 0x07,
0xe3, 0x70, 0xfe, 0xe6, 0xed, 0x74, 0x3c, 0x9a, 0x5c, 0x4c, 0xc6, 0xe7, 0xbd, 0xff, 0x48, 0x0b,
0x1a, 0xef, 0x9e, 0x9d, 0xf6, 0x2c, 0x53, 0x9c, 0x3e, 0xed, 0xd9, 0x67, 0x5f, 0x2c, 0x78, 0x14,
0xc9, 0x75, 0x65, 0xea, 0xcf, 0x5e, 0xa6, 0xd6, 0xfb, 0x0f, 0xe5, 0x4f, 0xb1, 0xe4, 0x28, 0x62,
0x4f, 0xaa, 0xd8, 0x8f, 0xa9, 0x30, 0x2f, 0xd4, 0x2f, 0x24, 0x4c, 0x58, 0x7a, 0x9b, 0xc7, 0xfe,
0xfc, 0x86, 0xf4, 0xcd, 0x6e, 0x5c, 0x8e, 0x86, 0x8b, 0xa6, 0xa1, 0x3d, 0xf9, 0x19, 0x00, 0x00,
0xff, 0xff, 0xfa, 0x4f, 0xa4, 0x56, 0xc7, 0x04, 0x00, 0x00,
}
| object88/langd | vendor/google.golang.org/genproto/googleapis/devtools/containeranalysis/v1alpha1/bill_of_materials.pb.go | GO | mit | 16,890 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Jan Kuhl</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="/stylesheets/style.css" rel="stylesheet" type="text/css" />
<link href="/feed/atom.xml" rel="alternate" type="application/atom+xml" />
<script src="/javascripts/css_browser_selector.js" type="text/javascript"></script>
</head>
<body>
<div id="header">
<div class="inside">
<h2><a href="/">Jan Kuhl</a></h2>
<p class="description">Geschenk-, Schul- und Kinderbuchautor</p>
</div>
</div>
<div id="primary" class="single-post">
<div class="inside">
<h1>Gefundene Inhalte zu "Unterrichtsmaterialien"</h1>
</div>
<div class="inside">
<div class="secondary">
<div class="featured">
<dl>
<dt>Erstmals veröffentlicht:</dt>
<dd>05.02.05</dd>
</dl>
<dl>
<dt>Updated:</dt>
<dd>20.11.07</dd>
</dl>
<dl>
<dt>Kategorien:</dt>
<dd>
<a href="/buecher">Buchveröffentlichungen</a>
</dd>
</dl>
<dl>
<dt>Tags:</dt>
<dd>
<a href="/tags/Teaser:Schulbuch" rel="tag">Teaser:Schulbuch</a>
<a href="/tags/Teaser:Unterrichtsmaterialien" rel="tag">Teaser:Unterrichtsmaterialien</a>
</dd>
</dl>
</div>
</div>
<hr class="hide" />
<div class="primary story">
<h1><a href="/2005/2/5/koenig-fittipaldi-unterrichtsmaterialien">König Fittipaldi Unterrichtsmaterialien</a></h1>
<p><p>Jan Kuhl
Materialien zum Unterricht</p>
<p>Materialien zu:<br/>
Jan Kuhl: König Fittipaldi und das Zauberkissen<br/>
40 Seiten.<br/>
€ 6,50/sFr 12,50<br/>
ISBN 3-927655-70-8<br/>
Erscheinungstermin: März 2005 </p>
<p>Die Materialien zum Unterricht bieten viele Möglichkeiten des Einsatzes im Unterricht. Die vorgeschlagenen Ideen und die unterschiedlichen Arbeitsblätter können auch fächerübergreifend eingesetzt werden. Differenzierte Aufgaben geben Hilfe zur Erschließung der Texte.</p>
<iframe src="http://rcm-de.amazon.de/e/cm?t=drvolger-21&o=3&p=8&l=as1&asins=3927655708&fc1=000000&IS2=1<1=_blank&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe></p>
</div>
<div class="clear"></div>
</div>
<hr class="hide" />
<div class="inside">
<p>
</p>
</div>
</div>
<!-- [END] #primary -->
<hr class="hide" />
<div id="ancillary">
<div class="inside">
<div class="block first">
<h2>Zur Person</h2>
<img src="/images/jankuhl.png" align=left height=120>
<p>Jan Kuhl ist Geschenk-, Schul- und Kinderbuchautor. Im Rahmen der Leseförderung an Grundschulen führt er regelmäßig gemeinsam mit SchülerInnen Kinderbuchprojekte durch.
Er ist Träger des Marburger Literaturpreises Regio 2005.</p>
</div>
<div class="block">
<h2>Weitere aktuelle Themen</h2>
<ul class="dates">
<li>
<a href="/2008/6/1/neu-neu-neu">
<span class="date">
01.06.
</span>
Neu! Neu! Neu!
</a>
</li>
<li>
<a href="/2008/5/31/ein-blick-durch-die-rosarote-brille">
<span class="date">
31.05.
</span>
Ein Blick durch die rosarote Brille...
</a>
</li>
<li>
<a href="/2008/5/31/jan-kuhl-referiert-auf-dem-jako-o-familienkongress-2008">
<span class="date">
31.05.
</span>
Jan Kuhl referiert auf dem JAKO-O-Familienkongress 2008
</a>
</li>
<li>
<a href="/2008/5/28/harry-sucht-sally-auf-der-frankfurter-buchmesse">
<span class="date">
28.05.
</span>
"Harry sucht Sally" auf der Frankfurter Buchmesse
</a>
</li>
<li>
<a href="/2007/11/18/meine-neue-website-ist-online">
<span class="date">
18.11.
</span>
Neue Webseite ist online!
</a>
</li>
<li><a href="/feed/atom.xml">
<img src="/images/feed_icon32x32.png" align=right height=16>
Abonniere Feed</a></li>
</ul>
</div>
<div class="block">
<h2>Konkrete Informationen zu</h2>
<ul class="counts">
<li><a href="http://astore.amazon.de/jankuhl-21">Online Shop</a>
</li>
<li><a class="selected" href="/profil">Profil</a></li>
<li><a href="/buecher">Buchveröffentlichungen</a></li>
<li><a href="/projekte">Projekte</a></li>
<li><a href="/gedanken-zu-schule-und-lernen">Gedanken zu Schule und Lernen</a></li>
<li><a href="/mein-leben-als-autor">Mein Leben als Autor</a></li>
<li><a href="/auszeichnungen-und-preise">Auszeichnungen und Preise</a></li>
<li><a href="/fotogalarie">Fotogalerie</a></li>
<li><a href="/pressestimmen">Pressestimmen</a></li>
</ul>
</div>
<div class="block">
<!-- tagcloud -->
<h2>Suche nach Stichworten/ Tagcloud</h2>
<p style="overflow:hidden" class="tagcloud">
<span style='font-size: 1.18em'><a title='Auszeichnung (6)' href='/tags/Auszeichnung'>Auszeichnung</a></span>/
<span style='font-size: 1.04em'><a title='Buchmesse (2)' href='/tags/Buchmesse'>Buchmesse</a></span>/
<span style='font-size: 1.07em'><a title='Jan-Kuhl (3)' href='/tags/Jan-Kuhl'>Jan-Kuhl</a></span>/
<span style='font-size: 1.15em'><a title='König-Fittipaldi (5)' href='/tags/König-Fittipaldi'>König-Fittipaldi</a></span>/
<span style='font-size: 1.18em'><a title='Literaturpreis (6)' href='/tags/Literaturpreis'>Literaturpreis</a></span>/
<span style='font-size: 1.00em'><a title='Neue ars edition Reihen 2008 (1)' href='/tags/Neue ars edition Reihen 2008'>Neue ars edition Reihen 2008</a></span>/
<span style='font-size: 1.41em'><a title='Presse (12)' href='/tags/Presse'>Presse</a></span>/
<span style='font-size: 1.11em'><a title='Projekt:Kinderbuch (4)' href='/tags/Projekt:Kinderbuch'>Kinderbuch</a></span>/
<span style='font-size: 1.15em'><a title='Projekt:König-Fittipaldi (5)' href='/tags/Projekt:König-Fittipaldi'>König-Fittipaldi</a></span>/
<span style='font-size: 1.04em'><a title='Projekt:Lesung (2)' href='/tags/Projekt:Lesung'>Lesung</a></span>/
<span style='font-size: 1.07em'><a title='Schreiben-mit-Kindern (3)' href='/tags/Schreiben-mit-Kindern'>Schreiben-mit-Kindern</a></span>/
<span style='font-size: 1.70em'><a title='Teaser:Geschenkbuch (20)' href='/tags/Teaser:Geschenkbuch'>Geschenkbuch</a></span>/
<span style='font-size: 1.00em'><a title='Teaser:Kinderbuch (1)' href='/tags/Teaser:Kinderbuch'>Kinderbuch</a></span>/
<span style='font-size: 1.00em'><a title='Teaser:Schulbuch (1)' href='/tags/Teaser:Schulbuch'>Schulbuch</a></span>/
<span style='font-size: 1.00em'><a title='Teaser:Unterrichtsmaterialien (1)' href='/tags/Teaser:Unterrichtsmaterialien'>Unterrichtsmaterialien</a></span>/
</p>
<!-- search -->
<div id="search" class="search">
<form action="/search" id="sform" method="get" name="sform">
<p>
<input type="text" id="q" name="q" tag="Warten" value="Stichworte eingeben und bestätigen" />
</p>
</form>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<hr class="hide" />
<div id="footer">
<div class="inside">
<p>Copyright © 2004-2008 Jan Kuhl. All rights reserved.</p>
<p><a href="/profil/impressum">Impressum</a></p>
</div>
</div>
<!-- [END] #footer -->
</body>
</html>
| vaudoc/jk | public/tags/Teaser:Unterrichtsmaterialien.html | HTML | mit | 7,936 |
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization
//
// 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.
//
#ifndef APPLESEED_RENDERER_MODELING_ENVIRONMENTEDF_LATLONGMAPENVIRONMENTEDF_H
#define APPLESEED_RENDERER_MODELING_ENVIRONMENTEDF_LATLONGMAPENVIRONMENTEDF_H
// appleseed.renderer headers.
#include "renderer/modeling/environmentedf/ienvironmentedffactory.h"
// appleseed.foundation headers.
#include "foundation/platform/compiler.h"
#include "foundation/utility/autoreleaseptr.h"
// appleseed.main headers.
#include "main/dllsymbol.h"
// Forward declarations.
namespace foundation { class Dictionary; }
namespace foundation { class DictionaryArray; }
namespace renderer { class EnvironmentEDF; }
namespace renderer { class ParamArray; }
namespace renderer
{
//
// An environment EDF based on latitude-longitude environment maps.
//
class APPLESEED_DLLSYMBOL LatLongMapEnvironmentEDFFactory
: public IEnvironmentEDFFactory
{
public:
// Return a string identifying this environment EDF model.
const char* get_model() const override;
// Return metadata for this environment EDF model.
foundation::Dictionary get_model_metadata() const override;
// Return metadata for the inputs of this environment EDF model.
foundation::DictionaryArray get_input_metadata() const override;
// Create a new environment EDF instance.
foundation::auto_release_ptr<EnvironmentEDF> create(
const char* name,
const ParamArray& params) const override;
};
} // namespace renderer
#endif // !APPLESEED_RENDERER_MODELING_ENVIRONMENTEDF_LATLONGMAPENVIRONMENTEDF_H
| Aakash1312/appleseed | src/appleseed/renderer/modeling/environmentedf/latlongmapenvironmentedf.h | C | mit | 2,926 |
<!DOCTYPE html>
<HTML><head><TITLE>Manpage of PERF\-SCRIPT</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">
</head>
<body>
<header class="site-header">
<div class="wrap"> <div class="site-title"><a href="/manpages/index.html">linux manpages</a></div>
<div class="site-description">{"type":"documentation"}</div>
</div>
</header>
<div class="page-content"><div class="wrap">
<H1>PERF\-SCRIPT</H1>
Section: Misc. Reference Manual Pages (1)<BR>Updated: 10/16/2012<BR><A HREF="#index">Index</A>
<A HREF="/manpages/index.html">Return to Main Contents</A><HR>
<A NAME="lbAB"> </A>
<H2>NAME</H2>
perf-script - Read perf.data (created by perf record) and display trace output
<A NAME="lbAC"> </A>
<H2>SYNOPSIS</H2>
<P>
<PRE>
<I>perf script</I> [<options>]
<I>perf script</I> [<options>] record <script> [<record-options>] <command>
<I>perf script</I> [<options>] report <script> [script-args]
<I>perf script</I> [<options>] <script> <required-script-args> [<record-options>] <command>
<I>perf script</I> [<options>] <top-script> [script-args]
</PRE>
<A NAME="lbAD"> </A>
<H2>DESCRIPTION</H2>
<P>
This command reads the input file and displays the trace recorded.
<P>
There are several variants of perf script:
<P>
<DL COMPACT><DT><DD>
<PRE>
'perf script' to see a detailed trace of the workload that was
recorded.
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
You can also run a set of pre-canned scripts that aggregate and
summarize the raw trace data in various ways (the list of scripts is
available via 'perf script -l'). The following variants allow you to
record and run those scripts:
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
'perf script record <script> <command>' to record the events required
for 'perf script report'. <script> is the name displayed in the
output of 'perf script --list' i.e. the actual script name minus any
language extension. If <command> is not specified, the events are
recorded using the -a (system-wide) 'perf record' option.
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
'perf script report <script> [args]' to run and display the results
of <script>. <script> is the name displayed in the output of 'perf
trace --list' i.e. the actual script name minus any language
extension. The perf.data output from a previous run of 'perf script
record <script>' is used and should be present for this command to
succeed. [args] refers to the (mainly optional) args expected by
the script.
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
'perf script <script> <required-script-args> <command>' to both
record the events required for <script> and to run the <script>
using 'live-mode' i.e. without writing anything to disk. <script>
is the name displayed in the output of 'perf script --list' i.e. the
actual script name minus any language extension. If <command> is
not specified, the events are recorded using the -a (system-wide)
'perf record' option. If <script> has any required args, they
should be specified before <command>. This mode doesn't allow for
optional script args to be specified; if optional script args are
desired, they can be specified using separate 'perf script record'
and 'perf script report' commands, with the stdout of the record step
piped to the stdin of the report script, using the '-o -' and '-i -'
options of the corresponding commands.
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
'perf script <top-script>' to both record the events required for
<top-script> and to run the <top-script> using 'live-mode'
i.e. without writing anything to disk. <top-script> is the name
displayed in the output of 'perf script --list' i.e. the actual
script name minus any language extension; a <top-script> is defined
as any script name ending with the string 'top'.
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
[<record-options>] can be passed to the record steps of 'perf script
record' and 'live-mode' variants; this isn't possible however for
<top-script> 'live-mode' or 'perf script report' variants.
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
See the 'SEE ALSO' section for links to language-specific
information on how to write and run your own trace scripts.
</PRE>
</DL>
<A NAME="lbAE"> </A>
<H2>OPTIONS</H2>
<P>
<command>...
<DL COMPACT><DT><DD>
Any command you can specify in a shell.
</DL>
<P>
-D, --dump-raw-script=
<DL COMPACT><DT><DD>
Display verbose dump of the trace data.
</DL>
<P>
-L, --Latency=
<DL COMPACT><DT><DD>
Show latency attributes (irqs/preemption disabled, etc).
</DL>
<P>
-l, --list=
<DL COMPACT><DT><DD>
Display a list of available trace scripts.
</DL>
<P>
-s [<I>lang</I>], --script=
<DL COMPACT><DT><DD>
Process trace data with the given script ([lang]:script[.ext]). If the string
<I>lang</I>
is specified in place of a script name, a list of supported languages will be displayed instead.
</DL>
<P>
-g, --gen-script=
<DL COMPACT><DT><DD>
Generate perf-script.[ext] starter script for given language, using current perf.data.
</DL>
<P>
-a
<DL COMPACT><DT><DD>
Force system-wide collection. Scripts run without a <command> normally use -a by default, while scripts run with a <command> normally doncqt - this option allows the latter to be run in system-wide mode.
</DL>
<P>
-i, --input=
<DL COMPACT><DT><DD>
Input file name. (default: perf.data unless stdin is a fifo)
</DL>
<P>
-d, --debug-mode
<DL COMPACT><DT><DD>
Do various checks like samples ordering and lost events.
</DL>
<P>
-f, --fields
<DL COMPACT><DT><DD>
Comma separated list of fields to print. Options are: comm, tid, pid, time, cpu, event, trace, ip, sym, dso, addr. Field list can be prepended with the type, trace, sw or hw, to indicate to which event type the field list applies. e.g., -f sw:comm,tid,time,ip,sym and -f trace:time,cpu,trace
<P>
<DL COMPACT><DT><DD>
<PRE>
perf script -f <fields>
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
is equivalent to:
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
perf script -f trace:<fields> -f sw:<fields> -f hw:<fields>
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
i.e., the specified fields apply to all event types if the type string
is not given.
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
The arguments are processed in the order received. A later usage can
reset a prior request. e.g.:
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
-f trace: -f comm,tid,time,ip,sym
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
The first -f suppresses trace events (field list is ""), but then the
second invocation sets the fields to comm,tid,time,ip,sym. In this case a
warning is given to the user:
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
"Overriding previous field request for all events."
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
Alternativey, consider the order:
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
-f comm,tid,time,ip,sym -f trace:
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
The first -f sets the fields for all events and the second -f
suppresses trace events. The user is given a warning message about
the override, and the result of the above is that only S/W and H/W
events are displayed with the given fields.
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
For the 'wildcard' option if a user selected field is invalid for an
event type, a message is displayed to the user that the option is
ignored for that type. For example:
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
$ perf script -f comm,tid,trace
'trace' not valid for hardware events. Ignoring.
'trace' not valid for software events. Ignoring.
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
Alternatively, if the type is given an invalid field is specified it
is an error. For example:
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
perf script -v -f sw:comm,tid,trace
'trace' not valid for software events.
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
At this point usage is displayed, and perf-script exits.
</PRE>
</DL>
<P>
<DL COMPACT><DT><DD>
<PRE>
Finally, a user may not set fields to none for all event types.
i.e., -f "" is not allowed.
</PRE>
</DL>
</DL>
<P>
-k, --vmlinux=<file>
<DL COMPACT><DT><DD>
vmlinux pathname
</DL>
<P>
--kallsyms=<file>
<DL COMPACT><DT><DD>
kallsyms pathname
</DL>
<P>
--symfs=<directory>
<DL COMPACT><DT><DD>
Look for files with symbols relative to this directory.
</DL>
<P>
-G, --hide-call-graph
<DL COMPACT><DT><DD>
When printing symbols do not display call chain.
</DL>
<P>
-C, --cpu
<DL COMPACT><DT><DD>
Only report samples for the list of CPUs provided. Multiple CPUs can be provided as a comma-separated list with no space: 0,1. Ranges of CPUs are specified with -: 0-2. Default is to report samples on all CPUs.
</DL>
<P>
-c, --comms=
<DL COMPACT><DT><DD>
Only display events for these comms. CSV that understands
m[blue]<B><A HREF="file://filename">file://filename</A></B>m[]
entries.
</DL>
<P>
-I, --show-info
<DL COMPACT><DT><DD>
Display extended information about the perf.data file. This adds information which may be very large and thus may clutter the display. It currently includes: cpu and numa topology of the host system. It can only be used with the perf script report mode.
</DL>
<A NAME="lbAF"> </A>
<H2>SEE ALSO</H2>
<P>
<B><A HREF="/manpages/index.html?1+perf-record">perf-record</A></B>(1), <B><A HREF="http://localhost/cgi-bin/man/man2html?1+perf-script-perl">perf-script-perl</A></B>(1), <B><A HREF="http://localhost/cgi-bin/man/man2html?1+perf-script-python">perf-script-python</A></B>(1)
<P>
<HR>
<A NAME="index"> </A><H2>Index</H2>
<DL>
<DT><A HREF="#lbAB">NAME</A><DD>
<DT><A HREF="#lbAC">SYNOPSIS</A><DD>
<DT><A HREF="#lbAD">DESCRIPTION</A><DD>
<DT><A HREF="#lbAE">OPTIONS</A><DD>
<DT><A HREF="#lbAF">SEE ALSO</A><DD>
</DL>
<HR>
This document was created by
<A HREF="/manpages/index.html">man2html</A>,
using the manual pages.<BR>
Time: 05:29:07 GMT, December 24, 2015
</div></div>
</body>
</HTML>
| yuweijun/yuweijun.github.io | manpages/man1/perf-script.1.html | HTML | mit | 10,363 |
<?php
namespace yanivgal\Exceptions;
use Exception;
class CronomJobException extends Exception { } | yanivgal/Cronom | src/Exceptions/CronomJobException.php | PHP | mit | 101 |
/*
FreeRTOS V7.4.0 - Copyright (C) 2013 Real Time Engineers Ltd.
FEATURES AND PORTS ARE ADDED TO FREERTOS ALL THE TIME. PLEASE VISIT
http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
***************************************************************************
* *
* FreeRTOS tutorial books are available in pdf and paperback. *
* Complete, revised, and edited pdf reference manuals are also *
* available. *
* *
* Purchasing FreeRTOS documentation will not only help you, by *
* ensuring you get running as quickly as possible and with an *
* in-depth knowledge of how to use FreeRTOS, it will also help *
* the FreeRTOS project to continue with its mission of providing *
* professional grade, cross platform, de facto standard solutions *
* for microcontrollers - completely free of charge! *
* *
* >>> See http://www.FreeRTOS.org/Documentation for details. <<< *
* *
* Thank you for using FreeRTOS, and thank you for your support! *
* *
***************************************************************************
This file is part of the FreeRTOS distribution.
FreeRTOS is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License (version 2) as published by the
Free Software Foundation AND MODIFIED BY the FreeRTOS exception.
>>>>>>NOTE<<<<<< The modification to the GPL is included to allow you to
distribute a combined work that includes FreeRTOS without being obliged to
provide the source code for proprietary components outside of the FreeRTOS
kernel.
FreeRTOS 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
and the FreeRTOS license exception along with FreeRTOS; if not itcan be
viewed here: http://www.freertos.org/a00114.html and also obtained by
writing to Real Time Engineers Ltd., contact details for whom are available
on the FreeRTOS WEB site.
1 tab == 4 spaces!
***************************************************************************
* *
* Having a problem? Start by reading the FAQ "My application does *
* not run, what could be wrong?" *
* *
* http://www.FreeRTOS.org/FAQHelp.html *
* *
***************************************************************************
http://www.FreeRTOS.org - Documentation, books, training, latest versions,
license and Real Time Engineers Ltd. contact details.
http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
including FreeRTOS+Trace - an indispensable productivity tool, and our new
fully thread aware and reentrant UDP/IP stack.
http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High
Integrity Systems, who sell the code with commercial support,
indemnification and middleware, under the OpenRTOS brand.
http://www.SafeRTOS.com - High Integrity Systems also provide a safety
engineered and independently SIL3 certified version for use in safety and
mission critical applications that require provable dependability.
*/
/*
* main-blinky.c is included when the "Blinky" build configuration is used.
* main-full.c is included when the "Full" build configuration is used.
*
* main-full.c (this file) defines a comprehensive demo that creates many
* tasks, queues, semaphores and timers. It also demonstrates how Cortex-M3
* interrupts can interact with FreeRTOS tasks/timers.
*
* This project runs on the SK-FM3-100PMC evaluation board, which is populated
* with an MB9BF5006N Cortex-M3 based microcontroller.
*
* The main() Function:
* main() creates three demo specific software timers, one demo specific queue,
* and two demo specific tasks. It then creates a whole host of 'standard
* demo' tasks/queues/semaphores, before starting the scheduler. The demo
* specific tasks and timers are described in the comments here. The standard
* demo tasks are described on the FreeRTOS.org web site.
*
* The standard demo tasks provide no specific functionality. They are
* included to both test the FreeRTOS port, and provide examples of how the
* various FreeRTOS API functions can be used.
*
* This demo creates 43 tasks in total. If you want a simpler demo, use the
* Blinky build configuration.
*
* The Demo Specific Queue Send Task:
* The queue send task is implemented by the prvQueueSendTask() function in
* this file. prvQueueSendTask() sits in a loop that causes it to repeatedly
* block for 200 milliseconds, before sending the value 100 to the queue that
* was created within main(). Once the value is sent, the task loops back
* around to block for another 200 milliseconds.
*
* The Demo Specific Queue Receive Task:
* The queue receive task is implemented by the prvQueueReceiveTask() function
* in this file. prvQueueReceiveTask() sits in a loop that causes it to
* repeatedly attempt to read data from the queue that was created within
* main(). When data is received, the task checks the value of the data, and
* if the value equals the expected 100, toggles an LED in the 7 segment display
* (see the documentation page for this demo on the FreeRTOS.org site to see
* which LED is used). The 'block time' parameter passed to the queue receive
* function specifies that the task should be held in the Blocked state
* indefinitely to wait for data to be available on the queue. The queue
* receive task will only leave the Blocked state when the queue send task
* writes to the queue. As the queue send task writes to the queue every 200
* milliseconds, the queue receive task leaves the Blocked state every 200
* milliseconds, and therefore toggles the LED every 200 milliseconds.
*
* The Demo Specific LED Software Timer and the Button Interrupt:
* The user button SW2 is configured to generate an interrupt each time it is
* pressed. The interrupt service routine switches an LED on, and resets the
* LED software timer. The LED timer has a 5000 millisecond (5 second) period,
* and uses a callback function that is defined to just turn the LED off again.
* Therefore, pressing the user button will turn the LED on, and the LED will
* remain on until a full five seconds pass without the button being pressed.
* See the documentation page for this demo on the FreeRTOS.org web site to see
* which LED is used.
*
* The Demo Specific "Check" Callback Function:
* This is called each time the 'check' timer expires. The check timer
* callback function inspects all the standard demo tasks to see if they are
* all executing as expected. The check timer is initially configured to
* expire every three seconds, but will shorted this to every 500ms if an error
* is ever discovered. The check timer callback toggles the LED defined by
* the mainCHECK_LED definition each time it executes. Therefore, if LED
* mainCHECK_LED is toggling every three seconds, then no error have been found.
* If LED mainCHECK_LED is toggling every 500ms, then at least one errors has
* been found. The variable pcStatusMessage is set to a string that indicates
* which task reported an error. See the documentation page for this demo on
* the FreeRTOS.org web site to see which LED in the 7 segment display is used.
*
* The Demo Specific "Digit Counter" Callback Function:
* This is called each time the 'digit counter' timer expires. It causes the
* digits 0 to 9 to be displayed in turn as the first character of the two
* character display. The LEDs in the other digit of the two character
* display are used as general purpose LEDs, as described in this comment block.
*
* The Demo Specific Idle Hook Function:
* The idle hook function demonstrates how to query the amount of FreeRTOS heap
* space that is remaining (see vApplicationIdleHook() defined in this file).
*
* The Demo Specific Tick Hook Function:
* The tick hook function is used to test the interrupt safe software timer
* functionality.
*/
/* Kernel includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "timers.h"
/* Fujitsu drivers/libraries. */
#include "mb9bf506n.h"
#include "system_mb9bf50x.h"
/* Common demo includes. */
#include "partest.h"
#include "flash.h"
#include "BlockQ.h"
#include "death.h"
#include "blocktim.h"
#include "semtest.h"
#include "GenQTest.h"
#include "QPeek.h"
#include "recmutex.h"
#include "TimerDemo.h"
#include "comtest2.h"
#include "PollQ.h"
#include "countsem.h"
#include "dynamic.h"
/* The rate at which data is sent to the queue, specified in milliseconds, and
converted to ticks using the portTICK_RATE_MS constant. */
#define mainQUEUE_SEND_FREQUENCY_MS ( 200 / portTICK_RATE_MS )
/* The number of items the queue can hold. This is 1 as the receive task
will remove items as they are added, meaning the send task should always find
the queue empty. */
#define mainQUEUE_LENGTH ( 1 )
/* The LED toggled by the check timer callback function. This is an LED in the
second digit of the two digit 7 segment display. See the documentation page
for this demo on the FreeRTOS.org web site to see which LED this relates to. */
#define mainCHECK_LED 0x07UL
/* The LED toggle by the queue receive task. This is an LED in the second digit
of the two digit 7 segment display. See the documentation page for this demo on
the FreeRTOS.org web site to see which LED this relates to. */
#define mainTASK_CONTROLLED_LED 0x06UL
/* The LED turned on by the button interrupt, and turned off by the LED timer.
This is an LED in the second digit of the two digit 7 segment display. See the
documentation page for this demo on the FreeRTOS.org web site to see which LED
this relates to. */
#define mainTIMER_CONTROLLED_LED 0x05UL
/* The LED used by the comtest tasks. See the comtest.c file for more
information. The LEDs used by the comtest task are in the second digit of the
two digit 7 segment display. See the documentation page for this demo on the
FreeRTOS.org web site to see which LEDs this relates to. */
#define mainCOM_TEST_LED ( 3 )
/* Constant used by the standard timer test functions. */
#define mainTIMER_TEST_PERIOD ( 50 )
/* Priorities used by the various different standard demo tasks. */
#define mainCHECK_TASK_PRIORITY ( configMAX_PRIORITIES - 1 )
#define mainQUEUE_POLL_PRIORITY ( tskIDLE_PRIORITY + 1 )
#define mainSEM_TEST_PRIORITY ( tskIDLE_PRIORITY + 1 )
#define mainBLOCK_Q_PRIORITY ( tskIDLE_PRIORITY + 2 )
#define mainCREATOR_TASK_PRIORITY ( tskIDLE_PRIORITY + 3 )
#define mainFLASH_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 )
#define mainINTEGER_TASK_PRIORITY ( tskIDLE_PRIORITY )
#define mainGEN_QUEUE_TASK_PRIORITY ( tskIDLE_PRIORITY )
#define mainCOM_TEST_PRIORITY ( tskIDLE_PRIORITY + 2 )
/* Priorities defined in this main-full.c file. */
#define mainQUEUE_RECEIVE_TASK_PRIORITY ( tskIDLE_PRIORITY + 2 )
#define mainQUEUE_SEND_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 )
/* The period at which the check timer will expire, in ms, provided no errors
have been reported by any of the standard demo tasks. ms are converted to the
equivalent in ticks using the portTICK_RATE_MS constant. */
#define mainCHECK_TIMER_PERIOD_MS ( 3000UL / portTICK_RATE_MS )
/* The period at which the check timer will expire, in ms, if an error has been
reported in one of the standard demo tasks. ms are converted to the equivalent
in ticks using the portTICK_RATE_MS constant. */
#define mainERROR_CHECK_TIMER_PERIOD_MS ( 500UL / portTICK_RATE_MS )
/* The period at which the digit counter timer will expire, in ms, and converted
to ticks using the portTICK_RATE_MS constant. */
#define mainDIGIT_COUNTER_TIMER_PERIOD_MS ( 250UL / portTICK_RATE_MS )
/* The LED will remain on until the button has not been pushed for a full
5000ms. */
#define mainLED_TIMER_PERIOD_MS ( 5000UL / portTICK_RATE_MS )
/* A zero block time. */
#define mainDONT_BLOCK ( 0UL )
/* Baud rate used by the comtest tasks. */
#define mainCOM_TEST_BAUD_RATE ( 115200UL )
/*-----------------------------------------------------------*/
/*
* Setup the NVIC, LED outputs, and button inputs.
*/
static void prvSetupHardware( void );
/*
* The application specific (not common demo) tasks as described in the comments
* at the top of this file.
*/
static void prvQueueReceiveTask( void *pvParameters );
static void prvQueueSendTask( void *pvParameters );
/*
* The LED timer callback function. This does nothing but switch an LED off.
*/
static void prvLEDTimerCallback( xTimerHandle xTimer );
/*
* The check timer callback function, as described at the top of this file.
*/
static void prvCheckTimerCallback( xTimerHandle xTimer );
/*
* The digit counter callback function, as described at the top of this file.
*/
static void prvDigitCounterTimerCallback( xTimerHandle xTimer );
/*
* This is not a 'standard' partest function, so the prototype is not in
* partest.h, and is instead included here.
*/
void vParTestSetLEDFromISR( unsigned portBASE_TYPE uxLED, signed portBASE_TYPE xValue );
/*-----------------------------------------------------------*/
/* The queue used by both application specific demo tasks defined in this file. */
static xQueueHandle xQueue = NULL;
/* The LED software timer. This uses prvLEDTimerCallback() as it's callback
function. */
static xTimerHandle xLEDTimer = NULL;
/* The digit counter software timer. This displays a counting digit on one half
of the seven segment displays. */
static xTimerHandle xDigitCounterTimer = NULL;
/* The check timer. This uses prvCheckTimerCallback() as its callback
function. */
static xTimerHandle xCheckTimer = NULL;
/* If an error is detected in a standard demo task, then pcStatusMessage will
be set to point to a string that identifies the offending task. This is just
to make debugging easier. */
static const char *pcStatusMessage = NULL;
/*-----------------------------------------------------------*/
int main(void)
{
/* Configure the NVIC, LED outputs and button inputs. */
prvSetupHardware();
/* Create the queue. */
xQueue = xQueueCreate( mainQUEUE_LENGTH, sizeof( unsigned long ) );
if( xQueue != NULL )
{
/* Start the two application specific demo tasks, as described in the
comments at the top of this file. */
xTaskCreate( prvQueueReceiveTask, ( signed char * ) "Rx", configMINIMAL_STACK_SIZE, NULL, mainQUEUE_RECEIVE_TASK_PRIORITY, NULL );
xTaskCreate( prvQueueSendTask, ( signed char * ) "TX", configMINIMAL_STACK_SIZE, NULL, mainQUEUE_SEND_TASK_PRIORITY, NULL );
/* Create the software timer that is responsible for turning off the LED
if the button is not pushed within 5000ms, as described at the top of
this file. */
xLEDTimer = xTimerCreate( ( const signed char * ) "LEDTimer", /* A text name, purely to help debugging. */
( mainLED_TIMER_PERIOD_MS ), /* The timer period, in this case 5000ms (5s). */
pdFALSE, /* This is a one shot timer, so xAutoReload is set to pdFALSE. */
( void * ) 0, /* The ID is not used, so can be set to anything. */
prvLEDTimerCallback /* The callback function that switches the LED off. */
);
/* Create the software timer that performs the 'check' functionality,
as described at the top of this file. */
xCheckTimer = xTimerCreate( ( const signed char * ) "CheckTimer",/* A text name, purely to help debugging. */
( mainCHECK_TIMER_PERIOD_MS ), /* The timer period, in this case 3000ms (3s). */
pdTRUE, /* This is an auto-reload timer, so xAutoReload is set to pdTRUE. */
( void * ) 0, /* The ID is not used, so can be set to anything. */
prvCheckTimerCallback /* The callback function that inspects the status of all the other tasks. */
);
/* Create the software timer that performs the 'digit counting'
functionality, as described at the top of this file. */
xDigitCounterTimer = xTimerCreate( ( const signed char * ) "DigitCounter", /* A text name, purely to help debugging. */
( mainDIGIT_COUNTER_TIMER_PERIOD_MS ), /* The timer period, in this case 3000ms (3s). */
pdTRUE, /* This is an auto-reload timer, so xAutoReload is set to pdTRUE. */
( void * ) 0, /* The ID is not used, so can be set to anything. */
prvDigitCounterTimerCallback /* The callback function that inspects the status of all the other tasks. */
);
/* Create a lot of 'standard demo' tasks. Over 40 tasks are created in
this demo. For a much simpler demo, select the 'blinky' build
configuration. */
vStartBlockingQueueTasks( mainBLOCK_Q_PRIORITY );
vCreateBlockTimeTasks();
vStartSemaphoreTasks( mainSEM_TEST_PRIORITY );
vStartGenericQueueTasks( mainGEN_QUEUE_TASK_PRIORITY );
vStartLEDFlashTasks( mainFLASH_TASK_PRIORITY );
vStartQueuePeekTasks();
vStartRecursiveMutexTasks();
vStartTimerDemoTask( mainTIMER_TEST_PERIOD );
vAltStartComTestTasks( mainCOM_TEST_PRIORITY, mainCOM_TEST_BAUD_RATE, mainCOM_TEST_LED );
vStartPolledQueueTasks( mainQUEUE_POLL_PRIORITY );
vStartCountingSemaphoreTasks();
vStartDynamicPriorityTasks();
/* The suicide tasks must be created last, as they need to know how many
tasks were running prior to their creation in order to ascertain whether
or not the correct/expected number of tasks are running at any given
time. */
vCreateSuicidalTasks( mainCREATOR_TASK_PRIORITY );
/* Start the tasks and timer running. */
vTaskStartScheduler();
}
/* If all is well, the scheduler will now be running, and the following line
will never be reached. If the following line does execute, then there was
insufficient FreeRTOS heap memory available for the idle and/or timer tasks
to be created. See the memory management section on the FreeRTOS web site
for more details. */
for( ;; );
}
/*-----------------------------------------------------------*/
static void prvCheckTimerCallback( xTimerHandle xTimer )
{
/* Check the standard demo tasks are running without error. Latch the
latest reported error in the pcStatusMessage character pointer. */
if( xAreGenericQueueTasksStillRunning() != pdTRUE )
{
pcStatusMessage = "Error: GenQueue";
}
if( xAreQueuePeekTasksStillRunning() != pdTRUE )
{
pcStatusMessage = "Error: QueuePeek\r\n";
}
if( xAreBlockingQueuesStillRunning() != pdTRUE )
{
pcStatusMessage = "Error: BlockQueue\r\n";
}
if( xAreBlockTimeTestTasksStillRunning() != pdTRUE )
{
pcStatusMessage = "Error: BlockTime\r\n";
}
if( xAreSemaphoreTasksStillRunning() != pdTRUE )
{
pcStatusMessage = "Error: SemTest\r\n";
}
if( xIsCreateTaskStillRunning() != pdTRUE )
{
pcStatusMessage = "Error: Death\r\n";
}
if( xAreRecursiveMutexTasksStillRunning() != pdTRUE )
{
pcStatusMessage = "Error: RecMutex\r\n";
}
if( xAreComTestTasksStillRunning() != pdPASS )
{
pcStatusMessage = "Error: ComTest\r\n";
}
if( xAreTimerDemoTasksStillRunning( ( mainCHECK_TIMER_PERIOD_MS ) ) != pdTRUE )
{
pcStatusMessage = "Error: TimerDemo";
}
if( xArePollingQueuesStillRunning() != pdTRUE )
{
pcStatusMessage = "Error: PollQueue";
}
if( xAreCountingSemaphoreTasksStillRunning() != pdTRUE )
{
pcStatusMessage = "Error: CountSem";
}
if( xAreDynamicPriorityTasksStillRunning() != pdTRUE )
{
pcStatusMessage = "Error: DynamicPriority";
}
/* Toggle the check LED to give an indication of the system status. If
the LED toggles every mainCHECK_TIMER_PERIOD_MS milliseconds then
everything is ok. A faster toggle indicates an error. */
vParTestToggleLED( mainCHECK_LED );
/* Have any errors been latch in pcStatusMessage? If so, shorten the
period of the check timer to mainERROR_CHECK_TIMER_PERIOD_MS milliseconds.
This will result in an increase in the rate at which mainCHECK_LED
toggles. */
if( pcStatusMessage != NULL )
{
/* This call to xTimerChangePeriod() uses a zero block time. Functions
called from inside of a timer callback function must *never* attempt
to block. */
xTimerChangePeriod( xCheckTimer, ( mainERROR_CHECK_TIMER_PERIOD_MS ), mainDONT_BLOCK );
}
}
/*-----------------------------------------------------------*/
static void prvLEDTimerCallback( xTimerHandle xTimer )
{
/* The timer has expired - so no button pushes have occurred in the last
five seconds - turn the LED off. */
vParTestSetLED( mainTIMER_CONTROLLED_LED, pdFALSE );
}
/*-----------------------------------------------------------*/
static void prvDigitCounterTimerCallback( xTimerHandle xTimer )
{
/* Define the bit patterns that display numbers on the seven segment display. */
static const unsigned short usNumbersPatterns[] = { 0xC000U, 0xF900U, 0xA400U, 0xB000U, 0x9900U, 0x9200U, 0x8200U, 0xF800U, 0x8000U, 0x9000U };
static long lCounter = 0L;
const long lNumberOfDigits = 10L;
/* Display the next number, counting up. */
FM3_GPIO->PDOR1 = usNumbersPatterns[ lCounter ];
/* Move onto the next digit. */
lCounter++;
/* Ensure the counter does not go off the end of the array. */
if( lCounter >= lNumberOfDigits )
{
lCounter = 0L;
}
}
/*-----------------------------------------------------------*/
/* The ISR executed when the user button is pushed. */
void INT0_7_Handler( void )
{
portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;
/* The button was pushed, so ensure the LED is on before resetting the
LED timer. The LED timer will turn the LED off if the button is not
pushed within 5000ms. */
vParTestSetLEDFromISR( mainTIMER_CONTROLLED_LED, pdTRUE );
/* This interrupt safe FreeRTOS function can be called from this interrupt
because the interrupt priority is below the
configMAX_SYSCALL_INTERRUPT_PRIORITY setting in FreeRTOSConfig.h. */
xTimerResetFromISR( xLEDTimer, &xHigherPriorityTaskWoken );
/* Clear the interrupt before leaving. This just clears all the interrupts
for simplicity, as only one is actually used in this simple demo anyway. */
FM3_EXTI->EICL = 0x0000;
/* If calling xTimerResetFromISR() caused a task (in this case the timer
service/daemon task) to unblock, and the unblocked task has a priority
higher than or equal to the task that was interrupted, then
xHigherPriorityTaskWoken will now be set to pdTRUE, and calling
portEND_SWITCHING_ISR() will ensure the unblocked task runs next. */
portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
}
/*-----------------------------------------------------------*/
static void prvQueueSendTask( void *pvParameters )
{
portTickType xNextWakeTime;
const unsigned long ulValueToSend = 100UL;
/* The timer command queue will have been filled when the timer test tasks
were created in main() (this is part of the test they perform). Therefore,
while the check and digit counter timers can be created in main(), they
cannot be started from main(). Once the scheduler has started, the timer
service task will drain the command queue, and now the check and digit
counter timers can be started successfully. */
xTimerStart( xCheckTimer, portMAX_DELAY );
xTimerStart( xDigitCounterTimer, portMAX_DELAY );
/* Initialise xNextWakeTime - this only needs to be done once. */
xNextWakeTime = xTaskGetTickCount();
for( ;; )
{
/* Place this task in the blocked state until it is time to run again.
The block time is specified in ticks, the constant used converts ticks
to ms. While in the Blocked state this task will not consume any CPU
time. */
vTaskDelayUntil( &xNextWakeTime, mainQUEUE_SEND_FREQUENCY_MS );
/* Send to the queue - causing the queue receive task to unblock and
toggle an LED. 0 is used as the block time so the sending operation
will not block - it shouldn't need to block as the queue should always
be empty at this point in the code. */
xQueueSend( xQueue, &ulValueToSend, mainDONT_BLOCK );
}
}
/*-----------------------------------------------------------*/
static void prvQueueReceiveTask( void *pvParameters )
{
unsigned long ulReceivedValue;
for( ;; )
{
/* Wait until something arrives in the queue - this task will block
indefinitely provided INCLUDE_vTaskSuspend is set to 1 in
FreeRTOSConfig.h. */
xQueueReceive( xQueue, &ulReceivedValue, portMAX_DELAY );
/* To get here something must have been received from the queue, but
is it the expected value? If it is, toggle the LED. */
if( ulReceivedValue == 100UL )
{
vParTestToggleLED( mainTASK_CONTROLLED_LED );
}
}
}
/*-----------------------------------------------------------*/
static void prvSetupHardware( void )
{
const unsigned short usButtonInputBit = 0x01U;
SystemInit();
SystemCoreClockUpdate();
/* Initialise the IO used for the LEDs on the 7 segment displays. */
vParTestInitialise();
/* Set the switches to input (P18->P1F). */
FM3_GPIO->DDR5 = 0x0000;
FM3_GPIO->PFR5 = 0x0000;
/* Assign the button input as GPIO. */
FM3_GPIO->PFR1 |= usButtonInputBit;
/* Button interrupt on falling edge. */
FM3_EXTI->ELVR = 0x0003;
/* Clear all external interrupts. */
FM3_EXTI->EICL = 0x0000;
/* Enable the button interrupt. */
FM3_EXTI->ENIR |= usButtonInputBit;
/* Setup the GPIO and the NVIC for the switch used in this simple demo. */
NVIC_SetPriority( EXINT0_7_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY );
NVIC_EnableIRQ( EXINT0_7_IRQn );
}
/*-----------------------------------------------------------*/
void vApplicationMallocFailedHook( void )
{
/* Called if a call to pvPortMalloc() fails because there is insufficient
free memory available in the FreeRTOS heap. pvPortMalloc() is called
internally by FreeRTOS API functions that create tasks, queues, software
timers, and semaphores. The size of the FreeRTOS heap is set by the
configTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. */
for( ;; );
}
/*-----------------------------------------------------------*/
void vApplicationStackOverflowHook( xTaskHandle pxTask, signed char *pcTaskName )
{
( void ) pcTaskName;
( void ) pxTask;
/* Run time stack overflow checking is performed if
configconfigCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook
function is called if a stack overflow is detected. */
taskDISABLE_INTERRUPTS();
for( ;; );
}
/*-----------------------------------------------------------*/
void vApplicationIdleHook( void )
{
volatile size_t xFreeStackSpace;
/* This function is called on each cycle of the idle task. In this case it
does nothing useful, other than report the amount of FreeRTOS heap that
remains unallocated. */
xFreeStackSpace = xPortGetFreeHeapSize();
if( xFreeStackSpace > 100 )
{
/* By now, the kernel has allocated everything it is going to, so
if there is a lot of heap remaining unallocated then
the value of configTOTAL_HEAP_SIZE in FreeRTOSConfig.h can be
reduced accordingly. */
}
}
/*-----------------------------------------------------------*/
void vApplicationTickHook( void )
{
/* Call the periodic timer test, which tests the timer API functions that
can be called from an ISR. */
vTimerPeriodicISRTests();
}
/*-----------------------------------------------------------*/
| andyOsaft/02_SourceCode | freeRTOS/FreeRTOSV7.4.0/FreeRTOSV7.4.0/FreeRTOS/Demo/CORTEX_MB9B500_IAR_Keil/main-full.c | C | mit | 28,151 |
module Fonenode
class SmsOutbox < SmsList
def initialize(client)
super(client)
@path = "sms/outbox"
@box_type = Sms::OUTBOUND
end
end
end | digitalnatives/fonenode | lib/fonenode/sms_outbox.rb | Ruby | mit | 169 |
import {Response} from './Response';
import {Settlement} from './Settlement';
export interface ReportResponse extends Response {
settlements: Settlement[];
}
| solinor/paymenthighway-javascript-lib | ts/src/model/response/ReportResponse.ts | TypeScript | mit | 163 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>VSTGUI: Class Members</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.4.5 -->
<div class="tabs">
<ul>
<li><a href="main.html"><span>Main Page</span></a></li>
<li id="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
</ul></div>
<div class="tabs">
<ul>
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li id="current"><a href="functions.html"><span>Class Members</span></a></li>
</ul></div>
<div class="tabs">
<ul>
<li id="current"><a href="functions.html"><span>All</span></a></li>
<li><a href="functions_func.html"><span>Functions</span></a></li>
<li><a href="functions_vars.html"><span>Variables</span></a></li>
<li><a href="functions_eval.html"><span>Enumerator</span></a></li>
<li><a href="functions_rela.html"><span>Related Functions</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="functions.html#index_a"><span>a</span></a></li>
<li><a href="functions_0x62.html#index_b"><span>b</span></a></li>
<li><a href="functions_0x63.html#index_c"><span>c</span></a></li>
<li><a href="functions_0x64.html#index_d"><span>d</span></a></li>
<li><a href="functions_0x65.html#index_e"><span>e</span></a></li>
<li><a href="functions_0x66.html#index_f"><span>f</span></a></li>
<li><a href="functions_0x67.html#index_g"><span>g</span></a></li>
<li><a href="functions_0x68.html#index_h"><span>h</span></a></li>
<li id="current"><a href="functions_0x69.html#index_i"><span>i</span></a></li>
<li><a href="functions_0x6b.html#index_k"><span>k</span></a></li>
<li><a href="functions_0x6c.html#index_l"><span>l</span></a></li>
<li><a href="functions_0x6d.html#index_m"><span>m</span></a></li>
<li><a href="functions_0x6e.html#index_n"><span>n</span></a></li>
<li><a href="functions_0x6f.html#index_o"><span>o</span></a></li>
<li><a href="functions_0x70.html#index_p"><span>p</span></a></li>
<li><a href="functions_0x72.html#index_r"><span>r</span></a></li>
<li><a href="functions_0x73.html#index_s"><span>s</span></a></li>
<li><a href="functions_0x74.html#index_t"><span>t</span></a></li>
<li><a href="functions_0x75.html#index_u"><span>u</span></a></li>
<li><a href="functions_0x76.html#index_v"><span>v</span></a></li>
<li><a href="functions_0x77.html#index_w"><span>w</span></a></li>
<li><a href="functions_0x78.html#index_x"><span>x</span></a></li>
<li><a href="functions_0x79.html#index_y"><span>y</span></a></li>
<li><a href="functions_0x7a.html#index_z"><span>z</span></a></li>
<li><a href="functions_0x7e.html#index_~"><span>~</span></a></li>
</ul>
</div>
<p>
Here is a list of all class members with links to the classes they belong to:
<p>
<h3><a class="anchor" name="index_i">- i -</a></h3><ul>
<li>id
: <a class="el" href="class_c_attribute_list_entry.html#b80bb7740288fda1f201890375a60c8f">CAttributeListEntry</a><li>idle()
: <a class="el" href="class_c_frame.html#83c70dfe6f63608e7a744ade05b027a9">CFrame</a>, <a class="el" href="class_plugin_g_u_i_editor.html#83c70dfe6f63608e7a744ade05b027a9">PluginGUIEditor</a>, <a class="el" href="class_a_eff_g_u_i_editor.html#83c70dfe6f63608e7a744ade05b027a9">AEffGUIEditor</a><li>iMaxPositions
: <a class="el" href="class_c_horizontal_switch.html#8b7788e9cc34b87d9a87edda82aa0c64">CHorizontalSwitch</a>, <a class="el" href="class_c_vertical_switch.html#8b7788e9cc34b87d9a87edda82aa0c64">CVerticalSwitch</a><li>inactiveTextColor
: <a class="el" href="class_c_tab_button.html#854e88dc82066d611e95235e9c652a64">CTabButton</a><li>inIdleStuff
: <a class="el" href="class_a_eff_g_u_i_editor.html#638794b08c00f9976403b4a5a22a2eb1">AEffGUIEditor</a><li>initFrame()
: <a class="el" href="class_c_frame.html#f9e4a0550ea9f6850b07f151aa95fc70">CFrame</a><li>initialPath
: <a class="el" href="struct_vst_file_select.html#46ee259bd7c37faa9a164bdf64f3cf6b">VstFileSelect</a><li>inset
: <a class="el" href="struct_c_rect.html#a89e199ff422c4a10702d45cb1c22cb1">CRect</a>, <a class="el" href="class_c_knob.html#99f74c03db9bc34e90ad3ede856995d3">CKnob</a><li>iNumbers
: <a class="el" href="class_c_special_digit.html#98b7973e2061d4b71133f353446a9a89">CSpecialDigit</a><li>invalidate()
: <a class="el" href="class_c_frame.html#019d8557ba2887c742e2776a06fa225d">CFrame</a><li>isCheckEntry()
: <a class="el" href="class_c_option_menu.html#78032dd2868ba69c91e5d9c7a0d25244">COptionMenu</a><li>isChild()
: <a class="el" href="class_c_view_container.html#253c108cfa5b1491e08f6ca0b2a6b77d">CViewContainer</a><li>isDirty()
: <a class="el" href="class_c_view_container.html#985382ac7111983e84cad27c0e47678f">CViewContainer</a>, <a class="el" href="class_c_view.html#985382ac7111983e84cad27c0e47678f">CView</a>, <a class="el" href="class_c_anim_knob.html#985382ac7111983e84cad27c0e47678f">CAnimKnob</a>, <a class="el" href="class_c_control.html#985382ac7111983e84cad27c0e47678f">CControl</a>, <a class="el" href="class_c_scroll_container.html#985382ac7111983e84cad27c0e47678f">CScrollContainer</a><li>isDoubleClick()
: <a class="el" href="class_c_control.html#a85cd88c0fe5782021d764038438bddf">CControl</a><li>isDropActive()
: <a class="el" href="class_c_frame.html#2cc1b0a705274a3d46c7a576126c359b">CFrame</a><li>isEmpty()
: <a class="el" href="struct_c_rect.html#9b3cd1fdd55d4ab99ca25647cb9d9672">CRect</a><li>isInside()
: <a class="el" href="struct_c_point.html#faf455806733f2f9c2912c52ea73b2b1">CPoint</a><li>isLoaded()
: <a class="el" href="class_c_bitmap.html#da596d61be0206f0418a7e6cd93baff9">CBitmap</a><li>isOpen()
: <a class="el" href="class_c_frame.html#b44117b31240bf82589e247ecd9fc53c">CFrame</a><li>isTypeOf()
: <a class="el" href="class_c_view.html#4def90ae4cb200341732f501c8cd6fd0">CView</a><li>isWindowOpened()
: <a class="el" href="class_c_auto_animation.html#f26a8994347c3d4887449717007b6e5c">CAutoAnimation</a><li>iterator
: <a class="el" href="class_c_drag_container.html#420cec00303cf5ff3ee30bf824fc1427">CDragContainer</a></ul>
<html>
<head>
<title>Empty</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Author" content="mario">
</head>
<body>
<br/>
<hr width="100%" size="2" align="left" />
<div align=left>
Copyright ©2006 <a href="http://www.steinberg.net" target="_blank"><u>Steinberg Media Technologies</u></a>.
All Rights Reserved.
</div>
</body>
</html>
| deepakgopinath/PpmAssignment | 3rdPartyLibs/vstsdk2.4/vstgui.sf/vstgui/Documentation/html/functions_0x69.html | HTML | mit | 6,836 |
'use strict';
// Proxy URL (optional)
const proxyUrl = 'drupal.dev';
// API keys
const TINYPNG_KEY = '';
// fonts
const fontList = [];
// vendors
const jsVendorList = [];
const cssVendorList = [];
// paths to relevant directories
const dirs = {
src: './src',
dest: './dist'
};
// paths to file sources
const sources = {
js: `${dirs.src}/**/*.js`,
scss: `${dirs.src}/**/*.scss`,
coreScss: `${dirs.src}/scss/main.scss`,
img: `./img/**/*.{png,jpg}`,
font: fontList,
jsVendor: jsVendorList,
cssVendor: cssVendorList
};
// paths to file destinations
const dests = {
js: `${dirs.dest}/js`,
css: `${dirs.dest}/css`,
img: `${dirs.dest}/img`,
sigFile: `./img/.tinypng-sigs`,
font: `${dirs.dest}/fonts`,
vendor: `${dirs.dest}/vendors`
};
// plugins
import gulp from 'gulp';
import browserSync from 'browser-sync';
import gulpLoadPlugins from 'gulp-load-plugins';
// auto-load plugins
const $ = gulpLoadPlugins();
/****************************************
Gulp Tasks
*****************************************/
// launch browser sync as a standalone local server
gulp.task('browser-sync-local', browserSyncLocal());
// browser-sync task for starting the server by proxying a local url
gulp.task('browser-sync-proxy', browserSyncProxy());
// copy vendor CSS
gulp.task('css-vendors', cssVendors());
// copy fonts
gulp.task('fonts', fonts());
// Lint Javascript Task
gulp.task('js-lint', javascriptLint());
// Concatenate and Minify Vendor JS
gulp.task('js-vendors', javascriptVendors());
// lint sass task
gulp.task('sass-lint', sassLint());
// Concatenate & Minify JS
gulp.task('scripts', ['js-lint'], scripts());
// compile, prefix, and minify the sass
gulp.task('styles', styles());
// compress and combine svg icons
gulp.task('svg', svg());
// Unit testing
gulp.task('test', test());
// compress png and jpg images via tinypng API
gulp.task('tinypng', tinypng());
// Watch Files For Changes
gulp.task('watch', watch());
// default task builds src, opens up a standalone server, and watches for changes
gulp.task('default', [
'fonts',
'styles',
'scripts',
'browser-sync-local',
'watch'
]);
// local task builds src, opens up a standalone server, and watches for changes
gulp.task('local', [
'fonts',
'styles',
'scripts',
'browser-sync-local',
'watch'
]);
// proxy task builds src, opens up a proxy server, and watches for changes
gulp.task('proxy', [
'fonts',
'styles',
'scripts',
'browser-sync-proxy',
'watch'
]);
// builds everything
gulp.task('build', [
'fonts',
'styles',
'scripts',
'css-vendors',
'js-vendors'
]);
// builds the vendor files
gulp.task('vendors', [
'css-vendors',
'js-vendors'
]);
// compresses imagery
gulp.task('images', [
'svg',
'tinypng'
]);
/****************************************
Task Logic
*****************************************/
function browserSyncLocal () {
return () => {
browserSync.init({
server: '../../../../'
});
};
}
function browserSyncProxy () {
return () => {
browserSync.init({
proxy: proxyUrl
});
};
}
function cssVendors () {
return () => {
return gulp.src(sources.cssVendor)
.pipe(gulp.dest(dests.vendor));
};
}
function fonts () {
return () => {
gulp.src(sources.font)
.pipe(gulp.dest(dests.font));
};
}
function javascriptLint () {
return () => {
return gulp.src(sources.js)
.pipe($.jshint({esversion: 6}))
.pipe($.jshint.reporter('jshint-stylish'));
};
}
function javascriptVendors () {
return () => {
return gulp.src(sources.jsVendor)
.pipe($.plumber())
.pipe($.concat('vendors.min.js'))
.pipe($.uglify())
.pipe(gulp.dest(dests.vendor));
};
}
function sassLint () {
return () => {
return gulp.src(sources.scss)
.pipe($.sassLint())
.pipe($.sassLint.format())
.pipe($.sassLint.failOnError());
};
}
function scripts () {
return () => {
return gulp.src(sources.js)
.pipe($.plumber())
.pipe($.sourcemaps.init())
.pipe($.concat('main.js'))
.pipe($.babel())
.pipe(gulp.dest(dests.js))
.pipe($.rename({suffix: '.min'}))
.pipe($.uglify())
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest(dests.js))
.pipe(browserSync.stream());
};
}
function styles () {
return () => {
return gulp.src(sources.coreScss)
.pipe($.sourcemaps.init())
.pipe($.sass().on('error', $.sass.logError))
.pipe($.autoprefixer(["> 1%", "last 2 versions"], { cascade: true }))
.pipe(gulp.dest(dests.css))
.pipe($.rename({suffix: '.min'}))
.pipe($.cleanCss())
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest(dests.css))
.pipe(browserSync.stream());
};
}
function svg () {
return () => {
return gulp.src('./img/icons/*.svg')
.pipe($.svgmin())
.pipe($.svgstore())
.pipe(gulp.dest('./img/icons'));
};
}
function test (done) {
return () => {
let server = new karma.Server('./karma.conf.js', done);
server.start();
};
}
function tinypng () {
return () => {
return gulp.src(sources.img)
.pipe($.tinypngCompress({
key: TINYPNG_KEY,
sigFile: dests.sigFile
}))
.pipe(gulp.dest(dests.img));
};
}
function watch () {
return () => {
gulp.watch(sources.js, ['scripts']);
gulp.watch(sources.scss, ['styles']);
gulp.watch('**/*.php', browserSync.reload);
};
}
| TricomB2B/tricom-drupal-7-base | gulpfile.babel.js | JavaScript | mit | 5,441 |
#ifndef FSM_CONSTS_H_INCLUDED
#define FSM_CONSTS_H_INCLUDED
// this is terible
const char matches[] = {
'\0', // 0
'\0',
'\0',
'\0',
'\0',
'\0', // 5
'\0',
'\0',
'\0',
'\0',
'\0', // 10
'\0',
'\0',
'\0',
'\0',
'\0', // 15
'\0',
'\0',
'\0',
'\0',
'\0', // 20
'\0',
'\0',
'\0',
'\0',
'\0', // 25
'\0',
'\0',
'\0',
'\0',
'\0', // 30
'\0',
'\0',
'\0',
'"',
'\0', // 35
'\0',
'\0',
'\0',
'\'',
')', // 40
'(',
'\0',
'\0',
'\0',
'\0', // 45
'\0',
'\0',
'\0',
'\0',
'\0', // 50
'\0',
'\0',
'\0',
'\0',
'\0', // 55
'\0',
'\0',
'\0',
'\0',
'>', // 60
'\0',
'<',
'\0',
'\0',
'\0', // 65
'\0',
'\0',
'\0',
'\0',
'\0', // 70
'\0',
'\0',
'\0',
'\0',
'\0', // 75
'\0',
'\0',
'\0',
'\0',
'\0', // 80
'\0',
'\0',
'\0',
'\0',
'\0', // 85
'\0',
'\0',
'\0',
'\0',
'\0', // 90
']',
'\0',
'[',
'\0',
'\0', // 95
'\0',
'\0',
'\0',
'\0',
'\0', // 100
'\0',
'\0',
'\0',
'\0',
'\0', // 105
'\0',
'\0',
'\0',
'\0',
'\0', // 110
'\0',
'\0',
'\0',
'\0',
'\0', // 115
'\0',
'\0',
'\0',
'\0',
'\0', // 120
'\0',
'\0',
'}',
'\0',
'{', // 125
'\0',
'\0',
};
#endif//FSM_CONSTS_H_INCLUDED
| floomby/assembler-assembler | fsm_consts.h | C | mit | 1,682 |
/*
* Copyright (c) 2014 Stephan D. Cote' - All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the MIT License which accompanies this distribution, and is
* available at http://creativecommons.org/licenses/MIT/
*
* Contributors:
* Stephan D. Cote
* - Initial concept and implementation
*/
package coyote.i13n;
//import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.AfterClass;
import org.junit.Test;
/**
*
*/
public class EventListTest {
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {}
/**
* Test method for {@link coyote.i13n.EventList#lastSequence()}.
*/
//@Test
public void testLastSequence() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#EventList()}.
*/
//@Test
public void testEventList() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#getMaxEvents()}.
*/
@Test
public void testGetMaxEvents() {
EventList list = new EventList();
list.setMaxEvents( 5 );
AppEvent alert0 = list.createEvent( "Zero" );
AppEvent alert1 = list.createEvent( "One" );
AppEvent alert2 = list.createEvent( "Two" );
AppEvent alert3 = list.createEvent( "Three" );
AppEvent alert4 = list.createEvent( "Four" );
AppEvent alert5 = list.createEvent( "Five" );
AppEvent alert6 = list.createEvent( "Six" );
//System.out.println( "Max="+list.getMaxEvents()+" Size=" + list.getSize() );
assertTrue( list._list.size() == 5 );
// should result in the list being trimmed immediately
list.setMaxEvents( 2 );
assertTrue( list._list.size() == 2 );
list.add( alert0 );
list.add( alert1 );
list.add( alert2 );
list.add( alert3 );
list.add( alert4 );
list.add( alert5 );
list.add( alert6 );
// should still only contain 2 events
assertTrue( list._list.size() == 2 );
// Check the first and last event in the list
assertEquals( alert5, list.getFirst() );
assertEquals( alert6, list.getLast() );
}
/**
* Test method for {@link coyote.i13n.EventList#setMaxEvents(int)}.
*/
//@Test
public void testSetMaxEvents() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#add(coyote.i13n.AppEvent)}.
*/
//@Test
public void testAdd() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#remove(coyote.i13n.AppEvent)}.
*/
//@Test
public void testRemove() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#get(long)}.
*/
//@Test
public void testGet() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#getFirst()}.
*/
//@Test
public void testGetFirst() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#getLast()}.
*/
//@Test
public void testGetLast() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#getSize()}.
*/
//@Test
public void testGetSize() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#createEvent(java.lang.String, java.lang.String, java.lang.String, java.lang.String, int, int, int, java.lang.String)}.
*/
//@Test
public void testCreateEventStringStringStringStringIntIntIntString() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#createEvent(java.lang.String)}.
*/
//@Test
public void testCreateEventString() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#createEvent(java.lang.String, int, int)}.
*/
//@Test
public void testCreateEventStringIntInt() {
fail( "Not yet implemented" );
}
}
| sdcote/loader | src/test/java/coyote/i13n/EventListTest.java | Java | mit | 4,336 |
<?php
/*
* This File is part of the Lucid\Common\Data package
*
* (c) iwyg <mail@thomas-appel.com>
*
* For full copyright and license information, please refer to the LICENSE file
* that was distributed with this package.
*/
namespace Lucid\Common\Struct;
use SplPriorityQueue;
/**
* @class PriorityQueue
* @see \SplPriorityQueue
*
* @package Lucid\Common\Data
* @version $Id$
* @author iwyg <mail@thomas-appel.com>
*/
class PriorityQueue extends SplPriorityQueue
{
/**
* queueOrder
*
* @var int
*/
private $queueOrder;
/**
* Constructor.
*/
public function __construct()
{
$this->queueOrder = PHP_INT_MAX;
}
/**
* {@inheritdoc}
*/
public function insert($datum, $priority)
{
if (is_int($priority)) {
$priority = [$priority, $this->queueOrder--];
}
parent::insert($datum, $priority);
}
}
| iwyg/common | src/Struct/PriorityQueue.php | PHP | mit | 933 |
'use strict';
const debug = require('debug')('WechatController');
const EventEmitter = require('events').EventEmitter;
const Cache = require('../../service/Cache');
const Wechat = require('../../service/Wechat');
const config = require('../../config');
const _ = require('lodash');
const async = require('async');
/* 微信公众平台连接认证 */
exports.wechatValidation = function (req, res, next) {
let signature = req.query.signature;
let timestamp = req.query.timestamp;
let nonce = req.query.nonce;
let echostr = req.query.echostr;
let flag = Wechat.validateSignature(signature, timestamp, nonce);
if (flag) return res.send(echostr);
else return res.send({success: false});
};
/* 更新access token */
exports.updateAccessToken = function (req, res, next) {
Wechat.updateAccessToken();
res.send('updateAccessToken');
};
/* 接收来自微信的消息推送 */
exports.processWechatEvent = function (req, res, next) {
let content = req.body.xml;
console.log('Event received. Event: %s', JSON.stringify(content));
res.send('success');
if(!content) return;
try {
let fromOpenId = content.FromUserName[0],
toOpenId = content.ToUserName[0],
createTime = content.CreateTime[0],
event = content.Event ? content.Event[0] : "",
eventKey = content.EventKey ? content.EventKey[0] : "",
msgType = content.MsgType[0],
msgId = content.MsgID ? content.MsgID[0] : "",
status = content.Status ? content.Status[0] : "",
ticket = content.Ticket ? content.Ticket[0] : null;
if(msgType === 'event') {
const WechatEvent = req.app.db.models.WechatEvent;
let wechatEvent = new WechatEvent({ event: content });
wechatEvent.save((err) => {
if(err) console.error(err, err.stack);
handleEvent(req, res, fromOpenId, event, eventKey, msgId, status, ticket);
});
}
} catch(e) {
console.error(e, e.stack);
}
};
function handleEvent(req, res, openId, name, key, msgId, status, ticket) {
const Subscriber = req.app.db.models.Subscriber;
const InvitationCard = req.app.db.models.InvitationCard;
name = String(name).toLowerCase();
if(name === 'scan') {
if(ticket) {
InvitationCard.findOne({ qrTicket: ticket }).populate('invitationTask').exec((err, cardDoc) => {
if(err) return console.error(err);
if(cardDoc && cardDoc.invitationTask.status === 'OPEN') {
if(cardDoc.openId === openId) {
return Wechat.sendText(openId, "你不能扫描自己的任务卡");
} else {
Subscriber.findOne({ openId, subscribe: true }).exec((err, subscriberDoc) => {
if(err) return console.error(err);
if(subscriberDoc) return Wechat.sendText(openId, "你已经关注,不能被邀请");
});
}
}
});
}
}
if(name === 'click') {
if(key.indexOf('invitationTask') === 0) {
let taskId = key.split('-')[1];
require('../../service/InvitationCard').sendCard(openId, taskId);
}
if(key.indexOf('message') === 0) {
let replyQueueId = key.split('-')[1];
let ReplyQueue = req.app.db.models.ReplyQueue;
let ReplyQueueLog = req.app.db.models.ReplyQueueLog;
function sendMessages(messageGroup) {
async.eachSeries(messageGroup, function(message, callback) {
if(message.type === 'text') {
return Wechat.sendText(openId, message.content).then((data) => {
setTimeout(callback, 1000);
}).catch(callback);
}
if(message.type === 'image') {
return Wechat.sendImage(openId, message.mediaId).then((data) => {
setTimeout(callback, 5000);
}).catch(callback);
}
}, function(err) {
err && console.log(err);
});
}
ReplyQueueLog.findOne({ openId, replyQueue: replyQueueId}).exec((err, log) => {
if(log) {
let nextIndex = log.clickCount;
if(nextIndex > log.messageGroupsSnapshot.length-1) {
nextIndex = log.messageGroupsSnapshot.length-1;
} else {
ReplyQueueLog.findByIdAndUpdate(log._id, { clickCount: nextIndex + 1 }, { new: true }).exec();
}
sendMessages(log.messageGroupsSnapshot[nextIndex])
} else {
ReplyQueue.findById(replyQueueId).exec((err, replyQueue) => {
new ReplyQueueLog({ openId: openId, replyQueue: replyQueueId, messageGroupsSnapshot: replyQueue.messageGroups, clickCount: 1 }).save();
sendMessages(replyQueue.messageGroups[0]);
});
}
});
}
}
if(name === 'subscribe') {
const workflow = new EventEmitter();
let introducer = null;
let card = null;
// 检查扫码标记
workflow.on('checkTicket', () => {
debug('Event: checkTicket');
if(ticket) return workflow.emit('findNewUser'); // 在数据库中寻找该"新"用户
return workflow.emit('getSubscriberInfo'); // 获得"新"用户详情
});
// 在数据库中寻找该用户
workflow.on('findNewUser', () => {
debug('Event: findNewUser');
Subscriber.findOne({ openId }).exec((err, doc) => {
if(err) return workflow.emit('error', err); // 错误
if(!doc) return workflow.emit('getTaskAndCard'); // 查找邀请卡和任务配置
InvitationCard.findOne({ openId, qrTicket: ticket }).exec((err, selfScanedCardDoc) => {
if(err) return workflow.emit('error', err); // 错误
if(selfScanedCardDoc) return Wechat.sendText(openId, "你不能扫描自己的任务卡");
if(doc.subscribe) return Wechat.sendText(openId, "你已经关注,不能被邀请");
Wechat.sendText(openId, "你已经被邀请过,不能被再次邀请");
});
return workflow.emit('getSubscriberInfo'); // 获得"新"用户详情
});
});
workflow.on('getTaskAndCard', () => {
debug('Event: getTaskAndCard');
InvitationCard.findOne({ qrTicket: ticket }).populate('invitationTask').exec((err, cardDoc) => {
if(err) return workflow.emit('error', err); // 错误
if(!cardDoc) return workflow.emit('getSubscriberInfo'); // 没有此邀请卡,获得"新"用户详情
if(!cardDoc.invitationTask) return workflow.emit('getSubscriberInfo'); // 邀请卡任务不存在,获得"新"用户详情
if(cardDoc.invitationTask.status !== 'OPEN') return workflow.emit('getSubscriberInfo'); // 邀请卡任务已关闭,获得"新"用户详情
card = cardDoc.toJSON();
Subscriber.findOne({ openId: cardDoc.openId }).exec((err, introducerDoc) => {
if(err) return workflow.emit('error', err); // 错误
if(!introducerDoc) return workflow.emit('getSubscriberInfo'); // 没有此邀请人,获得"新"用户详情
introducer = introducerDoc.toJSON();
return workflow.emit('invitedCountPlus'); // 增加邀请量
});
});
});
workflow.on('invitedCountPlus', () => {
debug('Event: invitedCountPlus');
InvitationCard.findOneAndUpdate({ qrTicket: ticket }, { $inc: { invitedCount: 1 }}, function(err, doc) {
if(err) return workflow.emit('error', err); // 错误
console.log(`[WechatController] Add Invitation: ${ticket}`);
workflow.emit('getSubscriberInfo');
});
});
workflow.on('getSubscriberInfo', () => {
debug('Event: getSubscriberInfo');
Wechat.getSubscriberInfo(openId).then((info) => {
let newData = {
openId: info.openid,
groupId: info.groupid,
unionId: info.unionid,
subscribe: info.subscribe ? true : false,
subscribeTime: new Date(info.subscribe_time * 1000),
nickname: info.nickname,
remark: info.remark,
gender: info.sex,
headImgUrl: info.headimgurl,
city: info.city,
province: info.province,
country: info.country,
language: info.language
};
if(introducer) {
newData.introducer = introducer._id;
if(card.invitationTask.invitedFeedback) {
let invitedCount = card.invitedCount + 1;
let remainCount = card.invitationTask.threshold - invitedCount;
let invitedFeedback = card.invitationTask.invitedFeedback;
if(remainCount > 0) {
invitedFeedback = invitedFeedback.replace(/###/g, info.nickname)
invitedFeedback = invitedFeedback.replace(/#invited#/g, invitedCount + '');
invitedFeedback = invitedFeedback.replace(/#remain#/g, remainCount + '')
Wechat.sendText(introducer.openId, invitedFeedback);
}
}
}
Subscriber.findOneAndUpdate({ openId }, newData, { upsert: true }, function(err, doc){
if(err) return workflow.emit('error', err); // 错误
console.log(`[WechatController] New Subscriber: ${openId}`);
});
}).catch((err) => {
if(err) return workflow.emit('error', err); // 错误
})
});
// 错误
workflow.on('error', (err, wechatMessage) => {
debug('Event: error');
if(err) {
console.error(err, err.stack);
} else {
console.error('Undefined Error Event');
}
});
workflow.emit('checkTicket');
}
if(name === 'unsubscribe') {
let Subscriber = req.app.db.models.Subscriber;
let newData = {
subscribe: false
};
Subscriber.findOneAndUpdate({ openId }, newData, { upsert: true }, function(err, doc){
if (err) return console.error(err);
console.log(`[WechatController] Unsubscribe: ${openId}`);
});
}
if(name === 'templatesendjobfinish') {
let TemplateSendLog = req.app.db.models.TemplateSendLog;
status = _.upperFirst(status);
TemplateSendLog.findOneAndUpdate({ msgId: msgId }, { status : status }, function(err, doc){
if (err) return console.log(err);
console.log(`[WechatController] TEMPLATESENDJOBFINISH: ${msgId}`);
});
}
} | xwang1024/bomblab | lib/controller/wechat/index.js | JavaScript | mit | 10,120 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>sudoku: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.1 / sudoku - 8.5.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
sudoku
<small>
8.5.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-03-10 01:39:32 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-10 01:39:32 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.13.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.13.1 Official release 4.13.1
ocaml-config 2 OCaml Switch Configuration
ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "matej.kosik@inria.fr"
homepage: "https://github.com/coq-contribs/sudoku"
license: "LGPL 2"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Sudoku"]
depends: [
"ocaml"
"coq" {>= "8.5" & < "8.6~"}
]
tags: [ "keyword:sudoku" "keyword:puzzles" "keyword:davis putnam" "category:Miscellaneous/Logical Puzzles and Entertainment" "date:2006-02" ]
authors: [ "Laurent Théry <thery@sophia.inria.fr>" ]
bug-reports: "https://github.com/coq-contribs/sudoku/issues"
dev-repo: "git+https://github.com/coq-contribs/sudoku.git"
synopsis: "A certified Sudoku solver"
description: """
A formalisation of Sudoku in Coq. It implements a naive
Davis-Putnam procedure to solve sudokus."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/sudoku/archive/v8.5.0.tar.gz"
checksum: "md5=7b87491f0d76c6d573bf686b68829739"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-sudoku.8.5.0 coq.8.13.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.1).
The following dependencies couldn't be met:
- coq-sudoku -> coq < 8.6~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-sudoku.8.5.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| coq-bench/coq-bench.github.io | clean/Linux-x86_64-4.13.1-2.0.10/released/8.13.1/sudoku/8.5.0.html | HTML | mit | 7,058 |
<?php
namespace Nemundo\Package\Bootstrap\Table;
use Nemundo\Html\Table\Table;
class BootstrapTable extends Table
{
/**
* @var bool
*/
public $smallTable = false;
/**
* @var bool
*/
public $hover = false;
/**
* @var bool
*/
public $inverse = false;
/**
* @var bool
*/
public $striped = false;
public function getContent()
{
$this->addCssClass('table');
if ($this->smallTable) {
$this->addCssClass('table-sm');
}
if ($this->hover) {
$this->addCssClass('table-hover');
}
if ($this->inverse) {
$this->addCssClass('table-inverse');
}
if ($this->striped) {
$this->addCssClass('table-striped');
}
return parent::getContent();
}
} | nemundo/framework | src/Package/Bootstrap/Table/BootstrapTable.php | PHP | mit | 853 |
<header class="header-site" role="banner">
<div class="content">
<h1>
<span class="site-title">{{site.username}}</span>
<span class="site-description">{{site.user_title}}</span>
</h1>
<div class="icons-home">
<a aria-label="Send email" href="mailto:{{site.email}}"><svg class="icon icon-email"><use xlink:href="#icon-email"></use></svg></a>
<a aria-label="My Twitter" target="_blank" href="https://twitter.com/{{site.twitter_username}}"><svg class="icon icon-twitter"><use xlink:href="#icon-twitter"></use></svg></a>
<a aria-label="Facebook" target="_blank" href="https://www.facebook.com/{{site.facebook_username}}"><svg class="icon icon-facebook"><use xlink:href="#icon-facebook"></use></svg></a>
<a aria-label="My Google Plus" target="_blank" href="https://plus.google.com/+{{site.gplus_username}}"><svg class="icon icon-google-plus"><use xlink:href="#icon-google-plus"></use></svg></a>
<a aria-label="My Github" target="_blank" href="https://github.com/{{site.github_username}}"><svg class="icon icon-github-alt"><use xlink:href="#icon-github-alt"></use></svg></a>
<a aria-label="Use the RSS to get updated" target="_blank" href="{{ "/feed.xml" | prepend: site.baseurl }}"><svg class="icon icon-rss"><use xlink:href="#icon-rss"></use></svg></a>
</div>
</div>
<a role="button" class="down" data-scroll href="#scroll"><svg class="icon icon-angle-down"><use xlink:href="#icon-angle-down"></use></svg></a>
{% include menu-search.html %}
</header>
| seb-Bolivia/seb-Bolivia.github.io | _includes/header-default.html | HTML | mit | 1,591 |
// get the languange parameter in the URL (i for case insensitive;
//exec for test for a match in a string and return thr first match)
function getURLParameter(key) {
var result = new RegExp(key + '=([^&]*)', 'i').exec(window.location.search);
return result && result[1] || '';
}
//
function toggleLang(lang) {
var lang = lang || 'de';
document.location = document.location.pathname + '?lang=' + lang;
}
// set UR
var lang = getURLParameter('lang') || 'de';
$('#lang').ready(function() {
$('#lang li').each(function() {
var li = $(this)[0];
if (li.id == lang) $(this).addClass('selected');
});
});
| geoadmin/web-storymaps | htdocs/common/js/toggleLang.js | JavaScript | mit | 624 |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Leave Group Types Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class PLTDataSet : EduHubDataSet<PLT>
{
/// <inheritdoc />
public override string Name { get { return "PLT"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal PLTDataSet(EduHubContext Context)
: base(Context)
{
Index_LEAVE_CODE = new Lazy<NullDictionary<string, IReadOnlyList<PLT>>>(() => this.ToGroupedNullDictionary(i => i.LEAVE_CODE));
Index_LEAVE_GROUP = new Lazy<NullDictionary<string, IReadOnlyList<PLT>>>(() => this.ToGroupedNullDictionary(i => i.LEAVE_GROUP));
Index_LEAVE_GROUP_LEAVE_CODE = new Lazy<Dictionary<Tuple<string, string>, PLT>>(() => this.ToDictionary(i => Tuple.Create(i.LEAVE_GROUP, i.LEAVE_CODE)));
Index_PLTKEY = new Lazy<Dictionary<string, PLT>>(() => this.ToDictionary(i => i.PLTKEY));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="PLT" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="PLT" /> fields for each CSV column header</returns>
internal override Action<PLT, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<PLT, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "PLTKEY":
mapper[i] = (e, v) => e.PLTKEY = v;
break;
case "LEAVE_GROUP":
mapper[i] = (e, v) => e.LEAVE_GROUP = v;
break;
case "LEAVE_CODE":
mapper[i] = (e, v) => e.LEAVE_CODE = v;
break;
case "CALC_METHOD":
mapper[i] = (e, v) => e.CALC_METHOD = v;
break;
case "PERIOD_ALLOT01":
mapper[i] = (e, v) => e.PERIOD_ALLOT01 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT02":
mapper[i] = (e, v) => e.PERIOD_ALLOT02 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT03":
mapper[i] = (e, v) => e.PERIOD_ALLOT03 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT04":
mapper[i] = (e, v) => e.PERIOD_ALLOT04 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT05":
mapper[i] = (e, v) => e.PERIOD_ALLOT05 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT06":
mapper[i] = (e, v) => e.PERIOD_ALLOT06 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT07":
mapper[i] = (e, v) => e.PERIOD_ALLOT07 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT08":
mapper[i] = (e, v) => e.PERIOD_ALLOT08 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT09":
mapper[i] = (e, v) => e.PERIOD_ALLOT09 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT10":
mapper[i] = (e, v) => e.PERIOD_ALLOT10 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT11":
mapper[i] = (e, v) => e.PERIOD_ALLOT11 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_ALLOT12":
mapper[i] = (e, v) => e.PERIOD_ALLOT12 = v == null ? (double?)null : double.Parse(v);
break;
case "PERIOD_LENGTH01":
mapper[i] = (e, v) => e.PERIOD_LENGTH01 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH02":
mapper[i] = (e, v) => e.PERIOD_LENGTH02 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH03":
mapper[i] = (e, v) => e.PERIOD_LENGTH03 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH04":
mapper[i] = (e, v) => e.PERIOD_LENGTH04 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH05":
mapper[i] = (e, v) => e.PERIOD_LENGTH05 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH06":
mapper[i] = (e, v) => e.PERIOD_LENGTH06 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH07":
mapper[i] = (e, v) => e.PERIOD_LENGTH07 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH08":
mapper[i] = (e, v) => e.PERIOD_LENGTH08 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH09":
mapper[i] = (e, v) => e.PERIOD_LENGTH09 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH10":
mapper[i] = (e, v) => e.PERIOD_LENGTH10 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH11":
mapper[i] = (e, v) => e.PERIOD_LENGTH11 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_LENGTH12":
mapper[i] = (e, v) => e.PERIOD_LENGTH12 = v == null ? (short?)null : short.Parse(v);
break;
case "PERIOD_UNITS":
mapper[i] = (e, v) => e.PERIOD_UNITS = v;
break;
case "ANNUAL_ENTITLEMENT":
mapper[i] = (e, v) => e.ANNUAL_ENTITLEMENT = v == null ? (double?)null : double.Parse(v);
break;
case "ROLL_OVER":
mapper[i] = (e, v) => e.ROLL_OVER = v;
break;
case "ROLL_PERCENT":
mapper[i] = (e, v) => e.ROLL_PERCENT = v == null ? (double?)null : double.Parse(v);
break;
case "LEAVE_LOADING":
mapper[i] = (e, v) => e.LEAVE_LOADING = v;
break;
case "LOADING_PERCENT":
mapper[i] = (e, v) => e.LOADING_PERCENT = v == null ? (double?)null : double.Parse(v);
break;
case "ACTIVE":
mapper[i] = (e, v) => e.ACTIVE = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="PLT" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="PLT" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="PLT" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{PLT}"/> of entities</returns>
internal override IEnumerable<PLT> ApplyDeltaEntities(IEnumerable<PLT> Entities, List<PLT> DeltaEntities)
{
HashSet<Tuple<string, string>> Index_LEAVE_GROUP_LEAVE_CODE = new HashSet<Tuple<string, string>>(DeltaEntities.Select(i => Tuple.Create(i.LEAVE_GROUP, i.LEAVE_CODE)));
HashSet<string> Index_PLTKEY = new HashSet<string>(DeltaEntities.Select(i => i.PLTKEY));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.PLTKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = false;
overwritten = overwritten || Index_LEAVE_GROUP_LEAVE_CODE.Remove(Tuple.Create(entity.LEAVE_GROUP, entity.LEAVE_CODE));
overwritten = overwritten || Index_PLTKEY.Remove(entity.PLTKEY);
if (entity.PLTKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<string, IReadOnlyList<PLT>>> Index_LEAVE_CODE;
private Lazy<NullDictionary<string, IReadOnlyList<PLT>>> Index_LEAVE_GROUP;
private Lazy<Dictionary<Tuple<string, string>, PLT>> Index_LEAVE_GROUP_LEAVE_CODE;
private Lazy<Dictionary<string, PLT>> Index_PLTKEY;
#endregion
#region Index Methods
/// <summary>
/// Find PLT by LEAVE_CODE field
/// </summary>
/// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param>
/// <returns>List of related PLT entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<PLT> FindByLEAVE_CODE(string LEAVE_CODE)
{
return Index_LEAVE_CODE.Value[LEAVE_CODE];
}
/// <summary>
/// Attempt to find PLT by LEAVE_CODE field
/// </summary>
/// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param>
/// <param name="Value">List of related PLT entities</param>
/// <returns>True if the list of related PLT entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByLEAVE_CODE(string LEAVE_CODE, out IReadOnlyList<PLT> Value)
{
return Index_LEAVE_CODE.Value.TryGetValue(LEAVE_CODE, out Value);
}
/// <summary>
/// Attempt to find PLT by LEAVE_CODE field
/// </summary>
/// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param>
/// <returns>List of related PLT entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<PLT> TryFindByLEAVE_CODE(string LEAVE_CODE)
{
IReadOnlyList<PLT> value;
if (Index_LEAVE_CODE.Value.TryGetValue(LEAVE_CODE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find PLT by LEAVE_GROUP field
/// </summary>
/// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param>
/// <returns>List of related PLT entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<PLT> FindByLEAVE_GROUP(string LEAVE_GROUP)
{
return Index_LEAVE_GROUP.Value[LEAVE_GROUP];
}
/// <summary>
/// Attempt to find PLT by LEAVE_GROUP field
/// </summary>
/// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param>
/// <param name="Value">List of related PLT entities</param>
/// <returns>True if the list of related PLT entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByLEAVE_GROUP(string LEAVE_GROUP, out IReadOnlyList<PLT> Value)
{
return Index_LEAVE_GROUP.Value.TryGetValue(LEAVE_GROUP, out Value);
}
/// <summary>
/// Attempt to find PLT by LEAVE_GROUP field
/// </summary>
/// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param>
/// <returns>List of related PLT entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<PLT> TryFindByLEAVE_GROUP(string LEAVE_GROUP)
{
IReadOnlyList<PLT> value;
if (Index_LEAVE_GROUP.Value.TryGetValue(LEAVE_GROUP, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find PLT by LEAVE_GROUP and LEAVE_CODE fields
/// </summary>
/// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param>
/// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param>
/// <returns>Related PLT entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public PLT FindByLEAVE_GROUP_LEAVE_CODE(string LEAVE_GROUP, string LEAVE_CODE)
{
return Index_LEAVE_GROUP_LEAVE_CODE.Value[Tuple.Create(LEAVE_GROUP, LEAVE_CODE)];
}
/// <summary>
/// Attempt to find PLT by LEAVE_GROUP and LEAVE_CODE fields
/// </summary>
/// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param>
/// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param>
/// <param name="Value">Related PLT entity</param>
/// <returns>True if the related PLT entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByLEAVE_GROUP_LEAVE_CODE(string LEAVE_GROUP, string LEAVE_CODE, out PLT Value)
{
return Index_LEAVE_GROUP_LEAVE_CODE.Value.TryGetValue(Tuple.Create(LEAVE_GROUP, LEAVE_CODE), out Value);
}
/// <summary>
/// Attempt to find PLT by LEAVE_GROUP and LEAVE_CODE fields
/// </summary>
/// <param name="LEAVE_GROUP">LEAVE_GROUP value used to find PLT</param>
/// <param name="LEAVE_CODE">LEAVE_CODE value used to find PLT</param>
/// <returns>Related PLT entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public PLT TryFindByLEAVE_GROUP_LEAVE_CODE(string LEAVE_GROUP, string LEAVE_CODE)
{
PLT value;
if (Index_LEAVE_GROUP_LEAVE_CODE.Value.TryGetValue(Tuple.Create(LEAVE_GROUP, LEAVE_CODE), out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find PLT by PLTKEY field
/// </summary>
/// <param name="PLTKEY">PLTKEY value used to find PLT</param>
/// <returns>Related PLT entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public PLT FindByPLTKEY(string PLTKEY)
{
return Index_PLTKEY.Value[PLTKEY];
}
/// <summary>
/// Attempt to find PLT by PLTKEY field
/// </summary>
/// <param name="PLTKEY">PLTKEY value used to find PLT</param>
/// <param name="Value">Related PLT entity</param>
/// <returns>True if the related PLT entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByPLTKEY(string PLTKEY, out PLT Value)
{
return Index_PLTKEY.Value.TryGetValue(PLTKEY, out Value);
}
/// <summary>
/// Attempt to find PLT by PLTKEY field
/// </summary>
/// <param name="PLTKEY">PLTKEY value used to find PLT</param>
/// <returns>Related PLT entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public PLT TryFindByPLTKEY(string PLTKEY)
{
PLT value;
if (Index_PLTKEY.Value.TryGetValue(PLTKEY, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a PLT table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[PLT](
[PLTKEY] varchar(16) NOT NULL,
[LEAVE_GROUP] varchar(8) NULL,
[LEAVE_CODE] varchar(8) NULL,
[CALC_METHOD] varchar(8) NULL,
[PERIOD_ALLOT01] float NULL,
[PERIOD_ALLOT02] float NULL,
[PERIOD_ALLOT03] float NULL,
[PERIOD_ALLOT04] float NULL,
[PERIOD_ALLOT05] float NULL,
[PERIOD_ALLOT06] float NULL,
[PERIOD_ALLOT07] float NULL,
[PERIOD_ALLOT08] float NULL,
[PERIOD_ALLOT09] float NULL,
[PERIOD_ALLOT10] float NULL,
[PERIOD_ALLOT11] float NULL,
[PERIOD_ALLOT12] float NULL,
[PERIOD_LENGTH01] smallint NULL,
[PERIOD_LENGTH02] smallint NULL,
[PERIOD_LENGTH03] smallint NULL,
[PERIOD_LENGTH04] smallint NULL,
[PERIOD_LENGTH05] smallint NULL,
[PERIOD_LENGTH06] smallint NULL,
[PERIOD_LENGTH07] smallint NULL,
[PERIOD_LENGTH08] smallint NULL,
[PERIOD_LENGTH09] smallint NULL,
[PERIOD_LENGTH10] smallint NULL,
[PERIOD_LENGTH11] smallint NULL,
[PERIOD_LENGTH12] smallint NULL,
[PERIOD_UNITS] varchar(6) NULL,
[ANNUAL_ENTITLEMENT] float NULL,
[ROLL_OVER] varchar(1) NULL,
[ROLL_PERCENT] float NULL,
[LEAVE_LOADING] varchar(1) NULL,
[LOADING_PERCENT] float NULL,
[ACTIVE] varchar(1) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [PLT_Index_PLTKEY] PRIMARY KEY CLUSTERED (
[PLTKEY] ASC
)
);
CREATE NONCLUSTERED INDEX [PLT_Index_LEAVE_CODE] ON [dbo].[PLT]
(
[LEAVE_CODE] ASC
);
CREATE NONCLUSTERED INDEX [PLT_Index_LEAVE_GROUP] ON [dbo].[PLT]
(
[LEAVE_GROUP] ASC
);
CREATE NONCLUSTERED INDEX [PLT_Index_LEAVE_GROUP_LEAVE_CODE] ON [dbo].[PLT]
(
[LEAVE_GROUP] ASC,
[LEAVE_CODE] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_CODE')
ALTER INDEX [PLT_Index_LEAVE_CODE] ON [dbo].[PLT] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_GROUP')
ALTER INDEX [PLT_Index_LEAVE_GROUP] ON [dbo].[PLT] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_GROUP_LEAVE_CODE')
ALTER INDEX [PLT_Index_LEAVE_GROUP_LEAVE_CODE] ON [dbo].[PLT] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_CODE')
ALTER INDEX [PLT_Index_LEAVE_CODE] ON [dbo].[PLT] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_GROUP')
ALTER INDEX [PLT_Index_LEAVE_GROUP] ON [dbo].[PLT] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PLT]') AND name = N'PLT_Index_LEAVE_GROUP_LEAVE_CODE')
ALTER INDEX [PLT_Index_LEAVE_GROUP_LEAVE_CODE] ON [dbo].[PLT] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="PLT"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="PLT"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<PLT> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<Tuple<string, string>> Index_LEAVE_GROUP_LEAVE_CODE = new List<Tuple<string, string>>();
List<string> Index_PLTKEY = new List<string>();
foreach (var entity in Entities)
{
Index_LEAVE_GROUP_LEAVE_CODE.Add(Tuple.Create(entity.LEAVE_GROUP, entity.LEAVE_CODE));
Index_PLTKEY.Add(entity.PLTKEY);
}
builder.AppendLine("DELETE [dbo].[PLT] WHERE");
// Index_LEAVE_GROUP_LEAVE_CODE
builder.Append("(");
for (int index = 0; index < Index_LEAVE_GROUP_LEAVE_CODE.Count; index++)
{
if (index != 0)
builder.Append(" OR ");
// LEAVE_GROUP
if (Index_LEAVE_GROUP_LEAVE_CODE[index].Item1 == null)
{
builder.Append("([LEAVE_GROUP] IS NULL");
}
else
{
var parameterLEAVE_GROUP = $"@p{parameterIndex++}";
builder.Append("([LEAVE_GROUP]=").Append(parameterLEAVE_GROUP);
command.Parameters.Add(parameterLEAVE_GROUP, SqlDbType.VarChar, 8).Value = Index_LEAVE_GROUP_LEAVE_CODE[index].Item1;
}
// LEAVE_CODE
if (Index_LEAVE_GROUP_LEAVE_CODE[index].Item2 == null)
{
builder.Append(" AND [LEAVE_CODE] IS NULL)");
}
else
{
var parameterLEAVE_CODE = $"@p{parameterIndex++}";
builder.Append(" AND [LEAVE_CODE]=").Append(parameterLEAVE_CODE).Append(")");
command.Parameters.Add(parameterLEAVE_CODE, SqlDbType.VarChar, 8).Value = Index_LEAVE_GROUP_LEAVE_CODE[index].Item2;
}
}
builder.AppendLine(") OR");
// Index_PLTKEY
builder.Append("[PLTKEY] IN (");
for (int index = 0; index < Index_PLTKEY.Count; index++)
{
if (index != 0)
builder.Append(", ");
// PLTKEY
var parameterPLTKEY = $"@p{parameterIndex++}";
builder.Append(parameterPLTKEY);
command.Parameters.Add(parameterPLTKEY, SqlDbType.VarChar, 16).Value = Index_PLTKEY[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the PLT data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the PLT data set</returns>
public override EduHubDataSetDataReader<PLT> GetDataSetDataReader()
{
return new PLTDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the PLT data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the PLT data set</returns>
public override EduHubDataSetDataReader<PLT> GetDataSetDataReader(List<PLT> Entities)
{
return new PLTDataReader(new EduHubDataSetLoadedReader<PLT>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class PLTDataReader : EduHubDataSetDataReader<PLT>
{
public PLTDataReader(IEduHubDataSetReader<PLT> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 38; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // PLTKEY
return Current.PLTKEY;
case 1: // LEAVE_GROUP
return Current.LEAVE_GROUP;
case 2: // LEAVE_CODE
return Current.LEAVE_CODE;
case 3: // CALC_METHOD
return Current.CALC_METHOD;
case 4: // PERIOD_ALLOT01
return Current.PERIOD_ALLOT01;
case 5: // PERIOD_ALLOT02
return Current.PERIOD_ALLOT02;
case 6: // PERIOD_ALLOT03
return Current.PERIOD_ALLOT03;
case 7: // PERIOD_ALLOT04
return Current.PERIOD_ALLOT04;
case 8: // PERIOD_ALLOT05
return Current.PERIOD_ALLOT05;
case 9: // PERIOD_ALLOT06
return Current.PERIOD_ALLOT06;
case 10: // PERIOD_ALLOT07
return Current.PERIOD_ALLOT07;
case 11: // PERIOD_ALLOT08
return Current.PERIOD_ALLOT08;
case 12: // PERIOD_ALLOT09
return Current.PERIOD_ALLOT09;
case 13: // PERIOD_ALLOT10
return Current.PERIOD_ALLOT10;
case 14: // PERIOD_ALLOT11
return Current.PERIOD_ALLOT11;
case 15: // PERIOD_ALLOT12
return Current.PERIOD_ALLOT12;
case 16: // PERIOD_LENGTH01
return Current.PERIOD_LENGTH01;
case 17: // PERIOD_LENGTH02
return Current.PERIOD_LENGTH02;
case 18: // PERIOD_LENGTH03
return Current.PERIOD_LENGTH03;
case 19: // PERIOD_LENGTH04
return Current.PERIOD_LENGTH04;
case 20: // PERIOD_LENGTH05
return Current.PERIOD_LENGTH05;
case 21: // PERIOD_LENGTH06
return Current.PERIOD_LENGTH06;
case 22: // PERIOD_LENGTH07
return Current.PERIOD_LENGTH07;
case 23: // PERIOD_LENGTH08
return Current.PERIOD_LENGTH08;
case 24: // PERIOD_LENGTH09
return Current.PERIOD_LENGTH09;
case 25: // PERIOD_LENGTH10
return Current.PERIOD_LENGTH10;
case 26: // PERIOD_LENGTH11
return Current.PERIOD_LENGTH11;
case 27: // PERIOD_LENGTH12
return Current.PERIOD_LENGTH12;
case 28: // PERIOD_UNITS
return Current.PERIOD_UNITS;
case 29: // ANNUAL_ENTITLEMENT
return Current.ANNUAL_ENTITLEMENT;
case 30: // ROLL_OVER
return Current.ROLL_OVER;
case 31: // ROLL_PERCENT
return Current.ROLL_PERCENT;
case 32: // LEAVE_LOADING
return Current.LEAVE_LOADING;
case 33: // LOADING_PERCENT
return Current.LOADING_PERCENT;
case 34: // ACTIVE
return Current.ACTIVE;
case 35: // LW_DATE
return Current.LW_DATE;
case 36: // LW_TIME
return Current.LW_TIME;
case 37: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // LEAVE_GROUP
return Current.LEAVE_GROUP == null;
case 2: // LEAVE_CODE
return Current.LEAVE_CODE == null;
case 3: // CALC_METHOD
return Current.CALC_METHOD == null;
case 4: // PERIOD_ALLOT01
return Current.PERIOD_ALLOT01 == null;
case 5: // PERIOD_ALLOT02
return Current.PERIOD_ALLOT02 == null;
case 6: // PERIOD_ALLOT03
return Current.PERIOD_ALLOT03 == null;
case 7: // PERIOD_ALLOT04
return Current.PERIOD_ALLOT04 == null;
case 8: // PERIOD_ALLOT05
return Current.PERIOD_ALLOT05 == null;
case 9: // PERIOD_ALLOT06
return Current.PERIOD_ALLOT06 == null;
case 10: // PERIOD_ALLOT07
return Current.PERIOD_ALLOT07 == null;
case 11: // PERIOD_ALLOT08
return Current.PERIOD_ALLOT08 == null;
case 12: // PERIOD_ALLOT09
return Current.PERIOD_ALLOT09 == null;
case 13: // PERIOD_ALLOT10
return Current.PERIOD_ALLOT10 == null;
case 14: // PERIOD_ALLOT11
return Current.PERIOD_ALLOT11 == null;
case 15: // PERIOD_ALLOT12
return Current.PERIOD_ALLOT12 == null;
case 16: // PERIOD_LENGTH01
return Current.PERIOD_LENGTH01 == null;
case 17: // PERIOD_LENGTH02
return Current.PERIOD_LENGTH02 == null;
case 18: // PERIOD_LENGTH03
return Current.PERIOD_LENGTH03 == null;
case 19: // PERIOD_LENGTH04
return Current.PERIOD_LENGTH04 == null;
case 20: // PERIOD_LENGTH05
return Current.PERIOD_LENGTH05 == null;
case 21: // PERIOD_LENGTH06
return Current.PERIOD_LENGTH06 == null;
case 22: // PERIOD_LENGTH07
return Current.PERIOD_LENGTH07 == null;
case 23: // PERIOD_LENGTH08
return Current.PERIOD_LENGTH08 == null;
case 24: // PERIOD_LENGTH09
return Current.PERIOD_LENGTH09 == null;
case 25: // PERIOD_LENGTH10
return Current.PERIOD_LENGTH10 == null;
case 26: // PERIOD_LENGTH11
return Current.PERIOD_LENGTH11 == null;
case 27: // PERIOD_LENGTH12
return Current.PERIOD_LENGTH12 == null;
case 28: // PERIOD_UNITS
return Current.PERIOD_UNITS == null;
case 29: // ANNUAL_ENTITLEMENT
return Current.ANNUAL_ENTITLEMENT == null;
case 30: // ROLL_OVER
return Current.ROLL_OVER == null;
case 31: // ROLL_PERCENT
return Current.ROLL_PERCENT == null;
case 32: // LEAVE_LOADING
return Current.LEAVE_LOADING == null;
case 33: // LOADING_PERCENT
return Current.LOADING_PERCENT == null;
case 34: // ACTIVE
return Current.ACTIVE == null;
case 35: // LW_DATE
return Current.LW_DATE == null;
case 36: // LW_TIME
return Current.LW_TIME == null;
case 37: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // PLTKEY
return "PLTKEY";
case 1: // LEAVE_GROUP
return "LEAVE_GROUP";
case 2: // LEAVE_CODE
return "LEAVE_CODE";
case 3: // CALC_METHOD
return "CALC_METHOD";
case 4: // PERIOD_ALLOT01
return "PERIOD_ALLOT01";
case 5: // PERIOD_ALLOT02
return "PERIOD_ALLOT02";
case 6: // PERIOD_ALLOT03
return "PERIOD_ALLOT03";
case 7: // PERIOD_ALLOT04
return "PERIOD_ALLOT04";
case 8: // PERIOD_ALLOT05
return "PERIOD_ALLOT05";
case 9: // PERIOD_ALLOT06
return "PERIOD_ALLOT06";
case 10: // PERIOD_ALLOT07
return "PERIOD_ALLOT07";
case 11: // PERIOD_ALLOT08
return "PERIOD_ALLOT08";
case 12: // PERIOD_ALLOT09
return "PERIOD_ALLOT09";
case 13: // PERIOD_ALLOT10
return "PERIOD_ALLOT10";
case 14: // PERIOD_ALLOT11
return "PERIOD_ALLOT11";
case 15: // PERIOD_ALLOT12
return "PERIOD_ALLOT12";
case 16: // PERIOD_LENGTH01
return "PERIOD_LENGTH01";
case 17: // PERIOD_LENGTH02
return "PERIOD_LENGTH02";
case 18: // PERIOD_LENGTH03
return "PERIOD_LENGTH03";
case 19: // PERIOD_LENGTH04
return "PERIOD_LENGTH04";
case 20: // PERIOD_LENGTH05
return "PERIOD_LENGTH05";
case 21: // PERIOD_LENGTH06
return "PERIOD_LENGTH06";
case 22: // PERIOD_LENGTH07
return "PERIOD_LENGTH07";
case 23: // PERIOD_LENGTH08
return "PERIOD_LENGTH08";
case 24: // PERIOD_LENGTH09
return "PERIOD_LENGTH09";
case 25: // PERIOD_LENGTH10
return "PERIOD_LENGTH10";
case 26: // PERIOD_LENGTH11
return "PERIOD_LENGTH11";
case 27: // PERIOD_LENGTH12
return "PERIOD_LENGTH12";
case 28: // PERIOD_UNITS
return "PERIOD_UNITS";
case 29: // ANNUAL_ENTITLEMENT
return "ANNUAL_ENTITLEMENT";
case 30: // ROLL_OVER
return "ROLL_OVER";
case 31: // ROLL_PERCENT
return "ROLL_PERCENT";
case 32: // LEAVE_LOADING
return "LEAVE_LOADING";
case 33: // LOADING_PERCENT
return "LOADING_PERCENT";
case 34: // ACTIVE
return "ACTIVE";
case 35: // LW_DATE
return "LW_DATE";
case 36: // LW_TIME
return "LW_TIME";
case 37: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "PLTKEY":
return 0;
case "LEAVE_GROUP":
return 1;
case "LEAVE_CODE":
return 2;
case "CALC_METHOD":
return 3;
case "PERIOD_ALLOT01":
return 4;
case "PERIOD_ALLOT02":
return 5;
case "PERIOD_ALLOT03":
return 6;
case "PERIOD_ALLOT04":
return 7;
case "PERIOD_ALLOT05":
return 8;
case "PERIOD_ALLOT06":
return 9;
case "PERIOD_ALLOT07":
return 10;
case "PERIOD_ALLOT08":
return 11;
case "PERIOD_ALLOT09":
return 12;
case "PERIOD_ALLOT10":
return 13;
case "PERIOD_ALLOT11":
return 14;
case "PERIOD_ALLOT12":
return 15;
case "PERIOD_LENGTH01":
return 16;
case "PERIOD_LENGTH02":
return 17;
case "PERIOD_LENGTH03":
return 18;
case "PERIOD_LENGTH04":
return 19;
case "PERIOD_LENGTH05":
return 20;
case "PERIOD_LENGTH06":
return 21;
case "PERIOD_LENGTH07":
return 22;
case "PERIOD_LENGTH08":
return 23;
case "PERIOD_LENGTH09":
return 24;
case "PERIOD_LENGTH10":
return 25;
case "PERIOD_LENGTH11":
return 26;
case "PERIOD_LENGTH12":
return 27;
case "PERIOD_UNITS":
return 28;
case "ANNUAL_ENTITLEMENT":
return 29;
case "ROLL_OVER":
return 30;
case "ROLL_PERCENT":
return 31;
case "LEAVE_LOADING":
return 32;
case "LOADING_PERCENT":
return 33;
case "ACTIVE":
return 34;
case "LW_DATE":
return 35;
case "LW_TIME":
return 36;
case "LW_USER":
return 37;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| garysharp/EduHub.Data | src/EduHub.Data/Entities/PLTDataSet.cs | C# | mit | 43,736 |
package iso20022
// Details of the standing settlement instruction to be applied.
type StandingSettlementInstruction9 struct {
// Specifies what settlement standing instruction database is to be used to derive the settlement parties involved in the transaction.
SettlementStandingInstructionDatabase *SettlementStandingInstructionDatabase3Choice `xml:"SttlmStgInstrDB"`
// Vendor of the Settlement Standing Instruction database requested to be consulted.
Vendor *PartyIdentification32Choice `xml:"Vndr,omitempty"`
// Delivering parties, other than the seller, needed for deriving the standing settlement instruction (for example, depository) or provided for information purposes (for example, instructing party settlement chain).
OtherDeliveringSettlementParties *SettlementParties23 `xml:"OthrDlvrgSttlmPties,omitempty"`
// Receiving parties, other than the buyer, needed for deriving the standing settlement instruction (for example, depository) or provided for information purposes (for example, instructing party settlement chain).
OtherReceivingSettlementParties *SettlementParties23 `xml:"OthrRcvgSttlmPties,omitempty"`
}
func (s *StandingSettlementInstruction9) AddSettlementStandingInstructionDatabase() *SettlementStandingInstructionDatabase3Choice {
s.SettlementStandingInstructionDatabase = new(SettlementStandingInstructionDatabase3Choice)
return s.SettlementStandingInstructionDatabase
}
func (s *StandingSettlementInstruction9) AddVendor() *PartyIdentification32Choice {
s.Vendor = new(PartyIdentification32Choice)
return s.Vendor
}
func (s *StandingSettlementInstruction9) AddOtherDeliveringSettlementParties() *SettlementParties23 {
s.OtherDeliveringSettlementParties = new(SettlementParties23)
return s.OtherDeliveringSettlementParties
}
func (s *StandingSettlementInstruction9) AddOtherReceivingSettlementParties() *SettlementParties23 {
s.OtherReceivingSettlementParties = new(SettlementParties23)
return s.OtherReceivingSettlementParties
}
| fgrid/iso20022 | StandingSettlementInstruction9.go | GO | mit | 1,985 |
'use strict';
var _get = require('babel-runtime/helpers/get')['default'];
var _inherits = require('babel-runtime/helpers/inherits')['default'];
var _createClass = require('babel-runtime/helpers/create-class')['default'];
var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
var _extends = require('babel-runtime/helpers/extends')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _EnhancedSwitch = require('./EnhancedSwitch');
var _EnhancedSwitch2 = _interopRequireDefault(_EnhancedSwitch);
var Radio = (function (_React$Component) {
_inherits(Radio, _React$Component);
function Radio() {
_classCallCheck(this, Radio);
_get(Object.getPrototypeOf(Radio.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Radio, [{
key: 'getValue',
value: function getValue() {
return this.refs.enhancedSwitch.getValue();
}
}, {
key: 'setChecked',
value: function setChecked(newCheckedValue) {
this.refs.enhancedSwitch.setSwitched(newCheckedValue);
}
}, {
key: 'isChecked',
value: function isChecked() {
return this.refs.enhancedSwitch.isSwitched();
}
}, {
key: 'render',
value: function render() {
var enhancedSwitchProps = {
ref: 'enhancedSwitch',
inputType: 'radio'
};
// labelClassName
return _react2['default'].createElement(_EnhancedSwitch2['default'], _extends({}, this.props, enhancedSwitchProps));
}
}]);
return Radio;
})(_react2['default'].Component);
exports['default'] = Radio;
module.exports = exports['default']; | andres81/auth-service | frontend/node_modules/react-icheck/lib/Radio.js | JavaScript | mit | 1,815 |
"""
Util classes
------------
Classes which represent data types useful for the package pySpatialTools.
"""
## Spatial elements collectors
from spatialelements import SpatialElementsCollection, Locations
## Membership relations
from Membership import Membership
| tgquintela/pySpatialTools | pySpatialTools/utils/util_classes/__init__.py | Python | mit | 266 |
!(function(root) {
function Grapnel(opts) {
"use strict";
var self = this; // Scope reference
this.events = {}; // Event Listeners
this.state = null; // Router state object
this.options = opts || {}; // Options
this.options.env = this.options.env || (!!(Object.keys(root).length === 0 && process && process.browser !== true) ? 'server' : 'client');
this.options.mode = this.options.mode || (!!(this.options.env !== 'server' && this.options.pushState && root.history && root.history.pushState) ? 'pushState' : 'hashchange');
this.version = '0.6.4'; // Version
if ('function' === typeof root.addEventListener) {
root.addEventListener('hashchange', function() {
self.trigger('hashchange');
});
root.addEventListener('popstate', function(e) {
// Make sure popstate doesn't run on init -- this is a common issue with Safari and old versions of Chrome
if (self.state && self.state.previousState === null) return false;
self.trigger('navigate');
});
}
return this;
};
/**
* Create a RegExp Route from a string
* This is the heart of the router and I've made it as small as possible!
*
* @param {String} Path of route
* @param {Array} Array of keys to fill
* @param {Bool} Case sensitive comparison
* @param {Bool} Strict mode
*/
Grapnel.regexRoute = function(path, keys, sensitive, strict) {
if (path instanceof RegExp) return path;
if (path instanceof Array) path = '(' + path.join('|') + ')';
// Build route RegExp
path = path.concat(strict ? '' : '/?')
.replace(/\/\(/g, '(?:/')
.replace(/\+/g, '__plus__')
.replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional) {
keys.push({
name: key,
optional: !!optional
});
slash = slash || '';
return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')' + (optional || '');
})
.replace(/([\/.])/g, '\\$1')
.replace(/__plus__/g, '(.+)')
.replace(/\*/g, '(.*)');
return new RegExp('^' + path + '$', sensitive ? '' : 'i');
};
/**
* ForEach workaround utility
*
* @param {Array} to iterate
* @param {Function} callback
*/
Grapnel._forEach = function(a, callback) {
if (typeof Array.prototype.forEach === 'function') return Array.prototype.forEach.call(a, callback);
// Replicate forEach()
return function(c, next) {
for (var i = 0, n = this.length; i < n; ++i) {
c.call(next, this[i], i, this);
}
}.call(a, callback);
};
/**
* Add an route and handler
*
* @param {String|RegExp} route name
* @return {self} Router
*/
Grapnel.prototype.get = Grapnel.prototype.add = function(route) {
var self = this,
middleware = Array.prototype.slice.call(arguments, 1, -1),
handler = Array.prototype.slice.call(arguments, -1)[0],
request = new Request(route);
var invoke = function RouteHandler() {
// Build request parameters
var req = request.parse(self.path());
// Check if matches are found
if (req.match) {
// Match found
var extra = {
route: route,
params: req.params,
req: req,
regex: req.match
};
// Create call stack -- add middleware first, then handler
var stack = new CallStack(self, extra).enqueue(middleware.concat(handler));
// Trigger main event
self.trigger('match', stack, req);
// Continue?
if (!stack.runCallback) return self;
// Previous state becomes current state
stack.previousState = self.state;
// Save new state
self.state = stack;
// Prevent this handler from being called if parent handler in stack has instructed not to propagate any more events
if (stack.parent() && stack.parent().propagateEvent === false) {
stack.propagateEvent = false;
return self;
}
// Call handler
stack.callback();
}
// Returns self
return self;
};
// Event name
var eventName = (self.options.mode !== 'pushState' && self.options.env !== 'server') ? 'hashchange' : 'navigate';
// Invoke when route is defined, and once again when app navigates
return invoke().on(eventName, invoke);
};
/**
* Fire an event listener
*
* @param {String} event name
* @param {Mixed} [attributes] Parameters that will be applied to event handler
* @return {self} Router
*/
Grapnel.prototype.trigger = function(event) {
var self = this,
params = Array.prototype.slice.call(arguments, 1);
// Call matching events
if (this.events[event]) {
Grapnel._forEach(this.events[event], function(fn) {
fn.apply(self, params);
});
}
return this;
};
/**
* Add an event listener
*
* @param {String} event name (multiple events can be called when separated by a space " ")
* @param {Function} callback
* @return {self} Router
*/
Grapnel.prototype.on = Grapnel.prototype.bind = function(event, handler) {
var self = this,
events = event.split(' ');
Grapnel._forEach(events, function(event) {
if (self.events[event]) {
self.events[event].push(handler);
} else {
self.events[event] = [handler];
}
});
return this;
};
/**
* Allow event to be called only once
*
* @param {String} event name(s)
* @param {Function} callback
* @return {self} Router
*/
Grapnel.prototype.once = function(event, handler) {
var ran = false;
return this.on(event, function() {
if (ran) return false;
ran = true;
handler.apply(this, arguments);
handler = null;
return true;
});
};
/**
* @param {String} Route context (without trailing slash)
* @param {[Function]} Middleware (optional)
* @return {Function} Adds route to context
*/
Grapnel.prototype.context = function(context) {
var self = this,
middleware = Array.prototype.slice.call(arguments, 1);
return function() {
var value = arguments[0],
submiddleware = (arguments.length > 2) ? Array.prototype.slice.call(arguments, 1, -1) : [],
handler = Array.prototype.slice.call(arguments, -1)[0],
prefix = (context.slice(-1) !== '/' && value !== '/' && value !== '') ? context + '/' : context,
path = (value.substr(0, 1) !== '/') ? value : value.substr(1),
pattern = prefix + path;
return self.add.apply(self, [pattern].concat(middleware).concat(submiddleware).concat([handler]));
}
};
/**
* Navigate through history API
*
* @param {String} Pathname
* @return {self} Router
*/
Grapnel.prototype.navigate = function(path) {
return this.path(path).trigger('navigate');
};
Grapnel.prototype.path = function(pathname) {
var self = this,
frag;
if ('string' === typeof pathname) {
// Set path
if (self.options.mode === 'pushState') {
frag = (self.options.root) ? (self.options.root + pathname) : pathname;
root.history.pushState({}, null, frag);
} else if (root.location) {
root.location.hash = (self.options.hashBang ? '!' : '') + pathname;
} else {
root._pathname = pathname || '';
}
return this;
} else if ('undefined' === typeof pathname) {
// Get path
if (self.options.mode === 'pushState') {
frag = root.location.pathname.replace(self.options.root, '');
} else if (self.options.mode !== 'pushState' && root.location) {
frag = (root.location.hash) ? root.location.hash.split((self.options.hashBang ? '#!' : '#'))[1] : '';
} else {
frag = root._pathname || '';
}
return frag;
} else if (pathname === false) {
// Clear path
if (self.options.mode === 'pushState') {
root.history.pushState({}, null, self.options.root || '/');
} else if (root.location) {
root.location.hash = (self.options.hashBang) ? '!' : '';
}
return self;
}
};
/**
* Create routes based on an object
*
* @param {Object} [Options, Routes]
* @param {Object Routes}
* @return {self} Router
*/
Grapnel.listen = function() {
var opts, routes;
if (arguments[0] && arguments[1]) {
opts = arguments[0];
routes = arguments[1];
} else {
routes = arguments[0];
}
// Return a new Grapnel instance
return (function() {
// TODO: Accept multi-level routes
for (var key in routes) {
this.add.call(this, key, routes[key]);
}
return this;
}).call(new Grapnel(opts || {}));
};
/**
* Create a call stack that can be enqueued by handlers and middleware
*
* @param {Object} Router
* @param {Object} Extend
* @return {self} CallStack
*/
function CallStack(router, extendObj) {
this.stack = CallStack.global.slice(0);
this.router = router;
this.runCallback = true;
this.callbackRan = false;
this.propagateEvent = true;
this.value = router.path();
for (var key in extendObj) {
this[key] = extendObj[key];
}
return this;
};
/**
* Build request parameters and allow them to be checked against a string (usually the current path)
*
* @param {String} Route
* @return {self} Request
*/
function Request(route) {
this.route = route;
this.keys = [];
this.regex = Grapnel.regexRoute(route, this.keys);
};
// This allows global middleware
CallStack.global = [];
/**
* Prevent a callback from being called
*
* @return {self} CallStack
*/
CallStack.prototype.preventDefault = function() {
this.runCallback = false;
};
/**
* Prevent any future callbacks from being called
*
* @return {self} CallStack
*/
CallStack.prototype.stopPropagation = function() {
this.propagateEvent = false;
};
/**
* Get parent state
*
* @return {Object} Previous state
*/
CallStack.prototype.parent = function() {
var hasParentEvents = !!(this.previousState && this.previousState.value && this.previousState.value == this.value);
return (hasParentEvents) ? this.previousState : false;
};
/**
* Run a callback (calls to next)
*
* @return {self} CallStack
*/
CallStack.prototype.callback = function() {
this.callbackRan = true;
this.timeStamp = Date.now();
this.next();
};
/**
* Add handler or middleware to the stack
*
* @param {Function|Array} Handler or a array of handlers
* @param {Int} Index to start inserting
* @return {self} CallStack
*/
CallStack.prototype.enqueue = function(handler, atIndex) {
var handlers = (!Array.isArray(handler)) ? [handler] : ((atIndex < handler.length) ? handler.reverse() : handler);
while (handlers.length) {
this.stack.splice(atIndex || this.stack.length + 1, 0, handlers.shift());
}
return this;
};
/**
* Call to next item in stack -- this adds the `req`, `event`, and `next()` arguments to all middleware
*
* @return {self} CallStack
*/
CallStack.prototype.next = function() {
var self = this;
return this.stack.shift().call(this.router, this.req, this, function next() {
self.next.call(self);
});
};
/**
* Match a path string -- returns a request object if there is a match -- returns false otherwise
*
* @return {Object} req
*/
Request.prototype.parse = function(path) {
var match = path.match(this.regex),
self = this;
var req = {
params: {},
keys: this.keys,
matches: (match || []).slice(1),
match: match
};
// Build parameters
Grapnel._forEach(req.matches, function(value, i) {
var key = (self.keys[i] && self.keys[i].name) ? self.keys[i].name : i;
// Parameter key will be its key or the iteration index. This is useful if a wildcard (*) is matched
req.params[key] = (value) ? decodeURIComponent(value) : undefined;
});
return req;
};
// Append utility constructors to Grapnel
Grapnel.CallStack = CallStack;
Grapnel.Request = Request;
if ('function' === typeof root.define && !root.define.amd.grapnel) {
root.define(function(require, exports, module) {
root.define.amd.grapnel = true;
return Grapnel;
});
} else if ('object' === typeof module && 'object' === typeof module.exports) {
module.exports = exports = Grapnel;
} else {
root.Grapnel = Grapnel;
}
}).call({}, ('object' === typeof window) ? window : this);
/*
var router = new Grapnel({ pushState : true, hashBang : true });
router.get('/products/:category/:id?', function(req){
var id = req.params.id,
category = req.params.category
console.log(category, id);
});
router.get('/tiempo', function(req){
console.log("tiempo!");
$("#matikbirdpath").load("views/rooms.html", function(res){
console.log(res);
console.log("hola");
});
});
router.get('/', function(req){
console.log(req.user);
console.log("hola!");
$("#matikbirdpath").load("views/rooms.html", function(res){
console.log(res);
console.log("hola");
});
});
router.navigate('/');
*/
NProgress.start();
var routes = {
'/' : function(req, e){
$("#matikbirdpath").load("views/main.html", function(res){
console.log(res);
NProgress.done();
});
},
'/dashboard' : function(req, e){
$("#matikbirdpath").load("views/dashboard.html", function(res){
console.log(res);
NProgress.done();
});
},
'/calendario' : function(req, e){
$("#matikbirdpath").load("views/calendario.html", function(res){
console.log(res);
console.log("hola");
});
},
'/now' : function(req, e){
$("#matikbirdpath").load("views/clase_ahora.html", function(res){
console.log(res);
console.log("hola");
});
},
'/category/:id' : function(req, e){
// Handle route
},
'/*' : function(req, e){
if(!e.parent()){
$("#matikbirdpath").load("views/main.html", function(res){
console.log(res);
NProgress.done();
});
}
}
}
var router = Grapnel.listen({ pushState : true, hashBang: true }, routes); | matikbird/matikbird.github.io | portfolio/copylee/assets/mtk-route.js | JavaScript | mit | 16,205 |
---
layout: post
date: 2016-04-28
title: "Le Spose di Giò PREV8_15 2015"
category: Le Spose di Giò
tags: [Le Spose di Giò,2015]
---
### Le Spose di Giò PREV8_15
Just **$379.99**
### 2015
<table><tr><td>BRANDS</td><td>Le Spose di Giò</td></tr><tr><td>Years</td><td>2015</td></tr></table>
<a href="https://www.readybrides.com/en/le-spose-di-gio/43231-le-spose-di-gio-prev815.html"><img src="//img.readybrides.com/94583/le-spose-di-gio-prev815.jpg" alt="Le Spose di Giò PREV8_15" style="width:100%;" /></a>
<!-- break -->
Buy it: [https://www.readybrides.com/en/le-spose-di-gio/43231-le-spose-di-gio-prev815.html](https://www.readybrides.com/en/le-spose-di-gio/43231-le-spose-di-gio-prev815.html)
| novstylessee/novstylessee.github.io | _posts/2016-04-28-Le-Spose-di-Gi-PREV815-2015.md | Markdown | mit | 706 |
package com.isme.zteui.cache;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.ImageLoader.ImageCache;
/**
* Title: Volley 的缓存类</br><br>
* Description: </br><br>
* Copyright: Copyright(c)2003</br><br>
* Company: ihalma </br><br>
* @author and</br><br>
* @version 1 </br><br>
* data: 2015-3-17</br>
*/
public class BitmapLruCache implements ImageCache {
private LruCache<String, Bitmap> mCache;
/**
* 最大缓存 10 M
*/
public BitmapLruCache() {
int maxSize = 1024 * 1024 * 10; //最大缓存10M
mCache = new LruCache<String, Bitmap>(maxSize){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
};
}
@Override
public Bitmap getBitmap(String url) {
return mCache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
mCache.put(url, bitmap);
}
}
| heyugtan/zteUI | ZTEUI/src/com/isme/zteui/cache/BitmapLruCache.java | Java | mit | 944 |
package uk.gov.gds.ier.transaction.overseas.dateLeftSpecial
import uk.gov.gds.ier.test.ControllerTestSuite
import uk.gov.gds.ier.model.{LastRegisteredToVote, LastRegisteredType, DOB, DateOfBirth}
import uk.gov.gds.ier.model.LastRegisteredType._
import uk.gov.gds.ier.transaction.overseas.InprogressOverseas
class DateLeftArmyStepTests extends ControllerTestSuite {
behavior of "DateLeftArmyStep.get"
it should "display the page" in {
running(FakeApplication()) {
val Some(result) = route(
FakeRequest(GET, "/register-to-vote/overseas/date-left-army").withIerSession()
)
status(result) should be(OK)
contentType(result) should be(Some("text/html"))
contentAsString(result) should include("When did you cease to be a member of the armed forces?")
contentAsString(result) should include("/register-to-vote/overseas/date-left-army")
}
}
behavior of "DateLeftArmyStep.post"
it should "bind successfully and redirect to the LastUKAddress step" in {
running(FakeApplication()) {
val Some(result) = route(
FakeRequest(POST, "/register-to-vote/overseas/date-left-army")
.withIerSession()
.withFormUrlEncodedBody(
"dateLeftSpecial.month" -> "10",
"dateLeftSpecial.year" -> "2000"
)
)
status(result) should be(SEE_OTHER)
redirectLocation(result) should be(Some("/register-to-vote/overseas/last-uk-address"))
}
}
it should "bind successfully and exit if it's been over 15 years when the user left the army" in {
running(FakeApplication()) {
val Some(result) = route(
FakeRequest(POST, "/register-to-vote/overseas/date-left-army")
.withIerSession()
.withFormUrlEncodedBody(
"dateLeftSpecial.month" -> "10",
"dateLeftSpecial.year" -> "1998"
)
)
status(result) should be(SEE_OTHER)
redirectLocation(result) should be(
Some("/register-to-vote/exit/overseas/left-service-over-15-years")
)
}
}
it should "display any errors on unsuccessful bind" in {
running(FakeApplication()) {
val Some(result) = route(
FakeRequest(POST, "/register-to-vote/overseas/date-left-army").withIerSession()
)
status(result) should be(OK)
contentAsString(result) should include("When did you cease to be a member of the armed forces?")
contentAsString(result) should include("Please answer this question")
contentAsString(result) should include("/register-to-vote/overseas/date-left-army")
}
}
behavior of "DateLeftArmyStep.editGet"
it should "display the edit page" in {
running(FakeApplication()) {
val Some(result) = route(
FakeRequest(GET, "/register-to-vote/overseas/edit/date-left-army").withIerSession()
)
status(result) should be(OK)
contentType(result) should be(Some("text/html"))
contentAsString(result) should include("When did you cease to be a member of the armed forces?")
contentAsString(result) should include("/register-to-vote/overseas/edit/date-left-army")
}
}
behavior of "DateLeftArmyStep.editPost"
it should "bind successfully and redirect to the lastUkAddress" in {
running(FakeApplication()) {
val Some(result) = route(
FakeRequest(POST, "/register-to-vote/overseas/edit/date-left-army")
.withIerSession()
.withFormUrlEncodedBody(
"dateLeftSpecial.month" -> "10",
"dateLeftSpecial.year" -> "2000")
)
status(result) should be(SEE_OTHER)
redirectLocation(result) should be(Some("/register-to-vote/overseas/last-uk-address"))
}
}
it should "bind successfully and exit if it's been over 15 years when the user left the army" in {
running(FakeApplication()) {
val Some(result) = route(
FakeRequest(POST, "/register-to-vote/overseas/edit/date-left-army")
.withIerSession()
.withFormUrlEncodedBody(
"dateLeftSpecial.month" -> "10",
"dateLeftSpecial.year" -> "1998"
)
)
status(result) should be(SEE_OTHER)
redirectLocation(result) should be(
Some("/register-to-vote/exit/overseas/left-service-over-15-years")
)
}
}
it should "display any errors on unsuccessful bind" in {
running(FakeApplication()) {
val Some(result) = route(
FakeRequest(POST, "/register-to-vote/overseas/edit/date-left-army").withIerSession()
)
status(result) should be(OK)
contentAsString(result) should include("When did you cease to be a member of the armed forces?")
contentAsString(result) should include("Please answer this question")
contentAsString(result) should include("/register-to-vote/overseas/edit/date-left-army")
}
}
behavior of "DateLeftArmyStep.post when complete application"
it should "bind successfully and redirect to the confirmation step if all steps complete" in {
running(FakeApplication()) {
val Some(result) = route(
FakeRequest(POST, "/register-to-vote/overseas/date-left-army")
.withIerSession()
.withApplication(completeOverseasApplication.copy(lastRegisteredToVote = Some(LastRegisteredToVote(LastRegisteredType.Forces))))
.withFormUrlEncodedBody(
"dateLeftSpecial.month" -> "10",
"dateLeftSpecial.year" -> "2000")
)
status(result) should be(SEE_OTHER)
redirectLocation(result) should be(Some("/register-to-vote/overseas/confirmation"))
}
}
behavior of "DateLeftArmyStep.editPost when complete application"
it should "bind successfully and redirect to the confirmation step if all steps complete" in {
running(FakeApplication()) {
val Some(result) = route(
FakeRequest(POST, "/register-to-vote/overseas/edit/date-left-army")
.withIerSession()
.withApplication(completeOverseasApplication.copy(lastRegisteredToVote = Some(LastRegisteredToVote(LastRegisteredType.Forces))))
.withFormUrlEncodedBody(
"dateLeftSpecial.month" -> "10",
"dateLeftSpecial.year" -> "2000")
)
status(result) should be(SEE_OTHER)
redirectLocation(result) should be(Some("/register-to-vote/overseas/confirmation"))
}
}
}
| michaeldfallen/ier-frontend | test/uk/gov/gds/ier/transaction/overseas/dateLeftSpecial/DateLeftArmyStepTests.scala | Scala | mit | 6,324 |
/* bzflag
* Copyright (c) 1993-2012 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* BillboardSceneNode:
* Encapsulates information for rendering a textured billboard.
*/
#ifndef BZF_BILLBOARD_SCENE_NODE_H
#define BZF_BILLBOARD_SCENE_NODE_H
#include "common.h"
#include "SceneNode.h"
#include "OpenGLLight.h"
class BillboardSceneNode : public SceneNode {
public:
BillboardSceneNode(const GLfloat pos[3]);
~BillboardSceneNode();
virtual BillboardSceneNode* copy() const;
void setLoop(bool = true);
void setDuration(float);
void resetTime();
void updateTime(float dt);
bool isAtEnd() const;
bool isLight() const;
void setLight(bool = true);
void setLightColor(GLfloat r, GLfloat g, GLfloat b);
void setLightAttenuation(GLfloat c, GLfloat l, GLfloat q);
void setLightScaling(GLfloat intensityScaleFactor);
void setLightFadeStartTime(float t);
void setGroundLight(bool value);
void setSize(float side);
void setSize(float width, float height);
void setColor(GLfloat r, GLfloat g,
GLfloat b, GLfloat a = 1.0f);
void setColor(const GLfloat* rgba);
void setTexture(const int);
void setTextureAnimation(int cu, int cv);
void move(const GLfloat pos[3]);
void setAngle(GLfloat);
void addLight(SceneRenderer&);
void notifyStyleChange();
void addRenderNodes(SceneRenderer&);
protected:
class BillboardRenderNode : public RenderNode {
public:
BillboardRenderNode(const BillboardSceneNode*);
~BillboardRenderNode();
void setColor(const GLfloat* rgba);
void render();
const GLfloat* getPosition() const { return sceneNode->getSphere(); }
void setFrame(float u, float v);
void setFrameSize(float du, float dv);
private:
const BillboardSceneNode* sceneNode;
float u, v;
GLfloat du, dv;
};
friend class BillboardRenderNode;
void setFrame();
void prepLight();
private:
bool show;
bool hasAlpha;
bool hasTexture;
bool hasTextureAlpha;
bool looping;
bool lightSource;
bool groundLight;
float width, height;
GLfloat color[4];
GLfloat angle;
GLfloat lightColor[3];
GLfloat lightScale;
float lightCutoffTime;
int cu, cv;
float t, duration;
OpenGLLight light;
OpenGLGState gstate;
BillboardRenderNode renderNode;
};
#endif // BZF_BILLBOARD_SCENE_NODE_H
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
| SlyMongoose/462Shootout | bzflag-2.4.2/include/BillboardSceneNode.h | C | mit | 2,940 |
# frozen_string_literal: true
module Hackbot
module Interactions
module Concerns
module Triggerable
extend ActiveSupport::Concern
SLACK_TEAM_ID = Rails.application.secrets.default_slack_team_id
class_methods do
# This constructs a fake Slack event to start the interaction with.
# It'll be sent to the interaction's start method.
def trigger(user_id, team = nil, channel_id = nil)
team ||= Hackbot::Team.find_by(team_id: SLACK_TEAM_ID)
event = FakeSlackEventService.new(team, user_id, channel_id).event
interaction = create(event: event, team: team)
interaction.handle
interaction.save!
interaction
end
end
end
end
end
end
| hackclub/api | app/models/hackbot/interactions/concerns/triggerable.rb | Ruby | mit | 794 |
module Fog
module Compute
class Google
class Mock
def insert_network(_network_name, _ip_range, _options = {})
Fog::Mock.not_implemented
end
end
class Real
def insert_network(network_name, ip_range, options = {})
api_method = @compute.networks.insert
parameters = {
"project" => @project
}
body_object = {
"name" => network_name,
"IPv4Range" => ip_range
}
body_object["description"] = options[:description] if options[:description]
body_object["gatewayIPv4"] = options[:gateway_ipv4] if options[:gateway_ipv4]
request(api_method, parameters, body_object)
end
end
end
end
end
| plribeiro3000/fog-google | lib/fog/compute/google/requests/insert_network.rb | Ruby | mit | 771 |
<!doctype html>
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<!-- begin SEO -->
<title>iVXjs</title>
<meta property="og:locale" content="en">
<meta property="og:site_name" content="iVXjs">
<meta property="og:title" content="iVXjs">
<link rel="canonical" href="http://localhost:4000/ivx-js/developer/configuration.rules/">
<meta property="og:url" content="http://localhost:4000/ivx-js/developer/configuration.rules/">
<script type="application/ld+json">
{
"@context" : "http://schema.org",
"@type" : "Person",
"name" : "Influence Technology",
"url" : "http://localhost:4000/ivx-js",
"sameAs" : null
}
</script>
<!-- end SEO -->
<link href="http://localhost:4000/ivx-js/feed.xml" type="application/atom+xml" rel="alternate" title="iVXjs Feed">
<!-- http://t.co/dKP3o1e -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
document.documentElement.className = document.documentElement.className.replace(/\bno-js\b/g, '') + ' js ';
</script>
<!-- For all browsers -->
<link rel="stylesheet" href="http://localhost:4000/ivx-js/assets/css/main.css">
<meta http-equiv="cleartype" content="on">
<!-- start custom head snippets -->
<!-- insert favicons. use http://realfavicongenerator.net/ -->
<!-- end custom head snippets -->
</head>
<body>
<!--[if lt IE 9]>
<div class="notice--danger align-center" style="margin: 0;">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</div>
<![endif]-->
<div class="masthead">
<div class="masthead__inner-wrap">
<div class="masthead__menu">
<nav id="site-nav" class="greedy-nav">
<button><div class="navicon"></div></button>
<ul class="visible-links">
<li class="masthead__menu-item masthead__menu-item--lg"><a href="http://localhost:4000/ivx-js/">iVXjs</a></li>
<li class="masthead__menu-item"><a href="http://localhost:4000/ivx-js/developer/tutorial.hello-world">Getting Started</a></li>
<li class="masthead__menu-item"><a href="http://localhost:4000/ivx-js/developer/tutorials">Tutorials</a></li>
<li class="masthead__menu-item"><a href="http://localhost:4000/ivx-js/developer/configuration">Configuration and Features</a></li>
</ul>
<ul class="hidden-links hidden"></ul>
</nav>
</div>
</div>
</div>
<div id="main" role="main">
<article class="page" itemscope itemtype="http://schema.org/CreativeWork">
<div class="page__inner-wrap">
<header>
</header>
<section class="page__content" itemprop="text">
<style>
/* Tooltip container */
.tooltip {
position: relative;
display: inline-block;
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
width:200px;
padding: 5px 5px;
border-radius: 6px;
border:solid 2px rgba(0,0,0,0.7);
background-color:white;
/* Position the tooltip text */
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -100px;
/* Fade in tooltip */
opacity: 0;
transition: opacity 0.5s;
}
/* Tooltip arrow */
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -9px;
border-width: 9px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.tooltip-header{
border-bottom:solid 1px;
text-align:center;
}
.addional-info-label{
display:block;
width:100%;
font-weight:bold;
}
.tooltip-content{
display:block;
width:100%;
padding:3px 10px;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
</style>
<h1 id="rules-configuration">Rules Configuration</h1>
<aside class="sidebar__right">
<nav class="toc">
<header><h4 class="nav__title"><i class="fa fa-file-text"></i> On This Page</h4></header>
<ul class="toc__menu" id="markdown-toc">
<li><a href="#rules-configuration" id="markdown-toc-rules-configuration">Rules Configuration</a> <ul>
<li><a href="#overview" id="markdown-toc-overview">Overview</a></li>
<li><a href="#note-about-this-documentation" id="markdown-toc-note-about-this-documentation">Note about this documentation</a></li>
<li><a href="#rule" id="markdown-toc-rule">Rule</a></li>
<li><a href="#condition-operator" id="markdown-toc-condition-operator">Condition Operator</a></li>
<li><a href="#base-conditions" id="markdown-toc-base-conditions">Base Conditions</a> <ul>
<li><a href="#input" id="markdown-toc-input">Input</a></li>
</ul>
</li>
<li><a href="#ivxio-conditions" id="markdown-toc-ivxio-conditions">iVXio Conditions</a> <ul>
<li><a href="#organization" id="markdown-toc-organization">Organization</a></li>
<li><a href="#entity" id="markdown-toc-entity">Entity</a></li>
<li><a href="#story-events" id="markdown-toc-story-events">Story Events</a></li>
<li><a href="#progress" id="markdown-toc-progress">Progress</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</aside>
<h2 id="overview">Overview</h2>
<p>Rules are objects in a JSON that determine whether an action is fired or a state is navigated to by a user.
In the basic library, you will natively be able to navigate the user based on the questions and forms they answered.</p>
<p>If you are using the iVX.io Data Module, you can use the Platform’s tracking of a user’s progress and their relationship to organizations and
entities to run rules.</p>
<h2 id="note-about-this-documentation">Note about this documentation</h2>
<p>This page assumes you know how Rules and Conditions work within the config. If you would like to learn more about how Rules work and where
you can use them, you can go to the main JSON configuration.</p>
<h2 id="rule">Rule</h2>
<p><em>Sample Data</em></p>
<p><a href="https://influencetech.github.io/ivx-js/developer/sample-JSON/rules.json">rules.json</a></p>
<p><em>Schema</em></p>
<p><a href="https://influencetech.github.io/ivx-js/developer/schemas/rules.jsond">rules.jsond</a></p>
<p><em>Base Properties</em></p>
<div id="rule-schema" class="json-schema-table-container" data-json-src="https://influencetech.github.io/ivx-js/developer/schemas/rules.jsond"></div>
<h2 id="condition-operator">Condition Operator</h2>
<p>Description: the condition operator determines which conditions within the rule must be true in order for the corresponding state associated with the rule to occur.</p>
<p>Operator Types:</p>
<ol>
<li>
<p>“and” (synonymous with && - ALL conditions must be true)</p>
</li>
<li>
<p>“or” (synonymous with || - One of the conditions must be true)</p>
</li>
<li>
<p>“not” (!cond1 && !cond2 - ALL conditions must NOT be true)</p>
</li>
</ol>
<h2 id="base-conditions">Base Conditions</h2>
<h3 id="input">Input</h3>
<p>Description: Inputs gather information about the user so they can be directed towards a specific state, and customize the experience based on the information gathered.</p>
<p><em>Sample Data</em></p>
<p><a href="https://influencetech.github.io/ivx-js/developer/sample-JSON/rules.conditions.input.json">rules.conditions.inputs.json</a></p>
<p><em>Schema</em></p>
<p><a href="https://influencetech.github.io/ivx-js/developer/schemas/rules.conditions.input.jsond">rules.condition.inputs.jsond</a></p>
<p><em>Base Properties</em></p>
<div id="input-condition-schema" class="json-schema-table-container" data-json-src="https://influencetech.github.io/ivx-js/developer/schemas/rules.conditions.input.jsond"></div>
<h2 id="ivxio-conditions">iVXio Conditions</h2>
<h3 id="organization">Organization</h3>
<p>Description: The organization condition is evaluated based on specific organization data set by the associated child entity this experience belongs to.</p>
<p><em>Sample Data</em></p>
<p><a href="https://influencetech.github.io/ivx-js/developer/sample-JSON/rules.conditions.organization.json">rules.conditions.organization.json</a></p>
<p><em>Schema</em></p>
<p><a href="https://influencetech.github.io/ivx-js/developer/schemas/rules.conditions.organization.jsond">rules.conditions.organization.jsond</a></p>
<p><em>Base Properties</em></p>
<div id="organization-condition-schema" class="json-schema-table-container" data-json-src="https://influencetech.github.io/ivx-js/developer/schemas/rules.conditions.organization.jsond"></div>
<h3 id="entity">Entity</h3>
<p>Description: The entity refers to any sub-organizations or partners affiliated with the parent organization.</p>
<p><em>Sample Data</em></p>
<p><a href="https://influencetech.github.io/ivx-js/developer/sample-JSON/rules.conditions.entity.json">rules.conditions.entity.json</a></p>
<p><em>Schema</em></p>
<p><a href="https://influencetech.github.io/ivx-js/developer/schemas/rules.conditions.entity.jsond">rules.conditions.entity.jsond</a></p>
<p><em>Base Properties</em></p>
<div id="entity-condition-schema" class="json-schema-table-container" data-json-src="https://influencetech.github.io/ivx-js/developer/schemas/rules.conditions.entity.jsond"></div>
<h3 id="story-events">Story Events</h3>
<p>Description: A story event occurs based on if the condition evaluates to fired or not fired, and is meant to guide the user to a specific state or place. The resulting action can be either within (story event) or outside (external event) of the experience.</p>
<p><em>Sample Data</em></p>
<p><a href="https://influencetech.github.io/ivx-js/developer/sample-JSON/rules.conditions.storyEvents.json">rules.conditions.storyEvents.json</a></p>
<p><em>Schema</em></p>
<p><a href="https://influencetech.github.io/ivx-js/developer/schemas/rules.conditions.storyEvents.jsond">rules.conditions.storyEvents.jsond</a></p>
<p><em>Base Properties</em></p>
<div id="storyEvents-condition-schema" class="json-schema-table-container" data-json-src="https://influencetech.github.io/ivx-js/developer/schemas/rules.conditions.storyEvents.jsond"></div>
<h3 id="progress">Progress</h3>
<p>Description: Progress refers to the user’s place in the experience and if something should be initiated once they have reached a point within the experience.</p>
<p><em>Sample Data</em></p>
<p><a href="https://influencetech.github.io/ivx-js/developer/sample-JSON/rules.conditions.progress.json">rules.conditions.progress.json</a></p>
<p><em>Schema</em></p>
<p><a href="https://influencetech.github.io/ivx-js/developer/schemas/rules.conditions.progress.jsond">rules.conditions.progress.jsond</a></p>
<p><em>Base Properties</em></p>
<div id="progress-condition-schema" class="json-schema-table-container" data-json-src="https://influencetech.github.io/ivx-js/developer/schemas/rules.conditions.progress.jsond"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.2/lodash.min.js"></script>
<script src="https://influencetech.github.io/ivx-js/assets/js/jsond-table-creator.js"></script>
</section>
<footer class="page__meta">
</footer>
</div>
</article>
</div>
<div class="page__footer">
<footer>
<!-- start custom footer snippets -->
<!-- end custom footer snippets -->
<div class="page__footer-follow">
<ul class="social-icons">
<li><strong>Follow:</strong></li>
<li><a href="http://localhost:4000/ivx-js/feed.xml"><i class="fa fa-fw fa-rss-square" aria-hidden="true"></i> Feed</a></li>
</ul>
</div>
<div class="page__footer-copyright">© 2018 Influence Technology. Powered by <a href="http://jekyllrb.com" rel="nofollow">Jekyll</a> & <a href="https://mademistakes.com/work/minimal-mistakes-jekyll-theme/" rel="nofollow">Minimal Mistakes</a>.</div>
</footer>
</div>
<script src="http://localhost:4000/ivx-js/assets/js/main.min.js"></script>
</body>
</html>
| influencetech/ivx-js | docs/_site/developer/configuration.rules/index.html | HTML | mit | 12,471 |
package warhammerrpg.database.exception;
import warhammerrpg.core.exception.WarhammerRpgException;
public class DatabaseException extends WarhammerRpgException {
public DatabaseException(Exception originalExceptionObject) {
super(originalExceptionObject);
}
public DatabaseException() {
super();
}
}
| tomaszkowalczyk94/warhammer-rpg-helper | src/main/java/warhammerrpg/database/exception/DatabaseException.java | Java | mit | 335 |
# BitcoinJS (bitcoinjs-lib)
[](https://travis-ci.org/bitcoinjs/bitcoinjs-lib)
[](https://coveralls.io/r/bitcoinjs/bitcoinjs-lib)
[](http://tip4commit.com/projects/735)
[](https://nodei.co/npm/bitcoinjs-lib/)
[](https://ci.testling.com/bitcoinjs/bitcoinjs-lib)
The pure JavaScript Bitcoin library for node.js and browsers.
A continued implementation of the original `0.1.3` version used by over a million wallet users; the backbone for almost all Bitcoin web wallets in production today.
## Features
- Clean: Pure JavaScript, concise code, easy to read.
- Tested: Coverage > 90%, third-party integration tests.
- Careful: Two person approval process for small, focused pull requests.
- Compatible: Works on Node.js and all modern browsers.
- Powerful: Support for advanced features, such as multi-sig, HD Wallets.
- Secure: Strong random number generation, PGP signed releases, trusted developers.
- Principled: No support for browsers with crap RNG (IE < 11)
- Standardized: Node community coding style, Browserify, Node's stdlib and Buffers.
- Fast: Optimized code, uses typed arrays instead of byte arrays for performance.
- Experiment-friendly: Bitcoin Mainnet and Testnet support.
- Altcoin-ready: Capable of working with bitcoin-derived cryptocurrencies (such as Dogecoin).
## Should I use this in production?
If you are thinking of using the master branch of this library in production, *stop*.
Master is not stable; it is our development branch, and only tagged releases may be classified as stable.
If you are looking for the original, it is tagged as `0.1.3`. Unless you need it for dependency reasons, it is strongly recommended that you use (or upgrade to) the newest version, which adds major functionality, cleans up the interface, fixes many bugs, and adds over 1,300 more tests.
## Installation
`npm install bitcoinjs-lib`
## Setup
### Node.js
var bitcoin = require('bitcoinjs-lib')
From the repo:
var bitcoin = require('./src/index.js')
### Browser
From the repository: Compile `bitcoinjs-min.js` with the following command:
$ npm run-script compile
From NPM:
$ npm -g install bitcoinjs-lib browserify uglify-js
$ browserify -r bitcoinjs-lib -s Bitcoin | uglifyjs > bitcoinjs.min.js
After loading this file in your browser, you will be able to use the global `bitcoin` object.
## Usage
These examples assume you are running bitcoinjs-lib in the browser.
### Generating a Bitcoin address
```javascript
key = bitcoin.ECKey.makeRandom()
// Print your private key (in WIF format)
console.log(key.toWIF())
// => Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct
// Print your public key (toString defaults to a Bitcoin address)
console.log(key.pub.getAddress().toString())
// => 14bZ7YWde4KdRb5YN7GYkToz3EHVCvRxkF
```
### Creating a Transaction
```javascript
tx = new bitcoin.Transaction()
// Add the input (who is paying) of the form [previous transaction hash, index of the output to use]
tx.addInput("aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31", 0)
// Add the output (who to pay to) of the form [payee's address, amount in satoshis]
tx.addOutput("1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK", 15000)
// Initialize a private key using WIF
key = bitcoin.ECKey.fromWIF("L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy")
// Sign the first input with the new key
tx.sign(0, key)
// Print transaction serialized as hex
console.log(tx.toHex())
// => 0100000001313eb630b128102b60241ca895f1d0ffca2170d5a0990e094f2182c102ab94aa000000008a47304402200169f1f844936dc60df54e812345f5dd3e6681fea52e33c25154ad9cc23a330402204381ed8e73d74a95b15f312f33d5a0072c7a12dd6c3294df6e8efbe4aff27426014104e75628573696aed32d7656fb35e9c71ea08eb6492837e13d2662b9a36821d0fff992692fd14d74fdec20fae29128ba12653249cbeef521fc5eba84dde0689f27ffffffff01983a0000000000001976a914ad618cf4333b3b248f9744e8e81db2964d0ae39788ac00000000
// You could now push the transaction onto the Bitcoin network manually (see https://blockchain.info/pushtx)
```
### Creating a P2SH Multsig Address
``` javascript
var bitcoin = require('bitcoinjs-lib')
var privKeys = [bitcoin.ECKey.makeRandom(), bitcoin.ECKey.makeRandom(), bitcoin.ECKey.makeRandom()]
var pubKeys = privKeys.map(function(x) { return x.pub })
var redeemScript = bitcoin.scripts.multisigOutput(2, pubKeys) // 2 of 3
var scriptPubKey = bitcoin.scripts.scriptHashOutput(redeemScript.getHash())
var multisigAddress = bitcoin.Address.fromOutputScript(scriptPubKey).toString()
console.log("multisigP2SH:", multisigAddress)
// => multisigP2SH: 35k9EWv2F1X5JKXHSF1DhTm7Ybdiwx4RkD
```
## Projects utilizing BitcoinJS
- [Coinpunk](https://coinpunk.com)
- [Hive Wallet](https://www.hivewallet.com)
- [Justchain Exchange](https://justcoin.com)
- [Skyhook ATM](http://projectskyhook.com)
- [BitAddress](https://www.bitaddress.org)
- [Blockchain.info](https://blockchain.info/wallet)
- [Brainwallet](https://brainwallet.github.io)
- [Dark Wallet](https://darkwallet.unsystem.net)
- [Dogechain Wallet](https://dogechain.info)
- [GreenAddress](https://greenaddress.it)
- [DecentralBank](http://decentralbank.co)
- [Quickcoin](https://wallet.quickcoin.co)
## Contributors
Stefan Thomas is the inventor and creator of this project. His pioneering work made Bitcoin web wallets possible.
Since then, many people have contributed. [Click here](https://github.com/bitcoinjs/bitcoinjs-lib/graphs/contributors) to see the comprehensive list.
Daniel Cousens, Wei Lu, JP Richardson and Kyle Drake lead the major refactor of the library from 0.1.3 to 1.0.0.
## Contributing
Join the ongoing IRC development channel at `#bitcoinjs-dev` on Freenode.
We are always accepting of Pull requests, but we do adhere to specific standards in regards to coding style, test driven development and commit messages.
Please make your best effort to adhere to these when contributing to save on trivial corrections.
### Running the test suite
$ npm test
$ npm run-script coverage
## Complementing Libraries
- [BIP39](https://github.com/weilu/bip39) - Mnemonic code for generating deterministic keys
- [BIP38](https://github.com/cryptocoinjs/bip38) - Passphrase-protected private keys
- [BCoin](https://github.com/indutny/bcoin) - BIP37 / Bloom Filters / SPV client
- [insight](https://github.com/bitpay/insight) - A bitcoin blockchain API for web wallets.
## Alternatives
- [Bitcore](https://github.com/bitpay/bitcore)
- [Cryptocoin](https://github.com/cryptocoinjs/cryptocoin)
## License
This library is free and open-source software released under the MIT license.
## Copyright
BitcoinJS (c) 2011-2014 Bitcoinjs-lib contributors
Released under MIT license
| MODULHAUS/bitcoinjs-lib | README.md | Markdown | mit | 7,003 |
package org.ethereum.android.service;
import android.os.Message;
public interface ConnectorHandler {
boolean handleMessage(Message message);
void onConnectorConnected();
void onConnectorDisconnected();
String getID();
}
| BlockchainSociety/ethereumj-android | ethereumj-core-android/src/main/java/org/ethereum/android/service/ConnectorHandler.java | Java | mit | 240 |
package gwent
const (
// AbilityNone means unit card has no ability at all
AbilityNone = iota
)
// CardUnit is single unit used for combat
type CardUnit struct {
UnitType CardType
UnitRange CardRange
UnitFaction CardFaction
UnitPower, UnitAbility int
UnitHero bool
BasicCard
}
// Play puts unit card to table
func (c *CardUnit) Play(p *Player, target Card) {
c.PutOnTable(p)
}
// PutOnTable puts unit card to table
func (c *CardUnit) PutOnTable(p *Player) {
//Add card to proper row
switch c.Range() {
case RangeClose:
p.RowClose = append(p.RowClose, c)
case RangeRanged:
p.RowRanged = append(p.RowRanged, c)
case RangeSiege:
p.RowSiege = append(p.RowSiege, c)
}
}
// Type reports type of this unit card
func (c *CardUnit) Type() CardType {
return c.UnitType
}
// Faction reports faction of this unit card
func (c *CardUnit) Faction() CardFaction {
return c.UnitFaction
}
// Range reports range of this unit card
func (c *CardUnit) Range() CardRange {
return c.UnitRange
}
// Power reports power of this unit card
func (c *CardUnit) Power(p *Player) int {
pwr := c.UnitPower
//Apply weather if not a hero card
if !c.Hero() && ((c.Range() == RangeClose && p.Game.WeatherClose) ||
(c.Range() == RangeRanged && p.Game.WeatherRanged) ||
(c.Range() == RangeSiege && p.Game.WeatherSiege)) {
pwr = 1
}
//Apply horn if available
if (c.Range() == RangeClose && p.HornClose) ||
(c.Range() == RangeRanged && p.HornRanged) ||
(c.Range() == RangeSiege && p.HornSiege) {
pwr *= 2
}
return pwr
}
// Hero reports if this unit card is hero card
func (c *CardUnit) Hero() bool {
return c.UnitHero
}
// Targettable reports if this card can be targetted or not
func (c *CardUnit) Targettable() bool {
//TODO: Treat by unit ability
return false
}
| bobesa/gwent | gwent/card.unit.go | GO | mit | 1,807 |
class Foo { [prop1]: string; } | motiz88/astring-flow | test/data/roundtrip/flow-parser-tests/test-046.js | JavaScript | mit | 30 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>18 --> 19</title>
<link href="./../../assets/style.css" rel="stylesheet">
</head>
<body>
<h2>You have to be fast</h2>
<a href="./7da62ab117a27e8ed347abb6844f95299b2c37f4fb4ab14c41ec8dfcb8c80f76.html">Teleport</a>
<hr>
<a href="./../../about.md">About</a> (Spoilers! )
<script src="./../../assets/md5.js"></script>
<script>
window.currentLevel = 7;
</script>
<script src="./../../assets/script.js"></script>
</body>
</html> | simonmysun/praxis | TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/ae941745dde38bef1cc20cc48dac5247104fc6f0db89bec7121c90d18e742ac4.html | HTML | mit | 550 |
package medtronic
import (
"bytes"
"fmt"
"log"
"github.com/ecc1/medtronic/packet"
)
// Command represents a pump command.
type Command byte
//go:generate stringer -type Command
const (
ack Command = 0x06
nak Command = 0x15
cgmWriteTimestamp Command = 0x28
setBasalPatternA Command = 0x30
setBasalPatternB Command = 0x31
setClock Command = 0x40
setMaxBolus Command = 0x41
bolus Command = 0x42
selectBasalPattern Command = 0x4A
setAbsoluteTempBasal Command = 0x4C
suspend Command = 0x4D
button Command = 0x5B
wakeup Command = 0x5D
setPercentTempBasal Command = 0x69
setMaxBasal Command = 0x6E
setBasalRates Command = 0x6F
clock Command = 0x70
pumpID Command = 0x71
battery Command = 0x72
reservoir Command = 0x73
firmwareVersion Command = 0x74
errorStatus Command = 0x75
historyPage Command = 0x80
carbUnits Command = 0x88
glucoseUnits Command = 0x89
carbRatios Command = 0x8A
insulinSensitivities Command = 0x8B
glucoseTargets512 Command = 0x8C
model Command = 0x8D
settings512 Command = 0x91
basalRates Command = 0x92
basalPatternA Command = 0x93
basalPatternB Command = 0x94
tempBasal Command = 0x98
glucosePage Command = 0x9A
isigPage Command = 0x9B
calibrationFactor Command = 0x9C
lastHistoryPage Command = 0x9D
glucoseTargets Command = 0x9F
settings Command = 0xC0
cgmPageCount Command = 0xCD
status Command = 0xCE
vcntrPage Command = 0xD5
)
// NoResponseError indicates that no response to a command was received.
type NoResponseError Command
func (e NoResponseError) Error() string {
return fmt.Sprintf("no response to %v", Command(e))
}
// NoResponse checks whether the pump has a NoResponseError.
func (pump *Pump) NoResponse() bool {
_, ok := pump.Error().(NoResponseError)
return ok
}
// InvalidCommandError indicates that the pump rejected a command as invalid.
type InvalidCommandError struct {
Command Command
PumpError PumpError
}
// PumpError represents an error response from the pump.
type PumpError byte
//go:generate stringer -type PumpError
// Pump error codes.
const (
CommandRefused PumpError = 0x08
SettingOutOfRange PumpError = 0x09
BolusInProgress PumpError = 0x0C
InvalidHistoryPageNumber PumpError = 0x0D
)
func (e InvalidCommandError) Error() string {
return fmt.Sprintf("%v error: %v", e.Command, e.PumpError)
}
// BadResponseError indicates an unexpected response to a command.
type BadResponseError struct {
Command Command
Data []byte
}
func (e BadResponseError) Error() string {
return fmt.Sprintf("unexpected response to %v: % X", e.Command, e.Data)
}
// BadResponse sets the pump's error state to a BadResponseError.
func (pump *Pump) BadResponse(cmd Command, data []byte) {
pump.SetError(BadResponseError{Command: cmd, Data: data})
}
const (
shortPacketLength = 6 // excluding CRC byte
longPacketLength = 70 // excluding CRC byte
encodedLongPacketLength = 107
payloadLength = 64
fragmentLength = payloadLength + 1 // including sequence number
doneBit = 1 << 7
maxNAKs = 10
)
var (
shortPacket = make([]byte, shortPacketLength)
longPacket = make([]byte, longPacketLength)
ackPacket []byte
)
func precomputePackets() {
addr := PumpAddress()
shortPacket[0] = packet.Pump
copy(shortPacket[1:4], addr)
longPacket[0] = packet.Pump
copy(longPacket[1:4], addr)
ackPacket = shortPumpPacket(ack)
}
// shortPumpPacket constructs a 7-byte packet with the specified command code:
// device type (0xA7)
// 3 bytes of pump ID
// command code
// length of parameters (0)
// CRC-8 (added by packet.Encode)
func shortPumpPacket(cmd Command) []byte {
p := shortPacket
p[4] = byte(cmd)
p[5] = 0
return packet.Encode(p)
}
// longPumpPacket constructs a 71-byte packet with
// the specified command code and parameters:
// device type (0xA7)
// 3 bytes of pump ID
// command code
// length of parameters (or fragment number if non-zero)
// 64 bytes of parameters plus zero padding
// CRC-8 (added by packet.Encode)
func longPumpPacket(cmd Command, fragNum int, params []byte) []byte {
p := longPacket
p[4] = byte(cmd)
if fragNum == 0 {
p[5] = byte(len(params))
} else {
// Use a fragment number instead of the length.
p[5] = uint8(fragNum)
}
copy(p[6:], params)
// Zero-pad the remainder of the packet.
for i := 6 + len(params); i < longPacketLength; i++ {
p[i] = 0
}
return packet.Encode(p)
}
// Execute sends a command and parameters to the pump and returns its response.
// Commands with parameters require an initial exchange with no parameters,
// followed by an exchange with the actual arguments.
func (pump *Pump) Execute(cmd Command, params ...byte) []byte {
if len(params) == 0 {
return pump.perform(cmd, cmd, shortPumpPacket(cmd))
}
pump.perform(cmd, ack, shortPumpPacket(cmd))
if pump.NoResponse() {
pump.SetError(fmt.Errorf("%v command not performed", cmd))
return nil
}
t := pump.Timeout()
defer pump.SetTimeout(t)
pump.SetTimeout(2 * t)
return pump.perform(cmd, ack, longPumpPacket(cmd, 0, params))
}
// ExtendedRequest sends a command and a sequence of parameter packets
// to the pump and returns its response.
func (pump *Pump) ExtendedRequest(cmd Command, params ...byte) []byte {
seqNum := 1
i := 0
var result []byte
done := false
for !done && pump.Error() == nil {
j := i + payloadLength
if j >= len(params) {
done = true
j = len(params)
}
if seqNum == 1 {
pump.perform(cmd, ack, shortPumpPacket(cmd))
if pump.NoResponse() {
pump.SetError(fmt.Errorf("%v command not performed", cmd))
break
}
}
p := longPumpPacket(cmd, seqNum, params[i:j])
data := pump.perform(cmd, ack, p)
result = append(result, data...)
seqNum++
i = j
}
if done {
t := pump.Timeout()
defer pump.SetTimeout(t)
pump.SetTimeout(2 * t)
p := longPumpPacket(cmd, seqNum|doneBit, nil)
data := pump.perform(cmd, ack, p)
result = append(result, data...)
}
return result
}
// ExtendedResponse sends a command and parameters to the pump and
// collects the sequence of packets that make up its response.
func (pump *Pump) ExtendedResponse(cmd Command, params ...byte) []byte {
var result []byte
data := pump.Execute(cmd, params...)
expected := 1
retries := pump.Retries()
defer pump.SetRetries(retries)
pump.SetRetries(1)
for pump.Error() == nil {
if len(data) != fragmentLength {
pump.SetError(fmt.Errorf("%v: received %d-byte response", cmd, len(data)))
break
}
seqNum := int(data[0] &^ doneBit)
if seqNum != expected {
pump.SetError(fmt.Errorf("%v: received response %d instead of %d", cmd, seqNum, expected))
break
}
result = append(result, data[1:]...)
if data[0]&doneBit != 0 {
break
}
// Acknowledge this fragment.
data = pump.perform(ack, cmd, ackPacket)
expected++
}
return result
}
// History pages are returned as a series of 65-byte fragments:
// sequence number (1 to numFragments)
// 64 bytes of payload
// The caller must send an ACK to receive the next fragment
// or a NAK to have the current one retransmitted.
// The 0x80 bit is set in the sequence number of the final fragment.
// The page consists of the concatenated payloads.
// The final 2 bytes are the CRC-16 of the preceding data.
type pageStructure struct {
paramBytes int // 1 or 4
numFragments int // 16 or 32 fragments of 64 bytes each
}
var pageData = map[Command]pageStructure{
historyPage: {
paramBytes: 1,
numFragments: 16,
},
glucosePage: {
paramBytes: 4,
numFragments: 16,
},
isigPage: {
paramBytes: 4,
numFragments: 32,
},
vcntrPage: {
paramBytes: 1,
numFragments: 16,
},
}
// Download requests the given history page from the pump.
func (pump *Pump) Download(cmd Command, page int) []byte {
maxTries := pump.Retries()
defer pump.SetRetries(maxTries)
pump.SetRetries(1)
for tries := 0; tries < maxTries; tries++ {
pump.SetError(nil)
data := pump.tryDownload(cmd, page)
if pump.Error() == nil {
logTries(cmd, tries)
return data
}
}
return nil
}
func (pump *Pump) tryDownload(cmd Command, page int) []byte {
data := pump.execPage(cmd, page)
if pump.Error() != nil {
return nil
}
numFragments := pageData[cmd].numFragments
results := make([]byte, 0, numFragments*payloadLength)
seq := 1
for {
payload, n := pump.checkFragment(page, data, seq, numFragments)
if pump.Error() != nil {
return nil
}
if n == seq {
results = append(results, payload...)
seq++
}
if n == numFragments {
return pump.checkPageCRC(page, results)
}
// Acknowledge the current fragment and receive the next.
next := pump.perform(ack, cmd, ackPacket)
if pump.Error() != nil {
if !pump.NoResponse() {
return nil
}
next = pump.handleNoResponse(cmd, page, seq)
}
data = next
}
}
func (pump *Pump) execPage(cmd Command, page int) []byte {
n := pageData[cmd].paramBytes
switch n {
case 1:
return pump.Execute(cmd, byte(page))
case 4:
return pump.Execute(cmd, marshalUint32(uint32(page))...)
default:
log.Panicf("%v: unexpected parameter size (%d bytes)", cmd, n)
}
panic("unreachable")
}
// checkFragment verifies that a fragment has the expected sequence number
// and returns the payload and sequence number.
func (pump *Pump) checkFragment(page int, data []byte, expected int, numFragments int) ([]byte, int) {
if len(data) != fragmentLength {
pump.SetError(fmt.Errorf("history page %d: unexpected fragment length (%d)", page, len(data)))
return nil, 0
}
seqNum := int(data[0] &^ doneBit)
if seqNum > expected {
// Missed fragment.
pump.SetError(fmt.Errorf("history page %d: received fragment %d instead of %d", page, seqNum, expected))
return nil, 0
}
if seqNum < expected {
// Skip duplicate responses.
return nil, seqNum
}
// This is the next fragment.
done := data[0]&doneBit != 0
if (done && seqNum != numFragments) || (!done && seqNum == numFragments) {
pump.SetError(fmt.Errorf("history page %d: unexpected final sequence number (%d)", page, seqNum))
return nil, seqNum
}
return data[1:], seqNum
}
// handleNoResponse sends NAKs to request retransmission of the expected fragment.
func (pump *Pump) handleNoResponse(cmd Command, page int, expected int) []byte {
for count := 0; count < maxNAKs; count++ {
pump.SetError(nil)
data := pump.perform(nak, cmd, shortPumpPacket(nak))
if pump.Error() == nil {
seqNum := int(data[0] &^ doneBit)
format := "history page %d: received fragment %d after %d NAK"
if count != 0 {
format += "s"
}
log.Printf(format, page, seqNum, count+1)
return data
}
if !pump.NoResponse() {
return nil
}
}
pump.SetError(fmt.Errorf("history page %d: lost fragment %d", page, expected))
return nil
}
// checkPageCRC verifies the history page CRC and returns the page data with the CRC removed.
// In a 2048-byte ISIG page, the CRC-16 is stored in the last 4 bytes: [high 0 low 0]
func (pump *Pump) checkPageCRC(page int, data []byte) []byte {
if len(data) != cap(data) {
pump.SetError(fmt.Errorf("history page %d: unexpected size (%d)", page, len(data)))
return nil
}
var dataCRC uint16
switch cap(data) {
case 1024:
dataCRC = twoByteUint(data[1022:])
data = data[:1022]
case 2048:
dataCRC = uint16(data[2044])<<8 | uint16(data[2046])
data = data[:2044]
default:
log.Panicf("unexpected history page size (%d)", cap(data))
}
calcCRC := packet.CRC16(data)
if calcCRC != dataCRC {
pump.SetError(fmt.Errorf("history page %d: computed CRC %04X but received %04X", page, calcCRC, dataCRC))
return nil
}
return data
}
func (pump *Pump) perform(cmd Command, resp Command, p []byte) []byte {
if pump.Error() != nil {
return nil
}
maxTries := pump.retries
if len(p) == encodedLongPacketLength {
// Don't attempt state-changing commands more than once.
maxTries = 1
}
for tries := 0; tries < maxTries; tries++ {
pump.SetError(nil)
response, rssi := pump.Radio.SendAndReceive(p, pump.Timeout())
if pump.Error() != nil {
continue
}
if len(response) == 0 {
pump.SetError(NoResponseError(cmd))
continue
}
data, err := packet.Decode(response)
if err != nil {
pump.SetError(err)
continue
}
if pump.unexpected(cmd, resp, data) {
return nil
}
logTries(cmd, tries)
pump.rssi = rssi
return data[5:]
}
if pump.Error() == nil {
panic("perform")
}
return nil
}
func logTries(cmd Command, tries int) {
if tries == 0 {
return
}
r := "retries"
if tries == 1 {
r = "retry"
}
log.Printf("%v command required %d %s", cmd, tries, r)
}
func (pump *Pump) unexpected(cmd Command, resp Command, data []byte) bool {
if len(data) < 6 {
pump.BadResponse(cmd, data)
return true
}
if !bytes.Equal(data[:4], shortPacket[:4]) {
pump.BadResponse(cmd, data)
return true
}
switch Command(data[4]) {
case cmd:
return false
case resp:
return false
case ack:
if cmd == cgmWriteTimestamp || cmd == wakeup {
return false
}
pump.BadResponse(cmd, data)
return true
case nak:
pump.SetError(InvalidCommandError{
Command: cmd,
PumpError: PumpError(data[5]),
})
return true
default:
pump.BadResponse(cmd, data)
return true
}
}
| ecc1/medtronic | command.go | GO | mit | 13,574 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.