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
220 Contains Duplicate III.py
class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ if k < 1 or t < 0: return False dic = {} t += 1 for i in range(len(nums)): ...
return False test = Solution() print(test.containsNearbyAlmostDuplicate([1, 3, 1], 1, 1))
return True if m + 1 in dic and abs(nums[i] - dic[m + 1]) < t: return True dic[m] = nums[i]
random_line_split
220 Contains Duplicate III.py
class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ if k < 1 or t < 0: return False dic = {} t += 1 for i in range(len(nums)): ...
if m - 1 in dic and abs(nums[i] - dic[m - 1]) < t: return True if m + 1 in dic and abs(nums[i] - dic[m + 1]) < t: return True dic[m] = nums[i] return False test = Solution() print(test.containsNearbyAlmostDuplicate([1, 3, 1], 1, 1))
return True
conditional_block
220 Contains Duplicate III.py
class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t):
dic[m] = nums[i] return False test = Solution() print(test.containsNearbyAlmostDuplicate([1, 3, 1], 1, 1))
""" :type nums: List[int] :type k: int :type t: int :rtype: bool """ if k < 1 or t < 0: return False dic = {} t += 1 for i in range(len(nums)): if i > k: del dic[nums[i - k - 1] // t] m = nums[i] ...
identifier_body
uninstall.ts
import { PackageManifestLog, StatsLog, } from '@pnpm/core-loggers' import { prepareEmpty } from '@pnpm/prepare' import { addDependenciesToPackage, mutateModules, } from '@pnpm/core' import sinon from 'sinon' import { testDefaults } from './../utils' test('uninstall package with no dependencies', async () => { ...
manifest, mutation: 'uninstallSome', rootDir: process.cwd(), }, ], await testDefaults({ nodeLinker: 'hoisted', pruneStore: true, save: true })))[0].manifest await project.storeHasNot('camelcase-keys', '3.0.0') await project.hasNot('camelcase-keys') await project.storeHasNot('camelcase', ...
await testDefaults({ nodeLinker: 'hoisted', save: true }) ) manifest = (await mutateModules([ { dependencyNames: ['camelcase-keys'],
random_line_split
qunit-bdd.js
/** * Processes the current contexts by setting them up as QUnit modules. * * @private */ function addTestsToQUnit() { if (options.randomize) { pendingContexts = randomize(pendingContexts); } pendingContexts.forEach(function(context) { QUnit.module(context.fullDescription(), {...
{ return contextStack[contextStack.length - 1]; }
identifier_body
qunit-bdd.js
Array.<T>} array * @return {Array.<T>} */ function shuffle(array) { var j, x, i = array.length; while (i) { j = Math.floor(Math.random() * i); x = array[--i]; array[i] = array[j]; array[j] = x; } return array; } var randomize = (typeof options.randomize === 'funct...
assertionWrapper
identifier_name
qunit-bdd.js
to be made available in all before/after/it blocks * for the current context. This helper allows you to create complex values * that are dependent on simpler values that may be overridden in child * contexts. * * `value` may either be a function, in which case the value is lazily * determined as need...
{ if (exports) { exports[key] = map[key]; } if (GLOBALS === true || (typeof GLOBALS === 'object' && GLOBALS[key] !== false)) { global[key] = map[key]; } }
conditional_block
qunit-bdd.js
* @param {object} env `this` inside the hook callback functions. */ Context.prototype.prependHook = function(hook, up, env) { var queue = []; var parent = this.parent; this[hook].forEach(function(fn) { queue.push(function() { if (QUnit.config.notrycatch) { fn.call(env); ...
* @param {up} boolean true to run from inside-out, false to run outside-in.
random_line_split
message.ts
import { Component } from '@angular/core'; import { NavController, NavParams, ActionSheetController, ModalController } from 'ionic-angular'; import { DataApi } from '../../provider/index'; import { MessageInterface } from '../../interface/message.interface'; import { TopicPage } from '../topic/topic'; import { LoginPag...
else { this.isLogin = false; } } ionViewWillEnter() { this.init(); } pullToRefresh(refresher) { this.getMessages().then(res => refresher.complete()); } getMessageCount() { this.dataApi.getMessageUnreadCount().then((res) => { this.messageCo...
{ this.isLogin = true; this.getMessages(); this.getMessageCount(); }
conditional_block
message.ts
import { Component } from '@angular/core'; import { NavController, NavParams, ActionSheetController, ModalController } from 'ionic-angular'; import { DataApi } from '../../provider/index'; import { MessageInterface } from '../../interface/message.interface'; import { TopicPage } from '../topic/topic'; import { LoginPag...
= this.modalCtrl.create(LoginPage); modal.onDidDismiss(data => { this.init(); }); modal.present(); } }
identifier_body
message.ts
import { Component } from '@angular/core'; import { NavController, NavParams, ActionSheetController, ModalController } from 'ionic-angular'; import { DataApi } from '../../provider/index'; import { MessageInterface } from '../../interface/message.interface'; import { TopicPage } from '../topic/topic'; import { LoginPag...
() { this.presentActionSheet().then((res) => { if (res) { this.dataApi.messageReadAll().then((res) => { console.log(res); this.getMessages(); }) } }) } presentActionSheet(): Promise < any > { ...
markAllRead
identifier_name
message.ts
import { Component } from '@angular/core'; import { NavController, NavParams, ActionSheetController, ModalController } from 'ionic-angular'; import { DataApi } from '../../provider/index'; import { MessageInterface } from '../../interface/message.interface'; import { TopicPage } from '../topic/topic'; import { LoginPag...
}); modal.present(); } }
random_line_split
frame_allocator.rs
use super::frame::{Frame, FrameAllocator}; use super::PAGE_SIZE; use ::kern::console as con; use con::LogLevel::*; use collections::Vec; const UNIT: usize = PAGE_SIZE; #[derive(Debug)] pub struct BuddyAllocator { pub start: usize, pub size: usize, tree: Vec<usize> } impl BuddyAllocator { pub fn new(...
(&self, n: usize) -> Option<usize> { if n >= self.tree.len() { None } else { let o = (n+1).next_power_of_two() / 2; let chunk = self.size / o; let offset = chunk * (n - o); return Some(self.start + offset * UNIT); } } fn mark_u...
address_of
identifier_name
frame_allocator.rs
use super::frame::{Frame, FrameAllocator}; use super::PAGE_SIZE; use ::kern::console as con; use con::LogLevel::*; use collections::Vec; const UNIT: usize = PAGE_SIZE; #[derive(Debug)] pub struct BuddyAllocator { pub start: usize, pub size: usize, tree: Vec<usize> } impl BuddyAllocator { pub fn new(...
}
random_line_split
frame_allocator.rs
use super::frame::{Frame, FrameAllocator}; use super::PAGE_SIZE; use ::kern::console as con; use con::LogLevel::*; use collections::Vec; const UNIT: usize = PAGE_SIZE; #[derive(Debug)] pub struct BuddyAllocator { pub start: usize, pub size: usize, tree: Vec<usize> } impl BuddyAllocator { pub fn new(...
let mut offset = (addr - self.start) / UNIT; if offset >= self.size { return; } let mut size = 1; let mut n = offset + self.size; while self.tree[n] != 0 { n = n / 2; size *= 2; } self.tree[n] = size; while n > 1 { ...
{ return; }
conditional_block
frame_allocator.rs
use super::frame::{Frame, FrameAllocator}; use super::PAGE_SIZE; use ::kern::console as con; use con::LogLevel::*; use collections::Vec; const UNIT: usize = PAGE_SIZE; #[derive(Debug)] pub struct BuddyAllocator { pub start: usize, pub size: usize, tree: Vec<usize> } impl BuddyAllocator { pub fn new(...
pub fn dump(&self) { for i in 1..self.tree.len() { if i.is_power_of_two() { printk!(Debug, "\n"); } printk!(Debug, "{} ", self.tree[i]); } printk!(Debug, "\n"); } fn address_of(&self, n: usize) -> Option<usize> { if n >= ...
{ let size = size / UNIT; let size = if size.is_power_of_two() { size } else { size.next_power_of_two() / 2 }; let mut tree = vec![0; size*2]; for i in 1..tree.len() { tree[i] = size * 2 / (i+1).next_power_of_two(); } printk!(Info, "BuddyAllocator {:x}\n", tr...
identifier_body
types.js
/*! * conkitty, https://github.com/hoho/conkitty * Copyright 2013-2014 Marat Abdullin * Released under the MIT license */ 'use strict'; module.exports = { TEMPLATE_NAME: 'template name', COMMAND_NAME: 'command name', VARIABLE: 'variable', JAVASCRIPT: 'JavaScript', STRING: 'string', CSS: 'cs...
CSS_IF: 'css conditional', ATTR: 'attribute', INCLUDE: 'file include', ARGUMENT_DECL: 'argument declaration', ARGUMENT_VAL: 'argument value', NODE_APPENDER: 'node appender' };
CSS_ATTR_NAME: 'css attribute name',
random_line_split
associated-types-eq-3.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn baz(x: &Foo<A=Bar>) { let _: Bar = x.boo(); } pub fn main() { let a = 42i; foo1(a); //~ERROR expected usize, found struct Bar baz(&a); //~ERROR expected usize, found struct Bar }
{ let _: Bar = x.boo(); //~ERROR mismatched types }
identifier_body
associated-types-eq-3.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn boo(&self) -> <Self as Foo>::A; } struct Bar; impl Foo for int { type A = uint; fn boo(&self) -> uint { 42 } } fn foo1<I: Foo<A=Bar>>(x: I) { let _: Bar = x.boo(); } fn foo2<I: Foo>(x: I) { let _: Bar = x.boo(); //~ERROR mismatched types } pub fn baz(x: &Foo<A=Bar>) { let _:...
// Test equality constraints on associated types. Check we get type errors // where we should. pub trait Foo { type A;
random_line_split
associated-types-eq-3.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<I: Foo>(x: I) { let _: Bar = x.boo(); //~ERROR mismatched types } pub fn baz(x: &Foo<A=Bar>) { let _: Bar = x.boo(); } pub fn main() { let a = 42i; foo1(a); //~ERROR expected usize, found struct Bar baz(&a); //~ERROR expected usize, found struct Bar }
foo2
identifier_name
bdz.py
import * from collections import deque from bitstring import BitArray import math class bdz(b_hash): """Class for perfect hash function generated by the BDZ algorithm. This algorithms uses uniform random hypergraph.""" def __init__(self): b_hash.__init__(self) self.known_keys = False #Keyse...
hyper = graph() hyper.set_order(self.function_number) hyper.add_vertices(self.m) #Generation of the edges of the hypergraph for x in self.key_set: values = list() for i in self.seed["hashes"]: #print("test",i.hash(x)%limit,limit*len(values)...
"""This is internal function. It generate random hypergraph according to the specification in the bdz class. It returns a queue of the edge and changes internal datastructure of BDZ class. Returned edges are ordered in such way, that they can be used for the construction of the PHF""" #First step is to initiali...
identifier_body
bdz.py
* from collections import deque from bitstring import BitArray import math class bdz(b_hash): """Class for perfect hash function generated by the BDZ algorithm. This algorithms uses uniform random hypergraph.""" def __init__(self): b_hash.__init__(self) self.known_keys = False #Keyset is no...
(self, key): limit = int(self.m /self.function_number) # print(limit) hashes = [x.hash(key)%limit for x in self.seed["hashes"]] h1 = [hashes[x]+x*limit for x in range(0,len(hashes))] g_val = [self
hash
identifier_name
bdz.py
* from collections import deque from bitstring import BitArray import math class bdz(b_hash): """Class for perfect hash function generated by the BDZ algorithm. This algorithms uses uniform random hypergraph.""" def __init__(self): b_hash.__init__(self) self.known_keys = False #Keyset is no...
self.hyper = hyper return queue_list def _found_g(self,v,ed,vi): """This function computes value of the g array for given vertex. It uses plus operation.""" s = [self.g[s1] for s1 in self.hyper.get_edge(ed).get_vertices()] sum1 = sum(s)-s[vi]; self.g[v] = (vi-sum1)...
e1 = hyper.get_vertex(v).get_edges()[0] position = hyper.get_edge_position(e1) #If it is not in the queue, put it there if used[position] == False: queue.append(position) queue_list.append(position) ...
conditional_block
bdz.py
* from collections import deque from bitstring import BitArray import math class bdz(b_hash): """Class for perfect hash function generated by the BDZ algorithm. This algorithms uses uniform random hypergraph.""" def __init__(self): b_hash.__init__(self) self.known_keys = False #Keyset is no...
def _found_g(self,v,ed,vi): """This function computes value of the g array for given vertex. It uses plus operation.""" s = [self.g[s1] for s1 in self.hyper.get_edge(ed).get_vertices()] sum1 = sum(s)-s[vi]; self.g[v] = (vi-sum1)%len(s) return True; def _found_g2(self,v,e...
queue_list.append(position) used[position] = True self.hyper = hyper return queue_list
random_line_split
account.py
# -*- coding: utf-8 -* import uuid import random import string from test import DjangoTestCase class Account(object): def __init__(self, email=None, password=None): self.email = email self.password = password @staticmethod def create_email(): return u"some.one+%s@example.com" % u...
def logout(self, email=None, password=None): data = {} if email is not None: data[u"email"] = email if password is not None: data[u"password"] = password return self.http_post(u"/logout", data)
data = {} if email is not None: data[u"email"] = email if password is not None: data[u"password"] = password return self.http_post(u"/login", data)
identifier_body
account.py
# -*- coding: utf-8 -* import uuid import random import string from test import DjangoTestCase class Account(object): def __init__(self, email=None, password=None): self.email = email self.password = password @staticmethod def create_email(): return u"some.one+%s@example.com" % u...
if password_confirmation is not None: data[u"password_confirmation"] = password_confirmation response = self.http_post(u"/signup", data) return Account(email=email, password=password), response def login(self, email=None, password=None): data = {} if email ...
data[u"password"] = password
conditional_block
account.py
# -*- coding: utf-8 -* import uuid import random import string from test import DjangoTestCase class Account(object): def
(self, email=None, password=None): self.email = email self.password = password @staticmethod def create_email(): return u"some.one+%s@example.com" % uuid.uuid4().hex.__str__() @staticmethod def create_password(length=20): return u"".join([random.choice(string.digits) fo...
__init__
identifier_name
account.py
# -*- coding: utf-8 -* import uuid import random import string from test import DjangoTestCase class Account(object): def __init__(self, email=None, password=None): self.email = email self.password = password @staticmethod def create_email(): return u"some.one+%s@example.com" % u...
return Account(email=email, password=password), response def login(self, email=None, password=None): data = {} if email is not None: data[u"email"] = email if password is not None: data[u"password"] = password return self.http_post(u"/login", dat...
if password_confirmation is not None: data[u"password_confirmation"] = password_confirmation response = self.http_post(u"/signup", data)
random_line_split
page_index.js
/*-- Addition for remembering expanded state of pages --*/ function writeSessionCookie(cookieName, cookieValue) { document.cookie = escape(cookieName) + "=" + escape(cookieValue) + ";"; } function toggle_viewers() { if (document.add.visibility.value == 'private') { document.getElementById('viewe...
else { document.images['plus_minus_' + id].src = plus.src; } } if (typeof jQuery != 'undefined') { jQuery(document).ready(function ($) { // fix for Flat Theme $('div.pages_list table td').css('padding-top', 0).css('padding-bottom', 0); $('table.pages_view tbody tr td')...
{ document.images['plus_minus_' + id].src = minus.src; }
conditional_block
page_index.js
/*-- Addition for remembering expanded state of pages --*/ function writeSessionCookie(cookieName, cookieValue) { document.cookie = escape(cookieName) + "=" + escape(cookieValue) + ";"; } function
() { if (document.add.visibility.value == 'private') { document.getElementById('viewers').style.display = 'block'; } else if (document.add.visibility.value == 'registered') { document.getElementById('viewers').style.display = 'block'; } else { document.getElementById('viewers')...
toggle_viewers
identifier_name
page_index.js
/*-- Addition for remembering expanded state of pages --*/ function writeSessionCookie(cookieName, cookieValue) { document.cookie = escape(cookieName) + "=" + escape(cookieValue) + ";"; } function toggle_viewers() { if (document.add.visibility.value == 'private') { document.getElementById('viewe...
var plus = new Image; plus.src = THEME_URL + "/images/expand.png"; var minus = new Image; minus.src = THEME_URL + "/images/collapse.png"; function toggle_plus_minus(id) { var img_src = document.images['plus_minus_' + id].src; if (img_src == plus.src) { document.images['plus_minus_' + id].sr...
{ if (document.getElementById(id).style.display == "block") { document.getElementById(id).style.display = "none"; writeSessionCookie(id, "0");//Addition for remembering expanded state of pages } else { document.getElementById(id).style.display = "block"; writeSessionCookie(...
identifier_body
page_index.js
/*-- Addition for remembering expanded state of pages --*/ function writeSessionCookie(cookieName, cookieValue) { document.cookie = escape(cookieName) + "=" + escape(cookieValue) + ";"; } function toggle_viewers() { if (document.add.visibility.value == 'private') { document.getElementById('viewe...
plus.src = THEME_URL + "/images/expand.png"; var minus = new Image; minus.src = THEME_URL + "/images/collapse.png"; function toggle_plus_minus(id) { var img_src = document.images['plus_minus_' + id].src; if (img_src == plus.src) { document.images['plus_minus_' + id].src = minus.src; } else ...
var plus = new Image;
random_line_split
targetImpedance.validator.ts
import { IPipeline, IStage, IStageOrTriggerTypeConfig } from 'core/domain'; import { NameUtils } from 'core/naming'; import { PipelineConfigService } from 'core/pipeline/config/services/PipelineConfigService'; import { IStageOrTriggerValidator, IValidatorConfig, PipelineConfigValidator } from './PipelineConfigValidato...
( pipeline: IPipeline, stage: IStage, validator: ITargetImpedanceValidationConfig, _config: IStageOrTriggerTypeConfig, ): string { const stagesToTest: IStage[] = PipelineConfigService.getAllUpstreamDependencies(pipeline, stage); const regions: string[] = stage['regions'] || []; let allRegi...
validate
identifier_name
targetImpedance.validator.ts
import { IPipeline, IStage, IStageOrTriggerTypeConfig } from 'core/domain'; import { NameUtils } from 'core/naming'; import { PipelineConfigService } from 'core/pipeline/config/services/PipelineConfigService'; import { IStageOrTriggerValidator, IValidatorConfig, PipelineConfigValidator } from './PipelineConfigValidato...
return null; } } PipelineConfigValidator.registerValidator('targetImpedance', new TargetImpedanceValidator());
{ return validator.message; }
conditional_block
targetImpedance.validator.ts
import { IPipeline, IStage, IStageOrTriggerTypeConfig } from 'core/domain'; import { NameUtils } from 'core/naming'; import { PipelineConfigService } from 'core/pipeline/config/services/PipelineConfigService'; import { IStageOrTriggerValidator, IValidatorConfig, PipelineConfigValidator } from './PipelineConfigValidato...
} }); if (!regionFound) { allRegionsFound = false; } }); if (!allRegionsFound) { return validator.message; } return null; } } PipelineConfigValidator.registerValidator('targetImpedance', new TargetImpedanceValidator());
stage['cluster'] && toTest['region'] === region ) { regionFound = true;
random_line_split
views.py
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import Q from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.decorators import method_decorator from django.views....
class PostComment(CreateView): """ Saves comments received to a post. Removed ability to GET the page. """ model = Comment fields = ['text'] @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(PostComment, self).dispatch(request, *args, **k...
model = Post template_name = 'post.html' def get_queryset(self): return self.model.objects.for_display()
random_line_split
views.py
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import Q from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.decorators import method_decorator from django.views....
(CreateView): """ Saves comments received to a post. Removed ability to GET the page. """ model = Comment fields = ['text'] @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(PostComment, self).dispatch(request, *args, **kwargs) def get...
PostComment
identifier_name
views.py
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import Q from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.decorators import method_decorator from django.views....
return qs class SinglePost(DetailView): """ Display a single selected post. """ model = Post template_name = 'post.html' def get_queryset(self): return self.model.objects.for_display() class PostComment(CreateView): """ Saves comments received to a post. Removed abi...
qs = qs.filter(Q(title__icontains=search_query) | Q(content__icontains=search_query))
conditional_block
views.py
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import Q from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.decorators import method_decorator from django.views....
class PostComment(CreateView): """ Saves comments received to a post. Removed ability to GET the page. """ model = Comment fields = ['text'] @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(PostComment, self).dispatch(request, *args, **...
""" Display a single selected post. """ model = Post template_name = 'post.html' def get_queryset(self): return self.model.objects.for_display()
identifier_body
movie-edit.component.ts
import { Component } from '@angular/core'; import { FormBuilder, ControlGroup, Validators } from '@angular/common'; import { ROUTER_DIRECTIVES, OnActivate, RouteSegment } from '@angular/router'; import { IMovie } from './movie'; import { MovieService } from './movie.service'; import { NumberValidator } from '../shared...
onValueChanged(data: any) { for (let field in this.formError) { if (this.formError.hasOwnProperty(field)) { let hasError = this.editForm.controls[field].dirty && !this.editForm.controls[field].valid; this.formError[field] = ''; ...
random_line_split
movie-edit.component.ts
import { Component } from '@angular/core'; import { FormBuilder, ControlGroup, Validators } from '@angular/common'; import { ROUTER_DIRECTIVES, OnActivate, RouteSegment } from '@angular/router'; import { IMovie } from './movie'; import { MovieService } from './movie.service'; import { NumberValidator } from '../shared...
saveMovie() { console.log(this.editForm); if (this.editForm.dirty && this.editForm.valid) { this.movie = this.editForm.value; alert(`Movie: ${JSON.stringify(this.editForm.value)}`); } } }
{ for (let field in this.formError) { if (this.formError.hasOwnProperty(field)) { let hasError = this.editForm.controls[field].dirty && !this.editForm.controls[field].valid; this.formError[field] = ''; if (hasError) { ...
identifier_body
movie-edit.component.ts
import { Component } from '@angular/core'; import { FormBuilder, ControlGroup, Validators } from '@angular/common'; import { ROUTER_DIRECTIVES, OnActivate, RouteSegment } from '@angular/router'; import { IMovie } from './movie'; import { MovieService } from './movie.service'; import { NumberValidator } from '../shared...
} } } saveMovie() { console.log(this.editForm); if (this.editForm.dirty && this.editForm.valid) { this.movie = this.editForm.value; alert(`Movie: ${JSON.stringify(this.editForm.value)}`); } } }
{ for (let key in this.editForm.controls[field].errors) { if (this.editForm.controls[field].errors.hasOwnProperty(key)) { this.formError[field] += this._validationMessages[field][key] + ' '; } } ...
conditional_block
movie-edit.component.ts
import { Component } from '@angular/core'; import { FormBuilder, ControlGroup, Validators } from '@angular/common'; import { ROUTER_DIRECTIVES, OnActivate, RouteSegment } from '@angular/router'; import { IMovie } from './movie'; import { MovieService } from './movie.service'; import { NumberValidator } from '../shared...
() { console.log(this.editForm); if (this.editForm.dirty && this.editForm.valid) { this.movie = this.editForm.value; alert(`Movie: ${JSON.stringify(this.editForm.value)}`); } } }
saveMovie
identifier_name
test_interleave_cc_1i.py
#!/usr/bin/env python # # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of GNUHAWK. # # GNUHAWK is free software: you can redistribute it and/or modify is under the # terms of the GNU General Public License as published by ...
self.assertEqual(port_obj._is_a(port.get_repid()), True) ####################################################################### # Make sure start and stop can be called without throwing exceptions self.comp.start() self.comp.stop() ############...
for port in self.scd.get_componentfeatures().get_ports().get_provides(): port_obj = self.comp.getPort(str(port.get_providesname())) self.assertNotEqual(port_obj, None) self.assertEqual(port_obj._non_existent(), False)
random_line_split
test_interleave_cc_1i.py
#!/usr/bin/env python # # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of GNUHAWK. # # GNUHAWK is free software: you can redistribute it and/or modify is under the # terms of the GNU General Public License as published by ...
self.assertEquals(props.has_key(expectedProp.id), True) ####################################################################### # Verify that all expected ports are available for port in self.scd.get_componentfeatures().get_ports().get_uses(): port_obj = self.com...
execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False) execparams = dict([(x.id, any.from_any(x.value)) for x in execparams]) self.launch(execparams) ####################################################################### # Ver...
identifier_body
test_interleave_cc_1i.py
#!/usr/bin/env python # # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of GNUHAWK. # # GNUHAWK is free software: you can redistribute it and/or modify is under the # terms of the GNU General Public License as published by ...
ossie.utils.testing.main("../interleave_cc_1i.spd.xml") # By default tests all implementations
conditional_block
test_interleave_cc_1i.py
#!/usr/bin/env python # # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of GNUHAWK. # # GNUHAWK is free software: you can redistribute it and/or modify is under the # terms of the GNU General Public License as published by ...
(ossie.utils.testing.ScaComponentTestCase): """Test for all component implementations in interleave_cc_1i""" def testScaBasicBehavior(self): ####################################################################### # Launch the component with the default execparams execparams = self.getPr...
ComponentTests
identifier_name
tree_reader.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fileencoding=utf-8 """ this takes a newick string as instr and reads the string and makes the nodes and returns the root node http://www.github.com/FePhyFoFum/quartetsampling This file is part of 'quartetsampling'. 'quartetsampling' is free software: you can redis...
(instr): root = None index = 0 nextchar = instr[index] start = True keepgoing = True curnode = None while keepgoing is True: if nextchar is "(": if start is True: root = Node() curnode = root start = False else: ...
read_tree_string
identifier_name
tree_reader.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fileencoding=utf-8 """ this takes a newick string as instr and reads the string and makes the nodes and returns the root node http://www.github.com/FePhyFoFum/quartetsampling This file is part of 'quartetsampling'. 'quartetsampling' is free software: you can redis...
newnode = Node() curnode.add_child(newnode) curnode = newnode elif nextchar is ',': curnode = curnode.parent elif nextchar is ")": curnode = curnode.parent index += 1 nextchar = instr[index] name ...
root = Node() curnode = root start = False else:
random_line_split
tree_reader.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fileencoding=utf-8 """ this takes a newick string as instr and reads the string and makes the nodes and returns the root node http://www.github.com/FePhyFoFum/quartetsampling This file is part of 'quartetsampling'. 'quartetsampling' is free software: you can redis...
name += nextchar index += 1 nextchar = instr[index] curnode.label = name index -= 1 elif nextchar == ';': keepgoing = False break elif nextchar == ":": index += 1 nextchar = instr[inde...
if nextchar is "(": if start is True: root = Node() curnode = root start = False else: newnode = Node() curnode.add_child(newnode) curnode = newnode elif nextchar is ',': curnode =...
conditional_block
tree_reader.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fileencoding=utf-8 """ this takes a newick string as instr and reads the string and makes the nodes and returns the root node http://www.github.com/FePhyFoFum/quartetsampling This file is part of 'quartetsampling'. 'quartetsampling' is free software: you can redis...
index += 1 nextchar = instr[index] name = "" while True: if nextchar is ',' or nextchar is ')' or nextchar is ':' \ or nextchar is ';' or nextchar is '[': break name += nextchar in...
root = None index = 0 nextchar = instr[index] start = True keepgoing = True curnode = None while keepgoing is True: if nextchar is "(": if start is True: root = Node() curnode = root start = False else: ...
identifier_body
EntityStatePeSubsystemType.py
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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 version. # # PySCAP is ...
return PE_SUBSYSTEM_ENUMERATION
identifier_body
EntityStatePeSubsystemType.py
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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 version. # # PySCAP is ...
# You should have received a copy of the GNU General Public License # along with PySCAP. If not, see <http://www.gnu.org/licenses/>. import logging from scap.model.oval_5 import PE_SUBSYSTEM_ENUMERATION from scap.model.oval_5.defs.EntityStateType import EntityStateType logger = logging.getLogger(__name__) class En...
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. #
random_line_split
EntityStatePeSubsystemType.py
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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 version. # # PySCAP is ...
(self): return PE_SUBSYSTEM_ENUMERATION
get_value_enum
identifier_name
snake.rs
use std::collections::VecDeque; const SNAKE_LENGTH: i32 = 5; const ROWS: u8 = 30; const COLS: u8 = 30; pub enum Direction { Up, Down, Left, Right, None, } pub struct Snake { pub p: VecDeque<(i32, i32)>, pub d: Direction, } pub struct Food { pub p: (i32, i32), pub f: FoodType, } ...
(&mut self, d: Direction) { match (&self.d, &d) { (&Direction::Up, &Direction::Down) | (&Direction::Down, &Direction::Up) | (&Direction::Left, &Direction::Right) | (&Direction::Right, &Direction::Left) => {} _ => self.d = d, } } pub fn...
set_direction
identifier_name
snake.rs
use std::collections::VecDeque; const SNAKE_LENGTH: i32 = 5; const ROWS: u8 = 30; const COLS: u8 = 30; pub enum Direction { Up, Down, Left, Right, None, } pub struct Snake { pub p: VecDeque<(i32, i32)>, pub d: Direction, } pub struct Food { pub p: (i32, i32), pub f: FoodType, } ...
impl Snake { pub fn new() -> Self { Snake { p: VecDeque::new(), d: Direction::None, } } pub fn collide_with_tail(&self) -> bool { let h = self.p.front().unwrap(); self.p.iter().skip(1).any(|&p| p == *h) } pub fn collide_with_food(&self, food: ...
f: FoodType::Apple, } } }
random_line_split
snake.rs
use std::collections::VecDeque; const SNAKE_LENGTH: i32 = 5; const ROWS: u8 = 30; const COLS: u8 = 30; pub enum Direction { Up, Down, Left, Right, None, } pub struct Snake { pub p: VecDeque<(i32, i32)>, pub d: Direction, } pub struct Food { pub p: (i32, i32), pub f: FoodType, } ...
pub fn collide_with_edge(&self) -> bool { (self.p[0].0 < 0) | (self.p[0].1 < 0) | (self.p[0].1 < 0) | (self.p[0].1 >= COLS as i32) | (self.p[0].0 >= ROWS as i32) } }
{ match (&self.d, &d) { (&Direction::Up, &Direction::Down) | (&Direction::Down, &Direction::Up) | (&Direction::Left, &Direction::Right) | (&Direction::Right, &Direction::Left) => {} _ => self.d = d, } }
identifier_body
test_dsd.py
# Copyright 2015 Kevin Reid <kpreid@switchb.org> # # This file is part of ShinySDR. # # ShinySDR 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 lat...
from __future__ import absolute_import, division from shinysdr.test.testutil import DemodulatorTestCase class TestDSD(DemodulatorTestCase): def setUp(self): self.setUpFor(mode='DSD', skip_if_unavailable=True)
# GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ShinySDR. If not, see <http://www.gnu.org/licenses/>.
random_line_split
test_dsd.py
# Copyright 2015 Kevin Reid <kpreid@switchb.org> # # This file is part of ShinySDR. # # ShinySDR 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 lat...
(self): self.setUpFor(mode='DSD', skip_if_unavailable=True)
setUp
identifier_name
test_dsd.py
# Copyright 2015 Kevin Reid <kpreid@switchb.org> # # This file is part of ShinySDR. # # ShinySDR 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 lat...
def setUp(self): self.setUpFor(mode='DSD', skip_if_unavailable=True)
identifier_body
unboxed-closures-infer-recursive-fn.rs
// run-pass #![feature(fn_traits, unboxed_closures)] use std::marker::PhantomData; // Test that we are able to infer a suitable kind for a "recursive" // closure. As far as I can tell, coding up a recursive closure // requires the good ol' [Y Combinator]. // // [Y Combinator]: https://en.wikipedia.org/wiki/Fixed-poi...
}; let factorial: YCombinator<_,u32,u32> = YCombinator::new(factorial); let r = factorial(10); assert_eq!(3628800, r); }
{arg * recur(arg-1)}
conditional_block
unboxed-closures-infer-recursive-fn.rs
// run-pass #![feature(fn_traits, unboxed_closures)] use std::marker::PhantomData; // Test that we are able to infer a suitable kind for a "recursive" // closure. As far as I can tell, coding up a recursive closure // requires the good ol' [Y Combinator]. // // [Y Combinator]: https://en.wikipedia.org/wiki/Fixed-poi...
(f: F) -> YCombinator<F,A,R> { YCombinator { func: f, marker: PhantomData } } } impl<A,R,F : Fn(&dyn Fn(A) -> R, A) -> R> Fn<(A,)> for YCombinator<F,A,R> { extern "rust-call" fn call(&self, (arg,): (A,)) -> R { (self.func)(self, arg) } } impl<A,R,F : Fn(&dyn Fn(A) -> R, A) -> R> FnMut<(A,)...
new
identifier_name
unboxed-closures-infer-recursive-fn.rs
// run-pass #![feature(fn_traits, unboxed_closures)] use std::marker::PhantomData; // Test that we are able to infer a suitable kind for a "recursive" // closure. As far as I can tell, coding up a recursive closure // requires the good ol' [Y Combinator]. // // [Y Combinator]: https://en.wikipedia.org/wiki/Fixed-poi...
impl<A,R,F : Fn(&dyn Fn(A) -> R, A) -> R> Fn<(A,)> for YCombinator<F,A,R> { extern "rust-call" fn call(&self, (arg,): (A,)) -> R { (self.func)(self, arg) } } impl<A,R,F : Fn(&dyn Fn(A) -> R, A) -> R> FnMut<(A,)> for YCombinator<F,A,R> { extern "rust-call" fn call_mut(&mut self, args: (A,)) -> R { ...
YCombinator { func: f, marker: PhantomData } } }
random_line_split
unboxed-closures-infer-recursive-fn.rs
// run-pass #![feature(fn_traits, unboxed_closures)] use std::marker::PhantomData; // Test that we are able to infer a suitable kind for a "recursive" // closure. As far as I can tell, coding up a recursive closure // requires the good ol' [Y Combinator]. // // [Y Combinator]: https://en.wikipedia.org/wiki/Fixed-poi...
} impl<A,R,F : Fn(&dyn Fn(A) -> R, A) -> R> Fn<(A,)> for YCombinator<F,A,R> { extern "rust-call" fn call(&self, (arg,): (A,)) -> R { (self.func)(self, arg) } } impl<A,R,F : Fn(&dyn Fn(A) -> R, A) -> R> FnMut<(A,)> for YCombinator<F,A,R> { extern "rust-call" fn call_mut(&mut self, args: (A,)) -> R...
{ YCombinator { func: f, marker: PhantomData } }
identifier_body
impl.ts
import { ApplicationAbstractStateAction } from "../../../action/impl" import { initValidateBoardStack } from "../../validate_board/infra/stack" import { updateBoardValidateState } from "../../validate_board/impl" import { ValidateBoardStore } from "../../validate_board/infra" import { BoardConverter } from "../../ke...
class Action<N extends string, T> extends ApplicationAbstractStateAction<ValidateBoardActionState> implements ValidateBoardAction<N, T> { readonly initialState: ValidateBoardActionState = initialValidateBoardState converter: BoardConverter<T> material: ValidateBoardMaterial<N> constructor(co...
{ const store: ValidateBoardStore = { stack: initValidateBoardStack(), } return new Action(converter, { updateValidateState: updateBoardValidateState(fields, store), }) }
identifier_body
impl.ts
import { ApplicationAbstractStateAction } from "../../../action/impl" import { initValidateBoardStack } from "../../validate_board/infra/stack" import { updateBoardValidateState } from "../../validate_board/impl" import { ValidateBoardStore } from "../../validate_board/infra" import { BoardConverter } from "../../ke...
(): ConvertBoardResult<T> { return this.converter() } }
get
identifier_name
impl.ts
import { ApplicationAbstractStateAction } from "../../../action/impl" import { initValidateBoardStack } from "../../validate_board/infra/stack" import { updateBoardValidateState } from "../../validate_board/impl" import { ValidateBoardStore } from "../../validate_board/infra" import { BoardConverter } from "../../ke...
}) } class Action<N extends string, T> extends ApplicationAbstractStateAction<ValidateBoardActionState> implements ValidateBoardAction<N, T> { readonly initialState: ValidateBoardActionState = initialValidateBoardState converter: BoardConverter<T> material: ValidateBoardMaterial<N> constr...
stack: initValidateBoardStack(), } return new Action(converter, { updateValidateState: updateBoardValidateState(fields, store),
random_line_split
notifications.js
import Ember from 'ember'; import {AjaxError} from 'ember-ajax/errors'; const { Service, computed: {filter}, get, set, isArray } = Ember; const emberA = Ember.A; // Notification keys take the form of "noun.verb.message", eg: // // "invite.resend.api-error" // "user.invite.already-invited" // // Th...
() { this.delayedNotifications.forEach((message) => { this.get('content').pushObject(message); }); this.delayedNotifications = []; }, closeNotification(notification) { let content = this.get('content'); if (typeof notification.toJSON === 'function') { ...
displayDelayed
identifier_name
notifications.js
import Ember from 'ember'; import {AjaxError} from 'ember-ajax/errors'; const { Service, computed: {filter}, get, set, isArray } = Ember; const emberA = Ember.A; // Notification keys take the form of "noun.verb.message", eg: // // "invite.resend.api-error" // "user.invite.already-invited" // // Th...
} , showAlert(message, options) { options = options || {}; this.handleNotification({ message, status: 'alert', type: options.type, key: options.key }, options.delayed); }, showNotification(message, options) { options = op...
{ // If this is an alert message from the server, treat it as html safe if (typeof message.toJSON === 'function' && message.get('status') === 'alert') { message.set('message', message.get('message').htmlSafe()); } if (!get(message, 'status')) { set(message, 'stat...
identifier_body
notifications.js
import Ember from 'ember'; import {AjaxError} from 'ember-ajax/errors'; const { Service, computed: {filter}, get, set, isArray } = Ember; const emberA = Ember.A; // Notification keys take the form of "noun.verb.message", eg: // // "invite.resend.api-error" // "user.invite.already-invited" // // Th...
set(message, 'status', 'notification'); } // close existing duplicate alerts/notifications to avoid stacking if (get(message, 'key')) { this._removeItems(get(message, 'status'), get(message, 'key')); } if (!delayed) { this.get('content').push...
if (typeof message.toJSON === 'function' && message.get('status') === 'alert') { message.set('message', message.get('message').htmlSafe()); } if (!get(message, 'status')) {
random_line_split
notifications.js
import Ember from 'ember'; import {AjaxError} from 'ember-ajax/errors'; const { Service, computed: {filter}, get, set, isArray } = Ember; const emberA = Ember.A; // Notification keys take the form of "noun.verb.message", eg: // // "invite.resend.api-error" // "user.invite.already-invited" // // Th...
}, displayDelayed() { this.delayedNotifications.forEach((message) => { this.get('content').pushObject(message); }); this.delayedNotifications = []; }, closeNotification(notification) { let content = this.get('content'); if (typeof notification.toJS...
{ // text error or no error this.showAlert(resp || options.defaultErrorText, options); }
conditional_block
default.py
'accounts.middleware.UserLanguageMiddleware', 'django_otp.middleware.OTPMiddleware', ) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.Sess...
random_line_split
test_greatest_hot_100_singles.py
import json import unittest import billboard class TestCurrentGreatestHot100Singles(unittest.TestCase): """Checks that the ChartData object for the current Greatest Hot 100 Singles chart has entries and instance variables that are valid and reasonable. Does not test whether the data is actually correct. ...
def test_json(self): self.assertTrue(json.loads(self.chart.json())) for entry in self.chart: self.assertTrue(json.loads(entry.json()))
self.assertGreater(len(entry.title), 0) self.assertGreater(len(entry.artist), 0) self.assertIsNone(entry.peakPos) self.assertIsNone(entry.lastPos) self.assertIsNone(entry.weeks) # Redundant because of test_ranks self.assertTrue(1 <= entry.rank <= 1...
conditional_block
test_greatest_hot_100_singles.py
import json import unittest import billboard class TestCurrentGreatestHot100Singles(unittest.TestCase): """Checks that the ChartData object for the current Greatest Hot 100 Singles chart has entries and instance variables that are valid and reasonable. Does not test whether the data is actually correct. ...
def test_json(self): self.assertTrue(json.loads(self.chart.json())) for entry in self.chart: self.assertTrue(json.loads(entry.json()))
self.assertEqual(len(self.chart), 100) for entry in self.chart: self.assertGreater(len(entry.title), 0) self.assertGreater(len(entry.artist), 0) self.assertIsNone(entry.peakPos) self.assertIsNone(entry.lastPos) self.assertIsNone(entry.weeks) ...
identifier_body
test_greatest_hot_100_singles.py
import json import unittest import billboard class TestCurrentGreatestHot100Singles(unittest.TestCase): """Checks that the ChartData object for the current Greatest Hot 100 Singles chart has entries and instance variables that are valid and reasonable. Does not test whether the data is actually correct. ...
(self): self.chart = billboard.ChartData('greatest-hot-100-singles') def test_date(self): self.assertIsNone(self.chart.date) # This chart has no dates def test_ranks(self): ranks = list(entry.rank for entry in self.chart) self.assertEqual(ranks, list(range(1, 101))) def t...
setUp
identifier_name
test_greatest_hot_100_singles.py
import json import unittest import billboard class TestCurrentGreatestHot100Singles(unittest.TestCase): """Checks that the ChartData object for the current Greatest Hot 100 Singles chart has entries and instance variables that are valid and reasonable. Does not test whether the data is actually correct. ...
self.assertIsNone(entry.peakPos) self.assertIsNone(entry.lastPos) self.assertIsNone(entry.weeks) # Redundant because of test_ranks self.assertTrue(1 <= entry.rank <= 100) self.assertIsInstance(entry.isNew, bool) def test_json(self): se...
for entry in self.chart: self.assertGreater(len(entry.title), 0) self.assertGreater(len(entry.artist), 0)
random_line_split
Softmax.ts
/** * @license * 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 a...
};
random_line_split
Softmax.ts
/** * @license * 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 a...
const sumExp = sum({inputs: {x: b}, backend, attrs: {axis: axes, keepDims: false}}); const sumExpReshaped = reshape({inputs: {x: sumExp}, backend, attrs: {shape: expandedShape}}); const res = realDiv({inputs: {a: b, b: sumExpReshaped}, backend}) as TensorInfo; backend.disposeIntermediateTens...
{ const {inputs, backend, attrs} = args; const {logits} = inputs; const {dim} = attrs; const axes = util.parseAxisParam([dim], logits.shape); const maxLogit = max({ inputs: {x: logits}, backend, attrs: {reductionIndices: axes, keepDims: false} }); const expandedShape = backend_util.expandSh...
identifier_body
Softmax.ts
/** * @license * 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 a...
(args: { inputs: SoftmaxInputs, backend: MathBackendWebGL, attrs: SoftmaxAttrs }): TensorInfo { const {inputs, backend, attrs} = args; const {logits} = inputs; const {dim} = attrs; const axes = util.parseAxisParam([dim], logits.shape); const maxLogit = max({ inputs: {x: logits}, backend, a...
softmax
identifier_name
cmd.rs
(42); /// ``` /// /// Because currently rust's currently does not have an ideal system /// for lifetimes of temporaries, sometimes you need to hold on to /// the initially generated command: /// /// ```rust,no_run /// # let client = redis::Client::open("redis://127.0.0.1/").unwrap(); /// # let con = client.get_connecti...
{ { let cmd = self.get_last_command(); cmd.arg(arg); } self }
identifier_body
cmd.rs
{ rv.extend(cmd.get_packed_command().into_iter()); } if atomic { rv.extend(cmd("EXEC").get_packed_command().into_iter()); } rv } /// A command acts as a builder interface to creating encoded redis /// requests. This allows you to easiy assemble a packed command /// by chaining argumen...
(&mut self, cmd: &Cmd) -> &mut Pipeline { self.commands.push(cmd.clone()); self } #[inline] fn get_last_command
add_command
identifier_name
cmd.rs
{ None } else { Some(encode_command(&self.args, cursor)) } } /// Returns true if the command is in scan mode. #[inline] pub fn in_scan_mode(&self) -> bool { self.cursor.is_some() } /// Sends the command as query to the connection and converts th...
/// .cmd("SET").arg("key_1").arg(42).ignore() /// .cmd("SET").arg("key_2").arg(43).ignore()
random_line_split
FilterSuggestionBuilder.js
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditio...
{ var start = input.selectionStart; var end = input.selectionEnd; var text = input.value; if (start !== end && end === text.length) input.value = text.substring(0, start); }, /** * @param {string} key * @return {!Array.<string>} */ _values: fun...
/** * @param {!HTMLInputElement} input */ unapplySuggestion: function(input)
random_line_split
FilterSuggestionBuilder.js
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditio...
return suggestions; }, /** * @param {!HTMLInputElement} input * @param {string} suggestion * @param {boolean} isIntermediate */ applySuggestion: function(input, suggestion, isIntermediate) { var text = input.value; var start = input.selectionStart; ...
{ var key = prefix.substring(0, valueDelimiterIndex); var value = prefix.substring(valueDelimiterIndex + 1); var items = this._values(key); for (var i = 0; i < items.length; ++i) { if (items[i].startsWith(value) && (items[i] !== value)) ...
conditional_block
palettesort.rs
use ::color::Color; /// Sort neighboring colors in the image to be neighbors in the palette as well. /// /// Fairly silly and useless, but makes the palette (especially of ordered dithered images) /// look a lot more tidy. pub fn sort_palette(palette: &Vec<Color>, image: &Vec<u8>) -> (Vec<Color>, Vec<u8>) { let nu...
let mut available: Vec<usize> = (0..num_colors).filter(|&i| i != best_index).collect(); let mut prev_index = best_index; while available.len() > 0 { let mut best_index = available[0]; let mut best_count = 0; for &index in &available { let count = neighbors[prev_index][ind...
mapping.push(best_index);
random_line_split
palettesort.rs
use ::color::Color; /// Sort neighboring colors in the image to be neighbors in the palette as well. /// /// Fairly silly and useless, but makes the palette (especially of ordered dithered images) /// look a lot more tidy. pub fn sort_palette(palette: &Vec<Color>, image: &Vec<u8>) -> (Vec<Color>, Vec<u8>) { let nu...
} mapping.push(best_index); let mut available: Vec<usize> = (0..num_colors).filter(|&i| i != best_index).collect(); let mut prev_index = best_index; while available.len() > 0 { let mut best_index = available[0]; let mut best_count = 0; for &index in &available { ...
{ best_index = index; best_count = count; }
conditional_block
palettesort.rs
use ::color::Color; /// Sort neighboring colors in the image to be neighbors in the palette as well. /// /// Fairly silly and useless, but makes the palette (especially of ordered dithered images) /// look a lot more tidy. pub fn sort_palette(palette: &Vec<Color>, image: &Vec<u8>) -> (Vec<Color>, Vec<u8>)
} } mapping.push(best_index); let mut available: Vec<usize> = (0..num_colors).filter(|&i| i != best_index).collect(); let mut prev_index = best_index; while available.len() > 0 { let mut best_index = available[0]; let mut best_count = 0; for &index in &available { ...
{ let num_colors = palette.len(); let mut counts: Vec<usize> = (0..num_colors).map(|_| 0).collect(); let mut neighbors: Vec<Vec<usize>> = (0..num_colors).map(|_| (0..num_colors).map(|_| 0).collect()).collect(); let mut last_index = 0; for &index in image { let index = index as usize;...
identifier_body
palettesort.rs
use ::color::Color; /// Sort neighboring colors in the image to be neighbors in the palette as well. /// /// Fairly silly and useless, but makes the palette (especially of ordered dithered images) /// look a lot more tidy. pub fn
(palette: &Vec<Color>, image: &Vec<u8>) -> (Vec<Color>, Vec<u8>) { let num_colors = palette.len(); let mut counts: Vec<usize> = (0..num_colors).map(|_| 0).collect(); let mut neighbors: Vec<Vec<usize>> = (0..num_colors).map(|_| (0..num_colors).map(|_| 0).collect()).collect(); let mut last_index =...
sort_palette
identifier_name
shape_intrinsic_tag_then_rec.rs
// xfail-fast // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <...
struct X { sp: Span, path: path } pub fn main() { let sp: Span = Span {lo: 57451u, hi: 57542u, expanded_from: os_none}; let t: @ty = @Spanned { data: 3u, span: sp }; let p_: Path_ = Path_ { global: true, idents: ~[~"hi"], types: ~[t] }; let p: path = Spanned { data: p_, span: sp }; let x = X { sp:...
type path = Spanned<Path_>; type ty = Spanned<ty_>;
random_line_split
shape_intrinsic_tag_then_rec.rs
// xfail-fast // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <...
{ sp: Span, path: path } pub fn main() { let sp: Span = Span {lo: 57451u, hi: 57542u, expanded_from: os_none}; let t: @ty = @Spanned { data: 3u, span: sp }; let p_: Path_ = Path_ { global: true, idents: ~[~"hi"], types: ~[t] }; let p: path = Spanned { data: p_, span: sp }; let x = X { sp: sp, path...
X
identifier_name
pipeline.py
# Copyright (C) 2008-2015 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman 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 you...
class IPipeline(Interface): """A pipeline of handlers.""" name = Attribute('Pipeline name; must be unique.') description = Attribute('A brief description of this pipeline.') def __iter__(): """Iterate over all the handlers in this pipeline."""
from zope.interface import Interface, Attribute
random_line_split
pipeline.py
# Copyright (C) 2008-2015 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman 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 you...
"""Iterate over all the handlers in this pipeline."""
identifier_body
pipeline.py
# Copyright (C) 2008-2015 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman 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 you...
(Interface): """A pipeline of handlers.""" name = Attribute('Pipeline name; must be unique.') description = Attribute('A brief description of this pipeline.') def __iter__(): """Iterate over all the handlers in this pipeline."""
IPipeline
identifier_name
plugin.py
# Copyright (c) 2015, MapR Technologies # # 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...
def get_node_processes(self, hadoop_version): return self._get_handler(hadoop_version).get_node_processes() def get_configs(self, hadoop_version): return self._get_handler(hadoop_version).get_configs() def configure_cluster(self, cluster): self._get_handler(cluster.hadoop_version...
return vhf.VersionHandlerFactory.get().get_versions()
identifier_body
plugin.py
# Copyright (c) 2015, MapR Technologies # # 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...
def get_versions(self): return vhf.VersionHandlerFactory.get().get_versions() def get_node_processes(self, hadoop_version): return self._get_handler(hadoop_version).get_node_processes() def get_configs(self, hadoop_version): return self._get_handler(hadoop_version).get_configs() ...
return MapRPlugin.description
random_line_split
plugin.py
# Copyright (c) 2015, MapR Technologies # # 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...
(self, hadoop_version): return self._get_handler(hadoop_version).get_node_processes() def get_configs(self, hadoop_version): return self._get_handler(hadoop_version).get_configs() def configure_cluster(self, cluster): self._get_handler(cluster.hadoop_version).configure_cluster(cluster)...
get_node_processes
identifier_name
yacc.py
"""SCons.Tool.yacc Tool-specific initialization for yacc. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission is hereby granted, free of charge, ...
(target, source, env): return _yaccEmitter(target, source, env, ['.yy'], '$YACCHXXFILESUFFIX') def generate(env): """Add Builders and construction variables for yacc to an Environment.""" c_file, cxx_file = SCons.Tool.createCFileBuilders(env) # C c_file.add_action('.y', YaccAction) c_file.add_...
yyEmitter
identifier_name
yacc.py
"""SCons.Tool.yacc Tool-specific initialization for yacc. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission is hereby granted, free of charge, ...
# If -d is specified on the command line, yacc will emit a .h # or .hpp file with the same name as the .c or .cpp output file. if '-d' in flags: target.append(targetBase + env.subst(hsuf, target=target, source=source)) # If -g is specified on the command line, yacc will emit a .vcg # fil...
target = [targetBase + ".m"] # the extension is ".m".
conditional_block
yacc.py
"""SCons.Tool.yacc Tool-specific initialization for yacc. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission is hereby granted, free of charge, ...
def generate(env): """Add Builders and construction variables for yacc to an Environment.""" c_file, cxx_file = SCons.Tool.createCFileBuilders(env) # C c_file.add_action('.y', YaccAction) c_file.add_emitter('.y', yEmitter) c_file.add_action('.yacc', YaccAction) c_file.add_emitter('.yacc'...
return _yaccEmitter(target, source, env, ['.yy'], '$YACCHXXFILESUFFIX')
identifier_body
yacc.py
"""SCons.Tool.yacc Tool-specific initialization for yacc. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission is hereby granted, free of charge, ...
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/...
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
random_line_split