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 |
|---|---|---|---|---|
App.tsx | import {
AreaBump,
Bar,
Bullet,
Bump,
Calendar,
Chord,
Choropleth,
CirclePacking,
Funnel,
GeoMap,
HeatMap,
Line,
Marimekko,
Network,
ParallelCoordinates,
Pie,
Radar,
Sankey,
ScatterPlot,
Stream,
Sunburst,
SwarmPlot,
TreeMap,
Voronoi,
Waffle,
} from './charts'
import {
... | () {
return (
<Router>
<div className={css({ display: 'flex', height: '100vh' })}>
<Navigation />
<div
className={css({
display: 'flex',
flex: 1,
flexDirection: 'column',
})}>
<ChartContainer title={<Title />}>
<Ro... | App | identifier_name |
environment_header_widget.tsx | /*
* Copyright 2021 ThoughtWorks, 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 or agr... | <KeyValuePair inline={true} data={new Map([["Pipeline Count", environment.pipelines().length]])}/>
<KeyValuePair inline={true} data={new Map([["Agent Count", agentCount]])}/>
</div>;
}
} | random_line_split | |
environment_header_widget.tsx | /*
* Copyright 2021 ThoughtWorks, 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 or agr... | extends MithrilViewComponent<EnvironmentHeaderAttrs> {
view(vnode: m.Vnode<EnvironmentHeaderAttrs>) {
const environment = vnode.attrs.environment;
const agentCount = environment.agents().filter((agent) => vnode.attrs.agents().hasAgent(agent.uuid())).length;
return <div class={styles.envHeader} data-test... | EnvironmentHeader | identifier_name |
app.ts | /**
* @module Core
*/
/// <reference path="corePlugin.ts"/>
module Core {
/**
* Controller that's attached to hawtio's drop-down console, mainly handles the
* clipboard icon at the bottom-right of the console.
*
* @method ConsoleController
* @for Core
* @static
* @param {*} $scope
* @param ... |
function clearLogs() {
$element.find('#log-panel-statements').children().remove();
}
};
}]);
/**
* Outermost controller attached to almost the root of the document, handles
* logging in and logging out, the PID/container indicator at the bottom right
* of the window and the docum... | {
var text = $templateCache.get("logClipboardTemplate").lines();
// remove start/end comment tags
text.removeAt(0);
text.removeAt(text.length - 1);
text.push('<ul>');
$element.find('#log-panel-statements').children().each(function(index, child:HTMLElement) {
tex... | identifier_body |
app.ts | /**
* @module Core
*/
/// <reference path="corePlugin.ts"/>
module Core {
/**
* Controller that's attached to hawtio's drop-down console, mainly handles the
* clipboard icon at the bottom-right of the console.
*
* @method ConsoleController
* @for Core
* @static
* @param {*} $scope
* @param ... | var icon2 = $element.find('.icon-trash');
if (this !== icon.get(0) && this !== icon2.get(0)) {
return;
}
if (this == icon.get(0)) {
copyToClipboard();
} else {
clearLogs();
notification('info', "Cleared logging console");
}
... | // this is apparently a global event handler for zero clipboard
// so you have to make sure you're handling the right click event
var icon = $element.find('.icon-copy'); | random_line_split |
app.ts | /**
* @module Core
*/
/// <reference path="corePlugin.ts"/>
module Core {
/**
* Controller that's attached to hawtio's drop-down console, mainly handles the
* clipboard icon at the bottom-right of the console.
*
* @method ConsoleController
* @for Core
* @static
* @param {*} $scope
* @param ... | else {
clearLogs();
notification('info', "Cleared logging console");
}
Core.$apply($scope);
});
function copyToClipboard() {
var text = $templateCache.get("logClipboardTemplate").lines();
// remove start/end comment tags
text.removeAt(0);
... | {
copyToClipboard();
} | conditional_block |
app.ts | /**
* @module Core
*/
/// <reference path="corePlugin.ts"/>
module Core {
/**
* Controller that's attached to hawtio's drop-down console, mainly handles the
* clipboard icon at the bottom-right of the console.
*
* @method ConsoleController
* @for Core
* @static
* @param {*} $scope
* @param ... | () {
$element.find('#log-panel-statements').children().remove();
}
};
}]);
/**
* Outermost controller attached to almost the root of the document, handles
* logging in and logging out, the PID/container indicator at the bottom right
* of the window and the document title
*
* @metho... | clearLogs | identifier_name |
import_google_data.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
_columns = {
'create_partner': fields.selection([('create_all','Create partner for each contact'),('create_address','Import only address')],'Options'),
'customer': fields.boolean('Customer', help="Check this box to set newly created partner as Customer."),
'supplier': fields.boolean('Suppl... | user_obj = self.pool.get('res.users').browse(cr, uid, uid)
google = self.pool.get('google.login')
res = []
try:
gd_client = google.google_login(user_obj.gmail_user, user_obj.gmail_password, type='calendar')
calendars = gd_client.GetAllCalendarsFeed()
for cal i... | identifier_body |
import_google_data.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | (osv.osv_memory):
_name = 'synchronize.google.import'
def _get_group(self, cr, uid, context=None):
user_obj = self.pool.get('res.users').browse(cr, uid, uid)
google=self.pool.get('google.login')
if not user_obj.gmail_user or not user_obj.gmail_password:
raise osv.except_osv(... | synchronize_google | identifier_name |
import_google_data.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
gd_client = google.google_login(user_obj.gmail_user,user_obj.gmail_password,type='group')
if not gd_client:
return [('failed', 'Connection to google fail')]
res = []
query = gdata.contacts.service.GroupsQuery(feed='/m8/feeds/groups/default/full')
if gd_client:
... | raise osv.except_osv(_('Warning !'), _("No Google Username or password Defined for user.\nPlease define in user view")) | conditional_block |
import_google_data.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | if context.get('contact'):
msg = " You're Contact are import in background, a email will be send when the process is finished to %s"%(user_obj.gmail_user)
gd_client = google.google_login(gmail_user, gmail_pwd, type='contact')
if not gd_client:
raise osv.excep... | raise osv.except_osv(_('Error'), _("Invalid login detail !\n Specify Username/Password."))
| random_line_split |
main.rs | use binaryninja::architecture::Architecture;
use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt};
// Standalone executables need to provide a main function for rustc
// Plugins should refer to `binaryninja::command::*` for the various registration callbacks.
fn main() {
// This loads all the core architec... | println!("Loading binary...");
let bv = binaryninja::open_view("/bin/cat").expect("Couldn't open `/bin/cat`");
println!("Filename: `{}`", bv.metadata().filename());
println!("File size: `{:#x}`", bv.len());
println!("Function count: {}", bv.functions().len());
for func in &bv.functions() {
... | binaryninja::headless::init();
// Your code here... | random_line_split |
main.rs | use binaryninja::architecture::Architecture;
use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt};
// Standalone executables need to provide a main function for rustc
// Plugins should refer to `binaryninja::command::*` for the various registration callbacks.
fn main() | match func.arch().instruction_text(
bv.read_buffer(addr, func.arch().max_instr_len())
.unwrap()
.get_data(),
addr,
) {
Some((_, tokens)) => {
tokens
... | {
// This loads all the core architecture, platform, etc plugins
// Standalone executables probably need to call this, but plugins do not
println!("Loading plugins...");
binaryninja::headless::init();
// Your code here...
println!("Loading binary...");
let bv = binaryninja::open_view("/bin/... | identifier_body |
main.rs | use binaryninja::architecture::Architecture;
use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt};
// Standalone executables need to provide a main function for rustc
// Plugins should refer to `binaryninja::command::*` for the various registration callbacks.
fn | () {
// This loads all the core architecture, platform, etc plugins
// Standalone executables probably need to call this, but plugins do not
println!("Loading plugins...");
binaryninja::headless::init();
// Your code here...
println!("Loading binary...");
let bv = binaryninja::open_view("/b... | main | identifier_name |
main.rs | use binaryninja::architecture::Architecture;
use binaryninja::binaryview::{BinaryViewBase, BinaryViewExt};
// Standalone executables need to provide a main function for rustc
// Plugins should refer to `binaryninja::command::*` for the various registration callbacks.
fn main() {
// This loads all the core architec... |
_ => (),
}
}
}
}
// Important! Standalone executables need to call shutdown or they will hang forever
binaryninja::headless::shutdown();
}
| {
tokens
.iter()
.for_each(|token| print!("{}", token.text().as_str()));
println!("")
} | conditional_block |
split.rs | // #![ warn( missing_docs ) ]
// #![ warn( missing_debug_implementations ) ]
use former::Former;
///
/// Either delimeter or delimeted with the slice on its string.
///
#[ derive( Debug ) ]
pub struct Split< 'a >
{
string : &'a str,
typ : SplitType,
}
impl< 'a > From< Split< 'a > > for String
{
fn from( src :... | }
//
impl< 'a > Iterator for SplitIterator< 'a >
{
type Item = Split< 'a >;
fn next( &mut self ) -> Option< Self::Item >
{
self.counter += 1;
if self.counter % 2 == 1
{
let next = self.iterator.next();
if let Some( next ) = next
{
Some( Split { string : next, typ : SplitTy... | delimeter,
counter,
}
} | random_line_split |
split.rs | // #![ warn( missing_docs ) ]
// #![ warn( missing_debug_implementations ) ]
use former::Former;
///
/// Either delimeter or delimeted with the slice on its string.
///
#[ derive( Debug ) ]
pub struct Split< 'a >
{
string : &'a str,
typ : SplitType,
}
impl< 'a > From< Split< 'a > > for String
{
fn from( src :... |
Some( Split { string : self.delimeter, typ : SplitType::Delimeter } )
// Some( Split::Delimeter( self.delimeter.clone() ) )
}
}
}
///
/// Options of function split.
///
#[ derive( Debug ) ]
#[ derive( Former ) ]
#[ form_after( fn split( self ) -> SplitIterator< 'a > ) ]
pub struct SplitOptions< 'a ... | {
self.iterator.next();
return None;
} | conditional_block |
split.rs | // #![ warn( missing_docs ) ]
// #![ warn( missing_debug_implementations ) ]
use former::Former;
///
/// Either delimeter or delimeted with the slice on its string.
///
#[ derive( Debug ) ]
pub struct Split< 'a >
{
string : &'a str,
typ : SplitType,
}
impl< 'a > From< Split< 'a > > for String
{
fn from( src :... |
}
///
/// Either delimeter or delimeted
///
#[ derive( Debug ) ]
pub enum SplitType
{
/// Substring of the original string with text inbetween delimeters.
Delimeted,
/// Delimeter.
Delimeter,
}
///
/// Split iterator.
///
#[ derive( Debug ) ]
pub struct SplitIterator< 'a >
{
iterator : std::iter::Peekabl... | {
src.string.into()
} | identifier_body |
split.rs | // #![ warn( missing_docs ) ]
// #![ warn( missing_debug_implementations ) ]
use former::Former;
///
/// Either delimeter or delimeted with the slice on its string.
///
#[ derive( Debug ) ]
pub struct Split< 'a >
{
string : &'a str,
typ : SplitType,
}
impl< 'a > From< Split< 'a > > for String
{
fn from( src :... | ( &self ) -> &'a str
{
self.delimeter
}
fn preserving_empty( &self ) -> bool
{
self.preserving_empty
}
fn preserving_delimeters( &self ) -> bool
{
self.preserving_delimeters
}
}
///
/// Function to split a string.
///
/// It produces former. To convert former into options and run algorithm ... | delimeter | identifier_name |
Main.js | 355],
0x2211: [893,446,1224,89,1135],
0x221A: [1280,0,770,63,803],
0x2229: [1039,520,1292,124,1169],
0x222B: [1310,654,1000,54,1001],
0x222C: [1310,654,1659,54,1540],
0x222D: [1310,654,2198,54,2079],
0x222E: [1310,654,1120,54,1001],
0x222F: [1310,654,1659,54,1540],
0x2230: [1310,654,2198,54,2079],
0... | random_line_split | ||
windowWhen.ts | import {Operator} from '../Operator';
import {Subscriber} from '../Subscriber';
import {Observable} from '../Observable';
import {Subject} from '../Subject';
import {Subscription} from '../Subscription';
import {tryCatch} from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
import {OuterSubscribe... | this.add(this.closingNotification = subscribeToResult(this, closingNotifier));
}
}
}
| {
if (innerSub) {
this.remove(innerSub);
innerSub.unsubscribe();
}
const prevWindow = this.window;
if (prevWindow) {
prevWindow.complete();
}
const window = this.window = new Subject<T>();
this.destination.next(window);
const closingNotifier = tryCatch(this.closingSe... | identifier_body |
windowWhen.ts | import {Operator} from '../Operator';
import {Subscriber} from '../Subscriber';
import {Observable} from '../Observable';
import {Subject} from '../Subject';
import {Subscription} from '../Subscription';
import {tryCatch} from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
import {OuterSubscribe... | <T> implements Operator<T, Observable<T>> {
constructor(private closingSelector: () => Observable<any>) {
}
call(subscriber: Subscriber<Observable<T>>, source: any): any {
return source._subscribe(new WindowSubscriber(subscriber, this.closingSelector));
}
}
/**
* We need this JSDoc comment for affecting ... | WindowOperator | identifier_name |
windowWhen.ts | import {Operator} from '../Operator';
import {Subscriber} from '../Subscriber';
import {Observable} from '../Observable';
import {Subject} from '../Subject';
import {Subscription} from '../Subscription';
import {tryCatch} from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
import {OuterSubscribe... |
const window = this.window = new Subject<T>();
this.destination.next(window);
const closingNotifier = tryCatch(this.closingSelector)();
if (closingNotifier === errorObject) {
const err = errorObject.e;
this.destination.error(err);
this.window.error(err);
} else {
this.add(... | {
prevWindow.complete();
} | conditional_block |
windowWhen.ts | import {Operator} from '../Operator';
import {Subscriber} from '../Subscriber';
import {Observable} from '../Observable';
import {Subject} from '../Subject';
import {Subscription} from '../Subscription';
import {tryCatch} from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
import {OuterSubscribe... |
class WindowOperator<T> implements Operator<T, Observable<T>> {
constructor(private closingSelector: () => Observable<any>) {
}
call(subscriber: Subscriber<Observable<T>>, source: any): any {
return source._subscribe(new WindowSubscriber(subscriber, this.closingSelector));
}
}
/**
* We need this JSDoc c... | (closingSelector: () => Observable<any>): Observable<Observable<T>>;
} | random_line_split |
_aux_tests_short_tapes.js | const typeResult = async (opt = {}, tape, context, appContext) => {
let cheerio = appContext.require('cheerio');
let get = appContext.get;
let _console = null;
let timeout = false;
/**/
let htmlRes = null;
let htmlLastRes = null;
let doc = null;
let expectedHtml = null;
let counter = 0;
... | if (htmlRes && htmlRes.length) htmlLastRes = htmlRes;
} catch (e) {
await tape.ok(false, ['error', e]);
if (!appContext.isDev) appContext.logger.warn(e, counter, opt.elHtml, doc);
return await _end();
}
}
if (opt.expe... | htmlRes = cheerio
.load(doc)(opt.elHtml || 'div')
.eq(0)
.html(); | random_line_split |
_aux_tests_short_tapes.js | const typeResult = async (opt = {}, tape, context, appContext) => {
let cheerio = appContext.require('cheerio');
let get = appContext.get;
let _console = null;
let timeout = false;
/**/
let htmlRes = null;
let htmlLastRes = null;
let doc = null;
let expectedHtml = null;
let counter = 0;
... |
if (cheerio && opt.elHtml) {
try {
htmlRes = cheerio
.load(doc)(opt.elHtml || 'div')
.eq(0)
.html();
if (htmlRes && htmlRes.length) htmlLastRes = htmlRes;
} catch (e) {
await tape.ok(fal... | {
await tape.ok(false, 'No document');
return await _end();
} | conditional_block |
XPathDocument.ts | import { SensorMLNamespaceResolver } from './SensorMLNamespaceResolver';
export class XPathDocument {
private static MEDIA_TYPE = 'application/xml';
public static parse(xml: string): XPathDocument {
let parser = new DOMParser();
let document = parser.parseFromString(xml, XPathDocument.MEDIA_T... | case XPathResult.BOOLEAN_TYPE:
return result.booleanValue;
case XPathResult.NUMBER_TYPE:
return result.numberValue;
case XPathResult.STRING_TYPE:
return result.stringValue;
case XPathResult.ORDERED_NODE_ITERATOR_TYPE:
... | case XPathResult.FIRST_ORDERED_NODE_TYPE:
return result.singleNodeValue;
case XPathResult.ANY_UNORDERED_NODE_TYPE:
return result.singleNodeValue; | random_line_split |
XPathDocument.ts | import { SensorMLNamespaceResolver } from './SensorMLNamespaceResolver';
export class XPathDocument {
private static MEDIA_TYPE = 'application/xml';
public static parse(xml: string): XPathDocument {
let parser = new DOMParser();
let document = parser.parseFromString(xml, XPathDocument.MEDIA_T... | (expression: string, context?: Node) {
context = context || this.document.documentElement;
let resolver: XPathNSResolver = {
lookupNamespaceURI(prefix: string): string {
return new SensorMLNamespaceResolver().getNamespace(prefix);
}
};
return this.... | _eval | identifier_name |
XPathDocument.ts | import { SensorMLNamespaceResolver } from './SensorMLNamespaceResolver';
export class XPathDocument {
private static MEDIA_TYPE = 'application/xml';
public static parse(xml: string): XPathDocument {
let parser = new DOMParser();
let document = parser.parseFromString(xml, XPathDocument.MEDIA_T... |
return array;
}
private parseIterator(result: XPathResult): Node[] {
let array: Node[] = [];
let node: Node = result.iterateNext();
while (node != null) {
array.push(node);
node = result.iterateNext();
}
return array;
}
private _... | {
array[i] = result.snapshotItem(i);
} | conditional_block |
xmlToJson.js | // Changes XML to JSON
exports.xml2json = function(xml){
return xmlToJson(xml);
};
function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) { // element
// do attributes
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.lengt... |
return obj;
}; | {
for(var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName... | conditional_block |
xmlToJson.js | // Changes XML to JSON
exports.xml2json = function(xml){
return xmlToJson(xml);
};
function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) { // element
// do attributes | obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) { // text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for(var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (type... | if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j); | random_line_split |
xmlToJson.js | // Changes XML to JSON
exports.xml2json = function(xml){
return xmlToJson(xml);
};
function | (xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) { // element
// do attributes
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attri... | xmlToJson | identifier_name |
xmlToJson.js | // Changes XML to JSON
exports.xml2json = function(xml){
return xmlToJson(xml);
};
function xmlToJson(xml) | for(var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] ... | {
// Create the return object
var obj = {};
if (xml.nodeType == 1) { // element
// do attributes
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.n... | identifier_body |
serial_driver.py | # -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import os
import logging
_logger = logging.getLogger(__name__)
try:
import serial
except ImportError:
_logger.error('Odoo module hw_serial depends on the pyserial python module')
serial = None
class SerialDriver(object)... | result['status'] = 'error'
result['message'] = 'The serial port was not found!'
return result
def serial_open(self, params):
try:
port = params.get('port', '/dev/ttyUSB0')
if not os.path.exists(port):
_logger.error('Serial port not fo... | result = {}
ser = self.serial_open(params)
if ser:
try:
if operation == 'read':
data = ser.readline()
result['data'] = data
else:
data = params.get('data', '')
encoding = params.ge... | identifier_body |
serial_driver.py | # -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import os
import logging
_logger = logging.getLogger(__name__)
try:
import serial
except ImportError:
_logger.error('Odoo module hw_serial depends on the pyserial python module')
serial = None
class SerialDriver(object)... | (self, operation, params):
result = {}
ser = self.serial_open(params)
if ser:
try:
if operation == 'read':
data = ser.readline()
result['data'] = data
else:
data = params.get('data', '')
... | serial_do_operation | identifier_name |
serial_driver.py | # -*- coding: utf-8 -*-
# See README file for full copyright and licensing details. | _logger = logging.getLogger(__name__)
try:
import serial
except ImportError:
_logger.error('Odoo module hw_serial depends on the pyserial python module')
serial = None
class SerialDriver(object):
def serial_do_operation(self, operation, params):
result = {}
ser = self.serial_open(para... |
import os
import logging
| random_line_split |
serial_driver.py | # -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import os
import logging
_logger = logging.getLogger(__name__)
try:
import serial
except ImportError:
_logger.error('Odoo module hw_serial depends on the pyserial python module')
serial = None
class SerialDriver(object)... |
return serial.Serial(port,
baudrate=int(params.get('baudrate', 9600)),
bytesize=int(params.get('bytesize', 8)),
stopbits=int(params.get('stopbits', 1)),
parity=params.get('par... | _logger.error('Serial port not found')
return None | conditional_block |
vgg.py | import tensorflow as tf
import numpy as np
import scipy.io
vgg_layers = [
'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',
'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',
'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3',
'conv4_1', 'relu4_1', 'con... |
return convnet, mean
def pre_process_image(image, mean_pixel):
return image - mean_pixel
def restore_image(image, mean_pixel):
return image + mean_pixel
| if vgg_layer_types[i] == 'conv':
# Convolution layer
kernel, bias = layers[i][0][0][0][0]
# (width, height, in_channels, out_channels) -> (height, width, in_channels, out_channels)
kernels = np.transpose(kernel, (1, 0, 2, 3))
bias = bias.reshape(-1)
... | conditional_block |
vgg.py | import tensorflow as tf
import numpy as np
import scipy.io
vgg_layers = [
'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',
'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',
'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3',
'conv4_1', 'relu4_1', 'con... |
def restore_image(image, mean_pixel):
return image + mean_pixel
| return image - mean_pixel | identifier_body |
vgg.py | import tensorflow as tf
import numpy as np
import scipy.io
vgg_layers = [
'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',
'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',
'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3',
'conv4_1', 'relu4_1', 'con... | (path_network, input_image):
# Load pretrained convnet
pretrained_net = scipy.io.loadmat(path_network)
# Mean of input pixels - used to normalize input images
mean = np.mean(pretrained_net['normalization'][0][0][0], axis = (0, 1))
layers = pretrained_net['layers'][0]
convnet = {}
current = ... | build_net | identifier_name |
vgg.py | import tensorflow as tf
import numpy as np
import scipy.io
vgg_layers = [
'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',
'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',
'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3',
'conv4_1', 'relu4_1', 'con... | elif vgg_layer_types[i] == 'pool':
# Pool layer
current = tf.nn.avg_pool(current, ksize = (1, 2, 2, 1), strides = (1, 2, 2, 1), padding = 'SAME')
convnet[name] = current
return convnet, mean
def pre_process_image(image, mean_pixel):
return image - mean_pixel
def rest... | current = tf.nn.bias_add(conv, bias)
elif vgg_layer_types[i] == 'relu':
# Relu layer
current = tf.nn.relu(current) | random_line_split |
settings.py | # Copyright (c) 2010-2013 by Yaco Sistemas <goinnn@gmail.com> or <pmartin@yaco.es>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option)... | INPLACE_FIELD_TYPES = getattr(settings, 'INPLACE_FIELD_TYPES', 'input, select, textarea')
INPLACE_FOCUS_WHEN_EDITING = getattr(settings, 'INPLACE_FOCUS_WHEN_EDITING', True) | INPLACE_GET_FIELD_URL = getattr(settings, 'INPLACE_GET_FIELD_URL', None)
INPLACE_SAVE_URL = getattr(settings, 'INPLACE_SAVE_URL', None)
| random_line_split |
sha1nexte.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn sha1nexte_1() {
run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM1)), operand2: Some(Dir... |
fn sha1nexte_3() {
run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 56, 200, 226], OperandSize::Qword)
}
fn sha1ne... | {
run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(EDI, Two, 1878744270, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15,... | identifier_body |
sha1nexte.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn sha1nexte_1() {
run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM1)), operand2: Some(Dir... | () {
run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(EDI, Two, 1878744270, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[... | sha1nexte_2 | identifier_name |
sha1nexte.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn sha1nexte_1() {
run_test(&Instruction { mnemonic: Mnemonic::SHA1NEXTE, operand1: Some(Direct(XMM1)), operand2: Some(Dir... | } | random_line_split | |
overrides.py | """Implementation of __array_function__ overrides from NEP-18."""
import collections
import functools
import os
import textwrap
from numpy.core._multiarray_umath import (
add_docstring, implement_array_function, _get_implementing_args)
from numpy.compat._inspect import getargspec
ARRAY_FUNCTION_ENABLED = bool(
... |
def set_module(module):
"""Decorator for overriding __module__ on a function or class.
Example usage::
@set_module('numpy')
def example():
pass
assert example.__module__ == 'numpy'
"""
def decorator(func):
if module is not None:
func.__module... | if dispatcher_spec.defaults != (None,) * len(dispatcher_spec.defaults):
raise RuntimeError('dispatcher functions can only use None for '
'default argument values') | conditional_block |
overrides.py | """Implementation of __array_function__ overrides from NEP-18."""
import collections
import functools
import os
import textwrap
from numpy.core._multiarray_umath import (
add_docstring, implement_array_function, _get_implementing_args)
from numpy.compat._inspect import getargspec
ARRAY_FUNCTION_ENABLED = bool(
... | )
def set_array_function_like_doc(public_api):
if public_api.__doc__ is not None:
public_api.__doc__ = public_api.__doc__.replace(
"${ARRAY_FUNCTION_LIKE}",
array_function_like_doc,
)
return public_api
add_docstring(
implement_array_function,
"""
Implement ... | The ``like`` keyword is an experimental feature pending on
acceptance of :ref:`NEP 35 <NEP35>`.""" | random_line_split |
overrides.py | """Implementation of __array_function__ overrides from NEP-18."""
import collections
import functools
import os
import textwrap
from numpy.core._multiarray_umath import (
add_docstring, implement_array_function, _get_implementing_args)
from numpy.compat._inspect import getargspec
ARRAY_FUNCTION_ENABLED = bool(
... | """Like array_function_dispatcher, but with function arguments flipped."""
def decorator(dispatcher):
return array_function_dispatch(
dispatcher, module, verify=verify,
docs_from_dispatcher=docs_from_dispatcher)(implementation)
return decorator | identifier_body | |
overrides.py | """Implementation of __array_function__ overrides from NEP-18."""
import collections
import functools
import os
import textwrap
from numpy.core._multiarray_umath import (
add_docstring, implement_array_function, _get_implementing_args)
from numpy.compat._inspect import getargspec
ARRAY_FUNCTION_ENABLED = bool(
... | (implementation, dispatcher):
"""Verify that a dispatcher function has the right signature."""
implementation_spec = ArgSpec(*getargspec(implementation))
dispatcher_spec = ArgSpec(*getargspec(dispatcher))
if (implementation_spec.args != dispatcher_spec.args or
implementation_spec.varargs !=... | verify_matching_signatures | identifier_name |
_Daypack.from.mocha.tests.ts | import chai from 'chai';
import assert from 'vet/utils/assert';
import isShape from 'vet/objects/isShape';
import Daypack from './';
describe(
'Daypack.from',
() => {
it(
'builds a new pack',
() => {
let pack = Daypack.from({ foo: 'bar' });
assert(
pack instanceof Daypack,
'pack is not i... | }
); | random_line_split | |
insertion.rs | // Copyright 2020 Johannes Köster.
// Licensed under the GNU GPLv3 license (https://opensource.org/licenses/GPL-3.0)
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::RefCell;
use std::cmp;
use std::rc::Rc;
use std::sync::Arc;
use anyhow::Result;
use bio::stat... | } {
Some(vec![0])
} else {
None
}
}
/// Return variant loci.
fn loci(&self) -> &Self::Loci {
&self.locus
}
/// Calculate probability for alt and reference allele.
fn allele_support(
&self,
evidence: &Self::Evidence,
... |
!self.locus().overlap(left, true).is_none()
|| !self.locus().overlap(right, true).is_none()
}
| conditional_block |
insertion.rs | // Copyright 2020 Johannes Köster.
// Licensed under the GNU GPLv3 license (https://opensource.org/licenses/GPL-3.0)
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::RefCell;
use std::cmp;
use std::rc::Rc;
use std::sync::Arc;
use anyhow::Result;
use bio::stat... | }
}
impl<R: Realigner> ReadSamplingBias for Insertion<R> {}
impl<R: Realigner> Variant for Insertion<R> {
type Evidence = PairedEndEvidence;
type Loci = MultiLocus;
fn is_valid_evidence(
&self,
evidence: &Self::Evidence,
_: &AlignmentProperties,
) -> Option<Vec<usize>> {
... | }
fn enclosable_len(&self) -> Option<u64> {
Some(self.ins_seq.len() as u64) | random_line_split |
insertion.rs | // Copyright 2020 Johannes Köster.
// Licensed under the GNU GPLv3 license (https://opensource.org/licenses/GPL-3.0)
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::RefCell;
use std::cmp;
use std::rc::Rc;
use std::sync::Arc;
use anyhow::Result;
use bio::stat... |
/// Calculate probability for alt and reference allele.
fn allele_support(
&self,
evidence: &Self::Evidence,
_alignment_properties: &AlignmentProperties,
) -> Result<Option<AlleleSupport>> {
match evidence {
PairedEndEvidence::SingleEnd(record) => Ok(Some(
... |
&self.locus
}
| identifier_body |
insertion.rs | // Copyright 2020 Johannes Köster.
// Licensed under the GNU GPLv3 license (https://opensource.org/licenses/GPL-3.0)
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::RefCell;
use std::cmp;
use std::rc::Rc;
use std::sync::Arc;
use anyhow::Result;
use bio::stat... |
&self,
evidence: &Self::Evidence,
_alignment_properties: &AlignmentProperties,
) -> Result<Option<AlleleSupport>> {
match evidence {
PairedEndEvidence::SingleEnd(record) => Ok(Some(
self.realigner
.borrow_mut()
.all... | llele_support( | identifier_name |
SubmissionTrayRadioInputGroup.js | /*
* Copyright (C) 2017 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas 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, version 3 of the License.
*
* Canvas is distribut... | ))
return (
<FormFieldGroup
description={I18n.t('Status')}
disabled={this.props.disabled}
layout="stacked"
rowSpacing="none"
>
{radioOptions}
</FormFieldGroup>
)
}
}
SubmissionTrayRadioInputGroup.propTypes = {
colors: shape({
late: string.i... | /> | random_line_split |
SubmissionTrayRadioInputGroup.js | /*
* Copyright (C) 2017 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas 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, version 3 of the License.
*
* Canvas is distribut... | (nextProps) {
if (
this.props.submissionUpdating &&
!nextProps.submissionUpdating &&
this.state.pendingUpdateData
) {
this.props.updateSubmission(this.state.pendingUpdateData)
this.setState({pendingUpdateData: null})
}
}
handleRadioInputChanged = ({target: {value}}) => {
... | componentWillReceiveProps | identifier_name |
cargo_run.rs | use std::path::Path;
use ops::{self, CompileFilter};
use util::{self, CargoResult, process, ProcessError};
use core::Package;
pub fn run(manifest_path: &Path,
options: &ops::CompileOptions,
args: &[String]) -> CargoResult<Option<ProcessError>> | if bins.next().is_some() {
match options.filter {
CompileFilter::Everything => {
bail!("`cargo run` requires that a project only have one \
executable; use the `--bin` option to specify which one \
to run")
}
C... | {
let config = options.config;
let root = try!(Package::for_path(manifest_path, config));
let mut bins = root.manifest().targets().iter().filter(|a| {
!a.is_lib() && !a.is_custom_build() && match options.filter {
CompileFilter::Everything => a.is_bin(),
CompileFilter::Only {... | identifier_body |
cargo_run.rs | use std::path::Path;
use ops::{self, CompileFilter};
use util::{self, CargoResult, process, ProcessError};
use core::Package;
pub fn run(manifest_path: &Path,
options: &ops::CompileOptions,
args: &[String]) -> CargoResult<Option<ProcessError>> {
let config = options.config;
let root = tr... | if bins.next().is_some() {
match options.filter {
CompileFilter::Everything => {
bail!("`cargo run` requires that a project only have one \
executable; use the `--bin` option to specify which one \
to run")
}
C... | }
}
} | random_line_split |
cargo_run.rs | use std::path::Path;
use ops::{self, CompileFilter};
use util::{self, CargoResult, process, ProcessError};
use core::Package;
pub fn | (manifest_path: &Path,
options: &ops::CompileOptions,
args: &[String]) -> CargoResult<Option<ProcessError>> {
let config = options.config;
let root = try!(Package::for_path(manifest_path, config));
let mut bins = root.manifest().targets().iter().filter(|a| {
!a.is_lib() && !a.... | run | identifier_name |
box.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Generic types for box properties.
use values::animated::ToAnimatedZero;
/// A generic value for the `vertica... | }
}
impl<L> ToAnimatedZero for VerticalAlign<L> {
fn to_animated_zero(&self) -> Result<Self, ()> {
Err(())
}
}
/// https://drafts.csswg.org/css-animations/#animation-iteration-count
#[derive(Clone, Debug, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub enum AnimationIterationCount<Number> {
... | VerticalAlign::Baseline | random_line_split |
box.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Generic types for box properties.
use values::animated::ToAnimatedZero;
/// A generic value for the `vertica... | <NonNegativeLength> {
/// A non-negative length.
Length(NonNegativeLength),
/// The keyword `none`.
None,
}
impl<L> Perspective<L> {
/// Returns `none`.
#[inline]
pub fn none() -> Self {
Perspective::None
}
}
| Perspective | identifier_name |
arm_32_arm_capstone.py | # ScratchABit - interactive disassembler
#
# Copyright (c) 2018 Paul Sokolovsky
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later... | return _any_capstone.Processor("arm_32", dis) | identifier_body | |
arm_32_arm_capstone.py | # ScratchABit - interactive disassembler
#
# Copyright (c) 2018 Paul Sokolovsky
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later... | #
# This program 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# alon... | random_line_split | |
arm_32_arm_capstone.py | # ScratchABit - interactive disassembler
#
# Copyright (c) 2018 Paul Sokolovsky
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later... | ():
return _any_capstone.Processor("arm_32", dis)
| PROCESSOR_ENTRY | identifier_name |
export.ts | import * as Expressions from "../../2_statements/expressions";
import {StatementNode} from "../../nodes";
import {CurrentScope} from "../_current_scope";
import {Source} from "../expressions/source";
import {Target} from "../expressions/target";
import {StatementSyntax} from "../_statement_syntax"; |
for (const s of node.findAllExpressions(Expressions.Source)) {
new Source().runSyntax(s, scope, filename);
}
for (const t of node.findDirectExpressions(Expressions.Target)) {
new Target().runSyntax(t, scope, filename);
}
const databaseName = node.findExpressionAfterToken("DATABASE");
... |
export class Export implements StatementSyntax {
public runSyntax(node: StatementNode, scope: CurrentScope, filename: string): void { | random_line_split |
export.ts | import * as Expressions from "../../2_statements/expressions";
import {StatementNode} from "../../nodes";
import {CurrentScope} from "../_current_scope";
import {Source} from "../expressions/source";
import {Target} from "../expressions/target";
import {StatementSyntax} from "../_statement_syntax";
export class Export... |
}
}
} | {
scope.getDDICReferences().addUsing(scope.getParentObj(), {object: found.object});
} | conditional_block |
export.ts | import * as Expressions from "../../2_statements/expressions";
import {StatementNode} from "../../nodes";
import {CurrentScope} from "../_current_scope";
import {Source} from "../expressions/source";
import {Target} from "../expressions/target";
import {StatementSyntax} from "../_statement_syntax";
export class | implements StatementSyntax {
public runSyntax(node: StatementNode, scope: CurrentScope, filename: string): void {
for (const s of node.findAllExpressions(Expressions.Source)) {
new Source().runSyntax(s, scope, filename);
}
for (const t of node.findDirectExpressions(Expressions.Target)) {
ne... | Export | identifier_name |
_googleappengine.py | visited.
if hasattr(req, 'redirect_dict'):
visited = new.redirect_dict = req.redirect_dict
if (visited.get(newurl, 0) >= self.max_repeats or
len(visited) >= self.max_redirections):
raise HTTPError(req.get_full_url(), code,
... | __init__ | identifier_name | |
_googleappengine.py | .HTMLParser's entitydefs.
return self.unescape_attr(name)
def unescape_attr_if_required(self, name):
return name # HTMLParser.HTMLParser already did it
class HeadParser(AbstractHeadParser, sgmllib.SGMLParser):
def _not_called(self):
assert False
def __init__(self):
... | raise ValueError() | conditional_block | |
_googleappengine.py | else:
method()
def unescape(self, name):
# Use the entitydefs passed into constructor, not
# HTMLParser.HTMLParser's entitydefs.
return self.unescape_attr(name)
def unescape_attr_if_required(self, name):
return name # HTMLParser.HTMLPar... | """
>>> parse_refresh_header("1; url=http://example.com/")
(1.0, 'http://example.com/')
>>> parse_refresh_header("1; url='http://example.com/'")
(1.0, 'http://example.com/')
>>> parse_refresh_header("1")
(1.0, None)
>>> parse_refresh_header("blah")
Traceback (most recent call last):
... | identifier_body | |
_googleappengine.py | Probably want to forget about the state of the current
# request, although that might interact poorly with other
# handlers that also use handler-specific request attributes
new = self.redirect_request(newurl, req, fp, code, msg, headers)
if new is None:
return
# lo... | visited = new.redirect_dict = req.redirect_dict = {}
visited[newurl] = visited.get(newurl, 0) + 1
# Don't close the fp until we are sure that we won't use it
# with HTTPError.
fp.read()
fp.close()
return self.parent.open(new)
http_error_301 = http_err... | if (visited.get(newurl, 0) >= self.max_repeats or
len(visited) >= self.max_redirections):
raise HTTPError(req.get_full_url(), code,
self.inf_msg + msg, headers, fp)
else: | random_line_split |
GenomeFeatureComparatorServer.py | (self, run_job_params, json_rpc_call_context = None):
return self._call('KBaseJobService.run_job', [run_job_params], json_rpc_call_context)[0]
def check_job(self, job_id, json_rpc_call_context = None):
return self._call('KBaseJobService.check_job', [job_id], json_rpc_call_context)[0]
class JSONRP... | run_job | identifier_name | |
GenomeFeatureComparatorServer.py | rpc_result = ""
else:
request_body = environ['wsgi.input'].read(body_size)
try:
req = json.loads(request_body)
except ValueError as ve:
err = {'error': {'code': -32700,
'name': "Parse error",
... | '''
By default, will start the server on localhost on a system assigned port
in the main thread. Excecution of the main thread will stay in the server
main loop until interrupted. To run the server in a separate process, and
thus allow the stop_server method to be called, set newprocess = True. This
... | identifier_body | |
GenomeFeatureComparatorServer.py | ):
def call(self, ctx, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = self.call_py(ctx, jsondata)
if resul... |
return None
def _call_method(self, ctx, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
... | return json.dumps(result, cls=JSONObjectEncoder) | conditional_block |
GenomeFeatureComparatorServer.py | ):
def call(self, ctx, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = self.call_py(ctx, jsondata)
if resul... |
def call_py(self, ctx, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only us... | raise newerr
return result | random_line_split |
main.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRouteSnapshot, NavigationEnd, RoutesRecognized } from '@angular/router';
import { JhiLanguageHelper, StateStorageService } from '../../shared';
@Component({
selector: 'jhi-main',
templateUrl: './main.component.html'
})
export class J... |
return title;
}
ngOnInit() {
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.jhiLanguageHelper.updateTitle(this.getPageTitle(this.router.routerState.snapshot.root));
}
});
}
}
| {
title = this.getPageTitle(routeSnapshot.firstChild) || title;
} | conditional_block |
main.component.ts | import { Component, OnInit } from '@angular/core'; |
@Component({
selector: 'jhi-main',
templateUrl: './main.component.html'
})
export class JhiMainComponent implements OnInit {
constructor(
private jhiLanguageHelper: JhiLanguageHelper,
private router: Router,
private $storageService: StateStorageService,
) {}
private getPag... | import { Router, ActivatedRouteSnapshot, NavigationEnd, RoutesRecognized } from '@angular/router';
import { JhiLanguageHelper, StateStorageService } from '../../shared'; | random_line_split |
main.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRouteSnapshot, NavigationEnd, RoutesRecognized } from '@angular/router';
import { JhiLanguageHelper, StateStorageService } from '../../shared';
@Component({
selector: 'jhi-main',
templateUrl: './main.component.html'
})
export class J... | (routeSnapshot: ActivatedRouteSnapshot) {
let title: string = (routeSnapshot.data && routeSnapshot.data['pageTitle']) ? routeSnapshot.data['pageTitle'] : 'softbillsApp';
if (routeSnapshot.firstChild) {
title = this.getPageTitle(routeSnapshot.firstChild) || title;
}
return tit... | getPageTitle | identifier_name |
main.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRouteSnapshot, NavigationEnd, RoutesRecognized } from '@angular/router';
import { JhiLanguageHelper, StateStorageService } from '../../shared';
@Component({
selector: 'jhi-main',
templateUrl: './main.component.html'
})
export class J... |
private getPageTitle(routeSnapshot: ActivatedRouteSnapshot) {
let title: string = (routeSnapshot.data && routeSnapshot.data['pageTitle']) ? routeSnapshot.data['pageTitle'] : 'softbillsApp';
if (routeSnapshot.firstChild) {
title = this.getPageTitle(routeSnapshot.firstChild) || title;
... | {} | identifier_body |
ProjectViewDialog.tsx | /*
MIT License
Copyright (c) 2021 Looker Data Sciences, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modi... | onClose,
}) => {
const closeDialog = () => {
onClose()
}
return (
<Dialog isOpen={!!project} onClose={closeDialog}>
<DialogHeader>{project?.title}</DialogHeader>
<DialogContent>
{!!project && <ProjectView project={project} />}
</DialogContent>
</Dialog>
)
} |
export const ProjectViewDialog: FC<ProjectViewDialogProps> = ({
project, | random_line_split |
UserCard.tsx | @author Adam Charron <adam.c@vanillaforums.com>
* @copyright 2009-2021 Vanilla Forums Inc.
* @license gpl-2.0-only
*/
import { cx } from "@emotion/css";
import { LoadStatus } from "@library/@types/api/core";
import { IUser, IUserFragment } from "@library/@types/api/users";
import { hasUserViewPermission } from "@l... | (props: React.PropsWithChildren<IProps> & { forceOpen?: boolean }) {
const [_isOpen, _setIsOpen] = useState(false);
const isOpen = props.forceOpen ?? _isOpen;
function setIsOpen(newOpen: boolean) {
_setIsOpen(newOpen);
// Kludge for interaction with old flyout system.
if (newOpen &&... | UserCardPopup | identifier_name |
UserCard.tsx | @author Adam Charron <adam.c@vanillaforums.com>
* @copyright 2009-2021 Vanilla Forums Inc.
* @license gpl-2.0-only
*/
import { cx } from "@emotion/css";
import { LoadStatus } from "@library/@types/api/core";
import { IUser, IUserFragment } from "@library/@types/api/users";
import { hasUserViewPermission } from "@l... |
const triggerID = useUniqueID("popupTrigger");
const contentID = triggerID + "-content";
const triggerRef = useRef<HTMLElement>(null);
const contentRef = useRef<HTMLElement>(null);
const device = useDevice();
const forceModal = device === Devices.MOBILE || device === Devices.XS;
if (!hasU... | {
_setIsOpen(newOpen);
// Kludge for interaction with old flyout system.
if (newOpen && window.closeAllFlyouts) {
window.closeAllFlyouts();
}
} | identifier_body |
UserCard.tsx | @author Adam Charron <adam.c@vanillaforums.com>
* @copyright 2009-2021 Vanilla Forums Inc.
* @license gpl-2.0-only
*/
import { cx } from "@emotion/css";
import { LoadStatus } from "@library/@types/api/core";
import { IUser, IUserFragment } from "@library/@types/api/users";
import { hasUserViewPermission } from "@l... | return {
props: hasUserViewPermission()
? {
"aria-controls": context.contentID,
"aria-expanded": context.isOpen,
"aria-haspopup": context.isOpen,
role: "button",
onClick: (e) => {
e.pr... | },
[context.setIsOpen, context.contentRef],
);
useFocusWatcher(context.triggerRef, handleFocusChange);
| random_line_split |
UserCard.tsx | @author Adam Charron <adam.c@vanillaforums.com>
* @copyright 2009-2021 Vanilla Forums Inc.
* @license gpl-2.0-only
*/
import { cx } from "@emotion/css";
import { LoadStatus } from "@library/@types/api/core";
import { IUser, IUserFragment } from "@library/@types/api/users";
import { hasUserViewPermission } from "@l... |
return {
...posDefault,
left,
};
}
/**
* The content of the user card, wrapped in a flyout.
*/
export function UserCardFlyout(props: React.ComponentProps<typeof UserCard>) {
const context = useUserCardContext();
const handleFocusChange = useCallback(
(hasFocus, newActiveEle... | {
// We have a collision.
// Just use default positioning.
return posDefault;
} | conditional_block |
jit.rs | #![feature(asm)]
use std::io::{prelude::*};
use std::env;
use std::fs::File;
use std::convert::TryInto;
use brainfuck as bf;
extern crate assembler;
use ::assembler::{
ExecutableAnonymousMemoryMap,
InstructionStream,
InstructionStreamHints
};
fn compile(expressions: &Vec<bf::Expression>, stream: &mut I... | // 46: 0f 05 syscall
bf::Expression::OutputValue => {
stream.emit_bytes(b"\x48\xc7\xc0");
stream.emit_double_word(0x02000004);
stream.emit_bytes(b"\x48\xc7\xc7\x01\x00\x00\x00");
stream.emit_bytes(b"\x... | // 0000000000000031 write:
// 31: 48 c7 c0 04 00 00 02 movq $33554436, %rax
// 38: 48 c7 c7 01 00 00 00 movq $1, %rdi
// 3f: 48 c7 c2 01 00 00 00 movq $1, %rdx | random_line_split |
jit.rs | #![feature(asm)]
use std::io::{prelude::*};
use std::env;
use std::fs::File;
use std::convert::TryInto;
use brainfuck as bf;
extern crate assembler;
use ::assembler::{
ExecutableAnonymousMemoryMap,
InstructionStream,
InstructionStreamHints
};
fn compile(expressions: &Vec<bf::Expression>, stream: &mut I... | () {
let args: Vec<String> = env::args().collect();
let filename = match args.get(1) {
Some(s) => s,
None => panic!("missing filename")
};
let mut contents = String::new();
let mut file = File::open(filename).expect("Error opening file");
file.read_to_string(&mut contents).exp... | main | identifier_name |
jit.rs | #![feature(asm)]
use std::io::{prelude::*};
use std::env;
use std::fs::File;
use std::convert::TryInto;
use brainfuck as bf;
extern crate assembler;
use ::assembler::{
ExecutableAnonymousMemoryMap,
InstructionStream,
InstructionStreamHints
};
fn compile(expressions: &Vec<bf::Expression>, stream: &mut I... | {
let args: Vec<String> = env::args().collect();
let filename = match args.get(1) {
Some(s) => s,
None => panic!("missing filename")
};
let mut contents = String::new();
let mut file = File::open(filename).expect("Error opening file");
file.read_to_string(&mut contents).expect... | identifier_body | |
filecount.js | 'use strict';
var fs = require('fs');
var path = require('path');
function numFiles(dir, items, callback) {
var total = items.length;
var files = 0;
var completed = 0;
if (total === 0) {
callback(null, 0);
}
items.forEach(function(item) {
fs.stat(path.join(dir, item), function(err, stats) {
... |
});
});
}
/**
* Count the number of files in a directory.
* @param {string} dir Path to directory.
* @param {function(Error, number)} callback Callback.
*/
module.exports = exports = function(dir, callback) {
fs.readdir(dir, function(err, items) {
if (err) {
return callback(err);
}
numFi... | {
callback(null, files);
} | conditional_block |
filecount.js | 'use strict';
var fs = require('fs');
var path = require('path');
function | (dir, items, callback) {
var total = items.length;
var files = 0;
var completed = 0;
if (total === 0) {
callback(null, 0);
}
items.forEach(function(item) {
fs.stat(path.join(dir, item), function(err, stats) {
if (err) {
return callback(err);
}
if (stats && stats.isFile()) ... | numFiles | identifier_name |
filecount.js | 'use strict';
var fs = require('fs');
var path = require('path');
function numFiles(dir, items, callback) | });
});
}
/**
* Count the number of files in a directory.
* @param {string} dir Path to directory.
* @param {function(Error, number)} callback Callback.
*/
module.exports = exports = function(dir, callback) {
fs.readdir(dir, function(err, items) {
if (err) {
return callback(err);
}
numFi... | {
var total = items.length;
var files = 0;
var completed = 0;
if (total === 0) {
callback(null, 0);
}
items.forEach(function(item) {
fs.stat(path.join(dir, item), function(err, stats) {
if (err) {
return callback(err);
}
if (stats && stats.isFile()) {
++files;
... | identifier_body |
filecount.js | 'use strict';
var fs = require('fs');
var path = require('path');
function numFiles(dir, items, callback) { | callback(null, 0);
}
items.forEach(function(item) {
fs.stat(path.join(dir, item), function(err, stats) {
if (err) {
return callback(err);
}
if (stats && stats.isFile()) {
++files;
}
++completed;
if (completed === total) {
callback(null, files);
... | var total = items.length;
var files = 0;
var completed = 0;
if (total === 0) { | random_line_split |
bus.ts | import { EventEmitter } from 'events'
const noop = () => true
/**
* Typesafe generic event bus extending standard EventEmitter
* Adds some convenience functions for interaction and testing.
*/
export class ServiceEventBus<ServiceEvents extends any> extends EventEmitter {
constructor() {
super()
}
/**
*... | func(...args)
resolve(args)
}
return new Promise<params>(resolve =>
this.once(event as any, resolver(resolve))
)
}
} | const resolver = (resolve: any) => (...args: any) => { | random_line_split |
bus.ts | import { EventEmitter } from 'events'
const noop = () => true
/**
* Typesafe generic event bus extending standard EventEmitter
* Adds some convenience functions for interaction and testing.
*/
export class ServiceEventBus<ServiceEvents extends any> extends EventEmitter {
constructor() {
super()
}
/**
*... |
/**
* Lets you wait for an event once.
* Returns the resolved args but also provides a callback.
*/
async promisifyEmitOnce<
T extends keyof ServiceEvents,
params extends ServiceEvents[T] extends (...args: infer U) => any
? U
: never
>(event: T, func: (...args: params) => void = noo... | {
return super.emit((event as unknown) as string, ...args)
} | identifier_body |
bus.ts | import { EventEmitter } from 'events'
const noop = () => true
/**
* Typesafe generic event bus extending standard EventEmitter
* Adds some convenience functions for interaction and testing.
*/
export class ServiceEventBus<ServiceEvents extends any> extends EventEmitter {
| () {
super()
}
/**
* Overrides EventEmitter.on, adding types
*/
on = <T extends keyof ServiceEvents>(event: T, func: ServiceEvents[T]) => {
return super.on((event as unknown) as string, func as any)
}
/**
* Overrides EventEmitter.emit, adding types
*/
emit<
T extends keyof ServiceEv... | constructor | identifier_name |
app.js | /**
* App
*
* Root application file.
* Load main controllers here.
*/
define([
"jquery",
"modules/connected-devices/index"
], function(
$,
ConnectedDevices
) {
"use strict";
var retriveData = function(callback) {
var connected_devices_request = $.getJSON("data/connected-dev... |
connected_devices = new ConnectedDevices({
el: $app_el.get(0),
data: connected_devices_data
});
connected_devices.render();
});
return true;
};
/*
*
*
*/
app.destroy = function() {
connected_dev... | {
return window.console.error(err);
} | conditional_block |
app.js | /**
* App
*
* Root application file.
* Load main controllers here.
*/
define([
"jquery",
"modules/connected-devices/index"
], function(
$,
ConnectedDevices
) {
"use strict";
var retriveData = function(callback) {
var connected_devices_request = $.getJSON("data/connected-dev... | return true;
};
/*
*
*
*/
app.destroy = function() {
connected_devices.destroy();
};
/*
*
*
*/
app.update = function() {
retriveData(function(err, connected_devices_data) {
if (err) {
return window.console.erro... |
});
| random_line_split |
S15.10.2.6_A3_T10.js | // Copyright 2009 the Sputnik authors. All rights reserved.
/**
* The production Assertion :: \b evaluates by returning an internal AssertionTester closure that takes a State argument x and performs the ...
*
* @path ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T10.js
* @description Execute /\brobot\b/.exec("pilot\n... |
//CHECK#4
for(var index=0; index<__expected.length; index++) {
if (__executed[index] !== __expected[index]) {
$ERROR('#4: __executed = /\\brobot\\b/.exec("pilot\\nsoviet robot\\topenoffice"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]);
}
} | random_line_split | |
S15.10.2.6_A3_T10.js | // Copyright 2009 the Sputnik authors. All rights reserved.
/**
* The production Assertion :: \b evaluates by returning an internal AssertionTester closure that takes a State argument x and performs the ...
*
* @path ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T10.js
* @description Execute /\brobot\b/.exec("pilot\n... |
}
| {
$ERROR('#4: __executed = /\\brobot\\b/.exec("pilot\\nsoviet robot\\topenoffice"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]);
} | conditional_block |
server.js | var http = require('http'),
browserify = require('browserify'),
literalify = require('literalify'),
React = require('react');
var App = require('./app');
http.createServer(function(req, res) {
if (req.url == '/') {
res.setHeader('Content-Type', 'text/html');
var props = {
items: [
... | console.log('Listening on 3000...');
}) | if (err) throw err; | random_line_split |
server.js | var http = require('http'),
browserify = require('browserify'),
literalify = require('literalify'),
React = require('react');
var App = require('./app');
http.createServer(function(req, res) {
if (req.url == '/') | );
res.end(html);
}
else if (req.url == '/bundle.js') {
res.setHeader('Content-Type', 'text/javascript');
browserify()
.add('./browser.js')
.transform(literalify.configure({react: 'window.React'}))
.bundle()
.pipe(res);
} else {
res.statusCode = 404;
res.end();
}... | {
res.setHeader('Content-Type', 'text/html');
var props = {
items: [
'Item 0',
'Item 1'
]
};
var html = React.renderToStaticMarkup(
<body>
<div id="content" dangerouslySetInnerHTML={{__html:
React.renderToString(<App items={props.items}/>)
}} /... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.