file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
main.rs
use std::hash::{Hash, Hasher}; use std::collections::HashSet; #[derive(Debug, Clone, Copy)] struct Foo { elem: usize, } impl PartialEq for Foo { #[inline] fn eq(&self, other: &Self) -> bool { self as *const Self == other as *const Self } } impl Eq for Foo {} impl Hash for Foo { #[inline] fn hash<H: ...
let a = Foo { elem: 5 }; let b = a.clone(); let c = a; let mut set = HashSet::new(); assert!(a != b); assert!(a != c); assert!(b != c); if !set.insert(a) { unreachable!(); } if !set.insert(b) { unreachable!(); } if !set.insert(c) { unreachable!(); } println!("{:#?}", set); ...
fn main() {
random_line_split
main.rs
use std::hash::{Hash, Hasher}; use std::collections::HashSet; #[derive(Debug, Clone, Copy)] struct
{ elem: usize, } impl PartialEq for Foo { #[inline] fn eq(&self, other: &Self) -> bool { self as *const Self == other as *const Self } } impl Eq for Foo {} impl Hash for Foo { #[inline] fn hash<H: Hasher>(&self, state: &mut H) { (self as *const Self).hash(state); } } fn main() { let a = Fo...
Foo
identifier_name
main.rs
use std::hash::{Hash, Hasher}; use std::collections::HashSet; #[derive(Debug, Clone, Copy)] struct Foo { elem: usize, } impl PartialEq for Foo { #[inline] fn eq(&self, other: &Self) -> bool { self as *const Self == other as *const Self } } impl Eq for Foo {} impl Hash for Foo { #[inline] fn hash<H: ...
if !set.insert(c) { unreachable!(); } println!("{:#?}", set); }
{ unreachable!(); }
conditional_block
api_config_test.ts
// Copyright 2018 Google Inc. All Rights Reserved. // // 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
// limitations under the License. import {ApiConfig, apiConfigFactory} from './api_config'; describe('ApiConfig', () => { it('should generate a class with the correct properties', () => { const config = new ApiConfig('http://example.com', 'http://chrome-example.com'); expect(config.baseUrl).toBe('ht...
// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and
random_line_split
MSChooser.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ve...
} def __init__(self, items = [], loop = False): """Initialisation. items = set of items that can be iterated over. Must be finite. If an iterator is supplied, it is enumerated into a list during initialisation. """ super(Chooser,self).__init__() self...
Inboxes = { "inbox" : "receive commands", "control" : "" } Outboxes = { "outbox" : "emits chosen items", "signal" : ""
random_line_split
MSChooser.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ve...
def shutdown(self): if self.dataReady("control"): message = self.recv("control") if isinstance(message, shutdownMicroprocess): self.send(message, "signal") return True return False def main(self): try: self.send( self.items[...
"""Initialisation. items = set of items that can be iterated over. Must be finite. If an iterator is supplied, it is enumerated into a list during initialisation. """ super(Chooser,self).__init__() self.items = list(items) self.index = 0 self.loop = loop
identifier_body
MSChooser.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ve...
(Axon.Component.component): """Chooses items out of a set, as directed by commands sent to its inbox Emits the first item at initialisation, then whenever a command is received it emits another item (unless you're asking it to step beyond the start or end of the set) """ Inboxes = { "inb...
Chooser
identifier_name
MSChooser.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ve...
elif msg == "FIRST": self.index = 0 elif msg == "LAST": self.index = 1 try: self.send( self.items[self.index], "outbox") except IndexError: pass done = self.shutdown() __kamaelia_components__ = ( Ch...
if self.loop: self.index = len(self.items)-1 else: self.index = 0
conditional_block
test_multicast.rs
use mio::*; use mio::udp::*; use bytes::{Buf, RingBuf, SliceBuf}; use std::str; use std::net::{SocketAddr};
const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str, buf: SliceBuf<'static>, rx_buf: RingBuf } impl UdpHandler { fn new(tx: UdpSocket, rx: UdpSocket, msg: &'static str) -> UdpHandler { UdpHandler { ...
use super::localhost;
random_line_split
test_multicast.rs
use mio::*; use mio::udp::*; use bytes::{Buf, RingBuf, SliceBuf}; use std::str; use std::net::{SocketAddr}; use super::localhost; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str, buf: SliceBuf<'static>, rx_bu...
(tx: UdpSocket, rx: UdpSocket, msg: &'static str) -> UdpHandler { UdpHandler { tx: tx, rx: rx, msg: msg, buf: SliceBuf::wrap(msg.as_bytes()), rx_buf: RingBuf::new(1024) } } fn handle_read(&mut self, event_loop: &mut EventLoop<UdpHandle...
new
identifier_name
test_multicast.rs
use mio::*; use mio::udp::*; use bytes::{Buf, RingBuf, SliceBuf}; use std::str; use std::net::{SocketAddr}; use super::localhost; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str, buf: SliceBuf<'static>, rx_bu...
} impl Handler for UdpHandler { type Timeout = usize; type Message = (); fn ready(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, events: EventSet) { if events.is_readable() { self.handle_read(event_loop, token, events); } if events.is_writable() { ...
{ match token { SENDER => { self.tx.send_to(&mut self.buf, &self.rx.local_addr().unwrap()).unwrap(); }, _ => () } }
identifier_body
test_multicast.rs
use mio::*; use mio::udp::*; use bytes::{Buf, RingBuf, SliceBuf}; use std::str; use std::net::{SocketAddr}; use super::localhost; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str, buf: SliceBuf<'static>, rx_bu...
} } #[test] pub fn test_multicast() { debug!("Starting TEST_UDP_CONNECTIONLESS"); let mut event_loop = EventLoop::new().unwrap(); let addr = localhost(); let any = "0.0.0.0:0".parse().unwrap(); let tx = UdpSocket::bound(&any).unwrap(); let rx = UdpSocket::bound(&addr).unwrap(); info...
{ self.handle_write(event_loop, token, events); }
conditional_block
global.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/. */ //! Abstractions for global scopes. //! //! This module contains smart pointers to global scopes, to simplify writ...
(global: &GlobalRef) -> GlobalField { match *global { Window(window) => WindowField(JS::from_rooted(window)), Worker(worker) => WorkerField(JS::from_rooted(worker)), } } /// Create a stack-bounded root for this reference. pub fn root(&self) -> GlobalRoot { ma...
from_rooted
identifier_name
global.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/. */ //! Abstractions for global scopes. //! //! This module contains smart pointers to global scopes, to simplify writ...
} } impl GlobalField { /// Create a new `GlobalField` from a rooted reference. pub fn from_rooted(global: &GlobalRef) -> GlobalField { match *global { Window(window) => WindowField(JS::from_rooted(window)), Worker(worker) => WorkerField(JS::from_rooted(worker)), } ...
WorkerRoot(ref worker) => Worker(worker.root_ref()), }
random_line_split
utils.js
/*istanbul ignore next*/'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable =...
if (success) { resolve(response); } else { reject(response); } }); } /** * Returns an already rejected promise. * @example * EgoJSUtils.rejectedPromise('error message').catch((e...
*/ value: function _fullfilledPromise(success, response) { return new Promise(function (resolve, reject) {
random_line_split
utils.js
/*istanbul ignore next*/'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable =...
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * A set of utlity methods. * @abstract */ var EgoJSUtils = (function () { function EgoJSUtils() { _classCallCheck(this, EgoJSUtils); } ...
{ return obj && obj.__esModule ? obj : { default: obj }; }
identifier_body
utils.js
/*istanbul ignore next*/'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable =...
(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * A set of utlity methods. * @abstract */ var EgoJSUtils = (function () { function EgoJSUtils() { _classCallCheck(this, EgoJSUtils); } _createClass(EgoJSUtils, ...
_classCallCheck
identifier_name
utils.js
/*istanbul ignore next*/'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable =...
}); } /** * Returns an already rejected promise. * @example * EgoJSUtils.rejectedPromise('error message').catch((e) => { * // It will log 'error message' * console.log(e); * }); * * @param {*} response - The ob...
{ reject(response); }
conditional_block
Setup-lang-ru-debug.js
/********************** tine translations of Setup**********************/ Locale.Gettext.prototype._msgs['./LC_MESSAGES/Setup'] = new Locale.Gettext.PO(({ "" : "Project-Id-Version: Tine 2.0\nPOT-Creation-Date: 2008-05-17 22:12+0100\nPO-Revision-Date: 2012-09-19 08:58+0000\nLast-Translator: corneliusweiss <mail@corneli...
, "Home Template" : "" , "Password Scheme" : "Схема пароля" , "PLAIN-MD5" : "PLAIN-MD5" , "MD5-CRYPT" : "MD5-CRYPT" , "SHA1" : "SHA1" , "SHA256" : "SHA256" , "SSHA256" : "SSHA256" , "SHA512" : "SHA512" , "SSHA512" : "SSHA512" , "PLAIN" : "PLAIN" , "Performing Environment Checks..." : "Проведение проверок окру...
random_line_split
page-actions.js
/* Copyright 2016 Mozilla Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed u...
const lastIndex = PagesSelectors.getLastPinnedPageIndex(getState()); dispatch(setPageIndex(pageId, lastIndex)); // Set the `pinned` state *last*, so that the above selector // actually does what we want. dispatch(setPageUIState(pageId, { pinned: false })); }; } export function showPageSearch(page...
return (dispatch, getState) => { // When there's no pinned pages, the "last pinned page index" will be -1.
random_line_split
page-actions.js
/* Copyright 2016 Mozilla Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed u...
export function setPageDetails(pageId, pageDetails) { return { type: ActionTypes.SET_PAGE_DETAILS, pageId, pageDetails, }; } export function setPageMeta(pageId, pageMeta) { return { type: ActionTypes.SET_PAGE_META, pageId, pageMeta, }; } export function setPageState(pageId, pageState...
{ return { type: ActionTypes.SET_PAGE_INDEX, pageId, pageIndex, }; }
identifier_body
page-actions.js
/* Copyright 2016 Mozilla Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed u...
(pageId) { return dispatch => { dispatch(setPageUIState(pageId, { searchVisible: false })); dispatch(setPageUIState(pageId, { searchFocused: false })); }; } export function showCurrentPageSearch() { return (dispatch, getState) => { dispatch(showPageSearch(PagesSelectors.getSelectedPageId(getState()))...
hidePageSearch
identifier_name
util.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use std::io::{self, Error, ErrorKind}; use rusoto_core::{ region::Region, request::{HttpClient, HttpConfig}, }; use rusoto_credential::{ AutoRefreshingProvider, AwsCredentials, ChainProvider, CredentialsError, ProvideAwsCredentials, }; use...
Err(e) => e, }; let def_error = match def_creds.await { res @ Ok(_) => return res, Err(e) => e, }; Err(CredentialsError::new(format_args!( "Couldn't find AWS credentials in default sources ({}) or k8s environment ({}).", def_err...
res @ Ok(_) => return res,
random_line_split
util.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use std::io::{self, Error, ErrorKind}; use rusoto_core::{ region::Region, request::{HttpClient, HttpConfig}, }; use rusoto_credential::{ AutoRefreshingProvider, AwsCredentials, ChainProvider, CredentialsError, ProvideAwsCredentials, }; use...
(&self) -> Result<AwsCredentials, CredentialsError> { // Prefer the web identity provider first for the kubernetes environment. // Search for both in parallel. let web_creds = self.web_identity_provider.credentials(); let def_creds = self.default_provider.credentials(); let k8s_e...
credentials
identifier_name
util.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use std::io::{self, Error, ErrorKind}; use rusoto_core::{ region::Region, request::{HttpClient, HttpConfig}, }; use rusoto_credential::{ AutoRefreshingProvider, AwsCredentials, ChainProvider, CredentialsError, ProvideAwsCredentials, }; use...
} #[async_trait] impl ProvideAwsCredentials for DefaultCredentialsProvider { async fn credentials(&self) -> Result<AwsCredentials, CredentialsError> { // Prefer the web identity provider first for the kubernetes environment. // Search for both in parallel. let web_creds = self.web_identity...
{ DefaultCredentialsProvider { default_provider: ChainProvider::new(), web_identity_provider: WebIdentityProvider::from_k8s_env(), } }
identifier_body
Paper.js
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { chainPropTypes, integerPropType, deepmerge } from '@material-ui/util...
/* Styles applied to the root element. */ backgroundColor: theme.palette.background.paper, color: theme.palette.text.primary, transition: theme.transitions.create('box-shadow') }, !styleProps.square && { borderRadius: theme.shape.borderRadius }, styleProps.variant === 'outlined' && { border:...
overridesResolver: overridesResolver })(function (_ref) { var theme = _ref.theme, styleProps = _ref.styleProps; return _extends({
random_line_split
Paper.js
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { chainPropTypes, integerPropType, deepmerge } from '@material-ui/util...
return null; }), /** * If `true`, rounded corners are disabled. * @default false */ square: PropTypes.bool, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object, /** * The variant to use. * @default 'elevation' ...
{ return new Error("Material-UI: Combining `elevation={".concat(elevation, "}` with `variant=\"").concat(variant, "\"` has no effect. Either use `elevation={0}` or use a different `variant`.")); }
conditional_block
index.js
var net = require('net'); var fs = require("fs"); var child_process = require("child_process"); var local_port = 8893; //在本地创建一个server监听本地local_port端口 net.createServer(function (client) { //首先监听浏览器的数据发送事件,直到收到的数据包含完整的http请求头 var buffer = new Buffer(0); client.on('data',function(data) { buffer = ...
en;i++) //{ // if (b[i] == 0x0d && b[i+1] == 0x0a && b[i+2] == 0x0d && b[i+3] == 0x0a) // { // return i+4; // } //} var index = b.toString().indexOf("\r\n\r\n"); if(index !== -1) { return index+4; } return -1; }
ngth); //buf1.copy(re); //buf2.copy(re,buf1.length); //return re; var bufArr = Array.prototype.slice.call(arguments); return Buffer.concat(bufArr); } /* 从缓存中找到头部结束标记("\r\n\r\n")的位置 */ function buffer_find_body(b) { //for(var i=0,len=b.length-3;i < l
conditional_block
index.js
var net = require('net'); var fs = require("fs"); var child_process = require("child_process"); var local_port = 8893; //在本地创建一个server监听本地local_port端口 net.createServer(function (client) { //首先监听浏览器的数据发送事件,直到收到的数据包含完整的http请求头 var buffer = new Buffer(0); client.on('data',function(data) { buffer = ...
buffer = buffer_add(new Buffer(header,'utf8'),buffer.slice(_body_pos)); } //建立到目标服务器的连接 var server = net.createConnection(req.port, req.host); //交换服务器与浏览器的数据 client.on("data", function(data){ server.write(data); }); server.on("data", function(data){ client.wri...
random_line_split
index.js
var net = require('net'); var fs = require("fs"); var child_process = require("child_process"); var local_port = 8893; //在本地创建一个server监听本地local_port端口 net.createServer(function (client) { //首先监听浏览器的数据发送事件,直到收到的数据包含完整的http请求头 var buffer = new Buffer(0); client.on('data',function(data) { buffer = ...
identifier_name
index.js
var net = require('net'); var fs = require("fs"); var child_process = require("child_process"); var local_port = 8893; //在本地创建一个server监听本地local_port端口 net.createServer(function (client) { //首先监听浏览器的数据发送事件,直到收到的数据包含完整的http请求头 var buffer = new Buffer(0); client.on('data',function(data) { buffer = ...
if (b[i] == 0x0d && b[i+1] == 0x0a && b[i+2] == 0x0d && b[i+3] == 0x0a) // { // return i+4; // } //} var index = b.toString().indexOf("\r\n\r\n"); if(index !== -1) { return index+4; } return -1; }
]+)\s([^\s]+)\sHTTP\/(\d.\d)/); if (arr && arr[1] && arr[2] && arr[3]) { var host = s.match(/Host\:\s+([^\n\s\r]+)/)[1]; if (host) { var _p = host.split(':',2); return { method: arr[1], host:_p[0], port:_p[1]?_p[1]:80, path: arr[2],http...
identifier_body
express.js
'use strict'; /** * Module dependencies. */ var express = require('express'), mean = require('meanio'), consolidate = require('consolidate'), mongoStore = require('connect-mongo')(express), flash = require('connect-flash'), helpers = require('view-helpers'), config = require('./config'), ...
};
{ var routes_path = appPath + '/server/routes'; var walk = function(path) { fs.readdirSync(path).forEach(function(file) { var newPath = path + '/' + file; var stat = fs.statSync(newPath); if (stat.isFile()) { if (/(.*)\.(js$...
identifier_body
express.js
'use strict'; /** * Module dependencies. */ var express = require('express'), mean = require('meanio'), consolidate = require('consolidate'), mongoStore = require('connect-mongo')(express), flash = require('connect-flash'), helpers = require('view-helpers'), config = require('./config'), ...
app.use(function(err, req, res, next) { // Treat as 404 if (~err.message.indexOf('not found')) return next(); // Log it console.error(err.stack); // Error page res.status(500).render('500', { ...
app.use(mean.chainware.after); // Assume "not found" in the error msgs is a 404. this is somewhat // silly, but valid, you can do whatever you like, set properties, // use instanceof etc.
random_line_split
express.js
'use strict'; /** * Module dependencies. */ var express = require('express'), mean = require('meanio'), consolidate = require('consolidate'), mongoStore = require('connect-mongo')(express), flash = require('connect-flash'), helpers = require('view-helpers'), config = require('./config'), ...
() { var routes_path = appPath + '/server/routes'; var walk = function(path) { fs.readdirSync(path).forEach(function(file) { var newPath = path + '/' + file; var stat = fs.statSync(newPath); if (stat.isFile()) { if (/(.*)\.(...
bootstrapRoutes
identifier_name
express.js
'use strict'; /** * Module dependencies. */ var express = require('express'), mean = require('meanio'), consolidate = require('consolidate'), mongoStore = require('connect-mongo')(express), flash = require('connect-flash'), helpers = require('view-helpers'), config = require('./config'), ...
// assign the template engine to .html files app.engine('html', consolidate[config.templateEngine]); // set .html as the default extension app.set('view engine', 'html'); // Set views path, template engine and default layout app.set('views', config.root + '/server/views'); // Enable jso...
{ app.use(express.logger('dev')); }
conditional_block
CarinaInterface.ts
export interface ChannelUpdate { online?: boolean; featured?: boolean; featureLevel?: number; partnered?: boolean; audience?: "family" | "teen" | "18+"; viewersTotal?: number; viewersCurrent?: number; numFollowers?: number; typeId?: number; type?: GameType; } export interface ChannelFollowed {
user?: { id: number; username: string; }; } export interface ChannelSubscribed { user?: { username: string; }; totalMonths?: number; } export interface ChannelHosted { hoster?: { token?: string; }; } export interface ChannelFeatured { featured?: boolean; featureLevel?: number; } export interface Ga...
following?: boolean;
random_line_split
randomWalk.js
'use strict'; var _ = require('underscore'), Util = require('../../shared/util'), Base = require('./base'), Action = require('../../action'), Types = require('./types'); var _parent = Base.prototype; var RandomWalk = Util.extend(Base, { properties: ['walkPropability'], ...
switch (_.random(3)) { case 0: return new Action.Move({deltaX: 1}); case 1: return new Action.Move({deltaX: -1}); case 2: return new Action.Move({deltaY: 1}); case 3: return new Action.Move({deltaY:...
{ return null; }
conditional_block
randomWalk.js
'use strict'; var _ = require('underscore'), Util = require('../../shared/util'), Base = require('./base'), Action = require('../../action'), Types = require('./types'); var _parent = Base.prototype; var RandomWalk = Util.extend(Base, { properties: ['walkPropability'], ...
return new Action.Move({deltaX: -1}); case 2: return new Action.Move({deltaY: 1}); case 3: return new Action.Move({deltaY: -1}); } return null; } }); module.exports = RandomWalk;
switch (_.random(3)) { case 0: return new Action.Move({deltaX: 1}); case 1:
random_line_split
event.ts
import { AxisScale } from '@visx/axis'; import { ScaleInput } from '@visx/scale'; import { Emitter } from 'mitt'; export type EventEmitterContextType = Emitter; /** Arguments for findNearestDatum* functions. */ export type NearestDatumArgs< XScale extends AxisScale, YScale extends AxisScale, Datum extends objec...
/** Return type for nearestDatum* functions. */ export type NearestDatumReturnType<Datum extends object> = { datum: Datum; index: number; distanceX: number; distanceY: number; } | null;
random_line_split
trait-inheritance-cross-trait-call.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let a = &A { x: 3 }; assert!(a.g() == 10); }
main
identifier_name
trait-inheritance-cross-trait-call.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
impl Foo for A { fn f(&self) -> int { 10 } } impl Bar for A { // Testing that this impl can call the impl of Foo fn g(&self) -> int { self.f() } } pub fn main() { let a = &A { x: 3 }; assert!(a.g() == 10); }
struct A { x: int }
random_line_split
myDevice.py
#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_pat...
#self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_i...
if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the...
conditional_block
myDevice.py
#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils')
sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProto...
random_line_split
myDevice.py
#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_pat...
def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSens...
global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze)
identifier_body
myDevice.py
#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_pat...
(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(se...
register
identifier_name
newTests.js
"use strict" const should = require('should') const rewire = require('rewire') const IC = rewire('../commands/new.js') describe('New command',() => { let mockFS = { outputFile : (filename,content) => { console.log(`mock writing to ${filename}`); return { then : () => { return { catch : () ...
cb(undefined,{editor : mockEditorCommand}) } } let dummyLaunchEditor = _ => {} let commonMocks = { fs : mockFS , propUtil : mockPropUtil , launchEditorForADR : dummyLaunchEditor , writeADR : (adrFilename,newADR) => { console.log(`Pretending to write to ${adrFilename}`)} } function...
let mockEditorCommand = "mockEditor" let mockPropUtil = { parse : (file,opts,cb) => {
random_line_split
newTests.js
"use strict" const should = require('should') const rewire = require('rewire') const IC = rewire('../commands/new.js') describe('New command',() => { let mockFS = { outputFile : (filename,content) => { console.log(`mock writing to ${filename}`); return { then : () => { return { catch : () ...
it("Should fail if passed an invalid title - that can't be used as a filename", () => { let revert = IC.__set__({ findADRDir : (startFrom, callback,notFoundHandler) => { callback('.') } , withAllADRFiles : (callback) => { callback(['1-adr1.md','2-adr2.md'])} }) let block = () => {IC(["bla",...
{ let copy = {} for (var k in commonMocks) copy[k] = commonMocks[k] for (var j in specificMocks) copy[j] = specificMocks[j] return copy; }
identifier_body
newTests.js
"use strict" const should = require('should') const rewire = require('rewire') const IC = rewire('../commands/new.js') describe('New command',() => { let mockFS = { outputFile : (filename,content) => { console.log(`mock writing to ${filename}`); return { then : () => { return { catch : () ...
(specificMocks) { let copy = {} for (var k in commonMocks) copy[k] = commonMocks[k] for (var j in specificMocks) copy[j] = specificMocks[j] return copy; } it("Should fail if passed an invalid title - that can't be used as a filename", () => { let revert = IC.__set__({ findADRDir : (startF...
modifiedCommonMocks
identifier_name
test.py
# -*- coding: utf-8 -*- # Copyright(C) 2010-2011 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your...
self.backend.get_torrent_file(l[0].id)
conditional_block
test.py
# -*- coding: utf-8 -*- # Copyright(C) 2010-2011 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your...
(self): l = list(self.backend.iter_torrents('sex')) if len(l) > 0: self.backend.get_torrent_file(l[0].id)
test_torrent
identifier_name
test.py
# -*- coding: utf-8 -*- # Copyright(C) 2010-2011 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your...
l = list(self.backend.iter_torrents('sex')) if len(l) > 0: self.backend.get_torrent_file(l[0].id)
identifier_body
test.py
# -*- coding: utf-8 -*- # Copyright(C) 2010-2011 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your...
if len(l) > 0: self.backend.get_torrent_file(l[0].id)
random_line_split
constants.ts
// TODO:vsavkin Use enums after switching to TypeScript import {StringWrapper, normalizeBool, isBlank} from 'angular2/src/facade/lang'; /** * CHECK_ONCE means that after calling detectChanges the mode of the change detector * will become CHECKED. */ export const CHECK_ONCE: string = "CHECK_ONCE"; /** * CHECKED me...
/** * CHECK_ALWAYS means that after calling detectChanges the mode of the change detector * will remain CHECK_ALWAYS. */ export const CHECK_ALWAYS: string = "ALWAYS_CHECK"; /** * DETACHED means that the change detector sub tree is not a part of the main tree and * should be skipped. */ export const DETACHED: str...
*/ export const CHECKED: string = "CHECKED";
random_line_split
constants.ts
// TODO:vsavkin Use enums after switching to TypeScript import {StringWrapper, normalizeBool, isBlank} from 'angular2/src/facade/lang'; /** * CHECK_ONCE means that after calling detectChanges the mode of the change detector * will become CHECKED. */ export const CHECK_ONCE: string = "CHECK_ONCE"; /** * CHECKED me...
/** * This is an experimental feature. Works only in Dart. */ export const ON_PUSH_OBSERVE = "ON_PUSH_OBSERVE";
{ return isBlank(changeDetectionStrategy) || StringWrapper.equals(changeDetectionStrategy, DEFAULT); }
identifier_body
constants.ts
// TODO:vsavkin Use enums after switching to TypeScript import {StringWrapper, normalizeBool, isBlank} from 'angular2/src/facade/lang'; /** * CHECK_ONCE means that after calling detectChanges the mode of the change detector * will become CHECKED. */ export const CHECK_ONCE: string = "CHECK_ONCE"; /** * CHECKED me...
(changeDetectionStrategy: string): boolean { return isBlank(changeDetectionStrategy) || StringWrapper.equals(changeDetectionStrategy, DEFAULT); } /** * This is an experimental feature. Works only in Dart. */ export const ON_PUSH_OBSERVE = "ON_PUSH_OBSERVE";
isDefaultChangeDetectionStrategy
identifier_name
VisualizeHistory.py
import matplotlib, os, errno # IF WE ARE ON SERVER WITH NO DISPLAY, then we use Agg: #print matplotlib.get_backend() if not('DISPLAY' in os.environ): matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np def visualize_history(hi, show=True, save=False, save_path='', show_also='', custom_title=N...
# list all data in history print(hi.keys()) # summarize history for loss plt.plot(hi['loss']) plt.plot(hi['val_loss']) if show_also <> '': plt.plot(hi[show_also], linestyle='dotted') plt.plot(hi['val_'+show_also], linestyle='dotted') if custom_title is None: plt.tit...
'''
random_line_split
VisualizeHistory.py
import matplotlib, os, errno # IF WE ARE ON SERVER WITH NO DISPLAY, then we use Agg: #print matplotlib.get_backend() if not('DISPLAY' in os.environ):
import matplotlib.pyplot as plt import numpy as np def visualize_history(hi, show=True, save=False, save_path='', show_also='', custom_title=None): # Visualize history of Keras model run. ''' Example calls: hi = model.fit(...) saveHistory(hi.history, 'tmp_saved_history.npy') visualize_histor...
matplotlib.use("Agg")
conditional_block
VisualizeHistory.py
import matplotlib, os, errno # IF WE ARE ON SERVER WITH NO DISPLAY, then we use Agg: #print matplotlib.get_backend() if not('DISPLAY' in os.environ): matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np def visualize_history(hi, show=True, save=False, save_path='', show_also='', custom_title=N...
(filename): # Load history object loaded = np.load(open(filename)) return loaded[()]['S']
loadHistory
identifier_name
VisualizeHistory.py
import matplotlib, os, errno # IF WE ARE ON SERVER WITH NO DISPLAY, then we use Agg: #print matplotlib.get_backend() if not('DISPLAY' in os.environ): matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np def visualize_history(hi, show=True, save=False, save_path='', show_also='', custom_title=N...
def loadHistory(filename): # Load history object loaded = np.load(open(filename)) return loaded[()]['S']
if not os.path.exists(os.path.dirname(filename)): try: os.makedirs(os.path.dirname(filename)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise to_be_saved = data = {'S': history_dict} np.save(open(filename, 'w'), t...
identifier_body
parse_grammar.rs
use super::grammars::{InputGrammar, PrecedenceEntry, Variable, VariableType}; use super::rules::{Precedence, Rule}; use anyhow::{anyhow, Result}; use serde::Deserialize; use serde_json::{Map, Value}; #[derive(Deserialize)] #[serde(tag = "type")] #[allow(non_camel_case_types)] enum RuleJSON { ALIAS { conten...
{ pub(crate) name: String, rules: Map<String, Value>, #[serde(default)] precedences: Vec<Vec<RuleJSON>>, #[serde(default)] conflicts: Vec<Vec<String>>, #[serde(default)] externals: Vec<RuleJSON>, #[serde(default)] extras: Vec<RuleJSON>, #[serde(default)] inline: Vec<Stri...
GrammarJSON
identifier_name
parse_grammar.rs
use super::grammars::{InputGrammar, PrecedenceEntry, Variable, VariableType}; use super::rules::{Precedence, Rule}; use anyhow::{anyhow, Result}; use serde::Deserialize; use serde_json::{Map, Value}; #[derive(Deserialize)] #[serde(tag = "type")] #[allow(non_camel_case_types)] enum RuleJSON { ALIAS { conten...
"type": "REPEAT1", "content": { "type": "SYMBOL", "name": "statement" } }, "statement": { "type": "STRING", "value": "foo" }...
random_line_split
filter_by_group.js
/** * AUTO-GENERATED - DO NOT EDIT. Source: https://github.com/gpuweb/cts **/ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } export class FilterByGroup { ...
matches(spec, testcase) { throw new Error('unimplemented'); } async iterate(loader) { const specs = await loader.listing(this.suite); const entries = []; const suite = this.suite; for (const { path, description } of specs) { if (path.startsWith(this.groupPrefix)) { ...
{ _defineProperty(this, "suite", void 0); _defineProperty(this, "groupPrefix", void 0); this.suite = suite; this.groupPrefix = groupPrefix; }
identifier_body
filter_by_group.js
/** * AUTO-GENERATED - DO NOT EDIT. Source: https://github.com/gpuweb/cts **/ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } export class FilterByGroup { ...
} return entries; } } //# sourceMappingURL=filter_by_group.js.map
}); }
random_line_split
filter_by_group.js
/** * AUTO-GENERATED - DO NOT EDIT. Source: https://github.com/gpuweb/cts **/ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else
return obj; } export class FilterByGroup { constructor(suite, groupPrefix) { _defineProperty(this, "suite", void 0); _defineProperty(this, "groupPrefix", void 0); this.suite = suite; this.groupPrefix = groupPrefix; } matches(spec, testcase) { throw new Error('unimplemented'); } async...
{ obj[key] = value; }
conditional_block
filter_by_group.js
/** * AUTO-GENERATED - DO NOT EDIT. Source: https://github.com/gpuweb/cts **/ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } export class
{ constructor(suite, groupPrefix) { _defineProperty(this, "suite", void 0); _defineProperty(this, "groupPrefix", void 0); this.suite = suite; this.groupPrefix = groupPrefix; } matches(spec, testcase) { throw new Error('unimplemented'); } async iterate(loader) { const specs = await...
FilterByGroup
identifier_name
vec-matching.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 x = [1, 2, 3]; match x { [a, b, c..] => { assert_eq!(a, 1); assert_eq!(b, 2); let expected: &[_] = &[3]; assert_eq!(c, expected); } } match x { [a.., b, c] => { let expected: &[_] = &[1]; assert_eq!(a, ex...
random_line_split
vec-matching.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 ...
pub fn main() { a(); b(); c(); d(); e(); }
{ let x: &[int] = &[1, 2, 3]; match x { [1, 2] => (), [..] => () } }
identifier_body
vec-matching.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 x: &[int] = &[1, 2, 3]; match x { [1, 2] => (), [..] => () } } pub fn main() { a(); b(); c(); d(); e(); }
e
identifier_name
test_0050_general.js
/* 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/. */ /* General nsIUpdateCheckListener onload and onerror error code and statusText Tests */ // Errors tested: // ...
// port not allowed - NS_ERROR_PORT_ACCESS_NOT_ALLOWED (2152398867) function run_test_pt9() { run_test_helper(run_test_pt10, AUS_Cr.NS_ERROR_PORT_ACCESS_NOT_ALLOWED, "testing port not allowed"); } // no data was received - NS_ERROR_NET_RESET (2152398868) function run_test_pt10() { run_test_help...
{ run_test_helper(run_test_pt9, AUS_Cr.NS_ERROR_OFFLINE, "testing network offline"); }
identifier_body
test_0050_general.js
/* 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/. */ /* General nsIUpdateCheckListener onload and onerror error code and statusText Tests */ // Errors tested: // ...
run_test_helper(run_test_pt16, 2153390069, "testing server certificate expired"); } // network is offline - NS_ERROR_DOCUMENT_NOT_CACHED (2152398918) function run_test_pt16() { run_test_helper(run_test_pt17, AUS_Cr.NS_ERROR_DOCUMENT_NOT_CACHED, "testing network is offline"); } ...
function run_test_pt15() {
random_line_split
test_0050_general.js
/* 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/. */ /* General nsIUpdateCheckListener onload and onerror error code and statusText Tests */ // Errors tested: // ...
(aNextRunFunc, aExpectedStatusCode, aMsg) { gStatusCode = null; gStatusText = null; gCheckFunc = check_test_helper; gNextRunFunc = aNextRunFunc; gExpectedStatusCode = aExpectedStatusCode; logTestInfo(aMsg, Components.stack.caller); gUpdateChecker.checkForUpdates(updateCheckListener, true); } function che...
run_test_helper
identifier_name
main.rs
fn main() { println!("Hello, world!"); let mut x: i32 = 5; x = 10; print_num(5); add_num(4, 6); let x1: i32; x1 = add_one(7); let f: fn(i32) -> i32 = add_one; let ff = add_one; let x2 = f(6); let x3 = ff(8); let x_bool = true; let y_bool: bool = false; pri...
; // y: i32 println!("y is {}", y); // Or let y = if x == 5 { 10 } else { 15 }; // y: i32 // Rust provide 3 kinds of iterative activity: loop, while, for. let mut x = 5; // mut x: i32 let mut done = false; // mut done: bool while !done { x += x - 3; println!("x iterativ...
{ 15 }
conditional_block
main.rs
fn main() { println!("Hello, world!"); let mut x: i32 = 5; x = 10; print_num(5); add_num(4, 6); let x1: i32; x1 = add_one(7); let f: fn(i32) -> i32 = add_one; let ff = add_one; let x2 = f(6); let x3 = ff(8); let x_bool = true; let y_bool: bool = false; pri...
(x: i32) -> i32 { x }
foo
identifier_name
main.rs
fn main() { println!("Hello, world!"); let mut x: i32 = 5; x = 10; print_num(5); add_num(4, 6); let x1: i32; x1 = add_one(7); let f: fn(i32) -> i32 = add_one; let ff = add_one; let x2 = f(6); let x3 = ff(8); let x_bool = true; let y_bool: bool = false; pri...
fn add_num(x: i32, y: i32){ println!("sum is {}", x + y); } fn add_one(x: i32) -> i32{ x + 1 } fn foo(x: i32) -> i32 { x }
{ println!("x is {}", x); }
identifier_body
main.rs
fn main() { println!("Hello, world!"); let mut x: i32 = 5; x = 10; print_num(5); add_num(4, 6); let x1: i32;
let x2 = f(6); let x3 = ff(8); let x_bool = true; let y_bool: bool = false; println!("x_bool's value: {}", x_bool); let x_char = 'H'; println!("x_char's value: {}", x_char); let a = [1, 2, 3]; //a: [i32; 3] let mut m = [1, 2, 3]; //m: [i32; 3] let aa = [0; 20]; //aa ...
x1 = add_one(7); let f: fn(i32) -> i32 = add_one; let ff = add_one;
random_line_split
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
"""Fast, reliable protein-coding gene prediction for prokaryotic genomes.""" homepage = "https://github.com/hyattpd/Prodigal" url = "https://github.com/hyattpd/Prodigal/archive/v2.6.3.tar.gz" version('2.6.3', '5181809fdb740e9a675cfdbb6c038466') def install(self, spec, prefix): make('...
identifier_body
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. #
# LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # 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 F...
# This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
random_line_split
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
(MakefilePackage): """Fast, reliable protein-coding gene prediction for prokaryotic genomes.""" homepage = "https://github.com/hyattpd/Prodigal" url = "https://github.com/hyattpd/Prodigal/archive/v2.6.3.tar.gz" version('2.6.3', '5181809fdb740e9a675cfdbb6c038466') def install(self, spec, ...
Prodigal
identifier_name
csv.py
class CSVWorksheet(WorksheetBase): def __init__(self, raw_sheet, ordinal): super().__init__(raw_sheet, ordinal) self.name = "Sheet 1" self.nrows = len(self.raw_sheet) self.ncols = max([len(r) for r in self.raw_sheet]) def parse_cell(self, cell, coords, cell_mode=CellMode.cooked): try: re...
import csv from . import WorksheetBase, WorkbookBase, CellMode
random_line_split
csv.py
import csv from . import WorksheetBase, WorkbookBase, CellMode class CSVWorksheet(WorksheetBase): def __init__(self, raw_sheet, ordinal): super().__init__(raw_sheet, ordinal) self.name = "Sheet 1" self.nrows = len(self.raw_sheet) self.ncols = max([len(r) for r in self.raw_sheet]) def
(self, cell, coords, cell_mode=CellMode.cooked): try: return int(cell) except ValueError: pass try: return float(cell) except ValueError: pass # TODO Check for dates? return cell def get_row(self, row_index): return self.raw_sheet[row_index] class CSVWorkbook(Wor...
parse_cell
identifier_name
csv.py
import csv from . import WorksheetBase, WorkbookBase, CellMode class CSVWorksheet(WorksheetBase): def __init__(self, raw_sheet, ordinal): super().__init__(raw_sheet, ordinal) self.name = "Sheet 1" self.nrows = len(self.raw_sheet) self.ncols = max([len(r) for r in self.raw_sheet]) def parse_cell(s...
def get_row(self, row_index): return self.raw_sheet[row_index] class CSVWorkbook(WorkbookBase): def iterate_sheets(self): with open(self.filename, "r") as rf: reader = csv.reader(rf) yield list(reader) def get_worksheet(self, raw_sheet, index): return CSVWorksheet(raw_sheet, index)
try: return int(cell) except ValueError: pass try: return float(cell) except ValueError: pass # TODO Check for dates? return cell
identifier_body
mapper.py
import sys from geopy import Point from django.apps import apps as django_apps from django.core.exceptions import ImproperlyConfigured from django.core.management.color import color_style from .geo_mixin import GeoMixin LANDMARK_NAME = 0 LATITUDE = 2 LETTERS = list(map(chr, range(65, 91))) LONGITUDE = 1 style = co...
self.load() def __repr__(self): return 'Mapper({0.map_area!r})'.format(self) def __str__(self): return '({0.map_area!r})'.format(self) def load(self): return None @property def __dict__(self): return { 'map_area': self.map_area, 'c...
self.item_model_cls = self.item_model self.item_label = self.item_model._meta.verbose_name
conditional_block
mapper.py
import sys from geopy import Point from django.apps import apps as django_apps from django.core.exceptions import ImproperlyConfigured from django.core.management.color import color_style from .geo_mixin import GeoMixin LANDMARK_NAME = 0 LATITUDE = 2 LETTERS = list(map(chr, range(65, 91))) LONGITUDE = 1 style = co...
(self): return self.radius def point_in_map_area(self, point): """Return True if point is within mapper area radius.""" return self.point_in_radius( point, self.area_center_point, self.area_radius) def raise_if_not_in_map_area(self, point): self.raise_if_not_in_radi...
area_radius
identifier_name
mapper.py
import sys from geopy import Point from django.apps import apps as django_apps from django.core.exceptions import ImproperlyConfigured from django.core.management.color import color_style from .geo_mixin import GeoMixin LANDMARK_NAME = 0 LATITUDE = 2 LETTERS = list(map(chr, range(65, 91))) LONGITUDE = 1 style = co...
raise ImproperlyConfigured( f'Invalid mapper_model. Got None. See {repr(self)}.') try: self.item_model = django_apps.get_model(*mapper_model.split('.')) except LookupError as e: sys.stdout.write(style.WARNING( f'\n Warning. Lookup erro...
mapper_model = self.mapper_model or app_config.mapper_model if not mapper_model:
random_line_split
mapper.py
import sys from geopy import Point from django.apps import apps as django_apps from django.core.exceptions import ImproperlyConfigured from django.core.management.color import color_style from .geo_mixin import GeoMixin LANDMARK_NAME = 0 LATITUDE = 2 LETTERS = list(map(chr, range(65, 91))) LONGITUDE = 1 style = co...
@property def area_center_point(self): return Point(self.center_lat, self.center_lon) @property def area_radius(self): return self.radius def point_in_map_area(self, point): """Return True if point is within mapper area radius.""" return self.point_in_radius( ...
return { 'map_area': self.map_area, 'center_lat': self.center_lat, 'center_lon': self.center_lon, 'radius': self.radius}
identifier_body
webpack.config.js
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { app: './demo/app.js', css: './demo/app.scss' }, module: { rules: [ { test: /\.(js|jsx)$/, use: ['ng-annotate-loader', 'babel-loader'], parser: { amd: false...
], output: { path: path.resolve(__dirname, 'bundle'), filename: '[name].bundle.js', } };
inject: true, minify: false, })
random_line_split
test_discover.py
# Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
(loader, tests, pattern): ext_plugins = plugins.TempestTestPluginManager() suite = unittest.TestSuite() base_path = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0] base_path = os.path.split(base_path)[0] # Load local tempest tests for test_dir in ['api', 'scenario']: full_t...
load_tests
identifier_name
test_discover.py
# Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
return suite
suite.addTests(loader.discover(test_dir, pattern=pattern, top_level_dir=top_path))
conditional_block
test_discover.py
# Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
ext_plugins = plugins.TempestTestPluginManager() suite = unittest.TestSuite() base_path = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0] base_path = os.path.split(base_path)[0] # Load local tempest tests for test_dir in ['api', 'scenario']: full_test_dir = os.path.join(base_pa...
identifier_body
test_discover.py
# Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
import unittest from tempest.test_discover import plugins def load_tests(loader, tests, pattern): ext_plugins = plugins.TempestTestPluginManager() suite = unittest.TestSuite() base_path = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0] base_path = os.path.split(base_path)[0] # Load ...
import os
random_line_split
server.js
'use strict'; import Component from './component'; import VolumeAttachment from './volume-attachment'; import Port from './port'; import {isString} from './util'; const Server = function (properties) { if (!(this instanceof Server)) { return new Server(properties); } Component.call(this, { ports: [],...
} }; }; Server.prototype.getResources = function () { const { id, zone, name, flavor, keyPair, image, ports } = this.properties; const networks = ports.map(port => ({ port: Component.resolve(port) })); const properties = { flavor, image }; Object.assign( properties, n...
random_line_split
server.js
'use strict'; import Component from './component'; import VolumeAttachment from './volume-attachment'; import Port from './port'; import {isString} from './util'; const Server = function (properties) { if (!(this instanceof Server))
Component.call(this, { ports: [], ...properties }); }; Server.prototype = Object.create(Component.prototype); Server.prototype.constructor = Server; Server.prototype.getDependencies = function () { return [ ...this.dependencies, ...this.properties.ports ] }; Server.prototype.attachVolume ...
{ return new Server(properties); }
conditional_block
ripple-renderer.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ElementRef, NgZone} from '@angular/core'; import {Platform} from '@angular/cdk/platform'; import {ViewportRu...
else { // Subtract scroll values from the coordinates because calculations below // are always relative to the viewport rectangle. let scrollPosition = this._ruler.getViewportScrollPosition(); pageX -= scrollPosition.left; pageY -= scrollPosition.top; } let radius = config.radius...
{ pageX = containerRect.left + containerRect.width / 2; pageY = containerRect.top + containerRect.height / 2; }
conditional_block
ripple-renderer.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ElementRef, NgZone} from '@angular/core'; import {Platform} from '@angular/cdk/platform'; import {ViewportRu...
/** Fades out a ripple reference. */ fadeOutRipple(rippleRef: RippleRef) { // For ripples that are not active anymore, don't re-un the fade-out animation. if (!this._activeRipples.delete(rippleRef)) { return; } let rippleEl = rippleRef.element; rippleEl.style.transitionDuration = `${RI...
{ let containerRect = this._containerElement.getBoundingClientRect(); if (config.centered) { pageX = containerRect.left + containerRect.width / 2; pageY = containerRect.top + containerRect.height / 2; } else { // Subtract scroll values from the coordinates because calculations below ...
identifier_body
ripple-renderer.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ElementRef, NgZone} from '@angular/core'; import {Platform} from '@angular/cdk/platform'; import {ViewportRu...
() { this._activeRipples.forEach(ripple => ripple.fadeOut()); } /** Sets the trigger element and registers the mouse events. */ setTriggerElement(element: HTMLElement | null) { // Remove all previously register event listeners from the trigger element. if (this._triggerElement) { this._triggerE...
fadeOutAll
identifier_name
ripple-renderer.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ElementRef, NgZone} from '@angular/core'; import {Platform} from '@angular/cdk/platform'; import {ViewportRu...
/** Function being called whenever the pointer leaves the trigger. */ private onPointerLeave() { if (this._isPointerDown) { this.onPointerUp(); } } /** Function being called whenever the trigger is being touched. */ private onTouchstart(event: TouchEvent) { if (!this.rippleDisabled) { ...
random_line_split
temperaturas.py
# -*- coding: utf-8 -*- ''' Crea un programa que analice el fichero y muestre: - Los años y sus temperaturas (máxima, mínima y media), ordenados por año - Los años y su tempertura media, ordenados por temperatura en orden descendente - Crea un fichero html: Encabezado: Temperaturas de Zaragoza Fuente: (la url,...
stado_temp(f): listado = obtener_listado(f) listado.sort(key=itemgetter(1), reverse=True) for x in listado: if not '-' in x[1:4]: print x[0:4] def crear_html(f): import sys from operator import itemgetter try: # Instrucción con riesgo f = open('temperaturas_zaragoza....
= obtener_listado(f) listado.sort() for x in listado: print x[0:4] def li
identifier_body
temperaturas.py
# -*- coding: utf-8 -*- ''' Crea un programa que analice el fichero y muestre: - Los años y sus temperaturas (máxima, mínima y media), ordenados por año - Los años y su tempertura media, ordenados por temperatura en orden descendente - Crea un fichero html: Encabezado: Temperaturas de Zaragoza Fuente: (la url,...
stado_temp(f): listado = obtener_listado(f) listado.sort(key=itemgetter(1), reverse=True) for x in listado: if not '-' in x[1:4]: print x[0:4] def crear_html(f): import sys from operator import itemgetter try: # Instrucción con riesgo f = open('temperaturas_zaragoza....
0:4] def li
conditional_block
temperaturas.py
# -*- coding: utf-8 -*- ''' Crea un programa que analice el fichero y muestre: - Los años y sus temperaturas (máxima, mínima y media), ordenados por año - Los años y su tempertura media, ordenados por temperatura en orden descendente - Crea un fichero html: Encabezado: Temperaturas de Zaragoza Fuente: (la url,...
if not '-' in x[1:4]: print x[0:4] def crear_html(f): import sys from operator import itemgetter try: # Instrucción con riesgo f = open('temperaturas_zaragoza.txt') except IOError: print 'Error, el fichero temperaturas_zaragoza no existe' sys.exit() opcion = int(raw_input('...
listado.sort(key=itemgetter(1), reverse=True) for x in listado:
random_line_split
temperaturas.py
# -*- coding: utf-8 -*- ''' Crea un programa que analice el fichero y muestre: - Los años y sus temperaturas (máxima, mínima y media), ordenados por año - Los años y su tempertura media, ordenados por temperatura en orden descendente - Crea un fichero html: Encabezado: Temperaturas de Zaragoza Fuente: (la url,...
listado = obtener_listado(f) listado.sort(key=itemgetter(1), reverse=True) for x in listado: if not '-' in x[1:4]: print x[0:4] def crear_html(f): import sys from operator import itemgetter try: # Instrucción con riesgo f = open('temperaturas_zaragoza.txt') except IOErr...
temp(f):
identifier_name