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
color.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Color", inherited=True) %> <% fr...
let s = match *self { % for color in system_colors + extra_colors: LookAndFeel_ColorID::eColorID_${to_rust_ident(color)} => "${color}", % endfor LookAndFeel_ColorID::eColorID_LAST_COLOR => unreachable!(), }; dest.wri...
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, {
random_line_split
loader.js
/** * @file loader.js */ import Component from '../component.js'; import Tech from './tech.js'; import window from 'global/window'; import toTitleCase from '../utils/to-title-case.js'; /** * The Media Loader is the component that decides which playback technology to load * when the player is initialized. * * @pa...
(player, options, ready){ super(player, options, ready); // If there are no sources when the player is initialized, // load the first supported playback technology. if (!options.playerOptions['sources'] || options.playerOptions['sources'].length === 0) { for (let i=0, j=options.playerOptions['te...
constructor
identifier_name
loader.js
/** * @file loader.js */ import Component from '../component.js'; import Tech from './tech.js'; import window from 'global/window'; import toTitleCase from '../utils/to-title-case.js'; /** * The Media Loader is the component that decides which playback technology to load * when the player is initialized. * * @pa...
} } Component.registerComponent('MediaLoader', MediaLoader); export default MediaLoader;
{ // // Loop through playback technologies (HTML5, Flash) and check for support. // // Then load the best source. // // A few assumptions here: // // All playback technologies respect preload false. player.src(options.playerOptions['sources']); }
conditional_block
loader.js
/** * @file loader.js */ import Component from '../component.js'; import Tech from './tech.js'; import window from 'global/window'; import toTitleCase from '../utils/to-title-case.js'; /** * The Media Loader is the component that decides which playback technology to load * when the player is initialized. * * @pa...
} } } else { // // Loop through playback technologies (HTML5, Flash) and check for support. // // Then load the best source. // // A few assumptions here: // // All playback technologies respect preload false. player.src(options.playerOptions['sources']); } } } ...
{ super(player, options, ready); // If there are no sources when the player is initialized, // load the first supported playback technology. if (!options.playerOptions['sources'] || options.playerOptions['sources'].length === 0) { for (let i=0, j=options.playerOptions['techOrder']; i<j.length; i...
identifier_body
loader.js
/** * @file loader.js */ import Component from '../component.js'; import Tech from './tech.js'; import window from 'global/window';
* when the player is initialized. * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class MediaLoader */ class MediaLoader extends Component { constructor(player, options, ready){ ...
import toTitleCase from '../utils/to-title-case.js'; /** * The Media Loader is the component that decides which playback technology to load
random_line_split
base.py
from __future__ import absolute_import, unicode_literals from django.db.models.lookups import Lookup from django.db.models.query import QuerySet from django.db.models.sql.where import SubqueryConstraint, WhereNode from django.utils.six import text_type class FilterError(Exception): pass
class BaseSearchQuery(object): DEFAULT_OPERATOR = 'or' def __init__(self, queryset, query_string, fields=None, operator=None, order_by_relevance=True): self.queryset = queryset self.query_string = query_string self.fields = fields self.operator = operator or self.DEFAULT_OPERAT...
class FieldError(Exception): pass
random_line_split
base.py
from __future__ import absolute_import, unicode_literals from django.db.models.lookups import Lookup from django.db.models.query import QuerySet from django.db.models.sql.where import SubqueryConstraint, WhereNode from django.utils.six import text_type class FilterError(Exception): pass class FieldError(Excep...
if field_name not in allowed_fields: raise FieldError( 'Cannot search with field "' + field_name + '". Please add index.SearchField(\'' + field_name + '\') to ' + model.__name__ + '.search_fields.' ) # Apply...
if isinstance(model_or_queryset, QuerySet): model = model_or_queryset.model queryset = model_or_queryset else: model = model_or_queryset queryset = model_or_queryset.objects.all() # # Model must be a class that is in the index # if not class_is_in...
identifier_body
base.py
from __future__ import absolute_import, unicode_literals from django.db.models.lookups import Lookup from django.db.models.query import QuerySet from django.db.models.sql.where import SubqueryConstraint, WhereNode from django.utils.six import text_type class FilterError(Exception): pass class FieldError(Excep...
if start is not None: if self.stop is not None: self.start = min(self.stop, self.start + start) else: self.start = self.start + start def _clone(self): klass = self.__class__ new = klass(self.backend, self.query, prefetch_related=sel...
self.stop = self.start + stop
conditional_block
base.py
from __future__ import absolute_import, unicode_literals from django.db.models.lookups import Lookup from django.db.models.query import QuerySet from django.db.models.sql.where import SubqueryConstraint, WhereNode from django.utils.six import text_type class FilterError(Exception): pass class FieldError(Excep...
(self, filters, connector, negated): raise NotImplementedError def _process_filter(self, field_attname, lookup, value): # Get the field field = self._get_filterable_field(field_attname) if field is None: raise FieldError( 'Cannot filter search results wi...
_connect_filters
identifier_name
cache.rs
use crate::error::CkError; use serde_json::Value; use std::collections::HashMap; use std::io; use std::path::{Path, PathBuf}; use fs_err as fs; #[derive(Debug)] pub struct Cache { root: PathBuf, files: HashMap<PathBuf, String>, values: HashMap<PathBuf, Value>, pub variables: HashMap<String, Value>, ...
} fn read_file(&mut self, path: PathBuf) -> Result<String, io::Error> { if let Some(f) = self.files.get(&path) { return Ok(f.clone()); } let file = fs::read_to_string(&path)?; self.files.insert(path, file.clone()); Ok(file) } /// Get the text fro...
{ self.last_path .as_ref() // FIXME: Point to a line number .expect("No last path set. Make sure to specify a full path before using `-`") .clone() }
conditional_block
cache.rs
use crate::error::CkError; use serde_json::Value; use std::collections::HashMap; use std::io; use std::path::{Path, PathBuf}; use fs_err as fs; #[derive(Debug)] pub struct Cache { root: PathBuf, files: HashMap<PathBuf, String>, values: HashMap<PathBuf, Value>, pub variables: HashMap<String, Value>, ...
/// Parse the JSON from a file. If called multiple times, the file will only be read once. pub fn get_value(&mut self, path: &String) -> Result<Value, CkError> { let path = self.resolve_path(path); if let Some(v) = self.values.get(&path) { return Ok(v.clone()); } ...
{ let path = self.resolve_path(path); self.read_file(path) }
identifier_body
cache.rs
use crate::error::CkError; use serde_json::Value; use std::collections::HashMap; use std::io; use std::path::{Path, PathBuf}; use fs_err as fs; #[derive(Debug)] pub struct Cache { root: PathBuf, files: HashMap<PathBuf, String>, values: HashMap<PathBuf, Value>, pub variables: HashMap<String, Value>, ...
.clone() } } fn read_file(&mut self, path: PathBuf) -> Result<String, io::Error> { if let Some(f) = self.files.get(&path) { return Ok(f.clone()); } let file = fs::read_to_string(&path)?; self.files.insert(path, file.clone()); Ok(fil...
.as_ref() // FIXME: Point to a line number .expect("No last path set. Make sure to specify a full path before using `-`")
random_line_split
cache.rs
use crate::error::CkError; use serde_json::Value; use std::collections::HashMap; use std::io; use std::path::{Path, PathBuf}; use fs_err as fs; #[derive(Debug)] pub struct Cache { root: PathBuf, files: HashMap<PathBuf, String>, values: HashMap<PathBuf, Value>, pub variables: HashMap<String, Value>, ...
(&mut self, path: PathBuf) -> Result<String, io::Error> { if let Some(f) = self.files.get(&path) { return Ok(f.clone()); } let file = fs::read_to_string(&path)?; self.files.insert(path, file.clone()); Ok(file) } /// Get the text from a file. If called mult...
read_file
identifier_name
crane.js
var THREE = require('three'); var ScapeStuff = require('../stuff'); var M4 = THREE.Matrix4; var ScapeCameraAddon = require('./addons/camera'); // ------------------------------------------------------------------ /** * Returns a mesh array for a tower crane. * @param {Object} options used to specify properties of...
// return all the crane bits. return crane; }; // ------------------------------------------------------------------ module.exports = ScapeCraneFactory;
{ crane = ScapeCameraAddon(crane, options, i); }
conditional_block
crane.js
var THREE = require('three'); var ScapeStuff = require('../stuff'); var M4 = THREE.Matrix4; var ScapeCameraAddon = require('./addons/camera'); // ------------------------------------------------------------------ /** * Returns a mesh array for a tower crane. * @param {Object} options used to specify properties of...
i.baseH = i.towerWidth * 2; // half of the height will be "underground" i.poleR = i.towerWidth / 10; i.ringR = ((i.towerWidth / 2) * Math.SQRT2) + 1.3 * i.poleR; i.ringH = i.towerWidth / 5; i.boomL = i.length; // length of crane boom i.cwbL = i.counterweightLength; // length of counterweight boom i.rodL = i.b...
{ var crane = { meshes: [], clickPoints: [] }; var i = { meshNames: [] }; i.towerWidth = options.width || 2; i.height = options.height || 50; i.length = options.length || 40; i.counterweightLength = options.counterweightLength || (i.length / 4); i.strutStuff = options.struts || ScapeStuff.glossBlack; i.baseS...
identifier_body
crane.js
var THREE = require('three'); var ScapeStuff = require('../stuff'); var M4 = THREE.Matrix4; var ScapeCameraAddon = require('./addons/camera'); // ------------------------------------------------------------------ /** * Returns a mesh array for a tower crane. * @param {Object} options used to specify properties of ...
// bottom left rod leftRodGeom.applyMatrix(new M4().makeTranslation(-0.5 * i.towerWidth + i.poleR, 0, -0.5 * i.towerWidth)); leftRodGeom.applyMatrix(rotate); i.meshNames.push('rodLeft'); crane.meshes.push(new THREE.Mesh(leftRodGeom, i.strutStuff)); // bottom right rod rightRodGeom.applyMatrix(new M4().makeTran...
topRodGeom.applyMatrix(rotate); i.meshNames.push('rodTop'); crane.meshes.push(new THREE.Mesh(topRodGeom, i.strutStuff));
random_line_split
crane.js
var THREE = require('three'); var ScapeStuff = require('../stuff'); var M4 = THREE.Matrix4; var ScapeCameraAddon = require('./addons/camera'); // ------------------------------------------------------------------ /** * Returns a mesh array for a tower crane. * @param {Object} options used to specify properties of...
(options) { var crane = { meshes: [], clickPoints: [] }; var i = { meshNames: [] }; i.towerWidth = options.width || 2; i.height = options.height || 50; i.length = options.length || 40; i.counterweightLength = options.counterweightLength || (i.length / 4); i.strutStuff = options.struts || ScapeStuff.glossBlack...
ScapeCraneFactory
identifier_name
tokenize.py
r"~") Bracket = '[][(){}]' Special = group(r'\r?\n', r'[:;.,`@]') Funny = group(Operator, Bracket, Special) PlainToken = group(Number, Funny, String, Name) Token = Ignore + PlainToken # First (or only) line of ' or " string. ContStr = group(r"[uUbB]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" + group("'", r'\...
if codec.name != 'utf-8': # This behaviour mimics the Python interpreter raise SyntaxError('encoding problem: utf-8') encoding += '-sig'
conditional_block
tokenize.py
r'[uU]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"') # Because of leftmost-then-longest match semantics, be sure to put the # longest operators first (e.g., if = came before ==, == would get # recognized as two instances of =). Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=", r"//=?", ...
def untokenize(self, iterable): for t in iterable: if len(t) == 2: self.compat(t, iterable) break tok_type, token, start, end, line = t self.add_whitespace(start) self.tokens.append(token) self.prev_row, self.prev_...
row, col = start assert row <= self.prev_row col_offset = col - self.prev_col if col_offset: self.tokens.append(" " * col_offset)
identifier_body
tokenize.py
r'[uU]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"') # Because of leftmost-then-longest match semantics, be sure to put the # longest operators first (e.g., if = came before ==, == would get # recognized as two instances of =). Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=", r"//=?", ...
(Exception): pass class StopTokenizing(Exception): pass def printtoken(type, token, xxx_todo_changeme, xxx_todo_changeme1, line): # for testing (srow, scol) = xxx_todo_changeme (erow, ecol) = xxx_todo_changeme1 print("%d,%d-%d,%d:\t%s\t%s" % \ (srow, scol, erow, ecol, tok_name[type], repr(token)))...
TokenError
identifier_name
tokenize.py
get_normal_name(orig_enc): """Imitates get_normal_name in tokenizer.c.""" # Only care about the first 12 characters. enc = orig_enc[:12].lower().replace("_", "-") if enc == "utf-8" or enc.startswith("utf-8-"): return "utf-8" if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \ enc....
random_line_split
index.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Logger; var _lodash = require('lodash'); var _moment = require('moment'); var _moment2 = _interopRequireDefault(_moment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } ...
Logger.prototype.trace = createLogLevel(logLevels.TRACE); Logger.prototype.info = createLogLevel(logLevels.INFO); Logger.prototype.warn = createLogLevel(logLevels.WARN); Logger.prototype.error = createLogLevel(logLevels.ERROR); Logger.prototype.log = function log(level) { for (var _len3 = arguments.length, args...
{ return function logWithLevel() { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } if (this.requestId) { _log.apply(undefined, [this.category, level, 'RequestId: ' + this.requestId].concat(args)); } _log.ap...
identifier_body
index.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Logger; var _lodash = require('lodash'); var _moment = require('moment'); var _moment2 = _interopRequireDefault(_moment); function
(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var logLevels = { TRACE: 'TRACE', INFO: 'INFO', WARN: 'WARN', ERROR: 'ERROR' }; function _log(category, level) { var _console2; var now = (0, _moment2.default)().format(); for (var _len = arguments.length, args = Array(_len > 2 ? _len - ...
_interopRequireDefault
identifier_name
index.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Logger; var _lodash = require('lodash'); var _moment = require('moment'); var _moment2 = _interopRequireDefault(_moment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } ...
return (_console2 = console).log.apply(_console2, [now + ' ' + level + ' [' + category + ']'].concat(args)); // eslint-disable-line no-console } function Logger(category, requestId) { this.category = category; this.requestId = requestId; } function createLogLevel(level) { return function logWithLevel() { ...
{ var _console; return (_console = console).error.apply(_console, [now + ' ' + level + ' [' + category + ']'].concat(args)); // eslint-disable-line no-console }
conditional_block
index.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Logger; var _lodash = require('lodash'); var _moment = require('moment'); var _moment2 = _interopRequireDefault(_moment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } ...
return (_console = console).error.apply(_console, [now + ' ' + level + ' [' + category + ']'].concat(args)); // eslint-disable-line no-console } return (_console2 = console).log.apply(_console2, [now + ' ' + level + ' [' + category + ']'].concat(args)); // eslint-disable-line no-console } function Logger(cate...
} if (level === logLevels.ERROR) { var _console;
random_line_split
nav.py
# Copyright (C) 2011, Endre Karlson # All rights reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This pro...
implements(IDetailNav) # Location + action location = 'detailnav_router' action = 'DetailNavRouter' def getDetailNavConfigs(self, uid=None, menuIds=None): args = myArgs()[0] return self._request(args, **kw) def getContextMenus(self, uid): args = myArgs()[0] return ...
identifier_body
nav.py
# Copyright (C) 2011, Endre Karlson # All rights reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This pro...
(self, uid): args = myArgs()[0] return self._request(args, **kw) def getSecurityPermissions(self, uid): args = myArgs()[0] return self._request(args, **kw)
getContextMenus
identifier_name
nav.py
# Copyright (C) 2011, Endre Karlson # All rights reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This pro...
""" DetailNav router for the Zenoss JSON API """ from zope.interface import implements from zenoss_api.interfaces import IDetailNav from zenoss_api.router import RouterBase from zenoss_api.utils import myArgs info = {"name": "nav", "author": "Endre Karlson endre.karlson@gmail.com", "version": "0.1", "cla...
random_line_split
index.tsx
import React from 'react'; import { useSelector } from 'react-redux'; import Icon from '../../../../icons'; import { AppState } from '../../../../reducers';
const useStyles = require('isomorphic-style-loader/useStyles'); const s = require('./importResultShow.scss'); const ImportResultShow: React.FC = () => { useStyles(s); const { successCount, pendingCount } = useSelector((state: AppState) => ({ successCount: state.importPaperDialogState.successCount, pendin...
random_line_split
trie_node.rs
use {TrieNode, KeyValue, NibbleVec, BRANCH_FACTOR}; use keys::*; macro_rules! no_children { () => ([ None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None ]) } impl<K, V> TrieNode<K, V> where K: TrieKey { /// Create a value-less,...
} (true, sub_tree_size) } }
{ match child.check_integrity_recursive(&trie_key) { (false, _) => return (false, sub_tree_size), (true, child_size) => sub_tree_size += child_size, } }
conditional_block
trie_node.rs
use {TrieNode, KeyValue, NibbleVec, BRANCH_FACTOR}; use keys::*; macro_rules! no_children { () => ([ None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None ]) } impl<K, V> TrieNode<K, V> where K: TrieKey { /// Create a value-less,...
() -> TrieNode<K, V> { TrieNode { key: NibbleVec::new(), key_value: None, children: no_children![], child_count: 0, } } /// Create a TrieNode with no children. pub fn with_key_value(key_fragments: NibbleVec, key: K, value: V) -> TrieNode<K, V>...
new
identifier_name
trie_node.rs
use {TrieNode, KeyValue, NibbleVec, BRANCH_FACTOR}; use keys::*; macro_rules! no_children { () => ([ None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None ]) } impl<K, V> TrieNode<K, V> where K: TrieKey { /// Create a value-less,...
/// Compute the number of keys and values in this node's subtrie. pub fn compute_size(&self) -> usize { let mut size = if self.key_value.is_some() { 1 } else { 0 }; for child in &self.children { if let &Some(ref child) = child { // TODO: could unroll this recursion ...
}) }
random_line_split
trie_node.rs
use {TrieNode, KeyValue, NibbleVec, BRANCH_FACTOR}; use keys::*; macro_rules! no_children { () => ([ None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None ]) } impl<K, V> TrieNode<K, V> where K: TrieKey { /// Create a value-less,...
/// Get a mutable value whilst checking a key match. pub fn value_checked_mut(&mut self, key: &K) -> Option<&mut V> { self.key_value.as_mut().map(|kv| { check_keys(&kv.key, key); &mut kv.value }) } /// Compute the number of keys and values in this node's subtri...
{ self.key_value.as_ref().map(|kv| { check_keys(&kv.key, key); &kv.value }) }
identifier_body
table.rs
Idx; use rustc_serialize::opaque::Encoder; use rustc_serialize::Encoder as _; use std::convert::TryInto; use std::marker::PhantomData; use std::num::NonZeroUsize; use tracing::debug; /// Helper trait, for encoding to, and decoding from, a fixed number of bytes. /// Used mainly for Lazy positions and lengths. /// Unche...
fn write_to_bytes(self, b: &mut [u8]) { self.map(|lazy| Lazy::<T>::from_position(lazy.position)).write_to_bytes(b); let len = self.map_or(0, |lazy| lazy.meta); let len: u32 = len.try_into().unwrap(); len.write_to_bytes(&mut b[u32::BYTE_LEN..]); } } /// Random-access table (i...
{ Some(Lazy::from_position_and_meta( <Option<Lazy<T>>>::from_bytes(b)?.position, u32::from_bytes(&b[u32::BYTE_LEN..]) as usize, )) }
identifier_body
table.rs
Idx; use rustc_serialize::opaque::Encoder; use rustc_serialize::Encoder as _; use std::convert::TryInto; use std::marker::PhantomData; use std::num::NonZeroUsize; use tracing::debug; /// Helper trait, for encoding to, and decoding from, a fixed number of bytes. /// Used mainly for Lazy positions and lengths. /// Unche...
(b: &[u8]) -> Self { Some(Lazy::from_position(NonZeroUsize::new(u32::from_bytes(b) as usize)?)) } fn write_to_bytes(self, b: &mut [u8]) { let position = self.map_or(0, |lazy| lazy.position.get()); let position: u32 = position.try_into().unwrap(); position.write_to_bytes(b) ...
from_bytes
identifier_name
table.rs
Idx; use rustc_serialize::opaque::Encoder; use rustc_serialize::Encoder as _; use std::convert::TryInto; use std::marker::PhantomData; use std::num::NonZeroUsize; use tracing::debug; /// Helper trait, for encoding to, and decoding from, a fixed number of bytes. /// Used mainly for Lazy positions and lengths. /// Unche...
Some(value).write_to_bytes_at(&mut self.bytes, i); } pub(crate) fn encode(&self, buf: &mut Encoder) -> Lazy<Table<I, T>> { let pos = buf.position(); buf.emit_raw_bytes(&self.bytes).unwrap(); Lazy::from_position_and_meta(NonZeroUsize::new(pos as usize).unwrap(), self.bytes.len(...
{ self.bytes.resize(needed, 0); }
conditional_block
table.rs
Idx; use rustc_serialize::opaque::Encoder; use rustc_serialize::Encoder as _; use std::convert::TryInto; use std::marker::PhantomData; use std::num::NonZeroUsize; use tracing::debug; /// Helper trait, for encoding to, and decoding from, a fixed number of bytes. /// Used mainly for Lazy positions and lengths. /// Unche...
// HACK(eddyb) this shouldn't be needed (see comments on the methods above). macro_rules! fixed_size_encoding_byte_len_and_defaults { ($byte_len:expr) => { const BYTE_LEN: usize = $byte_len; fn maybe_read_from_bytes_at(b: &[u8], i: usize) -> Option<Self> { const BYTE_LEN: usize = $byte_...
/// at `&mut b[i * Self::BYTE_LEN..]`, using `Self::write_to_bytes`. fn write_to_bytes_at(self, b: &mut [u8], i: usize); }
random_line_split
index.js
/* * * apiView * */ import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import { FormattedMessage } from 'react-intl' import { connect } from 'react-redux' import ReadMargin from 'components/ReadMargin' import View from 'components/View' import P from 'components/P' import messages from...
} WorldView.propTypes = { theme: PropTypes.string.isRequired } const mapStateToProps = (state) => ({ theme: state.get('theme') }) export default connect(mapStateToProps)(WorldView)
{ return ( <div> <View left={true}> <ReadMargin> <P><FormattedMessage {...messages.arasaacInWorld} /></P> </ReadMargin> </View> <iframe src="https://www.google.com/maps/d/u/0/embed?mid=1EBR3psLxK-G_WujU93NMWkfisTYK4HwY" width="100%" height="800"></ifram...
identifier_body
index.js
/* * * apiView * */ import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import { FormattedMessage } from 'react-intl' import { connect } from 'react-redux' import ReadMargin from 'components/ReadMargin' import View from 'components/View' import P from 'components/P' import messages from...
extends PureComponent { componentDidMount() { } render() { return ( <div> <View left={true}> <ReadMargin> <P><FormattedMessage {...messages.arasaacInWorld} /></P> </ReadMargin> </View> <iframe src="https://www.google.com/maps/d/u/0/embed?mid=1E...
WorldView
identifier_name
index.js
/* * * apiView * */ import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import { FormattedMessage } from 'react-intl' import { connect } from 'react-redux' import ReadMargin from 'components/ReadMargin' import View from 'components/View' import P from 'components/P' import messages from...
<P><FormattedMessage {...messages.arasaacInWorld} /></P> </ReadMargin> </View> <iframe src="https://www.google.com/maps/d/u/0/embed?mid=1EBR3psLxK-G_WujU93NMWkfisTYK4HwY" width="100%" height="800"></iframe> </div> ) } } WorldView.propTypes = { theme: PropTypes.strin...
<ReadMargin>
random_line_split
X11_MenuDialog.py
import sys,os,string def GFX_MenuDialog(filename,*items): file=open(filename,'w') file.writelines(map(lambda x:x+"\n", items)) file.close() os.system("python X11_MenuDialog.py "+filename); if __name__=="__main__": import qt,string class WidgetView ( qt.QWidget ): def
( self, *args ): apply( qt.QWidget.__init__, (self,) + args ) self.topLayout = qt.QVBoxLayout( self, 10 ) self.grid = qt.QGridLayout( 0, 0 ) self.topLayout.addLayout( self.grid, 10 ) # Create a list box self.lb = qt.QListBox( self, "listBox" ) file=open(sys.argv[1],'r') ...
__init__
identifier_name
X11_MenuDialog.py
import sys,os,string def GFX_MenuDialog(filename,*items): file=open(filename,'w') file.writelines(map(lambda x:x+"\n", items)) file.close() os.system("python X11_MenuDialog.py "+filename); if __name__=="__main__": import qt,string class WidgetView ( qt.QWidget ): def __init__( self, *arg...
self.topLayout.activate() def listBoxItemSelected( self, index ): txt = qt.QString() txt = "List box item %d selected" % index print txt file=open(sys.argv[1],'w') file.write(self.dasitems[index]) file.close(); a.quit() a = qt.QApplication( s...
apply( qt.QWidget.__init__, (self,) + args ) self.topLayout = qt.QVBoxLayout( self, 10 ) self.grid = qt.QGridLayout( 0, 0 ) self.topLayout.addLayout( self.grid, 10 ) # Create a list box self.lb = qt.QListBox( self, "listBox" ) file=open(sys.argv[1],'r') self.dasitems=map(lam...
identifier_body
X11_MenuDialog.py
import sys,os,string def GFX_MenuDialog(filename,*items): file=open(filename,'w') file.writelines(map(lambda x:x+"\n", items)) file.close() os.system("python X11_MenuDialog.py "+filename); if __name__=="__main__": import qt,string class WidgetView ( qt.QWidget ): def __init__( self, *arg...
self.grid.addMultiCellWidget( self.lb, 0, 0, 0, 0 ) self.connect( self.lb, qt.SIGNAL("selected(int)"), self.listBoxItemSelected ) self.topLayout.activate() def listBoxItemSelected( self, index ): txt = qt.QString() txt = "List box item %d selected" % index print t...
self.lb.insertItem(item)
conditional_block
X11_MenuDialog.py
import sys,os,string def GFX_MenuDialog(filename,*items): file=open(filename,'w') file.writelines(map(lambda x:x+"\n", items)) file.close() os.system("python X11_MenuDialog.py "+filename); if __name__=="__main__": import qt,string class WidgetView ( qt.QWidget ): def __init__( self, *args...
file.close() self.setCaption(self.dasitems.pop(0)) for item in self.dasitems: self.lb.insertItem(item) self.grid.addMultiCellWidget( self.lb, 0, 0, 0, 0 ) self.connect( self.lb, qt.SIGNAL("selected(int)"), self.listBoxItemSelected ) self.topLayout.activate() ...
self.lb = qt.QListBox( self, "listBox" ) file=open(sys.argv[1],'r') self.dasitems=map(lambda x:string.rstrip(x),file.readlines())
random_line_split
zhttpto.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #[feature(globs)]; use std::i...
() { let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap(); let mut acceptor = net::tcp::TcpListener::bind(addr).listen(); println(format!("Listening on [{:s}] ...", addr.to_str())); for stream in acceptor.incoming() { // Spawn a task to handle the connection ...
main
identifier_name
zhttpto.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #[feature(globs)]; use std::i...
else { println!("Error reading file. Recieved request :\n{:s}", request_str); let fr = ~"HTTP/1.1 418 I'M A TEAPOT\r\nContent-Type: text/html; charset=UTF-8\r\n\r\nI'm a teapot"; stream.write(fr.as_bytes()); println!("End o...
{ println!("File requested: {:s}", path_str); let mut file = buffered::BufferedReader::new(File::open(&cwdpath)); let fl_arr: ~[~str] = file.lines().collect(); let mut fr = ~"HTTP/1.1 200 OK\r\nContent-Type: text/html; ...
conditional_block
zhttpto.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #[feature(globs)]; use std::i...
let mut buf = [0, ..500]; stream.read(buf); let request_str = str::from_utf8(buf); let split_str: ~[&str] = request_str.split(' ').collect(); let path = os::getcwd(); let mut path_str: ~str; if split_str[0] == "GET" && spli...
{ let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap(); let mut acceptor = net::tcp::TcpListener::bind(addr).listen(); println(format!("Listening on [{:s}] ...", addr.to_str())); for stream in acceptor.incoming() { // Spawn a task to handle the connection ...
identifier_body
zhttpto.rs
// // zhttpto.rs // // Starting code for PS1 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.3 #[feature(globs)]; use std::i...
} }, None => () } let mut buf = [0, ..500]; stream.read(buf); let request_str = str::from_utf8(buf); let split_str: ~[&str] = request_str.split(' ').collect(); ...
match s.peer_name() { Some(pn) => {println(format!("Received connection from: [{:s}]", pn.to_str()));}, None => ()
random_line_split
snippet_parser.rs
use std::error::Error; use structs::*; use filesystem::read_file_to_json; use std::fs::read_dir; use filesystem::read_file_to_string; use std::fs::DirEntry; pub fn get_all_snippets() -> Result<Vec<Snippet>, Box<Error>> { let mut all_snippets = Vec::new(); let snippets_path = "./snippets/"; let snippets_dir...
.map(|x| x.as_str().expect("failed to parse crates").to_string()) .collect(), tags: info["tags"] .as_array() .expect("failed to parse tags") .into_iter() .map(|x| x.as_str().expect("failed to parse tags").to_string()) .collect()...
{ let uw = snippet_folder; let folder_relative_path = uw.path().display().to_string(); let folder_name = uw.file_name() .to_str() .expect("failed to get snippet folder name") .to_string(); let info_path = format!("{}/info.json", folder_relative_path); let content_path = forma...
identifier_body
snippet_parser.rs
use std::error::Error; use structs::*; use filesystem::read_file_to_json; use std::fs::read_dir; use filesystem::read_file_to_string; use std::fs::DirEntry; pub fn
() -> Result<Vec<Snippet>, Box<Error>> { let mut all_snippets = Vec::new(); let snippets_path = "./snippets/"; let snippets_dirs = read_dir(snippets_path).unwrap(); for snippet_folder in snippets_dirs { let uw = snippet_folder?; if uw.file_type().expect("failed to get folder type").is_di...
get_all_snippets
identifier_name
snippet_parser.rs
use std::error::Error; use structs::*; use filesystem::read_file_to_json; use std::fs::read_dir; use filesystem::read_file_to_string; use std::fs::DirEntry; pub fn get_all_snippets() -> Result<Vec<Snippet>, Box<Error>> { let mut all_snippets = Vec::new(); let snippets_path = "./snippets/"; let snippets_dir...
.to_str() .expect("failed to get snippet folder name") .to_string(); let info_path = format!("{}/info.json", folder_relative_path); let content_path = format!("{}/content.md", folder_relative_path); let info = read_file_to_json(&info_path); let content = read_file_to_string(&cont...
let folder_relative_path = uw.path().display().to_string(); let folder_name = uw.file_name()
random_line_split
snippet_parser.rs
use std::error::Error; use structs::*; use filesystem::read_file_to_json; use std::fs::read_dir; use filesystem::read_file_to_string; use std::fs::DirEntry; pub fn get_all_snippets() -> Result<Vec<Snippet>, Box<Error>> { let mut all_snippets = Vec::new(); let snippets_path = "./snippets/"; let snippets_dir...
} Ok(all_snippets) } fn parse_snippet(snippet_folder: &DirEntry) -> Snippet { let uw = snippet_folder; let folder_relative_path = uw.path().display().to_string(); let folder_name = uw.file_name() .to_str() .expect("failed to get snippet folder name") .to_string(); let i...
{ let snippet = parse_snippet(&uw); all_snippets.push(snippet); }
conditional_block
plugin.js
/** * @license Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Spell checker. */ // Register a plugin named "wsc". CKEDITOR.plugins.add( 'wsc', { requires: 'dialog', lang: 'af,ar,bg,bn,bs,ca,cs,...
CKEDITOR.dialog.add( commandName, this.path + 'dialogs/wsc.js' ); } }); CKEDITOR.config.wsc_customerId = CKEDITOR.config.wsc_customerId || '1:ua3xw1-2XyGJ3-GWruD3-6OFNT1-oXcuB1-nR6Bp4-hgQHc-EcYng3-sdRXG3-NOfFk'; CKEDITOR.config.wsc_customLoaderScript = CKEDITOR.config.wsc_customLoaderScript || null;
editor.ui.addButton && editor.ui.addButton( 'SpellChecker', { label: editor.lang.wsc.toolbar, command: commandName, toolbar: 'spellchecker,10' }); }
conditional_block
plugin.js
/** * @license Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Spell checker. */ // Register a plugin named "wsc". CKEDITOR.plugins.add( 'wsc', { requires: 'dialog', lang: 'af,ar,bg,bn,bs,ca,cs,...
}); } CKEDITOR.dialog.add( commandName, this.path + 'dialogs/wsc.js' ); } }); CKEDITOR.config.wsc_customerId = CKEDITOR.config.wsc_customerId || '1:ua3xw1-2XyGJ3-GWruD3-6OFNT1-oXcuB1-nR6Bp4-hgQHc-EcYng3-sdRXG3-NOfFk'; CKEDITOR.config.wsc_customLoaderScript = CKEDITOR.config.wsc_customLoaderScript || null;
label: editor.lang.wsc.toolbar, command: commandName, toolbar: 'spellchecker,10'
random_line_split
twitter.py
# coding: utf-8 from __future__ import absolute_import import flask import auth import config import model import util from main import app twitter_config = dict( access_token_url='https://api.twitter.com/oauth/access_token', authorize_url='https://api.twitter.com/oauth/authorize', base_url='https://api.twit...
request_token_url='https://api.twitter.com/oauth/request_token', ) twitter = auth.create_oauth_app(twitter_config, 'twitter') @app.route('/api/auth/callback/twitter/') def twitter_authorized(): response = twitter.authorized_response() if response is None: flask.flash('You denied the request to sign in.') ...
consumer_key=config.CONFIG_DB.twitter_consumer_key, consumer_secret=config.CONFIG_DB.twitter_consumer_secret,
random_line_split
twitter.py
# coding: utf-8 from __future__ import absolute_import import flask import auth import config import model import util from main import app twitter_config = dict( access_token_url='https://api.twitter.com/oauth/access_token', authorize_url='https://api.twitter.com/oauth/authorize', base_url='https://api.twit...
auth_id = 'twitter_%s' % response['user_id'] user_db = model.User.get_by('auth_ids', auth_id) return user_db or auth.create_user_db( auth_id=auth_id, name=response['screen_name'], username=response['screen_name'], )
identifier_body
twitter.py
# coding: utf-8 from __future__ import absolute_import import flask import auth import config import model import util from main import app twitter_config = dict( access_token_url='https://api.twitter.com/oauth/access_token', authorize_url='https://api.twitter.com/oauth/authorize', base_url='https://api.twit...
(): return auth.signin_oauth(twitter) def retrieve_user_from_twitter(response): auth_id = 'twitter_%s' % response['user_id'] user_db = model.User.get_by('auth_ids', auth_id) return user_db or auth.create_user_db( auth_id=auth_id, name=response['screen_name'], username=response['screen_name'], )
signin_twitter
identifier_name
twitter.py
# coding: utf-8 from __future__ import absolute_import import flask import auth import config import model import util from main import app twitter_config = dict( access_token_url='https://api.twitter.com/oauth/access_token', authorize_url='https://api.twitter.com/oauth/authorize', base_url='https://api.twit...
flask.session['oauth_token'] = ( response['oauth_token'], response['oauth_token_secret'], ) user_db = retrieve_user_from_twitter(response) return auth.signin_user_db(user_db) @twitter.tokengetter def get_twitter_token(): return flask.session.get('oauth_token') @app.route('/signin/twitter/') def ...
flask.flash('You denied the request to sign in.') return flask.redirect(util.get_next_url())
conditional_block
hidden-line.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 ...
/// /// ```rust /// mod to_make_deriving_work { // FIXME #4913 /// /// # #[derive(PartialEq)] // invisible /// # struct Foo; // invisible /// /// #[derive(PartialEq)] // Bar /// struct Bar(Foo); /// /// fn test() { /// let x = Bar(Foo); /// assert_eq!(x, x); // check that the derivings worked /// } /// /// } //...
/// The '# ' lines should be removed from the output, but the #[derive] should be /// retained.
random_line_split
hidden-line.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 ...
() {} // @!has hidden_line/fn.foo.html invisible // @matches - //pre "#\[derive\(PartialEq\)\] // Bar"
foo
identifier_name
hidden-line.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 ...
// @!has hidden_line/fn.foo.html invisible // @matches - //pre "#\[derive\(PartialEq\)\] // Bar"
{}
identifier_body
filehandler.rs
/* * The module filehandler consists of funtions to write * a string to a file and to read a file into a string */ use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::path::Path; use std::fs; /* * Reads a file with name @filename into * the referenced mutable String @content */ pub fn read_f...
(filename:String, content:String) { let path = Path::new(&filename); let parent = path.parent().unwrap(); match fs::create_dir_all(parent) { Ok(m) => m, Err(e) => panic!(e), // Parent-Folder could not be created }; let f = File::create(&filename); let mut file = match f { Ok(file) => file, ...
write_file
identifier_name
filehandler.rs
/* * The module filehandler consists of funtions to write * a string to a file and to read a file into a string */ use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::path::Path; use std::fs; /* * Reads a file with name @filename into * the referenced mutable String @content */ pub fn read_f...
{ let path = Path::new(&filename); let parent = path.parent().unwrap(); match fs::create_dir_all(parent) { Ok(m) => m, Err(e) => panic!(e), // Parent-Folder could not be created }; let f = File::create(&filename); let mut file = match f { Ok(file) => file, Err(m) => panic!("Datei kann nic...
identifier_body
filehandler.rs
/* * The module filehandler consists of funtions to write * a string to a file and to read a file into a string */ use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::path::Path; use std::fs; /* * Reads a file with name @filename into * the referenced mutable String @content */ pub fn read_f...
/* * Writes the String @content into a file * with the name @filename. It overwrites its * former content. */ pub fn write_file(filename:String, content:String) { let path = Path::new(&filename); let parent = path.parent().unwrap(); match fs::create_dir_all(parent) { Ok(m) => m, Err(e) => panic!(e), // ...
} content.push_str(&tmpcontent); }
random_line_split
comet-tower.component.ts
import { Component, ChangeDetectionStrategy, ChangeDetectorRef, OnInit, OnDestroy } from '@angular/core' import { Observable } from 'rxjs' import { Disposer } from '../../lib/class' import { ReactiveStoreService, KEY } from '../../state' @Component({ selector: 'app-comet-tower', template: ` <app-comet *ngFor...
riptIndex: number translatedIndex: number }
top: number transc
conditional_block
comet-tower.component.ts
import { Component, ChangeDetectionStrategy, ChangeDetectorRef, OnInit, OnDestroy } from '@angular/core' import { Observable } from 'rxjs' import { Disposer } from '../../lib/class' import { ReactiveStoreService, KEY } from '../../state' @Component({ selector: 'app-comet-tower', template: ` <app-comet *ngFor...
ousTop + diff > this.screenHeight * 0.7) { return 0 } else { return Math.round(previousTop + diff) } } } interface Comet { text: string top: number timestamp: number color: string } interface ScanLoopObject { top: number transcriptIndex: number translatedIndex: number }
* Math.random()) // 高さをランダムに決定。 } while (Math.abs(top - previousTop) < (this.screenHeight / 10)) // 前回と縦10分割位以上の差がつくこと。 return top } /** * Cometを表示する高さをランダムではなく上から順に決定していくアルゴリズム。 */ getTopPosition2(previousTop: number, diff: number): number { if (previ
identifier_body
comet-tower.component.ts
import { Component, ChangeDetectionStrategy, ChangeDetectorRef, OnInit, OnDestroy } from '@angular/core' import { Observable } from 'rxjs' import { Disposer } from '../../lib/class' import { ReactiveStoreService, KEY } from '../../state' @Component({ selector: 'app-comet-tower', template: ` <app-comet *ngFor...
interface Comet { text: string top: number timestamp: number color: string } interface ScanLoopObject { top: number transcriptIndex: number translatedIndex: number }
random_line_split
comet-tower.component.ts
import { Component, ChangeDetectionStrategy, ChangeDetectorRef, OnInit, OnDestroy } from '@angular/core' import { Observable } from 'rxjs' import { Disposer } from '../../lib/class' import { ReactiveStoreService, KEY } from '../../state' @Component({ selector: 'app-comet-tower', template: ` <app-comet *ngFor...
t { text: string top: number timestamp: number color: string } interface ScanLoopObject { top: number transcriptIndex: number translatedIndex: number }
interface Come
identifier_name
comment.component.ts
import { Component, Input } from '@angular/core'; import { Comment } from './comment.model'; import { FanType } from '../../enums/user-types.enum'; import { RouterLinks } from '../../enums'; import { ShortUserInfo } from '../short-user-info/short-user-info.interface'; @Component({ selector: 'app-comment', templat...
(commentData: Comment) { if (!commentData) { return; } this.commentData = commentData; this.commentator = { ...this.commentData.commentator, ...{ userProfileLink: { routerLink: this.commentData.commentator.type === FanType.type ? `/${RouterLinks.FanProfile}` : `/${Ro...
setCommentData
identifier_name
comment.component.ts
import { Component, Input } from '@angular/core'; import { Comment } from './comment.model'; import { FanType } from '../../enums/user-types.enum'; import { RouterLinks } from '../../enums'; import { ShortUserInfo } from '../short-user-info/short-user-info.interface'; @Component({ selector: 'app-comment', templat...
commentData: Comment; }
commentator: ShortUserInfo;
random_line_split
comment.component.ts
import { Component, Input } from '@angular/core'; import { Comment } from './comment.model'; import { FanType } from '../../enums/user-types.enum'; import { RouterLinks } from '../../enums'; import { ShortUserInfo } from '../short-user-info/short-user-info.interface'; @Component({ selector: 'app-comment', templat...
commentator: ShortUserInfo; commentData: Comment; }
{ if (!commentData) { return; } this.commentData = commentData; this.commentator = { ...this.commentData.commentator, ...{ userProfileLink: { routerLink: this.commentData.commentator.type === FanType.type ? `/${RouterLinks.FanProfile}` : `/${RouterLinks.ArtistProfile...
identifier_body
comment.component.ts
import { Component, Input } from '@angular/core'; import { Comment } from './comment.model'; import { FanType } from '../../enums/user-types.enum'; import { RouterLinks } from '../../enums'; import { ShortUserInfo } from '../short-user-info/short-user-info.interface'; @Component({ selector: 'app-comment', templat...
this.commentData = commentData; this.commentator = { ...this.commentData.commentator, ...{ userProfileLink: { routerLink: this.commentData.commentator.type === FanType.type ? `/${RouterLinks.FanProfile}` : `/${RouterLinks.ArtistProfile}`, queryParams: { id: ...
{ return; }
conditional_block
viewport.rs
use lsp_types::Range; use serde::{Deserialize, Serialize}; /// Visible lines of editor. /// /// Inclusive at start, exclusive at end. Both start and end are 0-based. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Copy, Clone)] pub struct Viewport { pub start: u64, pub end: u64, } impl Viewport { #...
#[test] fn test_overlaps() { use lsp_types::*; let viewport = Viewport::new(2, 7); assert_eq!( viewport.overlaps(Range::new(Position::new(0, 0), Position::new(1, 10))), false ); assert_eq!( viewport.overlaps(Range::new(Position::new(...
{ let viewport = Viewport::new(0, 7); assert_eq!(viewport.start, 0); assert_eq!(viewport.end, 7); }
identifier_body
viewport.rs
use lsp_types::Range; use serde::{Deserialize, Serialize}; /// Visible lines of editor. /// /// Inclusive at start, exclusive at end. Both start and end are 0-based. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Copy, Clone)] pub struct Viewport { pub start: u64, pub end: u64, } impl Viewport { #...
} #[test] fn test_overlaps() { use lsp_types::*; let viewport = Viewport::new(2, 7); assert_eq!( viewport.overlaps(Range::new(Position::new(0, 0), Position::new(1, 10))), false ); assert_eq!( viewport.overlaps(Range::new(Position:...
assert_eq!(viewport.end, 7);
random_line_split
viewport.rs
use lsp_types::Range; use serde::{Deserialize, Serialize}; /// Visible lines of editor. /// /// Inclusive at start, exclusive at end. Both start and end are 0-based. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Copy, Clone)] pub struct Viewport { pub start: u64, pub end: u64, } impl Viewport { #...
(start: u64, end: u64) -> Self { Self { start, end } } fn contains(&self, line: u64) -> bool { line >= self.start && line < self.end } pub fn overlaps(&self, range: Range) -> bool { self.contains(range.start.line) || self.contains(range.end.line) } } #[cfg(test)] mod test ...
new
identifier_name
mkart.rs
extern crate jiyunet_core as core; extern crate jiyunet_dag as dag; #[macro_use] extern crate clap; use std::fs; use std::io::Read; use core::io::BinaryComponent; use core::sig::Signed; use dag::artifact; use dag::segment; mod util; fn
() { let matches = clap_app!(jiyu_mkart => (version: "0.1.0") (author: "treyzania <treyzania@gmail.com>") (about: "Packages an file into a signed Jiyunet segment. Note that the segment is not likely to be valid on the blockchain due to noncing, etc.") (@arg src: +required "Source f...
main
identifier_name
mkart.rs
extern crate jiyunet_core as core; extern crate jiyunet_dag as dag; #[macro_use] extern crate clap; use std::fs; use std::io::Read; use core::io::BinaryComponent; use core::sig::Signed; use dag::artifact; use dag::segment; mod util; fn main()
let data = { let mut f: fs::File = fs::File::open(src).unwrap(); let mut v = Vec::new(); f.read_to_end(&mut v).expect("error reading provided artifact contents"); v }; let art = artifact::ArtifactData::new(atype, data); let seg = segment::Segment::new_artifact_seg(art, u...
{ let matches = clap_app!(jiyu_mkart => (version: "0.1.0") (author: "treyzania <treyzania@gmail.com>") (about: "Packages an file into a signed Jiyunet segment. Note that the segment is not likely to be valid on the blockchain due to noncing, etc.") (@arg src: +required "Source file...
identifier_body
mkart.rs
extern crate jiyunet_core as core; extern crate jiyunet_dag as dag; #[macro_use] extern crate clap; use std::fs; use std::io::Read; use core::io::BinaryComponent; use core::sig::Signed; use dag::artifact; use dag::segment; mod util;
fn main() { let matches = clap_app!(jiyu_mkart => (version: "0.1.0") (author: "treyzania <treyzania@gmail.com>") (about: "Packages an file into a signed Jiyunet segment. Note that the segment is not likely to be valid on the blockchain due to noncing, etc.") (@arg src: +required "...
random_line_split
fetch.js
/** * @module kat-cr/lib/fetch * @description * Wraps request in a Promise */ /** * The HTTP response class provided by request * @external HTTPResponse * @see {@link http://github.com/request/request} */ "use strict"; const request = (function loadPrivate(module) { let modulePath = require.resolve(module)...
/** Expose private request module for debugging */ module.exports._request = request;
};
random_line_split
images.js
import config from '../config'; import changed from 'gulp-changed'; import gulp from 'gulp'; import gulpif from 'gulp-if'; import imagemin from 'gulp-imagemin'; import browserSync from 'browser-sync'; function images(src, dest)
gulp.task('blogImages', function() { return images(config.blog.images.src, config.blog.images.dest); }); gulp.task('siteImages', function() { return images(config.site.images.src, config.site.images.dest); }); gulp.task('erpImages', function() { return images(config.erp.images.src, config.erp.images.dest); })...
{ return gulp.src(config.sourceDir + src) .pipe(changed(config.buildDir + dest)) // Ignore unchanged files .pipe(gulpif(global.isProd, imagemin())) // Optimize .pipe(gulp.dest(config.buildDir + dest)) .pipe(browserSync.stream()); }
identifier_body
images.js
import config from '../config'; import changed from 'gulp-changed'; import gulp from 'gulp'; import gulpif from 'gulp-if'; import imagemin from 'gulp-imagemin'; import browserSync from 'browser-sync'; function
(src, dest) { return gulp.src(config.sourceDir + src) .pipe(changed(config.buildDir + dest)) // Ignore unchanged files .pipe(gulpif(global.isProd, imagemin())) // Optimize .pipe(gulp.dest(config.buildDir + dest)) .pipe(browserSync.stream()); } gulp.task('blogImages', function() { ...
images
identifier_name
images.js
import config from '../config'; import changed from 'gulp-changed'; import gulp from 'gulp'; import gulpif from 'gulp-if'; import imagemin from 'gulp-imagemin'; import browserSync from 'browser-sync'; function images(src, dest) { return gulp.src(config.sourceDir + src) .pipe(changed...
}); gulp.task('erpImages', function() { return images(config.erp.images.src, config.erp.images.dest); }); gulp.task('modulesImages', function() { return images(config.modules.images.src, config.modules.images.dest); }); gulp.task('fbImages', function() { return images(config.fb.images.src, config.fb.images.des...
return images(config.site.images.src, config.site.images.dest);
random_line_split
dm_utils.py
from collections import namedtuple import io import re from six.moves.urllib.parse import urlparse from apitools.base.py import exceptions as apitools_exceptions from googlecloudsdk.api_lib.deployment_manager import dm_base from ruamel.yaml import YAML DM_OUTPUT_QUERY_REGEX = re.compile( r'!DMOutput\s+(?P<url>\bd...
def parse_dm_output_token(token, project=''): error_msg = ( 'The url must look like ' '$(out.${project}.${deployment}.${resource}.${name}" or ' '$(out.${deployment}.${resource}.${name}"' ) parts = token.split('.') # parts == 3 if project isn't specified in the token # par...
error_msg = ( 'The url must look like ' '"dm://${project}/${deployment}/${resource}/${name}" or' '"dm://${deployment}/${resource}/${name}"' ) parsed_url = urlparse(url) if parsed_url.scheme != 'dm': raise ValueError(error_msg) path = parsed_url.path.split('/')[1:] # ...
identifier_body
dm_utils.py
from collections import namedtuple import io import re from six.moves.urllib.parse import urlparse from apitools.base.py import exceptions as apitools_exceptions from googlecloudsdk.api_lib.deployment_manager import dm_base from ruamel.yaml import YAML DM_OUTPUT_QUERY_REGEX = re.compile( r'!DMOutput\s+(?P<url>\bd...
return output['finalValue']
conditional_block
dm_utils.py
from collections import namedtuple import io import re from six.moves.urllib.parse import urlparse from apitools.base.py import exceptions as apitools_exceptions from googlecloudsdk.api_lib.deployment_manager import dm_base from ruamel.yaml import YAML DM_OUTPUT_QUERY_REGEX = re.compile( r'!DMOutput\s+(?P<url>\bd...
# parts == 3 if project isn't specified in the token # parts == 4 if project is specified in the token if len(parts) == 3: return DMOutputQueryAttributes(project, *parts) elif len(parts) == 4: return DMOutputQueryAttributes(*parts) else: raise ValueError(error_msg) def get_...
'$(out.${project}.${deployment}.${resource}.${name}" or ' '$(out.${deployment}.${resource}.${name}"' ) parts = token.split('.')
random_line_split
dm_utils.py
from collections import namedtuple import io import re from six.moves.urllib.parse import urlparse from apitools.base.py import exceptions as apitools_exceptions from googlecloudsdk.api_lib.deployment_manager import dm_base from ruamel.yaml import YAML DM_OUTPUT_QUERY_REGEX = re.compile( r'!DMOutput\s+(?P<url>\bd...
(dm_base.DmCommand): """ Class representing the DM API This a proxy class only, so other modules in this project only import this local class instead of gcloud's. Here's the source: https://github.com/google-cloud-sdk/google-cloud-sdk/blob/master/lib/googlecloudsdk/api_lib/deployment_manager/dm_base.p...
DM_API
identifier_name
conf.py
like shown here. # sys.path.insert(0, os.path.abspath('.')) sys.path.append(os.path.abspath('_themes')) sys.path.append(os.path.abspath('../../../odoo')) # Load OpenERP with correct addons-path so the doc can be built even if # the addon import modules from other branches import openerp BASE_PATH = os.path.abspath(os...
# If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names # to template names. # ...
# html_last_updated_fmt = '%b %d, %Y'
random_line_split
change-password-prompt.component.ts
/** * Created by Андрей on 01.07.2017. */ import { Component } from '@angular/core'; import { DialogComponent, DialogService } from 'ng2-bootstrap-modal'; import { FormBuilder, FormControl, Validators } from '@angular/forms'; import { passConfirmValidation } from '../../auth-page/validators/pass-confirm.validator'; i...
gService: DialogService, private fb: FormBuilder, private userProfile: UserProfileService, private router: Router) { super(dialogService); } /** * Change new password * @param $event. This parameter contains data of the event. * @param value. This parameter con...
uctor(dialo
identifier_name
change-password-prompt.component.ts
/** * Created by Андрей on 01.07.2017. */ import { Component } from '@angular/core'; import { DialogComponent, DialogService } from 'ng2-bootstrap-modal'; import { FormBuilder, FormControl, Validators } from '@angular/forms'; import { passConfirmValidation } from '../../auth-page/validators/pass-confirm.validator'; i...
* Change new password * @param $event. This parameter contains data of the event. * @param value. This parameter contains data of the form for new password. */ public changePassword($event, value) { $event.preventDefault(); this.userProfile.changePassword(value) .subscribe(() => { t...
super(dialogService); } /**
identifier_body
change-password-prompt.component.ts
/** * Created by Андрей on 01.07.2017. */ import { Component } from '@angular/core'; import { DialogComponent, DialogService } from 'ng2-bootstrap-modal'; import { FormBuilder, FormControl, Validators } from '@angular/forms'; import { passConfirmValidation } from '../../auth-page/validators/pass-confirm.validator'; i...
public close() { this.dialogService.removeDialog(this); } }
* Close modal window */
random_line_split
reissue_certificate_order_request.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
'type': {'key': 'type', 'type': 'str'}, 'key_size': {'key': 'properties.keySize', 'type': 'int'}, 'delay_existing_revoke_in_hours': {'key': 'properties.delayExistingRevokeInHours', 'type': 'int'}, 'csr': {'key': 'properties.csr', 'type': 'str'}, 'is_private_key_external': {'key':...
_attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'kind': {'key': 'kind', 'type': 'str'},
random_line_split
reissue_certificate_order_request.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
:param is_private_key_external: Should we change the ASC type (from managed private key to external private key and vice versa). :type is_private_key_external: bool """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } ...
"""Class representing certificate reissue request. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource Name. :vartype name: str :param kind: Kind of resource. :type kind: str :ivar type...
identifier_body
reissue_certificate_order_request.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(self, kind=None, key_size=None, delay_existing_revoke_in_hours=None, csr=None, is_private_key_external=None): super(ReissueCertificateOrderRequest, self).__init__(kind=kind) self.key_size = key_size self.delay_existing_revoke_in_hours = delay_existing_revoke_in_hours self.csr = csr ...
__init__
identifier_name
syncer.rs
<Item=T>, T: Clone + Eq + Ord> { l: std::iter::Peekable<I>, r: std::iter::Peekable<J>, } impl<I: std::iter::Iterator<Item=T>, J: std::iter::Iterator<Item=T>, T: Clone + Ord> Comm<I, J, T> { pub fn new(left: I, right: J) -> Comm<I, J, T> { Comm { l: left.peekable(), r: right.peekable(), } } } impl<I: st...
<T>(conn: &postgres::Connection, k: &str, new: Vec<T>, old: &Vec<T>, heed_deletions: bool) -> Result<(Vec<T>, Vec<T>, Vec<T>)> where T: Clone + for<'de> Deserialize<'de> + Serialize + Eq + Ord + Debug { let (all, additions, deletions) = comm_list(new, old, heed_deletions); if !(additions.is_empty() && deletions...
update_list
identifier_name
syncer.rs
<Item=T>, T: Clone + Eq + Ord> { l: std::iter::Peekable<I>, r: std::iter::Peekable<J>, } impl<I: std::iter::Iterator<Item=T>, J: std::iter::Iterator<Item=T>, T: Clone + Ord> Comm<I, J, T> { pub fn new(left: I, right: J) -> Comm<I, J, T> { Comm { l: left.peekable(), r: right.peekable(), } } } impl<I: st...
// match x.cmp(y) { // o @ std::cmp::Ordering::Equal => { ret.push((o, l.next().and(r.next()).unwrap().clone())); }, // o @ std::cmp::Ordering::Less => { ret.push((o, l.next() .unwrap().clone())); }, // o @ std::cmp::Ordering::Greater => { ret.push((o, r.next() ...
// let mut ret: Vec<(std::cmp::Ordering, T)> = Vec::with_capacity(left.capacity()+right.capacity()); // let (mut l, mut r) = (left.iter().peekable(), right.iter().peekable()); // while l.peek().is_some() && r.peek().is_some() { // let x = l.peek().unwrap().clone(); // let y = r.peek().unwrap().cl...
random_line_split
syncer.rs
=T>, T: Clone + Eq + Ord> { l: std::iter::Peekable<I>, r: std::iter::Peekable<J>, } impl<I: std::iter::Iterator<Item=T>, J: std::iter::Iterator<Item=T>, T: Clone + Ord> Comm<I, J, T> { pub fn new(left: I, right: J) -> Comm<I, J, T> { Comm { l: left.peekable(), r: right.peekable(), } } } impl<I: std::it...
fn comm_map<'a, K, T>(mut new: BTreeMap<K, Vec<T>>, old: &'a mut BTreeMap<K, Vec<T>>, heed_deletions: bool) -> (BTreeMap<K, Vec<T>>, BTreeMap<K, Vec<T>>, BTreeMap<K, Vec<T>>) where T: Debug + Clone + for<'de> Deserialize<'de> + Serialize + Eq + Ord, K: Debug + Ord + Clone + for<'de> Deserialize<'de> + Serialize { ...
{ let (mut all, mut additions, mut deletions) : (Vec<T>, Vec<T>, Vec<T>) = (Vec::with_capacity(new.len()), vec![], vec![]); for (o, x) in Comm::new(new.into_iter(), old.iter().cloned()) { match o { std::cmp::Ordering::Equal => all.push(x), std::cmp::Ordering::Less => { additions....
identifier_body
firewall_cmds.py
util_lib import gcutil_errors from gcutil_lib import utils FLAGS = flags.FLAGS class FirewallCommand(command_base.GoogleComputeCommand): """Base command for working with the firewalls collection.""" print_spec = command_base.ResourcePrintSpec( summary=['name', 'network'], field_mappings=( ...
(object): """Class representing the list of a firewall's rules. This class is only used for parsing a firewall from command-line flags, for printing the firewall, we simply dump the JSON. """ @staticmethod def ParsePortSpecs(port_spec_strings): """Parse the port-specification portion of firewall rules...
FirewallRules
identifier_name
firewall_cmds.py
gcutil_lib import gcutil_errors from gcutil_lib import utils FLAGS = flags.FLAGS class FirewallCommand(command_base.GoogleComputeCommand): """Base command for working with the firewalls collection.""" print_spec = command_base.ResourcePrintSpec( summary=['name', 'network'], field_mappings=( ...
self.target_tags = [] def SetTags(self, source_tags, target_tags): self.source_tags = sorted(set(source_tags)) self.target_tags = sorted(set(target_tags)) def AddToFirewall(self, firewall): if self.source_ranges: firewall['sourceRanges'] = self.source_ranges if self.source_tags: fi...
self.port_specs = FirewallRules.ParsePortSpecs(allowed) self.source_ranges = allowed_ip_sources self.source_tags = []
random_line_split
firewall_cmds.py
util_lib import gcutil_errors from gcutil_lib import utils FLAGS = flags.FLAGS class FirewallCommand(command_base.GoogleComputeCommand): """Base command for working with the firewalls collection.""" print_spec = command_base.ResourcePrintSpec( summary=['name', 'network'], field_mappings=( ...
return data class FirewallRules(object): """Class representing the list of a firewall's rules. This class is only used for parsing a firewall from command-line flags, for printing the firewall, we simply dump the JSON. """ @staticmethod def ParsePortSpecs(port_spec_strings): """Parse the port-s...
as_string = str(allowed['IPProtocol']) if allowed.get('ports'): as_string += ': %s' % ', '.join(allowed['ports']) data.append(('allowed', as_string))
conditional_block
firewall_cmds.py
util_lib import gcutil_errors from gcutil_lib import utils FLAGS = flags.FLAGS class FirewallCommand(command_base.GoogleComputeCommand): """Base command for working with the firewalls collection.""" print_spec = command_base.ResourcePrintSpec( summary=['name', 'network'], field_mappings=( ...
def AddToFirewall(self, firewall): if self.source_ranges: firewall['sourceRanges'] = self.source_ranges if self.source_tags: firewall['sourceTags'] = self.source_tags if self.target_tags: firewall['targetTags'] = self.target_tags firewall['allowed'] = self.port_specs class AddFir...
self.source_tags = sorted(set(source_tags)) self.target_tags = sorted(set(target_tags))
identifier_body