text
stringlengths 2
1.04M
| meta
dict |
---|---|
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "820df871f076d30267e9a98add74aa43",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "f6addedee6065a542d220b10409fe774c18ee277",
"size": "200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Capparaceae/Linnaeobreynia/Linnaeobreynia domingensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import { autoBindMethodsForReact } from 'class-autobind-decorator';
import classnames from 'classnames';
import React, { Fragment, PureComponent } from 'react';
import ReactDOM from 'react-dom';
import { AUTOBIND_CFG } from '../../../common/constants';
import { DebouncedInput } from '../base/debounced-input';
import { CodeEditor, CodeEditorOnChange, UnconnectedCodeEditor } from './code-editor';
const MODE_INPUT = 'input';
const MODE_EDITOR = 'editor';
const TYPE_TEXT = 'text';
const NUNJUCKS_REGEX = /({%|%}|{{|}})/;
interface Props {
defaultValue: string;
id?: string;
type?: string;
mode?: string;
onBlur?: (e: FocusEvent) => void;
onKeyDown?: (e: KeyboardEvent, value?: any) => void;
onFocus?: (e: FocusEvent) => void;
onChange?: CodeEditorOnChange;
onPaste?: (e: ClipboardEvent) => void;
getAutocompleteConstants?: () => string[] | PromiseLike<string[]>;
placeholder?: string;
className?: string;
forceEditor?: boolean;
forceInput?: boolean;
readOnly?: boolean;
// TODO(TSCONVERSION) figure out why so many components pass this in yet it isn't used anywhere in this
disabled?: boolean;
}
interface State {
mode: string;
}
@autoBindMethodsForReact(AUTOBIND_CFG)
export class OneLineEditor extends PureComponent<Props, State> {
_editor: UnconnectedCodeEditor | null = null;
_input: DebouncedInput | null = null;
_mouseEnterTimeout: NodeJS.Timeout | null = null;
constructor(props: Props) {
super(props);
let mode;
if (props.forceInput) {
mode = MODE_INPUT;
} else if (props.forceEditor) {
mode = MODE_EDITOR;
} else if (this._mayContainNunjucks(props.defaultValue)) {
mode = MODE_EDITOR;
} else {
mode = MODE_INPUT;
}
this.state = {
mode,
};
}
focus(setToEnd = false) {
if (this.state.mode === MODE_EDITOR) {
if (this._editor && !this._editor?.hasFocus()) {
setToEnd ? this._editor?.focusEnd() : this._editor?.focus();
}
} else {
if (this._input && !this._input?.hasFocus()) {
setToEnd ? this._input?.focusEnd() : this._input?.focus();
}
}
}
focusEnd() {
this.focus(true);
}
selectAll() {
if (this.state.mode === MODE_EDITOR) {
this._editor?.selectAll();
} else {
this._input?.select();
}
}
getValue() {
if (this.state.mode === MODE_EDITOR) {
return this._editor?.getValue();
} else {
return this._input?.getValue();
}
}
getSelectionStart() {
if (this._editor) {
return this._editor?.getSelectionStart();
} else {
console.warn('Tried to get selection start of one-line-editor when <input>');
// @ts-expect-error -- TSCONVERSION
return this._input?.value.length;
}
}
getSelectionEnd() {
if (this._editor) {
return this._editor?.getSelectionEnd();
} else {
console.warn('Tried to get selection end of one-line-editor when <input>');
// @ts-expect-error -- TSCONVERSION
return this._input?.value.length;
}
}
componentDidMount() {
document.body.addEventListener('mousedown', this._handleDocumentMousedown);
}
componentWillUnmount() {
document.body.removeEventListener('mousedown', this._handleDocumentMousedown);
}
_handleDocumentMousedown(event: KeyboardEvent) {
if (!this._editor) {
return;
}
// Clear the selection if mousedown happens outside the input so we act like
// a regular <input>
// NOTE: Must be "mousedown", not "click" because "click" triggers on selection drags
const node = ReactDOM.findDOMNode(this._editor);
// @ts-expect-error -- TSCONVERSION
const clickWasOutsideOfComponent = !node.contains(event.target);
if (clickWasOutsideOfComponent) {
this._editor?.clearSelection();
}
}
_handleInputDragEnter() {
this._convertToEditorPreserveFocus();
}
_handleInputMouseEnter() {
// Convert to editor when user hovers mouse over input
/*
* NOTE: we're doing it in a timeout because we don't want to convert if the
* mouse goes in an out right away.
*/
this._mouseEnterTimeout = setTimeout(this._convertToEditorPreserveFocus, 100);
}
_handleInputMouseLeave() {
if (this._mouseEnterTimeout !== null) {
clearTimeout(this._mouseEnterTimeout);
}
}
_handleEditorMouseLeave() {
this._convertToInputIfNotFocused();
}
_handleEditorFocus(e) {
const focusedFromTabEvent = !!e.sourceCapabilities;
if (focusedFromTabEvent) {
this._editor?.focusEnd();
}
if (!this._editor) {
console.warn('Tried to focus editor when it was not mounted', this);
return;
}
// Set focused state
this._editor?.setAttribute('data-focused', 'on');
this.props.onFocus?.(e);
}
_handleInputFocus(e) {
// If we're focusing the whole thing, blur the input. This happens when
// the user tabs to the field.
const start = this._input?.getSelectionStart();
const end = this._input?.getSelectionEnd();
const focusedFromTabEvent = start === 0 && end === e.target.value.length;
if (focusedFromTabEvent) {
this._input?.focusEnd();
// Also convert to editor if we tabbed to it. Just in case the user
// needs an editor
this._convertToEditorPreserveFocus();
}
// Set focused state
this._input?.setAttribute('data-focused', 'on');
// Also call the regular callback
this.props.onFocus?.(e);
}
_handleInputChange(value) {
this._convertToEditorPreserveFocus();
this.props.onChange?.(value);
}
_handleInputKeyDown(event) {
if (this.props.onKeyDown) {
this.props.onKeyDown(event, event.target.value);
}
}
_handleInputBlur(e: FocusEvent) {
// Set focused state
this._input?.removeAttribute('data-focused');
this.props.onBlur?.(e);
}
_handleEditorBlur(e: FocusEvent) {
// Editor was already removed from the DOM, so do nothing
if (!this._editor) {
return;
}
// Set focused state
this._editor?.removeAttribute('data-focused');
if (!this.props.forceEditor) {
// Convert back to input sometime in the future.
// NOTE: this was originally added because the input would disappear if
// the user tabbed away very shortly after typing, but it's actually a pretty
// good feature.
setTimeout(() => {
this._convertToInputIfNotFocused();
}, 2000);
}
this.props.onBlur?.(e);
}
// @TODO Refactor this event handler. The way we search for a parent form node is not stable.
_handleKeyDown(event) {
// submit form if needed
if (event.keyCode === 13) {
let node = event.target;
for (let i = 0; i < 20 && node; i++) {
if (node.tagName === 'FORM') {
node.dispatchEvent(new window.Event('submit'));
event.preventDefault();
event.stopPropagation();
break;
}
node = node.parentNode;
}
}
this.props.onKeyDown?.(event, this.getValue());
}
_convertToEditorPreserveFocus() {
if (this.state.mode !== MODE_INPUT || this.props.forceInput) {
return;
}
if (!this._input) {
return;
}
if (this._input?.hasFocus()) {
const start = this._input?.getSelectionStart();
const end = this._input?.getSelectionEnd();
if (start === null || end === null) {
return;
}
// Wait for the editor to swap and restore cursor position
const check = () => {
if (this._editor) {
this._editor?.focus();
this._editor?.setSelection(start, end, 0, 0);
} else {
setTimeout(check, 40);
}
};
// Tell the component to show the editor
setTimeout(check);
}
this.setState({
mode: MODE_EDITOR,
});
}
_convertToInputIfNotFocused() {
if (this.state.mode === MODE_INPUT || this.props.forceEditor) {
return;
}
if (!this._editor || this._editor?.hasFocus()) {
return;
}
if (this._mayContainNunjucks(this.getValue())) {
return;
}
this.setState({
mode: MODE_INPUT,
});
}
_setEditorRef(n: UnconnectedCodeEditor) {
this._editor = n;
}
_setInputRef(n: DebouncedInput) {
this._input = n;
}
_mayContainNunjucks(text) {
// Not sure, but sometimes this isn't a string
if (typeof text !== 'string') {
return false;
}
// Does the string contain Nunjucks tags?
return !!text.match(NUNJUCKS_REGEX);
}
render() {
const {
id,
defaultValue,
className,
onChange,
placeholder,
onPaste,
getAutocompleteConstants,
mode: syntaxMode,
type: originalType,
} = this.props;
const { mode } = this.state;
const type = originalType || TYPE_TEXT;
const showEditor = mode === MODE_EDITOR;
if (showEditor) {
return (
<Fragment>
<CodeEditor
ref={this._setEditorRef}
defaultTabBehavior
hideLineNumbers
hideScrollbars
noMatchBrackets
noStyleActiveLine
noLint
singleLine
ignoreEditorFontSettings
enableNunjucks
autoCloseBrackets={false}
tabIndex={0}
id={id}
type={type}
mode={syntaxMode}
placeholder={placeholder}
onPaste={onPaste}
onBlur={this._handleEditorBlur}
onKeyDown={this._handleKeyDown}
onFocus={this._handleEditorFocus}
onMouseLeave={this._handleEditorMouseLeave}
onChange={onChange}
getAutocompleteConstants={getAutocompleteConstants}
className={classnames('editor--single-line', className)}
defaultValue={defaultValue}
/>
</Fragment>
);
} else {
return (
<DebouncedInput
ref={this._setInputRef}
// @ts-expect-error -- TSCONVERSION
id={id}
type={type}
className={className}
style={{
// background: 'rgba(255, 0, 0, 0.05)', // For debugging
width: '100%',
}}
placeholder={placeholder}
defaultValue={defaultValue}
onBlur={this._handleInputBlur}
onChange={this._handleInputChange}
onMouseEnter={this._handleInputMouseEnter}
onMouseLeave={this._handleInputMouseLeave}
onDragEnter={this._handleInputDragEnter}
onPaste={onPaste}
onFocus={this._handleInputFocus}
onKeyDown={this._handleInputKeyDown}
/>
);
}
}
}
| {
"content_hash": "fda1930cf77a74fa9eb63a6ab9b66188",
"timestamp": "",
"source": "github",
"line_count": 414,
"max_line_length": 105,
"avg_line_length": 25.792270531400966,
"alnum_prop": 0.602172691515265,
"repo_name": "getinsomnia/insomnia",
"id": "eeabbd54c174e4810b73123c72b60110093f5ea1",
"size": "10678",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "packages/insomnia-app/app/ui/components/codemirror/one-line-editor.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "96064"
},
{
"name": "Dockerfile",
"bytes": "1113"
},
{
"name": "HTML",
"bytes": "701"
},
{
"name": "JavaScript",
"bytes": "6665879"
},
{
"name": "Shell",
"bytes": "6934"
}
],
"symlink_target": ""
} |
import analyticsPageview from '../../app/mixins/analytics-preview'
export default analyticsPageView
| {
"content_hash": "7d0bf7c6dcd86bacd867d6b5e8f6bea1",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 66,
"avg_line_length": 33.666666666666664,
"alnum_prop": 0.8118811881188119,
"repo_name": "koriroys/ember-cli-ga",
"id": "8543b1937c5fa15af2ebb67df40877e0be38e75a",
"size": "101",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "addon/mixins/analytics-pageview.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1623"
},
{
"name": "JavaScript",
"bytes": "6271"
}
],
"symlink_target": ""
} |
/**
*============================================================================
* The Ohio State University Research Foundation, The University of Chicago -
* Argonne National Laboratory, Emory University, SemanticBits LLC,
* and Ekagra Software Technologies Ltd.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-portal/LICENSE.txt for details.
*============================================================================
**/
/**
*
*/
package gov.nih.nci.cagrid.tools;
import gov.nih.nci.cagrid.metadata.MetadataUtils;
import gov.nih.nci.cagrid.metadata.dataservice.DomainModel;
import gov.nih.nci.cagrid.sdkquery4.beans.domaininfo.DomainTypesInformation;
import gov.nih.nci.cagrid.sdkquery4.processor.DomainTypesInformationUtil;
import gov.nih.nci.cagrid.sdkquery4.style.beanmap.BeanTypeDiscoveryMapper;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
/**
* @author <a href="mailto:[email protected]">Joshua Phillips</a>
*
*/
public class GenBeanTypes {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
File beansJar = new File(args[0]);
DomainModel domainModel = MetadataUtils
.deserializeDomainModel(new FileReader(args[1]));
FileWriter writer = new FileWriter(args[2]);
BeanTypeDiscoveryMapper d = new BeanTypeDiscoveryMapper(beansJar, domainModel);
DomainTypesInformation info = d.discoverTypesInformation();
DomainTypesInformationUtil.serializeDomainTypesInformation(info, writer);
writer.flush();
writer.close();
}
}
| {
"content_hash": "0cd460e7e71c8d465208a0c0f52d7338",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 81,
"avg_line_length": 32.57142857142857,
"alnum_prop": 0.6923558897243107,
"repo_name": "NCIP/cagrid-portal",
"id": "223644eadcaf670ef75841cf211f1cf35753d6cf",
"size": "1596",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cagrid-portal/exp/model-gen/src/java/gov/nih/nci/cagrid/tools/GenBeanTypes.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "2937842"
},
{
"name": "JavaScript",
"bytes": "94652"
},
{
"name": "Logos",
"bytes": "64766"
},
{
"name": "Shell",
"bytes": "31573"
},
{
"name": "XSLT",
"bytes": "69341"
}
],
"symlink_target": ""
} |
<?php
namespace Facebook\Tests\FileUpload;
use Facebook\FileUpload\FacebookFile;
use Facebook\FacebookApp;
use Facebook\FacebookClient;
use Facebook\FileUpload\FacebookResumableUploader;
use Facebook\FileUpload\FacebookTransferChunk;
use Facebook\Tests\Fixtures\FakeGraphApiForResumableUpload;
class FacebookResumableUploaderTest extends \PHPUnit_Framework_TestCase
{
/**
* @var FacebookApp
*/
private $fbApp;
/**
* @var FacebookClient
*/
private $client;
/**
* @var FakeGraphApiForResumableUpload
*/
private $graphApi;
/**
* @var FacebookFile
*/
private $file;
protected function setUp()
{
$this->fbApp = new FacebookApp('app_id', 'app_secret');
$this->graphApi = new FakeGraphApiForResumableUpload();
$this->client = new FacebookClient($this->graphApi);
$this->file = new FacebookFile(__DIR__.'/../foo.txt');
}
public function testResumableUploadCanStartTransferAndFinish()
{
$uploader = new FacebookResumableUploader($this->fbApp, $this->client, 'access_token', 'v2.4');
$endpoint = '/me/videos';
$chunk = $uploader->start($endpoint, $this->file);
$this->assertInstanceOf('Facebook\FileUpload\FacebookTransferChunk', $chunk);
$this->assertEquals('42', $chunk->getUploadSessionId());
$this->assertEquals('1337', $chunk->getVideoId());
$newChunk = $uploader->transfer($endpoint, $chunk);
$this->assertEquals(20, $newChunk->getStartOffset());
$this->assertNotSame($newChunk, $chunk);
$finalResponse = $uploader->finish($endpoint, $chunk->getUploadSessionId(), []);
$this->assertTrue($finalResponse);
}
/**
* @expectedException \Facebook\Exceptions\FacebookResponseException
*/
public function testStartWillLetErrorResponsesThrow()
{
$this->graphApi->failOnStart();
$uploader = new FacebookResumableUploader($this->fbApp, $this->client, 'access_token', 'v2.4');
$uploader->start('/me/videos', $this->file);
}
public function testFailedResumableTransferWillNotThrowAndReturnSameChunk()
{
$this->graphApi->failOnTransfer();
$uploader = new FacebookResumableUploader($this->fbApp, $this->client, 'access_token', 'v2.4');
$chunk = new FacebookTransferChunk($this->file, '1', '2', '3', '4');
$newChunk = $uploader->transfer('/me/videos', $chunk);
$this->assertSame($newChunk, $chunk);
}
}
| {
"content_hash": "96deea873c33fad06695f8e9fb0f21df",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 103,
"avg_line_length": 31.45,
"alnum_prop": 0.6506359300476947,
"repo_name": "xvyx/staszic-librus",
"id": "c32b7fbacdaddc5a3afef0182e94114fb8008e32",
"size": "3591",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "includes/php-graph-sdk/tests/FileUpload/FacebookResumableUploaderTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "634694"
}
],
"symlink_target": ""
} |
var util = require('util');
var events = require('events');
var net = require('net');
var socket = new net.Socket();
// define a constructor (object) and inherit EventEmitter functions
function Telnet() {
events.EventEmitter.call(this);
if (false === (this instanceof Telnet)) return new Telnet();
}
util.inherits(Telnet, events.EventEmitter);
Telnet.prototype.connect = function(opts) {
var self = this;
var host = (typeof opts.host !== 'undefined' ? opts.host : '127.0.0.1');
var port = (typeof opts.port !== 'undefined' ? opts.port : 23);
this.timeout = (typeof opts.timeout !== 'undefined' ? opts.timeout : 500);
this.shellPrompt = (typeof opts.shellPrompt !== 'undefined'
? opts.shellPrompt : /(?:\/ )?#\s/);
this.loginPrompt = (typeof opts.loginPrompt !== 'undefined'
? opts.loginPrompt : /login[: ]*$/i);
this.passwordPrompt = (typeof opts.passwordPrompt !== 'undefined'
? opts.passwordPrompt : /Password: /i);
this.failedLoginPrompt = (typeof opts.failedLoginPrompt !== 'undefined'
? opts.failedLoginPrompt : undefined);
this.username = (typeof opts.username !== 'undefined' ? opts.username : 'root');
this.password = (typeof opts.password !== 'undefined' ? opts.password : 'guest');
this.irs = (typeof opts.irs !== 'undefined' ? opts.irs : '\r\n');
this.ors = (typeof opts.ors !== 'undefined' ? opts.ors : '\n');
this.echoLines = (typeof opts.echoLines !== 'undefined' ? opts.echoLines : 1);
this.pageSeparator = (typeof opts.pageSeparator !== 'undefined'
? opts.pageSeparator : '---- More');
this.response = '';
this.telnetState;
this.telnetSocket = net.createConnection({
port: port,
host: host
}, function() {
self.telnetState = 'start';
self.stringData = '';
self.emit('connect');
});
this.telnetSocket.setTimeout(this.timeout, function() {
if (self.telnetSocket._connecting === true) {
// info: cannot connect; emit error and destroy
self.emit('error', 'Cannot connect');
self.telnetSocket.destroy();
}
else self.emit('timeout');
});
this.telnetSocket.on('data', function(data) {
parseData(data, self);
});
this.telnetSocket.on('error', function(error) {
self.emit('error', error);
});
this.telnetSocket.on('end', function() {
self.emit('end');
});
this.telnetSocket.on('close', function() {
self.emit('close');
});
}
Telnet.prototype.exec = function(cmd, opts, callback) {
var self = this;
cmd += this.ors;
if (opts && opts instanceof Function) callback = opts;
else if (opts && opts instanceof Object) {
self.shellPrompt = opts.shellPrompt || self.shellPrompt;
self.loginPrompt = opts.loginPrompt || self.loginPrompt;
self.failedLoginPrompt = opts.failedLoginPrompt || self.failedLoginPrompt;
self.timeout = opts.timeout || self.timeout;
self.irs = opts.irs || self.irs;
self.ors = opts.ors || self.ors;
self.echoLines = opts.echoLines || self.echoLines;
}
if (this.telnetSocket.writable) {
this.telnetSocket.write(cmd, function() {
self.telnetState = 'response';
self.emit('writedone');
self.once('responseready', function() {
if (callback && self.cmdOutput !== 'undefined') {
callback(self.cmdOutput.join('\n'));
}
else if (callback && self.cmdOutput === 'undefined') callback;
// reset stored response
self.stringData = '';
});
});
}
}
Telnet.prototype.end = function() {
this.telnetSocket.end();
}
Telnet.prototype.destroy = function() {
this.telnetSocket.destroy();
}
function parseData(chunk, telnetObj) {
var promptIndex = '';
if (chunk[0] === 255 && chunk[1] !== 255) {
telnetObj.stringData = '';
var negReturn = negotiate(telnetObj, chunk);
if (negReturn == undefined) return;
else chunk = negReturn;
}
if (telnetObj.telnetState === 'start') {
telnetObj.telnetState = 'getprompt';
}
if (telnetObj.telnetState === 'getprompt') {
var stringData = chunk.toString();
var promptIndex = stringData.search(regexEscape(telnetObj.shellPrompt));
if (promptIndex !== -1) {
telnetObj.shellPrompt = stringData.substring(promptIndex);
telnetObj.telnetState = 'sendcmd';
telnetObj.stringData = '';
telnetObj.emit('ready', telnetObj.shellPrompt);
}
else if (stringData.search(regexEscape(telnetObj.loginPrompt)) !== -1) {
telnetObj.telnetState = 'login';
login(telnetObj, 'username');
}
else if (stringData.search(regexEscape(telnetObj.passwordPrompt)) !== -1) {
telnetObj.telnetState = 'login';
login(telnetObj, 'password');
}
else if (typeof telnetObj.failedLoginPrompt !== 'undefined' && stringData.search(telnetObj.failedLoginPrompt) !== -1) {
telnetObj.telnetState = 'failedlogin';
telnetObj.emit('failedlogin', stringData);
telnetObj.destroy();
}
else return;
}
else if (telnetObj.telnetState === 'response') {
var stringData = chunk.toString();
telnetObj.stringData += stringData;
promptIndex = stringData.search(regexEscape(telnetObj.shellPrompt));
if (promptIndex === -1 && stringData.length !== 0) {
if (stringData.search(regexEscape(telnetObj.pageSeparator)) !== -1) {
telnetObj.telnetSocket.write(Buffer('20', 'hex'));
}
return;
}
telnetObj.cmdOutput = telnetObj.stringData.split(telnetObj.irs);
for (var i = 0; i < telnetObj.cmdOutput.length; i++) {
if (telnetObj.cmdOutput[i].search(regexEscape(telnetObj.pageSeparator)) !== -1) {
telnetObj.cmdOutput[i] = telnetObj.cmdOutput[i].replace(telnetObj.pageSeparator, '');
if (telnetObj.cmdOutput[i].length === 0) telnetObj.cmdOutput.splice(i, 1);
}
}
if (telnetObj.echoLines === 1) telnetObj.cmdOutput.shift();
else if (telnetObj.echoLines > 1) telnetObj.cmdOutput.splice(0, telnetObj.echoLines);
// remove prompt
telnetObj.cmdOutput.pop();
telnetObj.emit('responseready');
}
}
function login(telnetObj, handle) {
if ((handle === 'username' || handle === 'password') && telnetObj.telnetSocket.writable) {
telnetObj.telnetSocket.write(telnetObj[handle] + telnetObj.ors, function() {
telnetObj.telnetState = 'getprompt';
});
}
}
function negotiate(telnetObj, chunk) {
// info: http://tools.ietf.org/html/rfc1143#section-7
// refuse to start performing and ack the start of performance
// DO -> WONT; WILL -> DO
var packetLength = chunk.length, negData = chunk, cmdData, negResp;
for (var i = 0; i < packetLength; i+=3) {
if (chunk[i] != 255) {
negData = chunk.slice(0, i);
cmdData = chunk.slice(i);
break;
}
}
negResp = negData.toString('hex').replace(/fd/g, 'fc').replace(/fb/g, 'fd');
if (telnetObj.telnetSocket.writable)
telnetObj.telnetSocket.write(Buffer(negResp, 'hex'));
if (cmdData != undefined) return cmdData;
else return;
}
function regexEscape(string) {
return string.toString().replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
module.exports = Telnet;
| {
"content_hash": "1dd759e5c3eeac914a9153423619e8f4",
"timestamp": "",
"source": "github",
"line_count": 222,
"max_line_length": 123,
"avg_line_length": 31.82882882882883,
"alnum_prop": 0.6446362864421172,
"repo_name": "micylt/LearningNode",
"id": "71607cf82e3e807f0e800cd3f5d0f15b66829f44",
"size": "7162",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "networking/node_modules/telnet-client/lib/telnet-client.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "15307"
}
],
"symlink_target": ""
} |
package com.ivstuart.tmud.spells;
import com.ivstuart.tmud.state.Item;
import com.ivstuart.tmud.state.Mob;
import com.ivstuart.tmud.state.Spell;
import com.ivstuart.tmud.state.util.EntityProvider;
public class CreateFood implements SpellEffect {
@Override
public void effect(Mob caster_, Mob target_, Spell spell, Item targetItem) {
Item item = EntityProvider.createItem("waffer-001");
caster_.getInventory().add(item);
caster_.out("You create an "+item.getBrief()+" your backpack");
}
public boolean isPositiveEffect() {
return true;
}
}
| {
"content_hash": "a76e77273fc4a6d158f1dc90887ba177",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 77,
"avg_line_length": 22.44,
"alnum_prop": 0.7468805704099821,
"repo_name": "ivstuart/tea-mud",
"id": "76bc879e47cca7c4b9e732304a85e942a4085be6",
"size": "1166",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/ivstuart/tmud/spells/CreateFood.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1515994"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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.
-->
<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.apache.nifi</groupId>
<artifactId>nifi-elasticsearch-bundle</artifactId>
<version>1.10.0-SNAPSHOT</version>
</parent>
<artifactId>nifi-elasticsearch-client-service-api-nar</artifactId>
<version>1.10.0-SNAPSHOT</version>
<packaging>nar</packaging>
<properties>
<maven.javadoc.skip>true</maven.javadoc.skip>
<source.skip>true</source.skip>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.nifi</groupId>
<artifactId>nifi-standard-services-api-nar</artifactId>
<version>1.10.0-SNAPSHOT</version>
<type>nar</type>
</dependency>
<dependency>
<groupId>org.apache.nifi</groupId>
<artifactId>nifi-elasticsearch-client-service-api</artifactId>
<version>1.10.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
| {
"content_hash": "f3edfe1cff72b489c82bbf9223640342",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 204,
"avg_line_length": 42.659574468085104,
"alnum_prop": 0.6912718204488778,
"repo_name": "joewitt/incubator-nifi",
"id": "c7fc9d1188d07ca40f5f4dc0a3e1131df7bf51b2",
"size": "2005",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nifi-nar-bundles/nifi-elasticsearch-bundle/nifi-elasticsearch-client-service-api-nar/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "20273"
},
{
"name": "CSS",
"bytes": "225299"
},
{
"name": "Clojure",
"bytes": "3993"
},
{
"name": "Dockerfile",
"bytes": "9932"
},
{
"name": "GAP",
"bytes": "30032"
},
{
"name": "Groovy",
"bytes": "1841699"
},
{
"name": "HTML",
"bytes": "639981"
},
{
"name": "Java",
"bytes": "35964644"
},
{
"name": "JavaScript",
"bytes": "2863409"
},
{
"name": "Lua",
"bytes": "983"
},
{
"name": "Python",
"bytes": "17954"
},
{
"name": "Ruby",
"bytes": "8028"
},
{
"name": "Shell",
"bytes": "81799"
},
{
"name": "XSLT",
"bytes": "5681"
}
],
"symlink_target": ""
} |
package org.eclipse.jdt.ui.actions;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.PlatformUI;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.ui.search.ElementQuerySpecification;
import org.eclipse.jdt.ui.search.QuerySpecification;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.search.JavaSearchScopeFactory;
import org.eclipse.jdt.internal.ui.search.SearchMessages;
import org.eclipse.jdt.internal.ui.search.SearchUtil;
/**
* Finds declarations of the selected element in working sets.
* The action is applicable to selections representing a Java element.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*
* @noextend This class is not intended to be subclassed by clients.
*/
public class FindDeclarationsInWorkingSetAction extends FindDeclarationsAction {
private IWorkingSet[] fWorkingSet;
/**
* Creates a new <code>FindDeclarationsInWorkingSetAction</code>. The action
* requires that the selection provided by the site's selection provider is of type
* <code>org.eclipse.jface.viewers.IStructuredSelection</code>. The user will be
* prompted to select the working sets.
*
* @param site the site providing context information for this action
*/
public FindDeclarationsInWorkingSetAction(IWorkbenchSite site) {
this(site, null);
}
/**
* Creates a new <code>FindDeclarationsInWorkingSetAction</code>. The action
* requires that the selection provided by the site's selection provider is of type
* <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
* @param workingSets the working sets to be used in the search
*/
public FindDeclarationsInWorkingSetAction(IWorkbenchSite site, IWorkingSet[] workingSets) {
super(site);
fWorkingSet= workingSets;
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
* @param editor the Java editor
*
* @noreference This constructor is not intended to be referenced by clients.
*/
public FindDeclarationsInWorkingSetAction(JavaEditor editor) {
this(editor, null);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*
* @param editor the Java editor
* @param workingSets the working sets to be used in the search
*
* @noreference This constructor is not intended to be referenced by clients.
*/
public FindDeclarationsInWorkingSetAction(JavaEditor editor, IWorkingSet[] workingSets) {
super(editor);
fWorkingSet= workingSets;
}
@Override
void init() {
setText(SearchMessages.Search_FindDeclarationsInWorkingSetAction_label);
setToolTipText(SearchMessages.Search_FindDeclarationsInWorkingSetAction_tooltip);
setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_DECL);
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_DECLARATIONS_IN_WORKING_SET_ACTION);
}
@Override
QuerySpecification createQuery(IJavaElement element) throws JavaModelException, InterruptedException {
JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
IWorkingSet[] workingSets= fWorkingSet;
if (fWorkingSet == null) {
workingSets= factory.queryWorkingSets();
if (workingSets == null)
return super.createQuery(element); // in workspace
}
SearchUtil.updateLRUWorkingSets(workingSets);
IJavaSearchScope scope= factory.createJavaSearchScope(workingSets, JavaSearchScopeFactory.NO_PROJ);
String description= factory.getWorkingSetScopeDescription(workingSets, JavaSearchScopeFactory.NO_PROJ);
return new ElementQuerySpecification(element, getLimitTo(), scope, description);
}
}
| {
"content_hash": "beed40209637b4fbe6dd4389884127b2",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 119,
"avg_line_length": 36.54545454545455,
"alnum_prop": 0.7830845771144279,
"repo_name": "brunyuriy/quick-fix-scout",
"id": "1c927fa6439c7d0074ab75aa967d8915682227e2",
"size": "4560",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "org.eclipse.jdt.ui_3.7.1.r371_v20110824-0800/src/org/eclipse/jdt/ui/actions/FindDeclarationsInWorkingSetAction.java",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3543"
},
{
"name": "HTML",
"bytes": "11246"
},
{
"name": "Java",
"bytes": "29448867"
}
],
"symlink_target": ""
} |
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Md_news extends CI_Model {
function listPosts() {
$this->db->select('posts.id,posts.title,posts.`date_add`,posts.is_visible,posts.is_active,users.name as user_name, languages.abbreviation');
$this->db->join('languages', 'languages.id = posts.languages_id', 'INNER');
$this->db->join('users', 'posts.users_id = users.id', 'INNER');
$this->db->order_by("posts.id", "desc");
return $this->db->get('posts');
}
function changeSpotlightNews($data) {
$data_arr = array(
'is_visible' => $data['is_visible']
);
$this->db->where('id', $data['id_post']);
$this->db->update('posts', $data_arr);
return $this->db->affected_rows();
}
function changeStatusNews($data) {
$data_arr = array(
'is_active' => $data['status']
);
$this->db->where('id', $data['id_post']);
$this->db->update('posts', $data_arr);
return $this->db->affected_rows();
}
/**
* Método para buscar registro do Post
*
* @param string $data - valor
* @param string $search - busca pelo id,slug
*/
function searchPost($data, $search) {
$this->db->select('id,title,slug,resume,description,date_start,is_visible,is_active,languages_id');
if ($search == 'id') {
$this->db->where("id", $data['id_post']);
} elseif ($search == 'slug') {
$this->db->where("slug", $data['slug']);
}
return $this->db->get('posts');
}
/**
* Método para buscar registro de Categorias
*
* @param string $data - valor
* @param string $search - busca pelo id_post,category-post (id_category,id_post)
*/
function searchPostCategory($data, $search) {
$this->db->select('posts_category.title,posts_category_relation.posts_category_id, posts_category_relation.posts_id');
$this->db->from('posts_category');
$this->db->join('posts_category_relation', 'posts_category_relation.posts_category_id = posts_category.id', 'inner');
if ($search == 'id_post') {
$this->db->where('posts_category_relation.posts_id', $data['id_post']);
} elseif ($search == 'category-post') {
$this->db->where('posts_category_relation.posts_category_id', $data['id_category']);
} elseif ($search == 'category-slug') {
$this->db->where('posts_category.slug', $data['slug_category']);
}
return $this->db->get();
}
/**
* Método para buscar registro de Tags
*
* @param string $data - valor
* @param string $search - busca pelo id_post,tag-post (id_tag,id_post)
*/
function searchPostTags($data, $search) {
$this->db->select('posts_tags.id as id_tag,posts_tags.tag');
$this->db->from('posts_tags');
$this->db->join('posts_tags_relation', 'posts_tags.id = posts_tags_relation.posts_tags_id', 'inner');
if ($search == 'id_post') {
$this->db->where("posts_tags_relation.posts_id", $data['id_post']);
} elseif ($search == 'tag-post') {
$this->db->where("posts_tags_relation.posts_tags_id", $data['id_tag']);
$this->db->where("posts_tags_relation.posts_id", $data['id_post']);
}
return $this->db->get();
}
function searchPostImage($data) {
$this->db->select('file');
$this->db->where('posts_id', $data['id_post']);
return $this->db->get('images');
}
function updatePost($data) {
$data_arr = array(
'title' => $data['title'],
'slug' => $data['slug'],
'resume' => $data['resume'],
'description' => $data['description'],
'date_start' => $data['date_start'],
'is_visible' => $data['is_visible'],
'is_active' => $data['status'],
'languages_id' => $data['language']
);
$this->db->where('id', $data['id_post']);
$this->db->update('posts', $data_arr);
$report = array('error' => $this->db->_error_number());
if (!$report['error']) {
return TRUE;
}
return FALSE;
}
function insertPost($data) {
$data = array(
'title' => $data['title'],
'slug' => $data['slug'],
'resume' => $data['resume'],
'description' => $data['description'],
'date_start' => $data['date_start'],
'is_visible' => $data['is_visible'],
'is_active' => $data['status'],
'users_id' => $this->session->userdata('user_id'),
'languages_id' => $data['language']
);
$this->db->insert('posts', $data);
return $this->db->insert_id();
}
function insertPostImage($data) {
$data = array(
'file' => $data['image'],
'category' => '1',
'posts_id' => $data['id_post']
);
$this->db->insert('images', $data);
return $this->db->affected_rows();
}
function updatePostImage($data) {
$data_arr = array(
'file' => $data['image']
);
$this->db->where('posts_id', $data['id_post']);
$this->db->update('images', $data_arr);
$report = array('error' => $this->db->_error_number());
if (!$report['error']) {
return TRUE;
}
return FALSE;
}
function insertPostCategory($data) {
$data = array(
'posts_id' => $data['id_post'],
'posts_category_id' => $data['id_category']
);
$this->db->insert('posts_category_relation', $data);
return $this->db->affected_rows();
}
function deletePostCategory($data) {
$this->db->delete('posts_category_relation', array('posts_id' => $data['id_post']));
return $this->db->affected_rows();
}
function insertPostTag($data) {
$data = array(
'tags_id' => $data['id_tag'],
'posts_id' => $data['id_post']
);
$this->db->insert('posts_tags_relation', $data);
return $this->db->affected_rows();
}
function deletePostTag($data) {
$this->db->delete('posts_tags_relation', array('posts_id' => $data['id_post']));
return $this->db->affected_rows();
}
function listCategories() {
$this->db->select('posts_category.id, parent_id, posts_category.title, posts_category.slug, posts_category.is_active, posts_category.languages_id, languages.abbreviation');
$this->db->join('languages', 'languages.id = posts_category.languages_id', 'INNER');
$this->db->order_by("title", "ASC");
return $this->db->get('posts_category');
}
function totalPostsCategory($id_category)
{
$this->db->select('posts_category_id');
$this->db->where('posts_category_id', $id_category);
return $this->db->get('posts_category_relation');
}
function insertCategory($data) {
$data = array(
'parent_id' => $data['id_category'],
'title' => $data['category'],
'slug' => $data['slug'],
'level' => $data['level'],
'languages_id' => $data['language'],
);
$this->db->insert('posts_category', $data);
return $this->db->affected_rows();
}
function searchAllCategory($parent_id, $level) {
$this->db->select("id, title, slug, level");
if ($parent_id > 0) {
$this->db->where("parent_id", $parent_id);
}
if ($level >= 0) {
$this->db->where("level", $level);
}
return $this->db->get("posts_category");
}
/**
* Método para buscar registro da Categoria
*
* @param string $data - valor
* @param string $search - busca pelo id,slug,level
*/
function searchCategory($data, $search) {
$this->db->select('id,parent_id,title,slug,level,languages_id');
if ($search == 'id') {
$this->db->where('id', $data['id_category']);
} elseif ($search == 'slug') {
$this->db->where('slug', $data['slug']);
} elseif ($search == 'level') {
$this->db->where('level', $data['level']);
}
return $this->db->get('posts_category');
}
function changeStatusCategories($data) {
$data_arr = array(
'is_active' => $data['status']
);
$this->db->where('id', $data['id_category']);
$this->db->update('posts_category', $data_arr);
return $this->db->affected_rows();
}
function insertTag($data) {
$data = array(
'tag' => $data['tag'],
'slug' => $data['slug'],
'languages_id' => $data['language'],
);
$this->db->insert('posts_tags', $data);
return $this->db->affected_rows();
}
function updateCategory($data) {
$data_arr = array(
'parent_id' => $data['category_parent'],
'title' => $data['category'],
'slug' => $data['slug'],
'languages_id' => $data['language']
);
$this->db->where('id', $data['id_category']);
$this->db->update('posts_category', $data_arr);
$report = array('error' => $this->db->_error_number());
if (!$report['error']) {
return TRUE;
}
return FALSE;
}
function listTags() {
$this->db->select('id, tag, languages.abbreviation');
$this->db->join('languages', 'languages.id = posts_tags.languages_id', 'INNER');
$this->db->order_by("tag", "asc");
return $this->db->get('posts_tags');
}
/**
* Método para buscar registro da Tag
*
* @param string $data - valor
* @param string $search - busca pelo id,tag,slug
*/
function searchTag($data, $search) {
$this->db->select('id,tag,languages_id');
if ($search == 'id') {
$this->db->where('id', $data['id_tag']);
} elseif ($search == 'tag') {
//$this->db->like('tag', $data['tag']);
$this->db->where('tag', $data['tag']);
} elseif ($search == 'slug') {
$this->db->where('slug', $data['slug']);
}
return $this->db->get('posts_tags');
}
function updateTag($data) {
$data_arr = array(
'tag' => $data['tag'],
'slug' => $data['slug'],
'languages_id' => $data['language']
);
$this->db->where('id', $data['id_tag']);
$this->db->update('posts_tags', $data_arr);
$report = array('error' => $this->db->_error_number());
if (!$report['error']) {
return TRUE;
}
return FALSE;
}
function deleteTag($data) {
$this->db->delete('posts_tags', array('id' => $data['id_tag']));
return $this->db->affected_rows();
}
function deleteTagRelation($data) {
$this->db->delete('posts_tags_relation', array('tags_id' => $data['id_tag']));
return $this->db->affected_rows();
}
function listComments()
{
$this->db->select('posts_comments.id, posts_comments.name, posts_comments.email, posts_comments.`date_add`, posts_comments.is_read, posts_comments.is_active, posts.title as post');
$this->db->join('posts', 'posts.id = posts_comments.posts_id', 'INNER');
$this->db->order_by('posts_comments.id', 'DESC');
return $this->db->get('posts_comments');
}
function changeStatusRead($data)
{
$data_arr = array(
'is_read' => $data['is_read'],
);
$this->db->where('id', $data['id_comment']);
$this->db->update('posts_comments', $data_arr);
return $this->db->affected_rows();
}
function changeStatusComments($data) {
$data_arr = array(
'is_active' => $data['status']
);
$this->db->where('id', $data['id_comment']);
$this->db->update('posts_comments', $data_arr);
return $this->db->affected_rows();
}
function searchComment($data)
{
$this->db->select('posts_comments.id,
posts_comments.name,
posts_comments.email,
posts_comments.text,
posts_comments.ip,
posts_comments.useragent,
posts_comments.`date_add`,
posts_comments.is_active,
posts.title as post');
$this->db->where('posts_comments.id', $data['id_comment']);
$this->db->join('posts', 'posts.id = posts_comments.posts_id', 'inner');
$this->db->order_by('posts_comments.id', 'desc');
return $this->db->get('posts_comments');
}
}
?> | {
"content_hash": "8fc5f5357cbf9629a84b73af327c86c4",
"timestamp": "",
"source": "github",
"line_count": 403,
"max_line_length": 182,
"avg_line_length": 31.60545905707196,
"alnum_prop": 0.5195100887179085,
"repo_name": "moreirainacio/grupotrilhas",
"id": "f030494a06c57d0b7520563c95a327c8ec803edb",
"size": "12742",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "painelctrl/application/models/md_news.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "962"
},
{
"name": "CSS",
"bytes": "1294583"
},
{
"name": "HTML",
"bytes": "6301806"
},
{
"name": "JavaScript",
"bytes": "981885"
},
{
"name": "PHP",
"bytes": "4902136"
}
],
"symlink_target": ""
} |
package boofcv.alg.interpolate.impl;
import boofcv.alg.interpolate.NearestNeighborPixelMB;
import boofcv.core.image.border.ImageBorder_IL_S32;
import boofcv.struct.image.InterleavedU16;
/**
* <p>
* Performs nearest neighbor interpolation to extract values between pixels in an image.
* </p>
*
* <p>
* NOTE: This code was automatically generated using {@link GenerateNearestNeighborPixel_IL}.
* </p>
*
* @author Peter Abeles
*/
public class NearestNeighborPixel_IL_U16 extends NearestNeighborPixelMB<InterleavedU16> {
private int pixel[] = new int[3];
public NearestNeighborPixel_IL_U16() {
}
public NearestNeighborPixel_IL_U16(InterleavedU16 orig) {
setImage(orig);
}
@Override
public void setImage(InterleavedU16 image) {
super.setImage(image);
int N = image.getImageType().getNumBands();
if( pixel.length != N )
pixel = new int[ N ];
}
@Override
public void get(float x, float y, float[] values) {
if (x < 0 || y < 0 || x > width-1 || y > height-1 ) {
((ImageBorder_IL_S32)border).get((int) Math.floor(x), (int) Math.floor(y), pixel);
for (int i = 0; i < pixel.length; i++) {
values[i] = pixel[i];
}
} else {
get_fast(x,y,values);
}
}
@Override
public void get_fast(float x, float y, float[] values) {
int xx = (int)x;
int yy = (int)y;
orig.unsafe_get(xx,yy,pixel);
for (int i = 0; i < pixel.length; i++) {
values[i] = pixel[i];
}
}
}
| {
"content_hash": "ce09f0be0a66ad156d38f52cf2d59f70",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 93,
"avg_line_length": 23.262295081967213,
"alnum_prop": 0.6617336152219874,
"repo_name": "bladestery/Sapphire",
"id": "a584bbb9df542cf8154555b25621f90725edf052",
"size": "2099",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "example_apps/AndroidStudioMinnie/sapphire/src/main/java/boofcv/alg/interpolate/impl/NearestNeighborPixel_IL_U16.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "139298"
},
{
"name": "C++",
"bytes": "1444206"
},
{
"name": "CMake",
"bytes": "3964660"
},
{
"name": "Java",
"bytes": "14581743"
},
{
"name": "Makefile",
"bytes": "107081"
},
{
"name": "Python",
"bytes": "11485"
},
{
"name": "Shell",
"bytes": "495"
}
],
"symlink_target": ""
} |
<?php
namespace Doctrine\SkeletonMapper\Tests;
interface DataTesterInterface
{
public function find($id);
public function set($id, $key, $value);
public function count();
}
| {
"content_hash": "0dfc51a2f9cf86eac52a8a50c1c8aa42",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 43,
"avg_line_length": 18.7,
"alnum_prop": 0.7112299465240641,
"repo_name": "zeroedin-bill/skeleton-mapper",
"id": "14412b2e32b0d324845a5fcc7366ac2b8ffc37e8",
"size": "187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/Doctrine/SkeletonMapper/Tests/DataTesterInterface.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "274309"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Alkitab App - Modern bible app with dramatic audio.</title>
<meta name="description" content="Alkitab App. Modern bible app with dramatic audio.">
<meta name="theme-color" content="#22223F">
<!-- Schema.org markup for Google+ -->
<meta itemprop="name" content="Alkitab App">
<meta itemprop="description" content="Alkitab App. Modern bible app with dramatic audio.
">
<meta itemprop="image" content="https://i.imgur.com/EHnfh79.png">
<!-- Twitter Card data -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@alkitabapp">
<meta name="twitter:title" content="Alkitab App">
<meta name="twitter:description" content="Alkitab App. Modern bible app with dramatic audio..
">
<meta name="twitter:creator" content="@sonnylazuardi">
<!-- Twitter summary card with large image must be at least 280x150px -->
<meta name="twitter:image" content="https://i.imgur.com/EHnfh79.png">
<meta name="twitter:image:alt" content="Alkitab App. Modern bible app with dramatic audio..
">
<!-- Open Graph data -->
<meta property="og:title" content="Alkitab App" />
<meta property="og:type" content="website" />
<meta property="og:url" content="http://alkitabapp.sonnylab.com" />
<meta property="og:image" content="https://i.imgur.com/EHnfh79.png" />
<meta property="og:description" content="Alkitab App. Modern bible app with dramatic audio..
" />
<meta name="google-site-verification" content="zM4kuBQ-Op_GKDizRX0nr0eu_Dpx_Mav0mPB0Nat-Ak" />
<link rel="stylesheet" href="/assets/styles/main.css">
<link rel="canonical" href="">
<link rel="icon" href="/assets/favicon.ico">
</head>
<body>
<main class="page-content" aria-label="Content">
<div class="wrapper">
<article class="h6-l bt b--black-10 dark-gray lh-copy-ns ph2 ph5-m opensans bg-headline">
<div class="flex flex-column flex-row-l justify-center tc ph4 center">
<div class="flex h-inherit items-center mw6-l mr5-l tc tl-l">
<div class="flex flex-column flex-auto">
<div class="dn db-l">
<div class="dtc v-mid tc">
<div class="link pr4 w3 dib flex items-center mt5 justify-center">
<img class="w3" src="/assets/images/logo.png" alt="Alkitab Logo">
</div>
</div>
</div>
<div class="dn-l">
<div class="pv4">
</div>
<div class="flex dtc v-mid tc items-center justify-center">
<div class="link w3 flex h-100 items-center justify-center">
<img class="w3" src="/assets/images/logo.png" alt="Alkitab Logo">
</div>
</div>
</div>
<div class="mw5 mt3 mb5 pr5-l">
<p class="f2 f2-ns white lh-copy fw9 ts">
Modern bible<br />
app with<br />
dramatic audio
</p>
<!-- Place this tag where you want the button to render. -->
<a class="github-button" href="https://github.com/sonnylazuardi/alkitab-app" data-icon="octicon-star" data-size="large" data-show-count="true" aria-label="Star sonnylazuardi/alkitab-app on GitHub">Star</a>
</div>
</div>
</div>
<div class="dn db-l">
<div class="flex mt5 h-100 items-center">
<img class="grow mw5" src="/assets/images/phone.png" alt="Alkitab App Mockup">
</div>
</div>
<div class="dn-l">
<div class="flex h-100 items-center justify-center">
<img class="grow mw5-m" src="/assets/images/phone.png" alt="Alkitab App Mockup">
</div>
</div>
</div>
</article>
<article class="bg-secondary ph4 ph5-m pv4 pv5-ns opensans nt5">
<div class="flex flex-column h-100 items-center justify-center mt3">
<p class="f4 f4-m f4-l fw7 black mb2">
Alkitab (Suara) App
</p>
<p class="f6 f6-ns dark-gray lh-copy mw5 mb4 tc">
Beautifully designed bible app that is optimized for speed.
This is an open source bible app built with the latest tech stack out there:
<strong>React Native & RealmJS</strong>
</p>
</div>
</article>
<article class="bg-primary h6-l dark-gray lh-copy-ns ph4 ph5-m pv4 pv5-ns opensans">
<div class="flex h-inherit tc-l justify-center">
<div class="flex flex-column mw8-l">
<div class="flex flex-column flex-row-l">
<div class="fl w-30-l pa2">
<p class="f6 f6-m f6-l fw7 white mb2">
Offline Access 🌩️
</p>
<p class="f6 f6-ns moon-gray lh-copy mw5 mb4">
Browse and read verses even if you are not connected to the internet
</p>
</div>
<div class="fl w-30-l pa2">
<p class="f6 f6-m f6-l fw7 white mb2">
Blazing Fast Search ⚡
</p>
<p class="f6 f6-ns moon-gray lh-copy mw5 mb4">
Search the verses by keyword, it will return as fast as you type
</p>
</div>
<div class="fl w-30-l pa2">
<p class="f6 f6-m f6-l fw7 white mb2">
Quick Jump 🏃
</p>
<p class="f6 f6-ns moon-gray lh-copy mw5 mb4">
Type the address and directly jump to that verse
</p>
</div>
<div class="fl w-30-l pa2">
<p class="f6 f6-m f6-l fw7 white mb2">
Dramatic Audio 🔊
</p>
<p class="f6 f6-ns moon-gray lh-copy mw5 mb4">
Play dramatic audio from alkitabsuara.com
</p>
</div>
</div>
</div>
</div>
</article>
<article class="bg-secondary ph4 ph5-m pv4 pv5-ns opensans team">
<div class="flex flex-column h-100 items-center justify-center mt3">
<p class="f4 f4-m f4-l fw7 black mb2">
Behind Alkitab App
</p>
<p class="f6 f6-ns dark-gray lh-copy mw6 mb4 tc">
I am a ux/frontend engineer who loves to design and create things.
I really want to build this thing since the alkitabsuara.com was launched because
they don't have any app (you need to download soundcloud app). This is one of the way to use
my talent for the Kingdom of God.
</p>
</div>
</article>
<article class="bg-primary h6-l dark-gray lh-copy-ns ph4 ph5-m pv4 pv5-ns opensans">
<div class="flex h-inherit tc-l justify-center">
<div class="flex flex-column mw8-l">
<div class="flex flex-column flex-row-l">
<div class="fl w-40-l pa2">
<a href="https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=1295808140&mt=8">
<img src="https://i.imgur.com/iEtbVXz.png" alt="ios" />
</a>
</div>
<div class="fl w-40-l pa2">
<a href="https://play.google.com/store/apps/details?id=com.sonnylab.alkitabapp">
<img src="https://i.imgur.com/EJBcqCg.png" alt="android" />
</a>
</div>
<div class="fl w-40-l pa2">
<a href="https://github.com/sonnylazuardi/alkitab-app">
<img src="https://i.imgur.com/uQyr7D4.png" alt="github" />
</a>
</div>
</div>
</div>
</div>
</article>
<footer class="pv4 ph4 ph5-m ph6-l bg-blue opensans">
<div class="flex flex-column h-100 items-center justify-center">
<p class="f6 f6-ns white lh-copy mw6 tc">
© 2017 by <a class="light-gray" href="https://github.com/sonnylazuardi">@sonnylazuardi</a> in Singapore with ❤️
</p>
</div>
</footer>
</div>
</main>
<!-- Place this tag in your head or just before your close body tag. -->
<script async defer src="https://buttons.github.io/buttons.js"></script>
</body>
</html>
| {
"content_hash": "7485183c4d84dc33901a409142abffb7",
"timestamp": "",
"source": "github",
"line_count": 213,
"max_line_length": 223,
"avg_line_length": 41.497652582159624,
"alnum_prop": 0.5308292793302409,
"repo_name": "sonnylazuardi/alkitab-app",
"id": "34db4aa3ed2110160ddbd4cb272fb47e4c96dfe3",
"size": "8857",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "old/website/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "8857"
},
{
"name": "Java",
"bytes": "1822"
},
{
"name": "JavaScript",
"bytes": "56474"
},
{
"name": "Objective-C",
"bytes": "5164"
},
{
"name": "Python",
"bytes": "1748"
}
],
"symlink_target": ""
} |
.. title:: clang-tidy - misc-throw-by-value-catch-by-reference
misc-throw-by-value-catch-by-reference
======================================
`cert-err09-cpp` redirects here as an alias for this check.
`cert-err61-cpp` redirects here as an alias for this check.
Finds violations of the rule "Throw by value, catch by reference" presented for
example in "C++ Coding Standards" by H. Sutter and A. Alexandrescu, as well as
the CERT C++ Coding Standard rule `ERR61-CPP. Catch exceptions by lvalue reference
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/ERR61-CPP.+Catch+exceptions+by+lvalue+reference>`_.
Exceptions:
* Throwing string literals will not be flagged despite being a pointer. They
are not susceptible to slicing and the usage of string literals is idomatic.
* Catching character pointers (``char``, ``wchar_t``, unicode character types)
will not be flagged to allow catching sting literals.
* Moved named values will not be flagged as not throwing an anonymous
temporary. In this case we can be sure that the user knows that the object
can't be accessed outside catch blocks handling the error.
* Throwing function parameters will not be flagged as not throwing an
anonymous temporary. This allows helper functions for throwing.
* Re-throwing caught exception variables will not be flragged as not throwing
an anonymous temporary. Although this can usually be done by just writing
``throw;`` it happens often enough in real code.
Options
-------
.. option:: CheckThrowTemporaries
Triggers detection of violations of the CERT recommendation ERR09-CPP. Throw
anonymous temporaries.
Default is `1`.
.. option:: WarnOnLargeObject
Also warns for any large, trivial object caught by value. Catching a large
object by value is not dangerous but affects the performance negatively. The
maximum size of an object allowed to be caught without warning can be set
using the `MaxSize` option.
Default is `0`.
.. option:: MaxSize
Determines the maximum size of an object allowed to be caught without
warning. Only applicable if `WarnOnLargeObject` is set to `1`. If option is
set by the user to `std::numeric_limits<uint64_t>::max()` then it reverts to
the default value.
Default is the size of `size_t`.
| {
"content_hash": "57f4429b1963854944a9129abf728a4d",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 106,
"avg_line_length": 44.19230769230769,
"alnum_prop": 0.7397737162750218,
"repo_name": "endlessm/chromium-browser",
"id": "cc970fe014cc1c3913f627a874fe850ea9211171",
"size": "2298",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "third_party/llvm/clang-tools-extra/docs/clang-tidy/checks/misc-throw-by-value-catch-by-reference.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?php
namespace Unsplash\Tests;
use \Unsplash as Unsplash;
use \VCR\VCR;
/**
* Class StatTest
* @package Unsplash\Tests
*/
class StatTest extends BaseTest
{
/**
* @var array
*/
protected $total = [];
public function setUp(): void
{
parent::setUp();
$connection = new Unsplash\Connection($this->provider, $this->accessToken);
Unsplash\HttpClient::$connection = $connection;
$this->total = [
"photo_downloads" => 0
];
}
public function testFindTotalStats()
{
VCR::insertCassette('stats.json');
$totalStats = Unsplash\Stat::total();
VCR::eject();
$this->assertEquals($this->total['photo_downloads'], $totalStats->photo_downloads);
}
}
| {
"content_hash": "99ada3dff8f8daacef6c58cc9e96b2ea",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 91,
"avg_line_length": 18.804878048780488,
"alnum_prop": 0.5810635538261998,
"repo_name": "CrewLabs/Unsplash-PHP",
"id": "fb643cf47366f1e38ae0566e6771c81107b5057f",
"size": "771",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/StatTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "73960"
},
{
"name": "Shell",
"bytes": "56"
}
],
"symlink_target": ""
} |
namespace coap {
class PDU {
public:
// Construct a confirmable empty message by default
PDU()
: max_message_size_(1152)
, version_(Version::v1)
, type_(Type::CON)
, token_length_(0)
, code_(Code::Empty)
, message_id_(0)
, token_()
, options_()
, payload_()
{ }
// Construct from binary
explicit PDU(const std::vector<uint8_t>& bin)
: raw_(bin)
{ }
~PDU() { }
// Header fields getter's
Version version() const { return version_; }
Type type() const { return type_; }
Code code() const { return code_; }
uint8_t token_length() const { return token_.size(); }
uint16_t message_id() const { return message_id_; }
Options options() const { return options_; }
std::vector<uint8_t> token() const { return token_; }
std::vector<uint8_t> payload() const { return payload_; }
// Header fields setter's
void set_version(Version v) { version_ = v; }
void set_type(Type v) { type_ = v; }
void set_message_id(uint16_t v) { message_id_ = v; }
void set_code(Code v) { code_ = v; }
void set_token(const std::vector<uint8_t>& token) {
// Copy at most 8 bytes.
std::copy_n(token.begin(),
std::min(8UL, token.size()),
std::back_inserter(token_));
}
void set_options(const Options& opts) { options_ = opts; }
void set_payload(const std::vector<uint8_t>& payload) { payload_ = payload; }
bool Encode(std::vector<uint8_t>& buf) const;
bool Decode(const std::vector<uint8_t>& buf);
// Serialise header to the end of the given unsigned char buffer
// (Also add Token which is not strictly header.)
bool EncodeHeader(std::vector<uint8_t>& buf) const;
// Parse header from the given unsigned char vector source starting
// from offset. On success the offset indicator is updated to point
// one past the last decoded byte.
bool DecodeHeader(const std::vector<uint8_t>& buf, size_t& offset);
friend std::ostream& operator<< (std::ostream&, const PDU&);
private:
bool PayloadFits(size_t heading_size, size_t payload_size) const;
private:
std::vector<uint8_t> raw_; // XXX(tho) needed?
size_t max_message_size_;
// Fixed Header fields
Version version_;
Type type_;
uint8_t token_length_;
Code code_;
uint16_t message_id_;
std::vector<uint8_t> token_;
Options options_;
std::vector<uint8_t> payload_;
};
} // namespace coap
#endif // COAP_PDU_H_
| {
"content_hash": "8abc6180684844d0fd5fec775d1e226d",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 79,
"avg_line_length": 28.535714285714285,
"alnum_prop": 0.6403838130997079,
"repo_name": "aaaarg/wt2",
"id": "944e14f2ec06243ac4afe5bfd7c97bfcc124d119",
"size": "2688",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/coap/pdu.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "44917"
},
{
"name": "Objective-C",
"bytes": "2321"
}
],
"symlink_target": ""
} |
/* ____ ___ *\
** / __ | ___ ____ /__/___ A library of building blocks **
** / __ / __ |/ ___|/ / ___| **
** / /_/ / /_/ /\__ \/ /\__ \ (c) 2012-2013 Reify It **
** |_____/\_____\____/__/\____/ http://basis.reify.it **
\* */
package basis.dispatch
package process
import basis.containers._
import basis.control._
/** A latch that relays its result in the context of some trace.
*
* @author Chris Sachs
* @version 0.1
* @since 0.1
*
* @groupprio Evaluating 1
* @groupprio Relaying 2
* @groupprio Composing 3
* @groupprio Recovering 4
*/
class React[A](protected val trace: Trace) extends Latch[A] with Relay[A] {
import MetaReact._
@volatile private[process] final var state: AnyRef = Batch.empty[Latch[A]]
final override def isSet: Boolean = state.isInstanceOf[_ Else _]
final override def set(result: Try[A]): Boolean = {
if (result == null) throw new NullPointerException
var s = null: AnyRef
do s = state
while (!s.isInstanceOf[_ Else _] && !Unsafe.compareAndSwapObject(this, StateOffset, s, result))
!s.isInstanceOf[_ Else _] && { s.asInstanceOf[Batch[Latch[A]]] traverse new Thunk.Signal(result); true }
}
override def forward[B >: A](that: Latch[B]): Unit = defer(that)
override def run[U](f: Try[A] => U): Unit = defer(new Thunk.Run(f)(trace))
override def foreach[U](f: A => U): Unit = defer(new Thunk.Foreach(f)(trace))
override def andThen[U](q: PartialFunction[Try[A], U]): Relay[A] = {
val r = new React[A](trace)
defer(new Thunk.AndThen(q, r)(trace))
r
}
override def choose[B](q: PartialFunction[A, B]): Relay[B] = {
val r = new React[B](trace)
defer(new Thunk.Choose(q, r)(trace))
r
}
override def map[B](f: A => B): Relay[B] = {
val r = new React[B](trace)
defer(new Thunk.Map(f, r)(trace))
r
}
override def flatMap[B](f: A => Relay[B]): Relay[B] = {
val r = new React[B](trace)
defer(new Thunk.FlatMap(f, r)(trace))
r
}
override def recover[B >: A](q: PartialFunction[Throwable, B]): Relay[B] = {
val r = new React[B](trace)
defer(new Thunk.Recover(q, r)(trace))
r
}
override def recoverWith[B >: A](q: PartialFunction[Throwable, Relay[B]]): Relay[B] = {
val r = new React[B](trace)
defer(new Thunk.RecoverWith(q, r)(trace))
r
}
override def filter(p: A => Boolean): Relay[A] = {
val r = new React[A](trace)
defer(new Thunk.Filter(p, r)(trace))
r
}
override def withFilter(p: A => Boolean): Relay[A] = {
val r = new React[A](trace)
defer(new Thunk.Filter(p, r)(trace))
r
}
override def zip[B](that: Relay[B]): Relay[(A, B)] = {
val r = new React.Zip[A, B](trace)
this forward new r.Set1
that forward new r.Set2
r
}
private[process] final def defer(latch: Latch[A]) {
if (latch == null) throw new NullPointerException
var s = null: AnyRef
do s = state
while (!s.isInstanceOf[_ Else _] &&
!Unsafe.compareAndSwapObject(this, StateOffset, state, state.asInstanceOf[Batch[Latch[A]]] :+ latch))
if (s.isInstanceOf[_ Else _]) latch set s.asInstanceOf[Try[A]]
}
}
private[basis] object React {
private[basis] final class Zip[A, B](override val trace: Trace) extends React[(A, B)](trace) {
@volatile private[process] final var _1: Try[A] = _
@volatile private[process] final var _2: Try[B] = _
def set1(result1: Try[A]) {
if (result1 == null) throw new NullPointerException
if (_1 == null) {
_1 = result1
if (result1.canTrap) set(result1.asInstanceOf[Nothing Else Throwable])
else {
val result2 = _2
if (result2 != null && result2.canBind)
set(Bind((result1.bind, result2.bind))) // safely races with set2
}
}
}
def set2(result2: Try[B]) {
if (result2 == null) throw new NullPointerException
if (_2 == null) {
_2 = result2
if (result2.canTrap) set(result2.asInstanceOf[Nothing Else Throwable])
else {
val result1 = _1
if (result1 != null && result1.canBind)
set(Bind((result1.bind, result2.bind))) // safely races with set1
}
}
}
final class Set1 extends Thunk[A](trace) {
override def apply(result: Try[A]): Unit = set1(result)
}
final class Set2 extends Thunk[B](trace) {
override def apply(result: Try[B]): Unit = set2(result)
}
}
}
| {
"content_hash": "49f2fccb1a6125a7a526df31c98b2e11",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 112,
"avg_line_length": 31.28476821192053,
"alnum_prop": 0.5550381033022862,
"repo_name": "ReifyIt/ortho-basis",
"id": "e63875501b5abc621c102731ef32a249ffdcf644",
"size": "4724",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "basis-dispatch/src/main/scala/basis/dispatch/process/React.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "46897"
},
{
"name": "C++",
"bytes": "772"
},
{
"name": "Java",
"bytes": "6788"
},
{
"name": "Scala",
"bytes": "96262"
}
],
"symlink_target": ""
} |
typedef int pid_t;
typedef unsigned int mode_t;
typedef unsigned int uid_t;
typedef unsigned int gid_t;
typedef unsigned long dev_t;
typedef unsigned long ino_t;
typedef unsigned long nlink_t;
typedef long blksize_t;
typedef long blkcnt_t;
typedef long ssize_t;
typedef long off_t; // @TODO: Is this where this is meant to be defined?
#endif
| {
"content_hash": "865806dcd3d113b89e4515dba32a32c8",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 72,
"avg_line_length": 24.571428571428573,
"alnum_prop": 0.7645348837209303,
"repo_name": "orodley/naive",
"id": "7c972f1e7964bb116d818368b6f8a67f1c6b680e",
"size": "404",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libc/include/sys/types.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "866"
},
{
"name": "C",
"bytes": "455710"
},
{
"name": "C++",
"bytes": "11868"
},
{
"name": "Makefile",
"bytes": "3703"
},
{
"name": "Python",
"bytes": "28167"
},
{
"name": "Shell",
"bytes": "2110"
}
],
"symlink_target": ""
} |
package com.thoughtworks.go.util;
import org.junit.Before;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.is;
public class DynamicReadWriteLockTest {
private DynamicReadWriteLock readWriteLock;
private volatile int numberOfLocks;
@Before public void setUp() {
readWriteLock = new DynamicReadWriteLock();
numberOfLocks = 0;
}
@After public void tearDown() {
}
@Test public void shouldEnforceMutualExclutionOfWriteLockForGivenName() throws InterruptedException {
readWriteLock.acquireWriteLock("foo");
new Thread(new Runnable() {
@Override
public void run() {
readWriteLock.acquireWriteLock("foo");
numberOfLocks++;
}
}).start();
Thread.sleep(1000);
assertThat(numberOfLocks, is(0));
}
@Test public void shouldNotEnforceMutualExclutionOfReadLockForGivenName() throws InterruptedException {
readWriteLock.acquireReadLock("foo");
new Thread(new Runnable() {
@Override
public void run() {
readWriteLock.acquireReadLock("foo");
numberOfLocks++;
}
}).start();
Thread.sleep(1000);
assertThat(numberOfLocks, is(1));
}
@Test public void shouldEnforceMutualExclutionOfReadAndWriteLockForGivenName() throws InterruptedException {
readWriteLock.acquireReadLock("foo");
new Thread(new Runnable() {
@Override
public void run() {
readWriteLock.acquireWriteLock("foo");
numberOfLocks++;
}
}).start();
Thread.sleep(1000);
assertThat(numberOfLocks, is(0));
}
@Test public void shouldEnforceMutualExclutionOfWriteAndReadLockForGivenName() throws InterruptedException {
readWriteLock.acquireWriteLock("foo");
new Thread(new Runnable() {
@Override
public void run() {
readWriteLock.acquireReadLock("foo");
numberOfLocks++;
}
}).start();
Thread.sleep(1000);
assertThat(numberOfLocks, is(0));
}
@Test public void shouldNotEnforceMutualExclutionOfWriteLockForDifferentNames() throws InterruptedException {
readWriteLock.acquireWriteLock("foo");
new Thread(new Runnable() {
@Override
public void run() {
readWriteLock.acquireWriteLock("bar");
numberOfLocks++;
}
}).start();
Thread.sleep(1000);
assertThat(numberOfLocks, is(1));
}
}
| {
"content_hash": "be798cd79d72b80011c6587bd501b47e",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 113,
"avg_line_length": 26.524271844660195,
"alnum_prop": 0.6035871156661786,
"repo_name": "arvindsv/gocd",
"id": "34862b2753545c8b4b81b81914f390a5cc04e771",
"size": "3333",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "util/src/test/java/com/thoughtworks/go/util/DynamicReadWriteLockTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "466"
},
{
"name": "CSS",
"bytes": "797200"
},
{
"name": "FreeMarker",
"bytes": "9764"
},
{
"name": "Groovy",
"bytes": "2240189"
},
{
"name": "HTML",
"bytes": "640932"
},
{
"name": "Java",
"bytes": "21023083"
},
{
"name": "JavaScript",
"bytes": "2539209"
},
{
"name": "NSIS",
"bytes": "23526"
},
{
"name": "PowerShell",
"bytes": "691"
},
{
"name": "Ruby",
"bytes": "1888167"
},
{
"name": "Shell",
"bytes": "169149"
},
{
"name": "TSQL",
"bytes": "200114"
},
{
"name": "TypeScript",
"bytes": "3070898"
},
{
"name": "XSLT",
"bytes": "203240"
}
],
"symlink_target": ""
} |
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Files - @typo3/icons</title>
<meta name="description" content="SVG icons for the TYPO3 CMS backend">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<style type="text/css">
.btn img {
display: block;
}
.btn-sm {
padding: 4px 12px;
line-height: 16px;
border-radius: 2px;
}
.btn-icon {
padding: 4px 4px;
border-radius: 2px;
font-size: 11px;
line-height: 1.5;
}
.btn-default {
color: #333333;
background-color: #eeeeee;
border-color: #bbbbbb;
}
.btn-default .icon-color {
fill: #333333;
}
.btn-grid {
margin: 2px;
float: left;
}
.table td {
vertical-align: middle;
white-space: nowrap;
}
.icon {
position: relative;
display: inline-block;
overflow: hidden;
white-space: nowrap;
vertical-align: -22%;
}
.icon img,
.icon svg {
display: block;
height: 100%;
width: 100%;
transform: translate3d(0,0,0);
}
.icon * {
display: block;
line-height: inherit;
}
.icon-markup {
position: absolute;
display: block;
text-align: center;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.icon-color {
fill: currentColor;
}
.icon-overlay {
position: absolute;
bottom: 0;
right: 0;
height: 68.75%;
width: 68.75%;
text-align: center;
}
.icon-spin .icon-markup {
-webkit-animation: icon-spin 2s infinite linear;
animation: icon-spin 2s infinite linear;
}
@-webkit-keyframes icon-spin {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@keyframes icon-spin {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
.icon-state-disabled .icon-markup {
opacity: 0.5;
}
.icon-size-small {
height: 16px;
width: 16px;
line-height: 16px;
}
.icon-size-small .icon-unify {
line-height: 16px;
font-size: 14px;
}
.icon-size-small .icon-overlay .icon-unify {
line-height: 10px;
font-size: 9px;
}
.icon-size-default {
height: 32px;
width: 32px;
line-height: 32px;
}
.icon-size-default .icon-unify {
line-height: 32px;
font-size: 28px;
}
.icon-size-default .icon-overlay .icon-unify {
line-height: 20px;
font-size: 18px;
}
.icon-size-large {
height: 48px;
width: 48px;
line-height: 48px;
}
.icon-size-large .icon-unify {
line-height: 48px;
font-size: 42px;
}
.icon-size-large .icon-overlay .icon-unify {
line-height: 30px;
font-size: 26px;
}
.icon-size-mega {
height: 64px;
width: 64px;
line-height: 64px;
}
.card {
overflow: hidden;
}
.card-deck {
margin-top: -15px;
margin-bottom: -15px;
}
.card-deck .card {
margin: 15px;
min-width: 250px;
}
.card-inverse .icon-color {
fill: #dddddd;
}
.card-group-element {
margin: -10px;
display: flex;
flex-wrap: wrap
}
.card-group-element-item {
width: 100%;
padding: 10px
}
.card-group-element-item .card {
height: 100%
}
.card-group-element-align-left {
justify-content: flex-start
}
.card-group-element-align-center {
justify-content: center
}
.card-group-element-align-right {
justify-content: flex-end
}
@media (min-width: 576px) {
.card-group-element-columns-2 .card-group-element-item {
width:calc(100% / 2)
}
}
@media (min-width: 768px) {
.card-group-element-columns-3 .card-group-element-item {
width:calc(100% / 3)
}
}
@media (min-width: 576px) {
.card-group-element-columns-4 .card-group-element-item {
width:calc(100% / 2)
}
}
@media (min-width: 1200px) {
.card-group-element-columns-4 .card-group-element-item {
width:calc(100% / 4)
}
}
</style>
</head>
<body>
<nav class="navbar sticky-top navbar-dark bg-dark navbar-expand-md">
<div class="container">
<a class="navbar-brand" href="index.html">@typo3/icons</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#mainnav" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="mainnav">
<ul class="navbar-nav ml-auto">
<li class="nav-item"><a class="nav-link" href="action.html">Action</a></li>
<li class="nav-item"><a class="nav-link" href="apps.html">Apps</a></li>
<li class="nav-item"><a class="nav-link" href="content.html">Content</a></li>
<li class="nav-item"><a class="nav-link" href="files.html">Files</a></li>
<li class="nav-item"><a class="nav-link" href="form.html">Form</a></li>
<li class="nav-item"><a class="nav-link" href="install.html">Install</a></li>
<li class="nav-item"><a class="nav-link" href="mimetypes.html">Mimetypes</a></li>
<li class="nav-item"><a class="nav-link" href="module.html">Module</a></li>
<li class="nav-item"><a class="nav-link" href="overlay.html">Overlay</a></li>
<li class="nav-item"><a class="nav-link" href="misc.html">Misc</a></li>
</ul>
</div>
</div>
</nav>
<div class="container py-5">
<h3 class="mb-3">
Files
<small class="text-muted">3</small>
</h3>
<div class="card-group-element card-group-element-columns-4">
<div class="card-group-element-item">
<div class="card">
<div class="card-header">files-folder-content</div>
<div class="card-body text-center">
<span class="icon icon-size-mega icon-state-default" title="files-folder-content">
<span class="icon-markup">
<img src="images/files/files-folder-content.svg" height="64" width="64">
</span>
</span>
</div>
</div>
</div>
<div class="card-group-element-item">
<div class="card">
<div class="card-header">files-folder-images</div>
<div class="card-body text-center">
<span class="icon icon-size-mega icon-state-default" title="files-folder-images">
<span class="icon-markup">
<img src="images/files/files-folder-images.svg" height="64" width="64">
</span>
</span>
</div>
</div>
</div>
<div class="card-group-element-item">
<div class="card">
<div class="card-header">files-folder</div>
<div class="card-body text-center">
<span class="icon icon-size-mega icon-state-default" title="files-folder">
<span class="icon-markup">
<img src="images/files/files-folder.svg" height="64" width="64">
</span>
</span>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
| {
"content_hash": "2b53afeed190b7dcf662826754dbbd35",
"timestamp": "",
"source": "github",
"line_count": 292,
"max_line_length": 219,
"avg_line_length": 37.907534246575345,
"alnum_prop": 0.4396964495437709,
"repo_name": "wmdbsystems/T3.Icons",
"id": "949779da762f33f5f09be403a94353ebf9a8c169",
"size": "11069",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/files.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "18926"
},
{
"name": "JavaScript",
"bytes": "3187"
}
],
"symlink_target": ""
} |
<?php
namespace Athena\Event\Subscriber\Builder;
use Athena\Event\Subscriber\UnitSubscriber;
use Athena\Logger\Interpreter\HtmlInterpreter;
use Athena\Stream\FileOutputStream;
class UnitSubscriberBuilder extends AbstractSubscriberBuilder
{
/**
* @return \Athena\Event\Subscriber\UnitSubscriber
*/
public function build()
{
$interpreter = new HtmlInterpreter('unit_report.twig');
$outputStream = new FileOutputStream($this->outputPathName."/report.html");
return new UnitSubscriber($interpreter, $outputStream);
}
}
| {
"content_hash": "749b40c7463c5807191a64bdf14f9b60",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 83,
"avg_line_length": 27.142857142857142,
"alnum_prop": 0.7298245614035088,
"repo_name": "athena-oss/plugin-php",
"id": "8af2d8876fb8a93985ba3b9bd8a41ceb3ce88a95",
"size": "570",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Event/Subscriber/Builder/UnitSubscriberBuilder.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Gherkin",
"bytes": "440"
},
{
"name": "HTML",
"bytes": "37994"
},
{
"name": "PHP",
"bytes": "232710"
},
{
"name": "Shell",
"bytes": "42132"
}
],
"symlink_target": ""
} |
import {Router} from '@angular/router';
import {ExistsGuardService} from './exists-guard';
import {fakeAsync, inject, TestBed, tick} from '@angular/core/testing';
import {Observable} from 'rxjs/Observable';
describe('Test Exists Guard Service', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
ExistsGuardService,
{
provide: Router,
useValue: jasmine.createSpyObj('router', ['navigate'])
},
{
provide: 'cacheExpiry',
useValue: 5000
}
]
});
});
it('should return false when not within expiry', fakeAsync(() => {
inject([ExistsGuardService], (existsGuardService: ExistsGuardService) => {
let result = true;
existsGuardService.isWithinExpiry(Observable.of(Date.now() - 6000)).subscribe(isExpired => result = isExpired);
tick();
expect(result).toBeFalsy();
})();
}));
it('should return true when within expiry', fakeAsync(() => {
inject([ExistsGuardService], (existsGuardService: ExistsGuardService) => {
let result = false;
existsGuardService.isWithinExpiry(Observable.of(Date.now() - 1000)).subscribe(isExpired => result = isExpired);
tick();
expect(result).toBeTruthy();
})();
}));
it('should route to /404 on exception and return false', fakeAsync(() => {
inject([ExistsGuardService, Router], (existsGuardService: ExistsGuardService, router: Router) => {
let result = true;
existsGuardService.routeTo404OnError(Observable.throw({})).subscribe(canActivate => result = canActivate);
tick();
expect(router.navigate).toHaveBeenCalledWith(['/404']);
expect(result).toBeFalsy();
})();
}));
});
| {
"content_hash": "37cf327a1c71d481a2e19b830f5313d1",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 117,
"avg_line_length": 26.134328358208954,
"alnum_prop": 0.6270702455739577,
"repo_name": "mifosio/fims-web-app",
"id": "4e65e0d28204f79cabc72bb136feb2731d56075a",
"size": "2352",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/app/common/guards/exists-guard.spec.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "9175"
},
{
"name": "HTML",
"bytes": "392320"
},
{
"name": "JavaScript",
"bytes": "3031"
},
{
"name": "TypeScript",
"bytes": "1875420"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
World Register of Marine Species
#### Published in
Arch. Protistenk. , 3, 367.
#### Original name
null
### Remarks
null | {
"content_hash": "ac4bfc754d6b7ff882cffc3bc3f7c1ff",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 32,
"avg_line_length": 11.538461538461538,
"alnum_prop": 0.6866666666666666,
"repo_name": "mdoering/backbone",
"id": "9dec3e29e423ce4fc36d4370b93ad6b1084b7919",
"size": "194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Protozoa/Euglenozoa/Trypanophis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
</head>
<body>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<div class="container">
<h1>jQuery plugin - textarea character counting</h1>
<h2>Features:</h2>
<ul>
<li>character counting for HTML textarea</li>
<li>Cross-browser compatible (Chrome, Opera, Safari, Firefox 3.6+, IE6+).</li>
<li>compatible with both jQuery 1 & 2</li>
<li>Designed with progressive enhancement in mind.</li>
<li>Optional "Strict mode" to trim off text over the limit</li>
</ul>
<p><strong>Normal mode</strong>, character count text will turn to red when character limit is reached.</p>
<div class="code-container">
<pre class="align-left"><code class="js">
$('textarea#textarea1').character_limit({
max_char: 100
});</code></pre>
</div>
<textarea
id="textarea1"
name="textarea1"
cols="40"
rows="5"
></textarea>
<p><strong>Strict mode</strong>, plugin will start to trim off additional text once the character count limit is reached.</p>
<div class="code-container">
<pre class="align-left"><code class="js">
$('textarea#textarea2').character_limit({
max_char: 100,
strict_mode: true
});</code></pre>
</div>
<textarea
id="textarea2"
name="textarea2"
cols="40"
rows="5"
></textarea>
<p>This jQuery plugin is developed and maintained by <a target="_blank" href="http://shawneey.github.io/Resume/">Xiao Yu (click to view my resume)</a>, a web developer / designer currently living in Melbourne, Australia.</p>
<p>For more details and documentation, please checkout the <a target="_blank" href="https://github.com/ShawneeY/jQuery-plugin---textarea-character-counting">github repo</a> for this project</p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js"></script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<script src="js/textarea_character_limit.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X');ga('send','pageview');
</script>
<script type="text/javascript">
//<![CDATA[
$(function() {
hljs.initHighlightingOnLoad();
$('textarea#textarea1').character_limit({
max_char: 100
});
$('textarea#textarea2').character_limit({
max_char: 100,
strict_mode: true
});
});
//]]>
</script>
</body>
</html>
| {
"content_hash": "ed1f61a6e5390dcd78b35b6f7700e314",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 232,
"avg_line_length": 40.68421052631579,
"alnum_prop": 0.5521776627856835,
"repo_name": "ShawneeY/jQuery-plugin---textarea-character-counting",
"id": "d35bc281bf6a0588687e90c2edd5f24fc0990964",
"size": "4638",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "24603"
},
{
"name": "CSS",
"bytes": "5937"
},
{
"name": "HTML",
"bytes": "8384"
},
{
"name": "JavaScript",
"bytes": "5007"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from datetime import timedelta
from optparse import make_option
from time import timezone
try:
from urllib.request import urlopen
from urllib.parse import urljoin
except ImportError:
from urllib import urlopen
from urlparse import urljoin
from django.core.management.base import CommandError
from mezzanine.blog.management.base import BaseImporterCommand
class Command(BaseImporterCommand):
"""
Import an RSS feed into the blog app.
"""
option_list = BaseImporterCommand.option_list + (
make_option("-r", "--rss-url", dest="rss_url",
help="RSS feed URL"),
make_option("-p", "--page-url", dest="page_url",
help="URL for a web page containing the RSS link"),
)
help = ("Import an RSS feed into the blog app. Requires the "
"dateutil and feedparser packages installed, and also "
"BeautifulSoup if using the --page-url option.")
def handle_import(self, options):
rss_url = options.get("rss_url")
page_url = options.get("page_url")
if not (page_url or rss_url):
raise CommandError("Either --rss-url or --page-url option "
"must be specified")
try:
from dateutil import parser
except ImportError:
raise CommandError("dateutil package is required")
try:
from feedparser import parse
except ImportError:
raise CommandError("feedparser package is required")
if not rss_url and page_url:
try:
from BeautifulSoup import BeautifulSoup
except ImportError:
raise CommandError("BeautifulSoup package is required")
for l in BeautifulSoup(urlopen(page_url).read()).findAll("link"):
if ("application/rss" in l.get("type", "") or
"application/atom" in l.get("type", "")):
rss_url = urljoin(page_url, l["href"])
break
else:
raise CommandError("Could not parse RSS link from the page")
posts = parse(rss_url)["entries"]
for post in posts:
if hasattr(post, 'content'):
content = post.content[0]["value"]
else:
content = post.summary
tags = [tag["term"] for tag in getattr(post, 'tags', [])]
pub_date = parser.parse(post.updated)
pub_date -= timedelta(seconds=timezone)
self.add_post(title=post.title, content=content,
pub_date=pub_date, tags=tags, old_url=None)
| {
"content_hash": "ec6929ef44c1d63bda6017041aa53a4e",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 77,
"avg_line_length": 37.166666666666664,
"alnum_prop": 0.5863228699551569,
"repo_name": "Kniyl/mezzanine",
"id": "0db6925641ee9d492f9402341722862ce9c6acc1",
"size": "2676",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "mezzanine/blog/management/commands/import_rss.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "345"
},
{
"name": "CSS",
"bytes": "104823"
},
{
"name": "HTML",
"bytes": "88734"
},
{
"name": "JavaScript",
"bytes": "250115"
},
{
"name": "Nginx",
"bytes": "2261"
},
{
"name": "Python",
"bytes": "1173765"
}
],
"symlink_target": ""
} |
'''
http://cosec.blogspot.com/2013_06_01_archive.html
Use this extension when you want to test 1 specific request and identify which cookies are important. The best way to do this is to identify a request that is
definitely for a private URL. Usually, cookies are valid across all the requests of the application, unless something is very horribly done so testing a few requests
should be good enough in most cases.
'''
from burp import IBurpExtender
from burp import IContextMenuFactory
from javax.swing import JMenuItem
import sys
import os
import re
#Adding directory to the path where Python searches for modules
module_folder = os.path.dirname('/home/arvind/Documents/Me/My_Projects/Git/WebAppsec/BurpExtensions/modules/')
sys.path.insert(0, module_folder)
import webcommon
class BurpExtender(IBurpExtender, IContextMenuFactory):
def registerExtenderCallbacks(self,callbacks):
self._callbacks= callbacks
self._helpers = callbacks.getHelpers()
callbacks.setExtensionName("Cookie Validator")
callbacks.registerContextMenuFactory(self)
def createMenuItems(self, invocation):
menu= []
#Need to ask someone how the f*** lambda actually works in code. I get it in theory.
menu.append(JMenuItem("Useful cookies", None, actionPerformed= lambda x,inv=invocation:self.initFunc(inv)))
return menu
def initFunc(self, invocation):
invMessage=invocation.getSelectedMessages()
bytes_req= invMessage[0].getRequest()
request= bytes_req.tostring()
response= invMessage[0].getResponse().tostring()
origlen= len(response)
requestArray= request.split('\n')
count, cookies= self.getCookies(requestArray, response)
cookies_that_matter= self.makeRequestsWithoutCookies(count, origlen, invMessage, requestArray, cookies)
if len(cookies_that_matter) > 0:
print 'Here is a list of cookies that might matter. The rest are most probably a waste of time you should spend no time analyzing in detail.'
print cookies_that_matter
else:
print 'No cookies matter. Test for Direct Request :)'
def makeRequestsWithoutCookies(self, count, origlen, invMessage, requestArray, cookies):
p1= '\n'.join(requestArray[0:count-1])
p2= '\n'.join(requestArray[count+1:])
cookieheader= 'Cookies: '
cookies_that_matter= []
orig_cookies= cookies.split(';')
for num,cookie in enumerate(orig_cookies):
r1= ''
r1= p1+'\n'+cookieheader
c1= orig_cookies
del(c1[num])
c2= ';'.join(c1)
r1 += c2
r1 += '\n'
r1 += p2
r1 += '\n'
new_bytesreq= self._helpers.stringToBytes(r1)
newresp= self._callbacks.makeHttpRequest(invMessage[0].getHttpService(), new_bytesreq)
r1= newresp.getResponse().tostring()
if origlen != len(r1):
cookies_that_matter.append(orig_cookies[num])
else:
continue
return cookies_that_matter
def getCookies(self, requestArray, response):
pattern= 'Cookie:\s*'
regex=re.compile(r'%s(.*)'%pattern, re.DOTALL|re.MULTILINE)
for count,r1 in enumerate(requestArray):
m1= regex.match(r1)
if m1 is not None:
cookies= m1.group(1)
break
else:
continue
cookies += ';'
return count, cookies
| {
"content_hash": "44378f6af5ae46617dc4a63a20502bc6",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 165,
"avg_line_length": 38.44565217391305,
"alnum_prop": 0.6465931580435397,
"repo_name": "arvinddoraiswamy/mywebappscripts",
"id": "18b930137aa3ed956bbbb9c8cfab909f58e39c4b",
"size": "3537",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BurpExtensions/CookieValidator.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1106"
},
{
"name": "Java",
"bytes": "290"
},
{
"name": "Python",
"bytes": "69122"
}
],
"symlink_target": ""
} |
<?php
namespace PHP_CodeSniffer\Standards\Generic\Tests\PHP;
use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest;
class LowerCaseKeywordUnitTest extends AbstractSniffUnitTest
{
/**
* Returns the lines where errors should occur.
*
* The key of the array should represent the line number and the value
* should represent the number of errors that should occur on that line.
*
* @return array<int, int>
*/
public function getErrorList()
{
return array(
10 => 3,
11 => 4,
12 => 1,
13 => 3,
14 => 7,
15 => 1,
16 => 1,
);
}//end getErrorList()
/**
* Returns the lines where warnings should occur.
*
* The key of the array should represent the line number and the value
* should represent the number of warnings that should occur on that line.
*
* @return array<int, int>
*/
public function getWarningList()
{
return array();
}//end getWarningList()
}//end class
| {
"content_hash": "24dd342b2e2e5294611f8fba3ff05ac8",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 78,
"avg_line_length": 22.38,
"alnum_prop": 0.5647899910634495,
"repo_name": "LCabreroG/opensource",
"id": "d944d489e49acbaf09fe00667f34e4611b7a411b",
"size": "1384",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseKeywordUnitTest.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "727"
},
{
"name": "Batchfile",
"bytes": "835"
},
{
"name": "CSS",
"bytes": "355396"
},
{
"name": "JavaScript",
"bytes": "548966"
},
{
"name": "PHP",
"bytes": "130407"
},
{
"name": "Shell",
"bytes": "3049"
}
],
"symlink_target": ""
} |
package org.apache.cassandra.utils;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.zip.Checksum;
import com.google.common.base.Joiner;
import com.google.common.collect.AbstractIterator;
import com.google.common.primitives.Longs;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.cache.IRowCacheProvider;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.io.IVersionedSerializer;
import org.apache.cassandra.io.util.DataOutputBuffer;
import org.apache.cassandra.io.util.IAllocator;
import org.apache.cassandra.net.AsyncOneResponse;
import org.apache.thrift.TBase;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.map.ObjectMapper;
public class FBUtilities
{
private static final Logger logger = LoggerFactory.getLogger(FBUtilities.class);
private static ObjectMapper jsonMapper = new ObjectMapper(new JsonFactory());
public static final BigInteger TWO = new BigInteger("2");
private static volatile InetAddress localInetAddress;
private static volatile InetAddress broadcastInetAddress;
public static int getAvailableProcessors()
{
if (System.getProperty("cassandra.available_processors") != null)
return Integer.parseInt(System.getProperty("cassandra.available_processors"));
else
return Runtime.getRuntime().availableProcessors();
}
private static final ThreadLocal<MessageDigest> localMD5Digest = new ThreadLocal<MessageDigest>()
{
@Override
protected MessageDigest initialValue()
{
return newMessageDigest("MD5");
}
@Override
public MessageDigest get()
{
MessageDigest digest = super.get();
digest.reset();
return digest;
}
};
private static final ThreadLocal<Random> localRandom = new ThreadLocal<Random>()
{
@Override
protected Random initialValue()
{
return new Random();
}
};
public static final int MAX_UNSIGNED_SHORT = 0xFFFF;
public static MessageDigest threadLocalMD5Digest()
{
return localMD5Digest.get();
}
public static MessageDigest newMessageDigest(String algorithm)
{
try
{
return MessageDigest.getInstance(algorithm);
}
catch (NoSuchAlgorithmException nsae)
{
throw new RuntimeException("the requested digest algorithm (" + algorithm + ") is not available", nsae);
}
}
public static Random threadLocalRandom()
{
return localRandom.get();
}
/**
* Please use getBroadcastAddress instead. You need this only when you have to listen/connect.
*/
public static InetAddress getLocalAddress()
{
if (localInetAddress == null)
try
{
localInetAddress = DatabaseDescriptor.getListenAddress() == null
? InetAddress.getLocalHost()
: DatabaseDescriptor.getListenAddress();
}
catch (UnknownHostException e)
{
throw new RuntimeException(e);
}
return localInetAddress;
}
public static InetAddress getBroadcastAddress()
{
if (broadcastInetAddress == null)
broadcastInetAddress = DatabaseDescriptor.getBroadcastAddress() == null
? getLocalAddress()
: DatabaseDescriptor.getBroadcastAddress();
return broadcastInetAddress;
}
public static Collection<InetAddress> getAllLocalAddresses()
{
Set<InetAddress> localAddresses = new HashSet<InetAddress>();
try
{
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
if (nets != null)
{
while (nets.hasMoreElements())
localAddresses.addAll(Collections.list(nets.nextElement().getInetAddresses()));
}
}
catch (SocketException e)
{
throw new AssertionError(e);
}
return localAddresses;
}
/**
* Given two bit arrays represented as BigIntegers, containing the given
* number of significant bits, calculate a midpoint.
*
* @param left The left point.
* @param right The right point.
* @param sigbits The number of bits in the points that are significant.
* @return A midpoint that will compare bitwise halfway between the params, and
* a boolean representing whether a non-zero lsbit remainder was generated.
*/
public static Pair<BigInteger,Boolean> midpoint(BigInteger left, BigInteger right, int sigbits)
{
BigInteger midpoint;
boolean remainder;
if (left.compareTo(right) < 0)
{
BigInteger sum = left.add(right);
remainder = sum.testBit(0);
midpoint = sum.shiftRight(1);
}
else
{
BigInteger max = TWO.pow(sigbits);
// wrapping case
BigInteger distance = max.add(right).subtract(left);
remainder = distance.testBit(0);
midpoint = distance.shiftRight(1).add(left).mod(max);
}
return Pair.create(midpoint, remainder);
}
public static int compareUnsigned(byte[] bytes1, byte[] bytes2, int offset1, int offset2, int len1, int len2)
{
return FastByteComparisons.compareTo(bytes1, offset1, len1, bytes2, offset2, len2);
}
/**
* @return The bitwise XOR of the inputs. The output will be the same length as the
* longer input, but if either input is null, the output will be null.
*/
public static byte[] xor(byte[] left, byte[] right)
{
if (left == null || right == null)
return null;
if (left.length > right.length)
{
byte[] swap = left;
left = right;
right = swap;
}
// left.length is now <= right.length
byte[] out = Arrays.copyOf(right, right.length);
for (int i = 0; i < left.length; i++)
{
out[i] = (byte)((left[i] & 0xFF) ^ (right[i] & 0xFF));
}
return out;
}
public static BigInteger hashToBigInteger(ByteBuffer data)
{
byte[] result = hash(data);
BigInteger hash = new BigInteger(result);
return hash.abs();
}
public static byte[] hash(ByteBuffer... data)
{
MessageDigest messageDigest = localMD5Digest.get();
for (ByteBuffer block : data)
{
if (block.hasArray())
messageDigest.update(block.array(), block.arrayOffset() + block.position(), block.remaining());
else
messageDigest.update(block.duplicate());
}
return messageDigest.digest();
}
@Deprecated
public static void serialize(TSerializer serializer, TBase struct, DataOutput out)
throws IOException
{
assert serializer != null;
assert struct != null;
assert out != null;
byte[] bytes;
try
{
bytes = serializer.serialize(struct);
}
catch (TException e)
{
throw new RuntimeException(e);
}
out.writeInt(bytes.length);
out.write(bytes);
}
@Deprecated
public static void deserialize(TDeserializer deserializer, TBase struct, DataInput in)
throws IOException
{
assert deserializer != null;
assert struct != null;
assert in != null;
byte[] bytes = new byte[in.readInt()];
in.readFully(bytes);
try
{
deserializer.deserialize(struct, bytes);
}
catch (TException ex)
{
throw new IOException(ex);
}
}
public static void sortSampledKeys(List<DecoratedKey> keys, Range<Token> range)
{
if (range.left.compareTo(range.right) >= 0)
{
// range wraps. have to be careful that we sort in the same order as the range to find the right midpoint.
final Token right = range.right;
Comparator<DecoratedKey> comparator = new Comparator<DecoratedKey>()
{
public int compare(DecoratedKey o1, DecoratedKey o2)
{
if ((right.compareTo(o1.token) < 0 && right.compareTo(o2.token) < 0)
|| (right.compareTo(o1.token) > 0 && right.compareTo(o2.token) > 0))
{
// both tokens are on the same side of the wrap point
return o1.compareTo(o2);
}
return o2.compareTo(o1);
}
};
Collections.sort(keys, comparator);
}
else
{
// unwrapped range (left < right). standard sort is all we need.
Collections.sort(keys);
}
}
public static String resourceToFile(String filename) throws ConfigurationException
{
ClassLoader loader = FBUtilities.class.getClassLoader();
URL scpurl = loader.getResource(filename);
if (scpurl == null)
throw new ConfigurationException("unable to locate " + filename);
return scpurl.getFile();
}
public static String getReleaseVersionString()
{
try
{
InputStream in = FBUtilities.class.getClassLoader().getResourceAsStream("org/apache/cassandra/config/version.properties");
if (in == null)
{
return "Unknown";
}
Properties props = new Properties();
props.load(in);
return props.getProperty("CassandraVersion");
}
catch (Exception e)
{
logger.warn("Unable to load version.properties", e);
return "debug version";
}
}
public static long timestampMicros()
{
// we use microsecond resolution for compatibility with other client libraries, even though
// we can't actually get microsecond precision.
return System.currentTimeMillis() * 1000;
}
public static void waitOnFutures(Iterable<Future<?>> futures)
{
for (Future f : futures)
waitOnFuture(f);
}
public static void waitOnFuture(Future<?> future)
{
try
{
future.get();
}
catch (ExecutionException ee)
{
throw new RuntimeException(ee);
}
catch (InterruptedException ie)
{
throw new AssertionError(ie);
}
}
public static void waitOnFutures(List<AsyncOneResponse> results, long ms) throws TimeoutException
{
for (AsyncOneResponse result : results)
result.get(ms, TimeUnit.MILLISECONDS);
}
public static IPartitioner newPartitioner(String partitionerClassName) throws ConfigurationException
{
if (!partitionerClassName.contains("."))
partitionerClassName = "org.apache.cassandra.dht." + partitionerClassName;
return FBUtilities.construct(partitionerClassName, "partitioner");
}
public static IAllocator newOffHeapAllocator(String offheap_allocator) throws ConfigurationException
{
if (!offheap_allocator.contains("."))
offheap_allocator = "org.apache.cassandra.io.util." + offheap_allocator;
return FBUtilities.construct(offheap_allocator, "off-heap allocator");
}
/**
* @return The Class for the given name.
* @param classname Fully qualified classname.
* @param readable Descriptive noun for the role the class plays.
* @throws ConfigurationException If the class cannot be found.
*/
public static <T> Class<T> classForName(String classname, String readable) throws ConfigurationException
{
try
{
return (Class<T>)Class.forName(classname);
}
catch (ClassNotFoundException e)
{
throw new ConfigurationException(String.format("Unable to find %s class '%s'", readable, classname));
}
catch (NoClassDefFoundError e)
{
throw new ConfigurationException(String.format("Unable to find %s class '%s'", readable, classname));
}
}
/**
* Constructs an instance of the given class, which must have a no-arg or default constructor.
* @param classname Fully qualified classname.
* @param readable Descriptive noun for the role the class plays.
* @throws ConfigurationException If the class cannot be found.
*/
public static <T> T construct(String classname, String readable) throws ConfigurationException
{
Class<T> cls = FBUtilities.classForName(classname, readable);
try
{
return cls.newInstance();
}
catch (IllegalAccessException e)
{
throw new ConfigurationException(String.format("Default constructor for %s class '%s' is inaccessible.", readable, classname));
}
catch (InstantiationException e)
{
throw new ConfigurationException(String.format("Cannot use abstract class '%s' as %s.", classname, readable));
}
catch (Exception e)
{
// Catch-all because Class.newInstance() "propagates any exception thrown by the nullary constructor, including a checked exception".
if (e.getCause() instanceof ConfigurationException)
throw (ConfigurationException)e.getCause();
throw new ConfigurationException(String.format("Error instantiating %s class '%s'.", readable, classname), e);
}
}
public static <T extends Comparable> SortedSet<T> singleton(T column)
{
return new TreeSet<T>(Arrays.asList(column));
}
public static String toString(Map<?,?> map)
{
Joiner.MapJoiner joiner = Joiner.on(", ").withKeyValueSeparator(":");
return joiner.join(map);
}
/**
* Used to get access to protected/private field of the specified class
* @param klass - name of the class
* @param fieldName - name of the field
* @return Field or null on error
*/
public static Field getProtectedField(Class klass, String fieldName)
{
Field field;
try
{
field = klass.getDeclaredField(fieldName);
field.setAccessible(true);
}
catch (Exception e)
{
throw new AssertionError(e);
}
return field;
}
public static IRowCacheProvider newCacheProvider(String cache_provider) throws ConfigurationException
{
if (!cache_provider.contains("."))
cache_provider = "org.apache.cassandra.cache." + cache_provider;
return FBUtilities.construct(cache_provider, "row cache provider");
}
public static <T> CloseableIterator<T> closeableIterator(Iterator<T> iterator)
{
return new WrappedCloseableIterator<T>(iterator);
}
public static Map<String, String> fromJsonMap(String json)
{
try
{
return jsonMapper.readValue(json, Map.class);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
public static List<String> fromJsonList(String json)
{
try
{
return jsonMapper.readValue(json, List.class);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
public static String json(Object object)
{
try
{
return jsonMapper.writeValueAsString(object);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
/**
* Starts and waits for the given @param pb to finish.
* @throws java.io.IOException on non-zero exit code
*/
public static void exec(ProcessBuilder pb) throws IOException
{
Process p = pb.start();
try
{
int errCode = p.waitFor();
if (errCode != 0)
{
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuilder sb = new StringBuilder();
String str;
while ((str = in.readLine()) != null)
sb.append(str).append(System.getProperty("line.separator"));
while ((str = err.readLine()) != null)
sb.append(str).append(System.getProperty("line.separator"));
throw new IOException("Exception while executing the command: "+ StringUtils.join(pb.command(), " ") +
", command error Code: " + errCode +
", command output: "+ sb.toString());
}
}
catch (InterruptedException e)
{
throw new AssertionError(e);
}
}
public static void sleep(int millis)
{
try
{
Thread.sleep(millis);
}
catch (InterruptedException e)
{
throw new AssertionError();
}
}
public static void updateChecksumInt(Checksum checksum, int v)
{
checksum.update((v >>> 24) & 0xFF);
checksum.update((v >>> 16) & 0xFF);
checksum.update((v >>> 8) & 0xFF);
checksum.update((v >>> 0) & 0xFF);
}
private static final class WrappedCloseableIterator<T>
extends AbstractIterator<T> implements CloseableIterator<T>
{
private final Iterator<T> source;
public WrappedCloseableIterator(Iterator<T> source)
{
this.source = source;
}
protected T computeNext()
{
if (!source.hasNext())
return endOfData();
return source.next();
}
public void close() {}
}
public static <T> byte[] serialize(T object, IVersionedSerializer<T> serializer, int version)
{
try
{
int size = (int) serializer.serializedSize(object, version);
DataOutputBuffer buffer = new DataOutputBuffer(size);
serializer.serialize(object, buffer, version);
assert buffer.getLength() == size && buffer.getData().length == size
: String.format("Final buffer length %s to accommodate data size of %s (predicted %s) for %s",
buffer.getData().length, buffer.getLength(), size, object);
return buffer.getData();
}
catch (IOException e)
{
// We're doing in-memory serialization...
throw new AssertionError(e);
}
}
}
| {
"content_hash": "db44273ef434284bbe8031b3be1eef8a",
"timestamp": "",
"source": "github",
"line_count": 612,
"max_line_length": 145,
"avg_line_length": 32.48202614379085,
"alnum_prop": 0.6000301826047588,
"repo_name": "dukechain/Qassandra",
"id": "e606e06492507ec103dc62722be99a5ab45f5c08",
"size": "20684",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/java/org/apache/cassandra/utils/FBUtilities.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3325"
},
{
"name": "Java",
"bytes": "10343039"
},
{
"name": "Python",
"bytes": "382871"
},
{
"name": "Shell",
"bytes": "38275"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="${applicationId}.test">
<uses-sdk tools:overrideLibrary="android.support.test.uiautomator.v18" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest> | {
"content_hash": "8b7f6cbe93d143d586a61effa0cfb680",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 80,
"avg_line_length": 46.45454545454545,
"alnum_prop": 0.7318982387475538,
"repo_name": "andrewjc/kheera-testrunner-android",
"id": "39f4e8a97ed5d9c7f27076f8f0c8618fabeaeeee",
"size": "511",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/src/androidTest/AndroidManifest.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "238739"
},
{
"name": "Shell",
"bytes": "951"
}
],
"symlink_target": ""
} |
'use strict';
const {CompositeDisposable} = require('atom');
const {addDisposableEventListener} = require('../../atom-helper');
class LoginElement extends HTMLElement {
constructor(name) {
super();
this.name = name;
this.innerHTML = `
<p>It seems like you already have a Kite account. Sign in with your login info.</p>
<form novalidate>
<input class='input-text' name="email" type="email"></input>
<input class='input-text' name="password" type="password"></input>
<button class="btn btn-primary btn-block" type="submit">Sign in</button>
<div class="secondary-actions">
<a class="back">Back</a>
<a class="reset-password secondary-cta">Forgot password</a>
</div>
<div class="status hidden"></div>
</form>
`;
this.form = this.querySelector('form');
this.input = this.querySelector('input[type="email"]');
this.password = this.querySelector('input[type="password"]');
this.submit = this.querySelector('button[type="submit"]');
this.backButton = this.querySelector('a.back');
this.forgotPassword = this.querySelector('a.reset-password');
this.status = this.querySelector('.status');
}
get data() {
return {email: this.input.value, password: this.password.value};
}
release() {
this.subscriptions && this.subscriptions.dispose();
delete this.install;
delete this.subscriptions;
}
init(install) {
this.subscriptions = new CompositeDisposable();
this.install = install;
this.classList.remove('disabled');
this.subscriptions.add(install.on('did-reset-password', email => {
atom.notifications.addSuccess(
`Instructions on how to reset your password should
have been sent to ${email}`);
}));
this.subscriptions.add(addDisposableEventListener(this.form, 'submit', () => {
this.classList.add('disabled');
this.install.emit('did-submit-credentials', this.data);
}));
this.subscriptions.add(addDisposableEventListener(this.forgotPassword, 'click', () => {
this.install.emit('did-forgot-password');
}));
this.subscriptions.add(addDisposableEventListener(this.backButton, 'click', () => {
this.install.emit('did-click-back');
}));
this.subscriptions.add(install.observeState(state => this.onStateChange(state)));
}
onStateChange(state) {
if (state.account.email) {
this.input.value = state.account.email;
}
if (state.account.password) {
this.input.password = state.account.password;
}
if (state.error) {
this.status.textContent = state.error.message;
this.status.classList.remove('hidden');
} else {
this.hideError();
}
}
hideError() {
this.status.textContent = '';
this.status.classList.add('hidden');
}
}
customElements.define('kite-atom-login', LoginElement);
module.exports = LoginElement;
| {
"content_hash": "db011e5caf24a318c0a65128bc7fdc10",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 91,
"avg_line_length": 30.568421052631578,
"alnum_prop": 0.6542699724517906,
"repo_name": "kiteco/kite-installer",
"id": "739366bbea12cf1989ed06098f103d0760a2a116",
"size": "2904",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/elements/atom/login-element.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "97262"
},
{
"name": "Less",
"bytes": "14249"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from datetime import datetime
import json
import logging
from flask import flash, Markup, redirect
from flask_appbuilder import CompactCRUDMixin, expose
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_appbuilder.security.decorators import has_access
from flask_babel import gettext as __
from flask_babel import lazy_gettext as _
from superset import appbuilder, db, security_manager, utils
from superset.connectors.base.views import DatasourceModelView
from superset.connectors.connector_registry import ConnectorRegistry
from superset.views.base import (
BaseSupersetView, DatasourceFilter, DeleteMixin,
get_datasource_exist_error_mgs, ListWidgetWithCheckboxes, SupersetModelView,
validate_json, YamlExportMixin,
)
from . import models
class DruidColumnInlineView(CompactCRUDMixin, SupersetModelView): # noqa
datamodel = SQLAInterface(models.DruidColumn)
list_title = _('List Druid Column')
show_title = _('Show Druid Column')
add_title = _('Add Druid Column')
edit_title = _('Edit Druid Column')
list_widget = ListWidgetWithCheckboxes
edit_columns = [
'column_name', 'verbose_name', 'description', 'dimension_spec_json', 'datasource',
'groupby', 'filterable', 'count_distinct', 'sum', 'min', 'max']
add_columns = edit_columns
list_columns = [
'column_name', 'verbose_name', 'type', 'groupby', 'filterable', 'count_distinct',
'sum', 'min', 'max']
can_delete = False
page_size = 500
label_columns = {
'column_name': _('Column'),
'type': _('Type'),
'datasource': _('Datasource'),
'groupby': _('Groupable'),
'filterable': _('Filterable'),
'count_distinct': _('Count Distinct'),
'sum': _('Sum'),
'min': _('Min'),
'max': _('Max'),
}
description_columns = {
'filterable': _(
'Whether this column is exposed in the `Filters` section '
'of the explore view.'),
'dimension_spec_json': utils.markdown(
'this field can be used to specify '
'a `dimensionSpec` as documented [here]'
'(http://druid.io/docs/latest/querying/dimensionspecs.html). '
'Make sure to input valid JSON and that the '
'`outputName` matches the `column_name` defined '
'above.',
True),
}
def pre_update(self, col):
# If a dimension spec JSON is given, ensure that it is
# valid JSON and that `outputName` is specified
if col.dimension_spec_json:
try:
dimension_spec = json.loads(col.dimension_spec_json)
except ValueError as e:
raise ValueError('Invalid Dimension Spec JSON: ' + str(e))
if not isinstance(dimension_spec, dict):
raise ValueError('Dimension Spec must be a JSON object')
if 'outputName' not in dimension_spec:
raise ValueError('Dimension Spec does not contain `outputName`')
if 'dimension' not in dimension_spec:
raise ValueError('Dimension Spec is missing `dimension`')
# `outputName` should be the same as the `column_name`
if dimension_spec['outputName'] != col.column_name:
raise ValueError(
'`outputName` [{}] unequal to `column_name` [{}]'
.format(dimension_spec['outputName'], col.column_name))
def post_update(self, col):
col.refresh_metrics()
def post_add(self, col):
self.post_update(col)
appbuilder.add_view_no_menu(DruidColumnInlineView)
class DruidMetricInlineView(CompactCRUDMixin, SupersetModelView): # noqa
datamodel = SQLAInterface(models.DruidMetric)
list_title = _('List Druid Metric')
show_title = _('Show Druid Metric')
add_title = _('Add Druid Metric')
edit_title = _('Edit Druid Metric')
list_columns = ['metric_name', 'verbose_name', 'metric_type']
edit_columns = [
'metric_name', 'description', 'verbose_name', 'metric_type', 'json',
'datasource', 'd3format', 'is_restricted', 'warning_text']
add_columns = edit_columns
page_size = 500
validators_columns = {
'json': [validate_json],
}
description_columns = {
'metric_type': utils.markdown(
'use `postagg` as the metric type if you are defining a '
'[Druid Post Aggregation]'
'(http://druid.io/docs/latest/querying/post-aggregations.html)',
True),
'is_restricted': _('Whether the access to this metric is restricted '
'to certain roles. Only roles with the permission '
"'metric access on XXX (the name of this metric)' "
'are allowed to access this metric'),
}
label_columns = {
'metric_name': _('Metric'),
'description': _('Description'),
'verbose_name': _('Verbose Name'),
'metric_type': _('Type'),
'json': _('JSON'),
'datasource': _('Druid Datasource'),
'warning_text': _('Warning Message'),
}
def post_add(self, metric):
if metric.is_restricted:
security_manager.merge_perm('metric_access', metric.get_perm())
def post_update(self, metric):
if metric.is_restricted:
security_manager.merge_perm('metric_access', metric.get_perm())
appbuilder.add_view_no_menu(DruidMetricInlineView)
class DruidClusterModelView(SupersetModelView, DeleteMixin, YamlExportMixin): # noqa
datamodel = SQLAInterface(models.DruidCluster)
list_title = _('List Druid Cluster')
show_title = _('Show Druid Cluster')
add_title = _('Add Druid Cluster')
edit_title = _('Edit Druid Cluster')
add_columns = [
'verbose_name', 'coordinator_host', 'coordinator_port',
'coordinator_endpoint', 'broker_host', 'broker_port',
'broker_endpoint', 'cache_timeout', 'cluster_name',
]
edit_columns = add_columns
list_columns = ['cluster_name', 'metadata_last_refreshed']
search_columns = ('cluster_name',)
label_columns = {
'cluster_name': _('Cluster'),
'coordinator_host': _('Coordinator Host'),
'coordinator_port': _('Coordinator Port'),
'coordinator_endpoint': _('Coordinator Endpoint'),
'broker_host': _('Broker Host'),
'broker_port': _('Broker Port'),
'broker_endpoint': _('Broker Endpoint'),
}
description_columns = {
'cache_timeout': _(
'Duration (in seconds) of the caching timeout for this cluster. '
'A timeout of 0 indicates that the cache never expires. '
'Note this defaults to the global timeout if undefined.'),
}
def pre_add(self, cluster):
security_manager.merge_perm('database_access', cluster.perm)
def pre_update(self, cluster):
self.pre_add(cluster)
def _delete(self, pk):
DeleteMixin._delete(self, pk)
appbuilder.add_view(
DruidClusterModelView,
name='Druid Clusters',
label=__('Druid Clusters'),
icon='fa-cubes',
category='Sources',
category_label=__('Sources'),
category_icon='fa-database',
)
class DruidDatasourceModelView(DatasourceModelView, DeleteMixin, YamlExportMixin): # noqa
datamodel = SQLAInterface(models.DruidDatasource)
list_title = _('List Druid Datasource')
show_title = _('Show Druid Datasource')
add_title = _('Add Druid Datasource')
edit_title = _('Edit Druid Datasource')
list_columns = [
'datasource_link', 'cluster', 'changed_by_', 'modified']
order_columns = ['datasource_link', 'modified']
related_views = [DruidColumnInlineView, DruidMetricInlineView]
edit_columns = [
'datasource_name', 'cluster', 'description', 'owner',
'is_hidden',
'filter_select_enabled', 'fetch_values_from',
'default_endpoint', 'offset', 'cache_timeout']
search_columns = (
'datasource_name', 'cluster', 'description', 'owner',
)
add_columns = edit_columns
show_columns = add_columns + ['perm', 'slices']
page_size = 500
base_order = ('datasource_name', 'asc')
description_columns = {
'slices': _(
'The list of charts associated with this table. By '
'altering this datasource, you may change how these associated '
'charts behave. '
'Also note that charts need to point to a datasource, so '
'this form will fail at saving if removing charts from a '
'datasource. If you want to change the datasource for a chart, '
"overwrite the chart from the 'explore view'"),
'offset': _('Timezone offset (in hours) for this datasource'),
'description': Markup(
'Supports <a href="'
'https://daringfireball.net/projects/markdown/">markdown</a>'),
'fetch_values_from': _(
'Time expression to use as a predicate when retrieving '
'distinct values to populate the filter component. '
'Only applies when `Enable Filter Select` is on. If '
'you enter `7 days ago`, the distinct list of values in '
'the filter will be populated based on the distinct value over '
'the past week'),
'filter_select_enabled': _(
"Whether to populate the filter's dropdown in the explore "
"view's filter section with a list of distinct values fetched "
'from the backend on the fly'),
'default_endpoint': _(
'Redirects to this endpoint when clicking on the datasource '
'from the datasource list'),
'cache_timeout': _(
'Duration (in seconds) of the caching timeout for this datasource. '
'A timeout of 0 indicates that the cache never expires. '
'Note this defaults to the cluster timeout if undefined.'),
}
base_filters = [['id', DatasourceFilter, lambda: []]]
label_columns = {
'slices': _('Associated Charts'),
'datasource_link': _('Data Source'),
'cluster': _('Cluster'),
'description': _('Description'),
'owner': _('Owner'),
'is_hidden': _('Is Hidden'),
'filter_select_enabled': _('Enable Filter Select'),
'default_endpoint': _('Default Endpoint'),
'offset': _('Time Offset'),
'cache_timeout': _('Cache Timeout'),
}
def pre_add(self, datasource):
with db.session.no_autoflush:
query = (
db.session.query(models.DruidDatasource)
.filter(models.DruidDatasource.datasource_name ==
datasource.datasource_name,
models.DruidDatasource.cluster_name ==
datasource.cluster.id)
)
if db.session.query(query.exists()).scalar():
raise Exception(get_datasource_exist_error_mgs(
datasource.full_name))
def post_add(self, datasource):
datasource.refresh_metrics()
security_manager.merge_perm('datasource_access', datasource.get_perm())
if datasource.schema:
security_manager.merge_perm('schema_access', datasource.schema_perm)
def post_update(self, datasource):
self.post_add(datasource)
def _delete(self, pk):
DeleteMixin._delete(self, pk)
appbuilder.add_view(
DruidDatasourceModelView,
'Druid Datasources',
label=__('Druid Datasources'),
category='Sources',
category_label=__('Sources'),
icon='fa-cube')
class Druid(BaseSupersetView):
"""The base views for Superset!"""
@has_access
@expose('/refresh_datasources/')
def refresh_datasources(self, refreshAll=True):
"""endpoint that refreshes druid datasources metadata"""
session = db.session()
DruidCluster = ConnectorRegistry.sources['druid'].cluster_class
for cluster in session.query(DruidCluster).all():
cluster_name = cluster.cluster_name
try:
cluster.refresh_datasources(refreshAll=refreshAll)
except Exception as e:
flash(
"Error while processing cluster '{}'\n{}".format(
cluster_name, utils.error_msg_from_exception(e)),
'danger')
logging.exception(e)
return redirect('/druidclustermodelview/list/')
cluster.metadata_last_refreshed = datetime.now()
flash(
'Refreshed metadata from cluster '
'[' + cluster.cluster_name + ']',
'info')
session.commit()
return redirect('/druiddatasourcemodelview/list/')
@has_access
@expose('/scan_new_datasources/')
def scan_new_datasources(self):
"""
Calling this endpoint will cause a scan for new
datasources only and add them.
"""
return self.refresh_datasources(refreshAll=False)
appbuilder.add_view_no_menu(Druid)
appbuilder.add_link(
'Scan New Datasources',
label=__('Scan New Datasources'),
href='/druid/scan_new_datasources/',
category='Sources',
category_label=__('Sources'),
category_icon='fa-database',
icon='fa-refresh')
appbuilder.add_link(
'Refresh Druid Metadata',
label=__('Refresh Druid Metadata'),
href='/druid/refresh_datasources/',
category='Sources',
category_label=__('Sources'),
category_icon='fa-database',
icon='fa-cog')
appbuilder.add_separator('Sources')
| {
"content_hash": "822feae4a0276b25cfbb03ee1685be78",
"timestamp": "",
"source": "github",
"line_count": 368,
"max_line_length": 90,
"avg_line_length": 37.39945652173913,
"alnum_prop": 0.6081522923781152,
"repo_name": "timifasubaa/incubator-superset",
"id": "7e50536195edcc7ecbe106fa9a2c56776f7aa36c",
"size": "13811",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "superset/connectors/druid/views.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "99374"
},
{
"name": "HTML",
"bytes": "100560"
},
{
"name": "JavaScript",
"bytes": "1563519"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Python",
"bytes": "1083714"
},
{
"name": "Shell",
"bytes": "1557"
},
{
"name": "Smarty",
"bytes": "1048"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="@color/ag_color_white" />
<corners
android:bottomLeftRadius="10dp"
android:bottomRightRadius="10dp"
android:topLeftRadius="0dp"
android:topRightRadius="0dp" />
</shape> | {
"content_hash": "5ea4eed61781660edf7791e5929d4ec8",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 67,
"avg_line_length": 29.25,
"alnum_prop": 0.6353276353276354,
"repo_name": "l1fan/GameAne",
"id": "095e76d3c1275b2a8bba0ee4d459a1c49035a09c",
"size": "351",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdks/kuaiyong/res/drawable/ag_corner_white.xml",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "5322"
},
{
"name": "Batchfile",
"bytes": "216"
},
{
"name": "CSS",
"bytes": "17478"
},
{
"name": "HTML",
"bytes": "118872"
},
{
"name": "Java",
"bytes": "180464"
},
{
"name": "Objective-C",
"bytes": "152626"
},
{
"name": "Shell",
"bytes": "529"
}
],
"symlink_target": ""
} |
import * as fs from "fs";
import { ATN } from "antlr4ts/atn";
import { Vocabulary, VocabularyImpl } from "antlr4ts";
import { CompatibleATNDeserializer } from "./CompatibleATNDeserializer";
export interface IInterpreterData {
atn: ATN;
vocabulary: Vocabulary;
ruleNames: string[];
channels: string[]; // Only valid for lexer grammars.
modes: string[]; // ditto
}
export class InterpreterDataReader {
public static parseFile(fileName: string): IInterpreterData {
const ruleNames: string[] = [];
const channels: string[] = [];
const modes: string[] = [];
const literalNames = [];
const symbolicNames = [];
const source = fs.readFileSync(fileName, "utf8");
const lines = source.split("\n");
let index = 0;
let line = lines[index++];
if (line !== "token literal names:") {
throw new Error("Unexpected data entry");
}
do {
line = lines[index++];
if (line.length === 0) {
break;
}
literalNames.push(line === "null" ? "" : line);
} while (true);
line = lines[index++];
if (line !== "token symbolic names:") {
throw new Error("Unexpected data entry");
}
do {
line = lines[index++];
if (line.length === 0) {
break;
}
symbolicNames.push(line === "null" ? "" : line);
} while (true);
line = lines[index++];
if (line !== "rule names:") {
throw new Error("Unexpected data entry");
}
do {
line = lines[index++];
if (line.length === 0) {
break;
}
ruleNames.push(line);
} while (true);
line = lines[index++];
if (line === "channel names:") { // Additional lexer data.
do {
line = lines[index++];
if (line.length === 0) {
break;
}
channels.push(line);
} while (true);
line = lines[index++];
if (line !== "mode names:") {
throw new Error("Unexpected data entry");
}
do {
line = lines[index++];
if (line.length === 0) {
break;
}
modes.push(line);
} while (true);
}
line = lines[index++];
if (line !== "atn:") {
throw new Error("Unexpected data entry");
}
line = lines[index++];
const elements = line.split(",");
let value;
const serializedATN = new Uint16Array(elements.length);
for (let i = 0; i < elements.length; ++i) {
const element = elements[i];
if (element.startsWith("[")) {
value = Number(element.substring(1).trim());
} else if (element.endsWith("]")) {
value = Number(element.substring(0, element.length - 1).trim());
} else {
value = Number(element.trim());
}
serializedATN[i] = value;
}
const deserializer = new CompatibleATNDeserializer();
return {
atn: deserializer.deserialize(serializedATN),
vocabulary: new VocabularyImpl(literalNames, symbolicNames, []),
ruleNames,
channels,
modes,
};
}
}
| {
"content_hash": "98fa885c585bf6e18ef6658071dd1cb7",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 80,
"avg_line_length": 28.691056910569106,
"alnum_prop": 0.4703882119580618,
"repo_name": "mike-lischke/vscode-antlr4",
"id": "3803ad9b51bdf8c295766014d0948075d8be63d8",
"size": "3700",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/backend/InterpreterDataReader.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "3239859"
},
{
"name": "C++",
"bytes": "76"
},
{
"name": "CSS",
"bytes": "12724"
},
{
"name": "JavaScript",
"bytes": "40179"
},
{
"name": "TypeScript",
"bytes": "953453"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you 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.
-->
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.bpel</groupId>
<artifactId>ode-axis2-war</artifactId>
<name>ODE :: Axis2 Based Web Application</name>
<packaging>pom</packaging>
<parent>
<groupId>org.wso2.bpel</groupId>
<artifactId>ode</artifactId>
<version>1.3.5-wso2v13-SNAPSHOT</version>
</parent>
<!--properties>
<mex.version>1.41</mex.version>
<jibx.version>1.1.5</jibx.version>
<tranql.version>1.1</tranql.version>
<opensaml.version>1.1</opensaml.version>
<bouncycastle.version>140</bouncycastle.version>
<geronimo-spec-jms.version>1.1-rc4</geronimo-spec-jms.version>
<jetty.version>6.1.3</jetty.version>
<testng.version>5.8</testng.version>
</properties-->
<dependencies>
<dependency>
<groupId>org.wso2.bpel</groupId>
<artifactId>ode-bpel-compiler</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.bpel</groupId>
<artifactId>ode-bpel-connector</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.bpel</groupId>
<artifactId>ode-bpel-dao</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.bpel</groupId>
<artifactId>ode-bpel-api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.bpel</groupId>
<artifactId>ode-bpel-epr</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.bpel</groupId>
<artifactId>ode-bpel-runtime</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.bpel</groupId>
<artifactId>ode-scheduler-simple</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.bpel</groupId>
<artifactId>ode-bpel-store</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.bpel</groupId>
<artifactId>ode-bpel-schemas</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.bpel</groupId>
<artifactId>ode-utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.bpel</groupId>
<artifactId>ode-dao-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.bpel</groupId>
<artifactId>ode-bpel-ql</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.bpel</groupId>
<artifactId>ode-axis2</artifactId>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-fastinfoset</artifactId>
<version>${axis2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-jaxbri</artifactId>
<version>${axis2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-jaxws</artifactId>
<version>${axis2.version}</version>
</dependency>
<!-- According to Axis2 team, axis2 get this dependency from JDK
This jar was there in 1.4.1. release -->
<!--dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-jaxws-api</artifactId>
<version>${axis2.version}</version>
</dependency-->
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-json</artifactId>
<version>${axis2.version}</version>
</dependency>
<!-- deprecated jar. This jar was there in 1.4.1 release -->
<!--dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-jws-api</artifactId>
<version>${axis2.version}</version>
</dependency-->
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-metadata</artifactId>
<version>${axis2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-spring</artifactId>
<version>${axis2.version}</version>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</dependency>
<dependency>
<groupId>woodstox</groupId>
<artifactId>wstx-asl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbytools</artifactId>
</dependency>
<dependency>
<groupId>org.jibx</groupId>
<artifactId>jibx-run</artifactId>
<version>${jibx.version}</version>
</dependency>
<dependency>
<groupId>tranql</groupId>
<artifactId>tranql-connector</artifactId>
<version>${tranql.version}</version>
</dependency>
<dependency>
<groupId>org.opensaml</groupId>
<artifactId>opensaml</artifactId>
<version>${opensaml.version}</version>
</dependency>
<dependency>
<groupId>bouncycastle</groupId>
<artifactId>bcprov-jdk15</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<dependency>
<groupId>geronimo-spec</groupId>
<artifactId>geronimo-spec-jms</artifactId>
<version>${geronimo-spec-jms.version}</version>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-ejb_2.1_spec</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.apache.geronimo.modules</groupId>
<artifactId>geronimo-kernel</artifactId>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
</dependency>
<!--
<dependency>
<groupId>org.apache.rampart</groupId>
<artifactId>rampart</artifactId>
<type>mar</type>
<version>${rampart.version}</version>
</dependency>
<dependency>
<groupId>org.apache.rampart</groupId>
<artifactId>rahas</artifactId>
<type>mar</type>
<version>${rampart.version}</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>addressing</artifactId>
<type>mar</type>
<version>${rampart.version}</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>mex</artifactId>
<type>mar</type>
<version>${mex.version}</version>
</dependency>
-->
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>mex</artifactId>
<classifier>impl</classifier>
<version>${mex.version}</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<classifier>jdk15</classifier>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
<version>${jetty.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-util</artifactId>
<version>${jetty.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>servlet-api-2.5</artifactId>
<version>${jetty.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.1.117</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack-axis2-webapp</id>
<phase>package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-webapp</artifactId>
<version>${axis2.version}</version>
<type>war</type>
<overWrite>false</overWrite>
</artifactItem>
</artifactItems>
<includes>axis2-web/**,WEB-INF/classes/org/**,WEB-INF/modules/*
</includes>
<outputDirectory>${project.build.directory}/axis2-webapp
</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>war-package</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>ode-axis2-war-${ode.version}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/main/assembly/bin.xml</descriptor>
</descriptors>
<tarLongFileMode>gnu</tarLongFileMode>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<execution>
<id>compiler-it</id>
<phase>pre-integration-test</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>resources-it</id>
<phase>pre-integration-test</phase>
<goals>
<goal>testResources</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<!--doclet does not support not-found="ignore" -->
<groupId>org.codehaus.groovy.maven</groupId>
<artifactId>gmaven-plugin</artifactId>
<executions>
<execution>
<id>prepare-itests</id>
<phase>pre-integration-test</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<source>${pom.basedir}/itest_setup.groovy</source>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<id>test-axis2-web</id>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<forkMode>always</forkMode>
<redirectTestOutputToFile>true</redirectTestOutputToFile>
<additionalClasspathElements>
<additionalClasspathElement>${project.build.directory}
</additionalClasspathElement>
</additionalClasspathElements>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "6b56cb99d5dfd9c680b563f1fd809105",
"timestamp": "",
"source": "github",
"line_count": 377,
"max_line_length": 91,
"avg_line_length": 38.241379310344826,
"alnum_prop": 0.505098148019699,
"repo_name": "isurusuranga/wso2-ode",
"id": "06aa0c1b4e75a44454a693350e573957fdf90242",
"size": "14417",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "axis2-war/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4070"
},
{
"name": "CSS",
"bytes": "35889"
},
{
"name": "Groovy",
"bytes": "3604"
},
{
"name": "HTML",
"bytes": "43482"
},
{
"name": "Java",
"bytes": "5369360"
},
{
"name": "JavaScript",
"bytes": "250376"
},
{
"name": "Ruby",
"bytes": "74329"
},
{
"name": "Shell",
"bytes": "6066"
},
{
"name": "XSLT",
"bytes": "6703"
}
],
"symlink_target": ""
} |
<?php
namespace CpanelBundle\Entity;
/**
* PanelChange
*/
class PanelChange
{
/**
* @var int
*/
private $id;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @var string
*/
private $comments;
/**
* @var \DateTime
*/
private $createdAt;
/**
* @var \DateTime
*/
private $updatedAt;
/**
* @var boolean
*/
private $isChanged;
/**
* @var string
*/
private $cost;
/**
* @var \CpanelBundle\Entity\PanelLabel
*/
private $panellabelin;
/**
* @var \CpanelBundle\Entity\PanelLabel
*/
private $panellabelout;
/**
* @var \CpanelBundle\Entity\User
*/
private $fosuser;
/**
* Set comments
*
* @param string $comments
*
* @return PanelChange
*/
public function setComments($comments)
{
$this->comments = $comments;
return $this;
}
/**
* Get comments
*
* @return string
*/
public function getComments()
{
return $this->comments;
}
/**
* Set createdAt
*
* @param \DateTime $createdAt
*
* @return PanelChange
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* @param \DateTime $updatedAt
*
* @return PanelChange
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set isChanged
*
* @param boolean $isChanged
*
* @return PanelChange
*/
public function setIsChanged($isChanged)
{
$this->isChanged = $isChanged;
return $this;
}
/**
* Get isChanged
*
* @return boolean
*/
public function getIsChanged()
{
return $this->isChanged;
}
/**
* Set cost
*
* @param string $cost
*
* @return PanelChange
*/
public function setCost($cost)
{
$this->cost = $cost;
return $this;
}
/**
* Get cost
*
* @return string
*/
public function getCost()
{
return $this->cost;
}
/**
* Set panellabelin
*
* @param \CpanelBundle\Entity\PanelLabel $panellabelin
*
* @return PanelChange
*/
public function setPanellabelin(\CpanelBundle\Entity\PanelLabel $panellabelin = null)
{
$this->panellabelin = $panellabelin;
return $this;
}
/**
* Get panellabelin
*
* @return \CpanelBundle\Entity\PanelLabel
*/
public function getPanellabelin()
{
return $this->panellabelin;
}
/**
* Set panellabelout
*
* @param \CpanelBundle\Entity\PanelLabel $panellabelout
*
* @return PanelChange
*/
public function setPanellabelout(\CpanelBundle\Entity\PanelLabel $panellabelout = null)
{
$this->panellabelout = $panellabelout;
return $this;
}
/**
* Get panellabelout
*
* @return \CpanelBundle\Entity\PanelLabel
*/
public function getPanellabelout()
{
return $this->panellabelout;
}
/**
* Set fosuser
*
* @param \CpanelBundle\Entity\User $fosuser
*
* @return PanelChange
*/
public function setFosuser(\CpanelBundle\Entity\User $fosuser = null)
{
$this->fosuser = $fosuser;
return $this;
}
/**
* Get fosuser
*
* @return \CpanelBundle\Entity\User
*/
public function getFosuser()
{
return $this->fosuser;
}
/**
* @var string
*/
private $shipping;
/**
* Set shipping
*
* @param string $shipping
*
* @return PanelChange
*/
public function setShipping($shipping)
{
$this->shipping = $shipping;
return $this;
}
/**
* Get shipping
*
* @return string
*/
public function getShipping()
{
return $this->shipping;
}
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $expensespanel;
/**
* Constructor
*/
public function __construct()
{
$this->expensespanel = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add expensespanel
*
* @param \CpanelBundle\Entity\ExpensesPanel $expensespanel
*
* @return PanelChange
*/
public function addExpensespanel(\CpanelBundle\Entity\ExpensesPanel $expensespanel)
{
$this->expensespanel[] = $expensespanel;
return $this;
}
/**
* Remove expensespanel
*
* @param \CpanelBundle\Entity\ExpensesPanel $expensespanel
*/
public function removeExpensespanel(\CpanelBundle\Entity\ExpensesPanel $expensespanel)
{
$this->expensespanel->removeElement($expensespanel);
}
/**
* Get expensespanel
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getExpensespanel()
{
return $this->expensespanel;
}
/**
* @var \CpanelBundle\Entity\PanelLabel
*/
private $panellabelnew;
/**
* Set panellabelnew
*
* @param \CpanelBundle\Entity\PanelLabel $panellabelnew
*
* @return PanelChange
*/
public function setPanellabelnew(\CpanelBundle\Entity\PanelLabel $panellabelnew = null)
{
$this->panellabelnew = $panellabelnew;
return $this;
}
/**
* Get panellabelnew
*
* @return \CpanelBundle\Entity\PanelLabel
*/
public function getPanellabelnew()
{
return $this->panellabelnew;
}
}
| {
"content_hash": "be1c29346edf2f72990f9a659f88d7e2",
"timestamp": "",
"source": "github",
"line_count": 361,
"max_line_length": 91,
"avg_line_length": 17.041551246537395,
"alnum_prop": 0.5308842652795839,
"repo_name": "syslock64/admin.ranceco.com",
"id": "4ea270839e2fb765766b63457e56377bec502813",
"size": "6152",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/CpanelBundle/Entity/PanelChange.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "157594"
},
{
"name": "HTML",
"bytes": "590084"
},
{
"name": "JavaScript",
"bytes": "365304"
},
{
"name": "PHP",
"bytes": "1014007"
}
],
"symlink_target": ""
} |
@interface ViewController ()
@property (weak, nonatomic) IBOutlet PLMaskAnimationView *maskAnimationView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}
- (void)onTimer
{
static float index = 0.f;
[_maskAnimationView setProgressValue:index];
index += .01;
NSLog(@"what are u doing");
if (index > 2.0) {
index = 0;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
| {
"content_hash": "5d3a4112dd78b8f486b8772a0eb38913",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 114,
"avg_line_length": 23.966666666666665,
"alnum_prop": 0.6995827538247567,
"repo_name": "PlanChang/MaskProgressView",
"id": "b8793b7e9a88762104dc46a80bb5d488b7550f9b",
"size": "913",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MaskAnimation/MaskAnimation/ViewController.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "6465"
}
],
"symlink_target": ""
} |
{% load enrichment_extra %}
<form>
<input type="submit" value="Save" disabled="true" class="btnSave noPrint" />
<p class="notice" id="unsavedNotice">Warning: Your changes have not yet been saved</p>
<p class="notice" id="savedNotice">No changes have been made - you may leave this page</p>
<p class="notice" id="savingNotice">Saving changes, please do not close this window</p>
<table class="selector noPrint">
<tr>
<th class="day">Enrichment Slot</th>
<th class="student">
<select id="massTeacher">
<option value="--">--</option>
{% for teacher in allTeachers %}
<option value="{{teacher.name}}">{{ teacher.name }}</option>
{% endfor %}
</select> <input type="checkbox" id="checkall" />
</th>
</tr>
{% for slot in slots %}
{% select_for slot student as select %}
<tr>
<td class="day">{{ slot.date}}<br /><spam style="color: #999">{{ slot.date | date:"l" }}</span></td>
<td class="day">{{ select | safe }}</td>
</tr>
{% endfor %}
</table>
<p class="noPrint">Total slots: {{ slots | length }}</p>
<input type="submit" value="Save" disabled="true" class="btnSave noPrint" />
</form>
<form id="saveData" method="post" action="{% url 'save_assignments' %}">
{% csrf_token %}
<input type="hidden" name="next" value="{{ request.path }}" id="redirectSavePath" />
</form> | {
"content_hash": "eef24f41be5391f8ff18b6b7d655d6d7",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 104,
"avg_line_length": 36.23076923076923,
"alnum_prop": 0.5874026893135174,
"repo_name": "rectory-school/rectory-apps",
"id": "06008c849ce900dca7491b25c527451a0e46ca21",
"size": "1413",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "enrichmentmanager/templates/enrichmentmanager/partial/single_student.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1150635"
},
{
"name": "HTML",
"bytes": "2337278"
},
{
"name": "JavaScript",
"bytes": "30707"
},
{
"name": "PHP",
"bytes": "51712"
},
{
"name": "Python",
"bytes": "455392"
},
{
"name": "Ruby",
"bytes": "524"
}
],
"symlink_target": ""
} |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "db.h"
#include "net.h"
#include "init.h"
#include "strlcpy.h"
#include "addrman.h"
#include "ui_interface.h"
#ifdef WIN32
#include <string.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniwget.h>
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
using namespace std;
using namespace boost;
static const int MAX_OUTBOUND_CONNECTIONS = 12;
void ThreadMessageHandler2(void* parg);
void ThreadSocketHandler2(void* parg);
void ThreadOpenConnections2(void* parg);
void ThreadOpenAddedConnections2(void* parg);
#ifdef USE_UPNP
void ThreadMapPort2(void* parg);
#endif
void ThreadDNSAddressSeed2(void* parg);
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
struct LocalServiceInfo {
int nScore;
int nPort;
};
//
// Global state variables
//
bool fClient = false;
bool fDiscover = true;
bool fUseUPnP = false;
uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);
static CCriticalSection cs_mapLocalHost;
static map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
CAddress addrSeenByPeer(CService("0.0.0.0", 0), nLocalServices);
uint64 nLocalHostNonce = 0;
array<int, THREAD_MAX> vnThreadsRunning;
static std::vector<SOCKET> vhListenSocket;
CAddrMan addrman;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
map<CInv, int64> mapAlreadyAskedFor;
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
static CSemaphore *semOutbound = NULL;
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", GetDefaultPort()));
}
void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
{
// Filter out duplicate requests
if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
return;
pindexLastGetBlocksBegin = pindexBegin;
hashLastGetBlocksEnd = hashEnd;
PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
{
if (fNoListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
{
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
{
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
{
CAddress ret(CService("0.0.0.0",0),0);
CService addr;
if (GetLocal(addr, paddrPeer))
{
ret = CAddress(addr);
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
}
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
{
strLine = "";
loop
{
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0)
{
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
}
else if (nBytes <= 0)
{
if (fShutdown)
return false;
if (nBytes < 0)
{
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
{
Sleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0)
{
// socket closed
printf("socket closed\n");
return false;
}
else
{
// socket error
int nErr = WSAGetLastError();
printf("recv failed: %d\n", nErr);
return false;
}
}
}
}
// used when scores of local addresses may have changed
// pushes better local address to peers
void static AdvertizeLocal()
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->fSuccessfullyConnected)
{
CAddress addrLocal = GetLocalAddress(&pnode->addr);
if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
{
pnode->PushAddress(addrLocal);
pnode->addrLocal = addrLocal;
}
}
}
}
void SetReachable(enum Network net, bool fFlag)
{
LOCK(cs_mapLocalHost);
vfReachable[net] = fFlag;
if (net == NET_IPV6 && fFlag)
vfReachable[NET_IPV4] = true;
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo &info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore + (fAlready ? 1 : 0);
info.nPort = addr.GetPort();
}
SetReachable(addr.GetNetwork());
}
AdvertizeLocal();
return true;
}
bool AddLocal(const CNetAddr &addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr &addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
AdvertizeLocal();
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
LOCK(cs_mapLocalHost);
enum Network net = addr.GetNetwork();
return vfReachable[net] && !vfLimited[net];
}
bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
{
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
string strLine;
while (RecvLine(hSocket, strLine))
{
if (strLine.empty()) // HTTP response is separated from headers by blank line
{
loop
{
if (!RecvLine(hSocket, strLine))
{
closesocket(hSocket);
return false;
}
if (pszKeyword == NULL)
break;
if (strLine.find(pszKeyword) != string::npos)
{
strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
break;
}
}
closesocket(hSocket);
if (strLine.find("<") != string::npos)
strLine = strLine.substr(0, strLine.find("<"));
strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
strLine.resize(strLine.size()-1);
CService addr(strLine,0,true);
printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
if (!addr.IsValid() || !addr.IsRoutable())
return false;
ipRet.SetIP(addr);
return true;
}
}
closesocket(hSocket);
return error("GetMyExternalIP() : connection closed");
}
// We now get our external IP from the IRC server first and only use this as a backup
bool GetMyExternalIP(CNetAddr& ipRet)
{
CService addrConnect;
const char* pszGet;
const char* pszKeyword;
for (int nLookup = 0; nLookup <= 1; nLookup++)
for (int nHost = 1; nHost <= 2; nHost++)
{
// We should be phasing out our use of sites like these. If we need
// replacements, we should ask for volunteers to put this simple
// php file on their web server that prints the client IP:
// <?php echo $_SERVER["REMOTE_ADDR"]; ?>
if (nHost == 1)
{
addrConnect = CService("91.198.22.70",80); // checkip.dyndns.org
if (nLookup == 1)
{
CService addrIP("checkip.dyndns.org", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET / HTTP/1.1\r\n"
"Host: checkip.dyndns.org\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = "Address:";
}
else if (nHost == 2)
{
addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
if (nLookup == 1)
{
CService addrIP("www.showmyip.com", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET /simple/ HTTP/1.1\r\n"
"Host: www.showmyip.com\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = NULL; // Returns just IP address
}
if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
return true;
}
return false;
}
void ThreadGetMyExternalIP(void* parg)
{
// Make this thread recognisable as the external IP detection thread
RenameThread("bitcoin-ext-ip");
CNetAddr addrLocalHost;
if (GetMyExternalIP(addrLocalHost))
{
printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
AddLocal(addrLocalHost, LOCAL_HTTP);
}
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
CNode* FindNode(const CNetAddr& ip)
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
}
return NULL;
}
CNode* FindNode(std::string addrName)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CService)pnode->addr == addr)
return (pnode);
}
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout)
{
if (pszDest == NULL) {
if (IsLocal(addrConnect))
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode)
{
if (nTimeout != 0)
pnode->AddRef(nTimeout);
else
pnode->AddRef();
return pnode;
}
}
/// debug print
printf("trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString().c_str(),
pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
// Connect
SOCKET hSocket;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
{
addrman.Attempt(addrConnect);
/// debug print
printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
// Set to non-blocking
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
#else
if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
#endif
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
if (nTimeout != 0)
pnode->AddRef(nTimeout);
else
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
return pnode;
}
else
{
return NULL;
}
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET)
{
printf("disconnecting node %s\n", addrName.c_str());
closesocket(hSocket);
hSocket = INVALID_SOCKET;
vRecv.clear();
}
}
void CNode::Cleanup()
{
}
void CNode::PushVersion()
{
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
CAddress addrMe = GetLocalAddress(&addr);
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
}
std::map<CNetAddr, int64> CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
void CNode::ClearBanned()
{
setBanned.clear();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
if (i != setBanned.end())
{
int64 t = (*i).second;
if (GetTime() < t)
fResult = true;
}
}
return fResult;
}
bool CNode::Misbehaving(int howmuch)
{
if (addr.IsLocal())
{
printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch);
return false;
}
nMisbehavior += howmuch;
if (nMisbehavior >= GetArg("-banscore", 100))
{
int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
{
LOCK(cs_setBanned);
if (setBanned[addr] < banTime)
setBanned[addr] = banTime;
}
CloseSocketDisconnect();
return true;
} else
printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
return false;
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats &stats)
{
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(addrName);
X(nVersion);
X(strSubVer);
X(fInbound);
X(nReleaseTime);
X(nStartingHeight);
X(nMisbehavior);
}
#undef X
void ThreadSocketHandler(void* parg)
{
// Make this thread recognisable as the networking thread
RenameThread("bitcoin-net");
try
{
vnThreadsRunning[THREAD_SOCKETHANDLER]++;
ThreadSocketHandler2(parg);
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
PrintException(&e, "ThreadSocketHandler()");
} catch (...) {
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
throw; // support pthread_cancel()
}
printf("ThreadSocketHandler exited\n");
}
void ThreadSocketHandler2(void* parg)
{
printf("ThreadSocketHandler started\n");
list<CNode*> vNodesDisconnected;
unsigned int nPrevNodeCount = 0;
loop
{
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
{
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
pnode->Cleanup();
// hold in disconnected pool until all refs are released
pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
{
// wait until threads are done using it
if (pnode->GetRefCount() <= 0)
{
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
TRY_LOCK(pnode->cs_vRecv, lockRecv);
if (lockRecv)
{
TRY_LOCK(pnode->cs_mapRequests, lockReq);
if (lockReq)
{
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
}
if (fDelete)
{
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
if (vNodes.size() != nPrevNodeCount)
{
nPrevNodeCount = vNodes.size();
uiInterface.NotifyNumConnectionsChanged(vNodes.size());
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
bool have_fds = false;
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
FD_SET(hListenSocket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket);
have_fds = true;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->hSocket == INVALID_SOCKET)
continue;
FD_SET(pnode->hSocket, &fdsetRecv);
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
have_fds = true;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend && !pnode->vSend.empty())
FD_SET(pnode->hSocket, &fdsetSend);
}
}
}
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
int nSelect = select(have_fds ? hSocketMax + 1 : 0,
&fdsetRecv, &fdsetSend, &fdsetError, &timeout);
vnThreadsRunning[THREAD_SOCKETHANDLER]++;
if (fShutdown)
return;
if (nSelect == SOCKET_ERROR)
{
if (have_fds)
{
int nErr = WSAGetLastError();
printf("socket select error %d\n", nErr);
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
Sleep(timeout.tv_usec/1000);
}
//
// Accept new connections
//
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
{
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
printf("Warning: Unknown socket family\n");
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET)
{
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK)
printf("socket error accept failed: %d\n", nErr);
}
else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
{
{
LOCK(cs_setservAddNodeAddresses);
if (!setservAddNodeAddresses.count(addr))
closesocket(hSocket);
}
}
else if (CNode::IsBanned(addr))
{
printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
closesocket(hSocket);
}
else
{
printf("accepted connection %s\n", addr.ToString().c_str());
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (fShutdown)
return;
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
{
TRY_LOCK(pnode->cs_vRecv, lockRecv);
if (lockRecv)
{
CDataStream& vRecv = pnode->vRecv;
unsigned int nPos = vRecv.size();
if (nPos > ReceiveBufferSize()) {
if (!pnode->fDisconnect)
printf("socket recv flood control disconnect (%"PRIszu" bytes)\n", vRecv.size());
pnode->CloseSocketDisconnect();
}
else {
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0)
{
vRecv.resize(nPos + nBytes);
memcpy(&vRecv[nPos], pchBuf, nBytes);
pnode->nLastRecv = GetTime();
}
else if (nBytes == 0)
{
// socket closed gracefully
if (!pnode->fDisconnect)
printf("socket closed\n");
pnode->CloseSocketDisconnect();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
if (!pnode->fDisconnect)
printf("socket recv error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend))
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
CDataStream& vSend = pnode->vSend;
if (!vSend.empty())
{
int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0)
{
vSend.erase(vSend.begin(), vSend.begin() + nBytes);
pnode->nLastSend = GetTime();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
printf("socket send error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Inactivity checking
//
if (pnode->vSend.empty())
pnode->nLastSendEmpty = GetTime();
if (GetTime() - pnode->nTimeConnected > 60)
{
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
{
printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
{
printf("socket not sending\n");
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastRecv > 90*60)
{
printf("socket inactivity timeout\n");
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
Sleep(10);
}
}
#ifdef USE_UPNP
void ThreadMapPort(void* parg)
{
// Make this thread recognisable as the UPnP thread
RenameThread("bitcoin-UPnP");
try
{
vnThreadsRunning[THREAD_UPNP]++;
ThreadMapPort2(parg);
vnThreadsRunning[THREAD_UPNP]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_UPNP]--;
PrintException(&e, "ThreadMapPort()");
} catch (...) {
vnThreadsRunning[THREAD_UPNP]--;
PrintException(NULL, "ThreadMapPort()");
}
printf("ThreadMapPort exited\n");
}
void ThreadMapPort2(void* parg)
{
printf("ThreadMapPort started\n");
std::string port = strprintf("%u", GetListenPort());
const char * multicastif = 0;
const char * minissdpdpath = 0;
struct UPNPDev * devlist = 0;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
#else
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1)
{
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
if(r != UPNPCOMMAND_SUCCESS)
printf("UPnP: GetExternalIPAddress() returned %d\n", r);
else
{
if(externalIPAddress[0])
{
printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
}
else
printf("UPnP: GetExternalIPAddress failed.\n");
}
}
string strDesc = "BlitzCoin " + FormatFullVersion();
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if(r!=UPNPCOMMAND_SUCCESS)
printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
else
printf("UPnP Port Mapping successful.\n");
int i = 1;
loop {
if (fShutdown || !fUseUPnP)
{
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
printf("UPNP_DeletePortMapping() returned : %d\n", r);
freeUPNPDevlist(devlist); devlist = 0;
FreeUPNPUrls(&urls);
return;
}
if (i % 600 == 0) // Refresh every 20 minutes
{
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if(r!=UPNPCOMMAND_SUCCESS)
printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
else
printf("UPnP Port Mapping successful.\n");;
}
Sleep(2000);
i++;
}
} else {
printf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist); devlist = 0;
if (r != 0)
FreeUPNPUrls(&urls);
loop {
if (fShutdown || !fUseUPnP)
return;
Sleep(2000);
}
}
}
void MapPort()
{
if (fUseUPnP && vnThreadsRunning[THREAD_UPNP] < 1)
{
if (!NewThread(ThreadMapPort, NULL))
printf("Error: ThreadMapPort(ThreadMapPort) failed\n");
}
}
#else
void MapPort()
{
// Intentionally left blank.
}
#endif
// DNS seeds
// Each pair gives a source name and a seed name.
// The first name is used as information source for addrman.
// The second name should resolve to a list of seed addresses.
static const char *strDNSSeed[][2] = {
{"", ""},
};
void ThreadDNSAddressSeed(void* parg)
{
// Make this thread recognisable as the DNS seeding thread
RenameThread("bitcoin-dnsseed");
try
{
vnThreadsRunning[THREAD_DNSSEED]++;
ThreadDNSAddressSeed2(parg);
vnThreadsRunning[THREAD_DNSSEED]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_DNSSEED]--;
PrintException(&e, "ThreadDNSAddressSeed()");
} catch (...) {
vnThreadsRunning[THREAD_DNSSEED]--;
throw; // support pthread_cancel()
}
printf("ThreadDNSAddressSeed exited\n");
}
void ThreadDNSAddressSeed2(void* parg)
{
printf("ThreadDNSAddressSeed started\n");
int found = 0;
if (!fTestNet)
{
printf("Loading addresses from DNS seeds (could take a while)\n");
for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
if (HaveNameProxy()) {
AddOneShot(strDNSSeed[seed_idx][1]);
} else {
vector<CNetAddr> vaddr;
vector<CAddress> vAdd;
if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
{
BOOST_FOREACH(CNetAddr& ip, vaddr)
{
int nOneDay = 24*3600;
CAddress addr = CAddress(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
}
}
}
printf("%d addresses found from DNS seeds\n", found);
}
unsigned int pnSeed[] =
{
};
void DumpAddresses()
{
int64 nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void ThreadDumpAddress2(void* parg)
{
vnThreadsRunning[THREAD_DUMPADDRESS]++;
while (!fShutdown)
{
DumpAddresses();
vnThreadsRunning[THREAD_DUMPADDRESS]--;
Sleep(100000);
vnThreadsRunning[THREAD_DUMPADDRESS]++;
}
vnThreadsRunning[THREAD_DUMPADDRESS]--;
}
void ThreadDumpAddress(void* parg)
{
// Make this thread recognisable as the address dumping thread
RenameThread("bitcoin-adrdump");
try
{
ThreadDumpAddress2(parg);
}
catch (std::exception& e) {
PrintException(&e, "ThreadDumpAddress()");
}
printf("ThreadDumpAddress exited\n");
}
void ThreadOpenConnections(void* parg)
{
// Make this thread recognisable as the connection opening thread
RenameThread("bitcoin-opencon");
try
{
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
ThreadOpenConnections2(parg);
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
PrintException(&e, "ThreadOpenConnections()");
} catch (...) {
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
PrintException(NULL, "ThreadOpenConnections()");
}
printf("ThreadOpenConnections exited\n");
}
void static ProcessOneShot()
{
string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
// ppcoin: stake bltzer thread
void static ThreadStakeBlitzer(void* parg)
{
printf("ThreadStakeBlitzer started\n");
CWallet* pwallet = (CWallet*)parg;
try
{
vnThreadsRunning[THREAD_BLTZER]++;
BitcoinMiner(pwallet, true);
vnThreadsRunning[THREAD_BLTZER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_BLTZER]--;
PrintException(&e, "ThreadStakeBlitzer()");
} catch (...) {
vnThreadsRunning[THREAD_BLTZER]--;
PrintException(NULL, "ThreadStakeBlitzer()");
}
printf("ThreadStakeBlitzer exiting, %d threads remaining\n", vnThreadsRunning[THREAD_BLTZER]);
}
void ThreadOpenConnections2(void* parg)
{
printf("ThreadOpenConnections started\n");
// Connect to specific addresses
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
{
for (int64 nLoop = 0;; nLoop++)
{
ProcessOneShot();
BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
{
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++)
{
Sleep(500);
if (fShutdown)
return;
}
}
Sleep(500);
}
}
// Initiate network connections
int64 nStart = GetTime();
loop
{
ProcessOneShot();
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
Sleep(500);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return;
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
CSemaphoreGrant grant(*semOutbound);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return;
// Add seed nodes if IRC isn't working
if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
{
std::vector<CAddress> vAdd;
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64 nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vAdd.push_back(addr);
}
addrman.Add(vAdd, CNetAddr("127.0.0.1"));
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
set<vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64 nANow = GetAdjustedTime();
int nTries = 0;
loop
{
// use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
// If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
// stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
// already-connected network ranges, ...) before trying new addrman addresses.
nTries++;
if (nTries > 100)
break;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// do not allow non-default ports, unless after 50 invalid addresses selected already
if (addr.GetPort() != GetDefaultPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections(void* parg)
{
// Make this thread recognisable as the connection opening thread
RenameThread("bitcoin-opencon");
try
{
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
ThreadOpenAddedConnections2(parg);
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
PrintException(&e, "ThreadOpenAddedConnections()");
} catch (...) {
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
PrintException(NULL, "ThreadOpenAddedConnections()");
}
printf("ThreadOpenAddedConnections exited\n");
}
void ThreadOpenAddedConnections2(void* parg)
{
printf("ThreadOpenAddedConnections started\n");
if (mapArgs.count("-addnode") == 0)
return;
if (HaveNameProxy()) {
while(!fShutdown) {
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
Sleep(500);
}
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
Sleep(120000); // Retry every 2 minutes
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
}
return;
}
vector<vector<CService> > vservAddressesToAdd(0);
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
{
vector<CService> vservNode(0);
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
{
vservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
BOOST_FOREACH(CService& serv, vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
loop
{
vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
BOOST_FOREACH(CService& addrNode, *(it))
if (pnode->addr == addrNode)
{
it = vservConnectAddresses.erase(it);
it--;
break;
}
}
BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
{
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
Sleep(500);
if (fShutdown)
return;
}
if (fShutdown)
return;
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
Sleep(120000); // Retry every 2 minutes
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
if (fShutdown)
return;
}
}
// if successful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
if (fShutdown)
return false;
if (!strDest)
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort().c_str()))
return false;
if (strDest && FindNode(strDest))
return false;
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
CNode* pnode = ConnectNode(addrConnect, strDest);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return false;
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
void ThreadMessageHandler(void* parg)
{
// Make this thread recognisable as the message handling thread
RenameThread("bitcoin-msghand");
try
{
vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
ThreadMessageHandler2(parg);
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
PrintException(&e, "ThreadMessageHandler()");
} catch (...) {
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
PrintException(NULL, "ThreadMessageHandler()");
}
printf("ThreadMessageHandler exited\n");
}
void ThreadMessageHandler2(void* parg)
{
printf("ThreadMessageHandler started\n");
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (!fShutdown)
{
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
// Receive messages
{
TRY_LOCK(pnode->cs_vRecv, lockRecv);
if (lockRecv)
ProcessMessages(pnode);
}
if (fShutdown)
return;
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SendMessages(pnode, pnode == pnodeTrickle);
}
if (fShutdown)
return;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
// Wait and allow messages to bunch up.
// Reduce vnThreadsRunning so StopNode has permission to exit while
// we're sleeping, but we must always check fShutdown after doing this.
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
Sleep(100);
if (fRequestShutdown)
StartShutdown();
vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
if (fShutdown)
return;
}
}
bool BindListenPort(const CService &addrBind, string& strError)
{
strError = "";
int nOne = 1;
#ifdef WIN32
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR)
{
strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
printf("%s\n", strError.c_str());
return false;
}
#endif
// Create socket for listening for incoming connections
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
{
strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
printf("%s\n", strError.c_str());
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET)
{
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
#ifndef WIN32
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows.
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
// Set to non-blocking, incoming connections will also inherit this
if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
#else
if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
#endif
{
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef USE_IPV6
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
#ifdef WIN32
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
#else
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#endif
#ifdef WIN32
int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
// this call is allowed to fail
setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
#endif
}
#endif
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. BlitzCoin is probably already running."), addrBind.ToString().c_str());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
printf("%s\n", strError.c_str());
return false;
}
printf("Bound to %s\n", addrBind.ToString().c_str());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
vhListenSocket.push_back(hListenSocket);
if (addrBind.IsRoutable() && fDiscover)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover()
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host IP
char pszHostName[1000] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
{
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr))
{
BOOST_FOREACH (const CNetAddr &addr, vaddr)
{
AddLocal(addr, LOCAL_IF);
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0)
{
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#ifdef USE_IPV6
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#endif
}
freeifaddrs(myaddrs);
}
#endif
// Don't use external IPv4 discovery, when -onlynet="IPv6"
if (!IsLimited(NET_IPV4))
NewThread(ThreadGetMyExternalIP, NULL);
}
void StartNode(void* parg)
{
// Make this thread recognisable as the startup thread
RenameThread("bitcoin-start");
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover();
//
// Start threads
//
/*
if (!GetBoolArg("-dnsseed", true))
printf("DNS seeding disabled\n");
else
if (!NewThread(ThreadDNSAddressSeed, NULL))
printf("Error: NewThread(ThreadDNSAddressSeed) failed\n");
*/
if (!GetBoolArg("-dnsseed", false))
printf("DNS seeding disabled\n");
if (GetBoolArg("-dnsseed", false))
printf("DNS seeding NYI\n");
// Map ports with UPnP
if (fUseUPnP)
MapPort();
// Get addresses from IRC and advertise ours
if (!NewThread(ThreadIRCSeed, NULL))
printf("Error: NewThread(ThreadIRCSeed) failed\n");
// Send and receive from sockets, accept connections
if (!NewThread(ThreadSocketHandler, NULL))
printf("Error: NewThread(ThreadSocketHandler) failed\n");
// Initiate outbound connections from -addnode
if (!NewThread(ThreadOpenAddedConnections, NULL))
printf("Error: NewThread(ThreadOpenAddedConnections) failed\n");
// Initiate outbound connections
if (!NewThread(ThreadOpenConnections, NULL))
printf("Error: NewThread(ThreadOpenConnections) failed\n");
// Process messages
if (!NewThread(ThreadMessageHandler, NULL))
printf("Error: NewThread(ThreadMessageHandler) failed\n");
// Dump network addresses
if (!NewThread(ThreadDumpAddress, NULL))
printf("Error; NewThread(ThreadDumpAddress) failed\n");
// ppcoin: bltz proof-of-stake blocks in the background
if (!NewThread(ThreadStakeBlitzer, pwalletMain))
printf("Error: NewThread(ThreadStakeBlitzer) failed\n");
// Generate coins in the background
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
}
bool StopNode()
{
printf("StopNode()\n");
fShutdown = true;
nTransactionsUpdated++;
int64 nStart = GetTime();
if (semOutbound)
for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
do
{
int nThreadsRunning = 0;
for (int n = 0; n < THREAD_MAX; n++)
nThreadsRunning += vnThreadsRunning[n];
if (nThreadsRunning == 0)
break;
if (GetTime() - nStart > 20)
break;
Sleep(20);
} while(true);
if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
if (vnThreadsRunning[THREAD_MINER] > 0) printf("ThreadBitcoinMiner still running\n");
if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
#ifdef USE_UPNP
if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n");
#endif
if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
if (vnThreadsRunning[THREAD_BLTZER] > 0) printf("ThreadStakeBlitzer still running\n");
while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0)
Sleep(20);
Sleep(50);
DumpAddresses();
return true;
}
class CNetCleanup
{
public:
CNetCleanup()
{
}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
closesocket(pnode->hSocket);
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET)
if (closesocket(hListenSocket) == SOCKET_ERROR)
printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
}
instance_of_cnetcleanup;
| {
"content_hash": "4fd8564c6b2b8087b8fa2f6a3be67828",
"timestamp": "",
"source": "github",
"line_count": 1960,
"max_line_length": 196,
"avg_line_length": 30.349489795918366,
"alnum_prop": 0.5500378246616794,
"repo_name": "bobfeldbauer/blitz",
"id": "3bdaa17657409d6371b387eba0069c720b13e477",
"size": "59485",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/net.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "61562"
},
{
"name": "C",
"bytes": "65871"
},
{
"name": "C++",
"bytes": "1621321"
},
{
"name": "IDL",
"bytes": "11588"
},
{
"name": "Objective-C",
"bytes": "2451"
},
{
"name": "Python",
"bytes": "11646"
},
{
"name": "Shell",
"bytes": "1026"
},
{
"name": "TypeScript",
"bytes": "232558"
}
],
"symlink_target": ""
} |
<?php
namespace ServerGrove\KbBundle\Composer;
use Composer\Util\Filesystem;
use Composer\Util\RemoteFilesystem;
/**
* Class JackrabbitInstaller
*
* @author Ismael Ambrosi<[email protected]>
*/
class JackrabbitInstaller
{
const JACKRABBIT_VERSION = '2.4.3';
/**
* @var string
*/
private static $downloadUrls;
/**
* @static
*
* @param \Composer\Script\CommandEvent $event
*/
public static function checkAndInstall($event)
{
$appDir = getcwd().'/app';
$resourcesPath = $appDir.'/Resources';
if (is_dir($resourcesPath)) {
$filesystem = new Filesystem();
$jackrabbitDir = $resourcesPath.'/java/jackrabbit';
$filesystem->ensureDirectoryExists($jackrabbitDir);
if (!self::check($jackrabbitDir) && false !== ($file = self::download($event->getIO(), $jackrabbitDir))) {
self::install($file, $appDir);
}
}
}
/**
* @static
*
* @param string $destination
*
* @return bool
*/
private static function check($destination)
{
$url = current(self::getDownloadUrl());
return false !== $url && file_exists($destination.'/'.basename(parse_url($url, PHP_URL_PATH)));
}
/**
* @static
*
* @param \Composer\IO\IOInterface $io
* @param string $destination
*
* @return bool
*/
private static function download(\Composer\IO\IOInterface $io, $destination)
{
$io->write('<info>Installing jackrabbit</info>');
if (false === ($urls = self::getDownloadUrl())) {
$io->write('Invalid URLs');
} else {
reset($urls);
$r = new RemoteFilesystem($io);
do {
try {
$url = current($urls);
$file = $destination.'/'.basename(parse_url($url, PHP_URL_PATH));
$io->write(sprintf('Retrieving Jackrabbit from "%s"', $url), true);
$result = $r->copy('', $url, $file, true);
} catch (\Composer\Downloader\TransportException $ex) {
$io->write('', true);
$result = false;
$file = null;
}
} while (false === $result && next($urls));
if (is_null($file)) {
throw new \Exception('Invalid file name');
}
return $file;
}
return false;
}
private static function install($file, $appDir)
{
$parametersFile = $appDir.'/config/jackrabbit.yml';
if (!file_exists($parametersFile)) {
touch($parametersFile);
}
$content = sprintf(
'parameters: %s doctrine_phpcr.jackrabbit_jar: %s%1$s',
PHP_EOL,
str_replace($appDir, '%kernel.root_dir%', $file)
);
file_put_contents($parametersFile, $content);
}
/**
* @static
* @return bool|string
*/
private static function getDownloadUrl()
{
if (!is_array(self::$downloadUrls)) {
$version = self::JACKRABBIT_VERSION;
if (false === ($content = file_get_contents(self::getMirrorListUrl($version)))) {
throw new \Exception('Unable to retrive mirror list');
}
$content = strip_tags($content);
$pattern = '#(?P<url>[https|http|ftp]+\://[\w\.\-/]+/jackrabbit\-standalone\-(?P<version>[0-9\.]+).jar)#';
if (!preg_match_all($pattern, $content, $out)) {
return false;
}
$map = array();
foreach ($out['url'] as $position => $url) {
if (isset($out['version'][$position]) && $version === $out['version'][$position]) {
$map[] = $url;
}
}
self::$downloadUrls = array_unique($map);
}
return self::$downloadUrls;
}
private static function getMirrorListUrl($version)
{
return strtr(
'http://www.apache.org/dyn/closer.cgi/jackrabbit/:version/jackrabbit-standalone-:version.jar',
array(':version' => $version)
);
}
}
| {
"content_hash": "9ff5363911413b28713b1a3e653488da",
"timestamp": "",
"source": "github",
"line_count": 153,
"max_line_length": 118,
"avg_line_length": 28,
"alnum_prop": 0.5042016806722689,
"repo_name": "servergrove/ServerGroveKbBundle",
"id": "b30623efc5530b939fa1cd1005c9a2b79b9f68e2",
"size": "4284",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Composer/JackrabbitInstaller.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "21898"
},
{
"name": "PHP",
"bytes": "194137"
}
],
"symlink_target": ""
} |
package scaldi.play
import play.api.ApplicationLoader.Context
import play.api._
import play.core.WebCommands
import scaldi._
class ScaldiApplicationLoader(val builder: ScaldiApplicationBuilder) extends ApplicationLoader {
def this() = this(new ScaldiApplicationBuilder())
def load(context: Context): Application =
builder
.in(context.environment)
.loadConfig(context.initialConfiguration)
.prependModule(new Module {
bind[OptionalDevContext] to new OptionalDevContext(context.devContext)
})
.build()
}
| {
"content_hash": "fbc0df6fe7e81548efc4ae6f6f16524a",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 96,
"avg_line_length": 29,
"alnum_prop": 0.7495462794918331,
"repo_name": "scaldi/scaldi-play",
"id": "72e0e5901a3f7f72d19d232aae31bb6f1e6520b0",
"size": "551",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/scaldi/play/ScaldiApplicationLoader.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "38411"
}
],
"symlink_target": ""
} |
If you'd like to hack on the Ruby code that drives this project, please
join us, we'd love to have you!
## What Are the Project Goals?
Homebrew-cask is an attempt to make a Linux-style package manager for
precompiled OS X software. Homebrew-cask is not yet as featureful as
`apt` or `yum`, but we are trying to be as close as we can get to those
tools from the user's point of view.
We manage installed files via the "symlink farm" method, like [GNU Stow](http://www.gnu.org/software/stow/)
and [Homebrew](http://brew.sh/).
## What Is the Design Philosophy?
Homebrew-cask is designed to work like a traditional Unix tool:
- All functionality should be accessible from the CLI. The user should
be freed (**freed!**) from interacting with a GUI.
- homebrew-cask should itself be scriptable.
Homebrew-cask is designed to work like Homebrew:
- Like Homebrew, we don't require the user to install with `sudo`. In
fact, we recommend against it.
## What Is the State of the Project?
This is a young project. We are just getting off the ground. We are still
revising our goals and adding new ones.
## What Needs to be Done?
Plenty. Start with [open issues](https://github.com/caskroom/homebrew-cask/issues?state=open) !
## Are You Interested in New Features?
Yes, definitely! Bring your own expertise. Just remember that the user
always comes first.
## Are You Interested in New Types of Packages?
Yes! (We call them "artifacts"). If something is useful (and precompiled)
then we'd like to enable users to install it via homebrew-cask.
## Could Homebrew-cask Also Be Used to Manage Settings?
It's a neat idea! We have talked about it but nobody has worked
on it:
- <https://gist.github.com/phinze/7cd361150816bd85304e>
- <https://github.com/caskroom/homebrew-cask/issues/1135>
## What About Installing by Copying Instead of Linking?
It's a neat idea! We have talked about it but nobody has worked on it:
- <https://github.com/caskroom/homebrew-cask/pull/2312#issuecomment-31859263>
We would want to make sure that uninstall works equally well when copying.
## What About a `brew cask upgrade` Command?
Yes, definitely! We have talked about it, and worked on some aspects
of it. But there is much left to do:
- <https://github.com/caskroom/homebrew-cask/issues/309>
## What About Installing Multiple Versions of a Package?
Yes, definitely! We have started working on it, so please contact us
directly if you want to help.
- <https://github.com/caskroom/homebrew-cask/issues/142>
## What About Dependencies?
Yes, definitely! We have started working on it, so please contact us
directly if you want to help.
## What Is Your Relationship to Homebrew?
We are independent of Homebrew as a project.
From the user's point of view, homebrew-cask is a subcommand of Homebrew,
so we try to match Homebrew semantics and philosophy wherever possible.
From the programmer's point of view, very little code is shared with Homebrew.
It turns out that Homebrew's code is tightly linked with the Homebrew
Formula definition. Casks are defined differently than Formulae, which
(unfortunately) is a barrier to re-using code.
## How Should I Set Up a Development Environment?
Cask authors often work directly within the Homebrew directory
under `/usr/local`. For coding, that is usually not sufficient.
We recommend the following:
1. Fork our repo: <https://github.com/caskroom/homebrew-cask/fork>
2. Clone a private copy of the repo:
```bash
git clone https://github.com/<username>/homebrew-cask.git
```
3. Add the official repo as the `upstream` remote:
```bash
cd homebrew-cask
git remote add upstream https://github.com/caskroom/homebrew-cask.git
```
4. Now you have two copies of the homebrew-cask codebase on disk: the
released version in `/usr/local/Library/Taps/caskroom/homebrew-cask`, and a
development version in your private repo. To symlink the `Casks`
and `rubylib` folders from `/usr/local/...` into your private repo,
run the following script:
```bash
/<path>/<to>/<private>/<repo>/developer/bin/develop_brew_cask
```
Now you can hack on your private repo, and use the `brew cask`
CLI like normal -- it will interact with your latest code.
5. Important: while in development mode, you can't safely run
Homebrew's `brew update` command. To switch back to production
mode, run
```bash
/<path>/<to>/<private>/<repo>/developer/bin/production_brew_cask
```
## How Can I Force a Specific Ruby Interpreter?
You can force a specific version of the Ruby interpreter, and/or an
alternate version of the `brew-cask` subcommand, by invoking `brew cask`
with fully-qualified paths, like this:
```bash
$ HOMEBREW_BREW_FILE=/usr/local/bin/brew /System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby /usr/local/Library/brew.rb /usr/local/bin/brew-cask.rb help
```
## Hanging out on IRC
We're on IRC at `#homebrew-cask` on Freenode. If you are going to develop for
homebrew-cask, it's a great idea to hang out with us there. Here's why:
- discuss your thoughts before coding and maybe get new ideas
- get feedback from the Travis-CI bot on build failures
- talk to [caskbot](https://github.com/passcod/caskbot) about checksums, version info, and releases
- just to be social!
## What Version of Ruby Should I Target?
We target the vendor-supplied Ruby interpreter. Apple provided Ruby 1.8.7
as recently as OS X 10.8 (Mountain Lion). Therefore, even though OS X 10.9
(Mavericks) has Ruby 2.0.0-p247, this project targets Ruby 1.8.7 for
backwards compatibility.
## Mind the test suite!
If you're making changes - please write some tests for them! Also be sure to
run the whole test suite using `rake test` before submitting (if you forget,
Travis-CI will do that for you and embarrass you in front of all your friends). :)
## Submitting Your Changes
See the relevant section in `CONTRIBUTING.md`:
[Submitting Your Changes](../CONTRIBUTING.md#submitting-your-changes)
### Commit Messages
The first line of a commit message (the summary line) is like the subject
line of an email. (See [CONTRIBUTING.md](../CONTRIBUTING.md#commit-messages)).
A short but complete summary line helps the maintainers respond to your
pull request more quickly.
### External Commands
Advanced users may create their own external commands for homebrew-cask by
following conventions similar to external commands for git or Homebrew. An
external command may be any executable on your `$PATH` which follows the
form `brewcask-<command>`. (So long as `<command>` does not conflict with
an existing command verb.) The command will be invoked by `exec` and passed
any unprocessed arguments from the original command-line. An external
command may also be implemented as an executable Ruby file, on your `$PATH`,
which follows the form `brewcask-<command>.rb`. The Ruby file will be
`required` and will have full access to the Ruby environments of both
homebrew-cask and Homebrew. Example external commands may be found in
`developer/examples`.
# <3 THANK YOU! <3
| {
"content_hash": "6776d9f4542148dd049fd862c0a92df9",
"timestamp": "",
"source": "github",
"line_count": 193,
"max_line_length": 172,
"avg_line_length": 36.44559585492228,
"alnum_prop": 0.7556155814614729,
"repo_name": "0asa/homebrew-cask",
"id": "e1c5c8862814c9b62ee706c82428d056d883f736",
"size": "7067",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "doc/HACKING.md",
"mode": "33188",
"license": "bsd-2-clause",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.iosdevlog.a152staticrequestfocus.MainActivity">
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:ems="10"
android:hint="EditText 1"
android:inputType="textPersonName">
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:ems="10"
android:hint="EditText 2"
android:inputType="textPersonName" />
</RelativeLayout>
| {
"content_hash": "2deb4438a3b18596ab865ced3ebfc640",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 74,
"avg_line_length": 37.75,
"alnum_prop": 0.6806475349521707,
"repo_name": "AndroidDevLog/AndroidDevLog",
"id": "a31e79f1346fa3f1340952c87fa13e0dcbcc3db2",
"size": "1359",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "152.StaticRequestFocus/app/src/main/res/layout/activity_main.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "262"
},
{
"name": "Java",
"bytes": "1360389"
},
{
"name": "PHP",
"bytes": "11775"
}
],
"symlink_target": ""
} |
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$suit = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.ps1", ".psm1")
$module= $here.Replace("\spec\ps_specs", "\ChefExtensionHandler\bin\$suit")
$code = Get-Content $module | Out-String
Invoke-Expression $code
$sharedHelper = $here.Replace("\spec\ps_specs", "\ChefExtensionHandler\bin\shared.ps1")
. $sharedHelper
describe "#Install-ChefClient" {
it "install chef and azure chef extension gem successfully" {
# create temp powershell file for mock Get-SharedHelper
$tempPS = ([System.IO.Path]::GetTempFileName() | Rename-Item -NewName { $_ -replace 'tmp$', 'ps1' } -PassThru)
mock Get-SharedHelper {return $tempPS}
$extensionRoot = "C:\Packages\Plugin\ChefExtensionHandler"
mock Chef-GetExtensionRoot {return $extensionRoot}
$localMsiPath = "C:\Packages\Plugin\ChefExtensionHandler\installer\chef-client-latest.msi"
mock Get-LocalDestinationMsiPath {return $localMsiPath}
$chefMsiLogPath = $env:tmp
mock Get-ChefClientMsiLogPath {return $chefMsiLogPath}
mock Archive-ChefClientLog
mock Run-ChefInstaller
mock Install-AzureChefExtensionGem
Install-ChefClient
# Delete temp file created for Get-SharedHelper
Remove-Item $tempPS
# Archive-ChefClientLog should called with $chefMsiLogPath params atleast 1 time
Assert-MockCalled Archive-ChefClientLog -Times 1 -ParameterFilter{$chefClientMsiLogPath -eq $chefMsiLogPath}
Assert-MockCalled Get-LocalDestinationMsiPath -Times 1 -ParameterFilter{$chefExtensionRoot -eq $extensionRoot}
Assert-MockCalled Run-ChefInstaller -Times 1 -ParameterFilter{$localDestinationMsiPath -eq $localMsiPath -and $chefClientMsiLogPath -eq $chefMsiLogPath}
Assert-MockCalled Install-AzureChefExtensionGem -Times 1 -ParameterFilter{$chefExtensionRoot -eq $extensionRoot}
Assert-VerifiableMocks
}
context "when chefClientMsiLogPath not exist" {
it "install chef client, azure chef extension gem and skip chef log archiving" {
mock Get-SharedHelper {return "C:"}
mock Chef-GetExtensionRoot -Verifiable
mock Get-LocalDestinationMsiPath -Verifiable
$chefMsiLogPath = "C:\invalid"
mock Get-ChefClientMsiLogPath {return $chefMsiLogPath} -Verifiable
mock Run-ChefInstaller -Verifiable
mock Install-AzureChefExtensionGem -Verifiable
mock Archive-ChefClientLog
Install-ChefClient
Assert-MockCalled Archive-ChefClientLog -Times 0 -ParameterFilter{$chefClientMsiLogPath -eq $chefMsiLogPath}
Assert-VerifiableMocks
}
}
}
describe "#Get-SharedHelper" {
it "returns shared helper" {
$extensionRoot = "C:\Users\azure\azure-chef-extension\ChefExtensionHandler"
mock Chef-GetExtensionRoot {return $extensionRoot} -Verifiable
$result = Get-SharedHelper
$result | should Be("$extensionRoot\\bin\\shared.ps1")
Assert-VerifiableMocks
}
}
describe "#Get-LocalDestinationMsiPath" {
it "contains chef-client-latest.msi path" {
$extensionRoot = "C:\Users\azure\azure-chef-extension\ChefExtensionHandler"
$result = Get-LocalDestinationMsiPath($extensionRoot)
$result | should Match("\\installer\\chef-client-latest.msi")
}
}
describe "#Get-ChefClientMsiLogPath" {
it "returns chef-client msi log path" {
$result = Get-ChefClientMsiLogPath
$env:temp = "C:\AppData\Temp"
$result | should Match("\\chef-client-msi806.log")
}
}
| {
"content_hash": "d57c751228e4bed7879047d1c4824645",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 156,
"avg_line_length": 36.59574468085106,
"alnum_prop": 0.7418604651162791,
"repo_name": "andrewelizondo/azure-chef-extension",
"id": "9d3ce33f24b43b5583abf18e3edd76f2f64f938b",
"size": "3867",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/ps_specs/chef-install.Tests.ps1",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "823"
},
{
"name": "HTML",
"bytes": "5580"
},
{
"name": "Nix",
"bytes": "293"
},
{
"name": "PowerShell",
"bytes": "46839"
},
{
"name": "Ruby",
"bytes": "110005"
},
{
"name": "Shell",
"bytes": "12554"
}
],
"symlink_target": ""
} |
import os
import hashlib
import binascii
import struct
import M2Crypto.RSA as RSA
import M2Crypto.BIO as BIO
from cStringIO import StringIO
# Package a pile of data, identified by user-id, into a distribution
# plus metadata.
# Input: A directory containing a bunch of files, each of whose name
# is a hexadecimal userID. Anything that isn't a hex userid gets
# hashed with sha256 and turned into one.
#
# Also required is a key for signing the metaindex.
# Output: A file and a metaindex file, as specified in spec.txt.
BUCKET_SIZE = 8*1024
HASH_LEN = 32
IDX_ENT_LEN = HASH_LEN * 2 + 4 + 4
def ceilDiv(a,b):
return (a + b - 1) // b
def fmt_u32(v):
return struct.pack("!L", v)
def zero_pad(s, n):
if len(s) > n:
return s[:n]
else:
return s+"\x00"*(n - len(s))
def get_public_key_digest(key):
bio = BIO.MemoryBuffer()
pub = RSA.new_pub_key(key.pub())
pub.save_key_der_bio(bio)
asn1 = bio.read()
bio.close()
return hashlib.sha256(asn1).digest()
class Distribution:
def __init__(self, directory):
self._dir = directory
self._files = [ ] # (filename, userid[binary], size, nBuckets)
self._user_buckets = 0
self._key = None
self._my_name = ""
self._my_id = "\x00"*HASH_LEN
def setIdentity(self, my_name, private_key):
self._my_name = my_name
self._key = private_key
self._my_id = get_public_key_digest(private_key)
def scanDirectory(self):
total_user_buckets = 0
for fn in os.listdir(self._dir):
if fn.startswith("."):
continue
userid = None
if len(fn) == HASH_LEN*2:
try:
userid = binascii.a2b_hex(fn)
except TypeError:
pass
if userid == None:
userid = hashlib.sha256(fn).digest()
size = os.stat(os.path.join(self._dir,fn)).st_size
n_buckets = ceilDiv(size, BUCKET_SIZE - HASH_LEN)
self._files.append((userid, fn, size, n_buckets))
total_user_buckets += n_buckets
self._files.sort()
self._user_buckets = total_user_buckets
def writeDistribution(self, outFname):
idx_ents_per_bucket = ceilDiv(BUCKET_SIZE, IDX_ENT_LEN)
idx_buckets = ceilDiv(len(self._files), idx_ents_per_bucket)
user_buckets = self._user_buckets
f_output = open(outFname+".bs%s"%BUCKET_SIZE, 'wb')
# This will NOT make for the nicest IO pattern in the whole world.
f_output.seek((user_buckets+idx_buckets-1)*BUCKET_SIZE)
# Perhaps we should flush these periodically?
index_entries = [ ] # (userid, bucket-idx, pos within bucket, digest)
last_digest = "\x00"*HASH_LEN
file_stride = BUCKET_SIZE - HASH_LEN
buckets_written = 0
for userid, fn, size, n_buckets in reversed(self._files):
with open(os.path.join(self._dir, fn), 'rb') as f_input:
for user_bucketnum in xrange(n_buckets-1, -1, -1):
d = hashlib.sha256(last_digest)
f_input.seek(user_bucketnum*file_stride, 0)
f_output.write(last_digest)
content = f_input.read(file_stride)
if len(content) < file_stride:
content += "\x00" * (file_stride - len(content))
f_output.write(content)
f_output.seek(-BUCKET_SIZE*2, 1)
d.update(content)
last_digest = d.digest()
buckets_written += 1
user_bucket_idx = user_buckets + idx_buckets - buckets_written
index_entries.append((userid, user_bucket_idx, 0, last_digest))
# Okay. Now we need to build the index blocks. This, we can do
# forwards.
index_entries.reverse()
f_output.seek(0)
idx_block_num = 0
metaindex_entries = [ ] # (first userid, hash of idx block)
for block_start in xrange(0, len(index_entries), idx_ents_per_bucket):
d = hashlib.sha256()
for userid, user_bucket_idx, offset, bucket_digest in \
index_entries[block_start:block_start+idx_ents_per_bucket]:
entry = "%s%s%s%s"%(userid,
fmt_u32(user_bucket_idx),
fmt_u32(offset),
bucket_digest)
assert len(entry) == IDX_ENT_LEN
d.update(entry)
f_output.write(entry)
f_output_pos = f_output.tell()
assert f_output_pos == (idx_block_num * BUCKET_SIZE +
IDX_ENT_LEN * len(index_entries[block_start:block_start+idx_ents_per_bucket]))
if f_output_pos < (idx_block_num+1)*BUCKET_SIZE:
padding = "\x00"*((idx_block_num+1)*BUCKET_SIZE - f_output_pos)
f_output.write(padding)
d.update(padding)
first_userid = index_entries[block_start][0]
idx_block_digest = d.digest()
metaindex_entries.append((first_userid, idx_block_digest))
f_output.close()
d = hashlib.sha256()
with open(outFname+".bs%s"%BUCKET_SIZE, 'rb') as f:
s = f.read(BUCKET_SIZE)
d.update(s)
distribution_digest = d.digest()
d = hashlib.sha256()
f_meta = open(outFname+".meta", 'wb')
# Version: 4 bytes
# Bucket size: 4 bytes.
# Nymserver name: HASH_LEN*2 bytes.
# Nymserver identity: HASH_LEN bytes.
# File name: HASH_LEN*2 bytes.
# Distribution digest: HASH_LEN bytes
# Number of entries in the metaindex==MLEN: 4 bytes
# Metaindex: MLen * (HASH_LEN*2) bytes
# SigLen: 4 bytes
# Signature: SigLen bytes
meta_hdr_parts = [ fmt_u32(0),
fmt_u32(BUCKET_SIZE),
zero_pad(self._my_name, HASH_LEN*2),
self._my_id,
zero_pad(outFname, HASH_LEN*2),
distribution_digest,
fmt_u32(len(metaindex_entries)) ]
meta_hdr = "".join(meta_hdr_parts)
f_meta.write(meta_hdr)
d.update(meta_hdr)
for userid, idx_block_digest in metaindex_entries:
formatted = userid + idx_block_digest
f_meta.write(formatted)
d.update(formatted)
metainfo_digest = d.digest()
# Last, try to sign this thing.
if self._key == None:
f_meta.write(fmt_u32(0))
f_meta.close()
return
signature = self._key.sign_rsassa_pss(metainfo_digest, 'sha256', 32)
f_meta.write(fmt_u32(len(signature)))
f_meta.write(signature)
f_meta.close()
if __name__ == '__main__':
import sys
if len(sys.argv) < 3:
print """\
Syntax:
maas.py KEY.pem directory
Outputs files in my-dist.bs8192, and my-dist.meta"""
sys.exit(1)
privkey = RSA.load_key(sys.argv[1])
dist = Distribution(sys.argv[2])
dist.scanDirectory()
dist.setIdentity("maas-demo", privkey)
dist.writeDistribution("my-dist")
## Permission is hereby granted, free of charge, to any person obtaining a copy
## of this software and associated documentation files (the "Software"), to
## deal in the Software without restriction, including without limitation the
## rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
## sell copies of the Software, and to permit persons to whom the Software is
## furnished to do so, subject to the following conditions:
##
## The above copyright notice and this permission notice shall be included in
## all copies or substantial portions of the Software.
##
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
## FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
## IN THE SOFTWARE.
| {
"content_hash": "eac4e6f31041cf4585c4c40d44feafa2",
"timestamp": "",
"source": "github",
"line_count": 231,
"max_line_length": 114,
"avg_line_length": 36.35930735930736,
"alnum_prop": 0.574949398737945,
"repo_name": "nmathewson/pynchon-gate",
"id": "463fbc1cb6c59a7c82eda19355f4078647816d89",
"size": "8574",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/maas/maas.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "96909"
},
{
"name": "Python",
"bytes": "22280"
}
],
"symlink_target": ""
} |
/**
*
* 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.
*
*/
package gov.services.permits.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import gov.services.permits.electrical.Ack;
import gov.services.permits.electrical.ElectricalPermitStatusRequest;
import gov.services.permits.electrical.ElectricalPermitStatusResponse;
import gov.services.permits.electrical.RaiseElectricalPermitRequest;
import gov.services.permits.electrical.RaiseElectricalPermitResponse;
import gov.services.permits.electrical.RescindElectricalPermitRequest;
import gov.services.permits.electrical.RescindElectricalPermitResponse;
import gov.services.permits.repo.ElectricalPermitRepository;
/**
* @author [email protected]
*
*/
@Endpoint
public class ElectricalPermitServiceEndpoint {
private static final String NS_URI = "http://services.gov/permits/electrical";
private ElectricalPermitRepository repository;
/**
* Required Repository for the web service to work
*
* @param repository
*/
@Autowired
public ElectricalPermitServiceEndpoint(ElectricalPermitRepository repository) {
this.repository = repository;
}
/**
*
* @param request
* @return
*/
@PayloadRoot(namespace = NS_URI, localPart = "RaiseElectricalPermitRequest")
@ResponsePayload
public RaiseElectricalPermitResponse raiseElectricalPermit(@RequestPayload RaiseElectricalPermitRequest request) {
RaiseElectricalPermitResponse response = new RaiseElectricalPermitResponse();
String permitId = repository.addElectricalPermitRequest(request);
if (ElectricalPermitRepository.DUPLICATE_CAPTION.equals(permitId)) {
response.setAck(Ack.REJECTED);
response.setRejectReason(ElectricalPermitRepository.DUPLICATE_CAPTION);
} else {
response.setAck(Ack.ACCEPTED);
response.setRequestId(permitId);
}
return response;
}
/**
*
* @param request
* @return
*/
@PayloadRoot(namespace = NS_URI, localPart = "ElectricalPermitStatusRequest")
@ResponsePayload
public ElectricalPermitStatusResponse electricalPermitStatus(
@RequestPayload ElectricalPermitStatusRequest request) {
ElectricalPermitStatusResponse response = new ElectricalPermitStatusResponse();
response.setStatus(repository.electricalPermitStatus(request.getRequestId()));
return response;
}
/**
*
* @param request
* @return
*/
@PayloadRoot(namespace = NS_URI, localPart = "RescindElectricalPermitRequest")
@ResponsePayload
public RescindElectricalPermitResponse rescindElectricalPermit(
@RequestPayload RescindElectricalPermitRequest request) {
RescindElectricalPermitResponse response = new RescindElectricalPermitResponse();
response.setResult(repository.rescindElectricalPermit(request.getRequestId()));
return response;
}
}
| {
"content_hash": "31f429996b4b252673ade2c88011745c",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 115,
"avg_line_length": 34.68627450980392,
"alnum_prop": 0.7979084228377614,
"repo_name": "diego-torres/solarVillage",
"id": "a6d7cb09583e4da7104f11ee55548148e77c1726",
"size": "3538",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "governmentPermitServices/permitServiceTier/src/main/java/gov/services/permits/web/ElectricalPermitServiceEndpoint.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "238"
},
{
"name": "FreeMarker",
"bytes": "25429"
},
{
"name": "HTML",
"bytes": "1583"
},
{
"name": "Java",
"bytes": "78918"
},
{
"name": "JavaScript",
"bytes": "5742"
},
{
"name": "TypeScript",
"bytes": "59992"
}
],
"symlink_target": ""
} |
package org.apache.tamaya.spisupport.propertysource;
import org.apache.tamaya.spi.ChangeSupport;
import org.apache.tamaya.spi.PropertySource;
import org.apache.tamaya.spi.PropertyValue;
import org.apache.tamaya.spisupport.PropertySourceComparator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiConsumer;
/**
* Property source effectively managed by the configuration context, allowing resetting of ordinal and its
* delegate (e.g. in case of refresh).
*/
class WrappedPropertySource implements PropertySource{
private Integer ordinal;
private PropertySource delegate;
private long loaded = System.currentTimeMillis();
private WrappedPropertySource(PropertySource delegate) {
this(delegate, null);
}
private WrappedPropertySource(PropertySource delegate, Integer ordinal) {
this.delegate = Objects.requireNonNull(delegate);
this.ordinal = ordinal;
}
public static WrappedPropertySource of(PropertySource ps) {
if(ps instanceof WrappedPropertySource){
return (WrappedPropertySource)ps;
}
return new WrappedPropertySource(ps);
}
public static WrappedPropertySource of(PropertySource ps, Integer ordinal) {
if(ps instanceof WrappedPropertySource){
return new WrappedPropertySource(((WrappedPropertySource)ps).getDelegate(), ordinal);
}
return new WrappedPropertySource(ps, ordinal);
}
public int getOrdinal() {
if(this.ordinal!=null){
return this.ordinal;
}
return PropertySourceComparator.getOrdinal(delegate);
}
public void setOrdinal(Integer ordinal) {
this.ordinal = ordinal;
}
public void setDelegate(PropertySource delegate) {
this.delegate = Objects.requireNonNull(delegate);
this.loaded = System.currentTimeMillis();
}
@Override
public String getName() {
return delegate.getName();
}
@Override
public PropertyValue get(String key) {
return delegate.get(key);
}
@Override
public Map<String, PropertyValue> getProperties() {
return delegate.getProperties();
}
@Override
public boolean isScannable() {
return delegate.isScannable();
}
@Override
public ChangeSupport getChangeSupport() {
return delegate.getChangeSupport();
}
@Override
public String getVersion() {
return delegate.getVersion();
}
@Override
public void addChangeListener(BiConsumer<Set<String>, PropertySource> l) {
delegate.addChangeListener(l);
}
@Override
public void removeChangeListener(BiConsumer<Set<String>, PropertySource> l) {
delegate.removeChangeListener(l);
}
@Override
public void removeAllChangeListeners() {
delegate.removeAllChangeListeners();
}
public PropertySource getDelegate() {
return delegate;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof WrappedPropertySource)) {
return false;
}
WrappedPropertySource that = (WrappedPropertySource) o;
return getDelegate().getName().equals(that.getDelegate().getName());
}
@Override
public int hashCode() {
return getDelegate().getName().hashCode();
}
@Override
public String toString() {
return "WrappedPropertySource{" +
"name=" + getName() +
", ordinal=" + getOrdinal() +
", scannable=" + isScannable() +
", changeSupport=" + getChangeSupport() +
", loadedAt=" + loaded +
", delegate-class=" + delegate.getClass().getName() +
'}';
}
}
| {
"content_hash": "04855d6815e760bec4a0168c242c926c",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 106,
"avg_line_length": 27.14788732394366,
"alnum_prop": 0.6448767833981842,
"repo_name": "apache/incubator-tamaya",
"id": "446df324982e895d8bd235d96562c1c2338ed2d4",
"size": "4676",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "code/spi-support/src/main/java/org/apache/tamaya/spisupport/propertysource/WrappedPropertySource.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "30796"
},
{
"name": "Java",
"bytes": "1036340"
},
{
"name": "Shell",
"bytes": "931"
}
],
"symlink_target": ""
} |
/*global require, describe, it , before, after, beforeEach, afterEach */
(function () {
"use strict";
var tl = require("../lib/timeline"),
should = require("should"),
today = new Date("2014/06/27"); // require("../lib/today").Today();
describe("testing days_ago", function () {
it("assuming that today is 2014/06/27", function () {
today.should.eql(new Date("2014/06/27"));
});
it("should find out that yesterday was 2014/06/26", function () {
today.days_ago(1).should.eql(new Date("2014/06/26"));
});
it("should find out that last week was 2014/06/20", function () {
today.days_ago(7).should.eql(new Date("2014/06/20"));
});
it("should find out than 10 days ago is further in the past than 1 days ago", function () {
should(today.days_ago(10).getTime() < today.days_ago(1).getTime()).equal(true);
});
});
describe("testing next_day", function () {
it("assuming that today is 2014/06/27", function () {
today.should.eql(new Date("2014/06/27"));
});
it("should find out that tomorrow will be 2014/06/28", function () {
today.next_day().should.eql(new Date("2014/06/28"));
});
it("should find out that tomorrow will be 2014/06/28", function () {
today.next_day(1).should.eql(new Date("2014/06/28"));
});
it("should find out that next week will be 2014/07/04", function () {
today.next_day(7).should.eql(new Date("2014/07/04"));
});
});
describe("testing weekday", function () {
it("should extend the Date object with a weekday method", function () {
should(Date.prototype).have.property("weekday");
});
it("assume that today is a friday as a prerequisite for the following test", function () {
today.weekday().should.equal("Fri");
});
it("should then check that one day ago was a Thurday", function () {
today.days_ago(1).weekday().should.equal("Thu");
});
it("should then check that two days ago was a Wedneday", function () {
today.days_ago(2).weekday().should.equal("Wed");
});
it("should then check that three days ago was a Tuesday", function () {
today.days_ago(3).weekday().should.equal("Tue");
});
it("should then check that four days ago was a Monday", function () {
today.days_ago(4).weekday().should.equal("Mon");
});
it("should then check that five days ago was a Sunday", function () {
today.days_ago(5).weekday().should.equal("Sun");
});
});
describe("testing working_days_ago", function () {
it("should extend the Date object with a working_days_ago method", function () {
should(Date.prototype).have.property("working_days_ago");
});
it("assume that today is a friday as a prerequisite for the following test", function () {
today.weekday().should.equal("Fri");
});
it("should verify that working_days_ago take the week end into account ( 5 working days ago is a Fri )", function () {
today.working_days_ago(5).weekday().should.equal("Fri");
});
});
describe("testing next_working_day",function(){
xit("should extend the Date object with a next_working_day method", function () {
should(Date.prototype).have.property("next_working_day");
});
});
describe("testing javascript Date behavior", function () {
it("should have a getMonth returning month in the range of [0,11] and getDate returning the day in the month [1,31]", function () {
var d1 = new Date("2012/04/30"); // 4 is for April
d1.weekday().should.equal("Mon");
d1.getMonth().should.equal(3); // getMonth starts at 0 (0 = Jan, 1 = Feb etc...)
d1.getDate().should.equal(30);
});
});
describe("Testing diffDate", function () {
it("should expose a diffDate method", function () {
should(tl).have.property("diffDate");
});
it("should return 1 when date are the same , by convention a job started today and finished today has a duration of 1 day", function () {
//
var d1 = new Date("2012/06/01");
var d2 = new Date("2012/06/01");
tl.diffDate(d2, d1).should.equal(1);
});
it("should return 2 for diff date between today and tommorrow", function () {
//
var d1 = new Date("2012/06/01");
var d2 = new Date("2012/06/02");
tl.diffDate(d1, d2).should.equal(2);
});
it("should return -2 for diff date between tommorrow and today", function () {
//
var d1 = new Date("2012/06/01");
var d2 = new Date("2012/06/02");
tl.diffDate(d2, d1).should.equal(-2);
});
});
describe("testing calculateNumberOfNonBusinessDays", function () {
// Friday 22 Juin 2012
var today = new Date("2012/06/22");
it("assuming that today is Friday 22th of June 2012 is a working day", function () {
today.weekday().should.equal("Fri");
});
it("should verify that Friday 22th of June 2012 is a working day", function () {
today.isWorkingDay().should.equal(true);
});
it("should verify that Friday 22th of June 2012 is not a week end", function () {
today.isWeekEnd().should.equal(false);
});
it("should verify that Friday 22th of June 2012 is not a bridge day", function () {
today.isBridge().should.equal(false);
});
it("should verify that Friday 22th of June 2012 is not a team vacation day", function () {
today.isVacation().should.equal(false);
});
it("should verify that Saturday 23th of June 2012 is NOT a working day", function () {
today.next_day(1).isWorkingDay().should.equal(false);
});
it("should verify that Saturday 23th of June 2012 is a week end", function () {
today.next_day(1).isWeekEnd().should.equal(true);
});
it("should verify that Saturday 23th of June 2012 is not a bridge day", function () {
today.next_day(1).isBridge().should.equal(false);
});
it("should verify that Saturday 23th of June 2012 is not a team vacation day", function () {
today.next_day(1).isVacation().should.equal(false);
});
it("should verify that calculateNumberOfNonBusinessDays in the period of [today,today+0days] returns the correct values", function () {
tl.calculateNumberOfNonBusinessDays(today, 0).should.eql({ weekend: 0, vacations: 0, bridge: 0, end_date: today });
});
it("should verify that calculateNumberOfNonBusinessDays in the period of [today,today+ 1 days] returns the correct values", function () {
tl.calculateNumberOfNonBusinessDays(today, 1).should.eql({ weekend: 0, vacations: 0, bridge: 0, end_date: today });
});
it("should verify that calculateNumberOfNonBusinessDays in the period of [today,today+ 2 days] returns the correct values", function () {
tl.calculateNumberOfNonBusinessDays(today, 2).should.eql({ weekend: 2, vacations: 0, bridge: 0, end_date: today.next_day(3) });
});
});
describe(" calculating the number of business day between two dates", function () {
var tuesday = today.days_ago(10);
var monday = tuesday.days_ago(1);
var sunday = tuesday.days_ago(2);
var saturday = tuesday.days_ago(3);
var friday = tuesday.days_ago(4);
it("assuming that date is " + tuesday + " is a working date", function () {
tuesday.isWorkingDay().should.eql(true);
tuesday.weekday().should.eql("Tue");
monday.isWorkingDay().should.eql(true); // Monday
monday.weekday().should.eql("Mon");
sunday.isWorkingDay().should.eql(false);
sunday.weekday().should.eql("Sun");
saturday.isWorkingDay().should.eql(false);
saturday.weekday().should.eql("Sat");
});
it("the number of business day between a working day and itself shall be 1", function () {
tl.calcBusinessDays(tuesday, tuesday).should.eql(1);
});
it("the number of business day between monday and tuesday shall be 2", function () {
tl.calcBusinessDays(monday, tuesday).should.eql(2);
});
it("the number of business day between saturday and tuesday shall be 2", function () {
tl.calcBusinessDays(saturday, tuesday).should.eql(2);
});
it("the number of business day between saturday and tuesday shall be 1", function () {
tl.calcBusinessDays(saturday, monday).should.eql(1);
});
it("the number of business day between friday and monday shall be 2", function () {
tl.calcBusinessDays(saturday, tuesday).should.eql(2);
});
});
describe("calculateBusinessDays with vacationTable", function () {
// 2012
// Avril Mai Juin
// di lu ma me je ve sa di lu ma me je ve sa di lu ma me je ve sa
// 1 2 3 4 5 6 7 1 2 3 4 5 1 2
// 8 9 10 11 12 13 14 6 7 8 9 10 11 12 3 4 5 6 7 8 9
// 15 16 17 18 19 20 21 13 14 15 16 17 18 19 10 11 12 13 14 15 16
// 22 23 24 25 26 27 28 20 21 22 23 24 25 26 17 18 19 20 21 22 23
// 29 30 27 28 29 30 31 24 25 26 27 28 29 30
var vacationTable = new tl.VacationTable();
vacationTable.add_recurrent_vacation_day("Labor Day", 1, 5);
vacationTable.add_recurrent_vacation_day("Victory", 8, 5);
var old_vacationTable;
before(function () {
old_vacationTable = tl.installVacationManager(vacationTable);
});
after(function () {
tl.installVacationManager(old_vacationTable);
});
var monday_30th_of_april = new Date("2012/04/30"); // Monday 30th of April
var labor_day = monday_30th_of_april.next_day();
it("labor day shall not be a working day", function () {
labor_day.isWorkingDay().should.eql(false);
});
it("labor day shall be a vacation day", function () {
labor_day.isVacation().should.eql(true);
});
it("labor day shall not be a bridge day", function () {
labor_day.isBridge().should.eql(false);
});
it("assuming that labor day is a recurrent non working day", function () {
var first_of_may_2012 = new Date("2012/05/01");
first_of_may_2012.weekday().should.eql("Tue");
vacationTable.isWorkingDay(first_of_may_2012).should.eql(false);
});
it("should verify that Monday before Labor day 2012 which is a Tuesday , is not a working day", function () {
// bridge
vacationTable.isBridgeDay(monday_30th_of_april).should.eql(true);
vacationTable.isWorkingDay(monday_30th_of_april).should.eql(false);
//xx monday_30th_of_april.isWorkingDay().should.equal(false);
});
it("should verify that the number of business day between monday and monday is 0", function () {
tl.calcBusinessDays(monday_30th_of_april, monday_30th_of_april).should.eql(0);
});
it("should calculate correct number of business date", function () {
tl.calcBusinessDays(monday_30th_of_april, "2012/05/02").should.eql(1); //
tl.calcBusinessDays(monday_30th_of_april, "2012/05/03").should.eql(2);
tl.calcBusinessDays(monday_30th_of_april, "2012/05/04").should.eql(3);
tl.calcBusinessDays(monday_30th_of_april, "2012/05/05").should.eql(3);
tl.calcBusinessDays(monday_30th_of_april, "2012/05/06").should.eql(3);
tl.calcBusinessDays(monday_30th_of_april, "2012/05/07").should.eql(3); // bridge
tl.calcBusinessDays(monday_30th_of_april, "2012/05/08").should.eql(3); // victory
tl.calcBusinessDays(monday_30th_of_april, "2012/05/09").should.eql(4);
tl.calcBusinessDays(monday_30th_of_april, "2012/05/10").should.eql(5);
tl.calcBusinessDays(monday_30th_of_april, "2012/05/11").should.eql(6); // friday
tl.calcBusinessDays(monday_30th_of_april, "2012/05/12").should.eql(6); // saturday
});
it("tl.calculateNumberOfNonBusinessDays(today,0)", function () {
tl.calculateNumberOfNonBusinessDays(monday_30th_of_april, 0).should.eql(
{ weekend: 0, vacations: 0, bridge: 0, end_date: monday_30th_of_april });
tl.calculateNumberOfNonBusinessDays(monday_30th_of_april, 1).should.eql(
{ weekend: 0, vacations: 1, bridge: 1, end_date: new Date("2012/05/02")});
});
it("1 working day from 30th of April should lead us to 2nd of May (skipping bridge and labor day)", function () {
monday_30th_of_april.addBusinessDay(1).should.eql(new Date("2012/05/02"));
});
it("2 working days from 30th of April should lead us to 3rd of May (skipping bridge and labor day)", function () {
monday_30th_of_april.addBusinessDay(2).should.eql(new Date("2012/05/03"));
});
it("3 working days from 30th of April should lead us to 4th of May (skipping bridge and labor day)", function () {
monday_30th_of_april.addBusinessDay(3).should.eql(new Date("2012/05/04"));
});
it("4 working days from 30th of April should lead us to 9th of May (skipping bridge and labor day)", function () {
monday_30th_of_april.addBusinessDay(4).should.eql(new Date("2012/05/09"));
});
});
describe("build_time_line", function () {
var monday = new Date("2013/07/01");
monday.weekday().should.eql("Mon");
var tuesday = monday.next_day(1);
var wednesday = monday.next_day(2);
var thursday = monday.next_day(3);
var friday_last_week = monday.days_ago(3);
friday_last_week.weekday().should.eql("Fri");
it("should create a time line with one single working day", function () {
monday.isWorkingDay().should.eql(true);
var timeline = tl.build_time_line(monday, monday);
timeline.length.should.equal(1);
timeline[0].should.eql(monday);
});
it("should create a time line with two consecutive working day", function () {
var timeline = tl.build_time_line(monday, tuesday);
timeline.length.should.equal(2);
timeline[0].should.eql(monday);
timeline[1].should.eql(tuesday);
});
it("should create a time line with two consecutive working day", function () {
var timeline = tl.build_time_line(monday, wednesday);
timeline.length.should.equal(3);
timeline[0].should.eql(monday);
timeline[1].should.eql(tuesday);
timeline[2].should.eql(wednesday);
});
it("should create a time line and exclude the week-end days", function () {
var timeline = tl.build_time_line(friday_last_week, tuesday);
timeline.length.should.equal(3);
timeline[0].should.eql(friday_last_week);
timeline[1].should.eql(monday);
timeline[2].should.eql(tuesday);
});
it("should create a time line starting on the previous working day when start date is not a working day ", function () {
var sunday = monday.days_ago(1);
sunday.isWorkingDay().should.eql(false);
var timeline = tl.build_time_line(sunday, tuesday);
timeline.length.should.equal(3);
timeline[0].should.eql(friday_last_week);
timeline[1].should.eql(monday);
timeline[2].should.eql(tuesday);
});
it("should handle invalid argument in time line gracefuly",function() {
var early_date = new Date("2010/01/01");
var later_date = new Date("2010/02/01");
should(function () {
tl.build_time_line(early_date, later_date);
}).not.throwError();
should(function () {
tl.build_time_line(later_date, early_date);
}).throwError();
});
it("should raise exception if timeline is toolarge",function(){
should(function(){
// timeline too large !
tl.build_time_line("2010/01/01","3100/01/01");
}).throwError();
});
});
})();
| {
"content_hash": "9ea06d73eb55d1f28560a71783570124",
"timestamp": "",
"source": "github",
"line_count": 406,
"max_line_length": 145,
"avg_line_length": 41.87684729064039,
"alnum_prop": 0.5794612398541348,
"repo_name": "erossignon/redmine-kanban-core",
"id": "5c3ad10c4f9aa3637ae30d0cb0ada8b5552925af",
"size": "17002",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/test_timeline.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "685137"
}
],
"symlink_target": ""
} |
i18n.pt = {
fullName: 'Português',
ok: 'ESTÁ BEM',
main: {
legend: 'Lenda',
diagram: 'Diagrama',
mapView: 'Ver o mapa',
favoriteView: 'Favoritos',
settings: 'Definições',
stationSelection: 'Selecione uma estação',
chartView: 'Vista Gráfico',
allPhenomena: 'Todos os Fenômenos',
phenomenon: 'Fenómeno',
favoritesList: 'Favoritos',
importFavorites: 'Importação',
exportFavorites: 'Exportação',
importExportHelp: 'Para importar um arquivo, por favor, escolha um arquivo exportado antes.',
noFileSelected: 'No arquivo selecionado'
},
chart: {
noTimeseriesSelected: 'Você selecionou nenhum timeseries, os timeseries selecionados têm nenhum valor no intervalo de tempo determinado ou os timeseries estão ocultas.',
outsideOfDataRange: 'Fora do intervalo de dados!',
annotation: 'Dados sem garantia!',
monthNames: [ 'Jan', 'Fevereiro', 'Estragar', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro' ]
},
table: {
time: 'Tempo'
},
map: {
userLocation: 'Aqui está a sua localização actual',
stationSelection: {
station: 'Estação',
selectAllTimeseries: 'selecionar todos os timeseries'
},
stationLocation: {
station: 'Estação',
timeseries: 'Timeseries',
provider: 'Provedor',
jumpBackToChart: 'de volta ao gráfico'
},
providerList: {
provider: 'Provedor',
stations: 'Estações',
timeseries: 'Timeseries',
phenomena: 'Fenómenos'
},
search: {
label: 'procurar endereço ...',
noResult: 'Desculpe, o endereço não pôde ser encontrado.'
}
},
listSelection: {
header: 'Selecione timeseries por lista',
headers: {
category: 'Categoria',
station: 'Estação',
phenomenon: 'Fenómeno',
procedure: 'Sensor'
},
warning: {
moreThanOneTimeseries: 'encontrado mais de um timeseries'
}
},
legend: {
entry: {
noData: 'Não há dados disponíveis',
jumpToLastValue: 'Ir para o último valor',
firstValueAt: 'Primeiro valor em',
lastValueAt: 'Última valor em'
}
},
export: {
label: 'Dados como CSV (arquivo ZIP)'
},
timeSelection: {
header: 'Intervalo de tempo',
presetsHeader: 'presets',
presets: {
lastHour: 'última hora',
today: 'hoje',
yesterday: 'ontem',
todayYesterday: 'hoje e ontem',
thisWeek: 'esta semana',
lastWeek: 'semana passada',
thisMonth: 'este mês',
lastMonth: 'mês passado',
thisYear: 'este ano',
lastYear: 'ano passado'
},
custom: {
header: 'personalizado',
start: 'Data de início',
end: 'A data de término'
},
warning: {
startBeforeEnd: 'A data de início não pode ser maior que a data final',
maxTimeRange: 'O intervalo de tempo não pode ser maior que um ano'
}
},
styleChange: {
header: 'Mude o estilo',
currentColor: 'Cor atual',
selectColor: 'Selecione uma nova cor',
selectBarInterval: 'Selecione o intervalo de bar',
barChartInterval: {
hour: 'Hora',
day: 'Dia',
week: 'Semana',
month: 'Mês'
},
zeroScaled: 'eixo Y em escala de zero',
groupedAxis: 'eixo agrupados'
},
settings: {
header: 'Definições',
chooseLanguage: 'Switch language',
requiresRestart: 'Necessidades Restart!',
permalink: {
create: 'Criar um permalink como',
inWindow: 'link em uma nova janela',
inMail: 'link em um e-mail',
inClipboard: 'Link para a área de transferência',
clipboardInfo: 'Copiar para a área de transferência:',
inQrCode: 'como QR-Code',
favorite: 'Salve ambiente de trabalho como entrada favorito'
},
clusterMarker: 'marcador de cluster',
markerWithLastInfo: {
header: 'marcador com informações último valor',
label: 'atenção - alguns provedor de dados são muito lentos'
},
saveStatus: {
header: 'Salvar ambiente',
label: 'Todos os timeseries, o período de tempo selecionado e as configurações são salvas contínua.'
},
resetStatus: 'Ambiente de redefinição',
generalizeData: 'generalizar dados',
imprint: {
header: 'Cunho',
github: 'Encontre este projeto no <a href="https://github.com/52North/js-sensorweb-client" target="_blank">GitHub</a>',
text: '<p> <a href="http://52north.org" target="_blank">52 ° Norte GmbH</a> é responsável por este site. </p><p> 52 ° Iniciativa do Norte para a Open Source Geospatial Software GmbH <br> Martin-Luther-King-Weg 24 <br> 48155 Muenster, Alemanha </p>'
}
},
permalink: {
noMatchingTimeseriesFound: 'Nenhum timeseries correspondente for encontrado.'
},
guide: {
start: {
request: 'Quando você iniciar este guia, o estado atual será reiniciado.'
},
step1: {
header: 'JavaScript Cliente - Visita Guiada',
text: 'Esse passeio dá em poucos passos uma visão geral como usar este cliente. Primeiro vamos adicionar timeseries do mapa.'
},
step2: {
header: 'Ir para o mapa',
text: 'Aqui vamos alterar a vista para obter um mapa.'
},
step3: {
header: 'Ver o mapa',
text: 'Esta é a visualização do mapa. No mapa você pode ver marcadores ou markergroups.'
},
step4: {
header: 'Mudança Provider',
text: 'Aqui você pode selecionar outro provedor timeseries.'
},
step5: {
header: 'Mostrar localização',
text: 'E aqui você pode localizar o seu dispositivo no mapa.'
},
step6: {
header: 'Lista seleção',
text: 'Aqui você pode selecionar um timeseries fora de listas ordenadas.'
},
step7: {
header: 'Selecione uma estação',
text: 'Por favor, selecione agora uma estação no mapa.'
},
step8: {
header: 'Select timeseries',
text: 'Selecione esta caixa de seleção. Se houver apenas um timeseries para esta estação, a caixa de seleção já está marcada. Agora você pode ir em frente com o botão "OK" para carregar os timeseries.'
},
step9: {
header: 'Entrada Legend',
text: 'Aqui você vê a série temporal acrescentou. Você pode excluir ou localizar a série de tempo ou mudar a cor.'
},
step10: {
header: 'Gráfico',
text: 'Este é o gráfico da série de tempo selecionado.'
},
step11: {
header: 'Alterar o tempo',
text: 'Aqui você pode alterar a extensão do tempo para a sua série de tempo selecionado.'
},
step12: {
header: 'Table View',
text: 'Aqui você tem uma tabela com os valores de dados brutos para sua série de tempo selecionado.'
},
step13: {
header: 'Gestão Favorita',
text: 'As entradas de legenda / timeseries poderiam ser salvos como favoritos. Neste ponto de vista todos os favoritos são listados e poderia ser mantida.'
},
step14: {
header: 'Terminado',
text: 'Bem feito! <br> Este cliente é um produto de <a href="http://52north.org" target="_blank">52 ° Norte GmbH</a> . Você pode encontrar o código fonte no <a href="https://github.com/52North/js-sensorweb-client" target="_blank">GitHub</a> .'
}
},
favorite: {
firstValueAt: 'Primeiro valor em',
lastValueAt: 'Última valor em',
label: 'favorito',
edit: {
header: 'Editar favorito'
},
group: {
add: 'O status '{0}' é adicionado à lista de favoritos.',
exists: 'Esse status ainda existe.',
noTimeseries: 'Atualmente não há timeseries são selecionados.',
notSupported: 'O provedor de uma entrada do status '{0}' não é suportada e não pode ser carregado.'
},
single: {
add: 'Um novo favorito '{0}' é adicionado à lista.',
remove: 'O favorito '{0}' é removido.',
exists: 'Este favorito ainda existe.',
notSupported: 'O provedor do favorito '{0}' não é suportado e não pode ser carregado.'
},
import: {
override: 'Você quer substituir seus favoritos atuais?',
wrongFile: 'Não foi possível ler o arquivo',
noValidJson: 'O arquivo JSON não é válido!',
header: 'Importar favoritos',
text: 'Aqui você pode importar seus favoritos exportados. Basta colar o JSON neste campo de texto:'
},
export: {
header: 'Exportar favoritos',
text: 'Aqui você pode exportar seus favoritos. Basta copiar o JSON fora desta caixa de texto e salvá-lo em um arquivo para importá-lo mais tarde:'
},
error: {
fileApiNotSupported: 'As APIs de arquivos não são totalmente suportados neste browser.'
}
},
inform: {
error: 'Ocorreu um erro:',
warn: 'Lembre-se que:'
}
};
| {
"content_hash": "f391ac73b5d1cbb18453013d97901681",
"timestamp": "",
"source": "github",
"line_count": 247,
"max_line_length": 254,
"avg_line_length": 35.21862348178138,
"alnum_prop": 0.6374295896080009,
"repo_name": "EHJ-52n/js-sensorweb-client",
"id": "4d6f0058d605fd53653bf5375ca7e5cfdf9716cb",
"size": "9502",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/js/i18n/pt.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "45675"
},
{
"name": "HTML",
"bytes": "36595"
},
{
"name": "JavaScript",
"bytes": "998638"
}
],
"symlink_target": ""
} |
"""Unit tests for SDF implementation for DirectRunner."""
from __future__ import absolute_import
from __future__ import division
import logging
import os
import unittest
from builtins import range
import apache_beam as beam
from apache_beam import Create
from apache_beam import DoFn
from apache_beam.io import filebasedsource_test
from apache_beam.io.restriction_trackers import OffsetRange
from apache_beam.io.restriction_trackers import OffsetRestrictionTracker
from apache_beam.pvalue import AsList
from apache_beam.pvalue import AsSingleton
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal_to
from apache_beam.transforms.core import RestrictionProvider
from apache_beam.transforms.trigger import AccumulationMode
from apache_beam.transforms.window import SlidingWindows
from apache_beam.transforms.window import TimestampedValue
class ReadFilesProvider(RestrictionProvider):
def initial_restriction(self, element):
size = os.path.getsize(element)
return OffsetRange(0, size)
def create_tracker(self, restriction):
return OffsetRestrictionTracker(restriction)
class ReadFiles(DoFn):
def __init__(self, resume_count=None):
self._resume_count = resume_count
def process(
self,
element,
restriction_tracker=DoFn.RestrictionParam(ReadFilesProvider()),
*args, **kwargs):
file_name = element
assert isinstance(restriction_tracker, OffsetRestrictionTracker)
with open(file_name, 'rb') as file:
pos = restriction_tracker.start_position()
if restriction_tracker.start_position() > 0:
file.seek(restriction_tracker.start_position() - 1)
line = file.readline()
pos = pos - 1 + len(line)
output_count = 0
while restriction_tracker.try_claim(pos):
line = file.readline()
len_line = len(line)
line = line.strip()
if not line:
break
if line is None:
break
yield line
output_count += 1
if self._resume_count and output_count == self._resume_count:
restriction_tracker.defer_remainder()
break
pos += len_line
class ExpandStringsProvider(RestrictionProvider):
def initial_restriction(self, element):
return OffsetRange(0, len(element[0]))
def create_tracker(self, restriction):
return OffsetRestrictionTracker(restriction)
# No initial split performed.
def split(self, element, restriction):
return [restriction,]
class ExpandStrings(DoFn):
def __init__(self, record_window=False):
self._record_window = record_window
def process(
self, element, side1, side2, side3, window=beam.DoFn.WindowParam,
restriction_tracker=DoFn.RestrictionParam(ExpandStringsProvider()),
*args, **kwargs):
side = []
side.extend(side1)
side.extend(side2)
side.extend(side3)
assert isinstance(restriction_tracker, OffsetRestrictionTracker)
side = list(side)
for i in range(restriction_tracker.start_position(),
restriction_tracker.stop_position()):
if restriction_tracker.try_claim(i):
if not side:
yield (
element[0] + ':' + str(element[1]) + ':' + str(int(window.start))
if self._record_window else element)
else:
for val in side:
ret = (
element[0] + ':' + str(element[1]) + ':' +
str(int(window.start)) if self._record_window else element)
yield ret + ':' + val
else:
break
class SDFDirectRunnerTest(unittest.TestCase):
def setUp(self):
super(SDFDirectRunnerTest, self).setUp()
# Importing following for DirectRunner SDF implemenation for testing.
from apache_beam.runners.direct import transform_evaluator
self._default_max_num_outputs = (
transform_evaluator._ProcessElementsEvaluator.DEFAULT_MAX_NUM_OUTPUTS)
def run_sdf_read_pipeline(
self, num_files, num_records_per_file, resume_count=None):
expected_data = []
file_names = []
for _ in range(num_files):
new_file_name, new_expected_data = filebasedsource_test.write_data(
num_records_per_file)
assert len(new_expected_data) == num_records_per_file
file_names.append(new_file_name)
expected_data.extend(new_expected_data)
assert len(expected_data) > 0
with TestPipeline() as p:
pc1 = (p
| 'Create1' >> beam.Create(file_names)
| 'SDF' >> beam.ParDo(ReadFiles(resume_count)))
assert_that(pc1, equal_to(expected_data))
# TODO(chamikara: verify the number of times process method was invoked
# using a side output once SDFs supports producing side outputs.
def test_sdf_no_checkpoint_single_element(self):
self.run_sdf_read_pipeline(
1,
self._default_max_num_outputs - 1)
def test_sdf_one_checkpoint_single_element(self):
self.run_sdf_read_pipeline(
1,
int(self._default_max_num_outputs + 1))
def test_sdf_multiple_checkpoints_single_element(self):
self.run_sdf_read_pipeline(
1,
int(self._default_max_num_outputs * 3))
def test_sdf_no_checkpoint_multiple_element(self):
self.run_sdf_read_pipeline(
5,
int(self._default_max_num_outputs - 1))
def test_sdf_one_checkpoint_multiple_element(self):
self.run_sdf_read_pipeline(
5,
int(self._default_max_num_outputs + 1))
def test_sdf_multiple_checkpoints_multiple_element(self):
self.run_sdf_read_pipeline(
5,
int(self._default_max_num_outputs * 3))
def test_sdf_with_resume_single_element(self):
resume_count = self._default_max_num_outputs // 10
# Makes sure that resume_count is not trivial.
assert resume_count > 0
self.run_sdf_read_pipeline(
1,
self._default_max_num_outputs - 1,
resume_count)
def test_sdf_with_resume_multiple_elements(self):
resume_count = self._default_max_num_outputs // 10
assert resume_count > 0
self.run_sdf_read_pipeline(
5,
int(self._default_max_num_outputs - 1),
resume_count)
def test_sdf_with_windowed_timestamped_input(self):
with TestPipeline() as p:
result = (p
| beam.Create([1, 3, 5, 10])
| beam.FlatMap(lambda t: [TimestampedValue(('A', t), t),
TimestampedValue(('B', t), t)])
| beam.WindowInto(SlidingWindows(10, 5),
accumulation_mode=AccumulationMode.DISCARDING)
| beam.ParDo(ExpandStrings(record_window=True), [], [], []))
expected_result = [
'A:1:-5', 'A:1:0', 'A:3:-5', 'A:3:0', 'A:5:0', 'A:5:5', 'A:10:5',
'A:10:10', 'B:1:-5', 'B:1:0', 'B:3:-5', 'B:3:0', 'B:5:0', 'B:5:5',
'B:10:5', 'B:10:10',]
assert_that(result, equal_to(expected_result))
def test_sdf_with_side_inputs(self):
with TestPipeline() as p:
side1 = p | 'Create1' >> Create(['1', '2'])
side2 = p | 'Create2' >> Create(['3', '4'])
side3 = p | 'Create3' >> Create(['5'])
result = (p
| 'create_main' >> beam.Create(['a', 'b', 'c'])
| beam.ParDo(ExpandStrings(), AsList(side1), AsList(side2),
AsSingleton(side3)))
expected_result = []
for c in ['a', 'b', 'c']:
for i in range(5):
expected_result.append(c + ':' + str(i+1))
assert_that(result, equal_to(expected_result))
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
unittest.main()
| {
"content_hash": "7778a6e5c8cff6c1e107a99b6e14a310",
"timestamp": "",
"source": "github",
"line_count": 239,
"max_line_length": 80,
"avg_line_length": 32.21757322175732,
"alnum_prop": 0.6338961038961038,
"repo_name": "markflyhigh/incubator-beam",
"id": "946ef342c373dd9354213ac5e3b90e2d706b64e8",
"size": "8485",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdks/python/apache_beam/runners/direct/sdf_direct_runner_test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1596"
},
{
"name": "CSS",
"bytes": "40964"
},
{
"name": "Dockerfile",
"bytes": "22983"
},
{
"name": "FreeMarker",
"bytes": "7428"
},
{
"name": "Go",
"bytes": "2508482"
},
{
"name": "Groovy",
"bytes": "300669"
},
{
"name": "HTML",
"bytes": "54277"
},
{
"name": "Java",
"bytes": "24796055"
},
{
"name": "JavaScript",
"bytes": "16472"
},
{
"name": "Jupyter Notebook",
"bytes": "54182"
},
{
"name": "Python",
"bytes": "4544133"
},
{
"name": "Ruby",
"bytes": "4099"
},
{
"name": "Shell",
"bytes": "180209"
}
],
"symlink_target": ""
} |
#include "DeviceKey.h"
#if DEVICEKEY_ENABLED
#include "mbedtls/cmac.h"
#include "mbedtls/platform.h"
#include "features/storage/kvstore/include/KVStore.h"
#include "features/storage/kvstore/tdbstore/TDBStore.h"
#include "features/storage/kvstore/kv_map/KVMap.h"
#include "features/storage/kvstore/conf/kv_config.h"
#include "mbed_wait_api.h"
#include <stdlib.h>
#include "platform/mbed_error.h"
#include <string.h>
#include "entropy.h"
#include "mbed_trace.h"
#define TRACE_GROUP "DEVKEY"
#if !defined(MBEDTLS_CMAC_C)
#error [NOT_SUPPORTED] MBEDTLS_CMAC_C needs to be enabled for this driver
#else
namespace mbed {
#define DEVKEY_WRITE_UINT32_LE( dst, src ) \
do \
{ \
(dst)[0] = ( (src) >> 0 ) & 0xFF; \
(dst)[1] = ( (src) >> 8 ) & 0xFF; \
(dst)[2] = ( (src) >> 16 ) & 0xFF; \
(dst)[3] = ( (src) >> 24 ) & 0xFF; \
} while( 0 )
#define DEVKEY_WRITE_UINT8_LE( dst, src ) \
do \
{ \
(dst)[0] = (src) & 0xFF; \
} while( 0 )
DeviceKey::DeviceKey()
{
int ret = kv_init_storage_config();
if (ret != MBED_SUCCESS) {
tr_error("DeviceKey: Fail to initialize KvStore configuration.");
}
#if defined(MBEDTLS_PLATFORM_C)
ret = mbedtls_platform_setup(NULL);
if (ret != MBED_SUCCESS) {
tr_error("DeviceKey: Fail in mbedtls_platform_setup.");
}
#endif /* MBEDTLS_PLATFORM_C */
return;
}
DeviceKey::~DeviceKey()
{
#if defined(MBEDTLS_PLATFORM_C)
mbedtls_platform_teardown(NULL);
#endif /* MBEDTLS_PLATFORM_C */
return;
}
int DeviceKey::generate_derived_key(const unsigned char *salt, size_t isalt_size, unsigned char *output,
uint16_t ikey_type)
{
uint32_t key_buff[DEVICE_KEY_32BYTE / sizeof(uint32_t)];
size_t actual_size = DEVICE_KEY_32BYTE;
if (DEVICE_KEY_16BYTE != ikey_type && DEVICE_KEY_32BYTE != ikey_type) {
return DEVICEKEY_INVALID_KEY_TYPE;
}
actual_size = DEVICE_KEY_16BYTE != ikey_type ? DEVICE_KEY_32BYTE : DEVICE_KEY_16BYTE;
//First try to read the key from KVStore
int ret = read_key_from_kvstore(key_buff, actual_size);
if (DEVICEKEY_SUCCESS != ret) {
return ret;
}
ret = get_derived_key(key_buff, actual_size, salt, isalt_size, output, ikey_type);
return ret;
}
int DeviceKey::device_inject_root_of_trust(uint32_t *value, size_t isize)
{
return write_key_to_kvstore(value, isize);
}
int DeviceKey::write_key_to_kvstore(uint32_t *input, size_t isize)
{
if (DEVICE_KEY_16BYTE != isize && DEVICE_KEY_32BYTE != isize) {
return DEVICEKEY_INVALID_KEY_SIZE;
}
//First we read if key exist. If it is exists, we return DEVICEKEY_ALREADY_EXIST error
uint32_t read_key[DEVICE_KEY_32BYTE / sizeof(uint32_t)] = {0};
size_t read_size = DEVICE_KEY_32BYTE;
int ret = read_key_from_kvstore(read_key, read_size);
if (DEVICEKEY_SUCCESS == ret) {
return DEVICEKEY_ALREADY_EXIST;
}
if (DEVICEKEY_NOT_FOUND != ret) {
return ret;
}
KVMap &kv_map = KVMap::get_instance();
KVStore *inner_store = kv_map.get_internal_kv_instance(NULL);
if (inner_store == NULL) {
return DEVICEKEY_SAVE_FAILED;
}
ret = ((TDBStore *)inner_store)->reserved_data_set(input, isize);
if (MBED_ERROR_WRITE_FAILED == ret) {
return DEVICEKEY_SAVE_FAILED;
}
if (MBED_SUCCESS != ret) {
return DEVICEKEY_KVSTORE_UNPREDICTED_ERROR;
}
return DEVICEKEY_SUCCESS;
}
int DeviceKey::read_key_from_kvstore(uint32_t *output, size_t &size)
{
if (size > (uint16_t) -1) {
return DEVICEKEY_INVALID_PARAM;
}
KVMap &kv_map = KVMap::get_instance();
KVStore *inner_store = kv_map.get_internal_kv_instance(NULL);
if (inner_store == NULL) {
return DEVICEKEY_NOT_FOUND;
}
int kvStatus = ((TDBStore *)inner_store)->reserved_data_get(output, size, &size);
if (MBED_ERROR_ITEM_NOT_FOUND == kvStatus) {
return DEVICEKEY_NOT_FOUND;
}
if (MBED_ERROR_READ_FAILED == kvStatus || MBED_ERROR_INVALID_SIZE == kvStatus) {
return DEVICEKEY_READ_FAILED;
}
if (MBED_SUCCESS != kvStatus) {
return DEVICEKEY_KVSTORE_UNPREDICTED_ERROR;
}
return DEVICEKEY_SUCCESS;
}
int DeviceKey::get_derived_key(uint32_t *ikey_buff, size_t ikey_size, const unsigned char *isalt,
size_t isalt_size, unsigned char *output, uint32_t ikey_type)
{
//KDF in counter mode implementation as described in Section 5.1
//of NIST SP 800-108, Recommendation for Key Derivation Using Pseudorandom Functions
int ret;
size_t counter = 0;
char separator = 0x00;
mbedtls_cipher_context_t ctx;
unsigned char output_len_enc[ 4 ] = {0};
unsigned char counter_enc[ 1 ] = {0};
DEVKEY_WRITE_UINT32_LE(output_len_enc, ikey_type);
mbedtls_cipher_type_t mbedtls_cipher_type = MBEDTLS_CIPHER_AES_128_ECB;
if (DEVICE_KEY_32BYTE == ikey_size) {
mbedtls_cipher_type = MBEDTLS_CIPHER_AES_256_ECB;
}
const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_type(mbedtls_cipher_type);
do {
mbedtls_cipher_init(&ctx);
ret = mbedtls_cipher_setup(&ctx, cipher_info);
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_starts(&ctx, (unsigned char *)ikey_buff, ikey_size * 8);
if (ret != 0) {
goto finish;
}
DEVKEY_WRITE_UINT8_LE(counter_enc, (counter + 1));
ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)counter_enc, sizeof(counter_enc));
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_update(&ctx, isalt, isalt_size);
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)&separator, sizeof(char));
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)&output_len_enc, sizeof(output_len_enc));
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_finish(&ctx, output + (DEVICE_KEY_16BYTE * (counter)));
if (ret != 0) {
goto finish;
}
mbedtls_cipher_free(&ctx);
counter++;
} while (DEVICE_KEY_16BYTE * counter < ikey_type);
finish:
if (DEVICEKEY_SUCCESS != ret) {
mbedtls_cipher_free(&ctx);
return DEVICEKEY_ERR_CMAC_GENERIC_FAILURE;
}
return DEVICEKEY_SUCCESS;
}
int DeviceKey::generate_root_of_trust()
{
int ret = DEVICEKEY_GENERATE_RANDOM_ERROR;
uint32_t key_buff[DEVICE_KEY_32BYTE / sizeof(uint32_t)];
size_t actual_size = DEVICE_KEY_32BYTE;
if (read_key_from_kvstore(key_buff, actual_size) == DEVICEKEY_SUCCESS) {
return DEVICEKEY_ALREADY_EXIST;
}
#if defined(DEVICE_TRNG) || defined(MBEDTLS_ENTROPY_NV_SEED) || defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
mbedtls_entropy_context *entropy = new mbedtls_entropy_context;
mbedtls_entropy_init(entropy);
memset(key_buff, 0, actual_size);
ret = mbedtls_entropy_func(entropy, (unsigned char *)key_buff, actual_size);
if (ret != MBED_SUCCESS) {
ret = DEVICEKEY_GENERATE_RANDOM_ERROR;
} else {
ret = DEVICEKEY_SUCCESS;
}
mbedtls_entropy_free(entropy);
delete entropy;
if (ret == DEVICEKEY_SUCCESS) {
ret = device_inject_root_of_trust(key_buff, actual_size);
}
#endif
return ret;
}
} // namespace mbed
#endif
#endif
| {
"content_hash": "27beee3c114045d02b589905cf2db212",
"timestamp": "",
"source": "github",
"line_count": 272,
"max_line_length": 105,
"avg_line_length": 29.448529411764707,
"alnum_prop": 0.5801498127340824,
"repo_name": "kjbracey-arm/mbed",
"id": "8b3e7922ae1d8597c3f2d3c32ea7b010f03e3832",
"size": "8637",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "features/device_key/source/DeviceKey.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "4905917"
},
{
"name": "C",
"bytes": "121674109"
},
{
"name": "C++",
"bytes": "7228843"
},
{
"name": "CMake",
"bytes": "4724"
},
{
"name": "HTML",
"bytes": "1107049"
},
{
"name": "Makefile",
"bytes": "4212"
},
{
"name": "Objective-C",
"bytes": "61382"
},
{
"name": "Python",
"bytes": "1766"
}
],
"symlink_target": ""
} |
@interface BSRecommentViewController : UIViewController
@end
| {
"content_hash": "143cbf5b5b13691770f30d68eb010d63",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 55,
"avg_line_length": 20.666666666666668,
"alnum_prop": 0.8548387096774194,
"repo_name": "zhunjiee/BaiSiBuDeJie",
"id": "823dcdcc63b28dcb237cfe6a7faceeea0ac4e659",
"size": "239",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BaiSiBuDeJie/BaiSiBuDeJie/Classes/FriendTrends(关注)/Controller/BSRecommentViewController.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "54687"
},
{
"name": "Objective-C",
"bytes": "1125292"
},
{
"name": "Objective-C++",
"bytes": "123538"
},
{
"name": "Ruby",
"bytes": "146"
},
{
"name": "Shell",
"bytes": "4937"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/dark_blue"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/fragment_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/fragment_child"
android:textSize="@dimen/text_size_normal" />
</LinearLayout> | {
"content_hash": "73ed6c645f961ed7907b3ab58eb182f3",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 72,
"avg_line_length": 34.21739130434783,
"alnum_prop": 0.6759847522236341,
"repo_name": "mengdd/HelloActivityAndFragment",
"id": "b8c10c5dc137820d0e2c438de21c785c2d1c05ef",
"size": "787",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/toolbar_child_fragment.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "101865"
}
],
"symlink_target": ""
} |
revstack-js
===========
A javascript sdk for the revstack api platform.
| {
"content_hash": "10d1a04910705c8adaccf5964dba18ed",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 47,
"avg_line_length": 18.25,
"alnum_prop": 0.6712328767123288,
"repo_name": "MISInteractive/revstack-js",
"id": "068c4d13e28b3c71a0576cdb1eb9b3446e9b86f4",
"size": "73",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "86842"
}
],
"symlink_target": ""
} |
import { mount, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
import { GlLoadingIcon } from '@gitlab/ui';
import ErrorMessage from '~/ide/components/error_message.vue';
const localVue = createLocalVue();
localVue.use(Vuex);
describe('IDE error message component', () => {
let wrapper;
const setErrorMessageMock = jest.fn();
const createComponent = messageProps => {
const fakeStore = new Vuex.Store({
actions: { setErrorMessage: setErrorMessageMock },
});
wrapper = mount(ErrorMessage, {
propsData: {
message: {
text: 'some text',
actionText: 'test action',
actionPayload: 'testActionPayload',
...messageProps,
},
},
store: fakeStore,
localVue,
});
};
beforeEach(() => {
setErrorMessageMock.mockReset();
});
afterEach(() => {
wrapper.destroy();
wrapper = null;
});
const findDismissButton = () => wrapper.find('button[aria-label=Dismiss]');
const findActionButton = () => wrapper.find('button.gl-alert-action');
it('renders error message', () => {
const text = 'error message';
createComponent({ text });
expect(wrapper.text()).toContain(text);
});
it('clears error message on dismiss click', () => {
createComponent();
findDismissButton().trigger('click');
expect(setErrorMessageMock).toHaveBeenCalledWith(expect.any(Object), null, undefined);
});
describe('with action', () => {
let actionMock;
const message = {
actionText: 'test action',
actionPayload: 'testActionPayload',
};
beforeEach(() => {
actionMock = jest.fn().mockResolvedValue();
createComponent({
...message,
action: actionMock,
});
});
it('renders action button', () => {
const button = findActionButton();
expect(button.exists()).toBe(true);
expect(button.text()).toContain(message.actionText);
});
it('does not show dismiss button', () => {
expect(findDismissButton().exists()).toBe(false);
});
it('dispatches action', () => {
findActionButton().trigger('click');
expect(actionMock).toHaveBeenCalledWith(message.actionPayload);
});
it('does not dispatch action when already loading', () => {
findActionButton().trigger('click');
actionMock.mockReset();
return wrapper.vm.$nextTick(() => {
findActionButton().trigger('click');
return wrapper.vm.$nextTick().then(() => {
expect(actionMock).not.toHaveBeenCalled();
});
});
});
it('shows loading icon when loading', () => {
let resolveAction;
actionMock.mockImplementation(
() =>
new Promise(resolve => {
resolveAction = resolve;
}),
);
findActionButton().trigger('click');
return wrapper.vm.$nextTick(() => {
expect(wrapper.find(GlLoadingIcon).isVisible()).toBe(true);
resolveAction();
});
});
it('hides loading icon when operation finishes', () => {
findActionButton().trigger('click');
return actionMock()
.then(() => wrapper.vm.$nextTick())
.then(() => {
expect(wrapper.find(GlLoadingIcon).isVisible()).toBe(false);
});
});
});
});
| {
"content_hash": "1083d0f9db5c802daac6fc76395ae079",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 90,
"avg_line_length": 26.055118110236222,
"alnum_prop": 0.5871864611665155,
"repo_name": "mmkassem/gitlabhq",
"id": "3a4dcc5873d245fe50c7b910019ad98ec4e3ed1b",
"size": "3309",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/frontend/ide/components/error_message_spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "113683"
},
{
"name": "CoffeeScript",
"bytes": "139197"
},
{
"name": "Cucumber",
"bytes": "119759"
},
{
"name": "HTML",
"bytes": "447030"
},
{
"name": "JavaScript",
"bytes": "29805"
},
{
"name": "Ruby",
"bytes": "2417833"
},
{
"name": "Shell",
"bytes": "14336"
}
],
"symlink_target": ""
} |
#ifndef XML2_PARSE_H_
#define XML2_PARSE_H_
#include <libxml/encoding.h>
#include <libxml/xmlwriter.h>
/**
* Parse using xml2 library.
*
* @param[in] content_p Xml bytes to parse.
* @param[in] lengthInBytes Length in bytes.
* @param[out] parsedLengthInBytes_p Length of result buffer in bytes.
* @return Parsed contents.
*/
xmlChar*
xml2_parse(
const char* content_p,
int lengthInBytes,
int* parsedLengthInBytes_p);
#endif /* XML2_PARSE_H_ */
| {
"content_hash": "c564cccd62cd14af72c53ef687ea8206",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 70,
"avg_line_length": 20.043478260869566,
"alnum_prop": 0.7006507592190889,
"repo_name": "AndersDala/java-libxml2",
"id": "c9bb2f75d6fedd27518e4c5786048b194ed525cf",
"size": "1644",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "se.liu.lysator.dahlberg.libxml2/src/main/c/xml2_parse.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "6273"
},
{
"name": "Java",
"bytes": "21035"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<title>Yoga & Devbootcamp</title>
<meta property="og:title" content="Yoga & Devbootcamp" />
<meta name="twitter:title" content="Yoga & Devbootcamp" />
<meta name="description" content="I never thought this day would come - me with a blog. I somehow doubt that blogging and tweeting will be the only new behaviors I will inherit from this educational adventure called Devbootcamp. This post marks the completion point of week one. The following is my response to a discussion on DBC culture.
I was first introduced to the DBC philosophy in a yoga studio. I’ve been an avid hot yoga practitioner for the past few years.">
<meta property="og:description" content="I never thought this day would come - me with a blog. I somehow doubt that blogging and tweeting will be the only new behaviors I will inherit from this educational adventure called Devbootcamp. This post marks the completion point of week one. The following is my response to a discussion on DBC culture.
I was first introduced to the DBC philosophy in a yoga studio. I’ve been an avid hot yoga practitioner for the past few years.">
<meta name="twitter:description" content="I never thought this day would come - me with a blog. I somehow doubt that blogging and tweeting will be the only new behaviors I will inherit from this educational adventure called Devbootcamp. This …">
<meta name="author" content="Kelly Ripple"/>
<link href='http://kellyripple.com/img/favicon.ico' rel='icon' type='image/x-icon'/>
<meta property="og:image" content="http://kellyripple.com/img/avatar-icon.png" />
<meta name="twitter:image" content="http://kellyripple.com/img/avatar-icon.png" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="@krippleffect" />
<meta name="twitter:creator" content="@krippleffect" />
<meta property="og:url" content="http://kellyripple.com/post/yoga-and-devbootcamp/" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Kelly Ripple" />
<meta name="generator" content="Hugo 0.39" />
<link rel="canonical" href="http://kellyripple.com/post/yoga-and-devbootcamp/" />
<link rel="alternate" href="http://kellyripple.com/index.xml" type="application/rss+xml" title="Kelly Ripple">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css" integrity="sha384-wITovz90syo1dJWVh32uuETPVEtGigN07tkttEqPv+uR2SE/mbQcG7ATL28aI9H0" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="http://kellyripple.com/css/main.css" /><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" />
<link rel="stylesheet" href="http://kellyripple.com/css/highlight.min.css" /><link rel="stylesheet" href="http://kellyripple.com/css/codeblock.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe.min.css" integrity="sha384-h/L2W9KefUClHWaty3SLE5F/qvc4djlyR4qY3NUV5HGQBBW7stbcfff1+I/vmsHh" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/default-skin/default-skin.min.css" integrity="sha384-iD0dNku6PYSIQLyfTOpB06F2KCZJAKLOThS5HRe8b3ibhdEQ6eKsFf/EeFxdOt5R" crossorigin="anonymous">
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
<div class="pswp__bg"></div>
<div class="pswp__scroll-wrap">
<div class="pswp__container">
<div class="pswp__item"></div>
<div class="pswp__item"></div>
<div class="pswp__item"></div>
</div>
<div class="pswp__ui pswp__ui--hidden">
<div class="pswp__top-bar">
<div class="pswp__counter"></div>
<button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
<button class="pswp__button pswp__button--share" title="Share"></button>
<button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
<button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
<div class="pswp__preloader">
<div class="pswp__preloader__icn">
<div class="pswp__preloader__cut">
<div class="pswp__preloader__donut"></div>
</div>
</div>
</div>
</div>
<div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
<div class="pswp__share-tooltip"></div>
</div>
<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
</button>
<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
</button>
<div class="pswp__caption">
<div class="pswp__caption__center"></div>
</div>
</div>
</div>
</div>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top navbar-custom">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="http://kellyripple.com">Kelly Ripple</a>
</div>
<div class="collapse navbar-collapse" id="main-navbar">
<ul class="nav navbar-nav navbar-right">
<li>
<a title="Blog" href="/">Blog</a>
</li>
<li>
<a title="Projects" href="/project">Projects</a>
</li>
<li>
<a title="About" href="/about">About</a>
</li>
<li>
<a title="Tags" href="/tags">Tags</a>
</li>
</ul>
</div>
<div class="avatar-container">
<div class="avatar-img-border">
<a title="Kelly Ripple" href="http://kellyripple.com">
<img class="avatar-img" src="http://kellyripple.com/img/avatar-icon.png" alt="Kelly Ripple" />
</a>
</div>
</div>
</div>
</nav>
<header class="header-section ">
<div class="intro-header no-img">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="post-heading">
<h1>Yoga & Devbootcamp</h1>
<span class="post-meta">
<i class="fa fa-calendar-o"></i> Posted on May 24, 2015
|
<i class="fa fa-clock-o"></i> 2 minutes (308 words)
</span>
</div>
</div>
</div>
</div>
</div>
</header>
<div class="container" role="main">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<article role="main" class="blog-post">
<p>I never thought this day would come - me with a blog. I somehow doubt that blogging and tweeting will be the only new behaviors I will inherit from this educational adventure called Devbootcamp. This post marks the completion point of week one. The following is my response to a discussion on DBC culture.</p>
<p>I was first introduced to the DBC philosophy in a yoga studio. I’ve been an avid hot yoga practitioner for the past few years. I went so far as to obtain a teacher’s certification - 200 hours of the best good sweaty fun that can be had while clothed. For those of you that have never done yoga and/or have no idea where I’m going with this, let me explain! The way you become ‘better’ at yoga is oddly similar to the way DBC would have us become ‘better’ at web development. Ready? I’m going to make a list of advice given to new boots:</p>
<ol>
<li>Come in with the attitude of “This is <em>my</em> time, I’m going to make it awesome”</li>
<li>Know that “This is all one big experiment”</li>
<li>“Bring yourself to the table and believe in others to do the same”</li>
<li>“Come in and MAKE A MESS”</li>
<li>Identify your fears because “Fear will only hold you back”</li>
<li>“We’ll provide the structure and the setting so that you can kick your own ass”</li>
<li>“To succeed, you have to make yourself vulnerable”</li>
<li>“Be motivated, be inspired, and be inspiring”</li>
</ol>
<p>The thing is, all of those phrases would be equally as appropriate if stated in a yoga class. It’s a radical shift from the traditional educational paradigm, that rewards being ‘right’ above being inspired. I find this new paradigm captivating. I truly believe it is the best mindset to have to succeed in … anything, and I’m incredibly grateful to have the opportunity to practice it.</p>
<div class="blog-tags">
<a href="http://kellyripple.com/tags/yoga/">yoga</a>
<a href="http://kellyripple.com/tags/devbootcamp/">devbootcamp</a>
</div>
</article>
<ul class="pager blog-pager">
<li class="next">
<a href="http://kellyripple.com/post/git-vs-github/" data-toggle="tooltip" data-placement="top" title="Git vs. Github">Next Post →</a>
</li>
</ul>
</div>
</div>
</div>
<footer>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<ul class="list-inline text-center footer-links">
<li>
<a href="mailto:[email protected]" title="Email me">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-envelope fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li>
<a href="https://github.com/kripple" title="GitHub">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-github fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li>
<a href="https://twitter.com/krippleffect" title="Twitter">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-twitter fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
</ul>
<p class="credits copyright text-muted">
<a href="kellyripple.com">Kelly Ripple</a>
•
2016
•
<a href="http://kellyripple.com">Kelly Ripple</a>
</p>
<p class="credits theme-by text-muted">
<a href="http://gohugo.io">Hugo v0.39</a> powered • Theme by <a href="http://deanattali.com/beautiful-jekyll/">Beautiful Jekyll</a> adapted to <a href="https://github.com/halogenica/beautifulhugo">Beautiful Hugo</a>
</p>
</div>
</div>
</div>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.js" integrity="sha384-/y1Nn9+QQAipbNQWU65krzJralCnuOasHncUFXGkdwntGeSvQicrYkiUBwsgUqc1" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/contrib/auto-render.min.js" integrity="sha384-dq1/gEHSxPZQ7DdrM82ID4YVol9BYyU7GbWlIwnwyPzotpoc57wDw/guX8EaYGPx" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="http://kellyripple.com/js/main.js"></script>
<script src="http://kellyripple.com/js/highlight.min.js"></script>
<script> hljs.initHighlightingOnLoad(); </script>
<script> $(document).ready(function() {$("pre.chroma").css("padding","0");}); </script><script> renderMathInElement(document.body); </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe.min.js" integrity="sha384-QELNnmcmU8IR9ZAykt67vGr9/rZJdHbiWi64V88fCPaOohUlHCqUD/unNN0BXSqy" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe-ui-default.min.js" integrity="sha384-m67o7SkQ1ALzKZIFh4CiTA8tmadaujiTa9Vu+nqPSwDOqHrDmxLezTdFln8077+q" crossorigin="anonymous"></script>
<script src="http://kellyripple.com/js/load-photoswipe.js"></script>
</body>
</html>
| {
"content_hash": "44d4924321597d36f6feb33ef6886ec5",
"timestamp": "",
"source": "github",
"line_count": 329,
"max_line_length": 591,
"avg_line_length": 42.75987841945289,
"alnum_prop": 0.6347028717657094,
"repo_name": "kripple/blog",
"id": "be05f8fa2a70717dfaa9fd48a49bbc3216613a50",
"size": "14070",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "post/yoga-and-devbootcamp/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23791"
},
{
"name": "HTML",
"bytes": "1145081"
},
{
"name": "JavaScript",
"bytes": "8320"
},
{
"name": "Shell",
"bytes": "748"
}
],
"symlink_target": ""
} |
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { OSharedModule } from '../../../shared/shared.module';
import { ORealInputModule } from '../real-input/o-real-input.module';
import { OCurrencyInputComponent } from './o-currency-input.component';
@NgModule({
declarations: [OCurrencyInputComponent],
imports: [CommonModule, OSharedModule, ORealInputModule],
exports: [OCurrencyInputComponent]
})
export class OCurrencyInputModule { }
| {
"content_hash": "4ada806047ec0c956ea2b235de3063ba",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 71,
"avg_line_length": 37.69230769230769,
"alnum_prop": 0.7428571428571429,
"repo_name": "OntimizeWeb/ontimize-web-ngx",
"id": "c706e923d75bafd3488d789cf66debe275bd05c9",
"size": "490",
"binary": false,
"copies": "2",
"ref": "refs/heads/8.x.x",
"path": "projects/ontimize-web-ngx/src/lib/components/input/currency-input/o-currency-input.module.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "190381"
},
{
"name": "JavaScript",
"bytes": "7594"
},
{
"name": "SCSS",
"bytes": "125972"
},
{
"name": "TypeScript",
"bytes": "1533764"
}
],
"symlink_target": ""
} |
package edu.neu.nutrons.fpmadop;
/**
* A {@link Block} that only runs when a specified {@link Bool} is true.
*
* @author Ziv
*/
public abstract class SometimesBlock extends Block {
private Bool active;
/**
* Creates a {@link Block} that is handled when the given boolean is true.
* @param active The block runs when {@link Bool#getB()} of this is true.
* @param thread The thread to be handled by.
*/
protected SometimesBlock(Bool active, BlockThread thread) {
super(thread);
this.active = active;
}
/**
* Creates a {@link Block} that only does things when the robot is enabled.
* @param thread The thread to be handled by.
*/
protected SometimesBlock(BlockThread thread) {
this(BoolFunc.not(MatchState.Mode.DISABLED), thread);
}
/**
* The method is called repeatedly, but only when as the robot is in its
* specified state. Analogous to {@link Block#handle()}.
*/
protected abstract void sometimesHandle();
protected final void handle() {
if(active.getB()) {
sometimesHandle();
}
}
}
| {
"content_hash": "a70dedb4948361b0659b7009fa0170fe",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 79,
"avg_line_length": 27.829268292682926,
"alnum_prop": 0.6292725679228747,
"repo_name": "vizziv/FPMadOP",
"id": "fbc6e915c474acd043201e515c0c3db761ac5aa4",
"size": "1141",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/edu/neu/nutrons/fpmadop/SometimesBlock.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "75195"
}
],
"symlink_target": ""
} |
Date: Thu, 21 Nov 1996 21:53:19 GMT
Server: NCSA/1.5
Content-type: text/html
<html>
<TITLE> Huang Guang-Rung (Michael)
</TITLE>
<body bgcolor=#FFFFFF>
<CENTER>
<H2> Welcome to Michael's kingdom </H2>
<!-- My New Book<P>
<!WA0><IMG SRC="http://www.cs.bu.edu/students/grads/ghuang/cover3.jpeg" alt="smile.gif" width=300 height=400>
<BR> <BR> -->
<HR>
<!-- <P><H3><EM> A man who is still chasing his
<STRONG> <!WA1><A href="http://www.cs.bu.edu/students/grads/ghuang/dream.html">dream
</A> </STRONG> </EM> </H3> </P> -->
</CENTER>
<center>
<APPLET
CODE="TextScrollerApplet.class" WIDTH=400 HEIGHT=30>
<PARAM NAME=text VALUE="Welcome to my homepage. Please enjoy your trip here...">
<PARAM NAME=speed VALUE="10">
<PARAM NAME=dist VALUE="5">
<PARAM NAME=font VALUE="Arial">
<PARAM NAME=size VALUE="15">
<PARAM NAME=style VALUE="Bold">
<PARAM NAME=alignment VALUE="Center">
<PARAM NAME=textColor VALUE="Blue">
<PARAM NAME=backgroundColor VALUE="ffffff">
</APPLET></center>
<H3>Personal Stuff:</H3><DIR>
<font size=+1>
<LI> <!WA2><A href = "http://www.cs.bu.edu/students/grads/ghuang/wai.html"> Who am I </A>
<LI> <!WA3><A href ="http://www.cs.bu.edu/students/grads/ghuang/research.html"> Current research</A>
<LI> <!WA4><A href ="http://www.cs.bu.edu/students/grads/ghuang/pi.html">More personal information </A>
<LI> <!WA5><A href="http://www.cs.bu.edu/students/grads/ghuang/resume.html"> My
resume </A>
<LI> <!WA6><A href="http://www.cs.bu.edu/students/grads/ghuang/publication.html">
My publications </A>
<LI> <!WA7><A href="http://engc.bu.edu/ECS/labs/kbsp/">My research group</A></font></DIR>
<HR>
<H3>Juliana's Work:</H3><DIR><font size=+1>
<LI><!WA8><A href="http://www.cs.bu.edu/students/grads/ghuang/logo/demo.html">Artemis Logo</A>
<LI><!WA9><A href="http://www.cs.bu.edu/students/grads/ghuang/net/demo.html">NetBenefit Logo</A></DIR></font>
<HR>
<H3>Course of Instruction:</H3><DIR><font size=+1>
<LI>CAS <!WA10><A href="http://www.cs.bu.edu/students/grads/ghuang/cs320/class.html">CS320</A> Programming Language
<LI>CAS <!WA11><A href="http://www.cs.bu.edu/students/grads/ghuang/cs111/class.html">CS111</A> Introduction of Computer Science
<LI>MET <!WA12><A href ="http://www.cs.bu.edu/students/grads/ghuang/class.html">CS301</A> Data Structure
</font>
</DIR>
<HR>
<H3>Misc.</H3><DIR><font size=+1>
<LI> <!WA13><A href = "http://www.cs.bu.edu/students/grads/ghuang/rest.html"> Take a rest </A>
<LI> <!WA14><A href ="http://www.cs.bu.edu/students/grads/ghuang/int.html">Interesting WEB points </A>
<LI> <!WA15><A href = "http://www.cs.bu.edu/students/grads/ghuang/taiwan.html">
Taiwan--My home country</A></font></DIR>
<HR> Last updated on <EM> October 4, 1996.</EM>
<HR>
<H5><!WA16><IMG SRC="http://www.cs.bu.edu/lib/pics/bu-logo.gif"><BR><!WA17><IMG SRC="http://www.cs.bu.edu/lib/pics/bu-label.gif"> <!WA18><A href = "http://web.bu.edu"> Boston University </A>--<!WA19><A HREF = "http://www.cs.bu.edu/"> Computer Science Department</A>
</H5>
<HR>
</body></html>
| {
"content_hash": "e429d258103e7793a59f873f6a1e3997",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 265,
"avg_line_length": 44.55223880597015,
"alnum_prop": 0.6767169179229481,
"repo_name": "ML-SWAT/Web2KnowledgeBase",
"id": "8354dba932187ba9ff89e61ea8443de085101b28",
"size": "2985",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "webkb/student/misc/http:^^www.cs.bu.edu^students^grads^ghuang^Home.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groff",
"bytes": "641"
},
{
"name": "HTML",
"bytes": "34381871"
},
{
"name": "Perl",
"bytes": "14786"
},
{
"name": "Perl6",
"bytes": "18697"
},
{
"name": "Python",
"bytes": "10084"
}
],
"symlink_target": ""
} |
package com.cardinfolink.showmoney.custom.stickyheadersrecyclerview;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
public interface StickyRecyclerHeadersAdapter<VH extends RecyclerView.ViewHolder> {
/**
* Get the ID of the header associated with this item. For example, if your headers group
* items by their first letter, you could return the character representation of the first letter.
* Return a value < 0 if the view should not have a header (like, a header view or footer view)
*
* @param position the position of the view to get the header ID of
* @return the header ID
*/
long getHeaderId(int position);
/**
* Creates a new ViewHolder for a header. This works the same way onCreateViewHolder in
* Recycler.Adapter, ViewHolders can be reused for different views. This is usually a good place
* to inflate the layout for the header.
*
* @param parent the view to create a header view holder for
* @return the view holder
*/
VH onCreateHeaderViewHolder(ViewGroup parent);
/**
* Binds an existing ViewHolder to the specified adapter position.
*
* @param holder the view holder
* @param position the adapter position
*/
void onBindHeaderViewHolder(VH holder, int position);
/**
* @return the number of views in the adapter
*/
int getItemCount();
}
| {
"content_hash": "0ebd498c6f1c6221b371adf448045ac0",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 100,
"avg_line_length": 35.23076923076923,
"alnum_prop": 0.7285298398835517,
"repo_name": "JieJacket/ShowMoney",
"id": "90820064f7de4bf05b2d122ae793babb06030bf0",
"size": "1374",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "stick-headers/src/main/java/com/cardinfolink/showmoney/custom/stickyheadersrecyclerview/StickyRecyclerHeadersAdapter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "207290"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>vst-32: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.1 / vst-32 - 2.7.1</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
vst-32
<small>
2.7.1
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-06 06:03:53 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-06 06:03:53 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.7.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
synopsis: "Verified Software Toolchain"
description: "The software toolchain includes static analyzers to check assertions about your program; optimizing compilers to translate your program to machine language; operating systems and libraries to supply context for your program. The Verified Software Toolchain project assures with machine-checked proofs that the assertions claimed at the top of the toolchain really hold in the machine-language program, running in the operating-system context."
authors: [
"Andrew W. Appel"
"Lennart Beringer"
"Sandrine Blazy"
"Qinxiang Cao"
"Santiago Cuellar"
"Robert Dockins"
"Josiah Dodds"
"Nick Giannarakis"
"Samuel Gruetter"
"Aquinas Hobor"
"Jean-Marie Madiot"
"William Mansky"
]
maintainer: "VST team"
homepage: "http://vst.cs.princeton.edu/"
dev-repo: "git+https://github.com/PrincetonUniversity/VST.git"
bug-reports: "https://github.com/PrincetonUniversity/VST/issues"
license: "https://raw.githubusercontent.com/PrincetonUniversity/VST/master/LICENSE"
build: [
[make "-j%{jobs}%" "BITSIZE=32"]
]
install: [
[make "install" "BITSIZE=32"]
]
depends: [
"ocaml"
"coq" {>= "8.12" & < "8.14"}
"coq-compcert-32" {(= "3.8") | (= "3.8~open-source")}
"coq-flocq" {>= "3.2.1"}
]
tags: [
"category:Computer Science/Semantics and Compilation/Semantics"
"keyword:C"
"logpath:VST"
"date:2020-12-20"
]
url {
src: "https://github.com/PrincetonUniversity/VST/archive/v2.7.1.tar.gz"
checksum: "sha512=cf8ab6bee5322a938859feaeb292220a32c5fa966f5fe183154ca0b6f6cb04129b5cb2c669af0ff1d95f6e962119f9eb0670c1b5150a62205c003650c625e455"
}
</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-vst-32.2.7.1 coq.8.7.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1).
The following dependencies couldn't be met:
- coq-vst-32 -> coq-compcert-32 (= 3.8 & = 3.8~open-source) -> coq >= 8.8.0 -> ocaml >= 4.09.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-vst-32.2.7.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "6e3d97180b315ab28f662abcf8bcc0ad",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 467,
"avg_line_length": 42.096774193548384,
"alnum_prop": 0.5670498084291188,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "ac3ab1183bfa0fa4029d8f39d9a8d4fb0f8b552d",
"size": "7855",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.07.1-2.0.6/released/8.7.1/vst-32/2.7.1.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
"""Helper methods for creating & verifying XSRF tokens."""
__authors__ = [
'"Doug Coker" <[email protected]>',
'"Joe Gregorio" <[email protected]>',
]
import base64
import hmac
import os # for urandom
import time
from oauth2client import util
# Delimiter character
DELIMITER = ':'
# 1 hour in seconds
DEFAULT_TIMEOUT_SECS = 1*60*60
@util.positional(2)
def generate_token(key, user_id, action_id="", when=None):
"""Generates a URL-safe token for the given user, action, time tuple.
Args:
key: secret key to use.
user_id: the user ID of the authenticated user.
action_id: a string identifier of the action they requested
authorization for.
when: the time in seconds since the epoch at which the user was
authorized for this action. If not set the current time is used.
Returns:
A string XSRF protection token.
"""
when = when or int(time.time())
digester = hmac.new(key)
digester.update(str(user_id))
digester.update(DELIMITER)
digester.update(action_id)
digester.update(DELIMITER)
digester.update(str(when))
digest = digester.digest()
token = base64.urlsafe_b64encode('%s%s%d' % (digest,
DELIMITER,
when))
return token
@util.positional(3)
def validate_token(key, token, user_id, action_id="", current_time=None):
"""Validates that the given token authorizes the user for the action.
Tokens are invalid if the time of issue is too old or if the token
does not match what generateToken outputs (i.e. the token was forged).
Args:
key: secret key to use.
token: a string of the token generated by generateToken.
user_id: the user ID of the authenticated user.
action_id: a string identifier of the action they requested
authorization for.
Returns:
A boolean - True if the user is authorized for the action, False
otherwise.
"""
if not token:
return False
try:
decoded = base64.urlsafe_b64decode(str(token))
token_time = long(decoded.split(DELIMITER)[-1])
except (TypeError, ValueError):
return False
if current_time is None:
current_time = time.time()
# If the token is too old it's not valid.
if current_time - token_time > DEFAULT_TIMEOUT_SECS:
return False
# The given token should match the generated one with the same time.
expected_token = generate_token(key, user_id, action_id=action_id,
when=token_time)
if len(token) != len(expected_token):
return False
# Perform constant time comparison to avoid timing attacks
different = 0
for x, y in zip(token, expected_token):
different |= ord(x) ^ ord(y)
if different:
return False
return True
| {
"content_hash": "92d60b5ff449fabd6fb7d3614b4ee141",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 74,
"avg_line_length": 29.896907216494846,
"alnum_prop": 0.636551724137931,
"repo_name": "jmgirven/warehouse",
"id": "abc466a0e56d547066565f65ba0640eda10bc246",
"size": "3506",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "oauth2client/xsrfutil.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "1127"
},
{
"name": "Python",
"bytes": "420100"
}
],
"symlink_target": ""
} |
<div class="main-content archive-page clearfix">
<div class="categorys-item">
#for(archive : archives)
<div class="categorys-title">${archive.dateStr}</div>
<div class="post-lists">
<div class="post-lists-body">
#for(article : archive.articles)
<div class="post-list-item">
<div class="post-list-item-container">
<div class="item-label">
<div class="item-title">
<a href="${(permalink())}">${title()}</a>
</div>
<div class="item-meta clearfix">
<div class="item-meta-date">发布于 ${created('yyyy-MM-dd')}</div>
</div>
</div>
</div>
</div>
#end
</div>
</div>
#end
</div>
</div>
#include('./partial/footer.html') | {
"content_hash": "0d798df9c0e2260fbd14c6fb2fe10428",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 94,
"avg_line_length": 38.73076923076923,
"alnum_prop": 0.4011916583912612,
"repo_name": "otale/tale",
"id": "e7aadd5e98ae874eb6ee4bde702941e97d5f0898",
"size": "1072",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/resources/templates/themes/default/archives.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "399583"
},
{
"name": "JavaScript",
"bytes": "950000"
},
{
"name": "Shell",
"bytes": "4068"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/BindingSample.iml" filepath="$PROJECT_DIR$/BindingSample.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
</modules>
</component>
</project> | {
"content_hash": "f56983cf6c410033756fa7da8e9c02dc",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 108,
"avg_line_length": 40.333333333333336,
"alnum_prop": 0.6666666666666666,
"repo_name": "Saint1991/BindingSample",
"id": "c5777dff472ca77e309c00757992ed22b035ea62",
"size": "363",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/modules.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1348"
},
{
"name": "Kotlin",
"bytes": "2710"
}
],
"symlink_target": ""
} |
[uigesturerecognizer](../../index.md) / [it.sephiroth.android.library.uigestures](../index.md) / [UIGestureRecognizerDelegate](index.md) / [removeGestureRecognizer](./remove-gesture-recognizer.md)
# removeGestureRecognizer
`fun removeGestureRecognizer(recognizer: `[`UIGestureRecognizer`](../-u-i-gesture-recognizer/index.md)`): `[`Boolean`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
### Parameters
`recognizer` - remove a previously added gesture recognizer
**Return**
true if succesfully removed from the list
**Since**
1.0.0
| {
"content_hash": "88607671ea6f2521e3d8587646b3c45b",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 196,
"avg_line_length": 35.375,
"alnum_prop": 0.7544169611307421,
"repo_name": "sephiroth74/AndroidUIGestureRecognizer",
"id": "0effdacd206cfbf69d3da71d0dc66d284b6ef6a1",
"size": "566",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/it.sephiroth.android.library.uigestures/-u-i-gesture-recognizer-delegate/remove-gesture-recognizer.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "3549"
},
{
"name": "Kotlin",
"bytes": "250812"
},
{
"name": "Shell",
"bytes": "3096"
}
],
"symlink_target": ""
} |
<?php
include_once('../../config/config.inc.php');
include_once('../../init.php');
include_once('../../modules/shopimporter/shopimporter.php');
$moduleName = Tools::getValue('moduleName');
if (!Tools::getValue('ajax') || Tools::getValue('token') != sha1(_COOKIE_KEY_.'ajaxShopImporter') || (!empty($moduleName) && !ctype_alnum($moduleName)))
die;
$className = Tools::getValue('className');
$getMethod = Tools::getValue('getMethod');
$limit = Tools::getValue('limit');
$nbr_import = Tools::getValue('nbr_import');
$server = Tools::getValue('server');
$user = Tools::getValue('user');
$password = Tools::getValue('password');
$database = Tools::getValue('database');
$prefix = Tools::getValue('prefix');
$save = Tools::getValue('save');
$url = Tools::getValue('url');
$loginws = Tools::getValue('loginws');
$apikey = Tools::getValue('apikey');
if (Tools::isSubmit('checkAndSaveConfig'))
{
//cleans the database if an import has already been done
$shop_importer = new shopImporter();
foreach($shop_importer->supportedImports as $key => $import)
if (array_key_exists('alterTable', $import))
$columns = Db::getInstance()->executeS('SHOW COLUMNS FROM `'._DB_PREFIX_.bqSQL($import['table']).'`');
foreach ($columns as $column)
if ($column['Field'] == $import['identifier'].'_'.$moduleName)
Db::getInstance()->execute('ALTER IGNORE TABLE `'._DB_PREFIX_.bqSQL($import['table']).'` DROP `'.bqSQL($import['identifier'].'_'.$moduleName).'`');
if ($link = @mysql_connect(Tools::getValue('server'), Tools::getValue('user'), Tools::getValue('password')))
{
if (!@mysql_select_db(Tools::getValue('database'), $link))
die('{"hasError" : true, "error" : ["'.$shop_importer->l('The database selection cannot be made.', 'ajax').'"]}');
else
{
@mysql_close($link);
die('{"hasError" : false, "error" : []}');
}
}
else
die('{"hasError" : true, "error" : ["'.$shop_importer->l('Link to database cannot be established.', 'ajax').'"]}');
}
if (Tools::isSubmit('getData') || Tools::isSubmit('syncLang') || Tools::isSubmit('syncCurrency'))
{
if (Tools::isSubmit('syncLang'))
$save = true;
if (file_exists('../../modules/'.$moduleName.'/'.$moduleName.'.php'))
{
require_once('../../modules/'.$moduleName.'/'.$moduleName.'.php');
$importModule = new $moduleName();
$importModule->server = $server;
$importModule->user = $user;
$importModule->passwd = $password;
$importModule->database = $database;
$importModule->prefix = $prefix;
if (!method_exists($importModule, $getMethod))
die('{"hasError" : true, "error" : ["not_exist"], "datas" : []}');
else
{
$return = call_user_func_array(array($importModule, $getMethod), array($limit, $nbr_import));
$shop_importer = new shopImporter();
$shop_importer->genericImport($className, $return, (bool)$save);
}
}
}
if (Tools::isSubmit('getDataWS') || Tools::isSubmit('syncLangWS') || Tools::isSubmit('syncCurrencyWS'))
{
if (Tools::isSubmit('syncLangWS'))
$save = true;
if (file_exists('../../modules/'.$moduleName.'/'.$moduleName.'.php'))
{
require_once('../../modules/'.$moduleName.'/'.$moduleName.'.php');
try
{
$importModule = new $moduleName();
$importModule->connect($url,$loginws,$apikey);
if (!method_exists($importModule, $getMethod))
die('{"hasError" : true, "error" : ["not_exist"], "datas" : []}');
else
{
$return = call_user_func_array(array($importModule, $getMethod), array($limit, $nbr_import));
$shop_importer = new shopImporter();
$shop_importer->genericImport($className, $return, (bool)$save);
}
die('{"hasError" : false, "error" : []}');
} catch (Exception $e)
{
die('{"hasError" : true, "error" : ['.json_encode($e->getMessage()).'], "datas" : []}');
}
}
}
if (Tools::isSubmit('truncatTable'))
{
$shop_importer = new shopImporter();
if ($shop_importer->truncateTable($className))
die('{"hasError" : false, "error" : []}');
else
die('{"hasError" : true, "error" : ["'.$className.'"]}');
}
if (Tools::isSubmit('alterTable'))
{
$shop_importer = new shopImporter();
if ($shop_importer->alterTable($className))
die('{"hasError" : false, "error" : []}');
else
die('{"hasError" : true, "error" : ["'.$className.'"]}');
}
if (Tools::isSubmit('displaySpecificOptions'))
{
if (file_exists('../../modules/'.$moduleName.'/'.$moduleName.'.php'))
{
$shop_importer = new shopImporter();
require_once('../../modules/'.$moduleName.'/'.$moduleName.'.php');
$importModule = new $moduleName();
$importModule->server = $server;
$importModule->user = $user;
$importModule->passwd = $password;
$importModule->database = $database;
$importModule->prefix = $prefix;
if ($link = @mysql_connect(Tools::getValue('server'), Tools::getValue('user'), Tools::getValue('password')))
{
if(!@mysql_select_db(Tools::getValue('database'), $link))
die($shop_importer->l('The database selection cannot be made.', 'ajax'));
elseif (method_exists($importModule, 'displaySpecificOptions'))
die($importModule->displaySpecificOptions());
else
die('not_exist');
}
else
die($shop_importer->l('Link to database cannot be established.', 'ajax'));
}
}
elseif (Tools::isSubmit('displaySpecificOptionsWsdl'))
{
if (file_exists('../../modules/'.$moduleName.'/'.$moduleName.'.php'))
{
require_once('../../modules/'.$moduleName.'/'.$moduleName.'.php');
$importModule = new $moduleName();
try
{
if (method_exists($importModule, 'displaySpecificOptions'))
die($importModule->displaySpecificOptions());
else
die('not_exist');
} catch (Exception $e)
{
die('{"hasError" : true, "error" : ['.json_encode($e->getMessage()).'], "datas" : []}');
}
}
}
if (Tools::isSubmit('connexionWs'))
{
if (file_exists('../../modules/'.$moduleName.'/'.$moduleName.'.php'))
{
require_once('../../modules/'.$moduleName.'/'.$moduleName.'.php');
try
{
$importModule = new $moduleName();
$importModule->connect($url,$loginws,$apikey);
die('{"hasError" : false, "error" : []}');
} catch (Exception $e)
{
die('{"hasError" : true, "error" : ['.json_encode($e->getMessage()).'], "datas" : []}');
}
}
}
if (Tools::isSubmit('validateSpecificOptions'))
{
if (file_exists('../../modules/'.$moduleName.'/'.$moduleName.'.php'))
{
require_once('../../modules/'.$moduleName.'/'.$moduleName.'.php');
$importModule = new $moduleName();
if (!method_exists($importModule, 'validateSpecificOptions'))
die('{"hasError" : true, "error" : ["not_exist"]}');
else
die($importModule->validateSpecificOptions());
}
}
if (Tools::isSubmit('displayConfigConnector'))
{
if (file_exists('../../modules/'.$moduleName.'/'.$moduleName.'.php'))
{
require_once('../../modules/'.$moduleName.'/'.$moduleName.'.php');
$importModule = new $moduleName();
if (!method_exists($importModule, 'displayConfigConnector'))
die('{"hasError" : true, "error" : ["not_exist"]}');
else
die($importModule->displayConfigConnector());
}
}
?> | {
"content_hash": "a750d3ed756968e59c832e6108b3a454",
"timestamp": "",
"source": "github",
"line_count": 214,
"max_line_length": 153,
"avg_line_length": 32.61214953271028,
"alnum_prop": 0.6260209199025648,
"repo_name": "timetre/tnk",
"id": "ccd53b5184e2adb981a445b6120f0f94c5355473",
"size": "6979",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "web/store/modules/shopimporter/ajax.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "863646"
},
{
"name": "JavaScript",
"bytes": "4442642"
},
{
"name": "PHP",
"bytes": "18308589"
}
],
"symlink_target": ""
} |
package org.cagrid.cds.wsrf.stubs;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import gov.nih.nci.cagrid.metadata.ServiceMetadata;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{gme://caGrid.caBIG/1.0/gov.nih.nci.cagrid.metadata}ServiceMetadata"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"serviceMetadata"
})
@XmlRootElement(name = "CredentialDelegationServiceResourceProperties")
public class CredentialDelegationServiceResourceProperties
implements Serializable
{
@XmlElement(name = "ServiceMetadata", namespace = "gme://caGrid.caBIG/1.0/gov.nih.nci.cagrid.metadata", required = true)
protected ServiceMetadata serviceMetadata;
/**
* Gets the value of the serviceMetadata property.
*
* @return
* possible object is
* {@link gov.nih.nci.cagrid.metadata.ServiceMetadata }
*
*/
public ServiceMetadata getServiceMetadata() {
return serviceMetadata;
}
/**
* Sets the value of the serviceMetadata property.
*
* @param value
* allowed object is
* {@link gov.nih.nci.cagrid.metadata.ServiceMetadata }
*
*/
public void setServiceMetadata(ServiceMetadata value) {
this.serviceMetadata = value;
}
}
| {
"content_hash": "1447fa02d18c8bcad9d3251de50fff5b",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 124,
"avg_line_length": 28.029411764705884,
"alnum_prop": 0.6810073452256034,
"repo_name": "NCIP/cagrid2",
"id": "6e50949245ea59eff7738bdee7548785dd396213",
"size": "1906",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cagrid-cds/cagrid-cds-api/src/main/java/org/cagrid/cds/wsrf/stubs/CredentialDelegationServiceResourceProperties.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "12022"
},
{
"name": "Java",
"bytes": "10516824"
},
{
"name": "Perl",
"bytes": "780"
},
{
"name": "Shell",
"bytes": "463"
},
{
"name": "XSLT",
"bytes": "9477"
}
],
"symlink_target": ""
} |
@interface WeiboPrepareViewController : BasicTableViewController
+(id) createWithURL:(NSURL*) sourceURL;
@end
| {
"content_hash": "49ca8ae3471835e79aa6f54200c384d8",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 64,
"avg_line_length": 36.666666666666664,
"alnum_prop": 0.8272727272727273,
"repo_name": "noolua/xImage",
"id": "3770914873f2350f471fe62daec753636beb3e00",
"size": "239",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xImage/WeiboPrepareViewController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "155"
},
{
"name": "Matlab",
"bytes": "138142"
},
{
"name": "Objective-C",
"bytes": "121599"
}
],
"symlink_target": ""
} |
export { default, getFlat } from '@datahub/utils/helpers/get-flat';
| {
"content_hash": "bb47a04155b582a153707100c3cc4ccd",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 67,
"avg_line_length": 68,
"alnum_prop": 0.7352941176470589,
"repo_name": "mars-lan/WhereHows",
"id": "aedf97c0d9d34434a1d4244806512a2c55ec8b30",
"size": "68",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "datahub-web/@datahub/utils/app/helpers/get-flat.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "104402"
},
{
"name": "Dockerfile",
"bytes": "2521"
},
{
"name": "HTML",
"bytes": "125023"
},
{
"name": "Java",
"bytes": "1431842"
},
{
"name": "JavaScript",
"bytes": "173397"
},
{
"name": "Python",
"bytes": "1419332"
},
{
"name": "Shell",
"bytes": "2470"
},
{
"name": "TypeScript",
"bytes": "559600"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<!--
~ Copyright 2015 JBoss, by Red Hat, Inc
~
~ 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.
-->
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.uberfire</groupId>
<artifactId>uberfire-commons-editor</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>uberfire-commons-editor-client</artifactId>
<name>Uberfire Commons Editor Client</name>
<description>Uberfire Commons Editor Client</description>
<dependencies>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
</dependency>
<dependency>
<groupId>org.jboss.errai</groupId>
<artifactId>errai-common</artifactId>
</dependency>
<dependency>
<groupId>org.jboss.errai</groupId>
<artifactId>errai-ioc</artifactId>
</dependency>
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-user</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.uberfire</groupId>
<artifactId>uberfire-commons-editor-api</artifactId>
</dependency>
<dependency>
<groupId>org.uberfire</groupId>
<artifactId>uberfire-api</artifactId>
</dependency>
<dependency>
<groupId>org.uberfire</groupId>
<artifactId>uberfire-client-all</artifactId>
</dependency>
<dependency>
<groupId>org.uberfire</groupId>
<artifactId>uberfire-client-api</artifactId>
</dependency>
<dependency>
<groupId>org.uberfire</groupId>
<artifactId>uberfire-workbench-client</artifactId>
</dependency>
<dependency>
<groupId>org.gwtbootstrap3</groupId>
<artifactId>gwtbootstrap3</artifactId>
</dependency>
<dependency>
<groupId>org.uberfire</groupId>
<artifactId>uberfire-widgets-commons</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.gwt.gwtmockito</groupId>
<artifactId>gwtmockito</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.uberfire</groupId>
<artifactId>uberfire-testing-utils</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
| {
"content_hash": "4613ffb4d16c8891c8921ef66e2e38bf",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 102,
"avg_line_length": 30.623762376237625,
"alnum_prop": 0.6766892984157775,
"repo_name": "kiereleaseuser/uberfire",
"id": "80fcb836e5651e4bcf739aeea84fe5c365946ee4",
"size": "3093",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "uberfire-extensions/uberfire-commons-editor/uberfire-commons-editor-client/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "71593"
},
{
"name": "FreeMarker",
"bytes": "45795"
},
{
"name": "HTML",
"bytes": "84136"
},
{
"name": "Java",
"bytes": "11055660"
},
{
"name": "JavaScript",
"bytes": "78660"
},
{
"name": "Shell",
"bytes": "1601"
}
],
"symlink_target": ""
} |
require 'java'
# Ruby-friendly extensions to the Servlet API.
module Java::JavaxServlet::ServletContext
# Fetch an attribute from the servlet context.
def [](key)
getAttribute(key.to_s)
end
# Set an attribute in the servlet context.
def []=(key, val)
setAttribute(key.to_s, val)
end
# Remove an attribute for the given key.
def delete(key)
removeAttribute(key.to_s)
end
# Retrieve all the attribute names (keys).
# like Hash#keys
def keys
getAttributeNames.to_a
end
# like Hash#values
def values
getAttributeNames.map { |name| getAttribute(name) }
end
# Iterate over every attribute name/value pair from the context.
# like Hash#each
def each
getAttributeNames.each { |name| yield(name, getAttribute(name)) }
end
end
module Java::JavaxServlet::ServletRequest
# Fetch an attribute from the servlet request.
def [](key)
getAttribute(key.to_s)
end
# Set an attribute in the servlet request.
def []=(key, val)
setAttribute(key.to_s, val)
end
# Remove an attribute for the given key.
def delete(key)
removeAttribute(key.to_s)
end
# Retrieve all the attribute names (keys) from the servlet request.
# like Hash#keys
def keys
getAttributeNames.to_a
end
# like Hash#values
def values
getAttributeNames.map { |name| getAttribute(name) }
end
# Iterate over every attribute name/value pair from the servlet request.
# like Hash#each
def each
getAttributeNames.each { |name| yield(name, getAttribute(name)) }
end
end
module Java::JavaxServletHttp::HttpSession
# Fetch an attribute from the session.
def [](key)
getAttribute(key.to_s)
end
# Set an attribute in the session.
def []=(key, val)
setAttribute(key.to_s, val)
end
# Remove an attribute for the given key.
def delete(key)
removeAttribute(key.to_s)
end
# Retrieve all the attribute names (keys) from the session.
# like Hash#keys
def keys
getAttributeNames.to_a
end
# like Hash#values
def values
getAttributeNames.map { |name| getAttribute(name) }
end
# Iterate over every attribute name/value pair from the session.
# like Hash#each
def each
getAttributeNames.each { |name| yield(name, getAttribute(name)) }
end
end
| {
"content_hash": "cdbcfccb6e7c754e9bbc1113061b90f8",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 74,
"avg_line_length": 25.08888888888889,
"alnum_prop": 0.6984056687333924,
"repo_name": "janrain/jruby-rack",
"id": "4df3b62e9152ce88b7acdc1a5a72e5190a838671",
"size": "2455",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/ruby/jruby/rack/servlet_ext.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "301129"
},
{
"name": "JavaScript",
"bytes": "22880"
},
{
"name": "Ruby",
"bytes": "503364"
},
{
"name": "Shell",
"bytes": "5705"
}
],
"symlink_target": ""
} |
<?php
namespace DTS\eBaySDK\MerchantData\Types;
/**
*
* @property \DTS\eBaySDK\MerchantData\Types\BotBlockRequestType $BotBlock
* @property \DTS\eBaySDK\MerchantData\Enums\DetailLevelCodeType[] $DetailLevel
* @property string $EndUserIP
* @property \DTS\eBaySDK\MerchantData\Enums\ErrorHandlingCodeType $ErrorHandling
* @property string $ErrorLanguage
* @property string $InvocationID
* @property string $MessageID
* @property string[] $OutputSelector
* @property \DTS\eBaySDK\MerchantData\Types\CustomSecurityHeaderType $RequesterCredentials
* @property \DTS\eBaySDK\MerchantData\Types\XMLRequesterCredentialsType $RequesterCredentials
* @property \DTS\eBaySDK\MerchantData\Types\XMLRequesterCredentialsType $RequesterCredentials
* @property string $Version
* @property \DTS\eBaySDK\MerchantData\Enums\WarningLevelCodeType $WarningLevel
*/
class AbstractRequestType extends \DTS\eBaySDK\Types\BaseType
{
/**
* @var array Properties belonging to objects of this class.
*/
private static $propertyTypes = array(
'BotBlock' => array(
'type' => 'DTS\eBaySDK\MerchantData\Types\BotBlockRequestType',
'unbound' => false,
'attribute' => false,
'elementName' => 'BotBlock'
),
'DetailLevel' => array(
'type' => 'string',
'unbound' => true,
'attribute' => false,
'elementName' => 'DetailLevel'
),
'EndUserIP' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'EndUserIP'
),
'ErrorHandling' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'ErrorHandling'
),
'ErrorLanguage' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'ErrorLanguage'
),
'InvocationID' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'InvocationID'
),
'MessageID' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'MessageID'
),
'OutputSelector' => array(
'type' => 'string',
'unbound' => true,
'attribute' => false,
'elementName' => 'OutputSelector'
),
'RequesterCredentials' => array(
'type' => 'DTS\eBaySDK\MerchantData\Types\CustomSecurityHeaderType',
'unbound' => false,
'attribute' => false,
'elementName' => 'RequesterCredentials'
),
'RequesterCredentials' => array(
'type' => 'DTS\eBaySDK\MerchantData\Types\XMLRequesterCredentialsType',
'unbound' => false,
'attribute' => false,
'elementName' => 'RequesterCredentials'
),
'RequesterCredentials' => array(
'type' => 'DTS\eBaySDK\MerchantData\Types\XMLRequesterCredentialsType',
'unbound' => false,
'attribute' => false,
'elementName' => 'RequesterCredentials'
),
'Version' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'Version'
),
'WarningLevel' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'WarningLevel'
)
);
/**
* @param array $values Optional properties and values to assign to the object.
*/
public function __construct(array $values = array())
{
list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);
parent::__construct($parentValues);
if (!array_key_exists(__CLASS__, self::$properties)) {
self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
}
if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
self::$xmlNamespaces[__CLASS__] = 'urn:ebay:apis:eBLBaseComponents';
}
$this->setValues(__CLASS__, $childValues);
}
}
| {
"content_hash": "3a3d6d45375a98df24a9462dec988fdb",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 116,
"avg_line_length": 34.69291338582677,
"alnum_prop": 0.5535633227417158,
"repo_name": "davidtsadler/ebay-sdk-merchant-data",
"id": "25b85aafc95521ec9643e9db6b076047bf10d246",
"size": "5136",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/DTS/eBaySDK/MerchantData/Types/AbstractRequestType.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "1975"
},
{
"name": "PHP",
"bytes": "1375723"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (C) 2018 V12 Technology Ltd.
This program is free software: you can redistribute it and/or modify
it under the terms of the Server Side Public License, version 1,
as published by MongoDB, Inc.
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
Server Side Public License for more details.
You should have received a copy of the Server Side Public License
along with this program. If not, see
<http://www.mongodb.com/licensing/server-side-public-license>.
-->
<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>
<groupId>com.fluxtion.example</groupId>
<artifactId>unplugged.parentpom</artifactId>
<name>unplugged :: parent pom</name>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.fluxtion</groupId>
<artifactId>compiler</artifactId>
<version>6.0.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
| {
"content_hash": "d375bc0ade57e07276eacf2633391a73",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 204,
"avg_line_length": 38.18604651162791,
"alnum_prop": 0.6900121802679658,
"repo_name": "v12technology/fluxtion-examples",
"id": "cc5d961145b99660f47b981d32237957ca5e18b8",
"size": "1642",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "unplugged/parentpom/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "38927"
}
],
"symlink_target": ""
} |
<?php
namespace App\Interfaces;
interface AppInterface {
public function __construct();
public function init();
}
| {
"content_hash": "f0f1ca0faceff30ae6e8164d30ca4236",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 32,
"avg_line_length": 13.444444444444445,
"alnum_prop": 0.71900826446281,
"repo_name": "Bajtlamer/wbengine-slim",
"id": "9e27236d19e1328e304b116e50f8ef2d195de8a0",
"size": "121",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "App/Src/Interfaces/AppInterface.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1054"
},
{
"name": "PHP",
"bytes": "4289"
},
{
"name": "Smarty",
"bytes": "6054"
}
],
"symlink_target": ""
} |
<?php
/**
* @see Zend_Gdata_Media
*/
require_once 'Zend/Gdata/Media.php';
/**
* @see Zend_Gdata_YouTube_VideoEntry
*/
require_once 'Zend/Gdata/YouTube/VideoEntry.php';
/**
* @see Zend_Gdata_YouTube_VideoFeed
*/
require_once 'Zend/Gdata/YouTube/VideoFeed.php';
/**
* @see Zend_Gdata_YouTube_CommentFeed
*/
require_once 'Zend/Gdata/YouTube/CommentFeed.php';
/**
* @see Zend_Gdata_YouTube_PlaylistListFeed
*/
require_once 'Zend/Gdata/YouTube/PlaylistListFeed.php';
/**
* @see Zend_Gdata_YouTube_SubscriptionFeed
*/
require_once 'Zend/Gdata/YouTube/SubscriptionFeed.php';
/**
* @see Zend_Gdata_YouTube_ContactFeed
*/
require_once 'Zend/Gdata/YouTube/ContactFeed.php';
/**
* @see Zend_Gdata_YouTube_PlaylistVideoFeed
*/
require_once 'Zend/Gdata/YouTube/PlaylistVideoFeed.php';
/**
* @see Zend_Gdata_YouTube_ActivityFeed
*/
require_once 'Zend/Gdata/YouTube/ActivityFeed.php';
/**
* @see Zend_Gdata_YouTube_InboxFeed
*/
require_once 'Zend/Gdata/YouTube/InboxFeed.php';
/**
* Service class for interacting with the YouTube Data API.
* @link http://code.google.com/apis/youtube/
*
* @category Zend
* @package Zend_Gdata
* @subpackage YouTube
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_YouTube extends Zend_Gdata_Media
{
const AUTH_SERVICE_NAME = 'youtube';
const CLIENTLOGIN_URL = 'https://www.google.com/youtube/accounts/ClientLogin';
const STANDARD_TOP_RATED_URI = 'https://gdata.youtube.com/feeds/api/standardfeeds/top_rated';
const STANDARD_MOST_VIEWED_URI = 'https://gdata.youtube.com/feeds/api/standardfeeds/most_viewed';
const STANDARD_RECENTLY_FEATURED_URI = 'https://gdata.youtube.com/feeds/api/standardfeeds/recently_featured';
const STANDARD_WATCH_ON_MOBILE_URI = 'https://gdata.youtube.com/feeds/api/standardfeeds/watch_on_mobile';
const STANDARD_TOP_RATED_URI_V2 =
'https://gdata.youtube.com/feeds/api/standardfeeds/top_rated';
const STANDARD_MOST_VIEWED_URI_V2 =
'https://gdata.youtube.com/feeds/api/standardfeeds/most_viewed';
const STANDARD_RECENTLY_FEATURED_URI_V2 =
'https://gdata.youtube.com/feeds/api/standardfeeds/recently_featured';
const STANDARD_WATCH_ON_MOBILE_URI_V2 =
'https://gdata.youtube.com/feeds/api/standardfeeds/watch_on_mobile';
const USER_URI = 'https://gdata.youtube.com/feeds/api/users';
const VIDEO_URI = 'https://gdata.youtube.com/feeds/api/videos';
const PLAYLIST_REL = 'http://gdata.youtube.com/schemas/2007#playlist';
const USER_UPLOADS_REL = 'http://gdata.youtube.com/schemas/2007#user.uploads';
const USER_PLAYLISTS_REL = 'http://gdata.youtube.com/schemas/2007#user.playlists';
const USER_SUBSCRIPTIONS_REL = 'http://gdata.youtube.com/schemas/2007#user.subscriptions';
const USER_CONTACTS_REL = 'http://gdata.youtube.com/schemas/2007#user.contacts';
const USER_FAVORITES_REL = 'http://gdata.youtube.com/schemas/2007#user.favorites';
const VIDEO_RESPONSES_REL = 'http://gdata.youtube.com/schemas/2007#video.responses';
const VIDEO_RATINGS_REL = 'http://gdata.youtube.com/schemas/2007#video.ratings';
const VIDEO_COMPLAINTS_REL = 'http://gdata.youtube.com/schemas/2007#video.complaints';
const ACTIVITY_FEED_URI = 'https://gdata.youtube.com/feeds/api/events';
const FRIEND_ACTIVITY_FEED_URI =
'https://gdata.youtube.com/feeds/api/users/default/friendsactivity';
/**
* The URI of the in-reply-to schema for comments in reply to
* other comments.
*
* @var string
*/
const IN_REPLY_TO_SCHEME =
'http://gdata.youtube.com/schemas/2007#in-reply-to';
/**
* The URI of the inbox feed for the currently authenticated user.
*
* @var string
*/
const INBOX_FEED_URI =
'https://gdata.youtube.com/feeds/api/users/default/inbox';
/**
* The maximum number of users for which activity can be requested for,
* as enforced by the API.
*
* @var integer
*/
const ACTIVITY_FEED_MAX_USERS = 20;
/**
* The suffix for a feed of favorites.
*
* @var string
*/
const FAVORITES_URI_SUFFIX = 'favorites';
/**
* The suffix for the user's upload feed.
*
* @var string
*/
const UPLOADS_URI_SUFFIX = 'uploads';
/**
* The suffix for a feed of video responses.
*
* @var string
*/
const RESPONSES_URI_SUFFIX = 'responses';
/**
* The suffix for a feed of related videos.
*
* @var string
*/
const RELATED_URI_SUFFIX = 'related';
/**
* The suffix for a feed of messages (inbox entries).
*
* @var string
*/
const INBOX_URI_SUFFIX = 'inbox';
/**
* Namespaces used for Zend_Gdata_YouTube
*
* @var array
*/
public static $namespaces = array(
array('yt', 'http://gdata.youtube.com/schemas/2007', 1, 0),
array('georss', 'http://www.georss.org/georss', 1, 0),
array('gml', 'http://www.opengis.net/gml', 1, 0),
array('media', 'http://search.yahoo.com/mrss/', 1, 0)
);
/**
* Create Zend_Gdata_YouTube object
*
* @param Zend_Http_Client $client (optional) The HTTP client to use when
* when communicating with the Google servers.
* @param string $applicationId The identity of the app in the form of
* Company-AppName-Version
* @param string $clientId The clientId issued by the YouTube dashboard
* @param string $developerKey The developerKey issued by the YouTube dashboard
*/
public function __construct($client = null,
$applicationId = 'MyCompany-MyApp-1.0', $clientId = null,
$developerKey = null)
{
$this->registerPackage('Zend_Gdata_YouTube');
$this->registerPackage('Zend_Gdata_YouTube_Extension');
$this->registerPackage('Zend_Gdata_Media');
$this->registerPackage('Zend_Gdata_Media_Extension');
// NOTE This constructor no longer calls the parent constructor
$this->setHttpClient($client, $applicationId, $clientId, $developerKey);
}
/**
* Set the Zend_Http_Client object used for communication
*
* @param Zend_Http_Client $client The client to use for communication
* @throws Zend_Gdata_App_HttpException
* @return Zend_Gdata_App Provides a fluent interface
*/
public function setHttpClient($client,
$applicationId = 'MyCompany-MyApp-1.0', $clientId = null,
$developerKey = null)
{
if ($client === null) {
$client = new Zend_Http_Client();
}
if (!$client instanceof Zend_Http_Client) {
require_once 'Zend/Gdata/App/HttpException.php';
throw new Zend_Gdata_App_HttpException(
'Argument is not an instance of Zend_Http_Client.');
}
if ($clientId != null) {
$client->setHeaders('X-GData-Client', $clientId);
}
if ($developerKey != null) {
$client->setHeaders('X-GData-Key', 'key='. $developerKey);
}
return parent::setHttpClient($client, $applicationId);
}
/**
* Retrieves a feed of videos.
*
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined
* @return Zend_Gdata_YouTube_VideoFeed The feed of videos found at the
* specified URL.
*/
public function getVideoFeed($location = null)
{
if ($location == null) {
$uri = self::VIDEO_URI;
} else if ($location instanceof Zend_Gdata_Query) {
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
}
/**
* Retrieves a specific video entry.
*
* @param mixed $videoId The ID of the video to retrieve.
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined.
* @param boolean $fullEntry (optional) Retrieve the full metadata for the
* entry. Only possible if entry belongs to currently authenticated
* user. An exception will be thrown otherwise.
* @throws Zend_Gdata_App_HttpException
* @return Zend_Gdata_YouTube_VideoEntry The video entry found at the
* specified URL.
*/
public function getVideoEntry($videoId = null, $location = null,
$fullEntry = false)
{
if ($videoId !== null) {
if ($fullEntry) {
return $this->getFullVideoEntry($videoId);
} else {
$uri = self::VIDEO_URI . "/" . $videoId;
}
} else if ($location instanceof Zend_Gdata_Query) {
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getEntry($uri, 'Zend_Gdata_YouTube_VideoEntry');
}
/**
* Retrieves a video entry from the user's upload feed.
*
* @param mixed $videoID The ID of the video to retrieve.
* @throws Zend_Gdata_App_HttpException
* @return Zend_Gdata_YouTube_VideoEntry|null The video entry to be
* retrieved, or null if it was not found or the user requesting it
* did not have the appropriate permissions.
*/
public function getFullVideoEntry($videoId)
{
$uri = self::USER_URI . "/default/" .
self::UPLOADS_URI_SUFFIX . "/$videoId";
return parent::getEntry($uri, 'Zend_Gdata_YouTube_VideoEntry');
}
/**
* Retrieves a feed of videos related to the specified video ID.
*
* @param string $videoId The videoId of interest
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined
* @return Zend_Gdata_YouTube_VideoFeed The feed of videos found at the
* specified URL.
*/
public function getRelatedVideoFeed($videoId = null, $location = null)
{
if ($videoId !== null) {
$uri = self::VIDEO_URI . "/" . $videoId . "/" .
self::RELATED_URI_SUFFIX;
} else if ($location instanceof Zend_Gdata_Query) {
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
}
/**
* Retrieves a feed of video responses related to the specified video ID.
*
* @param string $videoId The videoId of interest
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined
* @return Zend_Gdata_YouTube_VideoFeed The feed of videos found at the
* specified URL.
*/
public function getVideoResponseFeed($videoId = null, $location = null)
{
if ($videoId !== null) {
$uri = self::VIDEO_URI . "/" . $videoId . "/" .
self::RESPONSES_URI_SUFFIX;
} else if ($location instanceof Zend_Gdata_Query) {
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
}
/**
* Retrieves a feed of comments related to the specified video ID.
*
* @param string $videoId The videoId of interest
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined
* @return Zend_Gdata_YouTube_CommentFeed The feed of videos found at the
* specified URL.
*/
public function getVideoCommentFeed($videoId = null, $location = null)
{
if ($videoId !== null) {
$uri = self::VIDEO_URI . "/" . $videoId . "/comments";
} else if ($location instanceof Zend_Gdata_Query) {
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_YouTube_CommentFeed');
}
/**
* Retrieves a feed of comments related to the specified video ID.
*
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined
* @return Zend_Gdata_YouTube_CommentFeed The feed of videos found at the
* specified URL.
*/
public function getTopRatedVideoFeed($location = null)
{
$standardFeedUri = self::STANDARD_TOP_RATED_URI;
if ($this->getMajorProtocolVersion() == 2) {
$standardFeedUri = self::STANDARD_TOP_RATED_URI_V2;
}
if ($location == null) {
$uri = $standardFeedUri;
} else if ($location instanceof Zend_Gdata_Query) {
if ($location instanceof Zend_Gdata_YouTube_VideoQuery) {
if (!isset($location->url)) {
$location->setFeedType('top rated');
}
}
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
}
/**
* Retrieves a feed of the most viewed videos.
*
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined
* @return Zend_Gdata_YouTube_VideoFeed The feed of videos found at the
* specified URL.
*/
public function getMostViewedVideoFeed($location = null)
{
$standardFeedUri = self::STANDARD_MOST_VIEWED_URI;
if ($this->getMajorProtocolVersion() == 2) {
$standardFeedUri = self::STANDARD_MOST_VIEWED_URI_V2;
}
if ($location == null) {
$uri = $standardFeedUri;
} else if ($location instanceof Zend_Gdata_Query) {
if ($location instanceof Zend_Gdata_YouTube_VideoQuery) {
if (!isset($location->url)) {
$location->setFeedType('most viewed');
}
}
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
}
/**
* Retrieves a feed of recently featured videos.
*
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined
* @return Zend_Gdata_YouTube_VideoFeed The feed of videos found at the
* specified URL.
*/
public function getRecentlyFeaturedVideoFeed($location = null)
{
$standardFeedUri = self::STANDARD_RECENTLY_FEATURED_URI;
if ($this->getMajorProtocolVersion() == 2) {
$standardFeedUri = self::STANDARD_RECENTLY_FEATURED_URI_V2;
}
if ($location == null) {
$uri = $standardFeedUri;
} else if ($location instanceof Zend_Gdata_Query) {
if ($location instanceof Zend_Gdata_YouTube_VideoQuery) {
if (!isset($location->url)) {
$location->setFeedType('recently featured');
}
}
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
}
/**
* Retrieves a feed of videos recently featured for mobile devices.
* These videos will have RTSP links in the $entry->mediaGroup->content
*
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined
* @return Zend_Gdata_YouTube_VideoFeed The feed of videos found at the
* specified URL.
*/
public function getWatchOnMobileVideoFeed($location = null)
{
$standardFeedUri = self::STANDARD_WATCH_ON_MOBILE_URI;
if ($this->getMajorProtocolVersion() == 2) {
$standardFeedUri = self::STANDARD_WATCH_ON_MOBILE_URI_V2;
}
if ($location == null) {
$uri = $standardFeedUri;
} else if ($location instanceof Zend_Gdata_Query) {
if ($location instanceof Zend_Gdata_YouTube_VideoQuery) {
if (!isset($location->url)) {
$location->setFeedType('watch on mobile');
}
}
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
}
/**
* Retrieves a feed which lists a user's playlist
*
* @param string $user (optional) The username of interest
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined
* @return Zend_Gdata_YouTube_PlaylistListFeed The feed of playlists
*/
public function getPlaylistListFeed($user = null, $location = null)
{
if ($user !== null) {
$uri = self::USER_URI . '/' . $user . '/playlists';
} else if ($location instanceof Zend_Gdata_Query) {
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_YouTube_PlaylistListFeed');
}
/**
* Retrieves a feed of videos in a particular playlist
*
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined
* @return Zend_Gdata_YouTube_PlaylistVideoFeed The feed of videos found at
* the specified URL.
*/
public function getPlaylistVideoFeed($location)
{
if ($location instanceof Zend_Gdata_Query) {
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_YouTube_PlaylistVideoFeed');
}
/**
* Retrieves a feed of a user's subscriptions
*
* @param string $user (optional) The username of interest
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined
* @return Zend_Gdata_YouTube_SubscriptionListFeed The feed of subscriptions
*/
public function getSubscriptionFeed($user = null, $location = null)
{
if ($user !== null) {
$uri = self::USER_URI . '/' . $user . '/subscriptions';
} else if ($location instanceof Zend_Gdata_Query) {
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_YouTube_SubscriptionFeed');
}
/**
* Retrieves a feed of a user's contacts
*
* @param string $user (optional) The username of interest
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined
* @return Zend_Gdata_YouTube_ContactFeed The feed of contacts
*/
public function getContactFeed($user = null, $location = null)
{
if ($user !== null) {
$uri = self::USER_URI . '/' . $user . '/contacts';
} else if ($location instanceof Zend_Gdata_Query) {
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_YouTube_ContactFeed');
}
/**
* Retrieves a user's uploads
*
* @param string $user (optional) The username of interest
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined
* @return Zend_Gdata_YouTube_VideoFeed The videos uploaded by the user
*/
public function getUserUploads($user = null, $location = null)
{
if ($user !== null) {
$uri = self::USER_URI . '/' . $user . '/' .
self::UPLOADS_URI_SUFFIX;
} else if ($location instanceof Zend_Gdata_Query) {
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
}
/**
* Retrieves a user's favorites
*
* @param string $user (optional) The username of interest
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined
* @return Zend_Gdata_YouTube_VideoFeed The videos favorited by the user
*/
public function getUserFavorites($user = null, $location = null)
{
if ($user !== null) {
$uri = self::USER_URI . '/' . $user . '/' .
self::FAVORITES_URI_SUFFIX;
} else if ($location instanceof Zend_Gdata_Query) {
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
}
/**
* Retrieves a user's profile as an entry
*
* @param string $user (optional) The username of interest
* @param mixed $location (optional) The URL to query or a
* Zend_Gdata_Query object from which a URL can be determined
* @return Zend_Gdata_YouTube_UserProfileEntry The user profile entry
*/
public function getUserProfile($user = null, $location = null)
{
if ($user !== null) {
$uri = self::USER_URI . '/' . $user;
} else if ($location instanceof Zend_Gdata_Query) {
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getEntry($uri, 'Zend_Gdata_YouTube_UserProfileEntry');
}
/**
* Helper function for parsing a YouTube token response
*
* @param string $response The service response
* @throws Zend_Gdata_App_Exception
* @return array An array containing the token and URL
*/
public static function parseFormUploadTokenResponse($response)
{
// Load the feed as an XML DOMDocument object
@ini_set('track_errors', 1);
$doc = new DOMDocument();
$success = @$doc->loadXML($response);
@ini_restore('track_errors');
if (!$success) {
require_once 'Zend/Gdata/App/Exception.php';
throw new Zend_Gdata_App_Exception(
"Zend_Gdata_YouTube::parseFormUploadTokenResponse - " .
"DOMDocument cannot parse XML: $php_errormsg");
}
$responseElement = $doc->getElementsByTagName('response')->item(0);
$urlText = null;
$tokenText = null;
if ($responseElement != null) {
$urlElement =
$responseElement->getElementsByTagName('url')->item(0);
$tokenElement =
$responseElement->getElementsByTagName('token')->item(0);
if ($urlElement && $urlElement->hasChildNodes() &&
$tokenElement && $tokenElement->hasChildNodes()) {
$urlText = $urlElement->firstChild->nodeValue;
$tokenText = $tokenElement->firstChild->nodeValue;
}
}
if ($tokenText != null && $urlText != null) {
return array('token' => $tokenText, 'url' => $urlText);
} else {
require_once 'Zend/Gdata/App/Exception.php';
throw new Zend_Gdata_App_Exception(
'Form upload token not found in response');
}
}
/**
* Retrieves a YouTube token
*
* @param Zend_Gdata_YouTube_VideoEntry $videoEntry The video entry
* @param string $url The location as a string URL
* @throws Zend_Gdata_App_Exception
* @return array An array containing a token and URL
*/
public function getFormUploadToken($videoEntry,
$url='https://gdata.youtube.com/action/GetUploadToken')
{
if ($url != null && is_string($url)) {
// $response is a Zend_Http_response object
$response = $this->post($videoEntry, $url);
return self::parseFormUploadTokenResponse($response->getBody());
} else {
require_once 'Zend/Gdata/App/Exception.php';
throw new Zend_Gdata_App_Exception(
'Url must be provided as a string URL');
}
}
/**
* Retrieves the activity feed for users
*
* @param mixed $usernames A string identifying the usernames for which to
* retrieve activity for. This can also be a Zend_Gdata_Query
* object from which a URL can be determined.
* @throws Zend_Gdata_App_VersionException if using version less than 2.
* @return Zend_Gdata_YouTube_ActivityFeed
*/
public function getActivityForUser($username)
{
if ($this->getMajorProtocolVersion() == 1) {
require_once 'Zend/Gdata/App/VersionException.php';
throw new Zend_Gdata_App_VersionException('User activity feeds ' .
'are not available in API version 1.');
}
$uri = null;
if ($username instanceof Zend_Gdata_Query) {
$uri = $username->getQueryUrl();
} else {
if (count(explode(',', $username)) >
self::ACTIVITY_FEED_MAX_USERS) {
require_once 'Zend/Gdata/App/InvalidArgumentException.php';
throw new Zend_Gdata_App_InvalidArgumentException(
'Activity feed can only retrieve for activity for up to ' .
self::ACTIVITY_FEED_MAX_USERS . ' users per request');
}
$uri = self::ACTIVITY_FEED_URI . '?author=' . $username;
}
return parent::getFeed($uri, 'Zend_Gdata_YouTube_ActivityFeed');
}
/**
* Retrieve the activity of the currently authenticated users friend.
*
* @throws Zend_Gdata_App_Exception if not logged in.
* @return Zend_Gdata_YouTube_ActivityFeed
*/
public function getFriendActivityForCurrentUser()
{
if (!$this->isAuthenticated()) {
require_once 'Zend/Gdata/App/Exception.php';
throw new Zend_Gdata_App_Exception('You must be authenticated to ' .
'use the getFriendActivityForCurrentUser function in Zend_' .
'Gdata_YouTube.');
}
return parent::getFeed(self::FRIEND_ACTIVITY_FEED_URI,
'Zend_Gdata_YouTube_ActivityFeed');
}
/**
* Retrieve a feed of messages in the currently authenticated user's inbox.
*
* @throws Zend_Gdata_App_Exception if not logged in.
* @return Zend_Gdata_YouTube_InboxFeed|null
*/
public function getInboxFeedForCurrentUser()
{
if (!$this->isAuthenticated()) {
require_once 'Zend/Gdata/App/Exception.php';
throw new Zend_Gdata_App_Exception('You must be authenticated to ' .
'use the getInboxFeedForCurrentUser function in Zend_' .
'Gdata_YouTube.');
}
return parent::getFeed(self::INBOX_FEED_URI,
'Zend_Gdata_YouTube_InboxFeed');
}
/**
* Send a video message.
*
* Note: Either a Zend_Gdata_YouTube_VideoEntry or a valid video ID must
* be provided.
*
* @param string $body The body of the message
* @param Zend_Gdata_YouTube_VideoEntry (optional) The video entry to send
* @param string $videoId The id of the video to send
* @param string $recipientUserName The username of the recipient
* @throws Zend_Gdata_App_InvalidArgumentException if no valid
* Zend_Gdata_YouTube_VideoEntry or videoId were provided
* @return Zend_Gdata_YouTube_InboxEntry|null The
* Zend_Gdata_YouTube_Inbox_Entry representing the sent message.
*
*/
public function sendVideoMessage($body, $videoEntry = null,
$videoId = null, $recipientUserName)
{
if (!$videoId && !$videoEntry) {
require_once 'Zend/Gdata/App/InvalidArgumentException.php';
throw new Zend_Gdata_App_InvalidArgumentException(
'Expecting either a valid videoID or a videoEntry object in ' .
'Zend_Gdata_YouTube->sendVideoMessage().');
}
$messageEntry = new Zend_Gdata_YouTube_InboxEntry();
if ($this->getMajorProtocolVersion() == null ||
$this->getMajorProtocolVersion() == 1) {
if (!$videoId) {
$videoId = $videoEntry->getVideoId();
} elseif (strlen($videoId) < 12) {
//Append the full URI
$videoId = self::VIDEO_URI . '/' . $videoId;
}
$messageEntry->setId($this->newId($videoId));
// TODO there seems to be a bug where v1 inbox entries dont
// retain their description...
$messageEntry->setDescription(
new Zend_Gdata_YouTube_Extension_Description($body));
} else {
if (!$videoId) {
$videoId = $videoEntry->getVideoId();
$videoId = substr($videoId, strrpos($videoId, ':'));
}
$messageEntry->setId($this->newId($videoId));
$messageEntry->setSummary($this->newSummary($body));
}
$insertUrl = 'https://gdata.youtube.com/feeds/api/users/' .
$recipientUserName . '/inbox';
$response = $this->insertEntry($messageEntry, $insertUrl,
'Zend_Gdata_YouTube_InboxEntry');
return $response;
}
/**
* Post a comment in reply to an existing comment
*
* @param Zend_Gdata_YouTube_CommentEntry $commentEntry The comment entry
* to reply to
* @param string $commentText The text of the
* comment to post
* @return Zend_Gdata_YouTube_CommentEntry the posted comment
*/
public function replyToCommentEntry($commentEntry, $commentText)
{
$newComment = $this->newCommentEntry();
$newComment->content = $this->newContent()->setText($commentText);
$commentId = $commentEntry->getId();
$commentIdArray = explode(':', $commentId);
// create a new link element
$inReplyToLinkHref = self::VIDEO_URI . '/' . $commentIdArray[3] .
'/comments/' . $commentIdArray[5];
$inReplyToLink = $this->newLink($inReplyToLinkHref,
self::IN_REPLY_TO_SCHEME, $type="application/atom+xml");
$links = $newComment->getLink();
$links[] = $inReplyToLink;
$newComment->setLink($links);
$commentFeedPostUrl = self::VIDEO_URI . '/' . $commentIdArray[3] .
'/comments';
return $this->insertEntry($newComment,
$commentFeedPostUrl, 'Zend_Gdata_YouTube_CommentEntry');
}
}
| {
"content_hash": "4f91a53f1069dd6fdaf30698a5229fa2",
"timestamp": "",
"source": "github",
"line_count": 855,
"max_line_length": 113,
"avg_line_length": 36.330994152046785,
"alnum_prop": 0.5925699385120562,
"repo_name": "bluelovers/ZendFramework-1.x",
"id": "48de9f94afb342623db432bde243c3492def9074",
"size": "31777",
"binary": false,
"copies": "1",
"ref": "refs/heads/svn/master",
"path": "library/Zend/Gdata/YouTube.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "30072"
},
{
"name": "PHP",
"bytes": "30100372"
},
{
"name": "Shell",
"bytes": "5283"
}
],
"symlink_target": ""
} |
**1) Which time management and productivity ideas did you learn about?**
I took a spin through most of the links, and the ones that really stuck out to me were the Pomodoro technique and the link on starting small.
I like the Pomodoro in concept because of its simplicity and use of timeboxing as a way of setting microbursts of productivity.
I like the idea of starting small, since I usually try to start big and find this one particularly applicable to me.
**2) What is "Time Boxing?" How can I use it in Phase 0?**
Timeboxing, as I understand it, is setting a time limit on a specific goal and stopping work on it once that time is reached. The Pomodoro technique could be one example of this (very small timebox). Sprints, as employed by many product teams, would be a longer one.
I think timeboxing could be particularly useful in Phase 0 for helping me get through challenges in a timely and efficient manner. In particular, because of the remote learning, there are concepts that may not stick, so taking the initiative to set limits will help chunk up the work in a way that makes it digestible and allows for breaks and reflection, which will be a good tactic for revisiting work later.
**3) How do I manage my time currently?**
I usually wake up with a few objectives in mind for the next day or two. And make sure that I accomplish those. I try to be fluid and allow for flexibility whenever possible, so as not to impose unnecessary deadlines, but keeping a checklist does help me ensure critical items get completed.
The other technique I employ is setting milestones for bigger goals. For example, if my goal this week is to complete all Week 1 assignments, I will break it up, just as the module has into smaller ones. As I progress through the week, I will make sure that sufficient progress is made mid-week, and later in the week, so that I give myself a realistic chance at completing the entire set of challenges.
**4) Is my current strategy working?**
I think it does. Usually, really critical goals always find a way of getting completed by the due date, since I allow myself to think about what's important each day, and give myself progress checks throughout the course of the week to ensure that I'm not leaving myself with a lot of last minute to-do's.
**5) Can I employ any of the strategies?**
I really think I will give the general notion of timeboxing (loosely with Pomodoro, but maybe not 25 minute increments) a more serious thought. I apply it loosely, but allowing myself to truly focus in without distraction is something I struggle a bit with, so giving myself 1 hour productivity sprints I think will really help me focus.
**6) What is my overall plan for Phase 0 time management?**
My plan is to use my current productivity methods (not trying to change too much), while making improvements using some of the tips here.
In particular, because the work is already structured out with timing expectations, I hope to follow the pathway while keeping myself in check so that I do not leave too much for the end of the week. I will have a part time job during phase 0, so I know that last minute cramming will be very detrimental. I've worked with my part time employer to ensure I have some flexibility and have set expectations on my time outside of work, to make sure I can accomplish my DBC commitments.
I will definitely try timeboxing during my DBC time as well. I sometimes struggle with more nebulous goals, especially ones that are related to self learning (I'm better in person), so I think the short bursts of productivity will be really helpful by placing confines with clear objectives.
# 1.2 The Command Line
**1) What is a shell? What is bash?**
The shell is the way to access the commands (in any OS) -- essentially the command line. Bash appears to be the default / more specific shell type in Unix based OS (like MacOS).
**2) What was most challenging?**
I struggled a bit with the piping and env commands toward the end, at least in understanding what exactly they do. I also don't understand how different modifiers (like -rf for rm) will work, but hopefully that will become more apparent as more use cases come up.
I think this exercise was a great intro, but it's still challenging to see how everything will get be used going forward.
**3) Was I successful in using the commands?**
I think so. Some of them still don't make 100% sense, but I took good notes and I'm sure will explore the use cases more later on.
**4) In my opinion, most useful?**
Besides "cd" (obvs!), I really liked "ls", which I think will help for orienting around what is there in a given directory. I also like "less", which sounds like it will be super useful once we're editing code directly in the terminal.
**5) Commands**
pwd: Print working directory --> tells me where I am
ls: Lists all files / paths in current directory (or another specified directory)
mv: Deceptively appears to rename, rather than move!
cd: Takes me to a given path specified
../: When used with cd, takes me up one directory
touch: Creates a new file
mkdir: Make directory --> creates a new directory
less: Shows a full screen of a given file, space to paginate, q to exit
rmdir: Deletes a specified directory, as long as there's nothing else in it
rm: Deletes files, can delete a directory with things in it if specified correctly
help: Brings up a help dialogue
# 1.3 Forking and Cloning
**1) If I were going to write instructions for a new person on how to create a new repo, fork a repo, and clone a repo, what would they be? Why would I fork a repository as opposed to create a new one?**
**Creating a new repo:** To create a blank / empty repo, go to Github.com
1. Click the "+" on the top right and select new repository
2. Name the repo
3. Choose the access settings (private or public)
4. Select a license as needed
5. Save
**Forking a repo**
1. Using an existing repository
2. Find the "fork" button near the top right
3. Select the destination (usually your own username) for where you'd like to fork the repo
**Cloning a repo**
1. On a given repo, find the HTTPS clone URL (middle / bottom right of the screen)
2. In the shell, navigate to the directory where you'd like to clone the repo using "cd"
3. Type "git clone" followed by the URL, and hit enter
**Why fork vs. create new?**
Forking to me seems like copying an existing repo with information and work already done in it. It would be used for projects with collaboration, where we'd want to work on existing code but not disrupt the master. It's like copy-paste in my mind.
Creating new is more to create an empty repo.
**2) What struggles did I have setting up Git and Github? What did I learn?**
No struggles for me, the installation of git via the shell was simple, and joining Github was fairly straightforward as well.
The key learning for me here was the distinction between Git and Github, which is that one is local and one is remote, and that the remote version is a great online tool used for collaboration with larger teams. | {
"content_hash": "daab7b4fdaee5b317473e90e3c11a25d",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 483,
"avg_line_length": 57.33870967741935,
"alnum_prop": 0.7651195499296765,
"repo_name": "dma315/phase-0",
"id": "e9499ecbc7f1b98f04c2f3512c1ac96c01ba0bcb",
"size": "7134",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "week-1/reflections.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5971"
},
{
"name": "HTML",
"bytes": "29336"
},
{
"name": "JavaScript",
"bytes": "31948"
},
{
"name": "Ruby",
"bytes": "130426"
}
],
"symlink_target": ""
} |
<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>
<groupId>com.krishan</groupId>
<artifactId>spring-webmvc-basic</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring-webmvc-basic</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
| {
"content_hash": "31418115d48acc80b40686d52e1b9f02",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 104,
"avg_line_length": 29.30909090909091,
"alnum_prop": 0.6476426799007444,
"repo_name": "krishansubudhi/spring-practice",
"id": "771e4aab9d709d082c4334d4187dd064f657eecc",
"size": "1612",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spring-webmvc-basic/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "35065"
}
],
"symlink_target": ""
} |
"""
usage: mpdboot --totalnum=<n_to_start> [--file=<hostsfile>] [--help] \
[--rsh=<rshcmd>] [--user=<user>] [--mpd=<mpdcmd>] \
[--shell] [--verbose] [--chkup] [--chkuponly] [--maxbranch=<maxbranch>]
or, in short form,
mpdboot -n n_to_start [-f <hostsfile>] [-h] [-r <rshcmd>] [-u <user>] \
[-m <mpdcmd>] -s -v [-c]
--totalnum specifies the total number of mpds to start; at least
one mpd will be started locally if the local machine is in the hosts file
--file specifies the file of machines to start the rest of the mpds on;
it defaults to mpd.hosts
--mpd specifies the full path name of mpd on the remote hosts if it is
not in your path
--rsh specifies the name of the command used to start remote mpds; it
defaults to ssh; an alternative is rsh
--shell says that the Bourne shell is your default for rsh'
--verbose shows the ssh attempts as they occur; it does not provide
confirmation that the sshs were successful
--chkup requests that mpdboot try to verify that the hosts in the host file
are up before attempting start mpds on any of them; it just checks the number
of hosts specified by -n
--chkuponly requests that mpdboot try to verify that the hosts in the host file
are up; it then terminates; it just checks the number of hosts specified by -n
--maxbranch indicates the maximum number of mpds to enter the ring under another;
the default is 4
"""
# workaround to suppress deprecated module warnings in python2.6
# see https://trac.mcs.anl.gov/projects/mpich2/ticket/362 for tracking
import warnings
warnings.filterwarnings('ignore', '.*the popen2 module is deprecated.*', DeprecationWarning)
from time import ctime
__author__ = "Ralph Butler and Rusty Lusk"
__date__ = ctime()
__version__ = "$Revision: 1.1 $"
__credits__ = ""
import re
from os import environ, path, kill, access, X_OK
from sys import argv, exit, stdout
from popen2 import Popen4, Popen3, popen2
from socket import gethostname, gethostbyname_ex
from select import select, error
from signal import SIGKILL
from commands import getoutput, getstatusoutput
from mpdlib import mpd_set_my_id, mpd_get_my_username, mpd_same_ips, \
mpd_get_ranks_in_binary_tree, mpd_print, MPDSock
global myHost, fullDirName, rshCmd, user, mpdCmd, debug, verbose
def mpdboot():
global myHost, fullDirName, rshCmd, user, mpdCmd, debug, verbose
myHost = gethostname()
mpd_set_my_id('mpdboot_%s' % (myHost) )
fullDirName = path.abspath(path.split(argv[0])[0])
rshCmd = 'ssh'
user = mpd_get_my_username()
mpdCmd = path.join(fullDirName,'mpd.py')
hostsFilename = 'mpd.hosts'
totalnumToStart = 0
debug = 0
verbose = 0
chkupIndicator = 0 # 1 -> chk and start ; 2 -> just chk
maxUnderOneRoot = 4
try:
shell = path.split(environ['SHELL'])[-1]
except:
shell = 'csh'
if environ.has_key('MPD_TMPDIR'):
tmpdir = environ['MPD_TMPDIR']
else:
tmpdir = ''
argidx = 1 # skip arg 0
while argidx < len(argv):
if argv[argidx] == '-h' or argv[argidx] == '--help':
usage()
elif argv[argidx] == '-r': # or --rsh=
rshCmd = argv[argidx+1]
argidx += 2
elif argv[argidx].startswith('--rsh'):
splitArg = argv[argidx].split('=')
try:
rshCmd = splitArg[1]
except:
print 'mpdboot: invalid argument:', argv[argidx]
usage()
argidx += 1
elif argv[argidx] == '-u': # or --user=
user = argv[argidx+1]
argidx += 2
elif argv[argidx].startswith('--user'):
splitArg = argv[argidx].split('=')
try:
user = splitArg[1]
except:
print 'mpdboot: invalid argument:', argv[argidx]
usage()
argidx += 1
elif argv[argidx] == '-m': # or --mpd=
mpdCmd = argv[argidx+1]
argidx += 2
elif argv[argidx].startswith('--mpd'):
splitArg = argv[argidx].split('=')
try:
mpdCmd = splitArg[1]
except:
print 'mpdboot: invalid argument:', argv[argidx]
usage()
argidx += 1
elif argv[argidx] == '-f': # or --file=
hostsFilename = argv[argidx+1]
argidx += 2
elif argv[argidx].startswith('--file'):
splitArg = argv[argidx].split('=')
try:
hostsFilename = splitArg[1]
except:
print 'mpdboot: invalid argument:', argv[argidx]
usage()
argidx += 1
elif argv[argidx] == '-n': # or --totalnum=
totalnumToStart = int(argv[argidx+1])
argidx += 2
elif argv[argidx].startswith('--totalnum'):
splitArg = argv[argidx].split('=')
try:
totalnumToStart = int(splitArg[1])
except:
print 'mpdboot: invalid argument:', argv[argidx]
usage()
argidx += 1
elif argv[argidx].startswith('--maxbranch'):
splitArg = argv[argidx].split('=')
try:
maxUnderOneRoot = int(splitArg[1])
except:
print 'mpdboot: invalid argument:', argv[argidx]
usage()
argidx += 1
elif argv[argidx] == '-d' or argv[argidx] == '--debug':
debug = 1
argidx += 1
elif argv[argidx] == '-s' or argv[argidx] == '--shell':
shell = 'bourne'
argidx += 1
elif argv[argidx] == '-v' or argv[argidx] == '--verbose':
verbose = 1
argidx += 1
elif argv[argidx] == '-c' or argv[argidx] == '--chkup':
chkupIndicator = 1
argidx += 1
elif argv[argidx] == '--chkuponly':
chkupIndicator = 2
argidx += 1
else:
print 'mpdboot: unrecognized argument:', argv[argidx]
usage()
if debug:
print 'debug: starting'
lines = []
try:
f = open(hostsFilename,'r')
for line in f:
if not line or line[0] == '#':
continue
lines.append(line)
except:
print 'unable to open (or read) hostsfile %s' % (hostsFilename)
exit(-1)
if totalnumToStart == 0:
totalnumToStart = len(lines)
numRead = 0
hostsAndInfo = []
for line in lines:
line = line.strip()
splitLine = re.split(r'\s+',line)
host = splitLine[0]
ncpus = 1 # default
ifhn = '' # default
cons = '' # default
for kv in splitLine[1:]:
(k,v) = kv.split('=',1)
if k == 'ifhn':
ifhn = v
elif k == 'ncpus':
ncpus = int(v)
elif k == 'cons':
cons = v
else:
print "unrecognized key:", k
exit(-1)
hostsAndInfo.append( {'host' : host, 'ifhn' : ifhn, 'ncpus' : ncpus, 'cons' : cons} )
numRead += 1
if numRead >= totalnumToStart:
break
if len(hostsAndInfo) < totalnumToStart: # one is local
print 'totalnum=%d numhosts=%d' % (totalnumToStart,len(hostsAndInfo))
print 'there are not enough hosts on which to start all processes'
exit(-1)
if chkupIndicator:
hostsToCheck = [ hai['host'] for hai in hostsAndInfo ]
(upList,dnList) = chkupdn(hostsToCheck)
if dnList:
print "these hosts are down; exiting"
print dnList
exit(-1)
print "there are %d hosts up" % (len(upList))
if chkupIndicator == 2: # do the chkup and quit
exit(0)
try:
from os import sysconf
maxfds = sysconf('SC_OPEN_MAX')
except:
maxfds = 1024
maxAtOnce = min(128,maxfds-8) # -8 for stdout, etc. + a few more for padding
fd2idx = {}
hostsSeen = {}
fdsToSelect = []
numStarted = 0
numStarting = 0
numUnderCurrRoot = 0
possRoots = []
currRoot = 0
idxToStart = 0
while numStarted < totalnumToStart:
if numStarting < maxAtOnce and idxToStart < totalnumToStart:
if numUnderCurrRoot < maxUnderOneRoot:
if idxToStart == 0:
entryHost = ''
entryPort = ''
else:
entryHost = hostsAndInfo[currRoot]['host']
entryPort = hostsAndInfo[currRoot]['list_port']
hostsAndInfo[idxToStart]['entry_host'] = entryHost
hostsAndInfo[idxToStart]['entry_port'] = entryPort
if entryHost:
entryHost = '-h ' + entryHost
entryPort = '-p ' + str(entryPort)
ifhn = hostsAndInfo[idxToStart]['ifhn']
ncpus = hostsAndInfo[idxToStart]['ncpus']
cons = hostsAndInfo[idxToStart]['cons']
if ifhn:
ifhn = '--ifhn=%s' % (ifhn)
if ncpus:
ncpus = '--ncpus=%s' % (ncpus)
if cons == 'n':
cons = '-n'
mpdArgs = '%s %s %s %s %s ' % (cons,entryHost,entryPort,ifhn,ncpus)
if tmpdir:
mpdArgs += ' --tmpdir=%s' % (tmpdir)
(mpdPID,mpdFD) = launch_one_mpd(idxToStart,currRoot,mpdArgs,hostsAndInfo)
hostsAndInfo[idxToStart]['pid'] = mpdPID
hostsSeen[hostsAndInfo[idxToStart]['host']] = 1
fd2idx[mpdFD] = idxToStart
if idxToStart == 0:
handle_mpd_output(mpdFD,fd2idx,hostsAndInfo)
numStarted += 1
else:
numUnderCurrRoot += 1
fdsToSelect.append(mpdFD)
numStarting += 1
idxToStart += 1
else:
if possRoots:
currRoot = possRoots.pop()
numUnderCurrRoot = 0
selectTime = 0.01
else:
selectTime = 0.1
try:
(readyFDs,unused1,unused2) = select(fdsToSelect,[],[],selectTime)
except error, errmsg:
mpd_print(1,'mpdboot: select failed: errmsg=:%s:' % (errmsg) )
exit(-1)
for fd in readyFDs:
handle_mpd_output(fd,fd2idx,hostsAndInfo)
numStarted += 1
numStarting -= 1
possRoots.append(fd2idx[fd])
fdsToSelect.remove(fd)
fd.close()
def launch_one_mpd(idxToStart,currRoot,mpdArgs,hostsAndInfo):
global myHost, fullDirName, rshCmd, user, mpdCmd, debug, verbose
mpdHost = hostsAndInfo[idxToStart]['host']
if rshCmd == 'ssh':
rshArgs = '-x -n -q'
else:
rshArgs = '-n'
mpdHost = hostsAndInfo[idxToStart]['host']
cmd = "%s %s %s '%s %s -e -d' " % \
(rshCmd,rshArgs,mpdHost,mpdCmd,mpdArgs)
if verbose:
entryHost = hostsAndInfo[idxToStart]['entry_host']
entryPort = hostsAndInfo[idxToStart]['entry_port']
# print "LAUNCHED mpd on %s via %s %s" % (mpdHost,entryHost,str(entryPort))
print "LAUNCHED mpd on %s via %s" % (mpdHost,entryHost)
if debug:
print "debug: launch cmd=", cmd
mpd = Popen4(cmd,0)
mpdFD = mpd.fromchild
mpdPID = mpd.pid
return (mpdPID,mpdFD)
def handle_mpd_output(fd,fd2idx,hostsAndInfo):
global myHost, fullDirName, rshCmd, user, mpdCmd, debug, verbose
idx = fd2idx[fd]
host = hostsAndInfo[idx]['host']
# port = fd.readline().strip()
port = 'no_port'
for line in fd.readlines(): # handle output from shells that echo stuff
line = line.strip()
splitLine = line.split('=')
if splitLine[0] == 'mpd_port':
port = splitLine[1]
break
if debug:
print "debug: mpd on %s on port %s" % (host,port)
if port.isdigit():
hostsAndInfo[idx]['list_port'] = int(port)
tempSock = MPDSock(name='temp_to_mpd')
try:
tempSock.connect((host,int(port)))
except:
tempSock.close()
tempSock = 0
if tempSock:
msgToSend = { 'cmd' : 'ping', 'ifhn' : 'dummy', 'port' : 0}
tempSock.send_dict_msg(msgToSend)
msg = tempSock.recv_dict_msg() # RMB: WITH TIMEOUT ??
if not msg or not msg.has_key('cmd') or msg['cmd'] != 'challenge':
mpd_print(1,'failed to handshake mpd on %s; recvd output=%s' % (host,msg) )
tempOut = tempSock.recv(1000)
print tempOut
try: getoutput('%s/mpdallexit.py' % (fullDirName))
except: pass
exit(-1)
tempSock.close()
else:
mpd_print(1,'failed to connect to mpd on %s' % (host) )
try: getoutput('%s/mpdallexit.py' % (fullDirName))
except: pass
exit(-1)
else:
mpd_print(1,'from mpd on %s, invalid port info:' % (host) )
print port
print fd.read()
try: getoutput('%s/mpdallexit.py' % (fullDirName))
except: pass
exit(-1)
if verbose:
print "RUNNING: mpd on", hostsAndInfo[fd2idx[fd]]['host']
if debug:
print "debug: info for running mpd:", hostsAndInfo[fd2idx[fd]]
def chkupdn(hostList):
upList = []
dnList = []
for hostname in hostList:
print 'checking', hostname
if rshCmd == 'ssh':
rshArgs = '-x -n'
else:
rshArgs = '-n'
cmd = "%s %s %s /bin/echo hello" % (rshCmd,rshArgs,hostname)
runner = Popen3(cmd,1,0)
runout = runner.fromchild
runerr = runner.childerr
runin = runner.tochild
runpid = runner.pid
up = 0
try:
# (readyFDs,unused1,unused2) = select([runout,runerr],[],[],9)
(readyFDs,unused1,unused2) = select([runout],[],[],9)
except:
print 'select failed'
readyFDs = []
for fd in readyFDs: # may have runout and runerr sometimes
line = fd.readline()
if line and line.startswith('hello'):
up = 1
else:
pass
if up:
upList.append(hostname)
else:
dnList.append(hostname)
try:
kill(runpid,SIGKILL)
except:
pass
return(upList,dnList)
def usage():
print __doc__
stdout.flush()
exit(-1)
if __name__ == '__main__':
mpdboot()
| {
"content_hash": "1fba6cf257f05d4cc4d0976b94862424",
"timestamp": "",
"source": "github",
"line_count": 408,
"max_line_length": 93,
"avg_line_length": 36.245098039215684,
"alnum_prop": 0.529145252907763,
"repo_name": "gnu3ra/SCC15HPCRepast",
"id": "5d58ac21f5d0771dd8ee7e84eef5e52480aaad95",
"size": "14906",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "INSTALLATION/mpich2-1.4.1p1/src/pm/mpd/newboot.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "166901"
},
{
"name": "Awk",
"bytes": "4270"
},
{
"name": "Batchfile",
"bytes": "59453"
},
{
"name": "C",
"bytes": "89044644"
},
{
"name": "C#",
"bytes": "171870"
},
{
"name": "C++",
"bytes": "149286410"
},
{
"name": "CMake",
"bytes": "1277735"
},
{
"name": "CSS",
"bytes": "275497"
},
{
"name": "Cuda",
"bytes": "26749"
},
{
"name": "DIGITAL Command Language",
"bytes": "396318"
},
{
"name": "FORTRAN",
"bytes": "5955918"
},
{
"name": "Groff",
"bytes": "1536123"
},
{
"name": "HTML",
"bytes": "152716955"
},
{
"name": "IDL",
"bytes": "14"
},
{
"name": "Java",
"bytes": "1703162"
},
{
"name": "JavaScript",
"bytes": "132031"
},
{
"name": "Lex",
"bytes": "44890"
},
{
"name": "LiveScript",
"bytes": "299224"
},
{
"name": "Logos",
"bytes": "17671"
},
{
"name": "Makefile",
"bytes": "10089555"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Objective-C",
"bytes": "4756"
},
{
"name": "PHP",
"bytes": "74480"
},
{
"name": "Perl",
"bytes": "1444604"
},
{
"name": "Perl6",
"bytes": "9917"
},
{
"name": "PostScript",
"bytes": "4003"
},
{
"name": "Pure Data",
"bytes": "1710"
},
{
"name": "Python",
"bytes": "2280373"
},
{
"name": "QML",
"bytes": "593"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Scilab",
"bytes": "3012"
},
{
"name": "Shell",
"bytes": "11997985"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "696679"
},
{
"name": "Visual Basic",
"bytes": "11578"
},
{
"name": "XSLT",
"bytes": "771726"
},
{
"name": "Yacc",
"bytes": "140274"
}
],
"symlink_target": ""
} |
local OneHot, parent = torch.class('OneHot', 'nn.Module')
function OneHot:__init(outputSize)
parent.__init(self)
self.outputSize = outputSize
-- We'll construct one-hot encodings by using the index method to
-- reshuffle the rows of an identity matrix. To avoid recreating
-- it every iteration we'll cache it.
self._eye = torch.eye(outputSize)
end
function OneHot:updateOutput(input)
self.output:resize(input:size(1), self.outputSize):zero()
if self._eye == nil then
self._eye = torch.eye(self.outputSize)
end
local longInput = input:long():squeeze()
self.output:copy(self._eye:index(1, longInput))
return self.output
end
function OneHot:updateGradInput(input, gradOutput)
self.gradInput:resize(input:size(1))
return self.gradInput
end
| {
"content_hash": "c9dbafa5b155cb835bf792b5d580c68a",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 67,
"avg_line_length": 28.77777777777778,
"alnum_prop": 0.7297297297297297,
"repo_name": "andreaskoepf/matrixwalk",
"id": "5c1c5c775e55f29d5a57a51c26cf474ed052ae08",
"size": "777",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "layers/OneHot.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Lua",
"bytes": "39367"
},
{
"name": "Shell",
"bytes": "1697"
}
],
"symlink_target": ""
} |
@implementation NSAlert (ErrorDisable)
-(void)FIXsetMessageText:(NSString *)string {
NSLog(@"%@", string);
if([string containsString:@"There was a problem connecting to the server"]) {
[[self window] setHidden:YES];
}
[self FIXsetMessageText:string];
}
@end
| {
"content_hash": "0eb8cf1c223a404739ae334cda201ac1",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 81,
"avg_line_length": 25.818181818181817,
"alnum_prop": 0.6690140845070423,
"repo_name": "mathcolo/ConnectionErrorDisable",
"id": "9a9d4622eb53bca8c360a885956572f8e27bc07f",
"size": "468",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ConnectionErrorDisable/NSAlert+Fix.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "2183"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sinodata.evaluate"
android:versionCode="3"
android:versionName="1.03"
>
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:name="com.sinodata.evaluate.MyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Holo.Light.NoActionBar.Fullscreen">
<!-- android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" > -->
<activity
android:name="com.sinodata.evaluate.activities.SplashActivity"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.sinodata.evaluate.activities.WebViewActivity2"></activity>
<activity android:name="com.sinodata.evaluate.activities.ManageActivity"></activity>
<activity android:name="com.sinodata.evaluate.activities.PrepareActivity"></activity>
<activity android:name="com.sinodata.evaluate.activities.UserEvaluateListActivity"></activity>
<activity android:name="com.sinodata.evaluate.activities.ConstitutionInfo"></activity>
<activity android:name="com.sinodata.evaluate.activities.UserInformationRegisterActivity"></activity>
<activity android:name="com.sinodata.evaluate.activities.EvaluateChooseActivity"></activity>
<activity android:name="com.sinodata.evaluate.activities.WifiListActivity" ></activity>
<activity android:name="com.sinodata.evaluate.activities.MainActivity"></activity>
<activity android:name="com.sinodata.evaluate.activities.WebViewActivity"></activity>
<activity android:name="com.sinodata.evaluate.activities.EvaluateHistoryActivity"></activity>
<activity android:name="com.sinodata.evaluate.activities.InformationActivity"></activity>
<activity android:name="com.sinodata.evaluate.activities.ManagementActivity"></activity>
<receiver android:name="com.sinodata.evaluate.receiver.BootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
</manifest>
| {
"content_hash": "d8f19bc6752954f0a9328c57b7ee902d",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 109,
"avg_line_length": 57.19298245614035,
"alnum_prop": 0.7067484662576687,
"repo_name": "Murphy-Lin/zhongqi",
"id": "c505f8d0a9b7983375a853a75e7b998c3cd40dde",
"size": "3268",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AndroidManifest.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6369"
},
{
"name": "HTML",
"bytes": "44670"
},
{
"name": "Java",
"bytes": "155787"
}
],
"symlink_target": ""
} |
import sys
import logging
import os
import string
import re
import datetime
import yaml
from commands import *
# Initialize logging
logging.basicConfig(format='%(asctime)s [%(levelname)s] %(name)s - %(message)s', level=logging.WARNING)
_log = logging.getLogger()
_log.setLevel(logging.INFO)
class Gbp_Verify(object):
def __init__( self ):
"""
Init def
"""
self.err_strings=['Conflict','Bad Request','Error','Unknown','Unable']
def gbp_action_verify(self,cmd_val,action_name,*args,**kwargs):
"""
-- cmd_val== 0:list; 1:show
-- action_name == UUID or name_string
List/Show Policy Action
kwargs addresses the need for passing required/optional params
"""
if cmd_val == '' or action_name == '':
_log.info('''Function Usage: gbp_action_verify 0 "abc" \n
--cmd_val == 0:list; 1:show\n
-- action_name == UUID or name_string\n''')
return 0
#Build the command with mandatory param 'action_name'
if cmd_val == 0:
cmd = 'gbp policy-action-list | grep %s'% str(action_name)
for arg in args:
cmd = cmd + ' | grep %s' % arg
if cmd_val == 1:
cmd = "gbp policy-action-show "+str(action_name)
#_log.info(cmd)
# Execute the policy-action-verify-cmd
cmd_out = getoutput(cmd)
#_log.info(cmd_out)
# Catch for non-exception error strings, even though try clause succeded
for err in self.err_strings:
if re.search('\\b%s\\b' %(err), cmd_out, re.I):
_log.info(cmd_out)
_log.info( "Cmd execution failed! with this Return Error: \n%s" %(cmd_out))
return 0
if cmd_val == 0:
for arg in args:
if cmd_out.find(arg) == -1 or cmd_out.find(action_name) == -1:
_log.info(cmd_out)
_log.info("The Attribute== %s DID NOT MATCH for the Action == %s in LIST cmd" %(arg,action_name))
return 0
# If try clause succeeds for "verify" cmd then parse the cmd_out to match the user-fed expected attributes & their values
if cmd_val == 1:
for arg, val in kwargs.items():
if re.search("\\b%s\\b\s+\| \\b%s\\b.*" %(arg,val),cmd_out,re.I)==None:
_log.info(cmd_out)
_log.info("The Attribute== %s and its Value== %s DID NOT MATCH for the Action == %s" %(arg,val,action_name))
return 0
#_log.info("All attributes & values found Valid for the object Policy Action == %s" %(action_name))
return 1
def gbp_classif_verify(self,cmd_val,classifier_name,*args,**kwargs):
"""
-- cmd_val== 0:list; 1:show
-- classifier_name == UUID or name_string
List/Show Policy Action
kwargs addresses the need for passing required/optional params
"""
if cmd_val == '' or classifier_name == '':
_log.info('''Function Usage: gbp_classif_verify(0,name) \n
--cmd_val == 0:list 1:show\n
-- classifier_name == UUID or name_string\n''')
return 0
#Build the command with mandatory param 'classifier_name'
if cmd_val == 0:
cmd = 'gbp policy-classifier-list | grep %s'% str(classifier_name)
for arg in args:
cmd = cmd + ' | grep %s' % arg
if cmd_val == 1:
cmd = "gbp policy-classifier-show "+str(classifier_name)
# Execute the policy-classifier-verify-cmd
cmd_out = getoutput(cmd)
#_log.info(cmd_out)
# Catch for non-exception error strings, even though try clause succeded
for err in self.err_strings:
if re.search('\\b%s\\b' %(err), cmd_out, re.I):
_log.info(cmd_out)
_log.info( "Cmd execution failed! with this Return Error: \n%s" %(cmd_out))
return 0
if cmd_val == 0:
for arg in args:
if cmd_out.find(arg) == -1 or cmd_out.find(classifier_name) == -1:
_log.info(cmd_out)
_log.info("The Attribute== %s DID NOT MATCH for the Classifier == %s in LIST cmd" %(arg,classifier_name))
return 0
# If try clause succeeds for "verify" cmd then parse the cmd_out to match the user-fed expected attributes & their values
if cmd_val == 1:
for arg, val in kwargs.items():
if re.search("\\b%s\\b\s+\| \\b%s\\b.*" %(arg,val),cmd_out,re.I)==None:
_log.info(cmd_out)
_log.info("The Attribute== %s and its Value== %s DID NOT MATCH for the Claasifier == %s" %(arg,val,classifier_name))
return 0
#_log.info("All attributes & values found Valid for the object Policy Classifier == %s" %(classifier_name))
return 1
def gbp_policy_verify_all(self,cmd_val,verifyobj,name_uuid,*args,**kwargs):
"""
--verifyobj== policy-*(where *=action;classifer,rule,rule-set,target-group,target)
--cmd_val== 0:list; 1:show
kwargs addresses the need for passing required/optional params
"""
verifyobj_dict={"action":"policy-action","classifier":"policy-classifier","rule":"policy-rule",
"ruleset":"policy-rule-set","group":"group","target":"policy-target"}
if verifyobj != '':
if verifyobj not in verifyobj_dict:
raise KeyError
if cmd_val == '' or name_uuid == '':
_log.info('''Function Usage: gbp_policy_verify_all(0,'action','name_uuid')\n
--cmd_val == 0:list; 1:show\n
-- name_uuid == UUID or name_string\n''')
return 0
#Build the command with mandatory params
if cmd_val == 0:
cmd = 'gbp %s-list | grep ' % verifyobj_dict[verifyobj]+str(name_uuid)
for arg in args:
cmd = cmd + ' | grep %s' % arg
if cmd_val == 1:
cmd = 'gbp %s-show ' % verifyobj_dict[verifyobj]+str(name_uuid)
# Execute the policy-object-verify-cmd
cmd_out = getoutput(cmd)
# Catch for non-exception error strings
for err in self.err_strings:
if re.search('\\b%s\\b' %(err), cmd_out, re.I):
_log.info(cmd_out)
_log.info( "Cmd execution failed! with this Return Error: \n%s" %(cmd_out))
return 0
if cmd_val == 0:
if cmd_out == '': # The case when grep returns null
return 0
else :
for arg in args:
if cmd_out.find(arg) == -1 or cmd_out.find(name_uuid) == -1:
_log.info(cmd_out)
_log.info("The Attribute== %s DID NOT MATCH for the Policy Object == %s in LIST cmd" %(arg,verifyobj))
return 0
# If "verify" cmd succeeds then parse the cmd_out to match the user-fed expected attributes & their values
if cmd_val == 1:
for arg, val in kwargs.items():
if re.search("\\b%s\\b\s+\| \\b%s\\b.*" %(arg,val),cmd_out,re.I)==None:
_log.info(cmd_out)
_log.info("The Attribute== %s and its Value== %s DID NOT MATCH for the PolicyObject == %s" %(arg,val,verifyobj))
return 0
#_log.info("All attributes & values found Valid for the object Policy %s" %(verifyobj))
return 1
def gbp_l2l3ntk_pol_ver_all(self,cmd_val,verifyobj,name_uuid,ret='',*args,**kwargs):
"""
--verifyobj== *policy(where *=l2;l3,network)
--cmd_val== 0:list; 1:show
--ret=='default' <<< function will return some attribute values depending upon the verifyobj
kwargs addresses the need for passing required/optional params
"""
verifyobj_dict={"l2p":"l2policy","l3p":"l3policy","nsp":"network-service-policy"}
if verifyobj != '':
if verifyobj not in verifyobj_dict:
raise KeyError
if cmd_val == '' or name_uuid == '':
_log.info('''Function Usage: gbp_l2l3ntk_pol_ver_all(0,'l2p','name') \n
--cmd_val == 0:list; 1:show\n
--name_uuid == UUID or name_string\n''')
return 0
#Build the command with mandatory params
if cmd_val == 0:
cmd = 'gbp %s-list | grep ' % verifyobj_dict[verifyobj]+str(name_uuid)
for arg in args:
cmd = cmd + ' | grep %s' % arg
if cmd_val == 1:
cmd = 'gbp %s-show ' % verifyobj_dict[verifyobj]+str(name_uuid)
# Execute the policy-object-verify-cmd
cmd_out = getoutput(cmd)
#_log.info(cmd_out)
# Catch for non-exception error strings
for err in self.err_strings:
if re.search('\\b%s\\b' %(err), cmd_out, re.I):
_log.info(cmd_out)
_log.info( "Cmd execution failed! with this Return Error: \n%s" %(cmd_out))
return 0
if cmd_val == 0:
if cmd_out == '': # The case when grep returns null
return 0
else :
for arg in args:
if cmd_out.find(arg) == -1 or cmd_out.find(name_uuid) == -1:
_log.info(cmd_out)
_log.info("The Attribute== %s DID NOT MATCH for the Policy Object == %s in LIST cmd" %(arg,verifyobj))
return 0
# If "verify" succeeds cmd then parse the cmd_out to match the user-fed expected attributes & their values
if cmd_val==1 and ret=='default':
for arg, val in kwargs.items():
if re.search("\\b%s\\b\s+\| \\b%s\\b.*" %(arg,val),cmd_out,re.I)==None:
_log.info(cmd_out)
_log.info("The Attribute== %s and its Value== %s DID NOT MATCH for the PolicyObject == %s" %(arg,val,verifyobj))
return 0
if verifyobj=="l2p":
match = re.search("\\bl3_policy_id\\b\s+\| (.*) \|" ,cmd_out,re.I)
l3pid = match.group(1)
match = re.search("\\bnetwork_id\\b\s+\| (.*) \|" ,cmd_out,re.I)
ntkid = match.group(1)
return l3pid.rstrip(),ntkid.rstrip()
if verifyobj=="l3p":
match = re.search("\\brouters\\b\s+\| (.*) \|" ,cmd_out,re.I)
rtrid = match.group(1)
return rtrid.rstrip()
elif cmd_val == 1:
for arg, val in kwargs.items():
if arg == 'network_service_params': #Had to make this extra block only for NSP
if re.findall('(%s)' %(val),cmd_out) == []:
_log.info(cmd_out)
_log.info("The Attribute== %s and its Value== %s DID NOT MATCH for the PolicyObject == %s" %(arg,val,verifyobj))
return 0
elif re.search("\\b%s\\b\s+\| \\b%s\\b.*" %(arg,val),cmd_out,re.I)==None:
_log.info(cmd_out)
_log.info("The Attribute== %s and its Value== %s DID NOT MATCH for the PolicyObject == %s" %(arg,val,verifyobj))
return 0
else:
#_log.info("All attributes & values found Valid for the Policy Object %s" %(verifyobj))
return 1
def neut_ver_all(self,verifyobj,name_uuid,ret='',**kwargs):
"""
--verifyobj== net,subnet,port,router
--ret=='default' <<< function will return some attribute values depending upon the verifyobj
kwargs addresses the need for passing required/optional params
"""
if name_uuid == '':
_log.info('''Function Usage: neut_ver_all('net','name')\n
-- name_uuid == UUID or name_string\n''')
return 0
#Build the command with mandatory params
cmd = 'neutron %s-show ' % verifyobj+str(name_uuid)
_log.info('Neutron Cmd == %s\n' %(cmd))
# Execute the policy-object-verify-cmd
cmd_out = getoutput(cmd)
_log.info(cmd_out)
# Catch for non-exception error strings
for err in self.err_strings:
if re.search('\\b%s\\b' %(err), cmd_out, re.I):
_log.info(cmd_out)
_log.info( "Neutron Cmd execution failed! with this Return Error: \n%s" %(cmd_out))
return 0
if ret !='':
match=re.search("\\b%s\\b\s+\| (.*) \|" %(ret),cmd_out,re.I)
if match != None:
return match.group(1).rstrip()
else:
return 0
for arg, val in kwargs.items():
if isinstance(val,list): ## This is a case where more than 1 value is to verified for a given attribute
for i in val:
if cmd_out.find(i) == -1:
_log.info(cmd_out)
_log.info("The Attribute== %s and its Value== %s DID NOT MATCH for the NeutronObject == %s" %(arg,i,verifyobj))
return 0
else:
if re.search("\\b%s\\b\s+\| \\b%s\\b.*" %(arg,val),cmd_out,re.I)==None:
_log.info(cmd_out)
_log.info("The Attribute== %s and its Value== %s DID NOT MATCH for the NeutronObject == %s" %(arg,val,verifyobj))
return 0
#_log.info("All attributes & values found Valid for the object Policy %s" %(verifyobj))
return 1
def gbp_obj_ver_attr_all_values(self,verifyobj,name_uuid,attr,values):
"""
Function will verify multiple entries for any given attribute
of a Policy Object
--values=Must be a list
"""
verifyobj_dict={"action":"policy-action","classifier":"policy-classifier","rule":"policy-rule",
"ruleset":"policy-rule-set","group":"group","target":"policy-target",
"l2p":"l2policy","l3p":"l3policy","nsp":"network-service-policy"}
if verifyobj != '':
if verifyobj not in verifyobj_dict:
raise KeyError
if not isinstance(values,list):
raise TypeError
#Build the command with mandatory params
cmd = 'gbp %s-show ' % verifyobj_dict[verifyobj]+str(name_uuid)+' -F %s' %(attr)
# Execute the policy-object-verify-cmd
cmd_out = getoutput(cmd)
# Catch for non-exception error strings
for err in self.err_strings:
if re.search('\\b%s\\b' %(err), cmd_out, re.I):
_log.info( "Cmd execution failed! with this Return Error: \n%s" %(cmd_out))
return 0
_misses=[]
for val in values:
if cmd_out.find(val)==-1:
_misses.append(val)
if len(_misses)>0:
_log.info("\nFollowing Values of the Attribute for the Policy Object was NOT FOUND=%s" %(_misses))
return 0
#_log.info("All attributes & values found Valid for the object Policy %s" %(verifyobj))
return 1
def get_uuid_from_stack(self,yaml_file,heat_stack_name):
"""
Fetches the UUID of the GBP Objects created by Heat
"""
with open(yaml_file,'rt') as f:
heat_conf = yaml.load(f)
obj_uuid = {}
outputs_dict = heat_conf["outputs"] # This comprise dictionary with keys as in [outputs] block of yaml-based heat template
print outputs_dict
for key in outputs_dict.iterkeys():
cmd = 'heat stack-show %s | grep -B 2 %s' %(heat_stack_name,key)
print cmd
cmd_out = getoutput(cmd)
print cmd_out
match = re.search('\"\\boutput_value\\b\": \"(.*)\"' ,cmd_out,re.I)
if match != None:
obj_uuid[key] = match.group(1)
return obj_uuid
| {
"content_hash": "12e5c2c74319cd1b6080f013e0e3d773",
"timestamp": "",
"source": "github",
"line_count": 328,
"max_line_length": 132,
"avg_line_length": 47.68292682926829,
"alnum_prop": 0.5378516624040921,
"repo_name": "tbachman/group-based-policy",
"id": "f12662cda7b0e763623355325a4334edb9e399e0",
"size": "16213",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gbpservice/tests/contrib/gbpfunctests/libs/verify_libs.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Python",
"bytes": "2130911"
},
{
"name": "Shell",
"bytes": "28973"
}
],
"symlink_target": ""
} |
/***************************************************************************
* Server GUI "angelina" for "Projektkurs C++" WS 07/08 *
* *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "playground.h"
#include "pillar.h"
#include "defines.h"
#include "angelinaapplication.h"
#include <math.h>
#include <QPainter>
void Playground::reset()
{
robots.clear();
}
void Playground::placeRobot(const QColor &color, int teamID, double xpos, double ypos)
{
robots[teamID].color = color;
robots[teamID].x = xpos;
robots[teamID].y = ypos;
update();
}
void Playground::activateMeasurement(const QPointF &pos)
{
for(int i = 0; i < pillarList.size(); i++)
{
QPointF distVec = pillarList[i]->pos() - pos;
double dist = sqrt(distVec.x() * distVec.x() + distVec.y() * distVec.y());
pillarList[i]->showDistance(dist);
}
update();
}
void Playground::deactivateMeasurement()
{
for(int i = 0; i < pillarList.size(); i++)
{
pillarList[i]->hideDistance();
}
update();
}
void Playground::generateNewShape(double a, double b)
{
// TODO: Remove this function and also shape(), otherwise the collision detection of QGraphicsScene will fail
shapeP = QPainterPath();
if(a && b)
{
myA = a * PPME;
myB = b * PPME;
}
double currentX = 0.0;
double currentY = 0.0;
shapeP.addRect(currentX, currentY, 3.0*myA, myB);
// Upper border of playground
pillarList[0]->setPos(currentX, currentY);
currentX += myA/4.0;
pillarList[1]->setPos(currentX, currentY);
currentX += myA*(3.0/4.0);
pillarList[2]->setPos(currentX, currentY);
currentX += myA/2.0;
pillarList[3]->setPos(currentX, currentY);
currentX += myA/2.0;
pillarList[4]->setPos(currentX, currentY);
currentX += myA*(3.0/4.0);
pillarList[5]->setPos(currentX, currentY);
currentX += myA/4.0;
pillarList[6]->setPos(currentX, currentY);
// Lower border of playground
currentX = 0.0;
currentY += myB;
pillarList[7]->setPos(currentX, currentY);
currentX += myA/4.0;
pillarList[8]->setPos(currentX, currentY);
currentX += myA*(3.0/4.0);
pillarList[9]->setPos(currentX, currentY);
currentX += myA/2.0;
pillarList[10]->setPos(currentX, currentY);
currentX += myA/2.0;
pillarList[11]->setPos(currentX, currentY);
currentX += myA*(3.0/4.0);
pillarList[12]->setPos(currentX, currentY);
currentX += myA/4.0;
pillarList[13]->setPos(currentX, currentY);
}
void Playground::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
painter->setRenderHint(QPainter::Antialiasing);
// Actual playground
painter->setPen(Qt::black);
painter->setBrush(Qt::lightGray);
painter->drawPath(shapeP);
// Blue goal
painter->setPen(Qt::NoPen);
painter->setBrush(QColor(128,128,255));
painter->drawRect(myA/4.0, myB/2.0 - myB/6.0, myA/4.0, myB/3.0);
// Yellow goal
painter->setBrush(Qt::yellow);
painter->drawRect(3.0*myA - myA/4.0, myB/2.0 - myB/6.0, -myA/4.0, myB/3.0);
// Red lines (goals, center)
painter->setPen(QPen(Qt::red, 2.0, Qt::SolidLine));
painter->drawLine(myA/4.0, 0, myA/4.0, myB);
painter->drawLine(1.5*myA, 0, 1.5*myA, myB);
painter->drawLine((2.0 + 3.0/4.0)*myA, 0, (2.0 + 3.0/4.0)*myA, myB);
// Blue lines (neutral zone)
painter->setPen(QPen(Qt::blue, 2.0, Qt::SolidLine));
painter->drawLine(myA, 0, myA, myB);
painter->drawLine(2.0*myA, 0, 2.0*myA, myB);
//Robots
foreach(Robot robot, robots)
{
painter->setPen(Qt::black);
painter->setBrush(robot.color);
/* Actual robot is 30x20 cm, but we don't know the orientation, so we're
* painting a circle.
*/
painter->drawEllipse(-0.15*PPME + robot.x*PPME, -0.15*PPME + robot.y*PPME, 0.3*PPME, 0.3*PPME);
}
}
QRectF Playground::boundingRect() const
{
// Additional surroundings, looks better than no border at all
return QRectF(-0.5*PPME, -0.5*PPME, 3.0*myA + 1.0*PPME, myB + 1.0*PPME);
}
double Playground::getA() const
{
return myA / PPME;
}
double Playground::getB() const
{
return myB / PPME;
}
Playground::Playground():
myA(angelinaApp->getDefaultA() * PPME),
myB(angelinaApp->getDefaultB() * PPME)
{
for(int i = 0; i < 14; i++)
{
Pillar *pillar = new Pillar;
pillar->setParentItem(this);
pillarList << pillar;
}
generateNewShape();
}
| {
"content_hash": "9df08f1dc83fcd13a3d76538d6e08aa0",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 110,
"avg_line_length": 29.85,
"alnum_prop": 0.604317885724921,
"repo_name": "jdsika/TUM_AdvancedCourseCPP",
"id": "167dd83e4b47b7eb1e8ea73e0d3515ae914dbd1c",
"size": "5373",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "angelina/angelina/angelina/playground.cpp",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "29364"
},
{
"name": "C++",
"bytes": "2352728"
},
{
"name": "CMake",
"bytes": "54668"
},
{
"name": "Makefile",
"bytes": "53856"
},
{
"name": "PHP",
"bytes": "2324"
},
{
"name": "Shell",
"bytes": "407"
},
{
"name": "SourcePawn",
"bytes": "39321"
}
],
"symlink_target": ""
} |
var ometajs_ = require("ometajs");
var AbstractGrammar = ometajs_.grammars.AbstractGrammar;
var BSJSParser = ometajs_.grammars.BSJSParser;
var BSJSIdentity = ometajs_.grammars.BSJSIdentity;
var BSJSTranslator = ometajs_.grammars.BSJSTranslator;
var IokeLexer = function IokeLexer(source, opts) {
AbstractGrammar.call(this, source, opts);
};
IokeLexer.grammarName = "IokeLexer";
IokeLexer.match = AbstractGrammar.match;
IokeLexer.matchAll = AbstractGrammar.matchAll;
exports.IokeLexer = IokeLexer;
require("util").inherits(IokeLexer, AbstractGrammar);
IokeLexer.prototype["sChar"] = function $sChar() {
return this._atomic(function() {
var c;
return this._match("\\") && this._rule("char", false, [], null, this["char"]) && (c = this._getIntermediate(), true) && this._exec(JSON.parse("'\\" + c + "'"));
}) || this._atomic(function() {
var c;
return this._rule("char", false, [], null, this["char"]) && (c = this._getIntermediate(), true) && this._exec(c);
});
};
IokeLexer.prototype["iStartChar"] = function $iStartChar() {
var c;
return this._rule("char", false, [], null, this["char"]) && (c = this._getIntermediate(), true) && !(c >= "0" && c <= "9" || c == "." || c == "!" || c == "?" || c == " " || c == " " || c == "\n" || c == "" || c == "(" || c == ")" || c == "[" || c == "]" || c == "=");
};
IokeLexer.prototype["iEndChar"] = function $iEndChar() {
return this._atomic(function() {
var c;
return this._rule("iChar", false, [], null, this["iChar"]) && (c = this._getIntermediate(), true) && !(c == ":");
}) || this._match("!") || this._match("?");
};
IokeLexer.prototype["iChar"] = function $iChar() {
return this._atomic(function() {
return this._rule("iStartChar", false, [], null, this["iStartChar"]);
}) || this._atomic(function() {
return this._rule("digit", false, [], null, this["digit"]);
});
};
IokeLexer.prototype["identifier"] = function $identifier() {
return this._atomic(function() {
return this._rule("iStartChar", false, [], null, this["iStartChar"]) && this._any(function() {
return this._atomic(function() {
return this._rule("iChar", false, [], null, this["iChar"]);
});
}) && this._rule("iEndChar", false, [], null, this["iEndChar"]);
}) || this._atomic(function() {
return this._rule("iStartChar", false, [], null, this["iStartChar"]) && this._optional(function() {
return this._rule("iEndChar", false, [], null, this["iEndChar"]);
});
}) || this._atomic(function() {
return this._rule("operator", false, [], null, this["operator"]);
});
};
IokeLexer.prototype["operator"] = function $operator() {
return this._match("/") || this._match("|") || this._atomic(function() {
return this._match("|") && this._match("|");
}) || this._atomic(function() {
return this._match("&") && this._match("&");
}) || this._match("&") || this._atomic(function() {
return this._match("=") && this._match("=");
}) || this._atomic(function() {
return this._match("!") && this._match("=");
}) || this._atomic(function() {
return this._match("<") && this._match("=");
}) || this._atomic(function() {
return this._match(">") && this._match("=");
}) || this._match("<") || this._match(">");
};
IokeLexer.prototype["seperator"] = function $seperator() {
return this._match(" ");
};
IokeLexer.prototype["newline"] = function $newline() {
return this._atomic(function() {
return this._match("\r") && this._match("\n");
}) || this._match("\n") || this._match("\r");
};
IokeLexer.prototype["terminator"] = function $terminator() {
return this._match(".");
};
IokeLexer.prototype["openParen"] = function $openParen() {
return this._match("(");
};
IokeLexer.prototype["closeParen"] = function $closeParen() {
return this._match(")");
};
IokeLexer.prototype["comma"] = function $comma() {
return this._match(",");
};
IokeLexer.prototype["openSquare"] = function $openSquare() {
return this._match("[");
};
IokeLexer.prototype["closeSquare"] = function $closeSquare() {
return this._match("]");
};
IokeLexer.prototype["colon"] = function $colon() {
return this._match(":");
};
IokeLexer.prototype["hashrocket"] = function $hashrocket() {
return this._match("=") && this._match(">");
}; | {
"content_hash": "e38f56b08f4883820e1d07bd8a78c246",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 271,
"avg_line_length": 35.039370078740156,
"alnum_prop": 0.5683146067415731,
"repo_name": "CoderPuppy/loke-lang",
"id": "eb5023e9a2b9c25ab745a9d281c89ea3e06fedfe",
"size": "4450",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/parser/lexer.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "20426"
}
],
"symlink_target": ""
} |
package stackongo
import "strings"
// WikisForTags returns the wikis that go with the given set of tags
func (session Session) WikisForTags(tags []string, params map[string]string) (output *TagWikis, error error) {
request_path := strings.Join([]string{"tags", strings.Join(tags, ";"), "wikis"}, "/")
output = new(TagWikis)
error = session.get(request_path, params, output)
return
}
| {
"content_hash": "a10a225881a8ed9f94533b6c09e88fac",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 110,
"avg_line_length": 32.583333333333336,
"alnum_prop": 0.7186700767263428,
"repo_name": "laktek/Stack-on-Go",
"id": "f8397c290ba647baaee620d9789101b667d9146d",
"size": "391",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "stackongo/tag_wikis.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "138326"
}
],
"symlink_target": ""
} |
/**
* Command line Interface for the proxy server
* @author David Moss
*/
#include <ctype.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "proxycli.h"
#include "proxyserver.h"
#include "ioterror.h"
#include "iotdebug.h"
/** Port number */
static int port = DEFAULT_PROXY_PORT;
/** Pointer to the activation key string */
static char *activationKey;
/** Configuration file containing non-volatile proxy information */
static char configFilename[PROXYCLI_CONFIG_FILE_PATH_SIZE];
/***************** Private Prototypes ****************/
static void _proxycli_printUsage();
static void _proxycli_printVersion();
/***************** Public Functions ****************/
/**
* Parse the command line arguments, to be retrieved by getter functions when
* needed
*/
void proxycli_parse(int argc, char *argv[]) {
int c;
strncpy(configFilename, DEFAULT_PROXY_CONFIG_FILENAME, PROXYCLI_CONFIG_FILE_PATH_SIZE);
while ((c = getopt(argc, argv, "c:p:a:v")) != -1) {
switch (c) {
case 'c':
strncpy(configFilename, optarg, PROXYCLI_CONFIG_FILE_PATH_SIZE);
printf("[cli] Proxy config file set to %s\n", configFilename);
SYSLOG_INFO("[cli] Proxy config file set to %s", configFilename);
break;
case 'p':
// Set the port number
port = atoi(optarg);
break;
case 'a':
// Register using the given activation code
activationKey = optarg;
printf("[cli] Activating with key %s\n", activationKey);
SYSLOG_INFO("[cli] Activating with key %s", activationKey);
break;
case 'v':
_proxycli_printVersion();
exit(0);
break;
case '?':
_proxycli_printUsage();
exit(1);
break;
default:
printf("[cli] Unknown argument character code 0%o\n", c);
SYSLOG_ERR ("[cli] Unknown argument character code 0%o\n", c);
_proxycli_printUsage();
exit(1);
break;
}
}
}
/**
* @return the port number to open on
*/
int proxycli_getPort() {
return port;
}
/**
* @return the activation key, NULL if it was never set
*/
const char *proxycli_getActivationKey() {
return activationKey;
}
/**
* @return The configuration filename for the proxy
*/
const char *proxycli_getConfigFilename() {
return configFilename;
}
/***************** Private Functions ****************/
/**
* Instruct the user how to use the application
*/
static void _proxycli_printUsage() {
char *usage = ""
"Usage: ./proxyserver (options)\n"
"\t[-p port] : Define the port to open the proxy on\n"
"\t[-c filename] : The name of the configuration file for the proxy\n"
"\t[-a key] : Activate this proxy using the given activation key and exit\n"
"\t[-v] : Print version information\n"
"\t[-?] : Print this menu\n";
printf("%s", usage);
SYSLOG_INFO("%s", usage);
}
/**
* Print the version number
*/
static void _proxycli_printVersion() {
printf("Built on %s at %s\n", __DATE__, __TIME__);
printf("Git repository version %x\n", GIT_FIRMWARE_VERSION);
}
| {
"content_hash": "4a107a8c51edc294f728deb766b60e8b",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 89,
"avg_line_length": 23.83076923076923,
"alnum_prop": 0.6249193027759845,
"repo_name": "vprabu/iotsdk",
"id": "e51d7b4c11c41ade15d949e6c09fdb5bacfe2653",
"size": "4777",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "c/apps/proxyserver/cli/proxycli.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
/*
Do Exercise 5 but use a two-dimensional array to store input for 3
years of monthly sales. Report the total sales for each individual year
and for the combined years.
*/
#include <iostream>
using namespace std;
int main()
{
const int Months = 12;
const int Years = 3;
const char * monthNames[Months] = { "January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November", "December" };
int soldBooks[Years][Months] = {};
for (int i = 0; i < Years; ++i)
{
for (int j = 0; j < Months; ++j)
{
cout << "Enter a number of books sold during " << i + 1 << " year in " << monthNames[j] << ": ";
cin >> soldBooks[i][j];
}
}
int totalSales = 0;
for (int i = 0; i < Years; ++i)
{
int salesPerYear = 0;
for (int j = 0; j < Months; ++j)
salesPerYear += soldBooks[i][j];
cout << "The total sales for the " << i + 1 << " year: " << salesPerYear << endl;
totalSales += salesPerYear;
}
cout << "The total sales for " << Years << " years: " << totalSales << endl;
}
| {
"content_hash": "5d27b53130eed3857267de9ddaf8688a",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 108,
"avg_line_length": 31.2972972972973,
"alnum_prop": 0.5328151986183074,
"repo_name": "koponomarenko/prata-cpp-6th-edition-2016",
"id": "e4cdc3b8a56ec1f38ce1924dd4b330e95e264957",
"size": "1158",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chapter_05/task_06.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "60874"
},
{
"name": "Makefile",
"bytes": "2694"
}
],
"symlink_target": ""
} |
/*global tinymce:true */
tinymce.PluginManager.add('fullpage', function(editor) {
var each = tinymce.each, Node = tinymce.html.Node;
var head, foot;
function showDialog() {
var data = htmlToData();
editor.windowManager.open({
title: 'Document properties',
data: data,
defaults: {type: 'textbox', size: 40},
body: [
{name: 'title', label: 'Title'},
{name: 'keywords', label: 'Keywords'},
{name: 'description', label: 'Description'},
{name: 'robots', label: 'Robots'},
{name: 'author', label: 'Author'},
{name: 'docencoding', label: 'Encoding'}
],
onSubmit: function(e) {
dataToHtml(tinymce.extend(data, e.data));
}
});
}
function htmlToData() {
var headerFragment = parseHeader(), data = {}, elm, matches;
function getAttr(elm, name) {
var value = elm.attr(name);
return value || '';
}
// Default some values
data.fontface = editor.getParam("fullpage_default_fontface", "");
data.fontsize = editor.getParam("fullpage_default_fontsize", "");
// Parse XML PI
elm = headerFragment.firstChild;
if (elm.type == 7) {
data.xml_pi = true;
matches = /encoding="([^"]+)"/.exec(elm.value);
if (matches) {
data.docencoding = matches[1];
}
}
// Parse doctype
elm = headerFragment.getAll('#doctype')[0];
if (elm) {
data.doctype = '<!DOCTYPE' + elm.value + ">";
}
// Parse title element
elm = headerFragment.getAll('title')[0];
if (elm && elm.firstChild) {
data.title = elm.firstChild.value;
}
// Parse meta elements
each(headerFragment.getAll('meta'), function(meta) {
var name = meta.attr('name'), httpEquiv = meta.attr('http-equiv'), matches;
if (name) {
data[name.toLowerCase()] = meta.attr('content');
} else if (httpEquiv == "Content-Type") {
matches = /charset\s*=\s*(.*)\s*/gi.exec(meta.attr('content'));
if (matches) {
data.docencoding = matches[1];
}
}
});
// Parse html attribs
elm = headerFragment.getAll('html')[0];
if (elm) {
data.langcode = getAttr(elm, 'lang') || getAttr(elm, 'xml:lang');
}
// Parse stylesheets
data.stylesheets = [];
tinymce.each(headerFragment.getAll('link'), function(link) {
if (link.attr('rel') == 'stylesheet') {
data.stylesheets.push(link.attr('href'));
}
});
// Parse body parts
elm = headerFragment.getAll('body')[0];
if (elm) {
data.langdir = getAttr(elm, 'dir');
data.style = getAttr(elm, 'style');
data.visited_color = getAttr(elm, 'vlink');
data.link_color = getAttr(elm, 'link');
data.active_color = getAttr(elm, 'alink');
}
return data;
}
function dataToHtml(data) {
var headerFragment, headElement, html, elm, value, dom = editor.dom;
function setAttr(elm, name, value) {
elm.attr(name, value ? value : undefined);
}
function addHeadNode(node) {
if (headElement.firstChild) {
headElement.insert(node, headElement.firstChild);
} else {
headElement.append(node);
}
}
headerFragment = parseHeader();
headElement = headerFragment.getAll('head')[0];
if (!headElement) {
elm = headerFragment.getAll('html')[0];
headElement = new Node('head', 1);
if (elm.firstChild) {
elm.insert(headElement, elm.firstChild, true);
} else {
elm.append(headElement);
}
}
// Add/update/remove XML-PI
elm = headerFragment.firstChild;
if (data.xml_pi) {
value = 'version="1.0"';
if (data.docencoding) {
value += ' encoding="' + data.docencoding + '"';
}
if (elm.type != 7) {
elm = new Node('xml', 7);
headerFragment.insert(elm, headerFragment.firstChild, true);
}
elm.value = value;
} else if (elm && elm.type == 7) {
elm.remove();
}
// Add/update/remove doctype
elm = headerFragment.getAll('#doctype')[0];
if (data.doctype) {
if (!elm) {
elm = new Node('#doctype', 10);
if (data.xml_pi) {
headerFragment.insert(elm, headerFragment.firstChild);
} else {
addHeadNode(elm);
}
}
elm.value = data.doctype.substring(9, data.doctype.length - 1);
} else if (elm) {
elm.remove();
}
// Add meta encoding
elm = null;
each(headerFragment.getAll('meta'), function(meta) {
if (meta.attr('http-equiv') == 'Content-Type') {
elm = meta;
}
});
if (data.docencoding) {
if (!elm) {
elm = new Node('meta', 1);
elm.attr('http-equiv', 'Content-Type');
elm.shortEnded = true;
addHeadNode(elm);
}
elm.attr('content', 'text/html; charset=' + data.docencoding);
} else if (elm) {
elm.remove();
}
// Add/update/remove title
elm = headerFragment.getAll('title')[0];
if (data.title) {
if (!elm) {
elm = new Node('title', 1);
addHeadNode(elm);
} else {
elm.empty();
}
elm.append(new Node('#text', 3)).value = data.title;
} else if (elm) {
elm.remove();
}
// Add/update/remove meta
each('keywords,description,author,copyright,robots'.split(','), function(name) {
var nodes = headerFragment.getAll('meta'), i, meta, value = data[name];
for (i = 0; i < nodes.length; i++) {
meta = nodes[i];
if (meta.attr('name') == name) {
if (value) {
meta.attr('content', value);
} else {
meta.remove();
}
return;
}
}
if (value) {
elm = new Node('meta', 1);
elm.attr('name', name);
elm.attr('content', value);
elm.shortEnded = true;
addHeadNode(elm);
}
});
var currentStyleSheetsMap = {};
tinymce.each(headerFragment.getAll('link'), function(stylesheet) {
if (stylesheet.attr('rel') == 'stylesheet') {
currentStyleSheetsMap[stylesheet.attr('href')] = stylesheet;
}
});
// Add new
tinymce.each(data.stylesheets, function(stylesheet) {
if (!currentStyleSheetsMap[stylesheet]) {
elm = new Node('link', 1);
elm.attr({
rel: 'stylesheet',
text: 'text/css',
href: stylesheet
});
elm.shortEnded = true;
addHeadNode(elm);
}
delete currentStyleSheetsMap[stylesheet];
});
// Delete old
tinymce.each(currentStyleSheetsMap, function(stylesheet) {
stylesheet.remove();
});
// Update body attributes
elm = headerFragment.getAll('body')[0];
if (elm) {
setAttr(elm, 'dir', data.langdir);
setAttr(elm, 'style', data.style);
setAttr(elm, 'vlink', data.visited_color);
setAttr(elm, 'link', data.link_color);
setAttr(elm, 'alink', data.active_color);
// Update iframe body as well
dom.setAttribs(editor.getBody(), {
style : data.style,
dir : data.dir,
vLink : data.visited_color,
link : data.link_color,
aLink : data.active_color
});
}
// Set html attributes
elm = headerFragment.getAll('html')[0];
if (elm) {
setAttr(elm, 'lang', data.langcode);
setAttr(elm, 'xml:lang', data.langcode);
}
// No need for a head element
if (!headElement.firstChild) {
headElement.remove();
}
// Serialize header fragment and crop away body part
html = new tinymce.html.Serializer({
validate: false,
indent: true,
apply_source_formatting : true,
indent_before: 'head,html,body,meta,title,script,link,style',
indent_after: 'head,html,body,meta,title,script,link,style'
}).serialize(headerFragment);
head = html.substring(0, html.indexOf('</body>'));
}
function parseHeader() {
// Parse the contents with a DOM parser
return new tinymce.html.DomParser({
validate: false,
root_name: '#document'
}).parse(head);
}
function setContent(evt) {
var startPos, endPos, content = evt.content, headerFragment, styles = '', dom = editor.dom, elm;
if (evt.selection) {
return;
}
function low(s) {
return s.replace(/<\/?[A-Z]+/g, function(a) {
return a.toLowerCase();
});
}
// Ignore raw updated if we already have a head, this will fix issues with undo/redo keeping the head/foot separate
if (evt.format == 'raw' && head) {
return;
}
if (evt.source_view && editor.getParam('fullpage_hide_in_source_view')) {
return;
}
// Parse out head, body and footer
content = content.replace(/<(\/?)BODY/gi, '<$1body');
startPos = content.indexOf('<body');
if (startPos != -1) {
startPos = content.indexOf('>', startPos);
head = low(content.substring(0, startPos + 1));
endPos = content.indexOf('</body', startPos);
if (endPos == -1) {
endPos = content.length;
}
evt.content = content.substring(startPos + 1, endPos);
foot = low(content.substring(endPos));
} else {
head = getDefaultHeader();
foot = '\n</body>\n</html>';
}
// Parse header and update iframe
headerFragment = parseHeader();
each(headerFragment.getAll('style'), function(node) {
if (node.firstChild) {
styles += node.firstChild.value;
}
});
elm = headerFragment.getAll('body')[0];
if (elm) {
dom.setAttribs(editor.getBody(), {
style: elm.attr('style') || '',
dir: elm.attr('dir') || '',
vLink: elm.attr('vlink') || '',
link: elm.attr('link') || '',
aLink: elm.attr('alink') || ''
});
}
dom.remove('fullpage_styles');
var headElm = editor.getDoc().getElementsByTagName('head')[0];
if (styles) {
dom.add(headElm, 'style', {
id : 'fullpage_styles'
}, styles);
// Needed for IE 6/7
elm = dom.get('fullpage_styles');
if (elm.styleSheet) {
elm.styleSheet.cssText = styles;
}
}
var currentStyleSheetsMap = {};
tinymce.each(headElm.getElementsByTagName('link'), function(stylesheet) {
if (stylesheet.rel == 'stylesheet' && stylesheet.getAttribute('data-mce-fullpage')) {
currentStyleSheetsMap[stylesheet.href] = stylesheet;
}
});
// Add new
tinymce.each(headerFragment.getAll('link'), function(stylesheet) {
var href = stylesheet.attr('href');
if (!currentStyleSheetsMap[href] && stylesheet.attr('rel') == 'stylesheet') {
dom.add(headElm, 'link', {
rel: 'stylesheet',
text: 'text/css',
href: href,
'data-mce-fullpage': '1'
});
}
delete currentStyleSheetsMap[href];
});
// Delete old
tinymce.each(currentStyleSheetsMap, function(stylesheet) {
stylesheet.parentNode.removeChild(stylesheet);
});
}
function getDefaultHeader() {
var header = '', value, styles = '';
if (editor.getParam('fullpage_default_xml_pi')) {
header += '<?xml version="1.0" encoding="' + editor.getParam('fullpage_default_encoding', 'ISO-8859-1') + '" ?>\n';
}
header += editor.getParam('fullpage_default_doctype', '<!DOCTYPE html>');
header += '\n<html>\n<head>\n';
if ((value = editor.getParam('fullpage_default_title'))) {
header += '<title>' + value + '</title>\n';
}
if ((value = editor.getParam('fullpage_default_encoding'))) {
header += '<meta http-equiv="Content-Type" content="text/html; charset=' + value + '" />\n';
}
if ((value = editor.getParam('fullpage_default_font_family'))) {
styles += 'font-family: ' + value + ';';
}
if ((value = editor.getParam('fullpage_default_font_size'))) {
styles += 'font-size: ' + value + ';';
}
if ((value = editor.getParam('fullpage_default_text_color'))) {
styles += 'color: ' + value + ';';
}
header += '</head>\n<body' + (styles ? ' style="' + styles + '"' : '') + '>\n';
return header;
}
function getContent(evt) {
if (!evt.selection && (!evt.source_view || !editor.getParam('fullpage_hide_in_source_view'))) {
evt.content = tinymce.trim(head) + '\n' + tinymce.trim(evt.content) + '\n' + tinymce.trim(foot);
}
}
editor.addCommand('mceFullPageProperties', showDialog);
editor.addButton('fullpage', {
title: 'Document properties',
cmd : 'mceFullPageProperties'
});
editor.addMenuItem('fullpage', {
text: 'Document properties',
cmd : 'mceFullPageProperties',
context: 'file'
});
editor.on('BeforeSetContent', setContent);
editor.on('GetContent', getContent);
});
| {
"content_hash": "c1616cf6648a16c34b4a94e9f9485978",
"timestamp": "",
"source": "github",
"line_count": 477,
"max_line_length": 118,
"avg_line_length": 24.67714884696017,
"alnum_prop": 0.6140514824568856,
"repo_name": "killer-djon/dev-v2.web2book.ru",
"id": "06ff68410c9ad8c71cfd345ea11f7ed1b0d4592a",
"size": "11960",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/mixins/javascripts/tinymce4/plugins/fullpage/plugin.js",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "13"
},
{
"name": "CSS",
"bytes": "13253679"
},
{
"name": "HTML",
"bytes": "2708644"
},
{
"name": "Java",
"bytes": "1488388"
},
{
"name": "JavaScript",
"bytes": "30071773"
},
{
"name": "PHP",
"bytes": "24516943"
},
{
"name": "Python",
"bytes": "3330"
},
{
"name": "Ruby",
"bytes": "10354"
},
{
"name": "Shell",
"bytes": "6018"
},
{
"name": "Smarty",
"bytes": "15040"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("06. Sum Reversed Numbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06. Sum Reversed Numbers")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9bd8a2a5-ed35-496a-9577-e2d1de06a58d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "2e098601778c6af87202409e83f50fc6",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 39.333333333333336,
"alnum_prop": 0.7464689265536724,
"repo_name": "Stradjazz/SoftUni",
"id": "ea7bfc36dced04c2de4a0fb9819bb9e6246b2498",
"size": "1419",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Programming Fundamentals/19. Lists Exercises/06. Sum Reversed Numbers/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "197"
},
{
"name": "C#",
"bytes": "1572299"
},
{
"name": "CSS",
"bytes": "1026"
},
{
"name": "HTML",
"bytes": "64349"
},
{
"name": "JavaScript",
"bytes": "452482"
}
],
"symlink_target": ""
} |
describe("A suite", function () {
it("contains spec with an expectation", function () {
expect(true).toBe(true);
});
});
describe("A suite is just a function", function () {
var a;
it("and so is a spec", function () {
a = true;
expect(a).toBe(true);
});
});
describe("The 'toBe' matcher compares with ===", function () {
it("and has a positive case", function () {
expect(true).toBe(true);
});
it("and can have a negative case", function () {
expect(false).not.toBe(true);
});
});
describe("Included matchers:", function () {
it("The 'toBe' matcher compares with ===", function () {
var a = 12;
var b = a;
expect(a).toBe(b);
expect(a).not.toBe(null);
});
describe("The 'toEqual' matcher", function () {
it("works for simple literals and variables", function () {
var a = 12;
expect(a).toEqual(12);
});
it("should work for objects", function () {
var foo = {
a: 12,
b: 34
};
var bar = {
a: 12,
b: 34
};
expect(foo).toEqual(bar);
});
});
it("The 'toMatch' matcher is for regular expressions", function () {
var message = "foo bar baz";
expect(message).toMatch(/bar/);
expect(message).toMatch("bar");
expect(message).not.toMatch(/quux/);
});
it("The 'toBeDefined' matcher compares against `undefined`", function () {
var a = {
foo: "foo"
};
expect(a.foo).toBeDefined();
expect(a.bar).not.toBeDefined();
});
it("The `toBeUndefined` matcher compares against `undefined`", function () {
var a = {
foo: "foo"
};
expect(a.foo).not.toBeUndefined();
expect(a.bar).toBeUndefined();
});
it("The 'toBeNull' matcher compares against null", function () {
var a = null;
var foo = "foo";
expect(null).toBeNull();
expect(a).toBeNull();
expect(foo).not.toBeNull();
});
it("The 'toBeTruthy' matcher is for boolean casting testing", function () {
var a, foo = "foo";
expect(foo).toBeTruthy();
expect(a).not.toBeTruthy();
});
it("The 'toBeFalsy' matcher is for boolean casting testing", function () {
var a, foo = "foo";
expect(a).toBeFalsy();
expect(foo).not.toBeFalsy();
});
it("The 'toContain' matcher is for finding an item in an Array", function () {
var a = ["foo", "bar", "baz"];
expect(a).toContain("bar");
expect(a).not.toContain("quux");
});
it("The 'toBeLessThan' matcher is for mathematical comparisons", function () {
var pi = 3.1415926, e = 2.78;
expect(e).toBeLessThan(pi);
expect(pi).not.toBeLessThan(e);
});
it("The 'toBeGreaterThan' is for mathematical comparisons", function () {
var pi = 3.1415926, e = 2.78;
expect(pi).toBeGreaterThan(e);
expect(e).not.toBeGreaterThan(pi);
});
it("The 'toBeCloseTo' matcher is for precision math comparison", function () {
var pi = 3.1415926, e = 2.78;
expect(pi).not.toBeCloseTo(e, 2);
expect(pi).toBeCloseTo(e, 0);
});
it("The 'toThrow' matcher is for testing if a function throws an exception", function () {
var foo = function () {
return 1 + 2;
};
var bar = function () {
var a = undefined;
return a + 1;
};
expect(foo).not.toThrow();
expect(bar).toThrow();
});
it("The 'toThrowError' matcher is for testing a specific thrown exception", function () {
var foo = function () {
throw new TypeError("foo bar baz");
};
expect(foo).toThrowError("foo bar baz");
expect(foo).toThrowError(/bar/);
expect(foo).toThrowError(TypeError);
expect(foo).toThrowError(TypeError, "foo bar baz");
});
});
describe("A spec", function () {
it("is just a function, so it can contain any code", function () {
var foo = 0;
foo += 1;
expect(foo).toEqual(1);
});
it("can have more than one expectation", function () {
var foo = 0;
foo += 1;
expect(foo).toEqual(1);
expect(true).toEqual(true);
});
});
describe("A spec (with setup and tear-down)", function () {
var foo;
beforeEach(function () {
foo = 0;
foo += 1;
});
afterEach(function () {
foo = 0;
});
it("is just a function, so it can contain any code", function () {
expect(foo).toEqual(1);
});
it("can have more than one expectation", function () {
expect(foo).toEqual(1);
expect(true).toEqual(true);
});
});
describe("A spec", function () {
var foo;
beforeEach(function () {
foo = 0;
foo += 1;
});
afterEach(function () {
foo = 0;
});
it("is just a function, so it can contain any code", function () {
expect(foo).toEqual(1);
});
it("can have more than one expectation", function () {
expect(foo).toEqual(1);
expect(true).toEqual(true);
});
describe("nested inside a second describe", function () {
var bar;
beforeEach(function () {
bar = 1;
});
it("can reference both scopes as needed", function () {
expect(foo).toEqual(bar);
});
});
});
xdescribe("A spec", function () {
var foo;
beforeEach(function () {
foo = 0;
foo += 1;
});
it("is just a function, so it can contain any code", function () {
expect(foo).toEqual(1);
});
});
describe("Pending specs", function () {
xit("can be declared 'xit'", function () {
expect(true).toBe(false);
});
it("can be declared with 'it' but without a function");
it("can be declared by calling 'pending' in the spec body", function () {
expect(true).toBe(false);
pending(); // without reason
pending('this is why it is pending');
});
});
describe("A spy", function () {
var foo, bar = null;
beforeEach(function () {
foo = {
setBar: function (value) {
bar = value;
}
};
spyOn(foo, 'setBar');
foo.setBar(123);
foo.setBar(456, 'another param');
});
it("tracks that the spy was called", function () {
expect(foo.setBar).toHaveBeenCalled();
});
it("tracks all the arguments of its calls", function () {
expect(foo.setBar).toHaveBeenCalledWith(123);
expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
});
it("stops all execution on a function", function () {
expect(bar).toBeNull();
});
});
describe("A spy, when configured to call through", function () {
var foo, bar, fetchedBar;
beforeEach(function () {
foo = {
setBar: function (value) {
bar = value;
},
getBar: function () {
return bar;
}
};
spyOn(foo, 'getBar').and.callThrough();
foo.setBar(123);
fetchedBar = foo.getBar();
});
it("tracks that the spy was called", function () {
expect(foo.getBar).toHaveBeenCalled();
});
it("should not effect other functions", function () {
expect(bar).toEqual(123);
});
it("when called returns the requested value", function () {
expect(fetchedBar).toEqual(123);
});
});
describe("A spy, when configured to fake a return value", function () {
var foo, bar, fetchedBar;
beforeEach(function () {
foo = {
setBar: function (value) {
bar = value;
},
getBar: function () {
return bar;
}
};
spyOn(foo, "getBar").and.returnValue(745);
foo.setBar(123);
fetchedBar = foo.getBar();
});
it("tracks that the spy was called", function () {
expect(foo.getBar).toHaveBeenCalled();
});
it("should not effect other functions", function () {
expect(bar).toEqual(123);
});
it("when called returns the requested value", function () {
expect(fetchedBar).toEqual(745);
});
});
describe("A spy, when configured with an alternate implementation", function () {
var foo, bar, fetchedBar;
beforeEach(function () {
foo = {
setBar: function (value) {
bar = value;
},
getBar: function () {
return bar;
}
};
spyOn(foo, "getBar").and.callFake(function () {
return 1001;
});
foo.setBar(123);
fetchedBar = foo.getBar();
});
it("tracks that the spy was called", function () {
expect(foo.getBar).toHaveBeenCalled();
});
it("should not effect other functions", function () {
expect(bar).toEqual(123);
});
it("when called returns the requested value", function () {
expect(fetchedBar).toEqual(1001);
});
});
describe("A spy, when configured to throw a value", function () {
var foo, bar;
beforeEach(function () {
foo = {
setBar: function (value) {
bar = value;
}
};
spyOn(foo, "setBar").and.throwError("quux");
});
it("throws the value", function () {
expect(function () {
foo.setBar(123);
}).toThrowError("quux");
});
});
describe("A spy, when configured with multiple actions", function () {
var foo, bar, fetchedBar;
beforeEach(function () {
var _this = this;
foo = {
setBar: function (value) {
bar = value;
},
getBar: function () {
return bar;
}
};
spyOn(foo, 'getBar').and.callThrough().and.callFake(function () {
_this.fakeCalled = true;
});
foo.setBar(123);
fetchedBar = foo.getBar();
});
it("tracks that the spy was called", function () {
expect(foo.getBar).toHaveBeenCalled();
});
it("should not effect other functions", function () {
expect(bar).toEqual(123);
});
it("when called returns the requested value", function () {
expect(fetchedBar).toEqual(123);
});
it("should have called the fake implementation", function () {
expect(this.fakeCalled).toEqual(true);
});
});
describe("A spy", function () {
var foo, bar = null;
beforeEach(function () {
foo = {
setBar: function (value) {
bar = value;
}
};
spyOn(foo, 'setBar').and.callThrough();
});
it("can call through and then stub in the same spec", function () {
foo.setBar(123);
expect(bar).toEqual(123);
foo.setBar.and.stub();
bar = null;
foo.setBar(123);
expect(bar).toBe(null);
});
});
describe("A spy", function () {
var foo, bar = null;
beforeEach(function () {
foo = {
setBar: function (value) {
bar = value;
}
};
spyOn(foo, 'setBar');
});
it("tracks if it was called at all", function () {
expect(foo.setBar.calls.any()).toEqual(false);
foo.setBar();
expect(foo.setBar.calls.any()).toEqual(true);
});
it("tracks the number of times it was called", function () {
expect(foo.setBar.calls.count()).toEqual(0);
foo.setBar();
foo.setBar();
expect(foo.setBar.calls.count()).toEqual(2);
});
it("tracks the arguments of each call", function () {
foo.setBar(123);
foo.setBar(456, "baz");
expect(foo.setBar.calls.argsFor(0)).toEqual([123]);
expect(foo.setBar.calls.argsFor(1)).toEqual([456, "baz"]);
});
it("tracks the arguments of all calls", function () {
foo.setBar(123);
foo.setBar(456, "baz");
expect(foo.setBar.calls.allArgs()).toEqual([[123], [456, "baz"]]);
});
it("can provide the context and arguments to all calls", function () {
foo.setBar(123);
expect(foo.setBar.calls.all()).toEqual([{ object: foo, args: [123], returnValue: undefined }]);
});
it("has a shortcut to the most recent call", function () {
foo.setBar(123);
foo.setBar(456, "baz");
expect(foo.setBar.calls.mostRecent()).toEqual({ object: foo, args: [456, "baz"], returnValue: undefined });
});
it("has a shortcut to the first call", function () {
foo.setBar(123);
foo.setBar(456, "baz");
expect(foo.setBar.calls.first()).toEqual({ object: foo, args: [123], returnValue: undefined });
});
it("can be reset", function () {
foo.setBar(123);
foo.setBar(456, "baz");
expect(foo.setBar.calls.any()).toBe(true);
foo.setBar.calls.reset();
expect(foo.setBar.calls.any()).toBe(false);
});
});
describe("A spy, when created manually", function () {
var whatAmI;
beforeEach(function () {
whatAmI = jasmine.createSpy('whatAmI');
whatAmI("I", "am", "a", "spy");
});
it("is named, which helps in error reporting", function () {
expect(whatAmI.and.identity()).toEqual('whatAmI');
});
it("tracks that the spy was called", function () {
expect(whatAmI).toHaveBeenCalled();
});
it("tracks its number of calls", function () {
expect(whatAmI.calls.count()).toEqual(1);
});
it("tracks all the arguments of its calls", function () {
expect(whatAmI).toHaveBeenCalledWith("I", "am", "a", "spy");
});
it("allows access to the most recent call", function () {
expect(whatAmI.calls.mostRecent().args[0]).toEqual("I");
});
});
describe("Multiple spies, when created manually", function () {
var tape;
beforeEach(function () {
tape = jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']);
tape.play();
tape.pause();
tape.rewind(0);
});
it("creates spies for each requested function", function () {
expect(tape.play).toBeDefined();
expect(tape.pause).toBeDefined();
expect(tape.stop).toBeDefined();
expect(tape.rewind).toBeDefined();
});
it("tracks that the spies were called", function () {
expect(tape.play).toHaveBeenCalled();
expect(tape.pause).toHaveBeenCalled();
expect(tape.rewind).toHaveBeenCalled();
expect(tape.stop).not.toHaveBeenCalled();
});
it("tracks all the arguments of its calls", function () {
expect(tape.rewind).toHaveBeenCalledWith(0);
});
});
describe("jasmine.any", function () {
it("matches any value", function () {
expect({}).toEqual(jasmine.any(Object));
expect(12).toEqual(jasmine.any(Number));
});
describe("when used with a spy", function () {
it("is useful for comparing arguments", function () {
var foo = jasmine.createSpy('foo');
foo(12, function () {
return true;
});
expect(foo).toHaveBeenCalledWith(jasmine.any(Number), jasmine.any(Function));
});
});
});
describe("jasmine.objectContaining", function () {
var foo;
beforeEach(function () {
foo = {
a: 1,
b: 2,
bar: "baz"
};
});
it("matches objects with the expect key/value pairs", function () {
expect(foo).toEqual(jasmine.objectContaining({
bar: "baz"
}));
expect(foo).not.toEqual(jasmine.objectContaining({
c: 37
}));
});
describe("when used with a spy", function () {
it("is useful for comparing arguments", function () {
var callback = jasmine.createSpy('callback');
callback({
bar: "baz"
});
expect(callback).toHaveBeenCalledWith(jasmine.objectContaining({
bar: "baz"
}));
expect(callback).not.toHaveBeenCalledWith(jasmine.objectContaining({
c: 37
}));
});
});
});
describe("jasmine.arrayContaining", function () {
var foo;
beforeEach(function () {
foo = [1, 2, 3, 4];
});
it("matches arrays with some of the values", function () {
expect(foo).toEqual(jasmine.arrayContaining([3, 1]));
expect(foo).not.toEqual(jasmine.arrayContaining([6]));
});
describe("when used with a spy", function () {
it("is useful when comparing arguments", function () {
var callback = jasmine.createSpy('callback');
callback([1, 2, 3, 4]);
expect(callback).toHaveBeenCalledWith(jasmine.arrayContaining([4, 2, 3]));
expect(callback).not.toHaveBeenCalledWith(jasmine.arrayContaining([5, 2]));
});
});
});
describe("Manually ticking the Jasmine Clock", function () {
var timerCallback;
beforeEach(function () {
timerCallback = jasmine.createSpy("timerCallback");
jasmine.clock().install();
});
afterEach(function () {
jasmine.clock().uninstall();
});
it("causes a timeout to be called synchronously", function () {
setTimeout(function () {
timerCallback();
}, 100);
expect(timerCallback).not.toHaveBeenCalled();
jasmine.clock().tick(101);
expect(timerCallback).toHaveBeenCalled();
});
it("causes an interval to be called synchronously", function () {
setInterval(function () {
timerCallback();
}, 100);
expect(timerCallback).not.toHaveBeenCalled();
jasmine.clock().tick(101);
expect(timerCallback.calls.count()).toEqual(1);
jasmine.clock().tick(50);
expect(timerCallback.calls.count()).toEqual(1);
jasmine.clock().tick(50);
expect(timerCallback.calls.count()).toEqual(2);
});
describe("Mocking the Date object", function () {
it("mocks the Date object and sets it to a given time", function () {
var baseTime = new Date(2013, 9, 23);
jasmine.clock().mockDate(baseTime);
jasmine.clock().tick(50);
expect(new Date().getTime()).toEqual(baseTime.getTime() + 50);
});
});
});
describe("Asynchronous specs", function () {
var value;
beforeEach(function (done) {
setTimeout(function () {
value = 0;
done();
}, 1);
});
it("should support async execution of test preparation and expectations", function (done) {
value++;
expect(value).toBeGreaterThan(0);
done();
});
describe("long asynchronous specs", function () {
beforeEach(function (done) {
done();
}, 1000);
it("takes a long time", function (done) {
setTimeout(function () {
done();
}, 9000);
}, 10000);
afterEach(function (done) {
done();
}, 1000);
});
});
describe("Fail", function () {
it("should fail test when called without arguments", function () {
fail();
});
it("should fail test when called with a fail message", function () {
fail("The test failed");
});
it("should fail test when called an error", function () {
fail(new Error("The test failed with this error"));
});
});
// test based on http://jasmine.github.io/2.2/custom_equality.html
describe("custom equality", function () {
var myCustomEquality = function (first, second) {
if (typeof first == "string" && typeof second == "string") {
return first[0] == second[1];
}
};
beforeEach(function () {
jasmine.addCustomEqualityTester(myCustomEquality);
});
it("should be custom equal", function () {
expect("abc").toEqual("aaa");
});
it("should be custom not equal", function () {
expect("abc").not.toEqual("abc");
});
});
// test based on http://jasmine.github.io/2.2/custom_matcher.html
var customMatchers = {
toBeGoofy: function (util, customEqualityTesters) {
return {
compare: function (actual, expected) {
if (expected === undefined) {
expected = '';
}
var result = { pass: false };
result.pass = util.equals(actual.hyuk, "gawrsh" + expected, customEqualityTesters);
if (result.pass) {
result.message = "Expected " + actual + " not to be quite so goofy";
}
else {
result.message = "Expected " + actual + " to be goofy, but it was not very goofy";
}
return result;
}
};
}
};
describe("Custom matcher: 'toBeGoofy'", function () {
beforeEach(function () {
jasmine.addMatchers(customMatchers);
});
it("is available on an expectation", function () {
expect({
hyuk: 'gawrsh'
}).toBeGoofy();
});
it("can take an 'expected' parameter", function () {
expect({
hyuk: 'gawrsh is fun'
}).toBeGoofy(' is fun');
});
it("can be negated", function () {
expect({
hyuk: 'this is fun'
}).not.toBeGoofy();
});
});
(function () {
// from boot.js
var env = jasmine.getEnv();
var htmlReporter = new jasmine.HtmlReporter();
env.addReporter(htmlReporter);
var specFilter = new jasmine.HtmlSpecFilter();
env.specFilter = function (spec) {
return specFilter.matches(spec.getFullName());
};
var currentWindowOnload = window.onload;
window.onload = function () {
if (currentWindowOnload) {
currentWindowOnload(null);
}
htmlReporter.initialize();
env.execute();
};
})();
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
//# sourceMappingURL=jasmine-tests.js.map | {
"content_hash": "f1045182f825876233fd807eea41060d",
"timestamp": "",
"source": "github",
"line_count": 684,
"max_line_length": 115,
"avg_line_length": 32.469298245614034,
"alnum_prop": 0.537890044576523,
"repo_name": "Rmathusuthanan/My-C-Progects",
"id": "6b697e42dfc8bcbddb62a8ecdd815d3529d37903",
"size": "22312",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "typings/jasmine/jasmine-tests.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16737"
},
{
"name": "HTML",
"bytes": "31291"
},
{
"name": "JavaScript",
"bytes": "119516"
},
{
"name": "TypeScript",
"bytes": "181143"
}
],
"symlink_target": ""
} |
var Listing = require('../models/listing')
, User = require('../models/user')
, Review = require('../models/review')
, validator = require('validator');
module.exports = function(app) {
this.searchPage = function(req, res) {
res.render('search');
}
this.search = function(req, res) {
var searchExp = new RegExp(
'^/.*/' + validator.escape(req.search) + '/.*/$',
'i'
);
Listing.find({
$or : [
{ name: searchExp },
{ designer: searchExp },
{ price: searchExp },
{ sizing: searchExp },
{ description: searchExp }
]
}, function(err, listings) {
if (err) { throw err; }
else {
res.status(200).json(listings);
}
});
}
return this;
}
| {
"content_hash": "44a1b139157f649104423b23313fd809",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 55,
"avg_line_length": 22.38235294117647,
"alnum_prop": 0.5256241787122208,
"repo_name": "2nd47/house-party-sharing",
"id": "c63e56163ee27b23e627573c466f480ab186dece",
"size": "761",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/search.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8027"
},
{
"name": "HTML",
"bytes": "12554"
},
{
"name": "JavaScript",
"bytes": "32799"
}
],
"symlink_target": ""
} |
#pragma once
#include <mrpt/config.h>
#include <mrpt/hwdrivers/CImageGrabber_dc1394.h>
#include <mrpt/obs/CObservationStereoImages.h>
namespace mrpt::hwdrivers
{
/** Grabs from a "Bumblebee" or "Bumblebee2" stereo camera using raw access to
* the libdc1394 library.
* Only raw, unrectified images can be captured with this class, which can be
* manually rectified given
* correct calibration parameters.
*
* See mrpt::hwdrivers::CStereoGrabber_Bumblebee for another class capable of
* live capture of rectified images using
* the vendor (PointGreyResearch) Triclops API.
*
* Once connected to a camera, you can call `getStereoObservation()` to
* retrieve the stereo images.
*
* \sa You'll probably want to use instead the most generic camera grabber in
* MRPT: mrpt::hwdrivers::CCameraSensor
* \ingroup mrpt_hwdrivers_grp
*/
class CStereoGrabber_Bumblebee_libdc1394
{
public:
/** Constructor. Parameters have the same meaning as in
* CImageGrabber_dc1394::CImageGrabber_dc1394() */
CStereoGrabber_Bumblebee_libdc1394(
uint64_t cameraGUID, uint16_t cameraUnit, double frameRate);
CStereoGrabber_Bumblebee_libdc1394(
const CStereoGrabber_Bumblebee_libdc1394&) = delete;
CStereoGrabber_Bumblebee_libdc1394& operator=(
const CStereoGrabber_Bumblebee_libdc1394&) = delete;
/** Destructor */
virtual ~CStereoGrabber_Bumblebee_libdc1394();
/** Grab stereo images, and return the pair of rectified images.
* \param out_observation The object to be filled with sensed data.
*
* \note The member "CObservationStereoImages::refCameraPose" must be set on
* the return of
* this method by the user, since we don't know here the robot physical
* structure.
*
* \return false on any error, true if all go fine.
*/
bool getStereoObservation(
mrpt::obs::CObservationStereoImages& out_observation);
protected:
/** The actual capture object used in Linux / Mac. */
mrpt::hwdrivers::CImageGrabber_dc1394* m_firewire_capture;
/** If this has been correctly initiated */
bool m_bInitialized;
}; // End of class
static_assert(
!std::is_copy_constructible_v<CStereoGrabber_Bumblebee_libdc1394> &&
!std::is_copy_assignable_v<CStereoGrabber_Bumblebee_libdc1394>,
"Copy Check");
} // namespace mrpt::hwdrivers
| {
"content_hash": "71d635ac215ee9d5bfd4238750a269d2",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 78,
"avg_line_length": 33.71641791044776,
"alnum_prop": 0.7498893315626384,
"repo_name": "MRPT/mrpt",
"id": "6adaaf5067f8c2e52259f2319f70696d4deabd00",
"size": "2885",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "libs/hwdrivers/include/mrpt/hwdrivers/CStereoGrabber_Bumblebee_libdc1394.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "12930"
},
{
"name": "C",
"bytes": "6718494"
},
{
"name": "C++",
"bytes": "14447097"
},
{
"name": "CMake",
"bytes": "555861"
},
{
"name": "GLSL",
"bytes": "6522"
},
{
"name": "MATLAB",
"bytes": "8401"
},
{
"name": "Makefile",
"bytes": "517"
},
{
"name": "NSIS",
"bytes": "1922"
},
{
"name": "Python",
"bytes": "85724"
},
{
"name": "Shell",
"bytes": "16350"
}
],
"symlink_target": ""
} |
use approx::{AbsDiffEq, RelativeEq, UlpsEq};
use std::fmt;
use std::hash;
#[cfg(feature = "abomonation-serialize")]
use std::io::{Result as IOResult, Write};
#[cfg(feature = "serde-serialize")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "abomonation-serialize")]
use abomonation::Abomonation;
use simba::scalar::{RealField, SubsetOf};
use simba::simd::SimdRealField;
use crate::base::allocator::Allocator;
use crate::base::dimension::{DimName, DimNameAdd, DimNameSum, U1};
use crate::base::storage::Owned;
use crate::base::{DefaultAllocator, MatrixN, Scalar, VectorN};
use crate::geometry::{AbstractRotation, Point, Translation};
/// A direct isometry, i.e., a rotation followed by a translation, aka. a rigid-body motion, aka. an element of a Special Euclidean (SE) group.
#[repr(C)]
#[derive(Debug)]
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
#[cfg_attr(
feature = "serde-serialize",
serde(bound(serialize = "R: Serialize,
DefaultAllocator: Allocator<N, D>,
Owned<N, D>: Serialize"))
)]
#[cfg_attr(
feature = "serde-serialize",
serde(bound(deserialize = "R: Deserialize<'de>,
DefaultAllocator: Allocator<N, D>,
Owned<N, D>: Deserialize<'de>"))
)]
pub struct Isometry<N: Scalar, D: DimName, R>
where
DefaultAllocator: Allocator<N, D>,
{
/// The pure rotational part of this isometry.
pub rotation: R,
/// The pure translational part of this isometry.
pub translation: Translation<N, D>,
}
#[cfg(feature = "abomonation-serialize")]
impl<N, D, R> Abomonation for Isometry<N, D, R>
where
N: SimdRealField,
D: DimName,
R: Abomonation,
Translation<N, D>: Abomonation,
DefaultAllocator: Allocator<N, D>,
{
unsafe fn entomb<W: Write>(&self, writer: &mut W) -> IOResult<()> {
self.rotation.entomb(writer)?;
self.translation.entomb(writer)
}
fn extent(&self) -> usize {
self.rotation.extent() + self.translation.extent()
}
unsafe fn exhume<'a, 'b>(&'a mut self, bytes: &'b mut [u8]) -> Option<&'b mut [u8]> {
self.rotation
.exhume(bytes)
.and_then(|bytes| self.translation.exhume(bytes))
}
}
impl<N: Scalar + hash::Hash, D: DimName + hash::Hash, R: hash::Hash> hash::Hash
for Isometry<N, D, R>
where
DefaultAllocator: Allocator<N, D>,
Owned<N, D>: hash::Hash,
{
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.translation.hash(state);
self.rotation.hash(state);
}
}
impl<N: Scalar + Copy, D: DimName + Copy, R: AbstractRotation<N, D> + Copy> Copy
for Isometry<N, D, R>
where
DefaultAllocator: Allocator<N, D>,
Owned<N, D>: Copy,
{
}
impl<N: Scalar, D: DimName, R: AbstractRotation<N, D> + Clone> Clone for Isometry<N, D, R>
where
DefaultAllocator: Allocator<N, D>,
{
#[inline]
fn clone(&self) -> Self {
Self::from_parts(self.translation.clone(), self.rotation.clone())
}
}
impl<N: Scalar, D: DimName, R: AbstractRotation<N, D>> Isometry<N, D, R>
where
DefaultAllocator: Allocator<N, D>,
{
/// Creates a new isometry from its rotational and translational parts.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate approx;
/// # use std::f32;
/// # use nalgebra::{Isometry3, Translation3, UnitQuaternion, Vector3, Point3};
/// let tra = Translation3::new(0.0, 0.0, 3.0);
/// let rot = UnitQuaternion::from_scaled_axis(Vector3::y() * f32::consts::PI);
/// let iso = Isometry3::from_parts(tra, rot);
///
/// assert_relative_eq!(iso * Point3::new(1.0, 2.0, 3.0), Point3::new(-1.0, 2.0, 0.0), epsilon = 1.0e-6);
/// ```
#[inline]
pub fn from_parts(translation: Translation<N, D>, rotation: R) -> Self {
Self {
rotation,
translation,
}
}
}
impl<N: SimdRealField, D: DimName, R: AbstractRotation<N, D>> Isometry<N, D, R>
where
N::Element: SimdRealField,
DefaultAllocator: Allocator<N, D>,
{
/// Inverts `self`.
///
/// # Example
///
/// ```
/// # use std::f32;
/// # use nalgebra::{Isometry2, Point2, Vector2};
/// let iso = Isometry2::new(Vector2::new(1.0, 2.0), f32::consts::FRAC_PI_2);
/// let inv = iso.inverse();
/// let pt = Point2::new(1.0, 2.0);
///
/// assert_eq!(inv * (iso * pt), pt);
/// ```
#[inline]
#[must_use = "Did you mean to use inverse_mut()?"]
pub fn inverse(&self) -> Self {
let mut res = self.clone();
res.inverse_mut();
res
}
/// Inverts `self` in-place.
///
/// # Example
///
/// ```
/// # use std::f32;
/// # use nalgebra::{Isometry2, Point2, Vector2};
/// let mut iso = Isometry2::new(Vector2::new(1.0, 2.0), f32::consts::FRAC_PI_2);
/// let pt = Point2::new(1.0, 2.0);
/// let transformed_pt = iso * pt;
/// iso.inverse_mut();
///
/// assert_eq!(iso * transformed_pt, pt);
/// ```
#[inline]
pub fn inverse_mut(&mut self) {
self.rotation.inverse_mut();
self.translation.inverse_mut();
self.translation.vector = self.rotation.transform_vector(&self.translation.vector);
}
/// Appends to `self` the given translation in-place.
///
/// # Example
///
/// ```
/// # use std::f32;
/// # use nalgebra::{Isometry2, Translation2, Vector2};
/// let mut iso = Isometry2::new(Vector2::new(1.0, 2.0), f32::consts::FRAC_PI_2);
/// let tra = Translation2::new(3.0, 4.0);
/// // Same as `iso = tra * iso`.
/// iso.append_translation_mut(&tra);
///
/// assert_eq!(iso.translation, Translation2::new(4.0, 6.0));
/// ```
#[inline]
pub fn append_translation_mut(&mut self, t: &Translation<N, D>) {
self.translation.vector += &t.vector
}
/// Appends to `self` the given rotation in-place.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate approx;
/// # use std::f32;
/// # use nalgebra::{Isometry2, Translation2, UnitComplex, Vector2};
/// let mut iso = Isometry2::new(Vector2::new(1.0, 2.0), f32::consts::PI / 6.0);
/// let rot = UnitComplex::new(f32::consts::PI / 2.0);
/// // Same as `iso = rot * iso`.
/// iso.append_rotation_mut(&rot);
///
/// assert_relative_eq!(iso, Isometry2::new(Vector2::new(-2.0, 1.0), f32::consts::PI * 2.0 / 3.0), epsilon = 1.0e-6);
/// ```
#[inline]
pub fn append_rotation_mut(&mut self, r: &R) {
self.rotation = r.clone() * self.rotation.clone();
self.translation.vector = r.transform_vector(&self.translation.vector);
}
/// Appends in-place to `self` a rotation centered at the point `p`, i.e., the rotation that
/// lets `p` invariant.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate approx;
/// # use std::f32;
/// # use nalgebra::{Isometry2, Translation2, UnitComplex, Vector2, Point2};
/// let mut iso = Isometry2::new(Vector2::new(1.0, 2.0), f32::consts::FRAC_PI_2);
/// let rot = UnitComplex::new(f32::consts::FRAC_PI_2);
/// let pt = Point2::new(1.0, 0.0);
/// iso.append_rotation_wrt_point_mut(&rot, &pt);
///
/// assert_relative_eq!(iso * pt, Point2::new(-2.0, 0.0), epsilon = 1.0e-6);
/// ```
#[inline]
pub fn append_rotation_wrt_point_mut(&mut self, r: &R, p: &Point<N, D>) {
self.translation.vector -= &p.coords;
self.append_rotation_mut(r);
self.translation.vector += &p.coords;
}
/// Appends in-place to `self` a rotation centered at the point with coordinates
/// `self.translation`.
///
/// # Example
///
/// ```
/// # use std::f32;
/// # use nalgebra::{Isometry2, Translation2, UnitComplex, Vector2, Point2};
/// let mut iso = Isometry2::new(Vector2::new(1.0, 2.0), f32::consts::FRAC_PI_2);
/// let rot = UnitComplex::new(f32::consts::FRAC_PI_2);
/// iso.append_rotation_wrt_center_mut(&rot);
///
/// // The translation part should not have changed.
/// assert_eq!(iso.translation.vector, Vector2::new(1.0, 2.0));
/// assert_eq!(iso.rotation, UnitComplex::new(f32::consts::PI));
/// ```
#[inline]
pub fn append_rotation_wrt_center_mut(&mut self, r: &R) {
self.rotation = r.clone() * self.rotation.clone();
}
/// Transform the given point by this isometry.
///
/// This is the same as the multiplication `self * pt`.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate approx;
/// # use std::f32;
/// # use nalgebra::{Isometry3, Translation3, UnitQuaternion, Vector3, Point3};
/// let tra = Translation3::new(0.0, 0.0, 3.0);
/// let rot = UnitQuaternion::from_scaled_axis(Vector3::y() * f32::consts::FRAC_PI_2);
/// let iso = Isometry3::from_parts(tra, rot);
///
/// let transformed_point = iso.transform_point(&Point3::new(1.0, 2.0, 3.0));
/// assert_relative_eq!(transformed_point, Point3::new(3.0, 2.0, 2.0), epsilon = 1.0e-6);
/// ```
#[inline]
pub fn transform_point(&self, pt: &Point<N, D>) -> Point<N, D> {
self * pt
}
/// Transform the given vector by this isometry, ignoring the translation
/// component of the isometry.
///
/// This is the same as the multiplication `self * v`.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate approx;
/// # use std::f32;
/// # use nalgebra::{Isometry3, Translation3, UnitQuaternion, Vector3};
/// let tra = Translation3::new(0.0, 0.0, 3.0);
/// let rot = UnitQuaternion::from_scaled_axis(Vector3::y() * f32::consts::FRAC_PI_2);
/// let iso = Isometry3::from_parts(tra, rot);
///
/// let transformed_point = iso.transform_vector(&Vector3::new(1.0, 2.0, 3.0));
/// assert_relative_eq!(transformed_point, Vector3::new(3.0, 2.0, -1.0), epsilon = 1.0e-6);
/// ```
#[inline]
pub fn transform_vector(&self, v: &VectorN<N, D>) -> VectorN<N, D> {
self * v
}
/// Transform the given point by the inverse of this isometry. This may be
/// less expensive than computing the entire isometry inverse and then
/// transforming the point.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate approx;
/// # use std::f32;
/// # use nalgebra::{Isometry3, Translation3, UnitQuaternion, Vector3, Point3};
/// let tra = Translation3::new(0.0, 0.0, 3.0);
/// let rot = UnitQuaternion::from_scaled_axis(Vector3::y() * f32::consts::FRAC_PI_2);
/// let iso = Isometry3::from_parts(tra, rot);
///
/// let transformed_point = iso.inverse_transform_point(&Point3::new(1.0, 2.0, 3.0));
/// assert_relative_eq!(transformed_point, Point3::new(0.0, 2.0, 1.0), epsilon = 1.0e-6);
/// ```
#[inline]
pub fn inverse_transform_point(&self, pt: &Point<N, D>) -> Point<N, D> {
self.rotation
.inverse_transform_point(&(pt - &self.translation.vector))
}
/// Transform the given vector by the inverse of this isometry, ignoring the
/// translation component of the isometry. This may be
/// less expensive than computing the entire isometry inverse and then
/// transforming the point.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate approx;
/// # use std::f32;
/// # use nalgebra::{Isometry3, Translation3, UnitQuaternion, Vector3};
/// let tra = Translation3::new(0.0, 0.0, 3.0);
/// let rot = UnitQuaternion::from_scaled_axis(Vector3::y() * f32::consts::FRAC_PI_2);
/// let iso = Isometry3::from_parts(tra, rot);
///
/// let transformed_point = iso.inverse_transform_vector(&Vector3::new(1.0, 2.0, 3.0));
/// assert_relative_eq!(transformed_point, Vector3::new(-3.0, 2.0, 1.0), epsilon = 1.0e-6);
/// ```
#[inline]
pub fn inverse_transform_vector(&self, v: &VectorN<N, D>) -> VectorN<N, D> {
self.rotation.inverse_transform_vector(v)
}
}
// NOTE: we don't require `R: Rotation<...>` here because this is not useful for the implementation
// and makes it hard to use it, e.g., for Transform × Isometry implementation.
// This is OK since all constructors of the isometry enforce the Rotation bound already (and
// explicit struct construction is prevented by the dummy ZST field).
impl<N: SimdRealField, D: DimName, R> Isometry<N, D, R>
where
DefaultAllocator: Allocator<N, D>,
{
/// Converts this isometry into its equivalent homogeneous transformation matrix.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate approx;
/// # use std::f32;
/// # use nalgebra::{Isometry2, Vector2, Matrix3};
/// let iso = Isometry2::new(Vector2::new(10.0, 20.0), f32::consts::FRAC_PI_6);
/// let expected = Matrix3::new(0.8660254, -0.5, 10.0,
/// 0.5, 0.8660254, 20.0,
/// 0.0, 0.0, 1.0);
///
/// assert_relative_eq!(iso.to_homogeneous(), expected, epsilon = 1.0e-6);
/// ```
#[inline]
pub fn to_homogeneous(&self) -> MatrixN<N, DimNameSum<D, U1>>
where
D: DimNameAdd<U1>,
R: SubsetOf<MatrixN<N, DimNameSum<D, U1>>>,
DefaultAllocator: Allocator<N, DimNameSum<D, U1>, DimNameSum<D, U1>>,
{
let mut res: MatrixN<N, _> = crate::convert_ref(&self.rotation);
res.fixed_slice_mut::<D, U1>(0, D::dim())
.copy_from(&self.translation.vector);
res
}
}
impl<N: SimdRealField, D: DimName, R> Eq for Isometry<N, D, R>
where
R: AbstractRotation<N, D> + Eq,
DefaultAllocator: Allocator<N, D>,
{
}
impl<N: SimdRealField, D: DimName, R> PartialEq for Isometry<N, D, R>
where
R: AbstractRotation<N, D> + PartialEq,
DefaultAllocator: Allocator<N, D>,
{
#[inline]
fn eq(&self, right: &Self) -> bool {
self.translation == right.translation && self.rotation == right.rotation
}
}
impl<N: RealField, D: DimName, R> AbsDiffEq for Isometry<N, D, R>
where
R: AbstractRotation<N, D> + AbsDiffEq<Epsilon = N::Epsilon>,
DefaultAllocator: Allocator<N, D>,
N::Epsilon: Copy,
{
type Epsilon = N::Epsilon;
#[inline]
fn default_epsilon() -> Self::Epsilon {
N::default_epsilon()
}
#[inline]
fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
self.translation.abs_diff_eq(&other.translation, epsilon)
&& self.rotation.abs_diff_eq(&other.rotation, epsilon)
}
}
impl<N: RealField, D: DimName, R> RelativeEq for Isometry<N, D, R>
where
R: AbstractRotation<N, D> + RelativeEq<Epsilon = N::Epsilon>,
DefaultAllocator: Allocator<N, D>,
N::Epsilon: Copy,
{
#[inline]
fn default_max_relative() -> Self::Epsilon {
N::default_max_relative()
}
#[inline]
fn relative_eq(
&self,
other: &Self,
epsilon: Self::Epsilon,
max_relative: Self::Epsilon,
) -> bool {
self.translation
.relative_eq(&other.translation, epsilon, max_relative)
&& self
.rotation
.relative_eq(&other.rotation, epsilon, max_relative)
}
}
impl<N: RealField, D: DimName, R> UlpsEq for Isometry<N, D, R>
where
R: AbstractRotation<N, D> + UlpsEq<Epsilon = N::Epsilon>,
DefaultAllocator: Allocator<N, D>,
N::Epsilon: Copy,
{
#[inline]
fn default_max_ulps() -> u32 {
N::default_max_ulps()
}
#[inline]
fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
self.translation
.ulps_eq(&other.translation, epsilon, max_ulps)
&& self.rotation.ulps_eq(&other.rotation, epsilon, max_ulps)
}
}
/*
*
* Display
*
*/
impl<N: RealField + fmt::Display, D: DimName, R> fmt::Display for Isometry<N, D, R>
where
R: fmt::Display,
DefaultAllocator: Allocator<N, D> + Allocator<usize, D>,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let precision = f.precision().unwrap_or(3);
writeln!(f, "Isometry {{")?;
write!(f, "{:.*}", precision, self.translation)?;
write!(f, "{:.*}", precision, self.rotation)?;
writeln!(f, "}}")
}
}
| {
"content_hash": "128292fdab50b9857a18963f66c7f484",
"timestamp": "",
"source": "github",
"line_count": 492,
"max_line_length": 143,
"avg_line_length": 33.142276422764226,
"alnum_prop": 0.5780080951796884,
"repo_name": "sebcrozet/nalgebra",
"id": "2e4b7cd5d1fb0906117bcee1804846bf91fd7cc2",
"size": "16307",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/geometry/isometry.rs",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Makefile",
"bytes": "426"
},
{
"name": "Rust",
"bytes": "1147701"
},
{
"name": "Shell",
"bytes": "1330"
}
],
"symlink_target": ""
} |
@runner = VirtualMonkey::FeAppRunner.new(ENV['DEPLOYMENT'])
# Then I should stop the servers
@runner.behavior(:stop_all)
# Then I should set a variation for connecting to shared database host
@runner.set_var(:set_master_db_dnsname)
# When I launch the "Front End" servers
@runner.behavior(:launch_set, "Front End")
# Then I should wait for the state of "Front End" servers to be "booting"
@runner.behavior(:wait_for_set, "Front End", "booting")
# Then I should wait for the state of "Front End" servers to be "operational"
@runner.behavior(:wait_for_set, "Front End", "operational")
# Then I should set a variation LB_HOSTNAME
@runner.set_var(:set_lb_hostname)
# When I launch the "App Server" servers
@runner.behavior(:launch_set, "App Server")
# Then I should wait for the state of "App Server" servers to be "booting"
@runner.behavior(:wait_for_set, "App Server", "booting")
# Then I should wait for the state of "App Server" servers to be "operational"
@runner.behavior(:wait_for_set, "App Server", "operational")
# Then I should cross connect the frontends
@runner.behavior(:cross_connect_frontends)
# Then I should run unified application checks
@runner.behavior(:run_unified_application_checks, @runner.send(:app_servers))
# Then I should run frontend checks
@runner.behavior(:frontend_checks)
# Then I should run log rotation checks
@runner.behavior(:log_rotation_checks)
# Then I should test reboot operations on the deployment
@runner.behavior(:run_reboot_operations)
# Then I should check that monitoring is enabled
@runner.behavior(:check_monitoring)
| {
"content_hash": "970232e2b20d8bbe289de71cf6ff1121",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 79,
"avg_line_length": 35,
"alnum_prop": 0.7366459627329193,
"repo_name": "jeremyd/virtualmonkey",
"id": "ef4ad2240cc94247ca8f148851181a1f2bb3e5cb",
"size": "1764",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "features/php.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "141588"
}
],
"symlink_target": ""
} |
<HTML><HEAD>
<TITLE>Review for Natural Born Killers (1994)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0110632">Natural Born Killers (1994)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Ted+Prigge">Ted Prigge</A></H3><HR WIDTH="40%" SIZE="4">
<PRE>NATURAL BORN KILLERS (1994)
A Film Review by Ted Prigge
Copyright 1997 Ted Prigge</PRE>
<P>Director: Oliver Stone
Writers: Richard Rutowski, David Veloz, and Oliver Stone (based on a
script by Quentin Tarantino)
Starring: Woody Harrelson, Juliette Lewis, Robert Downey Jr., Tom
Sizemore, Tommy Lee Jones, Rodney Dangerfield, Edie McClurg, Bathalzar
Getty, Steven Wright, Arliss Howard, Ashley Judd, Rachel Ticotin, Denis
Leary, Mark Harmon, Jared Harris</P>
<P>"Natural Born Killers" is a tough flick to review. On one hand, the
message that is to be presented - that the media glorifies serial
killers too much, and one day it's going to self destruct into a giant
stream of pandemonium. But on the other hand, the film's first half has
almost nothing to do with the second half, thus quieting some of the
blows the second half tries to pull off. Yes, the film manages to bring
its brilliant view to the screen, and the message is conveyed. But
something is missing. So, this is basically a flawed masterpiece.</P>
<P>As the films previews and general media and contreversy over this state,
this is a film about two serial killers who capture the eye of the
media, making everyone seem to love them. The serial killers in this
film, named Mickey and Mallory (Woody Harrelson and Juliette Lewis,
respectively), are hick young adults who kill Mallory's parents, and
head off on a long killing spree, where 52 innocent or not-so-innocent
people are brutally killed.</P>
<P>The media jumps in on it when they are discovered, represented by a
hyprekinetic Aussie journalist named Wade Gale (Robert Downey Jr) who
hosts a TV show called "American Maniacs," which not only presents
coverage on serial killers past and present, but also glorifies the hell
out of them. We don't learn a lot about Wade, since he's basically a
characateur (and rightfully so), but we do learn that he is the
stereotypical view on the reporter: selfish, egotistical ("Where are the
close-ups of ME?!," he screams out once), and amoral. I mean, the guy's
not only married to the daughter of a rich man because he got her
pregnant, but he also has a mistress.</P>
<P>The film starts off with what seems to be a typical Mickey-and-Mallory
bloodbath: the two are in a little diner, are provoked by a couple
rednecks, then take everyone out except for one (chosen in a
horrifyingly sadistic, not to mention darkly comic, game of "Eeeny,
Meeeny, Miny, Moe!" - I'm trying my best to spell these, folks), who is
the chosen to tell the tale. It's a wonderfully done scene, filled with
lots of black comedy (shots on a bullet about to hit a woman's head,
then stops, then shows blood flying against the wall), lots of cool
violence (again the bullet and the woman), and even some great music (a
great chick punk tune blares out on the soundtrack). It's glorification
of what they do fits in perfectly with the movie, as we see the real
Mickey and Mallory viewed in the way a movie would present them,
although an Oliver Stone flick, judging from the style.</P>
<P>>From here, though, the film looses its way for about an hour. Instead
of viewing the message that's supposed to be given here, Stone goes off
on an ADD-filled ride. We see how they started out (in a brilliant
although kind of useless sequence where her family life is viewed as an
American sitcom, complete with a laugh-track). We see how they met, how
they killed her horrible father (Rodney Dangerfield, great job) and her
passive though chiken mother (Edie McClurg). Now this was a problem I
had with the movie: I felt bad that they killed the mother. I was happy
when Mickey beat the hell out of the father (that guy gets NO
respect...sorry, bad joke). But the mother was merely scared of him.
Of course she didn't do anything - the father would have kicked the hell
out of her. I mean, I shouldn't have felt bad for the mother dying, I
guess.</P>
<P>The film introduces Wade, his crew, and his stupid TV show, but then
drops him and goes off with Mickey and Mallory for a bit. This is where
it really goes wrong. The film tries to explain the two, how they fight
for no reason, how they felt bad for the accidental killing of an Indian
who tried to help them. But this fails. The scene where they are
caught at a "Drug Zone" where they are buying some poison-killer since
they were bitten by rattlesnakes is effective, with a Rodney King-esque
beating at the end, and a lot of great mood and composition.</P>
<P>Here is where the film goes right and doesn't wimp out until the final
credit has rolled by. We see them in prison after a year, seperated,
and Wade wants to do a live interview with Mickey after the superbowl,
mainly for high ratings. For the final hour, we get the mayhem the film
has been waiting to deliver. The story's boiler erupts, and we see what
happens when all these elements are mixed together. The broadcast of
the interview prompts a large-scale prison riot, and in this mayhem,
Mickey takes out all but two guards, and takes Wade and what's left of
his crew hostage on his search for Mallory's cell, the woman he hasn't
seen for an entire year.</P>
<P>The ending is brilliant, with great symbolism, and brings the film to an
almost satisfying conclusion, if it weren't for the lackluster first
half.</P>
<P>Anyway, the style of the film is definitely different than anything I've
ever seen before in a big-budget film. Oliver Stone, who is famous for
his quick editing (which was used to perfection in "JFK"), kind of
overdoes it. Yes, I know what he was getting at with switching between
black/white and color, regular Hollywood cameras and super 8, live
actoin and cartoons. But for all its worth, it's pretty headache
enducing. He sometimes switches things at wrong times, and I kind of
feel bad for the actors and crew, since they would probably do a couple
lines, then switch it off and get a whole new camera. And I pity the
man who had to edit this goddam thing.</P>
<P>The acting is very good, if not sometimes cartoonish. Olvier Stone has
said the film is supposed to be that way, since it's a ludicrous
situation. He's right. It's a fable, and any way to tell it in some
kind of gritty, realistic way would ruin the impact of the film.
Anyway, Woody and Juliette are a fantastic couple, each with his or her
great perks. Robert Downey Jr and Tommy Lee Jones REALLY go for the
high camp, and I can't even decide which one was more so. I'm not
saying they were bad, just a tad high on the cartoonish. I mean, when
Robert Downey Jr. talks about Elton John confessing his bisexuality to
Rolling Stone, he really goes so overboard that he makes Mickey look
sane. I also want to talk about how funny Steven Wright was, playing a
psychologist being interviewed by Wade...well, that was pretty much it.</P>
<P>I didn't like this film that much the first time I saw it. It was right
in the middle of my obsession with Quentin, and I couldn't believe that
Stone would be dissing Tarantino's original script so much. I've read
the Quentin version, and I kind of like it better (the whole first half
is pure Stone), but I'm glad Stone directed this, 'cause it wouldn't be
as good with Tarantino directing. But anyway, the second time I saw it,
it was the director's cut, and that, mixed with the fact that I was a
little over my Quentin obsession, I actually liked it.</P>
<P>With the director's cut, we get some extra footage that didn't make the
theater version of the film for various reasons. Interlaced with the
film are a couple brutal shots, like more of Woody raping that one
hostage, and a shot of Tommy Lee Jones's decapitated head on a stick.
But we also get some extra full scenes afterwards, narrated by Stone
himself.</P>
<P>The one that really got me was a further explanation of the
Indian-killing part. This seemed to deepen it, even if I found it kind
of unnecessary to the message of the film, but he took it out for "time
limiatations" (???). There's also a scene where Mickey kills a witness
(Ashley Judd) during their trial, and a totally unnecessary albeith
entertaining bit where Denis Leary gives a rant to the camera. We also
see the alternate ending, where Mickey and Mallory are killed by the
guardian angel guy (Arliss Howard), but the other ending was chosen
(thank god).</P>
<P>To bring a long story to a quick close, "Natural Born Killers" is
basically a flawed masterpiece, but at least gives its message across.
I'm not up for giving it a perfect rating, nor am I up for awarding it a
crap one, but since the positive things outweigh the negative, I'm
giving it a thumb up rating.</P>
<PRE>MY RATING (out of 4): ***</PRE>
<P>Homepage at: <A HREF="http://www.geocities.com/Hollywood/Hills/8335/">http://www.geocities.com/Hollywood/Hills/8335/</A></P>
<HR><P CLASS=flush><SMALL>The review above was posted to the
<A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR>
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.<BR>
Please direct comments/criticisms of the review to relevant newsgroups.<BR>
Broken URLs inthe reviews are the responsibility of the author.<BR>
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
</SMALL></P>
<P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P>
</P></BODY></HTML>
| {
"content_hash": "bbc672fbb5687266f32292a4b8792994",
"timestamp": "",
"source": "github",
"line_count": 155,
"max_line_length": 202,
"avg_line_length": 65.2258064516129,
"alnum_prop": 0.7552917903066271,
"repo_name": "xianjunzhengbackup/code",
"id": "6c7212a786220c7975771f1aca0b3f19c2c8a086",
"size": "10110",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data science/machine_learning_for_the_web/chapter_4/movie/9548.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "BitBake",
"bytes": "113"
},
{
"name": "BlitzBasic",
"bytes": "256"
},
{
"name": "CSS",
"bytes": "49827"
},
{
"name": "HTML",
"bytes": "157006325"
},
{
"name": "JavaScript",
"bytes": "14029"
},
{
"name": "Jupyter Notebook",
"bytes": "4875399"
},
{
"name": "Mako",
"bytes": "2060"
},
{
"name": "Perl",
"bytes": "716"
},
{
"name": "Python",
"bytes": "874414"
},
{
"name": "R",
"bytes": "454"
},
{
"name": "Shell",
"bytes": "3984"
}
],
"symlink_target": ""
} |
package util
import (
"errors"
"fmt"
"strings"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
utilfeature "k8s.io/apiserver/pkg/util/feature"
corelisters "k8s.io/client-go/listers/core/v1"
"k8s.io/component-helpers/storage/ephemeral"
"k8s.io/klog/v2"
"k8s.io/kubernetes/pkg/controller/volume/attachdetach/cache"
"k8s.io/kubernetes/pkg/features"
"k8s.io/kubernetes/pkg/volume"
"k8s.io/kubernetes/pkg/volume/csimigration"
"k8s.io/kubernetes/pkg/volume/util"
)
// CreateVolumeSpec creates and returns a mutatable volume.Spec object for the
// specified volume. It dereference any PVC to get PV objects, if needed.
// A volume.Spec that refers to an in-tree plugin spec is translated to refer
// to a migrated CSI plugin spec if all conditions for CSI migration on a node
// for the in-tree plugin is satisfied.
func CreateVolumeSpec(podVolume v1.Volume, pod *v1.Pod, nodeName types.NodeName, vpm *volume.VolumePluginMgr, pvcLister corelisters.PersistentVolumeClaimLister, pvLister corelisters.PersistentVolumeLister, csiMigratedPluginManager csimigration.PluginManager, csiTranslator csimigration.InTreeToCSITranslator) (*volume.Spec, error) {
claimName := ""
readOnly := false
if pvcSource := podVolume.VolumeSource.PersistentVolumeClaim; pvcSource != nil {
claimName = pvcSource.ClaimName
readOnly = pvcSource.ReadOnly
}
isEphemeral := false
if ephemeralSource := podVolume.VolumeSource.Ephemeral; ephemeralSource != nil && utilfeature.DefaultFeatureGate.Enabled(features.GenericEphemeralVolume) {
claimName = ephemeral.VolumeClaimName(pod, &podVolume)
isEphemeral = true
}
if claimName != "" {
klog.V(10).Infof(
"Found PVC, ClaimName: %q/%q",
pod.Namespace,
claimName)
// If podVolume is a PVC, fetch the real PV behind the claim
pvc, err := getPVCFromCache(pod.Namespace, claimName, pvcLister)
if err != nil {
return nil, fmt.Errorf(
"error processing PVC %q/%q: %v",
pod.Namespace,
claimName,
err)
}
if isEphemeral {
if err := ephemeral.VolumeIsForPod(pod, pvc); err != nil {
return nil, err
}
}
pvName, pvcUID := pvc.Spec.VolumeName, pvc.UID
klog.V(10).Infof(
"Found bound PV for PVC (ClaimName %q/%q pvcUID %v): pvName=%q",
pod.Namespace,
claimName,
pvcUID,
pvName)
// Fetch actual PV object
volumeSpec, err := getPVSpecFromCache(
pvName, readOnly, pvcUID, pvLister)
if err != nil {
return nil, fmt.Errorf(
"error processing PVC %q/%q: %v",
pod.Namespace,
claimName,
err)
}
volumeSpec, err = translateInTreeSpecToCSIIfNeeded(volumeSpec, nodeName, vpm, csiMigratedPluginManager, csiTranslator, pod.Namespace)
if err != nil {
return nil, fmt.Errorf(
"error performing CSI migration checks and translation for PVC %q/%q: %v",
pod.Namespace,
claimName,
err)
}
klog.V(10).Infof(
"Extracted volumeSpec (%v) from bound PV (pvName %q) and PVC (ClaimName %q/%q pvcUID %v)",
volumeSpec.Name(),
pvName,
pod.Namespace,
claimName,
pvcUID)
return volumeSpec, nil
}
// Do not return the original volume object, since it's from the shared
// informer it may be mutated by another consumer.
clonedPodVolume := podVolume.DeepCopy()
origspec := volume.NewSpecFromVolume(clonedPodVolume)
spec, err := translateInTreeSpecToCSIIfNeeded(origspec, nodeName, vpm, csiMigratedPluginManager, csiTranslator, pod.Namespace)
if err != nil {
return nil, fmt.Errorf(
"error performing CSI migration checks and translation for inline volume %q: %v",
podVolume.Name,
err)
}
return spec, nil
}
// getPVCFromCache fetches the PVC object with the given namespace and
// name from the shared internal PVC store.
// This method returns an error if a PVC object does not exist in the cache
// with the given namespace/name.
// This method returns an error if the PVC object's phase is not "Bound".
func getPVCFromCache(namespace string, name string, pvcLister corelisters.PersistentVolumeClaimLister) (*v1.PersistentVolumeClaim, error) {
pvc, err := pvcLister.PersistentVolumeClaims(namespace).Get(name)
if err != nil {
return nil, fmt.Errorf("failed to find PVC %s/%s in PVCInformer cache: %v", namespace, name, err)
}
if pvc.Status.Phase != v1.ClaimBound || pvc.Spec.VolumeName == "" {
return nil, fmt.Errorf(
"PVC %s/%s has non-bound phase (%q) or empty pvc.Spec.VolumeName (%q)",
namespace,
name,
pvc.Status.Phase,
pvc.Spec.VolumeName)
}
return pvc, nil
}
// getPVSpecFromCache fetches the PV object with the given name from the shared
// internal PV store and returns a volume.Spec representing it.
// This method returns an error if a PV object does not exist in the cache with
// the given name.
// This method deep copies the PV object so the caller may use the returned
// volume.Spec object without worrying about it mutating unexpectedly.
func getPVSpecFromCache(name string, pvcReadOnly bool, expectedClaimUID types.UID, pvLister corelisters.PersistentVolumeLister) (*volume.Spec, error) {
pv, err := pvLister.Get(name)
if err != nil {
return nil, fmt.Errorf("failed to find PV %q in PVInformer cache: %v", name, err)
}
if pv.Spec.ClaimRef == nil {
return nil, fmt.Errorf(
"found PV object %q but it has a nil pv.Spec.ClaimRef indicating it is not yet bound to the claim",
name)
}
if pv.Spec.ClaimRef.UID != expectedClaimUID {
return nil, fmt.Errorf(
"found PV object %q but its pv.Spec.ClaimRef.UID (%q) does not point to claim.UID (%q)",
name,
pv.Spec.ClaimRef.UID,
expectedClaimUID)
}
// Do not return the object from the informer, since the store is shared it
// may be mutated by another consumer.
clonedPV := pv.DeepCopy()
return volume.NewSpecFromPersistentVolume(clonedPV, pvcReadOnly), nil
}
// DetermineVolumeAction returns true if volume and pod needs to be added to dswp
// and it returns false if volume and pod needs to be removed from dswp
func DetermineVolumeAction(pod *v1.Pod, desiredStateOfWorld cache.DesiredStateOfWorld, defaultAction bool) bool {
if pod == nil || len(pod.Spec.Volumes) <= 0 {
return defaultAction
}
nodeName := types.NodeName(pod.Spec.NodeName)
keepTerminatedPodVolume := desiredStateOfWorld.GetKeepTerminatedPodVolumesForNode(nodeName)
if util.IsPodTerminated(pod, pod.Status) {
// if pod is terminate we let kubelet policy dictate if volume
// should be detached or not
return keepTerminatedPodVolume
}
return defaultAction
}
// ProcessPodVolumes processes the volumes in the given pod and adds them to the
// desired state of the world if addVolumes is true, otherwise it removes them.
func ProcessPodVolumes(pod *v1.Pod, addVolumes bool, desiredStateOfWorld cache.DesiredStateOfWorld, volumePluginMgr *volume.VolumePluginMgr, pvcLister corelisters.PersistentVolumeClaimLister, pvLister corelisters.PersistentVolumeLister, csiMigratedPluginManager csimigration.PluginManager, csiTranslator csimigration.InTreeToCSITranslator) {
if pod == nil {
return
}
if len(pod.Spec.Volumes) <= 0 {
klog.V(10).Infof("Skipping processing of pod %q/%q: it has no volumes.",
pod.Namespace,
pod.Name)
return
}
nodeName := types.NodeName(pod.Spec.NodeName)
if nodeName == "" {
klog.V(10).Infof(
"Skipping processing of pod %q/%q: it is not scheduled to a node.",
pod.Namespace,
pod.Name)
return
} else if !desiredStateOfWorld.NodeExists(nodeName) {
// If the node the pod is scheduled to does not exist in the desired
// state of the world data structure, that indicates the node is not
// yet managed by the controller. Therefore, ignore the pod.
klog.V(4).Infof(
"Skipping processing of pod %q/%q: it is scheduled to node %q which is not managed by the controller.",
pod.Namespace,
pod.Name,
nodeName)
return
}
// Process volume spec for each volume defined in pod
for _, podVolume := range pod.Spec.Volumes {
volumeSpec, err := CreateVolumeSpec(podVolume, pod, nodeName, volumePluginMgr, pvcLister, pvLister, csiMigratedPluginManager, csiTranslator)
if err != nil {
klog.V(10).Infof(
"Error processing volume %q for pod %q/%q: %v",
podVolume.Name,
pod.Namespace,
pod.Name,
err)
continue
}
attachableVolumePlugin, err :=
volumePluginMgr.FindAttachablePluginBySpec(volumeSpec)
if err != nil || attachableVolumePlugin == nil {
klog.V(10).Infof(
"Skipping volume %q for pod %q/%q: it does not implement attacher interface. err=%v",
podVolume.Name,
pod.Namespace,
pod.Name,
err)
continue
}
uniquePodName := util.GetUniquePodName(pod)
if addVolumes {
// Add volume to desired state of world
_, err := desiredStateOfWorld.AddPod(
uniquePodName, pod, volumeSpec, nodeName)
if err != nil {
klog.V(10).Infof(
"Failed to add volume %q for pod %q/%q to desiredStateOfWorld. %v",
podVolume.Name,
pod.Namespace,
pod.Name,
err)
}
} else {
// Remove volume from desired state of world
uniqueVolumeName, err := util.GetUniqueVolumeNameFromSpec(
attachableVolumePlugin, volumeSpec)
if err != nil {
klog.V(10).Infof(
"Failed to delete volume %q for pod %q/%q from desiredStateOfWorld. GetUniqueVolumeNameFromSpec failed with %v",
podVolume.Name,
pod.Namespace,
pod.Name,
err)
continue
}
desiredStateOfWorld.DeletePod(
uniquePodName, uniqueVolumeName, nodeName)
}
}
return
}
func translateInTreeSpecToCSIIfNeeded(spec *volume.Spec, nodeName types.NodeName, vpm *volume.VolumePluginMgr, csiMigratedPluginManager csimigration.PluginManager, csiTranslator csimigration.InTreeToCSITranslator, podNamespace string) (*volume.Spec, error) {
translatedSpec := spec
migratable, err := csiMigratedPluginManager.IsMigratable(spec)
if err != nil {
return nil, err
}
if !migratable {
// Jump out of translation fast so we don't check the node if the spec itself is not migratable
return spec, nil
}
migrationSupportedOnNode, err := isCSIMigrationSupportedOnNode(nodeName, spec, vpm, csiMigratedPluginManager)
if err != nil {
return nil, err
}
if migratable && migrationSupportedOnNode {
translatedSpec, err = csimigration.TranslateInTreeSpecToCSI(spec, podNamespace, csiTranslator)
if err != nil {
return nil, err
}
}
return translatedSpec, nil
}
func isCSIMigrationSupportedOnNode(nodeName types.NodeName, spec *volume.Spec, vpm *volume.VolumePluginMgr, csiMigratedPluginManager csimigration.PluginManager) (bool, error) {
if !utilfeature.DefaultFeatureGate.Enabled(features.CSIMigration) {
// If CSIMigration is disabled, CSI migration paths will not be taken for the node.
return false, nil
}
pluginName, err := csiMigratedPluginManager.GetInTreePluginNameFromSpec(spec.PersistentVolume, spec.Volume)
if err != nil {
return false, err
}
if len(pluginName) == 0 {
// Could not find a plugin name from translation directory, assume not translated
return false, nil
}
if csiMigratedPluginManager.IsMigrationCompleteForPlugin(pluginName) {
// All nodes are expected to have migrated CSI plugin installed and
// configured when CSI Migration Complete flag is enabled for a plugin.
// CSI migration is supported even if there is version skew between
// managers and node.
return true, nil
}
if len(nodeName) == 0 {
return false, errors.New("nodeName is empty")
}
kubeClient := vpm.Host.GetKubeClient()
if kubeClient == nil {
// Don't handle the controller/kubelet version skew check and fallback
// to just checking the feature gates. This can happen if
// we are in a standalone (headless) Kubelet
return true, nil
}
adcHost, ok := vpm.Host.(volume.AttachDetachVolumeHost)
if !ok {
// Don't handle the controller/kubelet version skew check and fallback
// to just checking the feature gates. This can happen if
// "enableControllerAttachDetach" is set to true on kubelet
return true, nil
}
if adcHost.CSINodeLister() == nil {
return false, errors.New("could not find CSINodeLister in attachDetachController")
}
csiNode, err := adcHost.CSINodeLister().Get(string(nodeName))
if err != nil {
return false, err
}
ann := csiNode.GetAnnotations()
if ann == nil {
return false, nil
}
mpa := ann[v1.MigratedPluginsAnnotationKey]
tok := strings.Split(mpa, ",")
mpaSet := sets.NewString(tok...)
isMigratedOnNode := mpaSet.Has(pluginName)
if isMigratedOnNode {
installed := false
driverName, err := csiMigratedPluginManager.GetCSINameFromInTreeName(pluginName)
if err != nil {
return isMigratedOnNode, err
}
for _, driver := range csiNode.Spec.Drivers {
if driver.Name == driverName {
installed = true
break
}
}
if !installed {
return true, fmt.Errorf("in-tree plugin %s is migrated on node %s but driver %s is not installed", pluginName, string(nodeName), driverName)
}
}
return isMigratedOnNode, nil
}
| {
"content_hash": "b579cb3c1eafbdd1572cc7124eb55f6f",
"timestamp": "",
"source": "github",
"line_count": 386,
"max_line_length": 341,
"avg_line_length": 33.41968911917098,
"alnum_prop": 0.7290697674418605,
"repo_name": "tpepper/kubernetes",
"id": "c811e94b4cda63d5b359986c52e867be0f35d205",
"size": "13469",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/controller/volume/attachdetach/util/util.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2840"
},
{
"name": "Dockerfile",
"bytes": "50453"
},
{
"name": "Go",
"bytes": "52162010"
},
{
"name": "HTML",
"bytes": "38"
},
{
"name": "Lua",
"bytes": "17200"
},
{
"name": "Makefile",
"bytes": "65376"
},
{
"name": "PowerShell",
"bytes": "119046"
},
{
"name": "Python",
"bytes": "3612956"
},
{
"name": "Ruby",
"bytes": "413"
},
{
"name": "Shell",
"bytes": "1576640"
},
{
"name": "sed",
"bytes": "1390"
}
],
"symlink_target": ""
} |
package org.visallo.tools.ontology.ingest.codegen;
import com.google.common.base.Strings;
import org.visallo.core.exception.VisalloException;
import org.visallo.core.util.VisalloLogger;
import org.visallo.core.util.VisalloLoggerFactory;
import org.visallo.tools.ontology.ingest.common.ConceptBuilder;
import org.visallo.web.clientapi.model.ClientApiOntology;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.function.Consumer;
public class ConceptWriter extends EntityWriter {
private static final VisalloLogger LOGGER = VisalloLoggerFactory.getLogger(ConceptWriter.class);
public ConceptWriter(String outputDirectory, ClientApiOntology ontology, boolean writeCoreVisalloClasses) {
super(outputDirectory, ontology, writeCoreVisalloClasses);
}
protected void writeClass(ClientApiOntology.Concept concept) {
String conceptPackage = packageNameFromIri(concept.getId());
if (conceptPackage != null) {
String conceptClassName = classNameFromIri(concept.getId());
// Don't expose the visallo internal concepts to the generated code
if (!writeCoreVisalloClasses && conceptPackage.startsWith("org.visallo") && !conceptClassName.equals("Root")) {
return;
}
LOGGER.debug("Create concept %s.%s", conceptPackage, conceptClassName);
try (PrintWriter writer = createWriter(conceptPackage, conceptClassName)) {
String parentClass = ConceptBuilder.class.getSimpleName();
if (!Strings.isNullOrEmpty(concept.getParentConcept())) {
parentClass = packageNameFromIri(concept.getParentConcept()) + "." + classNameFromIri(concept.getParentConcept());
}
Consumer<PrintWriter> constructorWriter = methodWriter -> {
writer.println(" public " + conceptClassName + "(String id) { super(id); }");
writer.println();
writer.println(" public " + conceptClassName + "(String id, String visibility) { super(id, visibility); }");
};
writeClass(
writer,
conceptPackage,
conceptClassName,
parentClass,
concept.getId(),
findPropertiesByIri(concept.getProperties()),
constructorWriter);
} catch (IOException e) {
throw new VisalloException("Unable to create concept class.", e);
}
}
}
} | {
"content_hash": "7dc9d56166f6f06fca5363a85efd65b9",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 134,
"avg_line_length": 44.94827586206897,
"alnum_prop": 0.635596471039509,
"repo_name": "visallo/visallo",
"id": "7e4247c3bc2fbed417b8b03e7be324939ff7820b",
"size": "2607",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/ontology-ingest/codegen/src/main/java/org/visallo/tools/ontology/ingest/codegen/ConceptWriter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "205371"
},
{
"name": "Go",
"bytes": "2988"
},
{
"name": "HTML",
"bytes": "66006"
},
{
"name": "Java",
"bytes": "3686598"
},
{
"name": "JavaScript",
"bytes": "4648797"
},
{
"name": "Makefile",
"bytes": "623"
},
{
"name": "Shell",
"bytes": "17212"
}
],
"symlink_target": ""
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH. 'core/REST_Controller.php';
class Dashboard extends REST_Controller {
protected $modelName = 'DashboardModel';
function __construct() {
parent::__construct();
}
} | {
"content_hash": "ac117823fca8666748cacb2543d5c8f8",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 63,
"avg_line_length": 28.22222222222222,
"alnum_prop": 0.7283464566929134,
"repo_name": "sidArts/lignioweb2",
"id": "d3b2fe170a027787bc0148a23b33de3d69d91601",
"size": "254",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/views/UserManagement/UserRoles.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "49436"
},
{
"name": "HTML",
"bytes": "62630"
},
{
"name": "JavaScript",
"bytes": "696034"
},
{
"name": "PHP",
"bytes": "2102074"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<script src="https://github.jspm.io/jmcriffey/[email protected]/traceur-runtime.js"></script>
<script src="https://jspm.io/[email protected]"></script>
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/angular2/bundles/angular2-polyfills.min.js"></script>
<script src="node_modules/rxjs/bundles/Rx.umd.js"></script>
<script src="node_modules/angular2/bundles/angular2-all.umd.js"></script>
<script src="app/app.component.js"></script>
<script src="app/main.js"></script>
<link rel="stylesheet" type="text/css" href="app/components/style.css">
</head>
<body>
<main-window>
<h1>Loading...</h1>
</main-window>
<script>
System.config({
baseURL: '/app'
});
System.import('bootstrap');
</script>
</body>
</html> | {
"content_hash": "8db7c621d31dbdeaea6980246b112285",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 108,
"avg_line_length": 26.3125,
"alnum_prop": 0.6555819477434679,
"repo_name": "thatknitter/GlobalGameJam2016",
"id": "b48c826e796c63d208e240a59e30c2b0c777d51d",
"size": "842",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1024"
},
{
"name": "HTML",
"bytes": "1502"
},
{
"name": "JavaScript",
"bytes": "523"
},
{
"name": "TypeScript",
"bytes": "562"
}
],
"symlink_target": ""
} |
make
if [ `lsmod | grep -o sonic` ]; then
sudo rmmod sonic
fi
sudo insmod ./sonic.ko || exit 1
sudo rm -f /dev/sonic_*
devnum=`grep sonic /proc/devices| awk '{print $1}'`
sudo mknod /dev/sonic_control c $devnum 0
sudo mknod /dev/sonic_port0 c $devnum 1
sudo mknod /dev/sonic_port1 c $devnum 2
sudo chmod 666 /dev/sonic_*
../bin/enable2ports.sh
../bin/enable5gts.sh
cd ../examples
make
| {
"content_hash": "a1e85060812784475c456b0abcb03300",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 51,
"avg_line_length": 18.80952380952381,
"alnum_prop": 0.6860759493670886,
"repo_name": "hanw/sonic",
"id": "3881dadcc4fc26dfeec15455b5abf902fa923957",
"size": "409",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "demo/load.sh",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "259623"
},
{
"name": "Gnuplot",
"bytes": "1917"
},
{
"name": "Makefile",
"bytes": "3236"
},
{
"name": "Python",
"bytes": "40387"
},
{
"name": "Shell",
"bytes": "24713"
}
],
"symlink_target": ""
} |
Subsets and Splits