text
stringlengths
2
1.04M
meta
dict
import {Tooltip} from "./tooltip" import {elt, insertCSS} from "../dom" import {defineParamHandler} from "../edit" import sortedInsert from "../util/sortedinsert" import {getIcon} from "./icons" export class Menu { constructor(pm, display) { this.display = display this.stack = [] this.pm = pm } show(content, displayInfo) { this.stack.length = 0 this.enter(content, displayInfo) } reset() { this.stack.length = 0 this.display.reset() } enter(content, displayInfo) { let pieces = [], explore = value => { if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) explore(value[i]) pieces.push(separator) } else if (!value.select || value.select(this.pm)) { pieces.push(value) } } explore(content) // Remove superfluous separators for (let i = 0; i < pieces.length; i++) if (pieces[i] == separator && (i == 0 || i == pieces.length - 1 || pieces[i + 1] == separator)) pieces.splice(i--, 1) if (!pieces.length) return this.display.clear() this.stack.push(pieces) this.draw(displayInfo) } get active() { return this.stack.length > 1 } draw(displayInfo) { let cur = this.stack[this.stack.length - 1] let rendered = elt("div", {class: "ProseMirror-menu"}, cur.map(item => renderItem(item, this))) if (this.stack.length > 1) this.display.enter(rendered, () => this.leave(), displayInfo) else this.display.show(rendered, displayInfo) } leave() { this.stack.pop() if (this.stack.length) this.draw() else this.display.reset() } } export class TooltipDisplay { constructor(tooltip, resetFunc) { this.tooltip = tooltip this.resetFunc = resetFunc } clear() { this.tooltip.close() } reset() { if (this.resetFunc) this.resetFunc() else this.clear() } show(dom, info) { this.tooltip.open(dom, info) } enter(dom, back, info) { let button = elt("div", {class: "ProseMirror-tooltip-back", title: "Back"}) button.addEventListener("mousedown", e => { e.preventDefault(); e.stopPropagation() back() }) this.show(elt("div", {class: "ProseMirror-tooltip-back-wrapper"}, dom, button), info) } } function title(pm, command) { let key = pm.keyForCommand(command.name) return key ? command.label + " (" + key + ")" : command.label } function renderIcon(command, menu) { let icon = resolveIcon(menu.pm, command) if (command.active(menu.pm)) icon.className += " ProseMirror-icon-active" let dom = elt("span", {class: "ProseMirror-menuicon", title: title(menu.pm, command)}, icon) dom.addEventListener("mousedown", e => { e.preventDefault(); e.stopPropagation() if (!command.params.length) { command.exec(menu.pm) menu.reset() } else if (command.params.length == 1 && command.params[0].type == "select") { showSelectMenu(menu.pm, command, dom) } else { menu.enter(readParams(command)) } }) return dom } function resolveIcon(pm, command) { for (;;) { let icon = command.info.icon if (!icon) break if (icon.from) { command = pm.commands[icon.from] if (!command) break } else { return getIcon(command.name, icon) } } return elt("span", null, "?") // FIXME saner default? } function renderSelect(item, menu) { let param = item.params[0] let value = !param.default ? null : param.default.call ? param.default(menu.pm) : param.default let dom = elt("div", {class: "ProseMirror-select ProseMirror-select-command-" + item.name, title: item.label}, !value ? (param.defaultLabel || "Select...") : value.display ? value.display(value) : value.label) dom.addEventListener("mousedown", e => { e.preventDefault(); e.stopPropagation() showSelectMenu(menu.pm, item, dom) }) return dom } export function showSelectMenu(pm, item, dom) { let param = item.params[0] let options = param.options.call ? param.options(pm) : param.options let menu = elt("div", {class: "ProseMirror-select-menu"}, options.map(o => { let dom = elt("div", null, o.display ? o.display(o) : o.label) dom.addEventListener("mousedown", e => { e.preventDefault() item.exec(pm, [o.value]) finish() }) return dom })) let pos = dom.getBoundingClientRect(), box = pm.wrapper.getBoundingClientRect() menu.style.left = (pos.left - box.left - 2) + "px" menu.style.top = (pos.top - box.top - 2) + "px" let done = false function finish() { if (done) return done = true document.body.removeEventListener("mousedown", finish) document.body.removeEventListener("keydown", finish) pm.wrapper.removeChild(menu) } document.body.addEventListener("mousedown", finish) document.body.addEventListener("keydown", finish) pm.wrapper.appendChild(menu) } function renderItem(item, menu) { if (item.display == "icon") return renderIcon(item, menu) else if (item.display == "select") return renderSelect(item, menu) else if (!item.display) throw new Error("Command " + item.name + " can not be shown in a menu") else return item.display(menu) } function buildParamForm(pm, command) { let prefill = command.info.prefillParams && command.info.prefillParams(pm) let fields = command.params.map((param, i) => { let field, name = "field_" + i let val = prefill ? prefill[i] : param.default || "" if (param.type == "text") field = elt("input", {name, type: "text", placeholder: param.name, value: val, autocomplete: "off"}) else if (param.type == "select") field = elt("select", {name}, (param.options.call ? param.options(pm) : param.options) .map(o => elt("option", {value: o.value, selected: o == val}, o.label))) else // FIXME more types throw new Error("Unsupported parameter type: " + param.type) return elt("div", null, field) }) return elt("form", null, fields) } function gatherParams(pm, command, form) { let bad = false let params = command.params.map((param, i) => { let val = form.elements["field_" + i].value if (val) return val if (param.default == null) bad = true else return param.default.call ? param.default(pm) : param.default }) return bad ? null : params } function paramForm(pm, command, callback) { let form = buildParamForm(pm, command), done = false let finish = result => { if (!done) { done = true callback(result) } } let submit = () => { // FIXME error messages finish(gatherParams(pm, command, form)) } form.addEventListener("submit", e => { e.preventDefault() submit() }) form.addEventListener("keydown", e => { if (e.keyCode == 27) { finish(null) } else if (e.keyCode == 13 && !(e.ctrlKey || e.metaKey || e.shiftKey)) { e.preventDefault() submit() } }) // FIXME too hacky? setTimeout(() => { let input = form.querySelector("input, textarea") if (input) input.focus() }, 20) return form } export function readParams(command) { return {display(menu) { return paramForm(menu.pm, command, params => { menu.pm.focus() if (params) { command.exec(menu.pm, params) menu.reset() } else { menu.leave() } }) }} } const separator = { display() { return elt("div", {class: "ProseMirror-menuseparator"}) } } export function commandGroups(pm, ...names) { return names.map(group => { let found = [] for (let name in pm.commands) { let cmd = pm.commands[name] if (cmd.info.menuGroup && cmd.info.menuGroup == group) sortedInsert(found, cmd, (a, b) => (a.info.menuRank || 50) - (b.info.menuRank || 50)) } return found }) } function tooltipParamHandler(pm, command, callback) { let tooltip = new Tooltip(pm, "center") tooltip.open(paramForm(pm, command, params => { pm.focus() tooltip.close() callback(params) })) } defineParamHandler("default", tooltipParamHandler) defineParamHandler("tooltip", tooltipParamHandler) // FIXME check for obsolete styles insertCSS(` .ProseMirror-menu { margin: 0 -4px; line-height: 1; white-space: pre; } .ProseMirror-tooltip .ProseMirror-menu { width: -webkit-fit-content; width: fit-content; } .ProseMirror-tooltip-back-wrapper { padding-left: 12px; } .ProseMirror-tooltip-back { position: absolute; top: 5px; left: 5px; cursor: pointer; } .ProseMirror-tooltip-back:after { content: "«"; } .ProseMirror-menuicon { margin: 0 7px; } .ProseMirror-menuseparator { display: inline-block; } .ProseMirror-menuseparator:after { content: "︙"; opacity: 0.5; padding: 0 4px; vertical-align: baseline; } .ProseMirror-select, .ProseMirror-select-menu { border: 1px solid #777; border-radius: 3px; font-size: 90%; } .ProseMirror-select { padding: 1px 12px 1px 4px; display: inline-block; vertical-align: middle; position: relative; cursor: pointer; margin: 0 8px; } .ProseMirror-select-command-textblockType { min-width: 3.2em; } .ProseMirror-select:after { content: "▿"; color: #777; position: absolute; right: 4px; } .ProseMirror-select-menu { position: absolute; background: #444; color: white; padding: 2px 2px; z-index: 15; } .ProseMirror-select-menu div { cursor: pointer; padding: 0 1em 0 2px; } .ProseMirror-select-menu div:hover { background: #777; } `)
{ "content_hash": "e1df1dce797613fbf092dc39e17c7a91", "timestamp": "", "source": "github", "line_count": 370, "max_line_length": 114, "avg_line_length": 25.708108108108107, "alnum_prop": 0.6264718250630782, "repo_name": "tecnogram888/prosemirror", "id": "8f781abda9d1c453a93c2deae9e2f7603f689174", "size": "9517", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/menu/menu.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "256" }, { "name": "HTML", "bytes": "4413" }, { "name": "JavaScript", "bytes": "346748" }, { "name": "Makefile", "bytes": "429" } ], "symlink_target": "" }
'use strict'; var path = require('path'); var grammar = require('./grammar.js'); function Parser() {} Parser.prototype.parse = function (src) { return grammar.parse(src); }; module.exports = Parser;
{ "content_hash": "4675840a5fa3df661b877ad22805d12c", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 41, "avg_line_length": 17.25, "alnum_prop": 0.6666666666666666, "repo_name": "djinn-games/djinn-parser", "id": "5ebfedef55711ff4f2b500991dbf9d6afc739d8c", "size": "207", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "lib/parser/browser.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "48861" }, { "name": "Yacc", "bytes": "12377" }, { "name": "xBase", "bytes": "4425" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> :root { --background: white; } @media (prefers-color-scheme: dark) { :root { --background: black; } } html, body { margin: 0; padding: 0; background: var(--background); } iframe { border: none; width: 100%; background: var(--background); } </style> </head> <body> <!-- NOTE: xslt 中引用的 js,只有在 iframe 中才能执行, 直接用 document.replace() 替换当前内容,不会执行引用的 JS 代码。 --> <iframe id="apidoc"></iframe> <script> async function loadXML(path) { const obj = await fetch(path); return (new DOMParser()).parseFromString(await obj.text(), "text/xml"); } function changeFrameHeight() { const iframe = document.getElementById("apidoc"); iframe.height = document.documentElement.clientHeight; } window.onresize = function () { changeFrameHeight(); } const queries = new URLSearchParams(window.location.search); const url = queries.get('url'); async function init() { const processor = new XSLTProcessor(); processor.importStylesheet(await loadXML('./apidoc.xsl')); const xml = await loadXML(url); const doc = processor.transformToDocument(xml); const html = (new XMLSerializer()).serializeToString(doc); const blob = new Blob([html], { type: 'text/html' }) const obj = URL.createObjectURL(blob) const iframe = document.getElementById('apidoc'); iframe.src = obj; iframe.addEventListener('load', (e) => { changeFrameHeight(); }); } try{ init() } catch (e) { console.error(e) } </script> </body> </html>
{ "content_hash": "881ddb1d1856ff218661a2ec5ac199bb", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 79, "avg_line_length": 23.678571428571427, "alnum_prop": 0.5686274509803921, "repo_name": "caixw/apidoc", "id": "e881f60a951e6016adc50be20f7fab76dd5e560d", "size": "2057", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/v5/view.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "348" }, { "name": "Dockerfile", "bytes": "112" }, { "name": "Go", "bytes": "750447" }, { "name": "PHP", "bytes": "171" }, { "name": "Shell", "bytes": "672" } ], "symlink_target": "" }
package Interface.exceptions; public class ConferenceNotFoundException extends Exception { private static final long serialVersionUID = -6544930467932823977L; public String[] args; public ConferenceNotFoundException() { this.args = new String[0]; } public ConferenceNotFoundException(final String message) { super(message); this.args = new String[0]; } }
{ "content_hash": "d6de5e17b5e1f91d3e9c3362b2174786", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 68, "avg_line_length": 20.88888888888889, "alnum_prop": 0.7606382978723404, "repo_name": "FranciscoKnebel/ufrgs-projects", "id": "c87c54004455a11f8b2831ea6d2da190893a7289", "size": "376", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PeerReview-Alligator/project/src/Interface/exceptions/ConferenceNotFoundException.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "7394" }, { "name": "C", "bytes": "7612048" }, { "name": "C#", "bytes": "72179" }, { "name": "C++", "bytes": "11421" }, { "name": "CSS", "bytes": "228414" }, { "name": "HTML", "bytes": "229777" }, { "name": "Java", "bytes": "47807" }, { "name": "JavaScript", "bytes": "67323" }, { "name": "Makefile", "bytes": "10628" }, { "name": "Objective-C", "bytes": "636" }, { "name": "PowerShell", "bytes": "4328" }, { "name": "Shell", "bytes": "18272" }, { "name": "Stata", "bytes": "8780" }, { "name": "SystemVerilog", "bytes": "1939" }, { "name": "Tcl", "bytes": "34853" }, { "name": "VHDL", "bytes": "483247" }, { "name": "Verilog", "bytes": "510" }, { "name": "XSLT", "bytes": "1422" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="triaina.webview" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="13" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application/> </manifest>
{ "content_hash": "846d7167c10a17d34e01f149cc841e39", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 78, "avg_line_length": 38.18181818181818, "alnum_prop": 0.7047619047619048, "repo_name": "vishyrich/triaina", "id": "9d92d6c8dc972928fcbed821ef24caa8e7ad8f99", "size": "420", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "android/WebViewBridge/AndroidManifest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "208" }, { "name": "Groovy", "bytes": "6894" }, { "name": "Java", "bytes": "664190" }, { "name": "JavaScript", "bytes": "12449" }, { "name": "Objective-C", "bytes": "33758" }, { "name": "Shell", "bytes": "861" } ], "symlink_target": "" }
<?php class FilterHandlerTest extends ehough_epilog_TestCase { private $_closure_testHandleWithCallback_test; /** * @covers ehough_epilog_handler_FilterHandler::isHandling */ public function testIsHandling() { $test = new ehough_epilog_handler_TestHandler(); $handler = new ehough_epilog_handler_FilterHandler($test, ehough_epilog_Logger::INFO, ehough_epilog_Logger::NOTICE); $this->assertFalse($handler->isHandling($this->getRecord(ehough_epilog_Logger::DEBUG))); $this->assertTrue($handler->isHandling($this->getRecord(ehough_epilog_Logger::INFO))); $this->assertTrue($handler->isHandling($this->getRecord(ehough_epilog_Logger::NOTICE))); $this->assertFalse($handler->isHandling($this->getRecord(ehough_epilog_Logger::WARNING))); $this->assertFalse($handler->isHandling($this->getRecord(ehough_epilog_Logger::ERROR))); $this->assertFalse($handler->isHandling($this->getRecord(ehough_epilog_Logger::CRITICAL))); $this->assertFalse($handler->isHandling($this->getRecord(ehough_epilog_Logger::ALERT))); $this->assertFalse($handler->isHandling($this->getRecord(ehough_epilog_Logger::EMERGENCY))); } /** * @covers ehough_epilog_handler_FilterHandler::handle * @covers ehough_epilog_handler_FilterHandler::setAcceptedLevels * @covers ehough_epilog_handler_FilterHandler::isHandling */ public function testHandleProcessOnlyNeededLevels() { $test = new ehough_epilog_handler_TestHandler(); $handler = new ehough_epilog_handler_FilterHandler($test, ehough_epilog_Logger::INFO, ehough_epilog_Logger::NOTICE); $handler->handle($this->getRecord(ehough_epilog_Logger::DEBUG)); $this->assertFalse($test->hasDebugRecords()); $handler->handle($this->getRecord(ehough_epilog_Logger::INFO)); $this->assertTrue($test->hasInfoRecords()); $handler->handle($this->getRecord(ehough_epilog_Logger::NOTICE)); $this->assertTrue($test->hasNoticeRecords()); $handler->handle($this->getRecord(ehough_epilog_Logger::WARNING)); $this->assertFalse($test->hasWarningRecords()); $handler->handle($this->getRecord(ehough_epilog_Logger::ERROR)); $this->assertFalse($test->hasErrorRecords()); $handler->handle($this->getRecord(ehough_epilog_Logger::CRITICAL)); $this->assertFalse($test->hasCriticalRecords()); $handler->handle($this->getRecord(ehough_epilog_Logger::ALERT)); $this->assertFalse($test->hasAlertRecords()); $handler->handle($this->getRecord(ehough_epilog_Logger::EMERGENCY)); $this->assertFalse($test->hasEmergencyRecords()); $test = new ehough_epilog_handler_TestHandler(); $handler = new ehough_epilog_handler_FilterHandler($test, array(ehough_epilog_Logger::INFO, ehough_epilog_Logger::ERROR)); $handler->handle($this->getRecord(ehough_epilog_Logger::DEBUG)); $this->assertFalse($test->hasDebugRecords()); $handler->handle($this->getRecord(ehough_epilog_Logger::INFO)); $this->assertTrue($test->hasInfoRecords()); $handler->handle($this->getRecord(ehough_epilog_Logger::NOTICE)); $this->assertFalse($test->hasNoticeRecords()); $handler->handle($this->getRecord(ehough_epilog_Logger::ERROR)); $this->assertTrue($test->hasErrorRecords()); $handler->handle($this->getRecord(ehough_epilog_Logger::CRITICAL)); $this->assertFalse($test->hasCriticalRecords()); } /** * @covers ehough_epilog_handler_FilterHandler::setAcceptedLevels * @covers ehough_epilog_handler_FilterHandler::getAcceptedLevels */ public function testAcceptedLevelApi() { $test = new ehough_epilog_handler_TestHandler(); $handler = new ehough_epilog_handler_FilterHandler($test); $levels = array(ehough_epilog_Logger::INFO, ehough_epilog_Logger::ERROR); $handler->setAcceptedLevels($levels); $this->assertSame($levels, $handler->getAcceptedLevels()); } /** * @covers ehough_epilog_handler_FilterHandler::handle */ public function testHandleUsesProcessors() { $test = new ehough_epilog_handler_TestHandler(); $handler = new ehough_epilog_handler_FilterHandler($test, ehough_epilog_Logger::DEBUG, ehough_epilog_Logger::EMERGENCY); $handler->pushProcessor( array($this, '__callback_testHandleUsesProcessors') ); $handler->handle($this->getRecord(ehough_epilog_Logger::WARNING)); $this->assertTrue($test->hasWarningRecords()); $records = $test->getRecords(); $this->assertTrue($records[0]['extra']['foo']); } public function __callback_testHandleUsesProcessors($record) { $record['extra']['foo'] = true; return $record; } /** * @covers ehough_epilog_handler_FilterHandler::handle */ public function testHandlerespectsBubble() { $test = new ehough_epilog_handler_TestHandler(); $handler = new ehough_epilog_handler_FilterHandler($test, ehough_epilog_Logger::INFO, ehough_epilog_Logger::NOTICE, false); $this->assertTrue($handler->handle($this->getRecord(ehough_epilog_Logger::INFO))); $this->assertFalse($handler->handle($this->getRecord(ehough_epilog_Logger::WARNING))); $handler = new ehough_epilog_handler_FilterHandler($test, ehough_epilog_Logger::INFO, ehough_epilog_Logger::NOTICE, true); $this->assertFalse($handler->handle($this->getRecord(ehough_epilog_Logger::INFO))); $this->assertFalse($handler->handle($this->getRecord(ehough_epilog_Logger::WARNING))); } /** * @covers ehough_epilog_handler_FilterHandler::handle */ public function testHandleWithCallback() { $this->_closure_testHandleWithCallback_test = new ehough_epilog_handler_TestHandler(); $handler = new ehough_epilog_handler_FilterHandler( array($this, '__callback_testHandleWithCallback'), ehough_epilog_Logger::INFO, ehough_epilog_Logger::NOTICE, false ); $handler->handle($this->getRecord(ehough_epilog_Logger::DEBUG)); $handler->handle($this->getRecord(ehough_epilog_Logger::INFO)); $this->assertFalse($this->_closure_testHandleWithCallback_test->hasDebugRecords()); $this->assertTrue($this->_closure_testHandleWithCallback_test->hasInfoRecords()); } public function __callback_testHandleWithCallback($record, $handler) { return $this->_closure_testHandleWithCallback_test; } /** * @covers ehough_epilog_handler_FilterHandler::handle * @expectedException RuntimeException */ public function testHandleWithBadCallbackThrowsException() { $handler = new ehough_epilog_handler_FilterHandler( array($this, '__callback_testHandleWithBadCallbackThrowsException') ); $handler->handle($this->getRecord(ehough_epilog_Logger::WARNING)); } public function __callback_testHandleWithBadCallbackThrowsException($record, $handler) { return 'foo'; } }
{ "content_hash": "954df69bf76d050dd08861b0321b0f78", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 131, "avg_line_length": 45.5859872611465, "alnum_prop": 0.6706720693027804, "repo_name": "ehough/epilog", "id": "5cc63063fd4f4fb83eb0da9fe401d3ea804edc7b", "size": "7157", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/test/php/ehough/epilog/handler/FilterHandlerTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "432495" } ], "symlink_target": "" }
<div class="code-block"> <div class="code-block__wrapper" data-syntax="scss"> ```scss /** * Nav specificiteit fix. * * Iemand gebruikte een ID in de headercode (`#header a {}`) die de nav * selectors overtroeft (`.site-nav a {}`). Gebruik !Important om het * te negeren totdat ik tijd heb om de koptekst te refactoren. */ .site-nav a { color: #BADA55 !important; } ``` </div> <div class="code-block__wrapper" data-syntax="sass"> ```sass /** * Nav specificiteit fix. * * Iemand gebruikte een ID in de headercode (`#header a {}`) die de nav * selectors overtroeft (`.site-nav a {}`). Gebruik !Important om het * te negeren totdat ik tijd heb om de koptekst te refactoren. */ .site-nav a color: #BADA55 !important ``` </div> </div>
{ "content_hash": "bf5106bb63bb72bf2c66c54b5394f529", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 71, "avg_line_length": 25.266666666666666, "alnum_prop": 0.6517150395778364, "repo_name": "HugoGiraudel/sass-guidelines", "id": "f6cddc8fc7beed5b4622248c0cef63c5f6f7d1bc", "size": "758", "binary": false, "copies": "1", "ref": "refs/heads/dependabot/npm_and_yarn/clean-css-cli-5.3.0", "path": "_includes/snippets/architecture/04/nl.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18615" }, { "name": "HTML", "bytes": "249305" }, { "name": "JavaScript", "bytes": "11334" }, { "name": "Ruby", "bytes": "2354" }, { "name": "Shell", "bytes": "803" } ], "symlink_target": "" }
jest.dontMock('../../components/shared/Star.jsx'); import React from 'react/addons'; import Star from '../../components/shared/Star.jsx'; const TestUtils = React.addons.TestUtils; function renderedOutput(elt) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(elt); return shallowRenderer.getRenderOutput(); } describe('<Star />', () => { let shallowStar, star, button; beforeEach(() => { shallowStar = renderedOutput(<Star repo='Blazar' branch='master'></Star>); star = TestUtils.renderIntoDocument(<Star repo='apple' branch='bacon'></Star>); button = TestUtils.findRenderedDOMComponentWithClass( star, 'sidebar__star' ); }); it('should have the right tag', () => { expect(shallowStar.type).toBe('span'); }); it('should call event handler when clicked', () => { star.setState({ starred: false }); expect(button.props.className).toBe('sidebar__star unselected'); }); });
{ "content_hash": "b6960a2c431f3aff2247444cbc3d4ae8", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 83, "avg_line_length": 26.694444444444443, "alnum_prop": 0.6711758584807492, "repo_name": "cgvarela/Blazar", "id": "8f7b7e351f565b73244cf7d0d0c36da05023c957", "size": "961", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BlazarUI/app/scripts/__tests__/shared/Star_spec.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "17581" }, { "name": "HTML", "bytes": "2480" }, { "name": "Java", "bytes": "148734" }, { "name": "JavaScript", "bytes": "159333" }, { "name": "Protocol Buffer", "bytes": "5135" }, { "name": "Shell", "bytes": "1330" } ], "symlink_target": "" }
--[[----------------------------------------------------------------------------- * Infected Wars, an open source Garry's Mod game-mode. * * Infected Wars is the work of multiple authors, * a full list can be found in CONTRIBUTORS.md. * For more information, visit https://github.com/JarnoVgr/InfectedWars * * Infected Wars is free software: you can redistribute it and/or modify * it under the terms of the MIT License. * * A full copy of the MIT License can be found in LICENSE.txt. -----------------------------------------------------------------------------]] -- gm13 workaround surface.OldCreateFont = surface.CreateFont function surface.CreateFont(arg1,arg2,arg3,arg4,arg5,arg6) --Call new style if there are only 2 arguments if arg3 == nil then surface.OldCreateFont(arg1,arg2) return end local name = arg6-- [6]-- or "None" local fontdata = { font = arg1,-- [1],-- or "Arial", size = arg2,-- [2],-- or 5, weight = arg3,-- [3],-- or 500, antialias = arg4,-- [4],-- or false, additive = arg5,-- [5],-- or true, } surface.OldCreateFont(name,fontdata) end h = ScrH() w = ScrW() PlayerIsAdmin = false HUD_ON = true COLOR_RED = Color(180, 0, 0, 255) COLOR_BLUE = Color(0, 0, 180, 255) COLOR_GREEN = Color(0, 180, 0, 255) COLOR_LIMEGREEN = Color(30, 180, 30, 255) COLOR_YELLOW = Color(180, 180, 0, 255) COLOR_WHITE = Color(255, 255, 255, 255) COLOR_BLACK = Color(0, 0, 0, 255) COLOR_ARMOR = Color(0,0,200,165) COLOR_DARKBLUE = Color(10, 80, 180, 255) COLOR_DARKGREEN = Color(0, 190, 0, 255) COLOR_GRAY = Color(170, 170, 170, 255) COLOR_DARKGRAY = Color(40, 40, 40, 255) COLOR_HURT1 = Color( 0, 255, 255, 255 ) COLOR_HURT2 = Color( 128, 255, 142, 255 ) COLOR_HURT3 = Color( 255, 233, 127, 255 ) COLOR_HURT4 = Color( 255, 127, 127, 255 ) COLOR_HUMAN_LIGHT = Color( 85, 150, 200, 255 ) SOUND_POWERACTIVATE = Sound("items/battery_pickup.wav") SOUND_WARNING = Sound("common/warning.wav") TOTALGIBS = 0 surface.CreateFont("Tahoma", 16, 1000, true, false, "ScoreboardText" ) surface.CreateFont("DooM", 14, 500, true, false, "DoomSmaller") surface.CreateFont("DooM", 18, 500, true, false, "DoomSmall") surface.CreateFont("DooM", 24, 500, true, false, "DoomMedium") surface.CreateFont("DooM", 40, 500, true, false, "DoomLarge") surface.CreateFont("Arial", 14, 500, true, false, "InfoSmaller") surface.CreateFont("Arial", 16, 500, true, false, "InfoSmall") surface.CreateFont("Arial", 26, 500, true, false, "InfoMedium") surface.CreateFont("Arial", 15, 700, true, false, "ArialB_15") surface.CreateFont("Arial", 16, 700, true, false, "ArialB_16") surface.CreateFont("Arial", 18, 700, true, false, "ArialB_18") surface.CreateFont("Arial", 18, 500, true, false, "Arial1_18",false,false,1) surface.CreateFont("Arial", 23, 500, true, false, "ArialBlur_23",false,false,1) surface.CreateFont("Arial", 20, 700, true, false, "ArialB_20") surface.CreateFont("Arial", 23, 700, true, false, "ArialB1_23") surface.CreateFont("Arial", 22, 700, true, false, "ArialB_22") surface.CreateFont("Arial", 26, 700, true, false, "ArialB_26") surface.CreateFont("Birdman", 19, 700, true, false, "BrdB_19") surface.CreateFont("Birdman", 18, 700, true, false, "BrdB_18") surface.CreateFont("Arial", 65, 700, true, false, "ArialB_65") surface.CreateFont("Arial", 50, 700, true, false, "ArialB_50") surface.CreateFont("Arial", 40, 700, true, false, "ArialB_40") surface.CreateFont("Arial", 36, 700, true, false, "ArialB_36") surface.CreateFont("Courier New", 20, 500, true, false, "EndRoundStats") include( 'sh_init.lua' ) include( 'cl_scoreboard.lua' ) include( 'cl_targetid.lua' ) include( 'cl_hudpickup.lua' ) include( 'cl_deathnotice.lua' ) include( 'cl_xrayvision.lua' ) include( 'cl_screeneffects.lua' ) include( 'cl_menu.lua' ) include( 'cl_radialmenu.lua' ) include( 'cl_hud.lua' ) include( 'greencoins/cl_greencoins.lua' ) include( 'debug/cl_debug.lua' ) CreateClientConVar("_iw_crosshair", 1, true, false) CreateClientConVar("_iw_crosshaircolor", "Default", true, false) CreateClientConVar("_iw_crosshairalpha", 200, true, false) CreateClientConVar("_iw_clhands", 1, true, false) CL_HANDS = util.tobool(GetConVarNumber("_iw_clhands")) function ToggleHands( pl,commandName,args ) local MySelf = LocalPlayer() CL_HANDS = util.tobool(args[1]) if CL_HANDS then RunConsoleCommand("_iw_clhands","1") MySelf:PrintMessage( HUD_PRINTTALK, "Custom hands enabled") else RunConsoleCommand("_iw_clhands","0") MySelf:PrintMessage( HUD_PRINTTALK, "Custom hands disabled") end end concommand.Add("iw_clhands",ToggleHands) --[[--------------------------------------------------------- Name: gamemode:Initialize( ) Desc: Called immediately after starting the gamemode ---------------------------------------------------------]] function GM:Initialize( ) timer.Create("adjusthud",1,0,function() h = ScrH() w = ScrW() end) -- adjust HUD screen dimensions in case the user changes them CrossInit() CurCrosshair = GetConVarNumber("_iw_crosshair") if not CROSSHAIR[CurCrosshair] then CurCrosshair = 1 end CurCrosshairColor = GetConVarString("_iw_crosshaircolor") if not CROSSHAIRCOLORS[CurCrosshairColor] then CurCrosshairColor = "Default" end RunConsoleCommand("_iw_crosshair",CurCrosshair) RunConsoleCommand("_iw_crosshaircolor",CurCrosshairColor) --Get changelog info http.Fetch(CHANGELOG_HTTP,ApplyChangeLog) self:InitializeVars() end function GM:InitializeVars() self:InitializeMenuVars() self.Reinforcements = 0 self.MaxReinforcements = 300 --keep it bigger to be sure that everything is fine :o self.Voted = false self.EquipedSuit = nil ROUNDTIME = 0 ROUNDLENGTH = 0 ENDROUND = false LASTHUMAN = false --resync between server and client if IsValid(MySelf) then MySelf.Class, MySelf.MaxHP, MySelf.SP, MySelf.MaxSP, MySelf.CurPower = nil end GAMEMODE.LastHumanStart = 0 GAMEMODE.ShowScoreboard = false statsreceived = false stattimer = 0 MapList = {} MapVotes = { curMap = 0, nextMap = 0, secondNextMap = 0 } gui.EnableScreenClicker(false) -- call PlayerEntitityStart when LocalPlayer is valid timer.Create("playervalid",0.01,0,function() if (LocalPlayer():IsValid()) then GAMEMODE:PlayerEntityStart() timer.Destroy("playervalid") end end) end function ApplyChangeLog(contents, size) --HELP_TEXT[7].Text = contents end function RestartRound() if DoXRay then XRayToggle() end hook.Remove("RenderScreenspaceEffects", "DrawEnding") GAMEMODE:InitializeVars() end usermessage.Hook("RestartRound", RestartRound) function CapReinforcements(um) local num = um:ReadShort() if num then GAMEMODE.MaxReinforcements = num end end usermessage.Hook("SendMaxReinforcements", CapReinforcements) function LastHuman() if LASTHUMAN then return end LASTHUMAN = true GAMEMODE.LastHumanStart = CurTime() -- deactivate radio RunConsoleCommand("stopsound") timer.Destroy("playtimer") timer.Destroy("nextplaytimer") if MUSIC_ENABLED then timer.Simple(0.1,function() surface.PlaySound(LASTSTANDMUSIC) end) end hook.Add("HUDPaint","LastHumanP",LastHumanPaint) end usermessage.Hook("lasthuman", LastHuman) /*-------------------------------------------------- -- This function is called when localplayer() is valid --------------------------------------------------*/ MySelf = nil function GM:PlayerEntityStart( ) -- recieve the maplist if (PlayerIsAdmin) then RunConsoleCommand("get_maplist") end -- set up defaults for current players for k, v in pairs(player.GetAll()) do v.TitleText = v.TitleText or "Guest" v.Class = v.Class or 0 v.Detectable = v.Detectable or false end -- Since the player is now valid, receive data RunConsoleCommand("data_synchronize") timer.Create("datachecktimer",4,0,CheckData) MySelf = LocalPlayer() MySelf.Class = MySelf.Class or 0 MySelf.MaxHP = MySelf.MaxHP or 100 MySelf.SP = MySelf.SP or 100 MySelf.MaxSP = MySelf.MaxSP or 100 MySelf.CurPower = MySelf.CurPower or 0 MySelf.TitleText = MySelf.TitleText or "Guest" MySelf.PreferBehemoth = true MySelf.TurretStatus = TurretStatus.inactive if RadioOn then RadioPlay(math.random(1,#Radio)) MySelf:PrintMessage(HUD_PRINTTALK,"Radio can be turned off in the Options panel (F3)") end end function CheckData() -- Double check if all data has been received local check = false for k, pl in pairs(player.GetAll()) do if (pl.TitleText == nil or pl.Class == 0 or pl.Detectable == nil) and (pl:Team() == TEAM_HUMAN or pl:Team() == TEAM_UNDEAD) then check = true end end if check then RunConsoleCommand("data_synchronize") end end --Force artistic Derma skin function GM:ForceDermaSkin() return "iw_skin" end --[[--------------------------------------------------------- Name: gamemode:InitPostEntity( ) Desc: Called as soon as all map entities have been spawned ---------------------------------------------------------]] function GM:InitPostEntity( ) end --[[--------------------- Calling late deploy ----------------------]] function CallLateDeploy() -- Call the deploy function (to apply the materials) -- Needed because deploy isn't called when player spawn for the first time --[[timer.Simple(0.01,function() if LocalPlayer():GetActiveWeapon().Deploy then LocalPlayer():GetActiveWeapon():Deploy() end end)]] end --[[--------------------------------------------------------- Name: gamemode:Think( ) Desc: Called every frame ---------------------------------------------------------]] local WaterDraintimer = 0 function GM:Think() if WaterDraintimer < CurTime() then WaterDraintimer = CurTime()+1 local MySelf = LocalPlayer() -- Decrement suit power when under water if MySelf:WaterLevel() > 1 then RunConsoleCommand("decrement_suit",math.Clamp(math.ceil(MySelf:WaterLevel())*2,1,6)) if MySelf:SuitPower() <= 0 and MySelf:Team() == TEAM_HUMAN then RunConsoleCommand("drown_me",3) end end end end --[[--------------------------------------------------------- Name: gamemode:PlayerDeath( ) Desc: Called when a player dies. If the attacker was a player then attacker will become a Player instead of an Entity. ---------------------------------------------------------]] function GM:PlayerDeath( ply, attacker ) end --------- Radio functions ----------------- CreateClientConVar("_iw_enableradio", 1, true, false) RadioOn = util.tobool(GetConVarNumber("_iw_enableradio")) for k=1, #Radio do util.PrecacheSound(Radio[k][1]) end CurPlaying = 1 function RadioPlay_old( nr ) RunConsoleCommand("stopsound") timer.Destroy("playtimer") timer.Destroy("nextplaytimer") if (nr > #Radio) then nr = 1 end print("Switching to song "..nr) RadioOn = true --seems the timers fail to create when they're also destroyed earlier in the same function :/ timer.Simple(0.1,function() timer.Create("playtimer",0.1, 1, function( the_nr ) print("Playing song "..the_nr) surface.PlaySound( the_nr ) end, Radio[nr][1]) timer.Create("nextplaytimer",tonumber(Radio[nr][2])+3, 1, function(nextnr) if RadioOn then --RadioPlay( nextnr ) end end, nr+1) end) CurPlaying = nr end CurSong = 1 --NextSong = 0 function HandleRadio() if LASTHUMAN then return end if RadioOn then if NextSong and NextSong < CurTime() then RunConsoleCommand("stopsound") if CurSong > #Radio then CurSong = 1 end local toplay = CurSong timer.Simple(0.1,function() print("Switching to song "..Radio[toplay][1]) surface.PlaySound(Radio[toplay][1]) end) NextSong = CurTime() + tonumber(Radio[toplay][2]) + 2 CurSong = CurSong + 1 end end end hook.Add("Think", "Radio", HandleRadio) NextDelay = 0 function RadioPlay( nr ) if NextDelay > CurTime() then return end NextDelay = CurTime() + 0.3 RunConsoleCommand("stopsound") RadioOn = true if (nr > #Radio) then nr = 1 end CurSong = nr NextSong = 0 --CurTime() + tonumber(Radio[CurSong][2]) + 2 --[[timer.Simple(0.1,function() print("Playing song "..Radio[CurSong][1]) surface.PlaySound(Radio[CurSong][1]) end)]] end function ToggleRadio( pl,commandName,args ) local MySelf = LocalPlayer() local org = RadioOn RadioOn = util.tobool(args[1]) RunConsoleCommand("stopsound") if RadioOn then RunConsoleCommand("_iw_enableradio","1") if not Org then MySelf:PrintMessage( HUD_PRINTTALK, "Radio on") end RadioPlay(tonumber(args[2])) else RunConsoleCommand("_iw_enableradio","0") if Org then MySelf:PrintMessage( HUD_PRINTTALK, "Radio off") end --timer.Destroy("playtimer") --timer.Destroy("nextplaytimer") end end concommand.Add("iw_enableradio",ToggleRadio) --[[--------------------------------------------------------- Name: gamemode:KeyPress( ) Desc: Player pressed a key (see IN enums) ---------------------------------------------------------]] function GM:KeyPress( player, key ) end ---- XRay timer works similiar, see xrayvision.lua ----- local Stimer = 0 local Sstep = SPEED_TIMER local function SpeedThink() local MySelf = LocalPlayer() -- If your suit power is 0, turn of Xray if (MySelf:GetPower() == 1) then if (MySelf:SuitPower() <= 0) then surface.PlaySound( SOUND_WARNING ) MySelf:SetPower( 3 ) -- turn off the power else -- Else, keep draining suit power (if we're truly running fast enough that is) if (Stimer <= CurTime()) then Stimer = CurTime()+Sstep if (MySelf:GetVelocity():Length() > 100) then local cost = HumanPowers[1].Cost if MySelf:HasBought("duracell2") then cost = cost * 0.75 end if MySelf.EquipedSuit == "scoutsspeedpack" then cost = cost * 0.5 end RunConsoleCommand("decrement_suit",tostring(cost)) end end end end end hook.Add("Think", "SpeedCheck", SpeedThink) --[[--------------------------------------------------------- Name: gamemode:KeyRelease( ) Desc: Player released a key (see IN enums) ---------------------------------------------------------]] function GM:KeyRelease( player, key ) end local nextjump = 0 function GM:PlayerBindPress( pl, bind, pressed ) if (bind == "+use" and pl:Alive() and pl:Team() == TEAM_UNDEAD and not pl:IsOnGround() and pl:GetPlayerClass() == CLASS_Z_BONES and pl:HasBought("deathpursuit") and nextjump < CurTime()) then local trace = pl:GetEyeTrace() if trace.Entity and trace.Entity:IsPlayer() and trace.Entity:Team() == TEAM_HUMAN then RunConsoleCommand("_iw_forceboost",trace.Entity:EntIndex()) nextjump = CurTime()+2 end end if string.find( bind, "zoom" ) then return true end end --[[--------------------------------------------------------- Unlock achievement ---------------------------------------------------------]] local unlockSound = Sound("weapons/physcannon/energy_disintegrate5.wav") local achvStack = 0 local achievTime = 0 function DrawAchievement() endX = w/2-200 endY = h/2-150 textEndX = w/2-90 textEndY = h/2-150 achievAlpha = achievAlpha or 255 achievX = achievX or {} achievY = achievY or {} achievX[1] = achievX[1] or endX-w -- four text location achievY[1] = achievY[1] or endY achievX[2] = achievX[2] or endX+w achievY[2] = achievY[2] or endY achievX[3] = achievX[3] or endX achievY[3] = achievY[3] or endY-h achievX[4] = achievX[4] or endX achievY[4] = achievY[4] or endY+h achievX[5] = achievX[5] or endX-w -- image location achievY[5] = achievY[5] or endY col = Color(255,255,255,achievAlpha) col2 = Color(0,0,0,achievAlpha) local rand = 0 local rand2 = 0 for k=1, 4 do rand = -2+math.Rand(0,4) rand2 = -2+math.Rand(0,4) if k == 4 then rand = 0 rand2 = 0 end draw.SimpleTextOutlined("Achievement Unlocked!","DoomSmall",achievX[k]+rand,achievY[k]+rand2,col, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, 1, col2) draw.SimpleTextOutlined(achievName,"DoomMedium",achievX[k]+rand,achievY[k]+20+rand2,col, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, 1, col2) if achievLoadout ~= "" then draw.SimpleTextOutlined(achievLoadout,"DoomSmall",achievX[k]+rand,achievY[k]+50+rand2,col, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, 1, col2) end end surface.SetTexture( achievImage ) surface.SetDrawColor( col ) surface.DrawTexturedRect( achievX[5], achievY[5],100,100 ) for k=1,4 do achievX[k] = math.Approach(achievX[k], textEndX, w*3*FrameTime()) achievY[k] = math.Approach(achievY[k], textEndY, h*3*FrameTime()) end achievX[5] = math.Approach(achievX[5], endX, w*3*FrameTime()) achievY[5] = math.Approach(achievY[5], endY, h*3*FrameTime()) if (achievTime < CurTime()+1) then achievAlpha = math.Approach(achievAlpha, 0, 255*FrameTime()) end if (achievTime < CurTime()) then hook.Remove("HUDPaint","DrawAchievement") for k=1, 5 do achievX[k] = nil achievY[k] = nil achievAlpha = nil end end end function IdentifyUnlock( stat ) local display = false local code = {} local disp = {} local retstr = "" for k, v in pairs(unlockData) do if table.HasValue(v,stat) then display = true for i, j in pairs(v) do if not LocalPlayer().DataTable["achievements"][j] then display = false break end end if display == true then table.insert(code,k) display = false end end end local tab = {} table.Add(tab,HumanClass) table.Add(tab,UndeadClass) if #code > 0 then for k, v in pairs(tab) do for i, j in pairs(v.SwepLoadout) do if table.HasValue(code,j.UnlockCode) then table.insert(disp,j.Name) end end end retstr = "Unlocked loadout: " if #disp > 0 then for y=1, #disp do retstr = retstr..disp[y] if y < #disp then retstr = retstr..", " end end end return retstr end return "" end function UnlockEffect( achv ) achvStack = achvStack+1 if achievTime < CurTime() then LocalPlayer().DataTable["achievements"][achv] = true achvStack = achvStack-1 achievName = achievementDesc[achv].Name achievImage = surface.GetTextureID(achievementDesc[achv].Image) achievTime = CurTime()+5 surface.PlaySound(unlockSound) achievLoadout = IdentifyUnlock( achv ) hook.Add("HUDPaint","DrawAchievement",DrawAchievement) else timer.Simple((achievTime-CurTime()+0.2)+5*(achvStack-1),function( str ) UnlockEffect(str) achvStack = achvStack-1 end,achv) -- Achievement display delays end end -- Receive max health status local function SetMaxHealth(um) local ent = um:ReadEntity() ent.MaxHP = um:ReadShort() end usermessage.Hook("SetMaxHP", SetMaxHealth) -- Receive suit power status local function SetSuitPower(um) local MySelf = LocalPlayer() MySelf.SP = um:ReadShort() end usermessage.Hook("SetSP", SetSuitPower) -- Receive max suit power status local function SetMaxSuitPower(um) local MySelf = LocalPlayer() MySelf.MaxSP = um:ReadShort() end usermessage.Hook("SetMaxSP", SetMaxSuitPower) -- Receive class status local function RecClass(um) local ent = um:ReadEntity() if ent:IsValid() then ent.Class = um:ReadShort() end end usermessage.Hook("SetClass", RecClass) -- Receive power status local function RecPower(um) local MySelf = LocalPlayer() MySelf.CurPower = um:ReadShort() local pf = { [0] = { 0, 150, 150 }, [1] = { 150, 0, 0 }, [2] = { 0, 0, 150 }, [3] = { 150, 150, 0 } } local pf2 = { [0] = { 255, 255, 255 }, [1] = { 150, 0, 0 }, [2] = { 0, 0, 250 }, [3] = { 255, 255, 255 } } CreatePowerFlash( pf[MySelf.CurPower][1], pf[MySelf.CurPower][2], pf[MySelf.CurPower][3] ) SuitBar.col = pf2[MySelf.CurPower] if MySelf.CurPower == 0 then PlugSuitBar(false) PlugHealthBar(false) else PlugSuitBar(true) if MySelf.CurPower == 3 then PlugHealthBar(true) else PlugHealthBar(false) end end -- Toggle XRay (it will only activate if player has Vision power) RunConsoleCommand("toggle_xrayvision") end usermessage.Hook("SetPower", RecPower) -- Receive detectability local function RecDetect(um) local ent = um:ReadEntity() if ent:IsValid() then ent.Detectable = um:ReadBool() end end usermessage.Hook("SetDetectable", RecDetect) -- Receive title local function RecTitle(um) local ent = um:ReadEntity() if ent:IsValid() then ent.TitleText = um:ReadString() end end usermessage.Hook("SetTitle", RecTitle) -- Receive player admin status locally local function SetPlayerIsAdmin(um) PlayerIsAdmin = um:ReadBool() end usermessage.Hook("SetAdmin", SetPlayerIsAdmin) -- receive data like title text, class, and max hp in one go local function SetData(um) local amount = um:ReadShort() local ent local pl for k=1,amount do pl = um:ReadEntity() pl.TitleText = um:ReadString() pl.Class = um:ReadShort() pl.Detectable = um:ReadBool() end end usermessage.Hook("SetData", SetData) -- receive all recorded data local function SetRecordData(um) local pl = um:ReadEntity() if not pl.DataTable then pl.DataTable = {{}} pl.DataTable["achievements"] = {} pl.DataTable["shopitems"] = {} end for k, v in pairs(recordData) do pl.DataTable[k] = um:ReadString() end for k, v in pairs(achievementDesc) do pl.DataTable["achievements"][k] = um:ReadBool() end pl.StatsReceived = true end usermessage.Hook("SetRecordData", SetRecordData) -- Receive map list MapList = {} local function ReceiveMapList(um) local index = um:ReadShort() local map = um:ReadString() map = string.gsub(map,".bsp","") MapList[index] = map end usermessage.Hook("RcMapList", ReceiveMapList) -- Timer function function GM:RoundTimeLeft() return( math.Clamp( ROUNDTIME - CurTime(), 0, ROUNDLENGTH) ) end local function SynchronizeTime(um) ROUNDLENGTH = um:ReadShort() ROUNDTIME = um:ReadLong() end usermessage.Hook("SendTime", SynchronizeTime) local function SynchronizeReinforcements(um) GAMEMODE.Reinforcements = um:ReadShort() GAMEMODE.MaxReinforcements = um:ReadShort() end usermessage.Hook("SendReinforce", SynchronizeReinforcements) statsreceived = false stattimer = 0 local function SetStats(um) StatsUndKiller = um:ReadString() StatsHumKiller = um:ReadString() StatsUndDmg = um:ReadString() StatsHumDmg = um:ReadString() StatsMostSocial = um:ReadString() StatsMostScary = um:ReadString() StatsMostUnlucky = um:ReadString() StatsRoundKills = um:ReadString() StatsRoundDamage = um:ReadString() statsreceived = true stattimer = CurTime() + 7 end usermessage.Hook("SendTopStats", SetStats) function PrintWeapons() for k, v in pairs(LocalPlayer():GetWeapons()) do Msg(v:GetPrintName().."\n") end end /*-------------------------------------------------------- Called when the round ends --------------------------------------------------------*/ local function EndRound( um ) GAMEMODE.TeamThatWon = um:ReadShort() GAMEMODE.ShowVoting = um:ReadBool() if GAMEMODE.ShowVoting then GAMEMODE.CanRestart = um:ReadBool() GAMEMODE.CurMap = um:ReadString() GAMEMODE.NextMap = um:ReadString() GAMEMODE.SecondNextMap = um:ReadString() end ENDROUND = true gui.EnableScreenClicker(true) LocalPlayer().Voted = 0 VoteBox = nil NextSong = nil RunConsoleCommand("stopsound") if MUSIC_ENABLED then --stop radio timer.Destroy("playtimer") timer.Destroy("nextplaytimer") local song = HUMANWINMUSIC if GAMEMODE.TeamThatWon == TEAM_UNDEAD then song = UNDEADWINMUSIC end timer.Simple(0.1,function( ms ) surface.PlaySound(ms) end,song) end hook.Add("RenderScreenspaceEffects", "DrawEnding", DrawEnding) -- Close all derma frames CloseFrames() end usermessage.Hook("GameEndRound", EndRound) function SyncVotes( um ) if not GAMEMODE.ShowVoting then return end MapVotes = { curMap = 0, nextMap = 0, secondNextMap = 0 } MapVotes.curMap = um:ReadShort() MapVotes.nextMap = um:ReadShort() MapVotes.secondNextMap = um:ReadShort() end usermessage.Hook("SynchronizeVotes", SyncVotes) GM.MapExploits = {} -- receive map exploit locations function RecMapExploits( um ) local tab = {} local reset = um:ReadBool() if reset == true then GAMEMODE.MapExploits = {} end local number = um:ReadShort() local start = um:ReadShort() for k=1, number do tab = {} tab.origin = um:ReadVector() tab.bsize = um:ReadShort() tab.type = um:ReadString() GAMEMODE.MapExploits[start+k-1] = tab number = number + 1 end end usermessage.Hook("mapexploits",RecMapExploits) function RecMapExploitsSingle( um ) local tab = {} tab.origin = um:ReadVector() tab.bsize = um:ReadShort() tab.type = um:ReadString() table.insert(GAMEMODE.MapExploits,tab) end usermessage.Hook("mapexploitssingle",RecMapExploitsSingle) // Receive shop data local function SetShopData(um) MySelf = LocalPlayer() if not MySelf.DataTable then MySelf.DataTable = {{}} MySelf.DataTable["achievements"] = {} MySelf.DataTable["shopitems"] = {} end for k, v in pairs(shopData) do MySelf.DataTable["shopitems"][k] = um:ReadBool() end end usermessage.Hook("SetShopData", SetShopData) /*--------------------------------------------------------- Name: gamemode:CreateMove( command ) Desc: Allows the client to change the move commands before it's send to the server ---------------------------------------------------------*/ function GM:CreateMove( cmd ) end /*--------------------------------------------------------- Name: gamemode:GUIMouseReleased( mousecode ) Desc: The mouse has been released on the game screen ---------------------------------------------------------*/ function GM:GUIMouseReleased( mousecode, AimVector ) hook.Call( "CallScreenClickHook", GAMEMODE, false, mousecode, AimVector ) end /*--------------------------------------------------------- Name: gamemode:ShutDown( ) Desc: Called when the Lua system is about to shut down ---------------------------------------------------------*/ function GM:ShutDown( ) end /*--------------------------------------------------------- Name: gamemode:RenderScreenspaceEffects( ) Desc: Bloom etc should be drawn here (or using this hook) ---------------------------------------------------------*/ function GM:RenderScreenspaceEffects() end /*--------------------------------------------------------- Name: gamemode:GetTeamColor( ent ) Desc: Return the color for this ent's team This is for chat and deathnotice text ---------------------------------------------------------*/ function GM:GetTeamColor( ent ) local team = TEAM_UNASSIGNED if (ent.Team) then team = ent:Team() end return GAMEMODE:GetTeamNumColor( team ) end function RestoreViewmodel(pl) timer.Simple ( 0.1, function() local MySelf = LocalPlayer() if MySelf:IsValid() then if MySelf ~= pl then return end local wep = MySelf:GetActiveWeapon() if wep then if !wep.Base or (wep.Base and not string.find(wep.Base,"iw_")) then local vm = MySelf:GetViewModel() if vm and vm:IsValid() then vm:SetColor(255, 255, 255, 255) end end end end end ) end /*--------------------------------------------------------- Name: ChatText Allows override of the chat text ---------------------------------------------------------*/ function GM:ChatText( playerindex, playername, text, filter ) if ( filter == "chat" ) then Msg( playername, ": ", text, "\n" ) else Msg( text, "\n" ) end return false end /*--------------------------------------------------------- Name: gamemode:PostProcessPermitted( str ) Desc: return true/false depending on whether this post process should be allowed ---------------------------------------------------------*/ function GM:PostProcessPermitted( str ) return true end /*--------------------------------------------------------- Name: gamemode:PostRenderVGUI( ) Desc: Called after VGUI has been rendered ---------------------------------------------------------*/ function GM:PostRenderVGUI() end /*--------------------------------------------------------- Name: gamemode:RenderScene( ) Desc: Render the scene ---------------------------------------------------------*/ function GM:RenderScene() end /*--------------------------------------------------------- Name: CalcView Allows override of the default view ---------------------------------------------------------*/ function GM:CalcView( ply, origin, angles, fov ) local MySelf = LocalPlayer() local wep = ply:GetActiveWeapon() -- Places eyes in ragdoll entity if MySelf:GetRagdollEntity() then local phys = MySelf:GetRagdollEntity():GetPhysicsObjectNum(12) local ragdoll = MySelf:GetRagdollEntity() if ragdoll then local lookup = MySelf:LookupAttachment("eyes") if lookup then local attach = ragdoll:GetAttachment(lookup) if attach then return {origin=attach.Pos, angles=attach.Ang} end end end end local view = {} view.origin = origin view.angles = angles view.fov = fov // Give the active weapon a go at changing the viewmodel position if ( IsValid( wep ) ) then local func = wep.GetViewModelPosition if ( func ) then view.vm_origin, view.vm_angles = func( wep, origin*1, angles*1 ) // Note: *1 to copy the object so the child function can't edit it. end local func = wep.CalcView if ( func ) then view.origin, view.angles, view.fov = func( wep, ply, origin*1, angles*1, fov ) // Note: *1 to copy the object so the child function can't edit it. end end return view end /*--------------------------------------------------------- Name: gamemode:PreDrawTranslucent( ) Desc: Called before drawing translucent entities ---------------------------------------------------------*/ function GM:PreDrawTranslucent() end /*--------------------------------------------------------- Name: gamemode:PostDrawTranslucent( ) Desc: Called after drawing translucent entities ---------------------------------------------------------*/ function GM:PostDrawTranslucent() end /*--------------------------------------------------------- Name: gamemode:PreDrawOpaque( ) Desc: Called before drawing opaque entities ---------------------------------------------------------*/ function GM:PreDrawOpaque() end /*--------------------------------------------------------- Name: gamemode:PostDrawOpaque( ) Desc: Called after drawing opaque entities ---------------------------------------------------------*/ function GM:PostDrawOpaque() end
{ "content_hash": "980a5154e2b86831a6b4e60afe533e75", "timestamp": "", "source": "github", "line_count": 1136, "max_line_length": 149, "avg_line_length": 26.599471830985916, "alnum_prop": 0.6373233610219413, "repo_name": "JarnoVgr/InfectedWars", "id": "66132aa32fc2cd8eefed5862eefa216100c87033", "size": "30217", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gamemode/cl_init.lua", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "926008" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace inBloom { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
{ "content_hash": "db60e3bc80c893d124d6a897a81c270c", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 99, "avg_line_length": 24.956521739130434, "alnum_prop": 0.5853658536585366, "repo_name": "dougloyo/inBloom", "id": "6b823487ad92895f311c27362f8990ddd99cb558", "size": "576", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "inBloom/App_Start/RouteConfig.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "98" }, { "name": "C#", "bytes": "17784" }, { "name": "JavaScript", "bytes": "158942" } ], "symlink_target": "" }
<?php namespace Oro\Bundle\SearchBundle\Datagrid\Extension\Pager; use Oro\Bundle\DataGridBundle\Datagrid\Common\DatagridConfiguration; use Oro\Bundle\DataGridBundle\Datasource\DatasourceInterface; use Oro\Bundle\DataGridBundle\Extension\Pager\AbstractPagerExtension; use Oro\Bundle\DataGridBundle\Extension\Pager\OrmPagerExtension; use Oro\Bundle\DataGridBundle\Extension\Pager\PagerInterface; use Oro\Bundle\DataGridBundle\Extension\Toolbar\ToolbarExtension; use Oro\Bundle\SearchBundle\Datagrid\Datasource\SearchDatasource; /** * Responsibility of this extension is to apply pagination on query for Search datasource */ class SearchPagerExtension extends OrmPagerExtension { /** @var IndexerPager */ protected $pager; /** * @param IndexerPager $pager */ public function __construct(IndexerPager $pager) { $this->pager = $pager; } /** * {@inheritDoc} */ public function isApplicable(DatagridConfiguration $config) { return AbstractPagerExtension::isApplicable($config) && SearchDatasource::TYPE === $config->getDatasourceType(); } /** * {@inheritDoc} */ public function visitDatasource(DatagridConfiguration $config, DatasourceInterface $datasource) { $defaultPerPage = $config->offsetGetByPath(ToolbarExtension::PAGER_DEFAULT_PER_PAGE_OPTION_PATH, 10); $onePage = $config->offsetGetByPath(ToolbarExtension::PAGER_ONE_PAGE_OPTION_PATH, false); /** @var $datasource SearchDatasource */ $this->pager->setQuery($datasource->getSearchQuery()); $this->pager->setPage($this->getOr(PagerInterface::PAGE_PARAM, 1)); if ($onePage) { $this->pager->setMaxPerPage(self::SOFT_LIMIT); } else { $this->pager->setMaxPerPage($this->getOr(PagerInterface::PER_PAGE_PARAM, $defaultPerPage)); } $this->pager->init(); } }
{ "content_hash": "e8eb57413d4e8884e79868c408e2e661", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 109, "avg_line_length": 32.779661016949156, "alnum_prop": 0.6923474663908997, "repo_name": "orocrm/platform", "id": "7231d177fd042019b64303c43bbb77795294cbda", "size": "1934", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Oro/Bundle/SearchBundle/Datagrid/Extension/Pager/SearchPagerExtension.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "618485" }, { "name": "Gherkin", "bytes": "158217" }, { "name": "HTML", "bytes": "1648915" }, { "name": "JavaScript", "bytes": "3326127" }, { "name": "PHP", "bytes": "37828618" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/buttonDark"> <item android:id="@android:id/mask"> <color android:color="@color/white"/> </item> </ripple>
{ "content_hash": "ea4aad9b26e79fb492dff9082243dbd7", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 66, "avg_line_length": 24.636363636363637, "alnum_prop": 0.6125461254612546, "repo_name": "Harreke/EasyApp", "id": "18d775125d70e0e8381feae2981002f01c22928f", "size": "271", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/src/main/res/drawable-v21/background_button_dark.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "525892" } ], "symlink_target": "" }
import * as React from 'react'; import * as classNames from 'classnames'; import './ui-grid-row.styl'; interface UIGridRowProps { children?: any; mod?: string; } export const UIGridRow = (props: UIGridRowProps) => { return <div className={classNames({ 'row': true, [`ui-grid-row_${props.mod}`]: !!props.mod })} > {props.children} </div>; };
{ "content_hash": "a1aaf568d01ca16ffe3ca61a29cf2959", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 58, "avg_line_length": 23.823529411764707, "alnum_prop": 0.5703703703703704, "repo_name": "xio4/unibot-manager", "id": "caad9068f08caf43ffab6e2e212c3aa8ee3abfbc", "size": "405", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/ui/grid/UIGridRow.tsx", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2260" }, { "name": "JavaScript", "bytes": "10429" }, { "name": "Smarty", "bytes": "391" }, { "name": "TypeScript", "bytes": "23101" } ], "symlink_target": "" }
class ReligionDeity < ActiveRecord::Base belongs_to :user, optional: true belongs_to :religion belongs_to :deity, optional: true end
{ "content_hash": "946fee4346b0a1a7719c4e39b5d837ac", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 40, "avg_line_length": 23.333333333333332, "alnum_prop": 0.75, "repo_name": "indentlabs/notebook", "id": "716c6732f2e733266e95d54438aa31871f279dad", "size": "140", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/page_groupers/religion_deity.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2868" }, { "name": "CoffeeScript", "bytes": "844" }, { "name": "Dockerfile", "bytes": "1466" }, { "name": "HTML", "bytes": "1063222" }, { "name": "JavaScript", "bytes": "170187" }, { "name": "Procfile", "bytes": "141" }, { "name": "Ruby", "bytes": "1052918" }, { "name": "SCSS", "bytes": "34415" } ], "symlink_target": "" }
// {block name="backend/customer/controller/detail"} // {$smarty.block.parent} Ext.define('Shopware.apps.CreateBackendOrder.controller.Detail', { override: 'Shopware.apps.Customer.controller.Detail', /** * Override init to add additional event for button to perform a backend order */ init: function() { var me = this; me.callParent(arguments); me.control({ 'customer-additional-panel': { performBackendOrder: me.onPerformBackendOrder } }); }, /** * opens the backend order subApplication and passes the user id * * @param record */ onPerformBackendOrder: function(record) { Shopware.app.Application.addSubApplication({ name: 'Shopware.apps.SwagBackendOrder', action: 'detail', params: { userId: record.data.id } }); }, /** * Overriding to set random password for new guest accounts */ onSaveCustomer: function(btn) { var me = this, win = btn.up('window'), form = win.down('form'), model = form.getRecord(); if (Ext.isDefined(me.subApplication.params)) { if (me.subApplication.params.guest === true) { var password = me.generateRandomPassword(); model.set('newPassword', password); } } me.callParent(arguments); }, /** * Override "getQuickView" (magicGetter) to prevent call function on null in this overwritten context. * * @return { object } */ getQuickView: function() { return { getStore: function() { return { load: Ext.emptyFn }; } }; }, /** * @returns { string } */ generateRandomPassword: function() { var pool = '01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', password = '', i = 8, length = pool.length; while (i--) { password += pool[Math.floor(length * Math.random())]; } return password; } }); // {/block}
{ "content_hash": "cdbb5f9b28038defcdb43d176c20d217", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 106, "avg_line_length": 26.261904761904763, "alnum_prop": 0.5339981867633726, "repo_name": "shopwareLabs/SwagBackendOrder", "id": "939f19ee34fefa43821cbf6435393e9e92339b54", "size": "2206", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Resources/views/backend/customer/controller/create_backend_order/detail.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "173411" }, { "name": "Makefile", "bytes": "2093" }, { "name": "PHP", "bytes": "267457" }, { "name": "Shell", "bytes": "553" } ], "symlink_target": "" }
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. 'use strict'; //////////////////////////////////////////////////////////////////////////////// // DirectoryTreeBase /** * Implementation of methods for DirectoryTree and DirectoryItem. These classes * inherits cr.ui.Tree/TreeItem so we can't make them inherit this class. * Instead, we separate their implementations to this separate object and call * it with setting 'this' from DirectoryTree/Item. */ var DirectoryItemTreeBaseMethods = {}; /** * Updates sub-elements of {@code this} reading {@code DirectoryEntry}. * The list of {@code DirectoryEntry} are not updated by this method. * * @param {boolean} recursive True if the all visible sub-directories are * updated recursively including left arrows. If false, the update walks * only immediate child directories without arrows. */ DirectoryItemTreeBaseMethods.updateSubElementsFromList = function(recursive) { var index = 0; var tree = this.parentTree_ || this; // If no parent, 'this' itself is tree. while (this.entries_[index]) { var currentEntry = this.entries_[index]; var currentElement = this.items[index]; var label = util.getEntryLabel(tree.volumeManager_, currentEntry); if (index >= this.items.length) { var item = new DirectoryItem(label, currentEntry, this, tree); this.add(item); index++; } else if (util.isSameEntry(currentEntry, currentElement.entry)) { currentElement.updateSharedStatusIcon(); if (recursive && this.expanded) currentElement.updateSubDirectories(true /* recursive */); index++; } else if (currentEntry.toURL() < currentElement.entry.toURL()) { var item = new DirectoryItem(label, currentEntry, this, tree); this.addAt(item, index); index++; } else if (currentEntry.toURL() > currentElement.entry.toURL()) { this.remove(currentElement); } } var removedChild; while (removedChild = this.items[index]) { this.remove(removedChild); } if (index === 0) { this.hasChildren = false; this.expanded = false; } else { this.hasChildren = true; } }; /** * Finds a parent directory of the {@code entry} in {@code this}, and * invokes the DirectoryItem.selectByEntry() of the found directory. * * @param {DirectoryEntry|Object} entry The entry to be searched for. Can be * a fake. * @return {boolean} True if the parent item is found. */ DirectoryItemTreeBaseMethods.searchAndSelectByEntry = function(entry) { for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; if (util.isDescendantEntry(item.entry, entry) || util.isSameEntry(item.entry, entry)) { item.selectByEntry(entry); return true; } } return false; }; Object.freeze(DirectoryItemTreeBaseMethods); var TREE_ITEM_INNTER_HTML = '<div class="tree-row">' + ' <span class="expand-icon"></span>' + ' <span class="icon"></span>' + ' <span class="label entry-name"></span>' + '</div>' + '<div class="tree-children"></div>'; //////////////////////////////////////////////////////////////////////////////// // DirectoryItem /** * A directory in the tree. Each element represents one directory. * * @param {string} label Label for this item. * @param {DirectoryEntry} dirEntry DirectoryEntry of this item. * @param {DirectoryItem|DirectoryTree} parentDirItem Parent of this item. * @param {DirectoryTree} tree Current tree, which contains this item. * @extends {cr.ui.TreeItem} * @constructor */ function DirectoryItem(label, dirEntry, parentDirItem, tree) { var item = new cr.ui.TreeItem(); DirectoryItem.decorate(item, label, dirEntry, parentDirItem, tree); return item; } /** * @param {HTMLElement} el Element to be DirectoryItem. * @param {string} label Label for this item. * @param {DirectoryEntry} dirEntry DirectoryEntry of this item. * @param {DirectoryItem|DirectoryTree} parentDirItem Parent of this item. * @param {DirectoryTree} tree Current tree, which contains this item. */ DirectoryItem.decorate = function(el, label, dirEntry, parentDirItem, tree) { el.__proto__ = DirectoryItem.prototype; (/** @type {DirectoryItem} */ el).decorate( label, dirEntry, parentDirItem, tree); }; DirectoryItem.prototype = { __proto__: cr.ui.TreeItem.prototype, /** * The DirectoryEntry corresponding to this DirectoryItem. This may be * a dummy DirectoryEntry. * @type {DirectoryEntry|Object} */ get entry() { return this.dirEntry_; }, /** * The element containing the label text and the icon. * @type {!HTMLElement} * @override */ get labelElement() { return this.firstElementChild.querySelector('.label'); } }; /** * Calls DirectoryItemTreeBaseMethods.updateSubElementsFromList(). * * @param {boolean} recursive True if the all visible sub-directories are * updated recursively including left arrows. If false, the update walks * only immediate child directories without arrows. */ DirectoryItem.prototype.updateSubElementsFromList = function(recursive) { DirectoryItemTreeBaseMethods.updateSubElementsFromList.call(this, recursive); }; /** * Calls DirectoryItemTreeBaseMethods.updateSubElementsFromList(). * * @param {DirectoryEntry|Object} entry The entry to be searched for. Can be * a fake. * @return {boolean} True if the parent item is found. */ DirectoryItem.prototype.searchAndSelectByEntry = function(entry) { return DirectoryItemTreeBaseMethods.searchAndSelectByEntry.call(this, entry); }; /** * @param {string} label Localized label for this item. * @param {DirectoryEntry} dirEntry DirectoryEntry of this item. * @param {DirectoryItem|DirectoryTree} parentDirItem Parent of this item. * @param {DirectoryTree} tree Current tree, which contains this item. */ DirectoryItem.prototype.decorate = function( label, dirEntry, parentDirItem, tree) { this.innerHTML = TREE_ITEM_INNTER_HTML; this.parentTree_ = tree; this.directoryModel_ = tree.directoryModel; this.parent_ = parentDirItem; this.label = label; this.dirEntry_ = dirEntry; this.fileFilter_ = this.directoryModel_.getFileFilter(); // Sets hasChildren=false tentatively. This will be overridden after // scanning sub-directories in updateSubElementsFromList(). this.hasChildren = false; this.addEventListener('expand', this.onExpand_.bind(this), false); var icon = this.querySelector('.icon'); icon.classList.add('volume-icon'); var location = tree.volumeManager.getLocationInfo(dirEntry); if (location && location.rootType && location.isRootEntry) { icon.setAttribute('volume-type-icon', location.rootType); } else { icon.setAttribute('file-type-icon', 'folder'); this.updateSharedStatusIcon(); } if (this.parentTree_.contextMenuForSubitems) this.setContextMenu(this.parentTree_.contextMenuForSubitems); // Adds handler for future change. this.parentTree_.addEventListener( 'contextMenuForSubitemsChange', function(e) { this.setContextMenu(e.newValue); }.bind(this)); if (parentDirItem.expanded) this.updateSubDirectories(false /* recursive */); }; /** * Overrides WebKit's scrollIntoViewIfNeeded, which doesn't work well with * a complex layout. This call is not necessary, so we are ignoring it. * * @param {boolean} unused Unused. * @override */ DirectoryItem.prototype.scrollIntoViewIfNeeded = function(unused) { }; /** * Removes the child node, but without selecting the parent item, to avoid * unintended changing of directories. Removing is done externally, and other * code will navigate to another directory. * * @param {!cr.ui.TreeItem} child The tree item child to remove. * @override */ DirectoryItem.prototype.remove = function(child) { this.lastElementChild.removeChild(child); if (this.items.length == 0) this.hasChildren = false; }; /** * Invoked when the item is being expanded. * @param {!UIEvent} e Event. * @private **/ DirectoryItem.prototype.onExpand_ = function(e) { this.updateSubDirectories( true /* recursive */, function() {}, function() { this.expanded = false; }.bind(this)); e.stopPropagation(); }; /** * Invoked when the tree item is clicked. * * @param {Event} e Click event. * @override */ DirectoryItem.prototype.handleClick = function(e) { cr.ui.TreeItem.prototype.handleClick.call(this, e); if (!e.target.classList.contains('expand-icon')) this.directoryModel_.activateDirectoryEntry(this.entry); }; /** * Retrieves the latest subdirectories and update them on the tree. * @param {boolean} recursive True if the update is recursively. * @param {function()=} opt_successCallback Callback called on success. * @param {function()=} opt_errorCallback Callback called on error. */ DirectoryItem.prototype.updateSubDirectories = function( recursive, opt_successCallback, opt_errorCallback) { if (util.isFakeEntry(this.entry)) { if (opt_errorCallback) opt_errorCallback(); return; } var sortEntries = function(fileFilter, entries) { entries.sort(util.compareName); return entries.filter(fileFilter.filter.bind(fileFilter)); }; var onSuccess = function(entries) { this.entries_ = entries; this.redrawSubDirectoryList_(recursive); opt_successCallback && opt_successCallback(); }.bind(this); var reader = this.entry.createReader(); var entries = []; var readEntry = function() { reader.readEntries(function(results) { if (!results.length) { onSuccess(sortEntries(this.fileFilter_, entries)); return; } for (var i = 0; i < results.length; i++) { var entry = results[i]; if (entry.isDirectory) entries.push(entry); } readEntry(); }.bind(this)); }.bind(this); readEntry(); }; /** * Searches for the changed directory in the current subtree, and if it is found * then updates it. * * @param {DirectoryEntry} changedDirectoryEntry The entry ot the changed * directory. */ DirectoryItem.prototype.updateItemByEntry = function(changedDirectoryEntry) { if (util.isSameEntry(changedDirectoryEntry, this.entry)) { this.updateSubDirectories(false /* recursive */); return; } // Traverse the entire subtree to find the changed element. for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; if (util.isDescendantEntry(item.entry, changedDirectoryEntry) || util.isSameEntry(item.entry, changedDirectoryEntry)) { item.updateItemByEntry(changedDirectoryEntry); break; } } }; /** * Update the icon based on whether the folder is shared on Drive. */ DirectoryItem.prototype.updateSharedStatusIcon = function() { var icon = this.querySelector('.icon'); this.parentTree_.metadataCache.getLatest( [this.dirEntry_], 'drive', function(metadata) { icon.classList.toggle('shared', metadata[0] && metadata[0].shared); }); }; /** * Redraw subitems with the latest information. The items are sorted in * alphabetical order, case insensitive. * @param {boolean} recursive True if the update is recursively. * @private */ DirectoryItem.prototype.redrawSubDirectoryList_ = function(recursive) { this.updateSubElementsFromList(recursive); }; /** * Select the item corresponding to the given {@code entry}. * @param {DirectoryEntry|Object} entry The entry to be selected. Can be a fake. */ DirectoryItem.prototype.selectByEntry = function(entry) { if (util.isSameEntry(entry, this.entry)) { this.selected = true; return; } if (this.searchAndSelectByEntry(entry)) return; // If the entry doesn't exist, updates sub directories and tries again. this.updateSubDirectories( false /* recursive */, this.searchAndSelectByEntry.bind(this, entry)); }; /** * Executes the assigned action as a drop target. */ DirectoryItem.prototype.doDropTargetAction = function() { this.expanded = true; }; /** * Sets the context menu for directory tree. * @param {cr.ui.Menu} menu Menu to be set. */ DirectoryItem.prototype.setContextMenu = function(menu) { var tree = this.parentTree_ || this; // If no parent, 'this' itself is tree. var locationInfo = tree.volumeManager_.getLocationInfo(this.entry); if (locationInfo && locationInfo.isEligibleForFolderShortcut) cr.ui.contextMenuHandler.setContextMenu(this, menu); }; DirectoryItem.prototype.activate = function() { this.parentTree_.directoryModel.activateDirectoryEntry(this.entry); }; //////////////////////////////////////////////////////////////////////////////// // VolumeItem /** * A TreeItem which represents a volume. Volume items are displayed as * top-level children of DirectoryTree. * * @param {DirectoryEntry} dirEntry DirectoryEntry of this item. * @param {NavigationModelItem} modelItem NavigationModelItem of this volume. * @param {DirectoryTree} tree Current tree, which contains this item. * @extends {cr.ui.TreeItem} * @constructor */ function VolumeItem(entry, modelItem, tree) { var item = new cr.ui.TreeItem(); item.__proto__ = VolumeItem.prototype; item.decorate(entry, modelItem, tree); return item; } VolumeItem.prototype = { __proto__: cr.ui.TreeItem.prototype, get entry() { return this.dirEntry_; }, get modelItem() { return this.modelItem_; }, get volumeInfo() { return this.volumeInfo_; }, get labelElement() { return this.firstElementChild.querySelector('.label'); }, // Overrides the property 'expanded' to prevent volume items from shrinking. get expanded() { return Object.getOwnPropertyDescriptor( cr.ui.TreeItem.prototype, 'expanded').get.call(this); }, set expanded(b) { if (!b) return; Object.getOwnPropertyDescriptor( cr.ui.TreeItem.prototype, 'expanded').set.call(this, b); } }; /** * Calls DirectoryItemTreeBaseMethods.updateSubElementsFromList(). * * @param {DirectoryEntry|Object} entry The entry to be searched for. Can be * a fake. * @return {boolean} True if the parent item is found. */ VolumeItem.prototype.searchAndSelectByEntry = function(entry) { return DirectoryItemTreeBaseMethods.searchAndSelectByEntry.call(this, entry); }; /** * Decorates this element. * @param {DirectoryEntry} dirEntry DirectoryEntry of this item. * @param {NavigationModelItem} modelItem NavigationModelItem of this volume. * @param {DirectoryTree} tree Current tree, which contains this item. */ VolumeItem.prototype.decorate = function(entry, modelItem, tree) { this.innerHTML = TREE_ITEM_INNTER_HTML; this.parentTree_ = tree; this.dirEntry_ = entry; this.modelItem_ = modelItem; this.volumeInfo_ = modelItem.volumeInfo; this.label = modelItem.volumeInfo.label; this.setupIcon_(this.querySelector('.icon'), this.volumeInfo); this.setupEjectButton_(this.rowElement); if (tree.contextMenuForRootItems) this.setContextMenu(tree.contextMenuForRootItems); this.updateSubDirectories(false /* recursive */); }; /** * Invoked when the tree item is clicked. * * @param {Event} e Click event. * @override */ VolumeItem.prototype.handleClick = function(e) { // If the currently selected volume is clicked, change current directory to // the volume's root. if (this.selected) this.activate(); cr.ui.TreeItem.prototype.handleClick.call(this, e); // Resets file selection when a volume is clicked. this.parentTree_.directoryModel.clearSelection(); // If the Drive volume is clicked, select one of the children instead of this // item itself. if (this.isDrive()) this.searchAndSelectByEntry(this.entry); }; /** * Retrieves the latest subdirectories and update them on the tree. * @param {boolean} recursive True if the update is recursively. */ VolumeItem.prototype.updateSubDirectories = function(recursive) { // Drive volume has children including fake entries (offline, recent, etc...). if (this.isDrive()) { var entries = [this.entry]; if (this.parentTree_.fakeEntriesVisible_) { for (var key in this.volumeInfo.fakeEntries) entries.push(this.volumeInfo.fakeEntries[key]); } // This list is sorted by URL on purpose. entries.sort(function(a, b) { return a.toURL() < b.toURL(); }); for (var i = 0; i < entries.length; i++) { var item = new DirectoryItem( util.getEntryLabel(this.parentTree_.volumeManager_, entries[i]), entries[i], this, this.parentTree_); this.add(item); item.updateSubDirectories(false); } this.expanded = true; } }; /** * Searches for the changed directory in the current subtree, and if it is found * then updates it. * * @param {DirectoryEntry} changedDirectoryEntry The entry ot the changed * directory. */ VolumeItem.prototype.updateItemByEntry = function(changedDirectoryEntry) { if (this.isDrive()) this.items[0].updateItemByEntry(changedDirectoryEntry); }; /** * Select the item corresponding to the given entry. * @param {DirectoryEntry|Object} entry The directory entry to be selected. Can * be a fake. */ VolumeItem.prototype.selectByEntry = function(entry) { // If this volume is drive, find the item to be selected amang children. if (this.isDrive()) { this.searchAndSelectByEntry(entry); return; } if (util.isSameEntry(this.entry, entry) || util.isDescendantEntry(this.entry, entry)) this.selected = true; }; /** * Sets the context menu for volume items. * @param {cr.ui.Menu} menu Menu to be set. */ VolumeItem.prototype.setContextMenu = function(menu) { if (this.isRemovable_()) cr.ui.contextMenuHandler.setContextMenu(this, menu); }; /** * Change current entry to this volume's root directory. */ VolumeItem.prototype.activate = function() { var directoryModel = this.parentTree_.directoryModel; var onEntryResolved = function(entry) { // Changes directory to the model item's root directory if needed. if (!util.isSameEntry(directoryModel.getCurrentDirEntry(), entry)) { metrics.recordUserAction('FolderShortcut.Navigate'); directoryModel.changeDirectoryEntry(entry); } }.bind(this); this.volumeInfo.resolveDisplayRoot( onEntryResolved, function() { // Error, the display root is not available. It may happen on Drive. this.parentTree_.dataModel.onItemNotFoundError(this.modelItem); }.bind(this)) }; /** * @return {boolean} True if this is Drive volume. */ VolumeItem.prototype.isDrive = function() { return this.volumeInfo.volumeType === VolumeManagerCommon.VolumeType.DRIVE; }; /** * @return {boolean} True if this volume can be removed by user operation. * @private */ VolumeItem.prototype.isRemovable_ = function() { var volumeType = this.volumeInfo.volumeType; return volumeType === VolumeManagerCommon.VolumeType.ARCHIVE || volumeType === VolumeManagerCommon.VolumeType.REMOVABLE || volumeType === VolumeManagerCommon.VolumeType.PROVIDED; }; /** * Set up icon of this volume item. * @param {HTMLElement} icon Icon element to be setup. * @param {VolumeInfo} volumeInfo VolumeInfo determines the icon type. * @private */ VolumeItem.prototype.setupIcon_ = function(icon, volumeInfo) { icon.classList.add('volume-icon'); if (volumeInfo.volumeType === 'provided') { var backgroundImage = '-webkit-image-set(' + 'url(chrome://extension-icon/' + volumeInfo.extensionId + '/24/1) 1x, ' + 'url(chrome://extension-icon/' + volumeInfo.extensionId + '/48/1) 2x);'; // The icon div is not yet added to DOM, therefore it is impossible to // use style.backgroundImage. icon.setAttribute( 'style', 'background-image: ' + backgroundImage); } icon.setAttribute('volume-type-icon', volumeInfo.volumeType); icon.setAttribute('volume-subtype', volumeInfo.deviceType); }; /** * Set up eject button if needed. * @param {HTMLElement} rowElement The parent element for eject button. * @private */ VolumeItem.prototype.setupEjectButton_ = function(rowElement) { if (this.isRemovable_()) { var ejectButton = cr.doc.createElement('div'); // Block other mouse handlers. ejectButton.addEventListener( 'mouseup', function(event) { event.stopPropagation() }); ejectButton.addEventListener( 'mousedown', function(event) { event.stopPropagation() }); ejectButton.className = 'root-eject'; ejectButton.addEventListener('click', function(event) { event.stopPropagation(); var unmountCommand = cr.doc.querySelector('command#unmount'); // Let's make sure 'canExecute' state of the command is properly set for // the root before executing it. unmountCommand.canExecuteChange(this); unmountCommand.execute(this); }.bind(this)); rowElement.appendChild(ejectButton); } }; //////////////////////////////////////////////////////////////////////////////// // ShortcutItem /** * A TreeItem which represents a shortcut for Drive folder. * Shortcut items are displayed as top-level children of DirectoryTree. * * @param {DirectoryEntry} dirEntry DirectoryEntry of this item. * @param {NavigationModelItem} modelItem NavigationModelItem of this volume. * @param {DirectoryTree} tree Current tree, which contains this item. * @extends {cr.ui.TreeItem} * @constructor */ function ShortcutItem(dirEntry, modelItem, tree) { var item = new cr.ui.TreeItem(); item.__proto__ = ShortcutItem.prototype; item.decorate(dirEntry, modelItem, tree); return item; } ShortcutItem.prototype = { __proto__: cr.ui.TreeItem.prototype, get entry() { return this.dirEntry_; }, get modelItem() { return this.modelItem_; }, get labelElement() { return this.firstElementChild.querySelector('.label'); } }; /** * Finds a parent directory of the {@code entry} in {@code this}, and * invokes the DirectoryItem.selectByEntry() of the found directory. * * @param {DirectoryEntry|Object} entry The entry to be searched for. Can be * a fake. * @return {boolean} True if the parent item is found. */ ShortcutItem.prototype.searchAndSelectByEntry = function(entry) { // Always false as shortcuts have no children. return false; }; /** * Decorates this element. * @param {DirectoryEntry} dirEntry DirectoryEntry of this item. * @param {NavigationModelItem} modelItem NavigationModelItem of this volume. * @param {DirectoryTree} tree Current tree, which contains this item. */ ShortcutItem.prototype.decorate = function(dirEntry, modelItem, tree) { this.innerHTML = TREE_ITEM_INNTER_HTML; this.parentTree_ = tree; this.label = dirEntry.name; this.dirEntry_ = dirEntry; this.modelItem_ = modelItem; var icon = this.querySelector('.icon'); icon.classList.add('volume-icon'); icon.setAttribute('volume-type-icon', VolumeManagerCommon.VolumeType.DRIVE); if (tree.contextMenuForRootItems) this.setContextMenu(tree.contextMenuForRootItems); }; /** * Invoked when the tree item is clicked. * * @param {Event} e Click event. * @override */ ShortcutItem.prototype.handleClick = function(e) { cr.ui.TreeItem.prototype.handleClick.call(this, e); this.parentTree_.directoryModel.clearSelection(); }; /** * Select the item corresponding to the given entry. * @param {DirectoryEntry} entry The directory entry to be selected. */ ShortcutItem.prototype.selectByEntry = function(entry) { if (util.isSameEntry(entry, this.entry)) this.selected = true; }; /** * Sets the context menu for shortcut items. * @param {cr.ui.Menu} menu Menu to be set. */ ShortcutItem.prototype.setContextMenu = function(menu) { cr.ui.contextMenuHandler.setContextMenu(this, menu); }; /** * Change current entry to the entry corresponding to this shortcut. */ ShortcutItem.prototype.activate = function() { var directoryModel = this.parentTree_.directoryModel; var onEntryResolved = function(entry) { // Changes directory to the model item's root directory if needed. if (!util.isSameEntry(directoryModel.getCurrentDirEntry(), entry)) { metrics.recordUserAction('FolderShortcut.Navigate'); directoryModel.changeDirectoryEntry(entry); } }.bind(this); // For shortcuts we already have an Entry, but it has to be resolved again // in case, it points to a non-existing directory. webkitResolveLocalFileSystemURL( this.entry.toURL(), onEntryResolved, function() { // Error, the entry can't be re-resolved. It may happen for shortcuts // which targets got removed after resolving the Entry during // initialization. this.parentTree_.dataModel.onItemNotFoundError(this.modelItem); }.bind(this)); }; //////////////////////////////////////////////////////////////////////////////// // DirectoryTree /** * Tree of directories on the middle bar. This element is also the root of * items, in other words, this is the parent of the top-level items. * * @constructor * @extends {cr.ui.Tree} */ function DirectoryTree() {} /** * Decorates an element. * @param {HTMLElement} el Element to be DirectoryTree. * @param {DirectoryModel} directoryModel Current DirectoryModel. * @param {VolumeManagerWrapper} volumeManager VolumeManager of the system. * @param {MetadataCache} metadataCache Shared MetadataCache instance. * @param {boolean} fakeEntriesVisible True if it should show the fakeEntries. */ DirectoryTree.decorate = function( el, directoryModel, volumeManager, metadataCache, fakeEntriesVisible) { el.__proto__ = DirectoryTree.prototype; (/** @type {DirectoryTree} */ el).decorate( directoryModel, volumeManager, metadataCache, fakeEntriesVisible); }; DirectoryTree.prototype = { __proto__: cr.ui.Tree.prototype, // DirectoryTree is always expanded. get expanded() { return true; }, /** * @param {boolean} value Not used. */ set expanded(value) {}, /** * The DirectoryEntry corresponding to this DirectoryItem. This may be * a dummy DirectoryEntry. * @type {DirectoryEntry|Object} * @override **/ get entry() { return this.dirEntry_; }, /** * The DirectoryModel this tree corresponds to. * @type {DirectoryModel} */ get directoryModel() { return this.directoryModel_; }, /** * The VolumeManager instance of the system. * @type {VolumeManager} */ get volumeManager() { return this.volumeManager_; }, /** * The reference to shared MetadataCache instance. * @type {MetadataCache} */ get metadataCache() { return this.metadataCache_; }, set dataModel(dataModel) { if (!this.onListContentChangedBound_) this.onListContentChangedBound_ = this.onListContentChanged_.bind(this); if (this.dataModel_) { this.dataModel_.removeEventListener( 'change', this.onListContentChangedBound_); this.dataModel_.removeEventListener( 'permuted', this.onListContentChangedBound_); } this.dataModel_ = dataModel; dataModel.addEventListener('change', this.onListContentChangedBound_); dataModel.addEventListener('permuted', this.onListContentChangedBound_); }, get dataModel() { return this.dataModel_; } }; cr.defineProperty(DirectoryTree, 'contextMenuForSubitems', cr.PropertyKind.JS); cr.defineProperty(DirectoryTree, 'contextMenuForRootItems', cr.PropertyKind.JS); /** * Calls DirectoryItemTreeBaseMethods.updateSubElementsFromList(). * * @param {boolean} recursive True if the all visible sub-directories are * updated recursively including left arrows. If false, the update walks * only immediate child directories without arrows. */ DirectoryTree.prototype.updateSubElementsFromList = function(recursive) { // First, current items which is not included in the models_[] should be // removed. for (var i = 0; i < this.items.length;) { var found = false; for (var j = 0; j < this.models_.length; j++) { if (util.isSameEntry(this.items[i].entry, this.models_[j].entry)) { found = true; break; } } if (!found) { if (this.items[i].selected) this.items[i].selected = false; this.remove(this.items[i]); } else { i++; } } // Next, insert items which is in models_[] but not in current items. var modelIndex = 0; var itemIndex = 0; while (modelIndex < this.models_.length) { if (itemIndex < this.items.length && util.isSameEntry(this.items[itemIndex].entry, this.models_[modelIndex].entry)) { if (recursive && this.items[itemIndex] instanceof VolumeItem) this.items[itemIndex].updateSubDirectories(true); } else { var model = this.models_[modelIndex]; if (model.modelItem.isVolume) { this.addAt(new VolumeItem(model.entry, model.modelItem, this), itemIndex); } else { this.addAt(new ShortcutItem(model.entry, model.modelItem, this), itemIndex); } } itemIndex++; modelIndex++; } if (itemIndex !== 0) this.hasChildren = true; }; /** * Finds a parent directory of the {@code entry} in {@code this}, and * invokes the DirectoryItem.selectByEntry() of the found directory. * * @param {DirectoryEntry|Object} entry The entry to be searched for. Can be * a fake. * @return {boolean} True if the parent item is found. */ DirectoryTree.prototype.searchAndSelectByEntry = function(entry) { // If the |entry| is same as one of volumes or shortcuts, select it. for (var i = 0; i < this.items.length; i++) { // Skips the Drive root volume. For Drive entries, one of children of Drive // root or shortcuts should be selected. var item = this.items[i]; if (item instanceof VolumeItem && item.isDrive()) continue; if (util.isSameEntry(item.entry, entry)) { this.dontHandleChangeEvent_ = true; item.selectByEntry(entry); this.dontHandleChangeEvent_ = false; return true; } } // Otherwise, search whole tree. this.dontHandleChangeEvent_ = true; var found = DirectoryItemTreeBaseMethods.searchAndSelectByEntry.call( this, entry); this.dontHandleChangeEvent_ = false; return found; }; /** * Decorates an element. * @param {DirectoryModel} directoryModel Current DirectoryModel. * @param {VolumeManagerWrapper} volumeManager VolumeManager of the system. * @param {MetadataCache} metadataCache Shared MetadataCache instance. * @param {boolean} fakeEntriesVisible True if it should show the fakeEntries. */ DirectoryTree.prototype.decorate = function( directoryModel, volumeManager, metadataCache, fakeEntriesVisible) { cr.ui.Tree.prototype.decorate.call(this); this.sequence_ = 0; this.directoryModel_ = directoryModel; this.volumeManager_ = volumeManager; this.metadataCache_ = metadataCache; this.models_ = []; this.fileFilter_ = this.directoryModel_.getFileFilter(); this.fileFilter_.addEventListener('changed', this.onFilterChanged_.bind(this)); this.directoryModel_.addEventListener('directory-changed', this.onCurrentDirectoryChanged_.bind(this)); // Add a handler for directory change. this.addEventListener('change', function() { if (this.selectedItem && !this.dontHandleChangeEvent_) this.selectedItem.activate(); }.bind(this)); this.privateOnDirectoryChangedBound_ = this.onDirectoryContentChanged_.bind(this); chrome.fileBrowserPrivate.onDirectoryChanged.addListener( this.privateOnDirectoryChangedBound_); this.scrollBar_ = new MainPanelScrollBar(); this.scrollBar_.initialize(this.parentNode, this); /** * Flag to show fake entries in the tree. * @type {boolean} * @private */ this.fakeEntriesVisible_ = fakeEntriesVisible; }; /** * Select the item corresponding to the given entry. * @param {DirectoryEntry|Object} entry The directory entry to be selected. Can * be a fake. */ DirectoryTree.prototype.selectByEntry = function(entry) { if (this.selectedItem && util.isSameEntry(entry, this.selectedItem.entry)) return; if (this.searchAndSelectByEntry(entry)) return; this.updateSubDirectories(false /* recursive */); var currentSequence = ++this.sequence_; var volumeInfo = this.volumeManager_.getVolumeInfo(entry); volumeInfo.resolveDisplayRoot(function() { if (this.sequence_ !== currentSequence) return; if (!this.searchAndSelectByEntry(entry)) this.selectedItem = null; }.bind(this)); }; /** * Select the volume or the shortcut corresponding to the given index. * @param {number} index 0-based index of the target top-level item. */ DirectoryTree.prototype.selectByIndex = function(index) { if (index < 0 || index >= this.items.length) return false; this.items[index].selected = true; return true; }; /** * Retrieves the latest subdirectories and update them on the tree. * * @param {boolean} recursive True if the update is recursively. * @param {function()=} opt_callback Called when subdirectories are fully * updated. */ DirectoryTree.prototype.updateSubDirectories = function( recursive, opt_callback) { var callback = opt_callback || function() {}; // Resolves all root entries for model items. var itemPromises = []; for (var i = 0; i < this.dataModel.length; i++) { if (this.dataModel.item(i).isVolume) { // Volume's root entries need to be resolved. itemPromises.push(new Promise(function(resolve, reject) { var modelItem = this.dataModel.item(i); modelItem.volumeInfo.resolveDisplayRoot(function(entry) { resolve({entry: entry, modelItem: modelItem}); }); }.bind(this))); } else { // Shortcuts' root entries can be obtained immediately. itemPromises.push( Promise.resolve({entry: this.dataModel.item(i).entry, modelItem: this.dataModel.item(i)})); } } // Redraws this tree using resolved root entries and volume info. Promise.all(itemPromises).then(function(results) { this.models_ = results; this.redraw(recursive); callback(); }.bind(this)); }; /** * Redraw the list. * @param {boolean} recursive True if the update is recursively. False if the * only root items are updated. */ DirectoryTree.prototype.redraw = function(recursive) { this.updateSubElementsFromList(recursive); }; /** * Invoked when the filter is changed. * @private */ DirectoryTree.prototype.onFilterChanged_ = function() { // Returns immediately, if the tree is hidden. if (this.hidden) return; this.redraw(true /* recursive */); }; /** * Invoked when a directory is changed. * @param {!UIEvent} event Event. * @private */ DirectoryTree.prototype.onDirectoryContentChanged_ = function(event) { if (event.eventType !== 'changed') return; for (var i = 0; i < this.items.length; i++) { if (this.items[i] instanceof VolumeItem) this.items[i].updateItemByEntry(event.entry); } }; /** * Invoked when the current directory is changed. * @param {!UIEvent} event Event. * @private */ DirectoryTree.prototype.onCurrentDirectoryChanged_ = function(event) { this.selectByEntry(event.newDirEntry); }; /** * Invoked when the volume list or shortcut list is changed. * @private */ DirectoryTree.prototype.onListContentChanged_ = function() { this.updateSubDirectories(false, function() { // If no item is selected now, try to select the item corresponding to // current directory because the current directory might have been populated // in this tree in previous updateSubDirectories(). if (!this.selectedItem) { var currentDir = this.directoryModel_.getCurrentDirEntry(); if (currentDir) this.selectByEntry(currentDir); } }.bind(this)); }; /** * Updates the UI after the layout has changed. */ DirectoryTree.prototype.relayout = function() { cr.dispatchSimpleEvent(this, 'relayout'); };
{ "content_hash": "1b9005a7a5430c74eb7b5b1f6b8bb00f", "timestamp": "", "source": "github", "line_count": 1141, "max_line_length": 80, "avg_line_length": 31.61174408413672, "alnum_prop": 0.6891790734425685, "repo_name": "xin3liang/platform_external_chromium_org", "id": "faec383f0b0debd6889b43b8e710af36d3c09e7f", "size": "36069", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ui/file_manager/file_manager/foreground/js/directory_tree.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Assembly", "bytes": "53530" }, { "name": "Awk", "bytes": "7721" }, { "name": "C", "bytes": "35959480" }, { "name": "C++", "bytes": "223698188" }, { "name": "CSS", "bytes": "973752" }, { "name": "Java", "bytes": "6804114" }, { "name": "JavaScript", "bytes": "12537619" }, { "name": "Mercury", "bytes": "9480" }, { "name": "Objective-C", "bytes": "880662" }, { "name": "Objective-C++", "bytes": "7094479" }, { "name": "PHP", "bytes": "61320" }, { "name": "Perl", "bytes": "644436" }, { "name": "Python", "bytes": "10027001" }, { "name": "Shell", "bytes": "1313358" }, { "name": "Standard ML", "bytes": "4131" }, { "name": "Tcl", "bytes": "277091" }, { "name": "XSLT", "bytes": "12410" }, { "name": "nesC", "bytes": "15206" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>interval: 3 m 16 s 🏆</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 / interval - 3.3.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> interval <small> 3.3.0 <span class="label label-success">3 m 16 s 🏆</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-06 05:16:16 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-06 05:16:16 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base 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 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 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;guillaume.melquiond@inria.fr&quot; homepage: &quot;https://coqinterval.gitlabpages.inria.fr/&quot; dev-repo: &quot;git+https://gitlab.inria.fr/coqinterval/interval.git&quot; bug-reports: &quot;https://gitlab.inria.fr/coqinterval/interval/issues&quot; license: &quot;CeCILL-C&quot; build: [ [&quot;./configure&quot;] [&quot;./remake&quot; &quot;-j%{jobs}%&quot;] ] install: [&quot;./remake&quot; &quot;install&quot;] depends: [ &quot;coq&quot; {&gt;= &quot;8.5&quot; &amp; &lt; &quot;8.7&quot;} | (&quot;coq&quot; {&gt;= &quot;8.7&quot;} &amp; &quot;coq-bignums&quot;) &quot;coq-flocq&quot; {&gt;= &quot;2.5.0&quot; &amp; &lt; &quot;3.0~&quot;} &quot;coq-mathcomp-ssreflect&quot; {&gt;= &quot;1.6&quot;} &quot;coq-coquelicot&quot; {&gt;= &quot;3.0&quot;} ] tags: [ &quot;keyword:interval arithmetic&quot; &quot;keyword:decision procedure&quot; &quot;keyword:floating-point arithmetic&quot; &quot;keyword:reflexive tactic&quot; &quot;keyword:Taylor models&quot; &quot;category:Mathematics/Real Calculus and Topology&quot; &quot;category:Computer Science/Decision Procedures and Certified Algorithms/Decision procedures&quot; ] authors: [ &quot;Guillaume Melquiond &lt;guillaume.melquiond@inria.fr&gt;&quot; ] synopsis: &quot;A Coq tactic for proving bounds on real-valued expressions automatically&quot; url { src: &quot;https://coqinterval.gitlabpages.inria.fr/releases/interval-3.3.0.tar.gz&quot; checksum: &quot;md5=5b50705041b3c95a43fa6789cca0aa89&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-interval.3.3.0 coq.8.8.1</code></dd> <dt>Return code</dt> <dd>0</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>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-interval.3.3.0 coq.8.8.1</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>10 m 49 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-interval.3.3.0 coq.8.8.1</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>3 m 16 s</dd> </dl> <h2>Installation size</h2> <p>Total: 20 M</p> <ul> <li>13 M <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/coqapprox/basic_rec.vo</code></li> <li>1 M <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_tactic.vo</code></li> <li>603 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/coqapprox/taylor_model_int_sharp.vo</code></li> <li>436 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_transcend.vo</code></li> <li>403 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_integral.vo</code></li> <li>380 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_bisect.vo</code></li> <li>351 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/coqapprox/poly_datatypes.vo</code></li> <li>323 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_interval_float.vo</code></li> <li>293 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_taylor_model.vo</code></li> <li>263 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_interval_float_full.vo</code></li> <li>231 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/bertrand.vo</code></li> <li>220 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_specific_ops.vo</code></li> <li>180 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/coqapprox/poly_bound.vo</code></li> <li>178 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_generic_proof.vo</code></li> <li>161 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_xreal_derive.vo</code></li> <li>150 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_missing.vo</code></li> <li>146 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_bigint_carrier.vo</code></li> <li>139 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/coqapprox/coquelicot_compl.vo</code></li> <li>128 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/coqapprox/poly_bound_quad.vo</code></li> <li>120 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_stdz_carrier.vo</code></li> <li>111 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/coqapprox/interval_compl.vo</code></li> <li>109 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_interval.vo</code></li> <li>107 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_generic.vo</code></li> <li>93 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/coqapprox/seq_compl.vo</code></li> <li>93 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/various_integrals.vo</code></li> <li>89 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/coqapprox/taylor_thm.vo</code></li> <li>72 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/coqapprox/taylor_poly.vo</code></li> <li>72 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_xreal.vo</code></li> <li>71 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/coqapprox/integral_pol.vo</code></li> <li>67 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_univariate.vo</code></li> <li>66 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_float_sig.vo</code></li> <li>65 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_generic_ops.vo</code></li> <li>60 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_specific_sig.vo</code></li> <li>59 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/Interval_definitions.vo</code></li> <li>55 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/coqapprox/xreal_ssr_compat.vo</code></li> <li>41 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/coqapprox/Rstruct.vo</code></li> <li>35 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Interval/BigNumsCompat.vo</code></li> </ul> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq-interval.3.3.0</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": "71f58280a3a8b2cb8f61354985ac6aa5", "timestamp": "", "source": "github", "line_count": 204, "max_line_length": 159, "avg_line_length": 57.22549019607843, "alnum_prop": 0.5860030837759123, "repo_name": "coq-bench/coq-bench.github.io", "id": "bdeef2089847d85af19f244d5f843264a581f6d8", "size": "11699", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.08.1-2.0.5/released/8.8.1/interval/3.3.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.springframework.beans.propertyeditors; import java.beans.PropertyEditorSupport; import java.util.StringJoiner; import org.springframework.lang.Nullable; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * Property editor for an array of {@link Class Classes}, to enable * the direct population of a {@code Class[]} property without having to * use a {@code String} class name property as bridge. * * <p>Also supports "java.lang.String[]"-style array class names, in contrast * to the standard {@link Class#forName(String)} method. * * @author Rob Harrop * @author Juergen Hoeller * @since 2.0 */ public class ClassArrayEditor extends PropertyEditorSupport { @Nullable private final ClassLoader classLoader; /** * Create a default {@code ClassEditor}, using the thread * context {@code ClassLoader}. */ public ClassArrayEditor() { this(null); } /** * Create a default {@code ClassArrayEditor}, using the given * {@code ClassLoader}. * @param classLoader the {@code ClassLoader} to use * (or pass {@code null} for the thread context {@code ClassLoader}) */ public ClassArrayEditor(@Nullable ClassLoader classLoader) { this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); } @Override public void setAsText(String text) throws IllegalArgumentException { if (StringUtils.hasText(text)) { String[] classNames = StringUtils.commaDelimitedListToStringArray(text); Class<?>[] classes = new Class<?>[classNames.length]; for (int i = 0; i < classNames.length; i++) { String className = classNames[i].trim(); classes[i] = ClassUtils.resolveClassName(className, this.classLoader); } setValue(classes); } else { setValue(null); } } @Override public String getAsText() { Class<?>[] classes = (Class[]) getValue(); if (ObjectUtils.isEmpty(classes)) { return ""; } StringJoiner sj = new StringJoiner(","); for (Class<?> klass : classes) { sj.add(ClassUtils.getQualifiedName(klass)); } return sj.toString(); } }
{ "content_hash": "37d853962faf983e717e3d5da9090270", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 94, "avg_line_length": 27.164556962025316, "alnum_prop": 0.7124883504193849, "repo_name": "spring-projects/spring-framework", "id": "0a2882a988c0c2b280a96813d2b57a3254c2ed48", "size": "2767", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "spring-beans/src/main/java/org/springframework/beans/propertyeditors/ClassArrayEditor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "32003" }, { "name": "CSS", "bytes": "1019" }, { "name": "Dockerfile", "bytes": "257" }, { "name": "FreeMarker", "bytes": "30820" }, { "name": "Groovy", "bytes": "6902" }, { "name": "HTML", "bytes": "1203" }, { "name": "Java", "bytes": "43939386" }, { "name": "JavaScript", "bytes": "280" }, { "name": "Kotlin", "bytes": "571613" }, { "name": "PLpgSQL", "bytes": "305" }, { "name": "Python", "bytes": "254" }, { "name": "Ruby", "bytes": "1060" }, { "name": "Shell", "bytes": "5374" }, { "name": "Smarty", "bytes": "700" }, { "name": "XSLT", "bytes": "2945" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.ow2.chameleon.everest</groupId> <artifactId>everest-it</artifactId> <version>1.0-SNAPSHOT</version> <relativePath>../../../pom.xml</relativePath> </parent> <artifactId>everest-ipojo-test</artifactId> </project>
{ "content_hash": "fc89639b1814fc98be4c67174582852e", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 108, "avg_line_length": 36.25, "alnum_prop": 0.646551724137931, "repo_name": "ow2-chameleon/everest", "id": "090a4530a1a6942fb18873bac30f3961c91edd55", "size": "580", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "everest-it/src/it/everest-ipojo-test/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "63389" }, { "name": "Java", "bytes": "833207" } ], "symlink_target": "" }
FROM python:2.7 RUN apt-get update -qq && \ DEBIAN_FRONTEND=noninteractive apt-get install --no-install-recommends -qq -y vim && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* && \ pip install ansible
{ "content_hash": "c930cea5c79f0e479d065224213594a8", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 90, "avg_line_length": 34, "alnum_prop": 0.6302521008403361, "repo_name": "kitpages/docker-ansible", "id": "ee12e68dee4b39d9c3b89f9bfb1ea4ecb100544a", "size": "238", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Dockerfile", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "2532" } ], "symlink_target": "" }
using System; namespace Imageboard10.Core.Utility { /// <summary> /// Класс-помощник с датами. /// </summary> public static class DatesHelper { private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); /// <summary> /// Перевести из UNIX-времени. /// </summary> /// <param name="timestamp">Временная метка.</param> /// <returns>Время.</returns> public static DateTime FromUnixTime(int timestamp) { return UnixEpoch.AddSeconds(timestamp).ToLocalTime(); } /// <summary> /// Время для пользователя. /// </summary> /// <param name="dateTime">Время.</param> /// <returns>Строка.</returns> public static string ToUserString(DateTime dateTime) { string dow = ""; switch (dateTime.DayOfWeek) { case DayOfWeek.Monday: dow = "Пнд"; break; case DayOfWeek.Tuesday: dow = "Втр"; break; case DayOfWeek.Wednesday: dow = "Срд"; break; case DayOfWeek.Thursday: dow = "Чтв"; break; case DayOfWeek.Friday: dow = "Птн"; break; case DayOfWeek.Saturday: dow = "Сбт"; break; case DayOfWeek.Sunday: dow = "Вск"; break; } return $"{dow} {dateTime.Day:D2}.{dateTime.Month:D2}.{dateTime.Year:D4} {dateTime.Hour:D2}:{dateTime.Minute:D2}"; } } }
{ "content_hash": "9e9656ba1bf0fa52d27ba39cc87ddbf1", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 125, "avg_line_length": 30.775862068965516, "alnum_prop": 0.457703081232493, "repo_name": "Opiumtm/Imageboard10", "id": "97af8565e5a365e4cdbaa0d660f8886deb719fe1", "size": "1896", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Imageboard10/Imageboard10.Core/Utility/DatesHelper.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1928772" } ], "symlink_target": "" }
how-to-demo =========== This project includes some useful(or not) demo/testbed I met/wrote before. ###android_load_res_dynamically This project show how to load resource/layouts/codes from an uninstalled apk file directly.
{ "content_hash": "936a49095abb1ca59db678f1b531688b", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 91, "avg_line_length": 28.25, "alnum_prop": 0.7522123893805309, "repo_name": "chloette/how-to-demo", "id": "61d1e329284ebb41d7e6bbbb9fb2a9872ad14f25", "size": "226", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "13572" } ], "symlink_target": "" }
import {makeExecutableSchema} from 'graphql-tools' import {SchemaBuilder} from './common/graphql' import {oncePerServices} from './common/services' import {missingArgument} from './common/utils/arguments' const hasOwnProperty = Object.prototype.hasOwnProperty; export default oncePerServices(function (services = missingArgument('services')) { return async function () { const typeDefs = []; const resolvers = Object.create(null); await (new SchemaBuilder({ excelDB: require('./services/excelDB/graphql').default(services), }).build({typeDefs, resolvers})); // DEBUG: Записывает схему в директорию /temp // const tempDir = require('path').join(process.cwd(), './temp') // await require('./common/utils/ensureDir').default(tempDir); // require('fs').writeFileSync(require('path').join(tempDir, 'v1.gql'), typeDefs.join('\n')); return makeExecutableSchema({ typeDefs, resolvers, }) } });
{ "content_hash": "4e25526c934b0cbe619d1fa452ae2f00", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 97, "avg_line_length": 31.866666666666667, "alnum_prop": 0.6903765690376569, "repo_name": "innervate-ru/Bot", "id": "c336046d180b9e4f368a8bbe86b9e78690fc45cd", "size": "982", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aslifeBorder/src/graphqlSchema.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2124" }, { "name": "HTML", "bytes": "1429" }, { "name": "JavaScript", "bytes": "957634" } ], "symlink_target": "" }
package ananas.waymq.droid; import java.util.HashMap; import java.util.Map; import ananas.waymq.droid.protocol.Protocol; import ananas.waymq.droid.task.BackgroundContext; import ananas.waymq.droid.task.BackgroundTask; import ananas.waymq.droid.task.DefaultServiceAgent; import ananas.waymq.droid.task.ForegroundContext; import ananas.waymq.droid.task.ServiceAgent; import ananas.waymq.droid.util.Util; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import com.alibaba.fastjson.JSONObject; public class EventActivity extends Activity { private ServiceAgent _agent; private TextView _text_title; private TextView _text_time; private TextView _text_content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_event); ServiceAgent agent = new DefaultServiceAgent(this); this._agent = agent; this._text_title = (TextView) this.findViewById(R.id.text_event_title); this._text_time = (TextView) this.findViewById(R.id.text_event_time); this._text_content = (TextView) this .findViewById(R.id.text_event_content); this.setupButtonListener(R.id.button_join); this.setupButtonListener(R.id.button_cancel); } private void setupButtonListener(int id) { Button btn = (Button) this.findViewById(id); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { int id = view.getId(); EventActivity.this.onClickButton(id); } }); } protected void onClickButton(int id) { switch (id) { case R.id.button_join: { this.doJoin(); break; } case R.id.button_cancel: { this.doCancel(); break; } default: break; } } private void doCancel() { this._agent.runInBackground(new BackgroundTask() { private Map<String, String> _param; private JSONObject _json; @Override public void onStart(ForegroundContext fc) { Map<String, String> param = new HashMap<String, String>(); this._param = param; param.put(Protocol.ParamKey.class_, Protocol.Event.class_name); param.put(Protocol.ParamKey.method_, Protocol.Event.do_cancel); } @Override public void onProcess(BackgroundContext bc) { ServiceAgent agent = bc.getServiceAgent(); Map<String, String> param = this._param; this._json = agent.requestJSON("POST", param); } @Override public void onFinish(ForegroundContext fc) { EventActivity.this.refresh(); } }); } private void doJoin() { this._agent.runInBackground(new BackgroundTask() { private Map<String, String> _param; private JSONObject _json; @Override public void onStart(ForegroundContext fc) { Map<String, String> param = new HashMap<String, String>(); this._param = param; param.put(Protocol.ParamKey.class_, Protocol.Event.class_name); param.put(Protocol.ParamKey.method_, Protocol.Event.do_join); } @Override public void onProcess(BackgroundContext bc) { ServiceAgent agent = bc.getServiceAgent(); Map<String, String> param = this._param; this._json = agent.requestJSON("POST", param); } @Override public void onFinish(ForegroundContext fc) { EventActivity.this.refresh(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { final int id = item.getItemId(); if (id == R.id.action_debug) { startActivity(new Intent(this, DebugActivity.class)); } else { return super.onOptionsItemSelected(item); } return true; } @Override protected void onPause() { this._agent.onPause(); super.onPause(); } @Override protected void onResume() { super.onResume(); this._agent.onResume(); this.refresh(); } @Override protected void onStart() { super.onStart(); this._agent.onStart(); } @Override protected void onStop() { this._agent.onStop(); super.onStop(); } private void refresh() { _agent.runInBackground(new BackgroundTask() { private Map<String, String> _param; private JSONObject _json; @Override public void onStart(ForegroundContext fc) { Map<String, String> param = new HashMap<String, String>(); this._param = param; param.put(Protocol.ParamKey.class_, Protocol.Event.class_name); param.put(Protocol.ParamKey.method_, Protocol.Event.do_get_info); } @Override public void onProcess(BackgroundContext bc) { ServiceAgent agent = bc.getServiceAgent(); Map<String, String> param = this._param; this._json = agent.requestJSON("GET", param); } @Override public void onFinish(ForegroundContext fc) { if (_json == null) { return; } JSONObject event = _json.getJSONObject("event"); TheEvent ev = new TheEvent(); ev.title = event.getString("title"); ev.content = event.getString("content"); ev.time_open = event.getLongValue("open_time"); EventActivity.this.refresh(ev); } }); } protected void refresh(TheEvent ev) { String time = Util.timeToString(ev.time_open); this._text_title.setText(ev.title); this._text_time.setText(time); this._text_content.setText(ev.content); } class TheEvent { protected String title; protected String content; protected long time_open; } }
{ "content_hash": "2b7d2c5404e15570c40f8f5675ec6602", "timestamp": "", "source": "github", "line_count": 235, "max_line_length": 74, "avg_line_length": 23.953191489361704, "alnum_prop": 0.7047432936578433, "repo_name": "xukun0217/wayMQ", "id": "34c76089febcc5fa1ef7c702166ec1f43dfb5420", "size": "5629", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wayMQ-droid/src/ananas/waymq/droid/EventActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "830" }, { "name": "Java", "bytes": "165841" }, { "name": "JavaScript", "bytes": "7277" } ], "symlink_target": "" }
package org.dosomething.android.receivers; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import org.dosomething.android.R; import org.dosomething.android.activities.Campaign; import org.dosomething.android.activities.Welcome; import org.dosomething.android.cache.DSPreferences; /** * AlarmReceiver * * Class to receive and handle triggers set by AlarmManager. */ public class AlarmReceiver extends BroadcastReceiver { public static final String EXTRA_CAMPAIGN_ID = "campaign-id"; public static final String EXTRA_CAMPAIGN_NAME = "campaign-name"; public static final String EXTRA_CAMPAIGN_STEP = "campaign-step"; public static final String NOTIFICATION_TYPE = "notification-type"; public static final String NOTIF_ALARM_CAMPAIGN = "Alarm.campaign"; public static final String NOTIF_CAMPAIGN_STEP_REMINDER = "Alarm.campaignStep"; public static final int ALARM_ID_REPORT_BACK = 100; public static final int ALARM_ID_CAMPAIGN_STEP_REMINDER = 101; @Override public void onReceive(Context context, Intent intent) { if (context != null) { NotificationManager notifManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); if (notifManager != null) { // Get data sent from the AlarmManager Bundle bundle = intent.getExtras(); String campaignId = bundle.getString(EXTRA_CAMPAIGN_ID); String campaignName = bundle.getString(EXTRA_CAMPAIGN_NAME); String notificationType = bundle.getString(NOTIFICATION_TYPE); if (notificationType.equals(NOTIF_ALARM_CAMPAIGN)) { Intent launchIntent = new Intent(context, Welcome.class); launchIntent.putExtra(NOTIF_ALARM_CAMPAIGN, campaignId); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, launchIntent, Intent.FLAG_ACTIVITY_NEW_TASK); // Display message reminding users to report back for campaign they signed up for String notifyTitle = context.getString(R.string.reminder_title); String notifyBody = context.getString(R.string.reminder_body_reportback, campaignName); // Build the notification NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.actionbar_logo) .setContentTitle(notifyTitle) .setContentText(notifyBody) .setContentIntent(pendingIntent); // Send the notification to the system notifManager.notify(ALARM_ID_REPORT_BACK, notifyBuilder.build()); } else if (notificationType.equals(NOTIF_CAMPAIGN_STEP_REMINDER)) { // Notification title String notifTitle = context.getString(R.string.reminder_title); // Notification body text includes campaign name and step the reminder is for String campaignStep = bundle.getString(EXTRA_CAMPAIGN_STEP); String notifBody = context.getString(R.string.reminder_campaign_step_body, campaignStep, campaignName); // Create the Intent to package with the notification Intent launchIntent = Campaign.getIntent(context, campaignId, campaignStep); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, launchIntent, Intent.FLAG_ACTIVITY_NEW_TASK); // Build the notification NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.actionbar_logo) .setContentTitle(notifTitle) .setContentText(notifBody) .setContentIntent(pendingIntent); // Send the notification to the system notifManager.notify(ALARM_ID_CAMPAIGN_STEP_REMINDER, notifyBuilder.build()); // Remove the log of this reminder from DSPreferences DSPreferences dsPrefs = new DSPreferences(context); dsPrefs.clearStepReminder(campaignId, campaignStep); } } } } }
{ "content_hash": "33005ca2083c90e8e69b5e99af3f1b17", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 133, "avg_line_length": 48.07142857142857, "alnum_prop": 0.6357461260878794, "repo_name": "DoSomething/ds-android", "id": "514c1913074047994b0d33b801f66f4fa6b39750", "size": "4711", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dosomething/src/org/dosomething/android/receivers/AlarmReceiver.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "4868" }, { "name": "Java", "bytes": "1510006" } ], "symlink_target": "" }
<html> <head> <title> Morning-after pill closer to approval </title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <?php include "../../legacy-includes/Script.htmlf" ?> </head> <body bgcolor="#FFFFCC" text="000000" link="990000" vlink="660000" alink="003366" leftmargin="0" topmargin="0"> <table width="744" cellspacing="0" cellpadding="0" border="0"> <tr><td width="474"><a name="Top"></a><?php include "../../legacy-includes/TopLogo.htmlf" ?></td> <td width="270"><?php include "../../legacy-includes/TopAd.htmlf" ?> </td></tr></table> <table width="744" cellspacing="0" cellpadding="0" border="0"> <tr><td width="18" bgcolor="FFCC66"></td> <td width="108" bgcolor="FFCC66" valign=top><?php include "../../legacy-includes/LeftButtons.htmlf" ?></td> <td width="18"></td> <td width="480" valign="top"> <?php include "../../legacy-includes/BodyInsert.htmlf" ?> <P><font face="Times New Roman, Times, serif" size="5"><b>Morning-after pill closer to approval</b></font></P> <P><font face="Times New Roman, Times, serif" size="2"><b>By Elizabeth Schulte</b></font><font face="Arial, Helvetica, sans-serif" size="2"> | January 2, 2004 | Page 2</font></P> <P><font face="Times New Roman, Times, serif" size="3">DESPITE AN all-out attack by the religious right, two advisory committees have recommended that the Food and Drug Administration (FDA) make the "morning-after" contraception pill available without a doctor's prescription. The pill--which is used to stop pregnancy within 72 hours after unprotected sex, or when contraception fails--would allow women the freedom to prevent an unwanted pregnancy without a time-consuming and costly doctor's visit.</P> <P>The treatment consists of two progestin pills taken 12 hours apart--and would cost about $30 without a prescription. The pill, which has been approved in 101 countries and is sold without a prescription in 33 of them, was approved in the U.S. on a prescription-only basis in 1999. Since then, it has been used by some 2.4 million women--even though it is not widely available.</P> <P>Among the advisory panel members, anti-abortionists like W. David Hager of the University of Kentucky and Joseph Stanford of the University of Utah want to force manufacturers of emergency contraception to print package warnings that the pills may "cause abortion." The bigots believe that women shouldn't be able to make decisions about whether to stop an unwanted pregnancy.</P> <P>The FDA is expected to make a final decision in early February on whether the pills will be available over the counter. If they do, it will be a long overdue victory for women's right to control their own bodies--and a blow to the right-wing fanatics who want to see that right taken away. As one young woman from the Gainesville, Fla., area chapter of the National Organization for Women told the advisory panels, "Women deserve access at any time, at any age, for any reason."</P> <?php include "../../legacy-includes/BottomNavLinks.htmlf" ?> <td width="12"></td> <td width="108" valign="top"> <?php include "../../legacy-includes/RightAdFolder.htmlf" ?> </td> </tr> </table> </body> </html>
{ "content_hash": "e8210158dc20f7fc0c97c51e57556bea", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 505, "avg_line_length": 63.28, "alnum_prop": 0.7316687737041719, "repo_name": "ISO-tech/sw-d8", "id": "2033c275c6cf7036d16a6f19f2211570c3400722", "size": "3164", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/2004-1/480/480_02_MorningAfter.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "30677" }, { "name": "Gherkin", "bytes": "3374" }, { "name": "HTML", "bytes": "269460" }, { "name": "Hack", "bytes": "35936" }, { "name": "JavaScript", "bytes": "104527" }, { "name": "PHP", "bytes": "53430607" }, { "name": "SCSS", "bytes": "50217" }, { "name": "Shell", "bytes": "8234" }, { "name": "Twig", "bytes": "57403" } ], "symlink_target": "" }
package at.ac.tuwien.ifs.tita.ui.uihelper; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.model.IModel; import org.wicketstuff.table.SelectableListItem; import org.wicketstuff.table.cell.CellEditor; import org.wicketstuff.table.cell.CellRender; /** * * Renders button delete. * * @author msiedler * */ public class ButtonEditRenderer implements CellRender, CellEditor { private IAdministrationPanel panel = null; public ButtonEditRenderer(IAdministrationPanel panel) { this.panel = panel; } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public Component getRenderComponent(String id, IModel model, SelectableListItem parent, int row, int column) { return new Label(id, model); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public Component getEditorComponent(String id, IModel model, SelectableListItem parent, int row, int column) { return new LenientAjaxButton(id) { @Override public void onSubmit(AjaxRequestTarget target, Form<?> form1) { panel.updateListEntity(target); } @Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); tag.put("class", "buttonEdit"); } }; } }
{ "content_hash": "f0560eb70cf077a4649bdb3ce6daaec1", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 75, "avg_line_length": 26.916666666666668, "alnum_prop": 0.6588235294117647, "repo_name": "tita/tita", "id": "f53b61797b5feaad81ed73afae21a9c7e7e77c68", "size": "2240", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tita-wicket/src/main/java/at/ac/tuwien/ifs/tita/ui/uihelper/ButtonEditRenderer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "902710" }, { "name": "JavaScript", "bytes": "9238" } ], "symlink_target": "" }
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 7, transform = "Integration", sigma = 0.0, exog_count = 20, ar_order = 0);
{ "content_hash": "31c7f817805b6676ad2072a1d8572905", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 167, "avg_line_length": 38.142857142857146, "alnum_prop": 0.7078651685393258, "repo_name": "antoinecarme/pyaf", "id": "5ad0610ddf64fa169b72fca40d6b2d057f2dec7a", "size": "267", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/artificial/transf_Integration/trend_PolyTrend/cycle_7/ar_/test_artificial_1024_Integration_PolyTrend_7__20.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Makefile", "bytes": "6773299" }, { "name": "Procfile", "bytes": "24" }, { "name": "Python", "bytes": "54209093" }, { "name": "R", "bytes": "807" }, { "name": "Shell", "bytes": "3619" } ], "symlink_target": "" }
<?php namespace Catalog\Controller; use Catalog\Form\FranchiseSearch; use Franchise\Model\Dao\FranchiseDao; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; class FranchiseController extends AbstractActionController { public function indexAction() { return new ViewModel(); } public function listAction() { $request = $this->getRequest(); $franchiseTableGateway = $this->getService('FranchiseTableGateway'); $franchiseDao = new FranchiseDao($franchiseTableGateway); $category = $this->getFranchiseCategorySelect(); $category[0] = 'Todas'; $franchiseAddForm = new FranchiseSearch(); $franchiseAddForm->get('category_id') ->setValueOptions($category) ->setValue(0); $franchies = $franchiseDao->getAll(); if ($request->isPost()) { $category_id = $request->getPost('category_id'); $name = $request->getPost('name'); if ($category_id > 0) { $franchies->where(array('category_id' => $category_id)); $franchiseAddForm->get('category_id')->setValue($category_id); }elseif($name){ $franchies->like('name', $name); } } $franchiesResult = $franchies->fetchAll(); //$franchies->count();die; $view['form'] = $franchiseAddForm; $view['franchieses'] = $franchiesResult; //print_r($franchiesResult);die; return new ViewModel($view); } private function getFranchiseCategorySelect() { $franchiseCategoryDao = $this->getService('FranchiseCategoryDao'); $results = $franchiseCategoryDao->getAllCategory(); $result = array(); foreach ($results as $bankR) { //$result[] = $row->getArrayCopy(); $result[$bankR->category_id] = $bankR->name; } return $result; } public function getService($serviceName) { $sm = $this->getServiceLocator(); $service = $sm->get($serviceName); return $service; } }
{ "content_hash": "1c81fbaa30e7a4b59b5afc1b096fbbff", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 78, "avg_line_length": 26.85185185185185, "alnum_prop": 0.5770114942528736, "repo_name": "oscar121/tesis", "id": "565b5e0249d726985db0492fbfd2f3909e752871", "size": "2175", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "module/Catalog/src/Catalog/Controller/FranchiseController.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "783" }, { "name": "CSS", "bytes": "1927890" }, { "name": "HTML", "bytes": "654850" }, { "name": "JavaScript", "bytes": "925820" }, { "name": "PHP", "bytes": "437749" } ], "symlink_target": "" }
import unittest from pyparsing import ParseException from tests.utils.grammar import get_record_grammar """ CWR Entire Work Title grammar tests. The following cases are tested: """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' class TestEntireWorkTitleGrammar(unittest.TestCase): def setUp(self): self.grammar = get_record_grammar('entire_work_title') def test_valid_full(self): record = 'EWT0000123400000023THE TITLE T0123456789ESLAST NAME 1 FIRST NAME 1 THE SOURCE 00014107338I-000000229-7LAST NAME 2 FIRST NAME 2 00014107339I-000000230-7ABCD0123456789' result = self.grammar.parseString(record)[0] self.assertEqual('EWT', result.record_type) self.assertEqual(1234, result.transaction_sequence_n) self.assertEqual(23, result.record_sequence_n) self.assertEqual('THE TITLE', result.title) self.assertEqual('T0123456789', result.iswc) self.assertEqual('ES', result.language_code) self.assertEqual('LAST NAME 1', result.writer_1_last_name) self.assertEqual('FIRST NAME 1', result.writer_1_first_name) self.assertEqual('THE SOURCE', result.source) self.assertEqual(14107338, result.writer_1_ipi_name_n) self.assertEqual('I-000000229-7', result.writer_1_ipi_base_n) self.assertEqual('LAST NAME 2', result.writer_2_last_name) self.assertEqual('FIRST NAME 2', result.writer_2_first_name) self.assertEqual(14107339, result.writer_2_ipi_name_n) self.assertEqual('I-000000230-7', result.writer_2_ipi_base_n) self.assertEqual('ABCD0123456789', result.submitter_work_n) class TestEntireWorkTitleGrammarException(unittest.TestCase): def setUp(self): self.grammar = get_record_grammar('entire_work_title') def test_empty(self): """ Tests that a exception is thrown when the the works number is zero. """ record = '' self.assertRaises(ParseException, self.grammar.parseString, record) def test_invalid(self): record = 'This is an invalid string' self.assertRaises(ParseException, self.grammar.parseString, record)
{ "content_hash": "5b685d5c5b0073d0e4aa35e1280b228e", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 383, "avg_line_length": 39.9, "alnum_prop": 0.6386800334168755, "repo_name": "weso/CWR-DataApi", "id": "c74d5b5bab19023c1698d711e77a2ae659c34ec6", "size": "2419", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/grammar/factory/record/test_entire_work_title.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "3830" }, { "name": "Makefile", "bytes": "2366" }, { "name": "Python", "bytes": "997385" } ], "symlink_target": "" }
package cmd import ( "fmt" "github.com/spf13/cobra" ) // versionCmd represents the version command var versionCmd = &cobra.Command{ Use: "version", Short: "Print version and exit", Run: func(cmd *cobra.Command, args []string) { fmt.Printf("%v built on %v\n", Version, BuildDate) }, } func init() { RootCmd.AddCommand(versionCmd) }
{ "content_hash": "9f9dd374e3d2d958f9656be6a846043a", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 52, "avg_line_length": 17.3, "alnum_prop": 0.6820809248554913, "repo_name": "turnerlabs/harbor-compose", "id": "407b22e15d089057dcc077de02fc45eabeb11f1d", "size": "346", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cmd/version.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "241" }, { "name": "Go", "bytes": "331648" }, { "name": "Shell", "bytes": "1066" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://www.netbeans.org/ns/project/1"> <type>org.netbeans.modules.php.project</type> <configuration> <data xmlns="http://www.netbeans.org/ns/php-project/1"> <name>DesafioMVC</name> </data> </configuration> </project>
{ "content_hash": "cf044b5e3cff3adac4ad13a365ff6f79", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 63, "avg_line_length": 35.666666666666664, "alnum_prop": 0.6074766355140186, "repo_name": "Reflej0/DesafioMVC", "id": "243aba75ae797f8f0e3377cd5363c856e6a07c36", "size": "321", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nbproject/project.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1073" }, { "name": "CSS", "bytes": "47780" }, { "name": "HTML", "bytes": "8476992" }, { "name": "JavaScript", "bytes": "60778" }, { "name": "PHP", "bytes": "1800474" } ], "symlink_target": "" }
<?php include('../Connections/db.php'); include("../classes/thumb.php"); $conn = @mysql_connect($hostname_db, $username_db, $password_db) or die ("Problemas na conexão."); $db = @mysql_select_db($database_db, $conn) or die ("Problemas na conexão"); $idusuario = base64_decode($_GET['iduser']); $idregistro = base64_decode($_GET['upload']); if(isset($_FILES['upl'])){ $errors= array(); $file_name = $_FILES['upl']['name']; $file_size =$_FILES['upl']['size']; $file_tmp =$_FILES['upl']['tmp_name']; $file_type=$_FILES['upl']['type']; $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION)); $extensions = array("ico"); if(in_array($file_ext,$extensions )=== false){ $errors[]="image extension not allowed, please choose a JPEG file."; } if($file_size > 2097152){ $errors[]='File size cannot exceed 2 MB'; } if(empty($errors)==true){ $ext = explode(".", $_FILES['Filedata']['name']); $targetFile = rand().".".$file_ext; $sql = mysql_query("UPDATE config SET favicon = '$targetFile' WHERE id = '$idregistro' "); move_uploaded_file($file_tmp,"../img/config/favicon/".$targetFile); //Thumbnail( "../img/config/".$targetFile, "../img/config/".$targetFile , 1024, 1024); echo '{"status":"success"}'; exit; }else{ print_r($errors); } } else{ $errors= array(); $errors[]="No image found"; print_r($errors); } ?>
{ "content_hash": "40714de0bca6ce503b59813d0fd15809", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 102, "avg_line_length": 35.69767441860465, "alnum_prop": 0.5517915309446254, "repo_name": "duarteleme/cms-duarteleme", "id": "c80b72ef8ed74e447d42dab9d718bcc5858aa2c4", "size": "1537", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "fonts/view/configfaviconUpload.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "354985" }, { "name": "HTML", "bytes": "1254395" }, { "name": "JavaScript", "bytes": "1933955" }, { "name": "PHP", "bytes": "1130301" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Windows.Forms; namespace App { public partial class ManageItems : Form { public bool Changed = false; private string WildItemCommon; private string WildItemUncommon; private string WildItemRare; private string Incense; public ManageItems(string c, string u, string r, string i) { InitializeComponent(); WildItemCommon = c; WildItemUncommon = u; WildItemRare = r; Incense = i; } private void ManageItems_Load(object sender, EventArgs e) { List<string> Items = Utilities.Helpers.GetAllItemConstantNames(); CommonItemInput.Items.AddRange(Items.ToArray()); UncommonItemInput.Items.AddRange(Items.ToArray()); RareItemInput.Items.AddRange(Items.ToArray()); IncenseInput.Items.AddRange(Items.ToArray()); CommonItemInput.Text = WildItemCommon; UncommonItemInput.Text = WildItemUncommon; RareItemInput.Text = WildItemRare; IncenseInput.Text = Incense; } private void SaveButton_Click(object sender, EventArgs e) { Changed = true; Close(); } } }
{ "content_hash": "efd629378a730de143c047002b086c57", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 77, "avg_line_length": 30.651162790697676, "alnum_prop": 0.6016691957511381, "repo_name": "akaDrimer/PBS-Editor", "id": "13daccd7cd9f82bd803f1be76c2d0ded9170f52d", "size": "1320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "App/Forms/PokemonEditorForms/ManageItems.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "116744" } ], "symlink_target": "" }
<%# Copyright 2013-2017 the original author or authors from the JHipster project. This file is part of the JHipster project, see http://www.jhipster.tech/ for more information. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -%> import { TestBed, async, tick, fakeAsync, inject } from '@angular/core/testing'; import { ActivatedRoute } from '@angular/router'; import { Observable } from 'rxjs/Rx'; import { <%=angularXAppName%>TestModule } from '../../../test.module'; import { MockActivatedRoute } from '../../../helpers/mock-route.service'; import { ActivateService } from '../../../../../../main/webapp/app/account/activate/activate.service'; import { ActivateComponent } from '../../../../../../main/webapp/app/account/activate/activate.component'; describe('Component Tests', () => { describe('ActivateComponent', () => { let comp: ActivateComponent; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [<%=angularXAppName%>TestModule], declarations: [ActivateComponent], providers: [ ActivateService, { provide: ActivatedRoute, useValue: new MockActivatedRoute({'key': 'ABC123'}) } ] }) .overrideTemplate(ActivateComponent, '') .compileComponents(); })); beforeEach(() => { const fixture = TestBed.createComponent(ActivateComponent); comp = fixture.componentInstance; }); it('calls activate.get with the key from params', inject([ActivateService], fakeAsync((service: ActivateService) => { spyOn(service, 'get').and.returnValue(Observable.of()); comp.ngOnInit(); tick(); expect(service.get).toHaveBeenCalledWith('ABC123'); }) ) ); it('should set set success to OK upon successful activation', inject([ActivateService], fakeAsync((service: ActivateService) => { spyOn(service, 'get').and.returnValue(Observable.of({})); comp.ngOnInit(); tick(); expect(comp.error).toBe(null); expect(comp.success).toEqual('OK'); }) ) ); it('should set set error to ERROR upon activation failure', inject([ActivateService], fakeAsync((service: ActivateService) => { spyOn(service, 'get').and.returnValue(Observable.throw('ERROR')); comp.ngOnInit(); tick(); expect(comp.error).toBe('ERROR'); expect(comp.success).toEqual(null); }) ) ); }); });
{ "content_hash": "0d909ee51f32db453295c66a0bf692e0", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 106, "avg_line_length": 35.822916666666664, "alnum_prop": 0.5591741785402733, "repo_name": "deepu105/generator-jhipster", "id": "822495e151808c4218605a408e0cbf84994bd5ca", "size": "3439", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "generators/client/templates/angular/src/test/javascript/spec/app/account/activate/_activate.component.spec.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5006" }, { "name": "CSS", "bytes": "87951" }, { "name": "Gherkin", "bytes": "179" }, { "name": "HTML", "bytes": "434215" }, { "name": "Java", "bytes": "1054668" }, { "name": "JavaScript", "bytes": "1322229" }, { "name": "Scala", "bytes": "7783" }, { "name": "Shell", "bytes": "32658" }, { "name": "TypeScript", "bytes": "550321" } ], "symlink_target": "" }
"""Config flow for HLK-SW16.""" import asyncio from hlk_sw16 import create_hlk_sw16_connection import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_HOST, CONF_PORT from homeassistant.core import HomeAssistant from .const import ( CONNECTION_TIMEOUT, DEFAULT_KEEP_ALIVE_INTERVAL, DEFAULT_PORT, DEFAULT_RECONNECT_INTERVAL, DOMAIN, ) from .errors import AlreadyConfigured, CannotConnect DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): str, vol.Optional(CONF_PORT, default=DEFAULT_PORT): vol.Coerce(int), } ) async def connect_client(hass, user_input): """Connect the HLK-SW16 client.""" client_aw = create_hlk_sw16_connection( host=user_input[CONF_HOST], port=user_input[CONF_PORT], loop=hass.loop, timeout=CONNECTION_TIMEOUT, reconnect_interval=DEFAULT_RECONNECT_INTERVAL, keep_alive_interval=DEFAULT_KEEP_ALIVE_INTERVAL, ) return await asyncio.wait_for(client_aw, timeout=CONNECTION_TIMEOUT) async def validate_input(hass: HomeAssistant, user_input): """Validate the user input allows us to connect.""" for entry in hass.config_entries.async_entries(DOMAIN): if ( entry.data[CONF_HOST] == user_input[CONF_HOST] and entry.data[CONF_PORT] == user_input[CONF_PORT] ): raise AlreadyConfigured try: client = await connect_client(hass, user_input) except asyncio.TimeoutError: raise CannotConnect try: def disconnect_callback(): if client.in_transaction: client.active_transaction.set_exception(CannotConnect) client.disconnect_callback = disconnect_callback await client.status() except CannotConnect: client.disconnect_callback = None client.stop() raise CannotConnect else: client.disconnect_callback = None client.stop() class SW16FlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle a HLK-SW16 config flow.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH async def async_step_import(self, user_input): """Handle import.""" return await self.async_step_user(user_input) async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: try: await validate_input(self.hass, user_input) address = f"{user_input[CONF_HOST]}:{user_input[CONF_PORT]}" return self.async_create_entry(title=address, data=user_input) except AlreadyConfigured: errors["base"] = "already_configured" except CannotConnect: errors["base"] = "cannot_connect" return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors )
{ "content_hash": "189b7c24790e4640de571b59cd587800", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 78, "avg_line_length": 30.96875, "alnum_prop": 0.6451395896400942, "repo_name": "titilambert/home-assistant", "id": "0a9ac79d1b701fc9f798fa7d1a158b1abd38d172", "size": "2973", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "homeassistant/components/hlk_sw16/config_flow.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1488" }, { "name": "Python", "bytes": "25849092" }, { "name": "Shell", "bytes": "4410" } ], "symlink_target": "" }
```toml [dependencies.spine_tiny] git = "http://github.com/tomaka/spine-rs" ``` ```rust extern crate spine; ``` Parses a Spine document and calculates what needs to be drawn. You can find an example [here](https://github.com/tafia/spine-render) ## Step 1: loading the document Call `skeleton::Skeleton::from_reader` to parse the content of a document. This function returns an `Err` if the document is not valid JSON or if something is not recognized in it. ```rust let file = File::open(&Path::new("skeleton.json")).unwrap(); let skeleton = spine::skeleton::Skeleton::from_reader(file).unwrap(); ``` ## Step 2: preparing for drawing You can retrieve the list of animations and skins provided a document: ```rust let skins = skeleton.get_skins_names(); let animations = skeleton.get_animations_names(); ``` You can also get a list of the names of all the sprites that can possibly be drawn by this Spine animation. ```rust let sprites = skeleton.get_attachments_names(); ``` Note that the names do not necessarily match file names. They are the same names that you have in the Spine editor. It is your job to turn these resource names into file names if necessary. ## Step 3: animating To run an animation, you first need to call `skeleton.get_animated_skin` to get a `SkinAnimation`. You then have 2 methods to get the sprites you need to draw: - directly call `animation.interpolate` for a given time - use a built-in `AnimationIter` iterator by calling `animation.run()` to run the animation with a constant period Both methods returns a `Sprites` iterator over the `Sprite`s do be drawn. ```rust let animation = skeleton.get_animated_skin("default", Some("walk")).unwrap(); // either use `interpolate` let sprites = animation.interpolate(0.3).unwrap(); // or use the iterator let sprites = animation .run(0.1) // iterator that interpolates sprites every 0.1s .nth(3); // get the 3rd item generated when time = 0.3 ``` The result contains an iterator over the sprites that need to be drawn with the `skeleton::SRT` (scale, rotate, translate)). The srt supposes that each sprite would cover the whole viewport (ie. drawn from `(-1, -1)` to `(1, 1)`). You can convert it to a premultiplied matrix using `srt.to_matrix3()` or `srt.to_matrix4` ; if you want to apply your own matrix `C` over the one returned `M`, you need to call `C * M`. ```rust for sprite in animation.interpolate(0.3).unwrap() { let texture = textures_list.get(&&*sprite.attachment).unwrap(); draw(texture, &sprite.srt, &sprite.color); } ```
{ "content_hash": "f313bb5b31f58c3b99a2a6d93a0c8a3b", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 98, "avg_line_length": 33.03846153846154, "alnum_prop": 0.7178890182382616, "repo_name": "tomaka/spine-rs", "id": "fa9ee8d6f3f2f57e0726070e883242248b06e56b", "size": "2586", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Rust", "bytes": "50544" } ], "symlink_target": "" }
package org.ethereum.db; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.Predicate; import org.ethereum.datasource.mapdb.MapDBFactory; import org.ethereum.util.FastByteComparisons; import org.mapdb.DB; import org.mapdb.Serializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import static org.ethereum.config.SystemProperties.CONFIG; /** * @author Mikhail Kalinin * @since 07.07.2015 */ public class HashStoreImpl implements HashStore { private static final Logger logger = LoggerFactory.getLogger("blockqueue"); private static final String STORE_NAME = "hashstore"; private MapDBFactory mapDBFactory; private DB db; private Map<Long, byte[]> hashes; private List<Long> index; private boolean initDone = false; private final ReentrantLock initLock = new ReentrantLock(); private final Condition init = initLock.newCondition(); @Override public void open() { new Thread(new Runnable() { @Override public void run() { initLock.lock(); try { db = mapDBFactory.createTransactionalDB(dbName()); hashes = db.hashMapCreate(STORE_NAME) .keySerializer(Serializer.LONG) .valueSerializer(Serializer.BYTE_ARRAY) .makeOrGet(); if(CONFIG.databaseReset()) { hashes.clear(); db.commit(); } index = new ArrayList<>(hashes.keySet()); sortIndex(); initDone = true; init.signalAll(); logger.info("Hash store loaded, size [{}]", size()); } finally { initLock.unlock(); } } }).start(); } private String dbName() { return String.format("%s/%s", STORE_NAME, STORE_NAME); } @Override public void close() { awaitInit(); db.close(); initDone = false; } @Override public void add(byte[] hash) { awaitInit(); addInner(false, hash); dbCommit("add"); } @Override public void addFirst(byte[] hash) { awaitInit(); addInner(true, hash); dbCommit("addFirst"); } @Override public void addBatch(Collection<byte[]> hashes) { awaitInit(); for (byte[] hash : hashes) { addInner(false, hash); } dbCommit("addBatch: " + hashes.size()); } @Override public void addFirstBatch(Collection<byte[]> hashes) { awaitInit(); for (byte[] hash : hashes) { addInner(true, hash); } dbCommit("addFirstBatch: " + hashes.size()); } private synchronized void addInner(boolean first, byte[] hash) { Long idx = createIndex(first); hashes.put(idx, hash); } @Override public byte[] peek() { awaitInit(); synchronized (this) { if(index.isEmpty()) { return null; } Long idx = index.get(0); return hashes.get(idx); } } @Override public byte[] poll() { awaitInit(); byte[] hash = pollInner(); dbCommit(); return hash; } @Override public List<byte[]> pollBatch(int qty) { awaitInit(); if(index.isEmpty()) { return Collections.emptyList(); } List<byte[]> hashes = new ArrayList<>(qty > size() ? qty : size()); while (hashes.size() < qty) { byte[] hash = pollInner(); if(hash == null) { break; } hashes.add(hash); } dbCommit("pollBatch: " + hashes.size()); return hashes; } private byte[] pollInner() { byte[] hash; synchronized (this) { if(index.isEmpty()) { return null; } Long idx = index.get(0); hash = hashes.get(idx); hashes.remove(idx); index.remove(0); } return hash; } @Override public boolean isEmpty() { awaitInit(); return index.isEmpty(); } @Override public Set<Long> getKeys() { awaitInit(); return hashes.keySet(); } @Override public int size() { awaitInit(); return index.size(); } @Override public void clear() { awaitInit(); synchronized (this) { index.clear(); hashes.clear(); } dbCommit(); } @Override public void removeAll(Collection<byte[]> removing) { awaitInit(); Set<Long> removed = new HashSet<>(); for(final Map.Entry<Long, byte[]> e : hashes.entrySet()) { byte[] hash = CollectionUtils.find(removing, new Predicate<byte[]>() { @Override public boolean evaluate(byte[] hash) { return FastByteComparisons.compareTo(hash, 0, 32, e.getValue(), 0, 32) == 0; } }); if(hash != null) { removed.add(e.getKey()); } } index.removeAll(removed); for(Long idx : removed) { hashes.remove(idx); } dbCommit(); } private void dbCommit() { dbCommit(""); } private void dbCommit(String info) { long s = System.currentTimeMillis(); db.commit(); logger.debug("HashStoreImpl: db.commit took " + (System.currentTimeMillis() - s) + " ms (" + info + ") " + Thread.currentThread().getName()); } private Long createIndex(boolean first) { Long idx; if(index.isEmpty()) { idx = 0L; index.add(idx); } else if(first) { idx = index.get(0) - 1; index.add(0, idx); } else { idx = index.get(index.size() - 1) + 1; index.add(idx); } return idx; } private void sortIndex() { Collections.sort(index); } public void setMapDBFactory(MapDBFactory mapDBFactory) { this.mapDBFactory = mapDBFactory; } private void awaitInit() { initLock.lock(); try { if(!initDone) { init.awaitUninterruptibly(); } } finally { initLock.unlock(); } } }
{ "content_hash": "04b4547f370258a748c77c60bf059bbe", "timestamp": "", "source": "github", "line_count": 265, "max_line_length": 149, "avg_line_length": 25.343396226415095, "alnum_prop": 0.5119118522930316, "repo_name": "caxqueiroz/ethereumj", "id": "a4743fa04c669567172db13919b6d332637c56ff", "size": "6716", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "ethereumj-core/src/main/java/org/ethereum/db/HashStoreImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1126" }, { "name": "Java", "bytes": "2014575" } ], "symlink_target": "" }
<?php namespace Com\DaufinBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class TypeValeurControllerTest extends WebTestCase { /* public function testCompleteScenario() { // Create a new client to browse the application $client = static::createClient(); // Create a new entry in the database $crawler = $client->request('GET', '/com_type_valeur/'); $this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /com_type_valeur/"); $crawler = $client->click($crawler->selectLink('Create a new entry')->link()); // Fill in the form and submit it $form = $crawler->selectButton('Create')->form(array( 'com_daufinbundle_typevaleur[field_name]' => 'Test', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check data in the show view $this->assertGreaterThan(0, $crawler->filter('td:contains("Test")')->count(), 'Missing element td:contains("Test")'); // Edit the entity $crawler = $client->click($crawler->selectLink('Edit')->link()); $form = $crawler->selectButton('Update')->form(array( 'com_daufinbundle_typevaleur[field_name]' => 'Foo', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check the element contains an attribute with value equals "Foo" $this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]'); // Delete the entity $client->submit($crawler->selectButton('Delete')->form()); $crawler = $client->followRedirect(); // Check the entity has been delete on the list $this->assertNotRegExp('/Foo/', $client->getResponse()->getContent()); } */ }
{ "content_hash": "32b349a2731c50dd0dc7a1c681a82aa9", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 131, "avg_line_length": 35.61818181818182, "alnum_prop": 0.6054109239407861, "repo_name": "zi9o/Daufin2", "id": "13ffe1c027d0c6352e728b7d15c0b683359634be", "size": "1959", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Com/DaufinBundle/Tests/Controller/TypeValeurControllerTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3433" }, { "name": "Batchfile", "bytes": "299" }, { "name": "CSS", "bytes": "486890" }, { "name": "HTML", "bytes": "694233" }, { "name": "JavaScript", "bytes": "570748" }, { "name": "PHP", "bytes": "1027182" }, { "name": "Shell", "bytes": "166" } ], "symlink_target": "" }
// // Copyright 2013-2014 Yummy Melon Software LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: Charles Y. Choi <charles.choi@yummymelon.com> // #import "DEABaseService.h" /** TI SensorTag CoreBluetooth service definition for thermometer. */ @interface DEATemperatureService : DEABaseService /** Inherited property of DEABaseService. Keys: @"ambientTemp", @"objectTemp". */ @property (nonatomic, strong, readonly) NSDictionary *sensorValues; /// Ambient temperature @property (nonatomic, strong, readonly) NSNumber *ambientTemp; /// Object temperature @property (nonatomic, strong, readonly) NSNumber *objectTemp; @end
{ "content_hash": "dbbab84ced0bc9a8edf588ba1ea8d9bc", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 75, "avg_line_length": 30.394736842105264, "alnum_prop": 0.7497835497835498, "repo_name": "flit/sensor-midi", "id": "f2133ad10f64e92a24bea2ccb0cbe0481f5f5564", "size": "1155", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Services/SensorTag/Services/DEATemperatureService.h", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "6714" }, { "name": "C++", "bytes": "376" }, { "name": "Objective-C", "bytes": "434243" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Am. J. Bot. , Suppl. 56(10): 1198 (1969) #### Original name Ascobolus testaceus var. difformis P. Karst. ### Remarks null
{ "content_hash": "cec65b4a992ea394eeb1359909bd7663", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 44, "avg_line_length": 14.23076923076923, "alnum_prop": 0.6756756756756757, "repo_name": "mdoering/backbone", "id": "26ceec2b872743a172bac310937ef60b71408035", "size": "267", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Pezizomycetes/Pezizales/Pezizaceae/Iodophanus/Iodophanus difformis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import re from docutils import nodes from pygments.lexers import guess_lexer, Python3Lexer, PythonLexer from sphinx.transforms import SphinxTransform from sphinx.transforms.post_transforms.code import TrimDoctestFlagsTransform docmark_re = re.compile(r"\s*#\s*\[(START|END)\s*[a-z_A-Z]+\].*$", re.MULTILINE) class TrimDocMarkerFlagsTransform(SphinxTransform): """ Trim doc marker like ``# [START howto_concept]` from python code-blocks. Based on: https://github.com/sphinx-doc/sphinx/blob/master/sphinx/transforms/post_transforms/code.py class TrimDoctestFlagsTransform """ default_priority = TrimDoctestFlagsTransform.default_priority + 1 def apply(self, **kwargs): for node in self.document.traverse(nodes.literal_block): if self.is_pycode(node): source = node.rawsource source = docmark_re.sub("", source) node.rawsource = source node[:] = [nodes.Text(source)] @staticmethod def is_pycode(node): # type: (nodes.literal_block) -> bool if node.rawsource != node.astext(): return False # skip parsed-literal node language = node.get("language") if language in ("py", "py3", "python", "python3", "default"): return True elif language == "guess": try: lexer = guess_lexer(node.rawsource) return isinstance(lexer, PythonLexer) or isinstance(lexer, Python3Lexer) except Exception: pass return False def setup(app): app.add_post_transform(TrimDocMarkerFlagsTransform) return {"version": "builtin", "parallel_read_safe": False, "parallel_write_safe": False}
{ "content_hash": "a902997d9e47c63e3d79f2843e49b5b2", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 94, "avg_line_length": 33.5, "alnum_prop": 0.6389207807118255, "repo_name": "r39132/airflow", "id": "01ec440d0e11242c6ecf464df7a4326df711d73c", "size": "2622", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/exts/removemarktransform.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "12126" }, { "name": "Dockerfile", "bytes": "4111" }, { "name": "HTML", "bytes": "128531" }, { "name": "JavaScript", "bytes": "22118" }, { "name": "Mako", "bytes": "1284" }, { "name": "Python", "bytes": "5928206" }, { "name": "Shell", "bytes": "41869" } ], "symlink_target": "" }
<?php /** * Created by PhpStorm. * User: Nadin Yamaui * Date: 10/30/2016 * Time: 5:02 PM */ namespace CaagSoftware\SimpleIntegration\Drivers\Git\Extensions; use Illuminate\Support\Collection; class Commits extends Collection { public function branch($name) { return $this->filter(function (Commit $commit) use ($name) { return $commit->branch == $name; }); } }
{ "content_hash": "0f97d316a59aa479db28d11f54993b8b", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 68, "avg_line_length": 19.428571428571427, "alnum_prop": 0.6421568627450981, "repo_name": "caagsoftware/simple-integration", "id": "f015484c83da62057d5623a78ff91ed6b0b4c839", "size": "408", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Drivers/Git/Extensions/Commits.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "21399" } ], "symlink_target": "" }
"use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const HTMLConstructor_helpers_html_constructor = require("../helpers/html-constructor.js").HTMLConstructor; const implSymbol = utils.implSymbol; const ctorRegistrySymbol = utils.ctorRegistrySymbol; const HTMLElement = require("./HTMLElement.js"); const interfaceName = "HTMLSpanElement"; exports.is = value => { return utils.isObject(value) && utils.hasOwn(value, implSymbol) && value[implSymbol] instanceof Impl.implementation; }; exports.isImpl = value => { return utils.isObject(value) && value instanceof Impl.implementation; }; exports.convert = (value, { context = "The provided value" } = {}) => { if (exports.is(value)) { return utils.implForWrapper(value); } throw new TypeError(`${context} is not of type 'HTMLSpanElement'.`); }; function makeWrapper(globalObject) { if (globalObject[ctorRegistrySymbol] === undefined) { throw new Error("Internal error: invalid global object"); } const ctor = globalObject[ctorRegistrySymbol]["HTMLSpanElement"]; if (ctor === undefined) { throw new Error("Internal error: constructor HTMLSpanElement is not installed on the passed global object"); } return Object.create(ctor.prototype); } exports.create = (globalObject, constructorArgs, privateData) => { const wrapper = makeWrapper(globalObject); return exports.setup(wrapper, globalObject, constructorArgs, privateData); }; exports.createImpl = (globalObject, constructorArgs, privateData) => { const wrapper = exports.create(globalObject, constructorArgs, privateData); return utils.implForWrapper(wrapper); }; exports._internalSetup = (wrapper, globalObject) => { HTMLElement._internalSetup(wrapper, globalObject); }; exports.setup = (wrapper, globalObject, constructorArgs = [], privateData = {}) => { privateData.wrapper = wrapper; exports._internalSetup(wrapper, globalObject); Object.defineProperty(wrapper, implSymbol, { value: new Impl.implementation(globalObject, constructorArgs, privateData), configurable: true }); wrapper[implSymbol][utils.wrapperSymbol] = wrapper; if (Impl.init) { Impl.init(wrapper[implSymbol]); } return wrapper; }; exports.new = globalObject => { const wrapper = makeWrapper(globalObject); exports._internalSetup(wrapper, globalObject); Object.defineProperty(wrapper, implSymbol, { value: Object.create(Impl.implementation.prototype), configurable: true }); wrapper[implSymbol][utils.wrapperSymbol] = wrapper; if (Impl.init) { Impl.init(wrapper[implSymbol]); } return wrapper[implSymbol]; }; const exposed = new Set(["Window"]); exports.install = (globalObject, globalNames) => { if (!globalNames.some(globalName => exposed.has(globalName))) { return; } if (globalObject.HTMLElement === undefined) { throw new Error("Internal error: attempting to evaluate HTMLSpanElement before HTMLElement"); } class HTMLSpanElement extends globalObject.HTMLElement { constructor() { return HTMLConstructor_helpers_html_constructor(globalObject, interfaceName, new.target); } } Object.defineProperties(HTMLSpanElement.prototype, { [Symbol.toStringTag]: { value: "HTMLSpanElement", configurable: true } }); if (globalObject[ctorRegistrySymbol] === undefined) { globalObject[ctorRegistrySymbol] = Object.create(null); } globalObject[ctorRegistrySymbol][interfaceName] = HTMLSpanElement; Object.defineProperty(globalObject, interfaceName, { configurable: true, writable: true, value: HTMLSpanElement }); }; const Impl = require("../nodes/HTMLSpanElement-impl.js");
{ "content_hash": "5e2d9c945a06d96fe2356ae9d35849cd", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 118, "avg_line_length": 31.91304347826087, "alnum_prop": 0.7294277929155313, "repo_name": "thomasoboyle/Exercism", "id": "fd8028d2efa05f5bae852e700c775838a8e79a4c", "size": "3670", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "typescript/hello-world/node_modules/jsdom/lib/jsdom/living/generated/HTMLSpanElement.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "781" }, { "name": "Ruby", "bytes": "96197" }, { "name": "TypeScript", "bytes": "218" } ], "symlink_target": "" }
package de.starwit.application; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Main SpringApplication to start the whole project */ @SpringBootApplication(scanBasePackages = { "de.starwit.rest", "de.starwit.service", "de.starwit.persistence", "de.starwit.generator.services","de.starwit.generator.mapper", "de.starwit.application.config"}) public class Application { public static void main(String[] args) { SpringApplication.run(new Class[] { Application.class }, args); } }
{ "content_hash": "c7bbb13cf1733a267acc14471e54559c", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 110, "avg_line_length": 36.5, "alnum_prop": 0.7517123287671232, "repo_name": "witchpou/lj-projectbuilder", "id": "747e9c139f1bc81a517cbdc69286d26b894c9468", "size": "584", "binary": false, "copies": "1", "ref": "refs/heads/feature/ab#245-add-new-fieldTypes", "path": "application/src/main/java/de/starwit/application/Application.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "21437" }, { "name": "Dockerfile", "bytes": "694" }, { "name": "FreeMarker", "bytes": "25356" }, { "name": "HTML", "bytes": "35625" }, { "name": "Java", "bytes": "109972" }, { "name": "JavaScript", "bytes": "50497" }, { "name": "PLSQL", "bytes": "69" }, { "name": "TSQL", "bytes": "27850" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/text_select" android:state_pressed="true" /> <item android:color="@color/text_select" android:state_selected="true" /> <item android:color="@color/text_topbar" /> </selector>
{ "content_hash": "124bc3963acfa8b084dae7dc2c823933", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 77, "avg_line_length": 53.833333333333336, "alnum_prop": 0.6996904024767802, "repo_name": "SYJack/MusicAndChat", "id": "c2397d6edd7cf28a45277ea8a719c64b1a6de5e7", "size": "323", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/drawable/drawer_dialog_text.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "15822" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2013 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:clipToPadding="false" android:scrollbarStyle="@integer/preference_scrollbar_style"> <LinearLayout android:id="@+id/all_details" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingTop="5dip" android:paddingBottom="5dip" android:orientation="vertical" android:paddingStart="?android:attr/listPreferredItemPaddingStart" android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"> <include layout="@layout/app_percentage_item" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- Force stop and report buttons --> <LinearLayout android:id="@+id/two_buttons_panel" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingBottom="6dip" android:orientation="vertical"> <include layout="@layout/two_buttons_panel"/> </LinearLayout> <TextView style="?android:attr/listSeparatorTextViewStyle" android:text="@string/details_subtitle" /> <LinearLayout android:id="@+id/details" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- Insert detail items here --> </LinearLayout> <TextView style="?android:attr/listSeparatorTextViewStyle" android:text="@string/services_subtitle" /> <LinearLayout android:id="@+id/services" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- Insert service items here --> </LinearLayout> </LinearLayout> </LinearLayout> </ScrollView>
{ "content_hash": "746ff8b2d51e43ccf8dbd1276fc4eb08", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 77, "avg_line_length": 35.86904761904762, "alnum_prop": 0.5967474278128112, "repo_name": "manuelmagix/android_packages_apps_Settings", "id": "fac9e9769f331c9c68c01e7965c7181779cdd562", "size": "3013", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "res/layout/process_stats_details.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "6041065" }, { "name": "Makefile", "bytes": "3909" } ], "symlink_target": "" }
 #include <aws/mobile/model/DescribeBundleResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Mobile::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; DescribeBundleResult::DescribeBundleResult() { } DescribeBundleResult::DescribeBundleResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } DescribeBundleResult& DescribeBundleResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("details")) { m_details = jsonValue.GetObject("details"); } return *this; }
{ "content_hash": "3524dd9633b2a83d06465a9bc3c564d6", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 108, "avg_line_length": 22.243243243243242, "alnum_prop": 0.764277035236938, "repo_name": "JoyIfBam5/aws-sdk-cpp", "id": "ff955511d935e4318107d79447e1e679dfd18bc0", "size": "1396", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-mobile/source/model/DescribeBundleResult.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "11868" }, { "name": "C++", "bytes": "167818064" }, { "name": "CMake", "bytes": "591577" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "271801" }, { "name": "Python", "bytes": "85650" }, { "name": "Shell", "bytes": "5277" } ], "symlink_target": "" }
package e2e_federation import ( "fmt" "time" "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/rand" "k8s.io/apimachinery/pkg/util/wait" kubeclientset "k8s.io/client-go/kubernetes" federationapi "k8s.io/kubernetes/federation/apis/federation/v1beta1" fedclientset "k8s.io/kubernetes/federation/client/clientset_generated/federation_clientset" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/test/e2e/common" "k8s.io/kubernetes/test/e2e/framework" fedframework "k8s.io/kubernetes/test/e2e_federation/framework" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var ( DefaultFederationName = "e2e-federation" // We use this to decide how long to wait for our DNS probes to succeed. DNSTTL = 180 * time.Second // TODO: make k8s.io/kubernetes/federation/pkg/federation-controller/service.minDnsTtl exported, and import it here. ) const ( // [30000, 32767] is the allowed default service nodeport range and our // tests just use the defaults. FederatedSvcNodePortFirst = 30000 FederatedSvcNodePortLast = 32767 ) var FederationSuite common.Suite func createClusterObjectOrFail(f *fedframework.Framework, context *fedframework.E2EContext, clusterNamePrefix string) { clusterName := clusterNamePrefix + context.Name framework.Logf("Creating cluster object: %s (%s, secret: %s)", clusterName, context.Cluster.Cluster.Server, context.Name) cluster := federationapi.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: clusterName, }, Spec: federationapi.ClusterSpec{ ServerAddressByClientCIDRs: []federationapi.ServerAddressByClientCIDR{ { ClientCIDR: "0.0.0.0/0", ServerAddress: context.Cluster.Cluster.Server, }, }, SecretRef: &v1.LocalObjectReference{ // Note: Name must correlate with federation build script secret name, // which currently matches the cluster name. // See federation/cluster/common.sh:132 Name: context.Name, }, }, } if clusterNamePrefix != "" { cluster.Labels = map[string]string{"prefix": clusterNamePrefix} } _, err := f.FederationClientset.Federation().Clusters().Create(&cluster) framework.ExpectNoError(err, fmt.Sprintf("creating cluster: %+v", err)) framework.Logf("Successfully created cluster object: %s (%s, secret: %s)", clusterName, context.Cluster.Cluster.Server, context.Name) } // waitForServiceOrFail waits until a service is either present or absent in the cluster specified by clientset. // If the condition is not met within timout, it fails the calling test. func waitForServiceOrFail(clientset *kubeclientset.Clientset, namespace string, service *v1.Service, present bool, timeout time.Duration) { By(fmt.Sprintf("Fetching a federated service shard of service %q in namespace %q from cluster", service.Name, namespace)) err := wait.PollImmediate(framework.Poll, timeout, func() (bool, error) { clusterService, err := clientset.CoreV1().Services(namespace).Get(service.Name, metav1.GetOptions{}) if (!present) && errors.IsNotFound(err) { // We want it gone, and it's gone. By(fmt.Sprintf("Success: shard of federated service %q in namespace %q in cluster is absent", service.Name, namespace)) return true, nil // Success } if present && err == nil { // We want it present, and the Get succeeded, so we're all good. if equivalent(*clusterService, *service) { By(fmt.Sprintf("Success: shard of federated service %q in namespace %q in cluster is present", service.Name, namespace)) return true, nil // Success } return false, nil } By(fmt.Sprintf("Service %q in namespace %q in cluster. Found: %v, waiting for Found: %v, trying again in %s (err=%v)", service.Name, namespace, clusterService != nil && err == nil, present, framework.Poll, err)) return false, nil }) framework.ExpectNoError(err, "Failed to verify service %q in namespace %q in cluster: Present=%v", service.Name, namespace, present) } // waitForServiceShardsOrFail waits for the service to appear in all clusters func waitForServiceShardsOrFail(namespace string, service *v1.Service, clusters fedframework.ClusterSlice) { framework.Logf("Waiting for service %q in %d clusters", service.Name, len(clusters)) for _, c := range clusters { waitForServiceOrFail(c.Clientset, namespace, service, true, fedframework.FederatedDefaultTestTimeout) } } func createService(clientset *fedclientset.Clientset, namespace, name string) (*v1.Service, error) { if clientset == nil || len(namespace) == 0 { return nil, fmt.Errorf("Internal error: invalid parameters passed to createService: clientset: %v, namespace: %v", clientset, namespace) } By(fmt.Sprintf("Creating federated service %q in namespace %q", name, namespace)) service := &v1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: namespace, }, Spec: v1.ServiceSpec{ Selector: FederatedServiceLabels, Type: v1.ServiceTypeClusterIP, Ports: []v1.ServicePort{ { Name: "http", Protocol: v1.ProtocolTCP, Port: 80, TargetPort: intstr.FromInt(8080), }, }, SessionAffinity: v1.ServiceAffinityNone, }, } By(fmt.Sprintf("Trying to create service %q in namespace %q", service.Name, namespace)) return clientset.CoreV1().Services(namespace).Create(service) } func createLBService(clientset *fedclientset.Clientset, namespace, name string) (*v1.Service, error) { if clientset == nil || len(namespace) == 0 { return nil, fmt.Errorf("Internal error: invalid parameters passed to createService: clientset: %v, namespace: %v", clientset, namespace) } By(fmt.Sprintf("Creating federated service (type: load balancer) %q in namespace %q", name, namespace)) // Tests can be run in parallel, so we need a different nodePort for // each test. // We add 1 to FederatedSvcNodePortLast because IntnRange's range end // is not inclusive. nodePort := int32(rand.IntnRange(FederatedSvcNodePortFirst, FederatedSvcNodePortLast+1)) service := &v1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: namespace, }, Spec: v1.ServiceSpec{ Selector: FederatedServiceLabels, Type: v1.ServiceTypeLoadBalancer, Ports: []v1.ServicePort{ { Name: "http", Protocol: v1.ProtocolTCP, Port: 80, TargetPort: intstr.FromInt(8080), NodePort: nodePort, }, }, SessionAffinity: v1.ServiceAffinityNone, }, } By(fmt.Sprintf("Trying to create service %q in namespace %q", service.Name, namespace)) return clientset.CoreV1().Services(namespace).Create(service) } func createServiceOrFail(clientset *fedclientset.Clientset, namespace, name string) *v1.Service { service, err := createService(clientset, namespace, name) framework.ExpectNoError(err, "Creating service %q in namespace %q", service.Name, namespace) By(fmt.Sprintf("Successfully created federated service %q in namespace %q", name, namespace)) return service } func createLBServiceOrFail(clientset *fedclientset.Clientset, namespace, name string) *v1.Service { service, err := createLBService(clientset, namespace, name) framework.ExpectNoError(err, "Creating service %q in namespace %q", service.Name, namespace) By(fmt.Sprintf("Successfully created federated service (type: load balancer) %q in namespace %q", name, namespace)) return service } func deleteServiceOrFail(clientset *fedclientset.Clientset, namespace string, serviceName string, orphanDependents *bool) { if clientset == nil || len(namespace) == 0 || len(serviceName) == 0 { Fail(fmt.Sprintf("Internal error: invalid parameters passed to deleteServiceOrFail: clientset: %v, namespace: %v, service: %v", clientset, namespace, serviceName)) } framework.Logf("Deleting service %q in namespace %v", serviceName, namespace) err := clientset.CoreV1().Services(namespace).Delete(serviceName, &metav1.DeleteOptions{OrphanDependents: orphanDependents}) framework.ExpectNoError(err, "Error deleting service %q from namespace %q", serviceName, namespace) // Wait for the service to be deleted. err = wait.Poll(5*time.Second, fedframework.FederatedDefaultTestTimeout, func() (bool, error) { _, err := clientset.Core().Services(namespace).Get(serviceName, metav1.GetOptions{}) if err != nil && errors.IsNotFound(err) { return true, nil } return false, err }) if err != nil { framework.DescribeSvc(namespace) framework.Failf("Error in deleting service %s: %v", serviceName, err) } } func cleanupServiceShardsAndProviderResources(namespace string, service *v1.Service, clusters fedframework.ClusterSlice) { framework.Logf("Deleting service %q in %d clusters", service.Name, len(clusters)) for _, c := range clusters { name := c.Name var cSvc *v1.Service err := wait.PollImmediate(framework.Poll, fedframework.FederatedDefaultTestTimeout, func() (bool, error) { var err error cSvc, err = c.Clientset.CoreV1().Services(namespace).Get(service.Name, metav1.GetOptions{}) if err != nil && !errors.IsNotFound(err) { // Get failed with an error, try again. framework.Logf("Failed to find service %q in namespace %q, in cluster %q: %v. Trying again in %s", service.Name, namespace, name, err, framework.Poll) return false, nil } else if errors.IsNotFound(err) { cSvc = nil By(fmt.Sprintf("Service %q in namespace %q in cluster %q not found", service.Name, namespace, name)) return true, err } By(fmt.Sprintf("Service %q in namespace %q in cluster %q found", service.Name, namespace, name)) return true, err }) if err != nil || cSvc == nil { By(fmt.Sprintf("Failed to find service %q in namespace %q, in cluster %q in %s", service.Name, namespace, name, fedframework.FederatedDefaultTestTimeout)) continue } if cSvc.Spec.Type == v1.ServiceTypeLoadBalancer { // In federation tests, e2e zone names are used to derive federation member cluster names zone := fedframework.GetZoneFromClusterName(name) serviceLBName := cloudprovider.GetLoadBalancerName(cSvc) framework.Logf("cleaning cloud provider resource for service %q in namespace %q, in cluster %q", service.Name, namespace, name) framework.CleanupServiceResources(c.Clientset, serviceLBName, zone) } err = cleanupServiceShard(c.Clientset, name, namespace, cSvc, fedframework.FederatedDefaultTestTimeout) if err != nil { framework.Logf("Failed to delete service %q in namespace %q, in cluster %q: %v", service.Name, namespace, name, err) } } } func cleanupServiceShard(clientset *kubeclientset.Clientset, clusterName, namespace string, service *v1.Service, timeout time.Duration) error { err := wait.PollImmediate(framework.Poll, timeout, func() (bool, error) { err := clientset.CoreV1().Services(namespace).Delete(service.Name, &metav1.DeleteOptions{}) if err != nil && !errors.IsNotFound(err) { // Deletion failed with an error, try again. framework.Logf("Failed to delete service %q in namespace %q, in cluster %q", service.Name, namespace, clusterName) return false, nil } By(fmt.Sprintf("Service %q in namespace %q in cluster %q deleted", service.Name, namespace, clusterName)) return true, nil }) return err } func podExitCodeDetector(f *fedframework.Framework, name, namespace string, code int32) func() error { // If we ever get any container logs, stash them here. logs := "" logerr := func(err error) error { if err == nil { return nil } if logs == "" { return err } return fmt.Errorf("%s (%v)", logs, err) } return func() error { pod, err := f.ClientSet.Core().Pods(namespace).Get(name, metav1.GetOptions{}) if err != nil { return logerr(err) } if len(pod.Status.ContainerStatuses) < 1 { return logerr(fmt.Errorf("no container statuses")) } // Best effort attempt to grab pod logs for debugging logs, err = framework.GetPodLogs(f.ClientSet, namespace, name, pod.Spec.Containers[0].Name) if err != nil { framework.Logf("Cannot fetch pod logs: %v", err) } status := pod.Status.ContainerStatuses[0] if status.State.Terminated == nil { return logerr(fmt.Errorf("container is not in terminated state")) } if status.State.Terminated.ExitCode == code { return nil } return logerr(fmt.Errorf("exited %d", status.State.Terminated.ExitCode)) } } func discoverService(f *fedframework.Framework, name string, exists bool, podName string) { command := []string{"sh", "-c", fmt.Sprintf("until nslookup '%s'; do sleep 10; done", name)} By(fmt.Sprintf("Looking up %q", name)) pod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: podName, }, Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: "federated-service-discovery-container", Image: "gcr.io/google_containers/busybox:1.24", Command: command, }, }, RestartPolicy: v1.RestartPolicyOnFailure, }, } nsName := f.FederationNamespace.Name By(fmt.Sprintf("Creating pod %q in namespace %q", pod.Name, nsName)) _, err := f.ClientSet.Core().Pods(nsName).Create(pod) framework.ExpectNoError(err, "Trying to create pod to run %q", command) By(fmt.Sprintf("Successfully created pod %q in namespace %q", pod.Name, nsName)) defer func() { By(fmt.Sprintf("Deleting pod %q from namespace %q", podName, nsName)) err := f.ClientSet.Core().Pods(nsName).Delete(podName, metav1.NewDeleteOptions(0)) framework.ExpectNoError(err, "Deleting pod %q from namespace %q", podName, nsName) By(fmt.Sprintf("Deleted pod %q from namespace %q", podName, nsName)) }() if exists { // TODO(mml): Eventually check the IP address is correct, too. Eventually(podExitCodeDetector(f, podName, nsName, 0), 3*DNSTTL, time.Second*2). Should(BeNil(), "%q should exit 0, but it never did", command) } else { Eventually(podExitCodeDetector(f, podName, nsName, 0), 3*DNSTTL, time.Second*2). ShouldNot(BeNil(), "%q should eventually not exit 0, but it always did", command) } } // BackendPodMap maps a cluster name to a backend pod created in that cluster type BackendPodMap map[string]*v1.Pod // createBackendPodsOrFail creates one pod in each cluster, and returns the created pods. If creation of any pod fails, // the test fails (possibly with a partially created set of pods). No retries are attempted. func createBackendPodsOrFail(clusters fedframework.ClusterSlice, namespace string, name string) BackendPodMap { pod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: name, // Namespace: namespace, Labels: FederatedServiceLabels, }, Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: name, Image: "gcr.io/google_containers/echoserver:1.6", }, }, RestartPolicy: v1.RestartPolicyAlways, }, } podMap := make(BackendPodMap) for _, c := range clusters { name := c.Name By(fmt.Sprintf("Creating pod %q in namespace %q in cluster %q", pod.Name, namespace, name)) createdPod, err := c.Clientset.CoreV1().Pods(namespace).Create(pod) framework.ExpectNoError(err, "Creating pod %q in namespace %q in cluster %q", name, namespace, name) By(fmt.Sprintf("Successfully created pod %q in namespace %q in cluster %q: %v", pod.Name, namespace, name, *createdPod)) podMap[name] = createdPod } return podMap } // deleteOneBackendPodOrFail deletes exactly one backend pod which must not be nil // The test fails if there are any errors. func deleteOneBackendPodOrFail(c *fedframework.Cluster, pod *v1.Pod) { Expect(pod).ToNot(BeNil()) err := c.Clientset.CoreV1().Pods(pod.Namespace).Delete(pod.Name, metav1.NewDeleteOptions(0)) msgFmt := fmt.Sprintf("Deleting Pod %q in namespace %q in cluster %q %%v", pod.Name, pod.Namespace, c.Name) if errors.IsNotFound(err) { framework.Logf(msgFmt, "does not exist. No need to delete it.") return } framework.ExpectNoError(err, msgFmt, "") framework.Logf(msgFmt, "was deleted") } // deleteBackendPodsOrFail deletes one pod from each cluster that has one. // If deletion of any pod fails, the test fails (possibly with a partially deleted set of pods). No retries are attempted. func deleteBackendPodsOrFail(clusters fedframework.ClusterSlice, backendPods BackendPodMap) { if backendPods == nil { return } for _, c := range clusters { if pod, ok := backendPods[c.Name]; ok { deleteOneBackendPodOrFail(c, pod) } else { By(fmt.Sprintf("No backend pod to delete for cluster %q", c.Name)) } } } // waitForReplicatSetToBeDeletedOrFail waits for the named ReplicaSet in namespace to be deleted. // If the deletion fails, the enclosing test fails. func waitForReplicaSetToBeDeletedOrFail(clientset *fedclientset.Clientset, namespace string, replicaSet string) { err := wait.Poll(5*time.Second, fedframework.FederatedDefaultTestTimeout, func() (bool, error) { _, err := clientset.Extensions().ReplicaSets(namespace).Get(replicaSet, metav1.GetOptions{}) if err != nil && errors.IsNotFound(err) { return true, nil } return false, err }) if err != nil { framework.Failf("Error in deleting replica set %s: %v", replicaSet, err) } }
{ "content_hash": "f736ce00af42945744372a0cd88d07fc", "timestamp": "", "source": "github", "line_count": 421, "max_line_length": 214, "avg_line_length": 40.465558194774346, "alnum_prop": 0.7220004695938014, "repo_name": "kad/kubernetes", "id": "0ddf52c0da59f534bac9dc542e75f7bef7cd20f5", "size": "17605", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/e2e_federation/util.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3293" }, { "name": "Go", "bytes": "43882430" }, { "name": "HTML", "bytes": "2714292" }, { "name": "Makefile", "bytes": "74292" }, { "name": "Nginx", "bytes": "595" }, { "name": "PowerShell", "bytes": "4261" }, { "name": "Protocol Buffer", "bytes": "505485" }, { "name": "Python", "bytes": "2337748" }, { "name": "Ruby", "bytes": "1591" }, { "name": "SaltStack", "bytes": "52331" }, { "name": "Shell", "bytes": "1595474" } ], "symlink_target": "" }
import {Component, Input, OnInit} from "@angular/core"; import {TestWithResults} from "./test-with-results"; import {StacktraceComponent} from "./stacktrace/stacktrace.component"; import {RouteParams, ROUTER_DIRECTIVES} from "@angular/router-deprecated"; import {TestResultService} from "./test-result.service"; import {TestResult} from "./test-result"; import {FailureReason} from "./failure-reason"; import {DurationComponent} from "../duration/duration.component"; @Component({ selector: 'test-results', templateUrl: 'app/test-result/test-results.html', styleUrls: ['app/test-result/test-results.css'], directives: [StacktraceComponent, ROUTER_DIRECTIVES, DurationComponent] }) export class TestResultsComponent implements OnInit { @Input() results: TestWithResults[]; testSuiteId: string; constructor( private _testResultService: TestResultService, private _routeParams: RouteParams) { } ngOnInit():any { this.testSuiteId = this._routeParams.get('testsuite_id'); } updateFailureReason(result: TestResult, failureReason: string) { result.failureReason = failureReason; this._testResultService.updateFailureReason(result); } failureReasons(): FailureReason[] { return FailureReason.all() } encode(input:string) { return encodeURIComponent(input) } }
{ "content_hash": "1a4356ad28c4a1d2bdd3afe7129a369f", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 75, "avg_line_length": 33.51219512195122, "alnum_prop": 0.7132459970887919, "repo_name": "ybonjour/test-store", "id": "1ca24dcb35b052ff2a819214a432d6d6fae3e6e0", "size": "1374", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/www/app/test-result/test-results.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "20369" }, { "name": "Dockerfile", "bytes": "1378" }, { "name": "Groovy", "bytes": "34822" }, { "name": "HTML", "bytes": "32605" }, { "name": "Java", "bytes": "32625" }, { "name": "JavaScript", "bytes": "6013" }, { "name": "Kotlin", "bytes": "173307" }, { "name": "Python", "bytes": "5893" }, { "name": "Ruby", "bytes": "3370" }, { "name": "Shell", "bytes": "4145" }, { "name": "TypeScript", "bytes": "105223" } ], "symlink_target": "" }
<?xml version='1.0' encoding='UTF-8'?> <ti:app xmlns:ti='http://ti.appcelerator.org'> <!-- These values are edited/maintained by Titanium Developer --> <id>com.arcaner.screengrabber</id> <name>screengrabber</name> <version>1.0</version> <publisher>marshall</publisher> <url>http://www.arcaner.com</url> <icon>default_app_logo.png</icon> <copyright>2009 by marshall</copyright> <!-- Window Definition - these values can be edited --> <window> <id>initial</id> <title>screengrabber</title> <url>app://index.html</url> <width>700</width> <max-width>3000</max-width> <min-width>0</min-width> <height>400</height> <max-height>3000</max-height> <min-height>0</min-height> <fullscreen>false</fullscreen> <resizable>true</resizable> <chrome scrollbars="true">true</chrome> <maximizable>true</maximizable> <minimizable>true</minimizable> <closeable>true</closeable> </window> </ti:app>
{ "content_hash": "4de40709e869293421a44b0f2c6a2b08", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 65, "avg_line_length": 30.24137931034483, "alnum_prop": 0.7297605473204105, "repo_name": "marshall/screengrabber", "id": "97315ced9385c50ef4131c8c2f2dfffd43973e49", "size": "877", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tiapp.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "57737" } ], "symlink_target": "" }
from __future__ import division import sys import os path = os.getcwd() rootpath = path[:path.rfind('FSSE') + 4] sys.path.append(rootpath) from deap import creator, base from deap.tools.emo import sortNondominated import pygmo from Metrics.gd import GD from Metrics.gs import GS from repeats import fetch_all_files import numpy as np import pandas as pd import warnings import pickle import pdb PRODUCT_LINE_ONLY = False MINIMUM_PFS = 3 """ GD GS GFS HV """ def identify_pareto(scores): mask = [True] * scores.shape[0] for i in range(scores.shape[0]): if (scores.iloc[:i] <= scores.iloc[i]).all(axis=1).any(): mask[i] = False elif (scores.iloc[i + 1:] <= scores.iloc[i]).all(axis=1).any(): mask[i] = False return mask def global_info(model): all_res = list() for file in os.listdir("../results"): if f"{model}." in file and '.res' in file: with open(f"../results/{file}") as f: for line in f.readlines(): if line.startswith('#'): continue all_res.append(line[:-1].split(' ')) objs_df = pd.DataFrame(all_res).convert_objects(convert_numeric=True) front_idx = identify_pareto(objs_df) objs_df.describe().to_pickle(f'PF_0/{model}_summary.pkl') objs_df[front_idx].reset_index(drop=True).to_pickle(f'PF_0/{model}_pf.pkl') def get_metrics(expr, fronts, front_srz): # step 1 do the normalization maxs, mins = front_srz.loc['max'], front_srz.loc['min'] expr_normed = (expr - mins) / (maxs - mins) fronts_normed = (fronts - mins) / (maxs - mins) # step2 calc the hypervolume hv = pygmo.hypervolume(expr_normed.values.tolist()).compute( [1] * expr.shape[1]) # step3 get the gd (general distance) gd = GD(fronts_normed.values, expr_normed.values) # step4 get the gs (general spread) gs = GS(fronts_normed.values, expr_normed.values) # step5 get the PFS in case someone need that pfs = expr_normed.shape[0] return hv, gd, gs, pfs def MAIN(model, alg): fronts = pd.read_pickle(f'PF_0/{model}_pf.pkl') front_srz = pd.read_pickle(f'PF_0/{model}_summary.pkl') stats = list() with open(f"../results/{model}.{alg}.res", 'r') as f: res = list() for line in f.read().splitlines(): if line.startswith('##'): res.clear() continue if line.startswith('# '): expr = pd.DataFrame(res).convert_objects(convert_numeric=True) hv, gd, gs, pfs = get_metrics(expr, fronts, front_srz) time = float(line.split(' ')[3]) evals = 0 # to be set if alg == 'NSGA2': evals = 30000 elif alg == 'RANDOM': evals = 10000 else: evals = int(line.split(' ')[4]) stats.append([hv, gd, gs, pfs, time, evals]) print('.', end='') res.append(line.split(' ')) stats_df = pd.DataFrame( stats, columns=['hv', 'gd', 'gs', 'pfs', 'time', 'evals']) print() print(stats_df) stats_df.to_pickle(f'../results/{model}.{alg}.stats.pkl') print('!DONE!') if __name__ == '__main__': warnings.filterwarnings("ignore") models = ['osp', 'osp2', 'ground', 'flight', 'p3a', 'p3b', 'p3c'] # models = ['osp'] # for model in models: # global_info(model) # print(f"{model} global_info Done.") for model in models: # for alg in ['NSGA2', 'RANDOM', 'SWAY', 'WORTHY']: for alg in ['WORTHY', 'WORTHY2']: print(f'Calculating {model} @ {alg}.') MAIN(model, alg) # sys.exit(0)
{ "content_hash": "e1bb4144f6ab80337bbec2988453f8d8", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 79, "avg_line_length": 29.976, "alnum_prop": 0.5596477181745396, "repo_name": "Ginfung/FSSE", "id": "dc10d401020d2e711af712dca6bb4ccbddb6176c", "size": "4969", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Metrics/all_metrics.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "159840" }, { "name": "Shell", "bytes": "237" } ], "symlink_target": "" }
package com.flightstats.flex.client; import com.flightstats.flex.FlexCredentials; import com.flightstats.flex.domain.schedules.SchedulesResponse; import org.junit.Test; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertFalse; public class SchedulesClientTest { //@Test public void testByCarrierAndFlightDepartingOnDate() { SchedulesClient client = SchedulesClient.builder() .appId(FlexCredentials.appId) .appKey(FlexCredentials.appKey) .build(); Map<String,String> params = new HashMap<>(); params.put(FlexHelper.EXTENDED_OPTIONS, FlexHelper.INCLUDE_NEW_FIELDS); SchedulesResponse response = client.byCarrierAndFlightDepartingOnDate("AA", "100", LocalDate.now(), params); System.out.println(response); } //@Test public void testByCarrierAndFlightArrivingOnDate() { SchedulesClient client = SchedulesClient.builder() .appId(FlexCredentials.appId) .appKey(FlexCredentials.appKey) .build(); Map<String,String> params = new HashMap<>(); params.put(FlexHelper.EXTENDED_OPTIONS, FlexHelper.INCLUDE_NEW_FIELDS); SchedulesResponse response = client.byCarrierAndFlightArrivingOnDate("AA", "100", LocalDate.now(), params); System.out.println(response); } //@Test public void testByRouteDepartingOnDate() { SchedulesClient client = SchedulesClient.builder() .appId(FlexCredentials.appId) .appKey(FlexCredentials.appKey) .build(); Map<String,String> params = new HashMap<>(); params.put(FlexHelper.EXTENDED_OPTIONS, FlexHelper.INCLUDE_NEW_FIELDS); SchedulesResponse response = client.byRouteDepartingOnDate("PDX", "SFO", LocalDate.now(), params); System.out.println(response); } //@Test public void testByRouteArrivingOnDate() { SchedulesClient client = SchedulesClient.builder() .appId(FlexCredentials.appId) .appKey(FlexCredentials.appKey) .build(); Map<String,String> params = new HashMap<>(); params.put(FlexHelper.EXTENDED_OPTIONS, FlexHelper.INCLUDE_NEW_FIELDS); SchedulesResponse response = client.byRouteArrivingOnDate("PDX", "SFO", LocalDate.now(), params); System.out.println(response); } //@Test public void byAirportDepartingOnDate() { SchedulesClient client = SchedulesClient.builder() .appId(FlexCredentials.appId) .appKey(FlexCredentials.appKey) .build(); Map<String,String> params = new HashMap<>(); params.put(FlexHelper.EXTENDED_OPTIONS, FlexHelper.INCLUDE_NEW_FIELDS); SchedulesResponse response = client.byAirportDepartingOnDate("PDX", LocalDateTime.now(), params); System.out.println(response); } //@Test public void byAirportArrivingOnDate() { SchedulesClient client = SchedulesClient.builder() .appId(FlexCredentials.appId) .appKey(FlexCredentials.appKey) .build(); Map<String,String> params = new HashMap<>(); params.put(FlexHelper.EXTENDED_OPTIONS, FlexHelper.INCLUDE_NEW_FIELDS); SchedulesResponse response = client.byAirportArrivingOnDate("PDX", LocalDateTime.now(), params); System.out.println(response); } }
{ "content_hash": "7a2c7f0e0dab70a7b92fe2a5b9225e35", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 116, "avg_line_length": 37.61702127659574, "alnum_prop": 0.6586538461538461, "repo_name": "flightstats/flex-example-clients", "id": "e90c1f41a2aa1e840619a306bc51d37d898055a2", "size": "3536", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ApiClients/JavaClient/src/test/java/com/flightstats/flex/client/SchedulesClientTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "130080" } ], "symlink_target": "" }
/** * @file fw_pos_control_l1_main.hpp * Implementation of a generic position controller based on the L1 norm. Outputs a bank / roll * angle, equivalent to a lateral motion (for copters and rovers). * * The implementation for the controllers is in the ECL library. This class only * interfaces to the library. * * @author Lorenz Meier <lorenz@px4.io> * @author Thomas Gubler <thomasgubler@gmail.com> * @author Andreas Antener <andreas@uaventure.com> */ #ifndef FIXEDWINGPOSITIONCONTROL_HPP_ #define FIXEDWINGPOSITIONCONTROL_HPP_ #include "launchdetection/LaunchDetector.h" #include "runway_takeoff/RunwayTakeoff.h" #include <float.h> #include <drivers/drv_hrt.h> #include <lib/ecl/geo/geo.h> #include <lib/l1/ECL_L1_Pos_Controller.hpp> #include <lib/tecs/TECS.hpp> #include <lib/landing_slope/Landingslope.hpp> #include <lib/mathlib/mathlib.h> #include <lib/perf/perf_counter.h> #include <px4_platform_common/px4_config.h> #include <px4_platform_common/defines.h> #include <px4_platform_common/module.h> #include <px4_platform_common/module_params.h> #include <px4_platform_common/posix.h> #include <px4_platform_common/px4_work_queue/WorkItem.hpp> #include <uORB/Publication.hpp> #include <uORB/Subscription.hpp> #include <uORB/SubscriptionCallback.hpp> #include <uORB/topics/airspeed_validated.h> #include <uORB/topics/manual_control_setpoint.h> #include <uORB/topics/parameter_update.h> #include <uORB/topics/position_controller_landing_status.h> #include <uORB/topics/position_controller_status.h> #include <uORB/topics/position_setpoint_triplet.h> #include <uORB/topics/tecs_status.h> #include <uORB/topics/vehicle_acceleration.h> #include <uORB/topics/vehicle_air_data.h> #include <uORB/topics/vehicle_angular_velocity.h> #include <uORB/topics/vehicle_attitude.h> #include <uORB/topics/vehicle_attitude_setpoint.h> #include <uORB/topics/vehicle_command.h> #include <uORB/topics/vehicle_control_mode.h> #include <uORB/topics/vehicle_global_position.h> #include <uORB/topics/vehicle_land_detected.h> #include <uORB/topics/vehicle_local_position.h> #include <uORB/topics/vehicle_status.h> #include <uORB/uORB.h> #include <vtol_att_control/vtol_type.h> using math::constrain; using math::max; using math::min; using math::radians; using matrix::Dcmf; using matrix::Eulerf; using matrix::Quatf; using matrix::Vector2f; using matrix::Vector3f; using matrix::wrap_pi; using uORB::SubscriptionData; using namespace launchdetection; using namespace runwaytakeoff; using namespace time_literals; static constexpr float HDG_HOLD_DIST_NEXT = 3000.0f; // initial distance of waypoint in front of plane in heading hold mode static constexpr float HDG_HOLD_REACHED_DIST = 1000.0f; // distance (plane to waypoint in front) at which waypoints are reset in heading hold mode static constexpr float HDG_HOLD_SET_BACK_DIST = 100.0f; // distance by which previous waypoint is set behind the plane static constexpr float HDG_HOLD_YAWRATE_THRESH = 0.15f; // max yawrate at which plane locks yaw for heading hold mode static constexpr float HDG_HOLD_MAN_INPUT_THRESH = 0.01f; // max manual roll/yaw input from user which does not change the locked heading static constexpr hrt_abstime T_ALT_TIMEOUT = 1_s; // time after which we abort landing if terrain estimate is not valid static constexpr float THROTTLE_THRESH = 0.05f; ///< max throttle from user which will not lead to motors spinning up in altitude controlled modes static constexpr float MANUAL_THROTTLE_CLIMBOUT_THRESH = 0.85f; ///< a throttle / pitch input above this value leads to the system switching to climbout mode static constexpr float ALTHOLD_EPV_RESET_THRESH = 5.0f; class FixedwingPositionControl final : public ModuleBase<FixedwingPositionControl>, public ModuleParams, public px4::WorkItem { public: FixedwingPositionControl(bool vtol = false); ~FixedwingPositionControl() override; /** @see ModuleBase */ static int task_spawn(int argc, char *argv[]); /** @see ModuleBase */ static int custom_command(int argc, char *argv[]); /** @see ModuleBase */ static int print_usage(const char *reason = nullptr); bool init(); private: void Run() override; orb_advert_t _mavlink_log_pub{nullptr}; uORB::SubscriptionCallbackWorkItem _local_pos_sub{this, ORB_ID(vehicle_local_position)}; uORB::Subscription _control_mode_sub{ORB_ID(vehicle_control_mode)}; ///< control mode subscription uORB::Subscription _global_pos_sub{ORB_ID(vehicle_global_position)}; uORB::Subscription _manual_control_setpoint_sub{ORB_ID(manual_control_setpoint)}; ///< notification of manual control updates uORB::Subscription _parameter_update_sub{ORB_ID(parameter_update)}; ///< notification of parameter updates uORB::Subscription _pos_sp_triplet_sub{ORB_ID(position_setpoint_triplet)}; uORB::Subscription _vehicle_air_data_sub{ORB_ID(vehicle_air_data)}; uORB::Subscription _vehicle_attitude_sub{ORB_ID(vehicle_attitude)}; ///< vehicle attitude subscription uORB::Subscription _vehicle_command_sub{ORB_ID(vehicle_command)}; ///< vehicle command subscription uORB::Subscription _vehicle_land_detected_sub{ORB_ID(vehicle_land_detected)}; ///< vehicle land detected subscription uORB::Subscription _vehicle_status_sub{ORB_ID(vehicle_status)}; ///< vehicle status subscription uORB::SubscriptionData<vehicle_angular_velocity_s> _vehicle_rates_sub{ORB_ID(vehicle_angular_velocity)}; uORB::Publication<vehicle_attitude_setpoint_s> _attitude_sp_pub; uORB::Publication<position_controller_status_s> _pos_ctrl_status_pub{ORB_ID(position_controller_status)}; ///< navigation capabilities publication uORB::Publication<position_controller_landing_status_s> _pos_ctrl_landing_status_pub{ORB_ID(position_controller_landing_status)}; ///< landing status publication uORB::Publication<tecs_status_s> _tecs_status_pub{ORB_ID(tecs_status)}; ///< TECS status publication manual_control_setpoint_s _manual_control_setpoint {}; ///< r/c channel data position_setpoint_triplet_s _pos_sp_triplet {}; ///< triplet of mission items vehicle_attitude_s _att {}; ///< vehicle attitude setpoint vehicle_attitude_setpoint_s _att_sp {}; ///< vehicle attitude setpoint vehicle_command_s _vehicle_command {}; ///< vehicle commands vehicle_control_mode_s _control_mode {}; ///< control mode vehicle_local_position_s _local_pos {}; ///< vehicle local position vehicle_land_detected_s _vehicle_land_detected {}; ///< vehicle land detected vehicle_status_s _vehicle_status {}; ///< vehicle status SubscriptionData<airspeed_validated_s> _airspeed_validated_sub{ORB_ID(airspeed_validated)}; SubscriptionData<vehicle_acceleration_s> _vehicle_acceleration_sub{ORB_ID(vehicle_acceleration)}; double _current_latitude{0}; double _current_longitude{0}; float _current_altitude{0.f}; perf_counter_t _loop_perf; ///< loop performance counter float _hold_alt{0.0f}; ///< hold altitude for altitude mode float _takeoff_ground_alt{0.0f}; ///< ground altitude at which plane was launched float _hdg_hold_yaw{0.0f}; ///< hold heading for velocity mode bool _hdg_hold_enabled{false}; ///< heading hold enabled bool _yaw_lock_engaged{false}; ///< yaw is locked for heading hold float _althold_epv{0.0f}; ///< the position estimate accuracy when engaging alt hold bool _was_in_deadband{false}; ///< wether the last stick input was in althold deadband float _min_current_sp_distance_xy{FLT_MAX}; position_setpoint_s _hdg_hold_prev_wp {}; ///< position where heading hold started position_setpoint_s _hdg_hold_curr_wp {}; ///< position to which heading hold flies hrt_abstime _control_position_last_called{0}; ///< last call of control_position /* Landing */ bool _land_noreturn_horizontal{false}; bool _land_noreturn_vertical{false}; bool _land_stayonground{false}; bool _land_motor_lim{false}; bool _land_onslope{false}; bool _land_abort{false}; Landingslope _landingslope; hrt_abstime _time_started_landing{0}; ///< time at which landing started float _t_alt_prev_valid{0}; ///< last terrain estimate which was valid hrt_abstime _time_last_t_alt{0}; ///< time at which we had last valid terrain alt float _flare_height{0.0f}; ///< estimated height to ground at which flare started float _flare_pitch_sp{0.0f}; ///< Current forced (i.e. not determined using TECS) flare pitch setpoint float _flare_curve_alt_rel_last{0.0f}; float _target_bearing{0.0f}; ///< estimated height to ground at which flare started bool _was_in_air{false}; ///< indicated wether the plane was in the air in the previous interation*/ hrt_abstime _time_went_in_air{0}; ///< time at which the plane went in the air /* Takeoff launch detection and runway */ LaunchDetector _launchDetector; LaunchDetectionResult _launch_detection_state{LAUNCHDETECTION_RES_NONE}; hrt_abstime _launch_detection_notify{0}; RunwayTakeoff _runway_takeoff; bool _last_manual{false}; ///< true if the last iteration was in manual mode (used to determine when a reset is needed) /* throttle and airspeed states */ bool _airspeed_valid{false}; ///< flag if a valid airspeed estimate exists hrt_abstime _airspeed_last_valid{0}; ///< last time airspeed was received. Used to detect timeouts. float _airspeed{0.0f}; float _eas2tas{1.0f}; float _groundspeed_undershoot{0.0f}; ///< ground speed error to min. speed in m/s Dcmf _R_nb; ///< current attitude float _roll{0.0f}; float _pitch{0.0f}; float _yaw{0.0f}; bool _reinitialize_tecs{true}; ///< indicates if the TECS states should be reinitialized (used for VTOL) bool _is_tecs_running{false}; hrt_abstime _last_tecs_update{0}; float _asp_after_transition{0.0f}; bool _was_in_transition{false}; bool _vtol_tailsitter{false}; Vector2f _transition_waypoint{NAN, NAN}; // estimator reset counters uint8_t _pos_reset_counter{0}; ///< captures the number of times the estimator has reset the horizontal position uint8_t _alt_reset_counter{0}; ///< captures the number of times the estimator has reset the altitude state ECL_L1_Pos_Controller _l1_control; TECS _tecs; uint8_t _type{0}; enum FW_POSCTRL_MODE { FW_POSCTRL_MODE_AUTO, FW_POSCTRL_MODE_POSITION, FW_POSCTRL_MODE_ALTITUDE, FW_POSCTRL_MODE_OTHER } _control_mode_current{FW_POSCTRL_MODE_OTHER}; ///< used to check the mode in the last control loop iteration. Use to check if the last iteration was in the same mode. param_t _param_handle_airspeed_trans{PARAM_INVALID}; float _param_airspeed_trans{NAN}; // Update our local parameter cache. int parameters_update(); // Update subscriptions void airspeed_poll(); void control_update(); void vehicle_attitude_poll(); void vehicle_command_poll(); void vehicle_control_mode_poll(); void vehicle_status_poll(); void status_publish(); void landing_status_publish(); void tecs_status_publish(); void abort_landing(bool abort); /** * Get a new waypoint based on heading and distance from current position * * @param heading the heading to fly to * @param distance the distance of the generated waypoint * @param waypoint_prev the waypoint at the current position * @param waypoint_next the waypoint in the heading direction */ void get_waypoint_heading_distance(float heading, position_setpoint_s &waypoint_prev, position_setpoint_s &waypoint_next, bool flag_init); /** * Return the terrain estimate during takeoff or takeoff_alt if terrain estimate is not available */ float get_terrain_altitude_takeoff(float takeoff_alt); /** * Check if we are in a takeoff situation */ bool in_takeoff_situation(); /** * Do takeoff help when in altitude controlled modes * @param hold_altitude altitude setpoint for controller * @param pitch_limit_min minimum pitch allowed */ void do_takeoff_help(float *hold_altitude, float *pitch_limit_min); /** * Update desired altitude base on user pitch stick input * * @param dt Time step * @return true if climbout mode was requested by user (climb with max rate and min airspeed) */ bool update_desired_altitude(float dt); bool control_position(const hrt_abstime &now, const Vector2f &curr_pos, const Vector2f &ground_speed, const position_setpoint_s &pos_sp_prev, const position_setpoint_s &pos_sp_curr, const position_setpoint_s &pos_sp_next); void control_takeoff(const hrt_abstime &now, const Vector2f &curr_pos, const Vector2f &ground_speed, const position_setpoint_s &pos_sp_prev, const position_setpoint_s &pos_sp_curr); void control_landing(const hrt_abstime &now, const Vector2f &curr_pos, const Vector2f &ground_speed, const position_setpoint_s &pos_sp_prev, const position_setpoint_s &pos_sp_curr); float get_tecs_pitch(); float get_tecs_thrust(); float get_demanded_airspeed(); float calculate_target_airspeed(float airspeed_demand, const Vector2f &ground_speed); /** * Handle incoming vehicle commands */ void handle_command(); void reset_takeoff_state(bool force = false); void reset_landing_state(); /* * Call TECS : a wrapper function to call the TECS implementation */ void tecs_update_pitch_throttle(const hrt_abstime &now, float alt_sp, float airspeed_sp, float pitch_min_rad, float pitch_max_rad, float throttle_min, float throttle_max, float throttle_cruise, bool climbout_mode, float climbout_pitch_min_rad, uint8_t mode = tecs_status_s::TECS_MODE_NORMAL); DEFINE_PARAMETERS( (ParamFloat<px4::params::FW_AIRSPD_MAX>) _param_fw_airspd_max, (ParamFloat<px4::params::FW_AIRSPD_MIN>) _param_fw_airspd_min, (ParamFloat<px4::params::FW_AIRSPD_TRIM>) _param_fw_airspd_trim, (ParamFloat<px4::params::FW_CLMBOUT_DIFF>) _param_fw_clmbout_diff, (ParamFloat<px4::params::FW_GND_SPD_MIN>) _param_fw_gnd_spd_min, (ParamFloat<px4::params::FW_L1_DAMPING>) _param_fw_l1_damping, (ParamFloat<px4::params::FW_L1_PERIOD>) _param_fw_l1_period, (ParamFloat<px4::params::FW_L1_R_SLEW_MAX>) _param_fw_l1_r_slew_max, (ParamFloat<px4::params::FW_R_LIM>) _param_fw_r_lim, (ParamFloat<px4::params::FW_LND_AIRSPD_SC>) _param_fw_lnd_airspd_sc, (ParamFloat<px4::params::FW_LND_ANG>) _param_fw_lnd_ang, (ParamFloat<px4::params::FW_LND_FL_PMAX>) _param_fw_lnd_fl_pmax, (ParamFloat<px4::params::FW_LND_FL_PMIN>) _param_fw_lnd_fl_pmin, (ParamFloat<px4::params::FW_LND_FLALT>) _param_fw_lnd_flalt, (ParamFloat<px4::params::FW_LND_HHDIST>) _param_fw_lnd_hhdist, (ParamFloat<px4::params::FW_LND_HVIRT>) _param_fw_lnd_hvirt, (ParamFloat<px4::params::FW_LND_THRTC_SC>) _param_fw_thrtc_sc, (ParamFloat<px4::params::FW_LND_TLALT>) _param_fw_lnd_tlalt, (ParamBool<px4::params::FW_LND_EARLYCFG>) _param_fw_lnd_earlycfg, (ParamBool<px4::params::FW_LND_USETER>) _param_fw_lnd_useter, (ParamFloat<px4::params::FW_P_LIM_MAX>) _param_fw_p_lim_max, (ParamFloat<px4::params::FW_P_LIM_MIN>) _param_fw_p_lim_min, (ParamFloat<px4::params::FW_T_CLMB_MAX>) _param_fw_t_clmb_max, (ParamFloat<px4::params::FW_T_HRATE_FF>) _param_fw_t_hrate_ff, (ParamFloat<px4::params::FW_T_HRATE_P>) _param_fw_t_hrate_p, (ParamFloat<px4::params::FW_T_INTEG_GAIN>) _param_fw_t_integ_gain, (ParamFloat<px4::params::FW_T_PTCH_DAMP>) _param_fw_t_ptch_damp, (ParamFloat<px4::params::FW_T_RLL2THR>) _param_fw_t_rll2thr, (ParamFloat<px4::params::FW_T_SINK_MAX>) _param_fw_t_sink_max, (ParamFloat<px4::params::FW_T_SINK_MIN>) _param_fw_t_sink_min, (ParamFloat<px4::params::FW_T_SPD_OMEGA>) _param_fw_t_spd_omega, (ParamFloat<px4::params::FW_T_SPDWEIGHT>) _param_fw_t_spdweight, (ParamFloat<px4::params::FW_T_SRATE_P>) _param_fw_t_srate_p, (ParamFloat<px4::params::FW_T_THR_DAMP>) _param_fw_t_thr_damp, (ParamFloat<px4::params::FW_T_THRO_CONST>) _param_fw_t_thro_const, (ParamFloat<px4::params::FW_T_TIME_CONST>) _param_fw_t_time_const, (ParamFloat<px4::params::FW_T_VERT_ACC>) _param_fw_t_vert_acc, (ParamFloat<px4::params::FW_THR_ALT_SCL>) _param_fw_thr_alt_scl, (ParamFloat<px4::params::FW_THR_CRUISE>) _param_fw_thr_cruise, (ParamFloat<px4::params::FW_THR_IDLE>) _param_fw_thr_idle, (ParamFloat<px4::params::FW_THR_LND_MAX>) _param_fw_thr_lnd_max, (ParamFloat<px4::params::FW_THR_MAX>) _param_fw_thr_max, (ParamFloat<px4::params::FW_THR_MIN>) _param_fw_thr_min, (ParamFloat<px4::params::FW_THR_SLEW_MAX>) _param_fw_thr_slew_max, // external parameters (ParamInt<px4::params::FW_ARSP_MODE>) _param_fw_arsp_mode, (ParamFloat<px4::params::FW_PSP_OFF>) _param_fw_psp_off, (ParamFloat<px4::params::FW_RSP_OFF>) _param_fw_rsp_off, (ParamFloat<px4::params::FW_MAN_P_MAX>) _param_fw_man_p_max, (ParamFloat<px4::params::FW_MAN_R_MAX>) _param_fw_man_r_max, (ParamFloat<px4::params::NAV_LOITER_RAD>) _param_nav_loiter_rad ) }; #endif // FIXEDWINGPOSITIONCONTROL_HPP_
{ "content_hash": "8e75187715b743a6290982d1afcad591", "timestamp": "", "source": "github", "line_count": 401, "max_line_length": 170, "avg_line_length": 41.82044887780549, "alnum_prop": 0.7289803220035778, "repo_name": "PX4/Firmware", "id": "27e453c15cb660e7c9ca98382260f4992dffda28", "size": "18506", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/modules/fw_pos_control_l1/FixedwingPositionControl.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "3744347" }, { "name": "C++", "bytes": "9697434" }, { "name": "CMake", "bytes": "1114053" }, { "name": "EmberScript", "bytes": "115886" }, { "name": "GDB", "bytes": "41" }, { "name": "Groovy", "bytes": "66180" }, { "name": "HTML", "bytes": "5343" }, { "name": "MATLAB", "bytes": "9938" }, { "name": "Makefile", "bytes": "20059" }, { "name": "Perl", "bytes": "11401" }, { "name": "Python", "bytes": "1321136" }, { "name": "Shell", "bytes": "308628" } ], "symlink_target": "" }
FOUNDATION_EXPORT double JTSImageVersionNumber; //! Project version string for JTSImage. FOUNDATION_EXPORT const unsigned char JTSImageVersionString[]; #import <JTSImage/JTSImageViewController.h> #import <JTSImage/JTSImageInfo.h> #import <JTSImage/JTSSimpleImageDownloader.h> #import <JTSImage/JTSAnimatedGIFUtility.h> #import <JTSImage/UIImage+JTSImageEffects.h>
{ "content_hash": "cf53cbb5a623e25fc2d59e52f4cbe658", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 62, "avg_line_length": 30.666666666666668, "alnum_prop": 0.8260869565217391, "repo_name": "colemancda/JTSImageViewController", "id": "df17109eb1f8b125d12be7402375708e30d1be6d", "size": "579", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Sample App/JTSImageVC/JTSImage/JTSImage.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "137271" }, { "name": "Ruby", "bytes": "757" } ], "symlink_target": "" }
HOMOTYPIC_SYNONYM #### According to Euro+Med Plantbase #### Published in null #### Original name null ### Remarks null
{ "content_hash": "a5536fb784488cbb0615354e07aeff16", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 18, "avg_line_length": 9.384615384615385, "alnum_prop": 0.6967213114754098, "repo_name": "mdoering/backbone", "id": "13ea72df4714070de959ca8c13cd6c0020e26270", "size": "170", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Cirsium/Cirsium byzantinum/ Syn. Cirsium polycephalum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/* * super.c contains code to handle the super-block tables. */ #include <stdarg.h> #include <linux/config.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/major.h> #include <linux/stat.h> #include <linux/errno.h> #include <linux/string.h> #include <linux/locks.h> #include <linux/mm.h> #include <asm/system.h> #include <asm/segment.h> #include <asm/bitops.h> extern struct file_operations * get_blkfops(unsigned int); extern struct file_operations * get_chrfops(unsigned int); extern void wait_for_keypress(void); extern int root_mountflags; struct super_block super_blocks[NR_SUPER]; static int do_remount_sb(struct super_block *sb, int flags, char * data); /* this is initialized in init/main.c */ dev_t ROOT_DEV = 0; static struct file_system_type * file_systems = NULL; int register_filesystem(struct file_system_type * fs) { struct file_system_type ** tmp; if (!fs) return -EINVAL; if (fs->next) return -EBUSY; tmp = &file_systems; while (*tmp) { if (strcmp((*tmp)->name, fs->name) == 0) return -EBUSY; tmp = &(*tmp)->next; } *tmp = fs; return 0; } int unregister_filesystem(struct file_system_type * fs) { struct file_system_type ** tmp; tmp = &file_systems; while (*tmp) { if (fs == *tmp) { *tmp = fs->next; fs->next = NULL; return 0; } tmp = &(*tmp)->next; } return -EINVAL; } static int fs_index(const char * __name) { struct file_system_type * tmp; char * name; int err, index; err = getname(__name, &name); if (err) return err; index = 0; for (tmp = file_systems ; tmp ; tmp = tmp->next) { if (strcmp(tmp->name, name) == 0) { putname(name); return index; } index++; } putname(name); return -EINVAL; } static int fs_name(unsigned int index, char * buf) { struct file_system_type * tmp; int err, len; tmp = file_systems; while (tmp && index > 0) { tmp = tmp->next; index--; } if (!tmp) return -EINVAL; len = strlen(tmp->name) + 1; err = verify_area(VERIFY_WRITE, buf, len); if (err) return err; memcpy_tofs(buf, tmp->name, len); return 0; } static int fs_maxindex(void) { struct file_system_type * tmp; int index; index = 0; for (tmp = file_systems ; tmp ; tmp = tmp->next) index++; return index; } /* * Whee.. Weird sysv syscall. */ asmlinkage int sys_sysfs(int option, ...) { va_list args; int retval = -EINVAL; unsigned int index; va_start(args, option); switch (option) { case 1: retval = fs_index(va_arg(args, const char *)); break; case 2: index = va_arg(args, unsigned int); retval = fs_name(index, va_arg(args, char *)); break; case 3: retval = fs_maxindex(); break; } va_end(args); return retval; } int get_filesystem_list(char * buf) { int len = 0; struct file_system_type * tmp; tmp = file_systems; while (tmp && len < PAGE_SIZE - 80) { len += sprintf(buf+len, "%s\t%s\n", tmp->requires_dev ? "" : "nodev", tmp->name); tmp = tmp->next; } return len; } struct file_system_type *get_fs_type(char *name) { struct file_system_type * fs = file_systems; if (!name) return fs; while (fs) { if (!strcmp(name,fs->name)) break; fs = fs->next; } return fs; } void __wait_on_super(struct super_block * sb) { struct wait_queue wait = { current, NULL }; add_wait_queue(&sb->s_wait, &wait); repeat: current->state = TASK_UNINTERRUPTIBLE; if (sb->s_lock) { schedule(); goto repeat; } remove_wait_queue(&sb->s_wait, &wait); current->state = TASK_RUNNING; } void sync_supers(dev_t dev) { struct super_block * sb; for (sb = super_blocks + 0 ; sb < super_blocks + NR_SUPER ; sb++) { if (!sb->s_dev) continue; if (dev && sb->s_dev != dev) continue; wait_on_super(sb); if (!sb->s_dev || !sb->s_dirt) continue; if (dev && (dev != sb->s_dev)) continue; if (sb->s_op && sb->s_op->write_super) sb->s_op->write_super(sb); } } static struct super_block * get_super(dev_t dev) { struct super_block * s; if (!dev) return NULL; s = 0+super_blocks; while (s < NR_SUPER+super_blocks) if (s->s_dev == dev) { wait_on_super(s); if (s->s_dev == dev) return s; s = 0+super_blocks; } else s++; return NULL; } void put_super(dev_t dev) { struct super_block * sb; if (dev == ROOT_DEV) { printk("VFS: Root device %d/%d: prepare for armageddon\n", MAJOR(dev), MINOR(dev)); return; } if (!(sb = get_super(dev))) return; if (sb->s_covered) { printk("VFS: Mounted device %d/%d - tssk, tssk\n", MAJOR(dev), MINOR(dev)); return; } if (sb->s_op && sb->s_op->put_super) sb->s_op->put_super(sb); } static struct super_block * read_super(dev_t dev,char *name,int flags, void *data, int silent) { struct super_block * s; struct file_system_type *type; if (!dev) return NULL; check_disk_change(dev); s = get_super(dev); if (s) return s; if (!(type = get_fs_type(name))) { printk("VFS: on device %d/%d: get_fs_type(%s) failed\n", MAJOR(dev), MINOR(dev), name); return NULL; } for (s = 0+super_blocks ;; s++) { if (s >= NR_SUPER+super_blocks) return NULL; if (!s->s_dev) break; } s->s_dev = dev; s->s_flags = flags; if (!type->read_super(s,data, silent)) { s->s_dev = 0; return NULL; } s->s_dev = dev; s->s_covered = NULL; s->s_rd_only = 0; s->s_dirt = 0; s->s_type = type; return s; } /* * Unnamed block devices are dummy devices used by virtual * filesystems which don't use real block-devices. -- jrs */ static char unnamed_dev_in_use[256/8] = { 0, }; static dev_t get_unnamed_dev(void) { int i; for (i = 1; i < 256; i++) { if (!set_bit(i,unnamed_dev_in_use)) return (UNNAMED_MAJOR << 8) | i; } return 0; } static void put_unnamed_dev(dev_t dev) { if (!dev) return; if (MAJOR(dev) == UNNAMED_MAJOR && clear_bit(MINOR(dev), unnamed_dev_in_use)) return; printk("VFS: put_unnamed_dev: freeing unused device %d/%d\n", MAJOR(dev), MINOR(dev)); } static int do_umount(dev_t dev) { struct super_block * sb; int retval; if (dev==ROOT_DEV) { /* Special case for "unmounting" root. We just try to remount it readonly, and sync() the device. */ if (!(sb=get_super(dev))) return -ENOENT; if (!(sb->s_flags & MS_RDONLY)) { fsync_dev(dev); retval = do_remount_sb(sb, MS_RDONLY, 0); if (retval) return retval; } return 0; } if (!(sb=get_super(dev)) || !(sb->s_covered)) return -ENOENT; if (!sb->s_covered->i_mount) printk("VFS: umount(%d/%d): mounted inode has i_mount=NULL\n", MAJOR(dev), MINOR(dev)); if (!fs_may_umount(dev, sb->s_mounted)) return -EBUSY; sb->s_covered->i_mount = NULL; iput(sb->s_covered); sb->s_covered = NULL; iput(sb->s_mounted); sb->s_mounted = NULL; if (sb->s_op && sb->s_op->write_super && sb->s_dirt) sb->s_op->write_super(sb); put_super(dev); return 0; } /* * Now umount can handle mount points as well as block devices. * This is important for filesystems which use unnamed block devices. * * There is a little kludge here with the dummy_inode. The current * vfs release functions only use the r_dev field in the inode so * we give them the info they need without using a real inode. * If any other fields are ever needed by any block device release * functions, they should be faked here. -- jrs */ asmlinkage int sys_umount(char * name) { struct inode * inode; dev_t dev; int retval; struct inode dummy_inode; struct file_operations * fops; if (!suser()) return -EPERM; retval = namei(name,&inode); if (retval) { retval = lnamei(name,&inode); if (retval) return retval; } if (S_ISBLK(inode->i_mode)) { dev = inode->i_rdev; if (IS_NODEV(inode)) { iput(inode); return -EACCES; } } else { if (!inode->i_sb || inode != inode->i_sb->s_mounted) { iput(inode); return -EINVAL; } dev = inode->i_sb->s_dev; iput(inode); memset(&dummy_inode, 0, sizeof(dummy_inode)); dummy_inode.i_rdev = dev; inode = &dummy_inode; } if (MAJOR(dev) >= MAX_BLKDEV) { iput(inode); return -ENXIO; } if (!(retval = do_umount(dev)) && dev != ROOT_DEV) { fops = get_blkfops(MAJOR(dev)); if (fops && fops->release) fops->release(inode,NULL); if (MAJOR(dev) == UNNAMED_MAJOR) put_unnamed_dev(dev); } if (inode != &dummy_inode) iput(inode); if (retval) return retval; fsync_dev(dev); return 0; } /* * do_mount() does the actual mounting after sys_mount has done the ugly * parameter parsing. When enough time has gone by, and everything uses the * new mount() parameters, sys_mount() can then be cleaned up. * * We cannot mount a filesystem if it has active, used, or dirty inodes. * We also have to flush all inode-data for this device, as the new mount * might need new info. */ static int do_mount(dev_t dev, const char * dir, char * type, int flags, void * data) { struct inode * dir_i; struct super_block * sb; int error; error = namei(dir,&dir_i); if (error) return error; if (dir_i->i_count != 1 || dir_i->i_mount) { iput(dir_i); return -EBUSY; } if (!S_ISDIR(dir_i->i_mode)) { iput(dir_i); return -ENOTDIR; } if (!fs_may_mount(dev)) { iput(dir_i); return -EBUSY; } sb = read_super(dev,type,flags,data,0); if (!sb) { iput(dir_i); return -EINVAL; } if (sb->s_covered) { iput(dir_i); return -EBUSY; } sb->s_covered = dir_i; dir_i->i_mount = sb->s_mounted; return 0; /* we don't iput(dir_i) - see umount */ } /* * Alters the mount flags of a mounted file system. Only the mount point * is used as a reference - file system type and the device are ignored. * FS-specific mount options can't be altered by remounting. */ static int do_remount_sb(struct super_block *sb, int flags, char *data) { int retval; if (!(flags & MS_RDONLY ) && sb->s_dev && is_read_only(sb->s_dev)) return -EACCES; /*flags |= MS_RDONLY;*/ /* If we are remounting RDONLY, make sure there are no rw files open */ if ((flags & MS_RDONLY) && !(sb->s_flags & MS_RDONLY)) if (!fs_may_remount_ro(sb->s_dev)) return -EBUSY; if (sb->s_op && sb->s_op->remount_fs) { retval = sb->s_op->remount_fs(sb, &flags, data); if (retval) return retval; } sb->s_flags = (sb->s_flags & ~MS_RMT_MASK) | (flags & MS_RMT_MASK); return 0; } static int do_remount(const char *dir,int flags,char *data) { struct inode *dir_i; int retval; retval = namei(dir,&dir_i); if (retval) return retval; if (dir_i != dir_i->i_sb->s_mounted) { iput(dir_i); return -EINVAL; } retval = do_remount_sb(dir_i->i_sb, flags, data); iput(dir_i); return retval; } static int copy_mount_options (const void * data, unsigned long *where) { int i; unsigned long page; struct vm_area_struct * vma; *where = 0; if (!data) return 0; vma = find_vma(current, (unsigned long) data); if (!vma || (unsigned long) data < vma->vm_start) return -EFAULT; i = vma->vm_end - (unsigned long) data; if (PAGE_SIZE <= (unsigned long) i) i = PAGE_SIZE-1; if (!(page = __get_free_page(GFP_KERNEL))) { return -ENOMEM; } memcpy_fromfs((void *) page,data,i); *where = page; return 0; } /* * Flags is a 16-bit value that allows up to 16 non-fs dependent flags to * be given to the mount() call (ie: read-only, no-dev, no-suid etc). * * data is a (void *) that can point to any structure up to * PAGE_SIZE-1 bytes, which can contain arbitrary fs-dependent * information (or be NULL). * * NOTE! As old versions of mount() didn't use this setup, the flags * has to have a special 16-bit magic number in the hight word: * 0xC0ED. If this magic word isn't present, the flags and data info * isn't used, as the syscall assumes we are talking to an older * version that didn't understand them. */ asmlinkage int sys_mount(char * dev_name, char * dir_name, char * type, unsigned long new_flags, void * data) { struct file_system_type * fstype; struct inode * inode; struct file_operations * fops; dev_t dev; int retval; char * t; unsigned long flags = 0; unsigned long page = 0; if (!suser()) return -EPERM; if ((new_flags & (MS_MGC_MSK | MS_REMOUNT)) == (MS_MGC_VAL | MS_REMOUNT)) { retval = copy_mount_options (data, &page); if (retval < 0) return retval; retval = do_remount(dir_name, new_flags & ~MS_MGC_MSK & ~MS_REMOUNT, (char *) page); free_page(page); return retval; } retval = copy_mount_options (type, &page); if (retval < 0) return retval; fstype = get_fs_type((char *) page); free_page(page); if (!fstype) return -ENODEV; t = fstype->name; fops = NULL; if (fstype->requires_dev) { retval = namei(dev_name,&inode); if (retval) return retval; if (!S_ISBLK(inode->i_mode)) { iput(inode); return -ENOTBLK; } if (IS_NODEV(inode)) { iput(inode); return -EACCES; } dev = inode->i_rdev; if (MAJOR(dev) >= MAX_BLKDEV) { iput(inode); return -ENXIO; } fops = get_blkfops(MAJOR(dev)); if (!fops) { iput(inode); return -ENOTBLK; } if (fops->open) { struct file dummy; /* allows read-write or read-only flag */ memset(&dummy, 0, sizeof(dummy)); dummy.f_inode = inode; dummy.f_mode = (new_flags & MS_RDONLY) ? 1 : 3; retval = fops->open(inode, &dummy); if (retval) { iput(inode); return retval; } } } else { if (!(dev = get_unnamed_dev())) return -EMFILE; inode = NULL; } page = 0; if ((new_flags & MS_MGC_MSK) == MS_MGC_VAL) { flags = new_flags & ~MS_MGC_MSK; retval = copy_mount_options(data, &page); if (retval < 0) { iput(inode); return retval; } } retval = do_mount(dev,dir_name,t,flags,(void *) page); free_page(page); if (retval && fops && fops->release) fops->release(inode, NULL); iput(inode); return retval; } void mount_root(void) { struct file_system_type * fs_type; struct super_block * sb; struct inode * inode, d_inode; struct file filp; int retval; memset(super_blocks, 0, sizeof(super_blocks)); #ifdef CONFIG_BLK_DEV_FD if (MAJOR(ROOT_DEV) == FLOPPY_MAJOR) { printk(KERN_NOTICE "VFS: Insert root floppy and press ENTER\n"); wait_for_keypress(); } #endif memset(&filp, 0, sizeof(filp)); memset(&d_inode, 0, sizeof(d_inode)); d_inode.i_rdev = ROOT_DEV; filp.f_inode = &d_inode; if ( root_mountflags & MS_RDONLY) filp.f_mode = 1; /* read only */ else filp.f_mode = 3; /* read write */ retval = blkdev_open(&d_inode, &filp); if(retval == -EROFS){ root_mountflags |= MS_RDONLY; filp.f_mode = 1; retval = blkdev_open(&d_inode, &filp); } for (fs_type = file_systems ; fs_type ; fs_type = fs_type->next) { if(retval) break; if (!fs_type->requires_dev) continue; sb = read_super(ROOT_DEV,fs_type->name,root_mountflags,NULL,1); if (sb) { inode = sb->s_mounted; inode->i_count += 3 ; /* NOTE! it is logically used 4 times, not 1 */ sb->s_covered = inode; sb->s_flags = root_mountflags; current->fs->pwd = inode; current->fs->root = inode; printk ("VFS: Mounted root (%s filesystem)%s.\n", fs_type->name, (sb->s_flags & MS_RDONLY) ? " readonly" : ""); return; } } panic("VFS: Unable to mount root fs on %02x:%02x", MAJOR(ROOT_DEV), MINOR(ROOT_DEV)); }
{ "content_hash": "2749cdd51c64bdb21252426fd4542a42", "timestamp": "", "source": "github", "line_count": 687, "max_line_length": 85, "avg_line_length": 21.950509461426492, "alnum_prop": 0.6223474801061007, "repo_name": "straceX/Ectoplasm", "id": "a428a7922355850cf42f3e79b5110e3da6a7ee19", "size": "15155", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "linux-1.2.0/linux/fs/super.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "496480" }, { "name": "C", "bytes": "12406430" }, { "name": "C++", "bytes": "53871" }, { "name": "Makefile", "bytes": "126601" }, { "name": "Objective-C", "bytes": "2880" }, { "name": "OpenEdge ABL", "bytes": "4189" }, { "name": "Perl", "bytes": "27231" }, { "name": "Shell", "bytes": "11773" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!-- Copyright 2003 - 2015 The eFaps Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <ui-command xmlns="http://www.efaps.org/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd"> <uuid>c2e1dc07-6b20-48fb-b969-543d1159be24</uuid> <file-application>eFapsApp-Sales</file-application> <definition> <version-expression>(version==latest)</version-expression> <name>Sales_DeliveryNoteTree_Doc_Menu_Action_AddInvoice</name> <target> <search>Sales_DeliveryNoteTree_Doc_Menu_Action_AddInvoice_Search</search> <execute program="org.efaps.esjp.common.uisearch.Connect"> <property name="ConnectParentAttribute">ToLink</property> <property name="ConnectChildAttribute">FromLink</property> <!-- Sales_Invoice2DeliveryNote --> <property name="ConnectType">4884c4ab-0bdb-4758-ae98-94d2931952ab</property> </execute> </target> <property name="Target">modal</property> <property name="TargetMode">edit</property> <property name="RecievingTicketStatus">Open</property> </definition> </ui-command>
{ "content_hash": "e9d5272d5b1bb00772272b0bc5a7b3cd", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 98, "avg_line_length": 47.3421052631579, "alnum_prop": 0.6953863257365203, "repo_name": "eFaps/eFapsApp-Sales", "id": "9cadd527ea672fb37cd3cea3e9f5e79432b9fb63", "size": "1799", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/efaps/UserInterface/Document/DeliveryNote/Sales_DeliveryNoteTree_Doc_Menu_Action_AddInvoice.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "3983951" }, { "name": "XSLT", "bytes": "6575" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>管理后台</title> <link rel="stylesheet" href="{skin:css/admin.css}" /> {js:jquery} {js:dialog} {js:form} {js:validate} {js:artTemplate} <script type='text/javascript' src="{theme:javascript/admin.js}"></script> </head> <body style="width:450px;min-height:200px;"> <div class="pop_win"> <form name="balanceForm" callback="submitCallback();" action="#"> <table class="form_table" style="width:95%"> <col width="120px" /> <col /> <tr> <td class="t_r">请选择:</td> <td> <select name="type" class="auto" pattern='required'> <option value="">请选择操作类型</option> <option value="recharge">充值账户余额</option> <option value="withdraw">账户余额提现</option> </select> </td> </tr> <tr> <td class="t_r">请输入金额:</td> <td><input name="balance" class="small" type="text" maxlength="8" pattern='float' alt='必须要填写金额数字' /></td> </tr> </table> </form> </div> <script type='text/javascript'> //提交回调函数 function submitCallback() { return false; } </script> </body> </html>
{ "content_hash": "af9c343e4631b48b40dba7d185022c60", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 121, "avg_line_length": 27.23913043478261, "alnum_prop": 0.6384676775738228, "repo_name": "yangxt/shop", "id": "0b4408c5e4c842b585f13fb3ce9b3d377aa6e2fb", "size": "1349", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "views/sysdefault/member/member_balance.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "295" }, { "name": "CSS", "bytes": "450176" }, { "name": "HTML", "bytes": "895170" }, { "name": "JavaScript", "bytes": "835221" }, { "name": "PHP", "bytes": "2335550" }, { "name": "XSLT", "bytes": "9223" } ], "symlink_target": "" }
var cbpAnimatedHeader = (function() { var docElem = document.documentElement, header = document.querySelector( '.navbar-default' ), didScroll = false, changeHeaderOn = 650; function init() { window.addEventListener( 'scroll', function( event ) { if( !didScroll ) { didScroll = true; setTimeout( scrollPage, 250 ); } }, false ); } function scrollPage() { var sy = scrollY(); if ( sy >= changeHeaderOn ) { classie.remove( header, 'navbar-hide'); classie.add( header, 'navbar-shrink' ); } else { if (sy > 30) { classie.add( header, 'navbar-hide' ); } else { classie.remove( header, 'navbar-hide'); } classie.remove( header, 'navbar-shrink' ); } didScroll = false; } function scrollY() { return window.pageYOffset || docElem.scrollTop; } init(); })();
{ "content_hash": "940beed770e5d92bea246202a27014e3", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 56, "avg_line_length": 18.977272727272727, "alnum_prop": 0.615568862275449, "repo_name": "suzunghia/suzunghia.github.io", "id": "658b9fd7494a4912d28d17ea28b4e9cc3538db49", "size": "1048", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/cbpAnimatedHeader.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "209625" }, { "name": "HTML", "bytes": "42418" }, { "name": "JavaScript", "bytes": "105500" }, { "name": "PHP", "bytes": "1097" } ], "symlink_target": "" }
#!/usr/bin/env python3 # from gpiozero import RGBLED from gpiozero import Button from signal import pause import os.path import yaml if ( os.path.isfile('config.yml')): with open("config.yml", "r") as configfile: cfg = yaml.load(configfile) elif ( os.path.isfile('config_orig.yml')): with open("config.yml", "r") as configfile: cfg = yaml.load(configfile) led = RGBLED(red=cfg['red_pin'], green=cfg['green_pin'], blue=cfg['blue_pin']) button = Button(cfg['button_pin']) state = 'init' led.color = (0,0,1) if ( os.path.isfile('performance.yml')): with open("performance.yml", "r") as configfile: cfg = yaml.load(configfile) elif ( os.path.isfile('performance_orig.yml')): with open("performance.yml", "r") as configfile: cfg = yaml.load(configfile) if cfg['performance'] == "": speed=2 elif cfg['performance'] == "silver": speed=2 elif cfg['performance'] == "gold": speed=1 elif cfg['performance'] == "platinum": speed=0.5 else: speed=2 def state_transition(): global state #eeeww #even worse: Read the file on every button press #better would be: https://github.com/gorakhargosh/watchdog#example-api-usage if ( os.path.isfile('performance.yml')): with open("performance.yml", "r") as configfile: cfg = yaml.load(configfile) elif ( os.path.isfile('performance_orig.yml')): with open("performance.yml", "r") as configfile: cfg = yaml.load(configfile) if cfg['performance'] == "": speed=2 elif cfg['performance'] == "silver": speed=2 elif cfg['performance'] == "gold": speed=1 elif cfg['performance'] == "platinum": speed=0.5 else: speed=2 print(state) if ( state is 'init'): state = 'init2green' led.blink(speed,speed,on_color=(0,1,0)) elif ( state is 'init2green'): state = 'green2yellow' led.blink(speed,speed,on_color = (1,0.7,0)) elif ( state is 'green2yellow'): state = 'yellow2red' led.blink(speed,speed,on_color = (1,0,0)) elif ( state is 'yellow2red'): state = 'red2yellow' led.blink(speed,speed,on_color = (1,0.7,0)) elif ( state is 'red2yellow'): state = 'yellow2green' led.blink(speed,speed,on_color = (0,1,0)) elif ( state is 'yellow2green'): state = 'green2yellow' led.blink(speed,speed,on_color = (1,1,0)) elif ( state is 'error'): state = 'init' led.blink(speed,speed,on_color = (1,1,1)) print(state) led.blink(speed,speed) button.when_pressed = state_transition pause()
{ "content_hash": "119b98b36507dc53a7a12ec7acd7d2d7", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 78, "avg_line_length": 26.804347826086957, "alnum_prop": 0.64882400648824, "repo_name": "helotism/show-cgfmgt", "id": "6487f23d503bc32d8656821c41f5c86201e2ddb1", "size": "2880", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/physical/button-rgbled-cycler/buttonpress-colorcycler.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "4083" }, { "name": "SaltStack", "bytes": "2899" } ], "symlink_target": "" }
<?xml version="1.0" ?> <container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <!-- <parameters> <parameter key="test_test.example.class">Test\Bundle\TestBundle\Example</parameter> </parameters> <services> <service id="test_test.example" class="%test_test.example.class%"> <argument type="service" id="service_id" /> <argument>plain_value</argument> <argument>%parameter_name%</argument> </service> </services> --> </container>
{ "content_hash": "17a805554240108bc78d1480672c68db", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 120, "avg_line_length": 34.8, "alnum_prop": 0.6379310344827587, "repo_name": "inmzombie/ejemplo-sonata", "id": "9d2470dac0d5209fd70c8da298f9f9ae5553d375", "size": "696", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Test/Bundle/TestBundle/Resources/config/services.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2204" }, { "name": "PHP", "bytes": "62192" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <!-- Google Tag Manager --> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-5DMHV7K');</script> <!-- End Google Tag Manager --> <meta charset="utf-8" /> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=2.5, user-scalable=1" /> <!-- Favicons --> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#74be3c"> <meta name="theme-color" content="#89bd62"> <!-- Title, Description --> <title>Culture Camp 2018 | Calaska Culture</title> <meta name="description" content="Learn how to make traditional Native Alaskan art. Activities include drum making, weaving, beading, and learning Haida language."> <!-- Open Graph Metadata --> <meta property="og:url" content="/events/anacortes-culture-camp-2018.html" /> <meta property="og:type" content="website" /> <meta property="og:title" content="Anacortes Culture Camp 2018" /> <meta property="og:description" content="Learn how to make traditional Native Alaskan art. Activities include drum making, weaving, beading, and learning Haida language." /> <meta property="og:image" content="/assets/img/events/sccc-2018-desktop.jpg" /> <!-- Stylesheets, Fonts, Neccessary Scripts --> <link href="https://fonts.googleapis.com/css?family=Montserrat|Oswald" rel="stylesheet"> <script src="https://www.paypalobjects.com/api/checkout.min.js"></script> </head> <link rel="stylesheet" href="../assets/css/style.min.css"> <body itemscope itemtype="http://schema.org/Event"> <!-- Google Tag Manager (noscript) --> <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-5DMHV7K" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <!-- End Google Tag Manager (noscript) --> <header class="hero hero--events"> <nav class="nav container"> <ul class="grid grid-5--small grid-5--medium grid-5--large"> <a class="grid__col nav__item" href="../"><li>Home</li></a> <a class="grid__col nav__item" href="../about.html"><li>About</li></a> <a class="grid__col nav__item" href="../events/"><li>Events</li></a> <a class="grid__col nav__item" href="../activities.html"><li>Activities</li></a> <a class="grid__col nav__item" href="../contact.html"><li>Contact</li></a> </ul> </nav> <div class="container"> <h1 class="hero__title hero__title--pages" itemprop="name">Anacortes Culture Camp 2018</h1> <p class="hero__sub-title" itemprop="description">Learn how to make traditional Native Alaskan art. Activities include drum making, paddle, making, weaving, and beading.</p> <div class="text-center"> <div class="share"><a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://calaska.org/events/anacortes-culture-camp-2018.html"><button class="share-icon--fb btn">&emsp;Share</button></a></div> <div class="share"><a href="mailto:?subject=Anacortes Culture Camp 2018 | Calaska Culture&body=Check out this culture day that Calaska Culture is hosting: https://calaska.org/events/anacortes-culture-camp-2018.html"><button class="share-icon--email btn">&emsp;Email</button></a></div> </div> </div> </header> <main> <section class="event-details container grid"> <div class="grid__col is-12"> <h2 class="text-center section-title section-title--light-bg">Event Details</h2> </div> <!-- Event Image --> <div class="grid__col is-6 vertically-center"> <picture class="media"> <source srcset="/assets/img/events/anacortes-2018-desktop.jpg" media="(min-width: 600px)"> <img class="media" itemprop="image" src="/assets/img/events/sccc-2018-desktop.jpg" alt="Anacortes Culture Camp 2018"> </picture> </div> <!-- Event Details Table --> <div class="grid__col is-6"> <table class="content-text"> <tr class="grid"> <th class="grid__col is-2">When:</th> <td class="grid__col is-10"><time itemprop="startDate" datetime="2018-05-27T11:00:00-07:00">May 27, 2018 | 11AM</time> - <time itemprop="endDate" datetime="2018-05-27T17:00:00-08:00">6PM</time></td> </tr> <tr class="grid" itemprop="location" itemscope itemtype="http://schema.org/Place"> <th class="grid__col is-2">Where:</th> <td class="grid__col is-10"> <div itemprop="address" itemscope itemtype="http://schema.org/PostalAddress"> &nbsp; <span itemprop="streetAddress">4407 Glasgow Way</span>, <span itemprop="addressLocality">Anacortes</span> <span itemprop="addressRegion">WA</span> </td> </tr> <tr class="grid" itemprop="offers" itemscope itemtype="http://schema.org/Offer"> <th class="grid__col is-2">Price: <span itemprop="priceCurrency" content="USD"></span> <span itemprop="availability" content="inStock"></span> <span itemprop="url" content="/events/anacortes-culture-camp-2018.html"></span> </th> <td class="grid__col is-10">$<span itemprop="price">50</span> per person | $35 extra for large drums</td> </tr> <tr class="grid"> <th class="grid__col is-2">Pay:</th> <td class="grid__col is-10"> <!-- Specify different payment options for each number of people --> <div class="select-container"> <label for="numPeople">Number of People/Tickets</label> <select id="numPeople" name="numPeople" class="custom-select" onchange="updateTotalPrice(price)"> <option value="1" selected>1 Person - $50</option> <option value="2">2 People - $100</option> <option value="3">3 People - $150</option> <option value="4">4 People - $200</option> <option value="5">5 People - $250</option> </select> </div> <!-- Specify number of large drums --> <div class="select-container"> <label for="numLargeDrums">Number of Large Drums</label> <select id="numLargeDrums" name="numLargeDrums" class="custom-select" onchange="updateTotalPrice(price)"> <option value="0" selected>0 Large Drums - $0</option> <option value="1">1 Large Drums - $35</option> <option value="2">2 Large Drums - $70</option> <option value="3">3 Large Drums - $105</option> <option value="4">4 Large Drums - $140</option> <option value="5">5 Large Drums - $175</option> </select> </div> Total Price = <span id="totalCost">$50</span> <!-- Render paypal button --> <div id="paypal-button-container" class="vertically-center"> <script> function isValid() { return document.querySelector('#check').checked; } function onChangeCheckbox(handler) { document.querySelector('#check').addEventListener('change', handler); } function toggleValidationMessage() { document.querySelector('#msg').style.display = (isValid() ? 'none' : 'block'); } function toggleButton(actions) { return isValid() ? actions.enable() : actions.disable(); } paypal.Button.render({ env: 'production', // sandbox | production // Specify the style of the button style: { label: 'pay', size: 'small', // small | medium | large | responsive shape: 'rect', // pill | rect color: 'gold' // gold | blue | silver | black }, // PayPal Client IDs - replace with your own // Create a PayPal app: https://developer.paypal.com/developer/applications/create client: { sandbox: 'AQ4H5Fx6Tr_uIVMLwlat2AbOIuIjSWfnx3sUcAmkDGRcjCJy9VscFsQt9P3JrOKkNqObdNKR5Z5FVon7', production: 'Ae6xUrF9xyRFJ2Mhb_19rqV1Om_-cLs1BvIV_iPNcsLXHc0Mo2rw7WdkKEPleIGzKxW7HANvCfDIv7U2' }, // Show the buyer a 'Pay Now' button in the checkout flow commit: true, // payment() is called when the button is clicked payment: function (data, actions) { // Get cost of tickets var num_people = document.getElementById('numPeople').value; var ticket_cost = num_people * 50.00; var tickets = { name: "Calaska Culture Tickets", description: "Anacortes Calaska Culture Camp 2018 tickets.", quantity: num_people.toString(), price: "50", tax: "0.00", currency: "USD" }; // Get cost of large drums var num_large_drums = document.getElementById('numLargeDrums').value; var drum_cost = num_large_drums * 35.00; var drums = { name: "Large Drum", description: "20\" drum instead of 12\" drum", quantity: num_large_drums.toString(), price: "35", tax: "0.00", currency: "USD" }; // Calculate total cost var cost = ticket_cost + drum_cost; // Assemble Payment Items var paymentItems = []; if (tickets.quantity !== 0) { paymentItems.push(tickets); } if (drums.quantity > 0) { paymentItems.push(drums); } // Make a call to the REST api to create the payment return actions.payment.create({ payment: { transactions: [ { amount: { total: cost, currency: 'USD' }, description: 'Anacortes Calaska Culture Camp Tickets', item_list: { items: paymentItems }, } ] }, // Do not collect shipping address experience: { input_fields: { no_shipping: 1 } } }); }, // onAuthorize() is called when the buyer approves the payment onAuthorize: function (data, actions) { // Make a call to the REST api to execute the payment return actions.payment.execute().then(function () { var successText = 'Payment Complete! We\'ll see you May 27th.'; window.alert(successText); document.getElementById('paypal-button-container').innerText = successText; document.getElementById('paypal-button-container').classList.add('success-text'); }); } }, '#paypal-button-container'); </script> </div> <!-- End of paypal button --> </td> </tr> </table> </div> <!-- Additional Event Details --> <div class="grid__col is-6 content-text"> <p> Please be ready to choose your projects. The following projects are included with your ticket purchase. </p> <ol> <li>Small Deer Hide Drum</li> <li>Drum Stick</li> <li>Small Cedar Paddle</li> <li>Beading Project</li> <li>Devils Club Beaded Necklace</li> <li>Weaving Project</li> </ol> </div> <!-- Google Maps iframe in #gMAp delayed until 1 second after page load using inline script --> <div class="grid__col is-6"> <div id='gMap' class="media--embed"> </div> </div> </section> </main> <footer class="footer bg--primary"> <div class="container grid"> <div class="grid__col is-12--small is-4--medium is-4--large footer__col"> <div class="footer__title">Activities</div> <a href="../activities.html#drums">Drum Making</a> <br> <a href="../activities.html#paddles">Paddle Carving</a> <br> <a href="../activities.html#beads">Beading</a> <br> <a href="../activities.html#weaving">Weaving</a> </div> <div class="grid__col is-12--small is-4--medium is-4--large footer__col"> <div class="footer__title">About</div> <a href="../about.html">About Us</a> <br> <a href="../events/#upcoming-events">Upcoming Events</a> <br> <a href="../events/#past-events">Past Events</a> </div> <div class="grid__col is-12--small is-4--medium is-4--large footer__col"> <div class="footer__title">Contact</div> <ul class="list-unstyled list-unstyled--fa-icons"> <li class="footer__item-icon--notify"><a href="../#event-notifications">Get Event Notifications</a></li> <li class="footer__item-icon--email"><a href="mailto:calaskacc@gmail.com">CalaskaCC@gmail.com</a></li> <li class="footer__item-icon--address">Isleton, CA 95641</li> </ul> </div> </div> </footer> <script> var price = { tickets: function() { // Get cost of tickets var num_people = document.getElementById('numPeople').value; return num_people * 50; }, drums: function(){ // Get cost of large drums var num_large_drums = document.getElementById('numLargeDrums').value; return num_large_drums * 35; }, total: function(){ // Calculate total cost return price.tickets() + price.drums(); } } function updateTotalPrice(price) { var el = document.getElementById('totalCost'); el.innerText = '$' + price.total(); } </script> <script> // Defer loading of gMap window.addEventListener('load', function(){ window.setTimeout(function(){ var element = document.getElementById('gMap'); var frame = document.createElement('iframe'); frame.src = 'https://www.google.com/maps/embed/v1/place?q=4407+Glasgow+Way,+Anacortes,+WA,+USA&key=AIzaSyBFw0Qbyq9zTFTd-tUY6dZWTgaQzuU17R8'; frame.frameBorder = '0'; frame.scrolling = 'no'; frame.marginHeight = '0'; frame.marginWidth = '0'; element.appendChild(frame); },1000) // Timeout length }); </script> </body> </html>
{ "content_hash": "181e12f9efbe1dfb603869ac4c088d3d", "timestamp": "", "source": "github", "line_count": 356, "max_line_length": 307, "avg_line_length": 50.53651685393258, "alnum_prop": 0.482519037296426, "repo_name": "Doanvin/ak-native-culture", "id": "f74662ec3252e1fbe95abec7b095b004d8c60101", "size": "17991", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/events/anacortes-culture-camp-2018.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "41841" }, { "name": "HTML", "bytes": "268395" }, { "name": "JavaScript", "bytes": "73816" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "5b56a941d5f2c6fc4e0b799f602b02b6", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "da4de4e71f956c76739028f2c95c57d0b1563b39", "size": "174", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Penaeaceae/Penaea/Penaea dahlgrenii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import { Benchmark } from './Benchmark'; export declare class DelegatedBenchmark extends Benchmark { private _executeCallback; constructor(name: string, description: string, executeCallback: (callback: (err?: any) => void) => void); execute(callback: (err?: any) => void): void; }
{ "content_hash": "43101a1a79be593069bb653074ac1cb4", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 109, "avg_line_length": 48.833333333333336, "alnum_prop": 0.7030716723549488, "repo_name": "pip-benchmark/pip-benchmark-node", "id": "190c776a53b0b90a2bcf1067004e77546307bc59", "size": "293", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "obj/src/DelegatedBenchmark.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "111" }, { "name": "TypeScript", "bytes": "161892" } ], "symlink_target": "" }
<HTML> <!-- Copyright (c) Jeremy Siek 2000 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) --> <Head> <Title>AdjacencyGraph</Title> <BODY BGCOLOR="#ffffff" LINK="#0000ee" TEXT="#000000" VLINK="#551a8b" ALINK="#ff0000"> <IMG SRC="../../../boost.png" ALT="C++ Boost" width="277" height="86"> <BR Clear> <H2><A NAME="concept:AdjacencyGraph"></A> AdjacencyGraph </H2> The AdjacencyGraph concept provides an interface for efficient access of the adjacent vertices to a vertex in a graph. This is quite similar to the <a href="./IncidenceGraph.html">IncidenceGraph</a> concept (the target of an out-edge is an adjacent vertex). Both concepts are provided because in some contexts there is only concern for the vertices, whereas in other contexts the edges are also important. <H3>Refinement of</H3> <a href="Graph.html">Graph</a> <h3>Notation</h3> <Table> <TR> <TD><tt>G</tt></TD> <TD>A type that is a model of Graph.</TD> </TR> <TR> <TD><tt>g</tt></TD> <TD>An object of type <tt>G</tt>.</TD> </TR> <TR> <TD><tt>v</tt></TD> <TD>An object of type <tt>boost::graph_traits&lt;G&gt;::vertex_descriptor</tt>.</TD> </TR> </table> <H3>Associated Types</H3> <Table border> <tr> <td><tt>boost::graph_traits&lt;G&gt;::traversal_category</tt><br><br> This tag type must be convertible to <tt>adjacency_graph_tag</tt>. </td> </tr> <TR> <TD><pre>boost::graph_traits&lt;G&gt;::adjacency_iterator</pre> An adjacency iterator for a vertex <i>v</i> provides access to the vertices adjacent to <i>v</i>. As such, the value type of an adjacency iterator is the vertex descriptor type of its graph. An adjacency iterator must meet the requirements of <a href="../../utility/MultiPassInputIterator.html">MultiPassInputIterator</a>. </TD> </TR> </table> <h3>Valid Expressions</h3> <table border> <tr> <td><a name="sec:adjacent-vertices"><TT>adjacent_vertices(v,&nbsp;g)</TT></a></TD> <TD> Returns an iterator-range providing access to the vertices adjacent to vertex <TT>v</TT> in graph <TT>g</TT>.<a href="#1">[1]</a> <br> Return type: <TT>std::pair&lt;adjacency_iterator,&nbsp;adjacency_iterator&gt;</TT> </TD> </TR> </table> <H3>Complexity guarantees</H3> The <TT>adjacent_vertices()</TT> function must return in constant time. <H3>See Also</H3> <a href="./graph_concepts.html">Graph concepts</a>, <a href="./adjacency_iterator.html"><tt>adjacency_iterator</tt></a> <H3>Concept Checking Class</H3> <PRE> template &lt;class G&gt; struct AdjacencyGraphConcept { typedef typename boost::graph_traits&lt;G&gt;::adjacency_iterator adjacency_iterator; void constraints() { BOOST_CONCEPT_ASSERT(( MultiPassInputIteratorConcept&lt;adjacency_iterator&gt; )); p = adjacent_vertices(v, g); v = *p.first; const_constraints(g); } void const_constraints(const G&amp; g) { p = adjacent_vertices(v, g); } std::pair&lt;adjacency_iterator,adjacency_iterator&gt; p; typename boost::graph_traits&lt;G&gt;::vertex_descriptor v; G g; }; </PRE> <h3>Design Rationale</h3> The AdjacencyGraph concept is somewhat frivolous since <a href="./IncidenceGraph.html">IncidenceGraph</a> really covers the same functionality (and more). The AdjacencyGraph concept exists because there are situations when <tt>adjacent_vertices()</tt> is more convenient to use than <tt>out_edges()</tt>. If you are constructing a graph class and do not want to put in the extra work of creating an adjacency iterator, have no fear. There is an adaptor class named <a href="./adjacency_iterator.html"> <tt>adjacency_iterator</tt></a> that you can use to create an adjacency iterator out of an out-edge iterator. <h3>Notes</h3> <a name="1">[1]</a> The case of a <I>multigraph</I> (where multiple edges can connect the same two vertices) brings up an issue as to whether the iterators returned by the <TT>adjacent_vertices()</TT> function access a range that includes each adjacent vertex once, or whether it should match the behavior of the <TT>out_edges()</TT> function, and access a range that may include an adjacent vertex more than once. For now the behavior is defined to match that of <TT>out_edges()</TT>, though this decision may need to be reviewed in light of more experience with graph algorithm implementations. <br> <HR> <TABLE> <TR valign=top> <TD nowrap>Copyright &copy; 2000-2001</TD><TD> <A HREF="http://www.boost.org/people/jeremy_siek.htm">Jeremy Siek</A>, Indiana University (<A HREF="mailto:jsiek@osl.iu.edu">jsiek@osl.iu.edu</A>) </TD></TR></TABLE> </BODY> </HTML>
{ "content_hash": "f19952d6937e77d8e6ac1d57adcfd05c", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 146, "avg_line_length": 27.92814371257485, "alnum_prop": 0.7034734133790738, "repo_name": "arangodb/arangodb", "id": "097ac90c532d8242220605495397263bfc27d5af", "size": "4664", "binary": false, "copies": "4", "ref": "refs/heads/devel", "path": "3rdParty/boost/1.78.0/libs/graph/doc/AdjacencyGraph.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "61827" }, { "name": "C", "bytes": "311036" }, { "name": "C++", "bytes": "35149373" }, { "name": "CMake", "bytes": "387268" }, { "name": "CSS", "bytes": "210549" }, { "name": "EJS", "bytes": "232160" }, { "name": "HTML", "bytes": "23114" }, { "name": "JavaScript", "bytes": "33841256" }, { "name": "LLVM", "bytes": "15003" }, { "name": "NASL", "bytes": "381737" }, { "name": "NSIS", "bytes": "47138" }, { "name": "Pascal", "bytes": "75391" }, { "name": "Perl", "bytes": "9811" }, { "name": "PowerShell", "bytes": "6806" }, { "name": "Python", "bytes": "190515" }, { "name": "SCSS", "bytes": "255542" }, { "name": "Shell", "bytes": "133576" }, { "name": "TypeScript", "bytes": "179074" }, { "name": "Yacc", "bytes": "79620" } ], "symlink_target": "" }
<?php namespace PW\UserBundle\EventListener; use Symfony\Component\DependencyInjection\ContainerAware, Doctrine\ODM\MongoDB\Event\LifecycleEventArgs, Doctrine\ODM\MongoDB\Event\PreUpdateEventArgs, PW\UserBundle\Document\Follow, PW\UserBundle\Document\User, PW\BoardBundle\Document\Board; class FollowListener extends ContainerAware { /** * @var \PW\UserBundle\Model\FollowManager */ protected $followManager; /** * @var \PW\BoardBundle\Model\BoardManager */ protected $boardManager; /** * @var \PW\ApplicationBundle\Model\EventManager */ protected $eventManager; /** * @param LifecycleEventArgs $args */ public function prePersist(LifecycleEventArgs $args) { $follow = $args->getDocument(); if ($follow instanceOf Follow) { $follower = $follow->getFollower(); $target = $follow->getTarget(); // // User if ($target instanceOf User) { // Is target following follower? $inverse = $this->getFollowManager()->isFollowing($target, $follower); if ($inverse) { $follow->setIsFriend(true); } } // // Board if ($target instanceOf Board) { $target->incFollowerCount(); } } } /** * @param LifecycleEventArgs $args */ public function postPersist(LifecycleEventArgs $args) { $follow = $args->getDocument(); if ($follow instanceOf Follow) { $follower = $follow->getFollower(); $target = $follow->getTarget(); // // User if ($target instanceOf User) { if ($follow->getIsFriend()) { // Is target following follower? $inverse = $this->getFollowManager()->isFollowing($target, $follower); if ($inverse && !$inverse->getIsFriend()) { $inverse->setIsFriend(true); $this->getFollowManager()->update($inverse); } } } } } /** * @param PreUpdateEventArgs $args */ public function preUpdate(PreUpdateEventArgs $args) { $follow = $args->getDocument(); if ($follow instanceOf Follow) { // // Deleted if ($args->hasChangedField('deleted')) { $deleted = $args->getNewValue('deleted'); if (!empty($deleted)) { $target = $follow->getTarget(); // // User if ($target instanceOf User) { if ($follow->getIsFriend()) { $follow->setIsFriend(false); } } // // Board if ($target instanceOf Board) { $target->decFollowerCount(); } } } // We are doing a update, so we must force Doctrine to update the // changeset in case we changed something above $dm = $args->getDocumentManager(); $uow = $dm->getUnitOfWork(); $meta = $dm->getClassMetadata(get_class($follow)); $uow->recomputeSingleDocumentChangeSet($meta, $follow); } } /** * Emit any events to the Event manager after a successful update. * * @param LifecycleEventArgs $args dunno */ public function postUpdate(LifecycleEventArgs $args) { $follow = $args->getDocument(); if ($follow instanceOf Follow) { // // Deleted if ($follow->getDeleted()) { $follower = $follow->getFollower(); $target = $follow->getTarget(); // // User if ($target instanceOf User) { // Is target following follower? $inverse = $this->getFollowManager()->isFollowing($target, $follower); if ($inverse && $inverse->getIsFriend()) { $inverse->setIsFriend(false); $this->getFollowManager()->update($inverse); } // Find all instances where $follower follows a board by $target $boardsFollowers = $this->getFollowManager()->getRepository() ->findByFollowerAndUser($follower, $target) ->eagerCursor(true) ->getQuery()->execute(); // Unfollow this User's Boards foreach ($boardsFollowers as $boardFollower /* @var $boardFollower Follow */) { $boardFollower->setNoEmit(true); $this->getFollowManager()->delete($boardFollower, $follow->getDeletedBy(), true, false); } $this->getFollowManager()->flush(); } } } } /** * Deleting all activities and notifications after removing follow * **/ public function preRemove(LifecycleEventArgs $args) { $follow = $args->getDocument(); $dm = $this->container->get('doctrine_mongodb.odm.document_manager'); $activity_manager = $this->container->get('pw_activity.activity_manager'); $notification_manager = $this->container->get('pw_activity.notification_manager'); if ($follow instanceOf Follow) { $activity_manager ->getRepository() ->createQueryBuilder() ->remove() //->field('target')->references($follow) ->field('target.$id')->equals(new \MongoId($follow->getId())) ->field('target.$ref')->equals('follows') ->getQuery() ->execute(); $notification_manager ->getRepository() ->createQueryBuilder() ->remove() //->field('target')->references($follow) ->field('target.$id')->equals(new \MongoId($follow->getId())) ->field('target.$ref')->equals('follows') ->getQuery() ->execute(); $target = $follow->getTarget(); if ($target instanceof User) { // also remove follows for collections of target User $follower = $follow->getFollower(); $this->getFollowManager()->getRepository() ->createQueryBuilder() ->remove() ->field('follower')->references($follower) ->field('user')->references($target) ->field('target.$ref')->equals('boards') ->getQuery() ->execute(); } } } /** * @return \PW\UserBundle\Model\FollowManager */ public function getFollowManager() { if ($this->followManager == null) { $this->followManager = $this->container->get('pw_user.follow_manager'); } return $this->followManager; } /** * @return \PW\BoardBundle\Model\BoardManager */ public function getBoardManager() { if ($this->boardManager == null) { $this->boardManager = $this->container->get('pw_board.board_manager'); } return $this->boardManager; } }
{ "content_hash": "4c36a7ee683e55d2c579a43021f108e5", "timestamp": "", "source": "github", "line_count": 238, "max_line_length": 112, "avg_line_length": 33.214285714285715, "alnum_prop": 0.47324478178368123, "repo_name": "SparkRebel/sparkrebel.com", "id": "c139c4dc66a056b0a149e45bf5dd180fd70e1159", "size": "7905", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/PW/UserBundle/EventListener/FollowListener.php", "mode": "33188", "license": "mit", "language": [ { "name": "DOT", "bytes": "6081" }, { "name": "JavaScript", "bytes": "464381" }, { "name": "PHP", "bytes": "2009857" }, { "name": "Shell", "bytes": "51995" } ], "symlink_target": "" }
<?php namespace Ph2p\Application; use Ph2p\Application\Commands\HashCommand; use Ph2p\Application\Commands\NodeCommand; use Ph2p\Application\Commands\ServerCommand; use Symfony\Component\Console\Application; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class Ph2p extends Application { const NAME = 'PH2P'; const VERSION = '1.0'; public function __construct() { parent::__construct(static::NAME, static::VERSION); } public function run(InputInterface $input = null, OutputInterface $output = null) { $this->add(new NodeCommand()); $this->add(new HashCommand()); $this->add(new ServerCommand()); parent::run($input, $output); } }
{ "content_hash": "12db412e3b722b18437a28b0361924ef", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 85, "avg_line_length": 26.413793103448278, "alnum_prop": 0.6971279373368147, "repo_name": "alrik11es/ph2p", "id": "ef2a84246d3145f6098fddeef0f35eb8dbcf5b36", "size": "766", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Application/Ph2p.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "10705" } ], "symlink_target": "" }
<div class="row m-b"> <div class="col-md-12"> <h4> Simple Tracker </h4> <span class="text-muted"> Simple tracker is a simple issue tracking system that can also be used as a blogging or gallery application. It is aimed at those who, like the author, need an easy system to record, prioritise, assign and resolve issues without the complexities of many of the systems out there. </span> <span class="block m-t"> Simple Tracker is aimed primarily at people with a good level of programming knowledge. This is by no means a finished piece of work. Please make improvements for your own use or better still, for sharing. </span> </div> </div> <div class="row"> <div class="col-md-12"> <h4> License </h4> <pre> Copyright (C) 2015 Lisol Ltd, info [at] lisol [dot] co [dot] uk This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. </pre> </div> </div>
{ "content_hash": "7bcbbd8a904ebbf1e6c411cb8ea4c249", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 211, "avg_line_length": 35.627906976744185, "alnum_prop": 0.6932114882506527, "repo_name": "justinnjoh/trackeros", "id": "7823bd7cd0ab16b8b8c2e753e0fb293f11f5512f", "size": "1533", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/views/home/about.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2346" }, { "name": "JavaScript", "bytes": "42569" }, { "name": "PHP", "bytes": "342280" } ], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>windows::object_handle_service::cancel</title> <link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../../index.html" title="Boost.Asio"> <link rel="up" href="../windows__object_handle_service.html" title="windows::object_handle_service"> <link rel="prev" href="async_wait.html" title="windows::object_handle_service::async_wait"> <link rel="next" href="close.html" title="windows::object_handle_service::close"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="async_wait.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../windows__object_handle_service.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="close.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="boost_asio.reference.windows__object_handle_service.cancel"></a><a class="link" href="cancel.html" title="windows::object_handle_service::cancel">windows::object_handle_service::cancel</a> </h4></div></div></div> <p> <a class="indexterm" name="idm45464954240704"></a> Cancel all asynchronous operations associated with the handle. </p> <pre class="programlisting"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="identifier">cancel</span><span class="special">(</span> <span class="identifier">implementation_type</span> <span class="special">&amp;</span> <span class="identifier">impl</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&amp;</span> <span class="identifier">ec</span><span class="special">);</span> </pre> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2016 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="async_wait.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../windows__object_handle_service.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="close.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "702b73832f95db154c6c1ba6e1d1c61b", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 462, "avg_line_length": 75.18867924528301, "alnum_prop": 0.6311166875784191, "repo_name": "FFMG/myoddweb.piger", "id": "b94473fc4608820f9f08f706c639ca089e1cf4c4", "size": "3985", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "myodd/boost/libs/asio/doc/html/boost_asio/reference/windows__object_handle_service/cancel.html", "mode": "33188", "license": "mit", "language": [ { "name": "Ada", "bytes": "89079" }, { "name": "Assembly", "bytes": "399228" }, { "name": "Batchfile", "bytes": "93889" }, { "name": "C", "bytes": "32256857" }, { "name": "C#", "bytes": "197461" }, { "name": "C++", "bytes": "200544641" }, { "name": "CMake", "bytes": "192771" }, { "name": "CSS", "bytes": "441704" }, { "name": "CWeb", "bytes": "174166" }, { "name": "Common Lisp", "bytes": "24481" }, { "name": "Cuda", "bytes": "52444" }, { "name": "DIGITAL Command Language", "bytes": "33549" }, { "name": "DTrace", "bytes": "2157" }, { "name": "Fortran", "bytes": "1856" }, { "name": "HTML", "bytes": "181677643" }, { "name": "IDL", "bytes": "14" }, { "name": "Inno Setup", "bytes": "9647" }, { "name": "JavaScript", "bytes": "705756" }, { "name": "Lex", "bytes": "1231" }, { "name": "Lua", "bytes": "3332" }, { "name": "M4", "bytes": "259214" }, { "name": "Makefile", "bytes": "1262318" }, { "name": "Max", "bytes": "36857" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "Objective-C", "bytes": "2167778" }, { "name": "Objective-C++", "bytes": "630" }, { "name": "PHP", "bytes": "59030" }, { "name": "PLSQL", "bytes": "22886" }, { "name": "Pascal", "bytes": "75208" }, { "name": "Perl", "bytes": "42080" }, { "name": "PostScript", "bytes": "13803" }, { "name": "PowerShell", "bytes": "11781" }, { "name": "Python", "bytes": "30377308" }, { "name": "QML", "bytes": "593" }, { "name": "QMake", "bytes": "16692" }, { "name": "Rebol", "bytes": "354" }, { "name": "Rich Text Format", "bytes": "6743" }, { "name": "Roff", "bytes": "55661" }, { "name": "Ruby", "bytes": "5532" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "783974" }, { "name": "TSQL", "bytes": "1201" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "32117" }, { "name": "Visual Basic", "bytes": "70" }, { "name": "XSLT", "bytes": "552736" }, { "name": "Yacc", "bytes": "19623" } ], "symlink_target": "" }
var ape = require('../ape.js'); var moduleManager = require('../modules/module_manager/module_manager.js'); var express = moduleManager.requireNodeModule('express'); var app = express(); var utils = require('../modules/utils/utils.js'); var async = moduleManager.requireNodeModule('async'); var logger = require("../modules/log_manager/log_manager.js"); var resp = require('../modules/response_manager/response_manager.js'); var errorMap = require('../modules/utils/errors.js'); var x3d = require('../modules/utils/errors.js');; app.get('/', function(req, res, next) { var respObj = new resp(req); respObj.setDescription('ApertusVR API Home'); res.send(respObj.toJSonString()); }); app.post('/setfastai', function (req, res, next) { var respObj = new resp(req); respObj.setDescription('Sets properties on several objects at the same time.'); if (!respObj.validateHttpParams(req, res)) { res.status(400).send(respObj.toJSonString()); return; } if (!req.body.classes) { if (!req.body.x) { logger.error('no x array in http req body.data'); var errObj = errorMap.items.dataNotPresented; errObj.message = 'Items array is not presented in Http Request body.data.'; respObj.addErrorItem(errObj); res.send(respObj.toJSonString()); return; } if (!req.body.y) { logger.error('no y array in http req body.data'); var errObj = errorMap.items.dataNotPresented; errObj.message = 'Items array is not presented in Http Request body.data.'; respObj.addErrorItem(errObj); res.send(respObj.toJSonString()); return; } if (!req.body.z) { logger.error('no z array in http req body.data'); var errObj = errorMap.items.dataNotPresented; errObj.message = 'Items array is not presented in Http Request body.data.'; respObj.addErrorItem(errObj); res.send(respObj.toJSonString()); return; } var respObj = new resp(req); for (var i = 0; i < req.body.x.length; i++) { var x_pos = 75*req.body.x[i]; var y_pos = 120*req.body.y[i]+5; var z_pos = 65*req.body.z[i]; console.log('x: ' + x_pos + ' y: ' + y_pos + ' z: ' + z_pos); ape.nbind.JsBindManager().getNode('dsa'+i, function (error, obj) { if (error) { respObj.addErrorItem({ name: 'invalidCast', msg: obj, code: 666 }); } else { obj.setPosition(ape.nbind.Vector3(x_pos, y_pos, z_pos)); } }); ape.nbind.JsBindManager().getNode('aaa' + i, function (error, obj) { if (error) { respObj.addErrorItem({ name: 'invalidCast', msg: obj, code: 666 }); } else { obj.setPosition(ape.nbind.Vector3(x_pos, y_pos+2, z_pos)); } }); } } else { var classes = req.body.classes; //number of classes var parentBox = ape.nbind.JsBindManager().createNode('xBox'); parentBox.setPosition(ape.nbind.Vector3(-20, 0, 10)); var boxSetObj = ape.nbind.JsBindManager().createBox('xAxis'); var dimensionsAtrr = ape.nbind.Vector3(0.2, 200, 0.2); boxSetObj.setParameters(dimensionsAtrr); boxSetObj.setParentNodeJsPtr(parentBox); var xMat = ape.nbind.JsBindManager().createManualMaterial("xmat" ); var diffuseColor = ape.nbind.Color(1, 0, 0, 1); xMat.setDiffuseColor(diffuseColor); boxSetObj.setManualMaterial(xMat); var parentNode1 = ape.nbind.JsBindManager().createNode('xtext' ); parentNode1.setPosition(ape.nbind.Vector3(-20, 100, 10)); var textGeometry = ape.nbind.JsBindManager().createText("Loss"); textGeometry.setParentNodeJsPtr(parentNode1); var parentBox2 = ape.nbind.JsBindManager().createNode('yBox'); parentBox2.setPosition(ape.nbind.Vector3(-20, 2, 10)); var boxSetObj = ape.nbind.JsBindManager().createBox('yAxis'); var dimensionsAtrr = ape.nbind.Vector3(0.2, 0.2, 200); boxSetObj.setParameters(dimensionsAtrr); boxSetObj.setParentNodeJsPtr(parentBox2); var yMat = ape.nbind.JsBindManager().createManualMaterial("ymat"); var diffuseColor = ape.nbind.Color(0, 0, 1, 1); yMat.setDiffuseColor(diffuseColor); boxSetObj.setManualMaterial(yMat); var parentNode1 = ape.nbind.JsBindManager().createNode('ytext1'); parentNode1.setPosition(ape.nbind.Vector3(-20, 2, 95)); var textGeometry = ape.nbind.JsBindManager().createText("Cat Prediction"); textGeometry.setParentNodeJsPtr(parentNode1); var parentNode1 = ape.nbind.JsBindManager().createNode('ytext2'); parentNode1.setPosition(ape.nbind.Vector3(-20, 2, -75)); var textGeometry = ape.nbind.JsBindManager().createText("Dog Prediction"); textGeometry.setParentNodeJsPtr(parentNode1); for (var i = 0; i < req.body.IDs.length; i++) { var image_path = req.body.IDs[i]; // paths to the validation set images var parentNode = ape.nbind.JsBindManager().createNode('dsa'+i); parentNode.setPosition(ape.nbind.Vector3(10, 30, 10)); //parentNode.setOrientation(new ape.nbind.Quaternion(0.7071, -0.7071, 0, 0)); var manualMaterial = ape.nbind.JsBindManager().createManualMaterial("sda" + i); var fileTexture = ape.nbind.JsBindManager().createFileTexture(image_path); fileTexture.setFileName(image_path); manualMaterial.setPassTexture(fileTexture); //var parentNode1 = ape.nbind.JsBindManager().createNode('aaa' + i); //parentNode1.setPosition(ape.nbind.Vector3(10, 30, 10)); //var text = ""; //if (image_path[image_path.length - 5] == 1) // text = "Neoplastic"; //else text = "NotNeoplastic"; //var textGeometry = ape.nbind.JsBindManager().createText(text + i); //textGeometry.setParentNodeJsPtr(parentNode1); //textGeometry.setCaption(text); var plane = ape.nbind.JsBindManager().createPlane('das' + i); var numSeg = ape.nbind.Vector2(2, 2); var size = ape.nbind.Vector2(10, 10); var tile = ape.nbind.Vector2(1, 1); plane.setParameters(numSeg, size, tile); plane.setParentNodeJsPtr(parentNode); plane.setManualMaterial(manualMaterial); } //var matItem = currentItem.siblings('Appearance').first().children('Material').first(); //self.parseMaterial(matItem, boxSetObj); /*if (parentNodeObj) { boxSetObj.setParentNodeJsPtr(parentNodeObj); log(' - this: ' + boxSetObj.getName() + ' - parentNode: ' + parentNodeObj.getName()); }*/ } }); app.post('/setproperties', function(req, res, next) { var respObj = new resp(req); respObj.setDescription('Sets properties on several objects at the same time.'); if (!respObj.validateHttpParams(req, res)) { res.status(400).send(respObj.toJSonString()); return; } if (!req.body.data) { logger.error('no data in http req body'); var errObj = errorMap.items.dataNotPresented; errObj.message = 'Data object is not presented in Http Request body.'; respObj.addErrorItem(errObj); res.send(respObj.toJSonString()); return; } if (!req.body.data.items) { logger.error('no items array in http req body.data'); var errObj = errorMap.items.dataNotPresented; errObj.message = 'Items array is not presented in Http Request body.data.'; respObj.addErrorItem(errObj); res.send(respObj.toJSonString()); return; } for (var i = 0; i < req.body.data.items.length; i++) { var item = req.body.data.items[i]; if (!item.type || !item.name) { logger.error('item has no type || name property'); continue; } if (item.type == "node") { ape.nbind.JsBindManager().getNode(item.name, function(error, obj) { if (error) { respObj.addErrorItem({ name: 'invalidCast', msg: obj, code: 666 }); } else { if (item.properties.orientation) { var q = utils.quaternionFromAngleAxis(item.properties.orientation.angle, item.properties.orientation.axis); obj.setOrientation(q); } } }); } else if (item.type === "gripper") { var mGripperLeftRootNodeInitialOrientation = ape.nbind.Quaternion(-0.99863, 0, 0, 0.0523337); var mGripperRightRootNodeInitialOrientation = ape.nbind.Quaternion(-0.99863, 0, 0, 0.0523337); var mGripperLeftHelperNodeInitialOrientation = ape.nbind.Quaternion(-0.418964, 0, 0, 0.908003); var mGripperRightHelperNodeInitialOrientation = ape.nbind.Quaternion(-0.418964, 0, 0, 0.908003); var mGripperLeftEndNodeInitialOrientation = ape.nbind.Quaternion(0.818923, 0, 0, 0.573904); var mGripperRightEndNodeInitialOrientation = ape.nbind.Quaternion(0.818923, 0, 0, 0.573904); var mGripperLeftRootOrientation = ape.nbind.Quaternion(1, 0, 0, 0); var mGripperRightRootOrientation = ape.nbind.Quaternion(1, 0, 0, 0); var gripperMaxValue = 255; var gripperMinValue = 0; var gripperCurrentValue = item.properties.value; var degreeStep = 45.0 / gripperMaxValue; var axis = ape.nbind.Vector3(0, 0, 1); var degree = ape.nbind.Degree(gripperCurrentValue * degreeStep) var orientation = ape.nbind.Quaternion(); orientation.FromAngleAxis(ape.nbind.Radian(degree.toRadian()), axis); async.waterfall( [ function (callback) { ape.nbind.JsBindManager().getNode('JOINT(Rotational)(gripR1)12ur10Gripper', function (error, obj) { if (error) { callback({ name: 'invalidCast', msg: obj, code: 666 }); } else { mGripperLeftRootOrientation = mGripperLeftRootNodeInitialOrientation.product(orientation); obj.setOrientation(mGripperLeftRootOrientation); callback(null); } }); }, function (callback) { ape.nbind.JsBindManager().getNode('JOINT(Rotational)(gripR1)18ur10Gripper', function (error, obj) { if (error) { callback({ name: 'invalidCast', msg: obj, code: 666 }); } else { mGripperRightRootOrientation = mGripperRightRootNodeInitialOrientation.product(orientation); obj.setOrientation(mGripperRightRootOrientation); callback(null); } }); }, function (callback) { ape.nbind.JsBindManager().getNode('JOINT(Rotational)(gripR5)16ur10Gripper', function (error, obj) { if (error) { callback({ name: 'invalidCast', msg: obj, code: 666 }); } else { obj.setOrientation(mGripperLeftHelperNodeInitialOrientation.product(orientation)); callback(null); } }); }, function (callback) { ape.nbind.JsBindManager().getNode('JOINT(Rotational)(gripR5)22ur10Gripper', function (error, obj) { if (error) { callback({ name: 'invalidCast', msg: obj, code: 666 }); } else { obj.setOrientation(mGripperRightHelperNodeInitialOrientation.product(orientation)); callback(null); } }); }, function (callback) { ape.nbind.JsBindManager().getNode('JOINT(Rotational)(gripR3)14ur10Gripper', function (error, obj) { if (error) { callback({ name: 'invalidCast', msg: obj, code: 666 }); } else { obj.setOrientation(mGripperLeftEndNodeInitialOrientation.product(mGripperLeftRootOrientation.Inverse())); callback(null); } }); }, function (callback) { ape.nbind.JsBindManager().getNode('JOINT(Rotational)(gripR3)20ur10Gripper', function (error, obj) { if (error) { callback({ name: 'invalidCast', msg: obj, code: 666 }); } else { obj.setOrientation(mGripperRightEndNodeInitialOrientation.product(mGripperRightRootOrientation.Inverse())); callback(null); } }); } ], function (err, results) { if (err) { logger.error('error: ', err); respObj.addErrorItem(err); } } ); } else if (item.type == "text") { ape.nbind.JsBindManager().getText(item.name, function (error, obj) { if (error) { respObj.addErrorItem({ name: 'invalidCast', msg: obj, code: 666 }); } else { if (item.properties && item.properties.caption) { obj.setCaption(item.properties.caption); } } }); } } respObj.addEventItem({ group: 'PROPERTIES', type: 'PROPERTIES_SET', subjectName: '' }); res.send(respObj.toJSonString()); }); module.exports = app;
{ "content_hash": "45425c0e3aa87ad0156ba8296b490fdb", "timestamp": "", "source": "github", "line_count": 346, "max_line_length": 115, "avg_line_length": 34.554913294797686, "alnum_prop": 0.666610906657745, "repo_name": "MTASZTAKI/ApertusVR", "id": "de961ccebac1c35134097b912836559ff087c3d5", "size": "13026", "binary": false, "copies": "1", "ref": "refs/heads/0.9", "path": "plugins/languageAPI/jsAPI/nodeJsPlugin/js/api/index.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": "" }
package com.roottony.gradleandroidmaven; public class HelloMavenLibrary { private final static String HELLO_MESSAGE = "Hello from local repo library!"; public String sayHello() { return HELLO_MESSAGE; } }
{ "content_hash": "0040734f8b593ee6acdce1695b826859", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 81, "avg_line_length": 20.727272727272727, "alnum_prop": 0.7149122807017544, "repo_name": "roottony/gradle-android-project", "id": "2bc2181a6bc249dff2b7241b086d7b30ca80f180", "size": "228", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GradleAndroidProject/prebuilt/sample-maven-uploaded-library/src/main/java/com/roottony/gradleandroidmaven/HelloMavenLibrary.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "1406" }, { "name": "Java", "bytes": "1144" }, { "name": "Shell", "bytes": "2314" } ], "symlink_target": "" }
<!-- ~ Copyright 2016 Cnlyml ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <div class="apiDetail"> <div> <h2><span>Function(event, treeId, treeNode)</span><span class="path">setting.callback.</span>onExpand</h2> <h3>概述<span class="h3_info">[ 依赖 <span class="highlight_green">jquery.ztree.core</span> 核心 js ]</span></h3> <div class="desc"> <p></p> <div class="longdesc"> <p>用于捕获节点被展开的事件回调函数</p> <p class="highlight_red">如果设置了 setting.callback.beforeExpand 方法,且返回 false,将无法触发 onExpand 事件回调函数。</p> <p>默认值:null</p> </div> </div> <h3>Function 参数说明</h3> <div class="desc"> <h4><b>event</b><span>js event 对象</span></h4> <p>标准的 js event 对象</p> <h4 class="topLine"><b>treeId</b><span>String</span></h4> <p>对应 zTree 的 <b class="highlight_red">treeId</b>,便于用户操控</p> <h4 class="topLine"><b>treeNode</b><span>JSON</span></h4> <p>被展开的节点 JSON 数据对象</p> </div> <h3>setting & function 举例</h3> <h4>1. 每次展开节点后, 弹出该节点的 tId、name 的信息</h4> <pre xmlns=""><code>function zTreeOnExpand(event, treeId, treeNode) { alert(treeNode.tId + ", " + treeNode.name); }; var setting = { callback: { onExpand: zTreeOnExpand } }; ......</code></pre> </div> </div>
{ "content_hash": "2039038489f5dbf62330f045d879819b", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 108, "avg_line_length": 33.9, "alnum_prop": 0.6707964601769911, "repo_name": "cnlyml/summer", "id": "6198fb0e225f7a1d3c07ac2316a9ba485a7138cc", "size": "1897", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "src/main/webapp/resources/js/plugins/zTree/api/cn/setting.callback.onExpand.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "601208" }, { "name": "Groovy", "bytes": "981" }, { "name": "HTML", "bytes": "1292074" }, { "name": "Java", "bytes": "262081" }, { "name": "JavaScript", "bytes": "1271778" }, { "name": "PHP", "bytes": "2830" } ], "symlink_target": "" }
<lists-frame list="list"> <form class="form-horizontal" role="form" name="newList" ng-submit="create(newList)"> <div class="row"> <div class="col-md-6"> <div class="form-group" ng-class="{'has-error': newList.label.$invalid}"> <label class="col-sm-3 control-label" for="label">Label</label> <div class="col-sm-9"> <input type="text" class="form-control" id="label" name="label" ng-model="list.label" placeholder="The list's label"> <p class="help-block" ng-show="newList.label.$invalid" ng-bind="newList.label.$message"></p> </div> </div> <div class="form-group"> <div class="col-sm-offset-3 col-sm-9"> <div class="checkbox"> <label> <input type="checkbox" ng-model="list.public"> Publicly visible </label> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-3 col-sm-9"> <button type="submit" class="btn btn-primary" ng-disabled="!canCreate()">Create</button> </div> </div> </div> </div> </form> </lists-frame>
{ "content_hash": "9cba57b55a40396d701881079943503b", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 104, "avg_line_length": 36.696969696969695, "alnum_prop": 0.5243600330305532, "repo_name": "mgax/aleph", "id": "d898a617bc782c70971d585a2c8e89e8e8453027", "size": "1212", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "aleph/static/templates/lists_new.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "47806" }, { "name": "HTML", "bytes": "35082" }, { "name": "JavaScript", "bytes": "32062" }, { "name": "Makefile", "bytes": "212" }, { "name": "Mako", "bytes": "412" }, { "name": "Python", "bytes": "99725" } ], "symlink_target": "" }
'use strict'; var getJumpControl = require('../mixin/get-jump-control'); var async = require('async'); function pathControl(url, data) { //null //{ // isLoged: false, //} var arr = url.split('/'); arr.forEach(function (item, i) { arr[i] = item.split('?')[0]; }); var lastElement = arr[arr.length - 1]; //dashboard.html var redirectionAddress; var needRedirect = false; var jumpControl = getJumpControl(data); jumpControl.forEach((item) => { //当在originPath中检索出存在某一特定的html时 并且condition为真时就跳转 if (~item.originPath.indexOf(lastElement) && item.condition) { redirectionAddress = item.targetPath; needRedirect = true; } }); return { needRedirect: needRedirect, targetPath: redirectionAddress }; } module.exports = function (req, res, next) { var userId; async.parallel({ isLoged: function (done) { done(null, Boolean(req.session.user)); } }, function (err, data) { //console.log(data); //{ // isLoged: false //} //console.log(req.url); // '/dashboard.html' var result = pathControl(req.url, data); if (result.needRedirect) { res.redirect(result.targetPath); } else { next(); } }); };
{ "content_hash": "213122f0c3f275e0b6c597295ed6d512", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 66, "avg_line_length": 18.205882352941178, "alnum_prop": 0.6090468497576736, "repo_name": "sialvsic/time-machine", "id": "7f60bd4277979a6aa22dbff284343d1804449861", "size": "1282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "middleware/session-check.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "402273" }, { "name": "HTML", "bytes": "17357" }, { "name": "JavaScript", "bytes": "36319857" } ], "symlink_target": "" }
package org.aws4j.data.dynamo.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention( RetentionPolicy.RUNTIME ) @Target( { ElementType.FIELD, ElementType.METHOD} ) public @interface DynamoIgnore { public String by(); }
{ "content_hash": "f529b0c6c6aad6dbfbab80fa71bd69c3", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 51, "avg_line_length": 27.076923076923077, "alnum_prop": 0.8039772727272727, "repo_name": "aws4j/dynamo-mapper", "id": "0c1d3a34d41ab27eff356736115aba112646eed4", "size": "352", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/aws4j/data/dynamo/annotation/DynamoIgnore.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "186459" } ], "symlink_target": "" }
Spree Auth (Sorcery) ================ Provides authentication and authorization services for use with Spree by using Sorcery and CanCan. In contrast to Devise, I like the simplicity and flexibility of Sorcery. With Sorcery, unique authentication flow can be easily added to Spree which I totally known what happened. However, I borrowed lots of controllers and views from Devise. Installation ------------ Add spree_auth_sorcery to your Gemfile: ```ruby gem 'spree_auth_sorcery' ``` Bundle your dependencies and run the installation generator: ```shell bundle bundle exec rails g spree_auth_sorcery:install ``` Testing ------- First bundle your dependencies, then run `rake`. `rake` will default to building the dummy app if it does not exist, then it will run specs. The dummy app can be regenerated by using `rake test_app`. ```shell bundle bundle exec rake ``` When testing your applications integration with this extension you may use it's factories. Simply add this require statement to your spec_helper: ```ruby require 'spree_auth_sorcery/factories' ``` Copyright (c) 2016 [name of extension creator], released under the New BSD License
{ "content_hash": "07a5422e6b286c82daddeed614089736", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 199, "avg_line_length": 26.930232558139537, "alnum_prop": 0.7547495682210709, "repo_name": "julewu/spree_auth_sorcery", "id": "2426091adea0335b63d854f4b2dfa724c903599d", "size": "1158", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "305" }, { "name": "HTML", "bytes": "5684" }, { "name": "JavaScript", "bytes": "299" }, { "name": "Ruby", "bytes": "29740" } ], "symlink_target": "" }
import { App } from '../components/app/app'; export declare const GESTURE_GO_BACK_SWIPE: string; export declare const GESTURE_MENU_SWIPE: string; export declare const GESTURE_ITEM_SWIPE: string; export declare const GESTURE_REFRESHER: string; export declare const enum GesturePriority { Minimun = -10000, VeryLow = -20, Low = -10, Normal = 0, High = 10, VeryHigh = 20, SlidingItem = -10, MenuSwipe = 10, GoBackSwipe = 20, Refresher = 0, } export interface GestureOptions { name: string; disableScroll?: boolean; priority?: number; } export interface BlockerOptions { disableScroll?: boolean; disable?: string[]; } export declare const BLOCK_ALL: BlockerOptions; export declare class GestureController { private _app; private id; private requestedStart; private disabledGestures; private disabledScroll; private capturedID; constructor(_app: App); createGesture(opts: GestureOptions): GestureDelegate; createBlocker(opts?: BlockerOptions): BlockerDelegate; newID(): number; start(gestureName: string, id: number, priority: number): boolean; capture(gestureName: string, id: number, priority: number): boolean; release(id: number): void; disableGesture(gestureName: string, id: number): void; enableGesture(gestureName: string, id: number): void; disableScroll(id: number): void; enableScroll(id: number): void; canStart(gestureName: string): boolean; isCaptured(): boolean; isScrollDisabled(): boolean; isDisabled(gestureName: string): boolean; } export declare class GestureDelegate { private name; private id; private controller; private priority; private disableScroll; constructor(name: string, id: number, controller: GestureController, priority: number, disableScroll: boolean); canStart(): boolean; start(): boolean; capture(): boolean; release(): void; destroy(): void; } export declare class BlockerDelegate { private id; private controller; private disable; private disableScroll; blocked: boolean; constructor(id: number, controller: GestureController, disable: string[], disableScroll: boolean); block(): void; unblock(): void; destroy(): void; }
{ "content_hash": "2045bac31204512d31c383e0217c095f", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 115, "avg_line_length": 30.83783783783784, "alnum_prop": 0.6980718667835232, "repo_name": "stevedevelope17/Pizzerie", "id": "97376ef6f030a2f2b7bb4ecd147e7edb8d1cac4e", "size": "2282", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "node_modules/ionic-angular/gestures/gesture-controller.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "12314" }, { "name": "C", "bytes": "638" }, { "name": "C#", "bytes": "20363" }, { "name": "C++", "bytes": "211682" }, { "name": "CSS", "bytes": "878304" }, { "name": "HTML", "bytes": "16343" }, { "name": "Java", "bytes": "349570" }, { "name": "JavaScript", "bytes": "39285" }, { "name": "Objective-C", "bytes": "109815" }, { "name": "TypeScript", "bytes": "163910" } ], "symlink_target": "" }
<?php namespace Elements\Bundle\ElementsCoreBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class DefaultControllerTest extends WebTestCase { public function testIndex() { $client = static::createClient(); $crawler = $client->request('GET', '/hello/Fabien'); $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0); } }
{ "content_hash": "d2ee80b75f2095d120c28191c197a59c", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 90, "avg_line_length": 24.529411764705884, "alnum_prop": 0.6858513189448441, "repo_name": "goElements/elements-old", "id": "04bcf5a52a4372f555a8787840510a76b19355b6", "size": "417", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/elements/src/Elements/Bundle/ElementsCoreBundle/Tests/Controller/DefaultControllerTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "57581" } ], "symlink_target": "" }
package org.sakaiproject.wicket.model; import java.text.SimpleDateFormat; import java.util.Date; public class SimpleDateFormatPropertyModel extends DecoratedPropertyModel { private static final long serialVersionUID = 1L; private SimpleDateFormat dateFormat; public SimpleDateFormatPropertyModel(Object modelObject, String expression) { super(modelObject, expression); this.dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a"); } @Override public Object convertObject(Object object) { if (object instanceof Date) { return dateFormat.format(object); } return null; } }
{ "content_hash": "8fd664e30564de9b6bf0469f73a1a85e", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 78, "avg_line_length": 22.25925925925926, "alnum_prop": 0.778702163061564, "repo_name": "payten/nyu-sakai-10.4", "id": "514fa35b7f476b2256fb71a85c9f9cdd6ac76f1b", "size": "1505", "binary": false, "copies": "2", "ref": "refs/heads/scormcloud", "path": "sakai-wicket-for-scorm/tool/src/java/org/sakaiproject/wicket/model/SimpleDateFormatPropertyModel.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "59098" }, { "name": "ApacheConf", "bytes": "15" }, { "name": "AspectJ", "bytes": "6831" }, { "name": "Batchfile", "bytes": "5172" }, { "name": "C++", "bytes": "477" }, { "name": "CSS", "bytes": "2952622" }, { "name": "ColdFusion", "bytes": "146057" }, { "name": "HTML", "bytes": "6159499" }, { "name": "Handlebars", "bytes": "24740" }, { "name": "Java", "bytes": "42729208" }, { "name": "JavaScript", "bytes": "7061288" }, { "name": "Lasso", "bytes": "26436" }, { "name": "PHP", "bytes": "222029" }, { "name": "PLSQL", "bytes": "2161361" }, { "name": "Perl", "bytes": "72300" }, { "name": "Python", "bytes": "86996" }, { "name": "Ruby", "bytes": "26953" }, { "name": "SQLPL", "bytes": "862" }, { "name": "Shell", "bytes": "17279" }, { "name": "SourcePawn", "bytes": "1220" }, { "name": "XSLT", "bytes": "278954" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <!-- The Getting started with FAKE - F# Make parameters will be replaced with the document title extracted from the <h1> element or file name, if there is no <h1> heading --> <title>Getting started with FAKE - F# Make </title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="FAKE - F# Make"> <meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull"> <script src="http://code.jquery.com/jquery-1.8.0.js"></script> <script src="http://code.jquery.com/ui/1.8.23/jquery-ui.js"></script> <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet"> <link type="text/css" rel="stylesheet" href="content/style.css" /> <script src="content/tips.js" type="text/javascript"></script> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="masthead"> <ul class="nav nav-pills pull-right"> <li><a href="http://fsharp.org">fsharp.org</a></li> <li><a href="https://github.com/fsharp/FAKE">github page</a></li> </ul> <h3 class="muted">FAKE - F# Make</h3> </div> <hr /> <div class="row"> <div class="span9" id="main"> <h1>Getting started with FAKE - F# Make</h1> <p>In this tutorial you will learn how to set up a complete build infrastructure with "FAKE - F# Make". This includes:</p> <ul> <li>how to install the latest FAKE version</li> <li>how to automatically compile your C# or F# projects</li> <li>how to automatically resolve nuget dependencies</li> <li>how to automatically run NUnit tests on your projects</li> <li>how to zip the output to a deployment folder</li> </ul> <h2>Install the F# compiler</h2> <p>"FAKE - F# Make" is completely written in F# and all build scripts will also be written in F#, but this doesn't imply that you have to learn programming in F#. In fact the "FAKE - F# Make" syntax is hopefully very easy to learn.</p> <h2>Download Calculator Sample</h2> <p>Now download the latest <a href="http://fsharp.github.io/FAKE/FAKE-Calculator.zip">FAKE-Calculator.zip</a> from the <a href="https://github.com/fsharp/FAKE">FAKE project site</a>. This sample includes 3 tiny projects and has basically the following structure:</p> <ul> <li>src/app <ul> <li>Calculator (command line)</li> <li>CalculatorLib (class library)</li> </ul></li> <li>src/test <ul> <li>Test.CalculatorLib</li> </ul></li> <li>tools <ul> <li>NUnit</li> <li>FxCop</li> </ul></li> <li>build.bat</li> <li>build.fsx</li> <li>completeBuild.bat</li> <li>completeBuild.fsx</li> <li>Calculator.sln</li> </ul> <h2>Getting "FAKE - F# Make" started</h2> <p>In the root of the project you will find a build.bat file:</p> <pre lang="batchfile">@echo off cls &quot;.nuget\NuGet.exe&quot; &quot;Install&quot; &quot;FAKE&quot; &quot;-OutputDirectory&quot; &quot;packages&quot; &quot;-ExcludeVersion&quot; &quot;packages\FAKE\tools\Fake.exe&quot; build.fsx pause</pre> <p>If you run this batch file from the command line then the latest FAKE version will be <a href="http://nuget.org/packages/FAKE/">downloaded via nuget</a> and your first FAKE script (build.fsx) will be executed. If everything works fine you will get the following output:</p> <p><img src="pics/gettingstarted/afterdownload.png" alt="alt text" title="Run the batch file" /></p> <p>Now open the <em>build.fsx</em> in Visual Studio or any text editor. It should look like this:</p> <table class="pre"><tr><td class="lines"><pre class="fssnip"> <span class="l"> 1: </span> <span class="l"> 2: </span> <span class="l"> 3: </span> <span class="l"> 4: </span> <span class="l"> 5: </span> <span class="l"> 6: </span> <span class="l"> 7: </span> <span class="l"> 8: </span> <span class="l"> 9: </span> <span class="l">10: </span> <span class="l">11: </span> </pre> </td> <td class="snippet"><pre class="fssnip"> <span class="c">// include Fake lib</span> <span class="prep">#r</span> <span class="s">@&quot;</span><span class="s">packages</span><span class="s">/</span><span class="s">FAKE</span><span class="s">/</span><span class="s">tools</span><span class="s">/</span><span class="s">FakeLib</span><span class="s">.</span><span class="s">dll</span><span class="s">&quot;</span> <span class="k">open</span> <span class="i">Fake</span> <span class="c">// Default target</span> <span class="i">Target</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="i">trace</span> <span class="s">&quot;</span><span class="s">Hello</span><span class="s"> </span><span class="s">World</span><span class="s"> </span><span class="s">from</span><span class="s"> </span><span class="s">FAKE</span><span class="s">&quot;</span> ) <span class="c">// start build</span> <span class="i">RunTargetOrDefault</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span></pre> </td> </tr> </table> <p>As you can see the code is really simple. The first line includes the FAKE library and is vital for all FAKE build scripts.</p> <p>After this header the <em>Default</em> target is defined. A target definition contains two important parts. The first is the name of the target (here "Default") and the second is an action (here a simple trace of "Hello world").</p> <p>The last line runs the "Default" target - which means it executes the defined action of the target.</p> <h2>Cleaning the last build output</h2> <p>A typical first step in most build scenarios is to clean the output of the last build. We can achieve this by modifying the <em>build.fsx</em> to the following:</p> <table class="pre"><tr><td class="lines"><pre class="fssnip"> <span class="l"> 1: </span> <span class="l"> 2: </span> <span class="l"> 3: </span> <span class="l"> 4: </span> <span class="l"> 5: </span> <span class="l"> 6: </span> <span class="l"> 7: </span> <span class="l"> 8: </span> <span class="l"> 9: </span> <span class="l">10: </span> <span class="l">11: </span> <span class="l">12: </span> <span class="l">13: </span> <span class="l">14: </span> <span class="l">15: </span> <span class="l">16: </span> <span class="l">17: </span> <span class="l">18: </span> <span class="l">19: </span> <span class="l">20: </span> <span class="l">21: </span> <span class="l">22: </span> </pre> </td> <td class="snippet"><pre class="fssnip"> <span class="c">// include Fake lib</span> <span class="prep">#r</span> <span class="s">&quot;</span><span class="s">packages</span><span class="s">/</span><span class="s">FAKE</span><span class="s">/</span><span class="s">tools</span><span class="s">/</span><span class="s">FakeLib</span><span class="s">.</span><span class="s">dll</span><span class="s">&quot;</span> <span class="k">open</span> <span class="i">Fake</span> <span class="c">// Properties</span> <span class="k">let</span> <span onmouseout="hideTip(event, 'fs1', 1)" onmouseover="showTip(event, 'fs1', 1)" class="i">buildDir</span> <span class="o">=</span> <span class="s">&quot;</span><span class="s">.</span><span class="s">/</span><span class="s">build</span><span class="s">/</span><span class="s">&quot;</span> <span class="c">// Targets</span> <span class="i">Target</span> <span class="s">&quot;</span><span class="s">Clean</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="i">CleanDir</span> <span onmouseout="hideTip(event, 'fs1', 2)" onmouseover="showTip(event, 'fs1', 2)" class="i">buildDir</span> ) <span class="i">Target</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="i">trace</span> <span class="s">&quot;</span><span class="s">Hello</span><span class="s"> </span><span class="s">World</span><span class="s"> </span><span class="s">from</span><span class="s"> </span><span class="s">FAKE</span><span class="s">&quot;</span> ) <span class="c">// Dependencies</span> <span class="s">&quot;</span><span class="s">Clean</span><span class="s">&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span> <span class="c">// start build</span> <span class="i">RunTargetOrDefault</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span></pre> </td> </tr> </table> <p>We introduced some new concepts in this snippet. At first we defined a global property called "buildDir" with the relative path of a temporary build folder.</p> <p>In the <em>Clean</em> target we use the CleanDir task to clean up this build directory. This simply deletes all files in the folder or creates the directory if necessary.</p> <p>In the dependencies section we say that the <em>Default</em> target has a dependency on the <em>Clean</em> target. In other words <em>Clean</em> is a prerequisite of <em>Default</em> and will be run before the execution of <em>Default</em>:</p> <p><img src="pics/gettingstarted/afterclean.png" alt="alt text" title="We introduced a Clean target" /></p> <h2>Compiling the application</h2> <p>In the next step we want to compile our C# libraries, which means we want to compile all csproj-files under <em>/src/app</em> with MSBuild:</p> <table class="pre"><tr><td class="lines"><pre class="fssnip"> <span class="l"> 1: </span> <span class="l"> 2: </span> <span class="l"> 3: </span> <span class="l"> 4: </span> <span class="l"> 5: </span> <span class="l"> 6: </span> <span class="l"> 7: </span> <span class="l"> 8: </span> <span class="l"> 9: </span> <span class="l">10: </span> <span class="l">11: </span> <span class="l">12: </span> <span class="l">13: </span> <span class="l">14: </span> <span class="l">15: </span> <span class="l">16: </span> <span class="l">17: </span> <span class="l">18: </span> <span class="l">19: </span> <span class="l">20: </span> <span class="l">21: </span> <span class="l">22: </span> <span class="l">23: </span> <span class="l">24: </span> <span class="l">25: </span> <span class="l">26: </span> <span class="l">27: </span> <span class="l">28: </span> <span class="l">29: </span> </pre> </td> <td class="snippet"><pre class="fssnip"> <span class="c">// include Fake lib</span> <span class="prep">#r</span> <span class="s">&quot;</span><span class="s">packages</span><span class="s">/</span><span class="s">FAKE</span><span class="s">/</span><span class="s">tools</span><span class="s">/</span><span class="s">FakeLib</span><span class="s">.</span><span class="s">dll</span><span class="s">&quot;</span> <span class="k">open</span> <span class="i">Fake</span> <span class="c">// Properties</span> <span class="k">let</span> <span onmouseout="hideTip(event, 'fs1', 3)" onmouseover="showTip(event, 'fs1', 3)" class="i">buildDir</span> <span class="o">=</span> <span class="s">&quot;</span><span class="s">.</span><span class="s">/</span><span class="s">build</span><span class="s">/</span><span class="s">&quot;</span> <span class="c">// Targets</span> <span class="i">Target</span> <span class="s">&quot;</span><span class="s">Clean</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="i">CleanDir</span> <span onmouseout="hideTip(event, 'fs1', 4)" onmouseover="showTip(event, 'fs1', 4)" class="i">buildDir</span> ) <span class="i">Target</span> <span class="s">&quot;</span><span class="s">BuildApp</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="o">!!</span> <span class="s">&quot;</span><span class="s">src</span><span class="s">/</span><span class="s">app</span><span class="s">/</span><span class="s">*</span><span class="s">*</span><span class="s">/</span><span class="s">*</span><span class="s">.</span><span class="s">csproj</span><span class="s">&quot;</span> <span class="o">|&gt;</span> <span class="i">MSBuildRelease</span> <span onmouseout="hideTip(event, 'fs1', 5)" onmouseover="showTip(event, 'fs1', 5)" class="i">buildDir</span> <span class="s">&quot;</span><span class="s">Build</span><span class="s">&quot;</span> <span class="o">|&gt;</span> <span class="i">Log</span> <span class="s">&quot;</span><span class="s">AppBuild</span><span class="s">-</span><span class="s">Output</span><span class="s">:</span><span class="s"> </span><span class="s">&quot;</span> ) <span class="i">Target</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="i">trace</span> <span class="s">&quot;</span><span class="s">Hello</span><span class="s"> </span><span class="s">World</span><span class="s"> </span><span class="s">from</span><span class="s"> </span><span class="s">FAKE</span><span class="s">&quot;</span> ) <span class="c">// Dependencies</span> <span class="s">&quot;</span><span class="s">Clean</span><span class="s">&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;</span><span class="s">BuildApp</span><span class="s">&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span> <span class="c">// start build</span> <span class="i">RunTargetOrDefault</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span></pre> </td> </tr> </table> <p>We defined a new build target named "BuildApp" which compiles all csproj-files with the MSBuild task and the build output will be copied to buildDir.</p> <p>In order to find the right project files FAKEscans the folder <em>src/app/</em> and all subfolders with the given pattern. Therefore a similar FileSet definition like in NAnt or MSBuild (see <a href="https://github.com/fsharp/FAKE">project page</a> for details) is used.</p> <p>In addition the target dependencies are extended again. Now <em>Default</em> is dependent on <em>BuildApp</em> and <em>BuildApp</em> needs <em>Clean</em> as a prerequisite.</p> <p>This means the execution order is: Clean ==> BuildApp ==> Default.</p> <p><img src="pics/gettingstarted/aftercompile.png" alt="alt text" title="We introduced a Build target" /></p> <h2>Compiling test projects</h2> <p>Now our main application will be built automatically and it's time to build the test project. We use the same concepts as before:</p> <table class="pre"><tr><td class="lines"><pre class="fssnip"> <span class="l"> 1: </span> <span class="l"> 2: </span> <span class="l"> 3: </span> <span class="l"> 4: </span> <span class="l"> 5: </span> <span class="l"> 6: </span> <span class="l"> 7: </span> <span class="l"> 8: </span> <span class="l"> 9: </span> <span class="l">10: </span> <span class="l">11: </span> <span class="l">12: </span> <span class="l">13: </span> <span class="l">14: </span> <span class="l">15: </span> <span class="l">16: </span> <span class="l">17: </span> <span class="l">18: </span> <span class="l">19: </span> <span class="l">20: </span> <span class="l">21: </span> <span class="l">22: </span> <span class="l">23: </span> <span class="l">24: </span> <span class="l">25: </span> <span class="l">26: </span> <span class="l">27: </span> <span class="l">28: </span> <span class="l">29: </span> <span class="l">30: </span> <span class="l">31: </span> <span class="l">32: </span> <span class="l">33: </span> <span class="l">34: </span> <span class="l">35: </span> <span class="l">36: </span> <span class="l">37: </span> </pre> </td> <td class="snippet"><pre class="fssnip"> <span class="c">// include Fake lib</span> <span class="prep">#r</span> <span class="s">&quot;</span><span class="s">packages</span><span class="s">/</span><span class="s">FAKE</span><span class="s">/</span><span class="s">tools</span><span class="s">/</span><span class="s">FakeLib</span><span class="s">.</span><span class="s">dll</span><span class="s">&quot;</span> <span class="k">open</span> <span class="i">Fake</span> <span class="c">// Properties</span> <span class="k">let</span> <span onmouseout="hideTip(event, 'fs1', 6)" onmouseover="showTip(event, 'fs1', 6)" class="i">buildDir</span> <span class="o">=</span> <span class="s">&quot;</span><span class="s">.</span><span class="s">/</span><span class="s">build</span><span class="s">/</span><span class="s">&quot;</span> <span class="k">let</span> <span onmouseout="hideTip(event, 'fs2', 7)" onmouseover="showTip(event, 'fs2', 7)" class="i">testDir</span> <span class="o">=</span> <span class="s">&quot;</span><span class="s">.</span><span class="s">/</span><span class="s">test</span><span class="s">/</span><span class="s">&quot;</span> <span class="c">// Targets</span> <span class="i">Target</span> <span class="s">&quot;</span><span class="s">Clean</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="i">CleanDirs</span> [<span onmouseout="hideTip(event, 'fs1', 8)" onmouseover="showTip(event, 'fs1', 8)" class="i">buildDir</span>; <span onmouseout="hideTip(event, 'fs2', 9)" onmouseover="showTip(event, 'fs2', 9)" class="i">testDir</span>] ) <span class="i">Target</span> <span class="s">&quot;</span><span class="s">BuildApp</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="o">!!</span> <span class="s">&quot;</span><span class="s">src</span><span class="s">/</span><span class="s">app</span><span class="s">/</span><span class="s">*</span><span class="s">*</span><span class="s">/</span><span class="s">*</span><span class="s">.</span><span class="s">csproj</span><span class="s">&quot;</span> <span class="o">|&gt;</span> <span class="i">MSBuildRelease</span> <span onmouseout="hideTip(event, 'fs1', 10)" onmouseover="showTip(event, 'fs1', 10)" class="i">buildDir</span> <span class="s">&quot;</span><span class="s">Build</span><span class="s">&quot;</span> <span class="o">|&gt;</span> <span class="i">Log</span> <span class="s">&quot;</span><span class="s">AppBuild</span><span class="s">-</span><span class="s">Output</span><span class="s">:</span><span class="s"> </span><span class="s">&quot;</span> ) <span class="i">Target</span> <span class="s">&quot;</span><span class="s">BuildTest</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="o">!!</span> <span class="s">&quot;</span><span class="s">src</span><span class="s">/</span><span class="s">test</span><span class="s">/</span><span class="s">*</span><span class="s">*</span><span class="s">/</span><span class="s">*</span><span class="s">.</span><span class="s">csproj</span><span class="s">&quot;</span> <span class="o">|&gt;</span> <span class="i">MSBuildDebug</span> <span onmouseout="hideTip(event, 'fs2', 11)" onmouseover="showTip(event, 'fs2', 11)" class="i">testDir</span> <span class="s">&quot;</span><span class="s">Build</span><span class="s">&quot;</span> <span class="o">|&gt;</span> <span class="i">Log</span> <span class="s">&quot;</span><span class="s">TestBuild</span><span class="s">-</span><span class="s">Output</span><span class="s">:</span><span class="s"> </span><span class="s">&quot;</span> ) <span class="i">Target</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="i">trace</span> <span class="s">&quot;</span><span class="s">Hello</span><span class="s"> </span><span class="s">World</span><span class="s"> </span><span class="s">from</span><span class="s"> </span><span class="s">FAKE</span><span class="s">&quot;</span> ) <span class="c">// Dependencies</span> <span class="s">&quot;</span><span class="s">Clean</span><span class="s">&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;</span><span class="s">BuildApp</span><span class="s">&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;</span><span class="s">BuildTest</span><span class="s">&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span> <span class="c">// start build</span> <span class="i">RunTargetOrDefault</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span></pre> </td> </tr> </table> <p>This time we defined a new target "BuildTest" which compiles all C# projects below <em>src/test/</em> in Debug mode and we put the target into our build order.</p> <p>If we run build.bat again we get an error like this:</p> <p><img src="pics/gettingstarted/compileerror.png" alt="alt text" title="Compile error" /></p> <p>The problem is that we didn't download the NUnit package from nuget. So let's fix this in the build script:</p> <table class="pre"><tr><td class="lines"><pre class="fssnip"> <span class="l">1: </span> <span class="l">2: </span> <span class="l">3: </span> <span class="l">4: </span> <span class="l">5: </span> <span class="l">6: </span> </pre> </td> <td class="snippet"><pre class="fssnip"> <span class="c">// include Fake lib</span> <span class="prep">#r</span> <span class="s">&quot;</span><span class="s">packages</span><span class="s">/</span><span class="s">FAKE</span><span class="s">/</span><span class="s">tools</span><span class="s">/</span><span class="s">FakeLib</span><span class="s">.</span><span class="s">dll</span><span class="s">&quot;</span> <span class="k">open</span> <span class="i">Fake</span> <span class="i">RestorePackages</span>() <span class="c">// ...</span></pre> </td> </tr> </table> <p>With this simple command FAKE will use nuget.exe to install all the package dependencies.</p> <h2>Running the tests with NUnit</h2> <p>Now all our projects will be compiled and we can use FAKE's NUnit task in order to let NUnit test our assembly:</p> <table class="pre"><tr><td class="lines"><pre class="fssnip"> <span class="l"> 1: </span> <span class="l"> 2: </span> <span class="l"> 3: </span> <span class="l"> 4: </span> <span class="l"> 5: </span> <span class="l"> 6: </span> <span class="l"> 7: </span> <span class="l"> 8: </span> <span class="l"> 9: </span> <span class="l">10: </span> <span class="l">11: </span> <span class="l">12: </span> <span class="l">13: </span> <span class="l">14: </span> <span class="l">15: </span> <span class="l">16: </span> <span class="l">17: </span> <span class="l">18: </span> <span class="l">19: </span> <span class="l">20: </span> <span class="l">21: </span> <span class="l">22: </span> <span class="l">23: </span> <span class="l">24: </span> <span class="l">25: </span> <span class="l">26: </span> <span class="l">27: </span> <span class="l">28: </span> <span class="l">29: </span> <span class="l">30: </span> <span class="l">31: </span> <span class="l">32: </span> <span class="l">33: </span> <span class="l">34: </span> <span class="l">35: </span> <span class="l">36: </span> <span class="l">37: </span> <span class="l">38: </span> <span class="l">39: </span> <span class="l">40: </span> <span class="l">41: </span> <span class="l">42: </span> <span class="l">43: </span> <span class="l">44: </span> <span class="l">45: </span> <span class="l">46: </span> <span class="l">47: </span> <span class="l">48: </span> </pre> </td> <td class="snippet"><pre class="fssnip"> <span class="c">// include Fake lib</span> <span class="prep">#r</span> <span class="s">&quot;</span><span class="s">packages</span><span class="s">/</span><span class="s">FAKE</span><span class="s">/</span><span class="s">tools</span><span class="s">/</span><span class="s">FakeLib</span><span class="s">.</span><span class="s">dll</span><span class="s">&quot;</span> <span class="k">open</span> <span class="i">Fake</span> <span class="i">RestorePackages</span>() <span class="c">// Properties</span> <span class="k">let</span> <span onmouseout="hideTip(event, 'fs1', 12)" onmouseover="showTip(event, 'fs1', 12)" class="i">buildDir</span> <span class="o">=</span> <span class="s">&quot;</span><span class="s">.</span><span class="s">/</span><span class="s">build</span><span class="s">/</span><span class="s">&quot;</span> <span class="k">let</span> <span onmouseout="hideTip(event, 'fs2', 13)" onmouseover="showTip(event, 'fs2', 13)" class="i">testDir</span> <span class="o">=</span> <span class="s">&quot;</span><span class="s">.</span><span class="s">/</span><span class="s">test</span><span class="s">/</span><span class="s">&quot;</span> <span class="c">// Targets</span> <span class="i">Target</span> <span class="s">&quot;</span><span class="s">Clean</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="i">CleanDirs</span> [<span onmouseout="hideTip(event, 'fs1', 14)" onmouseover="showTip(event, 'fs1', 14)" class="i">buildDir</span>; <span onmouseout="hideTip(event, 'fs2', 15)" onmouseover="showTip(event, 'fs2', 15)" class="i">testDir</span>] ) <span class="i">Target</span> <span class="s">&quot;</span><span class="s">BuildApp</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="o">!!</span> <span class="s">&quot;</span><span class="s">src</span><span class="s">/</span><span class="s">app</span><span class="s">/</span><span class="s">*</span><span class="s">*</span><span class="s">/</span><span class="s">*</span><span class="s">.</span><span class="s">csproj</span><span class="s">&quot;</span> <span class="o">|&gt;</span> <span class="i">MSBuildRelease</span> <span onmouseout="hideTip(event, 'fs1', 16)" onmouseover="showTip(event, 'fs1', 16)" class="i">buildDir</span> <span class="s">&quot;</span><span class="s">Build</span><span class="s">&quot;</span> <span class="o">|&gt;</span> <span class="i">Log</span> <span class="s">&quot;</span><span class="s">AppBuild</span><span class="s">-</span><span class="s">Output</span><span class="s">:</span><span class="s"> </span><span class="s">&quot;</span> ) <span class="i">Target</span> <span class="s">&quot;</span><span class="s">BuildTest</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="o">!!</span> <span class="s">&quot;</span><span class="s">src</span><span class="s">/</span><span class="s">test</span><span class="s">/</span><span class="s">*</span><span class="s">*</span><span class="s">/</span><span class="s">*</span><span class="s">.</span><span class="s">csproj</span><span class="s">&quot;</span> <span class="o">|&gt;</span> <span class="i">MSBuildDebug</span> <span onmouseout="hideTip(event, 'fs2', 17)" onmouseover="showTip(event, 'fs2', 17)" class="i">testDir</span> <span class="s">&quot;</span><span class="s">Build</span><span class="s">&quot;</span> <span class="o">|&gt;</span> <span class="i">Log</span> <span class="s">&quot;</span><span class="s">TestBuild</span><span class="s">-</span><span class="s">Output</span><span class="s">:</span><span class="s"> </span><span class="s">&quot;</span> ) <span class="i">Target</span> <span class="s">&quot;</span><span class="s">Test</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="o">!!</span> (<span onmouseout="hideTip(event, 'fs2', 18)" onmouseover="showTip(event, 'fs2', 18)" class="i">testDir</span> <span class="o">+</span> <span class="s">&quot;</span><span class="s">/</span><span class="s">NUnit</span><span class="s">.</span><span class="s">Test</span><span class="s">.</span><span class="s">*</span><span class="s">.</span><span class="s">dll</span><span class="s">&quot;</span>) <span class="o">|&gt;</span> <span class="i">NUnit</span> (<span class="k">fun</span> <span class="i">p</span> <span class="k">-&gt;</span> {<span class="i">p</span> <span class="k">with</span> <span class="i">DisableShadowCopy</span> <span class="o">=</span> <span class="k">true</span>; <span class="i">OutputFile</span> <span class="o">=</span> <span onmouseout="hideTip(event, 'fs2', 19)" onmouseover="showTip(event, 'fs2', 19)" class="i">testDir</span> <span class="o">+</span> <span class="s">&quot;</span><span class="s">TestResults</span><span class="s">.</span><span class="s">xml</span><span class="s">&quot;</span> }) ) <span class="i">Target</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="i">trace</span> <span class="s">&quot;</span><span class="s">Hello</span><span class="s"> </span><span class="s">World</span><span class="s"> </span><span class="s">from</span><span class="s"> </span><span class="s">FAKE</span><span class="s">&quot;</span> ) <span class="c">// Dependencies</span> <span class="s">&quot;</span><span class="s">Clean</span><span class="s">&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;</span><span class="s">BuildApp</span><span class="s">&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;</span><span class="s">BuildTest</span><span class="s">&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;</span><span class="s">Test</span><span class="s">&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span> <span class="c">// start build</span> <span class="i">RunTargetOrDefault</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span></pre> </td> </tr> </table> <p>Our new <em>Test</em> target scans the test directory for test assemblies and runs them with the NUnit runner. FAKE automatically tries to locate the runner in one of your subfolders. See the <a href="apidocs/fake-nunitparallel.html">NUnit task documentation</a> if you need to specify the tool path explicitly.</p> <p>The mysterious part <strong>(fun p -> ...)</strong> simply overrides the default parameters of the NUnit task and allows to specify concrete parameters.</p> <p><img src="pics/gettingstarted/alltestsgreen.png" alt="alt text" title="All tests green" /></p> <p>Alternatively you could also run the tests in parallel using the <a href="apidocs/fake-nunitparallel.html">NUnitParallel</a> task:</p> <table class="pre"><tr><td class="lines"><pre class="fssnip"> <span class="l">1: </span> <span class="l">2: </span> <span class="l">3: </span> <span class="l">4: </span> <span class="l">5: </span> <span class="l">6: </span> <span class="l">7: </span> </pre> </td> <td class="snippet"><pre class="fssnip"> <span class="i">Target</span> <span class="s">&quot;</span><span class="s">Test</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="o">!!</span> (<span onmouseout="hideTip(event, 'fs2', 20)" onmouseover="showTip(event, 'fs2', 20)" class="i">testDir</span> <span class="o">+</span> <span class="s">&quot;</span><span class="s">/</span><span class="s">NUnit</span><span class="s">.</span><span class="s">Test</span><span class="s">.</span><span class="s">*</span><span class="s">.</span><span class="s">dll</span><span class="s">&quot;</span>) <span class="o">|&gt;</span> <span class="i">NUnitParallel</span> (<span class="k">fun</span> <span class="i">p</span> <span class="k">-&gt;</span> {<span class="i">p</span> <span class="k">with</span> <span class="i">DisableShadowCopy</span> <span class="o">=</span> <span class="k">true</span>; <span class="i">OutputFile</span> <span class="o">=</span> <span onmouseout="hideTip(event, 'fs2', 21)" onmouseover="showTip(event, 'fs2', 21)" class="i">testDir</span> <span class="o">+</span> <span class="s">&quot;</span><span class="s">TestResults</span><span class="s">.</span><span class="s">xml</span><span class="s">&quot;</span> }) )</pre> </td> </tr> </table> <h2>Deploying a zip file</h2> <p>Now we want to deploy a *.zip file containing our application:</p> <table class="pre"><tr><td class="lines"><pre class="fssnip"> <span class="l"> 1: </span> <span class="l"> 2: </span> <span class="l"> 3: </span> <span class="l"> 4: </span> <span class="l"> 5: </span> <span class="l"> 6: </span> <span class="l"> 7: </span> <span class="l"> 8: </span> <span class="l"> 9: </span> <span class="l">10: </span> <span class="l">11: </span> <span class="l">12: </span> <span class="l">13: </span> <span class="l">14: </span> <span class="l">15: </span> <span class="l">16: </span> <span class="l">17: </span> <span class="l">18: </span> <span class="l">19: </span> <span class="l">20: </span> <span class="l">21: </span> <span class="l">22: </span> <span class="l">23: </span> <span class="l">24: </span> <span class="l">25: </span> <span class="l">26: </span> <span class="l">27: </span> <span class="l">28: </span> <span class="l">29: </span> <span class="l">30: </span> <span class="l">31: </span> <span class="l">32: </span> <span class="l">33: </span> <span class="l">34: </span> <span class="l">35: </span> <span class="l">36: </span> <span class="l">37: </span> <span class="l">38: </span> <span class="l">39: </span> <span class="l">40: </span> <span class="l">41: </span> <span class="l">42: </span> <span class="l">43: </span> <span class="l">44: </span> <span class="l">45: </span> <span class="l">46: </span> <span class="l">47: </span> <span class="l">48: </span> <span class="l">49: </span> <span class="l">50: </span> <span class="l">51: </span> <span class="l">52: </span> <span class="l">53: </span> <span class="l">54: </span> <span class="l">55: </span> <span class="l">56: </span> <span class="l">57: </span> <span class="l">58: </span> <span class="l">59: </span> </pre> </td> <td class="snippet"><pre class="fssnip"> <span class="c">// include Fake lib</span> <span class="prep">#r</span> <span class="s">&quot;</span><span class="s">tools</span><span class="s">/</span><span class="s">FAKE</span><span class="s">/</span><span class="s">tools</span><span class="s">/</span><span class="s">FakeLib</span><span class="s">.</span><span class="s">dll</span><span class="s">&quot;</span> <span class="k">open</span> <span class="i">Fake</span> <span class="i">RestorePackages</span>() <span class="c">// Properties</span> <span class="k">let</span> <span onmouseout="hideTip(event, 'fs1', 22)" onmouseover="showTip(event, 'fs1', 22)" class="i">buildDir</span> <span class="o">=</span> <span class="s">&quot;</span><span class="s">.</span><span class="s">/</span><span class="s">build</span><span class="s">/</span><span class="s">&quot;</span> <span class="k">let</span> <span onmouseout="hideTip(event, 'fs2', 23)" onmouseover="showTip(event, 'fs2', 23)" class="i">testDir</span> <span class="o">=</span> <span class="s">&quot;</span><span class="s">.</span><span class="s">/</span><span class="s">test</span><span class="s">/</span><span class="s">&quot;</span> <span class="k">let</span> <span onmouseout="hideTip(event, 'fs3', 24)" onmouseover="showTip(event, 'fs3', 24)" class="i">deployDir</span> <span class="o">=</span> <span class="s">&quot;</span><span class="s">.</span><span class="s">/</span><span class="s">deploy</span><span class="s">/</span><span class="s">&quot;</span> <span class="c">// version info</span> <span class="k">let</span> <span onmouseout="hideTip(event, 'fs4', 25)" onmouseover="showTip(event, 'fs4', 25)" class="i">version</span> <span class="o">=</span> <span class="s">&quot;</span><span class="s">0</span><span class="s">.</span><span class="s">2</span><span class="s">&quot;</span> <span class="c">// or retrieve from CI server</span> <span class="c">// Targets</span> <span class="i">Target</span> <span class="s">&quot;</span><span class="s">Clean</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="i">CleanDirs</span> [<span onmouseout="hideTip(event, 'fs1', 26)" onmouseover="showTip(event, 'fs1', 26)" class="i">buildDir</span>; <span onmouseout="hideTip(event, 'fs2', 27)" onmouseover="showTip(event, 'fs2', 27)" class="i">testDir</span>; <span onmouseout="hideTip(event, 'fs3', 28)" onmouseover="showTip(event, 'fs3', 28)" class="i">deployDir</span>] ) <span class="i">Target</span> <span class="s">&quot;</span><span class="s">BuildApp</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="o">!!</span> <span class="s">&quot;</span><span class="s">src</span><span class="s">/</span><span class="s">app</span><span class="s">/</span><span class="s">*</span><span class="s">*</span><span class="s">/</span><span class="s">*</span><span class="s">.</span><span class="s">csproj</span><span class="s">&quot;</span> <span class="o">|&gt;</span> <span class="i">MSBuildRelease</span> <span onmouseout="hideTip(event, 'fs1', 29)" onmouseover="showTip(event, 'fs1', 29)" class="i">buildDir</span> <span class="s">&quot;</span><span class="s">Build</span><span class="s">&quot;</span> <span class="o">|&gt;</span> <span class="i">Log</span> <span class="s">&quot;</span><span class="s">AppBuild</span><span class="s">-</span><span class="s">Output</span><span class="s">:</span><span class="s"> </span><span class="s">&quot;</span> ) <span class="i">Target</span> <span class="s">&quot;</span><span class="s">BuildTest</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="o">!!</span> <span class="s">&quot;</span><span class="s">src</span><span class="s">/</span><span class="s">test</span><span class="s">/</span><span class="s">*</span><span class="s">*</span><span class="s">/</span><span class="s">*</span><span class="s">.</span><span class="s">csproj</span><span class="s">&quot;</span> <span class="o">|&gt;</span> <span class="i">MSBuildDebug</span> <span onmouseout="hideTip(event, 'fs2', 30)" onmouseover="showTip(event, 'fs2', 30)" class="i">testDir</span> <span class="s">&quot;</span><span class="s">Build</span><span class="s">&quot;</span> <span class="o">|&gt;</span> <span class="i">Log</span> <span class="s">&quot;</span><span class="s">TestBuild</span><span class="s">-</span><span class="s">Output</span><span class="s">:</span><span class="s"> </span><span class="s">&quot;</span> ) <span class="i">Target</span> <span class="s">&quot;</span><span class="s">Test</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="o">!!</span> (<span onmouseout="hideTip(event, 'fs2', 31)" onmouseover="showTip(event, 'fs2', 31)" class="i">testDir</span> <span class="o">+</span> <span class="s">&quot;</span><span class="s">/</span><span class="s">NUnit</span><span class="s">.</span><span class="s">Test</span><span class="s">.</span><span class="s">*</span><span class="s">.</span><span class="s">dll</span><span class="s">&quot;</span>) <span class="o">|&gt;</span> <span class="i">NUnit</span> (<span class="k">fun</span> <span class="i">p</span> <span class="k">-&gt;</span> {<span class="i">p</span> <span class="k">with</span> <span class="i">DisableShadowCopy</span> <span class="o">=</span> <span class="k">true</span>; <span class="i">OutputFile</span> <span class="o">=</span> <span onmouseout="hideTip(event, 'fs2', 32)" onmouseover="showTip(event, 'fs2', 32)" class="i">testDir</span> <span class="o">+</span> <span class="s">&quot;</span><span class="s">TestResults</span><span class="s">.</span><span class="s">xml</span><span class="s">&quot;</span> }) ) <span class="i">Target</span> <span class="s">&quot;</span><span class="s">Zip</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="o">!!</span> (<span onmouseout="hideTip(event, 'fs1', 33)" onmouseover="showTip(event, 'fs1', 33)" class="i">buildDir</span> <span class="o">+</span> <span class="s">&quot;</span><span class="s">/</span><span class="s">*</span><span class="s">*</span><span class="s">/</span><span class="s">*</span><span class="s">.</span><span class="s">*</span><span class="s">&quot;</span>) <span class="o">--</span> <span class="s">&quot;</span><span class="s">*</span><span class="s">.</span><span class="s">zip</span><span class="s">&quot;</span> <span class="o">|&gt;</span> <span class="i">Zip</span> <span onmouseout="hideTip(event, 'fs1', 34)" onmouseover="showTip(event, 'fs1', 34)" class="i">buildDir</span> (<span onmouseout="hideTip(event, 'fs3', 35)" onmouseover="showTip(event, 'fs3', 35)" class="i">deployDir</span> <span class="o">+</span> <span class="s">&quot;</span><span class="s">Calculator</span><span class="s">.</span><span class="s">&quot;</span> <span class="o">+</span> <span onmouseout="hideTip(event, 'fs4', 36)" onmouseover="showTip(event, 'fs4', 36)" class="i">version</span> <span class="o">+</span> <span class="s">&quot;</span><span class="s">.</span><span class="s">zip</span><span class="s">&quot;</span>) ) <span class="i">Target</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span> (<span class="k">fun</span> _ <span class="k">-&gt;</span> <span class="i">trace</span> <span class="s">&quot;</span><span class="s">Hello</span><span class="s"> </span><span class="s">World</span><span class="s"> </span><span class="s">from</span><span class="s"> </span><span class="s">FAKE</span><span class="s">&quot;</span> ) <span class="c">// Dependencies</span> <span class="s">&quot;</span><span class="s">Clean</span><span class="s">&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;</span><span class="s">BuildApp</span><span class="s">&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;</span><span class="s">BuildTest</span><span class="s">&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;</span><span class="s">Test</span><span class="s">&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;</span><span class="s">Zip</span><span class="s">&quot;</span> <span class="o">==&gt;</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span> <span class="c">// start build</span> <span class="i">RunTargetOrDefault</span> <span class="s">&quot;</span><span class="s">Default</span><span class="s">&quot;</span></pre> </td> </tr> </table> <p>The new <em>Deploy</em> target scans the build directory for all files. The result will be zipped to <em>/deploy/Calculator.zip</em> via the Zip task.</p> <h2>What's next?</h2> <p>If you want you could now <a href="fxcop.html">add a FxCop target</a> to your build in order to check specific naming rules or framework guidelines.</p> <div class="tip" id="fs1">val buildDir : string<br /><br />Full name: gettingstarted.buildDir</div> <div class="tip" id="fs2">val testDir : string<br /><br />Full name: gettingstarted.testDir</div> <div class="tip" id="fs3">val deployDir : string<br /><br />Full name: gettingstarted.deployDir</div> <div class="tip" id="fs4">val version : string<br /><br />Full name: gettingstarted.version</div> </div> <div class="span3"> <img src="pics/logo.png" alt="FAKE - F# Make" style="width:150px;margin-left: 20px;" /> <ul class="nav nav-list" id="menu" style="margin-top: 20px;"> <li class="nav-header">FAKE - F# Make</li> <li><a href="index.html">Home page</a></li> <li class="divider"></li> <li><a href="https://nuget.org/packages/Fake">Get FAKE via NuGet</a></li> <li><a href="https://github.com/fsharp/FAKE">Source Code on GitHub</a></li> <li><a href="https://github.com/fsharp/FAKE/blob/develop/License.txt">License (MS-PL)</a></li> <li><a href="users.html">Who is using FAKE?</a></li> <li><a href="RELEASE_NOTES.html">Release Notes</a></li> <li><a href="contributing.html">Contributing to FAKE</a></li> <li><a href="http://stackoverflow.com/questions/tagged/f%23-fake">Ask a question</a></li> <li class="nav-header">Articles</li> <li><a href="gettingstarted.html">Getting started</a></li> <li class="divider"></li> <li><a href="nuget.html">NuGet package restore</a></li> <li><a href="fxcop.html">Using FxCop in a build</a></li> <li><a href="assemblyinfo.html">Generating AssemblyInfo</a></li> <li><a href="create-nuget-package.html">Create NuGet packages</a></li> <li><a href="specifictargets.html">Running specific targets</a></li> <li><a href="commandline.html">Running FAKE from command line</a></li> <li><a href="customtasks.html">Creating custom tasks</a></li> <li><a href="teamcity.html">TeamCity integration</a></li> <li><a href="canopy.html">Running canopy tests</a></li> <li><a href="octopusdeploy.html">Octopus Deploy</a></li> <li><a href="typescript.html">TypeScript support</a></li> <li class="divider"></li> <li><a href="deploy.html">Fake.Deploy</a></li> <li class="nav-header">Documentation</li> <li><a href="apidocs/index.html">API Reference</a></li> </ul> </div> </div> </div> <a href="https://github.com/fsharp/FAKE"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png" alt="Fork me on GitHub"></a> </body> </html>
{ "content_hash": "9f9e0b732d368a6c038828272ebaf3c4", "timestamp": "", "source": "github", "line_count": 711, "max_line_length": 698, "avg_line_length": 66.0450070323488, "alnum_prop": 0.617551854849014, "repo_name": "Elders/Hermes", "id": "dc1a1733824c403aca41b532fd140880265ef060", "size": "46958", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/FAKE/docs/gettingstarted.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "14880" }, { "name": "F#", "bytes": "5737" }, { "name": "Shell", "bytes": "129" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="/static/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="/static/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous"> <link href="/static/css/fonts.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="/static/css/mit_app_inventor.css"> <script type="text/javascript"> <!--//--><![CDATA[// ><!-- var gotoappinventor = function() { var referrer = document.location.pathname; var patt = /.*hour-of-code.*/; if (referrer.match(patt)) { window.open("http://code.appinventor.mit.edu/", "new"); } else { window.open("http://ai2.appinventor.mit.edu/", "new"); } } //--><!]]> </script> <title>Connectivity</title></head> <body class="mit_app_inventor"><nav class="navbar navbar-expand-xl navbar-light"> <a class="navbar-brand" href="http://appinventor.mit.edu/"> <img src="/static/images/logo2.png" alt="Logo"> </a> <button type="button" class="btn create-btn" style="margin-right: 20px;" onclick="gotoappinventor();">Create Apps!</button> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarContent" aria-controls="navbarContent" aria-expanded="false" aria-label="Toggle Navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarContent"> <ul class="navbar-nav" style="margin-left: auto;"> <li class="nav-item dropdown"> <a class="nav-link" href="http://appinventor.mit.edu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> About </a> <div class="dropdown-menu"> <a class="dropdown-item" href="http://appinventor.mit.edu/about-us">About App Inventor</a> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/our-team">Our Team</a> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/master-trainers">Master Trainers</a> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/app-month-gallery">App of the Month</a> <a class="dropdown-item" href="http://appinventor.mit.edu/ai2/ReleaseNotes">Release Notes</a> <a class="dropdown-item" href="http://appinventor.mit.edu/about/termsofservice" target="_blank">Terms of Service</a> </div> </li> <li class="nav-item dropdown"> <a class="nav-link" href="http://appinventor.mit.edu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Educators </a> <div class="dropdown-menu"> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/teach" target="_blank">Teach</a> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/ai2/tutorials">Tutorials</a> </div> </li> <li class="nav-item dropdown"> <a class="nav-link" href="http://appinventor.mit.edu/news" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> News </a> <div class="dropdown-menu"> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/news">In the news</a> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/events">Events</a> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/stories">Stories from the field</a> </div> </li> <li class="nav-item dropdown"> <a class="nav-link" href="http://appinventor.mit.edu/explore/resources" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Resources </a> <div class="dropdown-menu"> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/get-started">Get Started</a> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/library">Documentation</a> <a class="dropdown-item" href="https://community.appinventor.mit.edu" target="_blank">Forums</a> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/ai2/tutorials">Tutorials</a> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/books">App Inventor Books</a> <a class="dropdown-item" href="https://github.com/mit-cml/appinventor-sources" target="_blank">Open Source Information</a> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/research">Research</a> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/hour-of-code">Hour of Code</a> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/resources">Additional Resources</a> </div> </li> <li class="nav-item dropdown"> <a class="nav-link" href="http://appinventor.mit.edu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Blogs </a> <div class="dropdown-menu"> <a class="dropdown-item" href="http://appinventor.mit.edu/explore/blog">App Inventor Blog</a> </div> </li> </ul> <div style="display: inline-flex;margin-left:auto;margin-right:0"> <a href="https://giving.mit.edu/give/to?fundId=3832320" target="_blank"> <button type="button" class="btn donate-btn" style="margin-right: 20px;">Donate</button></a> <script> (function() { var cx = '005719495929270354943:tlvxrelje-e'; var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//www.google.com/cse/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); })(); </script> <gcse:searchbox-only></gcse:searchbox-only> </div> <!-- <form class="form-inline" action="/action_page.php"> <div class="form-group has-search"> <span class="fa fa-search form-control-feedback"></span> <input type="text" class="form-control" placeholder="Search"> </div> </form> --> </div> </nav> <div class="default-page"> <div class="header"> <h1 class="font-weight-bold text-center offset-xl-2 col-xl-8">Connectivity</h1> </div> <div class="container-fluid"> <article class="documentation"> <p><a href="index.html">« Back to index</a></p> <h1 id="connectivity">Connectivity</h1> <p>Table of Contents:</p> <ul> <li><a href="#ActivityStarter">ActivityStarter</a></li> <li><a href="#BluetoothClient">BluetoothClient</a></li> <li><a href="#BluetoothServer">BluetoothServer</a></li> <li><a href="#Serial">Serial</a></li> <li><a href="#Web">Web</a></li> </ul> <h2 id="ActivityStarter">ActivityStarter</h2> <p>A component that can launch an activity using the StartActivity method.</p> <p>Activities that can be launched include:</p> <ul> <li>Starting another App Inventor for Android app. To do so, first find out the class of the other application by downloading the source code and using a file explorer or unzip utility to find a file named “youngandroidproject/project.properties”. The first line of the file will start with “main=” and be followed by the class name; for example, <code class="highlighter-rouge">main=com.gmail.Bitdiddle.Ben.HelloPurr.Screen1</code>. (The first components indicate that it was created by Ben.Bitdiddle@gmail.com.) To make your <code class="highlighter-rouge">ActivityStarter</code> launch this application, set the following properties: <ul> <li><code class="highlighter-rouge">ActivityPackage</code> to the class name, dropping the last component (for example, <code class="highlighter-rouge">com.gmail.Bitdiddle.Ben.HelloPurr</code>)</li> <li><code class="highlighter-rouge">ActivityClass</code> to the entire class name (for example, <code class="highlighter-rouge">com.gmail.Bitdiddle.Ben.HelloPurr.Screen1</code>)</li> </ul> </li> <li>Starting the camera application by setting the following properties: <ul> <li><code class="highlighter-rouge">Action</code>: <code class="highlighter-rouge">android.intent.action.MAIN</code></li> <li><code class="highlighter-rouge">ActivityPackage</code>: <code class="highlighter-rouge">com.android.camera</code></li> <li><code class="highlighter-rouge">ActivityClass</code>: <code class="highlighter-rouge">com.android.camera.Camera</code></li> </ul> </li> <li>Performing web search. Assuming the term you want to search for is “vampire” (feel free to substitute your own choice), set the properties to: <ul> <li><code class="highlighter-rouge">Action</code>: <code class="highlighter-rouge">android.intent.action.WEB_SEARCH</code></li> <li><code class="highlighter-rouge">ExtraKey</code>: <code class="highlighter-rouge">query</code></li> <li><code class="highlighter-rouge">ExtraValue</code>: <code class="highlighter-rouge">vampire</code></li> <li><code class="highlighter-rouge">ActivityPackage</code>: <code class="highlighter-rouge">com.google.android.providers.enhancedgooglesearch</code></li> <li><code class="highlighter-rouge">ActivityClass</code>: <code class="highlighter-rouge">com.google.android.providers.enhancedgooglesearch.Launcher</code></li> </ul> </li> <li>Opening a browser to a specified web page. Assuming the page you want to go to is “www.facebook.com” (feel free to substitute your own choice), set the properties to: <ul> <li><code class="highlighter-rouge">Action</code>: <code class="highlighter-rouge">android.intent.action.VIEW</code></li> <li><code class="highlighter-rouge">DataUri</code>: <code class="highlighter-rouge">http://www.facebook.com</code></li> </ul> </li> </ul> <h3 id="ActivityStarter-Properties">Properties</h3> <dl class="properties"> <dt id="ActivityStarter.Action" class="text"><em>Action</em></dt> <dd>Specifies the action that will be used to start the activity.</dd> <dt id="ActivityStarter.ActivityClass" class="text"><em>ActivityClass</em></dt> <dd>Specifies the class part of the specific component that will be started.</dd> <dt id="ActivityStarter.ActivityPackage" class="text"><em>ActivityPackage</em></dt> <dd>Specifies the package part of the specific component that will be started.</dd> <dt id="ActivityStarter.DataType" class="text"><em>DataType</em></dt> <dd>Specifies the MIME type to pass to the activity.</dd> <dt id="ActivityStarter.DataUri" class="text"><em>DataUri</em></dt> <dd>Specifies the data URI that will be used to start the activity.</dd> <dt id="ActivityStarter.ExtraKey" class="text"><em>ExtraKey</em></dt> <dd>Specifies the extra key that will be passed to the activity. Obsolete. Should use Extras instead</dd> <dt id="ActivityStarter.ExtraValue" class="text"><em>ExtraValue</em></dt> <dd>Specifies the extra value that will be passed to the activity. Obsolete. Should use Extras instead</dd> <dt id="ActivityStarter.Extras" class="list bo"><em>Extras</em></dt> <dd>Returns the list of key-value pairs that will be passed as extra data to the activity.</dd> <dt id="ActivityStarter.Result" class="text ro bo"><em>Result</em></dt> <dd>Returns the result from the activity.</dd> <dt id="ActivityStarter.ResultName" class="text"><em>ResultName</em></dt> <dd>Specifies the name that will be used to retrieve a result from the activity.</dd> <dt id="ActivityStarter.ResultType" class="text ro bo"><em>ResultType</em></dt> <dd>Returns the MIME type from the activity.</dd> <dt id="ActivityStarter.ResultUri" class="text ro bo"><em>ResultUri</em></dt> <dd>Returns the URI from the activity.</dd> </dl> <h3 id="ActivityStarter-Events">Events</h3> <dl class="events"> <dt id="ActivityStarter.ActivityCanceled">ActivityCanceled()</dt> <dd>Event raised if this `ActivityStarter returns because the activity was canceled.</dd> <dt id="ActivityStarter.AfterActivity">AfterActivity(<em class="text">result</em>)</dt> <dd>Event raised after this <code class="highlighter-rouge">ActivityStarter</code> returns.</dd> </dl> <h3 id="ActivityStarter-Methods">Methods</h3> <dl class="methods"> <dt id="ActivityStarter.ResolveActivity" class="method returns text"><i></i> ResolveActivity()</dt> <dd>Returns the name of the activity that corresponds to this <code class="highlighter-rouge">ActivityStarter</code>, or an empty string if no corresponding activity can be found.</dd> <dt id="ActivityStarter.StartActivity" class="method"><i></i> StartActivity()</dt> <dd>Start the activity corresponding to this <code class="highlighter-rouge">ActivityStarter</code>.</dd> </dl> <h2 id="BluetoothClient">BluetoothClient</h2> <p>Use <code class="highlighter-rouge">BluetoothClient</code> to connect your device to other devices using Bluetooth. This component uses the Serial Port Profile (SPP) for communication. If you are interested in using Bluetooth low energy, please see the <a href="http://iot.appinventor.mit.edu/#/bluetoothle/bluetoothleintro">BluetoothLE</a> extension.</p> <h3 id="BluetoothClient-Properties">Properties</h3> <dl class="properties"> <dt id="BluetoothClient.AddressesAndNames" class="list ro bo"><em>AddressesAndNames</em></dt> <dd>Returns the list of paired Bluetooth devices. Each element of the returned list is a String consisting of the device’s address, a space, and the device’s name.</dd> <dt id="BluetoothClient.Available" class="boolean ro bo"><em>Available</em></dt> <dd>Returns <code class="logic block highlighter-rouge">true</code> if Bluetooth is available on the device, <code class="logic block highlighter-rouge">false</code> otherwise.</dd> <dt id="BluetoothClient.CharacterEncoding" class="text"><em>CharacterEncoding</em></dt> <dd>Returns the character encoding to use when sending and receiving text.</dd> <dt id="BluetoothClient.DelimiterByte" class="number"><em>DelimiterByte</em></dt> <dd>Returns the delimiter byte to use when passing a negative number for the numberOfBytes parameter when calling ReceiveText, ReceiveSignedBytes, or ReceiveUnsignedBytes.</dd> <dt id="BluetoothClient.DisconnectOnError" class="boolean"><em>DisconnectOnError</em></dt> <dd>Specifies whether BluetoothClient/BluetoothServer should be disconnected automatically when an error occurs.</dd> <dt id="BluetoothClient.Enabled" class="boolean ro bo"><em>Enabled</em></dt> <dd>Returns <code class="logic block highlighter-rouge">true</code> if Bluetooth is enabled, <code class="logic block highlighter-rouge">false</code> otherwise.</dd> <dt id="BluetoothClient.HighByteFirst" class="boolean"><em>HighByteFirst</em></dt> <dd>Specifies whether numbers are sent and received with the most significant byte first.</dd> <dt id="BluetoothClient.IsConnected" class="boolean ro bo"><em>IsConnected</em></dt> <dd>Returns <code class="logic block highlighter-rouge">frue</code> if a connection to a Bluetooth device has been made.</dd> <dt id="BluetoothClient.Secure" class="boolean"><em>Secure</em></dt> <dd>Specifies whether a secure connection should be used.</dd> </dl> <h3 id="BluetoothClient-Events">Events</h3> <p class="events">None</p> <h3 id="BluetoothClient-Methods">Methods</h3> <dl class="methods"> <dt id="BluetoothClient.BytesAvailableToReceive" class="method returns number"><i></i> BytesAvailableToReceive()</dt> <dd>Returns number of bytes available from the input stream.</dd> <dt id="BluetoothClient.Connect" class="method returns boolean"><i></i> Connect(<em class="text">address</em>)</dt> <dd>Connect to a Bluetooth device with the given address.</dd> <dt id="BluetoothClient.ConnectWithUUID" class="method returns boolean"><i></i> ConnectWithUUID(<em class="text">address</em>,<em class="text">uuid</em>)</dt> <dd>Connect to a Bluetooth device with the given address and a specific UUID.</dd> <dt id="BluetoothClient.Disconnect" class="method"><i></i> Disconnect()</dt> <dd>Disconnects from the connected Bluetooth device.</dd> <dt id="BluetoothClient.IsDevicePaired" class="method returns boolean"><i></i> IsDevicePaired(<em class="text">address</em>)</dt> <dd>Checks whether the Bluetooth device with the given address is paired.</dd> <dt id="BluetoothClient.ReceiveSigned1ByteNumber" class="method returns number"><i></i> ReceiveSigned1ByteNumber()</dt> <dd>Reads a signed 1-byte number.</dd> <dt id="BluetoothClient.ReceiveSigned2ByteNumber" class="method returns number"><i></i> ReceiveSigned2ByteNumber()</dt> <dd>Reads a signed 2-byte number.</dd> <dt id="BluetoothClient.ReceiveSigned4ByteNumber" class="method returns number"><i></i> ReceiveSigned4ByteNumber()</dt> <dd>Reads a signed 4-byte number.</dd> <dt id="BluetoothClient.ReceiveSignedBytes" class="method returns list"><i></i> ReceiveSignedBytes(<em class="number">numberOfBytes</em>)</dt> <dd>Reads a number of signed bytes from the input stream and returns them as a List. <p>If numberOfBytes is negative, this method reads until a delimiter byte value is read. The delimiter byte value is included in the returned list.</p> </dd> <dt id="BluetoothClient.ReceiveText" class="method returns text"><i></i> ReceiveText(<em class="number">numberOfBytes</em>)</dt> <dd>Reads a number of bytes from the input stream and converts them to text. <p>If numberOfBytes is negative, read until a delimiter byte value is read.</p> </dd> <dt id="BluetoothClient.ReceiveUnsigned1ByteNumber" class="method returns number"><i></i> ReceiveUnsigned1ByteNumber()</dt> <dd>Reads an unsigned 1-byte number.</dd> <dt id="BluetoothClient.ReceiveUnsigned2ByteNumber" class="method returns number"><i></i> ReceiveUnsigned2ByteNumber()</dt> <dd>Reads an unsigned 2-byte number.</dd> <dt id="BluetoothClient.ReceiveUnsigned4ByteNumber" class="method returns number"><i></i> ReceiveUnsigned4ByteNumber()</dt> <dd>Reads an unsigned 4-byte number.</dd> <dt id="BluetoothClient.ReceiveUnsignedBytes" class="method returns list"><i></i> ReceiveUnsignedBytes(<em class="number">numberOfBytes</em>)</dt> <dd>Reads a number of unsigned bytes from the input stream and returns them as a List. <p>If numberOfBytes is negative, this method reads until a delimiter byte value is read. The delimiter byte value is included in the returned list.</p> </dd> <dt id="BluetoothClient.Send1ByteNumber" class="method"><i></i> Send1ByteNumber(<em class="text">number</em>)</dt> <dd>Decodes the given number String to an integer and writes it as one byte to the output stream. <p>If the number could not be decoded to an integer, or the integer would not fit in one byte, then the Form’s ErrorOccurred event is triggered and this method returns without writing any bytes to the output stream.</p> </dd> <dt id="BluetoothClient.Send2ByteNumber" class="method"><i></i> Send2ByteNumber(<em class="text">number</em>)</dt> <dd>Decodes the given number String to an integer and writes it as two bytes to the output stream. <p>If the number could not be decoded to an integer, or the integer would not fit in two bytes, then the Form’s ErrorOccurred event is triggered and this method returns without writing any bytes to the output stream.</p> </dd> <dt id="BluetoothClient.Send4ByteNumber" class="method"><i></i> Send4ByteNumber(<em class="text">number</em>)</dt> <dd>Decodes the given number String to an integer and writes it as four bytes to the output stream. <p>If the number could not be decoded to an integer, or the integer would not fit in four bytes, then the Form’s ErrorOccurred event is triggered and this method returns without writing any bytes to the output stream.</p> </dd> <dt id="BluetoothClient.SendBytes" class="method"><i></i> SendBytes(<em class="list">list</em>)</dt> <dd>Takes each element from the given list, converts it to a String, decodes the String to an integer, and writes it as one byte to the output stream. <p>If an element could not be decoded to an integer, or the integer would not fit in one byte, then the Form’s ErrorOccurred event is triggered and this method returns without writing any bytes to the output stream.</p> </dd> <dt id="BluetoothClient.SendText" class="method"><i></i> SendText(<em class="text">text</em>)</dt> <dd>Converts the given text to bytes and writes them to the output stream.</dd> </dl> <h2 id="BluetoothServer">BluetoothServer</h2> <p>Use the <code class="highlighter-rouge">BluetoothServer</code> component to turn your device into a server that receive connections from other apps that use the <code class="highlighter-rouge">BluetoothClient</code> component.</p> <h3 id="BluetoothServer-Properties">Properties</h3> <dl class="properties"> <dt id="BluetoothServer.Available" class="boolean ro bo"><em>Available</em></dt> <dd>Returns <code class="logic block highlighter-rouge">true</code> if Bluetooth is available on the device, <code class="logic block highlighter-rouge">false</code> otherwise.</dd> <dt id="BluetoothServer.CharacterEncoding" class="text"><em>CharacterEncoding</em></dt> <dd>Returns the character encoding to use when sending and receiving text.</dd> <dt id="BluetoothServer.DelimiterByte" class="number"><em>DelimiterByte</em></dt> <dd>Returns the delimiter byte to use when passing a negative number for the numberOfBytes parameter when calling ReceiveText, ReceiveSignedBytes, or ReceiveUnsignedBytes.</dd> <dt id="BluetoothServer.Enabled" class="boolean ro bo"><em>Enabled</em></dt> <dd>Returns <code class="logic block highlighter-rouge">true</code> if Bluetooth is enabled, <code class="logic block highlighter-rouge">false</code> otherwise.</dd> <dt id="BluetoothServer.HighByteFirst" class="boolean"><em>HighByteFirst</em></dt> <dd>Specifies whether numbers are sent and received with the most significant byte first.</dd> <dt id="BluetoothServer.IsAccepting" class="boolean ro bo"><em>IsAccepting</em></dt> <dd>Returns true if this BluetoothServer component is accepting an incoming connection.</dd> <dt id="BluetoothServer.IsConnected" class="boolean ro bo"><em>IsConnected</em></dt> <dd>Returns <code class="logic block highlighter-rouge">frue</code> if a connection to a Bluetooth device has been made.</dd> <dt id="BluetoothServer.Secure" class="boolean"><em>Secure</em></dt> <dd>Specifies whether a secure connection should be used.</dd> </dl> <h3 id="BluetoothServer-Events">Events</h3> <dl class="events"> <dt id="BluetoothServer.ConnectionAccepted">ConnectionAccepted()</dt> <dd>Indicates that a bluetooth connection has been accepted.</dd> </dl> <h3 id="BluetoothServer-Methods">Methods</h3> <dl class="methods"> <dt id="BluetoothServer.AcceptConnection" class="method"><i></i> AcceptConnection(<em class="text">serviceName</em>)</dt> <dd>Accept an incoming connection with the Serial Port Profile (SPP).</dd> <dt id="BluetoothServer.AcceptConnectionWithUUID" class="method"><i></i> AcceptConnectionWithUUID(<em class="text">serviceName</em>,<em class="text">uuid</em>)</dt> <dd>Accept an incoming connection with a specific UUID.</dd> <dt id="BluetoothServer.BytesAvailableToReceive" class="method returns number"><i></i> BytesAvailableToReceive()</dt> <dd>Returns number of bytes available from the input stream.</dd> <dt id="BluetoothServer.Disconnect" class="method"><i></i> Disconnect()</dt> <dd>Disconnects from the connected Bluetooth device.</dd> <dt id="BluetoothServer.ReceiveSigned1ByteNumber" class="method returns number"><i></i> ReceiveSigned1ByteNumber()</dt> <dd>Reads a signed 1-byte number.</dd> <dt id="BluetoothServer.ReceiveSigned2ByteNumber" class="method returns number"><i></i> ReceiveSigned2ByteNumber()</dt> <dd>Reads a signed 2-byte number.</dd> <dt id="BluetoothServer.ReceiveSigned4ByteNumber" class="method returns number"><i></i> ReceiveSigned4ByteNumber()</dt> <dd>Reads a signed 4-byte number.</dd> <dt id="BluetoothServer.ReceiveSignedBytes" class="method returns list"><i></i> ReceiveSignedBytes(<em class="number">numberOfBytes</em>)</dt> <dd>Reads a number of signed bytes from the input stream and returns them as a List. <p>If numberOfBytes is negative, this method reads until a delimiter byte value is read. The delimiter byte value is included in the returned list.</p> </dd> <dt id="BluetoothServer.ReceiveText" class="method returns text"><i></i> ReceiveText(<em class="number">numberOfBytes</em>)</dt> <dd>Reads a number of bytes from the input stream and converts them to text. <p>If numberOfBytes is negative, read until a delimiter byte value is read.</p> </dd> <dt id="BluetoothServer.ReceiveUnsigned1ByteNumber" class="method returns number"><i></i> ReceiveUnsigned1ByteNumber()</dt> <dd>Reads an unsigned 1-byte number.</dd> <dt id="BluetoothServer.ReceiveUnsigned2ByteNumber" class="method returns number"><i></i> ReceiveUnsigned2ByteNumber()</dt> <dd>Reads an unsigned 2-byte number.</dd> <dt id="BluetoothServer.ReceiveUnsigned4ByteNumber" class="method returns number"><i></i> ReceiveUnsigned4ByteNumber()</dt> <dd>Reads an unsigned 4-byte number.</dd> <dt id="BluetoothServer.ReceiveUnsignedBytes" class="method returns list"><i></i> ReceiveUnsignedBytes(<em class="number">numberOfBytes</em>)</dt> <dd>Reads a number of unsigned bytes from the input stream and returns them as a List. <p>If numberOfBytes is negative, this method reads until a delimiter byte value is read. The delimiter byte value is included in the returned list.</p> </dd> <dt id="BluetoothServer.Send1ByteNumber" class="method"><i></i> Send1ByteNumber(<em class="text">number</em>)</dt> <dd>Decodes the given number String to an integer and writes it as one byte to the output stream. <p>If the number could not be decoded to an integer, or the integer would not fit in one byte, then the Form’s ErrorOccurred event is triggered and this method returns without writing any bytes to the output stream.</p> </dd> <dt id="BluetoothServer.Send2ByteNumber" class="method"><i></i> Send2ByteNumber(<em class="text">number</em>)</dt> <dd>Decodes the given number String to an integer and writes it as two bytes to the output stream. <p>If the number could not be decoded to an integer, or the integer would not fit in two bytes, then the Form’s ErrorOccurred event is triggered and this method returns without writing any bytes to the output stream.</p> </dd> <dt id="BluetoothServer.Send4ByteNumber" class="method"><i></i> Send4ByteNumber(<em class="text">number</em>)</dt> <dd>Decodes the given number String to an integer and writes it as four bytes to the output stream. <p>If the number could not be decoded to an integer, or the integer would not fit in four bytes, then the Form’s ErrorOccurred event is triggered and this method returns without writing any bytes to the output stream.</p> </dd> <dt id="BluetoothServer.SendBytes" class="method"><i></i> SendBytes(<em class="list">list</em>)</dt> <dd>Takes each element from the given list, converts it to a String, decodes the String to an integer, and writes it as one byte to the output stream. <p>If an element could not be decoded to an integer, or the integer would not fit in one byte, then the Form’s ErrorOccurred event is triggered and this method returns without writing any bytes to the output stream.</p> </dd> <dt id="BluetoothServer.SendText" class="method"><i></i> SendText(<em class="text">text</em>)</dt> <dd>Converts the given text to bytes and writes them to the output stream.</dd> <dt id="BluetoothServer.StopAccepting" class="method"><i></i> StopAccepting()</dt> <dd>Stop accepting an incoming connection.</dd> </dl> <h2 id="Serial">Serial</h2> <p>Component for Serial</p> <h3 id="Serial-Properties">Properties</h3> <dl class="properties"> <dt id="Serial.BaudRate" class="number"><em>BaudRate</em></dt> <dd>Returns the current baud rate</dd> <dt id="Serial.BufferSize" class="number"><em>BufferSize</em></dt> <dd>Returns the buffer size in bytes</dd> <dt id="Serial.IsInitialized" class="boolean ro bo"><em>IsInitialized</em></dt> <dd>Returns true when the Serial has been initialized.</dd> <dt id="Serial.IsOpen" class="boolean ro bo"><em>IsOpen</em></dt> <dd>Returns true when the Serial connection is open.</dd> </dl> <h3 id="Serial-Events">Events</h3> <p class="events">None</p> <h3 id="Serial-Methods">Methods</h3> <dl class="methods"> <dt id="Serial.CloseSerial" class="method returns boolean"><i></i> CloseSerial()</dt> <dd>Closes serial connection. Returns true when closed.</dd> <dt id="Serial.InitializeSerial" class="method"><i></i> InitializeSerial()</dt> <dd>Initializes serial connection.</dd> <dt id="Serial.OpenSerial" class="method returns boolean"><i></i> OpenSerial()</dt> <dd>Opens serial connection. Returns true when opened.</dd> <dt id="Serial.PrintSerial" class="method"><i></i> PrintSerial(<em class="text">data</em>)</dt> <dd>Writes given data to serial, and appends a new line at the end.</dd> <dt id="Serial.ReadSerial" class="method returns text"><i></i> ReadSerial()</dt> <dd>Reads data from serial.</dd> <dt id="Serial.WriteSerial" class="method"><i></i> WriteSerial(<em class="text">data</em>)</dt> <dd>Writes given data to serial.</dd> </dl> <h2 id="Web">Web</h2> <p>Non-visible component that provides functions for HTTP GET, POST, PUT, and DELETE requests.</p> <h3 id="Web-Properties">Properties</h3> <dl class="properties"> <dt id="Web.AllowCookies" class="boolean"><em>AllowCookies</em></dt> <dd>Specifies whether cookies should be allowed</dd> <dt id="Web.RequestHeaders" class="list bo"><em>RequestHeaders</em></dt> <dd>Sets the request headers.</dd> <dt id="Web.ResponseFileName" class="text"><em>ResponseFileName</em></dt> <dd>Specifies the name of the file where the response should be saved. If SaveResponse is true and ResponseFileName is empty, then a new file name will be generated.</dd> <dt id="Web.SaveResponse" class="boolean"><em>SaveResponse</em></dt> <dd>Specifies whether the response should be saved in a file.</dd> <dt id="Web.Timeout" class="number"><em>Timeout</em></dt> <dd>Returns the number of milliseconds that each request will wait for a response before they time out. If set to 0, then the request will wait for a response indefinitely.</dd> <dt id="Web.Url" class="text"><em>Url</em></dt> <dd>Specifies the URL.</dd> </dl> <h3 id="Web-Events">Events</h3> <dl class="events"> <dt id="Web.GotFile">GotFile(<em class="text">url</em>,<em class="number">responseCode</em>,<em class="text">responseType</em>,<em class="text">fileName</em>)</dt> <dd>Event indicating that a request has finished.</dd> <dt id="Web.GotText">GotText(<em class="text">url</em>,<em class="number">responseCode</em>,<em class="text">responseType</em>,<em class="text">responseContent</em>)</dt> <dd>Event indicating that a request has finished.</dd> <dt id="Web.TimedOut">TimedOut(<em class="text">url</em>)</dt> <dd>Event indicating that a request has timed out.</dd> </dl> <h3 id="Web-Methods">Methods</h3> <dl class="methods"> <dt id="Web.BuildRequestData" class="method returns text"><i></i> BuildRequestData(<em class="list">list</em>)</dt> <dd>Converts a list of two-element sublists, representing name and value pairs, to a string formatted as application/x-www-form-urlencoded media type, suitable to pass to PostText.</dd> <dt id="Web.ClearCookies" class="method"><i></i> ClearCookies()</dt> <dd>Clears all cookies for this Web component.</dd> <dt id="Web.Delete" class="method"><i></i> Delete()</dt> <dd>Performs an HTTP DELETE request using the Url property and retrieves the response. <p>If the SaveResponse property is true, the response will be saved in a file and the GotFile event will be triggered. The ResponseFileName property can be used to specify the name of the file.</p> <p>If the SaveResponse property is false, the GotText event will be triggered.</p> </dd> <dt id="Web.Get" class="method"><i></i> Get()</dt> <dd>Performs an HTTP GET request using the Url property and retrieves the response. <p>If the SaveResponse property is true, the response will be saved in a file and the GotFile event will be triggered. The ResponseFileName property can be used to specify the name of the file.</p> <p>If the SaveResponse property is false, the GotText event will be triggered.</p> </dd> <dt id="Web.HtmlTextDecode" class="method returns text"><i></i> HtmlTextDecode(<em class="text">htmlText</em>)</dt> <dd>Decodes the given HTML text value. <p>HTML Character Entities such as <code class="highlighter-rouge">&amp;amp;</code>, <code class="highlighter-rouge">&amp;lt;</code>, <code class="highlighter-rouge">&amp;gt;</code>, <code class="highlighter-rouge">&amp;apos;</code>, and <code class="highlighter-rouge">&amp;quot;</code> are changed to <code class="highlighter-rouge">&amp;</code>, <code class="highlighter-rouge">&lt;</code>, <code class="highlighter-rouge">&gt;</code>, <code class="highlighter-rouge">'</code>, and <code class="highlighter-rouge">"</code>. Entities such as <code class="highlighter-rouge">&amp;#xhhhh;</code>, and <code class="highlighter-rouge">&amp;#nnnn;</code> are changed to the appropriate characters.</p> </dd> <dt id="Web.JsonObjectEncode" class="method returns text"><i></i> JsonObjectEncode(<em class="any">jsonObject</em>)</dt> <dd>Returns the value of a built-in type (i.e., boolean, number, text, list, dictionary) in its JavaScript Object Notation representation. If the value cannot be represented as JSON, the Screen’s ErrorOccurred event will be run, if any, and the Web component will return the empty string.</dd> <dt id="Web.JsonTextDecode" class="method returns any"><i></i> JsonTextDecode(<em class="text">jsonText</em>)</dt> <dd>Decodes the given JSON encoded value to produce a corresponding AppInventor value. A JSON list <code class="highlighter-rouge">[x, y, z]</code> decodes to a list <code class="highlighter-rouge">(x y z)</code>, A JSON object with key A and value B, (denoted as <code class="highlighter-rouge">{A:B}</code>) decodes to a list <code class="highlighter-rouge">((A B))</code>, that is, a list containing the two-element list <code class="highlighter-rouge">(A B)</code>. <p>Use the method <a href="#Web.JsonTextDecodeWithDictionaries">JsonTextDecodeWithDictionaries</a> if you would prefer to get back dictionary objects rather than lists-of-lists in the result.</p> </dd> <dt id="Web.JsonTextDecodeWithDictionaries" class="method returns any"><i></i> JsonTextDecodeWithDictionaries(<em class="text">jsonText</em>)</dt> <dd>Decodes the given JSON encoded value to produce a corresponding App Inventor value. A JSON list [x, y, z] decodes to a list (x y z). A JSON Object with name A and value B, denoted as {a: b} decodes to a dictionary with the key a and value b.</dd> <dt id="Web.PatchFile" class="method"><i></i> PatchFile(<em class="text">path</em>)</dt> <dd>Performs an HTTP PATCH request using the Url property and data from the specified file. <p>If the SaveResponse property is true, the response will be saved in a file and the GotFile event will be triggered. The ResponseFileName property can be used to specify the name of the file.</p> <p>If the SaveResponse property is false, the GotText event will be triggered.</p> </dd> <dt id="Web.PatchText" class="method"><i></i> PatchText(<em class="text">text</em>)</dt> <dd>Performs an HTTP PATCH request using the Url property and the specified text. <p>The characters of the text are encoded using UTF-8 encoding.</p> <p>If the SaveResponse property is true, the response will be saved in a file and the GotFile event will be triggered. The responseFileName property can be used to specify the name of the file.</p> <p>If the SaveResponse property is false, the GotText event will be triggered.</p> </dd> <dt id="Web.PatchTextWithEncoding" class="method"><i></i> PatchTextWithEncoding(<em class="text">text</em>,<em class="text">encoding</em>)</dt> <dd>Performs an HTTP PATCH request using the Url property and the specified text. <p>The characters of the text are encoded using the given encoding.</p> <p>If the SaveResponse property is true, the response will be saved in a file and the GotFile event will be triggered. The ResponseFileName property can be used to specify the name of the file.</p> <p>If the SaveResponse property is false, the GotText event will be triggered.</p> </dd> <dt id="Web.PostFile" class="method"><i></i> PostFile(<em class="text">path</em>)</dt> <dd>Performs an HTTP POST request using the Url property and data from the specified file. <p>If the SaveResponse property is true, the response will be saved in a file and the GotFile event will be triggered. The ResponseFileName property can be used to specify the name of the file.</p> <p>If the SaveResponse property is false, the GotText event will be triggered.</p> </dd> <dt id="Web.PostText" class="method"><i></i> PostText(<em class="text">text</em>)</dt> <dd>Performs an HTTP POST request using the Url property and the specified text. <p>The characters of the text are encoded using UTF-8 encoding.</p> <p>If the SaveResponse property is true, the response will be saved in a file and the GotFile event will be triggered. The responseFileName property can be used to specify the name of the file.</p> <p>If the SaveResponse property is false, the GotText event will be triggered.</p> </dd> <dt id="Web.PostTextWithEncoding" class="method"><i></i> PostTextWithEncoding(<em class="text">text</em>,<em class="text">encoding</em>)</dt> <dd>Performs an HTTP POST request using the Url property and the specified text. <p>The characters of the text are encoded using the given encoding.</p> <p>If the SaveResponse property is true, the response will be saved in a file and the GotFile event will be triggered. The ResponseFileName property can be used to specify the name of the file.</p> <p>If the SaveResponse property is false, the GotText event will be triggered.</p> </dd> <dt id="Web.PutFile" class="method"><i></i> PutFile(<em class="text">path</em>)</dt> <dd>Performs an HTTP PUT request using the Url property and data from the specified file. <p>If the SaveResponse property is true, the response will be saved in a file and the GotFile event will be triggered. The ResponseFileName property can be used to specify the name of the file.</p> <p>If the SaveResponse property is false, the GotText event will be triggered.</p> </dd> <dt id="Web.PutText" class="method"><i></i> PutText(<em class="text">text</em>)</dt> <dd>Performs an HTTP PUT request using the Url property and the specified text. <p>The characters of the text are encoded using UTF-8 encoding.</p> <p>If the SaveResponse property is true, the response will be saved in a file and the GotFile event will be triggered. The responseFileName property can be used to specify the name of the file.</p> <p>If the SaveResponse property is false, the GotText event will be triggered.</p> </dd> <dt id="Web.PutTextWithEncoding" class="method"><i></i> PutTextWithEncoding(<em class="text">text</em>,<em class="text">encoding</em>)</dt> <dd>Performs an HTTP PUT request using the Url property and the specified text. <p>The characters of the text are encoded using the given encoding.</p> <p>If the SaveResponse property is true, the response will be saved in a file and the GotFile event will be triggered. The ResponseFileName property can be used to specify the name of the file.</p> <p>If the SaveResponse property is false, the GotText event will be triggered.</p> </dd> <dt id="Web.UriDecode" class="method returns text"><i></i> UriDecode(<em class="text">text</em>)</dt> <dd>Decodes the encoded text value so that the values aren’t URL encoded anymore.</dd> <dt id="Web.UriEncode" class="method returns text"><i></i> UriEncode(<em class="text">text</em>)</dt> <dd>Encodes the given text value so that it can be used in a URL.</dd> <dt id="Web.XMLTextDecode" class="method returns any"><i></i> XMLTextDecode(<em class="text">XmlText</em>)</dt> <dd>Decodes the given XML string to produce a list structure. <code class="highlighter-rouge">&lt;tag&gt;string&lt;/tag&gt;</code> decodes to a list that contains a pair of tag and string. More generally, if obj1, obj2, … are tag-delimited XML strings, then <code class="highlighter-rouge">&lt;tag&gt;obj1 obj2 ...&lt;/tag&gt;</code> decodes to a list that contains a pair whose first element is tag and whose second element is the list of the decoded obj’s, ordered alphabetically by tags. <p>Examples:</p> <ul> <li><code class="highlighter-rouge">&lt;foo&gt;&lt;123/foo&gt;</code> decodes to a one-item list containing the pair <code class="highlighter-rouge">(foo 123)</code></li> <li><code class="highlighter-rouge">&lt;foo&gt;1 2 3&lt;/foo&gt;</code> decodes to a one-item list containing the pair <code class="highlighter-rouge">(foo "1 2 3")</code></li> <li><code class="highlighter-rouge">&lt;a&gt;&lt;foo&gt;1 2 3&lt;/foo&gt;&lt;bar&gt;456&lt;/bar&gt;&lt;/a&gt;</code> decodes to a list containing the pair <code class="highlighter-rouge">(a X)</code> where X is a 2-item list that contains the pair <code class="highlighter-rouge">(bar 123)</code> and the pair <code class="highlighter-rouge">(foo "1 2 3")</code>.</li> </ul> <p>If the sequence of obj’s mixes tag-delimited and non-tag-delimited items, then the non-tag-delimited items are pulled out of the sequence and wrapped with a “content” tag. For example, decoding <code class="highlighter-rouge">&lt;a&gt;&lt;bar&gt;456&lt;/bar&gt;many&lt;foo&gt;1 2 3&lt;/foo&gt;apples&lt;a&gt;&lt;/code&gt;</code> is similar to above, except that the list X is a 3-item list that contains the additional pair whose first item is the string “content”, and whose second item is the list (many, apples). This method signals an error and returns the empty list if the result is not well-formed XML.</p> </dd> <dt id="Web.XMLTextDecodeAsDictionary" class="method returns any"><i></i> XMLTextDecodeAsDictionary(<em class="text">XmlText</em>)</dt> <dd>Decodes the given XML string to produce a dictionary structure. The dictionary includes the special keys <code class="highlighter-rouge">$tag</code>, <code class="highlighter-rouge">$localName</code>, <code class="highlighter-rouge">$namespace</code>, <code class="highlighter-rouge">$namespaceUri</code>, <code class="highlighter-rouge">$attributes</code>, and <code class="highlighter-rouge">$content</code>, as well as a key for each unique tag for every node, which points to a list of elements of the same structure as described here. <p>The <code class="highlighter-rouge">$tag</code> key is the full tag name, e.g., foo:bar. The <code class="highlighter-rouge">$localName</code> is the local portion of the name (everything after the colon <code class="highlighter-rouge">:</code> character). If a namespace is given (everything before the colon <code class="highlighter-rouge">:</code> character), it is provided in <code class="highlighter-rouge">$namespace</code> and the corresponding URI is given in <code class="highlighter-rouge">$namespaceUri</code>. The attributes are stored in a dictionary in <code class="highlighter-rouge">$attributes</code> and the child nodes are given as a list under <code class="highlighter-rouge">$content</code>.</p> <p><strong>More Information on Special Keys</strong></p> <p>Consider the following XML document:</p> <div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code> <span class="nt">&lt;ex:Book</span> <span class="na">xmlns:ex=</span><span class="s">"http://example.com/"</span><span class="nt">&gt;</span> <span class="nt">&lt;ex:title</span> <span class="na">xml:lang=</span><span class="s">"en"</span><span class="nt">&gt;</span>On the Origin of Species<span class="nt">&lt;/ex:title&gt;</span> <span class="nt">&lt;ex:author&gt;</span>Charles Darwin<span class="nt">&lt;/ex:author&gt;</span> <span class="nt">&lt;/ex:Book&gt;</span> </code></pre></div> </div> <p>When parsed, the <code class="highlighter-rouge">$tag</code> key will be <code class="highlighter-rouge">"ex:Book"</code>, the <code class="highlighter-rouge">$localName</code> key will be <code class="highlighter-rouge">"Book"</code>, the <code class="highlighter-rouge">$namespace</code> key will be <code class="highlighter-rouge">"ex"</code>, <code class="highlighter-rouge">$namespaceUri</code> will be <code class="highlighter-rouge">"http://example.com/"</code>, the <code class="highlighter-rouge">$attributes</code> key will be a dictionary <code class="highlighter-rouge">{}</code> (xmlns is removed for the namespace), and the <code class="highlighter-rouge">$content</code> will be a list of two items representing the decoded <code class="highlighter-rouge">&lt;ex:title&gt;</code> and <code class="highlighter-rouge">&lt;ex:author&gt;</code> elements. The first item, which corresponds to the <code class="highlighter-rouge">&lt;ex:title&gt;</code> element, will have an <code class="highlighter-rouge">$attributes</code> key containing the dictionary <code class="highlighter-rouge">{"xml:lang": "en"}</code>. For each <code class="highlighter-rouge">name=value</code> attribute on an element, a key-value pair mapping <code class="highlighter-rouge">name</code> to <code class="highlighter-rouge">value</code> will exist in the <code class="highlighter-rouge">$attributes</code> dictionary. In addition to these special keys, there will also be <code class="highlighter-rouge">"ex:title"</code> and <code class="highlighter-rouge">"ex:author"</code> to allow lookups faster than having to traverse the <code class="highlighter-rouge">$content</code> list.</p> </dd> </dl> </article> <script> // Handle redirection to documentation based on locale query parameter (if specified) (function() { var locale = window.location.search.match('[&?]locale=([a-zA-Z-]*)'); if (locale) { if (locale[1].indexOf('en') === 0) { // English needs to stay at the top level to not break existing links var page = window.location.pathname.split('/'); if (page.length === 5) { page.splice(2, 1); } else { // already on english return; } window.location.href = page.join('/'); } else { var page = window.location.pathname.split('/'); if (page.length === 4) { page.splice(2, 0, locale[1]); } else if (page[2].toLowerCase() != locale[1].toLowerCase()) { page[2] = locale[1]; } else { return; // already on the desired language } // Test that the page exists before redirecting. var xhr = new XMLHttpRequest(); xhr.open('HEAD', page.join('/'), false); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if ((xhr.status == 200 || xhr.status == 204)) { window.location.href = page.join('/'); } else if (xhr.status >= 400) { page.splice(2, 1); // go to english version window.location.href = page.join('/'); } } }; xhr.send(); } } })(); // Handle embedded documentation in help by removing website template if (window.self !== window.top) { setTimeout(function() { var videos = document.querySelectorAll('video'); for (var i = 0; i < videos.length; i++) { if (parseInt(videos[i].getAttribute('width')) > 360) { var aspect = parseInt(videos[i].getAttribute('height')) / parseInt(videos[i].getAttribute('width')); videos[i].setAttribute('width', '360'); videos[i].setAttribute('height', '' + (360 * aspect)); } } var h1 = document.querySelector('h1'); var article = document.querySelector('article'); article.insertBefore(h1, article.firstElementChild); document.body.innerHTML = article.outerHTML; }); } </script> </div> <div class="footer background-green"> <div class="row container"> <div class="col-xl-3"> <h3>MIT App Inventor</h3> <!-- <form class="form-inline" action="/action_page.php"> <div class="form-group has-search"> <span class="fa fa-search form-control-feedback"></span> <input type="text" class="form-control" placeholder="Search"> </div> </form> --> </div> <div class="col-xl-6 legal text-center"> <ul> <li> <a href="http://web.mit.edu" class="btn btn-link" role="button" target="_blank">© 2012-2020 Massachusetts Institute of Technology</a> </li> <li> <a href="http://creativecommons.org/licenses/by-sa/3.0/" target="_blank" class="btn btn-link" role="button">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0</a> </li> <li> <a href="http://appinventor.mit.edu/about/termsofservice" target="_blank" class="btn btn-link" role="button">Terms of Service and Privacy Policy</a> </li> </ul> </div> <div class="col-xl-3 links"> <a href="https://community.appinventor.mit.edu" target="_blank">Support / Help</a><br> <a href="mailto:appinventor@mit.edu">Other Inquiries</a> <div> <span>Twitter:</span> <a href="https://twitter.com/mitappinventor" target="_blank" class="btn btn-link" role="button">@MITAppInventor</a> <div> <div> <span>GitHub:</span> <a href="https://github.com/mit-cml" class="btn btn-link" role="button" target="_blank">mit-cml</a> <div> </div> </div> </div> </div> </div> </div> </div> <script src="/static/js/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="/static/js/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="/static/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <script async src="/static/js/widgets.js" charset="utf-8"></script> </div> </body> </html>
{ "content_hash": "1fc6a2cc49c75a788c33819a55a0df22", "timestamp": "", "source": "github", "line_count": 873, "max_line_length": 319, "avg_line_length": 59.39289805269187, "alnum_prop": 0.6929990356798457, "repo_name": "josmas/app-inventor", "id": "b1aac701efa52f4e96e6ee3ce0b1d08a0af444c9", "size": "51906", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "appinventor/docs/html/reference/components/connectivity.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "3281" }, { "name": "Batchfile", "bytes": "4359" }, { "name": "CSS", "bytes": "170379" }, { "name": "Dockerfile", "bytes": "535" }, { "name": "HTML", "bytes": "1332403" }, { "name": "Java", "bytes": "8152959" }, { "name": "JavaScript", "bytes": "606954" }, { "name": "Python", "bytes": "205314" }, { "name": "Ruby", "bytes": "1069" }, { "name": "SCSS", "bytes": "12605" }, { "name": "Scheme", "bytes": "159943" }, { "name": "Shell", "bytes": "7949" } ], "symlink_target": "" }
[![Build Status](https://app.travis-ci.com/joaomlneto/travis-ci-tutorial-java.svg?branch=master)](https://app.travis-ci.com/joaomlneto/travis-ci-tutorial-java) [![Code Coverage](https://codecov.io/github/joaomlneto/travis-ci-tutorial-java/coverage.svg)](https://codecov.io/gh/joaomlneto/travis-ci-tutorial-java) # travis-ci-tutorial-java Just to learn how to use travis-ci in a java project! This is a working minimal example of how to use Travis CI (and Codecov) with Java on GitHub. - It uses the [JUnit](https://junit.org) testing framework [Click here for the example using GitHub Actions instead of Travis CI](https://github.com/joaomlneto/github-ci-tutorial-java) # How To Start 1. [Fork](https://github.com/joaomlneto/travis-ci-tutorial-java/fork) this Repository 2. Go to [Travis CI](http://travis-ci.com) and enable the repository 3. Fix the `README.md` badges (replacing in the URL `joaomlneto` with `your-github-username`) and push the changes. This should trigger a build in Travis CI! ## Optional: Code Coverage with CodeCov This repository also integrates with Codecov to generate reports. What's done for you: - The [JaCoCo](https://www.jacoco.org) plugin is included in `pom.xml` - On `.travis.yml`, `after_success` target executes the Codecov script. If you want to use it: - Go to the Codecov website and create an account and setup permissions. - Add your repository (you can go there directly by going to https://codecov.io/gh/your-github-username/travis-ci-tutorial-java) - Fix the `README.md` badge. If you don't want it: - Remove the [JaCoCo](https://www.jacoco.org) plugin from the `pom.xml`. - Remove the `after_success` target in `.travis.yml` - Remove the badge from `README.md` # Contributing Spotted a mistake? Questions? Suggestions? [Open an Issue](https://github.com/joaomlneto/travis-ci-tutorial-java/issues/new)!
{ "content_hash": "f32f4ca28491d8f65fad303d37a4a976", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 159, "avg_line_length": 46.55, "alnum_prop": 0.7556390977443609, "repo_name": "joaomlneto/travis-ci-tutorial-java", "id": "7053910b3e2423f68a0f7557da1047e809114443", "size": "1862", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1032" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_31) on Wed Dec 17 20:48:16 PST 2014 --> <title>MetalFileChooserUI.FilterComboBoxModel (Java Platform SE 8 )</title> <meta name="date" content="2014-12-17"> <meta name="keywords" content="javax.swing.plaf.metal.MetalFileChooserUI.FilterComboBoxModel class"> <meta name="keywords" content="filters"> <meta name="keywords" content="propertyChange()"> <meta name="keywords" content="setSelectedItem()"> <meta name="keywords" content="getSelectedItem()"> <meta name="keywords" content="getSize()"> <meta name="keywords" content="getElementAt()"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="MetalFileChooserUI.FilterComboBoxModel (Java Platform SE 8 )"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/MetalFileChooserUI.FilterComboBoxModel.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;8</strong></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../javax/swing/plaf/metal/MetalFileChooserUI.FileRenderer.html" title="class in javax.swing.plaf.metal"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../javax/swing/plaf/metal/MetalFileChooserUI.FilterComboBoxRenderer.html" title="class in javax.swing.plaf.metal"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?javax/swing/plaf/metal/MetalFileChooserUI.FilterComboBoxModel.html" target="_top">Frames</a></li> <li><a href="MetalFileChooserUI.FilterComboBoxModel.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">javax.swing.plaf.metal</div> <h2 title="Class MetalFileChooserUI.FilterComboBoxModel" class="title">Class MetalFileChooserUI.FilterComboBoxModel</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li><a href="../../../../java/lang/Object.html" title="class in java.lang">java.lang.Object</a></li> <li> <ul class="inheritance"> <li><a href="../../../../javax/swing/AbstractListModel.html" title="class in javax.swing">javax.swing.AbstractListModel</a>&lt;<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>&gt;</li> <li> <ul class="inheritance"> <li>javax.swing.plaf.metal.MetalFileChooserUI.FilterComboBoxModel</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd><a href="../../../../java/beans/PropertyChangeListener.html" title="interface in java.beans">PropertyChangeListener</a>, <a href="../../../../java/io/Serializable.html" title="interface in java.io">Serializable</a>, <a href="../../../../java/util/EventListener.html" title="interface in java.util">EventListener</a>, <a href="../../../../javax/swing/ComboBoxModel.html" title="interface in javax.swing">ComboBoxModel</a>&lt;<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>&gt;, <a href="../../../../javax/swing/ListModel.html" title="interface in javax.swing">ListModel</a>&lt;<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>&gt;</dd> </dl> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../javax/swing/plaf/metal/MetalFileChooserUI.html" title="class in javax.swing.plaf.metal">MetalFileChooserUI</a></dd> </dl> <hr> <br> <pre>protected class <span class="typeNameLabel">MetalFileChooserUI.FilterComboBoxModel</span> extends <a href="../../../../javax/swing/AbstractListModel.html" title="class in javax.swing">AbstractListModel</a>&lt;<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>&gt; implements <a href="../../../../javax/swing/ComboBoxModel.html" title="interface in javax.swing">ComboBoxModel</a>&lt;<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>&gt;, <a href="../../../../java/beans/PropertyChangeListener.html" title="interface in java.beans">PropertyChangeListener</a></pre> <div class="block">Data model for a type-face selection combo-box.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../javax/swing/filechooser/FileFilter.html" title="class in javax.swing.filechooser">FileFilter</a>[]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../javax/swing/plaf/metal/MetalFileChooserUI.FilterComboBoxModel.html#filters">filters</a></span></code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="fields.inherited.from.class.javax.swing.AbstractListModel"> <!-- --> </a> <h3>Fields inherited from class&nbsp;javax.swing.<a href="../../../../javax/swing/AbstractListModel.html" title="class in javax.swing">AbstractListModel</a></h3> <code><a href="../../../../javax/swing/AbstractListModel.html#listenerList">listenerList</a></code></li> </ul> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier</th> <th class="colLast" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected </code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../javax/swing/plaf/metal/MetalFileChooserUI.FilterComboBoxModel.html#FilterComboBoxModel--">FilterComboBoxModel</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code><a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../javax/swing/plaf/metal/MetalFileChooserUI.FilterComboBoxModel.html#getElementAt-int-">getElementAt</a></span>(int&nbsp;index)</code> <div class="block">Returns the value at the specified index.</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code><a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../javax/swing/plaf/metal/MetalFileChooserUI.FilterComboBoxModel.html#getSelectedItem--">getSelectedItem</a></span>()</code> <div class="block">Returns the selected item</div> </td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../javax/swing/plaf/metal/MetalFileChooserUI.FilterComboBoxModel.html#getSize--">getSize</a></span>()</code> <div class="block">Returns the length of the list.</div> </td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../javax/swing/plaf/metal/MetalFileChooserUI.FilterComboBoxModel.html#propertyChange-java.beans.PropertyChangeEvent-">propertyChange</a></span>(<a href="../../../../java/beans/PropertyChangeEvent.html" title="class in java.beans">PropertyChangeEvent</a>&nbsp;e)</code> <div class="block">This method gets called when a bound property is changed.</div> </td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../javax/swing/plaf/metal/MetalFileChooserUI.FilterComboBoxModel.html#setSelectedItem-java.lang.Object-">setSelectedItem</a></span>(<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>&nbsp;filter)</code> <div class="block">Set the selected item.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.javax.swing.AbstractListModel"> <!-- --> </a> <h3>Methods inherited from class&nbsp;javax.swing.<a href="../../../../javax/swing/AbstractListModel.html" title="class in javax.swing">AbstractListModel</a></h3> <code><a href="../../../../javax/swing/AbstractListModel.html#addListDataListener-javax.swing.event.ListDataListener-">addListDataListener</a>, <a href="../../../../javax/swing/AbstractListModel.html#fireContentsChanged-java.lang.Object-int-int-">fireContentsChanged</a>, <a href="../../../../javax/swing/AbstractListModel.html#fireIntervalAdded-java.lang.Object-int-int-">fireIntervalAdded</a>, <a href="../../../../javax/swing/AbstractListModel.html#fireIntervalRemoved-java.lang.Object-int-int-">fireIntervalRemoved</a>, <a href="../../../../javax/swing/AbstractListModel.html#getListDataListeners--">getListDataListeners</a>, <a href="../../../../javax/swing/AbstractListModel.html#getListeners-java.lang.Class-">getListeners</a>, <a href="../../../../javax/swing/AbstractListModel.html#removeListDataListener-javax.swing.event.ListDataListener-">removeListDataListener</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a></h3> <code><a href="../../../../java/lang/Object.html#clone--">clone</a>, <a href="../../../../java/lang/Object.html#equals-java.lang.Object-">equals</a>, <a href="../../../../java/lang/Object.html#finalize--">finalize</a>, <a href="../../../../java/lang/Object.html#getClass--">getClass</a>, <a href="../../../../java/lang/Object.html#hashCode--">hashCode</a>, <a href="../../../../java/lang/Object.html#notify--">notify</a>, <a href="../../../../java/lang/Object.html#notifyAll--">notifyAll</a>, <a href="../../../../java/lang/Object.html#toString--">toString</a>, <a href="../../../../java/lang/Object.html#wait--">wait</a>, <a href="../../../../java/lang/Object.html#wait-long-">wait</a>, <a href="../../../../java/lang/Object.html#wait-long-int-">wait</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.javax.swing.ListModel"> <!-- --> </a> <h3>Methods inherited from interface&nbsp;javax.swing.<a href="../../../../javax/swing/ListModel.html" title="interface in javax.swing">ListModel</a></h3> <code><a href="../../../../javax/swing/ListModel.html#addListDataListener-javax.swing.event.ListDataListener-">addListDataListener</a>, <a href="../../../../javax/swing/ListModel.html#removeListDataListener-javax.swing.event.ListDataListener-">removeListDataListener</a></code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="filters"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>filters</h4> <pre>protected&nbsp;<a href="../../../../javax/swing/filechooser/FileFilter.html" title="class in javax.swing.filechooser">FileFilter</a>[] filters</pre> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="FilterComboBoxModel--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>FilterComboBoxModel</h4> <pre>protected&nbsp;FilterComboBoxModel()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="propertyChange-java.beans.PropertyChangeEvent-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>propertyChange</h4> <pre>public&nbsp;void&nbsp;propertyChange(<a href="../../../../java/beans/PropertyChangeEvent.html" title="class in java.beans">PropertyChangeEvent</a>&nbsp;e)</pre> <div class="block"><span class="descfrmTypeLabel">Description copied from interface:&nbsp;<code><a href="../../../../java/beans/PropertyChangeListener.html#propertyChange-java.beans.PropertyChangeEvent-">PropertyChangeListener</a></code></span></div> <div class="block">This method gets called when a bound property is changed.</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../../java/beans/PropertyChangeListener.html#propertyChange-java.beans.PropertyChangeEvent-">propertyChange</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../java/beans/PropertyChangeListener.html" title="interface in java.beans">PropertyChangeListener</a></code></dd> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>e</code> - A PropertyChangeEvent object describing the event source and the property that has changed.</dd> </dl> </li> </ul> <a name="setSelectedItem-java.lang.Object-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setSelectedItem</h4> <pre>public&nbsp;void&nbsp;setSelectedItem(<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>&nbsp;filter)</pre> <div class="block"><span class="descfrmTypeLabel">Description copied from interface:&nbsp;<code><a href="../../../../javax/swing/ComboBoxModel.html#setSelectedItem-java.lang.Object-">ComboBoxModel</a></code></span></div> <div class="block">Set the selected item. The implementation of this method should notify all registered <code>ListDataListener</code>s that the contents have changed.</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../../javax/swing/ComboBoxModel.html#setSelectedItem-java.lang.Object-">setSelectedItem</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../javax/swing/ComboBoxModel.html" title="interface in javax.swing">ComboBoxModel</a>&lt;<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>&gt;</code></dd> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>filter</code> - the list object to select or <code>null</code> to clear the selection</dd> </dl> </li> </ul> <a name="getSelectedItem--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getSelectedItem</h4> <pre>public&nbsp;<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>&nbsp;getSelectedItem()</pre> <div class="block"><span class="descfrmTypeLabel">Description copied from interface:&nbsp;<code><a href="../../../../javax/swing/ComboBoxModel.html#getSelectedItem--">ComboBoxModel</a></code></span></div> <div class="block">Returns the selected item</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../../javax/swing/ComboBoxModel.html#getSelectedItem--">getSelectedItem</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../javax/swing/ComboBoxModel.html" title="interface in javax.swing">ComboBoxModel</a>&lt;<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>&gt;</code></dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>The selected item or <code>null</code> if there is no selection</dd> </dl> </li> </ul> <a name="getSize--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getSize</h4> <pre>public&nbsp;int&nbsp;getSize()</pre> <div class="block"><span class="descfrmTypeLabel">Description copied from interface:&nbsp;<code><a href="../../../../javax/swing/ListModel.html#getSize--">ListModel</a></code></span></div> <div class="block">Returns the length of the list.</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../../javax/swing/ListModel.html#getSize--">getSize</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../javax/swing/ListModel.html" title="interface in javax.swing">ListModel</a>&lt;<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>&gt;</code></dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the length of the list</dd> </dl> </li> </ul> <a name="getElementAt-int-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getElementAt</h4> <pre>public&nbsp;<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>&nbsp;getElementAt(int&nbsp;index)</pre> <div class="block"><span class="descfrmTypeLabel">Description copied from interface:&nbsp;<code><a href="../../../../javax/swing/ListModel.html#getElementAt-int-">ListModel</a></code></span></div> <div class="block">Returns the value at the specified index.</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../../javax/swing/ListModel.html#getElementAt-int-">getElementAt</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../javax/swing/ListModel.html" title="interface in javax.swing">ListModel</a>&lt;<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>&gt;</code></dd> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>index</code> - the requested index</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the value at <code>index</code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/MetalFileChooserUI.FilterComboBoxModel.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;8</strong></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../javax/swing/plaf/metal/MetalFileChooserUI.FileRenderer.html" title="class in javax.swing.plaf.metal"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../javax/swing/plaf/metal/MetalFileChooserUI.FilterComboBoxRenderer.html" title="class in javax.swing.plaf.metal"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?javax/swing/plaf/metal/MetalFileChooserUI.FilterComboBoxModel.html" target="_top">Frames</a></li> <li><a href="MetalFileChooserUI.FilterComboBoxModel.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://download.oracle.com/javase/8/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../../legal/cpyr.html">Copyright</a> &#x00a9; 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p> </body> </html>
{ "content_hash": "adb846b0c5f5fb957fc08f55b2d0d8cb", "timestamp": "", "source": "github", "line_count": 463, "max_line_length": 889, "avg_line_length": 52.66522678185745, "alnum_prop": 0.6693323490813649, "repo_name": "fbiville/annotation-processing-ftw", "id": "b110198f722a041bd113e79288030ad4bb75a214", "size": "24384", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/java/jdk8/javax/swing/plaf/metal/MetalFileChooserUI.FilterComboBoxModel.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "191178" }, { "name": "HTML", "bytes": "63904" }, { "name": "Java", "bytes": "107042" }, { "name": "JavaScript", "bytes": "246677" } ], "symlink_target": "" }
{-# LANGUAGE FlexibleContexts, FlexibleInstances, GADTs, RecordWildCards, ScopedTypeVariables, StandaloneDeriving, TypeOperators #-} module UI.Layout where import Control.Applicative import Control.Comonad.Cofree.Cofreer import Control.Comonad.Trans.Cofree import Control.Monad.Free.Freer as Freer import Control.Monad.Trans.Free.Freer as FreerF import Data.Fixed import Data.Functor.Algebraic import Data.Functor.Classes import Data.Functor.Foldable hiding (unfold) import Data.Functor.Listable import Data.Functor.Union import Data.Maybe (catMaybes, fromMaybe) import Data.Semigroup import Data.Typeable import UI.Geometry data Alignment = Leading | Trailing | Centre | Full deriving (Eq, Ord, Show) data LayoutF a f where Inset :: Size a -> f -> LayoutF a f Offset :: Point a -> f -> LayoutF a f GetMaxSize :: LayoutF a (Size (Maybe a)) Align :: Alignment -> f -> LayoutF a f type Layout a = Freer (LayoutF a) type ALayout a b = Cofreer (FreerF (LayoutF a) b) -- Smart constructors inset :: InUnion fs (LayoutF a) => Size a -> Freer (Union fs) b -> Freer (Union fs) b inset by = wrapU . Inset by offset :: InUnion fs (LayoutF a) => Point a -> Freer (Union fs) b -> Freer (Union fs) b offset by = wrapU . Offset by resizeable :: InUnion fs (LayoutF a) => (Size (Maybe a) -> Freer (Union fs) b) -> Freer (Union fs) b resizeable = (getMaxSize >>=) getMaxSize :: InUnion fs (LayoutF a) => Freer (Union fs) (Size (Maybe a)) getMaxSize = inj GetMaxSize `Freer.Then` return stack :: (InUnion fs (LayoutF a), Real a) => Freer (Union fs) (Size a) -> Freer (Union fs) (Size a) -> Freer (Union fs) (Size a) stack top bottom = do Size w1 h1 <- top Size w2 h2 <- offset (Point 0 h1) bottom pure $ Size (max w1 w2) (h1 + h2) adjacent :: (InUnion fs (LayoutF a), Real a) => Freer (Union fs) (Size a) -> Freer (Union fs) (Size a) -> Freer (Union fs) (Size a) adjacent left right = do Size w1 h1 <- left Size w2 h2 <- offset (Point w1 0) right pure $ Size w2 (max h1 h2) alignLeft :: Layout a b -> Layout a b alignLeft = wrap . Align Leading alignRight :: Layout a b -> Layout a b alignRight = wrap . Align Trailing alignCentre :: Layout a b -> Layout a b alignCentre = wrap . Align Centre alignFull :: Layout a b -> Layout a b alignFull = wrap . Align Full align :: Alignment -> Layout a b -> Layout a b align = (wrap .) . Align -- Evaluation measureLayoutSize :: Real a => Layout a (Size a) -> Size a measureLayoutSize = maybe (Size 0 0) size . fitLayout (pure Nothing) fitLayoutSize :: Real a => Size (Maybe a) -> Layout a (Size a) -> Maybe (Size a) fitLayoutSize = (fmap size .) . fitLayout measureLayout :: Real a => Layout a (Size a) -> Rect a measureLayout = fromMaybe (Rect (Point 0 0) (Size 0 0)) . fitLayout (pure Nothing) fitLayout :: Real a => Size (Maybe a) -> Layout a (Size a) -> Maybe (Rect a) fitLayout = fitLayoutWith layoutAlgebra layoutAlgebra :: Real a => Algebra (Fitting (LayoutF a) a) (Maybe (Rect a)) layoutAlgebra (FittingState{..} :< layout) = case layout of FreerF.Return size | maxSize `encloses` size -> Just $ case alignment of Leading -> Rect origin minSize Trailing -> Rect origin { x = x origin + widthDiff} minSize Centre -> Rect origin { x = x origin + fromIntegral (widthDiff `div'` 2 :: Int)} minSize Full -> Rect origin fullSize where minSize = fullSize { width = width size } fullSize = fromMaybe <$> size <*> maxSize widthDiff = maybe 0 (+ negate (width size)) (width maxSize) layout `FreerF.Then` runF -> case layout of Inset by child -> Rect origin . (2 * by +) . size <$> runF child Offset by child -> Rect origin . (pointSize by +) . size <$> runF child GetMaxSize -> runF maxSize Align _ child -> do Rect _ size <- runF child pure $ Rect origin (fromMaybe <$> size <*> maxSize) _ -> Nothing where maxSize `encloses` size = and (maybe (const True) (>=) <$> maxSize <*> size) layoutRectanglesAlgebra :: Real a => Algebra (Fitting (LayoutF a) a) [Rect a] layoutRectanglesAlgebra = wrapAlgebra catMaybes (fmap Just) (collect layoutAlgebra) type Fitting f a = Bidi (FreerF f (Size a)) (FittingState a) data FittingState a = FittingState { alignment :: !Alignment, origin :: !(Point a), maxSize :: !(Size (Maybe a)) } deriving (Eq, Show) fitLayoutWith :: Real a => Algebra (Fitting (LayoutF a) a) b -> Size (Maybe a) -> Layout a (Size a) -> b fitLayoutWith algebra maxSize layout = hylo algebra layoutCoalgebra (FittingState Full (Point 0 0) maxSize :< project layout) layoutCoalgebra :: Real a => Coalgebra (Fitting (LayoutF a) a) (Fitting (LayoutF a) a (Layout a (Size a))) layoutCoalgebra = liftBidiCoalgebra layoutFCoalgebra layoutFCoalgebra :: Real a => CoalgebraFragment (LayoutF a) (FittingState a) (Size a) layoutFCoalgebra state@FittingState{..} run layoutF = case layoutF of Inset by child -> wrapState (FittingState alignment (addSizeToPoint origin by) (subtractSize maxSize (2 * by))) $ Inset by child Offset by child -> wrapState (FittingState alignment (liftA2 (+) origin by) (subtractSize maxSize (pointSize by))) $ Offset by child GetMaxSize -> wrapState state GetMaxSize Align alignment child -> wrapState (state { alignment = alignment }) $ Align alignment child where wrapState state = flip FreerF.Then (run state) subtractSize maxSize size = liftA2 (-) <$> maxSize <*> (Just <$> size) addSizeToPoint point = liftA2 (+) point . sizeExtent -- Instances instance (InUnion fs (LayoutF a), Real a) => Semigroup (Freer (Union fs) (Size a)) where (<>) = stack deriving instance Foldable (LayoutF a) instance (Show a, Show b) => Show (LayoutF a b) where showsPrec = liftShowsPrec showsPrec showList instance Show a => Show1 (LayoutF a) where liftShowsPrec sp _ d layout = case layout of Inset by child -> showsBinaryWith showsPrec sp "Inset" d by child Offset by child -> showsBinaryWith showsPrec sp "Offset" d by child GetMaxSize -> showString "GetMaxSize" Align alignment child -> showsBinaryWith showsPrec sp "AlignLeft" d alignment child instance Eq2 LayoutF where liftEq2 eqA eqF l1 l2 = case (l1, l2) of (Inset s1 c1, Inset s2 c2) -> liftEq eqA s1 s2 && eqF c1 c2 (Offset p1 c1, Offset p2 c2) -> liftEq eqA p1 p2 && eqF c1 c2 (GetMaxSize, GetMaxSize) -> True (Align a1 c1, Align a2 c2) -> a1 == a2 && eqF c1 c2 _ -> False instance Eq a => Eq1 (LayoutF a) where liftEq = liftEq2 (==) instance (Eq a, Eq f) => Eq (LayoutF a f) where (==) = liftEq (==) instance Listable2 LayoutF where liftTiers2 t1 t2 = liftCons2 (liftTiers t1) t2 Inset \/ liftCons2 (liftTiers t1) t2 Offset \/ liftCons2 tiers t2 Align instance Listable a => Listable1 (LayoutF a) where liftTiers = liftTiers2 tiers instance (Typeable a, Typeable b, Listable a, Listable b) => Listable (LayoutF a b) where tiers = case eqT :: Maybe (b :~: Size (Maybe a)) of Just Refl -> tiers1 \/ cons0 GetMaxSize Nothing -> tiers1 instance Listable Alignment where tiers = cons0 Leading \/ cons0 Trailing \/ cons0 Centre \/ cons0 Full
{ "content_hash": "e881520d936417c131758d3af75ab426", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 134, "avg_line_length": 37.962566844919785, "alnum_prop": 0.6851669249190027, "repo_name": "robrix/ui-effects", "id": "5cdab41dd08e3b45e2630326ff7cfd5468248889", "size": "7099", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/UI/Layout.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Haskell", "bytes": "73257" } ], "symlink_target": "" }
/** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #ifndef PingPong_H #define PingPong_H #include <thrift/TDispatchProcessor.h> #include "PingPong_types.h" class PingPongIf { public: virtual ~PingPongIf() {} virtual void ping(std::string& _return) = 0; }; class PingPongIfFactory { public: typedef PingPongIf Handler; virtual ~PingPongIfFactory() {} virtual PingPongIf* getHandler(const ::apache::thrift::TConnectionInfo& connInfo) = 0; virtual void releaseHandler(PingPongIf* /* handler */) = 0; }; class PingPongIfSingletonFactory : virtual public PingPongIfFactory { public: PingPongIfSingletonFactory(const boost::shared_ptr<PingPongIf>& iface) : iface_(iface) {} virtual ~PingPongIfSingletonFactory() {} virtual PingPongIf* getHandler(const ::apache::thrift::TConnectionInfo&) { return iface_.get(); } virtual void releaseHandler(PingPongIf* /* handler */) {} protected: boost::shared_ptr<PingPongIf> iface_; }; class PingPongNull : virtual public PingPongIf { public: virtual ~PingPongNull() {} void ping(std::string& /* _return */) { return; } }; class PingPong_ping_args { public: PingPong_ping_args() { } virtual ~PingPong_ping_args() throw() {} bool operator == (const PingPong_ping_args & /* rhs */) const { return true; } bool operator != (const PingPong_ping_args &rhs) const { return !(*this == rhs); } bool operator < (const PingPong_ping_args & ) const; uint32_t read(::apache::thrift::protocol::TProtocol* iprot); uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const; }; class PingPong_ping_pargs { public: virtual ~PingPong_ping_pargs() throw() {} uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const; }; typedef struct _PingPong_ping_result__isset { _PingPong_ping_result__isset() : success(false) {} bool success; } _PingPong_ping_result__isset; class PingPong_ping_result { public: PingPong_ping_result() : success() { } virtual ~PingPong_ping_result() throw() {} std::string success; _PingPong_ping_result__isset __isset; void __set_success(const std::string& val) { success = val; } bool operator == (const PingPong_ping_result & rhs) const { if (!(success == rhs.success)) return false; return true; } bool operator != (const PingPong_ping_result &rhs) const { return !(*this == rhs); } bool operator < (const PingPong_ping_result & ) const; uint32_t read(::apache::thrift::protocol::TProtocol* iprot); uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const; }; typedef struct _PingPong_ping_presult__isset { _PingPong_ping_presult__isset() : success(false) {} bool success; } _PingPong_ping_presult__isset; class PingPong_ping_presult { public: virtual ~PingPong_ping_presult() throw() {} std::string* success; _PingPong_ping_presult__isset __isset; uint32_t read(::apache::thrift::protocol::TProtocol* iprot); }; class PingPongClient : virtual public PingPongIf { public: PingPongClient(boost::shared_ptr< ::apache::thrift::protocol::TProtocol> prot) : piprot_(prot), poprot_(prot) { iprot_ = prot.get(); oprot_ = prot.get(); } PingPongClient(boost::shared_ptr< ::apache::thrift::protocol::TProtocol> iprot, boost::shared_ptr< ::apache::thrift::protocol::TProtocol> oprot) : piprot_(iprot), poprot_(oprot) { iprot_ = iprot.get(); oprot_ = oprot.get(); } boost::shared_ptr< ::apache::thrift::protocol::TProtocol> getInputProtocol() { return piprot_; } boost::shared_ptr< ::apache::thrift::protocol::TProtocol> getOutputProtocol() { return poprot_; } void ping(std::string& _return); void send_ping(); void recv_ping(std::string& _return); protected: boost::shared_ptr< ::apache::thrift::protocol::TProtocol> piprot_; boost::shared_ptr< ::apache::thrift::protocol::TProtocol> poprot_; ::apache::thrift::protocol::TProtocol* iprot_; ::apache::thrift::protocol::TProtocol* oprot_; }; class PingPongProcessor : public ::apache::thrift::TDispatchProcessor { protected: boost::shared_ptr<PingPongIf> iface_; virtual bool dispatchCall(::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, const std::string& fname, int32_t seqid, void* callContext); private: typedef void (PingPongProcessor::*ProcessFunction)(int32_t, ::apache::thrift::protocol::TProtocol*, ::apache::thrift::protocol::TProtocol*, void*); typedef std::map<std::string, ProcessFunction> ProcessMap; ProcessMap processMap_; void process_ping(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext); public: PingPongProcessor(boost::shared_ptr<PingPongIf> iface) : iface_(iface) { processMap_["ping"] = &PingPongProcessor::process_ping; } virtual ~PingPongProcessor() {} }; class PingPongProcessorFactory : public ::apache::thrift::TProcessorFactory { public: PingPongProcessorFactory(const ::boost::shared_ptr< PingPongIfFactory >& handlerFactory) : handlerFactory_(handlerFactory) {} ::boost::shared_ptr< ::apache::thrift::TProcessor > getProcessor(const ::apache::thrift::TConnectionInfo& connInfo); protected: ::boost::shared_ptr< PingPongIfFactory > handlerFactory_; }; class PingPongMultiface : virtual public PingPongIf { public: PingPongMultiface(std::vector<boost::shared_ptr<PingPongIf> >& ifaces) : ifaces_(ifaces) { } virtual ~PingPongMultiface() {} protected: std::vector<boost::shared_ptr<PingPongIf> > ifaces_; PingPongMultiface() {} void add(boost::shared_ptr<PingPongIf> iface) { ifaces_.push_back(iface); } public: void ping(std::string& _return) { size_t sz = ifaces_.size(); size_t i = 0; for (; i < (sz - 1); ++i) { ifaces_[i]->ping(_return); } ifaces_[i]->ping(_return); return; } }; #endif
{ "content_hash": "370c6d0857e1b97de7923c66c3d8d678", "timestamp": "", "source": "github", "line_count": 234, "max_line_length": 180, "avg_line_length": 25.683760683760685, "alnum_prop": 0.6825291181364392, "repo_name": "ezbake/ezbake-crypto-utils", "id": "a4c78903add0e61b4732eef0410feeaf3c2ebf82", "size": "6629", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/thrift/generated-sources/gen-cpp/PingPong.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "20843" }, { "name": "Java", "bytes": "104045" }, { "name": "Python", "bytes": "11250" }, { "name": "Ruby", "bytes": "3602" }, { "name": "Shell", "bytes": "1882" } ], "symlink_target": "" }
namespace TagLib.IFD.Entries { /// <summary> /// Contains a signed LONG value. /// </summary> public class SLongIFDEntry : IFDEntry { #region Properties /// <value> /// The ID of the tag, the current instance belongs to /// </value> public ushort Tag { get; private set; } /// <value> /// The value which is stored by the current instance /// </value> public int Value { get; private set; } #endregion #region Constructors /// <summary> /// Construcor. /// </summary> /// <param name="tag"> /// A <see cref="System.UInt16"/> with the tag ID of the entry this instance /// represents /// </param> /// <param name="value"> /// A <see cref="System.Int32"/> to be stored /// </param> public SLongIFDEntry (ushort tag, int value) { Tag = tag; Value = value; } #endregion #region Public Methods /// <summary> /// Renders the current instance to a <see cref="ByteVector"/> /// </summary> /// <param name="is_bigendian"> /// A <see cref="System.Boolean"/> indicating the endianess for rendering. /// </param> /// <param name="offset"> /// A <see cref="System.UInt32"/> with the offset, the data is stored. /// </param> /// <param name="type"> /// A <see cref="System.UInt16"/> the ID of the type, which is rendered /// </param> /// <param name="count"> /// A <see cref="System.UInt32"/> with the count of the values which are /// rendered. /// </param> /// <returns> /// A <see cref="ByteVector"/> with the rendered data. /// </returns> public ByteVector Render (bool is_bigendian, uint offset, out ushort type, out uint count) { type = (ushort) IFDEntryType.SLong; count = 1; return ByteVector.FromInt (Value, is_bigendian); } #endregion } }
{ "content_hash": "58dbb3b90af76e83f78d7d46274e1c70", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 92, "avg_line_length": 24.08, "alnum_prop": 0.5996677740863787, "repo_name": "rubenv/tripod", "id": "90a22ed1a7f89847b5dfd0e641b104037bb8be92", "size": "2682", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Libraries/TagLib/TagLib/IFD/Entries/SLongIFDEntry.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "4108146" }, { "name": "Shell", "bytes": "2195" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Can. J. Bot. 65(2): 387 (1987) #### Original name Wettsteinina savilei Shoemaker & C.E. Babc. ### Remarks null
{ "content_hash": "333a931dcf89147909e37dbde39dc126", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 43, "avg_line_length": 13.384615384615385, "alnum_prop": 0.6724137931034483, "repo_name": "mdoering/backbone", "id": "576aedc6e254cf2ba74cde751e8590420ba50e0b", "size": "241", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Wettsteinina/Wettsteinina savilei/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!-- Copyright (C) 2020 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources> <string name="app_name">Camera Pipe</string> <string name="data_key_name">%s\t</string> </resources>
{ "content_hash": "bd5a6fa0b1ce2321eb510be1d4954203", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 72, "avg_line_length": 39.05555555555556, "alnum_prop": 0.7638691322901849, "repo_name": "AndroidX/androidx", "id": "2b6880594a6a9bd6fe9823e80aa4355b70221578", "size": "703", "binary": false, "copies": "3", "ref": "refs/heads/androidx-main", "path": "camera/integration-tests/camerapipetestapp/src/main/res/values/donottranslate-strings.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AIDL", "bytes": "263978" }, { "name": "ANTLR", "bytes": "19860" }, { "name": "C", "bytes": "4764" }, { "name": "C++", "bytes": "9020585" }, { "name": "CMake", "bytes": "11999" }, { "name": "HTML", "bytes": "21175" }, { "name": "Java", "bytes": "59499889" }, { "name": "JavaScript", "bytes": "1343" }, { "name": "Kotlin", "bytes": "66123157" }, { "name": "Python", "bytes": "292398" }, { "name": "Shell", "bytes": "167367" }, { "name": "Swift", "bytes": "3153" }, { "name": "TypeScript", "bytes": "7599" } ], "symlink_target": "" }
import { Color } from '../color'; import { getKnownColor } from '../color/known-colors'; export type Parsed<V> = { start: number; end: number; value: V }; // Values export type URL = string; export type Angle = number; export interface Unit<T> { value: number; unit: string; } export type Length = Unit<'px' | 'dip'>; export type Percentage = Unit<'%'>; export type LengthPercentage = Length | Percentage; export type Keyword = string; export interface ColorStop { color: Color; offset?: LengthPercentage; } export interface LinearGradient { angle: number; colors: ColorStop[]; } export interface Background { readonly color?: number | Color; readonly image?: URL | LinearGradient; readonly repeat?: BackgroundRepeat; readonly position?: BackgroundPosition; readonly size?: BackgroundSize; } export type BackgroundRepeat = 'repeat' | 'repeat-x' | 'repeat-y' | 'no-repeat'; export type BackgroundSize = | 'auto' | 'cover' | 'contain' | { x: LengthPercentage; y: 'auto' | LengthPercentage; }; export type HorizontalAlign = 'left' | 'center' | 'right'; export type VerticalAlign = 'top' | 'center' | 'bottom'; export interface HorizontalAlignWithOffset { readonly align: 'left' | 'right'; readonly offset: LengthPercentage; } export interface VerticalAlignWithOffset { readonly align: 'top' | 'bottom'; readonly offset: LengthPercentage; } export interface BackgroundPosition { readonly x: HorizontalAlign | HorizontalAlignWithOffset; readonly y: VerticalAlign | VerticalAlignWithOffset; text?: string; } const urlRegEx = /\s*url\((?:(['"])([^\1]*)\1|([^)]*))\)\s*/gy; export function parseURL(text: string, start = 0): Parsed<URL> { urlRegEx.lastIndex = start; const result = urlRegEx.exec(text); if (!result) { return null; } const end = urlRegEx.lastIndex; const value: URL = result[2] || result[3]; return { start, end, value }; } const hexColorRegEx = /\s*#((?:[0-9A-F]{8})|(?:[0-9A-F]{6})|(?:[0-9A-F]{4})|(?:[0-9A-F]{3}))\s*/giy; export function parseHexColor(text: string, start = 0): Parsed<Color> { hexColorRegEx.lastIndex = start; const result = hexColorRegEx.exec(text); if (!result) { return null; } const end = hexColorRegEx.lastIndex; return { start, end, value: new Color('#' + result[1]) }; } const cssColorRegEx = /\s*((?:rgb|rgba|hsl|hsla|hsv|hsva)\([^\(\)]*\))/gy; export function parseCssColor(text: string, start = 0): Parsed<Color> { cssColorRegEx.lastIndex = start; const result = cssColorRegEx.exec(text); if (!result) { return null; } const end = cssColorRegEx.lastIndex; try { return { start, end, value: new Color(result[1]) }; } catch { return null; } } export function convertHSLToRGBColor(hue: number, saturation: number, lightness: number): { r: number; g: number; b: number } { // Per formula it will be easier if hue is divided to 60° and saturation to 100 beforehand // https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB hue /= 60; lightness /= 100; const chroma = ((1 - Math.abs(2 * lightness - 1)) * saturation) / 100, X = chroma * (1 - Math.abs((hue % 2) - 1)); // Add lightness match to all RGB components beforehand let { m: r, m: g, m: b } = { m: lightness - chroma / 2 }; if (0 <= hue && hue < 1) { r += chroma; g += X; } else if (hue < 2) { r += X; g += chroma; } else if (hue < 3) { g += chroma; b += X; } else if (hue < 4) { g += X; b += chroma; } else if (hue < 5) { r += X; b += chroma; } else if (hue < 6) { r += chroma; b += X; } return { r: Math.round(r * 0xff), g: Math.round(g * 0xff), b: Math.round(b * 0xff), }; } export function parseColorKeyword(value, start: number, keyword = parseKeyword(value, start)): Parsed<Color> { const parseColor = keyword && getKnownColor(keyword.value); if (parseColor != null) { const end = keyword.end; return { start, end, value: new Color(parseColor) }; } return null; } export function parseColor(value: string, start = 0, keyword = parseKeyword(value, start)): Parsed<Color> { return parseHexColor(value, start) || parseColorKeyword(value, start, keyword) || parseCssColor(value, start); } const keywordRegEx = /\s*([a-z][\w\-]*)\s*/giy; function parseKeyword(text: string, start = 0): Parsed<Keyword> { keywordRegEx.lastIndex = start; const result = keywordRegEx.exec(text); if (!result) { return null; } const end = keywordRegEx.lastIndex; const value = result[1]; return { start, end, value }; } const backgroundRepeatKeywords = new Set(['repeat', 'repeat-x', 'repeat-y', 'no-repeat']); export function parseRepeat(value: string, start = 0, keyword = parseKeyword(value, start)): Parsed<BackgroundRepeat> { if (keyword && backgroundRepeatKeywords.has(keyword.value)) { const end = keyword.end; const value = <BackgroundRepeat>keyword.value; return { start, end, value }; } return null; } const unitRegEx = /\s*([+\-]?(?:\d+\.\d+|\d+|\.\d+)(?:[eE][+\-]?\d+)?)([a-zA-Z]+|%)?\s*/gy; export function parseUnit(text: string, start = 0): Parsed<Unit<string>> { unitRegEx.lastIndex = start; const result = unitRegEx.exec(text); if (!result) { return null; } const end = unitRegEx.lastIndex; const value = parseFloat(result[1]); const unit = <any>result[2] || 'dip'; return { start, end, value: { value, unit } }; } export function parsePercentageOrLength(text: string, start = 0): Parsed<LengthPercentage> { const unitResult = parseUnit(text, start); if (unitResult) { const { start, end } = unitResult; const value = <LengthPercentage>unitResult.value; if (value.unit === '%') { value.value /= 100; } else if (!value.unit) { value.unit = 'dip'; } else if (value.unit === 'px' || value.unit === 'dip') { // same } else { return null; } return { start, end, value }; } return null; } const angleUnitsToRadMap: { [unit: string]: (start: number, end: number, value: number) => Parsed<Angle>; } = { deg: (start: number, end: number, deg: number) => ({ start, end, value: (deg / 180) * Math.PI, }), rad: (start: number, end: number, rad: number) => ({ start, end, value: rad, }), grad: (start: number, end: number, grad: number) => ({ start, end, value: (grad / 200) * Math.PI, }), turn: (start: number, end: number, turn: number) => ({ start, end, value: turn * Math.PI * 2, }), }; export function parseAngle(value: string, start = 0): Parsed<Angle> { const angleResult = parseUnit(value, start); if (angleResult) { const { start, end, value } = angleResult; return (angleUnitsToRadMap[value.unit] || ((_, __, ___) => null))(start, end, value.value); } return null; } const backgroundSizeKeywords = new Set(['auto', 'contain', 'cover']); export function parseBackgroundSize(value: string, start = 0, keyword = parseKeyword(value, start)): Parsed<BackgroundSize> { let end = start; if (keyword && backgroundSizeKeywords.has(keyword.value)) { end = keyword.end; const value = <'auto' | 'cover' | 'contain'>keyword.value; return { start, end, value }; } // Parse one or two lengths... the other will be "auto" const firstLength = parsePercentageOrLength(value, end); if (firstLength) { end = firstLength.end; const secondLength = parsePercentageOrLength(value, firstLength.end); if (secondLength) { end = secondLength.end; return { start, end, value: { x: firstLength.value, y: secondLength.value }, }; } else { return { start, end, value: { x: firstLength.value, y: 'auto' } }; } } return null; } const backgroundPositionKeywords = Object.freeze(new Set(['left', 'right', 'top', 'bottom', 'center'])); const backgroundPositionKeywordsDirection: { [align: string]: 'x' | 'center' | 'y'; } = { left: 'x', right: 'x', center: 'center', top: 'y', bottom: 'y', }; export function parseBackgroundPosition(text: string, start = 0, keyword = parseKeyword(text, start)): Parsed<BackgroundPosition> { function formatH(align: Parsed<HorizontalAlign>, offset: Parsed<LengthPercentage>) { if (align.value === 'center') { return 'center'; } if (offset && offset.value.value !== 0) { return { align: align.value, offset: offset.value }; } return align.value; } function formatV(align: Parsed<VerticalAlign>, offset: Parsed<LengthPercentage>) { if (align.value === 'center') { return 'center'; } if (offset && offset.value.value !== 0) { return { align: align.value, offset: offset.value }; } return align.value; } let end = start; if (keyword && backgroundPositionKeywords.has(keyword.value)) { end = keyword.end; const firstDirection = backgroundPositionKeywordsDirection[keyword.value]; const firstLength = firstDirection !== 'center' && parsePercentageOrLength(text, end); if (firstLength) { end = firstLength.end; } const secondKeyword = parseKeyword(text, end); if (secondKeyword && backgroundPositionKeywords.has(secondKeyword.value)) { end = secondKeyword.end; const secondDirection = backgroundPositionKeywordsDirection[secondKeyword.end]; if (firstDirection === secondDirection && firstDirection !== 'center') { return null; // Reject pair of both horizontal or both vertical alignments. } const secondLength = secondDirection !== 'center' && parsePercentageOrLength(text, end); if (secondLength) { end = secondLength.end; } if ((firstDirection === secondDirection && secondDirection === 'center') || firstDirection === 'x' || secondDirection === 'y') { return { start, end, value: { x: formatH(<Parsed<HorizontalAlign>>keyword, firstLength), y: formatV(<Parsed<VerticalAlign>>secondKeyword, secondLength), }, }; } else { return { start, end, value: { x: formatH(<Parsed<HorizontalAlign>>secondKeyword, secondLength), y: formatV(<Parsed<VerticalAlign>>keyword, firstLength), }, }; } } else { if (firstDirection === 'center') { return { start, end, value: { x: 'center', y: 'center' } }; } else if (firstDirection === 'x') { return { start, end, value: { x: formatH(<Parsed<HorizontalAlign>>keyword, firstLength), y: 'center', }, }; } else { return { start, end, value: { x: 'center', y: formatV(<Parsed<VerticalAlign>>keyword, firstLength), }, }; } } } else { const firstLength = parsePercentageOrLength(text, end); if (firstLength) { end = firstLength.end; const secondLength = parsePercentageOrLength(text, end); if (secondLength) { end = secondLength.end; return { start, end, value: { x: { align: 'left', offset: firstLength.value }, y: { align: 'top', offset: secondLength.value }, }, }; } else { return { start, end, value: { x: { align: 'left', offset: firstLength.value }, y: 'center', }, }; } } else { return null; } } } const directionRegEx = /\s*to\s*(left|right|top|bottom)\s*(left|right|top|bottom)?\s*/gy; const sideDirections = { top: (Math.PI * 0) / 2, right: (Math.PI * 1) / 2, bottom: (Math.PI * 2) / 2, left: (Math.PI * 3) / 2, }; const cornerDirections = { top: { right: (Math.PI * 1) / 4, left: (Math.PI * 7) / 4, }, right: { top: (Math.PI * 1) / 4, bottom: (Math.PI * 3) / 4, }, bottom: { right: (Math.PI * 3) / 4, left: (Math.PI * 5) / 4, }, left: { top: (Math.PI * 7) / 4, bottom: (Math.PI * 5) / 4, }, }; function parseDirection(text: string, start = 0): Parsed<Angle> { directionRegEx.lastIndex = start; const result = directionRegEx.exec(text); if (!result) { return null; } const end = directionRegEx.lastIndex; const firstDirection = result[1]; if (result[2]) { const secondDirection = result[2]; const value = cornerDirections[firstDirection][secondDirection]; return value === undefined ? null : { start, end, value }; } else { return { start, end, value: sideDirections[firstDirection] }; } } const openingBracketRegEx = /\s*\(\s*/gy; const closingBracketRegEx = /\s*\)\s*/gy; const closingBracketOrCommaRegEx = /\s*([),])\s*/gy; function parseArgumentsList<T>(text: string, start: number, argument: (value: string, lastIndex: number, index: number) => Parsed<T>): Parsed<Parsed<T>[]> { openingBracketRegEx.lastIndex = start; const openingBracket = openingBracketRegEx.exec(text); if (!openingBracket) { return null; } let end = openingBracketRegEx.lastIndex; const value: Parsed<T>[] = []; closingBracketRegEx.lastIndex = end; const closingBracket = closingBracketRegEx.exec(text); if (closingBracket) { return { start, end, value }; } for (let index = 0; true; index++) { const arg = argument(text, end, index); if (!arg) { return null; } end = arg.end; value.push(arg); closingBracketOrCommaRegEx.lastIndex = end; const closingBracketOrComma = closingBracketOrCommaRegEx.exec(text); if (closingBracketOrComma) { end = closingBracketOrCommaRegEx.lastIndex; if (closingBracketOrComma[1] === ',') { // noinspection UnnecessaryContinueJS continue; } else if (closingBracketOrComma[1] === ')') { return { start, end, value }; } } else { return null; } } } export function parseColorStop(text: string, start = 0): Parsed<ColorStop> { const color = parseColor(text, start); if (!color) { return null; } let end = color.end; const offset = parsePercentageOrLength(text, end); if (offset) { end = offset.end; return { start, end, value: { color: color.value, offset: offset.value }, }; } return { start, end, value: { color: color.value } }; } const linearGradientStartRegEx = /\s*linear-gradient\s*/gy; export function parseLinearGradient(text: string, start = 0): Parsed<LinearGradient> { linearGradientStartRegEx.lastIndex = start; const lgs = linearGradientStartRegEx.exec(text); if (!lgs) { return null; } let end = linearGradientStartRegEx.lastIndex; let angle = Math.PI; const colors: ColorStop[] = []; const parsedArgs = parseArgumentsList<Angle | ColorStop>(text, end, (text, start, index) => { if (index === 0) { // First arg can be gradient direction const angleArg = parseAngle(text, start) || parseDirection(text, start); if (angleArg) { angle = angleArg.value; return angleArg; } } const colorStop = parseColorStop(text, start); if (colorStop) { colors.push(colorStop.value); return colorStop; } return null; }); if (!parsedArgs) { return null; } end = parsedArgs.end; return { start, end, value: { angle, colors } }; } const slashRegEx = /\s*(\/)\s*/gy; function parseSlash(text: string, start: number): Parsed<'/'> { slashRegEx.lastIndex = start; const slash = slashRegEx.exec(text); if (!slash) { return null; } const end = slashRegEx.lastIndex; return { start, end, value: '/' }; } export function parseBackground(text: string, start = 0): Parsed<Background> { const value: any = {}; let end = start; while (end < text.length) { const keyword = parseKeyword(text, end); const color = parseColor(text, end, keyword); if (color) { value.color = color.value; end = color.end; continue; } const repeat = parseRepeat(text, end, keyword); if (repeat) { value.repeat = repeat.value; end = repeat.end; continue; } const position = parseBackgroundPosition(text, end, keyword); if (position) { position.value.text = text.substring(position.start, position.end); value.position = position.value; end = position.end; const slash = parseSlash(text, end); if (slash) { end = slash.end; const size = parseBackgroundSize(text, end); if (!size) { // Found / but no proper size following return null; } value.size = size.value; end = size.end; } continue; } const url = parseURL(text, end); if (url) { value.image = url.value; end = url.end; continue; } const gradient = parseLinearGradient(text, end); if (gradient) { value.image = gradient.value; end = gradient.end; continue; } return null; } return { start, end, value }; } // Selectors export type Combinator = '+' | '~' | '>' | ' '; export interface UniversalSelector { type: '*'; } export interface TypeSelector { type: ''; identifier: string; } export interface ClassSelector { type: '.'; identifier: string; } export interface IdSelector { type: '#'; identifier: string; } export interface PseudoClassSelector { type: ':'; identifier: string; } export type AttributeSelectorTest = '=' | '^=' | '$=' | '*=' | '~=' | '|='; export interface AttributeSelector { type: '[]'; property: string; test?: AttributeSelectorTest; value?: string; } export type SimpleSelector = UniversalSelector | TypeSelector | ClassSelector | IdSelector | PseudoClassSelector | AttributeSelector; export type SimpleSelectorSequence = SimpleSelector[]; export type SelectorCombinatorPair = [SimpleSelectorSequence, Combinator]; export type Selector = SelectorCombinatorPair[]; const universalSelectorRegEx = /\*/gy; export function parseUniversalSelector(text: string, start = 0): Parsed<UniversalSelector> { universalSelectorRegEx.lastIndex = start; const result = universalSelectorRegEx.exec(text); if (!result) { return null; } const end = universalSelectorRegEx.lastIndex; return { start, end, value: { type: '*' } }; } const simpleIdentifierSelectorRegEx = /(#|\.|:|\b)((?:[\w_-]|\\.)(?:[\w\d_-]|\\.)*)/guy; const unicodeEscapeRegEx = /\\([0-9a-fA-F]{1,5}\s|[0-9a-fA-F]{6})/g; export function parseSimpleIdentifierSelector(text: string, start = 0): Parsed<TypeSelector | ClassSelector | IdSelector | PseudoClassSelector> { simpleIdentifierSelectorRegEx.lastIndex = start; const result = simpleIdentifierSelectorRegEx.exec(text.replace(unicodeEscapeRegEx, (_, c) => '\\' + String.fromCodePoint(parseInt(c.trim(), 16)))); if (!result) { return null; } const end = simpleIdentifierSelectorRegEx.lastIndex; const type = <'#' | '.' | ':' | ''>result[1]; const identifier: string = result[2].replace(/\\/g, ''); const value = <TypeSelector | ClassSelector | IdSelector | PseudoClassSelector>{ type, identifier }; return { start, end, value }; } const attributeSelectorRegEx = /\[\s*([_\-\w][_\-\w\d]*)\s*(?:(=|\^=|\$=|\*=|\~=|\|=)\s*(?:([_\-\w][_\-\w\d]*)|"((?:[^\\"]|\\(?:"|n|r|f|\\|0-9a-f))*)"|'((?:[^\\']|\\(?:'|n|r|f|\\|0-9a-f))*)')\s*)?\]/gy; export function parseAttributeSelector(text: string, start: number): Parsed<AttributeSelector> { attributeSelectorRegEx.lastIndex = start; const result = attributeSelectorRegEx.exec(text); if (!result) { return null; } const end = attributeSelectorRegEx.lastIndex; const property = result[1]; if (result[2]) { const test = <AttributeSelectorTest>result[2]; const value = result[3] || result[4] || result[5]; return { start, end, value: { type: '[]', property, test, value } }; } return { start, end, value: { type: '[]', property } }; } export function parseSimpleSelector(text: string, start = 0): Parsed<SimpleSelector> { return parseUniversalSelector(text, start) || parseSimpleIdentifierSelector(text, start) || parseAttributeSelector(text, start); } export function parseSimpleSelectorSequence(text: string, start: number): Parsed<SimpleSelector[]> { let simpleSelector = parseSimpleSelector(text, start); if (!simpleSelector) { return null; } let end = simpleSelector.end; const value = <SimpleSelectorSequence>[]; while (simpleSelector) { value.push(simpleSelector.value); end = simpleSelector.end; simpleSelector = parseSimpleSelector(text, end); } return { start, end, value }; } const combinatorRegEx = /\s*([+~>])?\s*/gy; export function parseCombinator(text: string, start = 0): Parsed<Combinator> { combinatorRegEx.lastIndex = start; const result = combinatorRegEx.exec(text); if (!result) { return null; } const end = combinatorRegEx.lastIndex; const value = <Combinator>result[1] || ' '; return { start, end, value }; } const whiteSpaceRegEx = /\s*/gy; export function parseSelector(text: string, start = 0): Parsed<Selector> { let end = start; whiteSpaceRegEx.lastIndex = end; const leadingWhiteSpace = whiteSpaceRegEx.exec(text); if (leadingWhiteSpace) { end = whiteSpaceRegEx.lastIndex; } const value = <Selector>[]; let combinator: Parsed<Combinator>; let expectSimpleSelector = true; // Must have at least one let pair: SelectorCombinatorPair; do { const simpleSelectorSequence = parseSimpleSelectorSequence(text, end); if (!simpleSelectorSequence) { if (expectSimpleSelector) { return null; } else { break; } } end = simpleSelectorSequence.end; if (combinator) { // This logic looks weird; this `if` statement would occur on the next LOOP, so it effects the prior `pair` // variable which is already pushed into the `value` array is going to have its `undefined` set to this // value before the following statement creates a new `pair` memory variable. // noinspection JSUnusedAssignment pair[1] = combinator.value; } pair = [simpleSelectorSequence.value, undefined]; value.push(pair); combinator = parseCombinator(text, end); if (combinator) { end = combinator.end; } expectSimpleSelector = combinator && combinator.value !== ' '; // Simple selector must follow non trailing white space combinator } while (combinator); return { start, end, value }; }
{ "content_hash": "d17c52df8d45110691b414d1553c26f7", "timestamp": "", "source": "github", "line_count": 771, "max_line_length": 202, "avg_line_length": 27.718547341115436, "alnum_prop": 0.6567310841794956, "repo_name": "NativeScript/NativeScript", "id": "b3669b7c7ff756a3545828feabd0d672665e9361", "size": "21372", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "packages/core/css/parser.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "34822" }, { "name": "HTML", "bytes": "1307" }, { "name": "Java", "bytes": "494925" }, { "name": "JavaScript", "bytes": "69009" }, { "name": "Objective-C", "bytes": "49167" }, { "name": "SCSS", "bytes": "65" }, { "name": "Shell", "bytes": "14663" }, { "name": "TypeScript", "bytes": "3946056" } ], "symlink_target": "" }
<!DOCTYPE html> <html manifest="cache.manifest"> <head> <meta charset="utf-8"> <title>2048 5x5</title> <link href="style/main.css" rel="stylesheet" type="text/css"> <link rel="shortcut icon" href="favicon.ico"> <link rel="apple-touch-icon" href="meta/apple-touch-icon.png"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0, maximum-scale=1, user-scalable=no, minimal-ui"> </head> <body> <div class="container"> <div class="heading"> <h1 class="title">2048 5x5</h1> <div class="scores-container"> <div class="score-container">0</div> <div class="best-container">0</div> </div> </div> <p class="game-intro">Join the numbers and get to the <strong>2048 tile!</strong></p> <div class="game-container"> <div class="game-message"> <p></p> <div class="lower"> <a class="keep-playing-button">Keep going</a> <a class="retry-button">Try again</a> </div> </div> <div class="grid-container"> <div class="grid-row"> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> </div> <div class="grid-row"> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> </div> <div class="grid-row"> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> </div> <div class="grid-row"> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> </div> <div class="grid-row"> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> </div> </div> <div class="tile-container"> </div> </div> <p class="game-explanation"> <strong class="important">How to play:</strong> Use your <strong>arrow keys</strong> to move the tiles. When two tiles with the same number touch, they <strong>merge into one!</strong> </p> <p> This 5 x 5 fast paced version by <a href="https://glebbahmutov.com/">Gleb Bahmutov</a> was cloned from the "official" <a href="https://github.com/gabrielecirulli/2048">github source</a> authored by <a href="http://gabrielecirulli.com/">Gabriele Cirulli</a>. Read how I cloned and improved its quality in this <a href="https://glebbahmutov.com/blog/cloning-2048/">blog post</a>. </p> <hr> </div> <script src="js/animframe_polyfill.js"></script> <script src="js/keyboard_input_manager.js"></script> <script src="js/html_actuator.js"></script> <script src="js/grid.js"></script> <script src="js/tile.js"></script> <script src="js/local_score_manager.js"></script> <script src="js/game_manager.js"></script> <script src="js/application.js"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-41650865-2', 'glebbahmutov.com'); ga('send', 'pageview'); </script> </body> </html>
{ "content_hash": "84403a7f597d81a2241330dab53f4e9c", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 190, "avg_line_length": 37.05555555555556, "alnum_prop": 0.5822088955522239, "repo_name": "bahmutov/2048", "id": "8914f945d8165ddb46021433037a48f6ff693a80", "size": "4002", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "33108" }, { "name": "HTML", "bytes": "4002" }, { "name": "JavaScript", "bytes": "19752" } ], "symlink_target": "" }
package org.openkilda.rulemanager.factory.generator.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.openkilda.model.cookie.Cookie.DROP_VERIFICATION_LOOP_RULE_COOKIE; import static org.openkilda.rulemanager.Constants.Priority.DROP_DISCOVERY_LOOP_RULE_PRIORITY; import static org.openkilda.rulemanager.Utils.buildSwitch; import static org.openkilda.rulemanager.Utils.getCommand; import static org.openkilda.rulemanager.Utils.getMatchByField; import org.openkilda.model.Switch; import org.openkilda.model.SwitchId; import org.openkilda.model.cookie.Cookie; import org.openkilda.rulemanager.Field; import org.openkilda.rulemanager.FlowSpeakerData; import org.openkilda.rulemanager.OfTable; import org.openkilda.rulemanager.RuleManagerConfig; import org.openkilda.rulemanager.SpeakerData; import org.openkilda.rulemanager.match.FieldMatch; import org.junit.Before; import org.junit.Test; import java.util.Collections; import java.util.List; public class DropDiscoveryLoopRuleGeneratorTest { private RuleManagerConfig config; private DropDiscoveryLoopRuleGenerator generator; @Before public void setup() { config = mock(RuleManagerConfig.class); when(config.getDiscoveryBcastPacketDst()).thenReturn("00:26:E1:FF:FF:FF"); generator = DropDiscoveryLoopRuleGenerator.builder() .config(config) .build(); } @Test public void shouldBuildCorrectRuleForOf13() { Switch sw = buildSwitch("OF_13", Collections.emptySet()); List<SpeakerData> commands = generator.generateCommands(sw); assertEquals(1, commands.size()); FlowSpeakerData flowCommandData = getCommand(FlowSpeakerData.class, commands); assertEquals(sw.getSwitchId(), flowCommandData.getSwitchId()); assertEquals(sw.getOfVersion(), flowCommandData.getOfVersion().toString()); assertTrue(flowCommandData.getDependsOn().isEmpty()); assertEquals(new Cookie(DROP_VERIFICATION_LOOP_RULE_COOKIE), flowCommandData.getCookie()); assertEquals(OfTable.INPUT, flowCommandData.getTable()); assertEquals(DROP_DISCOVERY_LOOP_RULE_PRIORITY, flowCommandData.getPriority()); FieldMatch ethDstMatch = getMatchByField(Field.ETH_DST, flowCommandData.getMatch()); assertEquals(new SwitchId(config.getDiscoveryBcastPacketDst()).toLong(), ethDstMatch.getValue()); assertFalse(ethDstMatch.isMasked()); FieldMatch ethSrcMatch = getMatchByField(Field.ETH_SRC, flowCommandData.getMatch()); assertEquals(sw.getSwitchId().toLong(), ethSrcMatch.getValue()); assertFalse(ethSrcMatch.isMasked()); assertNull(flowCommandData.getInstructions().getApplyActions()); assertNull(flowCommandData.getInstructions().getGoToMeter()); assertNull(flowCommandData.getInstructions().getGoToTable()); assertNull(flowCommandData.getInstructions().getWriteMetadata()); assertNull(flowCommandData.getInstructions().getWriteActions()); } @Test public void shouldSkipRuleForOf12() { Switch sw = buildSwitch("OF_12", Collections.emptySet()); List<SpeakerData> commands = generator.generateCommands(sw); assertTrue(commands.isEmpty()); } }
{ "content_hash": "8ce01977e0857db9271b2bda2a7de97c", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 105, "avg_line_length": 39.94252873563219, "alnum_prop": 0.7522302158273382, "repo_name": "telstra/open-kilda", "id": "076eabf1f6fa040cd82f6113cc879aa2e6b05de2", "size": "4092", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src-java/rule-manager/rule-manager-implementation/src/test/java/org/openkilda/rulemanager/factory/generator/service/DropDiscoveryLoopRuleGeneratorTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "89798" }, { "name": "CMake", "bytes": "4314" }, { "name": "CSS", "bytes": "233390" }, { "name": "Dockerfile", "bytes": "30541" }, { "name": "Groovy", "bytes": "2234079" }, { "name": "HTML", "bytes": "362166" }, { "name": "Java", "bytes": "14631453" }, { "name": "JavaScript", "bytes": "369015" }, { "name": "Jinja", "bytes": "937" }, { "name": "Makefile", "bytes": "20500" }, { "name": "Python", "bytes": "367364" }, { "name": "Shell", "bytes": "62664" }, { "name": "TypeScript", "bytes": "867537" } ], "symlink_target": "" }
namespace ArduinoJson { namespace Internals { template <typename TSource, typename Enable = void> struct ValueSetter { template <typename TDestination> static bool set(JsonBuffer*, TDestination& destination, const TSource& source) { destination = source; return true; } }; template <typename TSource> struct ValueSetter<TSource, typename TypeTraits::EnableIf< StringFuncs<TSource>::should_duplicate>::type> { template <typename TDestination> static bool set(JsonBuffer* buffer, TDestination& destination, const TSource& source) { const char* copy = buffer->strdup(source); if (!copy) return false; destination = copy; return true; } }; } }
{ "content_hash": "31d4aa10c71feb835b1accbbb9f6ff9e", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 80, "avg_line_length": 27.62962962962963, "alnum_prop": 0.6648793565683646, "repo_name": "vkynchev/homepi", "id": "418c00222f42c150a8d531847427a2cb0bdadbf1", "size": "1059", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "libraries/ArduinoJson/include/ArduinoJson/Internals/ValueSetter.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "52243" }, { "name": "C", "bytes": "45616" }, { "name": "C++", "bytes": "286333" }, { "name": "CMake", "bytes": "3609" }, { "name": "JavaScript", "bytes": "674" }, { "name": "Python", "bytes": "94786" }, { "name": "Shell", "bytes": "5933" } ], "symlink_target": "" }
import { inject as service } from '@ember/service'; import Route from '@ember/routing/route'; export default class UsersRoute extends Route { @service session; queryParams = { query: { replace: true, }, searchTerms: { replace: true, }, }; async beforeModel(transition) { this.session.requireAuthentication(transition, 'login'); } }
{ "content_hash": "a9cef6d11a82149107883577f51efe43", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 60, "avg_line_length": 18.9, "alnum_prop": 0.6481481481481481, "repo_name": "ilios/frontend", "id": "43c6f1d7429b04f3a24daa2e5ca45b43ba5f143b", "size": "378", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/routes/users.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "399" }, { "name": "Dockerfile", "bytes": "190" }, { "name": "HTML", "bytes": "2351" }, { "name": "Handlebars", "bytes": "448021" }, { "name": "JavaScript", "bytes": "1795220" }, { "name": "SCSS", "bytes": "86795" } ], "symlink_target": "" }
package com.zenplanner.sql; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.Arrays; import java.util.List; import java.util.UUID; public class Column { private static final List<String> smallTypes = Arrays.asList(new String[]{ "uniqueidentifier", "bigint", "date", "datetime", "datetime2", "smalldatetime", "tinyint", "smallint", "int", "decimal", "bit", "money", "smallmoney", "char", "float", "image", "nchar", "datetimeoffset" }); private static final List<String> bigTypes = Arrays.asList(new String[]{"varchar", "nvarchar", "text"}); private String columnName; private String dataType; private boolean isPrimaryKey; /** * @return the SQL to add to a select clause for the given column */ public String getSelect() { if (smallTypes.contains(getDataType().toLowerCase())) { return String.format("HASHBYTES('md5', " + "case when [%s] is null then convert(varbinary,0) " + "else convert(varbinary, [%s]) end)", getColumnName(), getColumnName()); } if (bigTypes.contains(getDataType().toLowerCase())) { return String.format("HASHBYTES('md5', " + "case when [%s] is null then convert(varbinary,0) " + "else left(convert(nvarchar(max), [%s]), 500) end)", getColumnName(), getColumnName()); } throw new RuntimeException("Unknown type: " + getDataType()); } public Comparable<?> getValue(ResultSet rs) throws Exception { if("int".equals(dataType)) { return rs.getInt(columnName); } if("bigint".equals(dataType)) { return rs.getLong(columnName); } if("nchar".equals(dataType)) { return rs.getString(columnName); } if("varchar".equals(dataType)) { return rs.getString(columnName); } if("nvarchar".equals(dataType)) { return rs.getString(columnName); } if("uniqueidentifier".equals(dataType)) { byte[] bytes = rs.getBytes(columnName); UUID uuid = UuidUtil.byteArrayToUuid(bytes); return uuid; } if("datetimeoffset".equals(dataType)) { return rs.getDate(columnName); } if("date".equals(dataType)) { return rs.getDate(columnName); } throw new RuntimeException("Type not recognized: " + dataType); } public String getColumnName() { return columnName; } public void setColumnName(String columnName) { this.columnName = columnName; } public String getDataType() { return dataType; } public void setDataType(String dataType) { this.dataType = dataType; } public boolean isPrimaryKey() { return isPrimaryKey; } public void setPrimaryKey(boolean isPrimaryKey) { this.isPrimaryKey = isPrimaryKey; } }
{ "content_hash": "85a8015ee95ef8685f9f21ae59f6de1d", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 114, "avg_line_length": 32.361702127659576, "alnum_prop": 0.591715976331361, "repo_name": "ZenPlanner/dbsync", "id": "f315f4a22c1feb4afd0c0b6fe4ab39495c805f09", "size": "3042", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/zenplanner/sql/Column.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "75379" } ], "symlink_target": "" }
<html dir="LTR"> <head> <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" /> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" /> <title>CommandLine.CompareColumns Method</title> <xml> </xml> <link rel="stylesheet" type="text/css" href="MSDN.css" /> </head> <body id="bodyID" class="dtBODY"> <div id="nsbanner"> <div id="bannerrow1"> <table class="bannerparthead" cellspacing="0"> <tr id="hdr"> <td class="runninghead">SQL Schema Tool Help</td> <td class="product"> </td> </tr> </table> </div> <div id="TitleRow"> <h1 class="dtH1">CommandLine.CompareColumns Method </h1> </div> </div> <div id="nstext"> <p> Compares table columns from two distinct XML schema files. These files are generated by the SerializeDB method. This method is called from the CompareTables method. </p> <div class="syntax">private static <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemVoidClassTopic.htm">void</a> CompareColumns(<br />   <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemStringClassTopic.htm">string</a> <i>tableName</i>,<br />   <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemXmlXmlNodeListClassTopic.htm">XmlNodeList</a> <i>xnlSource</i>,<br />   <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemXmlXmlNodeListClassTopic.htm">XmlNodeList</a> <i>xnlDestination</i>,<br />   <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemXmlXmlDocumentClassTopic.htm">XmlDocument</a> <i>xmlDiffDoc</i>,<br />   <a href="Microsoft.XmlDiffPatch.XmlDiff.html">XmlDiff</a> <i>xmlDiff</i><br />);</div> <h4 class="dtH4">Parameters</h4> <dl> <dt> <i>tableName</i> </dt> <dd>The string value representing the current SQL table object.</dd> <dt> <i>xnlSource</i> </dt> <dd>The XmlNodeList, a collection of source XML nodes to compare with the destination XML nodes.</dd> <dt> <i>xnlDestination</i> </dt> <dd>The XmlNodeList, a collection of destination/target XML nodes to compare with the source XML nodes.</dd> <dt> <i>xmlDiffDoc</i> </dt> <dd>The XML Diffgram object to update.</dd> <dt> <i>xmlDiff</i> </dt> <dd>The XmlDiff Object used from the GotDotNet XmlDiff class. Performs the XML node compare.</dd> </dl> <h4 class="dtH4">See Also</h4> <p> <a href="Infor.SST.CommandLine.html">CommandLine Class</a> | <a href="Infor.SST.html">Infor.SST Namespace</a></p> <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;"> <param name="Keyword" value="CompareColumns method"> </param> <param name="Keyword" value="CompareColumns method, CommandLine class"> </param> <param name="Keyword" value="CommandLine.CompareColumns method"> </param> </object> <hr /> <div id="footer"> <p> </p> <p>Generated from assembly SST [1.0.2118.11998]</p> </div> </div> </body> </html>
{ "content_hash": "330d42c6a1ddbe1567d9e356ca816a80", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 781, "avg_line_length": 48.42857142857143, "alnum_prop": 0.6067846607669617, "repo_name": "lslewis901/SqlSchemaTool", "id": "5f010c08b6f4bdc2b1048dc868eacfc6af15470b", "size": "3390", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/Infor.SST.CommandLine.CompareColumns.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "2491181" }, { "name": "CSS", "bytes": "2319" }, { "name": "HTML", "bytes": "611656" }, { "name": "JavaScript", "bytes": "5371" }, { "name": "PLSQL", "bytes": "24772" }, { "name": "SQLPL", "bytes": "5669" }, { "name": "XSLT", "bytes": "295607" } ], "symlink_target": "" }
require 'spec_helper.rb' describe 'Credential' do it "can read" do @holodeck.mock(Twilio::Response.new(500, '')) expect { @client.ip_messaging.v2.credentials.list() }.to raise_exception(Twilio::REST::TwilioError) expect( @holodeck.has_request?(Holodeck::Request.new( method: 'get', url: 'https://ip-messaging.twilio.com/v2/Credentials', ))).to eq(true) end it "receives read_full responses" do @holodeck.mock(Twilio::Response.new( 200, %q[ { "credentials": [ { "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "friendly_name": "Test slow create", "type": "apn", "sandbox": "False", "date_created": "2015-10-07T17:50:01Z", "date_updated": "2015-10-07T17:50:01Z", "url": "https://ip-messaging.twilio.com/v2/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } ], "meta": { "page": 0, "page_size": 1, "first_page_url": "https://ip-messaging.twilio.com/v2/Credentials?PageSize=1&Page=0", "previous_page_url": null, "url": "https://ip-messaging.twilio.com/v2/Credentials?PageSize=1&Page=0", "next_page_url": null, "key": "credentials" } } ] )) actual = @client.ip_messaging.v2.credentials.list() expect(actual).to_not eq(nil) end it "receives read_empty responses" do @holodeck.mock(Twilio::Response.new( 200, %q[ { "credentials": [], "meta": { "page": 0, "page_size": 1, "first_page_url": "https://ip-messaging.twilio.com/v2/Credentials?PageSize=1&Page=0", "previous_page_url": null, "url": "https://ip-messaging.twilio.com/v2/Credentials?PageSize=1&Page=0", "next_page_url": null, "key": "credentials" } } ] )) actual = @client.ip_messaging.v2.credentials.list() expect(actual).to_not eq(nil) end it "can create" do @holodeck.mock(Twilio::Response.new(500, '')) expect { @client.ip_messaging.v2.credentials.create(type: 'gcm') }.to raise_exception(Twilio::REST::TwilioError) values = {'Type' => 'gcm', } expect( @holodeck.has_request?(Holodeck::Request.new( method: 'post', url: 'https://ip-messaging.twilio.com/v2/Credentials', data: values, ))).to eq(true) end it "receives create responses" do @holodeck.mock(Twilio::Response.new( 201, %q[ { "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "friendly_name": "Test slow create", "type": "apn", "sandbox": "False", "date_created": "2015-10-07T17:50:01Z", "date_updated": "2015-10-07T17:50:01Z", "url": "https://ip-messaging.twilio.com/v2/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } ] )) actual = @client.ip_messaging.v2.credentials.create(type: 'gcm') expect(actual).to_not eq(nil) end it "can fetch" do @holodeck.mock(Twilio::Response.new(500, '')) expect { @client.ip_messaging.v2.credentials('CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch() }.to raise_exception(Twilio::REST::TwilioError) expect( @holodeck.has_request?(Holodeck::Request.new( method: 'get', url: 'https://ip-messaging.twilio.com/v2/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', ))).to eq(true) end it "receives fetch responses" do @holodeck.mock(Twilio::Response.new( 200, %q[ { "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "friendly_name": "Test slow create", "type": "apn", "sandbox": "False", "date_created": "2015-10-07T17:50:01Z", "date_updated": "2015-10-07T17:50:01Z", "url": "https://ip-messaging.twilio.com/v2/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } ] )) actual = @client.ip_messaging.v2.credentials('CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch() expect(actual).to_not eq(nil) end it "can update" do @holodeck.mock(Twilio::Response.new(500, '')) expect { @client.ip_messaging.v2.credentials('CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').update() }.to raise_exception(Twilio::REST::TwilioError) expect( @holodeck.has_request?(Holodeck::Request.new( method: 'post', url: 'https://ip-messaging.twilio.com/v2/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', ))).to eq(true) end it "receives update responses" do @holodeck.mock(Twilio::Response.new( 200, %q[ { "sid": "CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "friendly_name": "Test slow create", "type": "apn", "sandbox": "False", "date_created": "2015-10-07T17:50:01Z", "date_updated": "2015-10-07T17:50:01Z", "url": "https://ip-messaging.twilio.com/v2/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } ] )) actual = @client.ip_messaging.v2.credentials('CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').update() expect(actual).to_not eq(nil) end it "can delete" do @holodeck.mock(Twilio::Response.new(500, '')) expect { @client.ip_messaging.v2.credentials('CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').delete() }.to raise_exception(Twilio::REST::TwilioError) expect( @holodeck.has_request?(Holodeck::Request.new( method: 'delete', url: 'https://ip-messaging.twilio.com/v2/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', ))).to eq(true) end it "receives delete responses" do @holodeck.mock(Twilio::Response.new( 204, nil, )) actual = @client.ip_messaging.v2.credentials('CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').delete() expect(actual).to eq(true) end end
{ "content_hash": "f98e91eab8303d40d796f5679657faa3", "timestamp": "", "source": "github", "line_count": 211, "max_line_length": 108, "avg_line_length": 29.744075829383885, "alnum_prop": 0.5882727852135118, "repo_name": "philnash/twilio-ruby", "id": "24fbeeac6eb204015aeb7059d879fde4b24bb195", "size": "6416", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "spec/integration/ip_messaging/v2/credential_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "108" }, { "name": "Makefile", "bytes": "1003" }, { "name": "Ruby", "bytes": "10247081" } ], "symlink_target": "" }
require 'rexml/document' module ActiveMerchant #:nodoc: module Billing #:nodoc: class SecurePayAuGateway < Gateway API_VERSION = 'xml-4.2' PERIODIC_API_VERSION = 'spxml-3.0' class_attribute :test_periodic_url, :live_periodic_url, :test_token_url, :live_token_url self.test_url = 'https://test.api.securepay.com.au/xmlapi/payment' self.live_url = 'https://api.securepay.com.au/xmlapi/payment' self.test_periodic_url = 'https://test.api.securepay.com.au/xmlapi/periodic' self.live_periodic_url = 'https://api.securepay.com.au/xmlapi/periodic' self.test_token_url = 'https://test.api.securepay.com.au/xmlapi/token' self.live_token_url = 'https://api.securepay.com.au/xmlapi/token' self.supported_countries = ['AU'] self.supported_cardtypes = [:visa, :master, :american_express, :diners_club, :jcb] # The homepage URL of the gateway self.homepage_url = 'http://securepay.com.au' # The name of the gateway self.display_name = 'SecurePay' class_attribute :request_timeout self.request_timeout = 60 self.money_format = :cents self.default_currency = 'AUD' # 0 Standard Payment # 4 Refund # 6 Client Reversal (Void) # 10 Preauthorise # 11 Preauth Complete (Advice) TRANSACTIONS = { :purchase => 0, :authorization => 10, :capture => 11, :void => 6, :refund => 4 } PERIODIC_ACTIONS = { :add_triggered => "add", :remove_triggered => "delete", :trigger => "trigger" } PERIODIC_TYPES = { :add_triggered => 4, :remove_triggered => nil, :trigger => nil } SUCCESS_CODES = [ '00', '08', '11', '16', '77' ] def initialize(options = {}) requires!(options, :login, :password) super end def purchase(money, credit_card_or_stored_id, options = {}) if credit_card_or_stored_id.respond_to?(:number) requires!(options, :order_id) commit :purchase, build_purchase_request(money, credit_card_or_stored_id, options) else options[:billing_id] = credit_card_or_stored_id.to_s commit_periodic(build_periodic_item(:trigger, money, nil, options)) end end def authorize(money, credit_card, options = {}) requires!(options, :order_id) commit :authorization, build_purchase_request(money, credit_card, options) end def capture(money, reference, options = {}) commit :capture, build_reference_request(money, reference) end def refund(money, reference, options = {}) commit :refund, build_reference_request(money, reference) end def credit(money, reference, options = {}) ActiveMerchant.deprecated CREDIT_DEPRECATION_MESSAGE refund(money, reference) end def void(reference, options = {}) commit :void, build_reference_request(nil, reference) end # if options[:store_as_token] is present, then use the token API # instead of adding the card as a payor def store(creditcard, options = {}) requires!(options, :billing_id, :amount) if options[:store_as_token].present? # store the card as a token commit_token(build_token_item(options[:amount], creditcard, options)) else # store the card as a payor commit_periodic(build_periodic_item(:add_triggered, options[:amount], creditcard, options)) end end def unstore(identification, options = {}) options[:billing_id] = identification commit_periodic(build_periodic_item(:remove_triggered, options[:amount], nil, options)) end def supports_scrubbing? true end def scrub(transcript) transcript. gsub(%r((<merchantID>).+(</merchantID>)), '\1[FILTERED]\2'). gsub(%r((<password>).+(</password>)), '\1[FILTERED]\2'). gsub(%r((<cardNumber>).+(</cardNumber>)), '\1[FILTERED]\2'). gsub(%r((<cvv>).+(</cvv>)), '\1[FILTERED]\2') end private def build_purchase_request(money, credit_card, options) xml = Builder::XmlMarkup.new currency = options[:currency] || currency(money) xml.tag! 'amount', localized_amount(money, currency) xml.tag! 'currency', currency xml.tag! 'purchaseOrderNo', options[:order_id].to_s.gsub(/[ ']/, '') xml.tag! 'CreditCardInfo' do xml.tag! 'cardNumber', credit_card.number xml.tag! 'expiryDate', expdate(credit_card) xml.tag! 'cvv', credit_card.verification_value if credit_card.verification_value? end xml.target! end def build_reference_request(money, reference) xml = Builder::XmlMarkup.new transaction_id, order_id, preauth_id, original_amount = reference.split('*') xml.tag! 'amount', (money ? amount(money) : original_amount) xml.tag! 'currency', options[:currency] || currency(money) xml.tag! 'txnID', transaction_id xml.tag! 'purchaseOrderNo', order_id xml.tag! 'preauthID', preauth_id xml.target! end def build_request(action, body) xml = Builder::XmlMarkup.new xml.instruct! xml.tag! 'SecurePayMessage' do xml.tag! 'MessageInfo' do xml.tag! 'messageID', SecureRandom.hex(15) xml.tag! 'messageTimestamp', generate_timestamp xml.tag! 'timeoutValue', request_timeout xml.tag! 'apiVersion', API_VERSION end xml.tag! 'MerchantInfo' do xml.tag! 'merchantID', @options[:login] xml.tag! 'password', @options[:password] end xml.tag! 'RequestType', 'Payment' xml.tag! 'Payment' do xml.tag! 'TxnList', "count" => 1 do xml.tag! 'Txn', "ID" => 1 do xml.tag! 'txnType', TRANSACTIONS[action] xml.tag! 'txnSource', 23 xml << body end end end end xml.target! end def commit(action, request) response = parse(ssl_post(test? ? self.test_url : self.live_url, build_request(action, request))) Response.new(success?(response), message_from(response), response, :test => test?, :authorization => authorization_from(response) ) end def build_periodic_item(action, money, credit_card, options) xml = Builder::XmlMarkup.new xml.tag! 'actionType', PERIODIC_ACTIONS[action] xml.tag! 'clientID', options[:billing_id].to_s if credit_card xml.tag! 'CreditCardInfo' do xml.tag! 'cardNumber', credit_card.number xml.tag! 'expiryDate', expdate(credit_card) xml.tag! 'cvv', credit_card.verification_value if credit_card.verification_value? end end xml.tag! 'amount', amount(money) xml.tag! 'periodicType', PERIODIC_TYPES[action] if PERIODIC_TYPES[action] xml.target! end def build_periodic_request(body) xml = Builder::XmlMarkup.new xml.instruct! xml.tag! 'SecurePayMessage' do xml.tag! 'MessageInfo' do xml.tag! 'messageID', SecureRandom.hex(15) xml.tag! 'messageTimestamp', generate_timestamp xml.tag! 'timeoutValue', request_timeout xml.tag! 'apiVersion', PERIODIC_API_VERSION end xml.tag! 'MerchantInfo' do xml.tag! 'merchantID', @options[:login] xml.tag! 'password', @options[:password] end xml.tag! 'RequestType', 'Periodic' xml.tag! 'Periodic' do xml.tag! 'PeriodicList', "count" => 1 do xml.tag! 'PeriodicItem', "ID" => 1 do xml << body end end end end xml.target! end def commit_periodic(request) my_request = build_periodic_request(request) #puts my_request response = parse(ssl_post(test? ? self.test_periodic_url : self.live_periodic_url, my_request, headers)) Response.new(success?(response), message_from(response), response, :test => test?, :authorization => authorization_from(response) ) end def build_token_item(money, credit_card, options) xml = Builder::XmlMarkup.new xml.tag! 'transactionReference', options[:billing_id].to_s if credit_card xml.tag! 'cardNumber', credit_card.number xml.tag! 'expiryDate', expdate(credit_card) end xml.tag! 'amount', amount(money) xml.target! end def build_token_request(body) xml = Builder::XmlMarkup.new xml.instruct! xml.tag! 'SecurePayMessage' do xml.tag! 'MessageInfo' do xml.tag! 'messageID', SecureRandom.hex(15) xml.tag! 'messageTimestamp', generate_timestamp xml.tag! 'timeoutValue', request_timeout xml.tag! 'apiVersion', PERIODIC_API_VERSION end xml.tag! 'MerchantInfo' do xml.tag! 'merchantID', @options[:login] xml.tag! 'password', @options[:password] end xml.tag! 'RequestType', 'addToken' xml.tag! 'Token' do xml.tag! 'TokenList', "count" => 1 do xml.tag! 'TokenItem', "ID" => 1 do xml << body end end end end xml.target! end def commit_token(request) my_request = build_token_request(request) #puts my_request response = parse(ssl_post(test? ? self.test_token_url : self.live_token_url, my_request, headers)) Response.new(success?(response), message_from(response), response, :test => test?, :authorization => authorization_from(response) ) end def success?(response) SUCCESS_CODES.include?(response[:response_code]) end def authorization_from(response) [response[:txn_id], response[:purchase_order_no], response[:preauth_id], response[:amount]].join('*') end def message_from(response) response[:response_text] || response[:status_description] end def expdate(credit_card) "#{format(credit_card.month, :two_digits)}/#{format(credit_card.year, :two_digits)}" end def parse(body) xml = REXML::Document.new(body) response = {} xml.root.elements.to_a.each do |node| parse_element(response, node) end response end def headers { 'Content-Type' => 'text/xml' } end def parse_element(response, node) if node.has_elements? node.elements.each{|element| parse_element(response, element) } else response[node.name.underscore.to_sym] = node.text end end # YYYYDDMMHHNNSSKKK000sOOO def generate_timestamp time = Time.now.utc time.strftime("%Y%d%m%H%M%S#{time.usec}+000") end end end end
{ "content_hash": "3a108a552c66304c5d7c5bad8a8eab2a", "timestamp": "", "source": "github", "line_count": 361, "max_line_length": 112, "avg_line_length": 31.329639889196677, "alnum_prop": 0.5762157382847038, "repo_name": "waysact/active_merchant", "id": "393779ea2116c9d6891d9ae1c70c5a6f1f7ba540", "size": "11310", "binary": false, "copies": "1", "ref": "refs/heads/waysact/master", "path": "lib/active_merchant/billing/gateways/secure_pay_au.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "198" }, { "name": "Ruby", "bytes": "8088671" }, { "name": "Shell", "bytes": "808" } ], "symlink_target": "" }
FROM balenalib/n510-tx2-fedora:33-run ENV GO_VERSION 1.17.7 # gcc for cgo RUN dnf install -y \ gcc-c++ \ gcc \ git \ && dnf clean all RUN mkdir -p /usr/local/go \ && curl -SLO "https://storage.googleapis.com/golang/go$GO_VERSION.linux-arm64.tar.gz" \ && echo "a5aa1ed17d45ee1d58b4a4099b12f8942acbd1dd09b2e9a6abb1c4898043c5f5 go$GO_VERSION.linux-arm64.tar.gz" | sha256sum -c - \ && tar -xzf "go$GO_VERSION.linux-arm64.tar.gz" -C /usr/local/go --strip-components=1 \ && rm -f go$GO_VERSION.linux-arm64.tar.gz ENV GOROOT /usr/local/go ENV GOPATH /go ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" WORKDIR $GOPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/613d8e9ca8540f29a43fddf658db56a8d826fffe/scripts/assets/tests/test-stack@golang.sh" \ && echo "Running test-stack@golang" \ && chmod +x test-stack@golang.sh \ && bash test-stack@golang.sh \ && rm -rf test-stack@golang.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Fedora 33 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.17.7 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "c280d390c93be052bcf9a8c58c4651c8", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 669, "avg_line_length": 53.89473684210526, "alnum_prop": 0.7158203125, "repo_name": "resin-io-library/base-images", "id": "9f7a4010489d4d37eef970846aa8fe6ad421e221", "size": "2069", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/golang/n510-tx2/fedora/33/1.17.7/run/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "71234697" }, { "name": "JavaScript", "bytes": "13096" }, { "name": "Shell", "bytes": "12051936" }, { "name": "Smarty", "bytes": "59789" } ], "symlink_target": "" }
require 'spec_helper' RSpec.describe Subjects::Remover do let(:workflow) { create(:workflow_with_subjects) } let(:subject_set) do create(:subject_set_with_subjects, workflows: [workflow]) end let(:subjects) { subject_set.subjects } let(:subject) { subjects.sample } let!(:linked_sws) do create( :subject_workflow_status, workflow: workflow, subject: subject, classifications_count: 0 ) end let(:panoptes_client) { instance_double(Panoptes::Client) } let(:remover) { Subjects::Remover.new(subject.id, panoptes_client) } describe "#cleanup" do describe "testing the client configuration" do it "should setup the panoptes client with the correct env" do expect(Panoptes::Client) .to receive(:new) .with(env: Rails.env) Subjects::Remover.new(subject.id) end end context "with a client test double testing the client configuration" do let(:discussions) { [] } before do allow(panoptes_client) .to receive(:discussions) .with(focus_id: subject.id, focus_type: "Subject") .and_return(discussions) end context "without a real subject" do let(:linked_sws) { nil } let(:subject) { double(id: 100) } it "should ignore non existant subject ids" do expect(remover.cleanup).to be_falsey end end it "should not remove a subject that has been classified" do create(:classification, subjects: [subject]) expect(remover.cleanup).to be_falsey end it "should not remove a subject that has been collected" do create(:collection, subjects: [subject]) expect(remover.cleanup).to be_falsey end context "with a talk discussions" do let(:discussions) { [{"dummy" => "discussion"}] } it "should not remove a subject that has been in a talk discussion" do expect(remover.cleanup).to be_falsey end end it "should remove a subject that has not been used" do remover.cleanup expect { Subject.find(subject.id) }.to raise_error(ActiveRecord::RecordNotFound) end context "with a non-zero count sws record" do let(:linked_sws) do create( :subject_workflow_status, workflow: workflow, subject: subject, classifications_count: 10 ) end it "should not remove a subject that has a non-zero count a sws record" do expect(remover.cleanup).to be_falsey end end context "with a retired count sws record" do let(:linked_sws) do create( :subject_workflow_status, workflow: workflow, subject: subject, retired_at: Time.now, retirement_reason: :flagged ) end it "should not remove a subject that has a retired sws record" do expect(remover.cleanup).to be_falsey end end it "should remove the associated set_member_subjects" do sms_ids = subject.set_member_subjects.map(&:id) remover.cleanup expect { SetMemberSubject.find(sms_ids) }.to raise_error(ActiveRecord::RecordNotFound) end it "should remove the associated media resources" do locations = subjects.map { |s| create(:medium, linked: s) } media_ids = subject.reload.locations.map(&:id) remover.cleanup expect { Medium.find(media_ids) }.to raise_error(ActiveRecord::RecordNotFound) end it "notify selector service about the subject removal" do expect(NotifySubjectSelectorOfRetirementWorker) .to receive(:perform_async) .with(subject.id, workflow.id) remover.cleanup end end end end
{ "content_hash": "c94b75b5e578c7caa47a14f573c1b20b", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 94, "avg_line_length": 31.276422764227643, "alnum_prop": 0.6178840655055887, "repo_name": "zooniverse/Panoptes", "id": "e2ca8c8373e7dfeb6a284b4ce947f3852e1a1ce5", "size": "3847", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/lib/subjects/remover_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "API Blueprint", "bytes": "154140" }, { "name": "CSS", "bytes": "6191" }, { "name": "Dockerfile", "bytes": "852" }, { "name": "HTML", "bytes": "60770" }, { "name": "JavaScript", "bytes": "2160" }, { "name": "Ruby", "bytes": "1523574" }, { "name": "Shell", "bytes": "1337" } ], "symlink_target": "" }