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
menu.py
""" Menu Model [DiamondQuest] Defines a menu. Author(s): Wilfrantz Dede, Jason C. McDonald, Stanislav Schmidt """ # LICENSE (BSD-3-Clause) # Copyright (c) 2020 MousePaw Media. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the...
@property def text(self): return self.raw_text @property def text_attributes(self): return self.attributes class ButtonType(Enum): STATIC = 0 # text never changes SCROLL = 1 # left/right arrows scroll through options INPUT = 2 # user can type into button text class B...
# icon
random_line_split
menu.py
""" Menu Model [DiamondQuest] Defines a menu. Author(s): Wilfrantz Dede, Jason C. McDonald, Stanislav Schmidt """ # LICENSE (BSD-3-Clause) # Copyright (c) 2020 MousePaw Media. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the...
return None
conditional_block
menu.py
""" Menu Model [DiamondQuest] Defines a menu. Author(s): Wilfrantz Dede, Jason C. McDonald, Stanislav Schmidt """ # LICENSE (BSD-3-Clause) # Copyright (c) 2020 MousePaw Media. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the...
(cls, menu_type): """Select which menu to use by default.""" cls.menu_in_use = menu_type def __init__(self, title, items): self.title = TextItem(title) self.items = items self.selectable_items = [ i for i, item in enumerate(items) if isinstance(item, ButtonItem) ...
use_menu
identifier_name
menu.py
""" Menu Model [DiamondQuest] Defines a menu. Author(s): Wilfrantz Dede, Jason C. McDonald, Stanislav Schmidt """ # LICENSE (BSD-3-Clause) # Copyright (c) 2020 MousePaw Media. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the...
@property def selected_item_idx(self): if self.which_selected == -1: return -1 return self.selectable_items[self.which_selected] def __iter__(self): iter(self.items) @classmethod def select_next_item(cls): menu = cls.get_menu() n_items = len(me...
self.title = TextItem(title) self.items = items self.selectable_items = [ i for i, item in enumerate(items) if isinstance(item, ButtonItem) ] self.which_selected = 0 if len(self.selectable_items) > 0 else -1
identifier_body
issue-18959.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 ...
<T>(&self, _: &T) {} } #[inline(never)] fn foo(b: &Bar) { b.foo(&0us) } fn main() { let mut thing = Thing; let test: &Bar = &mut thing; //~ ERROR cannot convert to a trait object foo(test); }
foo
identifier_name
issue-18959.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except accordin...
random_line_split
loadBalancingPolicySelector.component.ts
import type { IComponentOptions, IController } from 'angular'; import { module } from 'angular'; import { chain, get, has, intersection, set, without } from 'lodash'; import type { IGceBackendService, INamedPort } from '../../../../domain'; import './loadBalancingPolicySelector.component.less'; class GceLoadBalancin...
return []; } }; return chain(selected) .flatMap((lbName: string) => getThem(this.globalBackendServices, lbName)) .uniq() .value(); } private decimalToPercent(value: number): number { if (value === 0) { return 0; } return value ? Math.round(value * 100) :...
const portNames = filteredBackendServices.map((service: IGceBackendService) => service.portName); const portNameIntersection = intersection(portNames, inUsePortNames); return portNames.filter((portName) => !portNameIntersection.includes(portName)); } default:
random_line_split
loadBalancingPolicySelector.component.ts
import type { IComponentOptions, IController } from 'angular'; import { module } from 'angular'; import { chain, get, has, intersection, set, without } from 'lodash'; import type { IGceBackendService, INamedPort } from '../../../../domain'; import './loadBalancingPolicySelector.component.less'; class GceLoadBalancin...
() { if (!get(this.command, 'loadBalancingPolicy.namedPorts')) { set(this.command, 'loadBalancingPolicy.namedPorts', []); } this.command.loadBalancingPolicy.namedPorts.push({ name: '', port: 80 }); } public removeNamedPort(index: number) { this.command.loadBalancingPolicy.namedPorts.splice(i...
addNamedPort
identifier_name
loadBalancingPolicySelector.component.ts
import type { IComponentOptions, IController } from 'angular'; import { module } from 'angular'; import { chain, get, has, intersection, set, without } from 'lodash'; import type { IGceBackendService, INamedPort } from '../../../../domain'; import './loadBalancingPolicySelector.component.less'; class GceLoadBalancin...
else { balancingModes = ['RATE', 'UTILIZATION']; } } if (!balancingModes.includes(get(this.command, 'loadBalancingPolicy.balancingMode') as string)) { set(this.command, 'loadBalancingPolicy.balancingMode', balancingModes[0]); } return balancingModes; } public $onInit(): void {...
{ balancingModes = ['CONNECTION', 'UTILIZATION']; }
conditional_block
settings.py
": "blog"}, # ), # # Example of adding a field to *all* of Mezzanine's content types: # ( # "mezzanine.pages.models.Page.another_field", # "IntegerField", # 'django.db.models.' is implied if path is omitted. # (_("Another name"),), # {"blank": True, "default": 1}, # ), # ...
set_dynamic_settings(globals())
conditional_block
settings.py
.Setting")), # ("Users", ("auth.User", "auth.Group",)), # ) # A three item sequence, each containing a sequence of template tags # used to render the admin dashboard. # # DASHBOARD_TAGS = ( # ("blog_tags.quick_blog", "mezzanine_tags.app_list"), # ("comment_tags.recent_comments",), # ("mezzanine_tags.re...
# # Keyword args for field class. # {"blank": True, "upload_to": "blog"}, # ), # # Example of adding a field to *all* of Mezzanine's content types: # ( # "mezzanine.pages.models.Page.another_field", # "IntegerField", # 'django.db.models.' is implied if path is omitted. # ...
# "somelib.fields.ImageField", # # Positional args for field class. # (_("Image"),),
random_line_split
check_sign.js
var sign = require('./sign.js'); var request = require( 'request' ); var config = { appID:'wx9037bc18a8016fb5', appSecret:'c15c32f6f2ca373cd3b4545e768133db', url:'http://test.fangcheng.cn/test' }; var SIGNATURE = { appId:config.appID, jsapi_ticket:'', nonceStr:'', timestamp:'', url:'',...
function worker() { var currentTime = (new Date()).getTime(), dur = currentTime - SIGNATURE.beginTime; if(dur > 7200 * 1000 * 0.9) { getSignature(); } } return { started:false, start:function(){ if(!this.interval && !this.started) { ...
atureTimer() {
identifier_name
check_sign.js
var sign = require('./sign.js'); var request = require( 'request' ); var config = { appID:'wx9037bc18a8016fb5', appSecret:'c15c32f6f2ca373cd3b4545e768133db', url:'http://test.fangcheng.cn/test' }; var SIGNATURE = { appId:config.appID, jsapi_ticket:'', nonceStr:'', timestamp:'', url:'',...
this.started = false; } } } } ex ports.getSignature = function(callback) { if(!SIGNATURE.status) { getSignature(callback); if(!signatureTimer.started) { signatureTimer.start(); } } else { callback(SIGNATURE); } };
function worker() { var currentTime = (new Date()).getTime(), dur = currentTime - SIGNATURE.beginTime; if(dur > 7200 * 1000 * 0.9) { getSignature(); } } return { started:false, start:function(){ if(!this.interval && !this.started) { ...
identifier_body
check_sign.js
var sign = require('./sign.js'); var request = require( 'request' ); var config = { appID:'wx9037bc18a8016fb5', appSecret:'c15c32f6f2ca373cd3b4545e768133db', url:'http://test.fangcheng.cn/test' }; var SIGNATURE = { appId:config.appID, jsapi_ticket:'',
expires_in:7200, status:false },INTERVAL = 30 * 1000 * 60,//30分钟 signatureTimer = new SignatureTimer(); var accsess_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+config.appID+"&secret="+config.appSecret; function getSignature(callback) { request.get( accsess_url, ...
nonceStr:'', timestamp:'', url:'', signature:'', beginTime:(new Date()).getTime(),
random_line_split
check_sign.js
var sign = require('./sign.js'); var request = require( 'request' ); var config = { appID:'wx9037bc18a8016fb5', appSecret:'c15c32f6f2ca373cd3b4545e768133db', url:'http://test.fangcheng.cn/test' }; var SIGNATURE = { appId:config.appID, jsapi_ticket:'', nonceStr:'', timestamp:'', url:'',...
} return { started:false, start:function(){ if(!this.interval && !this.started) { this.interval = setInterval(worker,INTERVAL); this.started = true; } }, stop:function() { if(this.interval) { clearI...
getSignature(); }
conditional_block
kraken.rs
#[cfg(test)] mod kraken_tests { extern crate coinnect; use self::coinnect::bitstamp::BitstampCreds; use self::coinnect::kraken::{KrakenApi, KrakenCreds}; #[test] fn fail_with_invalid_creds() { let creds = BitstampCreds::new("", "", "", ""); let res = KrakenApi::new(creds); ...
}
}
random_line_split
kraken.rs
#[cfg(test)] mod kraken_tests { extern crate coinnect; use self::coinnect::bitstamp::BitstampCreds; use self::coinnect::kraken::{KrakenApi, KrakenCreds}; #[test] fn fail_with_invalid_creds() { let creds = BitstampCreds::new("", "", "", ""); let res = KrakenApi::new(creds); ...
/// IMPORTANT: Real keys are needed in order to retrieve a token #[test] #[cfg_attr(not(feature = "kraken_private_tests"), ignore)] fn get_websockets_token_should_return_a_token() { use std::path::PathBuf; let path = PathBuf::from("./keys_real.json"); let creds = KrakenCreds::n...
{ use std::path::PathBuf; let path = PathBuf::from("./keys_real.json"); let creds = KrakenCreds::new_from_file("account_kraken", path).unwrap(); let mut api = KrakenApi::new(creds).unwrap(); let result = api.get_account_balance().unwrap(); println!("{:?}", result); ...
identifier_body
kraken.rs
#[cfg(test)] mod kraken_tests { extern crate coinnect; use self::coinnect::bitstamp::BitstampCreds; use self::coinnect::kraken::{KrakenApi, KrakenCreds}; #[test] fn
() { let creds = BitstampCreds::new("", "", "", ""); let res = KrakenApi::new(creds); assert_eq!( res.unwrap_err().to_string(), "Invalid config: \nExpected: Kraken\nFind: Bitstamp" ); } /// IMPORTANT: Real keys are needed in order to retrieve the balance ...
fail_with_invalid_creds
identifier_name
parseOptions.py
from modules.Utils import runCommand import re import sys def
(command): so, se, rc = runCommand("gofed %s --help" % command) if rc != 0: return [] options = [] option_f = False for line in so.split("\n"): if line == "Options:": option_f = True continue if option_f == True: if line == "": break # line must start with two spaces and minus if len(li...
parseOptions
identifier_name
parseOptions.py
from modules.Utils import runCommand import re import sys def parseOptions(command): so, se, rc = runCommand("gofed %s --help" % command) if rc != 0: return [] options = [] option_f = False for line in so.split("\n"):
if line == "Options:": option_f = True continue if option_f == True: if line == "": break # line must start with two spaces and minus if len(line) < 3: continue if line[:3] != " -": continue line = line.strip() parts = line.split(' ')[0].split(',') if parts == []: c...
random_line_split
parseOptions.py
from modules.Utils import runCommand import re import sys def parseOptions(command): so, se, rc = runCommand("gofed %s --help" % command) if rc != 0: return [] options = [] option_f = False for line in so.split("\n"): if line == "Options:": option_f = True continue if option_f == True: if line ==...
else: print command + ":" + " ".join(options)
print command + ":"
conditional_block
parseOptions.py
from modules.Utils import runCommand import re import sys def parseOptions(command):
continue line = line.strip() parts = line.split(' ')[0].split(',') if parts == []: continue # do we have both short and long options? opts = map(lambda i: i.strip().split(' ')[0].split('=')[0], parts) for opt in opts: options.append(opt) return sorted(options) if __name__ == "__...
so, se, rc = runCommand("gofed %s --help" % command) if rc != 0: return [] options = [] option_f = False for line in so.split("\n"): if line == "Options:": option_f = True continue if option_f == True: if line == "": break # line must start with two spaces and minus if len(line) < 3: ...
identifier_body
parse-content.js
var fs = require('fs'), eol = require('eol'), path = require('path'), mkdirp = require('mkdirp'), watch = require('watch'); var specialFiles = { 'welcome.md': function(fileContent, consoleContent) { consoleContent.welcome = processFileContent(fileContent); }, 'config.json': function...
} else { consoleContent.files[file] = createContentFile(file, fileContent); } }); if (consoleContent.__config) { setFilePermissions(consoleContent.files, consoleContent.__config); delete consoleContent.__config;...
if (specialFiles[file]) { specialFiles[file](fileContent, consoleContent);
random_line_split
parse-content.js
var fs = require('fs'), eol = require('eol'), path = require('path'), mkdirp = require('mkdirp'), watch = require('watch'); var specialFiles = { 'welcome.md': function(fileContent, consoleContent) { consoleContent.welcome = processFileContent(fileContent); }, 'config.json': function...
var files = fs.readdirSync(consoleSrcPath); if (!files || files.length === 0) { console.log('No files found for ' + consoleSrcPath); } else { console.log('Processing content ' + folderName); var consoleContent = { files: {} }; ...
{ return; }
conditional_block
parse-content.js
var fs = require('fs'), eol = require('eol'), path = require('path'), mkdirp = require('mkdirp'), watch = require('watch'); var specialFiles = { 'welcome.md': function(fileContent, consoleContent) { consoleContent.welcome = processFileContent(fileContent); }, 'config.json': function...
if (!files || files.length === 0) { console.log('No files found for ' + consoleSrcPath); } else { console.log('Processing content ' + folderName); var consoleContent = { files: {} }; files.forEach(function(file) { ...
{ var srcPath = './src/content'; var targetPath = './dist/content'; var consoleFolders = fs.readdirSync(srcPath); if (!consoleFolders) { return; } consoleFolders.forEach(function(folderName) { var consoleSrcPath = srcPath + '/' + folderName; var consoleTargetPath = targ...
identifier_body
parse-content.js
var fs = require('fs'), eol = require('eol'), path = require('path'), mkdirp = require('mkdirp'), watch = require('watch'); var specialFiles = { 'welcome.md': function(fileContent, consoleContent) { consoleContent.welcome = processFileContent(fileContent); }, 'config.json': function...
(fileName, fileContent) { var parsed = path.parse(fileName); return { content: processFileContent(fileContent), base: fileName, name: parsed.name, ext: parsed.ext }; } function hasExecutableForFile(executables, fileName) { if (!executables) { return false; }...
createContentFile
identifier_name
regress-225831.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the Lic...
var N = 300; var a = new Array(N + 1); a[N] = 10; a[0] = 100; status = inSection(1); // build string of the form ++(a[++f().x + ++f().x + ... + ++f().x]) which // gives ++a[N] var str = "".concat("++(a[", repeat_str("++f().x + ", (N - 1)), "++f().x])"); // Use Script constructor instead of simple eval to test Rhi...
{ return {x: 0}; }
identifier_body
regress-225831.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the Lic...
() { return {x: 0}; } var N = 300; var a = new Array(N + 1); a[N] = 10; a[0] = 100; status = inSection(1); // build string of the form ++(a[++f().x + ++f().x + ... + ++f().x]) which // gives ++a[N] var str = "".concat("++(a[", repeat_str("++f().x + ", (N - 1)), "++f().x])"); // Use Script constructor instead of si...
f
identifier_name
regress-225831.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the Lic...
actual = uneval(script()); expect = str; } addThis(); //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function repeat_str(str, repeat_count) { var arr = new Array(--repeat_count); whil...
return "".concat.apply("", arr); }(); script = new Script(str); script();
random_line_split
regress-225831.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the Lic...
addThis(); status = inSection(2); // build string of the form (a[f().x-- + f().x-- + ... + f().x--])-- // which should give (a[0])-- if (typeof Script == 'undefined') { print('Test skipped. Script not defined.'); } else { str = "".concat("(a[", repeat_str("f().x-- + ", (N - 1)), "f().x--])--"); script = new S...
{ var script = new Script(str); script(); actual = a[N]; expect = 11; }
conditional_block
hls_playlist.py
uri iv key_format key_format_versions") # EXT-X-MAP Map = namedtuple("Map", "uri byterange") # EXT-X-MEDIA Media = namedtuple("Media", "uri type group_id language name default " "autoselect forced characteristics") # EXT-X-START Start = namedtuple("Start", "time_offset precise") # EXT-X...
(self, lineno, line): if lineno == 0 and not line.startswith("#EXTM3U"): raise ValueError("Missing #EXTM3U header") if not line.startswith("#"): if self.state.pop("expect_segment", None): byterange = self.state.pop("byterange", None) extinf = self...
parse_line
identifier_name
hls_playlist.py
namedtuple("Start", "time_offset precise") # EXT-X-STREAM-INF StreamInfo = namedtuple("StreamInfo", "bandwidth program_id codecs resolution " "audio video subtitles") # EXT-X-I-FRAME-STREAM-INF IFrameStreamInfo = namedtuple("IFrameStreamInfo", "bandwidth program_id " ...
def uri(self, uri): if uri and urlparse(uri).scheme: return uri
random_line_split
hls_playlist.py
("Map", "uri byterange") # EXT-X-MEDIA Media = namedtuple("Media", "uri type group_id language name default " "autoselect forced characteristics") # EXT-X-START Start = namedtuple("Start", "time_offset precise") # EXT-X-STREAM-INF StreamInfo = namedtuple("StreamInfo", "bandwidth program_i...
playlist.media.append(media)
conditional_block
hls_playlist.py
-Z\-]+)=(\d+\.\d+|0x[0-9A-z]+|\d+x\d+|\d+|" r"\"(.+?)\"|[0-9A-z\-]+)") class M3U8(object): def __init__(self): self.is_endlist = False self.is_master = False self.allow_cache = None self.discontinuity_sequence = None self.iframes_only = None self...
"""Attempts to parse a M3U8 playlist from a string of data. If specified, *base_uri* is the base URI that relative URIs will be joined together with, otherwise relative URIs will be as is. If specified, *parser* can be a M3U8Parser subclass to be used to parse the data. """ return parser(base...
identifier_body
models.py
""" Example ------- class SystemSetting(KVModel): pass setting = SystemSetting.create(key='foo', value=100) loaded_setting = SystemSetting.get_by_key('foo') """ from django.db import models from .fields import SerializableField class KVModel(models.Model): """ An Abstract model that has key and value...
abstract = True
identifier_body
models.py
""" Example ------- class SystemSetting(KVModel): pass setting = SystemSetting.create(key='foo', value=100) loaded_setting = SystemSetting.get_by_key('foo') """ from django.db import models from .fields import SerializableField class
(models.Model): """ An Abstract model that has key and value fields key -- Unique CharField of max_length 255 value -- SerializableField by default could be used to store bool, int, float, str, list, dict and date """ key = models.CharField(max_length=255, unique=True) value...
KVModel
identifier_name
models.py
""" Example ------- class SystemSetting(KVModel): pass setting = SystemSetting.create(key='foo', value=100) loaded_setting = SystemSetting.get_by_key('foo') """ from django.db import models from .fields import SerializableField class KVModel(models.Model): """ An Abstract model that has key and value...
""" return cls.objects.get(key=key) class Meta: abstract = True
A static method that returns a KVModel instance. key -- unique key that is used for the search. this method will throw a DoesNotExist exception if an object with the key provided is not found.
random_line_split
index.ts
import { Express } from 'express' import Crowi from 'server/crowi' import multer from 'multer' import form from '../form' import Admin from './admin' import API from './api' import Login from './login' import Me from './me' export default (crowi: Crowi, app: Express) => { const controllers = crowi.controllers c...
app.post('/_api/slack/event', slack.api.handleEvent) app.post('/_/edit', form.revision, loginRequired, csrf, page.pageEdit) app.get('/trash/$', loginRequired, page.deletedPageListShow) app.get('/trash/*/$', loginRequired, page.deletedPageListShow) app.get('/*/$', loginRequired, encodeSpace, page.pageListShow...
app.get('/_api/check_username', user.api.checkUsername) app.get('/_api/shares/accesses.list', accessTokenParser, loginRequired, shareAccess.api.list) app.get('/_api/user/recentlyViewed', loginRequired, user.api.getRecentlyViewedPages) app.get('/_api/users.list', accessTokenParser, loginRequired, user.api.list) ...
random_line_split
test_volcano_point_building.py
# coding=utf-8 """ InaSAFE Disaster risk assessment tool developed by AusAid and World Bank - **Impact function Test Cases.** .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; eithe...
(self): registry = ImpactFunctionManager().registry registry.clear() registry.register(VolcanoPointBuildingFunction) def test_run(self): """TestVolcanoPointBuildingFunction: Test running the IF.""" volcano_path = test_data_path('hazard', 'volcano_point.shp') building...
setUp
identifier_name
test_volcano_point_building.py
# coding=utf-8 """ InaSAFE Disaster risk assessment tool developed by AusAid and World Bank - **Impact function Test Cases.** .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; eithe...
# The buildings should all be categorised into 3000 zone zone_sum = sum(impact_layer.get_data( attribute=impact_function.target_field)) expected_sum = 3 * 181 message = 'Expecting %s, but it returns %s' % (expected_sum, zone_sum) self.assertEqual(zone_sum, expected_s...
"""TestVolcanoPointBuildingFunction: Test running the IF.""" volcano_path = test_data_path('hazard', 'volcano_point.shp') building_path = test_data_path('exposure', 'buildings.shp') hazard_layer = read_layer(volcano_path) exposure_layer = read_layer(building_path) impact_functi...
identifier_body
test_volcano_point_building.py
# coding=utf-8 """ InaSAFE Disaster risk assessment tool developed by AusAid and World Bank - **Impact function Test Cases.** .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; eithe...
message = 'The question should be %s, but it returns %s' % ( expected_question, impact_function.question) self.assertEqual(expected_question, impact_function.question, message) # The buildings should all be categorised into 3000 zone zone_sum = sum(impact_layer.get_data( ...
'In the event of volcano point how many buildings might be ' 'affected')
random_line_split
common.rs
//! Set of common types used through the app use async_std::sync::Arc; use std::fmt; use std::slice::Iter; use std::time::Instant; use unicode_segmentation::UnicodeSegmentation; pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; /// The Prompt represents the current query, the cur...
else { self.len() - self.cursor } } pub fn as_string(&self) -> String { self.query.iter().collect() } pub fn timestamp(&self) -> Instant { self.timestamp } pub fn len(&self) -> usize { self.query.len() } pub fn is_empty(&self) -> bool { ...
{ 0 }
conditional_block
common.rs
//! Set of common types used through the app use async_std::sync::Arc; use std::fmt; use std::slice::Iter; use std::time::Instant; use unicode_segmentation::UnicodeSegmentation; pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; /// The Prompt represents the current query, the cur...
(&self) -> Iter<'_, String> { self.graphemes_lw.iter() } pub fn is_empty(&self) -> bool { self.string.is_empty() } } impl From<&str> for Letters { fn from(string: &str) -> Self { Self::new(String::from(string)) } } impl From<String> for Letters { fn from(string: String...
lowercase_iter
identifier_name
common.rs
//! Set of common types used through the app use async_std::sync::Arc; use std::fmt; use std::slice::Iter; use std::time::Instant; use unicode_segmentation::UnicodeSegmentation; pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; /// The Prompt represents the current query, the cur...
pub fn cursor_until_end(&self) -> usize { if self.len() < self.cursor { 0 } else { self.len() - self.cursor } } pub fn as_string(&self) -> String { self.query.iter().collect() } pub fn timestamp(&self) -> Instant { self.timestamp ...
random_line_split
common.rs
//! Set of common types used through the app use async_std::sync::Arc; use std::fmt; use std::slice::Iter; use std::time::Instant; use unicode_segmentation::UnicodeSegmentation; pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; /// The Prompt represents the current query, the cur...
pub fn refresh(&mut self) { self.timestamp = Instant::now(); } } impl From<&String> for Prompt { fn from(string: &String) -> Self { let query = string.chars().collect::<Vec<char>>(); let cursor = query.len(); Self { query, cursor, ..Def...
{ self.query.is_empty() }
identifier_body
list-item-injection-service.ts
import {Observable} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; import {ZC_DL_BUTTON_SMALL_CLASS} from 'src/ts/constants'; import {DownloadButtonFactory} from 'src/ts/content/injection/download-button-factory'; import {addToButtonGroup} from 'src/ts/content/injection/injection-commons'; import {InjectionSign...
(onUnload$: Observable<any>, listItem: JQuery<HTMLElement>): void { const downloadInfoUrl = listItem .find('.soundTitle__title, .trackItem__trackTitle, .chartTrack__title > a') .first().prop('href'); const downloadButton = createDownloadButton(onUnload$, downloadInfoUrl); const buttonGroup = listItem.find...
addToListItem
identifier_name
list-item-injection-service.ts
import {Observable} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; import {ZC_DL_BUTTON_SMALL_CLASS} from 'src/ts/constants'; import {DownloadButtonFactory} from 'src/ts/content/injection/download-button-factory'; import {addToButtonGroup} from 'src/ts/content/injection/injection-commons'; import {InjectionSign...
.addClass(['sc-button-small', ZC_DL_BUTTON_SMALL_CLASS]); } function addToListItem(onUnload$: Observable<any>, listItem: JQuery<HTMLElement>): void { const downloadInfoUrl = listItem .find('.soundTitle__title, .trackItem__trackTitle, .chartTrack__title > a') .first().prop('href'); const downloadButton ...
}; function createDownloadButton(onUnload$: Observable<any>, downloadInfoUrl: string): JQuery<HTMLElement> { return DownloadButtonFactory.create(onUnload$, downloadInfoUrl)
random_line_split
list-item-injection-service.ts
import {Observable} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; import {ZC_DL_BUTTON_SMALL_CLASS} from 'src/ts/constants'; import {DownloadButtonFactory} from 'src/ts/content/injection/download-button-factory'; import {addToButtonGroup} from 'src/ts/content/injection/injection-commons'; import {InjectionSign...
, }; function createDownloadButton(onUnload$: Observable<any>, downloadInfoUrl: string): JQuery<HTMLElement> { return DownloadButtonFactory.create(onUnload$, downloadInfoUrl) .addClass(['sc-button-small', ZC_DL_BUTTON_SMALL_CLASS]); } function addToListItem(onUnload$: Observable<any>, listItem: JQuery<HTMLEleme...
{ const selector = '.soundList__item, .searchList__item, .trackList__item, ' + '.systemPlaylistTrackList__item, .chartTracks__item'; InjectionSignalFactory.create$(selector) .pipe(takeUntil(onUnload$)) .subscribe(addToListItem.bind(null, onUnload$)); }
identifier_body
user.py
import requests from .route import Route class UserRoute(Route): def me(self):
def user(self, id): """ Return the user with given id :rtype: dict """ return self._get_json('user/{0}', id) def all(self, start=0, amount=10): """ Return a list of all users :rtype: list """ return self._get_json('user/all', sta...
""" Return the currently authenticated user :rtype: dict """ return self._get_json('user')
identifier_body
user.py
import requests from .route import Route class UserRoute(Route): def me(self): """ Return the currently authenticated user :rtype: dict """ return self._get_json('user') def user(self, id): """ Return the user with given id :rtype: dict ...
def activate(self, key): """ Activates a new registree on the LEX with given activation key :rtype: None """ url = self._base + 'user/activate' r = requests.get(url, params={ 'activation_key': key }) r.raise_for_status()
raise Exception('None of the arguments may be "None"')
conditional_block
user.py
import requests from .route import Route class UserRoute(Route): def me(self): """ Return the currently authenticated user :rtype: dict """ return self._get_json('user') def user(self, id): """ Return the user with given id :rtype: dict ...
'password_2': password, 'email': email, 'fullname': full_name }) r.raise_for_status() else: raise Exception('None of the arguments may be "None"') def activate(self, key): """ Activates a new registree on th...
'password_1': password,
random_line_split
user.py
import requests from .route import Route class UserRoute(Route): def me(self): """ Return the currently authenticated user :rtype: dict """ return self._get_json('user') def user(self, id): """ Return the user with given id :rtype: dict ...
(self, username, password, email, full_name): """ Registers a new user on the LEX :rtype: None """ if all([username, password, email, full_name]): r = requests.post(self._base + 'user/register', params={ 'username': username, 'password_...
register
identifier_name
myAirSimClient.py
import numpy as np import time import math import cv2 from pylab import array, arange, uint8 from PIL import Image import eventlet from eventlet import Timeout import multiprocessing as mp # Change the path below to point to the directoy where you installed the AirSim PythonClient #sys.path.append('C:/Users/Kjell/Goog...
(self, goal, pos): pitch, roll, yaw = self.getPitchRollYaw() yaw = math.degrees(yaw) pos_angle = math.atan2(goal[1] - pos.y_val, goal[0]- pos.x_val) pos_angle = math.degrees(pos_angle) % 360 track = math.radians(pos_angle - yaw) return ((ma...
goal_direction
identifier_name
myAirSimClient.py
import numpy as np import time import math import cv2 from pylab import array, arange, uint8 from PIL import Image import eventlet from eventlet import Timeout import multiprocessing as mp # Change the path below to point to the directoy where you installed the AirSim PythonClient #sys.path.append('C:/Users/Kjell/Goog...
def take_action(self, action): #check if copter is on level cause sometimes he goes up without a reason x = 0 while self.getPosition().z_val < -7.0: self.moveToZ(-6, 3) time.sleep(1) print(self.getPosition().z_val, "and", x) x = x...
self.rotateByYawRate(-30, duration) start = time.time() return start, duration
identifier_body
myAirSimClient.py
import numpy as np import time import math import cv2 from pylab import array, arange, uint8 from PIL import Image import eventlet from eventlet import Timeout import multiprocessing as mp # Change the path below to point to the directoy where you installed the AirSim PythonClient #sys.path.append('C:/Users/Kjell/Goog...
self.moveByVelocity(0, 0, 0, 1) self.rotateByYawRate(0, 1) return collided def goal_direction(self, goal, pos): pitch, roll, yaw = self.getPitchRollYaw() yaw = math.degrees(yaw) pos_angle = math.atan2(goa...
if self.getCollisionInfo().has_collided == True: return True
conditional_block
myAirSimClient.py
import numpy as np import time import math import cv2 from pylab import array, arange, uint8 from PIL import Image import eventlet from eventlet import Timeout import multiprocessing as mp # Change the path below to point to the directoy where you installed the AirSim PythonClient #sys.path.append('C:/Users/Kjell/Goog...
pos_angle = math.atan2(goal[1] - pos.y_val, goal[0]- pos.x_val) pos_angle = math.degrees(pos_angle) % 360 track = math.radians(pos_angle - yaw) return ((math.degrees(track) - 180) % 360) - 180 def getScreenDepthVis(self, track): responses = self.sim...
random_line_split
test_container_quotas.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Cloudwatt # 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/licen...
nbefore = self._get_bytes_used() self.assertRaises(exceptions.OverLimit, self.object_client.create_object, self.container_name, object_name, data) nafter = self._get_bytes_used() self.assertEqual(nbefore, nafter) @testtools.skip...
def test_upload_large_object(self): """Attempts to upload an object lagger than the bytes quota.""" object_name = data_utils.rand_name(name="TestObject") data = data_utils.arbitrary_string(QUOTA_BYTES + 1)
random_line_split
test_container_quotas.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Cloudwatt # 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/licen...
(self): resp = self._get_container_metadata() return int(resp["x-container-object-count"]) def _get_bytes_used(self): resp = self._get_container_metadata() return int(resp["x-container-bytes-used"])
_get_object_count
identifier_name
test_container_quotas.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Cloudwatt # 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/licen...
@testtools.skipIf(not container_quotas_available, SKIP_MSG) @attr(type="smoke") def test_upload_valid_object(self): """Attempts to uploads an object smaller than the bytes quota.""" object_name = data_utils.rand_name(name="TestObject") data = data_utils.arbitrary_string(QUOTA_BYTES...
"""Cleans the container of any object after each test.""" self.delete_containers([self.container_name]) super(ContainerQuotasTest, self).tearDown()
identifier_body
test_container_quotas.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Cloudwatt # 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/licen...
nbefore = self._get_object_count() self.assertEqual(nbefore, QUOTA_COUNT) self.assertRaises(exceptions.OverLimit, self.object_client.create_object, self.container_name, "OverQuotaObject", "") nafter = self._get_object_count() ...
name = data_utils.rand_name(name="TestObject") self.object_client.create_object(self.container_name, name, "")
conditional_block
example-column-date-basic.component.ts
import { Component, ChangeDetectionStrategy } from '@angular/core'; const EXAMPLE_TAGS = [ 'column-date-basic', 'Cell value is date' ]; @Component({ selector: 'example-column-date-basic', templateUrl: 'example-column-date-basic.component.html', styleUrls: ['example-column-date-basic.component.scss'], changeDete...
{ static tags = EXAMPLE_TAGS; title = EXAMPLE_TAGS[1]; rows = [ { 'number': 100.12, 'bool': true, 'date': new Date(2018, 9, 12), 'arr': [new Date(2020, 9, 12), new Date(2020, 9, 10), new Date(2020, 10, 12), new Date(2020, 9, 12)], 'null': null, 'undefined': undefined, 'empty': '', 'text':...
ExampleColumnDateBasicComponent
identifier_name
example-column-date-basic.component.ts
import { Component, ChangeDetectionStrategy } from '@angular/core';
const EXAMPLE_TAGS = [ 'column-date-basic', 'Cell value is date' ]; @Component({ selector: 'example-column-date-basic', templateUrl: 'example-column-date-basic.component.html', styleUrls: ['example-column-date-basic.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class ExampleColumnDa...
random_line_split
parity.rs
use malachite_base::num::arithmetic::traits::Parity; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::runner::Runner; use malachite_nz_test_util::bench::bucketers::natural_bit_bucketer; use malachit...
(gm: GenMode, config: GenConfig, limit: usize, file_name: &str) { run_benchmark( "Natural.even()", BenchmarkType::Single, natural_gen().get(gm, &config), gm.name(), limit, file_name, &natural_bit_bucketer("n"), &mut [("Malachite", &mut |n| no_out!(n.ev...
benchmark_natural_even
identifier_name
parity.rs
use malachite_base::num::arithmetic::traits::Parity; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::runner::Runner; use malachite_nz_test_util::bench::bucketers::natural_bit_bucketer; use malachit...
"Natural.even()", BenchmarkType::Single, natural_gen().get(gm, &config), gm.name(), limit, file_name, &natural_bit_bucketer("n"), &mut [("Malachite", &mut |n| no_out!(n.even()))], ); } fn benchmark_natural_odd(gm: GenMode, config: GenConfig, limit: us...
fn benchmark_natural_even(gm: GenMode, config: GenConfig, limit: usize, file_name: &str) { run_benchmark(
random_line_split
parity.rs
use malachite_base::num::arithmetic::traits::Parity; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::runner::Runner; use malachite_nz_test_util::bench::bucketers::natural_bit_bucketer; use malachit...
fn benchmark_natural_odd(gm: GenMode, config: GenConfig, limit: usize, file_name: &str) { run_benchmark( "Natural.odd()", BenchmarkType::Single, natural_gen().get(gm, &config), gm.name(), limit, file_name, &natural_bit_bucketer("n"), &mut [("Malachit...
{ run_benchmark( "Natural.even()", BenchmarkType::Single, natural_gen().get(gm, &config), gm.name(), limit, file_name, &natural_bit_bucketer("n"), &mut [("Malachite", &mut |n| no_out!(n.even()))], ); }
identifier_body
parity.rs
use malachite_base::num::arithmetic::traits::Parity; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::runner::Runner; use malachite_nz_test_util::bench::bucketers::natural_bit_bucketer; use malachit...
else { println!("{} is not odd", n); } } } fn benchmark_natural_even(gm: GenMode, config: GenConfig, limit: usize, file_name: &str) { run_benchmark( "Natural.even()", BenchmarkType::Single, natural_gen().get(gm, &config), gm.name(), limit, fi...
{ println!("{} is odd", n); }
conditional_block
test_tabs.py
""" Test cases for tabs. """ from mock import MagicMock, Mock, patch from courseware.courses import get_course_by_id from courseware.views import get_static_tab_contents from django.test.utils import override_settings from django.core.urlresolvers import reverse from student.tests.factories import UserFactory from x...
) static_tab = get_static_tab_contents(request, course, tab) self.assertIn("this module is temporarily unavailable", static_tab) @override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE) class StaticTabDateTestCaseXML(LoginEnrollmentTestCase, ModuleStoreTestCase): # The follo...
# Test when render raises an exception with patch('courseware.views.get_module') as mock_module_render: mock_module_render.return_value = MagicMock( render=Mock(side_effect=Exception('Render failed!'))
random_line_split
test_tabs.py
""" Test cases for tabs. """ from mock import MagicMock, Mock, patch from courseware.courses import get_course_by_id from courseware.views import get_static_tab_contents from django.test.utils import override_settings from django.core.urlresolvers import reverse from student.tests.factories import UserFactory from x...
self.assertEqual(resp.status_code, 200) self.assertIn("OOGIE BLOOGIE", resp.content) @override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE) def test_get_static_tab_contents(self): course = get_course_by_id(self.toy_course_key) request = get_request_for_user(UserFactory.crea...
"""Test cases for Static Tab Dates.""" def setUp(self): self.course = CourseFactory.create() self.page = ItemFactory.create( category="static_tab", parent_location=self.course.location, data="OOGIE BLOOGIE", display_name="new_tab" ) self.toy_course_key = Slas...
identifier_body
test_tabs.py
""" Test cases for tabs. """ from mock import MagicMock, Mock, patch from courseware.courses import get_course_by_id from courseware.views import get_static_tab_contents from django.test.utils import override_settings from django.core.urlresolvers import reverse from student.tests.factories import UserFactory from x...
(LoginEnrollmentTestCase, ModuleStoreTestCase): # The following XML test course (which lives at common/test/data/2014) # is closed; we're testing that tabs still appear when # the course is already closed xml_course_key = SlashSeparatedCourseKey('edX', 'detached_pages', '2014') # this text appears ...
StaticTabDateTestCaseXML
identifier_name
pipeline.rs
use super::config::AgentConfig; use super::source::Source; use super::target::Target; use super::source::SourceBuilder; use super::target::TargetBuilder; use super::lang::SquiddyProgram; use super::lang::ast::Parser; use super::lang::compiler::Compiler; use super::lang::token::Tokenizer; use std::io::{Error, ErrorKind}...
}
{ while self.source.has_more() { let item = self.source.next(); for condition in &mut self.program.conditions { if condition.matcher.accept(&item) { for action in &mut condition.actions { if let Some(events) = action.perform()...
identifier_body
pipeline.rs
use super::config::AgentConfig; use super::source::Source; use super::target::Target; use super::source::SourceBuilder; use super::target::TargetBuilder; use super::lang::SquiddyProgram; use super::lang::ast::Parser; use super::lang::compiler::Compiler; use super::lang::token::Tokenizer; use std::io::{Error, ErrorKind}...
else { Err(Error::new(ErrorKind::Other, "No source definition found")) } } fn compile_program(_: &AgentConfig) -> Result<SquiddyProgram, Error> { Parser::parse(&Tokenizer::tokenize(Bytes::from("{hello world}"))) // TODO better error conversion .map_err(|_| Error::ne...
{ if let Ok(target) = TargetBuilder::build(config.target_type) { Ok(Pipeline { source: source, target: target, program: program }) } else { Err(Error::new(ErrorKind::Other, "No target defi...
conditional_block
pipeline.rs
use super::config::AgentConfig; use super::source::Source; use super::target::Target; use super::source::SourceBuilder; use super::target::TargetBuilder; use super::lang::SquiddyProgram; use super::lang::ast::Parser; use super::lang::compiler::Compiler; use super::lang::token::Tokenizer; use std::io::{Error, ErrorKind}...
} } else { Err(Error::new(ErrorKind::Other, "No source definition found")) } } fn compile_program(_: &AgentConfig) -> Result<SquiddyProgram, Error> { Parser::parse(&Tokenizer::tokenize(Bytes::from("{hello world}"))) // TODO better error conversion ...
random_line_split
pipeline.rs
use super::config::AgentConfig; use super::source::Source; use super::target::Target; use super::source::SourceBuilder; use super::target::TargetBuilder; use super::lang::SquiddyProgram; use super::lang::ast::Parser; use super::lang::compiler::Compiler; use super::lang::token::Tokenizer; use std::io::{Error, ErrorKind}...
(&mut self) -> () { while self.source.has_more() { let item = self.source.next(); for condition in &mut self.program.conditions { if condition.matcher.accept(&item) { for action in &mut condition.actions { if let Some(events) ...
run
identifier_name
geo.py
"""geo.py: Implementation of class AbstractTwitterGeoCommand and its subclasses. """ from argparse import ArgumentParser from . import (AbstractTwitterCommand, call_decorator) from ..parsers import (filter_args, cache) # GET geo/id/:place_id # POST geo/place DEPRECATED # GET geo/reverse_geocode # GET geo/search GEO...
(self): """Request GET geo/id/:place_id for Twitter.""" # pylint: disable=protected-access kwargs = dict(_id=self.args.place_id) return kwargs, self.twhandler.geo.id._id # hack? class ReverseGeocode(AbstractTwitterGeoCommand): """Search for up to 20 places that can be used as a pla...
__call__
identifier_name
geo.py
from . import (AbstractTwitterCommand, call_decorator) from ..parsers import (filter_args, cache) # GET geo/id/:place_id # POST geo/place DEPRECATED # GET geo/reverse_geocode # GET geo/search GEO_ID_PLACE_ID = ('geo/id/:place_id', 'id') GEO_REVERSE_GEOCODE = ('geo/reverse_geocode', 'reverse') GEO_SEARCH = ('geo/sear...
"""geo.py: Implementation of class AbstractTwitterGeoCommand and its subclasses. """ from argparse import ArgumentParser
random_line_split
geo.py
"""geo.py: Implementation of class AbstractTwitterGeoCommand and its subclasses. """ from argparse import ArgumentParser from . import (AbstractTwitterCommand, call_decorator) from ..parsers import (filter_args, cache) # GET geo/id/:place_id # POST geo/place DEPRECATED # GET geo/reverse_geocode # GET geo/search GEO...
@call_decorator def __call__(self): """Request GET geo/reverse_geocode for Twitter.""" kwargs = filter_args( vars(self.args), 'lat', 'long', 'accuracy', 'granularity', 'max_results') return kwargs, self.twhandler.geo.reverse_geocode class Search(AbstractTwitt...
parser = subparsers.add_parser( GEO_REVERSE_GEOCODE[0], aliases=GEO_REVERSE_GEOCODE[1:], parents=[parser_geo_common()], help=self.__doc__) parser.add_argument( 'long', metavar='{-180.0..180.0}', help='the longitude to search aro...
identifier_body
table_form.js
String.prototype.matchAll = function(regexp) { var matches = []; this.replace(regexp, function() { var arr = ([]).slice.call(arguments, 0); var extras = arr.splice(-2); arr.index = extras[0]; arr.input = extras[1]; matches.push(arr); }); return matches.length ? matches : null; }; (function () {...
current_table = null; current_table_editor = null; if (selected_idx == "new") { createNewTable(); } else if (selected_idx == "import") { showImportModal(); } else { current_table = selected_idx; current_table_editor = new tableEditor(findTables()[selected_idx].content, editor_element); ...
editor_element.innerHTML = '';
random_line_split
table_form.js
String.prototype.matchAll = function(regexp) { var matches = []; this.replace(regexp, function() { var arr = ([]).slice.call(arguments, 0); var extras = arr.splice(-2); arr.index = extras[0]; arr.input = extras[1]; matches.push(arr); }); return matches.length ? matches : null; }; (function () ...
current_table = "new"; current_table_editor = new tableEditor(demo_new_table, editor_element); } })();
wTable() {
identifier_name
table_form.js
String.prototype.matchAll = function(regexp) { var matches = []; this.replace(regexp, function() { var arr = ([]).slice.call(arguments, 0); var extras = arr.splice(-2); arr.index = extras[0]; arr.input = extras[1]; matches.push(arr); }); return matches.length ? matches : null; }; (function () ...
ent_table = "new"; current_table_editor = new tableEditor(demo_new_table, editor_element); } })();
identifier_body
table_form.js
String.prototype.matchAll = function(regexp) { var matches = []; this.replace(regexp, function() { var arr = ([]).slice.call(arguments, 0); var extras = arr.splice(-2); arr.index = extras[0]; arr.input = extras[1]; matches.push(arr); }); return matches.length ? matches : null; }; (function () ...
current_table_editor = new tableEditor(t.content, editor_element); break; } } } } // Try to get the currently selected table else if (textarea.selectionStart || textarea.selectionStart === 0) { var c = textarea.value.substr(textarea.selectionStart, textarea.selectionEnd - textarea.se...
/ Check if the cursor is in a table var prev_start = textarea.value.substr(0, textarea.selectionStart).lastIndexOf('[rltable'); var prev_end = textarea.value.substr(0, textarea.selectionStart).lastIndexOf('[/rltable'); var next_end = textarea.value.substr(textarea.selectionEnd).indexOf('[/rltable'); var ne...
conditional_block
first-contentful-paint.js
/** * @license 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 * Unless required by applicable law or a...
() { return { id: 'first-contentful-paint', title: str_(i18n.UIStrings.firstContentfulPaintMetric), description: str_(UIStrings.description), scoreDisplayMode: Audit.SCORING_MODES.NUMERIC, requiredArtifacts: ['traces', 'devtoolsLogs', 'TestedAsMobileDevice'], }; } /** * @re...
meta
identifier_name
first-contentful-paint.js
/** * @license 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 * Unless required by applicable law or a...
const trace = artifacts.traces[Audit.DEFAULT_PASS]; const devtoolsLog = artifacts.devtoolsLogs[Audit.DEFAULT_PASS]; const metricComputationData = {trace, devtoolsLog, settings: context.settings}; const metricResult = await ComputedFcp.request(metricComputationData, context); const scoreOptions = ...
* @return {Promise<LH.Audit.Product>} */ static async audit(artifacts, context) {
random_line_split
parse_and_typecheck.rs
use crate::ProtoPathBuf; /// Result of parsing `.proto` files. #[doc(hidden)] pub struct ParsedAndTypechecked { /// One entry for each input `.proto` file. pub relative_paths: Vec<ProtoPathBuf>, /// All parsed `.proto` files including dependencies of input files. pub file_descriptors: Vec<protobuf::des...
HashSet::from(["a.proto", "b.proto"]), protoc.file_descriptors.iter().map(|d| d.name()).collect() ); assert_eq!(1, protoc.file_descriptors[0].message_type.len()); assert_eq!(1, pure.file_descriptors[0].message_type.len()); assert_eq!( "Banana", ...
random_line_split
parse_and_typecheck.rs
use crate::ProtoPathBuf; /// Result of parsing `.proto` files. #[doc(hidden)] pub struct
{ /// One entry for each input `.proto` file. pub relative_paths: Vec<ProtoPathBuf>, /// All parsed `.proto` files including dependencies of input files. pub file_descriptors: Vec<protobuf::descriptor::FileDescriptorProto>, /// Description of the parser (e.g. to include in generated files). pub...
ParsedAndTypechecked
identifier_name
parse_and_typecheck.rs
use crate::ProtoPathBuf; /// Result of parsing `.proto` files. #[doc(hidden)] pub struct ParsedAndTypechecked { /// One entry for each input `.proto` file. pub relative_paths: Vec<ProtoPathBuf>, /// All parsed `.proto` files including dependencies of input files. pub file_descriptors: Vec<protobuf::des...
.input(&b_proto) .parse_and_typecheck() .unwrap(); assert_eq!(pure.relative_paths, protoc.relative_paths); assert_eq!(2, pure.file_descriptors.len()); assert_eq!(2, protoc.file_descriptors.len()); // TODO: make result more deterministic assert...
{ let dir = tempfile::tempdir().unwrap(); let a_proto = dir.path().join("a.proto"); let b_proto = dir.path().join("b.proto"); fs::write(&a_proto, "syntax = 'proto3'; message Apple {}").unwrap(); fs::write( &b_proto, "syntax = 'proto3'; import 'a.proto'; me...
identifier_body
character.component.ts
import { Component, OnInit } from '@angular/core'; import { Character } from '../../models/character.model'; import { CharacterService } from '../../services/character/character.service'; import { ToastService } from '../../services/shared/toast.service'; @Component({ moduleId: module.id, templateUrl: './char...
this.searchText = ''; this.firstItemToShow = 0; this.lastItemToShow = this.itemsPerPage; this._characterService.getCharacters() .subscribe((data: any) => { this.totalCharacters = data.body.length; this.characters = data.body; }, ...
private _toastService: ToastService) { } ngOnInit() { this.filterProp = ['name', 'homeland'];
random_line_split
character.component.ts
import { Component, OnInit } from '@angular/core'; import { Character } from '../../models/character.model'; import { CharacterService } from '../../services/character/character.service'; import { ToastService } from '../../services/shared/toast.service'; @Component({ moduleId: module.id, templateUrl: './char...
filterChanged(searchText: string) { this.searchText = searchText; } pageChanged(event: any): void { this.firstItemToShow = (event.page - 1) * this.itemsPerPage; this.lastItemToShow = this.firstItemToShow + this.itemsPerPage; } }
{ this.filterProp = ['name', 'homeland']; this.searchText = ''; this.firstItemToShow = 0; this.lastItemToShow = this.itemsPerPage; this._characterService.getCharacters() .subscribe((data: any) => { this.totalCharacters = data.body.length; ...
identifier_body
character.component.ts
import { Component, OnInit } from '@angular/core'; import { Character } from '../../models/character.model'; import { CharacterService } from '../../services/character/character.service'; import { ToastService } from '../../services/shared/toast.service'; @Component({ moduleId: module.id, templateUrl: './char...
(searchText: string) { this.searchText = searchText; } pageChanged(event: any): void { this.firstItemToShow = (event.page - 1) * this.itemsPerPage; this.lastItemToShow = this.firstItemToShow + this.itemsPerPage; } }
filterChanged
identifier_name
base.py
from itertools import chain import uuid import numpy as np from pyfr.nputil import fuzzysort class BaseReader(object, metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def to_pyfrm(self): mesh = self._to_raw_pyfr...
return pfaces def _ident_boundary_faces(self, bpart, resid): bfaces = defaultdict(list) bpents = set(self._bfacespents.values()) for epent, fnodes in bpart.items(): if epent in bpents: for fn in chain.from_iterable(fnodes.values()): ...
lf = resid.pop(tuple(sorted(lfn))) rf = resid.pop(tuple(sorted(rfn))) pfaces[pftype].append([lf, rf])
conditional_block
base.py
from itertools import chain import uuid import numpy as np from pyfr.nputil import fuzzysort class BaseReader(object, metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def
(self): mesh = self._to_raw_pyfrm() # Add metadata mesh['mesh_uuid'] = np.array(str(uuid.uuid4()), dtype='S') return mesh class NodalMeshAssembler(object): # Dimensionality of each element type _petype_ndim = {'tri': 2, 'quad': 2, 'tet': 3, 'hex': 3, 'pri'...
to_pyfrm
identifier_name
base.py
defaultdict from itertools import chain import uuid import numpy as np from pyfr.nputil import fuzzysort class BaseReader(object, metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def to_pyfrm(self): mesh = self....
def _pair_periodic_fluid_faces(self, bpart, resid): pfaces = defaultdict(list) nodepts = self._nodepts for lpent, rpent in self._pfacespents.values(): for pftype in bpart[lpent]: lfnodes = bpart[lpent][pftype] rfnodes = bpart[rpent][pftype] ...
pairs = defaultdict(list) resid = {} for pftype, faces in ffofaces.items(): for f, n in chain.from_iterable(zip(f, n) for f, n in faces): sn = tuple(n) # See if the nodes are in resid if sn in resid: pairs[pftype].append([...
identifier_body
base.py
defaultdict from itertools import chain import uuid import numpy as np from pyfr.nputil import fuzzysort class BaseReader(object, metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def to_pyfrm(self): mesh = self....
for fidx in foeles[:, pfnmap]]) fpts = fpts.swapaxes(0, 1) # Check parallelogram or not if np.any(np.abs(fpts[0] - fpts[1] - fpts[2] + fpts[3]) > 1e-10): raise ValueError('Pyramids with non-parallelogram bases are ' 'currently un...
# Face nodes fpts = np.array([[nodepts[i] for i in fidx]
random_line_split
class_inplace_op2.py
# Test inplace special methods enabled by MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS class A: def __imul__(self, other): print("__imul__") return self def __imatmul__(self, other): print("__imatmul__") return self def
(self, other): print("__ifloordiv__") return self def __itruediv__(self, other): print("__itruediv__") return self def __imod__(self, other): print("__imod__") return self def __ipow__(self, other): print("__ipow__") return self def __i...
__ifloordiv__
identifier_name
class_inplace_op2.py
# Test inplace special methods enabled by MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS class A: def __imul__(self, other): print("__imul__") return self def __imatmul__(self, other): print("__imatmul__") return self def __ifloordiv__(self, other): print("__ifloordiv__")...
return self def __irshift__(self, other): print("__irshift__") return self a = A() try: a *= None except TypeError: print("SKIP") raise SystemExit a @= None a //= None a /= None a %= None a **= None a |= None a ^= None a &= None a <<= None a >>= None # Normal operator shoul...
print("__iand__") return self def __ilshift__(self, other): print("__ilshift__")
random_line_split
class_inplace_op2.py
# Test inplace special methods enabled by MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS class A: def __imul__(self, other): print("__imul__") return self def __imatmul__(self, other): print("__imatmul__") return self def __ifloordiv__(self, other): print("__ifloordiv__")...
def __iand__(self, other): print("__iand__") return self def __ilshift__(self, other): print("__ilshift__") return self def __irshift__(self, other): print("__irshift__") return self a = A() try: a *= None except TypeError: print("SKIP") rai...
print("__ixor__") return self
identifier_body
backdrop.js
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.0.0-rc5-master-76c6299 */ goog.provide('ng.material.components.backdrop'); goog.require('ng.material.core'); /* * @ngdoc module * @name material.components.backdrop * @description Backdrop */ /** * @ngdoc directive * @na...
$mdTheming.inherit(element, element.parent()); }); } }]); ng.material.components.backdrop = angular.module("material.components.backdrop");
{ if ( parent.nodeName == 'BODY' ) { element.css({position : 'fixed'}); } var styles = $window.getComputedStyle(parent); if (styles.position == 'static') { // backdrop uses position:absolute and will not work properly with parent position:static (default...
conditional_block
backdrop.js
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.0.0-rc5-master-76c6299 */ goog.provide('ng.material.components.backdrop'); goog.require('ng.material.core'); /* * @ngdoc module * @name material.components.backdrop * @description Backdrop */ /** * @ngdoc directive * @na...
(scope, element, attrs) { // If body scrolling has been disabled using mdUtil.disableBodyScroll(), // adjust the 'backdrop' height to account for the fixed 'body' top offset var body = $window.getComputedStyle($document[0].body); if (body.position == 'fixed') { var hViewport = parseInt(...
postLink
identifier_name
backdrop.js
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.0.0-rc5-master-76c6299 */ goog.provide('ng.material.components.backdrop'); goog.require('ng.material.core'); /* * @ngdoc module * @name material.components.backdrop * @description Backdrop */ /** * @ngdoc directive * @na...
if (parent) { if ( parent.nodeName == 'BODY' ) { element.css({position : 'fixed'}); } var styles = $window.getComputedStyle(parent); if (styles.position == 'static') { // backdrop uses position:absolute and will not work properly with parent posi...
{ // If body scrolling has been disabled using mdUtil.disableBodyScroll(), // adjust the 'backdrop' height to account for the fixed 'body' top offset var body = $window.getComputedStyle($document[0].body); if (body.position == 'fixed') { var hViewport = parseInt(body.height, 10) + Math....
identifier_body
backdrop.js
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.0.0-rc5-master-76c6299 */ goog.provide('ng.material.components.backdrop'); goog.require('ng.material.core'); /* * @ngdoc module * @name material.components.backdrop * @description Backdrop */ /** * @ngdoc directive * @na...
return { restrict: 'E', link: postLink }; function postLink(scope, element, attrs) { // If body scrolling has been disabled using mdUtil.disableBodyScroll(), // adjust the 'backdrop' height to account for the fixed 'body' top offset var body = $window.getComputedStyle($docum...
angular .module('material.components.backdrop', ['material.core']) .directive('mdBackdrop', ["$mdTheming", "$animate", "$rootElement", "$window", "$log", "$$rAF", "$document", function BackdropDirective($mdTheming, $animate, $rootElement, $window, $log, $$rAF, $document) { var ERROR_CSS_POSITION = "<md-backdrop...
random_line_split
_student_t_likelihood_function.py
"""A likelihood function representing a Student-t distribution. Author: Ilias Bilionis Date: 1/21/2013 """ __all__ = ['StudentTLikelihoodFunction'] import numpy as np import scipy import math from . import GaussianLikelihoodFunction class StudentTLikelihoodFunction(GaussianLikelihoodFunction): """An...
def __init__(self, nu, num_input=None, data=None, mean_function=None, cov=None, name='Student-t Likelihood Function'): """Initialize the object. Arguments: nu --- The degrees of freedom of the distribution. Keyword Arguments num...
random_line_split