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
tags-section.component.ts
/** * @license * Copyright 2017 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law o...
// Clone the array tags = tags.slice(0); // Sort it tags.sort( (obj1, obj2) => { return obj1.name.toLowerCase().localeCompare(obj2.name.toLowerCase()); }); return tags; } /** * Called when the user changes the description of a tag. * @param...
{ tags = []; }
conditional_block
tags-section.component.ts
/** * @license * Copyright 2017 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law o...
import {RenameEntityDialogComponent, RenameEntityEvent} from "../../dialogs/rename-entity.component"; import {ObjectUtils} from "apicurio-ts-core"; @Component({ selector: "tags-section", templateUrl: "tags-section.component.html", encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetection...
import {CommandService} from "../../../_services/command.service"; import {AbstractBaseComponent} from "../../common/base-component"; import {DocumentService} from "../../../_services/document.service"; import {SelectionService} from "../../../_services/selection.service";
random_line_split
tags-section.component.ts
/** * @license * Copyright 2017 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law o...
/** * Opens the rename tag dialog. * @param tag */ public openRenameDialog(tag: OasTag): void { let tagNames: string[] = []; VisitorUtil.visitTree(tag.ownerDocument(), new class extends CombinedVisitorAdapter { public visitTag(node: OasTag): void { ta...
{ let command: ICommand = CommandFactory.createDeleteAllTagsCommand(); this.commandService.emit(command); }
identifier_body
tags-section.component.ts
/** * @license * Copyright 2017 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law o...
extends AbstractBaseComponent { @Input() document: OasDocument; @ViewChild("renameDialog", { static: true }) renameDialog: RenameEntityDialogComponent; /** * C'tor. * @param changeDetectorRef * @param documentService * @param commandService * @param selectionService */ ...
TagsSectionComponent
identifier_name
build.rs
extern crate gcc; use std::env; fn
() { let mut cfg = gcc::Config::new(); if env::var("TARGET").unwrap().contains("windows") { cfg.define("_WIN32", None); cfg.define("BZ_EXPORT", None); } cfg.include("bzip2-1.0.6") .define("BZ_NO_STDIO", None) .file("bzip2-1.0.6/blocksort.c") .file("bzip2-1.0.6/huff...
main
identifier_name
build.rs
extern crate gcc; use std::env; fn main() { let mut cfg = gcc::Config::new(); if env::var("TARGET").unwrap().contains("windows") { cfg.define("_WIN32", None); cfg.define("BZ_EXPORT", None); } cfg.include("bzip2-1.0.6") .define("BZ_NO_STDIO", None) .file("bzip2-1.0.6/blo...
.file("bzip2-1.0.6/decompress.c") .file("bzip2-1.0.6/bzlib.c") .compile("libbz2.a"); }
random_line_split
build.rs
extern crate gcc; use std::env; fn main() { let mut cfg = gcc::Config::new(); if env::var("TARGET").unwrap().contains("windows")
cfg.include("bzip2-1.0.6") .define("BZ_NO_STDIO", None) .file("bzip2-1.0.6/blocksort.c") .file("bzip2-1.0.6/huffman.c") .file("bzip2-1.0.6/crctable.c") .file("bzip2-1.0.6/randtable.c") .file("bzip2-1.0.6/compress.c") .file("bzip2-1.0.6/decompress.c") .file("...
{ cfg.define("_WIN32", None); cfg.define("BZ_EXPORT", None); }
conditional_block
build.rs
extern crate gcc; use std::env; fn main()
{ let mut cfg = gcc::Config::new(); if env::var("TARGET").unwrap().contains("windows") { cfg.define("_WIN32", None); cfg.define("BZ_EXPORT", None); } cfg.include("bzip2-1.0.6") .define("BZ_NO_STDIO", None) .file("bzip2-1.0.6/blocksort.c") .file("bzip2-1.0.6/huffman...
identifier_body
DomParser.js
li') { sibling = node.prev; if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) { sibling.append(node); continue; } sibling = node.next; if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) { sibling.insert(node, sibling.firstChild, t...
node.append(textNode).value = text; } }, comment: function(text) { node.append(createNode('#comment', 8)).value = text; }, pi: function(name, text) { node.append(createNode(name, 7)).value = text; removeWhitespaceBefore(node); }, doctype: function(text) ...
textNode = createNode('#text', 3); textNode.raw = !!raw;
random_line_split
DomParser.js
'li') { sibling = node.prev; if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) { sibling.append(node); continue; } sibling = node.next; if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) { sibling.insert(node, sibling.firstChild,...
() { var node = rootNode.firstChild, next, rootBlockNode; while (node) { next = node.next; if (node.type == 3 || (node.type == 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type'))) { if (!rootBlockNode) { // Create a new root block element ...
addRootBlocks
identifier_name
DomParser.js
li') { sibling = node.prev; if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) { sibling.append(node); continue; } sibling = node.next; if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) { sibling.insert(node, sibling.firstChild, t...
} ; function createNode(name, type) { var node = new Node(name, type), list; if (name in nodeFilters) { list = matchedNodes[name]; if (list) list.push(node); else matchedNodes[name] = [node]; } return node; }; function removeWhitespaceBefore(n...
{ var node = rootNode.firstChild, next, rootBlockNode; while (node) { next = node.next; if (node.type == 3 || (node.type == 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type'))) { if (!rootBlockNode) { // Create a new root block element roo...
identifier_body
DomParser.js
_block : settings.forced_root_block; whiteSpaceElements = schema.getWhiteSpaceElements(); startWhiteSpaceRegExp = /^[ \t\r\n]+/; endWhiteSpaceRegExp = /[ \t\r\n]+$/; allWhiteSpaceRegExp = /[ \t\r\n]+/g; isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/; function addRootBlocks() { var node = rootNo...
{ if (!nodes[fi].parent) nodes.splice(fi, 1); }
conditional_block
latex_codec.py
],'\\i') in _l2u: self.pos += delta # correct failure to undot i return unichr(_l2u[(c[0],'\\i')]) elif len(c) == 1 and c[0].startswith('\\char') and c[0][5:].isdigit(): self.pos += delta return unichr(int(c[0][5:])) # nothing ma...
q = self[offset+1] if q == '{' and self[offset+3] == '}': yield 4, (t,self[offset+2]) elif q: yield 2, (t,q) yield 1, t latex_equivalents = { 0x0009: ' ', 0x000a: '\n', 0x0023: '{\#}', 0x0026: '{\&}', 0x00a0: '{~}', ...
yield 3, (t,self[offset+1],t) else:
random_line_split
latex_codec.py
(self,input,errors='strict'): """Convert latex source string to unicode.""" if encoding: input = unicode(input,encoding,errors) # Note: we may get buffer objects here. # It is not permussable to call join on buffer objects # but we can make th...
decode
identifier_name
latex_codec.py
return (Codec().encode,Codec().decode,StreamReader,StreamWriter) def _tokenize(tex): """Convert latex source into sequence of single-token substrings.""" start = 0 try: # skip quickly across boring stuff pos = _stoppers.finditer(tex).next().span()[0] except StopIteration: ...
pass
identifier_body
latex_codec.py
],'\\i') in _l2u: self.pos += delta # correct failure to undot i return unichr(_l2u[(c[0],'\\i')]) elif len(c) == 1 and c[0].startswith('\\char') and c[0][5:].isdigit(): self.pos += delta return unichr(int(c[0][5:])) # nothing ma...
else: q = self[offset+1] if q == '{' and self[offset+3] == '}': yield 4, (t,self[offset+2]) elif q: yield 2, (t,q) yield 1, t latex_equivalents = { 0x0009: ' ', 0x000a: '\n', 0x0023: '{\#}', 0x0026: '{\&}', 0x0...
yield 3, (t,self[offset+1],t)
conditional_block
donews_spider.py
# -*- coding: utf-8 -*- __author__ = 'k' import re import scrapy from bs4 import BeautifulSoup import logging from thepaper.items import NewsItem import json logger = logging.getLogger("NbdSpider") from thepaper.settings import * from thepaper.util import judge_news_crawl import time class DonewsSpider(scrapy.spiders...
else: pageindex = temp[1].split("_",1)[-1].split(".",1)[0] soup = BeautifulSoup(response.body,"lxml") catalogue = soup.find("div",class_ ="arttitle").text.strip() news_list = soup.find("ul",class_ = "art_list mt11").find_all("li") for news in news_list: ti...
domain = "http://www.donews.com/net/" name = "donews" allowed_domains = ["donews.com",] flag = {} start_urls = [ "http://www.donews.com/net/", "http://www.donews.com/original/", ] def parse(self,response): origin_url = response.url topic_url = origin_url[:-1] ...
identifier_body
donews_spider.py
# -*- coding: utf-8 -*- __author__ = 'k' import re import scrapy from bs4 import BeautifulSoup import logging from thepaper.items import NewsItem import json logger = logging.getLogger("NbdSpider") from thepaper.settings import * from thepaper.util import judge_news_crawl import time class DonewsSpider(scrapy.spiders...
(self,response): origin_url = response.url temp = origin_url.rsplit("/",1) topic_url = temp[0] if temp[1] == "": pageindex = 1 else: pageindex = temp[1].split("_",1)[-1].split(".",1)[0] soup = BeautifulSoup(response.body,"lxml") catalogue =...
parse_topic
identifier_name
donews_spider.py
# -*- coding: utf-8 -*- __author__ = 'k' import re import scrapy from bs4 import BeautifulSoup import logging from thepaper.items import NewsItem import json logger = logging.getLogger("NbdSpider") from thepaper.settings import * from thepaper.util import judge_news_crawl import time class DonewsSpider(scrapy.spiders...
yield item
item['crawl_date'] = NOW
random_line_split
donews_spider.py
# -*- coding: utf-8 -*- __author__ = 'k' import re import scrapy from bs4 import BeautifulSoup import logging from thepaper.items import NewsItem import json logger = logging.getLogger("NbdSpider") from thepaper.settings import * from thepaper.util import judge_news_crawl import time class DonewsSpider(scrapy.spiders...
else: self.flag[topic_url] = pageindex if not self.flag[topic_url]: next_url = "%s/index_%s.html" % (topic_url,int(pageindex) + 1) yield scrapy.Request(next_url,callback=self.parse_topic) def parse_news(self,response): item = response.meta.get("...
yield scrapy.Request(item["news_url"],callback=self.parse_news,meta={'item':item})
conditional_block
data_store.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ loaded_data::runtime_types::Type, values::{GlobalValue, Value}, }; use move_core_types::{account_address::AccountAddress, language_storage::ModuleId}; use vm::errors::{PartialVMResult, VMResult}; /// Provide an imp...
pub trait DataStore { // --- // StateStore operations // --- /// Try to load a resource from remote storage and create a corresponding GlobalValue /// that is owned by the data store. fn load_resource( &mut self, addr: AccountAddress, ty: &Type, ) -> PartialVMResult<...
/// The `DataStore` is a generic concept that includes both data and events. /// A default implementation of the `DataStore` is `TransactionDataCache` which provides /// an in memory cache for a given transaction and the atomic transactional changes /// proper of a script execution (transaction).
random_line_split
SimpleApp.py
# Very simple example application for BrickPython. # # Copyright (c) 2014 Charles Weir. Shared under the MIT Licence. import sys, os # Python path kludge - omit these 2 lines if BrickPython is installed. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))) from BrickPython.CommandLineAp...
def doActivity(self): 'Coroutine to rotate a motor forward and backward' motorA = self.motor('A') motorA.zeroPosition() while True: print 'Moving forward' for i in motorA.moveTo( 2*90 ): yield print 'Moving back' for i...
CommandLineApplication.__init__(self) self.addSensorCoroutine( self.doActivity() )
identifier_body
SimpleApp.py
# Very simple example application for BrickPython. # # Copyright (c) 2014 Charles Weir. Shared under the MIT Licence. import sys, os # Python path kludge - omit these 2 lines if BrickPython is installed. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))) from BrickPython.CommandLineAp...
print 'Moving back' for i in motorA.moveTo( 0 ): yield if __name__ == "__main__": SimpleApp().mainloop()
yield
conditional_block
SimpleApp.py
# Very simple example application for BrickPython. # # Copyright (c) 2014 Charles Weir. Shared under the MIT Licence. import sys, os # Python path kludge - omit these 2 lines if BrickPython is installed. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))) from BrickPython.CommandLineAp...
(CommandLineApplication): 'Simple command line example application' def __init__(self): CommandLineApplication.__init__(self) self.addSensorCoroutine( self.doActivity() ) def doActivity(self): 'Coroutine to rotate a motor forward and backward' motorA = self.motor('A') ...
SimpleApp
identifier_name
SimpleApp.py
# Very simple example application for BrickPython. # # Copyright (c) 2014 Charles Weir. Shared under the MIT Licence.
import sys, os # Python path kludge - omit these 2 lines if BrickPython is installed. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))) from BrickPython.CommandLineApplication import CommandLineApplication class SimpleApp(CommandLineApplication): 'Simple command line example appl...
random_line_split
index.d.ts
// Type definitions for body-parser-xml 2.0 // Project: https://github.com/fiznool/body-parser-xml // Definitions by: tbounsiar <https://github.com/tbounsiar> // Piotr Błażejewicz <https://github.com/peterblazejewicz> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference typ...
* The type option is used to determine what media type the middleware will parse. * @default ['_/xml', '+xml'] */ type?: string | string[] | ((req: Request) => boolean) | undefined; /** * The verify option, if supplied, is called as verify(req, res, buf, encoding), ...
* @default '100kb' */ limit?: string | number | undefined; /**
random_line_split
main.py
# -*- coding: utf-8 -*- """Module for parsing main configuration file (nagios.cfg).""" from pynag.Utils import paths class MainConfig(object): """ Generic parser for files in the format of key=value. This is the format used by nagios.cfg and many other unix configuration files. """ def __init__(sel...
self.filename = filename self.data = self.parse() def get(self, attribute, default=None): """Get the first instance of key.""" for key, value in self.data: if key == attribute: return value def get_list(self, attribute): """Get a list of all...
filename = paths.find_main_configuration_file()
conditional_block
main.py
# -*- coding: utf-8 -*- """Module for parsing main configuration file (nagios.cfg).""" from pynag.Utils import paths class MainConfig(object): """ Generic parser for files in the format of key=value. This is the format used by nagios.cfg and many other unix configuration files. """ def __init__(sel...
(string): result = [] for line in string.splitlines(): # Strip out new line characters line = line.strip() # Skip blank lines if not line: continue # Skip comments if line.startswith("#") or line.startswith(';'): ...
_parse_string
identifier_name
main.py
# -*- coding: utf-8 -*- """Module for parsing main configuration file (nagios.cfg).""" from pynag.Utils import paths class MainConfig(object): """ Generic parser for files in the format of key=value. This is the format used by nagios.cfg and many other unix configuration files. """
filename = paths.find_main_configuration_file() self.filename = filename self.data = self.parse() def get(self, attribute, default=None): """Get the first instance of key.""" for key, value in self.data: if key == attribute: return value ...
def __init__(self, filename=None): if not filename:
random_line_split
main.py
# -*- coding: utf-8 -*- """Module for parsing main configuration file (nagios.cfg).""" from pynag.Utils import paths class MainConfig(object): """ Generic parser for files in the format of key=value. This is the format used by nagios.cfg and many other unix configuration files. """ def __init__(sel...
def get(self, attribute, default=None): """Get the first instance of key.""" for key, value in self.data: if key == attribute: return value def get_list(self, attribute): """Get a list of all values that have attribute_name 'key'.""" return [value f...
if not filename: filename = paths.find_main_configuration_file() self.filename = filename self.data = self.parse()
identifier_body
clone.ts
// export function deepClone(obj: any) { // return JSON.parse(JSON.stringify(obj)); // } function getDataType(data: any) { const dataType = Object.prototype.toString.call(data); if (dataType === '[object Object]') { return 'Object'; }
if (dataType === '[object Number]') { return 'Number'; } if (dataType === '[object String]') { return 'String'; } if (dataType === '[object Boolean]') { return 'Boolean'; } if (dataType === '[object Undefined]') { return 'Undefined'; } if (dataType ===...
if (dataType === '[object Array]') { return 'Array'; }
random_line_split
clone.ts
// export function deepClone(obj: any) { // return JSON.parse(JSON.stringify(obj)); // } function getDataType(data: any) { const dataType = Object.prototype.toString.call(data); if (dataType === '[object Object]') { return 'Object'; } if (dataType === '[object Array]') { return 'Arr...
if (dataType === '[object Boolean]') { return 'Boolean'; } if (dataType === '[object Undefined]') { return 'Undefined'; } if (dataType === '[object Null]') { return 'Null'; } if (dataType === '[object Date]') { return 'Date'; } } export function deepClon...
{ return 'String'; }
conditional_block
clone.ts
// export function deepClone(obj: any) { // return JSON.parse(JSON.stringify(obj)); // } function getDataType(data: any)
if (dataType === '[object Null]') { return 'Null'; } if (dataType === '[object Date]') { return 'Date'; } } export function deepClone(data: any) { let dataType = getDataType(data); let result; if (dataType === 'Object') { result = {}; } else if (dataType === 'Ar...
{ const dataType = Object.prototype.toString.call(data); if (dataType === '[object Object]') { return 'Object'; } if (dataType === '[object Array]') { return 'Array'; } if (dataType === '[object Number]') { return 'Number'; } if (dataType === '[object String]') { ...
identifier_body
clone.ts
// export function deepClone(obj: any) { // return JSON.parse(JSON.stringify(obj)); // } function
(data: any) { const dataType = Object.prototype.toString.call(data); if (dataType === '[object Object]') { return 'Object'; } if (dataType === '[object Array]') { return 'Array'; } if (dataType === '[object Number]') { return 'Number'; } if (dataType === '[object ...
getDataType
identifier_name
SuggestionsLazyTest.ts
import * as assert from "assert"; import { IDocumentStore, IndexDefinition, IndexFieldOptions, PutIndexesOperation } from "../../../src"; import { disposeTestDocumentStore, testContext } from "../../Utils/TestUtil"; import { User } from "../../Assets/Entities"; describe("SuggestionsLazyTest", function () { let s...
indexDefinition.name = "Test"; indexDefinition.maps = new Set<string>(["from doc in docs.Users select new { doc.name }"]); const indexFieldOptions = new IndexFieldOptions(); indexFieldOptions.suggestions = true; indexDefinition.fields = { name: indexFieldOptions ...
it("using linq", async () => { const indexDefinition = new IndexDefinition();
random_line_split
test_v2v_ansible.py
import fauxfactory import pytest from cfme import test_requirements from cfme.fixtures.provider import rhel7_minimal from cfme.infrastructure.provider.rhevm import RHEVMProvider from cfme.infrastructure.provider.virtualcenter import VMwareProvider from cfme.markers.env_markers.provider import ONE_PER_TYPE from cfme.ma...
# vm_obj is a list, with only 1 VM object, hence [0] src_vm_obj = form_data_vm_obj_single_datastore.vm_list[0] migration_plan_collection = appliance.collections.v2v_plans migration_plan = migration_plan_collection.create( name="plan_{}".format(fauxfactory.gen_alphanumeric()), descript...
infrastructure_mapping_collection.delete(mapping)
identifier_body
test_v2v_ansible.py
import fauxfactory import pytest from cfme import test_requirements from cfme.fixtures.provider import rhel7_minimal from cfme.infrastructure.provider.rhevm import RHEVMProvider from cfme.infrastructure.provider.virtualcenter import VMwareProvider from cfme.markers.env_markers.provider import ONE_PER_TYPE from cfme.ma...
(request, appliance, machine_credential, ansible_repository, playbook_type): """Add provisioning and retire ansible catalog item""" cat_item = appliance.collections.catalog_items.create( catalog_item_class=appliance.collections.catalog_items.ANSIBLE_PLAYBOOK, name=fauxfactory.gen_alphanumeric(),...
catalog_item
identifier_name
test_v2v_ansible.py
import fauxfactory import pytest from cfme import test_requirements from cfme.fixtures.provider import rhel7_minimal from cfme.infrastructure.provider.rhevm import RHEVMProvider from cfme.infrastructure.provider.virtualcenter import VMwareProvider from cfme.markers.env_markers.provider import ONE_PER_TYPE from cfme.ma...
return cat_item @pytest.mark.parametrize( "form_data_vm_obj_single_datastore", [["nfs", "nfs", rhel7_minimal]], indirect=True ) def test_migration_playbooks(request, appliance, v2v_providers, host_creds, conversion_tags, ansible_repository, form_data_vm_obj_single_datastore): ...
cat_item.delete()
conditional_block
test_v2v_ansible.py
import fauxfactory import pytest from cfme import test_requirements from cfme.fixtures.provider import rhel7_minimal from cfme.infrastructure.provider.rhevm import RHEVMProvider from cfme.infrastructure.provider.virtualcenter import VMwareProvider from cfme.markers.env_markers.provider import ONE_PER_TYPE from cfme.ma...
) def test_migration_playbooks(request, appliance, v2v_providers, host_creds, conversion_tags, ansible_repository, form_data_vm_obj_single_datastore): """Test for migrating vms with pre and post playbooks""" creds = credentials[v2v_providers.vmware_provider.data.templates.get("rhel7...
return cat_item @pytest.mark.parametrize( "form_data_vm_obj_single_datastore", [["nfs", "nfs", rhel7_minimal]], indirect=True
random_line_split
lib.rs
// Copyright 2016 Mozilla Foundation // // 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...
1 } }); } fn init_logging() { if env::var(LOGGING_ENV).is_ok() { match env_logger::Builder::from_env(LOGGING_ENV).try_init() { Ok(_) => (), Err(e) => panic!(format!("Failed to initalize logging: {:?}", e)), } } }
{ init_logging(); std::process::exit(match cmdline::parse() { Ok(cmd) => match commands::run_command(cmd) { Ok(s) => s, Err(e) => { eprintln!("sccache: error: {}", e); for e in e.chain().skip(1) { eprintln!("sccache: caused by: ...
identifier_body
lib.rs
// Copyright 2016 Mozilla Foundation // // 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...
}); } fn init_logging() { if env::var(LOGGING_ENV).is_ok() { match env_logger::Builder::from_env(LOGGING_ENV).try_init() { Ok(_) => (), Err(e) => panic!(format!("Failed to initalize logging: {:?}", e)), } } }
{ println!("sccache: {}", e); for e in e.chain().skip(1) { println!("sccache: caused by: {}", e); } cmdline::get_app().print_help().unwrap(); println!(); 1 }
conditional_block
lib.rs
// Copyright 2016 Mozilla Foundation // // 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...
mod protocol; pub mod server; #[cfg(feature = "simple-s3")] mod simples3; #[doc(hidden)] pub mod util; use std::env; const LOGGING_ENV: &str = "SCCACHE_LOG"; pub fn main() { init_logging(); std::process::exit(match cmdline::parse() { Ok(cmd) => match commands::run_command(cmd) { Ok(s) => ...
pub mod config; pub mod dist; mod jobserver; mod mock_command;
random_line_split
lib.rs
// Copyright 2016 Mozilla Foundation // // 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...
() { if env::var(LOGGING_ENV).is_ok() { match env_logger::Builder::from_env(LOGGING_ENV).try_init() { Ok(_) => (), Err(e) => panic!(format!("Failed to initalize logging: {:?}", e)), } } }
init_logging
identifier_name
searchBox.component.spec.ts
import { SearchBoxComponent } from './searchBox.component'; interface ITestObject { prop: string; } describe('SearchBoxComponent', () => {
beforeEach(() => { searchBox = new SearchBoxComponent<ITestObject>(); emitSpy = sinon.spy(); searchBox.filteredItems = <any>{ emit: emitSpy }; }); it('should filter the items and emit the results', () => { const items: ITestObject[] = [ { prop: 'something' }, { prop: 'other' }, { prop: 'something 2...
let searchBox: SearchBoxComponent<ITestObject>; let emitSpy: Sinon.SinonSpy;
random_line_split
mod.rs
_did_open_text_document, on_did_save_text_document, }, ExtensionConfig, }; use common::{PerfLogEvent, PerfLogger}; use crossbeam::{SendError, Sender}; use log::debug; use lsp_notification_dispatch::LSPNotificationDispatch; use lsp_request_dispatch::LSPRequestDispatch; use lsp_server::{ErrorCode, Notific...
{ let notification = LSPNotificationDispatch::new(notification, lsp_state) .on_notification_sync::<DidOpenTextDocument>(on_did_open_text_document)? .on_notification_sync::<DidCloseTextDocument>(on_did_close_text_document)? .on_notification_sync::<DidChangeTextDocument>(on_did_change_text_doc...
identifier_body
mod.rs
, graphql_tools::GraphQLExecuteQuery, hover::on_hover, js_language_server::JSLanguageServer, lsp::{ set_initializing_status, CompletionOptions, Connection, GotoDefinition, HoverRequest, InitializeParams, Message, ServerCapabilities, ServerResponse, TextDocumentSyncCapability, Tex...
dispatch_notification
identifier_name
mod.rs
_of_type_definition, on_goto_definition, GetSourceLocationOfTypeDefinition, }, graphql_tools::on_graphql_execute_query, graphql_tools::GraphQLExecuteQuery, hover::on_hover, js_language_server::JSLanguageServer, lsp::{ set_initializing_status, CompletionOptions, Connection, GotoDe...
} } } fn handle_request<TPerfLogger: PerfLogger + 'static>( lsp_state: &mut LSPState<TPerfLogger>, request: lsp_server::Request, sender: &Sender<Message>, perf_logger: &Arc<TPerfLogger>, ) -> Result<(), SendError<Message>> { debug!("request received {:?}", request); let get_server_...
{ panic!("Relay Language Server receiver error {:?}", error); }
conditional_block
mod.rs
use crate::{ code_action::on_code_action, completion::on_completion, goto_definition::{ on_get_source_location_of_type_definition, on_goto_definition, GetSourceLocationOfTypeDefinition, }, graphql_tools::on_graphql_execute_query, graphql_tools::GraphQLExecuteQuery, hover::on_...
mod lsp_state; mod lsp_state_resources;
random_line_split
systementitytype_args.py
# # Copyright (c) 2008-2015 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
(self, datasource) : ur"""Specifies the source which contains all the stored counter values. """ try : self._datasource = datasource except Exception as e: raise e
datasource
identifier_name
systementitytype_args.py
# # Copyright (c) 2008-2015 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
ur"""Specifies the source which contains all the stored counter values. """ try : self._datasource = datasource except Exception as e: raise e
identifier_body
systementitytype_args.py
# # Copyright (c) 2008-2015 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
try : self._datasource = datasource except Exception as e: raise e
@datasource.setter def datasource(self, datasource) : ur"""Specifies the source which contains all the stored counter values. """
random_line_split
HeadData.tsx
/* Copyright (C) 2019, 2020 Monomax Software Pty Ltd * * This file is part of Dnote.
* (at your option) any later version. * * Dnote is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a...
* * Dnote 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
random_line_split
setup.py
import os import sys from setuptools import setup, find_packages version = '0.3.3' def get_package_manifest(filename): packages = [] with open(filename) as package_file: for line in package_file.readlines(): line = line.strip() if not line: continue ...
include_package_data = True, packages=find_packages(exclude=["examples", "tests"]), zip_safe = False, )
test_suite='nose.collector',
random_line_split
setup.py
import os import sys from setuptools import setup, find_packages version = '0.3.3' def get_package_manifest(filename): packages = [] with open(filename) as package_file: for line in package_file.readlines(): line = line.strip() if not line: continue ...
(f): with open(os.path.join(os.path.dirname(__file__), f)) as f: return f.read().strip() setup( name='sockjs-gevent', version=version, description=('gevent base sockjs server'), long_description='\n\n'.join((read('README.md'), read('CHANGES.txt'))), classifiers=[ "Intended Audi...
read
identifier_name
setup.py
import os import sys from setuptools import setup, find_packages version = '0.3.3' def get_package_manifest(filename): packages = [] with open(filename) as package_file: for line in package_file.readlines(): line = line.strip() if not line: continue ...
def read(f): with open(os.path.join(os.path.dirname(__file__), f)) as f: return f.read().strip() setup( name='sockjs-gevent', version=version, description=('gevent base sockjs server'), long_description='\n\n'.join((read('README.md'), read('CHANGES.txt'))), classifiers=[ "In...
""" :returns: A list of packages required for running the tests. """ packages = get_package_manifest('requirements_dev.txt') try: from unittest import mock except ImportError: packages.append('mock') if sys.version_info[:2] < (2, 7): packages.append('unittest2') re...
identifier_body
setup.py
import os import sys from setuptools import setup, find_packages version = '0.3.3' def get_package_manifest(filename): packages = [] with open(filename) as package_file: for line in package_file.readlines(): line = line.strip() if not line: continue ...
if line.startswith('-e '): # not a valid package continue packages.append(line) return packages def get_install_requires(): """ :returns: A list of packages required for installation. """ return get_package_manifest('requirements.txt') ...
continue
conditional_block
wad.rs
use std::u8; use nom::{self, IResult, Needed, le_u32}; use super::util::fixed_length_ascii; use ::errors::{Result, nom_to_result}; use ::archive::wad::{BareWAD, BareWADHeader, BareWADDirectoryEntry, WADType}; named!(iwad_tag<WADType>, value!(WADType::IWAD, tag!(b"IWAD"))); named!(pwad_tag<WADType>, value!(WADType::...
{ // FIXME ambiguous whether the error was from parsing the header or the entries let header = nom_to_result("wad header", buf, wad_header(buf))?; // TODO buf is not actually the right place here let entries = nom_to_result("wad index", buf, wad_directory(buf, &header))?; Ok(BareWAD{ buffer: buf, he...
identifier_body
wad.rs
use std::u8; use nom::{self, IResult, Needed, le_u32}; use super::util::fixed_length_ascii; use ::errors::{Result, nom_to_result}; use ::archive::wad::{BareWAD, BareWADHeader, BareWADDirectoryEntry, WADType};
named!(wad_header<BareWADHeader>, do_parse!( identification: return_error!( nom::ErrorKind::Custom(1), alt!(iwad_tag | pwad_tag)) >> numlumps: le_u32 >> infotableofs: le_u32 >> (BareWADHeader{ identification, numlumps, infotableofs }) )); named!(wad_entry<BareWADDirectoryEntry>, dbg_d...
named!(iwad_tag<WADType>, value!(WADType::IWAD, tag!(b"IWAD"))); named!(pwad_tag<WADType>, value!(WADType::PWAD, tag!(b"PWAD")));
random_line_split
wad.rs
use std::u8; use nom::{self, IResult, Needed, le_u32}; use super::util::fixed_length_ascii; use ::errors::{Result, nom_to_result}; use ::archive::wad::{BareWAD, BareWADHeader, BareWADDirectoryEntry, WADType}; named!(iwad_tag<WADType>, value!(WADType::IWAD, tag!(b"IWAD"))); named!(pwad_tag<WADType>, value!(WADType::...
<'a>(buf: &'a [u8], header: &BareWADHeader) -> IResult<&'a [u8], Vec<BareWADDirectoryEntry<'a>>> { let lumpct = header.numlumps as usize; let offset = header.infotableofs as usize; // TODO can i unhardcode the size of a wad entry here? let tablelen = lumpct * 16; if buf.len() < offset + tablelen { ...
wad_directory
identifier_name
wad.rs
use std::u8; use nom::{self, IResult, Needed, le_u32}; use super::util::fixed_length_ascii; use ::errors::{Result, nom_to_result}; use ::archive::wad::{BareWAD, BareWADHeader, BareWADDirectoryEntry, WADType}; named!(iwad_tag<WADType>, value!(WADType::IWAD, tag!(b"IWAD"))); named!(pwad_tag<WADType>, value!(WADType::...
let mut ret = Vec::with_capacity(lumpct); let mut parse_from = &buf[offset..]; for _ in 0..lumpct { let (leftovers, entry) = try_parse!(parse_from, wad_entry); ret.push(entry); parse_from = leftovers; } Ok((parse_from, ret)) } // TODO problems to scan a wad map for: // - ...
{ return Err(nom::Err::Incomplete(Needed::Size(tablelen))); }
conditional_block
mirrorball.ts
const got2 = await read(fileHandle, sampleBuffer, 0, sampleSize, 0); hash.update(sampleBuffer); } return hash.digest("base64"); } finally { await fs.close(fileHandle); } }; function makePathTo(fileOrDir: string) { const dirName = path.dirname(fileOrDir); ...
} progStr += "]"; return progStr; } const padding = " "; function makeProgress(totalBytes: number) { const throttle = makeThrottle(); let totalProgress = 0; return (progressBytes: number | null) => { if (progressBytes === null) { process.stdout...
progStr += "|"; } for (let n = units + 1; n < barLength; n++) { progStr += "_";
random_line_split
mirrorball.ts
const got2 = await read(fileHandle, sampleBuffer, 0, sampleSize, 0); hash.update(sampleBuffer); } return hash.digest("base64"); } finally { await fs.close(fileHandle); } }; function makePathTo(fileOrDir: string) { const dirName = path.dirname(fileOrDir); ...
} } for (const hash in states[1]) { const first = states[0][hash], second = states[1][hash]; if (!first) { extras.push({ from: folderPaths[1], to: folderPaths[0], path: second.path, size: second.size ...
{ // var progresses = makeStateProgresses(); const states = await Promise.all(folderPaths.map((p, i) => fetchState(p))), extras: Extra[] = []; const sameFileDifferentPaths: { first: FileState, second: FileState }[] = []; for (const hash in states[0]) { const first = states[0][hash], ...
identifier_body
mirrorball.ts
StateWithHash } = {}, newState: { [hash: string]: FileState } = {}; try { state = JSON.parse(fs.readFileSync(stateFilePath, { encoding: "utf8" })); } catch (x) { } const previousHashes = Object.keys(state); const previousCount = previousHashes.length; previousHashes.forEach(hash =>...
{ deleteFile(extra.from + extra.path); }
conditional_block
mirrorball.ts
<T>(impl: (c: Callback<T>) => void) { return new Promise<T>((resolve, reject) => { impl((err, result) => { if (err) { reject(err); } else { resolve(result); } }); }); } function read(fd: number, buffer: Buffer, offset: number, ...
p
identifier_name
allocator.py
__author__ = "Jon Dawson" __copyright__ = "Copyright (C) 2012, Jonathan P Dawson" __version__ = "0.1" class Allocator: """Maintain a pool of registers, variables and arrays. Keep track of what they are used for.""" def __init__(self, reuse): self.registers = [] self.all_registers = {} ...
(self, reg): return self.all_registers[reg][1] def new(self, size, name="temporary_register"): assert type(size) == int reg = 0 while reg in self.registers or (reg in self.all_registers and self.regsize(reg) != size): reg += 1 self.registers.append(reg) s...
regsize
identifier_name
allocator.py
__author__ = "Jon Dawson" __copyright__ = "Copyright (C) 2012, Jonathan P Dawson" __version__ = "0.1" class Allocator: """Maintain a pool of registers, variables and arrays. Keep track of what they are used for.""" def __init__(self, reuse): self.registers = [] self.all_registers = {} ...
def new(self, size, name="temporary_register"): assert type(size) == int reg = 0 while reg in self.registers or (reg in self.all_registers and self.regsize(reg) != size): reg += 1 self.registers.append(reg) self.all_registers[reg] = (name, size) return r...
return self.all_registers[reg][1]
identifier_body
allocator.py
__author__ = "Jon Dawson" __copyright__ = "Copyright (C) 2012, Jonathan P Dawson" __version__ = "0.1" class Allocator: """Maintain a pool of registers, variables and arrays. Keep track of what they are used for.""" def __init__(self, reuse): self.registers = [] self.all_registers = {} ...
self.registers.append(reg) self.all_registers[reg] = (name, size) return reg def free(self, register): if register in self.registers and self.reuse: self.registers.remove(register)
reg += 1
conditional_block
allocator.py
__author__ = "Jon Dawson" __copyright__ = "Copyright (C) 2012, Jonathan P Dawson" __version__ = "0.1" class Allocator: """Maintain a pool of registers, variables and arrays. Keep track of what they are used for.""" def __init__(self, reuse): self.registers = [] self.all_registers = {} ...
def free(self, register): if register in self.registers and self.reuse: self.registers.remove(register)
reg += 1 self.registers.append(reg) self.all_registers[reg] = (name, size) return reg
random_line_split
projstore.py
targets', 'trans': 'transfiles', } } def __del__(self): try: self.close() except Exception: pass # ACCESSORS # def _get_sourcefiles(self): """Read-only access to ``self._sourcefiles``.""" return tuple(self._sourcef...
conversions_el = etree.Element('conversions') for in_fname, (out_fname, templ_fname) in six.iteritems(self.convert_map): if in_fname not in self._files or out_fname not in self._files: continue conv_el = etree.Element('conv') input_el = et...
conditional_block
projstore.py
'sources/doc.odt': ('trans/doc.odt.xlf', None), # 'trans/doc.odt.xlf': ('targets/doc.odt', 'sources/doc.odt') #} # The following dict groups together sets of mappings from a file # "type" string ("src", "tgt" or "trans") to various other values # or objects. self.T...
"""Remove the project file with name ``pfname`` and add the contents from ``infile`` to the project under the same file name. :returns: the results from :meth:`ProjectStore.append_file`. """ ftype = self.get_filename_type(pfname) self.remove_file(pfname) self.app...
def update_file(self, pfname, infile):
random_line_split
projstore.py
sources/doc.odt': ('trans/doc.odt.xlf', None), # 'trans/doc.odt.xlf': ('targets/doc.odt', 'sources/doc.odt') #} # The following dict groups together sets of mappings from a file # "type" string ("src", "tgt" or "trans") to various other values # or objects. self.TYP...
(self, realfname): """Try and find a project file name for the given real file name.""" for fname in self._files: if fname == realfname or self._files[fname] == realfname: return fname raise ValueError('Real file not in project store: %s' % (realfname)) def load(...
get_proj_filename
identifier_name
projstore.py
sources/doc.odt': ('trans/doc.odt.xlf', None), # 'trans/doc.odt.xlf': ('targets/doc.odt', 'sources/doc.odt') #} # The following dict groups together sets of mappings from a file # "type" string ("src", "tgt" or "trans") to various other values # or objects. self.TYP...
def remove_sourcefile(self, fname): self.remove_file(fname, ftype='src') def remove_targetfile(self, fname): self.remove_file(fname, ftype='tgt') def remove_transfile(self, fname): self.remove_file(fname, ftype='trans') def close(self): self.save() def get_file(...
"""Remove the file with the given project name from the project. If the file type ('src', 'trans' or 'tgt') is not given, it is guessed. """ if fname not in self._files: raise FileNotInProjectError(fname) if not ftype: # Guess file type (source/trans/target) ...
identifier_body
events.js
/** @license MIT License (c) copyright B Cavalier & J Hann */ /** * wire/dojo/events plugin * wire plugin that can connect event handlers after an object is * initialized, and disconnect them when an object is destroyed. * This implementation uses dojo.connect and dojo.disconnect to do * the work of connecting an...
(source, connect, options, wire) { return connection.parse(source, connect, options, wire, handleConnection); } /* Function: connectFacet Setup connections for each specified in the connects param. Each key in connects is a reference, and the corresponding value is an object whose keys ar...
connect
identifier_name
events.js
/** @license MIT License (c) copyright B Cavalier & J Hann */ /** * wire/dojo/events plugin * wire plugin that can connect event handlers after an object is * initialized, and disconnect them when an object is destroyed. * This implementation uses dojo.connect and dojo.disconnect to do * the work of connecting an...
resolver.resolve(); } }, facets: { connect: { connect: function(resolver, facet, wire) { resolver.resolve(connectFacet(wire, facet)); } } } }; } }; });
{ events.disconnect(connectHandles[i]); }
conditional_block
events.js
/** @license MIT License (c) copyright B Cavalier & J Hann */ /** * wire/dojo/events plugin * wire plugin that can connect event handlers after an object is * initialized, and disconnect them when an object is destroyed. * This implementation uses dojo.connect and dojo.disconnect to do * the work of connecting an...
/* Function: connectFacet Setup connections for each specified in the connects param. Each key in connects is a reference, and the corresponding value is an object whose keys are event names, and whose values are methods of object to invoke. For example: connect: { "refToOtherThin...
{ return connection.parse(source, connect, options, wire, handleConnection); }
identifier_body
events.js
/** @license MIT License (c) copyright B Cavalier & J Hann */ /** * wire/dojo/events plugin * wire plugin that can connect event handlers after an object is * initialized, and disconnect them when an object is destroyed. * This implementation uses dojo.connect and dojo.disconnect to do * the work of connecting an...
} } }; } }; });
connect: function(resolver, facet, wire) { resolver.resolve(connectFacet(wire, facet)); }
random_line_split
mod.rs
pub fn target_bin(&self, target: &str, b: &str) -> PathBuf { self.build_dir().join(target).join("debug") .join(&format!("{}{}", b, env::consts::EXE_SUFFIX)) } pub fn build_dir(&self) -> PathBuf { self.root.join("target") } pub fn process<T: AsRef<OsStr>>(&self,...
(mut self, expected: i32) -> Execs { self.expect_exit_code = Some(expected); self } pub fn with_stdout_contains<S: ToString>(mut self, expected: S) -> Execs { self.expect_stdout_contains.push(expected.to_string()); self } pub fn with_stderr_contains<S: ToString>(mut sel...
with_status
identifier_name
mod.rs
pub fn target_bin(&self, target: &str, b: &str) -> PathBuf { self.build_dir().join(target).join("debug") .join(&format!("{}{}", b, env::consts::EXE_SUFFIX)) } pub fn build_dir(&self) -> PathBuf { self.root.join("target") } pub fn process<T: AsRef<OsStr>>(&self,...
`{}`", diffs.connect("\n"), String::from_utf8_lossy(extra))) } fn match_json(&self, expected: &Json, stdout: &[u8]) -> ham::MatchResult { let stdout = match str::from_utf8(stdout) { Err(..) => return Err("stdout was not utf8 encoded"....
other output:\n\
random_line_split
mod.rs
fn match_stdout(&self, actual: &Output) -> ham::MatchResult { try!(self.match_std(self.expect_stdout.as_ref(), &actual.stdout, "stdout", &actual.stderr, false)); for expect in self.expect_stdout_contains.iter() { try!(self.match_std(Some(expect), &actual.stdout, ...
{ let actual = String::from_utf8_lossy(actual); let actual = actual.to_string(); ham::expect(actual == self.expected, actual) }
identifier_body
commands.rs
use std::string::String; use regex::Regex; use platform::EOL; use REHolder; pub fn show_help() -> String { "This is help page.".to_string() + EOL.as_ref() + "Or at leas will be....".as_ref() } pub fn set_regex(regex: &str, current_re: &mut REHolder) -> String { current_re.set(Regex::new(regex).unwrap())...
(input: &str, current_re: &REHolder) -> String { if !current_re.re.is_match(input) { return "Input does not match the pattern. ".to_string(); } let mut output = String::new(); for (ind, cap) in current_re.re.captures_iter(input).enumerate() { if ind > 0 { output += format!(...
test_input
identifier_name
commands.rs
use std::string::String; use regex::Regex; use platform::EOL; use REHolder; pub fn show_help() -> String { "This is help page.".to_string() + EOL.as_ref() + "Or at leas will be....".as_ref() } pub fn set_regex(regex: &str, current_re: &mut REHolder) -> String { current_re.set(Regex::new(regex).unwrap())...
let mut output = String::new(); for (ind, cap) in current_re.re.captures_iter(input).enumerate() { if ind > 0 { output += format!("==========={}", EOL).as_ref(); } output += format!(">>> Match #{}, capture groups: {}", ind + 1, EOL).as_ref(); for c_ind in 0..cap.le...
{ return "Input does not match the pattern. ".to_string(); }
conditional_block
commands.rs
use std::string::String; use regex::Regex; use platform::EOL; use REHolder; pub fn show_help() -> String { "This is help page.".to_string() + EOL.as_ref() +
current_re.set(Regex::new(regex).unwrap()); format!("Regex was set: {}\n", regex) } pub fn test_input(input: &str, current_re: &REHolder) -> String { if !current_re.re.is_match(input) { return "Input does not match the pattern. ".to_string(); } let mut output = String::new(); for (ind...
"Or at leas will be....".as_ref() } pub fn set_regex(regex: &str, current_re: &mut REHolder) -> String {
random_line_split
commands.rs
use std::string::String; use regex::Regex; use platform::EOL; use REHolder; pub fn show_help() -> String { "This is help page.".to_string() + EOL.as_ref() + "Or at leas will be....".as_ref() } pub fn set_regex(regex: &str, current_re: &mut REHolder) -> String
pub fn test_input(input: &str, current_re: &REHolder) -> String { if !current_re.re.is_match(input) { return "Input does not match the pattern. ".to_string(); } let mut output = String::new(); for (ind, cap) in current_re.re.captures_iter(input).enumerate() { if ind > 0 { ...
{ current_re.set(Regex::new(regex).unwrap()); format!("Regex was set: {}\n", regex) }
identifier_body
test_empty_dataset.py
import unittest import numpy as np from chainermn.datasets import create_empty_dataset import chainerx as chx class TestEmptyDataset(unittest.TestCase): def setUp(self): pass def check_create_empty_dataset(self, original_dataset): empty_dataset = create_empty_dataset(original_dataset) ...
def test_empty_dataset_numpy(self): self.check_empty_dataset(np) def test_empty_dataset_chx(self): self.check_empty_dataset(chx) def check_empty_dataset(self, xp): n = 10 self.check_create_empty_dataset([]) self.check_create_empty_dataset([0]) self.check_...
self.assertEqual((), empty_dataset[i])
conditional_block
test_empty_dataset.py
import unittest import numpy as np from chainermn.datasets import create_empty_dataset import chainerx as chx class TestEmptyDataset(unittest.TestCase): def setUp(self): pass def check_create_empty_dataset(self, original_dataset):
def test_empty_dataset_numpy(self): self.check_empty_dataset(np) def test_empty_dataset_chx(self): self.check_empty_dataset(chx) def check_empty_dataset(self, xp): n = 10 self.check_create_empty_dataset([]) self.check_create_empty_dataset([0]) self.check_...
empty_dataset = create_empty_dataset(original_dataset) self.assertEqual(len(original_dataset), len(empty_dataset)) for i in range(len(original_dataset)): self.assertEqual((), empty_dataset[i])
identifier_body
test_empty_dataset.py
import unittest import numpy as np from chainermn.datasets import create_empty_dataset import chainerx as chx class TestEmptyDataset(unittest.TestCase): def setUp(self): pass def check_create_empty_dataset(self, original_dataset): empty_dataset = create_empty_dataset(original_dataset) ...
self.check_create_empty_dataset(xp.array([0])) self.check_create_empty_dataset(xp.arange(n)) self.check_create_empty_dataset(xp.arange(n * 5 - 1))
self.check_create_empty_dataset([0]) self.check_create_empty_dataset(list(range(n))) self.check_create_empty_dataset(list(range(n * 5 - 1))) self.check_create_empty_dataset(xp.array([]))
random_line_split
test_empty_dataset.py
import unittest import numpy as np from chainermn.datasets import create_empty_dataset import chainerx as chx class TestEmptyDataset(unittest.TestCase): def
(self): pass def check_create_empty_dataset(self, original_dataset): empty_dataset = create_empty_dataset(original_dataset) self.assertEqual(len(original_dataset), len(empty_dataset)) for i in range(len(original_dataset)): self.assertEqual((), empty_dataset[i]) def ...
setUp
identifier_name
test_tctototal_streaming.py
#!/usr/bin/env python # Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia 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 ...
(self): envelope = range(22050) envelope.reverse() envelope = range(22050) + envelope gen = VectorInput(envelope) tcToTotal = sTCToTotal() p = Pool() gen.data >> tcToTotal.envelope tcToTotal.TCToTotal >> (p, 'lowlevel.tctototal') run...
testRegression
identifier_name
test_tctototal_streaming.py
#!/usr/bin/env python # Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia 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 ...
TextTestRunner(verbosity=2).run(suite)
conditional_block
test_tctototal_streaming.py
#!/usr/bin/env python # Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia 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 ...
self.assertRaises(RuntimeError, lambda: run(gen)) def testRegression(self): envelope = range(22050) envelope.reverse() envelope = range(22050) + envelope gen = VectorInput(envelope) tcToTotal = sTCToTotal() p = Pool() gen.data >> tcTo...
def testEmpty(self): gen = VectorInput([]) tcToTotal = sTCToTotal() p = Pool() gen.data >> tcToTotal.envelope tcToTotal.TCToTotal >> (p, 'lowlevel.tctototal') run(gen) self.assertRaises(KeyError, lambda: p['lowlevel.tctototal']) def testOneVa...
identifier_body
test_tctototal_streaming.py
#!/usr/bin/env python # Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia 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 ...
tcToTotal.TCToTotal >> (p, 'lowlevel.tctototal') self.assertRaises(RuntimeError, lambda: run(gen)) def testRegression(self): envelope = range(22050) envelope.reverse() envelope = range(22050) + envelope gen = VectorInput(envelope) tcToTotal = sT...
gen = VectorInput([1]) tcToTotal = sTCToTotal() p = Pool() gen.data >> tcToTotal.envelope
random_line_split
edit_post.js
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {PostOptions} from '@support/ui/component'; import {isAndroid} from '@support/utils'; class EditPostScreen { testID = { editPostScreen: 'edit_post.screen', closeEditPostButton: 'c...
export default editPostScreen;
const editPostScreen = new EditPostScreen();
random_line_split
edit_post.js
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {PostOptions} from '@support/ui/component'; import {isAndroid} from '@support/utils'; class
{ testID = { editPostScreen: 'edit_post.screen', closeEditPostButton: 'close.edit_post.button', messageInput: 'edit_post.message.input', saveButton: 'edit_post.save.button', }; editPostScreen = element(by.id(this.testID.editPostScreen)); closeEditPostButton = element(by...
EditPostScreen
identifier_name
edit_post.js
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {PostOptions} from '@support/ui/component'; import {isAndroid} from '@support/utils'; class EditPostScreen { testID = { editPostScreen: 'edit_post.screen', closeEditPostButton: 'c...
return this.editPostScreen; }; open = async () => { // # Swipe up panel on Android if (isAndroid()) { await PostOptions.slideUpPanel.swipe('up'); } // # Open edit post screen await PostOptions.editAction.tap(); return this.toBeVisible(); ...
{ await expect(this.editPostScreen).toExist(); }
conditional_block
lightcontrol.component.ts
import { Component, AfterViewChecked, Input, OnInit, OnChanges, SimpleChange, DoCheck, KeyValueDiffers, KeyValueChangeRecord, ChangeDetectorRef} from '@angular/core'; import {Light} from './light' import {LightControlService } from './lightcontrol.service'; import {ColorTransformations} from './col...
ngAfterViewChecked() { this.cdRef.detectChanges(); } ngDoCheck(){ var changes = this.differ.diff(this.selectedLight.state); if(changes) { console.log('Selected Light State - changes detected'); //this.lightService.setLight(this.selectedLight); ...
{ //this.sliderHue.value = this.selectedLight.hue; console.log(changes); //selectedLight changed - do not send event this.selectedLight.changegByEvent = true; //this.hueValue = this.selectedLight.hue; }
identifier_body
lightcontrol.component.ts
import { Component, AfterViewChecked, Input, OnInit, OnChanges, SimpleChange, DoCheck, KeyValueDiffers, KeyValueChangeRecord, ChangeDetectorRef} from '@angular/core'; import {Light} from './light' import {LightControlService } from './lightcontrol.service'; import {ColorTransformations} from './col...
else{ //this.selectedLight.changegByEvent = false; } this.selectedLight.changegByEvent = false; //this.boxColor = "red"; changes.forEachChangedItem((r : KeyValueChangeRecord) => { //console.log(r) ...
{ this.lightService.setLight(this.selectedLight); console.log("LightControlComponent::setLight(selectedLight)"); }
conditional_block
lightcontrol.component.ts
import { Component, AfterViewChecked, Input, OnInit, OnChanges, SimpleChange, DoCheck, KeyValueDiffers, KeyValueChangeRecord, ChangeDetectorRef} from '@angular/core'; import {Light} from './light' import {LightControlService } from './lightcontrol.service'; import {ColorTransformations} from './col...
() { this.cdRef.detectChanges(); } ngDoCheck(){ var changes = this.differ.diff(this.selectedLight.state); if(changes) { console.log('Selected Light State - changes detected'); //this.lightService.setLight(this.selectedLight); var hueNormal = ...
ngAfterViewChecked
identifier_name
lightcontrol.component.ts
import { Component, AfterViewChecked, Input, OnInit, OnChanges, SimpleChange, DoCheck, KeyValueDiffers, KeyValueChangeRecord, ChangeDetectorRef} from '@angular/core'; import {Light} from './light' import {LightControlService } from './lightcontrol.service'; import {ColorTransformations} from './col...
ngDoCheck(){ var changes = this.differ.diff(this.selectedLight.state); if(changes) { console.log('Selected Light State - changes detected'); //this.lightService.setLight(this.selectedLight); var hueNormal = this.selectedLight.state.hue/65535; var ...
}
random_line_split
jquery.highlightText.js
/** * Plugin that highlights matched word partials in a given element. * TODO: Add a function for restoring the previous text. * TODO: Accept mappings for converting shortcuts like WP: to Wikipedia:. */ ( function ( $ ) { $.highlightText = { // Split our pattern string at spaces and run our highlight function ...
return node; }, // scans a node looking for the pattern and wraps a span around each match innerHighlight: function ( node, pat ) { var i, match, pos, spannode, middlebit, middleclone; // if this is a text node if ( node.nodeType === 3 ) { // TODO - need to be smarter about the character matchin...
{ if ( patArray[i].length === 0 ) { continue; } $.highlightText.innerHighlight( node, patArray[i] ); }
conditional_block
jquery.highlightText.js
/** * Plugin that highlights matched word partials in a given element. * TODO: Add a function for restoring the previous text. * TODO: Accept mappings for converting shortcuts like WP: to Wikipedia:. */ ( function ( $ ) { $.highlightText = { // Split our pattern string at spaces and run our highlight function ...
// scans a node looking for the pattern and wraps a span around each match innerHighlight: function ( node, pat ) { var i, match, pos, spannode, middlebit, middleclone; // if this is a text node if ( node.nodeType === 3 ) { // TODO - need to be smarter about the character matching here. // non lati...
} return node; },
random_line_split