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
javalab.service.ts
import {Injectable} from "@angular/core"; import {Http, Headers, RequestOptions, RequestMethod, ResponseContentType} from "@angular/http"; import "rxjs/add/operator/toPromise"; import {FileNode, GlobalModel} from "../common"; import fileSaver = require("file-saver"); const BASE = "http://localhost:48080/rest/process";...
private searchNode(id: string, node: FileNode) { if (node.id === id) { return node; } else if (node.children !== null && node.children !== undefined) { var result = null; for (var i = 0; result === null && i < node.children.length; i++) { result ...
{ for (var node of tree) { var found = this.searchNode(id, node); if (found !== null) { return found; } } }
identifier_body
javalab.service.ts
import {Injectable} from "@angular/core"; import {Http, Headers, RequestOptions, RequestMethod, ResponseContentType} from "@angular/http"; import "rxjs/add/operator/toPromise"; import {FileNode, GlobalModel} from "../common"; import fileSaver = require("file-saver"); const BASE = "http://localhost:48080/rest/process";...
(model: GlobalModel) { let runCodeURL = BASE + "/run"; let body = JSON.stringify(model); let headers = new Headers({'Content-Type': 'application/json'}); let options = new RequestOptions({headers: headers}); return this.http.post(runCodeURL, body, options) .toPromise...
runCode
identifier_name
javalab.service.ts
import {Injectable} from "@angular/core"; import {Http, Headers, RequestOptions, RequestMethod, ResponseContentType} from "@angular/http"; import "rxjs/add/operator/toPromise"; import {FileNode, GlobalModel} from "../common"; import fileSaver = require("file-saver"); const BASE = "http://localhost:48080/rest/process";...
.toPromise() .then(res => res.json()) .catch(error => this.handleError); } findNodeById(id: string, tree: FileNode[]): FileNode { for (var node of tree) { var found = this.searchNode(id, node); if (found !== null) { return fou...
let headers = new Headers({'Content-Type': 'application/json'}); let options = new RequestOptions({headers: headers}); return this.http.post(testCodeURL, body, options)
random_line_split
new-unicode-escapes.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 ...
assert_eq!(s, correct_s); }
random_line_split
new-unicode-escapes.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 ...
() { let s = "\u{2603}"; assert_eq!(s, "☃"); let s = "\u{2a10}\u{2A01}\u{2Aa0}"; assert_eq!(s, "⨐⨁⪠"); let s = "\\{20}"; let mut correct_s = String::from_str("\\"); correct_s.push_str("{20}"); assert_eq!(s, correct_s); }
main
identifier_name
new-unicode-escapes.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 ...
{ let s = "\u{2603}"; assert_eq!(s, "☃"); let s = "\u{2a10}\u{2A01}\u{2Aa0}"; assert_eq!(s, "⨐⨁⪠"); let s = "\\{20}"; let mut correct_s = String::from_str("\\"); correct_s.push_str("{20}"); assert_eq!(s, correct_s); }
identifier_body
settings.py
# -*- coding: utf-8 -*- # Scrapy settings for aCloudGuru project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/lat...
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'aCloudGuru.middlewares.MyCustomSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # ...
random_line_split
main.rs
#![feature(proc_macro)] extern crate hyper; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate ansi_term; extern crate rocksdb; extern crate clap; #[macro_use(o, slog_log, slog_trace, slog_debug, slog_info, slog_warn, slog_error)] extern crate slog; extern crate slog_term; // #[macro_use...
identifier_body
main.rs
#![feature(proc_macro)] extern crate hyper; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate ansi_term; extern crate rocksdb; extern crate clap; #[macro_use(o, slog_log, slog_trace, slog_debug, slog_info, slog_warn, slog_error)] extern crate slog; extern crate slog_term; // #[macro_use...
(query: &str, cache_db: &DB, update_cache: bool, logger: &slog::Logger) -> Result<String, YDCVError> { let mut request_url = REQUEST_BASE.to_string(); request_url.push_str(query); let client = Client::new(); slog_debug!(logger, "开始从网络获取翻译结果"); let mut res = client.get(&request_url).header(Connec...
get_remote_json_translation
identifier_name
main.rs
#![feature(proc_macro)] extern crate hyper; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate ansi_term; extern crate rocksdb; extern crate clap; #[macro_use(o, slog_log, slog_trace, slog_debug, slog_info, slog_warn, slog_error)] extern crate slog; extern crate slog_term; // #[macro_use...
)) } fn main() { slog_envlogger::init().unwrap(); let drain = slog_term::streamer().compact().build().fuse(); let root_log = slog::Logger::root(drain, o!("version" => "0.3.0")); let matches = App::new("YDCV") .version("0.3.0") .author("Greedwolf DSS <greedwolf.dss@gmail.com>") ...
地缓存"); cache_db.put(query.as_bytes(), trans_result.translation_description().as_bytes())?; } Ok(trans_result.translation_description(
conditional_block
main.rs
#![feature(proc_macro)] extern crate hyper; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate ansi_term; extern crate rocksdb; extern crate clap; #[macro_use(o, slog_log, slog_trace, slog_debug, slog_info, slog_warn, slog_error)] extern crate slog; extern crate slog_term; // #[macro_use...
}, }; slog_debug!(root_log, "cache path: {}", cache_path); let db = match DB::open_default(cache_path.as_str()) { Ok(db) => db, Err(err) => { slog_error!(root_log, "无法创建RocksDB的存储目录 error: {}", err); return; } }; let db_key = trans.as_bytes()...
Some(path) => path, None => { slog_error!(root_log, "没有缓存路径"); return;
random_line_split
ecooputil.py
# # Author: Massimo Di Stefano , distem@rpi.edu - # http://tw.rpi.edu/web/person/MassimoDiStefano # ############################################################################### # Copyright (c) 2008-2014 Tetherless World Constellation at Rensselaer Polytechnic Institute # Permission is hereby grante...
return link except: print "can't generate gist, check if jist works bycommand line with: jist -p filename" if not jist: print 'cannot find jist utility, check if it is in your path' except IOError: ...
''' use the jist utility to paste a txt file on github as gist and return a link to it usage : gistit(notebookfile) @param filename: str - path to the a text file or notebook file (.json) @param jist: str - path to the executable jist (default=/usr/local/bin/jist) @param type: s...
identifier_body
ecooputil.py
# # Author: Massimo Di Stefano , distem@rpi.edu - # http://tw.rpi.edu/web/person/MassimoDiStefano # ############################################################################### # Copyright (c) 2008-2014 Tetherless World Constellation at Rensselaer Polytechnic Institute # Permission is hereby grante...
@return: None ''' if not os.path.exists(dir): os.makedirs(dir) def save_notebook(self, ID, notebookname, web=None, notebookdir=None): """ Save the notebook file as html and or as gist @param ID: directory name where to store the saved notebook @pa...
@param dir: str - path to a directory existent on the local filesystem
random_line_split
ecooputil.py
# # Author: Massimo Di Stefano , distem@rpi.edu - # http://tw.rpi.edu/web/person/MassimoDiStefano # ############################################################################### # Copyright (c) 2008-2014 Tetherless World Constellation at Rensselaer Polytechnic Institute # Permission is hereby grante...
if not link: print 'WORNING: qrcode not generated, set the option link to True' if link: filelink = outputfile.replace(apacheroot, '') link = 'http://' + os.path.normpath(hostname + '/' + filelink) raw_html = '<a href="%s" ...
pass
conditional_block
ecooputil.py
# # Author: Massimo Di Stefano , distem@rpi.edu - # http://tw.rpi.edu/web/person/MassimoDiStefano # ############################################################################### # Copyright (c) 2008-2014 Tetherless World Constellation at Rensselaer Polytechnic Institute # Permission is hereby granted...
(self, suffix, makedir=True): ''' generate a directory based on the suffix and a time stamp output looks like : suffix_Thursday_26_September_2013_06_28_49_PM usage: getID(suffix) @param suffix: str - suffix for the directory to be generated, @return: str - directory name ...
get_id
identifier_name
pipeline.js
// also can pass configs here. * pipeline.add("path/to/asset.js", { * type: "javascript", // or "css" to get default configs * main: "my_package/app/main", // main modules to build from * * // additional optional configs * * minify: true, // to minify * autocache: tr...
/** * Writes a single asset to the build directory. Invokes callback when done. * * @param {String} path Path to write, must match an added asset. * @param {String} buildir Base directory to build to. * @param {Function} done Called when done with possible error. * @return {void} */ Pi...
{ ASYNC.reduce(_values(pipeline.packagers), {}, function(memo, packager, next){ packager.findPaths(function(err, paths) { if (err) return next(err); paths.forEach(function(path) { if (!memo[path]) memo[path] = packager; }); next(null, memo); }); }, done); }
identifier_body
pipeline.js
* pipeline = new Pipeline(); // also can pass configs here. * pipeline.add("path/to/asset.js", { * type: "javascript", // or "css" to get default configs * main: "my_package/app/main", // main modules to build from * * // additional optional configs * * minify: true, //...
random_line_split
pipeline.js
// also can pass configs here. * pipeline.add("path/to/asset.js", { * type: "javascript", // or "css" to get default configs * main: "my_package/app/main", // main modules to build from * * // additional optional configs * * minify: true, // to minify * autocache: tr...
else { return done(new Error(path+' asset does not contain body')); } }); }); }); }; /** * Writes all defined assets to the named build directory. Invokes the callback * when done. * * @param {String} buildir Directory to build to * @param {Function} done Called when done w...
{ var encoding = asset.encoding || 'utf8'; FS.writeFile(dstPath, asset.body, encoding, function(err) { if (!err) self.info('wrote', dstPath); done(err); }); }
conditional_block
pipeline.js
(); // also can pass configs here. * pipeline.add("path/to/asset.js", { * type: "javascript", // or "css" to get default configs * main: "my_package/app/main", // main modules to build from * * // additional optional configs * * minify: true, // to minify * autocache:...
(pipeline, done) { ASYNC.reduce(_values(pipeline.packagers), {}, function(memo, packager, next){ packager.findPaths(function(err, paths) { if (err) return next(err); paths.forEach(function(path) { if (!memo[path]) memo[path] = packager; }); next(null, memo); }); }, done); } ...
_mapPaths
identifier_name
LogsStore.js
import alt from "../alt"; import LogsActions from "../actions/LogsActions"; import $ from "jquery"; // IPC hack (https://medium.freecodecamp.com/building-an-electron-application-with-create-react-app-97945861647c#.gi5l2hzbq) const electron = window.require("electron"); const fs = electron.remote.require("fs"); const r...
dialog.showErrorBox("Could not load logs!", "Please try again."); } } export default alt.createStore(LogsStore);
{ $(window).trigger("goBackToLogin"); return; }
conditional_block
LogsStore.js
import alt from "../alt"; import LogsActions from "../actions/LogsActions"; import $ from "jquery"; // IPC hack (https://medium.freecodecamp.com/building-an-electron-application-with-create-react-app-97945861647c#.gi5l2hzbq) const electron = window.require("electron"); const fs = electron.remote.require("fs"); const r...
(err) { if (err.response && err.response.status === 403) { $(window).trigger("goBackToLogin"); return; } dialog.showErrorBox("Could not load logs!", "Please try again."); } } export default alt.createStore(LogsStore);
getLogsFail
identifier_name
LogsStore.js
import alt from "../alt"; import LogsActions from "../actions/LogsActions"; import $ from "jquery"; // IPC hack (https://medium.freecodecamp.com/building-an-electron-application-with-create-react-app-97945861647c#.gi5l2hzbq) const electron = window.require("electron"); const fs = electron.remote.require("fs"); const r...
// GET LOGS SUCCESS getLogsSuccess(result) { this.logs = result.data; } // GET LOGS FAIL getLogsFail(err) { if (err.response && err.response.status === 403) { $(window).trigger("goBackToLogin"); return; } dialog.showErrorBox("Could not load logs!", "Please...
constructor() { this.bindActions(LogsActions); this.logs = []; }
random_line_split
test_yearmonth.py
# -*- coding: utf-8 -*- from __future__ import division from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import pytest from tableschema import types from tableschema.config import ERROR # Tests @pytest.mark.parametrize('format, value, result', [ ...
(format, value, result): assert types.cast_yearmonth(format, value) == result
test_cast_yearmonth
identifier_name
test_yearmonth.py
# -*- coding: utf-8 -*- from __future__ import division from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals
import pytest from tableschema import types from tableschema.config import ERROR # Tests @pytest.mark.parametrize('format, value, result', [ ('default', [2000, 10], (2000, 10)), ('default', (2000, 10), (2000, 10)), ('default', '2000-10', (2000, 10)), ('default', (2000, 10, 20), ERROR), ('default'...
random_line_split
test_yearmonth.py
# -*- coding: utf-8 -*- from __future__ import division from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import pytest from tableschema import types from tableschema.config import ERROR # Tests @pytest.mark.parametrize('format, value, result', [ ...
assert types.cast_yearmonth(format, value) == result
identifier_body
service.js
"use strict"; var assert = require('assert-plus'), util = require("util"), events = require("events"), servicePrefix = '/api'; /* { id: 1, version: 1, path: '/myserver/...' } Simple class for validating service resources */ function
(opts) { events.EventEmitter.call(this); this.update(opts); } util.inherits(Service, events.EventEmitter); Service.prototype.validate = function SocketValidate(opts){ var o = opts || {}; if (typeof this.path === 'undefined') { assert.string(o.path,'Service path'); } else { assert.o...
Service
identifier_name
service.js
"use strict"; var assert = require('assert-plus'), util = require("util"), events = require("events"), servicePrefix = '/api'; /* { id: 1, version: 1, path: '/myserver/...' } Simple class for validating service resources */ function Service(opts) { events.EventEmi...
this.emit('update',o); return this; }; Service.prototype.toJSON = function ServiceToJSON(){ return { id: this.id, version: this.version, path: this.path, seq: this.seq }; }; exports.Service = Service;
{ this.path = '/' + this.path; }
conditional_block
service.js
"use strict"; var assert = require('assert-plus'), util = require("util"), events = require("events"), servicePrefix = '/api'; /* { id: 1, version: 1, path: '/myserver/...' } Simple class for validating service resources */ function Service(opts)
util.inherits(Service, events.EventEmitter); Service.prototype.validate = function SocketValidate(opts){ var o = opts || {}; if (typeof this.path === 'undefined') { assert.string(o.path,'Service path'); } else { assert.optionalString(o.path,'Service path'); } if (typeof this.seq ...
{ events.EventEmitter.call(this); this.update(opts); }
identifier_body
service.js
"use strict"; var assert = require('assert-plus'), util = require("util"), events = require("events"), servicePrefix = '/api'; /* { id: 1, version: 1, path: '/myserver/...' } Simple class for validating service resources */ function Service(opts) { events.EventEmi...
this.validate(o); this.id = o.id || 1; this.version = o.version || 1; this.path = o.path || this.path; this.requiresAuthentication = o.requiresAuthentication || false; if (typeof o.seq !== 'undefined') { this.seq = o.seq; } if (this.path.substring(0,1) !== '/') { this....
Service.prototype.update = function ServiceUpdate(opts){ var o = opts || {};
random_line_split
dromaeo.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from metrics import power from telemetry import test from telemetry.core import util from telemetry.page import page_measurement from telemetry.pa...
if k == suffix: data_type = 'default' results.Add(Escape(k), 'runs/s', float(v), data_type=data_type) class _DromaeoBenchmark(test.Test): """A base class for Dromaeo benchmarks.""" test = _DromaeoMeasurement def CreatePageSet(self, options): """Makes a PageSet for Dromaeo benchmarks."""...
for k, v in score.iteritems(): data_type = 'unimportant'
random_line_split
dromaeo.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from metrics import power from telemetry import test from telemetry.core import util from telemetry.page import page_measurement from telemetry.pa...
(test.Test): """A base class for Dromaeo benchmarks.""" test = _DromaeoMeasurement def CreatePageSet(self, options): """Makes a PageSet for Dromaeo benchmarks.""" # Subclasses are expected to define a class member called query_param. if not hasattr(self, 'query_param'): raise NotImplementedErro...
_DromaeoBenchmark
identifier_name
dromaeo.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from metrics import power from telemetry import test from telemetry.core import util from telemetry.page import page_measurement from telemetry.pa...
url = 'file://index.html?%s&automated' % self.query_param dromaeo_dir = os.path.join(util.GetChromiumSrcDir(), 'chrome', 'test', 'data', 'dromaeo') ps = page_set.PageSet(file_path=dromaeo_dir) ps.AddPageWithDefaultRunNavigate(url) return ps class DromaeoDomCoreAttr(...
raise NotImplementedError('query_param not in Dromaeo benchmark.')
conditional_block
dromaeo.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from metrics import power from telemetry import test from telemetry.core import util from telemetry.page import page_measurement from telemetry.pa...
class DromaeoJslibEventPrototype(_DromaeoBenchmark): """Dromaeo JSLib event prototype JavaScript benchmark""" tag = 'jslibeventprototype' query_param = 'jslib-event-prototype' class DromaeoJslibModifyJquery(_DromaeoBenchmark): """Dromaeo JSLib modify jquery JavaScript benchmark""" tag = 'jslibmodifyjquer...
"""Dromaeo JSLib event jquery JavaScript benchmark""" tag = 'jslibeventjquery' query_param = 'jslib-event-jquery'
identifier_body
main.rs
use bracket_lib::prelude::*; enum GameMode { Menu, Playing, End, } struct Player { x: i32, y: i32, velocity: f32, } impl Player { fn new(x: i32, y: i32) -> Self { Player { x, y, velocity: 0.0, } } fn render(&mut self, ctx: &mut ...
} fn render(&mut self, ctx: &mut BTerm, player_x: i32) { let screen_x = self.x - player_x; let half_size = self.size / 2; // Draw the top half of the ovstacle for y in 0..self.gap_y - half_size { ctx.set( screen_x, y, ...
}
random_line_split
main.rs
use bracket_lib::prelude::*; enum GameMode { Menu, Playing, End, } struct Player { x: i32, y: i32, velocity: f32, } impl Player { fn new(x: i32, y: i32) -> Self { Player { x, y, velocity: 0.0, } } fn render(&mut self, ctx: &mut ...
} fn restart(&mut self) { self.player = Player::new(5, 25); self.frame_time = 0.0; self.mode = GameMode::Playing; } } impl GameState for State { fn tick(&mut self, ctx: &mut BTerm) { match self.mode { GameMode::Menu => self.main_menu(ctx), Ga...
{ match key { VirtualKeyCode::P => self.restart(), VirtualKeyCode::Q => ctx.quitting = true, _ => {} } }
conditional_block
main.rs
use bracket_lib::prelude::*; enum GameMode { Menu, Playing, End, } struct Player { x: i32, y: i32, velocity: f32, } impl Player { fn new(x: i32, y: i32) -> Self { Player { x, y, velocity: 0.0, } } fn render(&mut self, ctx: &mut ...
(&mut self) { self.velocity = -2.0; } } struct State { player: Player, frame_time: f32, obstacle: Obstacle, mode: GameMode, } impl State { fn new() -> Self { State { player: Player::new(5, 25), frame_time: 0.0, obstacle: Obstacle::new(SCREEN_...
flap
identifier_name
main.rs
use bracket_lib::prelude::*; enum GameMode { Menu, Playing, End, } struct Player { x: i32, y: i32, velocity: f32, } impl Player { fn new(x: i32, y: i32) -> Self { Player { x, y, velocity: 0.0, } } fn render(&mut self, ctx: &mut ...
} struct State { player: Player, frame_time: f32, obstacle: Obstacle, mode: GameMode, } impl State { fn new() -> Self { State { player: Player::new(5, 25), frame_time: 0.0, obstacle: Obstacle::new(SCREEN_WIDTH, 0), mode: GameMode::Menu, ...
{ self.velocity = -2.0; }
identifier_body
StepContent.js
import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import Collapse from '../Collapse'; import withStyles from '../styles/withStyles'; export const styles = theme => ({ /* Styles applied to the root element. */ root: { marginTop: 8, marginLeft: 12, // half icon paddi...
]), /** * Props applied to the `Transition` element. */ TransitionProps: PropTypes.object, }; export default withStyles(styles, { name: 'MuiStepContent' })(StepContent);
PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number }), PropTypes.oneOf(['auto']),
random_line_split
StepContent.js
import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import Collapse from '../Collapse'; import withStyles from '../styles/withStyles'; export const styles = theme => ({ /* Styles applied to the root element. */ root: { marginTop: 8, marginLeft: 12, // half icon paddi...
let transitionDuration = transitionDurationProp; if (transitionDurationProp === 'auto' && !TransitionComponent.muiSupportAuto) { transitionDuration = undefined; } return ( <div className={clsx(classes.root, { [classes.last]: last }, className)} ref={ref} {...other}> <TransitionComponent ...
{ if (orientation !== 'vertical') { console.error( 'Material-UI: <StepContent /> is only designed for use with the vertical stepper.', ); } }
conditional_block
mod.rs
// Copyright 2013 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 ...
pub use alloc::arc::{Arc, Weak}; pub use core::atomic; pub use self::barrier::{Barrier, BarrierWaitResult}; pub use self::condvar::{Condvar, StaticCondvar, CONDVAR_INIT}; pub use self::mutex::MUTEX_INIT; pub use self::mutex::{Mutex, MutexGuard, StaticMutex}; pub use self::once::{Once, ONCE_INIT}; pub use sys_common::p...
//! and/or blocking at all, but rather provide the necessary tools to build //! other types of concurrent primitives. #![stable(feature = "rust1", since = "1.0.0")]
random_line_split
App.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, o...
componentWillUnmount() { this.mounted = false; } requestPermissions = async () => { const { permissions, defaultTemplates, permissionTemplates } = await getPermissionTemplates(); if (this.mounted) { const sortedPerm = sortPermissions(permissions); const permissionTemplatesMerged = merg...
{ this.mounted = true; this.requestPermissions(); }
identifier_body
App.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, o...
return ( <Template refresh={this.requestPermissions} template={template} topQualifiers={this.props.appState.qualifiers} /> ); } renderHome() { return ( <Home permissionTemplates={this.state.permissionTemplates} permissions={this.state.permissi...
{ return null; }
conditional_block
App.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, o...
() { return ( <Home permissionTemplates={this.state.permissionTemplates} permissions={this.state.permissions} ready={this.state.ready} refresh={this.requestPermissions} topQualifiers={this.props.appState.qualifiers} /> ); } render() { const { id } = t...
renderHome
identifier_name
App.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, o...
import withAppStateContext from '../../../app/components/app-state/withAppStateContext'; import Suggestions from '../../../app/components/embed-docs-modal/Suggestions'; import { translate } from '../../../helpers/l10n'; import { AppState, Permission, PermissionTemplate } from '../../../types/types'; import '../../permi...
import { getPermissionTemplates } from '../../../api/permissions';
random_line_split
gallery.js
var albumId; var addPictures = function (result) { UserFBAlbums.update({id: albumId}, {$set: {'paging': result.paging}}); for (var i = 0; i < result.data.length; i++) { UserFBAlbums.update({id: albumId}, {$addToSet: {'pictures': result.data[i]}}); } IonLoading.hide(); }; Template.gallery.events(...
pictures.push({id: images[i]}); } } };
if (!albumId) { var images = Meteor.user().profile.facebookImageIds; for (var i = 0; i < images.length; i++) {
random_line_split
gallery.js
var albumId; var addPictures = function (result) { UserFBAlbums.update({id: albumId}, {$set: {'paging': result.paging}}); for (var i = 0; i < result.data.length; i++) { UserFBAlbums.update({id: albumId}, {$addToSet: {'pictures': result.data[i]}}); } IonLoading.hide(); }; Template.gallery.events(...
}.bind(this)); } }; Template.gallery.created = function () { albumId = Router.current().params._albumId; this.autorun(function () { this.subscription = Meteor.subscribe('user', Meteor.userId()); }.bind(this)); if (!albumId) { var images = Meteor.user().profile.facebookImag...
{ facebookApi.getPhotos({identifier: albumId}, function (result) { addPictures(result); }); }
conditional_block
date_and_time.rs
use expression::{Expression, SelectableExpression}; use query_builder::{QueryBuilder, BuildQueryResult}; use types::{Timestamp, VarChar}; pub struct AtTimeZone<Ts, Tz> { timestamp: Ts, timezone: Tz, } impl<Ts, Tz> AtTimeZone<Ts, Tz> { pub fn new(timestamp: Ts, timezone: Tz) -> Self { AtTimeZone { ...
(&self, out: &mut QueryBuilder) -> BuildQueryResult { try!(self.timestamp.to_sql(out)); out.push_sql(" AT TIME ZONE "); self.timezone.to_sql(out) } } impl<Ts, Tz, Qs> SelectableExpression<Qs> for AtTimeZone<Ts, Tz> where AtTimeZone<Ts, Tz>: Expression, {}
to_sql
identifier_name
date_and_time.rs
use expression::{Expression, SelectableExpression}; use query_builder::{QueryBuilder, BuildQueryResult}; use types::{Timestamp, VarChar}; pub struct AtTimeZone<Ts, Tz> { timestamp: Ts, timezone: Tz, } impl<Ts, Tz> AtTimeZone<Ts, Tz> { pub fn new(timestamp: Ts, timezone: Tz) -> Self { AtTimeZone { ...
} impl<Ts, Tz, Qs> SelectableExpression<Qs> for AtTimeZone<Ts, Tz> where AtTimeZone<Ts, Tz>: Expression, {}
{ try!(self.timestamp.to_sql(out)); out.push_sql(" AT TIME ZONE "); self.timezone.to_sql(out) }
identifier_body
date_and_time.rs
use expression::{Expression, SelectableExpression}; use query_builder::{QueryBuilder, BuildQueryResult}; use types::{Timestamp, VarChar}; pub struct AtTimeZone<Ts, Tz> { timestamp: Ts, timezone: Tz, }
} } } impl<Ts, Tz> Expression for AtTimeZone<Ts, Tz> where Ts: Expression<SqlType=Timestamp>, Tz: Expression<SqlType=VarChar>, { // FIXME: This should be Timestamptz when we support that type type SqlType = Timestamp; fn to_sql(&self, out: &mut QueryBuilder) -> BuildQueryResult { ...
impl<Ts, Tz> AtTimeZone<Ts, Tz> { pub fn new(timestamp: Ts, timezone: Tz) -> Self { AtTimeZone { timestamp: timestamp, timezone: timezone,
random_line_split
NavigateOverviewAction.ts
import { Subject } from 'rxjs'; import { ActionTarget, Action } from '../../../../angular'; import { NavigateService } from './navigate.service'; function objectTypeName(target: ActionTarget) { return Array.isArray(target) ? (target.length > 0) && target[0].objectType.name : target.objectType.name; } export class...
name = (target: ActionTarget) => 'Overview'; description = (target: ActionTarget) => `Go to ${objectTypeName(target)} overview`; disabled = () => false; execute = (target: ActionTarget) => { if (Array.isArray(target)) { if (target.length > 0) { this.navigateService.navigationService.overvi...
constructor(private navigateService: NavigateService) { } result = new Subject<boolean>();
random_line_split
NavigateOverviewAction.ts
import { Subject } from 'rxjs'; import { ActionTarget, Action } from '../../../../angular'; import { NavigateService } from './navigate.service'; function
(target: ActionTarget) { return Array.isArray(target) ? (target.length > 0) && target[0].objectType.name : target.objectType.name; } export class NavigateOverviewAction implements Action { constructor(private navigateService: NavigateService) { } result = new Subject<boolean>(); name = (target: ActionTarg...
objectTypeName
identifier_name
NavigateOverviewAction.ts
import { Subject } from 'rxjs'; import { ActionTarget, Action } from '../../../../angular'; import { NavigateService } from './navigate.service'; function objectTypeName(target: ActionTarget) { return Array.isArray(target) ? (target.length > 0) && target[0].objectType.name : target.objectType.name; } export class...
this.result.next(true); } }
{ this.navigateService.navigationService.overview(target); }
conditional_block
minicircuits.py
#!/usr/bin/env python3.4 # # Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
""" return bool(self._telnet_client.is_open) def open(self, host, port=23): """Opens a telnet connection to the desired AttenuatorDevice and queries basic information. Args:: host: A valid hostname (IP address or DNS-resolvable name) to an MC-D...
True if there is a successfully open connection to the AttenuatorDevice.
random_line_split
minicircuits.py
#!/usr/bin/env python3.4 # # Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
""" return bool(self._telnet_client.is_open) def open(self, host, port=23): """Opens a telnet connection to the desired AttenuatorDevice and queries basic information. Args:: host: A valid hostname (IP address or DNS-resolvable name) to an MC-D...
"""This provides a specific telnet-controlled implementation of AttenuatorDevice for Mini-Circuits RC-DAT attenuators. Attributes: path_count: The number of signal attenuation path this device has. """ def __init__(self, path_count=1): self.path_count = path_count # The telnet c...
identifier_body
minicircuits.py
#!/usr/bin/env python3.4 # # Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
def set_atten(self, idx, value): """Sets the attenuation value for a particular signal path. Args: idx: Zero-based index int which is the identifier for a particular signal path in an instrument. For instruments that only has one channel, this is igno...
self._telnet_client.close()
conditional_block
minicircuits.py
#!/usr/bin/env python3.4 # # Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
(self, path_count=1): self.path_count = path_count # The telnet client used to communicate with the attenuator device. self._telnet_client = telnet_client.TelnetClient( tx_cmd_separator="\r\n", rx_cmd_separator="\r\n", prompt="") @property def is_open(self): """This ...
__init__
identifier_name
SyntheticsLink.d.ts
// tslint:disable:no-single-declare-module js installs to root of node_modules declare module 'SyntheticsLink' { export = SyntheticsLink; /** * This class handles the creation of result for Synthetics Link. For each link, add url, text, parent url, status and failure reason using the methods below. * ...
withText(text: string): SyntheticsLink; withParentUrl(parentUrl: any): SyntheticsLink; withStatusCode(statusCode: any): SyntheticsLink; withStatusText(statusText: any): SyntheticsLink; withFailureReason(failureReason: any): SyntheticsLink; withScreenshotResult(screenshotR...
failureReason: string; screenshots: any[]; withLinkNum(linkNum: number): SyntheticsLink; withUrl(url: string): SyntheticsLink;
random_line_split
SyntheticsLink.d.ts
// tslint:disable:no-single-declare-module js installs to root of node_modules declare module 'SyntheticsLink' { export = SyntheticsLink; /** * This class handles the creation of result for Synthetics Link. For each link, add url, text, parent url, status and failure reason using the methods below. * ...
{ constructor(url: string); linkNum: number; url: string; text: string; parentUrl: string; status: { statusCode: string; statusText: string; }; failureReason: string; screenshots: any[]; withLinkNum(linkNum: number)...
SyntheticsLink
identifier_name
get-model-evaluation-tabular-classification.js
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
// Configure the parent resources const name = `projects/${project}/locations/${location}/models/${modelId}/evaluations/${evaluationId}`; const request = { name, }; // Get model evaluation request const [response] = await modelServiceClient.getModelEvaluation(request); console.log('G...
// Instantiates a client const modelServiceClient = new ModelServiceClient(clientOptions); async function getModelEvaluationTabularClassification() {
random_line_split
get-model-evaluation-tabular-classification.js
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
else { for (const meanAttribution of meanAttributions) { console.log('\t\tMean attribution'); console.log( `\t\t\tBaseline output value : \ ${meanAttribution.baselineOutputValue}` ); console.log( `\t\t\tInstance output value : \ ...
{ console.log('\t\t\t []'); }
conditional_block
get-model-evaluation-tabular-classification.js
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
(modelId, evaluationId, project, location = 'us-central1') { // [START aiplatform_get_model_evaluation_tabular_classification_sample] /** * TODO(developer): Uncomment these variables before running the sample * (not necessary if passing values as arguments). To obtain evaluationId, * instantiate the client...
main
identifier_name
get-model-evaluation-tabular-classification.js
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
console.log('\t\t{}'); } else { const meanAttributions = modelExplanation.meanAttributions; if (!meanAttributions) { console.log('\t\t\t []'); } else { for (const meanAttribution of meanAttributions) { console.log('\t\tMean attribution'); console.log( ...
{ // Configure the parent resources const name = `projects/${project}/locations/${location}/models/${modelId}/evaluations/${evaluationId}`; const request = { name, }; // Get model evaluation request const [response] = await modelServiceClient.getModelEvaluation(request); console.log(...
identifier_body
videojs-media-sources.js
(function(window){ var urlCount = 0, NativeMediaSource = window.MediaSource || window.WebKitMediaSource || {}, nativeUrl = window.URL || {}, EventEmitter, flvCodec = /video\/flv; codecs=["']vp6,aac["']/, objectUrlPrefix = 'blob:vjs-media-source/'; EventEmitter = function(){}; EventE...
}; // Source Buffer videojs.SourceBuffer = function(source){ videojs.SourceBuffer.prototype.init.call(this); this.source = source; this.buffer = []; }; videojs.SourceBuffer.prototype = new EventEmitter(); // accept video data and pass to the video (swf) object videojs.SourceBuffer.prototype...
{ throw new Error('Media Source not found (Video.js)'); }
conditional_block
videojs-media-sources.js
(function(window){ var urlCount = 0, NativeMediaSource = window.MediaSource || window.WebKitMediaSource || {}, nativeUrl = window.URL || {}, EventEmitter, flvCodec = /video\/flv; codecs=["']vp6,aac["']/, objectUrlPrefix = 'blob:vjs-media-source/'; EventEmitter = function(){}; EventE...
} this.sourceBuffers.push(sourceBuffer); return sourceBuffer; }; videojs.MediaSource.prototype.endOfStream = function(){ this.swfObj.vjs_endOfStream(); this.readyState = 'ended'; }; // store references to the media sources so they can be connected // to a video element (a swf object) v...
sourceBuffer = this.nativeSource.addSourceBuffer.apply(this.nativeSource, arguments);
random_line_split
network_common.py
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
def __call__(self, values): objects = list() for value in values: if isinstance(value, dict): for name, attr in iteritems(self._attributes): if attr.get('required') and name not in value: raise ValueError('missing required at...
self._attributes = attrs self.attr_names = frozenset(self._attributes.keys()) for name, attr in iteritems(self._attributes): if attr.get('key'): attr['required'] = True
identifier_body
network_common.py
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
for name, attr in iteritems(self._attributes): if attr.get('key'): attr['required'] = True def __call__(self, value): if isinstance(value, dict): unknown = set(value.keys()).difference(self.attr_names) if unknown: raise ValueError(...
def __init__(self, attrs): self._attributes = attrs self.attr_names = frozenset(self._attributes.keys())
random_line_split
network_common.py
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
(self, attrs): self._attributes = attrs self.attr_names = frozenset(self._attributes.keys()) for name, attr in iteritems(self._attributes): if attr.get('key'): attr['required'] = True def __call__(self, value): if isinstance(value, dict): unkn...
__init__
identifier_name
network_common.py
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
if not value.get(name): value[name] = attr.get('default') objects.append(value) else: obj = {} for name, attr in iteritems(self._attributes): if attr.get('key'): obj[name]...
raise ValueError('missing required attr %s' % name)
conditional_block
timeit.py
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "Ricardo Ribeiro" __credits__ = ["Ricardo Ribeiro"] __license__ = "MIT" __version__ = "0.0" __maintainer__ = "Ricardo Ribeiro" __email__ = "ricardojvr@gmail.com" __status__ = "Development" import time from datetime import datetime, ...
return timed
ts = time.time() result = method(*args, **kw) te = time.time() time_elapsed = datetime(1,1,1) + timedelta(seconds=(te-ts) ) print("%s: %d:%d:%d:%d;%d" % (method.__name__, time_elapsed.day-1, time_elapsed.hour, time_elapsed.minute, time_elapsed.second, time_elapsed.microsecond)) return result
identifier_body
timeit.py
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "Ricardo Ribeiro" __credits__ = ["Ricardo Ribeiro"] __license__ = "MIT" __version__ = "0.0" __maintainer__ = "Ricardo Ribeiro" __email__ = "ricardojvr@gmail.com" __status__ = "Development" import time from datetime import datetime, ...
return result return timed
random_line_split
timeit.py
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "Ricardo Ribeiro" __credits__ = ["Ricardo Ribeiro"] __license__ = "MIT" __version__ = "0.0" __maintainer__ = "Ricardo Ribeiro" __email__ = "ricardojvr@gmail.com" __status__ = "Development" import time from datetime import datetime, ...
(*args, **kw): ts = time.time() result = method(*args, **kw) te = time.time() time_elapsed = datetime(1,1,1) + timedelta(seconds=(te-ts) ) print("%s: %d:%d:%d:%d;%d" % (method.__name__, time_elapsed.day-1, time_elapsed.hour, time_elapsed.minute, time_elapsed.second, time_elapsed.microsecond)) return result ...
timed
identifier_name
jump_search.py
""" Jump Search Find an element in a sorted array. """ import math def jump_search(arr,target): """ Worst-case Complexity: O(√n) (root(n)) All items in list must be sorted like binary search Find block that contains target value and search it linearly in that block It returns a first target valu...
# find target value in block while arr[block_prev] < target : block_prev += 1 if block_prev == min(block, length) : return -1 # if there is target value in array, return it if arr[block_prev] == target : return block_prev return -1
ock_prev = block block += block_size
conditional_block
jump_search.py
""" Jump Search Find an element in a sorted array. """ import math def jump_search(arr,target): """ Worst-case Complexity: O(√n) (root(n)) All items in list must be sorted like binary search Find block that contains target value and search it linearly in that block It returns a first target valu...
# return -1 means that array doesn't contain target value # find block that contains target value if arr[length - 1] < target: return -1 while block <= length and arr[block - 1] < target: block_prev = block block += block_size # find target value in block while arr[bl...
block_size = int(math.sqrt(length)) block_prev = 0 block= block_size
random_line_split
jump_search.py
""" Jump Search Find an element in a sorted array. """ import math def jump_search(arr,target):
while block <= length and arr[block - 1] < target: block_prev = block block += block_size # find target value in block while arr[block_prev] < target : block_prev += 1 if block_prev == min(block, length) : return -1 # if there is target value in array, retu...
""" Worst-case Complexity: O(√n) (root(n)) All items in list must be sorted like binary search Find block that contains target value and search it linearly in that block It returns a first target value in array reference: https://en.wikipedia.org/wiki/Jump_search """ length = len(arr) ...
identifier_body
jump_search.py
""" Jump Search Find an element in a sorted array. """ import math def
(arr,target): """ Worst-case Complexity: O(√n) (root(n)) All items in list must be sorted like binary search Find block that contains target value and search it linearly in that block It returns a first target value in array reference: https://en.wikipedia.org/wiki/Jump_search """ len...
jump_search
identifier_name
modal.ts
import {Injectable, Injector, ComponentFactoryResolver} from '@angular/core'; import {Ng2vModalStack} from './modal-stack'; import {Ng2vModalRef} from './modal-ref'; /** * Represent options available when opening new modal windows. */ export interface Ng2vModalOptions { /** * Whether a backdrop element should ...
/** * A service to open modal windows. Creating a modal is straightforward: create a template and pass it as an argument to * the "open" method! */ @Injectable() export class Ng2vModal { constructor( private _moduleCFR: ComponentFactoryResolver, private _injector: Injector, private _modalStack: Ng2vModalSta...
* Custom class to append to the modal window */ windowClass?: string; }
random_line_split
modal.ts
import {Injectable, Injector, ComponentFactoryResolver} from '@angular/core'; import {Ng2vModalStack} from './modal-stack'; import {Ng2vModalRef} from './modal-ref'; /** * Represent options available when opening new modal windows. */ export interface Ng2vModalOptions { /** * Whether a backdrop element should ...
(content: any, options: Ng2vModalOptions = {}): Ng2vModalRef { return this._modalStack.open(this._moduleCFR, this._injector, content, options); } }
open
identifier_name
modal.ts
import {Injectable, Injector, ComponentFactoryResolver} from '@angular/core'; import {Ng2vModalStack} from './modal-stack'; import {Ng2vModalRef} from './modal-ref'; /** * Represent options available when opening new modal windows. */ export interface Ng2vModalOptions { /** * Whether a backdrop element should ...
/** * Opens a new modal window with the specified content and using supplied options. Content can be provided * as a TemplateRef or a component type. If you pass a component type as content than instances of those * components can be injected with an instance of the Ng2vActiveModal class. You can use metho...
{}
identifier_body
mod.rs
extern crate portaudio; extern crate vorbis; pub use self::portaudio::PortAudio; mod file { use super::vorbis::*; use std::path::Path; use std::fs::File; use std::io::{Read, Seek}; pub const MUSIC_PATH: &'static str = "../../sound/music.ogg"; pub fn
(path: &Path) -> Decoder<File> { let file = File::open(path).unwrap(); Decoder::new(file).unwrap() } pub fn read_consolidated_packet<R: Read + Seek>(decoder: Decoder<R>) -> Option<Packet> { let mut iter = decoder.into_packets().map(|item| { item.unwrap() }); match iter.next() { ...
open_file
identifier_name
mod.rs
extern crate portaudio; extern crate vorbis; pub use self::portaudio::PortAudio; mod file { use super::vorbis::*;
use std::fs::File; use std::io::{Read, Seek}; pub const MUSIC_PATH: &'static str = "../../sound/music.ogg"; pub fn open_file(path: &Path) -> Decoder<File> { let file = File::open(path).unwrap(); Decoder::new(file).unwrap() } pub fn read_consolidated_packet<R: Read + Seek>(decode...
use std::path::Path;
random_line_split
mod.rs
extern crate portaudio; extern crate vorbis; pub use self::portaudio::PortAudio; mod file { use super::vorbis::*; use std::path::Path; use std::fs::File; use std::io::{Read, Seek}; pub const MUSIC_PATH: &'static str = "../../sound/music.ogg"; pub fn open_file(path: &Path) -> Decoder<File> { ...
else { try!(stream.start()); } self.stream = Some(stream); Ok(()) } else { use std::path::Path; let packet = file::read_consolidated_packet(file::open_file(Path::new(file::MUSIC_PATH))).unwrap(); let (data, out_settings, ch...
{ try!(stream.stop()); }
conditional_block
mod.rs
extern crate portaudio; extern crate vorbis; pub use self::portaudio::PortAudio; mod file { use super::vorbis::*; use std::path::Path; use std::fs::File; use std::io::{Read, Seek}; pub const MUSIC_PATH: &'static str = "../../sound/music.ogg"; pub fn open_file(path: &Path) -> Decoder<File> { ...
pub fn is_playing(&self) -> Result<bool, portaudio::Error> { if let Some(stream) = self.stream.as_ref() { stream.is_active() } else { Ok(false) } } }
{ if let Some(mut stream) = self.stream.take() { try!(stream.stop()); stream.close() } else { Ok(()) } }
identifier_body
rtio.rs
hood). pub struct
{ /// Path to file to be opened pub path: Path, /// Flags for file access mode (as per open(2)) pub flags: int, /// File creation mode, ignored unless O_CREAT is passed as part of flags pub mode: int } /// Description of what to do when a file handle is closed pub enum CloseBehavior { /// ...
FileOpenConfig
identifier_name
rtio.rs
// option. This file may not be copied, modified, or distributed // except according to those terms. //! The EventLoop and internal synchronous I/O interface. use c_str::CString; use comm::{Sender, Receiver}; use kinds::Send; use libc::c_int; use libc; use mem; use ops::Drop; use option::{Option, Some, None}; use own...
// 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
random_line_split
angular-dropdown.directive.ts
import { Observable, BehaviorSubject, of } from 'rxjs'; import { skip, first, filter } from 'rxjs/operators'; import { Component, Directive, Attribute, Inject, Input, Output, ElementRef, AfterViewInit, OnChanges, ContentChild, SimpleChanges, EventEmitter, QueryList, ViewContainerRef, forw...
const dropdownElement = this.dropdownElement; if (!dropdownElement || !this.triggerElement) { return null; } const _calculatePosition = this.renderInPlace ? this.calculateInPlacePosition : this.calculatePosition; const options = { horizontalPosition: this.horizontalPositi...
{ return null; }
conditional_block
angular-dropdown.directive.ts
import { Observable, BehaviorSubject, of } from 'rxjs'; import { skip, first, filter } from 'rxjs/operators'; import { Component, Directive, Attribute, Inject, Input, Output, ElementRef, AfterViewInit, OnChanges, ContentChild, SimpleChanges, EventEmitter, QueryList, ViewContainerRef, forw...
} private initializeId(id?: string): void { if (id) { this.id = this.uniqueId = id; } else { this.uniqueId = generateDropdownId(); this.id = `ng-dropdown-${this.uniqueId}`; } } private createDefaultWormholeOutlet(): void { if (!this.document.getElementById('ng-dropdown-outlet...
return changes;
random_line_split
angular-dropdown.directive.ts
import { Observable, BehaviorSubject, of } from 'rxjs'; import { skip, first, filter } from 'rxjs/operators'; import { Component, Directive, Attribute, Inject, Input, Output, ElementRef, AfterViewInit, OnChanges, ContentChild, SimpleChanges, EventEmitter, QueryList, ViewContainerRef, forw...
(): HTMLElement | null { return this.document.getElementById(this.dropdownId); } @ContentChild(forwardRef(() => AngularDropdownContentComponent)) private dropdownContent?: AngularDropdownContentComponent; private uniqueId: number | string | null = null; private width: number | null = null; private doc...
dropdownElement
identifier_name
angular-dropdown.directive.ts
import { Observable, BehaviorSubject, of } from 'rxjs'; import { skip, first, filter } from 'rxjs/operators'; import { Component, Directive, Attribute, Inject, Input, Output, ElementRef, AfterViewInit, OnChanges, ContentChild, SimpleChanges, EventEmitter, QueryList, ViewContainerRef, forw...
enable(): void { this.disabled = false; } reposition = (): AngularDropdownPositionChanges | null => { if (!this._isOpen$.getValue()) { return null; } const dropdownElement = this.dropdownElement; if (!dropdownElement || !this.triggerElement) { return null; } const _cal...
{ this.disabled = true; this.close(); }
identifier_body
next.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::I...
// type Item = U::Item; // // #[inline] // fn next(&mut self) -> Option<U::Item> { // loop { // if let Some(ref mut inner) = self.frontiter { // if let Some(x) = inner.by_ref().next() { // return Some(x) // ...
// impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F> // where F: FnMut(I::Item) -> U, // {
random_line_split
next.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::I...
}
{ let a: A<T> = A { begin: 0, end: 10 }; let f: F = F; let mut flat_map: FlatMap<A<T>, U, F> = a.flat_map::<U, F>(f); for n in 0 .. 10 { for i in 0..n { let x: Option<<U as IntoIterator>::Item> = flat_map.next(); match x { Some(v) => { assert_eq!(v, i); } None => { assert!(false); } } }...
identifier_body
next.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; struct
<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } els...
A
identifier_name
next.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::I...
None => { assert!(false); } } } } assert_eq!(flat_map.next(), None::<Item>); } }
{ assert_eq!(v, i); }
conditional_block
issue-5554.rs
// Copyright 2013 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 ...
{ constants!(); }
identifier_body
issue-5554.rs
// Copyright 2013 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 ...
<T> { a: T, } // reordering these bounds stops the ICE // // nmatsakis: This test used to have the bounds Default + PartialEq + // Default, but having duplicate bounds became illegal. impl<T: Default + PartialEq> Default for X<T> { fn default() -> X<T> { X { a: Default::default() } } } macro_rules...
X
identifier_name
issue-5554.rs
// Copyright 2013 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 ...
// Default, but having duplicate bounds became illegal. impl<T: Default + PartialEq> Default for X<T> { fn default() -> X<T> { X { a: Default::default() } } } macro_rules! constants { () => { let _ : X<isize> = Default::default(); } } pub fn main() { constants!(); }
// reordering these bounds stops the ICE // // nmatsakis: This test used to have the bounds Default + PartialEq +
random_line_split
mercator.js
// @license // Redistribution and use in source and binary forms ... // Copyright 2012 Carnegie Mellon University. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of sou...
(lat) { return Math.log((1 + Math.sin(lat * Math.PI / 180)) / Math.cos(lat * Math.PI / 180)); } function rawUnprojectLat(y) { return (2 * Math.atan(Math.exp(y)) - Math.PI / 2) * 180 / Math.PI; } function interpolate(x, fromLow, fromHigh, toLow, toHigh) { return (x - fromLow) / (fromHigh - fromLow)...
rawProjectLat
identifier_name
mercator.js
// @license // Redistribution and use in source and binary forms ... // Copyright 2012 Carnegie Mellon University. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of sou...
function interpolate(x, fromLow, fromHigh, toLow, toHigh) { return (x - fromLow) / (fromHigh - fromLow) * (toHigh - toLow) + toLow; } this.latlngToPoint = function(latlng) { var x = interpolate(latlng.lng, west, east, 0, width); var y = interpolate(rawProjectLat(latlng.lat), rawProjectLat(north), r...
{ return (2 * Math.atan(Math.exp(y)) - Math.PI / 2) * 180 / Math.PI; }
identifier_body
mercator.js
// @license // Redistribution and use in source and binary forms ... // Copyright 2012 Carnegie Mellon University. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of sou...
return (2 * Math.atan(Math.exp(y)) - Math.PI / 2) * 180 / Math.PI; } function interpolate(x, fromLow, fromHigh, toLow, toHigh) { return (x - fromLow) / (fromHigh - fromLow) * (toHigh - toLow) + toLow; } this.latlngToPoint = function(latlng) { var x = interpolate(latlng.lng, west, east, 0, width); ...
} function rawUnprojectLat(y) {
random_line_split
values.rs
&mut CssWriter<W>) -> fmt::Result where W: Write { dest.write_str(self.0.as_ref()) } } /// Type used as the associated type in the `OneOrMoreSeparated` trait on a /// type to indicate that a serialized list of elements of this type is /// separated by commas. pub struct Comma; /// Type used as the associ...
{ return true; }
conditional_block
values.rs
T> where T: AsRef<str> + ?Sized + 'a, { #[inline] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { dest.write_str(self.0.as_ref()) } } /// Type used as the associated type in the `OneOrMoreSeparated` trait on a /// type to indicate that a serialized list of elements...
is_ok
identifier_name