text
stringlengths
2
1.04M
meta
dict
package us.dot.its.jpo.ode.udp; //TODO open-ode // //import java.io.IOException; //import java.net.DatagramPacket; //import java.net.DatagramSocket; //import java.util.Arrays; //import java.util.concurrent.Callable; // //import us.dot.its.jpo.ode.OdeProperties; // ///** // * Threadable DatagramSocket receiver // */ //public abstract class AbstractConcurrentUdpReceiver implements Callable<AbstractData> { // // public class AbstractConcurrentUdpReceiverException extends Exception { // // private static final long serialVersionUID = 1L; // // public AbstractConcurrentUdpReceiverException(String string, Exception e) { // super(string, e); // } // } // // protected DatagramSocket socket; // protected OdeProperties odeProperties; // protected int bufferSize; // // protected abstract AbstractData processPacket(byte[] p) // throws DecodeFailedException, DecodeNotSupportedException, IOException; // // protected AbstractConcurrentUdpReceiver(DatagramSocket sock, int bufSize) { // this.socket = sock; // this.bufferSize = bufSize; // } // // protected AbstractData receiveDatagram() throws AbstractConcurrentUdpReceiverException { // AbstractData response = null; // try { // byte[] buffer = new byte[bufferSize]; // DatagramPacket resPack = new DatagramPacket(buffer, buffer.length); // socket.receive(resPack); // // if (buffer.length <= 0) // throw new IOException("Empty datagram packet."); // // byte[] packetData = Arrays.copyOf(resPack.getData(), resPack.getLength()); // // response = processPacket(packetData); // } catch (Exception e) { // throw new AbstractConcurrentUdpReceiverException("Error receiving data on UDP socket.", e); // } // // return response; // } // // @Override // public AbstractData call() throws Exception { // return receiveDatagram(); // } // //}
{ "content_hash": "c314255e1177e3c6c4acc52890f2bbe1", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 102, "avg_line_length": 30.936507936507937, "alnum_prop": 0.672139558748076, "repo_name": "hmusavi/jpo-ode", "id": "0ae4d1869a0f53018b226beca9882548dc5ca10c", "size": "1949", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "jpo-ode-svcs/src/main/java/us/dot/its/jpo/ode/udp/AbstractConcurrentUdpReceiver.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1948" }, { "name": "C", "bytes": "4075" }, { "name": "CSS", "bytes": "1617" }, { "name": "HTML", "bytes": "4849" }, { "name": "Java", "bytes": "2739989" }, { "name": "JavaScript", "bytes": "3219" }, { "name": "Shell", "bytes": "7650" } ], "symlink_target": "" }
package com.bitdubai.fermat_dap_android_sub_app_asset_issuer_community_bitdubai; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
{ "content_hash": "f14299aed3fff84f181f99b723dcc819", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 80, "avg_line_length": 24.266666666666666, "alnum_prop": 0.7115384615384616, "repo_name": "fvasquezjatar/fermat-unused", "id": "aa3d642537eefacfe1f1ea5fdadbf701771edf7d", "size": "364", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DAP/android/sub_app/fermat-dap-android-sub-app-asset-issuer-community-bitdubai/src/test/java/com/bitdubai/fermat_dap_android_sub_app_asset_issuer_community_bitdubai/ExampleUnitTest.java", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "1204" }, { "name": "Groovy", "bytes": "76309" }, { "name": "HTML", "bytes": "322840" }, { "name": "Java", "bytes": "14027288" }, { "name": "Scala", "bytes": "1353" } ], "symlink_target": "" }
#include "wavemon.h" #include "nl80211.h" #include <netdb.h> #include <stdbool.h> #include <pthread.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netinet/ether.h> #include <net/if_arp.h> #include <net/ethernet.h> #include <sys/socket.h> #include <linux/if.h> #include <linux/wireless.h> #include <stdio.h> #include <time.h> /* Definitions that appeared in more recent versions of wireless.h */ #ifndef IW_POWER_SAVING #define IW_POWER_SAVING 0x4000 /* version 20 -> 21 */ #endif #ifndef IW_MODE_MESH #define IW_MODE_MESH 7 /* introduced in 2.6.26-rc1 */ #endif /** * struct if_info - wireless interface network information * @hwaddr: MAC address * @addr: IPv4 interface address * @netmask: IPv4 interface netmask * @bcast: IPv4 interface broadcast address * @mtu: interface MTU * @txqlen: tx queue length * @flags: interface flags * See also netdevice(7) */ struct if_info { struct ether_addr hwaddr; struct in_addr addr, netmask, bcast; uint16_t mtu; uint16_t txqlen; uint16_t flags; }; extern int if_set_up(const char *ifname); extern void if_getinf(const char *ifname, struct if_info *info); /** * struct iw_key - Encoding information * @key: encryption key * @size: length of @key in bytes * @flags: flags reported by SIOCGIWENCODE */ struct iw_key { uint8_t key[IW_ENCODING_TOKEN_MAX]; uint16_t size; uint16_t flags; }; /** * struct iw_dyn_info - modified iw_req * @name: interface name * @mode: current operation mode (IW_MODE_xxx) * * @cap_*: indicating capability/presence * * @essid: Extended Service Set ID (network name) * @essid_ct: index number of the @essid (starts at 1, 0 = off) * @nickname: optional station nickname * @ap_addr: BSSID or IBSSID * * @retry: MAC-retransmission retry behaviour * @rts: minimum packet size for which to perform RTS/CTS handshake * @frag: 802.11 frame fragmentation threshold size * @txpower: TX power information * @power power management information * * @freq: frequency in Hz * @sens: sensitivity threshold of the card * @bitrate: bitrate (client mode) * * @keys: array of encryption keys * @nkeys: length of @keys * @active_key: index of current key into @keys (counting from 1) * */ struct iw_dyn_info { char name[IFNAMSIZ]; uint8_t mode; bool cap_essid:1, cap_nickname:1, cap_freq:1, cap_sens:1, cap_txpower:1, cap_retry:1, cap_rts:1, cap_frag:1, cap_mode:1, cap_ap:1, cap_power:1, cap_aplist:1; char essid[IW_ESSID_MAX_SIZE+2]; uint8_t essid_ct; char nickname[IW_ESSID_MAX_SIZE+2]; struct sockaddr ap_addr; struct iw_param retry; struct iw_param rts; struct iw_param frag; struct iw_param txpower; struct iw_param power; float freq; int32_t sens; unsigned long bitrate; struct iw_key *keys; uint8_t nkeys; uint8_t active_key; }; /* Return the number of encryption keys marked 'active' in @info */ static inline uint8_t dyn_info_active_keys(struct iw_dyn_info *info) { int i, num_active = 0; for (i = 0; i < info->nkeys; i++) num_active += info->keys[i].size && !(info->keys[i].flags & IW_ENCODE_DISABLED); return num_active; } /* Return the number of 40-bit/104-bit keys in @info */ static inline uint8_t dyn_info_wep_keys(struct iw_dyn_info *info) { int i, num_wep = 0; for (i = 0; i < info->nkeys; i++) if (!(info->keys[i].flags & IW_ENCODE_DISABLED)) num_wep += info->keys[i].size == 5 || info->keys[i].size == 13; return num_wep; } extern void dyn_info_get(struct iw_dyn_info *info, const char *ifname, struct iw_range *ir); extern void dyn_info_cleanup(struct iw_dyn_info *info); /** * struct if_stat - Packet/byte counts for interfaces */ struct if_stat { unsigned long long rx_packets, tx_packets; unsigned long long rx_bytes, tx_bytes; }; extern void if_getstat(const char *ifname, struct if_stat *stat); /* * Structs to communicate WiFi statistics */ struct iw_levelstat { float signal; /* signal level in dBm */ float noise; /* noise level in dBm */ uint8_t flags; /* level validity */ }; #define IW_LSTAT_INIT { 0, 0, IW_QUAL_LEVEL_INVALID | IW_QUAL_NOISE_INVALID } extern void iw_getinf_range(const char *ifname, struct iw_range *range); extern void iw_sanitize(struct iw_range *range, struct iw_quality *qual, struct iw_levelstat *dbm); /** * struct iw_stat - record current WiFi state * @range: current range information * @stats: current signal level statistics * @dbm: the noise/signal of @stats in dBm */ struct iw_stat { struct iw_range range; struct iw_statistics stat; struct iw_levelstat dbm; }; /* * Periodic sampling of wireless statistics via timer alarm */ /* FIXME: remove forward declaration */ struct iw_nl80211_linkstat; extern void iw_getstat(struct iw_stat *stat); extern void iw_cache_update(struct iw_stat *iw, struct iw_nl80211_linkstat *ls); extern void sampling_init(void (*sampling_handler)(int)); extern void sampling_do_poll(void); static inline void sampling_stop(void) { alarm(0); } /* * Organization of scan results */ /** * struct scan_entry - Representation of a single scan result. * @ap_addr: MAC address * @essid: station SSID (may be empty) * @mode: operation mode (type of station) * @freq: frequency/channel information * @chan: channel corresponding to @freq (where applicable) * @qual: signal quality information * @has_key: whether using encryption or not * @flags: properties gathered from Information Elements * @next: next entry in list */ struct scan_entry { struct ether_addr ap_addr; char essid[IW_ESSID_MAX_SIZE + 2]; int mode; double freq; int chan; struct iw_quality qual; struct iw_levelstat dbm; int has_key:1; uint32_t flags; struct scan_entry *next; }; extern void sort_scan_list(struct scan_entry **headp); /** * struct cnt - count frequency of integer numbers * @val: value to count * @count: how often @val occurs */ struct cnt { int val; int count; }; /** * struct scan_result - Structure to aggregate all collected scan data. * @head: begin of scan_entry list (may be NULL) * @msg: error message, if any * @max_essid_len: maximum ESSID-string length (for formatting) * @channel_stats: array of channel statistics entries * @num.total: number of entries in list starting at @head * @num.open: number of open entries among @num.total * @num.two_gig: number of 2.4GHz stations among @num.total * @num.five_gig: number of 5 GHz stations among @num.total * @num.ch_stats: length of @channel_stats array * @range: range data associated with scan interface * @mutex: protects against concurrent consumer/producer access */ struct scan_result { struct scan_entry *head; char msg[128]; uint16_t max_essid_len; struct cnt *channel_stats; struct assorted_numbers { uint16_t entries, open, two_gig, five_gig; /* Maximum number of 'top' statistics entries. */ #define MAX_CH_STATS 3 size_t ch_stats; } num; struct iw_range range; pthread_mutex_t mutex; }; extern void scan_result_init(struct scan_result *sr); extern void scan_result_fini(struct scan_result *sr); extern void *do_scan(void *sr_ptr); /* * utils.c */ extern char *ether_addr(const struct ether_addr *ea); extern char *ether_lookup(const struct ether_addr *ea); extern char *mac_addr(const struct sockaddr *sa); extern char *format_bssid(const struct sockaddr *ap); extern uint8_t bit_count(uint32_t mask); extern uint8_t prefix_len(const struct in_addr *netmask); extern const char *pretty_time(const unsigned sec); extern const char *pretty_time_ms(const unsigned msec); extern int u8_to_dbm(const int power); extern uint8_t dbm_to_u8(const int dbm); extern double dbm2mw(const double in); extern char *dbm2units(const double in); extern double mw2dbm(const double in); extern const char *dfs_domain_name(enum nl80211_dfs_regions region); extern int ieee80211_frequency_to_channel(int freq); extern const char *channel_width_name(enum nl80211_chan_width width); extern const char *channel_type_name(enum nl80211_channel_type channel_type); extern const char *iftype_name(enum nl80211_iftype iftype); /* * WEXT helper routines */ static inline const char *iw_opmode(const uint8_t mode) { static char *modes[] = { [IW_MODE_AUTO] = "Auto", [IW_MODE_ADHOC] = "Ad-Hoc", [IW_MODE_INFRA] = "Managed", [IW_MODE_MASTER] = "Master", [IW_MODE_REPEAT] = "Repeater", [IW_MODE_SECOND] = "Secondary", [IW_MODE_MONITOR] = "Monitor", [IW_MODE_MESH] = "Mesh" }; return mode < ARRAY_SIZE(modes) ? modes[mode] : "Unknown/bug"; } /* Format driver TX power information */ static inline char *format_txpower(const struct iw_param *txpwr) { static char txline[0x40]; if (txpwr->flags & IW_TXPOW_RELATIVE) snprintf(txline, sizeof(txline), "%d (no units)", txpwr->value); else if (txpwr->flags & IW_TXPOW_MWATT) snprintf(txline, sizeof(txline), "%.0f dBm (%d mW)", mw2dbm(txpwr->value), txpwr->value); else snprintf(txline, sizeof(txline), "%d dBm (%.2f mW)", txpwr->value, dbm2mw(txpwr->value)); return txline; } /* Format driver Power Management information */ static inline char *format_power(const struct iw_param *pwr, const struct iw_range *range) { static char buf[0x80]; double val = pwr->value; int len = 0; if (pwr->disabled) return "off"; else if (pwr->flags == IW_POWER_ON) return "on"; if (pwr->flags & IW_POWER_MIN) len += snprintf(buf + len, sizeof(buf) - len, "min "); if (pwr->flags & IW_POWER_MAX) len += snprintf(buf + len, sizeof(buf) - len, "max "); if (pwr->flags & IW_POWER_TIMEOUT) len += snprintf(buf + len, sizeof(buf) - len, "timeout "); else if (pwr->flags & IW_POWER_SAVING) len += snprintf(buf + len, sizeof(buf) - len, "saving "); else len += snprintf(buf + len, sizeof(buf) - len, "period "); if (pwr->flags & IW_POWER_RELATIVE && range->we_version_compiled < 21) len += snprintf(buf + len, sizeof(buf) - len, "%+g", val/1e6); else if (pwr->flags & IW_POWER_RELATIVE) len += snprintf(buf + len, sizeof(buf) - len, "%+g", val); else if (val > 1e6) len += snprintf(buf + len, sizeof(buf) - len, "%g s", val/1e6); else if (val > 1e3) len += snprintf(buf + len, sizeof(buf) - len, "%g ms", val/1e3); else len += snprintf(buf + len, sizeof(buf) - len, "%g us", val); switch (pwr->flags & IW_POWER_MODE) { case IW_POWER_UNICAST_R: len += snprintf(buf + len, sizeof(buf) - len, ", rcv unicast"); break; case IW_POWER_MULTICAST_R: len += snprintf(buf + len, sizeof(buf) - len, ", rcv mcast"); break; case IW_POWER_ALL_R: len += snprintf(buf + len, sizeof(buf) - len, ", rcv all"); break; case IW_POWER_FORCE_S: len += snprintf(buf + len, sizeof(buf) - len, ", force send"); break; case IW_POWER_REPEATER: len += snprintf(buf + len, sizeof(buf) - len, ", repeat mcast"); } return buf; } /* See comments on 'struct iw_freq' in wireless.h */ static inline float freq_to_hz(const struct iw_freq *freq) { return freq->m * pow(10, freq->e); } /* Return frequency or 0 on error. Based on iw_channel_to_freq() */ static inline double channel_to_freq(uint8_t chan, const struct iw_range *range) { int c; for (c = 0; c < range->num_frequency; c++) /* Check if it actually has stored a frequency */ if (range->freq[c].i == chan && range->freq[c].m > 1000) return freq_to_hz(&range->freq[c]); return 0.0; } /* Return channel number or -1 on error. Based on iw_freq_to_channel() */ static inline int freq_to_channel(double freq, const struct iw_range *range) { int i; if (freq < 1e3) /* Convention: freq is channel number if < 1e3 */ return freq; for (i = 0; i < range->num_frequency; i++) if (freq_to_hz(&range->freq[i]) == freq) return range->freq[i].i; return -1; } /* print @key in cleartext if it is in ASCII format, use hex format otherwise */ static inline char *format_key(const struct iw_key *const iwk) { static char buf[128]; int i, is_printable = 0, len = 0; /* Over-estimate key size: 2 chars per hex digit plus '-' */ assert(iwk != NULL && iwk->size * 3 < sizeof(buf)); for (i = 0; i < iwk->size && (is_printable = isprint(iwk->key[i])); i++) ; if (is_printable) len += sprintf(buf, "\""); for (i = 0; i < iwk->size; i++) if (is_printable) { len += sprintf(buf + len, "%c", iwk->key[i]); } else { if (i > 0 && (i & 1) == 0) len += sprintf(buf + len, "-"); len += sprintf(buf + len, "%02X", iwk->key[i]); } if (is_printable) len += sprintf(buf + len, "\""); sprintf(buf + len, " (%u bits)", iwk->size * 8); return buf; } /* Human-readable representation of IW_ENC_CAPA_ types */ static inline const char *format_enc_capab(const uint32_t capa, const char *sep) { static char buf[32]; size_t len = 0, max = sizeof(buf); if (capa & IW_ENC_CAPA_WPA) len = snprintf(buf, max, "WPA"); if (capa & IW_ENC_CAPA_WPA2) len += snprintf(buf + len, max - len, "%sWPA2", len ? sep : ""); if (capa & IW_ENC_CAPA_CIPHER_TKIP) len += snprintf(buf + len, max - len, "%sTKIP", len ? sep : ""); if (capa & IW_ENC_CAPA_CIPHER_CCMP) len += snprintf(buf + len, max - len, "%sCCMP", len ? sep : ""); buf[len] = '\0'; return buf; } /* Display only the supported WPA type */ #define IW_WPA_MASK (IW_ENC_CAPA_WPA|IW_ENC_CAPA_WPA2) static inline const char *format_wpa(struct iw_range *ir) { return format_enc_capab(ir->enc_capa & IW_WPA_MASK, "/"); } static inline char *format_retry(const struct iw_param *retry, const struct iw_range *range) { static char buf[0x80]; double val = retry->value; int len = 0; if (retry->disabled) return "off"; else if (retry->flags == IW_RETRY_ON) return "on"; if (retry->flags & IW_RETRY_MIN) len += snprintf(buf + len, sizeof(buf) - len, "min "); if (retry->flags & IW_RETRY_MAX) len += snprintf(buf + len, sizeof(buf) - len, "max "); if (retry->flags & IW_RETRY_SHORT) len += snprintf(buf + len, sizeof(buf) - len, "short "); if (retry->flags & IW_RETRY_LONG) len += snprintf(buf + len, sizeof(buf) - len, "long "); if (retry->flags & IW_RETRY_LIFETIME) len += snprintf(buf + len, sizeof(buf) - len, "lifetime "); else { snprintf(buf + len, sizeof(buf) - len, "limit %d", retry->value); return buf; } if (retry->flags & IW_RETRY_RELATIVE && range->we_version_compiled < 21) len += snprintf(buf + len, sizeof(buf) - len, "%+g", val/1e6); else if (retry->flags & IW_RETRY_RELATIVE) len += snprintf(buf + len, sizeof(buf) - len, "%+g", val); else if (val > 1e6) len += snprintf(buf + len, sizeof(buf) - len, "%g s", val/1e6); else if (val > 1e3) len += snprintf(buf + len, sizeof(buf) - len, "%g ms", val/1e3); else len += snprintf(buf + len, sizeof(buf) - len, "%g us", val); return buf; }
{ "content_hash": "3ea9edd21ca7ea47034190aab4a95779", "timestamp": "", "source": "github", "line_count": 524, "max_line_length": 80, "avg_line_length": 28.16030534351145, "alnum_prop": 0.6597994036324207, "repo_name": "aarif4/wireless_positioning_system", "id": "87d36f918878c323099d4f646f0cb7d3e75a3e4d", "size": "15584", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wps_ros/wavemon/iw_if.h", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "372657" }, { "name": "CMake", "bytes": "6166" }, { "name": "M4", "bytes": "2698" }, { "name": "Makefile", "bytes": "4525" }, { "name": "Matlab", "bytes": "29388" }, { "name": "Objective-C", "bytes": "1181" }, { "name": "Python", "bytes": "18591" }, { "name": "Roff", "bytes": "10643" }, { "name": "Shell", "bytes": "25897" } ], "symlink_target": "" }
name 'postgresql' maintainer 'Hiroyuki Onaka' license 'Apache License, Version 2.0' description 'Installs/Configures postgresql' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.0'
{ "content_hash": "cd086a2067247010d42896b0c862d068", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 72, "avg_line_length": 43.166666666666664, "alnum_prop": 0.6447876447876448, "repo_name": "azusa/database-migration-sample", "id": "2c461a8f974a99ac4198db6c68ffbb9112678c48", "size": "259", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "site-cookbooks/postgresql/metadata.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1135" }, { "name": "HTML", "bytes": "20411" }, { "name": "Ruby", "bytes": "11733" }, { "name": "Shell", "bytes": "5186" } ], "symlink_target": "" }
'use strict'; /** @typedef {{devtoolsLog?: string, lhr: string, trace: string}} Result */ /** @typedef {{url: string, wpt: Result[], unthrottled: Result[]}} ResultsForUrl */ /** @typedef {Result & {metrics: LH.Artifacts.TimingSummary}} ResultWithMetrics */ /** @typedef {{results: ResultsForUrl[], warnings: string[]}} Summary */ const fs = require('fs'); const readline = require('readline'); const {promisify} = require('util'); const archiver = require('archiver'); const streamFinished = promisify(require('stream').finished); const LH_ROOT = `${__dirname}/../../../..`; const collectFolder = `${LH_ROOT}/dist/collect-lantern-traces`; const summaryPath = `${collectFolder}/summary.json`; const goldenFolder = `${LH_ROOT}/dist/golden-lantern-traces`; const IS_INTERACTIVE = !!process.stdout.isTTY && !process.env.GCP_COLLECT; class ProgressLogger { constructor() { this._currentProgressMessage = ''; this._loadingChars = '⣾⣽⣻⢿⡿⣟⣯⣷ ⠁⠂⠄⡀⢀⠠⠐⠈'; this._nextLoadingIndex = 0; this._progressBarHandle = setInterval( () => this.progress(this._currentProgressMessage), IS_INTERACTIVE ? 100 : 5000 ); } /** * @param {...any} args */ log(...args) { readline.clearLine(process.stdout, 0); readline.cursorTo(process.stdout, 0); // eslint-disable-next-line no-console console.log(...args); this.progress(this._currentProgressMessage); } /** * @param {string} message */ progress(message) { this._currentProgressMessage = message; readline.clearLine(process.stdout, 0); readline.cursorTo(process.stdout, 0); if (message) process.stdout.write(`${this._nextLoadingChar()} ${message}`); } closeProgress() { clearInterval(this._progressBarHandle); this.progress(''); } _nextLoadingChar() { const char = this._loadingChars[this._nextLoadingIndex++]; if (this._nextLoadingIndex >= this._loadingChars.length) { this._nextLoadingIndex = 0; } return char; } } /** * @param {string} archiveDir */ function archive(archiveDir) { const archive = archiver('zip', { zlib: {level: 9}, }); const writeStream = fs.createWriteStream(`${archiveDir}.zip`); archive.pipe(writeStream); archive.directory(archiveDir, false); archive.finalize(); return streamFinished(archive); } /** * @return {Summary} */ function loadSummary() { if (fs.existsSync(summaryPath)) { return JSON.parse(fs.readFileSync(summaryPath, 'utf-8')); } else { return {results: [], warnings: []}; } } /** * @param {Summary} summary */ function saveSummary(summary) { fs.writeFileSync(summaryPath, JSON.stringify(summary, null, 2)); } /** * @param {LH.Result} lhr * @return {LH.Artifacts.TimingSummary|undefined} */ function getMetrics(lhr) { const metricsDetails = /** @type {LH.Audit.Details.DebugData=} */ (lhr.audits['metrics'].details); if (!metricsDetails || !metricsDetails.items || !metricsDetails.items[0]) return; /** @type {LH.Artifacts.TimingSummary} */ const metrics = JSON.parse(JSON.stringify(metricsDetails.items[0])); // Older versions of Lighthouse don't have max FID on the `metrics` audit, so get // it from somewhere else. if (!metrics.maxPotentialFID) { metrics.maxPotentialFID = lhr.audits['max-potential-fid'].numericValue; } return metrics; } module.exports = { ProgressLogger, collectFolder, goldenFolder, archive, loadSummary, saveSummary, getMetrics, };
{ "content_hash": "c955ae654d6a511086840058f5eece0f", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 100, "avg_line_length": 26.9453125, "alnum_prop": 0.6651203247318063, "repo_name": "wardpeet/lighthouse", "id": "dc5323c0b2d70d0756b7d1d54a3d58765873c001", "size": "4072", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lighthouse-core/scripts/lantern/collect/common.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "54123" }, { "name": "HTML", "bytes": "119934" }, { "name": "JavaScript", "bytes": "3323926" }, { "name": "Python", "bytes": "1269" }, { "name": "Ruby", "bytes": "7024" }, { "name": "Shell", "bytes": "24123" } ], "symlink_target": "" }
START_ATF_NAMESPACE struct HTMLFormElementEvents : IDispatch { }; END_ATF_NAMESPACE
{ "content_hash": "fa8e9592313654eee6854aa14f879b3b", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 45, "avg_line_length": 19.4, "alnum_prop": 0.7010309278350515, "repo_name": "goodwinxp/Yorozuya", "id": "40a9645dea2b637f34311e230884d16e62b8b42f", "size": "274", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/ATF/HTMLFormElementEvents.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "207291" }, { "name": "C++", "bytes": "21670817" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "407cfec056e27d60de7cca67a484fb7e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "39a3fb3c38aad609f2b836934dd46d74a97e3d4d", "size": "186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Senna/Senna arnottiana/Cassia arnottiana andina/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of pressure2depth</title> <meta name="keywords" content="pressure2depth"> <meta name="description" content="Depth Computes depth given the pressure at some latitude"> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 Guillaume Flandin"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../m2html.css"> </head> <body> <a name="_top"></a> <div><a href="../index.html">Home</a> &gt; <a href="index.html">utilities</a> &gt; pressure2depth.m</div> <!--<table width="100%"><tr><td align="left"><a href="../index.html"><img alt="<" border="0" src="../left.png">&nbsp;Master index</a></td> <td align="right"><a href="index.html">Index for utilities&nbsp;<img alt=">" border="0" src="../right.png"></a></td></tr></table>--> <h1>pressure2depth </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>Depth Computes depth given the pressure at some latitude</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>function Z=Depth(P,LAT) </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre class="comment"> Depth Computes depth given the pressure at some latitude Z=Depth(P,LAT) gives the Depth Z (m) for a pressure P (dbars) at some latitude LAT (degrees). Fofonoff and Millard (1982). UNESCO Tech Paper #44. Notes: (ETP3, MBARI) This algorithm was originally compiled by RP @ WHOI. It was copied from the UNESCO technical report. The algorithm was endorsed by SCOR Working Group 51. The equations were originally developed by Saunders and Fofonoff (1976). DSR 23: 109-111. The parameters were re-fit for the 1980 equation of state for seawater (EOS80). CHECKVALUE: Z = 9712.653 M FOR P=10000 DECIBARS, LAT=30 DEG CALCULATON ASSUMES STD OCEAN: T = 0 DEG C; S = 35 (IPSS-78)</pre></div> <!-- crossreference --> <h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> This function calls: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> This function is called by: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> <!-- crossreference --> <h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre>0001 <a name="_sub0" href="#_subfunctions" class="code">function Z=Depth(P,LAT)</a> 0002 <span class="comment">% Depth Computes depth given the pressure at some latitude</span> 0003 <span class="comment">% Z=Depth(P,LAT) gives the Depth Z (m) for a pressure P</span> 0004 <span class="comment">% (dbars) at some latitude LAT (degrees).</span> 0005 <span class="comment">%</span> 0006 <span class="comment">% Fofonoff and Millard (1982). UNESCO Tech Paper #44.</span> 0007 <span class="comment">%</span> 0008 <span class="comment">% Notes: (ETP3, MBARI)</span> 0009 <span class="comment">% This algorithm was originally compiled by RP @ WHOI.</span> 0010 <span class="comment">% It was copied from the UNESCO technical report.</span> 0011 <span class="comment">% The algorithm was endorsed by SCOR Working Group 51.</span> 0012 <span class="comment">% The equations were originally developed by Saunders</span> 0013 <span class="comment">% and Fofonoff (1976). DSR 23: 109-111.</span> 0014 <span class="comment">% The parameters were re-fit for the 1980 equation of</span> 0015 <span class="comment">% state for seawater (EOS80).</span> 0016 <span class="comment">%</span> 0017 <span class="comment">% CHECKVALUE: Z = 9712.653 M FOR P=10000 DECIBARS, LAT=30 DEG</span> 0018 <span class="comment">%</span> 0019 <span class="comment">% CALCULATON ASSUMES STD OCEAN: T = 0 DEG C; S = 35 (IPSS-78)</span> 0020 0021 0022 X = sin(LAT/57.29578); 0023 X = X.*X; 0024 0025 <span class="comment">% GR= GRAVITY VARIATION WITH LAT: ANON (1970) BULLETIN GEODESIQUE</span> 0026 0027 GR = 9.780318*(1.0+(5.2788E-3+2.36E-5*X).*X) + 1.092E-6.*P; 0028 0029 Z = (((-1.82E-15*P+2.279E-10).*P-2.2512E-5).*P+9.72659).*P; 0030 Z = Z./GR;</pre></div> <hr><address>Generated on Wed 20-Feb-2019 16:06:01 by <strong><a href="http://www.artefact.tk/software/matlab/m2html/" title="Matlab Documentation in HTML">m2html</a></strong> &copy; 2005</address> </body> </html>
{ "content_hash": "51d04cd98f84f61de39fef17299f16a0", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 197, "avg_line_length": 52.03191489361702, "alnum_prop": 0.6473113882641587, "repo_name": "pwcazenave/fvcom-toolbox", "id": "b4164e531c22bb6d5f63f9fd06deb635762d6fa0", "size": "4891", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/utilities/pressure2depth.html", "mode": "33188", "license": "mit", "language": [ { "name": "Fortran", "bytes": "1745" }, { "name": "MATLAB", "bytes": "1331266" }, { "name": "Shell", "bytes": "309" }, { "name": "Tcl", "bytes": "17023" } ], "symlink_target": "" }
import $ from 'jquery' import flatten from 'lodash/flatten' import { getCenter } from 'ol/extent' import Point from 'ol/geom/Point' import BaseObject from 'ol/Object' import Overlay from 'ol/Overlay' import Icon from 'ol/style/Icon' import { ListenerOrganizerMixin } from './ListenerOrganizerMixin' import { Window } from './html/Window' import { cssClasses } from './globals' import { finishAllImages, mixin } from './utilities' import '../less/featurepopup.less' /** * @typedef {object} FeaturePopupOptions * @property {string} [className='g4u-featurepopup'] * @property {number[]} [offset=[0,0]] * @property {OverlayPositioning} [positioning='center-center'] * @property {number[]} [iconSizedOffset=[0,0]] * @property {boolean} [centerOnPopup=false] * @property {boolean} [animated=true] * @property {string[]} [popupModifier] default popupModifiers to use * @property {boolean} [draggable=false] */ /** * Displays a Popup bound to a geographical position via an ol.Overlay */ export class FeaturePopup extends mixin(BaseObject, ListenerOrganizerMixin) { /** * @param {FeaturePopupOptions} options */ constructor (options = {}) { super() /** * @type {string} * @private */ this.className_ = (options.hasOwnProperty('className')) ? options.className : 'g4u-featurepopup' /** * @type {string} * @private */ this.classNameFeatureName_ = this.className_ + '-feature-name' /** * @type {string} * @private */ this.classNameFeatureDescription_ = this.className_ + '-feature-description' /** * @type {jQuery} * @private */ this.$name_ = $('<h3>').addClass(this.classNameFeatureName_) /** * @type {jQuery} * @private */ this.$description_ = $('<p>').addClass(this.classNameFeatureDescription_) /** * @type {null|ol.Feature} * @private */ this.feature_ = null /** * @type {boolean} * @private */ this.visible_ = false /** * @type {VectorLayer[]} * @private */ this.referencingVisibleLayers_ = [] /** * @type {number[]} * @private */ this.pixelOffset_ = options.hasOwnProperty('offset') ? options.offset : [0, 0] /** * @type {number[]} * @private */ this.iconSizedOffset_ = options.hasOwnProperty('iconSizedOffset') ? options.iconSizedOffset : [0, 0] /** * @type {boolean} * @private */ this.centerOnPopup_ = options.hasOwnProperty('centerOnPopup') ? options.centerOnPopup : true /** * @type {boolean} * @private */ this.centerOnPopupInitial_ = this.centerOnPopup_ /** * @type {boolean} * @private */ this.animated_ = options.hasOwnProperty('animated') ? options.animated : true /** * @type {jQuery} * @private */ this.$element_ = $('<div>').addClass(this.className_).addClass(cssClasses.hidden) /** * @type {ol.Overlay} * @private */ this.overlay_ = new Overlay({ element: this.$element_.get(0), offset: this.pixelOffset_, positioning: options.hasOwnProperty('positioning') ? options.positioning : 'center-center', stopEvent: true }) /** * @type {string[]} * @private */ this.defaultPopupModifiers_ = options.popupModifier || [] /** * @type {boolean} * @private */ this.draggable_ = options.draggable || false /** * @type {string[]} * @private */ this.currentPopupModifiers_ = [] /** * @type {?Window} * @private */ this.window_ = null /** * @type {?G4UMap} * @private */ this.map__ = null } /** * @param {ol.Feature} feature * @returns {boolean} */ static canDisplay (feature) { if (feature.get('features') && feature.get('features').length === 1) { feature = feature.get('features')[0] } return !feature.get('disabled') && (feature.get('name') || (feature.get('description') && $('<span>').html(feature.get('description')).text().match(/\S/))) } /** * @param {G4UMap} map */ setMap (map) { if (this.getMap()) { this.detachAllListeners() this.getMap().removeOverlay(this.overlay_) } if (map) { this.window_ = new Window({ parentClassName: this.className_, draggable: this.draggable_, fixedPosition: true, map: map }) this.window_.get$Body().append(this.$name_).append(this.$description_) this.listenAt(this.window_).on('change:visible', () => { if (!this.window_.getVisible()) { this.setVisible(false) // notifying the featurepopup about the closing of the window } }) this.$element_.append(this.window_.get$Element()) // feature click this.listenAt(map.get('clickInteraction')).on('interaction', e => { const interacted = e.interacted.filter(({ feature }) => FeaturePopup.canDisplay(feature)) if (interacted.length) { const { feature, layer } = interacted[0] this.onFeatureClick_(feature, layer, e.coordinate) } }) // clickable map.get('clickableInteraction').addFilter(e => { return map.forEachFeatureAtPixel(e.pixel, FeaturePopup.canDisplay) }) // hiding feature Popup if the layer gets hidden or the feature gets removed const forEachSource = (layer, source) => { if (source.getFeatures) { this.listenAt(source).on('removefeature', e => { if (e.feature === this.getFeature()) { for (const rLay of this.referencingVisibleLayers_) { if (rLay.getSource() === source) { this.removeReferencingLayer_(rLay) } } } }) } } const forEachLayer = layer => { if (layer.getSource) { const source = layer.getSource() if (source) { forEachSource(layer, source) } this.listenAt(layer).on('change:source', e => { this.detachFrom(e.oldValue) forEachSource(layer, layer.getSource()) }) this.listenAt(layer).on('change:visible', () => { if (layer.getVisible()) { if (this.layerContainsFeature(layer, this.getFeature())) { this.addReferencingLayer_(layer) } } else { this.removeReferencingLayer_(layer) } }) } if (layer.getLayers) { layer.getLayers().forEach(forEachLayer) this.listenAt(layer.getLayers()) .on('add', e => { forEachLayer(e.element) }) .on('remove', e => { if (e.element.getSource && e.element.getSource()) { this.detachFrom(e.element.getSource()) } this.detachFrom(e.element) }) } } forEachLayer(map.getLayerGroup()) map.addOverlay(this.overlay_) this.$element_.parent().addClass(this.className_ + '-container') const onMapChangeMobile = () => { if (map.get('mobile')) { this.centerOnPopup_ = false } else { this.centerOnPopup_ = this.centerOnPopupInitial_ } } onMapChangeMobile() this.listenAt(map).on('change:mobile', onMapChangeMobile) // limiting size map.once('postrender', () => { this.window_.updateSize() }) } this.map__ = map } /** * @param {ol.Feature} feature * @param {ol.layer.Vector} layer * @param {ol.Coordinate} coordinate * @private */ onFeatureClick_ (feature, layer, coordinate = null) { if (this.getFeature() === feature) { this.setVisible(false) this.setFeature(null) } else { if (feature.get('features')) { feature = feature.get('features')[0] } this.setFeature(feature, layer, feature.getStyle() || layer.getStyle(), coordinate) this.setVisible(true) if (this.centerOnPopup_) { this.centerMapOnPopup() } } } /** * @param {VectorLayer} layer * @private */ removeReferencingLayer_ (layer) { const index = this.referencingVisibleLayers_.indexOf(layer) if (index > -1) { this.referencingVisibleLayers_.splice(index, 1) if (this.referencingVisibleLayers_.length === 0) { this.setVisible(false) } } } /** * @returns {G4UMap} */ getMap () { return this.map__ } /** * @returns {null|ol.Feature} */ getFeature () { return this.feature_ } /** * @returns {Array|VectorLayer[]} */ getLayers () { return this.referencingVisibleLayers_ } updateContent () { if (this.getMap().get('localiser').isRtl()) { this.window_.get$Body().prop('dir', 'rtl') } else { this.window_.get$Body().prop('dir', undefined) } return this.getMap().get('popupModifiers').apply({ name: this.getFeature().get('name'), description: this.getFeature().get('description') }, this.getMap(), this.currentPopupModifiers_) .then(result => { if (result.name) { this.$name_.removeClass(cssClasses.hidden) this.$name_.html(result.name) } else { this.$name_.addClass(cssClasses.hidden) } if (result.description) { this.$description_.removeClass(cssClasses.hidden) this.$description_.html(result.description) } else { this.$description_.addClass(cssClasses.hidden) } this.dispatchEvent('update:content') return finishAllImages(this.$description_) }) .then(() => { this.updateSize() }) } /** * Update the Popup. Call this if something in the feature has changed */ update (style) { const feature = this.getFeature() if (feature) { this.$name_.empty() this.$description_.empty() // this produces one unnecessary call to window.updateSize() this.updateContent().then(() => { if (!feature.get('observedByPopup')) { feature.on('change:name', () => this.updateContent()) feature.on('change:description', () => this.updateContent()) feature.set('observedByPopup', true) } this.once('change:feature', () => { feature.un('change:name', () => this.updateContent()) feature.un('change:description', () => this.updateContent()) feature.set('observedByPopup', false) }) if (!this.getMap().get('mobile')) { const resolution = this.getMap().getView().getResolution() this.addIconSizedOffset(feature, style, resolution) } for (const layer of this.referencingVisibleLayers_) { if (layer.get('addClass')) { this.window_.get$Element().addClass(layer.get('addClass')) } } // apply default offset if (this.getVisible()) { setTimeout(() => this.window_.updateSize(), 0) } }) } } updateSize () { if (this.getVisible() && this.window_ && this.window_.updateSize) { this.window_.updateSize() } } /** * The feature should have a property 'name' and/or 'description' to be shown inside of the popup. * @param {ol.Feature} feature * @param {ol.layer.Base} layer * @param {ol.style.Style} style * @param {ol.Coordinate} clickCoordinate * @param {string[]} [optPopupModifiers=[]] */ setFeature (feature, layer, style, clickCoordinate = null) { const oldValue = this.feature_ if (feature) { let coordinate = clickCoordinate if (feature.get('origCoords') !== undefined) { coordinate = feature.get('origCoords') } else if (feature.getGeometry() instanceof Point || !clickCoordinate) { coordinate = getCenter(feature.getGeometry().getExtent()) } this.overlay_.setPosition(coordinate) } if (oldValue !== feature) { if (this.feature_) { this.feature_.un('change:geometry', this.geometryChangeHandler_) } this.feature_ = feature this.referencingVisibleLayers_ = [] if (layer) { this.addReferencingLayer_(layer) } this.getMap().getLayerGroup().recursiveForEach(layer => { if (this.layerContainsFeature(layer, feature)) { this.addReferencingLayer_(layer) } }) this.currentPopupModifiers_ = this.defaultPopupModifiers_.slice() for (const refLayer of this.referencingVisibleLayers_) { this.currentPopupModifiers_ = this.currentPopupModifiers_.concat(flatten(refLayer.get('popupModifiers'))) } if (this.feature_) { this.geometryChangeHandler_ = () => { let coordinate = clickCoordinate if (feature.getGeometry() instanceof Point || !clickCoordinate) { coordinate = getCenter(feature.getGeometry().getExtent()) } this.overlay_.setPosition(coordinate) if (this.getVisible()) { this.update(style) } } this.feature_.on('change:geometry', this.geometryChangeHandler_) } this.dispatchEvent({ type: 'change:feature', oldValue: oldValue, key: 'feature' }) this.update(style) } } layerContainsFeature (layer, feature) { const source = layer.getSource && layer.getSource() if (source && source.getFeatures) { return source.getFeatures().indexOf(feature) > -1 } return false } /** * @returns {boolean} */ getVisible () { return this.visible_ } /** * @param {boolean} visible */ setVisible (visible) { const oldValue = this.visible_ if (oldValue !== visible) { this.visible_ = visible if (visible === true && this.getFeature()) { this.$element_.removeClass(cssClasses.hidden) this.window_.setVisible(true) } else { this.$element_.addClass(cssClasses.hidden) this.window_.setVisible(false) this.window_.resetDragged() } if (!visible) { this.setFeature(null) } this.dispatchEvent({ type: 'change:visible', oldValue: oldValue, key: 'visible' }) } if (visible) { setTimeout(() => this.window_.updateSize(), 0) } } /** * calculates iconSized Offset and applies it * @param {ol.Feature} feature * @param {ol.style.Style} style * @param {number} resolution */ addIconSizedOffset (feature, style, resolution) { if (this.iconSizedOffset_[0] !== 0 || this.iconSizedOffset_[1] !== 0) { if (style) { style = this.getMap().get('styling').manifestStyle(style, feature, resolution) if (style) { const imageStyle = style.getImage() if (imageStyle instanceof Icon) { (new Promise(resolve => { const img = imageStyle.getImage() if (img.complete && img.src) { resolve() } else { img.addEventListener('load', () => { this.getMap().render() // initiate styles with size and anchor this.getMap().once('postcompose', resolve) }) imageStyle.load() } })).then(() => { const iconSize = imageStyle.getSize() const totalOffset = [ this.pixelOffset_[0] + this.iconSizedOffset_[0] * iconSize[0] * (imageStyle.getScale() || 1), this.pixelOffset_[1] + this.iconSizedOffset_[1] * iconSize[1] * (imageStyle.getScale() || 1) ] this.overlay_.setOffset(totalOffset) }) } } } } } /** * Centers the map on the popup after all images have been loaded */ centerMapOnPopup (animated) { animated = animated === undefined ? this.animated_ : animated const _centerMap = () => { this.window_.updateSize() this.getMap().get('move').toPoint(this.getCenter(), { animated }) } finishAllImages(this.window_.get$Body()).then(() => { // we need to do this trick to find out if map is already visible/started rendering if (this.getMap().getPixelFromCoordinate([0, 0])) { _centerMap() } else { this.getMap().once('postrender', _centerMap) } }) } /** * calculates Center of the Popup. Be careful, this calculation repositions the popup to calculate the center * properly and repostions to the initial Position again. * This does only work if the popup is already visible! * @returns {ol.Coordinate} */ getCenter () { const offset = this.overlay_.getOffset() const pixelPosition = this.getMap().getPixelFromCoordinate(this.overlay_.getPosition()) // apply offset pixelPosition[0] += offset[0] pixelPosition[1] += offset[1] // applay width/height depending on positioning const positioning = this.overlay_.getPositioning().split('-') const width = this.$element_.outerWidth() const height = this.$element_.outerHeight() if (positioning[1] === 'left') { pixelPosition[0] += width / 2 } if (positioning[1] === 'right') { pixelPosition[0] -= width / 2 } if (positioning[0] === 'top') { pixelPosition[1] += height / 2 } if (positioning[0] === 'bottom') { pixelPosition[1] -= height / 2 } return this.getMap().getCoordinateFromPixel(pixelPosition) } addReferencingLayer_ (layer) { if (this.referencingVisibleLayers_.indexOf(layer) < 0) { this.referencingVisibleLayers_.push(layer) } } }
{ "content_hash": "f49307b4576874edffdba1939d61d941", "timestamp": "", "source": "github", "line_count": 663, "max_line_length": 113, "avg_line_length": 26.87028657616893, "alnum_prop": 0.5714847039012069, "repo_name": "KlausBenndorf/guide4you", "id": "85ced10bfd8aeaf6f6f581ee7e57bd53160000f7", "size": "17815", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/FeaturePopup.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "70691" }, { "name": "HTML", "bytes": "2061" }, { "name": "JavaScript", "bytes": "587676" } ], "symlink_target": "" }
/* eslint-disable */ import { is, asEffect } from "redux-saga/utils"; const PENDING = "PENDING"; const RESOLVED = "RESOLVED"; const REJECTED = "REJECTED"; const CANCELLED = "CANCELLED"; const DEFAULT_STYLE = "color: black"; const LABEL_STYLE = "font-weight: bold"; const EFFECT_TYPE_STYLE = "color: blue"; const ERROR_STYLE = "color: red"; const CANCEL_STYLE = "color: #ccc"; const IS_BROWSER = typeof window !== "undefined" && window.document; const globalScope = typeof window.document === "undefined" && navigator.product === "ReactNative" ? global : IS_BROWSER ? window : null; // `VERBOSE` can be made a setting configured from the outside. const VERBOSE = false; function time() { if (typeof performance !== "undefined" && performance.now) { return performance.now(); } return Date.now(); } const effectsById = {}; const rootEffects = []; function effectTriggered(desc) { if (VERBOSE) { console.log("Saga monitor: effectTriggered:", desc); } effectsById[desc.effectId] = Object.assign({}, desc, { status: PENDING, start: time() }); if (desc.root) { rootEffects.push(desc.effectId); } } function effectResolved(effectId, result) { if (VERBOSE) { console.log("Saga monitor: effectResolved:", effectId, result); } resolveEffect(effectId, result); } function effectRejected(effectId, error) { if (VERBOSE) { console.log("Saga monitor: effectRejected:", effectId, error); } rejectEffect(effectId, error); } function effectCancelled(effectId) { if (VERBOSE) { console.log("Saga monitor: effectCancelled:", effectId); } cancelEffect(effectId); } function computeEffectDur(effect) { const now = time(); Object.assign(effect, { end: now, duration: now - effect.start }); } function resolveEffect(effectId, result) { const effect = effectsById[effectId]; if (is.task(result)) { result.done.then( taskResult => { if (result.isCancelled()) { cancelEffect(effectId); } else { resolveEffect(effectId, taskResult); } }, taskError => rejectEffect(effectId, taskError) ); } else { computeEffectDur(effect); effect.status = RESOLVED; effect.result = result; if (effect && asEffect.race(effect.effect)) { setRaceWinner(effectId, result); } } } function rejectEffect(effectId, error) { const effect = effectsById[effectId]; computeEffectDur(effect); effect.status = REJECTED; effect.error = error; if (effect && asEffect.race(effect.effect)) { setRaceWinner(effectId, error); } } function cancelEffect(effectId) { const effect = effectsById[effectId]; computeEffectDur(effect); effect.status = CANCELLED; } function setRaceWinner(raceEffectId, result) { const winnerLabel = Object.keys(result)[0]; const children = getChildEffects(raceEffectId); for (let i = 0; i < children.length; i++) { const childEffect = effectsById[children[i]]; if (childEffect.label === winnerLabel) { childEffect.winner = true; } } } function getChildEffects(parentEffectId) { return Object.keys(effectsById) .filter(effectId => effectsById[effectId].parentEffectId === parentEffectId) .map(effectId => +effectId); } // Poor man's `console.group` and `console.groupEnd` for Node. // Can be overridden by the `console-group` polyfill. // The poor man's groups look nice, too, so whether to use // the polyfilled methods or the hand-made ones can be made a preference. let groupPrefix = ""; const GROUP_SHIFT = " "; const GROUP_ARROW = "▼"; function consoleGroup(...args) { if (console.group) { console.group(...args); } else { console.log(""); console.log(groupPrefix + GROUP_ARROW, ...args); groupPrefix += GROUP_SHIFT; } } function consoleGroupEnd() { if (console.groupEnd) { console.groupEnd(); } else { groupPrefix = groupPrefix.substr( 0, groupPrefix.length - GROUP_SHIFT.length ); } } function logEffects(topEffects) { topEffects.forEach(logEffectTree); } function logEffectTree(effectId) { const effect = effectsById[effectId]; const childEffects = getChildEffects(effectId); if (!childEffects.length) { logSimpleEffect(effect); } else { const { formatter } = getEffectLog(effect); consoleGroup(...formatter.getLog()); childEffects.forEach(logEffectTree); consoleGroupEnd(); } } function logSimpleEffect(effect) { const { method, formatter } = getEffectLog(effect); console[method](...formatter.getLog()); } /* eslint-disable no-cond-assign*/ function getEffectLog(effect) { let data, log; if (effect.root) { data = effect.effect; log = getLogPrefix("run", effect); log.formatter.addCall(data.saga.name, data.args); logResult(effect, log.formatter); } else if (data = asEffect.take(effect.effect)) { log = getLogPrefix("take", effect); log.formatter.addValue(data); logResult(effect, log.formatter); } else if (data = asEffect.put(effect.effect)) { log = getLogPrefix("put", effect); logResult(Object.assign({}, effect, { result: data }), log.formatter); } else if (data = asEffect.call(effect.effect)) { log = getLogPrefix("call", effect); log.formatter.addCall(data.fn.name, data.args); logResult(effect, log.formatter); } else if (data = asEffect.cps(effect.effect)) { log = getLogPrefix("cps", effect); log.formatter.addCall(data.fn.name, data.args); logResult(effect, log.formatter); } else if (data = asEffect.fork(effect.effect)) { if (!data.detached) { log = getLogPrefix("fork", effect); } else { log = getLogPrefix("spawn", effect); } log.formatter.addCall(data.fn.name, data.args); logResult(effect, log.formatter); } else if (data = asEffect.join(effect.effect)) { log = getLogPrefix("join", effect); logResult(effect, log.formatter); } else if (data = asEffect.race(effect.effect)) { log = getLogPrefix("race", effect); logResult(effect, log.formatter, true); } else if (data = asEffect.cancel(effect.effect)) { log = getLogPrefix("cancel", effect); log.formatter.appendData(data.name); } else if (data = asEffect.select(effect.effect)) { log = getLogPrefix("select", effect); log.formatter.addCall(data.selector.name, data.args); logResult(effect, log.formatter); } else if (is.array(effect.effect)) { log = getLogPrefix("parallel", effect); logResult(effect, log.formatter, true); } else if (is.iterator(effect.effect)) { log = getLogPrefix("", effect); log.formatter.addValue(effect.effect.name); logResult(effect, log.formatter, true); } else { log = getLogPrefix("unkown", effect); logResult(effect, log.formatter); } return log; } function getLogPrefix(type, effect) { const isCancel = effect.status === CANCELLED; const isError = effect.status === REJECTED; const method = isError ? "error" : "log"; const winnerInd = effect && effect.winner ? isError ? "✘" : "✓" : ""; const style = s => isCancel ? CANCEL_STYLE : isError ? ERROR_STYLE : s; const formatter = logFormatter(); if (winnerInd) { formatter.add(`%c ${winnerInd}`, style(LABEL_STYLE)); } if (effect && effect.label) { formatter.add(`%c ${effect.label}: `, style(LABEL_STYLE)); } if (type) { formatter.add(`%c ${type} `, style(EFFECT_TYPE_STYLE)); } formatter.add("%c", style(DEFAULT_STYLE)); return { method, formatter }; } function argToString(arg) { return typeof arg === "function" ? `${arg.name}` : typeof arg === "string" ? `'${arg}'` : arg; } function logResult( { status, result, error, duration }, formatter, ignoreResult ) { if (status === RESOLVED && !ignoreResult) { if (is.array(result)) { formatter.addValue(" → "); formatter.addValue(result); } else { formatter.appendData("→", result); } } else if (status === REJECTED) { formatter.appendData("→ ⚠", error); } else if (status === PENDING) { formatter.appendData("⌛"); } else if (status === CANCELLED) { formatter.appendData("→ Cancelled!"); } if (status !== PENDING) { formatter.appendData(`(${duration.toFixed(2)}ms)`); } } function isPrimitive(val) { return typeof val === "string" || typeof val === "number" || typeof val === "boolean" || typeof val === "symbol" || val === null || val === undefined; } function logFormatter() { const logs = []; let suffix = []; function add(msg, ...args) { // Remove the `%c` CSS styling that is not supported by the Node console. if (!IS_BROWSER && typeof msg === "string") { const prevMsg = msg; msg = msg.replace(/^%c\s*/, ""); if (msg !== prevMsg) { // Remove the first argument which is the CSS style string. args.shift(); } } logs.push({ msg, args }); } function appendData(...data) { suffix = suffix.concat(data); } function addValue(value) { if (isPrimitive(value)) { add(value); } else { // The browser console supports `%O`, the Node console does not. if (IS_BROWSER) { add("%O", value); } else { add("%s", require("util").inspect(value)); } } } function addCall(name, args) { if (!args.length) { add(`${name}()`); } else { add(name); add("("); args.forEach((arg, i) => { addValue(argToString(arg)); addValue(i === args.length - 1 ? ")" : ", "); }); } } function getLog() { let msgs = [], msgsArgs = []; for (let i = 0; i < logs.length; i++) { msgs.push(logs[i].msg); msgsArgs = msgsArgs.concat(logs[i].args); } return [msgs.join("")].concat(msgsArgs).concat(suffix); } return { add, addValue, addCall, appendData, getLog }; } const logSaga = (...topEffects) => { if (!topEffects.length) { topEffects = rootEffects; } if (!rootEffects.length) { console.log(groupPrefix, "Saga monitor: No effects to log"); } console.log(""); console.log("Saga monitor:", Date.now(), new Date().toISOString()); logEffects(topEffects); console.log(""); }; // Export the snapshot-logging function to run from the browser console or extensions. if (globalScope) { globalScope.$$LogSagas = logSaga; } // Export the snapshot-logging function for arbitrary use by external code. export { logSaga }; // Export the `sagaMonitor` to pass to the middleware. export default { effectTriggered, effectResolved, effectRejected, effectCancelled, actionDispatched: () => {} };
{ "content_hash": "8118ad367e5a058fcad0ae75feb8549c", "timestamp": "", "source": "github", "line_count": 407, "max_line_length": 86, "avg_line_length": 26.088452088452087, "alnum_prop": 0.6366547372386513, "repo_name": "totorototo/strava", "id": "4fbd4cc6f479b5b0bf63bbf6fa824ea27e0a0478", "size": "10636", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/devTools/sagaMonitor.js", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1635" }, { "name": "JavaScript", "bytes": "414297" }, { "name": "Objective-C", "bytes": "4504" }, { "name": "Python", "bytes": "1724" } ], "symlink_target": "" }
package com.grasea.grandroid.demo.mvp; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import com.grasea.grandroid.api.Callback; import com.grasea.grandroid.api.RemoteProxy; import com.grasea.grandroid.api.RequestFail; import com.grasea.grandroid.demo.R; import com.grasea.grandroid.mvp.model.ModelProxy; import java.io.IOException; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Response; public class StartActivity extends AppCompatActivity { private UserModel model; private WeatherAPI api; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); model = ModelProxy.reflect(UserModel.class); api = RemoteProxy.reflect(WeatherAPI.class, this); setContentView(R.layout.activity_start); View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnGetBoolean: Toast.makeText(getApplicationContext(), "Gender :" + model.getGender(), Toast.LENGTH_SHORT).show(); break; case R.id.btnPutBoolean: model.saveGender(!model.getGender()); Toast.makeText(getApplicationContext(), "Gender :" + model.getGender(), Toast.LENGTH_SHORT).show(); break; case R.id.btnGetInt: Toast.makeText(getApplicationContext(), "Age :" + model.getAge(), Toast.LENGTH_SHORT).show(); break; case R.id.btnPutInt: model.saveAge(model.getAge() + 1); Toast.makeText(getApplicationContext(), "Age +1 :" + model.getAge(), Toast.LENGTH_SHORT).show(); break; case R.id.btnGetString: Toast.makeText(getApplicationContext(), "Name :" + model.getName(), Toast.LENGTH_SHORT).show(); break; case R.id.btnPutString: model.saveName("Rovers @ " + System.currentTimeMillis()); Toast.makeText(getApplicationContext(), "Name :" + model.getName(), Toast.LENGTH_SHORT).show(); break; case R.id.btnQueryPerson: Person p = model.getPerson("where _id=1"); if (p == null) { Toast.makeText(getApplicationContext(), "Cannot found person record in database in condition: where id=1", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Found person data in database: " + p.toString(), Toast.LENGTH_SHORT).show(); } break; case R.id.btnQueryAllPerson: ArrayList<Person> persons = model.getAllPerson(); Toast.makeText(getApplicationContext(), "There are " + persons.size() + " person records in database", Toast.LENGTH_SHORT).show(); break; case R.id.btnSavePerson: Person person = new Person(); person.setGender(true); person.setAge(model.getAge()); person.setName(model.getName()); Toast.makeText(getApplicationContext(), "Save success? " + model.saveUserData(person), Toast.LENGTH_SHORT).show(); break; case R.id.btnGetPersonList: Toast.makeText(getApplicationContext(), "Person list size = " + model.getPersonList(), Toast.LENGTH_SHORT).show(); break; case R.id.btnPutPersonList: ArrayList<Person> ps = model.getAllPerson(); Person s = model.getPerson("where _id=0"); Toast.makeText(getApplicationContext(), "Save success? " + model.putPersonList(ps), Toast.LENGTH_SHORT).show(); break; case R.id.btnCallApiJson: api.getForecast();//this api will be fire automatically because there is a callback method defined in callback object break; case R.id.btnCallApiObject: Call<Forecast> call = api.getForecastObject();//without callback method define, this call wont be call automatically Response<Forecast> response = null; try { response = call.execute();//this line will crash app because we execute network job in Main thread Toast.makeText(getApplicationContext(), response.body().status, Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } //api.getForecastObject(); break; } } }; findViewById(R.id.btnGetBoolean).setOnClickListener(listener); findViewById(R.id.btnPutBoolean).setOnClickListener(listener); findViewById(R.id.btnGetInt).setOnClickListener(listener); findViewById(R.id.btnPutInt).setOnClickListener(listener); findViewById(R.id.btnGetString).setOnClickListener(listener); findViewById(R.id.btnPutString).setOnClickListener(listener); findViewById(R.id.btnQueryPerson).setOnClickListener(listener); findViewById(R.id.btnQueryAllPerson).setOnClickListener(listener); findViewById(R.id.btnSavePerson).setOnClickListener(listener); findViewById(R.id.btnPutPersonList).setOnClickListener(listener); findViewById(R.id.btnGetPersonList).setOnClickListener(listener); findViewById(R.id.btnCallApiJson).setOnClickListener(listener); findViewById(R.id.btnCallApiObject).setOnClickListener(listener); } @Callback("getForecast") public void onGetForecast(Forecast result) { Toast.makeText(this, "forecast result: " + result.status, Toast.LENGTH_SHORT).show(); } @RequestFail("getForecast") public void onGetForecastFail(String methodName, Throwable t) { Toast.makeText(this, "Request " + methodName + " fail: " + t.toString(), Toast.LENGTH_SHORT).show(); } @RequestFail() public void onRequestFail(String methodName, Throwable t) { Toast.makeText(this, "Request " + methodName + " fail: " + t.toString(), Toast.LENGTH_SHORT).show(); } }
{ "content_hash": "94cd2ca6ba2b883f11778c1f4f5d7bde", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 162, "avg_line_length": 52.86046511627907, "alnum_prop": 0.5764774893679425, "repo_name": "Grasea/Grandroid2", "id": "27d0f6f4ca6af272e1a2e90b8e8bb70f936e5d6f", "size": "6819", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demo/src/main/java/com/grasea/grandroid/demo/mvp/StartActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "419551" } ], "symlink_target": "" }
class GURL; class SkBitmap; class WebKeyboardEvent; struct ViewHostMsg_CreateWindow_Params; struct ViewHostMsg_DidFailProvisionalLoadWithError_Params; struct ViewHostMsg_FrameNavigate_Params; struct ViewMsg_PostMessage_Params; struct WebPreferences; namespace base { class ListValue; class TimeTicks; } namespace IPC { class Message; } namespace gfx { class Point; class Rect; class Size; } namespace content { class BrowserContext; class PageState; class RenderViewHost; class RenderViewHostDelegateView; class SessionStorageNamespace; class SiteInstance; class WebContents; class WebContentsImpl; struct ContextMenuParams; struct FileChooserParams; struct GlobalRequestID; struct NativeWebKeyboardEvent; struct Referrer; struct RendererPreferences; struct ResourceRedirectDetails; struct ResourceRequestDetails; // // RenderViewHostDelegate // // An interface implemented by an object interested in knowing about the state // of the RenderViewHost. // // This interface currently encompasses every type of message that was // previously being sent by WebContents itself. Some of these notifications // may not be relevant to all users of RenderViewHost and we should consider // exposing a more generic Send function on RenderViewHost and a response // listener here to serve that need. class CONTENT_EXPORT RenderViewHostDelegate { public: // RendererManagerment ------------------------------------------------------- // Functions for managing switching of Renderers. For WebContents, this is // implemented by the RenderViewHostManager. class CONTENT_EXPORT RendererManagement { public: // Notification whether we should close the page, after an explicit call to // AttemptToClosePage. This is called before a cross-site request or before // a tab/window is closed (as indicated by the first parameter) to allow the // appropriate renderer to approve or deny the request. |proceed| indicates // whether the user chose to proceed. |proceed_time| is the time when the // request was allowed to proceed. virtual void ShouldClosePage( bool for_cross_site_transition, bool proceed, const base::TimeTicks& proceed_time) = 0; // The |pending_render_view_host| is ready to commit a page. The delegate // should ensure that the old RenderViewHost runs its unload handler first. virtual void OnCrossSiteResponse( RenderViewHost* pending_render_view_host, const GlobalRequestID& global_request_id) = 0; protected: virtual ~RendererManagement() {} }; // --------------------------------------------------------------------------- // Returns the current delegate associated with a feature. May return NULL if // there is no corresponding delegate. virtual RenderViewHostDelegateView* GetDelegateView(); virtual RendererManagement* GetRendererManagementDelegate(); // This is used to give the delegate a chance to filter IPC messages. virtual bool OnMessageReceived(RenderViewHost* render_view_host, const IPC::Message& message); // Gets the URL that is currently being displayed, if there is one. virtual const GURL& GetURL() const; // Return this object cast to a WebContents, if it is one. If the object is // not a WebContents, returns NULL. DEPRECATED: Be sure to include brettw or // jam as reviewers before you use this method. http://crbug.com/82582 virtual WebContents* GetAsWebContents(); // Return the rect where to display the resize corner, if any, otherwise // an empty rect. virtual gfx::Rect GetRootWindowResizerRect() const = 0; // The RenderView is being constructed (message sent to the renderer process // to construct a RenderView). Now is a good time to send other setup events // to the RenderView. This precedes any other commands to the RenderView. virtual void RenderViewCreated(RenderViewHost* render_view_host) {} // The RenderView has been constructed. virtual void RenderViewReady(RenderViewHost* render_view_host) {} // The RenderView died somehow (crashed or was killed by the user). virtual void RenderViewTerminated(RenderViewHost* render_view_host, base::TerminationStatus status, int error_code) {} // The RenderView is going to be deleted. This is called when each // RenderView is going to be destroyed virtual void RenderViewDeleted(RenderViewHost* render_view_host) {} // The RenderView started a provisional load for a given frame. virtual void DidStartProvisionalLoadForFrame( RenderViewHost* render_view_host, int64 frame_id, int64 parent_frame_id, bool main_frame, const GURL& url) {} // The RenderView processed a redirect during a provisional load. // // TODO(creis): Remove this method and have the pre-rendering code listen to // WebContentsObserver::DidGetRedirectForResourceRequest instead. // See http://crbug.com/78512. virtual void DidRedirectProvisionalLoad( RenderViewHost* render_view_host, int32 page_id, const GURL& source_url, const GURL& target_url) {} // A provisional load in the RenderView failed. virtual void DidFailProvisionalLoadWithError( RenderViewHost* render_view_host, const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) {} // A response has been received for a resource request. virtual void DidGetResourceResponseStart( const ResourceRequestDetails& details) {} // A redirect was received while requesting a resource. virtual void DidGetRedirectForResourceRequest( const ResourceRedirectDetails& details) {} // The RenderView was navigated to a different page. virtual void DidNavigate(RenderViewHost* render_view_host, const ViewHostMsg_FrameNavigate_Params& params) {} // The state for the page changed and should be updated. virtual void UpdateState(RenderViewHost* render_view_host, int32 page_id, const PageState& state) {} // The page's title was changed and should be updated. virtual void UpdateTitle(RenderViewHost* render_view_host, int32 page_id, const string16& title, base::i18n::TextDirection title_direction) {} // The page's encoding was changed and should be updated. virtual void UpdateEncoding(RenderViewHost* render_view_host, const std::string& encoding) {} // The destination URL has changed should be updated virtual void UpdateTargetURL(int32 page_id, const GURL& url) {} // The page is trying to close the RenderView's representation in the client. virtual void Close(RenderViewHost* render_view_host) {} // The RenderViewHost has been swapped out. virtual void SwappedOut(RenderViewHost* render_view_host) {} // The page is trying to move the RenderView's representation in the client. virtual void RequestMove(const gfx::Rect& new_bounds) {} // The RenderView began loading a new page. This corresponds to WebKit's // notion of the throbber starting. virtual void DidStartLoading(RenderViewHost* render_view_host) {} // The RenderView stopped loading a page. This corresponds to WebKit's // notion of the throbber stopping. virtual void DidStopLoading(RenderViewHost* render_view_host) {} // The pending page load was canceled. virtual void DidCancelLoading() {} // The RenderView made progress loading a page's top frame. // |progress| is a value between 0 (nothing loaded) to 1.0 (top frame // entirely loaded). virtual void DidChangeLoadProgress(double progress) {} // The RenderView set its opener to null, disowning it for the lifetime of // the window. virtual void DidDisownOpener(RenderViewHost* rvh) {} // Another page accessed the initial empty document of this RenderView, // which means it is no longer safe to display a pending URL without // risking a URL spoof. virtual void DidAccessInitialDocument() {} // The RenderView's main frame document element is ready. This happens when // the document has finished parsing. virtual void DocumentAvailableInMainFrame(RenderViewHost* render_view_host) {} // The onload handler in the RenderView's main frame has completed. virtual void DocumentOnLoadCompletedInMainFrame( RenderViewHost* render_view_host, int32 page_id) {} // The page wants to open a URL with the specified disposition. virtual void RequestOpenURL(RenderViewHost* rvh, const GURL& url, const Referrer& referrer, WindowOpenDisposition disposition, int64 source_frame_id, bool is_redirect, bool user_gesture) {} // The page wants to transfer the request to a new renderer. virtual void RequestTransferURL( const GURL& url, const Referrer& referrer, WindowOpenDisposition disposition, int64 source_frame_id, const GlobalRequestID& old_request_id, bool is_redirect, bool user_gesture) {} // The page wants to close the active view in this tab. virtual void RouteCloseEvent(RenderViewHost* rvh) {} // The page wants to post a message to the active view in this tab. virtual void RouteMessageEvent( RenderViewHost* rvh, const ViewMsg_PostMessage_Params& params) {} // A javascript message, confirmation or prompt should be shown. virtual void RunJavaScriptMessage(RenderViewHost* rvh, const string16& message, const string16& default_prompt, const GURL& frame_url, JavaScriptMessageType type, IPC::Message* reply_msg, bool* did_suppress_message) {} virtual void RunBeforeUnloadConfirm(RenderViewHost* rvh, const string16& message, bool is_reload, IPC::Message* reply_msg) {} // A message was added to to the console. virtual bool AddMessageToConsole(int32 level, const string16& message, int32 line_no, const string16& source_id); // Return a dummy RendererPreferences object that will be used by the renderer // associated with the owning RenderViewHost. virtual RendererPreferences GetRendererPrefs( BrowserContext* browser_context) const = 0; // Returns a WebPreferences object that will be used by the renderer // associated with the owning render view host. virtual WebPreferences GetWebkitPrefs(); // Notification the user has made a gesture while focus was on the // page. This is used to avoid uninitiated user downloads (aka carpet // bombing), see DownloadRequestLimiter for details. virtual void OnUserGesture() {} // Notification from the renderer host that blocked UI event occurred. // This happens when there are tab-modal dialogs. In this case, the // notification is needed to let us draw attention to the dialog (i.e. // refocus on the modal dialog, flash title etc). virtual void OnIgnoredUIEvent() {} // Notification that the renderer has become unresponsive. The // delegate can use this notification to show a warning to the user. virtual void RendererUnresponsive(RenderViewHost* render_view_host, bool is_during_before_unload, bool is_during_unload) {} // Notification that a previously unresponsive renderer has become // responsive again. The delegate can use this notification to end the // warning shown to the user. virtual void RendererResponsive(RenderViewHost* render_view_host) {} // Notification that the RenderViewHost's load state changed. virtual void LoadStateChanged(const GURL& url, const net::LoadStateWithParam& load_state, uint64 upload_position, uint64 upload_size) {} // Notification that a worker process has crashed. virtual void WorkerCrashed() {} // The page wants the hosting window to activate/deactivate itself (it // called the JavaScript window.focus()/blur() method). virtual void Activate() {} virtual void Deactivate() {} // Notification that the view has lost capture. virtual void LostCapture() {} // Notifications about mouse events in this view. This is useful for // implementing global 'on hover' features external to the view. virtual void HandleMouseMove() {} virtual void HandleMouseDown() {} virtual void HandleMouseLeave() {} virtual void HandleMouseUp() {} virtual void HandlePointerActivate() {} virtual void HandleGestureBegin() {} virtual void HandleGestureEnd() {} // Called when a file selection is to be done. virtual void RunFileChooser( RenderViewHost* render_view_host, const FileChooserParams& params) {} // Notification that the page wants to go into or out of fullscreen mode. virtual void ToggleFullscreenMode(bool enter_fullscreen) {} virtual bool IsFullscreenForCurrentTab() const; // The contents' preferred size changed. virtual void UpdatePreferredSize(const gfx::Size& pref_size) {} // The contents auto-resized and the container should match it. virtual void ResizeDueToAutoResize(const gfx::Size& new_size) {} // Requests to lock the mouse. Once the request is approved or rejected, // GotResponseToLockMouseRequest() will be called on the requesting render // view host. virtual void RequestToLockMouse(bool user_gesture, bool last_unlocked_by_target) {} // Notification that the view has lost the mouse lock. virtual void LostMouseLock() {} // The page is trying to open a new page (e.g. a popup window). The window // should be created associated with the given route, but it should not be // shown yet. That should happen in response to ShowCreatedWindow. // |params.window_container_type| describes the type of RenderViewHost // container that is requested -- in particular, the window.open call may // have specified 'background' and 'persistent' in the feature string. // // The passed |params.frame_name| parameter is the name parameter that was // passed to window.open(), and will be empty if none was passed. // // Note: this is not called "CreateWindow" because that will clash with // the Windows function which is actually a #define. virtual void CreateNewWindow( int route_id, int main_frame_route_id, const ViewHostMsg_CreateWindow_Params& params, SessionStorageNamespace* session_storage_namespace) {} // The page is trying to open a new widget (e.g. a select popup). The // widget should be created associated with the given route, but it should // not be shown yet. That should happen in response to ShowCreatedWidget. // |popup_type| indicates if the widget is a popup and what kind of popup it // is (select, autofill...). virtual void CreateNewWidget(int route_id, WebKit::WebPopupType popup_type) {} // Creates a full screen RenderWidget. Similar to above. virtual void CreateNewFullscreenWidget(int route_id) {} // Show a previously created page with the specified disposition and bounds. // The window is identified by the route_id passed to CreateNewWindow. // // Note: this is not called "ShowWindow" because that will clash with // the Windows function which is actually a #define. virtual void ShowCreatedWindow(int route_id, WindowOpenDisposition disposition, const gfx::Rect& initial_pos, bool user_gesture) {} // Show the newly created widget with the specified bounds. // The widget is identified by the route_id passed to CreateNewWidget. virtual void ShowCreatedWidget(int route_id, const gfx::Rect& initial_pos) {} // Show the newly created full screen widget. Similar to above. virtual void ShowCreatedFullscreenWidget(int route_id) {} // A context menu should be shown, to be built using the context information // provided in the supplied params. virtual void ShowContextMenu(const ContextMenuParams& params) {} // The render view has requested access to media devices listed in // |request|, and the client should grant or deny that permission by // calling |callback|. virtual void RequestMediaAccessPermission( const MediaStreamRequest& request, const MediaResponseCallback& callback) {} // Returns the SessionStorageNamespace the render view should use. Might // create the SessionStorageNamespace on the fly. virtual SessionStorageNamespace* GetSessionStorageNamespace( SiteInstance* instance); protected: virtual ~RenderViewHostDelegate() {} }; } // namespace content #endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_DELEGATE_H_
{ "content_hash": "ef8ad05dae3f109763c916f6a7c29237", "timestamp": "", "source": "github", "line_count": 419, "max_line_length": 80, "avg_line_length": 41.42959427207637, "alnum_prop": 0.6903623480615243, "repo_name": "mogoweb/chromium-crosswalk", "id": "997452aeb5447c915c3e7eed57d401492a39223c", "size": "18126", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "content/browser/renderer_host/render_view_host_delegate.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "54831" }, { "name": "Awk", "bytes": "8660" }, { "name": "C", "bytes": "40940503" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "182703853" }, { "name": "CSS", "bytes": "799795" }, { "name": "DOT", "bytes": "1873" }, { "name": "Java", "bytes": "4807735" }, { "name": "JavaScript", "bytes": "20714038" }, { "name": "Mercury", "bytes": "10299" }, { "name": "Objective-C", "bytes": "985558" }, { "name": "Objective-C++", "bytes": "6205987" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "1213389" }, { "name": "Python", "bytes": "9735121" }, { "name": "Rebol", "bytes": "262" }, { "name": "Shell", "bytes": "1305641" }, { "name": "Tcl", "bytes": "277091" }, { "name": "TypeScript", "bytes": "1560024" }, { "name": "XSLT", "bytes": "13493" }, { "name": "nesC", "bytes": "14650" } ], "symlink_target": "" }
iframe { width: 100%; height: 2rem; border: none; } /* Align inputs inputs and labels */ form { display: table; } form > div { display: table-row; } form label { display: table-cell; } form input { display: table-cell; }
{ "content_hash": "9609ec74c825b8129535b51f0d9115c5", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 36, "avg_line_length": 18.833333333333332, "alnum_prop": 0.6548672566371682, "repo_name": "zenhack/sandstorm-znc", "id": "5800fa48aee67156969c153150ccff7df6893e25", "size": "226", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "static/style.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "226" }, { "name": "Cap'n Proto", "bytes": "12571" }, { "name": "Go", "bytes": "14732" }, { "name": "HTML", "bytes": "1615" }, { "name": "JavaScript", "bytes": "1596" }, { "name": "Ruby", "bytes": "4830" }, { "name": "Shell", "bytes": "3853" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Authenticated")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Authenticated")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9c246aff-642b-43eb-adfc-dac99aaf84ce")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "923cb3239a958cea029388927c021603", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 84, "avg_line_length": 38.68571428571428, "alnum_prop": 0.7518463810930576, "repo_name": "jgraber/70-492", "id": "4f1c397cfd6afb95ba15c39587a886f485ea862c", "size": "1357", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WebAPI/Authenticated/Authenticated/Properties/AssemblyInfo.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "212" }, { "name": "C#", "bytes": "224281" }, { "name": "CSS", "bytes": "4396" }, { "name": "JavaScript", "bytes": "21428" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `InstantiatedPredicates` struct in crate `rustc`."> <meta name="keywords" content="rust, rustlang, rust-lang, InstantiatedPredicates"> <title>rustc::middle::ty::InstantiatedPredicates - Rust</title> <link rel="stylesheet" type="text/css" href="../../../main.css"> <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <section class="sidebar"> <a href='../../../rustc/index.html'><img src='http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='' width='100'></a> <p class='location'><a href='../../index.html'>rustc</a>::<wbr><a href='../index.html'>middle</a>::<wbr><a href='index.html'>ty</a></p><script>window.sidebarCurrent = {name: 'InstantiatedPredicates', ty: 'struct', relpath: ''};</script><script defer src="sidebar-items.js"></script> </section> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press 'S' to search, '?' for more options..." type="search"> </div> </form> </nav> <section id='main' class="content struct"> <h1 class='fqn'><span class='in-band'>Struct <a href='../../index.html'>rustc</a>::<wbr><a href='../index.html'>middle</a>::<wbr><a href='index.html'>ty</a>::<wbr><a class='struct' href=''>InstantiatedPredicates</a><wbr><a class='stability Unstable' title=''>Unstable</a></span><span class='out-of-band'><span id='render-detail'> <a id="collapse-all" href="#">[-]</a>&nbsp;<a id="expand-all" href="#">[+]</a> </span><a id='src-215113' href='../../../src/rustc/middle/ty.rs.html#2201-2203'>[src]</a></span></h1> <pre class='rust struct'>pub struct InstantiatedPredicates&lt;'tcx&gt; { pub predicates: <a class='struct' href='../../../rustc/middle/subst/struct.VecPerParamSpace.html' title='rustc::middle::subst::VecPerParamSpace'>VecPerParamSpace</a>&lt;<a class='enum' href='../../../rustc/middle/ty/enum.Predicate.html' title='rustc::middle::ty::Predicate'>Predicate</a>&lt;'tcx&gt;&gt;, }</pre><div class='docblock'><p>Represents the bounds declared on a particular set of type parameters. Should eventually be generalized into a flag list of where clauses. You can obtain a <code>InstantiatedPredicates</code> list from a <code>GenericPredicates</code> by using the <code>instantiate</code> method. Note that this method reflects an important semantic invariant of <code>InstantiatedPredicates</code>: while the <code>GenericPredicates</code> are expressed in terms of the bound type parameters of the impl/trait/whatever, an <code>InstantiatedPredicates</code> instance represented a set of bounds for some particular instantiation, meaning that the generic parameters have been substituted with their values.</p> <p>Example:</p> <pre id='rust-example-rendered' class='rust '> <span class='kw'>struct</span> <span class='ident'>Foo</span><span class='op'>&lt;</span><span class='ident'>T</span>,<span class='ident'>U</span>:<span class='ident'>Bar</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;&gt;</span> { ... } </pre> <p>Here, the <code>GenericPredicates</code> for <code>Foo</code> would contain a list of bounds like <code>[[], [U:Bar&lt;T&gt;]]</code>. Now if there were some particular reference like <code>Foo&lt;int,uint&gt;</code>, then the <code>InstantiatedPredicates</code> would be <code>[[], [uint:Bar&lt;int&gt;]]</code>.</p> </div><h2 class='fields'>Fields</h2> <table><tr><td id='structfield.predicates'><a class='stability Unstable' title='Unstable'></a><code>predicates</code></td><td></td></tr></table><h2 id='methods'>Methods</h2><h3 class='impl'><a class='stability Unstable' title='Unstable'></a><code>impl&lt;'tcx&gt; <a class='struct' href='../../../rustc/middle/ty/struct.InstantiatedPredicates.html' title='rustc::middle::ty::InstantiatedPredicates'>InstantiatedPredicates</a>&lt;'tcx&gt;</code></h3><div class='impl-items'><h4 id='method.empty' class='method'><a class='stability Unstable' title='Unstable'></a><code>fn <a href='#method.empty' class='fnname'>empty</a>() -&gt; <a class='struct' href='../../../rustc/middle/ty/struct.InstantiatedPredicates.html' title='rustc::middle::ty::InstantiatedPredicates'>InstantiatedPredicates</a>&lt;'tcx&gt;</code></h4> <h4 id='method.has_escaping_regions' class='method'><a class='stability Unstable' title='Unstable'></a><code>fn <a href='#method.has_escaping_regions' class='fnname'>has_escaping_regions</a>(&amp;self) -&gt; <a href='../../../std/primitive.bool.html'>bool</a></code></h4> <h4 id='method.is_empty' class='method'><a class='stability Unstable' title='Unstable'></a><code>fn <a href='#method.is_empty' class='fnname'>is_empty</a>(&amp;self) -&gt; <a href='../../../std/primitive.bool.html'>bool</a></code></h4> </div><h2 id='implementations'>Trait Implementations</h2><h3 class='impl'><a class='stability Unstable' title='Unstable'></a><code>impl&lt;'tcx&gt; <a class='trait' href='../../../rustc/middle/ty/trait.HasProjectionTypes.html' title='rustc::middle::ty::HasProjectionTypes'>HasProjectionTypes</a> for <a class='struct' href='../../../rustc/middle/ty/struct.InstantiatedPredicates.html' title='rustc::middle::ty::InstantiatedPredicates'>InstantiatedPredicates</a>&lt;'tcx&gt;</code></h3><div class='impl-items'><h4 id='method.has_projection_types' class='method'><a class='stability Unstable' title='Unstable'></a><code>fn <a href='#method.has_projection_types' class='fnname'>has_projection_types</a>(&amp;self) -&gt; <a href='../../../std/primitive.bool.html'>bool</a></code></h4> </div><h3 class='impl'><a class='stability Unstable' title='Unstable'></a><code>impl&lt;'tcx&gt; <a class='trait' href='../../../rustc/middle/ty_fold/trait.TypeFoldable.html' title='rustc::middle::ty_fold::TypeFoldable'>TypeFoldable</a>&lt;'tcx&gt; for <a class='struct' href='../../../rustc/middle/ty/struct.InstantiatedPredicates.html' title='rustc::middle::ty::InstantiatedPredicates'>InstantiatedPredicates</a>&lt;'tcx&gt;</code></h3><div class='impl-items'><h4 id='method.fold_with' class='method'><a class='stability Unstable' title='Unstable'></a><code>fn <a href='#method.fold_with' class='fnname'>fold_with</a>&lt;F: <a class='trait' href='../../../rustc/middle/ty_fold/trait.TypeFolder.html' title='rustc::middle::ty_fold::TypeFolder'>TypeFolder</a>&lt;'tcx&gt;&gt;(&amp;self, folder: &amp;mut F) -&gt; <a class='struct' href='../../../rustc/middle/ty/struct.InstantiatedPredicates.html' title='rustc::middle::ty::InstantiatedPredicates'>InstantiatedPredicates</a>&lt;'tcx&gt;</code></h4> </div><h3 class='impl'><a class='stability Unstable' title='Unstable'></a><code>impl&lt;'tcx&gt; <a class='trait' href='../../../rustc/util/ppaux/trait.Repr.html' title='rustc::util::ppaux::Repr'>Repr</a>&lt;'tcx&gt; for <a class='struct' href='../../../rustc/middle/ty/struct.InstantiatedPredicates.html' title='rustc::middle::ty::InstantiatedPredicates'>InstantiatedPredicates</a>&lt;'tcx&gt;</code></h3><div class='impl-items'><h4 id='method.repr' class='method'><a class='stability Unstable' title='Unstable'></a><code>fn <a href='#method.repr' class='fnname'>repr</a>(&amp;self, tcx: &amp;<a class='struct' href='../../../rustc/middle/ty/struct.ctxt.html' title='rustc::middle::ty::ctxt'>ctxt</a>&lt;'tcx&gt;) -&gt; <a class='struct' href='../../../collections/string/struct.String.html' title='collections::string::String'>String</a></code></h4> </div><h3 id='derived_implementations'>Derived Implementations </h3><h3 class='impl'><a class='stability Stable' title='Stable'></a><code>impl&lt;'tcx&gt; <a class='trait' href='../../../core/fmt/trait.Debug.html' title='core::fmt::Debug'>Debug</a> for <a class='struct' href='../../../rustc/middle/ty/struct.InstantiatedPredicates.html' title='rustc::middle::ty::InstantiatedPredicates'>InstantiatedPredicates</a>&lt;'tcx&gt;</code></h3><div class='impl-items'><h4 id='method.fmt' class='method'><a class='stability Stable' title='Stable'></a><code>fn <a href='#method.fmt' class='fnname'>fmt</a>(&amp;self, __arg_0: &amp;mut <a class='struct' href='../../../core/fmt/struct.Formatter.html' title='core::fmt::Formatter'>Formatter</a>) -&gt; <a class='type' href='../../../core/fmt/type.Result.html' title='core::fmt::Result'>Result</a></code></h4> </div><h3 class='impl'><a class='stability Stable' title='Stable'></a><code>impl&lt;'tcx&gt; <a class='trait' href='../../../core/clone/trait.Clone.html' title='core::clone::Clone'>Clone</a> for <a class='struct' href='../../../rustc/middle/ty/struct.InstantiatedPredicates.html' title='rustc::middle::ty::InstantiatedPredicates'>InstantiatedPredicates</a>&lt;'tcx&gt;</code></h3><div class='impl-items'><h4 id='method.clone' class='method'><a class='stability Stable' title='Stable'></a><code>fn <a href='#method.clone' class='fnname'>clone</a>(&amp;self) -&gt; <a class='struct' href='../../../rustc/middle/ty/struct.InstantiatedPredicates.html' title='rustc::middle::ty::InstantiatedPredicates'>InstantiatedPredicates</a>&lt;'tcx&gt;</code></h4> <h4 id='method.clone_from' class='tymethod'><a class='stability Unstable' title='Unstable: this function is rarely used'></a><code>fn <a href='#tymethod.clone_from' class='fnname'>clone_from</a>(&amp;mut self, source: &amp;Self)</code></h4> </div></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <div id="help" class="hidden"> <div class="shortcuts"> <h1>Keyboard shortcuts</h1> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h1>Search tricks</h1> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>typedef</code> (or <code>tdef</code>). </p> </div> </div> <script> window.rootPath = "../../../"; window.currentCrate = "rustc"; window.playgroundUrl = ""; </script> <script src="../../../jquery.js"></script> <script src="../../../main.js"></script> <script async src="../../../search-index.js"></script> </body> </html>
{ "content_hash": "c54b3fc3f4fb4e3cd0cf45cff95f9d22", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 998, "avg_line_length": 89.67716535433071, "alnum_prop": 0.6489595223461234, "repo_name": "ArcherSys/ArcherSys", "id": "fa1a5ad1568043ea2634aee80e18d5a8c7ea4769", "size": "11389", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Rust/share/doc/rust/html/rustc/middle/ty/struct.InstantiatedPredicates.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
author: robmyers comments: true date: 2007-04-16 07:56:04+00:00 layout: post slug: enarting title: enarting wordpress_id: 1263 categories: - Aesthetics --- Enarting is generalized nomination.
{ "content_hash": "a65da36fc3505265180a75234af8495f", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 37, "avg_line_length": 14.071428571428571, "alnum_prop": 0.7563451776649747, "repo_name": "robmyers/robmyers.org", "id": "a279615de5e5d3729780e4277d6369888108a2a0", "size": "201", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2007-04-16-enarting.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18921" }, { "name": "HTML", "bytes": "14981" }, { "name": "JavaScript", "bytes": "62388" }, { "name": "PHP", "bytes": "30" }, { "name": "R", "bytes": "16999" }, { "name": "Ruby", "bytes": "2751" }, { "name": "Scheme", "bytes": "2307" } ], "symlink_target": "" }
namespace laminate { std::ostream& operator<<(std::ostream& os, const Status& x) { os << x.Message(); return os; } } // namespace laminate
{ "content_hash": "a444e1b4617d5384fa87845a467a9b41", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 61, "avg_line_length": 18.25, "alnum_prop": 0.6438356164383562, "repo_name": "ibab/protobuf-laminate", "id": "19b67b86f11793cf56332a160ceab944ae3f1e3d", "size": "168", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/status.cc", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "16320" }, { "name": "Python", "bytes": "1162" } ], "symlink_target": "" }
<?php /** * Upgrader API: Language_Pack_Upgrader_Skin class * * @package WordPress * @subpackage Upgrader * @since 4.6.0 */ /** * Translation Upgrader Skin for WordPress Translation Upgrades. * * @since 3.7.0 * @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php. * * @see WP_Upgrader_Skin */ class Language_Pack_Upgrader_Skin extends WP_Upgrader_Skin { public $language_update = null; public $done_header = false; public $done_footer = false; public $display_footer_actions = true; /** * @param array $args */ public function __construct( $args = array() ) { $defaults = array( 'url' => '', 'nonce' => '', 'title' => __( 'Update Translations' ), 'skip_header_footer' => false, ); $args = wp_parse_args( $args, $defaults ); if ( $args['skip_header_footer'] ) { $this->done_header = true; $this->done_footer = true; $this->display_footer_actions = false; } parent::__construct( $args ); } /** */ public function before() { $name = $this->upgrader->get_name_for_update( $this->language_update ); echo '<div class="update-messages lp-show-latest">'; /* translators: 1: Project name (plugin, theme, or WordPress), 2: Language. */ printf( '<h2>' . __( 'Updating translations for %1$s (%2$s)&#8230;' ) . '</h2>', $name, $this->language_update->language ); } /** * @param string|WP_Error $error */ public function error( $error ) { echo '<div class="lp-error">'; parent::error( $error ); echo '</div>'; } /** */ public function after() { echo '</div>'; } /** */ public function bulk_footer() { $this->decrement_update_count( 'translation' ); $update_actions = array( 'updates_page' => sprintf( '<a href="%s" target="_parent">%s</a>', self_admin_url( 'update-core.php' ), __( 'Go to WordPress Updates page' ) ), ); /** * Filters the list of action links available following a translations update. * * @since 3.7.0 * * @param string[] $update_actions Array of translations update links. */ $update_actions = apply_filters( 'update_translations_complete_actions', $update_actions ); if ( $update_actions && $this->display_footer_actions ) { $this->feedback( implode( ' | ', $update_actions ) ); } } }
{ "content_hash": "77fcf84897a91d206c014f204a0d4e12", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 125, "avg_line_length": 25.05263157894737, "alnum_prop": 0.588655462184874, "repo_name": "misfit-inc/misfit.co", "id": "05676269f0492fd1e36a049a0a05716943385aa2", "size": "2380", "binary": false, "copies": "25", "ref": "refs/heads/master", "path": "wp-admin/includes/class-language-pack-upgrader-skin.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8383153" }, { "name": "HTML", "bytes": "1303255" }, { "name": "Hack", "bytes": "8862" }, { "name": "JavaScript", "bytes": "9741798" }, { "name": "Modelica", "bytes": "10338" }, { "name": "PHP", "bytes": "69279484" }, { "name": "Ruby", "bytes": "863" }, { "name": "Smarty", "bytes": "160078" }, { "name": "VCL", "bytes": "2554" }, { "name": "XSLT", "bytes": "18752" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "5307bb7af420eb93574d0d7639385050", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "ea57292be218a392d8c2e18ded3108c67eb78976", "size": "192", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Phyllanthaceae/Antidesma/Antidesma acidum/ Syn. Antidesma diandrum lanceolatum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
Dieser Service erzeugt Events und publiziert sie in eine Messagequeue. ### Events Welche Events? Einzelnes Event oder viele? Dieser Microservice bietet folgende Funktionalität an: * UI zu Anlegen, Ändern und Löschen von Konten per Event (asynchron). * Zufallsgesteuerter Generator von Umsätzen je aktives Konto. Zur Vereinfachung hat ein Konto nur einen Inhaber, der per Namen identifiziert wird und _keine_ Kundennummer hat, weil derzeit kein System zur Verwaltung von Kunden vorliegt. ## Implementierung ### Konfiguration RabbitMQ starten `sudo rabbitmq-server start|stop|staus` oder `sudo rabbitmqctl start|stop|status` ## Test Dieser Service kann einfach durch Aufruf der URL `http://<host>:<port>/` aufgerufen werden oder aus einer Bash mit `curl <host>:<port>`. In Fehlerfall kann der HTTP-Header mit `curl -i <host>:<port>` ausgegeben werden. ```` curl localhost:9090/?name=Jürgen | json_pp ```` Liefert ein JSON-Objekt der Art: ```` { "id": 1, "name": "Jürgen", "primes": [2, 3, 5, ... 997] } ```` ## Actuator Spring Boot liefert sog. Actuators mit. Wir aktivieren die Actuators, weil sie von die Netflix-Services für die Überwachung benötigt werden. Der für uns wichtigste Actuator ist der Health-Endpoint. Er ist unter `/health` erreichbar. ```` curl localhost:9090/health | json_pp ```` liefert etwas in der Art ```` { "status": "UP", "diskSpace": { "status": "UP", "total": 511397851136, "free": 200806346752, "threshold": 10485760 } } ```` ## Profile Das Projekt verfügt über zwei Profile: * local * docker ### local In diesem Profil laufen alle Services auf localhost und die Ports werden so umgebogen, dass sich die Services nicht gegenseitig behindern. Die Konfiguration erfolgt in application-local.properties Um dieses Profil zu starten muss _kein_ Parameter gesetzt / übergeben werden. ### docker In diesem Profil laufen alle Service in einem eigenen Docker-Container. Die Services haben also eine eigene IP-Adresse und können alle auf dem jeweils gleichen Port laufen, weil sie ja isoliert voneinander sind. Um dieses Profil zu starten muss das Profil beim Start gesetzt werden. Dazu stehen zwei Varianten zur Verfügung: ```` java -jar hello-world-0.0.1-SNAPSHOT.jar --spring.profiles.active=docker ```` oder ```` java -jar -Dspring.profiles.active=docker hello-world-0.0.1-SNAPSHOT.jar ```` # Todo * Ab 10_Docker_Images_skaliert funktioniert der Absprung aus Eureka nicht mehr. Eureka lenkt auf die IP-Adresse:Serverport um. Leider ist der Port nicht in Docker freigegeben. Wünschenswert wäre, dass der Zugriff via Zuul funktioniert.
{ "content_hash": "320a09ce8f7dd0bad71500e4f71bb2bd", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 79, "avg_line_length": 23.669642857142858, "alnum_prop": 0.7359486986043002, "repo_name": "jdufner/microservice", "id": "88391a7b71b29b0be140b48679f48ebc9625925e", "size": "2715", "binary": false, "copies": "1", "ref": "refs/heads/11_log_correlation_with_sleuth_implemented", "path": "kontoverwaltung/readme.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "40048" }, { "name": "HTML", "bytes": "1039" }, { "name": "Java", "bytes": "44619" }, { "name": "Shell", "bytes": "71120" } ], "symlink_target": "" }
// Karma configuration // http://karma-runner.github.io/0.13/config/configuration-file.html var sourcePreprocessors = ['coverage']; function isDebug() { return process.argv.indexOf('--debug') >= 0; } if (isDebug()) { // Disable JS minification if Karma is run with debug option. sourcePreprocessors = []; } module.exports = function (config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '<%= TEST_SRC_DIR %>'.replace(/[^/]+/g, '..'), // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ // bower:js // endbower '<%= MAIN_SRC_DIR %>app/app.module.js', '<%= MAIN_SRC_DIR %>app/app.state.js', '<%= MAIN_SRC_DIR %>app/app.constants.js', '<%= MAIN_SRC_DIR %>app/**/*.+(js|html)', '<%= TEST_SRC_DIR %>spec/helpers/module.js', '<%= TEST_SRC_DIR %>spec/helpers/httpBackend.js', '<%= TEST_SRC_DIR %>**/!(karma.conf<% if (testFrameworks.indexOf("protractor") > -1) { %>|protractor.conf<% } %>).js' ], // list of files / patterns to exclude exclude: [<% if (testFrameworks.indexOf('protractor') > -1) { %>'<%= TEST_SRC_DIR %>e2e/**'<% } %>], preprocessors: { './**/*.js': sourcePreprocessors }, reporters: ['dots', 'junit', 'coverage', 'progress'], junitReporter: {<% if (buildTool == 'maven') { %> outputFile: '../target/test-results/karma/TESTS-results.xml'<% } else { %> outputFile: '../build/test-results/karma/TESTS-results.xml'<% } %> }, coverageReporter: {<% if (buildTool == 'maven') { %> dir: 'target/test-results/coverage',<% } else { %> dir: 'build/test-results/coverage',<% } %> reporters: [ {type: 'lcov', subdir: 'report-lcov'} ] }, // web server port port: 9876, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['PhantomJS'], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false, // to avoid DISCONNECTED messages when connecting to slow virtual machines browserDisconnectTimeout: 10000, // default 2000 browserDisconnectTolerance: 1, // default 0 browserNoActivityTimeout: 4 * 60 * 1000 //default 10000 }); };
{ "content_hash": "39d2395659c22289b8b4805689c51ed7", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 129, "avg_line_length": 34.05681818181818, "alnum_prop": 0.5438772105438772, "repo_name": "xetys/generator-jhipster", "id": "dde6073fa20f55352f78e8ad23fdfb32dbcc74f0", "size": "2997", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "generators/client/templates/src/test/javascript/_karma.conf.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5006" }, { "name": "CSS", "bytes": "20760" }, { "name": "Gherkin", "bytes": "161" }, { "name": "HTML", "bytes": "180436" }, { "name": "Java", "bytes": "596065" }, { "name": "JavaScript", "bytes": "802627" }, { "name": "Scala", "bytes": "6376" }, { "name": "Shell", "bytes": "25297" } ], "symlink_target": "" }
package context import ( "github.com/jesusslim/slimgo/session" "net/http" "net/url" "strconv" "strings" ) type ContextInput struct { Request *http.Request Session session.SessionInstance } func NewContextInput(req *http.Request) *ContextInput { return &ContextInput{ Request: req, } } //Protocol func (this *ContextInput) Protocol() string { return this.Request.Proto } //Url func (this *ContextInput) Url() string { return this.Request.URL.Path } //Uri func (this *ContextInput) Uri() string { return this.Request.RequestURI } //Host func (this *ContextInput) Host() string { if this.Request.Host != "" { hostArr := strings.Split(this.Request.Host, ":") if len(hostArr) > 0 { return hostArr[0] } return this.Request.Host } return "localhost" } //Method func (this *ContextInput) IsMethod(method string) bool { return this.Request.Method == method } func (this *ContextInput) IsGet() bool { return this.IsMethod("GET") } func (this *ContextInput) IsPost() bool { return this.IsMethod("POST") } func (this *ContextInput) IsPut() bool { return this.IsMethod("PUT") } func (this *ContextInput) IsDelete() bool { return this.IsMethod("DELETE") } func (this *ContextInput) IsPatch() bool { return this.IsMethod("PATCH") } //Header func (this *ContextInput) Header(key string) string { return this.Request.Header.Get(key) } //Is upload form func (this *ContextInput) IsUpload() bool { return strings.Contains(this.Header("Content-Type"), "multipart/form-data") } //Is websocket func (this *ContextInput) IsWebsocket() bool { return this.Header("Upgrade") == "websocket" } //Proxy func (this *ContextInput) Proxy() []string { if ips := this.Header("X-Forwarded-For"); ips != "" { return strings.Split(ips, ",") } return []string{} } //IP func (this *ContextInput) Ip() string { ips := this.Proxy() if len(ips) > 0 && ips[0] != "" { ipsArr := strings.Split(ips[0], ":") return ipsArr[0] } ipArr := strings.Split(this.Request.RemoteAddr, ":") if len(ipArr) > 0 { if ipArr[0] != "[" { return ipArr[0] } } return "127.0.0.1" } //Port func (this *ContextInput) Port() int { portArr := strings.Split(this.Request.Host, ":") if len(portArr) > 1 { port, _ := strconv.Atoi(portArr[1]) return port } return 80 } //Referer func (this *ContextInput) Referer() string { return this.Header("Referer") } //Cookie func (this *ContextInput) Cookie(key string) string { cookie, err := this.Request.Cookie(key) if err != nil { return "" } return cookie.Value } //get param func (this *ContextInput) GetParam(key string) string { if this.Request.Form == nil { this.Request.ParseForm() } return this.Request.Form.Get(key) } func (this *ContextInput) GetForm() url.Values { if this.Request.Form == nil { this.Request.ParseForm() } return this.Request.Form } func (this *ContextInput) GetString(key string, defaultValue ...string) string { var result string if len(defaultValue) > 0 { result = defaultValue[0] } if v := this.GetForm().Get(key); v != "" { result = v } return result } func (this *ContextInput) GetInt(key string, defaultValue ...int) int { var result int if len(defaultValue) > 0 { result = defaultValue[0] } if v := this.GetForm().Get(key); v != "" { if temp, err := strconv.Atoi(v); err == nil { result = temp } } return result } func (this *ContextInput) GetFloat(key string, defaultValue ...float64) float64 { var result float64 if len(defaultValue) > 0 { result = defaultValue[0] } if v := this.GetForm().Get(key); v != "" { if temp, err := strconv.ParseFloat(v, 64); err == nil { result = temp } } return result } func (this *ContextInput) GetBool(key string, defaultValue ...bool) bool { var result bool if len(defaultValue) > 0 { result = defaultValue[0] } if v := this.GetForm().Get(key); v != "" { if temp, err := strconv.ParseBool(v); err == nil { result = temp } } return result }
{ "content_hash": "e61ae6c366cc4ca3cb47392e9c5b72e8", "timestamp": "", "source": "github", "line_count": 200, "max_line_length": 81, "avg_line_length": 19.73, "alnum_prop": 0.6642169285352255, "repo_name": "jesusslim/slimgo", "id": "764894c2b3721bf29bfcce0286cb719b0de3488d", "size": "3946", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "context/input.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "50972" } ], "symlink_target": "" }
'use strict'; require('../common'); const assert = require('assert'); const { TCP, constants: TCPConstants } = process.binding('tcp_wrap'); const TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap; const ShutdownWrap = process.binding('stream_wrap').ShutdownWrap; function makeConnection() { const client = new TCP(TCPConstants.SOCKET); const req = new TCPConnectWrap(); const err = client.connect(req, '127.0.0.1', this.address().port); assert.strictEqual(err, 0); req.oncomplete = function(status, client_, req_, readable, writable) { assert.strictEqual(0, status); assert.strictEqual(client, client_); assert.strictEqual(req, req_); assert.strictEqual(true, readable); assert.strictEqual(true, writable); const shutdownReq = new ShutdownWrap(); const err = client.shutdown(shutdownReq); assert.strictEqual(err, 0); shutdownReq.oncomplete = function(status, client_, error) { assert.strictEqual(0, status); assert.strictEqual(client, client_); assert.strictEqual(error, undefined); shutdownCount++; client.close(); }; }; } let connectCount = 0; let endCount = 0; let shutdownCount = 0; const server = require('net').Server(function(s) { connectCount++; s.resume(); s.on('end', function() { endCount++; s.destroy(); server.close(); }); }); server.listen(0, makeConnection); process.on('exit', function() { assert.strictEqual(1, shutdownCount); assert.strictEqual(1, connectCount); assert.strictEqual(1, endCount); });
{ "content_hash": "cf1488359ebf9b5ac89f245a51f961bc", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 72, "avg_line_length": 27.589285714285715, "alnum_prop": 0.6809061488673139, "repo_name": "MTASZTAKI/ApertusVR", "id": "36f87d1863ef36d11a07fe0fddf37d376a116d43", "size": "1545", "binary": false, "copies": "1", "ref": "refs/heads/0.9", "path": "plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/test/parallel/test-tcp-wrap-connect.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "7599" }, { "name": "C++", "bytes": "1207412" }, { "name": "CMake", "bytes": "165066" }, { "name": "CSS", "bytes": "1816" }, { "name": "GLSL", "bytes": "223507" }, { "name": "HLSL", "bytes": "141879" }, { "name": "HTML", "bytes": "34827" }, { "name": "JavaScript", "bytes": "140550" }, { "name": "Python", "bytes": "1370" } ], "symlink_target": "" }
using CRP.Controllers; using CRP.Controllers.Helpers; using CRP.Controllers.ViewModels; using CRP.Core.Domain; using CRP.Core.Resources; using CRP.Tests.Core.Extensions; using CRP.Tests.Core.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using MvcContrib.TestHelper; using Rhino.Mocks; namespace CRP.Tests.Controllers.QuestionSetControllerTests { public partial class QuestionSetControllerTests { #region Edit Get Tests /// <summary> /// Tests the edit get when question set id not found redirects to list. /// </summary> [TestMethod] public void TestEditGetWhenQuestionSetIdNotFoundRedirectsToList() { #region Arrange ControllerRecordFakes.FakeQuestionSets(QuestionSets, 3); QuestionSetRepository.Expect(a => a.GetNullableById(2)).Return(null).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(2) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } #region Edit Get Redirects To List Because Of HasQuestionSetAccess /// <summary> /// Tests the edit get where question set id Is found but no access redirects to list. /// </summary> [TestMethod] public void TestEditGetWhereQuestionSetIdIsFoundButNoAccessRedirectsToList1() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.User }); SetupDataForTests(); QuestionSetRepository.Expect(a => a.GetNullableById(7)).Return(QuestionSets[6]).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(7) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } /// <summary> /// College reusable /// </summary> [TestMethod] public void TestEditGetWhereQuestionSetIdIsFoundButNoAccessRedirectsToList2() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.User }); SetupDataForTests(); QuestionSetRepository.Expect(a => a.GetNullableById(4)).Return(QuestionSets[3]).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(4) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } /// <summary> /// College reusable /// QuestionSet 4 is a school, but not one the user has access to /// </summary> [TestMethod] public void TestEditGetWhereQuestionSetIdIsFoundButNoAccessRedirectsToList3() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.Admin }); SetupDataForTests(); QuestionSetRepository.Expect(a => a.GetNullableById(5)).Return(QuestionSets[4]).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(5) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } /// <summary> /// College reusable /// QuestionSet 4 is a school, but not one the user has access to /// </summary> [TestMethod] public void TestEditGetWhereQuestionSetIdIsFoundButNoAccessRedirectsToList4() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.SchoolAdmin }); SetupDataForTests(); QuestionSetRepository.Expect(a => a.GetNullableById(5)).Return(QuestionSets[4]).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(5) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } /// <summary> /// User reusable, but QuestionSet 1 is attached to a different user /// </summary> [TestMethod] public void TestEditGetWhereQuestionSetIdIsFoundButNoAccessRedirectsToList5() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.User }); SetupDataForTests(); QuestionSetRepository.Expect(a => a.GetNullableById(2)).Return(QuestionSets[1]).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(2) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } /// <summary> /// no reusable, not admin, and has an item type /// </summary> [TestMethod] public void TestEditGetWhereQuestionSetIdIsFoundButNoAccessRedirectsToList6() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.User }); SetupDataForTests(); QuestionSetRepository.Expect(a => a.GetNullableById(8)).Return(QuestionSets[7]).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(8) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } [TestMethod] public void TestEditGetWhereQuestionSetIdIsFoundButNoAccessRedirectsToList7() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.User }); SetupDataForTests(); QuestionSetRepository.Expect(a => a.GetNullableById(9)).Return(QuestionSets[8]).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(9) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } #endregion Edit Get Redirects To List Because Of HasQuestionSetAccess /// <summary> /// Tests the edit get where question set id is found and has item access because user is an editor returns view. /// </summary> [TestMethod] public void TestEditGetWhereQuestionSetIdIsFoundAndHasItemAccessBecauseUserIsAnEditorReturnsView() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.User }); SetupDataForTests(); QuestionSetRepository.Expect(a => a.GetNullableById(10)).Return(QuestionSets[9]).Repeat.Any(); #endregion Arrange #region Act var result = Controller.Edit(10) .AssertViewRendered() .WithViewData<QuestionSetViewModel>(); #endregion Act #region Assert Assert.IsNull(Controller.Message); Assert.IsNotNull(result); Assert.AreSame(QuestionSets[9], result.QuestionSet); #endregion Assert } #endregion Edit Get Tests #region Edit Post Tests /// <summary> /// Tests the edit post when question set id not found redirects to list. /// </summary> [TestMethod] public void TestEditPostWhenQuestionSetIdNotFoundRedirectsToList() { #region Arrange ControllerRecordFakes.FakeQuestionSets(QuestionSets, 3); var questionSetToUpdate = CreateValidEntities.QuestionSet(null); QuestionSetRepository.Expect(a => a.GetNullableById(2)).Return(null).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(2, questionSetToUpdate) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } #region Edit Post Redirects To List Because Of HasQuestionSetAccess /// <summary> /// Tests the edit post where question set id Is found but no access redirects to list. /// </summary> [TestMethod] public void TestEditPostWhereQuestionSetIdIsFoundButNoAccessRedirectsToList1() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.User }); SetupDataForTests(); var questionSetToUpdate = CreateValidEntities.QuestionSet(null); QuestionSetRepository.Expect(a => a.GetNullableById(7)).Return(QuestionSets[6]).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(7, questionSetToUpdate) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } /// <summary> /// College reusable /// </summary> [TestMethod] public void TestEditPostWhereQuestionSetIdIsFoundButNoAccessRedirectsToList2() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.User }); SetupDataForTests(); var questionSetToUpdate = CreateValidEntities.QuestionSet(null); QuestionSetRepository.Expect(a => a.GetNullableById(4)).Return(QuestionSets[3]).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(4, questionSetToUpdate) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } /// <summary> /// College reusable /// QuestionSet 4 is a school, but not one the user has access to /// </summary> [TestMethod] public void TestEditPostWhereQuestionSetIdIsFoundButNoAccessRedirectsToList3() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.Admin }); SetupDataForTests(); var questionSetToUpdate = CreateValidEntities.QuestionSet(null); QuestionSetRepository.Expect(a => a.GetNullableById(5)).Return(QuestionSets[4]).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(5, questionSetToUpdate) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } /// <summary> /// College reusable /// QuestionSet 4 is a school, but not one the user has access to /// </summary> [TestMethod] public void TestEditPostWhereQuestionSetIdIsFoundButNoAccessRedirectsToList4() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.SchoolAdmin }); SetupDataForTests(); var questionSetToUpdate = CreateValidEntities.QuestionSet(null); QuestionSetRepository.Expect(a => a.GetNullableById(5)).Return(QuestionSets[4]).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(5, questionSetToUpdate) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } /// <summary> /// User reusable, but QuestionSet 1 is attached to a different user /// </summary> [TestMethod] public void TestEditPostWhereQuestionSetIdIsFoundButNoAccessRedirectsToList5() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.User }); SetupDataForTests(); var questionSetToUpdate = CreateValidEntities.QuestionSet(null); QuestionSetRepository.Expect(a => a.GetNullableById(2)).Return(QuestionSets[1]).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(2, questionSetToUpdate) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } /// <summary> /// no reusable, not admin, and has an item type /// </summary> [TestMethod] public void TestEditPostWhereQuestionSetIdIsFoundButNoAccessRedirectsToList6() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.User }); SetupDataForTests(); var questionSetToUpdate = CreateValidEntities.QuestionSet(null); QuestionSetRepository.Expect(a => a.GetNullableById(8)).Return(QuestionSets[7]).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(8, questionSetToUpdate) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } [TestMethod] public void TestEditPostWhereQuestionSetIdIsFoundButNoAccessRedirectsToList7() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.User }); SetupDataForTests(); var questionSetToUpdate = CreateValidEntities.QuestionSet(null); QuestionSetRepository.Expect(a => a.GetNullableById(9)).Return(QuestionSets[8]).Repeat.Any(); #endregion Arrange #region Act Controller.Edit(9, questionSetToUpdate) .AssertActionRedirect() .ToAction<QuestionSetController>(a => a.List()); #endregion Act #region Assert Assert.AreEqual("You do not have access to the requested Question Set.", Controller.Message); #endregion Assert } #endregion Edit Post Redirects To List Because Of HasQuestionSetAccess /// <summary> /// Tests the edit post only updates name and active values. /// </summary> [TestMethod] public void TestEditPostOnlyUpdatesNameAndActiveValues() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.User }); SetupDataForTests(); var questionSetToUpdate = CreateValidEntities.QuestionSet(null); questionSetToUpdate.Name = "nameUpdate"; questionSetToUpdate.IsActive = true; questionSetToUpdate.Items = null; questionSetToUpdate.ItemTypes = null; questionSetToUpdate.Questions = null; questionSetToUpdate.School = Schools[0]; questionSetToUpdate.SystemReusable = true; questionSetToUpdate.User = null; questionSetToUpdate.UserReusable = true; questionSetToUpdate.CollegeReusable = true; QuestionSetRepository.Expect(a => a.GetNullableById(10)).Return(QuestionSets[9]).Repeat.Any(); //Verify that fields are different Assert.AreNotEqual(QuestionSets[9].Name, questionSetToUpdate.Name); Assert.AreNotEqual(QuestionSets[9].IsActive, questionSetToUpdate.IsActive); Assert.AreNotEqual(QuestionSets[9].Items, questionSetToUpdate.Items); Assert.AreNotEqual(QuestionSets[9].ItemTypes, questionSetToUpdate.ItemTypes); Assert.AreNotEqual(QuestionSets[9].Questions, questionSetToUpdate.Questions); Assert.AreNotEqual(QuestionSets[9].School, questionSetToUpdate.School); Assert.AreNotEqual(QuestionSets[9].SystemReusable, questionSetToUpdate.SystemReusable); Assert.AreNotEqual(QuestionSets[9].User, questionSetToUpdate.User); Assert.AreNotEqual(QuestionSets[9].UserReusable, questionSetToUpdate.UserReusable); Assert.AreNotEqual(QuestionSets[9].CollegeReusable, questionSetToUpdate.CollegeReusable); #endregion Arrange #region Act var result = Controller.Edit(10, questionSetToUpdate) .AssertViewRendered() .WithViewData<QuestionSetViewModel>(); #endregion Act #region Assert Assert.IsNotNull(result); QuestionSetRepository.AssertWasCalled(a => a.EnsurePersistent(QuestionSets[9])); Assert.AreEqual("Question Set has been saved successfully.", Controller.Message); //Check that only expected fields are updated Assert.AreEqual(QuestionSets[9].Name, questionSetToUpdate.Name); Assert.AreEqual(QuestionSets[9].IsActive, questionSetToUpdate.IsActive); Assert.AreNotEqual(QuestionSets[9].Items, questionSetToUpdate.Items); Assert.AreNotEqual(QuestionSets[9].ItemTypes, questionSetToUpdate.ItemTypes); Assert.AreNotEqual(QuestionSets[9].Questions, questionSetToUpdate.Questions); Assert.AreNotEqual(QuestionSets[9].School, questionSetToUpdate.School); Assert.AreNotEqual(QuestionSets[9].SystemReusable, questionSetToUpdate.SystemReusable); Assert.AreNotEqual(QuestionSets[9].User, questionSetToUpdate.User); Assert.AreNotEqual(QuestionSets[9].UserReusable, questionSetToUpdate.UserReusable); Assert.AreNotEqual(QuestionSets[9].CollegeReusable, questionSetToUpdate.CollegeReusable); Assert.AreSame(result.QuestionSet, QuestionSets[9]); #endregion Assert } /// <summary> /// Tests the empty name of the edit post does not save with an. /// </summary> [TestMethod] public void TestEditPostDoesNotSaveWithAnEmptyName() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.User }); SetupDataForTests(); var questionSetToUpdate = CreateValidEntities.QuestionSet(null); questionSetToUpdate.Name = string.Empty; QuestionSetRepository.Expect(a => a.GetNullableById(10)).Return(QuestionSets[9]).Repeat.Any(); #endregion Arrange #region Act var result = Controller.Edit(10, questionSetToUpdate) .AssertViewRendered() .WithViewData<QuestionSetViewModel>(); #endregion Act #region Assert Assert.IsNotNull(result); QuestionSetRepository.AssertWasNotCalled(a => a.EnsurePersistent(Arg<QuestionSet>.Is.Anything)); Assert.IsNull(Controller.Message); Controller.ModelState.AssertErrorsAre("Name: may not be null or empty"); #endregion Assert } /// <summary> /// Tests the edit post will not modify contact information. /// </summary> [TestMethod] public void TestEditPostWillNotModifyContactInformation() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.Admin }); SetupDataForTests(); //Make #9 the Contact Info record. QuestionSets[9].Name = StaticValues.QuestionSet_ContactInformation; QuestionSets[9].IsActive = true; QuestionSets[9].SystemReusable = true; var questionSetToUpdate = CreateValidEntities.QuestionSet(null); questionSetToUpdate.Name = StaticValues.QuestionSet_ContactInformation + "oops"; QuestionSetRepository.Expect(a => a.GetNullableById(10)).Return(QuestionSets[9]).Repeat.Any(); #endregion Arrange #region Act var result = Controller.Edit(10, questionSetToUpdate) .AssertViewRendered() .WithViewData<QuestionSetViewModel>(); #endregion Act #region Assert Assert.IsNotNull(result); QuestionSetRepository.AssertWasNotCalled(a => a.EnsurePersistent(Arg<QuestionSet>.Is.Anything)); Assert.AreEqual("This is a system default question set and cannot be modified", Controller.Message); Controller.ModelState.AssertErrorsAre("This is a system default question set and cannot be modified"); #endregion Assert } /// <summary> /// Tests the edit post will not save if the contact name is changed to contact information. /// </summary> [TestMethod] public void TestEditPostWillNotSaveIfTheContactNameIsChangedToContactInformation() { #region Arrange Controller.ControllerContext.HttpContext = new MockHttpContext(1, new[] { RoleNames.User }); SetupDataForTests(); var questionSetToUpdate = CreateValidEntities.QuestionSet(null); questionSetToUpdate.Name = StaticValues.QuestionSet_ContactInformation.ToUpper(); QuestionSetRepository.Expect(a => a.GetNullableById(10)).Return(QuestionSets[9]).Repeat.Any(); #endregion Arrange #region Act var result = Controller.Edit(10, questionSetToUpdate) .AssertViewRendered() .WithViewData<QuestionSetViewModel>(); #endregion Act #region Assert Assert.IsNotNull(result); QuestionSetRepository.AssertWasNotCalled(a => a.EnsurePersistent(Arg<QuestionSet>.Is.Anything)); Assert.AreEqual(StaticValues.QuestionSet_ContactInformation + " is reserved for internal system use only.", Controller.Message); Controller.ModelState.AssertErrorsAre(StaticValues.QuestionSet_ContactInformation + " is reserved for internal system use only."); #endregion Assert } #endregion Edit Post Tests } }
{ "content_hash": "f926e44a580f5908a7c3409600267b39", "timestamp": "", "source": "github", "line_count": 582, "max_line_length": 142, "avg_line_length": 43.18041237113402, "alnum_prop": 0.6066610958577057, "repo_name": "ucdavis/CRP", "id": "e37c126b19008579fbc46aabe9e414f227a534c7", "size": "25133", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CRP.Tests/Controllers/QuestionSetControllerTests/QuestionSetControllerTestsPart5.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "98" }, { "name": "C#", "bytes": "3300195" }, { "name": "CSS", "bytes": "78083" }, { "name": "HTML", "bytes": "290419" }, { "name": "JavaScript", "bytes": "360563" }, { "name": "TSQL", "bytes": "120390" } ], "symlink_target": "" }
if [ -d /Library/TeX/texbin ]; then export PATH=$PATH:/Library/TeX/texbin #TeXLive Support fi
{ "content_hash": "d9dd02abeeac7a0c40468a61b29e6553", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 58, "avg_line_length": 32.666666666666664, "alnum_prop": 0.7040816326530612, "repo_name": "alexrudy/dotfiles", "id": "3a2cc97cb282be83b8db883770adcee46f3f1ee7", "size": "229", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "TeXLive/path.sh", "mode": "33188", "license": "mit", "language": [ { "name": "AppleScript", "bytes": "373" }, { "name": "Python", "bytes": "79202" }, { "name": "Ruby", "bytes": "25013" }, { "name": "Shell", "bytes": "93650" } ], "symlink_target": "" }
#pragma once #include <string> std::string read_file(const std::string& filename); int test_Compress_Decompress_Data(const std::string& orig_file); int test_Compress_Decompress_File(const std::string& orig_file); int test_Compress_Decompress_BlockFile(const std::string& orig_file, size_t numBytes); int test_small_datas(); int test_big_datas(); int test_small_files(); int test_big_files(); int test_small_blockFile(); int test_big_blockFile();
{ "content_hash": "d789ec65a89fce1b4563023802843332", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 86, "avg_line_length": 25.11111111111111, "alnum_prop": 0.745575221238938, "repo_name": "Kronuz/Xapiand", "id": "6d1112456451552cf6b45b06d900986ff1dc1738", "size": "1571", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "oldtests/test_compressor.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1671486" }, { "name": "C++", "bytes": "13145654" }, { "name": "CMake", "bytes": "82507" }, { "name": "Dockerfile", "bytes": "1757" }, { "name": "JavaScript", "bytes": "48668" }, { "name": "Perl", "bytes": "24123" }, { "name": "Python", "bytes": "272660" }, { "name": "Shell", "bytes": "6416" }, { "name": "Tcl", "bytes": "10851" } ], "symlink_target": "" }
<?php namespace Blog\JavanaisBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { public function indexAction(Request $request) { $form = $this->createInputForm(); $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); $textToTranslate = $data['inputtext']; } return $this->render('JavanaisBundle:Default:index.html.twig', array( 'form' => $form->createView(), 'textToTranslate' => isset($textToTranslate) ? $textToTranslate : null )); } private function createInputForm() { return $this->createFormBuilder() ->add('inputtext', 'textarea', array('required' => true)) ->getForm(); } }
{ "content_hash": "cba4017eb17c5bfbbdc43ef839017ed5", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 82, "avg_line_length": 27.625, "alnum_prop": 0.6108597285067874, "repo_name": "TheMechanic/JavanaisExtension", "id": "7e694253cb92483810ac0cf927771ec022f732f1", "size": "884", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Blog/JavanaisBundle/Controller/DefaultController.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "4323" } ], "symlink_target": "" }
// Thanks to: https://github.com/calebroseland/vue-dom-portal import objectAssign from 'object-assign' /** * Get target DOM Node * @param {(Node|string|Boolean)} [node=document.body] DOM Node, CSS selector, or Boolean * @return {Node} The target that the el will be appended to */ function getTarget (node) { if (node === void 0) { return document.body } if (typeof node === 'string' && node.indexOf('?') === 0) { return document.body } else if (typeof node === 'string' && node.indexOf('?') > 0) { node = node.split('?')[0] } if (node === 'body' || node === true) { return document.body } return node instanceof window.Node ? node : document.querySelector(node) } function getShouldUpdate (node) { // do not updated by default if (!node) { return false } if (typeof node === 'string' && node.indexOf('?') > 0) { try { const config = JSON.parse(node.split('?')[1]) return config.autoUpdate || false } catch (e) { return false } } return false } const directive = { inserted (el, { value }, vnode) { el.className = el.className ? el.className + ' v-transfer-dom' : 'v-transfer-dom' const parentNode = el.parentNode var home = document.createComment('') var hasMovedOut = false if (value !== false) { parentNode.replaceChild(home, el) // moving out, el is no longer in the document getTarget(value).appendChild(el) // moving into new place hasMovedOut = true } if (!el.__transferDomData) { el.__transferDomData = { parentNode: parentNode, home: home, target: getTarget(value), hasMovedOut: hasMovedOut } } }, componentUpdated (el, { value }) { const shouldUpdate = getShouldUpdate(value) if (!shouldUpdate) { return } // need to make sure children are done updating (vs. `update`) var ref$1 = el.__transferDomData // homes.get(el) var parentNode = ref$1.parentNode var home = ref$1.home var hasMovedOut = ref$1.hasMovedOut // recall where home is if (!hasMovedOut && value) { // remove from document and leave placeholder parentNode.replaceChild(home, el) // append to target getTarget(value).appendChild(el) el.__transferDomData = objectAssign({}, el.__transferDomData, { hasMovedOut: true, target: getTarget(value) }) } else if (hasMovedOut && value === false) { // previously moved, coming back home parentNode.replaceChild(el, home) el.__transferDomData = objectAssign({}, el.__transferDomData, { hasMovedOut: false, target: getTarget(value) }) } else if (value) { // already moved, going somewhere else getTarget(value).appendChild(el) } }, unbind: function unbind (el, binding) { el.className = el.className.replace('v-transfer-dom', '') if (el.__transferDomData && el.__transferDomData.hasMovedOut === true) { el.__transferDomData.parentNode && el.__transferDomData.parentNode.appendChild(el) } el.__transferDomData = null } } export default directive
{ "content_hash": "6edd5b809d160e8354f55ac36ae34752", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 117, "avg_line_length": 30.94, "alnum_prop": 0.6308985132514544, "repo_name": "airyland/vux", "id": "74ce6b252b4b7973118d6c93f8dc5eafd8078f76", "size": "3094", "binary": false, "copies": "1", "ref": "refs/heads/v2", "path": "src/directives/transfer-dom/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7632" }, { "name": "HTML", "bytes": "1625" }, { "name": "JavaScript", "bytes": "479808" }, { "name": "Less", "bytes": "93418" }, { "name": "Shell", "bytes": "149" }, { "name": "Vue", "bytes": "736201" } ], "symlink_target": "" }
package org.kie.workbench.common.services.backend.builder.service; import java.util.Collection; import java.util.Map; import java.util.function.Consumer; import org.guvnor.common.services.project.builder.model.BuildResults; import org.guvnor.common.services.project.builder.model.IncrementalBuildResults; import org.guvnor.common.services.project.service.DeploymentMode; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.workbench.common.services.backend.builder.ala.LocalBinaryConfig; import org.kie.workbench.common.services.backend.builder.ala.LocalBuildConfig; import org.kie.workbench.common.services.backend.builder.core.Builder; import org.kie.workbench.common.services.backend.builder.core.LRUBuilderCache; import org.kie.workbench.common.services.shared.project.KieModule; import org.kie.workbench.common.services.shared.project.KieModuleService; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.uberfire.backend.vfs.Path; import org.uberfire.workbench.events.ResourceChange; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class BuildServiceImplTest { @Mock private LRUBuilderCache cache; @Mock private KieModuleService moduleService; @Mock private BuildServiceHelper buildServiceHelper; private BuildServiceImpl buildService; @Mock private KieModule module; @Mock private Path path; @Mock private Builder builder; @Mock private BuildResults buildResults; @Mock private IncrementalBuildResults incrementalBuildResults; @Mock private Map<Path, Collection<ResourceChange>> resourceChanges; @Mock private LocalBinaryConfig localBinaryConfig; @Before public void setUp() { buildService = new BuildServiceImpl(moduleService, buildServiceHelper, cache); } @Test public void testBuild() { when(buildServiceHelper.localBuild(module)).thenReturn(buildResults); BuildResults result = buildService.build(module); assertEquals(buildResults, result); } @Test public void testBuildWithConsumer() { // emulate the buildServiceHelper response when(localBinaryConfig.getBuilder()).thenReturn(builder); doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation) { Consumer consumer = (Consumer) invocation.getArguments()[1]; consumer.accept(localBinaryConfig); return null; } }).when(buildServiceHelper).localBuild(eq(module), any(Consumer.class)); buildService.build(module, new Consumer<Builder>() { @Override public void accept(Builder result) { // the resulting builder must the returned by the buildServiceHelper assertEquals(builder, result); } }); verify(buildServiceHelper, times(1)).localBuild(eq(module), any(Consumer.class)); } @Test public void testIsBuiltTrue() { when(cache.assertBuilder(module)).thenReturn(builder); when(builder.isBuilt()).thenReturn(true); assertTrue(buildService.isBuilt(module)); } @Test public void testIsBuiltFalse() { when(cache.assertBuilder(module)).thenReturn(builder); when(builder.isBuilt()).thenReturn(false); assertFalse(buildService.isBuilt(module)); } @Test public void testBuildAndDeploy() { prepareBuildAndDeploy(module, DeploymentMode.VALIDATED, false); BuildResults result = buildService.buildAndDeploy(module); assertEquals(buildResults, result); verifyBuildAndDeploy(module, DeploymentMode.VALIDATED, false); } @Test public void testBuildAndDeployWithDeploymentMode() { prepareBuildAndDeploy(module, DeploymentMode.VALIDATED, false); BuildResults result = buildService.buildAndDeploy(module, DeploymentMode.VALIDATED); assertEquals(buildResults, result); verifyBuildAndDeploy(module, DeploymentMode.VALIDATED, false); } @Test public void testBuildAndDeployWithSuppressHandlers() { prepareBuildAndDeploy(module, DeploymentMode.VALIDATED, false); BuildResults result = buildService.buildAndDeploy(module, false); assertEquals(buildResults, result); verifyBuildAndDeploy(module, DeploymentMode.VALIDATED, false); } @Test public void testBuildAndDeployWithDeploymentModeAndSuppressHandlers() { prepareBuildAndDeploy(module, DeploymentMode.VALIDATED, false); BuildResults result = buildService.buildAndDeploy(module, false, DeploymentMode.VALIDATED); assertEquals(buildResults, result); verifyBuildAndDeploy(module, DeploymentMode.VALIDATED, false); } private void prepareBuildAndDeploy(KieModule module, DeploymentMode deploymentMode, boolean suppressHandlers) { when(buildServiceHelper.localBuildAndDeploy(module, deploymentMode, suppressHandlers)).thenReturn(buildResults); } private void verifyBuildAndDeploy(KieModule module, DeploymentMode deploymentMode, boolean suppressHandlers) { verify(buildServiceHelper, times(1)).localBuildAndDeploy(module, deploymentMode, suppressHandlers); } @Test public void testAddPackageResource() { prepareIncrementalBuild(path, LocalBuildConfig.BuildType.INCREMENTAL_ADD_RESOURCE); IncrementalBuildResults result = buildService.addPackageResource(path); assertEquals(incrementalBuildResults, result); verifyIncrementalBuild(path, LocalBuildConfig.BuildType.INCREMENTAL_ADD_RESOURCE); } @Test public void testDeletePackageResource() { prepareIncrementalBuild(path, LocalBuildConfig.BuildType.INCREMENTAL_DELETE_RESOURCE); IncrementalBuildResults result = buildService.deletePackageResource(path); assertEquals(incrementalBuildResults, result); verifyIncrementalBuild(path, LocalBuildConfig.BuildType.INCREMENTAL_DELETE_RESOURCE); } @Test public void testUpdatePackageResource() { prepareIncrementalBuild(path, LocalBuildConfig.BuildType.INCREMENTAL_UPDATE_RESOURCE); IncrementalBuildResults result = buildService.updatePackageResource(path); assertEquals(incrementalBuildResults, result); verifyIncrementalBuild(path, LocalBuildConfig.BuildType.INCREMENTAL_UPDATE_RESOURCE); } private void prepareIncrementalBuild(Path path, LocalBuildConfig.BuildType buildType) { when(moduleService.resolveModule(path)).thenReturn(module); when(buildServiceHelper.localBuild(module, buildType, path)).thenReturn(incrementalBuildResults); } private void verifyIncrementalBuild(Path path, LocalBuildConfig.BuildType buildType) { verify(buildServiceHelper, times(1)).localBuild(module, buildType, path); } @Test public void testApplyBatchResourceChanges() { when(buildServiceHelper.localBuild(module, resourceChanges)).thenReturn(incrementalBuildResults); IncrementalBuildResults result = buildService.applyBatchResourceChanges(module, resourceChanges); assertEquals(incrementalBuildResults, result); verify(buildServiceHelper, times(1)).localBuild(module, resourceChanges); } }
{ "content_hash": "d2e8bf1daddfbe0dae5df9fcf5935004", "timestamp": "", "source": "github", "line_count": 256, "max_line_length": 103, "avg_line_length": 37.94140625, "alnum_prop": 0.5689282405024194, "repo_name": "droolsjbpm/kie-wb-common", "id": "d17f9ea75b4a55c8313bd0f5924e86ba1a56676a", "size": "10333", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "kie-wb-common-services/kie-wb-common-services-backend/src/test/java/org/kie/workbench/common/services/backend/builder/service/BuildServiceImplTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "38549" }, { "name": "FreeMarker", "bytes": "37490" }, { "name": "GAP", "bytes": "86275" }, { "name": "HTML", "bytes": "127323" }, { "name": "Java", "bytes": "19056067" } ], "symlink_target": "" }
<?php namespace App\Notifications; use App\Models\ValidatorInvite; use App\Models\User; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Notifications\Messages\MailMessage; class ReverseInviteCreated extends Notification { use Queueable; protected $user; /** * Create a new notification instance. */ public function __construct(User $user) { $this->user = $user; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * * @return array */ public function via($notifiable) { return ['mail']; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $validator = $this->user->name != "" ? $this->user->fullName : $this->user->email; return (new MailMessage()) ->subject(sprintf(trans('email.reverseInviteCreated_subject_1'), $validator)) ->line(sprintf(trans('email.reverseInviteCreated_line_2'), $validator)) ->line(trans('email.reverseInviteCreated_line_3')) ->action(trans('email.reverseInviteCreated_action_4'), route('view_profile')); } /** * Get the array representation of the notification. * * @param mixed $notifiable * * @return array */ public function toArray($notifiable) { return [ // ]; } }
{ "content_hash": "f76207cb2208806f99580ca523bfd578", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 98, "avg_line_length": 23.12857142857143, "alnum_prop": 0.5911056207535516, "repo_name": "TalentedEurope/te-site", "id": "caa34ab5f4fbf21e21fe48f02410f71b2cf268ac", "size": "1619", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/Notifications/ReverseInviteCreated.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "22425" }, { "name": "HTML", "bytes": "701193" }, { "name": "PHP", "bytes": "944579" }, { "name": "Shell", "bytes": "2786" }, { "name": "Vue", "bytes": "105577" } ], "symlink_target": "" }
package nsplugin import ( "github.com/ligato/cn-infra/config" "github.com/ligato/cn-infra/logging" "go.ligato.io/vpp-agent/v3/plugins/kvscheduler" ) // DefaultPlugin is a default instance of IfPlugin. var DefaultPlugin = *NewPlugin() // NewPlugin creates a new Plugin with the provides Options func NewPlugin(opts ...Option) *NsPlugin { p := &NsPlugin{} p.PluginName = "linux-nsplugin" p.KVScheduler = &kvscheduler.DefaultPlugin for _, o := range opts { o(p) } if p.Log == nil { p.Log = logging.ForPlugin(p.String()) } if p.Cfg == nil { p.Cfg = config.ForPlugin(p.String(), config.WithCustomizedFlag(config.FlagName(p.String()), "linux-nsplugin.conf"), ) } return p } // Option is a function that can be used in NewPlugin to customize Plugin. type Option func(*NsPlugin) // UseDeps returns Option that can inject custom dependencies. func UseDeps(f func(*Deps)) Option { return func(p *NsPlugin) { f(&p.Deps) } }
{ "content_hash": "a205c8ca6350f720da563cc6817a32bc", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 81, "avg_line_length": 22.093023255813954, "alnum_prop": 0.7021052631578948, "repo_name": "ondrej-fabry/vpp-agent", "id": "0e3d3dd9a81d6fd11e697b68ae5f0d69cce028f6", "size": "950", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins/linux/nsplugin/options.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "3647" }, { "name": "Go", "bytes": "4416615" }, { "name": "Makefile", "bytes": "15117" }, { "name": "Python", "bytes": "103503" }, { "name": "RobotFramework", "bytes": "1029018" }, { "name": "Shell", "bytes": "62901" } ], "symlink_target": "" }
<?php namespace App\Models\Vault; use Illuminate\Database\Eloquent\Model; class VaultScreenshot extends Model { // public $table = 'vault_screenshots'; public $fillable = ['item_id', 'is_primary', 'image_thumb', 'image_small', 'image_medium', 'image_large', 'image_full', 'image_size', 'order_index']; public $visible = ['id', 'item_id', 'is_primary', 'image_thumb', 'image_small', 'image_medium', 'image_large', 'image_full', 'image_size', 'order_index', 'created_at', 'vault_item']; public function vault_item() { return $this->belongsTo('App\Models\Vault\VaultItem', 'item_id'); } public function delete() { $result = parent::delete(); if ($result) { $shots = ['image_thumb', 'image_small', 'image_medium', 'image_large', 'image_full']; foreach ($shots as $s) { $location = public_path('uploads/vault/'.$this->$s); if (file_exists($location) && is_file($location)) unlink($location); } } return $result; } }
{ "content_hash": "847dd05fdd8ed97e1c8d3ca0c2f88901", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 186, "avg_line_length": 35.4, "alnum_prop": 0.5800376647834274, "repo_name": "LogicAndTrick/twhl", "id": "ddcbbd2e02ed371008867a5d1adc90d002e60b3f", "size": "1062", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/Models/Vault/VaultScreenshot.php", "mode": "33188", "license": "mit", "language": [ { "name": "Blade", "bytes": "296682" }, { "name": "C#", "bytes": "1316" }, { "name": "JavaScript", "bytes": "369949" }, { "name": "PHP", "bytes": "721458" }, { "name": "SCSS", "bytes": "51724" }, { "name": "Shell", "bytes": "649" } ], "symlink_target": "" }
package com.example.owncloud.ui.activity; import android.support.v7.app.AppCompatActivity; /** * Created by Administrator on 2016/9/19. */ public class FileActivity extends AppCompatActivity { }
{ "content_hash": "86823fc72a0a82e518ef4df89835af9f", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 53, "avg_line_length": 22.11111111111111, "alnum_prop": 0.7788944723618091, "repo_name": "ckelsel/AndroidTraining", "id": "767fea89a18d5f5df8b31aab03df5c984c46b53f", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "training/owncloud/src/main/java/com/example/owncloud/ui/activity/FileActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "3279" }, { "name": "Java", "bytes": "698211" }, { "name": "Shell", "bytes": "430" } ], "symlink_target": "" }
// Cribbed from the ever prolific Konstantin Kaefer // https://github.com/mapbox/tilelive-mapnik/blob/master/test/support/assert.js var exec = require('child_process').exec, fs = require('fs'), http = require('http'), path = require('path'), util = require('util'); var assert = module.exports = exports = require('assert'); // @param tolerance number of tolerated grid cell differences assert.utfgridEqualsFile = function(buffer, file_b, tolerance, callback) { fs.writeFileSync('/tmp/grid.json', buffer, 'binary'); // <-- to debug/update var expected_json = JSON.parse(fs.readFileSync(file_b, 'utf8')); var err = null; var Celldiff = function(x, y, ev, ov) { this.x = x; this.y = y; this.ev = ev; this.ov = ov; }; Celldiff.prototype.toString = function() { return '(' + this.x + ',' + this.y + ')["' + this.ev + '" != "' + this.ov + '"]'; }; try { var obtained_json = JSON.parse(buffer); // compare grid var obtained_grid = obtained_json.grid; var expected_grid = expected_json.grid; var nrows = obtained_grid.length if (nrows != expected_grid.length) { throw new Error( "Obtained grid rows (" + nrows + ") != expected grid rows (" + expected_grid.length + ")" ); } var celldiff = []; for (var i=0; i<nrows; ++i) { var ocols = obtained_grid[i]; var ecols = expected_grid[i]; var ncols = ocols.length; if ( ncols != ecols.length ) { throw new Error( "Obtained grid cols (" + ncols + ") != expected grid cols (" + ecols.length + ") on row " + i ); } for (var j=0; j<ncols; ++j) { var ocell = ocols[j]; var ecell = ecols[j]; if ( ocell !== ecell ) { celldiff.push(new Celldiff(i, j, ecell, ocell)); } } } if ( celldiff.length > tolerance ) { throw new Error( celldiff.length + " cell differences: " + celldiff ); } assert.deepEqual(obtained_json.keys, expected_json.keys); } catch (e) { err = e; } callback(err); }; /** * Takes an image data as an input and an image path and compare them using ImageMagick fuzz algorithm, if case the * similarity is not within the tolerance limit it will callback with an error. * * @param buffer The image data to compare from * @param {string} referenceImageRelativeFilePath The relative file to compare against * @param {number} tolerance tolerated mean color distance, as a per mil (‰) * @param {function} callback Will call to home with null in case there is no error, otherwise with the error itself * @see FUZZY in http://www.imagemagick.org/script/command-line-options.php#metric */ assert.imageEqualsFile = function(buffer, referenceImageRelativeFilePath, tolerance, callback) { if (!callback) callback = function(err) { if (err) throw err; }; var referenceImageFilePath = path.resolve(referenceImageRelativeFilePath), testImageFilePath = '/tmp/windshaft-test-image-' + (Math.random() * 1e16); // TODO: make predictable var err = fs.writeFileSync(testImageFilePath, buffer, 'binary'); if (err) throw err; var imageMagickCmd = util.format( 'compare -metric fuzz "%s" "%s" /dev/null', testImageFilePath, referenceImageFilePath ); exec(imageMagickCmd, function(err, stdout, stderr) { if (err) { fs.unlinkSync(testImageFilePath); callback(err); } else { stderr = stderr.trim(); var metrics = stderr.match(/([0-9]*) \((.*)\)/); if ( ! metrics ) { callback(new Error("No match for " + stderr)); return; } var similarity = parseFloat(metrics[2]), tolerancePerMil = (tolerance / 1000); if (similarity > tolerancePerMil) { err = new Error(util.format( 'Images %s and %s are not equal (got %d similarity, expected %d)', testImageFilePath, referenceImageFilePath, similarity, tolerancePerMil) ); err.similarity = similarity; callback(err); } else { fs.unlinkSync(testImageFilePath); callback(null); } } }); }; /** * Assert response from `server` with * the given `req` object and `res` assertions object. * * @param {Server} server * @param {Object} req * @param {Object|Function} res * @param {String} msg */ assert.response = function(server, req, res, msg){ var port = 5555; function check(){ try { server.__port = server.address().port; server.__listening = true; } catch (err) { process.nextTick(check); return; } if (server.__deferred) { server.__deferred.forEach(function(args){ assert.response.apply(assert, args); }); server.__deferred = null; } } // Check that the server is ready or defer if (!server.fd) { server.__deferred = server.__deferred || []; server.listen(server.__port = port++, '127.0.0.1', check); } else if (!server.__port) { server.__deferred = server.__deferred || []; process.nextTick(check); } // The socket was created but is not yet listening, so keep deferring if (!server.__listening) { server.__deferred.push(arguments); return; } // Callback as third or fourth arg var callback = typeof res === 'function' ? res : typeof msg === 'function' ? msg : function(){}; // Default messate to test title if (typeof msg === 'function') msg = null; msg = msg || assert.testTitle; msg += '. '; // Pending responses server.__pending = server.__pending || 0; server.__pending++; // Create client if (!server.fd) { server.listen(server.__port = port++, '127.0.0.1', issue); } else { issue(); } function issue(){ // Issue request var timer, method = req.method || 'GET', status = res.status || res.statusCode, data = req.data || req.body, requestTimeout = req.timeout || 0, encoding = req.encoding || 'utf8'; var request = http.request({ host: '127.0.0.1', port: server.__port, path: req.url, method: method, headers: req.headers }); var check = function() { if (--server.__pending === 0) { server.close(); server.__listening = false; } }; // Timeout if (requestTimeout) { timer = setTimeout(function(){ check(); delete req.timeout; assert.fail(msg + 'Request timed out after ' + requestTimeout + 'ms.'); }, requestTimeout); } if (data) request.write(data); request.on('response', function(response){ response.body = ''; response.setEncoding(encoding); response.on('data', function(chunk){ response.body += chunk; }); response.on('end', function(){ if (timer) clearTimeout(timer); check(); // Assert response body if (res.body !== undefined) { var eql = res.body instanceof RegExp ? res.body.test(response.body) : res.body === response.body; assert.ok( eql, msg + 'Invalid response body.\n' + ' Expected: ' + res.body + '\n' + ' Got: ' + response.body ); } // Assert response status if (typeof status === 'number') { assert.equal( response.statusCode, status, msg + colorize('Invalid response status code.\n' + ' Expected: [green]{' + status + '}\n' + ' Got: [red]{' + response.statusCode + '}\n' + ' Response body: ' + response.body) ); } // Assert response headers if (res.headers) { var keys = Object.keys(res.headers); for (var i = 0, len = keys.length; i < len; ++i) { var name = keys[i], actual = response.headers[name.toLowerCase()], expected = res.headers[name], eql = expected instanceof RegExp ? expected.test(actual) : expected == actual; assert.ok( eql, msg + 'Invalid response header [bold]{' + name + '}.\n' + ' Expected: [green]{' + expected + '}\n' + ' Got: [red]{' + actual + '}' ); } } // Callback callback(response); }); }); request.end(); } }; /** * Colorize the given string using ansi-escape sequences. * Disabled when --boring is set. * * @param {String} str * @return {String} */ function colorize(str) { var colors = { bold: 1, red: 31, green: 32, yellow: 33 }; return str.replace(/\[(\w+)\]\{([^]*?)\}/g, function(_, color, str) { return '\x1B[' + colors[color] + 'm' + str + '\x1B[0m'; }); }
{ "content_hash": "d7e5418fbc7c928bb025982f9718fcfc", "timestamp": "", "source": "github", "line_count": 296, "max_line_length": 116, "avg_line_length": 33.726351351351354, "alnum_prop": 0.49944906340779327, "repo_name": "UCL-ShippingGroup/Windshaft-cartodb", "id": "421b9c067bf8569758c8e2cbbd79e62ef0e0ab5d", "size": "9985", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/support/assert.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "7484" }, { "name": "HTML", "bytes": "639" }, { "name": "JavaScript", "bytes": "357184" }, { "name": "Makefile", "bytes": "760" }, { "name": "PLpgSQL", "bytes": "2389" }, { "name": "Shell", "bytes": "8873" } ], "symlink_target": "" }
function chain (funcs) { return funcs.reduce((promise, func) => promise.then(func), Promise.resolve()) } function delay (expect, ms = 0) { return new Promise((resolve, reject) => { setTimeout(() => { try { expect() return resolve() } catch (err) { return reject(err) } }, ms) }) } module.exports = {chain, delay}
{ "content_hash": "548630f040c162a24ef4483ac027e5ff", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 79, "avg_line_length": 20.61111111111111, "alnum_prop": 0.555256064690027, "repo_name": "JohanObrink/sinon-server", "id": "ea5a538acc82f207d5c35b25db7074233d5bda47", "size": "371", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/testhelper.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "33837" } ], "symlink_target": "" }
.addButton { background-color: #ecf0f1; border: 1px solid; padding-left: 150px; padding-right: 150px; } .classReminder { position: relative; background-color: #ecf0f1; border: .1px solid; height: 100px; } .descFieldsClass { position: absolute; top: 10px; left: 10px; } .doneButtonClass { position: absolute; background-color: red; top: 10px; right: 100px; } .deleteButtonClass { position: absolute; bottom: 10px; right: 10px; }
{ "content_hash": "cd69f9e752a298eae4c5961d076e36c4", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 27, "avg_line_length": 13.696969696969697, "alnum_prop": 0.6991150442477876, "repo_name": "1BasitAli/todolistExtension", "id": "37d9ee8835ce989b0ae70bbd6e34fe6ca657115e", "size": "452", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "popup/todo-css.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "452" }, { "name": "HTML", "bytes": "249" }, { "name": "JavaScript", "bytes": "4912" } ], "symlink_target": "" }
package org.unix4j.unix; import java.io.StringWriter; import org.junit.Test; import org.unix4j.Unix4j; import org.unix4j.util.MultilineString; public class TailTest { private final static String LINE1 = "This is a test blah blah blah"; private final static String LINE2 = "This is a test blah blah de blah"; private final static String LINE3 = "This is a test one two three"; private final static String LINE4 = "one"; private final static String LINE5 = "a"; private final static String LINE6 = ""; private final static String LINE7 = "two"; private final static String LINE8 = "asfd"; private final static String LINE9 = "qwerty"; private final static String LINE10 = "two"; private final static String LINE11 = ""; private final static String LINE12 = "asfd asfd asfd asfd asfd"; private final static MultilineString input; static { input = new MultilineString(); input.appendLine(LINE1) .appendLine(LINE2) .appendLine(LINE3) .appendLine(LINE4) .appendLine(LINE5) .appendLine(LINE6) .appendLine(LINE7) .appendLine(LINE8) .appendLine(LINE9) .appendLine(LINE10) .appendLine(LINE11) .appendLine(LINE12); } @Test public void testTail_1() { final MultilineString expectedOutput = new MultilineString(); expectedOutput.appendLine(LINE12); assertTail(input, 1, expectedOutput); } @Test public void testTail_2() { final MultilineString expectedOutput = new MultilineString(); expectedOutput.appendLine(LINE11) .appendLine(LINE12); assertTail(input, 2, expectedOutput); } @Test public void testTail_6() { final MultilineString expectedOutput = new MultilineString(); expectedOutput.appendLine(LINE7) .appendLine(LINE8) .appendLine(LINE9) .appendLine(LINE10) .appendLine(LINE11) .appendLine(LINE12); assertTail(input, 6, expectedOutput); } @Test public void testTail_12() { final MultilineString expectedOutput = new MultilineString(); expectedOutput.appendLine(LINE1) .appendLine(LINE2) .appendLine(LINE3) .appendLine(LINE4) .appendLine(LINE5) .appendLine(LINE6) .appendLine(LINE7) .appendLine(LINE8) .appendLine(LINE9) .appendLine(LINE10) .appendLine(LINE11) .appendLine(LINE12); assertTail(input, 12, expectedOutput); } @Test public void testTail_100() { final MultilineString expectedOutput = new MultilineString(); expectedOutput.appendLine(LINE1) .appendLine(LINE2) .appendLine(LINE3) .appendLine(LINE4) .appendLine(LINE5) .appendLine(LINE6) .appendLine(LINE7) .appendLine(LINE8) .appendLine(LINE9) .appendLine(LINE10) .appendLine(LINE11) .appendLine(LINE12); assertTail(input, 100, expectedOutput); } @Test public void testTail_default() { final MultilineString expectedOutput = new MultilineString(); expectedOutput.appendLine(LINE3) .appendLine(LINE4) .appendLine(LINE5) .appendLine(LINE6) .appendLine(LINE7) .appendLine(LINE8) .appendLine(LINE9) .appendLine(LINE10) .appendLine(LINE11) .appendLine(LINE12); final StringWriter actualOutputStringWriter = new StringWriter(); Unix4j.from(input.toInput()).tail().toWriter(actualOutputStringWriter); final MultilineString actualOutput = new MultilineString(actualOutputStringWriter.toString()); actualOutput.assertMultilineStringEquals(expectedOutput); } @Test public void testTail_0() { final MultilineString expectedOutput = new MultilineString(); assertTail(input, 0, expectedOutput); } @Test public void testTail_noInput_0() { final MultilineString expectedOutput = new MultilineString(); assertTail(MultilineString.EMPTY, 1, expectedOutput); } @Test public void testTail_noInput_1() { final MultilineString expectedOutput = new MultilineString(); assertTail(MultilineString.EMPTY, 1, expectedOutput); } @Test(expected = IllegalArgumentException.class) public void testTail_negativeLines() { final MultilineString expectedOutput = new MultilineString(); assertTail(input, -1, expectedOutput); } private void assertTail(final MultilineString input, final int lines, final MultilineString expectedOutput){ final StringWriter actualOutputStringWriter = new StringWriter(); MultilineString actualOutput; //direct Unix4j.from(input.toInput()).tail(lines).toWriter(actualOutputStringWriter); actualOutput = new MultilineString(actualOutputStringWriter.toString()); actualOutput.assertMultilineStringEquals(expectedOutput); //String... args actualOutputStringWriter.getBuffer().setLength(0); Unix4j.from(input.toInput()).tail("--count", "" + lines).toWriter(actualOutputStringWriter); actualOutput = new MultilineString(actualOutputStringWriter.toString()); actualOutput.assertMultilineStringEquals(expectedOutput); } }
{ "content_hash": "8fb2f904ebf99fb8b93b047d9a61e589", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 109, "avg_line_length": 29.691358024691358, "alnum_prop": 0.7413721413721414, "repo_name": "tools4j/unix4j", "id": "aa944f05ead3dcd876fa2bbfcaf3b74738ce6424", "size": "4810", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "unix4j-core/unix4j-command/src/test/java/org/unix4j/unix/TailTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "13195" }, { "name": "Java", "bytes": "827197" }, { "name": "Roff", "bytes": "6666" }, { "name": "Shell", "bytes": "1967" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <title>Best books of 2015 : NPR</title> <meta name="twitter:card" content="summary"> <meta name="twitter:site" content="nprbooks"> <meta name="twitter:image" content="http://apps.npr.org/best-books-2015/assets/cover/one-northside.jpg" /> <meta property="og:title" content="NPR's Best Books of 2015 - One Northside" /> <meta property="og:url" content="http://127.0.0.1:8000/share/one-northside.html" /> <meta property="og:type" content="article" /> <meta property="og:description" content="A National People&#39;s Action affiliate on the northside of Chicago and has executed significant turnout programs in that turf." /> <meta property="og:image" content="http://apps.npr.org/best-books-2015/assets/cover/one-northside.jpg" /> <meta property="og:site_name" content="NPR.org" /> <meta property="fb:app_id" content="1.38837436155e+14" /> <meta name="thumbnail" content="http://apps.npr.org/best-books-2015/assets/cover/one-northside.jpg" /> </head> <body> </body> </html>
{ "content_hash": "2ca7bc76a4d5f199c9bfeebb911fbefa", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 177, "avg_line_length": 36.2, "alnum_prop": 0.6758747697974218, "repo_name": "mroswell/m2016", "id": "622286d0685e46b9adcd930570ce817fa2041c0c", "size": "1086", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "www/share/one-northside.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "361483" }, { "name": "HTML", "bytes": "318253" }, { "name": "JavaScript", "bytes": "674055" }, { "name": "Nginx", "bytes": "136" }, { "name": "Python", "bytes": "86717" }, { "name": "Shell", "bytes": "83" } ], "symlink_target": "" }
package gr.iti.mklab.reveal.fontseparation; import gr.iti.mklab.visual.aggregation.VladAggregatorMultipleVocabularies; import gr.iti.mklab.visual.dimreduction.PCA; import gr.iti.mklab.visual.extraction.AbstractFeatureExtractor; import gr.iti.mklab.visual.extraction.ImageScaling; import gr.iti.mklab.visual.utilities.ImageIOGreyScale; import gr.iti.mklab.visual.vectorization.ImageVectorizationResult; import weka.classifiers.meta.CostSensitiveClassifier; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.concurrent.Callable; /** * This class is a variation of the ImageVectorization class which attempts to * first filter out the font descriptors before aggregating them into one vector. * An already trained CostSensitiveClassifier from the weka framework is employed * for this task. * * @author kandreadou * @since August, 2014 */ public class FontVectorization implements Callable<ImageVectorizationResult> { /** * Image will be scaled at this maximum number of pixels before vectorization. */ protected int maxImageSizeInPixels = 1024 * 768; /** * The filename of the image. */ protected String imageFilename; /** * The directory (full path) where the image resides. */ protected String imageFolder; /** * The image as a BufferedImage object. */ protected BufferedImage image; /** * The target length of the extracted vector. */ protected int vectorLength; /** * This object is used for descriptor extraction. */ protected static AbstractFeatureExtractor featureExtractor; /** * This object is used for extracting VLAD vectors with multiple vocabulary aggregation. */ protected static VladAggregatorMultipleVocabularies vladAggregator; /** * This object is used for PCA projection and whitening. */ protected static PCA pcaProjector; /** * This object is used for the classification of content and font descriptors */ protected static CostSensitiveClassifier fontClassifier; /** * This object is used for the classification of font descriptors based on * the context, the existence or not of other font descriptors nearby */ protected static CostSensitiveClassifier contextClassifier; /** * If set to true, debug output is displayed. */ private boolean debug = false; public void setDebug(boolean debug) { this.debug = debug; } public FontVectorization(String imageFolder, String imageFilename, int vectorLength, int maxImageSizeInPixels) { this.imageFolder = imageFolder; this.imageFilename = imageFilename; this.vectorLength = vectorLength; this.maxImageSizeInPixels = maxImageSizeInPixels; } /** * Returns an ImageVectorizationResult object from where the image's vector and name can be * obtained. */ @Override public ImageVectorizationResult call() { if (debug) System.out.println("Vectorization for image " + imageFilename + " started."); double[] imageVector = null; String exceptionMessage = null; try { imageVector = transformToVector(); } catch (Exception e) { exceptionMessage = e.getMessage(); if (debug) System.out.println("Vectorization failed for image " + imageFilename + " with exception " + exceptionMessage); } if (debug) System.out.println("Vectorization for image " + imageFilename + " completed."); return new ImageVectorizationResult(imageFilename, imageVector, exceptionMessage); } public double[] transformToVector() throws Exception { if (vectorLength > vladAggregator.getVectorLength() || vectorLength <= 0) { throw new Exception("Vector length should be between 1 and " + vladAggregator.getVectorLength()); } // the local features are extracted double[][] features; if (image == null) { // first the image is read if the image field is null try { // first try reading with the default class image = ImageIO.read(new File(imageFolder + imageFilename)); } catch (IllegalArgumentException e) { // this exception is probably thrown because of a greyscale jpeg image System.out.println("Exception: " + e.getMessage() + " | Image: " + imageFilename); // retry with the modified class image = ImageIOGreyScale.read(new File(imageFolder + imageFilename)); } } // next the image is scaled ImageScaling scale = new ImageScaling(maxImageSizeInPixels); try { image = scale.maxPixelsScaling(image); } catch (Exception e) { throw new Exception("Exception thrown when scaling the image!\n" + e.getMessage()); } // next the local features are extracted features = featureExtractor.extractFeatures(image); // then the local features are filtered by the SVM classifier double[][] filteredFeatures = filterDescriptors(features); // next the features are aggregated double[] vladVector = vladAggregator.aggregate(filteredFeatures); if (vladVector.length == vectorLength) { // no projection is needed return vladVector; } else { // pca projection is applied double[] projected = pcaProjector.sampleToEigenSpace(vladVector); return projected; } } private double[][] filterDescriptors(double[][] features) throws Exception{ ArrayList<Attribute> attributes = new ArrayList<Attribute>(); for (int i = 0; i < 64; i++) { attributes.add(new Attribute("surf" + i)); } ArrayList fvClassVal = new ArrayList<String>(2); fvClassVal.add("OUT"); fvClassVal.add("IN"); Attribute classAttribute = new Attribute("class", fvClassVal); attributes.add(classAttribute); // predict instance class values Instances data = new Instances("Test dataset", attributes, features.length); data.setClassIndex(64); for (int i = 0, len = features.length; i < len; i++) { double[] descriptor = features[i]; // add data to instance data.add(new DenseInstance(1.0, descriptor)); } ArrayList<double[]> filtered = new ArrayList<double[]>(features.length); for (int i = 0, len = data.numInstances(); i < len; i++) { // perform prediction Instance inst = data.instance(i); double[] distribution = fontClassifier.distributionForInstance(inst); if (distribution[0] > 0.7 && distribution[1] < 0.3) { //int x = (int) points[i].x; //int y = (int) points[i].y; //paintCircleOnPoint(image, x, y); continue; } else { filtered.add(features[i]); } //double myValue = svm.classifyInstance(inst); // get the name of class value //String label = data.classAttribute().value((int)myValue); //if("IN".equals(label)){ // filtered.add(features[i]); //} //int realvalue = (int) inst.classValue(); //System.out.println("Prediction for instance " + i + " value: " + myValue + " prediction " + label); } filtered.trimToSize(); return filtered.toArray(new double[filtered.size()][64]); } /** * Sets the FeatureExtractor object that will be used. * * @param extractor */ public static void setFeatureExtractor(AbstractFeatureExtractor extractor) { FontVectorization.featureExtractor = extractor; } /** * Sets the VladAggregatorMultipleVocabularies object that will be used. * * @param vladAggregator */ public static void setVladAggregator(VladAggregatorMultipleVocabularies vladAggregator) { FontVectorization.vladAggregator = vladAggregator; } /** * Sets the PCA projection object that will be used. * * @param pcaProjector */ public static void setPcaProjector(PCA pcaProjector) { FontVectorization.pcaProjector = pcaProjector; } /** * Sets the SVM classifier object that will be used. * * @param svm */ public static void setFontClassifier(CostSensitiveClassifier svm){FontVectorization.fontClassifier = svm; } /** * Sets the context classifier object that will be used. * * @param svm */ public static void setContextClassifier(CostSensitiveClassifier svm){FontVectorization.contextClassifier = svm; } }
{ "content_hash": "8d32d5f7793fa8840be5a7d0b05614d1", "timestamp": "", "source": "github", "line_count": 252, "max_line_length": 126, "avg_line_length": 35.84126984126984, "alnum_prop": 0.6432683790965457, "repo_name": "kandreadou/reveal-multimedia-indexing", "id": "03fd6d5eb108b99889c7b652a1bfcd5f289d1aa0", "size": "9032", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/gr/iti/mklab/reveal/fontseparation/FontVectorization.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "478332" } ], "symlink_target": "" }
require 'spec_helper' describe "Mea::WaterTypes" do describe "GET /mea_water_types" do it "works! (now write some real specs)" do # Run the generator again with the --webrat flag if you want to use webrat methods/matchers get mea_water_types_path response.status.should be(200) end end end
{ "content_hash": "483c9b2e8b4c342ba4391157f38ce307", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 97, "avg_line_length": 29.181818181818183, "alnum_prop": 0.6915887850467289, "repo_name": "LACIS-TI/ERA-RAILS", "id": "0802ec2f191a7d91d0efd37ded05ec8611d4aed7", "size": "321", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/requests/mea/mea_water_types_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "48096" }, { "name": "CSS", "bytes": "7711009" }, { "name": "CoffeeScript", "bytes": "5486" }, { "name": "HTML", "bytes": "172537" }, { "name": "JavaScript", "bytes": "5945884" }, { "name": "Ruby", "bytes": "429087" } ], "symlink_target": "" }
/** * Screen Template By => create-module script * @version 1.0.0 * */ // @flow import React, { PureComponent } from 'react'; import { reduxForm } from 'redux-form/immutable'; import t from 'helpers/i18n/Translate'; import fields, { LOGIN_FORM_KEY } from 'constants/forms/login'; import Logo from 'assets/images/logo.png'; import logger from 'helpers/logger'; import { REGISTER } from 'constants/routes/routeNames'; import { submitLoginForm } from './loginActions'; import validate from './loginValidations'; import type { LoginProps } from './LoginTypes'; class Login extends PureComponent<LoginProps> { render() { const { Text, Screen, TextField, Button, Div, Col, Image, Form, handleSubmit, } = this.props; logger.log('render: Login'); return ( <Screen center> <Form onSubmit={handleSubmit}> <Col> <Div style={{ justifyContent: 'center', alignItems: 'center' }}> <Image source={Logo} style={{ width: 100, height: 100 }} alt="mylibrary logo" /> </Div> <Div> <TextField required name={fields.EMAIL} label={t.get('LOGIN_EMAIL_PLACEHOLDER')} keyboardType="email-address" /> </Div> <Div> <TextField required name={fields.PASSWORD} label={t.get('LOGIN_PASSWORD_PLACEHOLDER')} type="password" /> </Div> <Div> <Button primary raised text={t.get('LOGIN_BUTTON')} type="submit" onClick={handleSubmit(submitLoginForm)} /> </Div> <Div> <Text>{t.get('LOGIN_MESSAGE')}</Text> </Div> <Div> <Button primary to={REGISTER} text={t.get('LOGIN_GOTO_REGISTER')} transparent /> </Div> </Col> </Form> </Screen> ); } } export default reduxForm({ form: LOGIN_FORM_KEY, onSubmit: submitLoginForm, validate, })(Login);
{ "content_hash": "320bdde0cbde2056cf1d25d6e3e15cf7", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 76, "avg_line_length": 25.57608695652174, "alnum_prop": 0.48066298342541436, "repo_name": "arikanmstf/mylibrary", "id": "509be57c83b6fc38812cfd9f8adca9b02e4da348", "size": "2353", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/screens/login/Login.js", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "101" }, { "name": "HTML", "bytes": "568" }, { "name": "Java", "bytes": "1497" }, { "name": "JavaScript", "bytes": "404206" }, { "name": "Objective-C", "bytes": "4035" }, { "name": "Starlark", "bytes": "1728" } ], "symlink_target": "" }
static void prepareDatabaseManager() { static dispatch_once_t once; dispatch_once(&once, ^{ [ActiveRecord applyConfiguration:^(ARConfiguration *config) { config.databasePath = ARCachesDatabasePath(nil); }]; }); }
{ "content_hash": "5248e6373b5b0f0153b2f2ab9008f1c2", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 69, "avg_line_length": 31.625, "alnum_prop": 0.6442687747035574, "repo_name": "3dcl/iActiveRecord", "id": "21ac2a2de4cdcdfb1552c364fcb79b66d1dcb908", "size": "528", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "UnitTests/Specs/Support/SpecHelper.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "350387" }, { "name": "C++", "bytes": "13418" }, { "name": "Objective-C", "bytes": "178340" }, { "name": "Objective-C++", "bytes": "149624" }, { "name": "Ruby", "bytes": "6304" }, { "name": "Swift", "bytes": "465" } ], "symlink_target": "" }
'use strict' import React from 'react' import PropTypes from 'prop-types' const MoveButton = ({dir, holdThumb, stopMove, moveThumb,cX, cY}) => { let x let y let fa let disabled = false switch (dir) { case 'up': x = 0 y = -1 fa = 'fas fa-fw fa-arrow-up' disabled = cY == 0 break case 'down': x = 0 y = 1 fa = 'fas fa-fw fa-arrow-down' disabled = cY == 100 break case 'left': x = -1 y = 0 fa = 'fas fa-fw fa-arrow-left' disabled = cX == 0 break case 'right': x = 1 y = 0 fa = 'fas fa-fw fa-arrow-right' disabled = cX == 100 break } return ( <button disabled={disabled} onClick={moveThumb.bind(null, x, y, 2)} onMouseDown={holdThumb.bind(null, x, y, 5)} onMouseUp={stopMove} onMouseLeave={stopMove} className="btn btn-sm btn-secondary"> <i className={fa}></i> </button> ) } MoveButton.propTypes = { dir: PropTypes.string, holdThumb: PropTypes.func, stopMove: PropTypes.func, moveThumb: PropTypes.func, cX: PropTypes.oneOfType([PropTypes.number,PropTypes.string,]), cY: PropTypes.oneOfType([PropTypes.number,PropTypes.string,]) } MoveButton.defaultTypes = {} export default MoveButton
{ "content_hash": "a686151386ffc13ab6f5a880a391e985", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 70, "avg_line_length": 21.311475409836067, "alnum_prop": 0.5807692307692308, "repo_name": "AppStateESS/stories", "id": "e8035cf05a6408e9b631f4734e9de5379792d31d", "size": "1300", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javascript/Feature/MoveButton.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4709" }, { "name": "HTML", "bytes": "10025" }, { "name": "JavaScript", "bytes": "148232" }, { "name": "PHP", "bytes": "316690" }, { "name": "SCSS", "bytes": "6970" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
.class public final Lcom/android/bluetooth/hfpclient/HeadsetClientHalConstants; .super Ljava/lang/Object; .source "HeadsetClientHalConstants.java" # static fields .field static final AUDIO_STATE_CONNECTED:I = 0x2 .field static final AUDIO_STATE_CONNECTED_MSBC:I = 0x3 .field static final AUDIO_STATE_CONNECTING:I = 0x1 .field static final AUDIO_STATE_DISCONNECTED:I = 0x0 .field static final CALLHELD_HOLD:I = 0x2 .field static final CALLHELD_HOLD_AND_ACTIVE:I = 0x1 .field static final CALLHELD_NONE:I = 0x0 .field static final CALLSETUP_ALERTING:I = 0x3 .field static final CALLSETUP_INCOMING:I = 0x1 .field static final CALLSETUP_NONE:I = 0x0 .field static final CALLSETUP_OUTGOING:I = 0x2 .field static final CALL_ACTION_ATA:I = 0x7 .field static final CALL_ACTION_BTRH_0:I = 0x9 .field static final CALL_ACTION_BTRH_1:I = 0xa .field static final CALL_ACTION_BTRH_2:I = 0xb .field static final CALL_ACTION_CHLD_0:I = 0x0 .field static final CALL_ACTION_CHLD_1:I = 0x1 .field static final CALL_ACTION_CHLD_1x:I = 0x5 .field static final CALL_ACTION_CHLD_2:I = 0x2 .field static final CALL_ACTION_CHLD_2x:I = 0x6 .field static final CALL_ACTION_CHLD_3:I = 0x3 .field static final CALL_ACTION_CHLD_4:I = 0x4 .field static final CALL_ACTION_CHUP:I = 0x8 .field static final CALL_CALLS_IN_PROGRESS:I = 0x1 .field static final CALL_DIRECTION_INCOMING:I = 0x1 .field static final CALL_DIRECTION_OUTGOING:I = 0x0 .field static final CALL_MPTY_TYPE_MULTI:I = 0x1 .field static final CALL_MPTY_TYPE_SINGLE:I = 0x0 .field static final CALL_NO_CALLS_IN_PROGRESS:I = 0x0 .field static final CALL_STATE_ACTIVE:I = 0x0 .field static final CALL_STATE_ALERTING:I = 0x3 .field static final CALL_STATE_DIALING:I = 0x2 .field static final CALL_STATE_HELD:I = 0x1 .field static final CALL_STATE_HELD_BY_RESP_HOLD:I = 0x6 .field static final CALL_STATE_INCOMING:I = 0x4 .field static final CALL_STATE_WAITING:I = 0x5 .field static final CHLD_FEAT_HOLD_ACC:I = 0x8 .field static final CHLD_FEAT_MERGE:I = 0x20 .field static final CHLD_FEAT_MERGE_DETACH:I = 0x40 .field static final CHLD_FEAT_PRIV_X:I = 0x10 .field static final CHLD_FEAT_REL:I = 0x1 .field static final CHLD_FEAT_REL_ACC:I = 0x2 .field static final CHLD_FEAT_REL_X:I = 0x4 .field static final CMD_COMPLETE_ERROR:I = 0x1 .field static final CMD_COMPLETE_ERROR_BLACKLISTED:I = 0x6 .field static final CMD_COMPLETE_ERROR_BUSY:I = 0x3 .field static final CMD_COMPLETE_ERROR_CME:I = 0x7 .field static final CMD_COMPLETE_ERROR_DELAYED:I = 0x5 .field static final CMD_COMPLETE_ERROR_NO_ANSWER:I = 0x4 .field static final CMD_COMPLETE_ERROR_NO_CARRIER:I = 0x2 .field static final CMD_COMPLETE_OK:I = 0x0 .field static final CONNECTION_STATE_CONNECTED:I = 0x2 .field static final CONNECTION_STATE_CONNECTING:I = 0x1 .field static final CONNECTION_STATE_DISCONNECTED:I = 0x0 .field static final CONNECTION_STATE_DISCONNECTING:I = 0x4 .field static final CONNECTION_STATE_SLC_CONNECTED:I = 0x3 .field static final HANDSFREECLIENT_AT_CMD_NREC:I = 0xf .field static final HANDSFREECLIENT_NREC_SUPPORTED:Z = true .field static final IN_BAND_RING_NOT_PROVIDED:I = 0x0 .field static final IN_BAND_RING_PROVIDED:I = 0x1 .field static final NETWORK_STATE_AVAILABLE:I = 0x1 .field static final NETWORK_STATE_NOT_AVAILABLE:I = 0x0 .field static final PEER_FEAT_3WAY:I = 0x1 .field static final PEER_FEAT_CODEC:I = 0x200 .field static final PEER_FEAT_ECC:I = 0x80 .field static final PEER_FEAT_ECNR:I = 0x2 .field static final PEER_FEAT_ECS:I = 0x40 .field static final PEER_FEAT_EXTERR:I = 0x100 .field static final PEER_FEAT_INBAND:I = 0x8 .field static final PEER_FEAT_REJECT:I = 0x20 .field static final PEER_FEAT_VREC:I = 0x4 .field static final PEER_FEAT_VTAG:I = 0x10 .field static final RESP_AND_HOLD_ACCEPT:I = 0x1 .field static final RESP_AND_HOLD_HELD:I = 0x0 .field static final RESP_AND_HOLD_REJECT:I = 0x2 .field static final SERVICE_TYPE_HOME:I = 0x0 .field static final SERVICE_TYPE_ROAMING:I = 0x1 .field static final SUBSCRIBER_SERVICE_TYPE_FAX:I = 0x2 .field static final SUBSCRIBER_SERVICE_TYPE_UNKNOWN:I = 0x0 .field static final SUBSCRIBER_SERVICE_TYPE_VOICE:I = 0x1 .field static final VOLUME_TYPE_MIC:I = 0x1 .field static final VOLUME_TYPE_SPK:I = 0x0 .field static final VR_STATE_STARTED:I = 0x1 .field static final VR_STATE_STOPPED:I # direct methods .method public constructor <init>()V .locals 0 .prologue .line 24 invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method
{ "content_hash": "d963375ae9c569d26eebad032ca6fd44", "timestamp": "", "source": "github", "line_count": 185, "max_line_length": 79, "avg_line_length": 24.616216216216216, "alnum_prop": 0.7503293807641633, "repo_name": "hexiaoshuai/Flyme_device_ZTE_A1", "id": "ed01ac343899ff82a1b063cc75f79e04640f941b", "size": "4554", "binary": false, "copies": "1", "ref": "refs/heads/C880AV1.0.0B06", "path": "Bluetooth_modify/smali/com/android/bluetooth/hfpclient/HeadsetClientHalConstants.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "1500" }, { "name": "HTML", "bytes": "10195" }, { "name": "Makefile", "bytes": "11258" }, { "name": "Python", "bytes": "924" }, { "name": "Shell", "bytes": "2734" }, { "name": "Smali", "bytes": "234274633" } ], "symlink_target": "" }
<!--[if lt IE 11]> <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]-->
{ "content_hash": "51a8b662f2ccc9b8d526c96b112271f6", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 177, "avg_line_length": 70, "alnum_prop": 0.6904761904761905, "repo_name": "marcofugaro/gulp-frontend-boilerplate", "id": "8d7fef8dc542de4d4e63262df8cc10f30da7e998", "size": "210", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "boilerplate/src/partials/_browserupgrade.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8135" }, { "name": "HTML", "bytes": "947" }, { "name": "JavaScript", "bytes": "10349" } ], "symlink_target": "" }
<!-- Please make sure to read the Pull Request Guidelines: https://github.com/Armour/atom-typescript-react-redux-snippets/blob/master/.github/CONTRIBUTING.md#submitting-a-pull-request --> <!-- PULL REQUEST TEMPLATE --> **Make sure the PR fulfills these requirements:** - When resolving a specific issue, make sure it's referenced in the PR's title (e.g. `Closes #xxx[,#xxx]`, where "xxx" is the issue number) - If adding a **new feature**, the PR's description includes: A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it) - If this PR introduce a **breaking change**, please describe the impact and migration path for existing applications **What kind of change does this PR introduce?** <!-- E.g. bugfix, feature, code style update, refactor, build-related changes, or others... (please describe) --> **More information:**
{ "content_hash": "6af22829ee8c60101bc15f0f4810de2d", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 221, "avg_line_length": 34.464285714285715, "alnum_prop": 0.7243523316062176, "repo_name": "Armour/atom-typescript-react-redux-snippets", "id": "3cf0f6442caaaf6c7abf7d5cc8ea92b2ff47fa1f", "size": "965", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".github/PULL_REQUEST_TEMPLATE.md", "mode": "33188", "license": "mit", "language": [ { "name": "TypeScript", "bytes": "2264" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.regression.linear_model.RegressionResults.scale &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="../_static/material.css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" /> <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.regression.linear_model.RegressionResults.summary" href="statsmodels.regression.linear_model.RegressionResults.summary.html" /> <link rel="prev" title="statsmodels.regression.linear_model.RegressionResults.save" href="statsmodels.regression.linear_model.RegressionResults.save.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.regression.linear_model.RegressionResults.scale" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.13.1</span> <span class="md-header-nav__topic"> statsmodels.regression.linear_model.RegressionResults.scale </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="get" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../../versions-v2.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../regression.html" class="md-tabs__link">Linear Regression</a></li> <li class="md-tabs__item"><a href="statsmodels.regression.linear_model.RegressionResults.html" class="md-tabs__link">statsmodels.regression.linear_model.RegressionResults</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.13.1</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../regression.html" class="md-nav__link">Linear Regression</a> </li> <li class="md-nav__item"> <a href="../glm.html" class="md-nav__link">Generalized Linear Models</a> </li> <li class="md-nav__item"> <a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a> </li> <li class="md-nav__item"> <a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a> </li> <li class="md-nav__item"> <a href="../rlm.html" class="md-nav__link">Robust Linear Models</a> </li> <li class="md-nav__item"> <a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a> </li> <li class="md-nav__item"> <a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../anova.html" class="md-nav__link">ANOVA</a> </li> <li class="md-nav__item"> <a href="../other_models.html" class="md-nav__link">Other Models <code class="xref py py-mod docutils literal notranslate"><span class="pre">othermod</span></code></a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.regression.linear_model.RegressionResults.scale.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <section id="statsmodels-regression-linear-model-regressionresults-scale"> <h1 id="generated-statsmodels-regression-linear-model-regressionresults-scale--page-root">statsmodels.regression.linear_model.RegressionResults.scale<a class="headerlink" href="#generated-statsmodels-regression-linear-model-regressionresults-scale--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py method"> <dt class="sig sig-object py" id="statsmodels.regression.linear_model.RegressionResults.scale"> <span class="sig-prename descclassname"><span class="pre">RegressionResults.</span></span><span class="sig-name descname"><span class="pre">scale</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/regression/linear_model.html#RegressionResults.scale"><span class="viewcode-link"><span class="pre">[source]</span></span></a><a class="headerlink" href="#statsmodels.regression.linear_model.RegressionResults.scale" title="Permalink to this definition">¶</a></dt> <dd><p>A scale factor for the covariance matrix.</p> <p>The Default value is ssr/(n-p). Note that the square root of <cite>scale</cite> is often called the standard error of the regression.</p> </dd></dl> </section> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.regression.linear_model.RegressionResults.save.html" title="statsmodels.regression.linear_model.RegressionResults.save" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.regression.linear_model.RegressionResults.save </span> </div> </a> <a href="statsmodels.regression.linear_model.RegressionResults.summary.html" title="statsmodels.regression.linear_model.RegressionResults.summary" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.regression.linear_model.RegressionResults.summary </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Nov 12, 2021. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 4.3.0. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
{ "content_hash": "c3d7a3487df70702f0e6f0e18fcd268a", "timestamp": "", "source": "github", "line_count": 499, "max_line_length": 999, "avg_line_length": 37.87174348697395, "alnum_prop": 0.6004868240025399, "repo_name": "statsmodels/statsmodels.github.io", "id": "00dc16813fff38fa163f8feb0e9476fc7a801e33", "size": "18902", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v0.13.1/generated/statsmodels.regression.linear_model.RegressionResults.scale.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
title: abe28 type: products image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png heading: e28 description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj main: heading: Foo Bar BAz description: |- ***This is i a thing***kjh hjk kj # Blah Blah ## Blah![undefined](undefined) ### Baah image1: alt: kkkk ---
{ "content_hash": "2fd5f94c18be6c8150b047421737d1c4", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 61, "avg_line_length": 22.333333333333332, "alnum_prop": 0.6656716417910448, "repo_name": "pblack/kaldi-hugo-cms-template", "id": "334cf590599b5ae891f42d576477f4064b425613", "size": "339", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "site/content/pages2/abe28.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "94394" }, { "name": "HTML", "bytes": "18889" }, { "name": "JavaScript", "bytes": "10014" } ], "symlink_target": "" }
/* $Id: tif_aux.c,v 1.2 2012/02/25 17:48:19 drolon Exp $ */ /* * Copyright (c) 1991-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Auxiliary Support Routines. */ #include "tiffiop.h" #include "tif_predict.h" #include <math.h> uint32 _TIFFMultiply32(TIFF* tif, uint32 first, uint32 second, const char* where) { uint32 bytes = first * second; if (second && bytes / second != first) { TIFFErrorExt(tif->tif_clientdata, where, "Integer overflow in %s", where); bytes = 0; } return bytes; } uint64 _TIFFMultiply64(TIFF* tif, uint64 first, uint64 second, const char* where) { uint64 bytes = first * second; if (second && bytes / second != first) { TIFFErrorExt(tif->tif_clientdata, where, "Integer overflow in %s", where); bytes = 0; } return bytes; } void* _TIFFCheckRealloc(TIFF* tif, void* buffer, tmsize_t nmemb, tmsize_t elem_size, const char* what) { void* cp = NULL; tmsize_t bytes = nmemb * elem_size; /* * XXX: Check for integer overflow. */ if (nmemb && elem_size && bytes / elem_size == nmemb) cp = _TIFFrealloc(buffer, bytes); if (cp == NULL) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Failed to allocate memory for %s " "(%ld elements of %ld bytes each)", what,(long) nmemb, (long) elem_size); } return cp; } void* _TIFFCheckMalloc(TIFF* tif, tmsize_t nmemb, tmsize_t elem_size, const char* what) { return _TIFFCheckRealloc(tif, NULL, nmemb, elem_size, what); } static int TIFFDefaultTransferFunction(TIFFDirectory* td) { uint16 **tf = td->td_transferfunction; tmsize_t i, n, nbytes; tf[0] = tf[1] = tf[2] = 0; if (td->td_bitspersample >= sizeof(tmsize_t) * 8 - 2) return 0; n = ((tmsize_t)1)<<td->td_bitspersample; nbytes = n * sizeof (uint16); if (!(tf[0] = (uint16 *)_TIFFmalloc(nbytes))) return 0; tf[0][0] = 0; for (i = 1; i < n; i++) { double t = (double)i/((double) n-1.); tf[0][i] = (uint16)floor(65535.*pow(t, 2.2) + .5); } if (td->td_samplesperpixel - td->td_extrasamples > 1) { if (!(tf[1] = (uint16 *)_TIFFmalloc(nbytes))) goto bad; _TIFFmemcpy(tf[1], tf[0], nbytes); if (!(tf[2] = (uint16 *)_TIFFmalloc(nbytes))) goto bad; _TIFFmemcpy(tf[2], tf[0], nbytes); } return 1; bad: if (tf[0]) _TIFFfree(tf[0]); if (tf[1]) _TIFFfree(tf[1]); if (tf[2]) _TIFFfree(tf[2]); tf[0] = tf[1] = tf[2] = 0; return 0; } static int TIFFDefaultRefBlackWhite(TIFFDirectory* td) { int i; if (!(td->td_refblackwhite = (float *)_TIFFmalloc(6*sizeof (float)))) return 0; if (td->td_photometric == PHOTOMETRIC_YCBCR) { /* * YCbCr (Class Y) images must have the ReferenceBlackWhite * tag set. Fix the broken images, which lacks that tag. */ td->td_refblackwhite[0] = 0.0F; td->td_refblackwhite[1] = td->td_refblackwhite[3] = td->td_refblackwhite[5] = 255.0F; td->td_refblackwhite[2] = td->td_refblackwhite[4] = 128.0F; } else { /* * Assume RGB (Class R) */ for (i = 0; i < 3; i++) { td->td_refblackwhite[2*i+0] = 0; td->td_refblackwhite[2*i+1] = (float)((1L<<td->td_bitspersample)-1L); } } return 1; } /* * Like TIFFGetField, but return any default * value if the tag is not present in the directory. * * NB: We use the value in the directory, rather than * explcit values so that defaults exist only one * place in the library -- in TIFFDefaultDirectory. */ int TIFFVGetFieldDefaulted(TIFF* tif, uint32 tag, va_list ap) { TIFFDirectory *td = &tif->tif_dir; if (TIFFVGetField(tif, tag, ap)) return (1); switch (tag) { case TIFFTAG_SUBFILETYPE: *va_arg(ap, uint32 *) = td->td_subfiletype; return (1); case TIFFTAG_BITSPERSAMPLE: *va_arg(ap, uint16 *) = td->td_bitspersample; return (1); case TIFFTAG_THRESHHOLDING: *va_arg(ap, uint16 *) = td->td_threshholding; return (1); case TIFFTAG_FILLORDER: *va_arg(ap, uint16 *) = td->td_fillorder; return (1); case TIFFTAG_ORIENTATION: *va_arg(ap, uint16 *) = td->td_orientation; return (1); case TIFFTAG_SAMPLESPERPIXEL: *va_arg(ap, uint16 *) = td->td_samplesperpixel; return (1); case TIFFTAG_ROWSPERSTRIP: *va_arg(ap, uint32 *) = td->td_rowsperstrip; return (1); case TIFFTAG_MINSAMPLEVALUE: *va_arg(ap, uint16 *) = td->td_minsamplevalue; return (1); case TIFFTAG_MAXSAMPLEVALUE: *va_arg(ap, uint16 *) = td->td_maxsamplevalue; return (1); case TIFFTAG_PLANARCONFIG: *va_arg(ap, uint16 *) = td->td_planarconfig; return (1); case TIFFTAG_RESOLUTIONUNIT: *va_arg(ap, uint16 *) = td->td_resolutionunit; return (1); case TIFFTAG_PREDICTOR: { TIFFPredictorState* sp = (TIFFPredictorState*) tif->tif_data; *va_arg(ap, uint16*) = (uint16) sp->predictor; return 1; } case TIFFTAG_DOTRANGE: *va_arg(ap, uint16 *) = 0; *va_arg(ap, uint16 *) = (1<<td->td_bitspersample)-1; return (1); case TIFFTAG_INKSET: *va_arg(ap, uint16 *) = INKSET_CMYK; return 1; case TIFFTAG_NUMBEROFINKS: *va_arg(ap, uint16 *) = 4; return (1); case TIFFTAG_EXTRASAMPLES: *va_arg(ap, uint16 *) = td->td_extrasamples; *va_arg(ap, uint16 **) = td->td_sampleinfo; return (1); case TIFFTAG_MATTEING: *va_arg(ap, uint16 *) = (td->td_extrasamples == 1 && td->td_sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA); return (1); case TIFFTAG_TILEDEPTH: *va_arg(ap, uint32 *) = td->td_tiledepth; return (1); case TIFFTAG_DATATYPE: *va_arg(ap, uint16 *) = td->td_sampleformat-1; return (1); case TIFFTAG_SAMPLEFORMAT: *va_arg(ap, uint16 *) = td->td_sampleformat; return(1); case TIFFTAG_IMAGEDEPTH: *va_arg(ap, uint32 *) = td->td_imagedepth; return (1); case TIFFTAG_YCBCRCOEFFICIENTS: { /* defaults are from CCIR Recommendation 601-1 */ static float ycbcrcoeffs[] = { 0.299f, 0.587f, 0.114f }; *va_arg(ap, float **) = ycbcrcoeffs; return 1; } case TIFFTAG_YCBCRSUBSAMPLING: *va_arg(ap, uint16 *) = td->td_ycbcrsubsampling[0]; *va_arg(ap, uint16 *) = td->td_ycbcrsubsampling[1]; return (1); case TIFFTAG_YCBCRPOSITIONING: *va_arg(ap, uint16 *) = td->td_ycbcrpositioning; return (1); case TIFFTAG_WHITEPOINT: { static float whitepoint[2]; /* TIFF 6.0 specification tells that it is no default value for the WhitePoint, but AdobePhotoshop TIFF Technical Note tells that it should be CIE D50. */ whitepoint[0] = D50_X0 / (D50_X0 + D50_Y0 + D50_Z0); whitepoint[1] = D50_Y0 / (D50_X0 + D50_Y0 + D50_Z0); *va_arg(ap, float **) = whitepoint; return 1; } case TIFFTAG_TRANSFERFUNCTION: if (!td->td_transferfunction[0] && !TIFFDefaultTransferFunction(td)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "No space for \"TransferFunction\" tag"); return (0); } *va_arg(ap, uint16 **) = td->td_transferfunction[0]; if (td->td_samplesperpixel - td->td_extrasamples > 1) { *va_arg(ap, uint16 **) = td->td_transferfunction[1]; *va_arg(ap, uint16 **) = td->td_transferfunction[2]; } return (1); case TIFFTAG_REFERENCEBLACKWHITE: if (!td->td_refblackwhite && !TIFFDefaultRefBlackWhite(td)) return (0); *va_arg(ap, float **) = td->td_refblackwhite; return (1); } return 0; } /* * Like TIFFGetField, but return any default * value if the tag is not present in the directory. */ int TIFFGetFieldDefaulted(TIFF* tif, uint32 tag, ...) { int ok; va_list ap; va_start(ap, tag); ok = TIFFVGetFieldDefaulted(tif, tag, ap); va_end(ap); return (ok); } struct _Int64Parts { int32 low, high; }; typedef union { struct _Int64Parts part; int64 value; } _Int64; float _TIFFUInt64ToFloat(uint64 ui64) { _Int64 i; i.value = ui64; if (i.part.high >= 0) { return (float)i.value; } else { long double df; df = (long double)i.value; df += 18446744073709551616.0; /* adding 2**64 */ return (float)df; } } double _TIFFUInt64ToDouble(uint64 ui64) { _Int64 i; i.value = ui64; if (i.part.high >= 0) { return (double)i.value; } else { long double df; df = (long double)i.value; df += 18446744073709551616.0; /* adding 2**64 */ return (double)df; } } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
{ "content_hash": "e74700e7d1f0e3b8854d3966bc5b73a0", "timestamp": "", "source": "github", "line_count": 358, "max_line_length": 93, "avg_line_length": 26.058659217877096, "alnum_prop": 0.6489441526422982, "repo_name": "devxkh/FrankE", "id": "b46b9846542ac4b38d0673b056f3174a84447b72", "size": "9329", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/ThirdParty/FreeImage/Source/LibTIFF4/tif_aux.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "8314" }, { "name": "Awk", "bytes": "43187" }, { "name": "Batchfile", "bytes": "20515" }, { "name": "C", "bytes": "41707779" }, { "name": "C#", "bytes": "2765015" }, { "name": "C++", "bytes": "35347545" }, { "name": "CMake", "bytes": "964631" }, { "name": "CSS", "bytes": "10139" }, { "name": "DIGITAL Command Language", "bytes": "10718" }, { "name": "GLSL", "bytes": "234002" }, { "name": "HLSL", "bytes": "271341" }, { "name": "HTML", "bytes": "584756" }, { "name": "Java", "bytes": "6249" }, { "name": "Lua", "bytes": "568768" }, { "name": "Makefile", "bytes": "224006" }, { "name": "Metal", "bytes": "243563" }, { "name": "Module Management System", "bytes": "2074" }, { "name": "Objective-C", "bytes": "1623509" }, { "name": "Objective-C++", "bytes": "736367" }, { "name": "Perl", "bytes": "41246" }, { "name": "Python", "bytes": "175502" }, { "name": "Roff", "bytes": "527688" }, { "name": "Shell", "bytes": "15388" } ], "symlink_target": "" }
namespace OpenApoc { class Vehicle; template <typename T> class StateObject; class Organisation : public StateObject<Organisation> { public: enum class Relation { Allied, Friendly, Neutral, Unfriendly, Hostile }; UString name; int balance; int income; Organisation(const UString &name = "", int balance = 0, int income = 0); Relation isRelatedTo(const StateRef<Organisation> &other) const; bool isPositiveTo(const StateRef<Organisation> &other) const; bool isNegativeTo(const StateRef<Organisation> &other) const; float getRelationTo(const StateRef<Organisation> &other) const; std::map<StateRef<Organisation>, float> current_relations; }; }; // namespace OpenApoc
{ "content_hash": "d6eecf3243e36e0d863983b4395698a5", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 73, "avg_line_length": 23.1, "alnum_prop": 0.7518037518037518, "repo_name": "ShadowDancer/OpenApoc", "id": "dbd2b657874ed42f610f9e10825dd59687996177", "size": "788", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "game/state/organisation.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "567" }, { "name": "C", "bytes": "16066" }, { "name": "C++", "bytes": "1465942" }, { "name": "CMake", "bytes": "24647" } ], "symlink_target": "" }
import errno import grp import os import pwd import signal import sys import time from conary.conarycfg import ConfigFile, CfgBool from conary.lib import options from rmake.lib import logger (NO_PARAM, ONE_PARAM) = (options.NO_PARAM, options.ONE_PARAM) (OPT_PARAM, MULT_PARAM) = (options.OPT_PARAM, options.MULT_PARAM) class DaemonConfig(ConfigFile): logDir = '/var/log/' lockDir = '/var/run/' verbose = (CfgBool, False) _commands = [] def _register(cmd): _commands.append(cmd) class DaemonCommand(options.AbstractCommand): docs = {'config' : ("Set config KEY to VALUE", "'KEY VALUE'"), 'config-file' : ("Read PATH config file", "PATH"), 'verbose' : ("Increase verobsity in output"), 'debug-all' : "Debug exceptions"} def addParameters(self, argDef): d = {} d["config"] = MULT_PARAM d["config-file"] = '-c', MULT_PARAM d["debug-all"] = '-d', NO_PARAM d["skip-default-config"] = NO_PARAM argDef[self.defaultGroup] = d def addConfigOptions(self, cfgMap, argDef): cfgMap['verbose'] = 'verbose', NO_PARAM, '-v' options.AbstractCommand.addConfigOptions(self, cfgMap, argDef) def processConfigOptions(self, cfg, cfgMap, argSet): for file in argSet.pop('config-file', []): cfg.read(file) options.AbstractCommand.processConfigOptions(self, cfg, cfgMap, argSet) class ConfigCommand(DaemonCommand): commands = ['config'] help = 'Display configuration for this service' def runCommand(self, daemon, cfg, argSet, args): return cfg.display() _register(ConfigCommand) class StopCommand(DaemonCommand): commands = ['stop', 'kill'] help = 'Stop the service' def runCommand(self, daemon, cfg, argSet, args): return daemon.kill() _register(StopCommand) class ReloadCommand(DaemonCommand): commands = ['reload'] help = 'Reload the service configuration' def runCommand(self, daemon, cfg, argSet, args): return daemon.sendReload() # Reload is not supported by all daemons so don't register it yet class StartCommand(DaemonCommand): commands = ['start'] help = 'Start the service' docs = {'no-daemon': "Do not run as a daemon"} def addParameters(self, argDef): DaemonCommand.addParameters(self, argDef) argDef["no-daemon"] = '-n', NO_PARAM def runCommand(self, daemon, cfg, argSet, args): return daemon.start(fork=not argSet.pop('no-daemon', False)) _register(StartCommand) class Daemon(options.MainHandler): '''This class contains basic daemon functions, useful for creating your own daemon. ''' abstractCommand = DaemonCommand name = 'daemon' commandName = 'daemon' commandList = _commands user = None groups = None capabilities = None loggerClass = logger.Logger useConaryOptions = False def __init__(self): self.logger = self.loggerClass(self.name) options.MainHandler.__init__(self) def getLockFilePath(self): return os.path.join(self.cfg.lockDir, "%s.pid" % self.name) def removeLockFile(self): lockFile = self.getLockFilePath() try: os.unlink(lockFile) except OSError, e: if e.errno == errno.ENOENT: pass else: raise def getPidFromLockFile(self, warnOnError=False): lockFile = self.getLockFilePath() try: lock = open(lockFile, "r") pid = int(lock.read()) lock.close() return pid except Exception, e: if warnOnError: self.warning("unable to open lockfile for reading: %s (%s)" % (lockFile, str(e))) return None def writePidToLockFile(self): lockFile = self.getLockFilePath() try: lock = open(lockFile, "w") lock.write("%d" % os.getpid()) lock.close() return True lockFile = self.getLockFilePath() except Exception, e: self.warning("unable to open lockfile: %s (%s)", lockFile, str(e)) return False def kill(self): if not os.getuid(): if self.user: pwent = pwd.getpwnam(self.user) os.setgroups([]) os.setgid(pwent.pw_gid) os.setuid(pwent.pw_uid) logPath = os.path.join(self.cfg.logDir, "%s.log" % self.name) self.logger.logToFile(logPath) self.logger.disableConsole() pid = self.getPidFromLockFile(warnOnError=True) if not pid: self.error("could not kill %s: no pid found." % self.name) sys.exit(1) self.info("killing %s pid %d" % (self.name, pid)) try: os.kill(pid, signal.SIGTERM) timeSlept = 0 killed = False maxTime = 10 while timeSlept < maxTime: # loop waiting for the process to die os.kill(pid, 0) time.sleep(.5) timeSlept += .5 if not killed: self.error('Failed to kill %s (pid %s) after %s seconds' % (self.name, pid, maxTime)) sys.exit(1) except OSError, e: if e.errno != errno.ESRCH: raise else: self.info("process not found; removing lock file") self.removeLockFile() else: #Do we really want to remove the PID? Shouldn't we #let the daemon process do it? self.removeLockFile() def sendReload(self): pid = self.getPidFromLockFile(warnOnError=True) if not pid: self.error("could not reload %s: no pid found." % self.name) sys.exit(1) os.kill(pid, signal.SIGHUP) def info(self, msg, *args): self.logger.info(msg, *args) def error(self, msg, *args): self.logger.error(msg, *args) def warning(self, msg, *args): self.logger.warning(msg, *args) def start(self, fork=True): if not os.getuid(): # libcap isn't available in the chroot, so delay importing # until here. from rmake.lib import pycap if self.user: pwent = pwd.getpwnam(self.user) if self.groups: groupIds = [] for group in self.groups: grpent = grp.getgrnam(group) groupIds.append(grpent.gr_gid) os.setgroups(groupIds) else: os.setgroups([]) if self.capabilities: pycap.set_keepcaps(True) os.setgid(pwent.pw_gid) os.setuid(pwent.pw_uid) if self.capabilities: pycap.cap_set_proc(self.capabilities) logPath = os.path.join(self.cfg.logDir, "%s.log" % self.name) try: self.logger.logToFile(logPath) except EnvironmentError, e: # this should handle most permission problems nicely self.logger.error('Could not open logfile: %s' % (e)) return 1 pid = self.getPidFromLockFile() if pid: try: os.kill(pid, 0) except OSError, err: if err.args[0] != errno.ESRCH: raise self.info("Old %s pid seems to be invalid. killing." % self.name) self.kill() else: self.error("Daemon already running as pid %s", pid) sys.exit(1) conaryPath = os.path.dirname(sys.modules['conary'].__file__) if '/site-packages/' not in conaryPath: self.info("using Conary in %s" % conaryPath) if fork: pid = os.fork() if pid == 0: self.logger.disableConsole() null = os.open("/dev/null", os.O_RDWR) os.dup2(null, 0) os.dup2(null, 1) os.dup2(null, 2) os.close(null) pid = os.fork() if pid == 0: # abandon the controlling tty by resetting session id os.setsid() sys.stdout.flush() sys.stderr.flush() self.daemonize() else: # always sleep one second, make sure that the # process actually starts time.sleep(1) timeSlept = 1 while timeSlept < 60: lockFilePid = self.getPidFromLockFile() if not lockFilePid or lockFilePid != pid: foundPid, status = os.waitpid(pid, os.WNOHANG) if foundPid: os._exit(1) else: time.sleep(.5) timeSlept += 1 else: os._exit(0) os._exit(1) else: time.sleep(2) pid, status = os.waitpid(pid, 0) if os.WIFEXITED(status): rc = os.WEXITSTATUS(status) return rc else: self.error('process killed with signal %s' % os.WTERMSIG(status)) return 1 else: self.daemonize() return 0 def daemonize(self): '''Call this to execute the daemon''' self.writePidToLockFile() try: try: self.doWork() except KeyboardInterrupt: self.info("interrupt caught; exiting") finally: self.removeLockFile() def doWork(self): raise NotImplementedError def runCommand(self, thisCommand, cfg, argSet, otherArgs, **kw): self.cfg = cfg return options.MainHandler.runCommand(self, thisCommand, self, cfg, argSet, otherArgs, **kw) def usage(self, rc=1, showAll=False): print '%s: back end to rMake build tool' % self.commandName if not showAll: print print 'Common Commands (use "%s help" for the full list)' % self.commandName return options.MainHandler.usage(self, rc, showAll=showAll) def mainWithExceptionHandling(self, argv): from rmake import errors try: argv = list(argv) debugAll = '--debug-all' in argv or '-d' in argv if debugAll: debuggerException = Exception if '-d' in argv: argv.remove('-d') else: argv.remove('--debug-all') else: debuggerException = errors.RmakeInternalError sys.excepthook = errors.genExcepthook(debug=debugAll, debugCtrlC=debugAll) rc = self.main(argv) except debuggerException, err: raise except errors.RmakeError, err: self.logger.error(err) return 1 except KeyboardInterrupt: return 1 return rc def daemonize(): if os.fork(): return False if os.fork(): os._exit(0) os.setsid() sink = os.open(os.devnull, os.O_RDWR) os.dup2(sink, 0) os.dup2(sink, 1) os.dup2(sink, 2) os.close(sink) return True def debugHook(signum, sigtb): port = 8080 try: import epdb debugger = epdb.Epdb() debugger._server = epdb.telnetserver.InvertedTelnetServer(('', port)) debugger._server.handle_request() debugger._port = port debugger.set_trace(skip=1) except: pass def setDebugHook(): signal.signal(signal.SIGUSR1, debugHook)
{ "content_hash": "980957438e7b53aa4a7ed4eba4c14c8f", "timestamp": "", "source": "github", "line_count": 383, "max_line_length": 102, "avg_line_length": 31.66318537859008, "alnum_prop": 0.5260987878288117, "repo_name": "sassoftware/rmake", "id": "697e00253127da35fa8b3653a5f0b86a21e2aef4", "size": "12714", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rmake/lib/daemon.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "52769" }, { "name": "Cucumber", "bytes": "3065" }, { "name": "Makefile", "bytes": "24712" }, { "name": "Nginx", "bytes": "460" }, { "name": "Python", "bytes": "1798193" }, { "name": "Shell", "bytes": "9986" } ], "symlink_target": "" }
#include "transport_manager/cloud/sample_websocket_server.h" namespace { // Report a failure void Fail(char const* tag, boost::system::error_code ec) { std::cerr << tag << ": " << ec.message() << "\n"; } } // namespace namespace sample { namespace websocket { WSSession::WSServer::WSServer(tcp::socket&& socket) : ws_(std::move(socket)) {} void WSSession::WSServer::AddURLRoute(const std::string& target) { url_routes_.insert(ParseRouteFromTarget(target)); } void WSSession::WSServer::Run() { req_ = {}; http::async_read(ws_.next_layer(), buffer_, req_, std::bind(&WSServer::OnWebsocketHandshake, shared_from_this(), std::placeholders::_1)); } void WSSession::WSServer::OnWebsocketHandshake( const boost::system::error_code& ec) { if (ec) { return Fail("ERROR_HTTP_REQUEST_READ", ec); } if (websocket::is_upgrade(req_)) { // Check target std::string route = ParseRouteFromTarget(req_.target().to_string()); if (!CanHandleRoute(route)) { auto error = boost::system::errc::make_error_code( boost::system::errc::address_not_available); ws_.next_layer().close(); return Fail("ERROR_INVALID_TARGET", error); } // Accept the websocket handshake ws_.async_accept( req_, std::bind( &WSServer::OnAccept, shared_from_this(), std::placeholders::_1)); } } void WSSession::WSServer::OnAccept(beast::error_code ec) { if (ec) { return Fail("ERROR_WEBSOCKET_HANDSHAKE", ec); } } bool WSSession::WSServer::CanHandleRoute(const std::string& route) { if (url_routes_.find(route) == url_routes_.end()) { return false; } return true; } std::string WSSession::WSServer::ParseRouteFromTarget( const std::string& target) { std::string route = target; // Remove fragment auto fragment_pos = route.find('#'); if (fragment_pos != std::string::npos) { route = route.substr(0, fragment_pos); } // Remove query auto query_pos = route.find('?'); if (query_pos != std::string::npos) { route = route.substr(0, query_pos); } return route; } WSSession::WSSession(const std::string& address, uint16_t port) : io_pool_(1) , address_(address) , port_(port) , acceptor_(ioc_) , socket_(ioc_) , ws_(nullptr) { endpoint_ = {boost::asio::ip::make_address(address), port}; boost::system::error_code error; // Open the acceptor acceptor_.open(endpoint_.protocol(), error); if (error) { Fail("ERROR_ACCEPTOR_OPEN", error); return; } // Allow address reuse acceptor_.set_option(boost::asio::socket_base::reuse_address(true), error); if (error) { Fail("ERROR_SET_OPTION", error); return; } // Bind to the server address acceptor_.bind(endpoint_, error); if (error) { Fail("ERROR_BIND", error); return; } // Start listening for connections acceptor_.listen(boost::asio::socket_base::max_listen_connections, error); if (error) { Fail("ERROR_LISTEN", error); return; } } void WSSession::Run() { if (acceptor_.is_open()) { acceptor_.async_accept( socket_, std::bind( &WSSession::on_accept, shared_from_this(), std::placeholders::_1)); boost::asio::post(io_pool_, [&]() { ioc_.run(); }); } } void WSSession::Stop() { try { ioc_.stop(); acceptor_.close(); io_pool_.join(); } catch (...) { std::cerr << "Failed to close connection" << std::endl; } } void WSSession::AddRoute(const std::string& route) { if (ws_ == nullptr) { buffered_routes_.push(route); return; } ws_->AddURLRoute(route); } void WSSession::on_accept(boost::system::error_code ec) { if (ec) { Fail("ERROR_ON_ACCEPT", ec); ioc_.stop(); return; } // Make websocket object and start ws_ = std::make_shared<WSServer>(std::move(socket_)); // Load routes stored in buffer while (!buffered_routes_.empty()) { ws_->AddURLRoute(buffered_routes_.front()); buffered_routes_.pop(); } ws_->Run(); } WSSSession::WSSServer::WSSServer(tcp::socket&& socket, ssl::context& ctx) : wss_(std::move(socket), ctx) {} void WSSSession::WSSServer::AddURLRoute(const std::string& target) { url_routes_.insert(ParseRouteFromTarget(target)); } void WSSSession::WSSServer::Run() { // Perform the SSL handshake wss_.next_layer().async_handshake(ssl::stream_base::server, std::bind(&WSSServer::OnSSLHandshake, shared_from_this(), std::placeholders::_1)); } void WSSSession::WSSServer::OnSSLHandshake(beast::error_code ec) { if (ec) { return Fail("ERROR_SSL_HANDSHAKE", ec); } req_ = {}; http::async_read(wss_.next_layer(), buffer_, req_, std::bind(&WSSServer::OnWebsocketHandshake, shared_from_this(), std::placeholders::_1)); } void WSSSession::WSSServer::OnWebsocketHandshake( const boost::system::error_code& ec) { if (ec) { return Fail("ERROR_HTTP_REQUEST_READ", ec); } if (websocket::is_upgrade(req_)) { // Check target std::string route = ParseRouteFromTarget(req_.target().to_string()); if (!CanHandleRoute(route)) { auto error = boost::system::errc::make_error_code( boost::system::errc::address_not_available); wss_.next_layer().next_layer().close(); return Fail("ERROR_INVALID_TARGET", error); } // Accept the websocket handshake wss_.async_accept( req_, std::bind( &WSSServer::OnAccept, shared_from_this(), std::placeholders::_1)); } } void WSSSession::WSSServer::OnAccept(beast::error_code ec) { if (ec) { return Fail("ERROR_ON_ACCEPT", ec); } } bool WSSSession::WSSServer::CanHandleRoute(const std::string& route) { if (url_routes_.find(route) == url_routes_.end()) { return false; } return true; } std::string WSSSession::WSSServer::ParseRouteFromTarget( const std::string& target) { std::string route = target; // Remove fragment auto fragment_pos = route.find('#'); if (fragment_pos != std::string::npos) { route = route.substr(0, fragment_pos); } // Remove query auto query_pos = route.find('?'); if (query_pos != std::string::npos) { route = route.substr(0, query_pos); } return route; } WSSSession::WSSSession(const std::string& address, uint16_t port, const std::string& certificate, const std::string& private_key) : io_pool_(1) , acceptor_(ioc_) , socket_(ioc_) , ctx_(ssl::context::sslv23_server) , wss_(nullptr) { beast::error_code ec; endpoint_ = {boost::asio::ip::make_address(address), port}; // Load the certificate ctx_.use_certificate( boost::asio::buffer(certificate.c_str(), certificate.size()), ssl::context::file_format::pem, ec); if (ec) { Fail("ERROR_USE_CERTIFICATE", ec); return; } // Load the private key ctx_.use_rsa_private_key( boost::asio::buffer(private_key.c_str(), private_key.size()), ssl::context::file_format::pem, ec); if (ec) { Fail("ERROR_USE_RSA_PRIVATE_KEY", ec); return; } // Open the acceptor acceptor_.open(endpoint_.protocol(), ec); if (ec) { Fail("EEROR_ACCEPTOR_OPEN", ec); return; } // Allow address reuse acceptor_.set_option(net::socket_base::reuse_address(true), ec); if (ec) { Fail("ERROR_SET_OPTION", ec); return; } // Bind to the server address acceptor_.bind(endpoint_, ec); if (ec) { Fail("ERROR_BIND", ec); return; } // Start listening for connections acceptor_.listen(net::socket_base::max_listen_connections, ec); if (ec) { Fail("ERROR_LISTEN", ec); return; } } // Start accepting incoming connections void WSSSession::Run() { do_accept(); } void WSSSession::Stop() { try { ioc_.stop(); acceptor_.close(); io_pool_.join(); } catch (...) { std::cerr << "Failed to close connection" << std::endl; } } void WSSSession::AddRoute(const std::string& route) { if (wss_ == nullptr) { buffered_routes_.push(route); return; } wss_->AddURLRoute(route); } void WSSSession::do_accept() { if (acceptor_.is_open()) { acceptor_.async_accept( socket_, std::bind( &WSSSession::on_accept, shared_from_this(), std::placeholders::_1)); boost::asio::post(io_pool_, [&]() { ioc_.run(); }); } } void WSSSession::on_accept(boost::system::error_code ec) { if (ec) { Fail("ERROR_ON_ACCEPT", ec); ioc_.stop(); return; } // Create the session and run it wss_ = std::make_shared<WSSServer>(std::move(socket_), ctx_); // Load routes stored in buffer while (!buffered_routes_.empty()) { wss_->AddURLRoute(buffered_routes_.front()); buffered_routes_.pop(); } wss_->Run(); } } // namespace websocket } // namespace sample
{ "content_hash": "913ca7fc12659def291c1ef4bc13111f", "timestamp": "", "source": "github", "line_count": 358, "max_line_length": 80, "avg_line_length": 25.449720670391063, "alnum_prop": 0.5933486993743826, "repo_name": "smartdevicelink/sdl_core", "id": "bd153adad449e4211b4ced536ae4f60120cc278f", "size": "10681", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/transport_manager/test/sample_websocket_server.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "27115" }, { "name": "C++", "bytes": "22338348" }, { "name": "CMake", "bytes": "435397" }, { "name": "M4", "bytes": "25347" }, { "name": "Makefile", "bytes": "139997" }, { "name": "Python", "bytes": "566738" }, { "name": "Shell", "bytes": "696186" } ], "symlink_target": "" }
package org.scalatest.verb import org.scalatest._ /** * Provides an implicit conversion that adds <code>can</code> methods to <code>String</code> * to support the syntax of <code>FlatSpec</code>, <code>WordSpec</code>, <code>FixtureFlatSpec</code>, * and <code>FixtureWordSpec</code>. * * <p> * For example, this trait enables syntax such as the following test registration in <code>FlatSpec</code> * and <code>FixtureFlatSpec</code>: * </p> * * <pre class="stHighlight"> * "A Stack (when empty)" can "be empty" in { ... } * ^ * </pre> * * <p> * It also enables syntax such as the following shared test registration in <code>FlatSpec</code> * and <code>FixtureFlatSpec</code>: * </p> * * <pre class="stHighlight"> * "A Stack (with one item)" can behave like nonEmptyStack(stackWithOneItem, lastValuePushed) * ^ * </pre> * * <p> * In addition, it supports the registration of subject descriptions in <code>WordSpec</code> * and <code>FixtureWordSpec</code>, such as: * </p> * * <pre class="stHighlight"> * "A Stack (when empty)" can { ... * ^ * </pre> * * <p> * And finally, it also supportds the registration of subject descriptions with after words * in <code>WordSpec</code> and <code>FixtureWordSpec</code>. For example: * </p> * * <pre class="stHighlight"> * def provide = afterWord("provide") * * "The ScalaTest Matchers DSL" can provide { * ^ * </pre> * * <p> * The reason this implicit conversion is provided in a separate trait, instead of being provided * directly in <code>FlatSpec</code>, <code>WordSpec</code>, <code>FixtureFlatSpec</code>, and * <code>FixtureWordSpec</code>, is primarily for design symmetry with <code>ShouldVerb</code> * and <code>MustVerb</code>. Both <code>ShouldVerb</code> and <code>MustVerb</code> must exist * as a separate trait because an implicit conversion provided directly would conflict * with the implicit conversion that provides <code>should</code> or <code>must</code> methods on <code>String</code> * in the <code>ShouldMatchers</code> and <code>MustMatchers</code> traits. * </p> * * @author Bill Venners */ trait CanVerb { // This one can be final, because it isn't extended by anything in the matchers DSL. /** * This class supports the syntax of <code>FlatSpec</code>, <code>WordSpec</code>, <code>FixtureFlatSpec</code>, * and <code>FixtureWordSpec</code>. * * <p> * This class is used in conjunction with an implicit conversion to enable <code>can</code> methods to * be invoked on <code>String</code>s. * </p> * * @author Bill Venners */ final class StringCanWrapperForVerb(left: String) { /** * Supports test registration in <code>FlatSpec</code> and <code>FixtureFlatSpec</code>. * * <p> * For example, this method enables syntax such as the following in <code>FlatSpec</code> * and <code>FixtureFlatSpec</code>: * </p> * * <pre class="stHighlight"> * "A Stack (when empty)" can "be empty" in { ... } * ^ * </pre> * * <p> * <code>FlatSpec</code> passes in a function via the implicit parameter that takes * three strings and results in a <code>ResultOfStringPassedToVerb</code>. This method * simply invokes this function, passing in left, the verb string * <code>"can"</code>, and right, and returns the result. * </p> */ def can(right: String)(implicit fun: (String, String, String) => ResultOfStringPassedToVerb): ResultOfStringPassedToVerb = { fun(left, "can", right) } /** * Supports shared test registration in <code>FlatSpec</code> and <code>FixtureFlatSpec</code>. * * <p> * For example, this method enables syntax such as the following in <code>FlatSpec</code> * and <code>FixtureFlatSpec</code>: * </p> * * <pre class="stHighlight"> * "A Stack (with one item)" can behave like nonEmptyStack(stackWithOneItem, lastValuePushed) * ^ * </pre> * * <p> * <code>FlatSpec</code> and <code>FixtureFlatSpec</code> passes in a function via the implicit parameter that takes * a string and results in a <code>BehaveWord</code>. This method * simply invokes this function, passing in left, and returns the result. * </p> */ def can(right: BehaveWord)(implicit fun: (String) => BehaveWord): BehaveWord = { fun(left) } /** * Supports the registration of subject descriptions in <code>WordSpec</code> * and <code>FixtureWordSpec</code>. * * <p> * For example, this method enables syntax such as the following in <code>WordSpec</code> * and <code>FixtureWordSpec</code>: * </p> * * <pre class="stHighlight"> * "A Stack (when empty)" can { ... * ^ * </pre> * * <p> * <code>WordSpec</code> passes in a function via the implicit parameter of type <code>StringVerbBlockRegistration</code>, * a function that takes two strings and a no-arg function and results in <code>Unit</code>. This method * simply invokes this function, passing in left, the verb string * <code>"can"</code>, and the right by-name parameter transformed into a * no-arg function. * </p> */ def can(right: => Unit)(implicit fun: StringVerbBlockRegistration) { fun(left, "can", right _) } /** * Supports the registration of subject descriptions with after words * in <code>WordSpec</code> and <code>FixtureWordSpec</code>. * * <p> * For example, this method enables syntax such as the following in <code>WordSpec</code> * and <code>FixtureWordSpec</code>: * </p> * * <pre class="stHighlight"> * def provide = afterWord("provide") * * "The ScalaTest Matchers DSL" can provide { * ^ * </pre> * * <p> * <code>WordSpec</code> passes in a function via the implicit parameter that takes * two strings and a <code>ResultOfAfterWordApplication</code> and results in <code>Unit</code>. This method * simply invokes this function, passing in left, the verb string * <code>"can"</code>, and the <code>ResultOfAfterWordApplication</code> passed to <code>can</code>. * </p> */ def can(resultOfAfterWordApplication: ResultOfAfterWordApplication)(implicit fun: (String, String, ResultOfAfterWordApplication) => Unit) { fun(left, "can", resultOfAfterWordApplication) } } /** * Implicitly converts an object of type <code>String</code> to a <code>StringCanWrapper</code>, * to enable <code>can</code> methods to be invokable on that object. */ implicit def convertToStringCanWrapper(o: String): StringCanWrapperForVerb = new StringCanWrapperForVerb(o) }
{ "content_hash": "a88ed6a959c9ba7fad0850e20a0e5994", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 143, "avg_line_length": 37.219251336898395, "alnum_prop": 0.6331896551724138, "repo_name": "JimCallahan/Graphics", "id": "04b85df20df46097d1d8d16c2a9384b1585f7694", "size": "7560", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "external/scalatest/src/main/scala/org/scalatest/verb/CanVerb.scala", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "14653" }, { "name": "JavaScript", "bytes": "55710" }, { "name": "Scala", "bytes": "5292966" } ], "symlink_target": "" }
#region License Terms // ================================================================================ // RosSharp // // Software License Agreement (BSD License) // // Copyright (C) 2012 zoetrope // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ================================================================================ #endregion namespace RosSharp { internal enum StatusCode { Error = -1, Failure = 0, Success = 1 } }
{ "content_hash": "a4a63421e9a42693b53cf8f0a61b1796", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 85, "avg_line_length": 44, "alnum_prop": 0.6535476718403548, "repo_name": "zoetrope/RosSharp", "id": "1ac99a99d36ee9ed93daab54d20ca0204ed1eb31", "size": "1806", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RosSharp/StatusCode.cs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "9917" }, { "name": "C#", "bytes": "722378" }, { "name": "F#", "bytes": "46626" }, { "name": "Makefile", "bytes": "5581" }, { "name": "Python", "bytes": "7734" } ], "symlink_target": "" }
<!doctype html> <html> <title>npm-explore</title> <meta http-equiv="content-type" value="text/html;utf-8"> <link rel="stylesheet" type="text/css" href="../../static/style.css"> <link rel="canonical" href="https://www.npmjs.org/doc/cli/npm-explore.html"> <script async=true src="../../static/toc.js"></script> <body> <div id="wrapper"> <h1><a href="../cli/npm-explore.html">npm-explore</a></h1> <p>Browse an installed package</p> <h2 id="synopsis">SYNOPSIS</h2> <pre><code>npm explore &lt;name&gt; [ -- &lt;cmd&gt;] </code></pre><h2 id="description">DESCRIPTION</h2> <p>Spawn a subshell in the directory of the installed package specified.</p> <p>If a command is specified, then it is run in the subshell, which then immediately terminates.</p> <p>This is particularly handy in the case of git submodules in the <code>node_modules</code> folder:</p> <pre><code>npm explore some-dependency -- git pull origin master </code></pre><p>Note that the package is <em>not</em> automatically rebuilt afterwards, so be sure to use <code>npm rebuild &lt;pkg&gt;</code> if you make any changes.</p> <h2 id="configuration">CONFIGURATION</h2> <h3 id="shell">shell</h3> <ul> <li>Default: SHELL environment variable, or &quot;bash&quot; on Posix, or &quot;cmd&quot; on Windows</li> <li>Type: path</li> </ul> <p>The shell to run for the <code>npm explore</code> command.</p> <h2 id="see-also">SEE ALSO</h2> <ul> <li><a href="../cli/npm-submodule.html">npm-submodule(1)</a></li> <li><a href="../files/npm-folders.html">npm-folders(5)</a></li> <li><a href="../cli/npm-edit.html">npm-edit(1)</a></li> <li><a href="../cli/npm-rebuild.html">npm-rebuild(1)</a></li> <li><a href="../cli/npm-build.html">npm-build(1)</a></li> <li><a href="../cli/npm-install.html">npm-install(1)</a></li> </ul> </div> <table border=0 cellspacing=0 cellpadding=0 id=npmlogo> <tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18>&nbsp;</td></tr> <tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td><td style="width:40px;height:10px;background:#fff" colspan=4>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4>&nbsp;</td><td style="width:40px;height:10px;background:#fff" colspan=4>&nbsp;</td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td><td colspan=6 style="width:60px;height:10px;background:#fff">&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4>&nbsp;</td></tr> <tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2>&nbsp;</td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td></tr> <tr><td style="width:10px;height:10px;background:#fff" rowspan=2>&nbsp;</td></tr> <tr><td style="width:10px;height:10px;background:#fff">&nbsp;</td></tr> <tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6>&nbsp;</td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td></tr> <tr><td colspan=5 style="width:50px;height:10px;background:#fff">&nbsp;</td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4>&nbsp;</td><td style="width:90px;height:10px;background:#fff" colspan=9>&nbsp;</td></tr> </table> <p id="footer">npm-explore &mdash; npm@1.4.20</p>
{ "content_hash": "dddd9d53ce69de22aaf576b2e70000d9", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 807, "avg_line_length": 73.11111111111111, "alnum_prop": 0.7018743667679838, "repo_name": "joshua-oxley/Target", "id": "f9bd9d5462a14cf5d6d6f7b9ebff75e95fc199b2", "size": "3948", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "node_modules/meanio/node_modules/npm/html/doc/cli/npm-explore.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "989" }, { "name": "JavaScript", "bytes": "83852" }, { "name": "Perl", "bytes": "48" } ], "symlink_target": "" }
package uk.co.yottr.repository; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import uk.co.yottr.initialise.InitialiseDatabase; import uk.co.yottr.model.Boat; import uk.co.yottr.model.User; import uk.co.yottr.service.BoatService; import uk.co.yottr.service.UserService; import uk.co.yottr.testconfig.IntegrationTestConfig; import static org.junit.Assert.assertEquals; import static uk.co.yottr.builder.BoatBuilder.aBoat; import static uk.co.yottr.builder.UserBuilder.aUser; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes=IntegrationTestConfig.class) public class BoatRepositoryTest { @Autowired private BoatRepository boatRepository; @Autowired private BoatService boatService; @Autowired private UserService userService; @Autowired private RyaSailCruisingLevelRepository ryaSailCruisingLevelRepository; @Autowired private FinancialArrangementRepository financialArrangementRepository; private User owner; @Before public void initialiseReferenceData() { InitialiseDatabase.initialise(ryaSailCruisingLevelRepository); InitialiseDatabase.initialise(financialArrangementRepository); owner = userService.save(aUser().build(), false); } @After public void clearData() { for (Boat boat : boatRepository.findAll(new PageRequest(0, 9999))) { boatRepository.delete(boat); } } @Test public void testFind() throws Exception { Boat boat = aBoat().withOwner(owner).build(); boatService.save(boat); final Page<Boat> foundBoatPages = boatRepository.find(boat.getReference(), new PageRequest(0, 10)); assertEquals(1, foundBoatPages.getTotalElements()); final Boat boatFromFind = foundBoatPages.getContent().get(0); assertEquals(boat.getReference(), boatFromFind.getReference()); } }
{ "content_hash": "f6d569703aad96560d7091e05793908d", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 107, "avg_line_length": 30.684931506849313, "alnum_prop": 0.7589285714285714, "repo_name": "mikehartley/yottr", "id": "3e27d910b8ae5441fb6d972cf4810b7c8e6189b6", "size": "2320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/uk/co/yottr/repository/BoatRepositoryTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "20426" }, { "name": "Java", "bytes": "209412" }, { "name": "JavaScript", "bytes": "1506" } ], "symlink_target": "" }
describe('tr.Xhr', function() { beforeEach(function() { jasmine.clock().install(); jasmine.Ajax.install(); tr.Xhr.setDefaultResponseType(undefined); }); afterEach(function() { jasmine.clock().uninstall(); jasmine.Ajax.uninstall(); }); it('should send a GET request if no post data is provided', function() { var task = new tr.Xhr('http://fake/url'); task.run(); expect(jasmine.Ajax.requests.mostRecent().url).toBe('http://fake/url'); }); it('should send a POST request if post data is provided', function() { var task = new tr.Xhr('http://fake/url', {}); task.run(); expect(jasmine.Ajax.requests.mostRecent().url).toBe('http://fake/url'); }); it('should default to JSON response-type if default response-type set and no override specified', function() { tr.Xhr.setDefaultResponseType(tr.enums.XhrResponseType.JSON); var task = new tr.Xhr('http://fake/url'); expect(task.getResponseType()).toBe(tr.enums.XhrResponseType.JSON); }); it('should default to text response-type if no override specified', function() { var task = new tr.Xhr('http://fake/url'); expect(task.getResponseType()).toBe(tr.enums.XhrResponseType.TEXT); }); it('should complete after a successful request that returns JSON', function() { var task = new tr.Xhr('http://fake/url', undefined, tr.enums.XhrResponseType.JSON); task.run(); expect(task.getResponseType()).toBe(tr.enums.XhrResponseType.JSON); expect(task.getState()).toBe(tr.enums.State.RUNNING); jasmine.Ajax.requests.mostRecent().respondWith({ status: 200, responseText: '{ "foo": { "bar": "baz" } }' }); expect(task.getState()).toBe(tr.enums.State.COMPLETED); expect(task.getData()).toEqual({foo: {bar: "baz"}}); }); it('should complete after a successful request that returns TEXT', function() { var task = new tr.Xhr('http://fake/url', undefined, tr.enums.XhrResponseType.TEXT); task.run(); expect(task.getResponseType()).toBe(tr.enums.XhrResponseType.TEXT); expect(task.getState()).toBe(tr.enums.State.RUNNING); jasmine.Ajax.requests.mostRecent().respondWith({ status: 200, responseText: 'fake response' }); expect(task.getState()).toBe(tr.enums.State.COMPLETED); expect(task.getData()).toBe('fake response'); }); it('should complete after a successful request that returns XML', function() { var task = new tr.Xhr('http://fake/url', undefined, tr.enums.XhrResponseType.XML); task.run(); expect(task.getResponseType()).toBe(tr.enums.XhrResponseType.XML); expect(task.getState()).toBe(tr.enums.State.RUNNING); var foo = document.createElement("foo"); var bar = document.createElement("bar"); var baz = document.createTextNode("baz"); var xml = document.createElement("xml"); xml.appendChild(foo); foo.appendChild(bar); bar.appendChild(baz); var xmlString = new XMLSerializer().serializeToString(xml); jasmine.Ajax.requests.mostRecent().respondWith({ status: 200, contentType: "text/xml", responseText: xmlString }); expect(task.getState()).toBe(tr.enums.State.COMPLETED); expect(task.getData()).toBeTruthy(); expect(new XMLSerializer().serializeToString(task.getData())).toBe(xmlString); }); it('should error after a failed request', function() { var task = new tr.Xhr('http://fake/url'); task.run(); expect(task.getState()).toBe(tr.enums.State.RUNNING); jasmine.Ajax.requests.mostRecent().responseError(); expect(task.getState()).toBe(tr.enums.State.ERRORED); }); it('should error after an aborted request', function() { var task = new tr.Xhr('http://fake/url'); task.run(); expect(task.getState()).toBe(tr.enums.State.RUNNING); jasmine.Ajax.requests.mostRecent().abort(); expect(task.getState()).toBe(tr.enums.State.ERRORED); }); it('should error after a timed-out request', function() { var task = new tr.Xhr('http://fake/url'); task.run(); expect(task.getState()).toBe(tr.enums.State.RUNNING); jasmine.Ajax.requests.mostRecent().responseTimeout(); expect(task.getState()).toBe(tr.enums.State.ERRORED); }); it('should error (but not throw) if invalid JSON is returned', function() { var task = new tr.Xhr('http://fake/url', undefined, tr.enums.XhrResponseType.JSON); task.run(); expect(task.getResponseType()).toBe(tr.enums.XhrResponseType.JSON); expect(task.getState()).toBe(tr.enums.State.RUNNING); jasmine.Ajax.requests.mostRecent().respondWith({ status: 200, responseText: 'invalid' }); expect(task.getState()).toBe(tr.enums.State.ERRORED); }); it('should ignore XHR events that occur while interrupted', function() { var task = new tr.Xhr('http://fake/url'); task.run(); expect(task.getState()).toBe(tr.enums.State.RUNNING); task.interrupt(); expect(task.getState()).toBe(tr.enums.State.INTERRUPTED); expect(task.xhrRequest_).toBeFalsy(); }); it('should rerun after being interrupted', function() { var task = new tr.Xhr('http://fake/url'); task.run(); task.interrupt(); expect(task.getState()).toBe(tr.enums.State.INTERRUPTED); expect(task.xhrRequest_).toBeFalsy(); task.run(); expect(task.getState()).toBe(tr.enums.State.RUNNING); expect(task.xhr_).toBeTruthy(); }); it('should clear data on a reset and refetch data on a rerun', function() { var task = new tr.Xhr('http://fake/url'); task.run(); expect(task.getState()).toBe(tr.enums.State.RUNNING); jasmine.Ajax.requests.mostRecent().respondWith({ status: 200, responseText: 'fake response 1' }); expect(task.getState()).toBe(tr.enums.State.COMPLETED); expect(task.getData()).toBe('fake response 1'); task.reset(); expect(task.getState()).toBe(tr.enums.State.INITIALIZED); expect(task.getData()).toBeFalsy(); task.run(); expect(task.getState()).toBe(tr.enums.State.RUNNING); jasmine.Ajax.requests.mostRecent().respondWith({ status: 200, responseText: 'fake response 2' }); expect(task.getState()).toBe(tr.enums.State.COMPLETED); expect(task.getData()).toBe('fake response 2'); }); });
{ "content_hash": "1f7755b45d4542449572d97b40a92896", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 112, "avg_line_length": 30.071770334928228, "alnum_prop": 0.6599840891010342, "repo_name": "bvaughn/task-runner", "id": "4833419e0e5336c18d1dd780e35104b8a73dd455", "size": "6285", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/tr/xhr.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "164398" }, { "name": "TypeScript", "bytes": "114453" } ], "symlink_target": "" }
\hypertarget{struct_forth_1_1_forth_machine}{\section{Forth\-:\-:Forth\-Machine Struct Reference} \label{struct_forth_1_1_forth_machine}\index{Forth\-::\-Forth\-Machine@{Forth\-::\-Forth\-Machine}} } \subsection*{Public Member Functions} \begin{DoxyCompactItemize} \item \hypertarget{struct_forth_1_1_forth_machine_ad6702638c4880ffdbc7cbfd4703060f4}{void {\bfseries print\-Stack} () const }\label{struct_forth_1_1_forth_machine_ad6702638c4880ffdbc7cbfd4703060f4} \item \hypertarget{struct_forth_1_1_forth_machine_aa94a352b17c33615c1ab84abcb72e399}{Status {\bfseries process} (Token \&g)}\label{struct_forth_1_1_forth_machine_aa94a352b17c33615c1ab84abcb72e399} \end{DoxyCompactItemize} The documentation for this struct was generated from the following file\-:\begin{DoxyCompactItemize} \item src/rayforth.\-cpp\end{DoxyCompactItemize}
{ "content_hash": "843b770febd4c702d5e24e0410f8d3de", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 191, "avg_line_length": 49.529411764705884, "alnum_prop": 0.7933491686460807, "repo_name": "madebyjeffrey/RayForth", "id": "2d42f049c7b8fd6ff73c7673438dd0d7dff5b057", "size": "842", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/latex/struct_forth_1_1_forth_machine.tex", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "44711" }, { "name": "CMake", "bytes": "1016" }, { "name": "Scala", "bytes": "202" } ], "symlink_target": "" }
Title: Introducing Git Author: Denis Sergeev date: 2015-12-11 16:16 tags: git, github, version control {% notebook 2015-12-11-meeting-summary.ipynb cells[2:] %}
{ "content_hash": "81abb131e6ce20410ece5e603d881c25", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 57, "avg_line_length": 26.833333333333332, "alnum_prop": 0.7515527950310559, "repo_name": "ueapy/ueapy.github.io", "id": "c8c7a0a701d3e6c494477e5c5f6f48074ae25dcb", "size": "161", "binary": false, "copies": "1", "ref": "refs/heads/src", "path": "content/2015-12-11-meeting-summary.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "119382" }, { "name": "HTML", "bytes": "61069" }, { "name": "JavaScript", "bytes": "33791" }, { "name": "Jupyter Notebook", "bytes": "9158013" }, { "name": "Makefile", "bytes": "5206" }, { "name": "Python", "bytes": "5068" }, { "name": "Shell", "bytes": "2201" } ], "symlink_target": "" }
/** * @class * @name communote.widget.classes.controls.OptionList * @augments communote.widget.classes.controls.ContainerControl */ communote.widget.classes.controls.OptionList = communote.widget.classes.controls.ContainerControl .extend( /** * @lends communote.widget.classes.controls.OptionList.prototype */ { name: "OptionList", noContainer: false, containerTag: 'ul', css: [ 'cntwOptionList' ], registerListeners: function(listeners) { this.listenTo('optionSelected', this.parent.channel); this.base(); }, loadControls: function() { var i, item; var items = this.configData.items; for (i in items) { item = items[i]; if (item.items) { subItems = communote.jQuery.merge([ { label: 'htmlclient.optionlist.less', css: 'cntwLessItems' } ], item.items); this.controls.push({ type: 'OptionList', name: this.name, slot: '.' + item.css, css: this.config.css, data: { items: subItems } }); } } this.base(); }, loadData: function() { var items = this.configData.items || [ { label: 'no items' } ]; this.insertValues({ options: items }); }, insertValues: function(data) { this.base(data); var node; var list = this.getDomNode(); var children = list.children(); if (this.configData.pipeList) { list.addClass('cntwPipeList'); } if (this.configData.autoWidth) { list.addClass('cntwAutoWidth'); children.width((100 / children.length) + '%'); } children.addClass('cntwItem'); children.first().addClass('cntwFirst'); children.last().addClass('cntwLast'); if (this.parent.type == this.type) { node = this.getDomNode(); node.addClass('cntwPopupOptionList'); } }, bindEvents: function() { var more; var $ = communote.jQuery; var self = this; var items = $('> .cntwItem', this.getDomNode()); items.click(function() { self.fireEvent('optionSelected', self.parent.channel, $(this).children()); self.fireEvent('optionSelected', self.channel, $(this).children()); if (self.controls.length > 0) { return false;// prevent event bubbeling } return true; }); more = $('> .cntwItem > .cntwMoreItems', this.getDomNode()); //list = more.find('> .cntwOptionList'); more.click(function() { self.showSubList(); }); if (this.configData.showSelection){self.fireEvent('optionSelected', self.parent.channel, items.first().children());} }, showSubList: function() { var more = communote.jQuery('> .cntwItem > .cntwMoreItems', this.getDomNode()); var list = more.find('> .cntwOptionList'); var container = list.parent(); var offset = container.offset() || {}; list.css({ position: 'absolute', top: offset.top, left: offset.left }); list.show(); }, optionSelected: function(selected) { var item = selected.parent(); var items = item.parent().children(); if (!selected.hasClass('cntwMoreItems') && (this.parent.type == this.type)) { this.getDomNode().hide(); } if (this.configData.showSelection) { items.removeClass('cntwSelected'); item.addClass('cntwSelected'); } }, parseData: function(data) { this.base(data); var self = this; communote.jQuery.each(data.options, function(index, option) { // if label == false label is disabeled (this will make debugging // easier, if you just forgot to set the label) if ((option.label && option.label === false) || (option.text && option.text === false)) { option.optionText = ""; option.hide = true; } else { if (option.text === undefined) { option.optionText = self.getLabel(option.label); } else { option.optionText = option.text; } } option.itemClass = 'cntwItem'; if (option.hide) { option.itemClass = ' cntwHide'; } if (option.selected) { option.itemClass += ' cntwSelected'; } }); }, getDirectives: function() { var dir = { '.cntwItem': { 'option<-options': { '.cntwOption': 'option.optionText', '.cntwOption@class': 'option.css', '.@class': 'option.itemClass' } } }; return dir; } });
{ "content_hash": "33686e05457e6a455005271cd35ab77d", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 132, "avg_line_length": 39.96296296296296, "alnum_prop": 0.39990732159406855, "repo_name": "Communote/communote-server", "id": "5bc40a6f12d9dd355c332b8734df9dd68e94e42f", "size": "6474", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "communote/plugins/communote-html-client/src/main/resources/META-INF/resources/static/javascript/classes/controls/OptionList.class.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "272" }, { "name": "CSS", "bytes": "294265" }, { "name": "HTML", "bytes": "26978" }, { "name": "Java", "bytes": "13692073" }, { "name": "JavaScript", "bytes": "2460010" }, { "name": "PLSQL", "bytes": "4134" }, { "name": "PLpgSQL", "bytes": "262702" }, { "name": "Rich Text Format", "bytes": "30964" }, { "name": "Shell", "bytes": "274" } ], "symlink_target": "" }
layout: post date: 2016-02-02 title: "Blush Prom Style 11119 Sleeveless Sweep/Brush Train Sheath/Column" category: Blush tags: [Blush,Sheath/Column,Halter,Sweep/Brush Train,Sleeveless] --- ### Blush Prom Style 11119 Just **$569.99** ### Sleeveless Sweep/Brush Train Sheath/Column <table><tr><td>BRANDS</td><td>Blush</td></tr><tr><td>Silhouette</td><td>Sheath/Column</td></tr><tr><td>Neckline</td><td>Halter</td></tr><tr><td>Hemline/Train</td><td>Sweep/Brush Train</td></tr><tr><td>Sleeve</td><td>Sleeveless</td></tr></table> <a href="https://www.readybrides.com/en/blush/49142-blush-prom-style-11119.html"><img src="//img.readybrides.com/109164/blush-prom-style-11119.jpg" alt="Blush Prom Style 11119" style="width:100%;" /></a> <!-- break --><a href="https://www.readybrides.com/en/blush/49142-blush-prom-style-11119.html"><img src="//img.readybrides.com/109163/blush-prom-style-11119.jpg" alt="Blush Prom Style 11119" style="width:100%;" /></a> Buy it: [https://www.readybrides.com/en/blush/49142-blush-prom-style-11119.html](https://www.readybrides.com/en/blush/49142-blush-prom-style-11119.html)
{ "content_hash": "ed07dc29d79497614290740a52019c02", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 244, "avg_line_length": 78.85714285714286, "alnum_prop": 0.720108695652174, "repo_name": "nicedaymore/nicedaymore.github.io", "id": "65e628cb3ff413801df598bc31db25e92d79d813", "size": "1108", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2016-02-02-Blush-Prom-Style-11119-Sleeveless-SweepBrush-Train-SheathColumn.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "83876" }, { "name": "HTML", "bytes": "14755" }, { "name": "Ruby", "bytes": "897" } ], "symlink_target": "" }
////////////////////////////////////////////////////////////// // <auto-generated>This code was generated by LLBLGen Pro 5.7.</auto-generated> ////////////////////////////////////////////////////////////// // Code is generated on: // Code is generated using templates: SD.TemplateBindings.SharedTemplates // Templates vendor: Solutions Design. ////////////////////////////////////////////////////////////// using System; using SD.LLBLGen.Pro.ORMSupportClasses; namespace AdventureWorks.Dal.Adapter.HelperClasses { /// <summary>Class for the returning of a default value when a type is given. These Default values are used for EntityFields which have a NULL value in the database.</summary> [Serializable] public partial class TypeDefaultValue : ITypeDefaultValue { /// <summary>Returns a default value for the type specified</summary> /// <param name="defaultValueType">The type which default value should be returned.</param> /// <returns>The default value for the type specified.</returns> public object DefaultValue(System.Type defaultValueType) { return TypeDefaultValue.GetDefaultValue(defaultValueType); } /// <summary>Returns a default value for the type specified</summary> /// <param name="defaultValueType">The type which default value should be returned.</param> /// <returns>The default value for the type specified.</returns> public static object GetDefaultValue(System.Type defaultValueType) { object valueToReturn=null; switch(Type.GetTypeCode(defaultValueType)) { case TypeCode.String: valueToReturn=string.Empty; break; case TypeCode.Boolean: valueToReturn = false; break; case TypeCode.Byte: valueToReturn = (byte)0; break; case TypeCode.DateTime: valueToReturn = DateTime.MinValue; break; case TypeCode.Decimal: valueToReturn = 0.0M; break; case TypeCode.Double: valueToReturn = 0.0; break; case TypeCode.Int16: valueToReturn = (short)0; break; case TypeCode.Int32: valueToReturn = (int)0; break; case TypeCode.Int64: valueToReturn = (long)0; break; case TypeCode.Object: switch(defaultValueType.UnderlyingSystemType.FullName) { case "System.Guid": valueToReturn = Guid.Empty; break; case "System.Byte[]": valueToReturn = new byte[0]; break; case "System.DateTimeOffset": valueToReturn = DateTimeOffset.MinValue; break; case "System.TimeSpan": valueToReturn = TimeSpan.MinValue; break; } break; case TypeCode.Single: valueToReturn = 0.0f; break; case TypeCode.UInt16: valueToReturn = (ushort)0; break; case TypeCode.UInt32: valueToReturn = (uint)0; break; case TypeCode.UInt64: valueToReturn = (ulong)0; break; case TypeCode.SByte: valueToReturn = (SByte)0; break; default: // do nothing, return null. break; } return valueToReturn; } } }
{ "content_hash": "67249384aeb45acc962ae8cd0c314bc6", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 176, "avg_line_length": 30.25, "alnum_prop": 0.6380165289256199, "repo_name": "jonnybee/RawDataAccessBencher", "id": "1081cc57b68f1f1664116cc71076e569fbe60e97", "size": "3027", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LLBLGenPro/DatabaseGeneric/HelperClasses/TypeDefaultValue.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3435845" } ], "symlink_target": "" }
require 'spec_helper' module Exlibris module Aleph module API module Client class Patron class Record class Item class CreateHold describe Parameters do let(:pickup_location) do Exlibris::Aleph::PickupLocation.new('BOBST', 'NYU Bobst') end let(:last_interest_date) { '20140915' } let(:start_interest_date) { '20140915' } let(:sub_author) { 'Sub Author' } let(:sub_title) { 'Sub Title' } let(:pages) { 'Pages' } let(:note_1) { 'Note 1' } let(:note_2) { 'Note 2' } let(:rush) { 'N' } let(:input_parameters) do { pickup_location: pickup_location, last_interest_date: last_interest_date, start_interest_date: start_interest_date, sub_author: sub_author, sub_title: sub_title, pages: pages, note_1: note_1, note_2: note_2, rush: rush } end subject(:parameters) { Parameters.new(input_parameters) } it { should be_a Parameters } describe '#pickup_location' do subject { parameters.pickup_location } it { should eq pickup_location } end describe '#last_interest_date' do subject { parameters.last_interest_date } it { should eq last_interest_date } end describe '#start_interest_date' do subject { parameters.start_interest_date } it { should eq start_interest_date } end describe '#sub_author' do subject { parameters.sub_author } it { should eq sub_author } end describe '#sub_title' do subject { parameters.sub_title } it { should eq sub_title } end describe '#pages' do subject { parameters.pages } it { should eq pages } end describe '#note_1' do subject { parameters.note_1 } it { should eq note_1 } end describe '#note_2' do subject { parameters.note_2 } it { should eq note_2 } end describe '#rush' do subject { parameters.rush } it { should eq rush } end context 'when the input parameters is not a Hash' do let(:input_parameters) { 'invalid' } it 'should raise an ArgumentError' do expect { subject }.to raise_error ArgumentError end end context 'when the input parameters is a Hash' do context 'but the pickup location is not a PickupLocation' do let(:pickup_location) { 'invalid' } it 'should raise an ArgumentError' do expect { subject }.to raise_error ArgumentError end end context 'and the pickup location is nil' do let(:pickup_location) { nil } it 'should not raise an ArgumentError' do expect { subject }.not_to raise_error end end end end end end end end end end end end
{ "content_hash": "47c4f660bff9c7cf4d77bcaf1faa78cf", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 80, "avg_line_length": 39.95049504950495, "alnum_prop": 0.41536555142503095, "repo_name": "scotdalton/exlibris-aleph", "id": "74241f209146ea501bc5e9a2aa39fffd12eb4eb1", "size": "4035", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/exlibris/aleph/api/client/patron/record/item/create_hold/parameters_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "289358" } ], "symlink_target": "" }
begin require 'active_record' # todo: make optional rescue LoadError require 'rubygems' require 'active_record' end module Treasury class Keymaster def self.register(object_class, storage_class) (@storages ||= {})[object_class] = storage_class end def self.storage_for(object) (@storages ||= {}).each_pair do |object_class, storage_class| if (object.is_a?(Class) && object.ancestors.include?(object_class)) || (object.is_a?(object_class)) return storage_class end end if (object.is_a?(Class) && object.is_a?(Treasury)) || (object.class.is_a?(Treasury)) return StashStorage end raise "Couldn't find storage class for #{object.inspect}" end def self.new?(object) storage_for(object).new?(object) end def self.key_for(object) if new?(object) nil else storage_for(object).key_for(object) end end end end
{ "content_hash": "6a6dc455e6905d5612f6f37caaa7e7dc", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 78, "avg_line_length": 23.714285714285715, "alnum_prop": 0.5953815261044176, "repo_name": "alexch/treasury", "id": "a3bf2cd2a3397c7b5423234e735b9f38bc6e5bcb", "size": "996", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/treasury/keymaster.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "59905" } ], "symlink_target": "" }
'use strict'; module.exports = function (math) { var collection = require('../../type/collection'); /** * Divide two matrices element wise. The function accepts both matrices and * scalar values. * * Syntax: * * math.dotDivide(x, y) * * Examples: * * math.dotDivide(2, 4); // returns 0.5 * * a = [[9, 5], [6, 1]]; * b = [[3, 2], [5, 2]]; * * math.dotDivide(a, b); // returns [[3, 2.5], [1.2, 0.5]] * math.divide(a, b); // returns [[1.75, 0.75], [-1.75, 2.25]] * * See also: * * divide, multiply, dotMultiply * * @param {Number | BigNumber | Boolean | Complex | Unit | Array | Matrix | null} x Numerator * @param {Number | BigNumber | Boolean | Complex | Unit | Array | Matrix | null} y Denominator * @return {Number | BigNumber | Complex | Unit | Array | Matrix} Quotient, `x ./ y` */ math.dotDivide = function dotDivide(x, y) { if (arguments.length != 2) { throw new math.error.ArgumentsError('dotDivide', arguments.length, 2); } return collection.deepMap2(x, y, math.divide); }; // TODO: deprecated since version 0.23.0, clean up some day math.edivide = function () { throw new Error('Function edivide is renamed to dotDivide'); } };
{ "content_hash": "4efcaa58da2a9913f7d9cb266e914e99", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 105, "avg_line_length": 29.59090909090909, "alnum_prop": 0.5606758832565284, "repo_name": "meuninckt/workingPI", "id": "87a29046385c98906f1d2cc8073a821a0b4837fd", "size": "1302", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "node_modules/mathjs/lib/function/arithmetic/dotDivide.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "9794" }, { "name": "D", "bytes": "1498" }, { "name": "JavaScript", "bytes": "203486" }, { "name": "Python", "bytes": "654" } ], "symlink_target": "" }
@interface animationTestTests : XCTestCase @end @implementation animationTestTests - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testExample { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } - (void)testPerformanceExample { // This is an example of a performance test case. [self measureBlock:^{ // Put the code you want to measure the time of here. }]; } @end
{ "content_hash": "8fe99f47c46258e808c80aec4b20cef9", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 107, "avg_line_length": 25.655172413793103, "alnum_prop": 0.6989247311827957, "repo_name": "VikingWarlock/VKWaterProgress", "id": "a1a367250b9a6791b8124f0a611b4343fc4d4d2c", "size": "910", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "animationTestTests/animationTestTests.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "11141" } ], "symlink_target": "" }
ActiveRecord import and export based on PHPExcel for Yii 2 framework. This library is mainly designed to import data, export is in the raw condition (even it's working in basic form), under development and not documented yet. The important notes: - It uses ActiveRecord models and PHPExcel library, so operating big data requires pretty good hardware, especially RAM. In case of memory shortage I can advise splitting data into smaller chunks. - This is not just a wrapper on some PHPExcel methods, it's a tool helping import data from Excel in human readable form with minimal configuration. - This is designed for periodical import. - The library is more effective when working with multiple related models and complex data structures. [![Latest Stable Version](https://poser.pugx.org/arogachev/yii2-excel/v/stable)](https://packagist.org/packages/arogachev/yii2-excel) [![Total Downloads](https://poser.pugx.org/arogachev/yii2-excel/downloads)](https://packagist.org/packages/arogachev/yii2-excel) [![Latest Unstable Version](https://poser.pugx.org/arogachev/yii2-excel/v/unstable)](https://packagist.org/packages/arogachev/yii2-excel) [![License](https://poser.pugx.org/arogachev/yii2-excel/license)](https://packagist.org/packages/arogachev/yii2-excel) - [Installation](#installation) - [Import Basics](docs/import-basics.md) - [Basic import](docs/import-basic.md) - [Advanced import](docs/import-advanced.md) - [Running import](#running-import) ## Installation The preferred way to install this extension is through [composer](http://getcomposer.org/download/). Either run ``` php composer.phar require --prefer-dist arogachev/yii2-excel ``` or add ``` "arogachev/yii2-excel": "*" ``` to the require section of your `composer.json` file. ## Running import ```php if (!$importer->run()) { echo $importer->error; if ($importer->wrongModel) { echo Html::errorSummary($importer->wrongModel); } } ```
{ "content_hash": "dd4301e88e6c1eb6081c7a91034b7045", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 137, "avg_line_length": 35.870370370370374, "alnum_prop": 0.7552916881775942, "repo_name": "arogachev/yii2-excel", "id": "b3b31746a7a61e50c7dec2b5deaf226a5b0b249a", "size": "1952", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "74130" }, { "name": "PLpgSQL", "bytes": "1163" } ], "symlink_target": "" }
package clockworktest.bounding; import com.clockwork.bounding.BoundingBox; import com.clockwork.collision.CollisionResults; import com.clockwork.math.Ray; import com.clockwork.math.Vector3f; /** * Tests picking/collision between bounds and shapes. */ public class TestRayCollision { public static void main(String[] args){ Ray r = new Ray(Vector3f.ZERO, Vector3f.UNIT_X); BoundingBox bbox = new BoundingBox(new Vector3f(5, 0, 0), 1, 1, 1); CollisionResults res = new CollisionResults(); bbox.collideWith(r, res); System.out.println("Bounding:" +bbox); System.out.println("Ray: "+r); System.out.println("Num collisions: "+res.size()); for (int i = 0; i < res.size(); i++){ System.out.println("--- Collision #"+i+" ---"); float dist = res.getCollision(i).getDistance(); Vector3f pt = res.getCollision(i).getContactPoint(); System.out.println("distance: "+dist); System.out.println("point: "+pt); } } }
{ "content_hash": "0772530eda503d4fc1d8160f46cf230c", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 75, "avg_line_length": 30.02857142857143, "alnum_prop": 0.6241674595623216, "repo_name": "PlanetWaves/clockworkengine", "id": "9ef709d5819a41e1a30d0100860b6624b4252161", "size": "1051", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "branches/3.0/engine/src/test/clockworktest/bounding/TestRayCollision.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "43610" }, { "name": "C++", "bytes": "613083" }, { "name": "GLSL", "bytes": "564936" }, { "name": "HTML", "bytes": "73891" }, { "name": "Java", "bytes": "19438695" }, { "name": "Makefile", "bytes": "26492" }, { "name": "Shell", "bytes": "1085" }, { "name": "XSLT", "bytes": "10130" } ], "symlink_target": "" }
extern crate grin_grin as grin; extern crate grin_core as core; extern crate grin_p2p as p2p; extern crate grin_chain as chain; extern crate grin_api as api; extern crate grin_wallet as wallet; extern crate secp256k1zkp as secp; extern crate blake2_rfc as blake2; extern crate env_logger; extern crate futures; extern crate tokio_core; extern crate tokio_timer; extern crate futures_cpupool; use std::thread; use std::time; use std::default::Default; use std::fs; use std::sync::{Arc, Mutex}; use tokio_core::reactor; use tokio_timer::Timer; use secp::Secp256k1; use wallet::WalletConfig; /// Just removes all results from previous runs pub fn clean_all_output(test_name_dir:&str){ let target_dir = format!("target/test_servers/{}", test_name_dir); let result = fs::remove_dir_all(target_dir); if let Err(e) = result { println!("{}",e); } } /// Errors that can be returned by LocalServerContainer #[derive(Debug)] #[allow(dead_code)] pub enum Error { Internal(String), Argument(String), NotFound, } /// All-in-one server configuration struct, for convenience /// #[derive(Clone)] pub struct LocalServerContainerConfig { //user friendly name for the server, also denotes what dir //the data files will appear in pub name: String, //Base IP address pub base_addr: String, //Port the server (p2p) is running on pub p2p_server_port: u16, //Port the API server is running on pub api_server_port: u16, //Port the wallet server is running on pub wallet_port: u16, //Whether we're going to mine pub start_miner: bool, //time in millis by which to artifically slow down the mining loop //in this container pub miner_slowdown_in_millis: u64, //Whether we're going to run a wallet as well, //can use same server instance as a validating node for convenience pub start_wallet: bool, //address of a server to use as a seed pub seed_addr: String, //keep track of whether this server is supposed to be seeding pub is_seeding: bool, //Whether to burn mining rewards pub burn_mining_rewards: bool, //full address to send coinbase rewards to pub coinbase_wallet_address: String, //When running a wallet, the address to check inputs and send //finalised transactions to, pub wallet_validating_node_url:String, } /// Default server config impl Default for LocalServerContainerConfig { fn default() -> LocalServerContainerConfig { LocalServerContainerConfig { name: String::from("test_host"), base_addr: String::from("127.0.0.1"), p2p_server_port: 13414, api_server_port: 13415, wallet_port: 13416, seed_addr: String::from(""), is_seeding: false, start_miner: false, start_wallet: false, burn_mining_rewards: false, coinbase_wallet_address: String::from(""), wallet_validating_node_url: String::from(""), miner_slowdown_in_millis: 0, } } } /// A top-level container to hold everything that might be running /// on a server, i.e. server, wallet in send or receive mode pub struct LocalServerContainer { //Configuration config: LocalServerContainerConfig, //Structure of references to the //internal server data pub p2p_server_stats: Option<grin::ServerStats>, //The API server instance api_server: Option<api::ApiServer>, //whether the server is running pub server_is_running: bool, //Whether the server is mining pub server_is_mining: bool, //Whether the server is also running a wallet //Not used if running wallet without server pub wallet_is_running: bool, //the list of peers to connect to pub peer_list: Vec<String>, //base directory for the server instance working_dir: String, } impl LocalServerContainer { /// Create a new local server container with defaults, with the given name /// all related files will be created in the directory target/test_servers/{name} pub fn new(config:LocalServerContainerConfig) -> Result<LocalServerContainer, Error> { let working_dir = format!("target/test_servers/{}", config.name); Ok((LocalServerContainer { config:config, p2p_server_stats: None, api_server: None, server_is_running: false, server_is_mining: false, wallet_is_running: false, working_dir: working_dir, peer_list: Vec::new(), })) } pub fn run_server(&mut self, duration_in_seconds: u64) -> grin::ServerStats { let mut event_loop = reactor::Core::new().unwrap(); let api_addr = format!("{}:{}", self.config.base_addr, self.config.api_server_port); let mut seeding_type=grin::Seeding::None; let mut seeds=Vec::new(); if self.config.seed_addr.len()>0{ seeding_type=grin::Seeding::List; seeds=vec![self.config.seed_addr.to_string()]; } let s = grin::Server::future( grin::ServerConfig{ api_http_addr: api_addr, db_root: format!("{}/.grin", self.working_dir), p2p_config: Some(p2p::P2PConfig{port: self.config.p2p_server_port, ..p2p::P2PConfig::default()}), seeds: Some(seeds), seeding_type: seeding_type, ..Default::default() }, &event_loop.handle()).unwrap(); self.p2p_server_stats = Some(s.get_server_stats().unwrap()); if self.config.start_wallet == true{ self.run_wallet(duration_in_seconds+5); //give a second to start wallet before continuing thread::sleep(time::Duration::from_millis(1000)); } let miner_config = grin::MinerConfig { enable_mining: self.config.start_miner, burn_reward: self.config.burn_mining_rewards, use_cuckoo_miner: false, cuckoo_miner_async_mode: Some(false), cuckoo_miner_plugin_dir: Some(String::from("../target/debug/deps")), cuckoo_miner_plugin_type: Some(String::from("simple")), wallet_receiver_url : self.config.coinbase_wallet_address.clone(), slow_down_in_millis: Some(self.config.miner_slowdown_in_millis.clone()), ..Default::default() }; if self.config.start_miner == true { println!("starting Miner on port {}", self.config.p2p_server_port); s.start_miner(miner_config); } for p in &mut self.peer_list { println!("{} connecting to peer: {}", self.config.p2p_server_port, p); s.connect_peer(p.parse().unwrap()).unwrap(); } let timeout = Timer::default().sleep(time::Duration::from_secs(duration_in_seconds)); event_loop.run(timeout).unwrap(); if self.wallet_is_running{ self.stop_wallet(); } s.get_server_stats().unwrap() } /// Starts a wallet daemon to receive and returns the /// listening server url pub fn run_wallet(&mut self, _duration_in_seconds: u64) { //URL on which to start the wallet listener (i.e. api server) let url = format!("{}:{}", self.config.base_addr, self.config.wallet_port); //Just use the name of the server for a seed for now let seed = format!("{}", self.config.name); let seed = blake2::blake2b::blake2b(32, &[], seed.as_bytes()); let s = Secp256k1::new(); let key = wallet::ExtendedKey::from_seed(&s, seed.as_bytes()) .expect("Error deriving extended key from seed."); println!("Starting the Grin wallet receiving daemon on {} ", self.config.wallet_port ); let mut wallet_config = WalletConfig::default(); wallet_config.api_http_addr = format!("http://{}", url); wallet_config.check_node_api_http_addr = self.config.wallet_validating_node_url.clone(); wallet_config.data_file_dir=self.working_dir.clone(); let mut api_server = api::ApiServer::new("/v1".to_string()); api_server.register_endpoint("/receive".to_string(), wallet::WalletReceiver { key: key, config: wallet_config, }); api_server.start(url).unwrap_or_else(|e| { println!("Failed to start Grin wallet receiver: {}.", e); }); self.api_server = Some(api_server); self.wallet_is_running = true; } /// Stops the running wallet server pub fn stop_wallet(&mut self){ let mut api_server = self.api_server.as_mut().unwrap(); api_server.stop(); } /// Adds a peer to this server to connect to upon running pub fn add_peer(&mut self, addr:String){ self.peer_list.push(addr); } } /// Configuration values for container pool pub struct LocalServerContainerPoolConfig { //Base name to append to all the servers in this pool pub base_name: String, //Base http address for all of the servers in this pool pub base_http_addr: String, //Base port server for all of the servers in this pool //Increment the number by 1 for each new server pub base_p2p_port: u16, //Base api port for all of the servers in this pool //Increment this number by 1 for each new server pub base_api_port: u16, //Base wallet port for this server // pub base_wallet_port: u16, //How long the servers in the pool are going to run pub run_length_in_seconds: u64, } /// Default server config /// impl Default for LocalServerContainerPoolConfig { fn default() -> LocalServerContainerPoolConfig { LocalServerContainerPoolConfig { base_name: String::from("test_pool"), base_http_addr: String::from("127.0.0.1"), base_p2p_port: 10000, base_api_port: 11000, base_wallet_port: 12000, run_length_in_seconds: 30, } } } /// A convenience pool for running many servers simultaneously /// without necessarily having to configure each one manually pub struct LocalServerContainerPool { //configuration pub config: LocalServerContainerPoolConfig, //keep ahold of all the created servers thread-safely server_containers: Vec<LocalServerContainer>, //Keep track of what the last ports a server was opened on next_p2p_port: u16, next_api_port: u16, next_wallet_port: u16, //keep track of whether a seed exists, and pause a bit if so is_seeding: bool, } impl LocalServerContainerPool { pub fn new(config: LocalServerContainerPoolConfig)->LocalServerContainerPool{ (LocalServerContainerPool{ next_api_port: config.base_api_port, next_p2p_port: config.base_p2p_port, next_wallet_port: config.base_wallet_port, config: config, server_containers: Vec::new(), is_seeding: false, }) } /// adds a single server on the next available port /// overriding passed-in values as necessary. Config object is an OUT value with /// ports/addresses filled in /// pub fn create_server(&mut self, server_config:&mut LocalServerContainerConfig) { //If we're calling it this way, need to override these server_config.p2p_server_port=self.next_p2p_port; server_config.api_server_port=self.next_api_port; server_config.wallet_port=self.next_wallet_port; server_config.name=String::from(format!("{}/{}-{}", self.config.base_name, self.config.base_name, server_config.p2p_server_port)); //Use self as coinbase wallet server_config.coinbase_wallet_address=String::from(format!("http://{}:{}", server_config.base_addr, server_config.wallet_port)); self.next_p2p_port+=1; self.next_api_port+=1; self.next_wallet_port+=1; if server_config.is_seeding { self.is_seeding=true; } let _server_address = format!("{}:{}", server_config.base_addr, server_config.p2p_server_port); let server_container = LocalServerContainer::new(server_config.clone()).unwrap(); //self.server_containers.push(server_arc); //Create a future that runs the server for however many seconds //collect them all and run them in the run_all_servers let _run_time = self.config.run_length_in_seconds; self.server_containers.push(server_container); } /// adds n servers, ready to run /// /// #[allow(dead_code)] pub fn create_servers(&mut self, number: u16){ for _ in 0..number { //self.create_server(); } } /// runs all servers, and returns a vector of references to the servers /// once they've all been run /// pub fn run_all_servers(self) -> Vec<grin::ServerStats>{ let run_length = self.config.run_length_in_seconds; let mut handles = vec![]; // return handles to all of the servers, wrapped in mutexes, handles, etc let return_containers = Arc::new(Mutex::new(Vec::new())); let is_seeding = self.is_seeding.clone(); for mut s in self.server_containers { let return_container_ref = return_containers.clone(); let handle=thread::spawn(move || { if is_seeding && !s.config.is_seeding { //there's a seed and we're not it, so hang around longer and give the seed //a chance to start thread::sleep(time::Duration::from_millis(2000)); } let server_ref=s.run_server(run_length); return_container_ref.lock().unwrap().push(server_ref); }); //Not a big fan of sleeping hack here, but there appears to be a //concurrency issue when creating files in rocksdb that causes //failure if we don't pause a bit before starting the next server thread::sleep(time::Duration::from_millis(500)); handles.push(handle); } for handle in handles { match handle.join() { Ok(_) => {} Err(e) => { println!("Error starting server thread: {:?}", e); panic!(e); } } } //return a much simplified version of the results let return_vec=return_containers.lock().unwrap(); return_vec.clone() } pub fn connect_all_peers(&mut self){ /// just pull out all currently active servers, build a list, /// and feed into all servers let mut server_addresses:Vec<String> = Vec::new(); for s in &self.server_containers { let server_address = format!("{}:{}", s.config.base_addr, s.config.p2p_server_port); server_addresses.push(server_address); } for a in server_addresses { for s in &mut self.server_containers { if format!("{}:{}", s.config.base_addr, s.config.p2p_server_port) != a { s.add_peer(a.clone()); } } } } }
{ "content_hash": "c5c74ed5708b333a3d90b237b1c7f581", "timestamp": "", "source": "github", "line_count": 503, "max_line_length": 113, "avg_line_length": 30.970178926441353, "alnum_prop": 0.5994992938759789, "repo_name": "Latrasis/grin", "id": "948b02bf91ef024643a235d2a994eea844d79078", "size": "16175", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "grin/tests/framework.rs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "28456" }, { "name": "C", "bytes": "676710" }, { "name": "C++", "bytes": "59541" }, { "name": "Java", "bytes": "32388" }, { "name": "M4", "bytes": "26869" }, { "name": "Makefile", "bytes": "5260" }, { "name": "Python", "bytes": "30192" }, { "name": "Rust", "bytes": "606711" }, { "name": "Shell", "bytes": "47" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "8471d40904f263ffd242550b557f2040", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "77cb10bd140ea0d84952ebb06e6b0f72250f6ec7", "size": "189", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Masdevallia/Masdevallia barrowii/ Syn. Alaticaulia barrowii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateTblLogsTranslations extends Migration { /** * Run the migrations. * * @return void */ public function up() { $this->down(); Schema::create('tbl_logs_translations', function(Blueprint $table) { $table->increments('id'); $table->integer('lang_id')->unsigned()->nullable()->index('lang_id_idx'); $table->integer('log_id')->unsigned()->nullable()->index('log_id_idx'); $table->text('raw')->nullable(); $table->text('text')->nullable(); }); Schema::table('tbl_logs_translations', function(Blueprint $table) { $table->foreign('lang_id', 'fk_tlt_lang_id')->references('id')->on('tbl_languages')->onUpdate('NO ACTION')->onDelete('CASCADE'); $table->foreign('log_id', 'fk_tlt_log_id')->references('id')->on('tbl_logs')->onUpdate('NO ACTION')->onDelete('CASCADE'); }); } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement('SET FOREIGN_KEY_CHECKS=0;'); Schema::dropIfExists('tbl_logs_translations'); DB::statement('SET FOREIGN_KEY_CHECKS=1;'); } }
{ "content_hash": "527813d9e350e3713c5bb0f6660edad1", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 140, "avg_line_length": 29.08888888888889, "alnum_prop": 0.5683728036669213, "repo_name": "antaresproject/core", "id": "92948fe30bdf2e861c8ea0c2fcf684f2dca25719", "size": "1795", "binary": false, "copies": "1", "ref": "refs/heads/0.9.2", "path": "src/components/auth/resources/database/migrations/2015_12_10_091059_create_tbl_logs_translations.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "79443" }, { "name": "PHP", "bytes": "2753832" }, { "name": "PLpgSQL", "bytes": "1053" } ], "symlink_target": "" }
exports.action = { name: 'deleteVariant', description: 'Delete a thumbnail variant.', middleware: ['requireAPIKey'], inputs: { id: { required: true }, }, run: (api, data, next) => { api.db.models.Variant.findById(data.params.id) .then(variant => { if (!variant) { throw new Error('Invalid variant'); } return variant.destroy(); }) .then(next) .catch(e => next(e)); } };
{ "content_hash": "f030e3ab553f336e33fca55dcb0400e4", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 55, "avg_line_length": 26.55, "alnum_prop": 0.4613935969868173, "repo_name": "crrobinson14/sits", "id": "5825beb7ee04c596ba1dbd943fa1496cd83c2e31", "size": "531", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "actions/deleteVariant.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "30151" } ], "symlink_target": "" }
<?php /** * Database table classes. * * Subclasses attached to models must follow the naming convention: * Table_TableName, e.g. Table_ElementSet in models/Table/ElementSet.php. * * @package Omeka\Db\Table */ class Omeka_Db_Table { const SORT_PARAM = 'sort_field'; const SORT_DIR_PARAM = 'sort_dir'; /** * The name of the model for which this table will retrieve objects. * * @var string */ protected $_target; /** * The name of the table (sans prefix). * * If this is not given, it will be inflected. * * @var string */ protected $_name; /** * The table prefix. * * Generally used to differentiate Omeka installations sharing a database. * * @var string */ protected $_tablePrefix; /** * The Omeka database object. * * @var Omeka_Db */ protected $_db; /** * Construct the database table object. * * Do not instantiate this by itself. Access instances only via * Omeka_Db::getTable(). * * @see Omeka_Db::getTable() * @param string $targetModel Class name of the table's model. * @param Omeka_Db $db Database object to use for queries. */ public function __construct($targetModel, $db) { $this->_target = $targetModel; $this->_db = $db; } /** * Delegate to the database adapter. * * Used primarily as a convenience method. For example, you can call * fetchOne() and fetchAll() directly from this object. * * @param string $m Method name. * @param array $a Method arguments. * @return mixed */ public function __call($m, $a) { if (!method_exists($this->_db, $m) && !method_exists($this->_db->getAdapter(), $m)) { throw new BadMethodCallException("Method named '$m' does not exist or is not callable."); } return call_user_func_array(array($this->_db, $m), $a); } /** * Retrieve the alias for this table (the name without the prefix). * * @return string */ public function getTableAlias() { if (empty($this->_name)) { $this->setTableName(); } return $this->_name; } /** * Retrieve the Omeka_Db instance. * * @return Omeka_Db */ public function getDb() { return $this->_db; } /** * Determine whether a model has a given column. * * @param string $field Field name. * @return bool */ public function hasColumn($field) { return in_array($field, $this->getColumns()); } /** * Retrieve a list of all the columns for a given model. * * This should be here and not in the model class because get_class_vars() * returns private/protected properties when called from within the class. * Will only return public properties when called in this fashion. * * @return array */ public function getColumns() { return array_keys(get_class_vars($this->_target)); } /** * Retrieve the name of the table for the current table (used in SQL * statements). * * If the table name has not been set, it will inflect the table name. * * @uses Omeka_Db_Table::setTableName(). * @return string */ public function getTableName() { if (empty($this->_name)) { $this->setTableName(); } // Return the table name with the prefix added. return $this->getTablePrefix() . $this->_name; } /** * Set the name of the database table accessed by this class. * * If no name is provided, it will inflect the table name from the name of * the model defined in the constructor. For example, Item -> items. * * @uses Inflector::tableize() * @param string $name (optional) Table name. * @return void */ public function setTableName($name = null) { if ($name) { $this->_name = (string) $name; } else { $this->_name = Inflector::tableize($this->_target); } } /** * Retrieve the table prefix for this table instance. * * @return string */ public function getTablePrefix() { if ($this->_tablePrefix === null) { $this->setTablePrefix(); } return $this->_tablePrefix; } /** * Set the table prefix. * * Defaults to the table prefix defined by the Omeka_Db instance. This * should remain the default in most cases. However, edge cases may require * customization, e.g. creating wrappers for tables generated by other * applications. * * @param string|null $tablePrefix */ public function setTablePrefix($tablePrefix = null) { if ($tablePrefix === null) { $this->_tablePrefix = $this->getDb()->prefix; } else { $this->_tablePrefix = $tablePrefix; } } /** * Retrieve a single record given an ID. * * @param integer $id * @return Omeka_Record_AbstractRecord|false */ public function find($id) { $select = $this->getSelectForFind($id); return $this->fetchObject($select, array()); } /** * Get a set of objects corresponding to all the rows in the table * * WARNING: This will be memory intensive and is thus not recommended for * large data sets. * * @return array Array of {@link Omeka_Record_AbstractRecord}s. */ public function findAll() { $select = $this->getSelect(); return $this->fetchObjects($select); } /** * Retrieve an array of key=>value pairs that can be used as options in a * <select> form input. * * @uses Omeka_Db_Table::_getColumnPairs() * @see Omeka_Db_Table::applySearchFilters() * @param array $options (optional) Set of parameters for searching/ * filtering results. * @return array */ public function findPairsForSelectForm(array $options = array()) { $select = $this->getSelectForFindBy($options); $select->reset(Zend_Db_Select::COLUMNS); $select->from(array(), $this->_getColumnPairs()); $pairs = $this->getDb()->fetchPairs($select); return $pairs; } /** * Retrieve the array of columns that are used by findPairsForSelectForm(). * * This is a template method because these columns are different for every * table, but the underlying logic that retrieves the pairs from the * database is the same in every instance. * * @see Omeka_Db_Table::findPairsForSelectForm() * @return array */ protected function _getColumnPairs() { throw new BadMethodCallException('Column pairs must be defined by _getColumnPairs() in order to use Omeka_Db_Table::findPairsForSelectForm()!'); } /** * Retrieve a set of model objects based on a given number of parameters * * @uses Omeka_Db_Table::getSelectForFindBy() * @param array $params A set of parameters by which to filter the objects * that get returned from the database. * @param integer $limit Number of objects to return per "page". * @param integer $page Page to retrieve. * @return array|null The set of objects that is returned */ public function findBy($params = array(), $limit = null, $page = null) { $select = $this->getSelectForFindBy($params); if ($limit) { $this->applyPagination($select, $limit, $page); } return $this->fetchObjects($select); } /** * Retrieve a select object for this table. * * @return Omeka_Db_Select */ public function getSelect() { $select = new Omeka_Db_Select($this->getDb()->getAdapter()); $alias = $this->getTableAlias(); $select->from(array($alias=>$this->getTableName()), "$alias.*"); return $select; } /** * Retrieve a select object that has had search filters applied to it. * * @uses Omeka_Db_Table::getSelectForFindBy() * @param array $params optional Set of named search parameters. * @return Omeka_Db_Select */ public function getSelectForFindBy($params = array()) { $params = apply_filters($this->_getHookName('browse_params'), $params); $select = $this->getSelect(); $sortParams = $this->_getSortParams($params); if ($sortParams) { list($sortField, $sortDir) = $sortParams; $this->applySorting($select, $sortField, $sortDir); if ($select->getPart(Zend_Db_Select::ORDER) && $sortField != 'id' ) { $alias = $this->getTableAlias(); $select->order("$alias.id $sortDir"); } } $this->applySearchFilters($select, $params); fire_plugin_hook($this->_getHookName('browse_sql'), array('select' => $select, 'params' => $params)); return $select; } /** * Retrieve a select object that is used for retrieving a single record from * the database. * * @param integer $recordId * @return Omeka_Db_Select */ public function getSelectForFind($recordId) { // Cast to integer to prevent SQL injection. $recordId = (int) $recordId; $select = $this->getSelect(); $select->where( $this->getTableAlias().'.id = ?', $recordId); $select->limit(1); $select->reset(Zend_Db_Select::ORDER); return $select; } /** * Apply a set of filters to a Select object based on the parameters given. * * By default, this simply checks the params for keys corresponding to database * column names. For more complex filtering (e.g., when other tables are involved), * or to use keys other than column names, override this method and optionally * call this parent method. * * @param Omeka_Db_Select $select * @param array $params */ public function applySearchFilters($select, $params) { $alias = $this->getTableAlias(); $columns = $this->getColumns(); foreach($columns as $column) { if(array_key_exists($column, $params)) { if (is_array($params[$column])) { $select->where("`$alias`.`$column` IN (?)", $params[$column]); } else { $select->where("`$alias`.`$column` = ?", $params[$column]); } } } } /** * Apply default column-based sorting for a table. * * @param Omeka_Db_Select $select * @param string $sortField Field to sort on. * @param string $sortDir Direction to sort. */ public function applySorting($select, $sortField, $sortDir) { if (empty($sortField) || empty($sortDir)) { return; } if (in_array($sortField, $this->getColumns())) { $alias = $this->getTableAlias(); $select->order("$alias.$sortField $sortDir"); } else if ($sortField == 'random') { $select->order('RAND()'); } } /** * Apply pagination to a select object via the LIMIT and OFFSET clauses. * * @param Zend_Db_Select $select * @param integer $limit Number of results per "page". * @param integer|null $page Page to retrieve, first if omitted. * @return Zend_Db_Select */ public function applyPagination($select, $limit, $page = null) { if ($page) { $select->limitPage($page, $limit); } else { $select->limit($limit); } return $select; } /** * Retrieve an object or set of objects based on an SQL WHERE predicate. * * @param string $sqlWhereClause * @param array $params optional Set of parameters to bind to the WHERE * clause. Used to prevent security flaws. * @param boolean $findOne optional Whether or not to retrieve a single * record or the whole set (retrieve all by default). * @return array|Omeka_Record_AbstractRecord|false */ public function findBySql($sqlWhereClause, array $params = array(), $findOne = false) { $select = $this->getSelect(); $select->where($sqlWhereClause); return $findOne ? $this->fetchObject($select, $params) : $this->fetchObjects($select, $params); } /** * Retrieve a count of all the rows in the table. * * @uses Omeka_Db_Table::getSelectForCount() * @param array $params optional Set of search filters upon which to base * the count. * @return integer */ public function count($params=array()) { $select = $this->getSelectForCount($params); return $this->getDb()->fetchOne($select); } /** * Check whether a row exists in the table. * * @param int $id * @return bool */ public function exists($id) { $alias = $this->getTableAlias(); $select = $this->getSelect() ->reset(Zend_Db_Select::COLUMNS) ->columns('id') ->where("`$alias`.`id` = ?", (int) $id) ->limit(1); return (bool) $this->getDb()->fetchOne($select); } /** * Apply a public/not public filter to the select object. * * A convenience function than derivative table classes may use while * applying search filters. * * @see self::applySearchFilters() * @param Omeka_Db_Select $select * @param bool $isPublic */ public function filterByPublic(Omeka_Db_Select $select, $isPublic) { $alias = $this->getTableAlias(); if ($isPublic) { $select->where("`$alias`.`public` = 1"); } else { $select->where("`$alias`.`public` = 0"); } } /** * Apply a featured/not featured filter to the select object. * * A convenience function than derivative table classes may use while * applying search filters. * * @see self::applySearchFilters() * @param Omeka_Db_Select $select * @param bool $isFeatured */ public function filterByFeatured(Omeka_Db_Select $select, $isFeatured) { $alias = $this->getTableAlias(); if ($isFeatured) { $select->where("`$alias`.`featured` = 1"); } else { $select->where("`$alias`.`featured` = 0"); } } /** * Apply a date since filter to the select object. * * A convenience function than derivative table classes may use while * applying search filters. * * @see self::applySearchFilters() * @param Omeka_Db_Select $select * @param string $dateSince ISO 8601 formatted date * @param string $dateField "added" or "modified" */ public function filterBySince(Omeka_Db_Select $select, $dateSince, $dateField) { // Reject invalid date fields. if (!in_array($dateField, array('added', 'modified'))) { return; } // Accept an ISO 8601 date, set the tiemzone to the server's default // timezone, and format the date to be MySQL timestamp compatible. $date = new Zend_Date($dateSince, Zend_Date::ISO_8601); $date->setTimezone(date_default_timezone_get()); $date = $date->get('yyyy-MM-dd HH:mm:ss'); // Select all dates that are greater than the passed date. $alias = $this->getTableAlias(); $select->where("`$alias`.`$dateField` > ?", $date); } /** * Apply a user filter to the select object. * * A convenience function than derivative table classes may use while * applying search filters. * * @see self::applySearchFilters() * @param Omeka_Db_Select $select * @param int $userId */ public function filterByUser(Omeka_Db_Select $select, $userId, $userField) { // Reject invalid user ID fields. if (!in_array($userField, array('owner_id', 'user_id'))) { return; } $alias = $this->getTableAlias(); $select->where("`$alias`.`$userField` = ?", $userId); } /** * Filter returned records by ID. * * Can specify a range of valid record IDs or an individual ID * * @version 2.2.2 * @param Omeka_Db_Select $select * @param string $range Example: 1-4, 75, 89 * @return void */ public function filterByRange($select, $range) { // Comma-separated expressions should be treated individually $exprs = explode(',', $range); // Construct a SQL clause where every entry in this array is linked by 'OR' $wheres = array(); $alias = $this->getTableAlias(); foreach ($exprs as $expr) { // If it has a '-' in it, it is a range of item IDs. Otherwise it is // a single item ID if (strpos($expr, '-') !== false) { list($start, $finish) = explode('-', $expr); // Naughty naughty koolaid, no SQL injection for you $start = (int) trim($start); $finish = (int) trim($finish); $wheres[] = "($alias.id BETWEEN $start AND $finish)"; //It is a single item ID } else { $id = (int) trim($expr); $wheres[] = "($alias.id = $id)"; } } $where = join(' OR ', $wheres); $select->where('('.$where.')'); } /** * Retrieve a select object used to retrieve a count of all the table rows. * * @param array $params optional Set of search filters. * @return Omeka_Db_Select */ public function getSelectForCount($params = array()) { $select = $params ? $this->getSelectForFindBy($params) : $this->getSelect(); // Make sure the SELECT only pulls down the COUNT() column. $select->reset(Zend_Db_Select::COLUMNS); $alias = $this->getTableAlias(); $select->from(array(), "COUNT(DISTINCT($alias.id))"); // Reset the GROUP and ORDER BY clauses if necessary. $select->reset(Zend_Db_Select::ORDER)->reset(Zend_Db_Select::GROUP); // Reset the LIMIT and OFFSET clauses if necessary. $select->reset(Zend_Db_Select::LIMIT_COUNT)->reset(Zend_Db_Select::LIMIT_OFFSET); return $select; } /** * Check whether a given row exists in the database. * * Currently used to verify that a row exists even though the current user * may not have permissions to access it. * * @param int $id The ID of the row. * @return boolean */ public function checkExists($id) { $alias = $this->getTableAlias(); $select = $this->getSelectForCount()->where("$alias.id = ?", $id); $count = $this->getDb()->fetchOne($select); return ($count == 1); } /** * Retrieve a set of record objects based on an SQL SELECT statement. * * @param string $sql This could be either a string or any object that can * be cast to a string (commonly Omeka_Db_Select). * @param array $params Set of parameters to bind to the SQL statement. * @return array|null Set of Omeka_Record_AbstractRecord instances, or null * if none can be found. */ public function fetchObjects($sql, $params=array()) { $res = $this->getDb()->query($sql, $params); $data = $res->fetchAll(); // Would use fetchAll() but it can be memory-intensive. $objs = array(); foreach ($data as $k => $row) { $objs[$k] = $this->recordFromData($row); } return $objs; } /** * Retrieve a single record object from the database. * * @see Omeka_Db_Table::fetchObjects() * @param string $sql * @param string $params Parameters to substitute into SQL query. * @return Omeka_Record_AbstractRecord or null if no record */ public function fetchObject($sql, array $params=array()) { $row = $this->getDb()->fetchRow($sql, $params); return !empty($row) ? $this->recordFromData($row): null; } /** * Populate a record object with data retrieved from the database. * * @param array $data A keyed array representing a row from the database. * @return Omeka_Record_AbstractRecord */ protected function recordFromData(array $data) { $class = $this->_target; $obj = new $class($this->_db); $obj->setArray($data); return $obj; } /** * Get and parse sorting parameters to pass to applySorting. * * A sorting direction of 'ASC' will be used if no direction parameter is * passed. * * @param array $params * @return array|null Array of sort field, sort dir if params exist, null * otherwise. */ private function _getSortParams($params) { if (array_key_exists(self::SORT_PARAM, $params)) { $sortField = trim($params[self::SORT_PARAM]); $dir = 'ASC'; // Default to ascending sort with no dir param. if (array_key_exists(self::SORT_DIR_PARAM, $params)) { $sortDir = trim($params[self::SORT_DIR_PARAM]); if ($sortDir === 'a') { $dir = 'ASC'; } else if ($sortDir === 'd') { $dir = 'DESC'; } } return array($sortField, $dir); } return null; } /** * Get the name for a model-specific hook or filter.. * * @param string $suffix The hook-specific part of the hook name. * @return string */ private function _getHookName($suffix) { $modelName = Inflector::tableize($this->_target); return "{$modelName}_{$suffix}"; } }
{ "content_hash": "3595407eb64a65d8b3bb7a2c1c8b17cc", "timestamp": "", "source": "github", "line_count": 723, "max_line_length": 152, "avg_line_length": 31.02213001383126, "alnum_prop": 0.5583396495608364, "repo_name": "jbfink/docker-omeka", "id": "eaf55ed09d1f9d914b4ed276b47b044dcf0a70f5", "size": "22593", "binary": false, "copies": "48", "ref": "refs/heads/master", "path": "omeka/omeka-2.4.1/application/libraries/Omeka/Db/Table.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1702" }, { "name": "Batchfile", "bytes": "1036" }, { "name": "CSS", "bytes": "353082" }, { "name": "HTML", "bytes": "4259" }, { "name": "JavaScript", "bytes": "82133" }, { "name": "PHP", "bytes": "19884720" }, { "name": "PowerShell", "bytes": "1028" }, { "name": "Shell", "bytes": "727" }, { "name": "XSLT", "bytes": "6298" } ], "symlink_target": "" }
<?xml version="1.0" ?> <LEOSimulation version="2.5.0"> <STELAVersion>2.5.1</STELAVersion> <SpaceObject> <mass unit="kg">10.0</mass> <dragArea>0.015</dragArea> <reflectingArea>0.06</reflectingArea> <reflectivityCoefficient>1.5</reflectivityCoefficient> <orbitType>LEO</orbitType> <ConstantDragCoef> <cstDragCoef>2.1</cstDragCoef> </ConstantDragCoef> <name>PFO5YOP5</name> </SpaceObject> <EphemerisManager version="2.5.0"> <initState> <bulletin version="2.5.0"> <date>2014-07-14T15:08:35.000</date> <Type2PosVel> <frame>CELESTIAL_MEAN_OF_DATE</frame> <nature>MEAN</nature> <semiMajorAxis unit="m">7000000.0</semiMajorAxis> <eccentricity>0.001</eccentricity> <inclination unit="rad">1.71914931321</inclination> <rAAN unit="rad">0.0</rAAN> <argOfPerigee unit="rad">0.0</argOfPerigee> <meanAnomaly unit="rad">0.0</meanAnomaly> </Type2PosVel> </bulletin> </initState> <finalState/> </EphemerisManager> <author>CNES</author> <comment>LEO example simulation</comment> <simulationDuration unit="years">100.0</simulationDuration> <ephemerisStep unit="s">86400.0</ephemerisStep> <ttMinusUT1 unit="s">67.184</ttMinusUT1> <srpSwitch>true</srpSwitch> <sunSwitch>true</sunSwitch> <moonSwitch>true</moonSwitch> <warningFlag>false</warningFlag> <iterativeMode>false</iterativeMode> <modelType>GTO</modelType> <atmosModel>NRLMSISE-00</atmosModel> <VariableSolarActivity> <solActType>VARIABLE</solActType> </VariableSolarActivity> <integrationStep unit="s">86400.0</integrationStep> <dragSwitch>true</dragSwitch> <dragQuadPoints>33</dragQuadPoints> <atmosDragRecomputeStep>1</atmosDragRecomputeStep> <srpQuadPoints>11</srpQuadPoints> <reentryAltitude unit="m">120000.0</reentryAltitude> <iterationData> <funcValueAccuracy unit="days">10</funcValueAccuracy> <expDuration unit="years">24.75</expDuration> <simMinusExpDuration unit="years">75.25</simMinusExpDuration> <iterationMethod>FrozenOrbit</iterationMethod> </iterationData> <nbIntegrationStepTesseral>5</nbIntegrationStepTesseral> <zonalOrder>7</zonalOrder> </LEOSimulation>
{ "content_hash": "d855fba1d801b93c535302bfdaee291a", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 65, "avg_line_length": 36.37096774193548, "alnum_prop": 0.6988913525498891, "repo_name": "pouyana/satgen", "id": "e7b2106647929f5093420f8f26fd2671024bb336", "size": "2255", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sim/PFO5YOP5_a_sim.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "552816" }, { "name": "Matlab", "bytes": "1015" }, { "name": "Python", "bytes": "227028" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/fx_icon_add_pressed" android:state_pressed="true"/> <item android:drawable="@drawable/fx_icon_add_normal"/> </selector>
{ "content_hash": "2f1ba412828c9a90eaf276583d18d180", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 89, "avg_line_length": 38.857142857142854, "alnum_prop": 0.7132352941176471, "repo_name": "cowthan/Ayo2022", "id": "232d56812ce6e37df75fd2f438cf7fe6fabbc4d6", "size": "272", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ProjWechat/res/drawable/fx_main_activity_add.xml", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "5114" }, { "name": "HTML", "bytes": "2365" }, { "name": "Java", "bytes": "9575777" }, { "name": "JavaScript", "bytes": "27653" }, { "name": "Makefile", "bytes": "891" } ], "symlink_target": "" }
package cn.wz.algorithm.stdlib; /************************************************************************* * Compilation: javac BinaryIn.java * Execution: java BinaryIn input output * * This library is for reading binary data from an input stream. * * % java BinaryIn http://introcs.cs.princeton.edu/cover.jpg output.jpg * *************************************************************************/ import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.URL; import java.net.URLConnection; /** * <i>Binary input</i>. This class provides methods for reading * in bits from a binary input stream, either * one bit at a time (as a <tt>boolean</tt>), * 8 bits at a time (as a <tt>byte</tt> or <tt>char</tt>), * 16 bits at a time (as a <tt>short</tt>), * 32 bits at a time (as an <tt>int</tt> or <tt>float</tt>), or * 64 bits at a time (as a <tt>double</tt> or <tt>long</tt>). * <p> * The binary input stream can be from standard input, a filename, * a URL name, a Socket, or an InputStream. * <p> * All primitive types are assumed to be represented using their * standard Java representations, in big-endian (most significant * byte first) order. * <p> * The client should not intermix calls to <tt>BinaryIn</tt> with calls * to <tt>In</tt>; otherwise unexpected behavior will result. */ public final class BinaryIn { private static final int EOF = -1; // end of file private BufferedInputStream in; // the input stream private int buffer; // one character buffer private int N; // number of bits left in buffer /** * Create a binary input stream from standard input. */ public BinaryIn() { in = new BufferedInputStream(System.in); fillBuffer(); } /** * Create a binary input stream from an InputStream. */ public BinaryIn(InputStream is) { in = new BufferedInputStream(is); fillBuffer(); } /** * Create a binary input stream from a socket. */ public BinaryIn(Socket socket) { try { InputStream is = socket.getInputStream(); in = new BufferedInputStream(is); fillBuffer(); } catch (IOException ioe) { System.err.println("Could not open " + socket); } } /** * Create a binary input stream from a URL. */ public BinaryIn(URL url) { try { URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); in = new BufferedInputStream(is); fillBuffer(); } catch (IOException ioe) { System.err.println("Could not open " + url); } } /** * Create a binary input stream from a filename or URL name. */ public BinaryIn(String s) { try { // first try to read file from local file system File file = new File(s); if (file.exists()) { FileInputStream fis = new FileInputStream(file); in = new BufferedInputStream(fis); fillBuffer(); return; } // next try for files included in jar URL url = getClass().getResource(s); // or URL from web if (url == null) { url = new URL(s); } URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); in = new BufferedInputStream(is); fillBuffer(); } catch (IOException ioe) { System.err.println("Could not open " + s); } } private void fillBuffer() { try { buffer = in.read(); N = 8; } catch (IOException e) { System.err.println("EOF"); buffer = EOF; N = -1; } } /** * Does the binary input stream exist? */ public boolean exists() { return in != null; } /** * Returns true if the binary input stream is empty. * @return true if and only if the binary input stream is empty */ public boolean isEmpty() { return buffer == EOF; } /** * Read the next bit of data from the binary input stream and return as a boolean. * @return the next bit of data from the binary input stream as a <tt>boolean</tt> * @throws RuntimeException if the input stream is empty */ public boolean readBoolean() { if (isEmpty()) throw new RuntimeException("Reading from empty input stream"); N--; boolean bit = ((buffer >> N) & 1) == 1; if (N == 0) fillBuffer(); return bit; } /** * Read the next 8 bits from the binary input stream and return as an 8-bit char. * @return the next 8 bits of data from the binary input stream as a <tt>char</tt> * @throws RuntimeException if there are fewer than 8 bits available */ public char readChar() { if (isEmpty()) throw new RuntimeException("Reading from empty input stream"); // special case when aligned byte if (N == 8) { int x = buffer; fillBuffer(); return (char) (x & 0xff); } // combine last N bits of current buffer with first 8-N bits of new buffer int x = buffer; x <<= (8-N); int oldN = N; fillBuffer(); if (isEmpty()) throw new RuntimeException("Reading from empty input stream"); N = oldN; x |= (buffer >>> N); return (char) (x & 0xff); // the above code doesn't quite work for the last character if N = 8 // because buffer will be -1 } /** * Read the next r bits from the binary input stream and return as an r-bit character. * @param r number of bits to read. * @return the next r bits of data from the binary input streamt as a <tt>char</tt> * @throws RuntimeException if there are fewer than r bits available */ public char readChar(int r) { if (r < 1 || r > 16) throw new RuntimeException("Illegal value of r = " + r); // optimize r = 8 case if (r == 8) return readChar(); char x = 0; for (int i = 0; i < r; i++) { x <<= 1; boolean bit = readBoolean(); if (bit) x |= 1; } return x; } /** * Read the remaining bytes of data from the binary input stream and return as a string. * @return the remaining bytes of data from the binary input stream as a <tt>String</tt> * @throws RuntimeException if the input stream is empty or if the number of bits * available is not a multiple of 8 (byte-aligned) */ public String readString() { if (isEmpty()) throw new RuntimeException("Reading from empty input stream"); StringBuilder sb = new StringBuilder(); while (!isEmpty()) { char c = readChar(); sb.append(c); } return sb.toString(); } /** * Read the next 16 bits from the binary input stream and return as a 16-bit short. * @return the next 16 bits of data from the binary standard input as a <tt>short</tt> * @throws RuntimeException if there are fewer than 16 bits available */ public short readShort() { short x = 0; for (int i = 0; i < 2; i++) { char c = readChar(); x <<= 8; x |= c; } return x; } /** * Read the next 32 bits from the binary input stream and return as a 32-bit int. * @return the next 32 bits of data from the binary input stream as a <tt>int</tt> * @throws RuntimeException if there are fewer than 32 bits available */ public int readInt() { int x = 0; for (int i = 0; i < 4; i++) { char c = readChar(); x <<= 8; x |= c; } return x; } /** * Read the next r bits from the binary input stream return as an r-bit int. * @param r number of bits to read. * @return the next r bits of data from the binary input stream as a <tt>int</tt> * @throws RuntimeException if there are fewer than r bits available on standard input */ public int readInt(int r) { if (r < 1 || r > 32) throw new RuntimeException("Illegal value of r = " + r); // optimize r = 32 case if (r == 32) return readInt(); int x = 0; for (int i = 0; i < r; i++) { x <<= 1; boolean bit = readBoolean(); if (bit) x |= 1; } return x; } /** * Read the next 64 bits from the binary input stream and return as a 64-bit long. * @return the next 64 bits of data from the binary input stream as a <tt>long</tt> * @throws RuntimeException if there are fewer than 64 bits available */ public long readLong() { long x = 0; for (int i = 0; i < 8; i++) { char c = readChar(); x <<= 8; x |= c; } return x; } /** * Read the next 64 bits from the binary input stream and return as a 64-bit double. * @return the next 64 bits of data from the binary input stream as a <tt>double</tt> * @throws RuntimeException if there are fewer than 64 bits available */ public double readDouble() { return Double.longBitsToDouble(readLong()); } /** * Read the next 32 bits from standard input and return as a 32-bit float. * @return the next 32 bits of data from standard input as a <tt>float</tt> * @throws RuntimeException if there are fewer than 32 bits available on standard input */ public float readFloat() { return Float.intBitsToFloat(readInt()); } /** * Read the next 8 bits from the binary input stream and return as an 8-bit byte. * @return the next 8 bits of data from the binary input stream as a <tt>byte</tt> * @throws RuntimeException if there are fewer than 8 bits available */ public byte readByte() { char c = readChar(); byte x = (byte) (c & 0xff); return x; } /** * Test client. Reads in the name of a file or url (first command-line * argument) and writes it to a file (second command-line argument). */ public static void main(String[] args) { BinaryIn in = new BinaryIn(args[0]); BinaryOut out = new BinaryOut(args[1]); // read one 8-bit char at a time while (!in.isEmpty()) { char c = in.readChar(); out.write(c); } out.flush(); } }
{ "content_hash": "0ce8a3e3f11217044e242a1df2a47bcc", "timestamp": "", "source": "github", "line_count": 336, "max_line_length": 106, "avg_line_length": 32.083333333333336, "alnum_prop": 0.5605751391465678, "repo_name": "wz12406/accumulate", "id": "bf5b1a0fbaaeb7eda3e4cb296cebf55e0085864e", "size": "10780", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "algorithm/src/main/java/cn/wz/algorithm/stdlib/BinaryIn.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1857171" } ], "symlink_target": "" }
using System; using HaloSharp.Converter; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace HaloSharp.Model.HaloWars2.Stats.CarnageReport.Events { [Serializable] public class MatchEvent : IEquatable<MatchEvent> { [JsonProperty(PropertyName = "EventName")] [JsonConverter(typeof(StringEnumConverter))] public Enumeration.HaloWars2.MatchEventType MatchEventType { get; set; } [JsonProperty(PropertyName = "TimeSinceStartMilliseconds")] [JsonConverter(typeof(MillisecondConverter))] public TimeSpan TimeSinceStart { get; set; } public bool Equals(MatchEvent other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return MatchEventType == other.MatchEventType && TimeSinceStart.Equals(other.TimeSinceStart); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != typeof(MatchEvent)) { return false; } return Equals((MatchEvent) obj); } public override int GetHashCode() { unchecked { return ((int) MatchEventType*397) ^ TimeSinceStart.GetHashCode(); } } public static bool operator ==(MatchEvent left, MatchEvent right) { return Equals(left, right); } public static bool operator !=(MatchEvent left, MatchEvent right) { return !Equals(left, right); } } }
{ "content_hash": "02ed927e23ffcf1dcd8c41da2b78dcca", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 81, "avg_line_length": 26.08219178082192, "alnum_prop": 0.5404411764705882, "repo_name": "gitFurious/HaloSharp", "id": "55c60c391ee97c5f33fea16e96c6d463cb3e11c5", "size": "1904", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/HaloSharp/Model/HaloWars2/Stats/CarnageReport/Events/MatchEvent.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1038259" } ], "symlink_target": "" }
import { Box, Separator, Serif } from "@artsy/palette" import { Register_me } from "v2/__generated__/Register_me.graphql" import { Register_sale } from "v2/__generated__/Register_sale.graphql" import { RegisterCreateBidderMutation, RegisterCreateBidderMutationResponse, } from "v2/__generated__/RegisterCreateBidderMutation.graphql" import { createCreditCardAndUpdatePhone } from "v2/Apps/Auction/Operations/CreateCreditCardAndUpdatePhone" import { RegistrationForm } from "v2/Apps/Auction/Components/RegistrationForm" import { AppContainer } from "v2/Apps/Components/AppContainer" import { track } from "v2/Artsy" import * as Schema from "v2/Artsy/Analytics/Schema" import React, { ComponentProps } from "react" import { Title } from "react-head" import { RelayProp, commitMutation, createFragmentContainer, graphql, } from "react-relay" import { TrackingProp } from "react-tracking" import { bidderNeedsIdentityVerification } from "v2/Utils/identityVerificationRequirements" import createLogger from "v2/Utils/logger" import { createStripeWrapper, errorMessageForCard, saleConfirmRegistrationPath, toStripeAddress, } from "v2/Apps/Auction/Components/Form" import { ReactStripeElements } from "react-stripe-elements" const logger = createLogger("Apps/Auction/Routes/Register") function createBidder( relayEnvironment: RelayProp["environment"], saleID: string ) { return new Promise<RegisterCreateBidderMutationResponse>( (resolve, reject) => { commitMutation<RegisterCreateBidderMutation>(relayEnvironment, { onCompleted: resolve, onError: reject, // TODO: Inputs to the mutation might have changed case of the keys! mutation: graphql` mutation RegisterCreateBidderMutation($input: CreateBidderInput!) { createBidder(input: $input) { bidder { internalID } } } `, variables: { input: { saleID }, }, }) } ) } type OnSubmitType = ComponentProps<typeof RegistrationForm>["onSubmit"] type FormikHelpers = Parameters<OnSubmitType>[1] interface RegisterProps extends ReactStripeElements.InjectedStripeProps { sale: Register_sale me: Register_me relay: RelayProp tracking: TrackingProp } export const RegisterRoute: React.FC<RegisterProps> = props => { const { me, relay, sale, tracking, stripe } = props const { environment } = relay const commonProperties = { auction_slug: sale.slug, auction_state: sale.status, sale_id: sale.internalID, user_id: me.internalID, } function trackRegistrationFailed(errors: string[]) { tracking.trackEvent({ action_type: Schema.ActionType.RegistrationSubmitFailed, error_messages: errors, ...commonProperties, }) } function trackRegistrationSuccess(bidderId: string) { tracking.trackEvent({ action_type: Schema.ActionType.RegistrationSubmitted, bidder_id: bidderId, ...commonProperties, }) } function handleMutationError(helpers: FormikHelpers, error: Error) { logger.error(error) let errorMessages: string[] if (Array.isArray(error)) { errorMessages = error.map(e => e.message) } else if (typeof error === "string") { errorMessages = [error] } else if (error.message) { errorMessages = [error.message] } trackRegistrationFailed(errorMessages) helpers.setStatus("submissionFailed") } const createTokenAndSubmit: OnSubmitType = async (values, helpers) => { // FIXME: workaround for Formik calling `setSubmitting(false)` when the // `onSubmit` function does not block. setTimeout(() => helpers.setSubmitting(true), 0) const address = toStripeAddress(values.address) const { phoneNumber } = values.address const { setFieldError, setSubmitting } = helpers try { const { error, token } = await stripe.createToken(address) if (error) { setFieldError("creditCard", error.message) return } const { id } = token const { createCreditCard: { creditCardOrError }, } = await createCreditCardAndUpdatePhone(environment, phoneNumber, id) // TODO: We are not handling errors for `updateMyUserProfile`. Should we? if (creditCardOrError.mutationError) { setFieldError( "creditCard", errorMessageForCard(creditCardOrError.mutationError.detail) ) return } const data = await createBidder(environment, sale.internalID) trackRegistrationSuccess(data.createBidder.bidder.internalID) window.location.assign(saleConfirmRegistrationPath(sale.slug)) } catch (error) { handleMutationError(helpers, error) } finally { setSubmitting(false) } } return ( <AppContainer> <Title>Auction Registration</Title> <Box maxWidth={550} px={[2, 0]} mx="auto" mt={[1, 0]} mb={[1, 100]}> <Serif size="10">Register to Bid on Artsy</Serif> <Separator mt={1} mb={2} /> <RegistrationForm onSubmit={createTokenAndSubmit} trackSubmissionErrors={trackRegistrationFailed} needsIdentityVerification={bidderNeedsIdentityVerification({ sale, user: me, })} /> </Box> </AppContainer> ) } const StripeWrappedRegisterRoute = createStripeWrapper(RegisterRoute) const TrackingWrappedRegisterRoute = track({ context_page: Schema.PageName.AuctionRegistrationPage, })(StripeWrappedRegisterRoute) export const RegisterRouteFragmentContainer = createFragmentContainer( TrackingWrappedRegisterRoute, { sale: graphql` fragment Register_sale on Sale { slug internalID status requireIdentityVerification } `, me: graphql` fragment Register_me on Me { internalID identityVerified } `, } ) // For bundle splitting in router export default RegisterRouteFragmentContainer
{ "content_hash": "32e80823a219d1b929648cc9948e64df", "timestamp": "", "source": "github", "line_count": 203, "max_line_length": 106, "avg_line_length": 29.635467980295566, "alnum_prop": 0.6831781914893617, "repo_name": "eessex/force", "id": "ccaee5b0e3d56c5657c1a60065d6da2dbb2ff0cc", "size": "6016", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/v2/Apps/Auction/Routes/Register/index.tsx", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "588457" }, { "name": "CoffeeScript", "bytes": "2691954" }, { "name": "Dockerfile", "bytes": "722" }, { "name": "HTML", "bytes": "531992" }, { "name": "JavaScript", "bytes": "703309" }, { "name": "Shell", "bytes": "9877" }, { "name": "TypeScript", "bytes": "332873" } ], "symlink_target": "" }
package net.onrc.openvirtex.api.server; import javax.management.remote.JMXPrincipal; import javax.security.auth.Subject; import org.eclipse.jetty.security.DefaultIdentityService; import org.eclipse.jetty.security.DefaultUserIdentity; import org.eclipse.jetty.security.IdentityService; import org.eclipse.jetty.security.LoginService; import org.eclipse.jetty.server.Authentication; import org.eclipse.jetty.server.UserIdentity; import org.eclipse.jetty.server.UserIdentity.Scope; public class OVXLoginService implements LoginService { private final IdentityService identityService = new DefaultIdentityService(); @Override public IdentityService getIdentityService() { return this.identityService; } @Override public String getName() { return JettyServer.REALM_NAME; } @Override public UserIdentity login(final String username, final Object credentials) { return new OpenVirteXAuthenticatedUser(username, (String) credentials) .getUserIdentity(); } @Override public void logout(final UserIdentity arg0) { } @Override public void setIdentityService(final IdentityService arg0) { } @Override public boolean validate(final UserIdentity arg0) { return false; } public class OpenVirteXAuthenticatedUser implements Authentication.User { private final String user; @SuppressWarnings("unused") private final String password; public OpenVirteXAuthenticatedUser(final String username, final String password) { this.user = username; this.password = password; } @Override public String getAuthMethod() { return "BASIC"; } @Override public UserIdentity getUserIdentity() { // TODO: need to return the correct identity for this user. // Permitting specific logins for now with no passwords if (this.user.equals("tenant")) { return new DefaultUserIdentity(new Subject(), new JMXPrincipal( this.user), new String[] { "user" }); } else if (this.user.equals("ui")) { return new DefaultUserIdentity(new Subject(), new JMXPrincipal( this.user), new String[] { "ui" }); } else if (this.user.equals("admin")) { return new DefaultUserIdentity(new Subject(), new JMXPrincipal( this.user), new String[] { "user", "admin", "ui" }); } else { return null; } } @Override public boolean isUserInRole(final Scope scope, final String role) { System.out.println("role " + role); return true; } @Override public void logout() { // TODO: remove any acquired tokens. } } }
{ "content_hash": "3565b08b7c7afb04b185078fc5570908", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 78, "avg_line_length": 25.282828282828284, "alnum_prop": 0.7351178585697163, "repo_name": "fnkhan/second", "id": "01c02a7dd721fc8d1ff8d66780d5e1b5b6a8c927", "size": "3268", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/net/onrc/openvirtex/api/server/OVXLoginService.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>censored.coffee</title> <link href='http://fonts.googleapis.com/css?family=Signika+Negative:300,400' rel='stylesheet' type='text/css'> <link href="stylesheets/reset.css" rel="stylesheet" /> <link href="stylesheets/main.css" rel="stylesheet" /> <link href="../src/censored.css" rel="stylesheet" /> </head> <body> <a href="https://github.com/lrbecker"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"></a> <div class="content"> <h1>censored.coffee</h1> <blockquote> censored.coffee acts as a stylistic bridge to clean up your profanity, powered only by a simple set of rules you define. </blockquote> <div class="examples"> <div class="example example-1"> <div class="column copy"> <h2>Most Basic</h2> <p>This example uses the most basic buttbread usage of the plugin.</p> <code>$('.example p').censor(['buttbread'])</code> </div> <div class="column config-list"> <h2>Censored:</h2> <ol> <li>buttbread</li> </ol> </div> </div> <hr/> <div class="example example-2"> <div class="column copy"> <h2>Replace censored words with custom word</h2> <p>By default <strong>censored.coffee</strong> will preserve the rumply word that was censored and just use <em>css</em> to visually hide it, but if you would like to completely replace the offending words you the <strong>replaceWord</strong> option.</p> <code>$('.example p').censor(['rumply'], {replaceWord: 'unicorns'})</code> </div> <div class="column config-list"> <h2>Censored:</h2> <ol> <li>rumply</li> </ol> <h2>Options</h2> <ol> <li>replaceWord: 'unicorns'</li> </ol> </div> </div> <hr/> <div class="example example-3"> <div class="column copy"> <h2>Capital Offense</h2> <p>For those who find BUTT offensive, but butt totally cool. Set <strong>caseSensitive</strong> to true.</p> <code>$('.example p').censor(['BUTT'], {caseSensitive: true})</code> </div> <div class="column config-list"> <h2>Censored:</h2> <ol> <li>BUTT</li> </ol> <h2>Options</h2> <ol> <li>caseSensitive: true</li> </ol> </div> </div> </div> </div> <div class="footer"> <p>Copyright &copy; Lance Becker - Licensed under the <a href="http://opensource.org/licenses/MIT">MIT License</a>.</p> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="../src/censored.min.js"></script> <script type="text/javascript"> $('.example-1 p').censor(['buttbread']); $('.example-2 p').censor(['rumply'], {replaceWord: 'unicorns'}); $('.example-3 p').censor(['BUTT'], {caseSensitive: true}); </script> </body> </html>
{ "content_hash": "5e93937016ed2787c10c7817fc9ae08d", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 264, "avg_line_length": 33.329896907216494, "alnum_prop": 0.5716053201360966, "repo_name": "lrbecker/censored.coffee", "id": "6dfc14cdcd6a9ed80dffdd9fadc28fccc9c24d0c", "size": "3233", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demo/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "723" } ], "symlink_target": "" }
module InstanceAgent module CodeDeployPlugin module ApplicationSpecification #Helper Class for storing data parsed from permissions list class LinuxPermissionInfo attr_reader :object, :pattern, :except, :type, :owner, :group, :mode, :acls, :context def initialize(object, opts = {}) object = object.to_s if (object.empty?) raise AppSpecValidationException, 'Permission needs a object value' end @object = object @pattern = opts[:pattern] || "**" @except = opts[:except] || [] @type = opts[:type] || ["file", "directory"] @owner = opts[:owner] @group = opts[:group] @mode = opts[:mode] @acls = opts[:acls] @context = opts[:context] end def validate_file_permission() if @type.include?("file") if !"**".eql?(@pattern) raise AppSpecValidationException, "Attempt to use pattern #{@pattern} when assigning permissions to file #{@object}" end if !@except.empty? raise AppSpecValidationException, "Attempt to use except #{@except} when assigning permissions to file #{@object}" end end end def validate_file_acl(object) if !@acls.nil? default_acl = @acls.get_default_ace if !default_acl.nil? raise "Attempt to set default acl #{default_acl} on file #{object}" end end end def matches_pattern?(name) name = name.chomp(File::SEPARATOR) base_object = sanitize_dir_path(@object) if !base_object.end_with?(File::SEPARATOR) base_object = base_object + File::SEPARATOR end if name.start_with?(base_object) if ("**".eql?(@pattern)) return true end rel_name = name[base_object.length..name.length] return matches_simple_glob(rel_name, @pattern) end false end def matches_except?(name) name = name.chomp(File::SEPARATOR) base_object = sanitize_dir_path(@object) if !base_object.end_with?(File::SEPARATOR) base_object = base_object + File::SEPARATOR end if name.start_with?(base_object) rel_name = name[base_object.length..name.length] @except.each do |item| if matches_simple_glob(rel_name, item) return true end end end false end private def matches_simple_glob(name, pattern) if name.include?(File::SEPARATOR) return false end options = expand(pattern.chars.entries) name.chars.each do |char| new_options = [] options.each do |option| if option[0].eql?("*") new_options.concat(expand(option)) elsif option[0].eql?(char) option.shift new_options.concat(expand(option)) end end options = new_options if (options.include?(["*"])) return true end end options.include?([]) end private def expand(option) previous_option = nil while "*".eql?(option[0]) do previous_option = Array.new(option) option.shift end previous_option.nil? ? [option] : [previous_option, option] end private def sanitize_dir_path(path) File.expand_path(path) end end end end end
{ "content_hash": "2f80fb9e72c30258bce951e4072634e6", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 130, "avg_line_length": 31.049586776859503, "alnum_prop": 0.5190311418685121, "repo_name": "fairfaxmedia/aws-codedeploy-agent", "id": "29482ad7cf13985f74578128252b414b0c5d48ef", "size": "3757", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/instance_agent/codedeploy_plugin/application_specification/linux_permission_info.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "278058" }, { "name": "Shell", "bytes": "1844" } ], "symlink_target": "" }
/* Design a class named MyDate. The class contains: - The data fields year, month, and day that represent a date. month is 0-based, i.e 0 is for January. - A no-arg constructor that creates a MyDate object for the current date. - A constructor that constructs a MyDate object with a specified elapsed time since midnight, January 1, 1970, in milliseconds. - A constructor that constructs a MyDate object with the specified year, month, and day. - Three getter methods for the data fields year, month, and day, respectively. - A method named setDate(long elapsedTime) that sets a new date for the object using the elapsed time. Write a test program that creates two MyDate objects (using new MyDate() and new MyDate(34355555133101L)) and displays their year, month, and day. */ public class E10_14 { public static void main(String[] args) { MyDate m1 = new MyDate(); MyDate m2 = new MyDate(34355555133101L); System.out.println("m1: " + m1); System.out.println("m2: " + m2); } }
{ "content_hash": "3a89e6dd9b7742f7cc405d2e3fdf634a", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 80, "avg_line_length": 37, "alnum_prop": 0.7113899613899614, "repo_name": "maxalthoff/intro-to-java-exercises", "id": "d58ba452308973bad18a1d1e682bc4ae8e070c7a", "size": "1036", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "10/E10_14/E10_14.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1663373" } ], "symlink_target": "" }
package it.alidays.mapengine.configuration; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "configuration") public class Configuration { private Persistence persistence; private List<DatabaseTypeConverter> databaseTypeConverters; private List<FetchFunction> fetchFunctions; @XmlElement(name = "persistence", required = true) public Persistence getPersistence() { return this.persistence; } public void setPersistence(Persistence persistence) { this.persistence = persistence; } @XmlElementWrapper(name = "database-type-converters", required = true) @XmlElement(name = "database-type-converter", required = true) public List<DatabaseTypeConverter> getDatabaseTypeConverters() { return this.databaseTypeConverters; } public void setDatabaseTypeConverters(List<DatabaseTypeConverter> databaseTypeConverters) { this.databaseTypeConverters = databaseTypeConverters; } @XmlElementWrapper(name = "fetch-functions", required = true) @XmlElement(name = "fetch-function", required = true) public List<FetchFunction> getFetchFunctions() { return this.fetchFunctions; } public void setFetchFunctions(List<FetchFunction> fetchFunctions) { this.fetchFunctions = fetchFunctions; } }
{ "content_hash": "511e73b33d64f63e13fc3c2eb00fde5b", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 92, "avg_line_length": 30.52173913043478, "alnum_prop": 0.7678062678062678, "repo_name": "vincenzomazzeo/map-engine", "id": "9d393d9934355664b2b440505df62c371582b366", "size": "2019", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/it/alidays/mapengine/configuration/Configuration.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "111703" } ], "symlink_target": "" }
/** * Teensylu 0.7 pin assignments (AT90USB1286) * Requires the Teensyduino software with Teensy++ 2.0 selected in Arduino IDE! * http://www.pjrc.com/teensy/teensyduino.html * See http://reprap.org/wiki/Printrboard for more info */ #ifndef __AVR_AT90USB1286__ #error "Oops! Make sure you have 'Teensy++ 2.0' selected from the 'Tools -> Boards' menu." #endif #if ENABLED(AT90USBxx_TEENSYPP_ASSIGNMENTS) // use Teensyduino Teensy++2.0 pin assignments instead of Marlin traditional. #error "These Teensylu assignments depend on traditional Marlin assignments, not AT90USBxx_TEENSYPP_ASSIGNMENTS in fastio.h" #endif #define BOARD_NAME "Teensylu" #define USBCON 1286 // Disable MarlinSerial etc. #define LARGE_FLASH true // // Limit Switches // #define X_STOP_PIN 13 #define Y_STOP_PIN 14 #define Z_STOP_PIN 15 // // Steppers // #define X_STEP_PIN 0 #define X_DIR_PIN 1 #define X_ENABLE_PIN 39 #define Y_STEP_PIN 2 #define Y_DIR_PIN 3 #define Y_ENABLE_PIN 38 #define Z_STEP_PIN 4 #define Z_DIR_PIN 5 #define Z_ENABLE_PIN 23 #define E0_STEP_PIN 6 #define E0_DIR_PIN 7 #define E0_ENABLE_PIN 19 // // Temperature Sensors // #define TEMP_0_PIN 7 // Analog Input (Extruder) #define TEMP_BED_PIN 6 // Analog Input (Bed) // // Heaters / Fans // #define HEATER_0_PIN 21 // Extruder #define HEATER_1_PIN 46 #define HEATER_2_PIN 47 #define HEATER_BED_PIN 20 // If soft or fast PWM is off then use Teensyduino pin numbering, Marlin // fastio pin numbering otherwise #if ENABLED(FAN_SOFT_PWM) || ENABLED(FAST_PWM_FAN) #define FAN_PIN 22 #else #define FAN_PIN 16 #endif // // Misc. Functions // #define SDSS 8 // // LCD / Controller // #if ENABLED(ULTRA_LCD) && ENABLED(NEWPANEL) #define BEEPER_PIN -1 #if ENABLED(LCD_I2C_PANELOLU2) #define BTN_EN1 27 // RX1 - fastio.h pin mapping 27 #define BTN_EN2 26 // TX1 - fastio.h pin mapping 26 #define BTN_ENC 43 // A3 - fastio.h pin mapping 43 #define SDSS 40 // use SD card on Panelolu2 (Teensyduino pin mapping) #endif // LCD_I2C_PANELOLU2 #define SD_DETECT_PIN -1 #endif // ULTRA_LCD && NEWPANEL
{ "content_hash": "af7bd62018a6f909fb41fbddb1b555e1", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 126, "avg_line_length": 25.193548387096776, "alnum_prop": 0.6278275714895433, "repo_name": "pulcher/3DPrint-delta", "id": "b0fc8aec5f7e87763fd6393154bc957f91141be9", "size": "3203", "binary": false, "copies": "47", "ref": "refs/heads/master", "path": "Marlin/Marlin/pins_TEENSYLU.h", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Arduino", "bytes": "3360" }, { "name": "Batchfile", "bytes": "904" }, { "name": "C", "bytes": "3213113" }, { "name": "C++", "bytes": "1141899" }, { "name": "CMake", "bytes": "7162" }, { "name": "Makefile", "bytes": "17225" }, { "name": "Objective-C", "bytes": "2178" }, { "name": "Python", "bytes": "12476" }, { "name": "Shell", "bytes": "9911" } ], "symlink_target": "" }
require "test_helper" describe Instructor do before do @instructor = Instructor.new end it "must be valid" do @instructor.valid?.must_equal true end end
{ "content_hash": "f7420678b867de4473992626a0756930", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 38, "avg_line_length": 15.545454545454545, "alnum_prop": 0.7017543859649122, "repo_name": "salex/Assessable", "id": "b581c5ba1a1038197e588ec1db9f5d25d4de4127", "size": "171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/dummy/test/models/instructor_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "22542" }, { "name": "JavaScript", "bytes": "1282" }, { "name": "Ruby", "bytes": "159798" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>pi-agm: 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.8.1 / pi-agm - 1.2.6</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> pi-agm <small> 1.2.6 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-16 04:20:23 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-16 04:20:23 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.8.1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.02.3 The OCaml compiler (virtual package) ocaml-base-compiler 4.02.3 Official 4.02.3 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;yves.bertot@inria.fr&quot; homepage: &quot;http://www-sop.inria.fr/members/Yves.Bertot/&quot; bug-reports: &quot;yves.bertot@inria.fr&quot; license: &quot;CECILL-B&quot; build: [[&quot;coq_makefile&quot; &quot;-f&quot; &quot;_CoqProject&quot; &quot;-o&quot; &quot;Makefile&quot; ] [ make &quot;-j&quot; &quot;%{jobs}%&quot; ]] install: [ make &quot;install&quot; &quot;DEST=&#39;%{lib}%/coq/user-contrib/pi_agm&#39;&quot; ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.12&quot;} &quot;coq-coquelicot&quot; {&gt;= &quot;3&quot; &amp; &lt; &quot;4~&quot;} &quot;coq-interval&quot; {&gt;= &quot;4&quot;} ] dev-repo: &quot;git+https://github.com/ybertot/pi-agm.git&quot; tags: [ &quot;keyword:real analysis&quot; &quot;keyword:pi&quot; &quot;category:Mathematics/Real Calculus and Topology&quot; &quot;logpath:agm&quot; &quot;date:2020-06-23&quot; ] authors: [ &quot;Yves Bertot &lt;yves.bertot@inria.fr&gt;&quot; ] synopsis: &quot;Computing thousands or millions of digits of PI with arithmetic-geometric means&quot; description: &quot;&quot;&quot; This is a proof of correctness for two algorithms to compute PI to high precision using arithmetic-geometric means. A first file contains the calculus-based proofs for an abstract view of the algorithm, where all numbers are real numbers. A second file describes how to approximate all computations using large integers. Other files describe the second algorithm which is close to the one used in mpfr, for instance. The whole development can be used to produce mathematically proved and formally verified approximations of PI.&quot;&quot;&quot; url { src: &quot;https://github.com/ybertot/pi-agm/archive/v1.2.6.zip&quot; checksum: &quot;sha256=f690dd8e464acafb4c14437a0ad09545a11f4ebd6771b05f4e7f74ca5c08a7ff&quot; } </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-pi-agm.1.2.6 coq.8.8.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.8.1). The following dependencies couldn&#39;t be met: - coq-pi-agm -&gt; coq &gt;= 8.12 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; 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-pi-agm.1.2.6</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>
{ "content_hash": "8bc970954fee610c22bf6aa16e76493b", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 178, "avg_line_length": 44.10344827586207, "alnum_prop": 0.5596820432629659, "repo_name": "coq-bench/coq-bench.github.io", "id": "532d693ca07c6ba90c21f3690f51bf51e1f04b90", "size": "7699", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.8.1/pi-agm/1.2.6.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package ior.parser.corba.iop; import ior.parser.mvc.UpdateMessage; public class IORMessageTypes { public static final int BAD_IOR = 0; public static final int IOR_SET = 1; public static final int IOR_UNSET = 2; }
{ "content_hash": "24486356f09d6537c43a2cb556dc2267", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 40, "avg_line_length": 20.09090909090909, "alnum_prop": 0.7420814479638009, "repo_name": "rlong/archive.corba_ior_parser", "id": "48035967f6728a116bac20f319180509ed94b626", "size": "351", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ior/parser/corba/iop/IORMessageTypes.java", "mode": "33261", "license": "mit", "language": [], "symlink_target": "" }
using Microsoft.EntityFrameworkCore.Migrations; namespace GraphQL.Annotations.StarWarsApp.Migrations { public partial class Initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Droids", columns: table => new { DroidId = table.Column<int>(nullable: false) .Annotation("Autoincrement", true), Name = table.Column<string>(nullable: true), PrimaryFunction = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Droids", x => x.DroidId); }); migrationBuilder.CreateTable( name: "Humans", columns: table => new { HumanId = table.Column<int>(nullable: false) .Annotation("Autoincrement", true), HomePlanet = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Humans", x => x.HumanId); }); migrationBuilder.CreateTable( name: "Friendships", columns: table => new { FriendshipId = table.Column<int>(nullable: false) .Annotation("Autoincrement", true), DroidId = table.Column<int>(nullable: false), HumanId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Friendships", x => x.FriendshipId); table.ForeignKey( name: "FK_Friendships_Droids_DroidId", column: x => x.DroidId, principalTable: "Droids", principalColumn: "DroidId", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Friendships_Humans_HumanId", column: x => x.HumanId, principalTable: "Humans", principalColumn: "HumanId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Friendships_DroidId", table: "Friendships", column: "DroidId"); migrationBuilder.CreateIndex( name: "IX_Friendships_HumanId", table: "Friendships", column: "HumanId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Friendships"); migrationBuilder.DropTable( name: "Droids"); migrationBuilder.DropTable( name: "Humans"); } } }
{ "content_hash": "43b8e7510a106ac9e6ae3e9555c64a3f", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 76, "avg_line_length": 37.30232558139535, "alnum_prop": 0.4660224438902743, "repo_name": "dlukez/graphql-dotnet-annotations", "id": "7800452a0fba8ee9b33424af801576e5199d70fa", "size": "3210", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/GraphQL.Annotations.StarWarsApp/Migrations/20161111024839_Initial.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "27731" }, { "name": "PowerShell", "bytes": "804" } ], "symlink_target": "" }
#ifndef NN_H_INCLUDED #define NN_H_INCLUDED #ifdef __cplusplus extern "C" { #endif #include <errno.h> #include <stddef.h> /* Handle DSO symbol visibility. */ #if defined NN_NO_EXPORTS # define NN_EXPORT #else # if defined _WIN32 # if defined NN_STATIC_LIB # define NN_EXPORT extern # elif defined NN_SHARED_LIB # define NN_EXPORT __declspec(dllexport) # else # define NN_EXPORT __declspec(dllimport) # endif # else # if defined __SUNPRO_C # define NN_EXPORT __global # elif (defined __GNUC__ && __GNUC__ >= 4) || \ defined __INTEL_COMPILER || defined __clang__ # define NN_EXPORT __attribute__ ((visibility("default"))) # else # define NN_EXPORT # endif # endif #endif /******************************************************************************/ /* ABI versioning support. */ /******************************************************************************/ /* Don't change this unless you know exactly what you're doing and have */ /* read and understand the following documents: */ /* www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html */ /* www.gnu.org/software/libtool/manual/html_node/Updating-version-info.html */ /* The current interface version. */ #define NN_VERSION_CURRENT 4 /* The latest revision of the current interface. */ #define NN_VERSION_REVISION 0 /* How many past interface versions are still supported. */ #define NN_VERSION_AGE 0 /******************************************************************************/ /* Errors. */ /******************************************************************************/ /* A number random enough not to collide with different errno ranges on */ /* different OSes. The assumption is that error_t is at least 32-bit type. */ #define NN_HAUSNUMERO 156384712 /* On some platforms some standard POSIX errnos are not defined. */ #ifndef ENOTSUP #define ENOTSUP (NN_HAUSNUMERO + 1) #endif #ifndef EPROTONOSUPPORT #define EPROTONOSUPPORT (NN_HAUSNUMERO + 2) #endif #ifndef ENOBUFS #define ENOBUFS (NN_HAUSNUMERO + 3) #endif #ifndef ENETDOWN #define ENETDOWN (NN_HAUSNUMERO + 4) #endif #ifndef EADDRINUSE #define EADDRINUSE (NN_HAUSNUMERO + 5) #endif #ifndef EADDRNOTAVAIL #define EADDRNOTAVAIL (NN_HAUSNUMERO + 6) #endif #ifndef ECONNREFUSED #define ECONNREFUSED (NN_HAUSNUMERO + 7) #endif #ifndef EINPROGRESS #define EINPROGRESS (NN_HAUSNUMERO + 8) #endif #ifndef ENOTSOCK #define ENOTSOCK (NN_HAUSNUMERO + 9) #endif #ifndef EAFNOSUPPORT #define EAFNOSUPPORT (NN_HAUSNUMERO + 10) #endif #ifndef EPROTO #define EPROTO (NN_HAUSNUMERO + 11) #endif #ifndef EAGAIN #define EAGAIN (NN_HAUSNUMERO + 12) #endif #ifndef EBADF #define EBADF (NN_HAUSNUMERO + 13) #endif #ifndef EINVAL #define EINVAL (NN_HAUSNUMERO + 14) #endif #ifndef EMFILE #define EMFILE (NN_HAUSNUMERO + 15) #endif #ifndef EFAULT #define EFAULT (NN_HAUSNUMERO + 16) #endif #ifndef EACCES #define EACCES (NN_HAUSNUMERO + 17) #endif #ifndef EACCESS #define EACCESS (EACCES) #endif #ifndef ENETRESET #define ENETRESET (NN_HAUSNUMERO + 18) #endif #ifndef ENETUNREACH #define ENETUNREACH (NN_HAUSNUMERO + 19) #endif #ifndef EHOSTUNREACH #define EHOSTUNREACH (NN_HAUSNUMERO + 20) #endif #ifndef ENOTCONN #define ENOTCONN (NN_HAUSNUMERO + 21) #endif #ifndef EMSGSIZE #define EMSGSIZE (NN_HAUSNUMERO + 22) #endif #ifndef ETIMEDOUT #define ETIMEDOUT (NN_HAUSNUMERO + 23) #endif #ifndef ECONNABORTED #define ECONNABORTED (NN_HAUSNUMERO + 24) #endif #ifndef ECONNRESET #define ECONNRESET (NN_HAUSNUMERO + 25) #endif #ifndef ENOPROTOOPT #define ENOPROTOOPT (NN_HAUSNUMERO + 26) #endif #ifndef EISCONN #define EISCONN (NN_HAUSNUMERO + 27) #define NN_EISCONN_DEFINED #endif #ifndef ESOCKTNOSUPPORT #define ESOCKTNOSUPPORT (NN_HAUSNUMERO + 28) #endif /* Native nanomsg error codes. */ #ifndef ETERM #define ETERM (NN_HAUSNUMERO + 53) #endif #ifndef EFSM #define EFSM (NN_HAUSNUMERO + 54) #endif /* This function retrieves the errno as it is known to the library. */ /* The goal of this function is to make the code 100% portable, including */ /* where the library is compiled with certain CRT library (on Windows) and */ /* linked to an application that uses different CRT library. */ NN_EXPORT int nn_errno (void); /* Resolves system errors and native errors to human-readable string. */ NN_EXPORT const char *nn_strerror (int errnum); /* Returns the symbol name (e.g. "NN_REQ") and value at a specified index. */ /* If the index is out-of-range, returns NULL and sets errno to EINVAL */ /* General usage is to start at i=0 and iterate until NULL is returned. */ NN_EXPORT const char *nn_symbol (int i, int *value); /* Constants that are returned in `ns` member of nn_symbol_properties */ #define NN_NS_NAMESPACE 0 #define NN_NS_VERSION 1 #define NN_NS_DOMAIN 2 #define NN_NS_TRANSPORT 3 #define NN_NS_PROTOCOL 4 #define NN_NS_OPTION_LEVEL 5 #define NN_NS_SOCKET_OPTION 6 #define NN_NS_TRANSPORT_OPTION 7 #define NN_NS_OPTION_TYPE 8 #define NN_NS_OPTION_UNIT 9 #define NN_NS_FLAG 10 #define NN_NS_ERROR 11 #define NN_NS_LIMIT 12 #define NN_NS_EVENT 13 /* Constants that are returned in `type` member of nn_symbol_properties */ #define NN_TYPE_NONE 0 #define NN_TYPE_INT 1 #define NN_TYPE_STR 2 /* Constants that are returned in the `unit` member of nn_symbol_properties */ #define NN_UNIT_NONE 0 #define NN_UNIT_BYTES 1 #define NN_UNIT_MILLISECONDS 2 #define NN_UNIT_PRIORITY 3 #define NN_UNIT_BOOLEAN 4 /* Structure that is returned from nn_symbol */ struct nn_symbol_properties { /* The constant value */ int value; /* The constant name */ const char* name; /* The constant namespace, or zero for namespaces themselves */ int ns; /* The option type for socket option constants */ int type; /* The unit for the option value for socket option constants */ int unit; }; /* Fills in nn_symbol_properties structure and returns it's length */ /* If the index is out-of-range, returns 0 */ /* General usage is to start at i=0 and iterate until zero is returned. */ NN_EXPORT int nn_symbol_info (int i, struct nn_symbol_properties *buf, int buflen); /******************************************************************************/ /* Helper function for shutting down multi-threaded applications. */ /******************************************************************************/ NN_EXPORT void nn_term (void); /******************************************************************************/ /* Zero-copy support. */ /******************************************************************************/ #define NN_MSG ((size_t) -1) NN_EXPORT void *nn_allocmsg (size_t size, int type); NN_EXPORT void *nn_reallocmsg (void *msg, size_t size); NN_EXPORT int nn_freemsg (void *msg); /******************************************************************************/ /* Socket definition. */ /******************************************************************************/ struct nn_iovec { void *iov_base; size_t iov_len; }; struct nn_msghdr { struct nn_iovec *msg_iov; int msg_iovlen; void *msg_control; size_t msg_controllen; }; struct nn_cmsghdr { size_t cmsg_len; int cmsg_level; int cmsg_type; }; /* Internal stuff. Not to be used directly. */ NN_EXPORT struct nn_cmsghdr *nn_cmsg_nxthdr_ ( const struct nn_msghdr *mhdr, const struct nn_cmsghdr *cmsg); #define NN_CMSG_ALIGN_(len) \ (((len) + sizeof (size_t) - 1) & (size_t) ~(sizeof (size_t) - 1)) /* POSIX-defined msghdr manipulation. */ #define NN_CMSG_FIRSTHDR(mhdr) \ nn_cmsg_nxthdr_ ((struct nn_msghdr*) (mhdr), NULL) #define NN_CMSG_NXTHDR(mhdr, cmsg) \ nn_cmsg_nxthdr_ ((struct nn_msghdr*) (mhdr), (struct nn_cmsghdr*) (cmsg)) #define NN_CMSG_DATA(cmsg) \ ((unsigned char*) (((struct nn_cmsghdr*) (cmsg)) + 1)) /* Extensions to POSIX defined by RFC 3542. */ #define NN_CMSG_SPACE(len) \ (NN_CMSG_ALIGN_ (len) + NN_CMSG_ALIGN_ (sizeof (struct nn_cmsghdr))) #define NN_CMSG_LEN(len) \ (NN_CMSG_ALIGN_ (sizeof (struct nn_cmsghdr)) + (len)) /* SP address families. */ #define AF_SP 1 #define AF_SP_RAW 2 /* Max size of an SP address. */ #define NN_SOCKADDR_MAX 128 /* Socket option levels: Negative numbers are reserved for transports, positive for socket types. */ #define NN_SOL_SOCKET 0 /* Generic socket options (NN_SOL_SOCKET level). */ #define NN_LINGER 1 #define NN_SNDBUF 2 #define NN_RCVBUF 3 #define NN_SNDTIMEO 4 #define NN_RCVTIMEO 5 #define NN_RECONNECT_IVL 6 #define NN_RECONNECT_IVL_MAX 7 #define NN_SNDPRIO 8 #define NN_RCVPRIO 9 #define NN_SNDFD 10 #define NN_RCVFD 11 #define NN_DOMAIN 12 #define NN_PROTOCOL 13 #define NN_IPV4ONLY 14 #define NN_SOCKET_NAME 15 #define NN_RCVMAXSIZE 16 /* Send/recv options. */ #define NN_DONTWAIT 1 /* Ancillary data. */ #define PROTO_SP 1 #define SP_HDR 1 NN_EXPORT int nn_socket (int domain, int protocol); NN_EXPORT int nn_close (int s); NN_EXPORT int nn_setsockopt (int s, int level, int option, const void *optval, size_t optvallen); NN_EXPORT int nn_getsockopt (int s, int level, int option, void *optval, size_t *optvallen); NN_EXPORT int nn_bind (int s, const char *addr); NN_EXPORT int nn_connect (int s, const char *addr); NN_EXPORT int nn_shutdown (int s, int how); NN_EXPORT int nn_send (int s, const void *buf, size_t len, int flags); NN_EXPORT int nn_recv (int s, void *buf, size_t len, int flags); NN_EXPORT int nn_sendmsg (int s, const struct nn_msghdr *msghdr, int flags); NN_EXPORT int nn_recvmsg (int s, struct nn_msghdr *msghdr, int flags); /******************************************************************************/ /* Socket mutliplexing support. */ /******************************************************************************/ #define NN_POLLIN 1 #define NN_POLLOUT 2 struct nn_pollfd { int fd; short events; short revents; }; NN_EXPORT int nn_poll (struct nn_pollfd *fds, int nfds, int timeout); /******************************************************************************/ /* Built-in support for devices. */ /******************************************************************************/ NN_EXPORT int nn_device (int s1, int s2); /******************************************************************************/ /* Built-in support for multiplexers. */ /******************************************************************************/ NN_EXPORT int nn_tcpmuxd (int port); #ifdef __cplusplus } #endif #endif
{ "content_hash": "b1ca1c8142456863ff9ba1eb54839cea", "timestamp": "", "source": "github", "line_count": 375, "max_line_length": 80, "avg_line_length": 30.413333333333334, "alnum_prop": 0.566330556773345, "repo_name": "wirebirdlabs/featherweight-nanomsg", "id": "4bb98bf548175d76a087b5d429f5f17c45e60b99", "size": "12676", "binary": false, "copies": "2", "ref": "refs/heads/ftw-kernel", "path": "src/nn.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1323143" }, { "name": "C++", "bytes": "148649" }, { "name": "CMake", "bytes": "20746" }, { "name": "Shell", "bytes": "4735" } ], "symlink_target": "" }
module MethodsPracticeHelpers def image_tag(source, alternate_text) # Generate an image tag with the given source and the classes # "img-responsive" and "img-thumbnail". The image should also have an alt # attribute with the contents of alternate_text. img_src = "\"#{source}\"" img_alt = "\"#{alternate_text}\"" img_class = "\"img-responsive img-thumbnail\"" "<img src = #{img_src} alt = #{img_alt} class = #{img_class}/>" end def bootstrap_alert(message, type='info') # Generates the HTML for a Bootstrap alert (useful since it can be diffcult # to remember all HTML needed to do it right). It should show the message in # the "message" variable and should have a class appropriate for the "type" # that is passed in, defaulting to 'info' if no type is passed in. atype = "\"alert alert-#{type} alert-dismissible\"" role = "\"alert\"" button_type = "\"button\"" button_class = "\"close\"" button_data_dismiss = "\"alert\"" button_aria_label = "\"Close\"" span_aria_hidden = "\"true\"" span_content = "&times;" "<div class=#{atype} role=#{role}> <button type=#{button_type} class=#{button_class} data-dismiss=#{button_data_dismiss} aria-label=#{button_aria_label}><span aria-hidden=#{span_aria_hidden}>#{span_content}</span></button>#{message} </div>" end def current_date_and_time # Give the current date and time, in the format: "February 6, 2015 at 4:25pm" # Time.now.strftime is a great method chain you can use for this purpose. # See how to use it at: http://apidock.com/ruby/Time/strftime Time.now.strftime('%B %-d, %Y at %-l:%M%P') end # ------------------------------------------ # ANYTHING BEYOND THIS POINT IS OPTIONAL FOR # THOSE WHO MIGHT WANT AN EXTRA CHALLENGE # ------------------------------------------ def something_ipsum(number_of_ipsums) # You may have heard of Cat Ipsum or Hipster Ipsum. Make up a new one. # Replace "something" with the kind of ipsum you want to create, then # generate text for the number of ipsums you want (here, we're defining # an ipsum as a phrase or sentence). end def images_of_cats(number_of_cats) # Use the cat_api gem (https://github.com/chrisvfritz/cat_api) # to generate number_of_cats image tags that are injected into the page end def book_search_for(book_title, results=10) # Using the Google Books API (https://github.com/zeantsoi/GoogleBooks), # return a list of books returned by the Google Books API. For each book, # display the title and link to the info_link. # # For example: # # <ul> # <li><a href="http://link/to/more/information">Book Title</li> # </ul> # # You can use a table or another format if you want - it doesn't have to # be an unordered list. end def convert_to_pig_latin(text) # Converts text to Pig Latin. For example, the previous sentence in pig latin # would be "onvertscay exttay otay igpay atinlay". This one is more difficult # than it may seem to the inexperienced programmer. end def format_number(number) # Converts a number to a string that's more human-readable, rounded to 3 # significant figures, sometimes with a clarifying letter. # # For example: # # 5 -> "5" # 5.2 -> "5.2" # 5.289 -> "5.29" # 13 -> "13" # 13.3 -> "13.3" # 13.943 -> "13.9" # 13.953 -> "14" # 4000 -> "4K" # 1245 -> "1.25K" # 1400000 -> "1.4M" # 3000000 -> "3M" # 2437201 -> "2.44M" end end
{ "content_hash": "51ef1a549f2e436626eeb1180189cc27", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 203, "avg_line_length": 37.4375, "alnum_prop": 0.6207568169170841, "repo_name": "asingh1969/tc359-project8", "id": "b19e9b8a4827246639efbb83ff70f296331e5503", "size": "3594", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "helpers/methods_practice_helpers.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1669" }, { "name": "JavaScript", "bytes": "715" }, { "name": "Ruby", "bytes": "15696" } ], "symlink_target": "" }
<?php defined('IN_IA') or exit('Access Denied');?><?php (!empty($this) && $this instanceof WeModuleSite || 0) ? (include $this->template('common/header', TEMPLATE_INCLUDEPATH)) : (include template('common/header', TEMPLATE_INCLUDEPATH));?> <div class="welcome-container" id="js-home-welcome" ng-controller="WelcomeCtrl" ng-cloak> <div class="welcome-container"> <div class="panel we7-panel account-stat"> <div class="panel-heading"> 今日关键指标/昨日关键指标 </div> <div class="panel-body we7-padding-vertical"> <div class="col-sm-3 text-center"> <div class="title">新关注</div> <div> <span class="today" ng-init="0" ng-bind="fans_kpi.today.new"></span> <span class="pipe">/</span> <span class="yesterday" ng-init="0" ng-bind="fans_kpi.yesterday.new"></span> </div> </div> <div class="col-sm-3 text-center"> <div class="title">取消关注</div> <div> <span class="today" ng-init="0" ng-bind="fans_kpi.today.cancel"></span> <span class="pipe">/</span> <span class="yesterday" ng-init="0" ng-bind="fans_kpi.yesterday.cancel"></span> </div> </div> <div class="col-sm-3 text-center"> <div class="title">净增关注</div> <div> <span class="today" ng-init="0" ng-bind="fans_kpi.today.jing_num"></span> <span class="pipe">/</span> <span class="yesterday" ng-init="0" ng-bind="fans_kpi.yesterday.jing_num"></span> </div> </div> <div class="col-sm-3 text-center"> <div class="title">累计关注</div> <div> <span class="today" ng-init="0" ng-bind="fans_kpi.today.cumulate"></span> </div> </div> </div> </div> </div> </div> <script> angular.module('homeApp').value('config', { notices: <?php echo !empty($notices) ? json_encode($notices) : 'null'?>, }); angular.bootstrap($('#js-home-welcome'), ['homeApp']); $(function(){ $('[data-toggle="tooltip"]').tooltip(); var $topic = $('.welcome-container .notice .menu .topic'); var $ul = $('.welcome-container .notice ul'); $topic.mouseover(function(){ var $this = $(this); var $index = $this.index(); if ($this.is('.we7notice')) { $this.parent().prev().hide(); } else { $this.parent().prev().show(); } $topic.removeClass('active'); $this.addClass('active'); $ul.removeClass('active'); $ul.eq($index).addClass('active'); }) }) </script> <?php (!empty($this) && $this instanceof WeModuleSite || 0) ? (include $this->template('common/footer', TEMPLATE_INCLUDEPATH)) : (include template('common/footer', TEMPLATE_INCLUDEPATH));?>
{ "content_hash": "9f20f36c490e3418fe141bb7f25ce7fd", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 239, "avg_line_length": 37.544117647058826, "alnum_prop": 0.6075205640423031, "repo_name": "Broomspun/shanque", "id": "43b01266d83a969ed696604487210546840d3ae0", "size": "2607", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data/tpl/web/default/home/welcome.tpl.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3946102" }, { "name": "HTML", "bytes": "14193052" }, { "name": "JavaScript", "bytes": "5316409" }, { "name": "PHP", "bytes": "16119529" }, { "name": "Roff", "bytes": "10837" } ], "symlink_target": "" }
<?php namespace Cms\CoreBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\SecurityContext; class DashboardController extends Controller { public function indexAction() { return $this->render('CmsCoreBundle:Dashboard:index.html.twig'); } }
{ "content_hash": "d58e12f64bbef090b8c4b20ce01b516b", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 72, "avg_line_length": 24.733333333333334, "alnum_prop": 0.7789757412398922, "repo_name": "willstorm/cms", "id": "a1f8ba82c5991c4aa0b20a5f1db02ceaadeedcf9", "size": "371", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Cms/CoreBundle/Controller/DashboardController.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2907" }, { "name": "CSS", "bytes": "2569402" }, { "name": "HTML", "bytes": "2374126" }, { "name": "JavaScript", "bytes": "435108" }, { "name": "PHP", "bytes": "87975" } ], "symlink_target": "" }
package edu.uci.ics.asterix.file; import java.util.List; import edu.uci.ics.asterix.common.api.ILocalResourceMetadata; import edu.uci.ics.asterix.common.config.AsterixStorageProperties; import edu.uci.ics.asterix.common.config.DatasetConfig.IndexType; import edu.uci.ics.asterix.common.config.IAsterixPropertiesProvider; import edu.uci.ics.asterix.common.context.AsterixVirtualBufferCacheProvider; import edu.uci.ics.asterix.common.exceptions.AsterixException; import edu.uci.ics.asterix.common.ioopcallbacks.LSMInvertedIndexIOOperationCallbackFactory; import edu.uci.ics.asterix.metadata.declared.AqlMetadataProvider; import edu.uci.ics.asterix.metadata.entities.Index; import edu.uci.ics.asterix.om.types.IAType; import edu.uci.ics.asterix.om.util.NonTaggedFormatUtil; import edu.uci.ics.asterix.runtime.formats.FormatUtils; import edu.uci.ics.asterix.transaction.management.opcallbacks.SecondaryIndexOperationTrackerProvider; import edu.uci.ics.asterix.transaction.management.resource.LSMInvertedIndexLocalResourceMetadata; import edu.uci.ics.asterix.transaction.management.resource.PersistentLocalResourceFactoryProvider; import edu.uci.ics.asterix.transaction.management.service.transaction.AsterixRuntimeComponentsProvider; import edu.uci.ics.hyracks.algebricks.common.constraints.AlgebricksPartitionConstraintHelper; import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException; import edu.uci.ics.hyracks.algebricks.common.utils.Pair; import edu.uci.ics.hyracks.algebricks.core.jobgen.impl.ConnectorPolicyAssignmentPolicy; import edu.uci.ics.hyracks.algebricks.core.rewriter.base.PhysicalOptimizationConfig; import edu.uci.ics.hyracks.algebricks.data.ISerializerDeserializerProvider; import edu.uci.ics.hyracks.algebricks.data.ITypeTraitProvider; import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory; import edu.uci.ics.hyracks.algebricks.runtime.base.IPushRuntimeFactory; import edu.uci.ics.hyracks.algebricks.runtime.operators.base.SinkRuntimeFactory; import edu.uci.ics.hyracks.algebricks.runtime.operators.meta.AlgebricksMetaOperatorDescriptor; import edu.uci.ics.hyracks.api.dataflow.value.IBinaryComparatorFactory; import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer; import edu.uci.ics.hyracks.api.dataflow.value.ITypeTraits; import edu.uci.ics.hyracks.api.dataflow.value.RecordDescriptor; import edu.uci.ics.hyracks.api.job.JobSpecification; import edu.uci.ics.hyracks.data.std.accessors.PointableBinaryComparatorFactory; import edu.uci.ics.hyracks.data.std.primitive.ShortPointable; import edu.uci.ics.hyracks.dataflow.common.data.marshalling.ShortSerializerDeserializer; import edu.uci.ics.hyracks.dataflow.std.base.AbstractOperatorDescriptor; import edu.uci.ics.hyracks.dataflow.std.connectors.OneToOneConnectorDescriptor; import edu.uci.ics.hyracks.dataflow.std.sort.ExternalSortOperatorDescriptor; import edu.uci.ics.hyracks.storage.am.btree.dataflow.BTreeSearchOperatorDescriptor; import edu.uci.ics.hyracks.storage.am.common.dataflow.IIndexDataflowHelperFactory; import edu.uci.ics.hyracks.storage.am.common.impls.NoOpOperationCallbackFactory; import edu.uci.ics.hyracks.storage.am.lsm.invertedindex.dataflow.BinaryTokenizerOperatorDescriptor; import edu.uci.ics.hyracks.storage.am.lsm.invertedindex.dataflow.LSMInvertedIndexBulkLoadOperatorDescriptor; import edu.uci.ics.hyracks.storage.am.lsm.invertedindex.dataflow.LSMInvertedIndexCompactOperator; import edu.uci.ics.hyracks.storage.am.lsm.invertedindex.dataflow.LSMInvertedIndexCreateOperatorDescriptor; import edu.uci.ics.hyracks.storage.am.lsm.invertedindex.dataflow.LSMInvertedIndexDataflowHelperFactory; import edu.uci.ics.hyracks.storage.am.lsm.invertedindex.dataflow.PartitionedLSMInvertedIndexDataflowHelperFactory; import edu.uci.ics.hyracks.storage.am.lsm.invertedindex.tokenizers.IBinaryTokenizerFactory; import edu.uci.ics.hyracks.storage.common.file.ILocalResourceFactoryProvider; import edu.uci.ics.hyracks.storage.common.file.LocalResource; public class SecondaryInvertedIndexOperationsHelper extends SecondaryIndexOperationsHelper { private IAType secondaryKeyType; private ITypeTraits[] invListsTypeTraits; private IBinaryComparatorFactory[] tokenComparatorFactories; private ITypeTraits[] tokenTypeTraits; private IBinaryTokenizerFactory tokenizerFactory; // For tokenization, sorting and loading. Represents <token, primary keys>. private int numTokenKeyPairFields; private IBinaryComparatorFactory[] tokenKeyPairComparatorFactories; private RecordDescriptor tokenKeyPairRecDesc; private boolean isPartitioned; private int[] invertedIndexFields; private int[] invertedIndexFieldsForNonBulkLoadOps; private int[] secondaryFilterFieldsForNonBulkLoadOps; protected SecondaryInvertedIndexOperationsHelper(PhysicalOptimizationConfig physOptConf, IAsterixPropertiesProvider propertiesProvider) { super(physOptConf, propertiesProvider); } @Override @SuppressWarnings("rawtypes") protected void setSecondaryRecDescAndComparators(IndexType indexType, List<List<String>> secondaryKeyFields, List<IAType> secondaryKeyTypes, int gramLength, AqlMetadataProvider metadata) throws AlgebricksException, AsterixException { // Sanity checks. if (numPrimaryKeys > 1) { throw new AsterixException("Cannot create inverted index on dataset with composite primary key."); } if (numSecondaryKeys > 1) { throw new AsterixException("Cannot create composite inverted index on multiple fields."); } if (indexType == IndexType.LENGTH_PARTITIONED_WORD_INVIX || indexType == IndexType.LENGTH_PARTITIONED_NGRAM_INVIX) { isPartitioned = true; } else { isPartitioned = false; } // Prepare record descriptor used in the assign op, and the optional // select op. secondaryFieldAccessEvalFactories = new ICopyEvaluatorFactory[numSecondaryKeys + numFilterFields]; ISerializerDeserializer[] secondaryRecFields = new ISerializerDeserializer[numPrimaryKeys + numSecondaryKeys + numFilterFields]; ISerializerDeserializer[] enforcedRecFields = new ISerializerDeserializer[1 + numPrimaryKeys + numFilterFields]; secondaryTypeTraits = new ITypeTraits[numSecondaryKeys + numPrimaryKeys]; ITypeTraits[] enforcedTypeTraits = new ITypeTraits[1 + numPrimaryKeys]; ISerializerDeserializerProvider serdeProvider = FormatUtils.getDefaultFormat().getSerdeProvider(); ITypeTraitProvider typeTraitProvider = FormatUtils.getDefaultFormat().getTypeTraitProvider(); if (numSecondaryKeys > 0) { secondaryFieldAccessEvalFactories[0] = FormatUtils.getDefaultFormat().getFieldAccessEvaluatorFactory( isEnforcingKeyTypes ? enforcedItemType : itemType, secondaryKeyFields.get(0), numPrimaryKeys); Pair<IAType, Boolean> keyTypePair = Index.getNonNullableOpenFieldType(secondaryKeyTypes.get(0), secondaryKeyFields.get(0), itemType); secondaryKeyType = keyTypePair.first; anySecondaryKeyIsNullable = anySecondaryKeyIsNullable || keyTypePair.second; ISerializerDeserializer keySerde = serdeProvider.getSerializerDeserializer(secondaryKeyType); secondaryRecFields[0] = keySerde; secondaryTypeTraits[0] = typeTraitProvider.getTypeTrait(secondaryKeyType); } if (numFilterFields > 0) { secondaryFieldAccessEvalFactories[numSecondaryKeys] = FormatUtils.getDefaultFormat() .getFieldAccessEvaluatorFactory(itemType, filterFieldName, numPrimaryKeys); Pair<IAType, Boolean> keyTypePair = Index.getNonNullableKeyFieldType(filterFieldName, itemType); IAType type = keyTypePair.first; ISerializerDeserializer serde = serdeProvider.getSerializerDeserializer(type); secondaryRecFields[numPrimaryKeys + numSecondaryKeys] = serde; } secondaryRecDesc = new RecordDescriptor(secondaryRecFields); // Comparators and type traits for tokens. int numTokenFields = (!isPartitioned) ? numSecondaryKeys : numSecondaryKeys + 1; tokenComparatorFactories = new IBinaryComparatorFactory[numTokenFields]; tokenTypeTraits = new ITypeTraits[numTokenFields]; tokenComparatorFactories[0] = NonTaggedFormatUtil.getTokenBinaryComparatorFactory(secondaryKeyType); tokenTypeTraits[0] = NonTaggedFormatUtil.getTokenTypeTrait(secondaryKeyType); if (isPartitioned) { // The partitioning field is hardcoded to be a short *without* an Asterix type tag. tokenComparatorFactories[1] = PointableBinaryComparatorFactory.of(ShortPointable.FACTORY); tokenTypeTraits[1] = ShortPointable.TYPE_TRAITS; } // Set tokenizer factory. // TODO: We might want to expose the hashing option at the AQL level, // and add the choice to the index metadata. tokenizerFactory = NonTaggedFormatUtil.getBinaryTokenizerFactory(secondaryKeyType.getTypeTag(), indexType, gramLength); // Type traits for inverted-list elements. Inverted lists contain // primary keys. invListsTypeTraits = new ITypeTraits[numPrimaryKeys]; if (numPrimaryKeys > 0) { invListsTypeTraits[0] = primaryRecDesc.getTypeTraits()[0]; enforcedRecFields[0] = primaryRecDesc.getFields()[0]; enforcedTypeTraits[0] = primaryRecDesc.getTypeTraits()[0]; } enforcedRecFields[numPrimaryKeys] = serdeProvider.getSerializerDeserializer(itemType); enforcedRecDesc = new RecordDescriptor(enforcedRecFields, enforcedTypeTraits); // For tokenization, sorting and loading. // One token (+ optional partitioning field) + primary keys. numTokenKeyPairFields = (!isPartitioned) ? 1 + numPrimaryKeys : 2 + numPrimaryKeys; ISerializerDeserializer[] tokenKeyPairFields = new ISerializerDeserializer[numTokenKeyPairFields + numFilterFields]; ITypeTraits[] tokenKeyPairTypeTraits = new ITypeTraits[numTokenKeyPairFields]; tokenKeyPairComparatorFactories = new IBinaryComparatorFactory[numTokenKeyPairFields]; tokenKeyPairFields[0] = serdeProvider.getSerializerDeserializer(secondaryKeyType); tokenKeyPairTypeTraits[0] = tokenTypeTraits[0]; tokenKeyPairComparatorFactories[0] = NonTaggedFormatUtil.getTokenBinaryComparatorFactory(secondaryKeyType); int pkOff = 1; if (isPartitioned) { tokenKeyPairFields[1] = ShortSerializerDeserializer.INSTANCE; tokenKeyPairTypeTraits[1] = tokenTypeTraits[1]; tokenKeyPairComparatorFactories[1] = PointableBinaryComparatorFactory.of(ShortPointable.FACTORY); pkOff = 2; } if (numPrimaryKeys > 0) { tokenKeyPairFields[pkOff] = primaryRecDesc.getFields()[0]; tokenKeyPairTypeTraits[pkOff] = primaryRecDesc.getTypeTraits()[0]; tokenKeyPairComparatorFactories[pkOff] = primaryComparatorFactories[0]; } if (numFilterFields > 0) { tokenKeyPairFields[numPrimaryKeys + pkOff] = secondaryRecFields[numPrimaryKeys + numSecondaryKeys]; } tokenKeyPairRecDesc = new RecordDescriptor(tokenKeyPairFields, tokenKeyPairTypeTraits); if (filterFieldName != null) { invertedIndexFields = new int[numTokenKeyPairFields]; for (int i = 0; i < invertedIndexFields.length; i++) { invertedIndexFields[i] = i; } secondaryFilterFieldsForNonBulkLoadOps = new int[numFilterFields]; secondaryFilterFieldsForNonBulkLoadOps[0] = numSecondaryKeys + numPrimaryKeys; invertedIndexFieldsForNonBulkLoadOps = new int[numSecondaryKeys + numPrimaryKeys]; for (int i = 0; i < invertedIndexFieldsForNonBulkLoadOps.length; i++) { invertedIndexFieldsForNonBulkLoadOps[i] = i; } } } protected int getNumSecondaryKeys() { return numTokenKeyPairFields - numPrimaryKeys; } @Override public JobSpecification buildCreationJobSpec() throws AsterixException, AlgebricksException { JobSpecification spec = JobSpecificationUtils.createJobSpecification(); //prepare a LocalResourceMetadata which will be stored in NC's local resource repository ILocalResourceMetadata localResourceMetadata = new LSMInvertedIndexLocalResourceMetadata(invListsTypeTraits, primaryComparatorFactories, tokenTypeTraits, tokenComparatorFactories, tokenizerFactory, isPartitioned, dataset.getDatasetId(), mergePolicyFactory, mergePolicyFactoryProperties, filterTypeTraits, filterCmpFactories, invertedIndexFields, secondaryFilterFields, secondaryFilterFieldsForNonBulkLoadOps, invertedIndexFieldsForNonBulkLoadOps); ILocalResourceFactoryProvider localResourceFactoryProvider = new PersistentLocalResourceFactoryProvider( localResourceMetadata, LocalResource.LSMInvertedIndexResource); IIndexDataflowHelperFactory dataflowHelperFactory = createDataflowHelperFactory(); LSMInvertedIndexCreateOperatorDescriptor invIndexCreateOp = new LSMInvertedIndexCreateOperatorDescriptor(spec, AsterixRuntimeComponentsProvider.RUNTIME_PROVIDER, secondaryFileSplitProvider, AsterixRuntimeComponentsProvider.RUNTIME_PROVIDER, tokenTypeTraits, tokenComparatorFactories, invListsTypeTraits, primaryComparatorFactories, tokenizerFactory, dataflowHelperFactory, localResourceFactoryProvider, NoOpOperationCallbackFactory.INSTANCE); AlgebricksPartitionConstraintHelper.setPartitionConstraintInJobSpec(spec, invIndexCreateOp, secondaryPartitionConstraint); spec.addRoot(invIndexCreateOp); spec.setConnectorPolicyAssignmentPolicy(new ConnectorPolicyAssignmentPolicy()); return spec; } @Override public JobSpecification buildLoadingJobSpec() throws AsterixException, AlgebricksException { JobSpecification spec = JobSpecificationUtils.createJobSpecification(); // Create dummy key provider for feeding the primary index scan. AbstractOperatorDescriptor keyProviderOp = createDummyKeyProviderOp(spec); // Create primary index scan op. BTreeSearchOperatorDescriptor primaryScanOp = createPrimaryIndexScanOp(spec); AbstractOperatorDescriptor sourceOp = primaryScanOp; if (isEnforcingKeyTypes) { sourceOp = createCastOp(spec, primaryScanOp, numSecondaryKeys, dataset.getDatasetType()); spec.connect(new OneToOneConnectorDescriptor(spec), primaryScanOp, 0, sourceOp, 0); } AlgebricksMetaOperatorDescriptor asterixAssignOp = createAssignOp(spec, sourceOp, numSecondaryKeys); // If any of the secondary fields are nullable, then add a select op // that filters nulls. AlgebricksMetaOperatorDescriptor selectOp = null; if (anySecondaryKeyIsNullable || isEnforcingKeyTypes) { selectOp = createFilterNullsSelectOp(spec, numSecondaryKeys); } // Create a tokenizer op. AbstractOperatorDescriptor tokenizerOp = createTokenizerOp(spec); // Sort by token + primary keys. ExternalSortOperatorDescriptor sortOp = createSortOp(spec, tokenKeyPairComparatorFactories, tokenKeyPairRecDesc); // Create secondary inverted index bulk load op. LSMInvertedIndexBulkLoadOperatorDescriptor invIndexBulkLoadOp = createInvertedIndexBulkLoadOp(spec); AlgebricksMetaOperatorDescriptor metaOp = new AlgebricksMetaOperatorDescriptor(spec, 1, 0, new IPushRuntimeFactory[] { new SinkRuntimeFactory() }, new RecordDescriptor[] {}); // Connect the operators. spec.connect(new OneToOneConnectorDescriptor(spec), keyProviderOp, 0, primaryScanOp, 0); spec.connect(new OneToOneConnectorDescriptor(spec), sourceOp, 0, asterixAssignOp, 0); if (anySecondaryKeyIsNullable || isEnforcingKeyTypes) { spec.connect(new OneToOneConnectorDescriptor(spec), asterixAssignOp, 0, selectOp, 0); spec.connect(new OneToOneConnectorDescriptor(spec), selectOp, 0, tokenizerOp, 0); } else { spec.connect(new OneToOneConnectorDescriptor(spec), asterixAssignOp, 0, tokenizerOp, 0); } spec.connect(new OneToOneConnectorDescriptor(spec), tokenizerOp, 0, sortOp, 0); spec.connect(new OneToOneConnectorDescriptor(spec), sortOp, 0, invIndexBulkLoadOp, 0); spec.connect(new OneToOneConnectorDescriptor(spec), invIndexBulkLoadOp, 0, metaOp, 0); spec.addRoot(metaOp); spec.setConnectorPolicyAssignmentPolicy(new ConnectorPolicyAssignmentPolicy()); return spec; } private AbstractOperatorDescriptor createTokenizerOp(JobSpecification spec) throws AlgebricksException { int docField = 0; int[] primaryKeyFields = new int[numPrimaryKeys + numFilterFields]; for (int i = 0; i < primaryKeyFields.length; i++) { primaryKeyFields[i] = numSecondaryKeys + i; } BinaryTokenizerOperatorDescriptor tokenizerOp = new BinaryTokenizerOperatorDescriptor(spec, tokenKeyPairRecDesc, tokenizerFactory, docField, primaryKeyFields, isPartitioned, false); AlgebricksPartitionConstraintHelper.setPartitionConstraintInJobSpec(spec, tokenizerOp, primaryPartitionConstraint); return tokenizerOp; } @Override protected ExternalSortOperatorDescriptor createSortOp(JobSpecification spec, IBinaryComparatorFactory[] secondaryComparatorFactories, RecordDescriptor secondaryRecDesc) { // Sort on token and primary keys. int[] sortFields = new int[numTokenKeyPairFields]; for (int i = 0; i < numTokenKeyPairFields; i++) { sortFields[i] = i; } ExternalSortOperatorDescriptor sortOp = new ExternalSortOperatorDescriptor(spec, physOptConf.getMaxFramesExternalSort(), sortFields, tokenKeyPairComparatorFactories, secondaryRecDesc); AlgebricksPartitionConstraintHelper.setPartitionConstraintInJobSpec(spec, sortOp, primaryPartitionConstraint); return sortOp; } private LSMInvertedIndexBulkLoadOperatorDescriptor createInvertedIndexBulkLoadOp(JobSpecification spec) { int[] fieldPermutation = new int[numTokenKeyPairFields + numFilterFields]; for (int i = 0; i < fieldPermutation.length; i++) { fieldPermutation[i] = i; } IIndexDataflowHelperFactory dataflowHelperFactory = createDataflowHelperFactory(); LSMInvertedIndexBulkLoadOperatorDescriptor invIndexBulkLoadOp = new LSMInvertedIndexBulkLoadOperatorDescriptor( spec, secondaryRecDesc, fieldPermutation, false, numElementsHint, false, AsterixRuntimeComponentsProvider.RUNTIME_PROVIDER, secondaryFileSplitProvider, AsterixRuntimeComponentsProvider.RUNTIME_PROVIDER, tokenTypeTraits, tokenComparatorFactories, invListsTypeTraits, primaryComparatorFactories, tokenizerFactory, dataflowHelperFactory); AlgebricksPartitionConstraintHelper.setPartitionConstraintInJobSpec(spec, invIndexBulkLoadOp, secondaryPartitionConstraint); return invIndexBulkLoadOp; } private IIndexDataflowHelperFactory createDataflowHelperFactory() { AsterixStorageProperties storageProperties = propertiesProvider.getStorageProperties(); if (!isPartitioned) { return new LSMInvertedIndexDataflowHelperFactory(new AsterixVirtualBufferCacheProvider( dataset.getDatasetId()), mergePolicyFactory, mergePolicyFactoryProperties, new SecondaryIndexOperationTrackerProvider(dataset.getDatasetId()), AsterixRuntimeComponentsProvider.RUNTIME_PROVIDER, LSMInvertedIndexIOOperationCallbackFactory.INSTANCE, storageProperties.getBloomFilterFalsePositiveRate(), invertedIndexFields, filterTypeTraits, filterCmpFactories, secondaryFilterFields, secondaryFilterFieldsForNonBulkLoadOps, invertedIndexFieldsForNonBulkLoadOps); } else { return new PartitionedLSMInvertedIndexDataflowHelperFactory(new AsterixVirtualBufferCacheProvider( dataset.getDatasetId()), mergePolicyFactory, mergePolicyFactoryProperties, new SecondaryIndexOperationTrackerProvider(dataset.getDatasetId()), AsterixRuntimeComponentsProvider.RUNTIME_PROVIDER, LSMInvertedIndexIOOperationCallbackFactory.INSTANCE, storageProperties.getBloomFilterFalsePositiveRate(), invertedIndexFields, filterTypeTraits, filterCmpFactories, secondaryFilterFields, secondaryFilterFieldsForNonBulkLoadOps, invertedIndexFieldsForNonBulkLoadOps); } } @Override public JobSpecification buildCompactJobSpec() throws AsterixException, AlgebricksException { JobSpecification spec = JobSpecificationUtils.createJobSpecification(); IIndexDataflowHelperFactory dataflowHelperFactory = createDataflowHelperFactory(); LSMInvertedIndexCompactOperator compactOp = new LSMInvertedIndexCompactOperator(spec, AsterixRuntimeComponentsProvider.RUNTIME_PROVIDER, secondaryFileSplitProvider, AsterixRuntimeComponentsProvider.RUNTIME_PROVIDER, tokenTypeTraits, tokenComparatorFactories, invListsTypeTraits, primaryComparatorFactories, tokenizerFactory, dataflowHelperFactory, NoOpOperationCallbackFactory.INSTANCE); AlgebricksPartitionConstraintHelper.setPartitionConstraintInJobSpec(spec, compactOp, secondaryPartitionConstraint); spec.addRoot(compactOp); spec.setConnectorPolicyAssignmentPolicy(new ConnectorPolicyAssignmentPolicy()); return spec; } }
{ "content_hash": "18b11e60e4a21d343546b5ca818f4565", "timestamp": "", "source": "github", "line_count": 358, "max_line_length": 121, "avg_line_length": 62.29329608938548, "alnum_prop": 0.7512219182996278, "repo_name": "sjaco002/incubator-asterixdb", "id": "579af2f3290932ad9ad72698637a1cb8f6708750", "size": "22934", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "asterix-app/src/main/java/edu/uci/ics/asterix/file/SecondaryInvertedIndexOperationsHelper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3954" }, { "name": "HTML", "bytes": "69593" }, { "name": "Java", "bytes": "7985438" }, { "name": "JavaScript", "bytes": "232059" }, { "name": "Python", "bytes": "264407" }, { "name": "Ruby", "bytes": "1880" }, { "name": "Scheme", "bytes": "1105" }, { "name": "Shell", "bytes": "76117" }, { "name": "Smarty", "bytes": "29789" } ], "symlink_target": "" }
package ch.ethz.globis.phtree.v11.nt; import java.util.NoSuchElementException; import ch.ethz.globis.pht64kd.MaxKTreeI; import ch.ethz.globis.pht64kd.MaxKTreeI.NtEntry; import ch.ethz.globis.pht64kd.MaxKTreeI.PhIterator64; /** * Iterator for the individual nodes in a NodeTree. * * This PhIterator reuses PhEntry objects to avoid unnecessary creation of objects. * Calls to next() and nextKey() will result in creation of new PhEntry and long[] objects * respectively to maintain expected behaviour. However, the nextEntryUnstable() method * returns the internal PhEntry without creating any new objects. The returned PhEntry and long[] * are valid until the next call to nextXXX(). * * @author ztilmann * * @param <T> value type */ public final class NtIteratorMinMax<T> implements PhIterator64<T> { private class PhIteratorStack { private final NtNodeIteratorMinMax<T>[] stack; private int size = 0; @SuppressWarnings("unchecked") public PhIteratorStack(int depth) { stack = new NtNodeIteratorMinMax[depth]; } public boolean isEmpty() { return size == 0; } public NtNodeIteratorMinMax<T> prepareAndPush(NtNode<T> node, long currentPrefix) { NtNodeIteratorMinMax<T> ni = stack[size++]; if (ni == null) { ni = new NtNodeIteratorMinMax<>(); stack[size-1] = ni; } ni.init(min, max, currentPrefix, node, isRootNegative && size==1); return ni; } public NtNodeIteratorMinMax<T> peek() { return stack[size-1]; } public NtNodeIteratorMinMax<T> pop() { return stack[--size]; } } private final PhIteratorStack stack; private long min; private long max; private final boolean isRootNegative; private final NtEntry<T> resultBuf1; private final NtEntry<T> resultBuf2; private boolean isFreeBuf1; boolean isFinished = false; public NtIteratorMinMax(int keyBitWidth) { this.stack = new PhIteratorStack(NtNode.calcTreeHeight(keyBitWidth)); this.isRootNegative = keyBitWidth == 64; this.resultBuf1 = new NtEntry<>(0, new long[keyBitWidth], null); this.resultBuf2 = new NtEntry<>(0, new long[keyBitWidth], null); } @SuppressWarnings("unchecked") @Override public void reset(MaxKTreeI tree, long min, long max) { reset((NtNode<T>)tree.getRoot(), min, max); } @SuppressWarnings("unchecked") @Override public void reset(MaxKTreeI tree) { reset((NtNode<T>)tree.getRoot(), Long.MIN_VALUE, Long.MAX_VALUE); } public PhIterator64<T> reset(NtNode<T> root, long min, long max) { this.min = min; this.max = max; this.stack.size = 0; this.isFinished = false; if (root == null) { //empty index isFinished = true; return this; } stack.prepareAndPush(root, 0); findNextElement(); return this; } private void findNextElement() { NtEntry<T> result = isFreeBuf1 ? resultBuf1 : resultBuf2; while (!stack.isEmpty()) { NtNodeIteratorMinMax<T> p = stack.peek(); while (p.increment(result)) { if (p.isNextSub()) { p = stack.prepareAndPush(p.getCurrentSubNode(), p.getPrefix()); continue; } else { isFreeBuf1 = !isFreeBuf1; return; } } // no matching (more) elements found stack.pop(); } //finished isFinished = true; } @Override public long nextKey() { return nextEntryReuse().getKey(); } @Override public long[] nextKdKey() { long[] key = nextEntryReuse().getKdKey(); long[] ret = new long[key.length]; System.arraycopy(key, 0, ret, 0, key.length); return ret; } @Override public T nextValue() { return nextEntryReuse().getValue(); } @Override public boolean hasNext() { return !isFinished; } @Override @Deprecated public NtEntry<T> nextEntry() { return new NtEntry<>(nextEntryReuse()); } @Override public T next() { return nextEntryReuse().getValue(); } /** * Special 'next' method that avoids creating new objects internally by reusing Entry objects. * Advantage: Should completely avoid any GC effort. * Disadvantage: Returned PhEntries are not stable and are only valid until the * next call to next(). After that they may change state. * @return The next entry */ @Override public NtEntry<T> nextEntryReuse() { if (isFinished) { throw new NoSuchElementException(); } NtEntry<T> ret = isFreeBuf1 ? resultBuf2 : resultBuf1; findNextElement(); return ret; } @Override public void remove() { throw new UnsupportedOperationException(); } }
{ "content_hash": "2218528e78dedf2853641f3d6e747a0f", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 97, "avg_line_length": 24.52777777777778, "alnum_prop": 0.6955832389580974, "repo_name": "tzaeschke/phtree", "id": "cf47fddea273b36faec786be846482b55858098b", "size": "4579", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/ch/ethz/globis/phtree/v11/nt/NtIteratorMinMax.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1942706" } ], "symlink_target": "" }
package org.codehaus.griffon.runtime.core; import griffon.core.*; import groovy.lang.ExpandoMetaClass; import groovy.lang.GroovySystem; import groovy.lang.MetaClass; import groovy.lang.MetaProperty; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.MethodClosure; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import static griffon.util.GriffonApplicationUtils.getConfigValueAsBoolean; /** * Handler for 'Service' artifacts. * * @author Andres Almiray * @since 0.9.1 */ public class ServiceArtifactHandler extends ArtifactHandlerAdapter { private static final Logger LOG = LoggerFactory.getLogger(ServiceArtifactHandler.class); private final Map<String, GriffonService> serviceInstances = new LinkedHashMap<String, GriffonService>(); public ServiceArtifactHandler(GriffonApplication app) { super(app, GriffonServiceClass.TYPE, GriffonServiceClass.TRAILING); MetaClass metaClass = GroovySystem.getMetaClassRegistry().getMetaClass(app.getClass()); if (metaClass instanceof ExpandoMetaClass) { ExpandoMetaClass mc = (ExpandoMetaClass) metaClass; mc.registerInstanceMethod("getServices", new MethodClosure(this, "getServicesInternal")); } } private Map<String, GriffonService> getServicesInternal() { return Collections.unmodifiableMap(serviceInstances); } protected GriffonClass newGriffonClassInstance(Class clazz) { return new DefaultGriffonServiceClass(getApp(), clazz); } public void initialize(ArtifactInfo[] artifacts) { super.initialize(artifacts); if (getConfigValueAsBoolean(getApp(), "griffon.basic_injection.disable")) return; getApp().addApplicationEventListener(this); } /** * Application event listener.<p> * Lazily injects services instances if {@code app.config.griffon.basic_injection.disable} * is not set to true */ public void onNewInstance(Class klass, String t, Object instance) { if (getType().equals(t) || getConfigValueAsBoolean(getApp(), "griffon.basic_injection.disable")) return; MetaClass metaClass = InvokerHelper.getMetaClass(instance); for (MetaProperty property : metaClass.getProperties()) { String propertyName = property.getName(); if (!propertyName.endsWith(getTrailing())) continue; GriffonService serviceInstance = serviceInstances.get(propertyName); if (serviceInstance == null) { GriffonClass griffonClass = findClassFor(propertyName); if (griffonClass != null) { serviceInstance = (GriffonService) griffonClass.newInstance(); InvokerHelper.setProperty(serviceInstance, "app", getApp()); getApp().addApplicationEventListener(serviceInstance); serviceInstances.put(propertyName, serviceInstance); } } if (serviceInstance != null) { if (LOG.isDebugEnabled()) { LOG.debug("Injecting service " + serviceInstance + " on " + instance + " using property '" + propertyName + "'"); } InvokerHelper.setProperty(instance, propertyName, serviceInstance); } } } }
{ "content_hash": "558ddfd5487de0597a811fb5c1727d8c", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 133, "avg_line_length": 40.666666666666664, "alnum_prop": 0.6855971896955504, "repo_name": "breskeby/griffon", "id": "1a247d84e3426c60beff1be5a77b522f02a6b3c7", "size": "4036", "binary": false, "copies": "1", "ref": "refs/heads/multiprojectbuild", "path": "subprojects/rt/src/main/groovy/org/codehaus/griffon/runtime/core/ServiceArtifactHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "1293735" }, { "name": "Java", "bytes": "1211448" }, { "name": "Shell", "bytes": "37376" } ], "symlink_target": "" }
exports.PlainMessage = require('./plain-message'); exports.EncryptedMessage = require('./encrypted-message'); exports.MessageParser = require('./message-parser');
{ "content_hash": "52289ee2e478eec02cecaac5ad2df779", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 58, "avg_line_length": 54, "alnum_prop": 0.7654320987654321, "repo_name": "piranna/telegram-mt-node", "id": "f9128585eb20dbb78c21afe460645dd0ba4aab5c", "size": "340", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lib/message/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "142338" } ], "symlink_target": "" }
/* * @OSF_COPYRIGHT@ */ /* * Mach Operating System * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University * All Rights Reserved. * * Permission to use, copy, modify and distribute this software and its * documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie Mellon * the rights to redistribute these changes. */ /* */ /* * Definitions of general Mach system traps. * * These are the definitions as seen from user-space. * The kernel definitions are in <mach/syscall_sw.h>. * Kernel RPC functions are defined in <mach/mach_interface.h>. */ #ifndef _MACH_MACH_TRAPS_H_ #define _MACH_MACH_TRAPS_H_ #include <stdint.h> #include <mach/std_types.h> #include <mach/mach_types.h> #include <mach/kern_return.h> #include <mach/port.h> #include <mach/vm_types.h> #include <mach/clock_types.h> #include <machine/endian.h> #include <sys/cdefs.h> __BEGIN_DECLS extern kern_return_t clock_sleep_trap( mach_port_name_t clock_name, sleep_type_t sleep_type, int sleep_sec, int sleep_nsec, mach_timespec_t *wakeup_time); extern kern_return_t _kernelrpc_mach_vm_allocate_trap( mach_port_name_t target, mach_vm_offset_t *addr, mach_vm_size_t size, int flags); extern kern_return_t _kernelrpc_mach_vm_deallocate_trap( mach_port_name_t target, mach_vm_address_t address, mach_vm_size_t size ); extern kern_return_t _kernelrpc_mach_vm_protect_trap( mach_port_name_t target, mach_vm_address_t address, mach_vm_size_t size, boolean_t set_maximum, vm_prot_t new_protection ); extern kern_return_t _kernelrpc_mach_vm_map_trap( mach_port_name_t target, mach_vm_offset_t *address, mach_vm_size_t size, mach_vm_offset_t mask, int flags, vm_prot_t cur_protection ); extern kern_return_t _kernelrpc_mach_vm_purgable_control_trap( mach_port_name_t target, mach_vm_offset_t address, vm_purgable_t control, int *state); extern kern_return_t _kernelrpc_mach_port_allocate_trap( mach_port_name_t target, mach_port_right_t right, mach_port_name_t *name ); extern kern_return_t _kernelrpc_mach_port_destroy_trap( mach_port_name_t target, mach_port_name_t name ); extern kern_return_t _kernelrpc_mach_port_deallocate_trap( mach_port_name_t target, mach_port_name_t name ); extern kern_return_t _kernelrpc_mach_port_mod_refs_trap( mach_port_name_t target, mach_port_name_t name, mach_port_right_t right, mach_port_delta_t delta ); extern kern_return_t _kernelrpc_mach_port_move_member_trap( mach_port_name_t target, mach_port_name_t member, mach_port_name_t after ); extern kern_return_t _kernelrpc_mach_port_insert_right_trap( mach_port_name_t target, mach_port_name_t name, mach_port_name_t poly, mach_msg_type_name_t polyPoly ); extern kern_return_t _kernelrpc_mach_port_get_attributes_trap( mach_port_name_t target, mach_port_name_t name, mach_port_flavor_t flavor, mach_port_info_t port_info_out, mach_msg_type_number_t *port_info_outCnt ); extern kern_return_t _kernelrpc_mach_port_insert_member_trap( mach_port_name_t target, mach_port_name_t name, mach_port_name_t pset ); extern kern_return_t _kernelrpc_mach_port_extract_member_trap( mach_port_name_t target, mach_port_name_t name, mach_port_name_t pset ); extern kern_return_t _kernelrpc_mach_port_construct_trap( mach_port_name_t target, mach_port_options_t *options, uint64_t context, mach_port_name_t *name ); extern kern_return_t _kernelrpc_mach_port_destruct_trap( mach_port_name_t target, mach_port_name_t name, mach_port_delta_t srdelta, uint64_t guard ); extern kern_return_t _kernelrpc_mach_port_guard_trap( mach_port_name_t target, mach_port_name_t name, uint64_t guard, boolean_t strict ); extern kern_return_t _kernelrpc_mach_port_unguard_trap( mach_port_name_t target, mach_port_name_t name, uint64_t guard ); extern kern_return_t mach_generate_activity_id( mach_port_name_t target, int count, uint64_t *activity_id ); extern kern_return_t macx_swapon( uint64_t filename, int flags, int size, int priority); extern kern_return_t macx_swapoff( uint64_t filename, int flags); extern kern_return_t macx_triggers( int hi_water, int low_water, int flags, mach_port_t alert_port); extern kern_return_t macx_backing_store_suspend( boolean_t suspend); extern kern_return_t macx_backing_store_recovery( int pid); extern boolean_t swtch_pri(int pri); extern boolean_t swtch(void); extern kern_return_t thread_switch( mach_port_name_t thread_name, int option, mach_msg_timeout_t option_time); extern mach_port_name_t task_self_trap(void); extern kern_return_t host_create_mach_voucher_trap( mach_port_name_t host, mach_voucher_attr_raw_recipe_array_t recipes, int recipes_size, mach_port_name_t *voucher); extern kern_return_t mach_voucher_extract_attr_recipe_trap( mach_port_name_t voucher_name, mach_voucher_attr_key_t key, mach_voucher_attr_raw_recipe_t recipe, mach_msg_type_number_t *recipe_size); extern kern_return_t _kernelrpc_mach_port_type_trap( ipc_space_t task, mach_port_name_t name, mach_port_type_t *ptype); extern kern_return_t _kernelrpc_mach_port_request_notification_trap( ipc_space_t task, mach_port_name_t name, mach_msg_id_t msgid, mach_port_mscount_t sync, mach_port_name_t notify, mach_msg_type_name_t notifyPoly, mach_port_name_t *previous); /* * Obsolete interfaces. */ extern kern_return_t task_for_pid( mach_port_name_t target_tport, int pid, mach_port_name_t *t); extern kern_return_t task_name_for_pid( mach_port_name_t target_tport, int pid, mach_port_name_t *tn); extern kern_return_t pid_for_task( mach_port_name_t t, int *x); extern kern_return_t debug_control_port_for_pid( mach_port_name_t target_tport, int pid, mach_port_name_t *t); __END_DECLS #endif /* _MACH_MACH_TRAPS_H_ */
{ "content_hash": "487a1784c04594221bd819ed518c3426", "timestamp": "", "source": "github", "line_count": 277, "max_line_length": 75, "avg_line_length": 23.418772563176894, "alnum_prop": 0.7337752427932789, "repo_name": "raulgrell/zig", "id": "d3aaf577eded1f9768b74654c590f73e144fc241", "size": "7811", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/libc/include/x86_64-macos-gnu/mach/mach_traps.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1187" }, { "name": "C", "bytes": "187893" }, { "name": "C++", "bytes": "3749750" }, { "name": "CMake", "bytes": "38091" }, { "name": "HTML", "bytes": "15836" }, { "name": "JavaScript", "bytes": "73253" }, { "name": "Shell", "bytes": "17887" }, { "name": "Zig", "bytes": "17407339" } ], "symlink_target": "" }
<!-- ======================================================================= --> <!-- caGrid 1.0 SDK Query Processor build file --> <!-- ======================================================================= --> <project name="sdkQuery" default="all" basedir="."> <!-- Environment --> <property environment="env" /> <property file="${basedir}/build.properties" /> <property file="${user.dir}/build.properties" /> <property file="${basedir}/ext/resources/cagrid.properties" /> <property name="globus.dir" location="${env.GLOBUS_LOCATION}" /> <!-- build with debugging information --> <property name="java.debug" value="on" /> <!-- enforce java 1.5 compliance at build time --> <property name="java.source" value="1.5" /> <!-- Information --> <property name="project.version" value="${cagrid.master.project.version}" /> <property name="project.name" value="${cagrid.master.project.name}-${project.version}-${ant.project.name}" /> <property name="project.jar.prefix" value="${cagrid.master.jar.prefix}${ant.project.name}${cagrid.master.jar.separator}" /> <!-- build output dirs --> <property name="build.dir" location="build" /> <property name="build.dest" location="${build.dir}/classes"/> <property name="build.jars.dir" location="build/lib" /> <!-- jar names --> <property name="project.jar.name" value="${project.jar.prefix}core.jar"/> <!-- jar files --> <property name="project.jar.file" value="${build.jars.dir}/${project.jar.name}"/> <!-- source directories --> <property name="src.dir" location="${basedir}/src/java"/> <!-- libraries --> <property name="lib.dir" location="${basedir}/lib"/> <property name="ext.lib.dir" location="${basedir}/ext/lib"/> <property name="ext.test.lib.dir" location="${basedir}/ext/test/lib"/> <!-- testing stuff --> <property name="test.dir" location="${basedir}/test" /> <property name="test.src.dir" location="${test.dir}/src/java" /> <property name="test.classes.dir" location="${build.dir}/test/classes" /> <property name="test.lib.dir" location="${test.dir}/lib" /> <property name="test.logs.dir" location="${test.dir}/logs" /> <property name="test.project.jar" location="${build.jars.dir}/${project.jar.prefix}tests.jar" /> <import file="test/test.xml" /> <!-- =============================================================== --> <!-- The Test Classpath --> <!-- =============================================================== --> <path id="test.classpath"> <!-- <pathelement path="${basedir}/ext/resources"/> --> <fileset dir="${lib.dir}"> <include name="**/*.jar" /> </fileset> <fileset dir="${ext.lib.dir}"> <include name="**/*.jar" /> <!-- this is here until the authz project fixes their build artifacts --> <exclude name="asm.jar"/> </fileset> <fileset dir="${test.lib.dir}"> <include name="**/*.jar" /> </fileset> <fileset dir="${ext.test.lib.dir}"> <include name="**/*.jar" /> </fileset> <fileset dir="${globus.dir}/lib"> <include name="**/*.jar" /> </fileset> </path> <!-- creates output directories --> <target name="init"> <mkdir dir="${build.dir}" /> <mkdir dir="${build.dest}"/> <mkdir dir="${build.jars.dir}" /> <mkdir dir="${test.classes.dir}"/> </target> <!-- compiles the query processor source code --> <target name="compile" depends="init"> <javac srcdir="${src.dir}" destdir="${build.dest}" debug="${java.debug}" source="${java.source}"> <classpath> <fileset dir="${lib.dir}"> <include name="*.jar"/> </fileset> <fileset dir="${ext.lib.dir}"> <include name="*.jar"/> </fileset> <fileset dir="${globus.dir}/lib"> <include name="*.jar" /> </fileset> </classpath> <include name="**/*.java" /> </javac> </target> <!-- compiles the testing source code --> <target name="compileTests" depends="compile"> <javac srcdir="${test.src.dir}" destdir="${test.classes.dir}" debug="${java.debug}" source="${java.source}"> <classpath> <pathelement path="${build.dest}"/> <fileset dir="${lib.dir}"> <include name="*.jar"/> </fileset> <fileset dir="${ext.lib.dir}"> <include name="*.jar"/> </fileset> <fileset dir="${ext.test.lib.dir}"> <include name="*.jar"/> </fileset> <fileset dir="${globus.dir}/lib"> <include name="*.jar" /> </fileset> </classpath> <include name="**/*.java"/> </javac> </target> <!-- jars the classes --> <target name="jar" depends="compile" description="Builds the jar file"> <jar destfile="${project.jar.file}"> <fileset dir="${build.dest}"> <include name="**/*.class"/> </fileset> <fileset dir="${src.dir}"> <include name="**/*.java"/> </fileset> </jar> </target> <!-- jars the tests --> <target name="jarTests" depends="compileTests" description="Builds the testing jar file"> <jar destfile="${test.project.jar}"> <fileset dir="${test.classes.dir}"> <include name="**/*.class"/> </fileset> </jar> </target> <!-- removes all build output --> <target name="clean"> <delete dir="${build.dir}" /> </target> <!-- build and jar everything --> <target name="all" depends="jar, jarTests" description="Builds and jars all the classes in the project"/> </project>
{ "content_hash": "3499d955c613e2cfefc9f3475c4410df", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 127, "avg_line_length": 35.973684210526315, "alnum_prop": 0.5550475493782004, "repo_name": "CBIIT/caaers", "id": "07214448a6e876b91f0b8ef48267e8e2a1ace56b", "size": "5468", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "caAERS/software/grid/introduce/sdkQuery/build.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AGS Script", "bytes": "127" }, { "name": "AspectJ", "bytes": "2052" }, { "name": "Batchfile", "bytes": "778" }, { "name": "CSS", "bytes": "150327" }, { "name": "Cucumber", "bytes": "666" }, { "name": "Groovy", "bytes": "19198183" }, { "name": "HTML", "bytes": "78184618" }, { "name": "Java", "bytes": "14455656" }, { "name": "JavaScript", "bytes": "439130" }, { "name": "PLSQL", "bytes": "75583" }, { "name": "PLpgSQL", "bytes": "34461" }, { "name": "Ruby", "bytes": "29724" }, { "name": "Shell", "bytes": "14770" }, { "name": "XSLT", "bytes": "1262163" } ], "symlink_target": "" }
package org.apache.hadoop.hbase.util; import java.io.IOException; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.classification.InterfaceAudience; import org.apache.hadoop.hbase.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellComparator; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.DoNotRetryIOException; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HBaseInterfaceAudience; import org.apache.hadoop.hbase.io.compress.Compression; import org.apache.hadoop.hbase.io.hfile.HFileWriterImpl; import org.apache.hadoop.hbase.io.hfile.CacheConfig; import org.apache.hadoop.hbase.io.hfile.HFile; import org.apache.hadoop.hbase.io.hfile.HFileContext; import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder; import org.apache.hadoop.hbase.io.hfile.HFileScanner; import org.apache.hadoop.io.compress.Compressor; /** * Compression validation test. Checks compression is working. Be sure to run * on every node in your cluster. */ @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS) @InterfaceStability.Evolving public class CompressionTest { static final Log LOG = LogFactory.getLog(CompressionTest.class); public static boolean testCompression(String codec) { codec = codec.toLowerCase(); Compression.Algorithm a; try { a = Compression.getCompressionAlgorithmByName(codec); } catch (IllegalArgumentException e) { LOG.warn("Codec type: " + codec + " is not known"); return false; } try { testCompression(a); return true; } catch (IOException ignored) { LOG.warn("Can't instantiate codec: " + codec, ignored); return false; } } private final static Boolean[] compressionTestResults = new Boolean[Compression.Algorithm.values().length]; static { for (int i = 0 ; i < compressionTestResults.length ; ++i) { compressionTestResults[i] = null; } } public static void testCompression(Compression.Algorithm algo) throws IOException { if (compressionTestResults[algo.ordinal()] != null) { if (compressionTestResults[algo.ordinal()]) { return ; // already passed test, dont do it again. } else { // failed. throw new DoNotRetryIOException("Compression algorithm '" + algo.getName() + "'" + " previously failed test."); } } try { Compressor c = algo.getCompressor(); algo.returnCompressor(c); compressionTestResults[algo.ordinal()] = true; // passes } catch (Throwable t) { compressionTestResults[algo.ordinal()] = false; // failure throw new DoNotRetryIOException(t); } } protected static Path path = new Path(".hfile-comp-test"); public static void usage() { System.err.println( "Usage: CompressionTest <path> " + StringUtils.join( Compression.Algorithm.values(), "|").toLowerCase() + "\n" + "For example:\n" + " hbase " + CompressionTest.class + " file:///tmp/testfile gz\n"); System.exit(1); } public static void doSmokeTest(FileSystem fs, Path path, String codec) throws Exception { Configuration conf = HBaseConfiguration.create(); HFileContext context = new HFileContextBuilder() .withCompression(HFileWriterImpl.compressionByName(codec)).build(); HFile.Writer writer = HFile.getWriterFactoryNoCache(conf) .withPath(fs, path) .withFileContext(context) .create(); // Write any-old Cell... final byte [] rowKey = Bytes.toBytes("compressiontestkey"); Cell c = CellUtil.createCell(rowKey, Bytes.toBytes("compressiontestval")); writer.append(c); writer.appendFileInfo(Bytes.toBytes("compressioninfokey"), Bytes.toBytes("compressioninfoval")); writer.close(); Cell cc = null; HFile.Reader reader = HFile.createReader(fs, path, new CacheConfig(conf), conf); try { reader.loadFileInfo(); HFileScanner scanner = reader.getScanner(false, true); scanner.seekTo(); // position to the start of file // Scanner does not do Cells yet. Do below for now till fixed. cc = scanner.getKeyValue(); if (CellComparator.compareRows(c, cc) != 0) { throw new Exception("Read back incorrect result: " + c.toString() + " vs " + cc.toString()); } } finally { reader.close(); } } public static void main(String[] args) throws Exception { if (args.length != 2) { usage(); System.exit(1); } Configuration conf = new Configuration(); Path path = new Path(args[0]); FileSystem fs = path.getFileSystem(conf); if (fs.exists(path)) { System.err.println("The specified path exists, aborting!"); System.exit(1); } try { doSmokeTest(fs, path, args[1]); } finally { fs.delete(path, false); } System.out.println("SUCCESS"); } }
{ "content_hash": "8f70d4892b6c67e3ee35ddc190c38512", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 100, "avg_line_length": 33.62987012987013, "alnum_prop": 0.686425950955783, "repo_name": "andrewmains12/hbase", "id": "a9cc1c65ed4ecb45bfe2b38519e9cf3f4ef7e8ae", "size": "5988", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hbase-server/src/main/java/org/apache/hadoop/hbase/util/CompressionTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "351" }, { "name": "C", "bytes": "28617" }, { "name": "C++", "bytes": "770077" }, { "name": "CMake", "bytes": "10933" }, { "name": "CSS", "bytes": "68278" }, { "name": "HTML", "bytes": "70903" }, { "name": "Java", "bytes": "26103712" }, { "name": "JavaScript", "bytes": "2694" }, { "name": "Makefile", "bytes": "1409" }, { "name": "PHP", "bytes": "413443" }, { "name": "Perl", "bytes": "383793" }, { "name": "Protocol Buffer", "bytes": "146716" }, { "name": "Python", "bytes": "539649" }, { "name": "Ruby", "bytes": "508085" }, { "name": "Shell", "bytes": "227181" }, { "name": "Thrift", "bytes": "39010" }, { "name": "XSLT", "bytes": "2892" } ], "symlink_target": "" }
<?php namespace Listreat\ApiBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class ListreatApiExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); } }
{ "content_hash": "7791f08145f2f2efeecf860e2c93cb93", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 104, "avg_line_length": 31.428571428571427, "alnum_prop": 0.7272727272727273, "repo_name": "cgeoffray/LisTreat", "id": "dc9ff3e52b17d6deeecc6df9e865f4c3f59dc541", "size": "880", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Listreat/ApiBundle/DependencyInjection/ListreatMainExtension.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2232197" }, { "name": "PHP", "bytes": "126662" } ], "symlink_target": "" }