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
plot.py
import sys, os, math import time import numpy as np from pandas.io.parsers import read_csv from sklearn.decomposition import PCA from sklearn.cross_validation import StratifiedShuffleSplit from sklearn import metrics import sklearn.svm as svm from sklearn.naive_bayes import MultinomialNB
from sklearn.tree import DecisionTreeClassifier from sklearn.lda import LDA from sklearn.cross_validation import train_test_split import matplotlib.pyplot as plt cut_pt = 1 print ("Reading the file...") input_res = read_csv(os.path.expanduser("input/train.csv"), nrows=3000) # load pandas dataframe input_res = input_...
from sklearn.naive_bayes import GaussianNB
random_line_split
growl.ts
import { IBot, IBotCommand, IBotCommandHelp, IBotMessage } from '../api' import { getRandomInt } from '../utils' interface IMountain { name: string height: number img?: string } export default class GrowlCommand implements IBotCommand { private readonly CMD_REGEXP = /^(or|ор)(?: |$)/im private _mo...
otMessage): Promise<void> { const id = getRandomInt(0, this._mountains.length) const low = id > 0 ? this._mountains[id - 1] : undefined const hi = id < this._mountains.length - 1 ? this._mountains[id + 1] : undefined if (!hi) { if (low && low.img) { answer.set...
wer: IB
identifier_name
growl.ts
import { IBot, IBotCommand, IBotCommandHelp, IBotMessage } from '../api' import { getRandomInt } from '../utils' interface IMountain { name: string height: number img?: string } export default class GrowlCommand implements IBotCommand { private readonly CMD_REGEXP = /^(or|ор)(?: |$)/im private _mo...
${low.name}" (${low.height}м) и ниже "${hi.name}" (${hi.height}м)!`) } } }
ор ниже всех гор!') } else { answer.setDescription(`Ваш ор выше "
conditional_block
growl.ts
import { IBot, IBotCommand, IBotCommandHelp, IBotMessage } from '../api' import { getRandomInt } from '../utils' interface IMountain { name: string height: number img?: string } export default class GrowlCommand implements IBotCommand { private readonly CMD_REGEXP = /^(or|ор)(?: |$)/im private _mo...
Bot, dataPath: string): void { this._mountains = (require(`${dataPath}`) as IMountain[]).sort((a, b) => a.height - b.height) } public isValid(msg: string): boolean { return this.CMD_REGEXP.test(msg) } public async process(msg: string, answer: IBotMessage): Promise<void> { const ...
return { caption: 'ор / or', description: 'Показывает уровень ора.' } } public init(bot: I
identifier_body
growl.ts
import { IBot, IBotCommand, IBotCommandHelp, IBotMessage } from '../api' import { getRandomInt } from '../utils' interface IMountain { name: string height: number img?: string } export default class GrowlCommand implements IBotCommand { private readonly CMD_REGEXP = /^(or|ор)(?: |$)/im private _mo...
answer.setImage(hi.img) } if (!low) { answer.setDescription('Ваш ор ниже всех гор!') } else { answer.setDescription(`Ваш ор выше "${low.name}" (${low.height}м) и ниже "${hi.name}" (${hi.height}м)!`) } } }
answer.setDescription('Ваш ор выше всех гор!') return } if (hi && hi.img) {
random_line_split
controller.js
/* Copyright (C) 2013 Bryan Hughes <bryan@theoreticalideations.com> This file is part of Aquarium Control. Aquarium Control 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, ...
exec(driverPath + ' off'); log('info', 'Controller started'); process.on('message', function (message) { if (message.type === 'lights.set') { process.send({ destination: 'master', type: 'log', data: { level: 'info', message: 'State change: ' + message.data } }); switch(message.data) { ...
{ process.send({ destination: 'master', type: 'log', data: { level: level, message: message } }); }
identifier_body
controller.js
/* Copyright (C) 2013 Bryan Hughes <bryan@theoreticalideations.com> This file is part of Aquarium Control. Aquarium Control 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, ...
case STATE_OFF: exec(driverPath + ' off'); break; case STATE_DAY: exec(driverPath + ' day'); break; case STATE_NIGHT: exec(driverPath + ' night'); break; } } });
switch(message.data) {
random_line_split
controller.js
/* Copyright (C) 2013 Bryan Hughes <bryan@theoreticalideations.com> This file is part of Aquarium Control. Aquarium Control 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, ...
(level, message) { process.send({ destination: 'master', type: 'log', data: { level: level, message: message } }); } exec(driverPath + ' off'); log('info', 'Controller started'); process.on('message', function (message) { if (message.type === 'lights.set') { process.send({ destination: 'master'...
log
identifier_name
popup.tsx
/* * popup.tsx * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This progr...
); };
random_line_split
lib.rs
for a file with a given HANDLE. #[cfg(windows)] MapFd(libc::HANDLE), /// Create a memory mapping for a file with a given fd. #[cfg(not(windows))] MapFd(c_int), /// When using `MapFd`, the start of the map is `usize` bytes from the start /// of the file. MapOffset(usize), /// On POSI...
, MapNonStandardFlags(..) => {} } } let flProtect = match (executable, readable, writable) { (false, false, false) if handle.is_none() => libc::PAGE_NOACCESS, (false, true, false) => libc::PAGE_READONLY, (false, true, true) => libc::PAGE_R...
{ offset = offset_; }
conditional_block
lib.rs
() -> usize { unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize } } #[cfg(windows)] fn page_size() -> usize { unsafe { let mut info = mem::zeroed(); libc::GetSystemInfo(&mut info); return info.dwPageSize as usize; } } /// A memory mapped file or chunk of memory. This is a very sy...
page_size
identifier_name
lib.rs
mapping for a file with a given HANDLE. #[cfg(windows)] MapFd(libc::HANDLE), /// Create a memory mapping for a file with a given fd. #[cfg(not(windows))] MapFd(c_int), /// When using `MapFd`, the start of the map is `usize` bytes from the start /// of the file. MapOffset(usize), ///...
}, MapOffset(offset_) => { offset = offset_ as off_t; }, MapNonStandardFlags(f) => { custom_flags = true; flags = f }, } } if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; } let r = unsafe { libc::mmap(addr as *mut c...
MapFd(fd_) => { flags |= libc::MAP_FILE; fd = fd_;
random_line_split
rideshare.js
/** Projeto OTTC - Operadora de Tecnologia de Transporte Compartilhado Copyright (C) <2017> Scipopulis Desenvolvimento e Análise de Dados Ltda 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, ei...
logger.debug("message finished"); return callback(null); }); }); }); }; RideShareProcessor.convertMessage = function (msg, callback) { logger.debug("rideShareProcessor: convertingMessage ",msg); RideShareProcessor.findUser(msg, function(err, user) {...
return callback({reuse: true, msg:err}); }
random_line_split
rideshare.js
/** Projeto OTTC - Operadora de Tecnologia de Transporte Compartilhado Copyright (C) <2017> Scipopulis Desenvolvimento e Análise de Dados Ltda 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, ei...
logger.debug("message finished"); return callback(null); }); }); }); }; RideShareProcessor.convertMessage = function (msg, callback) { logger.debug("rideShareProcessor: convertingMessage ",msg); RideShareProcessor.findUser(msg, function(err, user) {...
logger.error("->> ERRO on save Message:",converted_msg.service, converted_msg.agency,err); return callback({reuse: true, msg:err}); }
conditional_block
time_zone.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use glib_sys; use translate::*; use GString; use TimeType; glib_wrapper! { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TimeZone(Shared<glib_sys::GTimeZ...
(seconds: i32) -> TimeZone { unsafe { from_glib_full(glib_sys::g_time_zone_new_offset(seconds)) } } pub fn new_utc() -> TimeZone { unsafe { from_glib_full(glib_sys::g_time_zone_new_utc()) } } pub fn find_interval(&self, type_: TimeType, time_: i64) -> i32 { unsafe { ...
new_offset
identifier_name
time_zone.rs
use glib_sys; use translate::*; use GString; use TimeType; glib_wrapper! { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TimeZone(Shared<glib_sys::GTimeZone>); match fn { ref => |ptr| glib_sys::g_time_zone_ref(ptr), unref => |ptr| glib_sys::g_time_zone_unref(ptr), ...
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT
random_line_split
time_zone.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use glib_sys; use translate::*; use GString; use TimeType; glib_wrapper! { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TimeZone(Shared<glib_sys::GTimeZ...
#[cfg(any(feature = "v2_58", feature = "dox"))] pub fn get_identifier(&self) -> GString { unsafe { from_glib_none(glib_sys::g_time_zone_get_identifier(self.to_glib_none().0)) } } pub fn get_offset(&self, interval: i32) -> i32 { unsafe { glib_sys::g_time_zone_get_offset(self.to_glib_no...
{ unsafe { from_glib_none(glib_sys::g_time_zone_get_abbreviation( self.to_glib_none().0, interval, )) } }
identifier_body
models.py
from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.conf import settings from django.db import models from django.core.urlresolvers import reverse from django.db.models.signals import pre_save from django.utils import timezone from django.utils.text import...
def create_slug(instance, new_slug = None): career_slug = slugify(instance.title) if new_slug is not None: career_slug = new_slug qs = Career.objects.filter(career_slug = career_slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" %(career_slug, qs.first().id) ...
class Meta: ordering = ["-timestamp", "-updated"]
random_line_split
models.py
from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.conf import settings from django.db import models from django.core.urlresolvers import reverse from django.db.models.signals import pre_save from django.utils import timezone from django.utils.text import...
(self): return self.role def __str__(self): return self.role def get_absolute_url(self): return reverse('careers:detail', kwargs = {'slug':self.career_slug}) class Meta: ordering = ["-timestamp", "-updated"] def create_slug(instance, new_slug = None): career_slug = ...
__unicode__
identifier_name
models.py
from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.conf import settings from django.db import models from django.core.urlresolvers import reverse from django.db.models.signals import pre_save from django.utils import timezone from django.utils.text import...
pre_save.connect(pre_save_post_receiver, sender = Career)
instance.career_slug = create_slug(instance)
conditional_block
models.py
from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.conf import settings from django.db import models from django.core.urlresolvers import reverse from django.db.models.signals import pre_save from django.utils import timezone from django.utils.text import...
def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.career_slug: instance.career_slug = create_slug(instance) pre_save.connect(pre_save_post_receiver, sender = Career)
career_slug = slugify(instance.title) if new_slug is not None: career_slug = new_slug qs = Career.objects.filter(career_slug = career_slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" %(career_slug, qs.first().id) return create_slug(instance, slug = new_s...
identifier_body
enocean.py
""" Support for EnOcean binary sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.enocean/ """ import logging import voluptuous as vol from homeassistant.components.binary_sensor import ( BinarySensorDevice, PLATFORM_SCHEMA, SENS...
"""Initialize the EnOcean binary sensor.""" enocean.EnOceanDevice.__init__(self) self.stype = "listener" self.dev_id = dev_id self.which = -1 self.onoff = -1 self.devname = devname self._sensor_class = sensor_class @property def name(self): ...
"""Representation of EnOcean binary sensors such as wall switches.""" def __init__(self, dev_id, devname, sensor_class):
random_line_split
enocean.py
""" Support for EnOcean binary sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.enocean/ """ import logging import voluptuous as vol from homeassistant.components.binary_sensor import ( BinarySensorDevice, PLATFORM_SCHEMA, SENS...
elif value2 == 0x30: self.which = 1 self.onoff = 0 elif value2 == 0x10: self.which = 1 self.onoff = 1 self.hass.bus.fire('button_pressed', {"id": self.dev_id, 'pushed': value, ...
self.which = 0 self.onoff = 1
conditional_block
enocean.py
""" Support for EnOcean binary sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.enocean/ """ import logging import voluptuous as vol from homeassistant.components.binary_sensor import ( BinarySensorDevice, PLATFORM_SCHEMA, SENS...
def value_changed(self, value, value2): """Fire an event with the data that have changed. This method is called when there is an incoming packet associated with this platform. """ self.update_ha_state() if value2 == 0x70: self.which = 0 self...
"""Return the class of this sensor.""" return self._sensor_class
identifier_body
enocean.py
""" Support for EnOcean binary sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.enocean/ """ import logging import voluptuous as vol from homeassistant.components.binary_sensor import ( BinarySensorDevice, PLATFORM_SCHEMA, SENS...
(enocean.EnOceanDevice, BinarySensorDevice): """Representation of EnOcean binary sensors such as wall switches.""" def __init__(self, dev_id, devname, sensor_class): """Initialize the EnOcean binary sensor.""" enocean.EnOceanDevice.__init__(self) self.stype = "listener" self.dev...
EnOceanBinarySensor
identifier_name
requireParameterTypeRule.ts
import {RuleFailure} from 'tslint/lib/lint'; import {AbstractRule} from 'tslint/lib/rules'; import {RuleWalker} from 'tslint/lib/language/walker'; import * as ts from 'typescript'; export class Rule extends AbstractRule { public static FAILURE_STRING = "missing type declaration"; public apply(sourceFile: ts.Sourc...
(node: ts.MethodDeclaration) { if (node.name.getText().charAt(0) !== '_') { node.parameters.forEach((p: ts.ParameterDeclaration) => { // a parameter's "type" could be a specific string value, for example `fn(option: // "someOption", anotherOption: number)` if (p.type == null || p.type....
visitMethodDeclaration
identifier_name
requireParameterTypeRule.ts
import {RuleFailure} from 'tslint/lib/lint'; import {AbstractRule} from 'tslint/lib/rules'; import {RuleWalker} from 'tslint/lib/language/walker'; import * as ts from 'typescript'; export class Rule extends AbstractRule { public static FAILURE_STRING = "missing type declaration"; public apply(sourceFile: ts.Sourc...
if (ns.charAt(0) === '_') return; let failure = this.createFailure(location, 1, "expected parameter " + ns + " to have a type"); this.addFailure(failure); } } }
{ ns = (<ts.Identifier>name).text; }
conditional_block
requireParameterTypeRule.ts
import {RuleFailure} from 'tslint/lib/lint'; import {AbstractRule} from 'tslint/lib/rules'; import {RuleWalker} from 'tslint/lib/language/walker'; import * as ts from 'typescript'; export class Rule extends AbstractRule { public static FAILURE_STRING = "missing type declaration"; public apply(sourceFile: ts.Sourc...
// a parameter's "type" could be a specific string value, for example `fn(option: // "someOption", anotherOption: number)` if (p.type == null || p.type.kind !== ts.SyntaxKind.StringLiteral) { this.checkTypeAnnotation(p.getEnd(), <ts.TypeNode>p.type, p.name); } }); } ...
if (node.name.getText().charAt(0) !== '_') { node.parameters.forEach((p: ts.ParameterDeclaration) => {
random_line_split
requireParameterTypeRule.ts
import {RuleFailure} from 'tslint/lib/lint'; import {AbstractRule} from 'tslint/lib/rules'; import {RuleWalker} from 'tslint/lib/language/walker'; import * as ts from 'typescript'; export class Rule extends AbstractRule { public static FAILURE_STRING = "missing type declaration"; public apply(sourceFile: ts.Sourc...
private checkTypeAnnotation(location: number, typeAnnotation: ts.TypeNode, name?: ts.Node) { if (typeAnnotation == null) { let ns = "<name missing>"; if (name != null && name.kind === ts.SyntaxKind.Identifier) { ns = (<ts.Identifier>name).text; } if (ns.charAt(0) === '_') return;...
{ if (node.name.getText().charAt(0) !== '_') { node.parameters.forEach((p: ts.ParameterDeclaration) => { // a parameter's "type" could be a specific string value, for example `fn(option: // "someOption", anotherOption: number)` if (p.type == null || p.type.kind !== ts.SyntaxKind.String...
identifier_body
kl25z_map.rs
// Copyright 2014 Martin Kojtal (0xc0170) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or a...
(port: u32) -> &'static Port { unsafe { &*((BASE_PORTA + (port*0x1000)) as *const Port) } } } const BASE_MCG : u32 = 0x40064000; pub struct Mcg { pub c1 : VolatileRW<u8>, pub c2 : VolatileRW<u8>, pub c3 : VolatileRW<u8>, pub c4 : VolatileRW<u8>, pub c5 : VolatileRW<...
get
identifier_name
kl25z_map.rs
// Copyright 2014 Martin Kojtal (0xc0170) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or a...
pub cr : VolatileRW<u8>, } impl Osc0 { pub fn get() -> &'static Osc0 { unsafe { &*(BASE_OSC0 as *const Osc0) } } } const BASE_PTA :u32 = 0x400FF000; pub struct Gpio { pub pdor : VolatileRW<u32>, pub psor : VolatileRW<u32>, pub pcor : VolatileRW<u32>, pub ptor :...
const BASE_OSC0 : u32 = 0x40065000; pub struct Osc0 {
random_line_split
kl25z_map.rs
// Copyright 2014 Martin Kojtal (0xc0170) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or a...
} const BASE_PORTA : u32 = 0x40049000; pub struct Port { pub pcr : [VolatileRW<u32>; 32], pub gpclr : VolatileRW<u32>, pub gpchr : VolatileRW<u32>, pub reserved_0 : [u8; 24], pub isfr : VolatileRW<u32>, } impl Port { pub fn get(port: u32) -> &'static Port { unsafe { &*((B...
{ unsafe { &*(BASE_SIM as *const Sim) } }
identifier_body
toolbar-controller.js
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distribut...
} else { $scope.items.push(toolbarItems[i]); } } }); $scope.secondaryItems = FLOWABLE.TOOLBAR_CONFIG.secondaryItems; // Call configurable click handler (From http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-...
{ $scope.items.push(toolbarItems[i]); }
conditional_block
toolbar-controller.js
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distribut...
$scope.editorFactory.promise.then(function () { var toolbarItems = FLOWABLE.TOOLBAR_CONFIG.items; $scope.items = []; for (var i = 0; i < toolbarItems.length; i++) { if ($rootScope.modelData.model.modelType === 'form') { if (!toolbarItems[...
angular.module('flowableModeler') .controller('ToolbarController', ['$scope', '$http', '$modal', '$q', '$rootScope', '$translate', '$location', 'editorManager', function ($scope, $http, $modal, $q, $rootScope, $translate, $location, editorManager) {
random_line_split
utils.rs
//! Shared mathematical utility functions. /// Cut value to be inside given range /// /// ``` /// use image::math::utils; /// /// assert_eq!(utils::clamp(-5, 0, 10), 0); /// assert_eq!(utils::clamp( 6, 0, 10), 6); /// assert_eq!(utils::clamp(15, 0, 10), 10); /// ``` #[inline] #[deprecated] pub fn clamp<N>(a: N, min:...
/// Calculates the width and height an image should be resized to. /// This preserves aspect ratio, and based on the `fill` parameter /// will either fill the dimensions to fit inside the smaller constraint /// (will overflow the specified bounds on one axis to preserve /// aspect ratio), or will shrink so that both ...
{ if a < min { return min; } if a > max { return max; } a }
identifier_body
utils.rs
//! Shared mathematical utility functions. /// Cut value to be inside given range /// /// ``` /// use image::math::utils; /// /// assert_eq!(utils::clamp(-5, 0, 10), 0); /// assert_eq!(utils::clamp( 6, 0, 10), 6); /// assert_eq!(utils::clamp(15, 0, 10), 10); /// ``` #[inline] #[deprecated] pub fn clamp<N>(a: N, min:...
else { u64::from(width) * u64::from(nheight) / u64::from(height) }; let intermediate = std::cmp::max(1, intermediate); if use_width { if intermediate <= u64::from(::std::u32::MAX) { (nwidth, intermediate as u32) } else { ( (u64::from(nwidth) *...
{ u64::from(height) * u64::from(nwidth) / u64::from(width) }
conditional_block
utils.rs
//! Shared mathematical utility functions. /// Cut value to be inside given range /// /// ``` /// use image::math::utils; /// /// assert_eq!(utils::clamp(-5, 0, 10), 0); /// assert_eq!(utils::clamp( 6, 0, 10), 6); /// assert_eq!(utils::clamp(15, 0, 10), 10); /// ``` #[inline] #[deprecated] pub fn clamp<N>(a: N, min:...
() { let result = super::resize_dimensions(1, 150, 128, 128, false); assert!(result.0 > 0); assert!(result.1 > 0); } #[test] fn resize_handles_overflow() { let result = super::resize_dimensions(100, ::std::u32::MAX, 200, ::std::u32::MAX, true); assert!(result.0 == 10...
resize_never_rounds_to_zero
identifier_name
utils.rs
//! Shared mathematical utility functions. /// Cut value to be inside given range /// /// ``` /// use image::math::utils; /// /// assert_eq!(utils::clamp(-5, 0, 10), 0); /// assert_eq!(utils::clamp( 6, 0, 10), 6); /// assert_eq!(utils::clamp(15, 0, 10), 10); /// ``` #[inline] #[deprecated] pub fn clamp<N>(a: N, min:...
/// (will overflow the specified bounds on one axis to preserve /// aspect ratio), or will shrink so that both dimensions are /// completely contained with in the given `width` and `height`, /// with empty space on one axis. pub(crate) fn resize_dimensions(width: u32, height: u32, nwidth: u32, nheight: u32, fill: bool)...
/// Calculates the width and height an image should be resized to. /// This preserves aspect ratio, and based on the `fill` parameter /// will either fill the dimensions to fit inside the smaller constraint
random_line_split
input.ts
.focused = false; this.stateChanges.next(); } } protected _disabled = false; /** * Implemented as part of MatFormFieldControl. * @docs-private */ @Input() get id(): string { return this._id; } set id(value: string) { this._id = value || this._uid; } protected _id: string; /** * I...
{ throw getMatInputUnsupportedTypeError(this._type); }
conditional_block
input.ts
{ if (this.ngControl && this.ngControl.disabled !== null) { return this.ngControl.disabled; } return this._disabled; } set disabled(value: boolean) { this._disabled = coerceBooleanProperty(value); // Browsers may not fire the blur event if the input is disabled too quickly. // Reset ...
_dirtyCheckNativeValue
identifier_name
input.ts
// Native input properties that are overwritten by Angular inputs need to be synced with // the native input element. Otherwise property bindings for those don't work. '[attr.id]': 'id', '[attr.placeholder]': '_getPlaceholderAttribute()', // At the time of writing, we have a lot of customer tests th...
} ngAfterViewInit() { if (this._platform.isBrowser) { this._autofillMonitor.monitor(this._elementRef.nativeElement).subscribe(event => { this.autofilled = event.isAutofilled; this.stateChanges.next(); }); } } ngOnChanges() { this.stateChanges.next(); } ngOnDestroy(...
random_line_split
input.ts
= false; this.stateChanges.next(); } } protected _disabled = false; /** * Implemented as part of MatFormFieldControl. * @docs-private */ @Input() get id(): string { return this._id; } set id(value: string) { this._id = value || this._uid; } protected _id: string; /** * Implement...
{ if (MAT_INPUT_INVALID_TYPES.indexOf(this._type) > -1) { throw getMatInputUnsupportedTypeError(this._type); } }
identifier_body
service.py
# -*- coding: utf-8 -*- # Copyright (C) 2014 by Clearcode <http://clearcode.cc> # and associates (see AUTHORS.md). # This file is part of ianitor. # ianitor 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 Foundat...
(self): """ Deregister service from consul cluster. :return: None """ logger.debug("deregistering service") with ignore_connection_errors("deregister"): self.session.agent.service.deregister(self.service_id) def keep_alive(self): """ Kee...
deregister
identifier_name
service.py
# -*- coding: utf-8 -*- # Copyright (C) 2014 by Clearcode <http://clearcode.cc> # and associates (see AUTHORS.md). # This file is part of ianitor. # ianitor 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 Foundat...
self.process = None self.ttl = ttl self.service_name = service_name self.tags = tags or [] self.port = port self.service_id = service_id or service_name self.check_id = "service:" + self.service_id def start(self): """ Start service process. ...
self.command = command self.session = session
random_line_split
service.py
# -*- coding: utf-8 -*- # Copyright (C) 2014 by Clearcode <http://clearcode.cc> # and associates (see AUTHORS.md). # This file is part of ianitor. # ianitor 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 Foundat...
self.kill()
conditional_block
service.py
# -*- coding: utf-8 -*- # Copyright (C) 2014 by Clearcode <http://clearcode.cc> # and associates (see AUTHORS.md). # This file is part of ianitor. # ianitor 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 Foundat...
def is_up(self): """ Poll service process to check if service is up. :return: """ logger.debug("polling service") return bool(self.process) and self.process.poll() is None def kill(self): """ Kill service process and make sure it is deregistere...
""" Start service process. :return: """ logger.debug("starting service: %s" % " ".join(self.command)) self.process = subprocess.Popen(self.command) self.register()
identifier_body
schema.ts
import Key from './key'; import Model from './model'; import utils from './utils'; /** * Schema */ export default class Schema { /** * Schema keys */ public keys: Array<Key> = []; /** * The model */ public Model: any; /** * The Model JS object */ public modeljs: any; /** * Cach...
for (let i = constructors.length - 1; i >= 0; i--) { utils.extend(schema, constructors[i].schema); } let index = 0; utils.forEach(schema, (value, name) => { const key = new this.modeljs.Key(this, name, value); this.cache.index.keys[name] = index++; this.keys.push(key); }); ...
{ constructors.push(model); model = utils.getParent(model); }
conditional_block
schema.ts
import Key from './key'; import Model from './model'; import utils from './utils'; /** * Schema */ export default class
{ /** * Schema keys */ public keys: Array<Key> = []; /** * The model */ public Model: any; /** * The Model JS object */ public modeljs: any; /** * Cache */ public cache: any = { index: { keys: {} }, mutators: { get: {}, set: {} } }; con...
Schema
identifier_name
schema.ts
import Key from './key'; import Model from './model'; import utils from './utils'; /** * Schema */ export default class Schema { /** * Schema keys */ public keys: Array<Key> = []; /** * The model */ public Model: any; /** * The Model JS object */ public modeljs: any; /** * Cach...
this.cache.index.keys[name] = index++; this.keys.push(key); }); } }
{ const constructors = [], schema = {}; this.modeljs = modeljs; this.Model = model; if (utils.isUndefined(this.modeljs.types[(this.Model as any).Collection])) { throw new this.modeljs.Exception('Collection `' + (this.Model as any).Collection + '` is not registered'); } this.Model...
identifier_body
schema.ts
import Key from './key'; import Model from './model'; import utils from './utils'; /** * Schema */ export default class Schema { /** * Schema keys */ public keys: Array<Key> = []; /** * The model */ public Model: any; /** * The Model JS object */ public modeljs: any; /** * Cach...
} }
random_line_split
sendmoremoney.rs
//! Send More Money. //! //! https://en.wikipedia.org/wiki/Verbal_arithmetic extern crate puzzle_solver; use puzzle_solver::{Puzzle,Solution,VarToken}; fn make_send_more_money() -> (Puzzle, Vec<VarToken>) { let mut sys = Puzzle::new(); let vars = sys.new_vars_with_candidates_1d(8, &[0,1,2,3,4,5,6,7,8,9]); ...
} #[test] fn sendmoremoney_naive() { let (mut sys, vars) = make_send_more_money(); let dict = sys.solve_unique().expect("solution"); print_send_more_money(&dict, &vars); verify_send_more_money(&dict, &vars); println!("sendmoremoney_naive: {} guesses", sys.num_guesses()); }
{ let carry = [0,1]; let (mut sys, vars) = make_send_more_money(); let (s, e, n, d) = (vars[0], vars[1], vars[2], vars[3]); let (m, o, r, y) = (vars[4], vars[5], vars[6], vars[7]); let c1 = sys.new_var_with_candidates(&carry); let c2 = sys.new_var_with_candidates(&carry); let c3 = sys.new_v...
identifier_body
sendmoremoney.rs
//! Send More Money. //! //! https://en.wikipedia.org/wiki/Verbal_arithmetic extern crate puzzle_solver; use puzzle_solver::{Puzzle,Solution,VarToken}; fn make_send_more_money() -> (Puzzle, Vec<VarToken>) { let mut sys = Puzzle::new(); let vars = sys.new_vars_with_candidates_1d(8, &[0,1,2,3,4,5,6,7,8,9]); ...
} #[test] fn sendmoremoney_naive() { let (mut sys, vars) = make_send_more_money(); let dict = sys.solve_unique().expect("solution"); print_send_more_money(&dict, &vars); verify_send_more_money(&dict, &vars); println!("sendmoremoney_naive: {} guesses", sys.num_guesses()); }
println!("sendmoremoney_carry: {} guesses", sys.num_guesses());
random_line_split
sendmoremoney.rs
//! Send More Money. //! //! https://en.wikipedia.org/wiki/Verbal_arithmetic extern crate puzzle_solver; use puzzle_solver::{Puzzle,Solution,VarToken}; fn
() -> (Puzzle, Vec<VarToken>) { let mut sys = Puzzle::new(); let vars = sys.new_vars_with_candidates_1d(8, &[0,1,2,3,4,5,6,7,8,9]); let (s, e, n, d) = (vars[0], vars[1], vars[2], vars[3]); let (m, o, r, y) = (vars[4], vars[5], vars[6], vars[7]); sys.remove_candidates(s, &[0]); sys.remove_candid...
make_send_more_money
identifier_name
15.2.3.6-4-528.js
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es5id: 15.2.3.6-4-528 description: > ES5 Attributes - fail to update [[Configurable]] attribute of accessor property ([[Get]] is a Function, [[Set]] is undefined, [[E...
Object.defineProperty(obj, "prop", { configurable: true }); $ERROR("Expected TypeError"); } catch (e) { assert(e instanceof TypeError); var desc2 = Object.getOwnPropertyDescriptor(obj, "prop"); assert.sameValue(desc1.configurable, false); assert.sameValue(desc2.configurable, false...
var desc1 = Object.getOwnPropertyDescriptor(obj, "prop"); try {
random_line_split
triggers.py
from django.db import transaction from denorm.db import base class RandomBigInt(base.RandomBigInt): def sql(self): return '(9223372036854775806::INT8 * ((RANDOM()-0.5)*2.0) )::INT8' class TriggerNestedSelect(base.TriggerNestedSelect): def sql(self): columns = self.columns table = se...
if not conditions: cond = "TRUE" else: cond = "AND".join(conditions) sql = """ CREATE OR REPLACE FUNCTION func_%(name)s() RETURNS TRIGGER AS $$ BEGIN IF %(cond)s THEN %(actions)s END IF; RETURN NULL; END; $$ LANGUAGE plpg...
conditions.append("(OLD.%s=%s)" % (ct_field, content_type))
conditional_block
triggers.py
from django.db import transaction from denorm.db import base class RandomBigInt(base.RandomBigInt): def sql(self): return '(9223372036854775806::INT8 * ((RANDOM()-0.5)*2.0) )::INT8' class TriggerNestedSelect(base.TriggerNestedSelect): def sql(self): columns = self.columns table = se...
if self.content_type_field: name += "_%s" % self.content_type return name def sql(self): name = self.name() params = [] action_set = set() for a in self.actions: sql, action_params = a.sql() if sql: action_set.add(s...
class Trigger(base.Trigger): def name(self): name = base.Trigger.name(self)
random_line_split
triggers.py
from django.db import transaction from denorm.db import base class RandomBigInt(base.RandomBigInt): def sql(self): return '(9223372036854775806::INT8 * ((RANDOM()-0.5)*2.0) )::INT8' class TriggerNestedSelect(base.TriggerNestedSelect): def sql(self): columns = self.columns table = se...
(self): cursor = self.cursor() cursor.execute("SELECT lanname FROM pg_catalog.pg_language WHERE lanname ='plpgsql'") if not cursor.fetchall(): cursor.execute('CREATE LANGUAGE plpgsql') for name, trigger in self.triggers.iteritems(): sql, args = trigger.sql() ...
install
identifier_name
triggers.py
from django.db import transaction from denorm.db import base class RandomBigInt(base.RandomBigInt): def sql(self): return '(9223372036854775806::INT8 * ((RANDOM()-0.5)*2.0) )::INT8' class TriggerNestedSelect(base.TriggerNestedSelect): def sql(self): columns = self.columns table = se...
# If Django didn't know what this field type should be # then compare it as text - Fixes a problem of trying to # compare PostGIS geometry fields. conditions.append("(OLD.%(f)s::%(t)s IS DISTINCT FROM NEW.%(f)s::%(t)s)" % {'f': field, 't': ...
name = self.name() params = [] action_set = set() for a in self.actions: sql, action_params = a.sql() if sql: action_set.add(sql) params.extend(action_params) actions = ";\n ".join(action_set) + ';' table = self.db_table ...
identifier_body
work.tsx
import React, { useEffect, useRef } from 'react' import styles from './styles/work.module.css' import { graphql, Link, useStaticQuery } from 'gatsby' import Img from 'gatsby-image' const Hnb = require('../icons/hnb.svg') const Floomx = require('../icons/floomx.svg') const Acuris = require('../icons/acuris.svg') const...
workplaceDesc: `PageUp is a pioneer HR software that streamlines recruitment, development and retention of talent.`, role: 'Junior developer -> Developer -> Senior developer.', project: `PageUp is where I honed myself as a developer. I worked on many projects in several different teams. I could talk for hou...
<Pageup /> </div> ), workplace: '2014 - 2018, PageUp (pageuppeople.com)', href: 'https://www.pageuppeople.com/',
random_line_split
index.ts
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
main();
{ // check that the client instance can be created const phishingProtectionServiceV1Beta1Client = new PhishingProtectionServiceV1Beta1Client(); doStuffWithPhishingProtectionServiceV1Beta1Client( phishingProtectionServiceV1Beta1Client ); }
identifier_body
index.ts
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
phishingProtectionServiceV1Beta1Client ); } main();
random_line_split
index.ts
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
( client: PhishingProtectionServiceV1Beta1Client ) { client.close(); } function main() { // check that the client instance can be created const phishingProtectionServiceV1Beta1Client = new PhishingProtectionServiceV1Beta1Client(); doStuffWithPhishingProtectionServiceV1Beta1Client( phishingProtectionS...
doStuffWithPhishingProtectionServiceV1Beta1Client
identifier_name
taxi_pipeline_kubernetes_test.py
# Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
super().setUp() self._test_dir = os.path.join( os.environ.get('TEST_UNDECLARED_OUTPUTS_DIR', self.get_temp_dir()), self._testMethodName) def testTaxiPipelineCheckDagConstruction(self): logical_pipeline = taxi_pipeline_kubernetes.create_pipeline( pipeline_name='Test', pipel...
class TaxiPipelineKubernetesTest(tf.test.TestCase): def setUp(self):
random_line_split
taxi_pipeline_kubernetes_test.py
# Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
(self): logical_pipeline = taxi_pipeline_kubernetes.create_pipeline( pipeline_name='Test', pipeline_root=self._test_dir, data_root=self._test_dir, module_file=self._test_dir, serving_model_dir=self._test_dir, beam_pipeline_args=[]) self.assertEqual(9, len(logical_...
testTaxiPipelineCheckDagConstruction
identifier_name
taxi_pipeline_kubernetes_test.py
# Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
def testTaxiPipelineCheckDagConstruction(self): logical_pipeline = taxi_pipeline_kubernetes.create_pipeline( pipeline_name='Test', pipeline_root=self._test_dir, data_root=self._test_dir, module_file=self._test_dir, serving_model_dir=self._test_dir, beam_pipeline_a...
super().setUp() self._test_dir = os.path.join( os.environ.get('TEST_UNDECLARED_OUTPUTS_DIR', self.get_temp_dir()), self._testMethodName)
identifier_body
taxi_pipeline_kubernetes_test.py
# Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
tf.test.main()
conditional_block
Util.js
var Util = { addClass: function(cl, el){ if( el.className.trim() == '' || el.className.indexOf(cl) == -1 ){ el.className += ' '+ cl; } }, hasClass: function(cl, el){ return el.className.split(' ').indexOf( cl.replace('.', '') ) > -1; }, removeClass: function(cl, el){ if( el...
(data, formData){ var buildStr = !formData; if( buildStr ) formData = []; for( var key in data ){ if( data.hasOwnProperty(key) ){ var dat = data[key]; if( dat instanceof Array ){ for( var i=0; i<dat.length; i++ ){ var item = ( dat[i...
addObjectData
identifier_name
Util.js
var Util = { addClass: function(cl, el){ if( el.className.trim() == '' || el.className.indexOf(cl) == -1 ){ el.className += ' '+ cl; } }, hasClass: function(cl, el){ return el.className.split(' ').indexOf( cl.replace('.', '') ) > -1; }, removeClass: function(cl, el){ if( el...
}catch( error ){ resp = req.responseText; } resolve( resp ); if( opts.onSuccess ) opts.onSuccess( resp ); }else{ try{ resp = JSON.parse(req.responseText); }catch( error ){ resp = req.re...
if( req.status == 200 ){ try{ resp = JSON.parse(req.responseText);
random_line_split
Util.js
var Util = { addClass: function(cl, el){ if( el.className.trim() == '' || el.className.indexOf(cl) == -1 ){ el.className += ' '+ cl; } }, hasClass: function(cl, el){ return el.className.split(' ').indexOf( cl.replace('.', '') ) > -1; }, removeClass: function(cl, el){ if( el...
}else{ if( buildStr ) formData.push( key +'='+ dat ); else formData.append( key, dat ); } } } if( buildStr ){ return formData.join('&'); } } function buildFormData(){ var formData; if( reqType == 'GET' )...
{ var buildStr = !formData; if( buildStr ) formData = []; for( var key in data ){ if( data.hasOwnProperty(key) ){ var dat = data[key]; if( dat instanceof Array ){ for( var i=0; i<dat.length; i++ ){ var item = ( dat[i] instanceof Obj...
identifier_body
Util.js
var Util = { addClass: function(cl, el){ if( el.className.trim() == '' || el.className.indexOf(cl) == -1 ){ el.className += ' '+ cl; } }, hasClass: function(cl, el){ return el.className.split(' ').indexOf( cl.replace('.', '') ) > -1; }, removeClass: function(cl, el){ if( el...
} if( opts.data ){ if( typeof formData == 'string' ) formData = addObjectData(opts.data); else addObjectData(opts.data, formData); } return formData; } var promise = new Promise(function(resolve, reject){ req.open( reqType, reqURL, true ); ...
{ formData = new FormData(); }
conditional_block
legends.ts
namespace Legends { import plt = Bokeh.Plotting import linspace = Bokeh.LinAlg.linspace console.log(`Bokeh ${Bokeh.version}`); Bokeh.set_log_level("info"); const x = linspace(0, 4*Math.PI, 100) const y = x.map((v) => Math.sin(v)) const y2 = y.map((v) => 2*v) const y3 = y.map((v) => 3*...
p2.line(x, y, {legend: "sin(x)"}) p2.line(x, y2, {legend: "2*sin(x)", /*line_dash: [4, 4],*/ line_color: "orange", line_width: 2}) p2.square(x, y3, {legend: "3*sin(x)", fill_color: null, line_color: "green"}) p2.line(x, y3, {legend: "3*sin(x)", line_color: "green"}) plt.show(new Bokeh.Column({chi...
const p2 = plt.figure({title: "Another Legend Example", x_range: xr, y_range: yr}) p2.circle(x, y, {legend: "sin(x)"})
random_line_split
heart.js
/*global window*/ (function($){ 'use strict'; var Observable = function(){ this.observers = {}; }; Observable.prototype.on = function(event, observer){ (this.observers[event] = this.observers[event] || []).push(observer); }; Observable.prototype.emit = function(event){ v...
return this._alpha; }; var Step = function(){}; Step.prototype.description = function(){ return this.type + this.x + ',' + this.y; }; var MoveTo = function(x, y){ Step.call(this); this.type = 'M'; this.x = x; this.y = y; }; MoveTo.prototype ...
{ this.emit('alpha', this._alpha); }
conditional_block
heart.js
/*global window*/ (function($){ 'use strict'; var Observable = function(){ this.observers = {}; }; Observable.prototype.on = function(event, observer){ (this.observers[event] = this.observers[event] || []).push(observer); }; Observable.prototype.emit = function(event){ v...
return point.description(); }).join(''); }; })(window.heart = window.heart || {});
random_line_split
setup.py
""" Setup file. """ import os from setuptools import setup, find_packages
with open(os.path.join(here, 'README.rst')) as f: README = f.read() requires = ['cornice', 'metlog-py', 'mozsvc', 'PasteScript', 'waitress', 'PyBrowserID', 'Requests', 'webtest'] setup(name='fxap', version=0.1, description='fxap', long_description=README, license='MPLv2.0', classifiers=[ ...
here = os.path.abspath(os.path.dirname(__file__))
random_line_split
cargo.rs
#![allow(unstable)] extern crate "rustc-serialize" as rustc_serialize; extern crate cargo; #[macro_use] extern crate log; use std::collections::BTreeSet; use std::os; use std::io; use std::io::fs::{self, PathExtensions}; use std::io::process::{Command,InheritFd,ExitStatus,ExitSignal}; use cargo::{execute_main_withou...
println!(" {}", command); }; return Ok(None) } let (mut args, command) = match flags.arg_command.as_slice() { "" | "help" if flags.arg_args.len() == 0 => { shell.set_verbose(true); let args = &[os::args()[0].clone(), "-h".to_string()]; ...
for command in list_commands().into_iter() {
random_line_split
cargo.rs
#![allow(unstable)] extern crate "rustc-serialize" as rustc_serialize; extern crate cargo; #[macro_use] extern crate log; use std::collections::BTreeSet; use std::os; use std::io; use std::io::fs::{self, PathExtensions}; use std::io::process::{Command,InheritFd,ExitStatus,ExitSignal}; use cargo::{execute_main_withou...
{ let mut dirs = vec![]; match os::self_exe_path() { Some(path) => { dirs.push(path.join("../lib/cargo")); dirs.push(path); }, None => {} }; match std::os::getenv("PATH") { Some(val) => { for dir in os::split_paths(val).iter() { ...
identifier_body
cargo.rs
#![allow(unstable)] extern crate "rustc-serialize" as rustc_serialize; extern crate cargo; #[macro_use] extern crate log; use std::collections::BTreeSet; use std::os; use std::io; use std::io::fs::{self, PathExtensions}; use std::io::process::{Command,InheritFd,ExitStatus,ExitSignal}; use cargo::{execute_main_withou...
(cmd: &str, args: &[String], shell: &mut MultiShell) { let command = match find_command(cmd) { Some(command) => command, None => { let msg = match find_closest(cmd) { Some(closest) => format!("No such subcommand\n\n\tDid you mean `{}`?\n", closest), None =...
execute_subcommand
identifier_name
matrix.component.ts
import { Input, AfterContentInit, Component, ElementRef, SimpleChanges, OnChanges } from '@angular/core'; import { MatrixData, MatrixOpts } from './interfaces'; declare let d3: any; // reference to window.d3 declare let KashMatrix: any; // reference to window.KashMatrix @Component( {selector: 'd3-matrix'...
private dataUpdate(data: MatrixData){ if (!this.svgElement || !data['length']) return; this.svgElement.datum(data); } private optionsUpdate(opts: MatrixOpts){ if (!opts || !this.chartModel) return; for (let key in opts) this.chartModel[key](opts[key]); } ngOnChanges(changes: SimpleChang...
{ if (!this.svgElement || !this.chartModel) return; this.svgElement.call(this.chartModel); // render the chart }
identifier_body
matrix.component.ts
import { Input, AfterContentInit, Component, ElementRef, SimpleChanges, OnChanges } from '@angular/core'; import { MatrixData, MatrixOpts } from './interfaces'; declare let d3: any; // reference to window.d3 declare let KashMatrix: any; // reference to window.KashMatrix @Component( {selector: 'd3-matrix'...
implements AfterContentInit, OnChanges { constructor(private elementRef: ElementRef) {} @Input() data: MatrixData = []; // from attributes @Input() opts: MatrixOpts = {}; // from attributes svgElement: any = null; // svg chartModel: any = KashMatrix(); // chart model, invoked ngAfterContentInit(...
MatrixComponent
identifier_name
matrix.component.ts
import { Input, AfterContentInit, Component, ElementRef, SimpleChanges, OnChanges } from '@angular/core'; import { MatrixData, MatrixOpts } from './interfaces'; declare let d3: any; // reference to window.d3 declare let KashMatrix: any; // reference to window.KashMatrix
constructor(private elementRef: ElementRef) {} @Input() data: MatrixData = []; // from attributes @Input() opts: MatrixOpts = {}; // from attributes svgElement: any = null; // svg chartModel: any = KashMatrix(); // chart model, invoked ngAfterContentInit() { const element = this.elementRef.nat...
@Component( {selector: 'd3-matrix', template: ``}) export class MatrixComponent implements AfterContentInit, OnChanges {
random_line_split
test_daemon.py
#!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
# Copyright 2014 Hewlett-Packard Development Company, L.P. #
random_line_split
test_daemon.py
#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # 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 # # Unles...
for x in iterate_timeout(30, "daemon to start"): if os.path.exists(pidfile): break os.unlink(flagfile) for x in iterate_timeout(30, "daemon to stop"): if not os.path.exists(pidfile): break
self._cleanups = [] daemon_test(pidfile, flagfile)
conditional_block
test_daemon.py
#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # 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 # # Unles...
(testtools.TestCase): log = logging.getLogger("zuul.test.daemon") def setUp(self): super(TestDaemon, self).setUp() self.test_root = self.useFixture(fixtures.TempDir( rootdir=os.environ.get("ZUUL_TEST_ROOT"))).path def test_daemon(self): pidfile = os.path.join(self.test_...
TestDaemon
identifier_name
test_daemon.py
#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # 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 # # Unles...
break
log = logging.getLogger("zuul.test.daemon") def setUp(self): super(TestDaemon, self).setUp() self.test_root = self.useFixture(fixtures.TempDir( rootdir=os.environ.get("ZUUL_TEST_ROOT"))).path def test_daemon(self): pidfile = os.path.join(self.test_root, "daemon.pid") ...
identifier_body
ports.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
161: true, // snmp 179: true, // BGP 389: true, // ldap 427: true, // SLP (Also used by Apple Filing Protocol) 465: true, // smtp+ssl 512: true, // print / exec 513: true, // login 514: true, // shell 515: true, // printer 526: true, // tempo 530...
139: true, // netbios 143: true, // imap2
random_line_split
ports.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
// If we receive any non ECONNREFUSED error, it means the port is used but we cannot connect if (err.code !== 'ECONNREFUSED') { return doFindFreePort(startPort + stride, giveUpAfter - 1, stride, clb); } // Otherwise it means the port is free to use! return clb(startPort); }); client.connect(startPort,...
{ if (giveUpAfter === 0) { return clb(0); } const client = new net.Socket(); // If we can connect to the port it means the port is already taken so we continue searching client.once('connect', () => { dispose(client); return doFindFreePort(startPort + stride, giveUpAfter - 1, stride, clb); }); client.o...
identifier_body
ports.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
const client = new net.Socket(); // If we can connect to the port it means the port is already taken so we continue searching client.once('connect', () => { dispose(client); return doFindFreePort(startPort + stride, giveUpAfter - 1, stride, clb); }); client.once('data', () => { // this listener is requi...
{ return clb(0); }
conditional_block
ports.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(startPort: number, giveUpAfter: number, timeout: number, stride = 1): Promise<number> { let done = false; return new Promise(resolve => { const timeoutHandle = setTimeout(() => { if (!done) { done = true; return resolve(0); } }, timeout); doFindFreePort(startPort, giveUpAfter, stride, (port) =>...
findFreePort
identifier_name
DynamicRoutePage.tsx
import * as React from 'react'; import {Page, Navbar, ContentBlockTitle, ContentBlock, List, ListItem, ListLabel, ListGroup, ListButton} from 'framework7-react'; import {getCurrentRoute} from '../App'; export class DynamicRoutePage extends React.Component<any, any> { private currentRoute: any; constructor(pro...
</ContentBlock> <ContentBlock inner> <p>Route <b>params</b> are also passed as component props:</p> <ul> <li><b>id:</b> {this.props.id}</li> <li><b>post_id:</b> {this.props.post_id}</li> ...
</ul> </li> <li><b>Route:</b> {this.currentRoute.route.path}</li> </ul>
random_line_split
DynamicRoutePage.tsx
import * as React from 'react'; import {Page, Navbar, ContentBlockTitle, ContentBlock, List, ListItem, ListLabel, ListGroup, ListButton} from 'framework7-react'; import {getCurrentRoute} from '../App'; export class DynamicRoutePage extends React.Component<any, any> { private currentRoute: any; constructor(pro...
<ul> { Object.keys(this.currentRoute.query).map((queryItem, index) => { return (<li key={index}><b>{`${queryItem}:`}</b> {this.currentRoute.query[queryItem]}</li>); ...
{ return ( <Page> <Navbar backLink="Back" title="Lists" sliding></Navbar> <ContentBlock inner> <ul> <li><b>Url:</b> {this.currentRoute.url}</li> <li><b>Path:</b> {this.currentRoute.path}</li> ...
identifier_body
DynamicRoutePage.tsx
import * as React from 'react'; import {Page, Navbar, ContentBlockTitle, ContentBlock, List, ListItem, ListLabel, ListGroup, ListButton} from 'framework7-react'; import {getCurrentRoute} from '../App'; export class DynamicRoutePage extends React.Component<any, any> { private currentRoute: any;
(props: any, context: any) { super(props, context); this.currentRoute = getCurrentRoute(); } render() { return ( <Page> <Navbar backLink="Back" title="Lists" sliding></Navbar> <ContentBlock inner> <ul> ...
constructor
identifier_name
mediawiki.action.edit.editWarning.js
/* * Javascript for module editWarning */ ( function ( mw, $ ) { 'use strict'; $( function () { var allowCloseWindow, $textBox = $( '#wpTextbox1' ), $summary = $( '#wpSummary' ), $both = $textBox.add( $summary ); // Check if EditWarning is enabled and if we need it if ( !mw.user.options.get( 'useed...
} ); } ); }( mediaWiki, jQuery ) );
random_line_split
mediawiki.action.edit.editWarning.js
/* * Javascript for module editWarning */ ( function ( mw, $ ) { 'use strict'; $( function () { var allowCloseWindow, $textBox = $( '#wpTextbox1' ), $summary = $( '#wpSummary' ), $both = $textBox.add( $summary ); // Check if EditWarning is enabled and if we need it if ( !mw.user.options.get( 'useed...
// Save the original value of the text fields $both.each( function ( index, element ) { var $element = $( element ); $element.data( 'origtext', $element.textSelection( 'getContents' ) ); } ); allowCloseWindow = mw.confirmCloseWindow( { test: function () { // We use .textSelection, because editor...
{ return true; }
conditional_block
autocomplete-trigger.ts
Defaults to the autocomplete trigger element. */ @Input('matAutocompleteConnectedTo') connectedTo: _MatAutocompleteOriginBase; /** * `autocomplete` attribute to be set on the input element. * @docs-private */ @Input('autocomplete') autocompleteAttribute: string = 'off'; /** * Whether the autoc...
(fn: () => {}) { this._onTouched = fn; } // Implemented as part of ControlValueAccessor. setDisabledState(isDisabled: boolean) { this._element.nativeElement.disabled = isDisabled; } _handleKeydown(event: KeyboardEvent): void { const keyCode = event.keyCode; // Prevent the default action on ...
registerOnTouched
identifier_name
autocomplete-trigger.ts
Defaults to the autocomplete trigger element. */ @Input('matAutocompleteConnectedTo') connectedTo: _MatAutocompleteOriginBase; /** * `autocomplete` attribute to be set on the input element. * @docs-private */ @Input('autocomplete') autocompleteAttribute: string = 'off'; /** * Whether the autoc...
if (this._overlayAttached) { this._overlayRef!.updatePosition(); } } /** * A stream of actions that should close the autocomplete panel, including * when an option is selected, on blur, and when TAB is pressed. */ get panelClosingActions(): Observable<MatOptionSelectionChange|null> { r...
random_line_split
autocomplete-trigger.ts
ClickStream(), this._overlayRef ? this._overlayRef.detachments().pipe(filter(() => this._overlayAttached)) : observableOf() ).pipe( // Normalize the output so we return a consistent type. map(event => event instanceof MatOptionSelectionChange ? event : null) ); } /** S...
{ const toDisplay = this.autocomplete && this.autocomplete.displayWith ? this.autocomplete.displayWith(value) : value; // Simply falling back to an empty string if the display value is falsy does not work properly. // The display value can also be the number zero and shouldn't fall back to an e...
identifier_body
autocomplete-trigger.ts
value is falsy does not work properly. // The display value can also be the number zero and shouldn't fall back to an empty string. const inputValue = toDisplay != null ? toDisplay : ''; // If it's used within a `MatFormField`, we should set it through the property so it can go // through change detec...
{ const element = option._getHostElement(); const newScrollPosition = _getOptionScrollPosition( element.offsetTop, element.offsetHeight, autocomplete._getScrollTop(), autocomplete.panel.nativeElement.offsetHeight ); autocomplete._setScrollTop(newS...
conditional_block
EventListener.js
/** * Created by vladi on 27-Jan-17. */ import { removeEventListenerById, suspendEventListenerById, restoreEventListenerById, isListenerSuspended, listenerExists, addTypeFilter, addTypeFilters, resetTypeFilter, removeTypeFilter,
constructor(listenerUid, onRemoveCallback) { this.listenerUid = listenerUid; this._onRemoveCallback = onRemoveCallback; } filter(mixed) { if (mixed) { Array.isArray(mixed) ? addTypeFilters(this.listenerUid, mixed) : addTypeFilter(this.listenerUid, mixed) } ...
removeTypeFilters } from './EventsControl'; export default class EventListener {
random_line_split
EventListener.js
/** * Created by vladi on 27-Jan-17. */ import { removeEventListenerById, suspendEventListenerById, restoreEventListenerById, isListenerSuspended, listenerExists, addTypeFilter, addTypeFilters, resetTypeFilter, removeTypeFilter, removeTypeFilters } from './EventsControl'; expor...
filter(mixed) { if (mixed) { Array.isArray(mixed) ? addTypeFilters(this.listenerUid, mixed) : addTypeFilter(this.listenerUid, mixed) } return this; } unFilter(mixed) { if (mixed) { Array.isArray(mixed) ? removeTypeFilters(this.listenerUid, mixed) : ...
{ this.listenerUid = listenerUid; this._onRemoveCallback = onRemoveCallback; }
identifier_body
EventListener.js
/** * Created by vladi on 27-Jan-17. */ import { removeEventListenerById, suspendEventListenerById, restoreEventListenerById, isListenerSuspended, listenerExists, addTypeFilter, addTypeFilters, resetTypeFilter, removeTypeFilter, removeTypeFilters } from './EventsControl'; expor...
return this; } unFilter(mixed) { if (mixed) { Array.isArray(mixed) ? removeTypeFilters(this.listenerUid, mixed) : removeTypeFilter(this.listenerUid, mixed) } else { resetTypeFilter(this.listenerUid); } return this; } remove() { i...
{ Array.isArray(mixed) ? addTypeFilters(this.listenerUid, mixed) : addTypeFilter(this.listenerUid, mixed) }
conditional_block