file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
places_sidebar.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! GtkPlacesSidebar — Sidebar that displays frequently-used places in the file system use f...
pub fn set_show_connect_to_server(&self, show_connect_to_server: bool) { unsafe { ffi::gtk_places_sidebar_set_show_connect_to_server(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(show_connect_to_server)) } } pub fn get_show_connect_to_server(&self) -> bool { unsafe { to_...
unsafe { to_bool(ffi::gtk_places_sidebar_get_show_desktop(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } }
identifier_body
scrollableElementOptions.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
* The scrollable element should not do any DOM mutations until renderNow() is called. * Defaults to false. */ lazyRender?: boolean; /** * CSS Class name for the scrollable element. */ className?: string; /** * Drop subtle horizontal and vertical shadows. * Defaults to false. */ useShadows?: boolean...
/**
random_line_split
che-empty-state.directive.ts
/* * Copyright (c) 2015-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API a...
/** * Defines a directive for creating empty state widget that are working either on desktop or on mobile devices. * It will change upon width of the screen * @author Oleksii Orel */ export class CheEmptyState implements ng.IDirective { restrict = 'E'; replace = true; transclude = false; templateUrl = 'co...
random_line_split
che-empty-state.directive.ts
/* * Copyright (c) 2015-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API a...
implements ng.IDirective { restrict = 'E'; replace = true; transclude = false; templateUrl = 'components/widget/empty-state/che-empty-state.html'; // scope values scope = { value: '@cheValue', prompt: '@?chePrompt', iconClass: '@cheIconClass' }; }
CheEmptyState
identifier_name
pagination.ts
import { Component, EventEmitter } from 'angular2/core' import { Page } from '../models' import * as _ from 'lodash' @Component({ selector: 'pagination', template: require('./pagination.jade'), inputs: [ 'page' ], events: [ 'pageChange' ] }) export class PaginationComponent { pages: number[] p...
() { return this._page } gotoPage (page: number) { if (page < 0) return this.page.current = page this.pageChange.emit(this.page) this._refresh() } nextPage () { if (this.page.current < this.page.total - 1) this.gotoPage(this.page.current + 1) } prevPage () { if (this.pa...
page
identifier_name
pagination.ts
import { Component, EventEmitter } from 'angular2/core' import { Page } from '../models' import * as _ from 'lodash' @Component({ selector: 'pagination', template: require('./pagination.jade'),
'pageChange' ] }) export class PaginationComponent { pages: number[] pageChange: EventEmitter<Page> = new EventEmitter() private _page: Page refresh () { this.page.current = 0 this._refresh() } set page (page: Page) { this._page = page this.refresh() } get page () { return...
inputs: [ 'page' ], events: [
random_line_split
pagination.ts
import { Component, EventEmitter } from 'angular2/core' import { Page } from '../models' import * as _ from 'lodash' @Component({ selector: 'pagination', template: require('./pagination.jade'), inputs: [ 'page' ], events: [ 'pageChange' ] }) export class PaginationComponent { pages: number[] p...
prevPage () { if (this.page.current > 0) this.gotoPage(this.page.current - 1) } private _refresh () { this.page.total = Math.ceil(this.page.itemCount / this.page.itemPerPage) let r = [] if (this.page.current - 2 > 0) r = [0, -1] r = r.concat(_.range(Math.max(this.page.current - 2, 0),...
{ if (this.page.current < this.page.total - 1) this.gotoPage(this.page.current + 1) }
identifier_body
InputParameter.ts
import {Parameter} from "./Parameter"; import {InputBinding} from "./InputBinding"; import {CWLType} from "./CWLType"; import {InputRecordSchema} from "./InputRecordSchema"; import {InputEnumSchema} from "./InputEnumSchema"; import {InputArraySchema} from "./InputArraySchema"; export interface InputParameter extends ...
*/ inputBinding?: InputBinding; /** * The default value for this parameter if not provided in the input * object. * */ default?: any; /** * Specify valid types of data that may be assigned to this parameter. * */ type?: CWLType | InputRecordSchema ...
/** * Describes how to handle the inputs of a process and convert them * into a concrete form for execution, such as command line parameters. *
random_line_split
Future.ts
)=>{ if (err) { reject(err); } else { resolve(data); } })); } /** * Build a successful Future with the value you provide. */ static ok<T>(val:T): Future<T> { return new Future(Promise.resolve([val])); } /...
type FutOptPair = [Future<T>,Option<T>]; // map the failures to successes with option.none // backup the original future object matching the new future const velts = origElts .map( f => f .map<FutOptPair>(item => [f, Option.of(item)]) ...
{ return Future.ok(Option.none<T>()); }
conditional_block
Future.ts
)=>{ if (err) { reject(err); } else { resolve(data); } })); } /** * Build a successful Future with the value you provide. */ static ok<T>(val:T): Future<T>
/** * Build a failed Future with the error data you provide. */ static failed<T>(reason: any): Future<T> { return new Future(Promise.reject(reason)); } /** * Creates a Future from a function returning a Promise, * which can be inline in the call, for instance: * ...
{ return new Future(Promise.resolve([val])); }
identifier_body
Future.ts
await` works directly. * * Please rather use [[Future.map]] or [[Future.flatMap]]. */ then<TResult1 = T, TResult2 = never>( onfulfilled: ((value: T) => TResult1 | PromiseLike<TResult1>), onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<...
/** * Transform the value contained in a successful Future. Has no effect * if the Future was failed. Will turn a successful Future in a failed * one if you throw an exception in the map callback (but please don't
random_line_split
Future.ts
value of that first * future. * * Also see [[Future.firstCompletedOf]] */ static firstSuccessfulOf<T>(elts: Iterable<Future<T>>): Future<T> { // https://stackoverflow.com/a/37235274/516188 return Future.of( Promise.all(Vector.ofIterable(elts).map(p => { ...
onFailure
identifier_name
Utilities.js
angular.module('app').factory('Utilities', [ '$window', function ($window) { var QueryString = (function (a) { if (a == "") { return {}; } var i; var b = {}; for (i = 0; i < a.length; ++i) { var p = a[i].split('='); if (p.length != 2) { ...
/** * Remove duplicates and empty values in array */ function cleanArray(array, duplicateKey) { if(!jQuery.isArray(array)) { return []; } if(!duplicateKey) { duplicateKey = 'category'; } //Remove empty values var newArray = ...
{ var i; for (i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; }
identifier_body
Utilities.js
angular.module('app').factory('Utilities', [ '$window', function ($window) { var QueryString = (function (a) { if (a == "") { return {}; } var i; var b = {}; for (i = 0; i < a.length; ++i) { var p = a[i].split('='); if (p.length != 2) { ...
(xml) { if (window.ActiveXObject) { return xml.xml; } else { return (new XMLSerializer()).serializeToString(xml); } } return { queryParam: function (key) { return QueryString[key]; }, parseHTML: jQuery.parseHTML, random...
xmlToString
identifier_name
Utilities.js
angular.module('app').factory('Utilities', [ '$window', function ($window) { var QueryString = (function (a) { if (a == "") { return {}; } var i; var b = {}; for (i = 0; i < a.length; ++i) { var p = a[i].split('='); if (p.length != 2) { ...
}); array = newArray; //Remove duplicates var newObject = {}; angular.forEach(array, function(value, key) { //set category as key and save key (overwriting old key) newObject[value[duplicateKey]]=key; }); newArray = []; angular.f...
{ newArray.push(value); }
conditional_block
Utilities.js
angular.module('app').factory('Utilities', [ '$window', function ($window) { var QueryString = (function (a) { if (a == "") { return {}; } var i; var b = {}; for (i = 0; i < a.length; ++i) { var p = a[i].split('='); if (p.length != 2) { ...
//Remove empty values var newArray = []; angular.forEach(array, function(value, key) { if (value[duplicateKey]){ newArray.push(value); } }); array = newArray; //Remove duplicates var newObject = {}; angular.forEach...
if(!duplicateKey) { duplicateKey = 'category'; }
random_line_split
typedeclarationnode.py
# -*- coding: utf-8 -*- """ Clase C{TypeDeclarationNode} del árbol de sintáxis abstracta. """ from pytiger2c.ast.declarationnode import DeclarationNode class TypeDeclarationNode(DeclarationNode): """ Clase C{TypeDeclarationNode} del árbol de sintáxis abstracta. Representa las distintas declaracione...
): """ Método para obtener el valor de la propiedad C{name}. """ return self._name def _set_name(self, name): """ Método para cambiar el valor de la propiedad C{name}. """ self._name = name name = property(_get_name, _set_name) d...
name(self
identifier_name
typedeclarationnode.py
# -*- coding: utf-8 -*- """ Clase C{TypeDeclarationNode} del árbol de sintáxis abstracta. """ from pytiger2c.ast.declarationnode import DeclarationNode class TypeDeclarationNode(DeclarationNode): """ Clase C{TypeDeclarationNode} del árbol de sintáxis abstracta. Representa las distintas declaracione...
def _set_name(self, name): """ Método para cambiar el valor de la propiedad C{name}. """ self._name = name name = property(_get_name, _set_name) def _get_type(self): """ Método para obtener el valor de la propiedad C{type}. """ return...
Método para obtener el valor de la propiedad C{name}. """ return self._name
identifier_body
typedeclarationnode.py
# -*- coding: utf-8 -*-
from pytiger2c.ast.declarationnode import DeclarationNode class TypeDeclarationNode(DeclarationNode): """ Clase C{TypeDeclarationNode} del árbol de sintáxis abstracta. Representa las distintas declaraciones de tipos presentes en el lenguaje de Tige. De esta clase heredan las declaraciones de rec...
""" Clase C{TypeDeclarationNode} del árbol de sintáxis abstracta. """
random_line_split
test_cts_collection_inheritance.py
from unittest import TestCase from MyCapytain.resources.collections.cts import XmlCtsTextInventoryMetadata, XmlCtsTextgroupMetadata, XmlCtsWorkMetadata, XmlCtsEditionMetadata, XmlCtsTranslationMetadata from MyCapytain.resources.prototypes.cts.inventory import CtsTextgroupMetadata with open("tests/testing_data/examples...
(self): TI = XmlCtsTextInventoryMetadata.parse(resource=SENECA) self.assertCountEqual( [str(descendant.get_label()) for descendant in TI.descendants], ["Seneca, Lucius Annaeus", "de Ira", "de Vita Beata", "de consolatione ad Helviam", "de Constantia", "de Tranquilita...
test_title
identifier_name
test_cts_collection_inheritance.py
from unittest import TestCase
with open("tests/testing_data/examples/getcapabilities.seneca.xml") as f: SENECA = f.read() class TestCollectionCtsInheritance(TestCase): def test_types(self): TI = XmlCtsTextInventoryMetadata.parse(resource=SENECA) self.assertCountEqual( [type(descendant) for descendant in TI.desc...
from MyCapytain.resources.collections.cts import XmlCtsTextInventoryMetadata, XmlCtsTextgroupMetadata, XmlCtsWorkMetadata, XmlCtsEditionMetadata, XmlCtsTranslationMetadata from MyCapytain.resources.prototypes.cts.inventory import CtsTextgroupMetadata
random_line_split
test_cts_collection_inheritance.py
from unittest import TestCase from MyCapytain.resources.collections.cts import XmlCtsTextInventoryMetadata, XmlCtsTextgroupMetadata, XmlCtsWorkMetadata, XmlCtsEditionMetadata, XmlCtsTranslationMetadata from MyCapytain.resources.prototypes.cts.inventory import CtsTextgroupMetadata with open("tests/testing_data/examples...
def test_title(self): TI = XmlCtsTextInventoryMetadata.parse(resource=SENECA) self.assertCountEqual( [str(descendant.get_label()) for descendant in TI.descendants], ["Seneca, Lucius Annaeus", "de Ira", "de Vita Beata", "de consolatione ad Helviam", "de Constantia", ...
TI = XmlCtsTextInventoryMetadata.parse(resource=SENECA) self.assertCountEqual( [type(descendant) for descendant in TI.descendants], [XmlCtsTextgroupMetadata] + [XmlCtsWorkMetadata] * 10 + [XmlCtsEditionMetadata] * 10, "Descendant should be correctly parsed into correct types"...
identifier_body
url.rs
use std::marker::PhantomData; use std::time::Duration; use irc::client::prelude::*; use lazy_static::lazy_static; use regex::Regex; use crate::plugin::*; use crate::utils::Url; use crate::FrippyClient; use self::error::*; use crate::error::ErrorKind as FrippyErrorKind; use crate::error::FrippyError; use failure::Fa...
fn find_title(body: &str) -> Result<Self, UrlError> { Self::find_by_delimiters(body, ["<title", ">", "</title>"]) } // TODO Improve logic fn get_usefulness(self, url: &str) -> Self { let mut usefulness = 0; for word in WORD_RE.find_iter(&self.0) { let w = word.as_s...
{ Self::find_by_delimiters(body, ["property=\"og:title\"", "content=\"", "\""]) }
identifier_body
url.rs
use std::marker::PhantomData; use std::time::Duration; use irc::client::prelude::*; use lazy_static::lazy_static; use regex::Regex; use crate::plugin::*; use crate::utils::Url; use crate::FrippyClient; use self::error::*; use crate::error::ErrorKind as FrippyErrorKind; use crate::error::FrippyError; use failure::Fa...
(max_kib: usize) -> Self { UrlTitles { max_kib, phantom: PhantomData, } } fn grep_url<'a>(&self, msg: &'a str) -> Option<Url<'a>> { let captures = URL_RE.captures(msg)?; debug!("Url captures: {:?}", captures); Some(captures.get(2)?.as_str().into(...
new
identifier_name
url.rs
use std::marker::PhantomData; use std::time::Duration; use irc::client::prelude::*; use lazy_static::lazy_static; use regex::Regex; use crate::plugin::*; use crate::utils::Url; use crate::FrippyClient; use self::error::*; use crate::error::ErrorKind as FrippyErrorKind; use crate::error::FrippyError; use failure::Fa...
} _ => ExecutionStatus::Done, } } fn execute_threaded( &self, client: &Self::Client, message: &Message, ) -> Result<(), FrippyError> { if let Command::PRIVMSG(_, ref content) = message.command { let title = self.url(content).conte...
{ ExecutionStatus::Done }
conditional_block
url.rs
use std::marker::PhantomData; use std::time::Duration; use irc::client::prelude::*; use lazy_static::lazy_static; use regex::Regex; use crate::plugin::*; use crate::utils::Url; use crate::FrippyClient; use self::error::*; use crate::error::ErrorKind as FrippyErrorKind; use crate::error::FrippyError; use failure::Fa...
body[start..] .find(delimiters[2]) .map(|offset| start + offset) .map(|end| &body[start..end]) }) }) .and_then(|s| s.and_then(|s| s)) .ok_or(ErrorKind::Miss...
random_line_split
DeleteDataForm.tsx
// Libraries import React, {useReducer, FunctionComponent} from 'react' import moment from 'moment' import {Form, Grid, Columns, Panel} from '@influxdata/clockface' // Components import BucketsDropdown from 'src/shared/components/DeleteDataForm/BucketsDropdown' import TimeRangeDropdown from 'src/shared/components/Dele...
return { ...state, filters: state.filters.map((filter, i) => i === action.index ? action.filter : filter ), } case 'DELETE_FILTER': return { ...state, filters: state.filters.filter((_, i) => i !== action.index), } case 'SET_DELETION_S...
{ return {...state, filters: [...state.filters, action.filter]} }
conditional_block
DeleteDataForm.tsx
// Libraries import React, {useReducer, FunctionComponent} from 'react' import moment from 'moment' import {Form, Grid, Columns, Panel} from '@influxdata/clockface' // Components import BucketsDropdown from 'src/shared/components/DeleteDataForm/BucketsDropdown' import TimeRangeDropdown from 'src/shared/components/Dele...
state.filters.every(f => !!f.key && !!f.value) const handleDelete = async () => { try { dispatch({ type: 'SET_DELETION_STATUS', deletionStatus: RemoteDataState.Loading, }) const deleteRequest = { query: { bucket: state.bucketName, org: orgID, ...
const canDelete = state.isSerious && state.deletionStatus === RemoteDataState.NotStarted &&
random_line_split
html-paths.js
var _ = require("underscore"); var html = require("../html"); exports.topLevelElement = topLevelElement; exports.elements = elements; exports.element = element; function topLevelElement(tagName, attributes) { return elements([element(tagName, attributes, { fresh: true })]); } function elements(elementStyles...
(tagName, attributes, options) { options = options || {}; return new Element(tagName, attributes, options); } function Element(tagName, attributes, options) { var tagNames = {}; if (_.isArray(tagName)) { tagName.forEach(function (tagName) { tagNames[tagName] = true; }); tagName = tagName[0];...
element
identifier_name
html-paths.js
var _ = require("underscore"); var html = require("../html"); exports.topLevelElement = topLevelElement; exports.elements = elements; exports.element = element; function topLevelElement(tagName, attributes) { return elements([element(tagName, attributes, { fresh: true })]); } function elements(elementStyles...
else { tagNames[tagName] = true; } this.tagName = tagName; this.tagNames = tagNames; this.attributes = attributes || {}; this.fresh = options.fresh; this.separator = options.separator; } Element.prototype.matchesElement = function (element) { return this.tagNames[element.tagName] && _.isEqual(this....
{ tagName.forEach(function (tagName) { tagNames[tagName] = true; }); tagName = tagName[0]; }
conditional_block
html-paths.js
var _ = require("underscore"); var html = require("../html"); exports.topLevelElement = topLevelElement; exports.elements = elements; exports.element = element; function topLevelElement(tagName, attributes)
function elements(elementStyles) { return new HtmlPath(elementStyles.map(function (elementStyle) { if (_.isString(elementStyle)) { return element(elementStyle); } else { return elementStyle; } })); } function HtmlPath(elements) { this._elements = elements; } HtmlPath.prototype.wrap = f...
{ return elements([element(tagName, attributes, { fresh: true })]); }
identifier_body
html-paths.js
var _ = require("underscore"); var html = require("../html"); exports.topLevelElement = topLevelElement; exports.elements = elements; exports.element = element; function topLevelElement(tagName, attributes) { return elements([element(tagName, attributes, { fresh: true })]); }
if (_.isString(elementStyle)) { return element(elementStyle); } else { return elementStyle; } })); } function HtmlPath(elements) { this._elements = elements; } HtmlPath.prototype.wrap = function wrap(children) { var result = children(); for (var index = this._elements.length - 1; inde...
function elements(elementStyles) { return new HtmlPath(elementStyles.map(function (elementStyle) {
random_line_split
aead.rs
], output: &mut W) -> Result<(), DecryptError> { let mut chacha20 = ChaCha20::new(key, nonce); let mut poly1305 = Poly1305::new(&chacha20.next().as_bytes()[..32]); let aad_len = aad.len() as u64; let input_len = input.len() as u64; assert!(tag.len() == 16); if input_le...
random_line_split
aead.rs
5, 0xf0, 0x47, 0x39, 0x17, 0xc1, 0x40, 0x2b, 0x80, 0x09, 0x9d, 0xca, 0x5c, 0xbc, 0x20, 0x70, 0x75, 0xc0]; static CIPHERTEXT: &'static [u8] = &[ 0x64, 0xa0, 0x86, 0x15, 0x75, 0x86, 0x1a, 0xf4, 0x60, 0xf0, 0x62, 0xc7, 0x9b, 0xe6, 0x43, 0xbd, 0x5e, 0x80, 0x5c, 0xfd, 0x34, 0x5c,...
bench_encrypt
identifier_name
aead.rs
x94, 0x81, 0x14, 0xad, 0x17, 0x6e, 0x00, 0x8d, 0x33, 0xbd, 0x60, 0xf9, 0x82, 0xb1, 0xff, 0x37, 0xc8, 0x55, 0x97, 0x97, 0xa0, 0x6e, 0xf4, 0xf0, 0xef, 0x61, 0xc1, 0x86, 0x32, 0x4e, 0x2b, 0x35, 0x06, 0x38, 0x36, 0x06, 0x90, 0x7b, 0x6a, 0x7c, 0x02, 0xb0, 0xf9, 0xf6, 0x15, 0x7...
{ bench_decrypt(b, &[!0; 16], &[!0; 65536]) }
identifier_body
characterdata.rs
ChildrenMutation, Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use dom::virtualmethods::vtable_for; use dom_struct::dom_struct; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: ...
#[inline] pub fn append_data(&self, data: &str) { self.data.borrow_mut().push_str(data); self.content_changed(); } fn content_changed(&self) { let node = self.upcast::<Node>(); node.dirty(NodeDamage::OtherNodeDamage); } } impl CharacterDataMethods for CharacterData...
self.data.borrow() }
random_line_split
characterdata.rs
ChildrenMutation, Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use dom::virtualmethods::vtable_for; use dom_struct::dom_struct; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: ...
(&self) -> &str { &(*self.unsafe_get()).data.borrow_for_layout() } } /// Split the
data_for_layout
identifier_name
characterdata.rs
ChildrenMutation, Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use dom::virtualmethods::vtable_for; use dom_struct::dom_struct; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: ...
pub fn clone_with_data(&self, data: DOMString, document: &Document) -> Root<Node> { match self.upcast::<Node>().type_id() { NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => { Root::upcast(Comment::new(data, &document)) } NodeTypeId::CharacterDa...
{ CharacterData { node: Node::new_inherited(document), data: DOMRefCell::new(data), } }
identifier_body
characterdata.rs
(NodeDamage::OtherNodeDamage); } } impl CharacterDataMethods for CharacterData { // https://dom.spec.whatwg.org/#dom-characterdata-data fn Data(&self) -> DOMString { self.data.borrow().clone() } // https://dom.spec.whatwg.org/#dom-characterdata-data fn SetData(&self, data: DOMString) {...
{ let (a, b) = s.split_at(i); return Ok((a, None, b)); }
conditional_block
cell-command-standard.py
import sys, os, subprocess, tempfile, shlex, glob result = None d = None def
(message, headline): msg = "Line {0}:\n {1}\n{2}:\n{3}"\ .format(PARAMS["lineno"], PARAMS["source"], headline, message) return msg try: #print("RUN", PARAMS["source"]) d = tempfile.mkdtemp(dir="/dev/shm") command_params = [] created_files = [] for ref in PARAMS["refs"]: if ...
format_msg
identifier_name
cell-command-standard.py
import sys, os, subprocess, tempfile, shlex, glob result = None d = None def format_msg(message, headline): msg = "Line {0}:\n {1}\n{2}:\n{3}"\ .format(PARAMS["lineno"], PARAMS["source"], headline, message) return msg try: #print("RUN", PARAMS["source"]) d = tempfile.mkdtemp(dir="/dev/shm") ...
result = stderr_data elif return_mode == "capture": result = capture_data finally: if d is not None: os.system("rm -rf %s" % d) return result
random_line_split
cell-command-standard.py
import sys, os, subprocess, tempfile, shlex, glob result = None d = None def format_msg(message, headline):
try: #print("RUN", PARAMS["source"]) d = tempfile.mkdtemp(dir="/dev/shm") command_params = [] created_files = [] for ref in PARAMS["refs"]: if isinstance(ref, str): value = globals()[ref] inp_type = PARAMS["inputs"][ref] if inp_type == "variable": ...
msg = "Line {0}:\n {1}\n{2}:\n{3}"\ .format(PARAMS["lineno"], PARAMS["source"], headline, message) return msg
identifier_body
cell-command-standard.py
import sys, os, subprocess, tempfile, shlex, glob result = None d = None def format_msg(message, headline): msg = "Line {0}:\n {1}\n{2}:\n{3}"\ .format(PARAMS["lineno"], PARAMS["source"], headline, message) return msg try: #print("RUN", PARAMS["source"]) d = tempfile.mkdtemp(dir="/dev/shm") ...
#TODO return_mode, see above if return_mode == "stdout": result = stdout_data elif return_mode == "stderr": result = stderr_data elif return_mode == "capture": result = capture_data finally: if d is not None: os.system("rm -rf %s" % d) return result
new_files = [] for dirpath, dirnames, filenames in os.walk(d): for filename in filenames: new_file = os.path.join(dirpath, filename) if new_file not in created_files: new_files.append(new_file) capture_data = {} for f in new_files: ...
conditional_block
sight.py
""" Lonely Planet Sight Model """ from __future__ import absolute_import, print_function import re from bs4 import BeautifulSoup from django.db import models from django.utils.translation import ugettext as _ from core.models.sight import THSight from core.utils import urllib2 from .abstract import LonelyPlanetAbst...
class LPSight(LonelyPlanetAbstractModel): """ Represents a Lonely Planet page with information about a City Sight """ class Meta(object): verbose_name = _('Lonely Planet Sight') ordering = ['name'] lpplace = models.ForeignKey( LPPlace, blank=False, null=False...
exclude_years=u'(?!-?\d?yr)', hours=u'(?!am|pm|hr|\xBD)', )
random_line_split
sight.py
""" Lonely Planet Sight Model """ from __future__ import absolute_import, print_function import re from bs4 import BeautifulSoup from django.db import models from django.utils.translation import ugettext as _ from core.models.sight import THSight from core.utils import urllib2 from .abstract import LonelyPlanetAbst...
(cls, url, parent=None, recursive=True, **kwargs): """ Given an url, extract and build a LPSight """ verbose = kwargs.get('verbose', 0) new_sight = None try: new_sight = LPSight.objects.get(url=url) cls._log( _(u'Sight[{id}]: {name}...
build_from_url
identifier_name
sight.py
""" Lonely Planet Sight Model """ from __future__ import absolute_import, print_function import re from bs4 import BeautifulSoup from django.db import models from django.utils.translation import ugettext as _ from core.models.sight import THSight from core.utils import urllib2 from .abstract import LonelyPlanetAbst...
if 'Prices' in info: data['cost'] = info['Prices'] geoposition = info.get('geopoint', None) if geoposition: data['geoposition'] = geoposition data['exact_location'] = True else: data['exact_location'] = False if 'image' in info:...
data['how_to_get_there'] = info['Getting there']
conditional_block
sight.py
""" Lonely Planet Sight Model """ from __future__ import absolute_import, print_function import re from bs4 import BeautifulSoup from django.db import models from django.utils.translation import ugettext as _ from core.models.sight import THSight from core.utils import urllib2 from .abstract import LonelyPlanetAbst...
@classmethod def html_nearby_extractor(cls): """ Return a string with the arguments necessary to extract all the nearby sights """ return '.nearby-cards__content .card__mask' @classmethod def update_sight(cls, sight, overwrite=False, **kwargs): """ ...
""" Return a string with the arguments necessary to split a sight list from html """ return '.stack__content > .grid-wrapper--10 .card__mask'
identifier_body
facetrack.py
#!/usr/bin/env python # # Released under the BSD license. See LICENSE file for details. """ This program basically does face detection an blurs the face out. """ print __doc__ from SimpleCV import Camera, Display, HaarCascade # Initialize the camera cam = Camera() # Create the display to show the image display = Di...
img = cam.getImage().flipHorizontal().scale(0.5) # Load in trained face file faces = img.findHaarFeatures(haarcascade) # Pixelize the detected face if faces: bb = faces[-1].boundingBox() img = img.pixelize(10, region=(bb[0], bb[1], bb[2], bb[3])) # Display the image img.save(disp...
conditional_block
facetrack.py
#!/usr/bin/env python # # Released under the BSD license. See LICENSE file for details. """ This program basically does face detection an blurs the face out. """ print __doc__ from SimpleCV import Camera, Display, HaarCascade # Initialize the camera cam = Camera() # Create the display to show the image display = Di...
# Load in trained face file faces = img.findHaarFeatures(haarcascade) # Pixelize the detected face if faces: bb = faces[-1].boundingBox() img = img.pixelize(10, region=(bb[0], bb[1], bb[2], bb[3])) # Display the image img.save(display)
# Loop forever while display.isNotDone(): # Get image, flip it so it looks mirrored, scale to speed things up img = cam.getImage().flipHorizontal().scale(0.5)
random_line_split
issue-16747.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<'a, T: ListItem<'a>> { //~^ ERROR the parameter type `T` may not live long enough //~^^ HELP consider adding an explicit lifetime bound //~^^^ NOTE ...so that the reference type `&'a [T]` does not outlive the data it points at slice: &'a [T] } impl<'a, T: ListItem<'a>> Collection for List<'a, T> { fn len(&sel...
List
identifier_name
issue-16747.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() {}
random_line_split
MonitoredSocket.ts
import net = require("net"); /** * Represents a given host and port. Handles checking whether a host * is up or not, as well as if it is accessible on the given port. */ class MonitoredSocket { /** * Returns whether the host can be accessed on its port. */ public isUp: boolean; private socke...
onConnectFailure(callback: { (sock: MonitoredSocket, conn?: any): void }, conn?: any) { this.isUp = false; // Cleanup this.socket.destroy(); callback(this, conn); } toString(): string { return this.endpoint + ":" + this.port; } serialize(): string { ...
this.isUp = true; // We're good! Close the socket this.socket.end(); callback(this, conn); }
identifier_body
MonitoredSocket.ts
import net = require("net"); /** * Represents a given host and port. Handles checking whether a host * is up or not, as well as if it is accessible on the given port. */
/** * Returns whether the host can be accessed on its port. */ public isUp: boolean; private socket: net.Socket; constructor( public endpoint: string, public port: number ) { this.socket = new net.Socket(); } connect(successCallback: { (sock: MonitoredSock...
class MonitoredSocket {
random_line_split
MonitoredSocket.ts
import net = require("net"); /** * Represents a given host and port. Handles checking whether a host * is up or not, as well as if it is accessible on the given port. */ class MonitoredSocket { /** * Returns whether the host can be accessed on its port. */ public isUp: boolean; private socke...
: string { return this.endpoint + ":" + this.port; } serialize(): string { return JSON.stringify({ "socket": this.endpoint + ":" + this.port, "status": this.isUp }); } } export = MonitoredSocket;
String()
identifier_name
import-glob-0.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern...
// file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
random_line_split
import-glob-0.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { f1(); f2(); f999(); // 'export' currently doesn't work? f4(); }
main
identifier_name
import-glob-0.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} fn main() { f1(); f2(); f999(); // 'export' currently doesn't work? f4(); }
{ debug!("f4"); }
identifier_body
Bar.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Animated, Easing, View, } from 'react-native'; const INDETERMINATE_WIDTH_FACTOR = 0.3; const BAR_WIDTH_ZERO_POSITION = INDETERMINATE_WIDTH_FACTOR / (1 + INDETERMINATE_WIDTH_FACTOR); export default class ProgressBar extends Co...
() { if (this.props.indeterminate) { this.animate(); } } componentWillReceiveProps(props) { if (props.indeterminate !== this.props.indeterminate) { if (props.indeterminate) { this.animate(); } else { Animated.spring(this.state.animationValue, { toValue: BAR_W...
componentDidMount
identifier_name
Bar.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Animated, Easing, View, } from 'react-native'; const INDETERMINATE_WIDTH_FACTOR = 0.3; const BAR_WIDTH_ZERO_POSITION = INDETERMINATE_WIDTH_FACTOR / (1 + INDETERMINATE_WIDTH_FACTOR); export default class ProgressBar extends Co...
overflow: 'hidden', backgroundColor: unfilledColor, }; const progressStyle = { backgroundColor: color, height, width: innerWidth, transform: [{ translateX: this.state.animationValue.interpolate({ inputRange: [0, 1], outputRange: [innerWidth * -INDE...
{ const { borderColor, borderRadius, borderWidth, children, color, height, style, unfilledColor, width, ...restProps } = this.props; const innerWidth = width - (borderWidth * 2); const containerStyle = { width, borderWidth, b...
identifier_body
Bar.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Animated, Easing, View, } from 'react-native'; const INDETERMINATE_WIDTH_FACTOR = 0.3; const BAR_WIDTH_ZERO_POSITION = INDETERMINATE_WIDTH_FACTOR / (1 + INDETERMINATE_WIDTH_FACTOR); export default class ProgressBar extends Co...
else { this.state.progress.setValue(progress); } } } animate() { this.state.animationValue.setValue(0); Animated.timing(this.state.animationValue, { toValue: 1, duration: 1000, easing: Easing.linear, isInteraction: false, }).start((endState) => { if (end...
{ Animated.spring(this.state.progress, { toValue: progress, bounciness: 0, }).start(); }
conditional_block
Bar.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Animated, Easing, View, } from 'react-native'; const INDETERMINATE_WIDTH_FACTOR = 0.3; const BAR_WIDTH_ZERO_POSITION = INDETERMINATE_WIDTH_FACTOR / (1 + INDETERMINATE_WIDTH_FACTOR); export default class ProgressBar extends Co...
width: PropTypes.number, }; static defaultProps = { animated: true, borderRadius: 4, borderWidth: 1, color: 'rgba(0, 122, 255, 1)', height: 6, indeterminate: false, progress: 0, width: 150, }; constructor(props) { super(props); const progress = Math.min(Math.max(pro...
height: PropTypes.number, indeterminate: PropTypes.bool, progress: PropTypes.number, style: View.propTypes.style, unfilledColor: PropTypes.string,
random_line_split
product.js
'use strict' const voucherifyClient = require('../src/index') const voucherify = voucherifyClient({ applicationId: 'c70a6f00-cf91-4756-9df5-47628850002b', clientSecretKey: '3266b9f8-e246-4f79-bdf0-833929b1380c' }) const payload = { name: 'Apple iPhone 6', metadata: { type: 'normal' }, attributes: [ ...
.catch((err) => { console.log('Result:', err) return product }) .then((product) => { skuId = null return product }) }) }) .then((product) => { console.log('==== DELETE ====') return voucherify.products.delete(product.id) .then(() => { console.log('Checking...') re...
.then(() => { console.log('Checking...') return voucherify.products.getSku(product.id, skuId)
random_line_split
product.js
'use strict' const voucherifyClient = require('../src/index') const voucherify = voucherifyClient({ applicationId: 'c70a6f00-cf91-4756-9df5-47628850002b', clientSecretKey: '3266b9f8-e246-4f79-bdf0-833929b1380c' }) const payload = { name: 'Apple iPhone 6', metadata: { type: 'normal' }, attributes: [ ...
console.log('==== DELETE - SKU ====') return voucherify.products.deleteSku(product.id, skuId) .then(() => { console.log('Checking...') return voucherify.products.getSku(product.id, skuId) .catch((err) => { console.log('Result:', err) return product }) .then((product) => { ...
{ return product }
conditional_block
plot.js
Ext.BLANK_IMAGE_URL = '/vendor/ext/3.4.1/resources/images/default/s.gif'; Ext.override(Ext.form.ComboBox, { doQuery : function(q, forceAll){ if(q === undefined || q === null){ q = ''; } var qe = { query: q, forceAll: forceAll, combo: this, cancel:false }; if(this.fireEvent('beforequery', qe)===false ...
(){ var ds = datepicker.getValue(); var ds2 = ds.add(Date.DAY, dayInterval.getValue()); var url = String.format('plot.php?station={0}&sday={1}&eday={2}&var={3}', stationCB.getValue(), ds.format('Y-m-d'), ds2.format('Y-m-d'), varCB.getValue()); Ext.get("imagedisplay").dom.src = url; /* Now adjust the ...
updateImage
identifier_name
plot.js
Ext.BLANK_IMAGE_URL = '/vendor/ext/3.4.1/resources/images/default/s.gif'; Ext.override(Ext.form.ComboBox, { doQuery : function(q, forceAll){ if(q === undefined || q === null){ q = ''; } var qe = { query: q, forceAll: forceAll, combo: this, cancel:false }; if(this.fireEvent('beforequery', qe)===false ...
} });
{ stateCB.setValue( tokens2[0] ); stationCB.setValue( tokens2[1] ); varCB.setValue( tokens2[2] ); datepicker.setValue( tokens2[3] ); dayInterval.setValue( tokens2[4] ); updateImage(); }
conditional_block
plot.js
Ext.BLANK_IMAGE_URL = '/vendor/ext/3.4.1/resources/images/default/s.gif'; Ext.override(Ext.form.ComboBox, { doQuery : function(q, forceAll){ if(q === undefined || q === null){ q = ''; } var qe = { query: q, forceAll: forceAll, combo: this, cancel:false }; if(this.fireEvent('beforequery', qe)===false ...
["NJ","New Jersey"], ["NM","New Mexico"], ["NY","New York"], ["NC","North Carolina"], ["ND","North Dakota"], ["OH","Ohio"], ["OK","Oklahoma"], ["OR","Oregon"], ["PA","Pennsylvania"], ["RI","Rhode Island"], ["SC","South Carolina"], ["SD","South Dakota"], ["TN","Tennessee"], ["TX","Texas"], ["UT","Utah"], ...
["NH","New Hampshire"],
random_line_split
plot.js
Ext.BLANK_IMAGE_URL = '/vendor/ext/3.4.1/resources/images/default/s.gif'; Ext.override(Ext.form.ComboBox, { doQuery : function(q, forceAll){ if(q === undefined || q === null){ q = ''; } var qe = { query: q, forceAll: forceAll, combo: this, cancel:false }; if(this.fireEvent('beforequery', qe)===false ...
new Ext.form.FormPanel({ applyTo : 'myform', labelAlign : 'top', width : 320, style : 'padding-left: 5px;', title : 'Make Plot Selections Below...', items : [stateCB, stationCB, varCB, datepicker, dayInterval], buttons : [{ text : 'Create Graph', handler : function(){ updateImage(); ...
{ var ds = datepicker.getValue(); var ds2 = ds.add(Date.DAY, dayInterval.getValue()); var url = String.format('plot.php?station={0}&sday={1}&eday={2}&var={3}', stationCB.getValue(), ds.format('Y-m-d'), ds2.format('Y-m-d'), varCB.getValue()); Ext.get("imagedisplay").dom.src = url; /* Now adjust the UR...
identifier_body
index.ts
/// <reference path='../node_modules/typescript/lib/typescriptServices.d.ts' /> /// <reference path="./defines.d.ts"/> /// <reference path='../typings/tsd.d.ts' /> import * as _ from 'lodash'; import * as path from 'path'; import { ICompilerOptions } from './host'; import { createResolver } from './deps'; import { fi...
console.error('Error in bail mode:', e, e.stack.join ? e.stack.join ('\n') : e.stack ); process.exit(1); } } catch (err) { console.error(err.toString(), err.stack.toString()); callback(err, helpers.codegenErrorReport([err]))...
} try { callback(null, resultText, resultSourceMap); } catch (e) {
random_line_split
index.ts
/// <reference path='../node_modules/typescript/lib/typescriptServices.d.ts' /> /// <reference path="./defines.d.ts"/> /// <reference path='../typings/tsd.d.ts' /> import * as _ from 'lodash'; import * as path from 'path'; import { ICompilerOptions } from './host'; import { createResolver } from './deps'; import { fi...
let depsInjector = { add: (depFileName) => webpack.addDependency(depFileName), clear: webpack.clearDependencies.bind(webpack) }; let applyDeps = _.once(() => { depsInjector.clear(); depsInjector.add(fileName); state.fileAnalyzer.dependencies.applyCompiledFiles(fileN...
{ if (webpack.cacheable) { webpack.cacheable(); } let options = <ICompilerOptions>loaderUtils.parseQuery(webpack.query); let instanceName = options.instanceName || 'default'; let instance = ensureInstance(webpack, options, instanceName); let state = instance.tsState; let callback ...
identifier_body
index.ts
/// <reference path='../node_modules/typescript/lib/typescriptServices.d.ts' /> /// <reference path="./defines.d.ts"/> /// <reference path='../typings/tsd.d.ts' /> import * as _ from 'lodash'; import * as path from 'path'; import { ICompilerOptions } from './host'; import { createResolver } from './deps'; import { fi...
(webpack: IWebPack, text: string): Promise<void> { if (webpack.cacheable) { webpack.cacheable(); } let options = <ICompilerOptions>loaderUtils.parseQuery(webpack.query); let instanceName = options.instanceName || 'default'; let instance = ensureInstance(webpack, options, instanceName); ...
compiler
identifier_name
index.ts
/// <reference path='../node_modules/typescript/lib/typescriptServices.d.ts' /> /// <reference path="./defines.d.ts"/> /// <reference path='../typings/tsd.d.ts' /> import * as _ from 'lodash'; import * as path from 'path'; import { ICompilerOptions } from './host'; import { createResolver } from './deps'; import { fi...
instance.compiledFiles[fileName] = true; let doUpdate = false; if (instance.options.useWebpackText) { if (state.updateFile(fileName, text, true)) { doUpdate = true; } } try { let wasChanged = await state.fileAnalyzer.checkDependencies(resolver, fileName); ...
{ if (instance.externalsInvocation) { await instance.externalsInvocation; } else { let promises = instance.options.externals.map(async (external) => { await state.fileAnalyzer.checkDependencies(resolver, external); }); instance.externalsIn...
conditional_block
targz.py
"""tarball Tool-specific initialization for tarball. """ ## Commands to tackle a command based implementation: ##to unpack on the fly... ##gunzip < FILE.tar.gz | tar xvf - ##to pack on the fly... ##tar cvf - FILE-LIST | gzip -c > FILE.tar.gz import os.path import SCons.Builder import SCons.Node.FS ...
return internal_targz
def generate(env): pass def exists(env):
random_line_split
targz.py
"""tarball Tool-specific initialization for tarball. """ ## Commands to tackle a command based implementation: ##to unpack on the fly... ##gunzip < FILE.tar.gz | tar xvf - ##to pack on the fly... ##tar cvf - FILE-LIST | gzip -c > FILE.tar.gz import os.path import SCons.Builder import SCons.Node.FS ...
compression = env.get('TARGZ_COMPRESSION_LEVEL',TARGZ_DEFAULT_COMPRESSION_LEVEL) base_dir = os.path.normpath( env.get('TARGZ_BASEDIR', env.Dir('.')).abspath ) target_path = str(target[0]) fileobj = gzip.GzipFile( target_path, 'wb', compression ) tar = tarfile.TarFile(os.pat...
for name in names: path = os.path.join(dirname, name) if os.path.isfile(path): tar.add(path, archive_name(path) )
identifier_body
targz.py
"""tarball Tool-specific initialization for tarball. """ ## Commands to tackle a command based implementation: ##to unpack on the fly... ##gunzip < FILE.tar.gz | tar xvf - ##to pack on the fly... ##tar cvf - FILE-LIST | gzip -c > FILE.tar.gz import os.path import SCons.Builder import SCons.Node.FS ...
os.path.walk(source_path, visit, tar) else: tar.add(source_path, archive_name(source_path) ) # filename, arcname tar.close() targzAction = SCons.Action.Action(targz, varlist=['TARGZ_COMPRESSION_LEVEL','TARGZ_BASEDIR']) def makeBuilder( emitter = ...
def targz(target, source, env): def archive_name( path ): path = os.path.normpath( os.path.abspath( path ) ) common_path = os.path.commonprefix( (base_dir, path) ) archive_name = path[len(common_path):] return archive_name def visit(tar...
conditional_block
targz.py
"""tarball Tool-specific initialization for tarball. """ ## Commands to tackle a command based implementation: ##to unpack on the fly... ##gunzip < FILE.tar.gz | tar xvf - ##to pack on the fly... ##tar cvf - FILE-LIST | gzip -c > FILE.tar.gz import os.path import SCons.Builder import SCons.Node.FS ...
(env): pass def exists(env): return internal_targz
generate
identifier_name
MatplotlibImportTimingWidget.py
# coding=utf-8 ''' Created on 6.6.2013 Updated on 29.8.2013 Potku is a graphical user interface for analyzation and visualization of measurement data collected from a ToF-ERD telescope. For physics calculations Potku uses external analyzation components. Copyright (C) Timo Konu This program is free software; you...
self): '''Custom toolbar buttons be here. ''' self.__tool_label = self.mpl_toolbar.children()[24] self.__button_drag = self.mpl_toolbar.children()[12] self.__button_zoom = self.mpl_toolbar.children()[14] self.__button_drag.clicked.connect(self.__uncheck_custom_buttons) ...
_fork_toolbar_buttons(
identifier_name
MatplotlibImportTimingWidget.py
# coding=utf-8 ''' Created on 6.6.2013 Updated on 29.8.2013 Potku is a graphical user interface for analyzation and visualization of measurement data collected from a ToF-ERD telescope. For physics calculations Potku uses external analyzation components. Copyright (C) Timo Konu This program is free software; you...
self.data = [] with open(output_file) as fp: for line in fp: if not line: # Can still result in empty lines at the end, skip. continue split = line.strip().split("\t") time_diff = int(split[3]) # if time_dif...
self.__limit_low, self.__limit_high, timing_key)) self.__limit_prev = 0
random_line_split
MatplotlibImportTimingWidget.py
# coding=utf-8 ''' Created on 6.6.2013 Updated on 29.8.2013 Potku is a graphical user interface for analyzation and visualization of measurement data collected from a ToF-ERD telescope. For physics calculations Potku uses external analyzation components. Copyright (C) Timo Konu This program is free software; you...
# Set values to parent dialog (main_frame = ImportTimingGraphDialog) self.main_frame.timing_low.setValue(self.__limit_low) self.main_frame.timing_high.setValue(self.__limit_high) self.main_frame.setWindowTitle("{0} - Timing: ({1},{2})".format( ...
elf.__limit_low, self.__limit_high = \ self.__limit_high, self.__limit_low
conditional_block
MatplotlibImportTimingWidget.py
# coding=utf-8 ''' Created on 6.6.2013 Updated on 29.8.2013 Potku is a graphical user interface for analyzation and visualization of measurement data collected from a ToF-ERD telescope. For physics calculations Potku uses external analyzation components. Copyright (C) Timo Konu This program is free software; you...
def __uncheck_custom_buttons(self): self.limButton.setChecked(False) def __uncheck_built_in_buttons(self): self.__button_drag.setChecked(False) self.__button_zoom.setChecked(False) self.__tool_label.setText("") self.mpl_toolbar.mode = ""
''Click event on limit button. ''' if self.limButton.isChecked(): self.__uncheck_built_in_buttons() self.__tool_label.setText("timing limit tool") self.mpl_toolbar.mode = "timing limit tool" else: self.__tool_label.setText("") self.mpl_...
identifier_body
attachment.py
"""Module provides provides a convinient class :class:`Attachment` to access (Create, Read, Delete) document attachments.""" import base64, logging
from httperror import * from httpc import HttpSession, ResourceNotFound, OK, CREATED from couchpy import CouchPyError # TODO : # 1. URL-encoding for attachment file-names log = logging.getLogger( __name__ ) def _readattach( conn, paths=[], hthdrs={} ) : """ GET...
from os.path import basename from copy import deepcopy from mimetypes import guess_type
random_line_split
attachment.py
"""Module provides provides a convinient class :class:`Attachment` to access (Create, Read, Delete) document attachments.""" import base64, logging from os.path import basename from copy import deepcopy from mimetypes import guess_type from httperror import *...
def data( self, hthdrs={} ) : """Returns the content of the file attached to the document. Can optionally take a dictionary of http headers. """ hthdrs = self.conn.mixinhdrs( self.hthdrs, hthdrs ) data, content_type = self.getattachment( sel...
"""Information from attachment stub in the document. If `field` key-word argument is provided, value of that particular field is returned, otherwise, entire dictionary of information is returned """ a = self.doc.doc.get( '_attachments', {} ).get( self.filename, {} ) val = a if fi...
identifier_body
attachment.py
"""Module provides provides a convinient class :class:`Attachment` to access (Create, Read, Delete) document attachments.""" import base64, logging from os.path import basename from copy import deepcopy from mimetypes import guess_type from httperror import *...
def _writeattach( conn, paths=[], body='', hthdrs={}, **query ) : """ PUT /<db>/<doc>/<attachment> PUT /<db>/_design/<design-doc>/<attachment> query, rev=<_rev> """ if 'Content-Length' not in hthdrs : raise CouchPyError( '`Content-Length` header field not supplied' ) if 'Co...
return (None, None, None)
conditional_block
attachment.py
"""Module provides provides a convinient class :class:`Attachment` to access (Create, Read, Delete) document attachments.""" import base64, logging from os.path import basename from copy import deepcopy from mimetypes import guess_type from httperror import *...
( self, field=None ) : """Information from attachment stub in the document. If `field` key-word argument is provided, value of that particular field is returned, otherwise, entire dictionary of information is returned """ a = self.doc.doc.get( '_attachments', {} ).get( self.filen...
attachinfo
identifier_name
Gruntfile.js
/******************************************************************************* Add to .git/hooks/pre-commit (and chmod +x) to enable auto-linting/uglifying: #!/bin/sh grunt build if [ $? -ne 0 ]; then exit 1 fi git add deflector.min.js exit 0 **********************************************************************...
}, uglify: { all: { files: { 'deflector.min.js': 'deflector.js' }} }, watch: { all: { files: ['deflector.js', 'deflector.test.js'], tasks: ['build'] } } }); for (var key in grunt.file.readJSON('package....
tunnelTimeout: 5, concurrency: 3 } }
random_line_split
Gruntfile.js
/******************************************************************************* Add to .git/hooks/pre-commit (and chmod +x) to enable auto-linting/uglifying: #!/bin/sh grunt build if [ $? -ne 0 ]; then exit 1 fi git add deflector.min.js exit 0 *********************************************************************...
} grunt.registerTask('build', ['jshint', 'uglify', 'qunit']); grunt.registerTask('test', ['build', 'connect', 'saucelabs-qunit']); grunt.registerTask('default', ['build', 'connect', 'watch']); };
{ grunt.loadNpmTasks(key); }
conditional_block
file_finder.py
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-FileFinder', 'Author': ['@harmj0y'], 'Description': ('Finds sensitive files on the domain.'), 'Background' : True, 'OutputExt...
script += ' | Out-String | %{$_ + \"`n\"};"`n'+str(moduleName)+' completed!"' return script
if option.lower() != "agent": if values['Value'] and values['Value'] != '': if values['Value'].lower() == "true": # if we're just adding a switch script += " -" + str(option) else: script += "...
conditional_block
file_finder.py
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]):
} # any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : { 'Description' : 'Agent to run module on.', 'Required' : Tru...
self.info = { 'Name': 'Invoke-FileFinder', 'Author': ['@harmj0y'], 'Description': ('Finds sensitive files on the domain.'), 'Background' : True, 'OutputExtension' : None, 'NeedsAdmin' : False, 'OpsecSafe' : True, ...
identifier_body
file_finder.py
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-FileFinder', 'Author': ['@harmj0y'], 'Description': ('Finds sensitive files on the domain.'), 'Background' : True, 'OutputExt...
# any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : { 'Description' : 'Agent to run module on.', 'Required' : True, ...
] }
random_line_split
file_finder.py
from lib.common import helpers class
: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-FileFinder', 'Author': ['@harmj0y'], 'Description': ('Finds sensitive files on the domain.'), 'Background' : True, 'OutputExtension' : None, 'Ne...
Module
identifier_name
main.rs
extern crate prometheus; extern crate hyper; extern crate dotenv; extern crate rusoto; extern crate ctrlc; #[macro_use] extern crate serde_derive; extern crate serde_yaml; extern crate time; extern crate env_logger; mod config; mod poller; mod periodic; mod server; mod termination; mod pagination; mod aws_poller; use...
.unwrap(); let _aws_instances_runner = AsyncPeriodicRunner::new(aws_instances_poller, polling_period.clone()); let _aws_spot_prices_runner = AsyncPeriodicRunner::new(aws_spot_prices_poller, polling_period.clone()); TerminationGuard::new(); let _ = listening.close(); }
{ inject_environment(); env_logger::init().unwrap(); let config = config::DeucalionSettings::from_filename("config.yml") .expect("Could not load configuration"); let polling_period = config.polling_period() .unwrap_or(Duration::from_secs(60)); let aws_instances_poller = AwsInstances...
identifier_body
main.rs
extern crate prometheus; extern crate hyper; extern crate dotenv; extern crate rusoto; extern crate ctrlc; #[macro_use] extern crate serde_derive; extern crate serde_yaml; extern crate time; extern crate env_logger; mod config; mod poller; mod periodic; mod server; mod termination; mod pagination; mod aws_poller; use...
TerminationGuard::new(); let _ = listening.close(); }
random_line_split
main.rs
extern crate prometheus; extern crate hyper; extern crate dotenv; extern crate rusoto; extern crate ctrlc; #[macro_use] extern crate serde_derive; extern crate serde_yaml; extern crate time; extern crate env_logger; mod config; mod poller; mod periodic; mod server; mod termination; mod pagination; mod aws_poller; use...
() { match dotenv::dotenv() { Ok(_) | Err(dotenv::DotenvError::Io) => // it is ok if the .env file was not found return, Err(dotenv::DotenvError::Parsing {line}) => panic!(".env file parsing failed at {:?}", line), Err(err) => panic!(err) } } fn main() { inje...
inject_environment
identifier_name
test_parse.js
var assert = require('assert') var parse = require('../').parse function addTest(arg, bulk) { function fn_json5()
function fn_strict() { //console.log('testing: ', arg) try { var x = parse(arg, {mode: 'json'}) } catch(err) { x = 'fail' } try { var z = JSON.parse(arg) } catch(err) { z = 'fail' } assert.deepEqual(x, z) } if (typeof(describe) === 'function' && !bulk) { ...
{ //console.log('testing: ', arg) try { var x = parse(arg) } catch(err) { x = 'fail' } try { var z = eval('(function(){"use strict"\nreturn ('+String(arg)+'\n)\n})()') } catch(err) { z = 'fail' } assert.deepEqual(x, z) }
identifier_body
test_parse.js
var assert = require('assert') var parse = require('../').parse function addTest(arg, bulk) { function fn_json5() { //console.log('testing: ', arg) try { var x = parse(arg) } catch(err) {
var z = eval('(function(){"use strict"\nreturn ('+String(arg)+'\n)\n})()') } catch(err) { z = 'fail' } assert.deepEqual(x, z) } function fn_strict() { //console.log('testing: ', arg) try { var x = parse(arg, {mode: 'json'}) } catch(err) { x = 'fail' } try { ...
x = 'fail' } try {
random_line_split
test_parse.js
var assert = require('assert') var parse = require('../').parse function
(arg, bulk) { function fn_json5() { //console.log('testing: ', arg) try { var x = parse(arg) } catch(err) { x = 'fail' } try { var z = eval('(function(){"use strict"\nreturn ('+String(arg)+'\n)\n})()') } catch(err) { z = 'fail' } assert.deepEqual(x, z) } fu...
addTest
identifier_name
test_parse.js
var assert = require('assert') var parse = require('../').parse function addTest(arg, bulk) { function fn_json5() { //console.log('testing: ', arg) try { var x = parse(arg) } catch(err) { x = 'fail' } try { var z = eval('(function(){"use strict"\nreturn ('+String(arg)+'\n)\n})()...
} addTest('"\\uaaaa\\u0000\\uFFFF\\uFaAb"') addTest(' "\\xaa\\x00\xFF\xFa\0\0" ') addTest('"\\\'\\"\\b\\f\\t\\n\\r\\v"') addTest('"\\q\\w\\e\\r\\t\\y\\\\i\\o\\p\\[\\/\\\\"') addTest('"\\\n\\\r\n\\\n"') addTest('\'\\\n\\\r\n\\\n\'') addTest(' null') addTest('true ') addTest('false') addTest(' Infinity ') addTest('+...
{ fn_json5() fn_strict() }
conditional_block
app.ts
/// <reference path='./Scripts/DlhSoft.ProjectData.GanttChart.HTML.Controls.d.ts'/> import GanttChartView = DlhSoft.Controls.GanttChartView; import GanttChartItem = GanttChartView.Item; import PredecessorItem = GanttChartView.PredecessorItem; // Query string syntax: ?theme // Supported themes: Default, Generic-bright...
if (ganttChartView) ganttChartView.refresh(); } // Initialize the component. var ganttChartView = DlhSoft.Controls.GanttChartView.initialize(ganttChartViewElement, items, settings); // Update zoom level settings upon user commands. zoomLevelTextBox.addEventListener('change', updateZoomLevel); zoomLevelTex...
settings.isMouseWheelZoomEnabled = !disableMouseWheelZoomCheckBox.checked;
random_line_split
app.ts
/// <reference path='./Scripts/DlhSoft.ProjectData.GanttChart.HTML.Controls.d.ts'/> import GanttChartView = DlhSoft.Controls.GanttChartView; import GanttChartItem = GanttChartView.Item; import PredecessorItem = GanttChartView.PredecessorItem; // Query string syntax: ?theme // Supported themes: Default, Generic-bright...
// Initialize the component. var ganttChartView = DlhSoft.Controls.GanttChartView.initialize(ganttChartViewElement, items, settings); // Update zoom level settings upon user commands. zoomLevelTextBox.addEventListener('change', updateZoomLevel); zoomLevelTextBox.addEventListener('keyup', updateZoomLevel); disableMouse...
var hourWidth = parseFloat(zoomLevelTextBox.value); if (hourWidth > 0) settings.hourWidth = hourWidth; settings.isMouseWheelZoomEnabled = !disableMouseWheelZoomCheckBox.checked; if (ganttChartView) ganttChartView.refresh(); }
identifier_body
app.ts
/// <reference path='./Scripts/DlhSoft.ProjectData.GanttChart.HTML.Controls.d.ts'/> import GanttChartView = DlhSoft.Controls.GanttChartView; import GanttChartItem = GanttChartView.Item; import PredecessorItem = GanttChartView.PredecessorItem; // Query string syntax: ?theme // Supported themes: Default, Generic-bright...
{ var hourWidth = parseFloat(zoomLevelTextBox.value); if (hourWidth > 0) settings.hourWidth = hourWidth; settings.isMouseWheelZoomEnabled = !disableMouseWheelZoomCheckBox.checked; if (ganttChartView) ganttChartView.refresh(); } // Initialize the component. var ganttChartView = DlhSof...
dateZoomLevel()
identifier_name
fields.py
# -*- coding: UTF-8 -*- #------------------------------------------------------------------------------ # file: fields.py # License: LICENSE.TXT # Author: Ioannis Tziakos # # Copyright (c) 2011, Enthought, Inc. # All rights reserved. #------------------------------------------------------------------------------ i...
n lines class ListItemField(Field): """ Field that in rst is formated as an item in the list ignoring any field.type information. """ def to_rst(self, indent=4, prefix=''): """ Outputs field in rst using as items in an list. Arguments --------- indent : int ...
ype_str) retur
conditional_block