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
favoritos.component.ts
import { Component, AfterViewInit } from "@angular/core"; import { Favorite } from "../favorite"; import { FavoriteService } from "../favorite.service"; import "rxjs/add/operator/map"; @Component({ selector: "app-favoritos", templateUrl: "./favoritos.component.html", styleUrls: ["./favoritos.component.scss...
serie.isFavorito = !!y; }); this.series.push(serie); }); let chunk = 3; let temparray = []; for (let i = 0; i < this.series.length; i += chunk) { temparray = this.series.slice(i, i + chunk); ...
{ this.favoriteService.PesquisarFavoritos().subscribe(data => { this.series = []; this.seriesView = [null]; if (!data || Object.prototype.toString.call(data) !== "[object Array]") { return; } data.forEach(x => { let se...
identifier_body
favoritos.component.ts
import { Component, AfterViewInit } from "@angular/core"; import { Favorite } from "../favorite"; import { FavoriteService } from "../favorite.service"; import "rxjs/add/operator/map"; @Component({ selector: "app-favoritos", templateUrl: "./favoritos.component.html", styleUrls: ["./favoritos.component.scss...
constructor(private favoriteService: FavoriteService) { } ngAfterViewInit() { this.pesquisarFavoritos(); } pesquisarFavoritos(): void { this.favoriteService.PesquisarFavoritos().subscribe(data => { this.series = []; this.seriesView = [null]; if (!da...
series: Favorite[] = []; seriesView: [Favorite[]];
random_line_split
Database.js
/* * This file is part of the easy framework. * * (c) Julien Sergent <sergent.julien@icloud.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ const ConfigLoader = require( 'easy/core/ConfigLoader' ) const EventsEmitter = require( 'eve...
/** * init - init attributes */ init() { this._instance = null this._connector = this._config.connector this.resetProperties() } /** * Reset instance and connected state * * @memberOf Database */ resetProperties() { this._connected = f...
{ this._config = config this.stateEmitter = new EventsEmitter() this.name = config.config.name this.init() }
identifier_body
Database.js
/* * This file is part of the easy framework. * * (c) Julien Sergent <sergent.julien@icloud.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ const ConfigLoader = require( 'easy/core/ConfigLoader' ) const EventsEmitter = require( 'eve...
() { this._instance = null this._connector = this._config.connector this.resetProperties() } /** * Reset instance and connected state * * @memberOf Database */ resetProperties() { this._connected = false this._connectionError = null } /**...
init
identifier_name
Database.js
/* * This file is part of the easy framework. * * (c) Julien Sergent <sergent.julien@icloud.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ const ConfigLoader = require( 'easy/core/ConfigLoader' ) const EventsEmitter = require( 'eve...
} /** * Set connection error * * @returns {Database} * * @memberOf Database */ set connectionError( error ) { this._connectionError = error return this } } module.exports = Database
* @memberOf Database */ get connectionError() { return this._connectionError
random_line_split
Database.js
/* * This file is part of the easy framework. * * (c) Julien Sergent <sergent.julien@icloud.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ const ConfigLoader = require( 'easy/core/ConfigLoader' ) const EventsEmitter = require( 'eve...
if ( error ) { throw new Error( error ) } } /** * Reset database connection and instance * * @memberOf Database */ disconnect() { const oldConnected = this.connected this.resetProperties() if ( this.connected !== oldConnected ) { ...
{ this.stateEmitter.emit( 'change', this.connected ) }
conditional_block
stubs.py
import logging import os import time from urllib2 import HTTPError, URLError from djangoappengine.boot import PROJECT_DIR from djangoappengine.utils import appid, have_appserver REMOTE_API_SCRIPTS = ( '$PYTHON_LIB/google/appengine/ext/remote_api/handler.py', 'google.appengine.ext.remote_api.handler.applicati...
(self, connection, datastore_path=None): if self.active_stubs == 'test': self.deactivate_test_stubs() self.activate_test_stubs(connection, datastore_path) elif self.active_stubs == 'local': self.setup_local_stubs(connection) elif self.active_stubs == 'remote...
reset_stubs
identifier_name
stubs.py
import logging import os import time from urllib2 import HTTPError, URLError from djangoappengine.boot import PROJECT_DIR from djangoappengine.utils import appid, have_appserver REMOTE_API_SCRIPTS = ( '$PYTHON_LIB/google/appengine/ext/remote_api/handler.py', 'google.appengine.ext.remote_api.handler.applicati...
def setup_stubs(self, connection): if self.active_stubs is not None: return if not have_appserver: self.activate_stubs(connection) def activate_stubs(self, connection): try: from google.appengine.tools import dev_appserver_main self.setu...
self.testbed = None self.active_stubs = None self.pre_test_stubs = None
identifier_body
stubs.py
import logging import os import time from urllib2 import HTTPError, URLError from djangoappengine.boot import PROJECT_DIR from djangoappengine.utils import appid, have_appserver REMOTE_API_SCRIPTS = ( '$PYTHON_LIB/google/appengine/ext/remote_api/handler.py', 'google.appengine.ext.remote_api.handler.applicati...
if not have_appserver: self.activate_stubs(connection) def activate_stubs(self, connection): try: from google.appengine.tools import dev_appserver_main self.setup_local_stubs(connection) except ImportError: self.activate_test_stubs(connection)...
def setup_stubs(self, connection): if self.active_stubs is not None: return
random_line_split
stubs.py
import logging import os import time from urllib2 import HTTPError, URLError from djangoappengine.boot import PROJECT_DIR from djangoappengine.utils import appid, have_appserver REMOTE_API_SCRIPTS = ( '$PYTHON_LIB/google/appengine/ext/remote_api/handler.py', 'google.appengine.ext.remote_api.handler.applicati...
else: try: remote_api_stub.MaybeInvokeAuthentication() except HTTPError, e: raise URLError("%s\n" "Couldn't reach remote_api handler at %s.\n" "Make sure you've deployed your project and " ...
try: remote_api_stub.MaybeInvokeAuthentication() except HTTPError, e: if not have_appserver: logging.info("Retrying in %d seconds..." % retry_delay) time.sleep(retry_delay) retry_delay *= 2 else: ...
conditional_block
home.component.ts
import { Component, ChangeDetectorRef } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import { Router } from '@angular/router'; import { Observable, Subject } from 'rxjs/Rx'; import { Ruleset } from '../shared'; declare var SHACLValidator: any; @Component({ selector: 'home', temp...
} private formatErrors(error: any) { return Observable.throw(error.json()); } }
{ console.error('Invalid source data: ', this.sourceData); this.isValidating = false; this.isValidationSuccess = false; }
conditional_block
home.component.ts
import { Component, ChangeDetectorRef } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import { Router } from '@angular/router'; import { Observable, Subject } from 'rxjs/Rx'; import { Ruleset } from '../shared'; declare var SHACLValidator: any; @Component({ selector: 'home', temp...
(e, report) { this.reportConforms = report.conforms(); console.info("Conforms: " + this.reportConforms); if (this.reportConforms === false) { var R = []; report.results().forEach(function (result) { R.push({ severity: result.severity(), focusNode: result.focusNode(...
handleValidationResult
identifier_name
home.component.ts
import { Component, ChangeDetectorRef } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import { Router } from '@angular/router'; import { Observable, Subject } from 'rxjs/Rx'; import { Ruleset } from '../shared'; declare var SHACLValidator: any; @Component({ selector: 'home', temp...
validateRuleset(data: string, rules: string) { console.info('Validating data:'); console.info(data); console.info('Validating SHACL:'); console.info(rules); // The reference to 'this' is lost when invoking the JS validate function. var t = this; this.validator.validate(data, "text/turtl...
.map(res => useProxy ? res.json() : res); }
random_line_split
gateway_scanner.py
""" GatewayScanner is an abstraction for searching for KNX/IP devices on the local network. * It walks through all network interfaces * and sends UDP multicast search requests * it returns the first found device """ from __future__ import annotations import asyncio from functools import partial import logging from ty...
def __repr__(self) -> str: """Return object as representation string.""" return ( "GatewayDescriptor(\n" f" name={self.name},\n" f" ip_addr={self.ip_addr},\n" f" port={self.port},\n" f" local_interface={self.local_interface},\n...
random_line_split
gateway_scanner.py
""" GatewayScanner is an abstraction for searching for KNX/IP devices on the local network. * It walks through all network interfaces * and sends UDP multicast search requests * it returns the first found device """ from __future__ import annotations import asyncio from functools import partial import logging from ty...
logger = logging.getLogger("xknx.log") class GatewayDescriptor: """Used to return information about the discovered gateways.""" def __init__( self, ip_addr: str, port: int, local_ip: str = "", local_interface: str = "", name: str = "UNKNOWN", supports...
from xknx.xknx import XKNX
conditional_block
gateway_scanner.py
""" GatewayScanner is an abstraction for searching for KNX/IP devices on the local network. * It walks through all network interfaces * and sends UDP multicast search requests * it returns the first found device """ from __future__ import annotations import asyncio from functools import partial import logging from ty...
) search_request = SearchRequest(self.xknx, discovery_endpoint=discovery_endpoint) udp_transport.send(KNXIPFrame.init_from_body(search_request)) def _response_rec_callback( self, knx_ip_frame: KNXIPFrame, source: HPAI, udp_transport: UDPTransport, i...
"""Send a search request on a specific interface.""" logger.debug("Searching on %s / %s", interface, ip_addr) udp_transport = UDPTransport( self.xknx, (ip_addr, 0), (self.xknx.multicast_group, self.xknx.multicast_port), multicast=True, ) ...
identifier_body
gateway_scanner.py
""" GatewayScanner is an abstraction for searching for KNX/IP devices on the local network. * It walks through all network interfaces * and sends UDP multicast search requests * it returns the first found device """ from __future__ import annotations import asyncio from functools import partial import logging from ty...
(self, interface: str, ip_addr: str) -> None: """Send a search request on a specific interface.""" logger.debug("Searching on %s / %s", interface, ip_addr) udp_transport = UDPTransport( self.xknx, (ip_addr, 0), (self.xknx.multicast_group, self.xknx.multicast_...
_search_interface
identifier_name
OWMAPlot.py
, because it calls qApp.processEvents # which can result in 'event queue climbing' and max. recursion error if GUI thread # gets another advance signal before it finishes with this one if not self._delay: try: self._delay = True self.redirect.progressB...
callback=self.onMergeMethodChange, addSpace=True) box = gui.doubleSpin(self.controlArea, self, "zCutoff", 0.0, 3.0, 0.01, box="Z-Score Cutoff", callback=[self.replotMA, self.commitIf]) gui.separator(sel...
super().__init__(parent) # GUI box = gui.widgetBox(self.controlArea, "Info", addSpace=True) self.infoBox = gui.widgetLabel(box, "No data on input.") box = gui.widgetBox(self.controlArea, "Split by", addSpace=True) self.groupCombo = gui.comboBox( box, self, "selected...
identifier_body
OWMAPlot.py
because it calls qApp.processEvents # which can result in 'event queue climbing' and max. recursion error if GUI thread # gets another advance signal before it finishes with this one if not self._delay: try: self._delay = True self.redirect.progressBa...
(*args, **kwargs): try: return func(*args, **kwargs) except BaseException as ex: sys.excepthook(*sys.exc_info()) raise return wrapped class OWMAPlot(widget.OWWidget): name = "MA Plot" description = "Normalize expression array data on a MA - plot" ic...
wrapped
identifier_name
OWMAPlot.py
because it calls qApp.processEvents # which can result in 'event queue climbing' and max. recursion error if GUI thread # gets another advance signal before it finishes with this one if not self._delay: try: self._delay = True self.redirect.progressBa...
return ret col_labels = filterSingleValues(col_labels) row_labels = filterSingleValues(row_labels) return col_labels + row_labels def setData(self, data): self.closeContext() self.clear() self.unconditional_commit() self.data = data sel...
match = [(n, v, a) for n, v, a in labels if n == name] if len(match) > 1: ret.append((name, value, axis))
conditional_block
OWMAPlot.py
) # GUI box = gui.widgetBox(self.controlArea, "Info", addSpace=True) self.infoBox = gui.widgetLabel(box, "No data on input.") box = gui.widgetBox(self.controlArea, "Split by", addSpace=True) self.groupCombo = gui.comboBox( box, self, "selectedGroup", callback=self.o...
random_line_split
CCConfig.js
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ /** * <p> * The current version of Cocos2d-html5 being used.<br/> * Please DO NOT remove this String, it is an important flag for bug tracki...
* <p> * By default, cc.TextureAtlas (used by many cocos2d classes) will use VAO (Vertex Array Objects).<br/> * Apple recommends its usage but they might consume a lot of memory, specially if you use many of them.<br/> * So for certain cases, where you might need hundreds of VAO objects, it might be a go...
* @type Number */ cc.TEXTURE_ATLAS_USE_TRIANGLE_STRIP = 0; /**
random_line_split
mod_sesamstrasse.py
import datetime, re from mod_helper import * debug = True def sesamstrasseShow(): mediaList = ObjectContainer(no_cache=True) if debug == True: Log("Running sesamstrasseShow()...") try: urlMain = "http://www.sesamstrasse.de" content = getURL(urlMain+"/home/homepage1077.html") spl = content.split('<div class=...
item = { 'title':title, 'url':url, 'thumb':thumb, 'duration':int(duration)*60000 } if debug == True: Log("Adding: " + title) vo = sesamstrasseCreateVideoObject(item) mediaList.add(vo) return mediaList except Exception as e: if debug == True: Log("ERROR: " + str(e)) def sesamstrass...
date = date[:date.rfind('.')].strip() duration = match[0][1] title = date+" - "+title
random_line_split
mod_sesamstrasse.py
import datetime, re from mod_helper import * debug = True def sesamstrasseShow(): mediaList = ObjectContainer(no_cache=True) if debug == True: Log("Running sesamstrasseShow()...") try: urlMain = "http://www.sesamstrasse.de" content = getURL(urlMain+"/home/homepage1077.html") spl = content.split('<div class=...
(item, container = False): if debug == True: Log("Running sesamstrasseCreateVideoObject()...") if debug == True: Log("Creating VideoObject: " + str(item)) try: vo = VideoClipObject( key = Callback(sesamstrasseCreateVideoObject, item = item, container = True), title = item['title'], thumb = item['thumb'],...
sesamstrasseCreateVideoObject
identifier_name
mod_sesamstrasse.py
import datetime, re from mod_helper import * debug = True def sesamstrasseShow(): mediaList = ObjectContainer(no_cache=True) if debug == True: Log("Running sesamstrasseShow()...") try: urlMain = "http://www.sesamstrasse.de" content = getURL(urlMain+"/home/homepage1077.html") spl = content.split('<div class=...
else: suffix_id = '3000' content = getURL(url) json_uuid = re.findall('player_image-(.+?)_', content)[0] json_url = 'http://www.sesamstrasse.de/sendungsinfos/sesamstrasse%s-ppjson_image-%s.json' % (suffix_id, json_uuid) json = getURL(json_url) regex_qualities = '\.,(.+?),\.' qualities = re.findall(regex_...
regex_suffix_id = ',sesamstrasse(.+?).html' try: suffix_id = re.findall(regex_suffix_id, url)[0] except: suffix_id = '3000'
conditional_block
mod_sesamstrasse.py
import datetime, re from mod_helper import * debug = True def sesamstrasseShow(): mediaList = ObjectContainer(no_cache=True) if debug == True: Log("Running sesamstrasseShow()...") try: urlMain = "http://www.sesamstrasse.de" content = getURL(urlMain+"/home/homepage1077.html") spl = content.split('<div class=...
return ObjectContainer(objects = [vo]) else: return vo except Exception as e: if debug == True: Log("ERROR: " + str(e)) def sesamstrasseGetStreamingUrl(url): if debug == True: Log("Running sesamstrasseGetStreamingUrl()...") try: quality = 'hd' if ',sesamstrasse' in url: regex_suffix_id = ',sesams...
if debug == True: Log("Running sesamstrasseCreateVideoObject()...") if debug == True: Log("Creating VideoObject: " + str(item)) try: vo = VideoClipObject( key = Callback(sesamstrasseCreateVideoObject, item = item, container = True), title = item['title'], thumb = item['thumb'], duration = item['duratio...
identifier_body
timeout.js
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b)...
* * If provided argument was Date, returned Observable behaves differently. It throws * if Observable did not complete before provided Date. This means that periods between * emission of particular values do not matter in this case. If Observable did not complete * before provided Date, source Observable will be u...
* stream will end with an error and source Observable will be unsubscribed. * These checks are performed throughout whole lifecycle of Observable - from the moment * it was subscribed to, until it completes or errors itself. Thus every value must be * emitted within specified period since previous value.
random_line_split
timeout.js
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b)...
(due, scheduler) { if (scheduler === void 0) { scheduler = async_1.async; } var absoluteTimeout = isDate_1.isDate(due); var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due); return function (source) { return source.lift(new TimeoutOperator(waitFor, absoluteTimeout, scheduler, new Tim...
timeout
identifier_name
timeout.js
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b)...
TimeoutSubscriber.dispatchTimeout = function (subscriber) { subscriber.error(subscriber.errorInstance); }; TimeoutSubscriber.prototype.scheduleTimeout = function () { var action = this.action; if (action) { // Recycle the action if we've already scheduled one. All the pr...
{ var _this = _super.call(this, destination) || this; _this.absoluteTimeout = absoluteTimeout; _this.waitFor = waitFor; _this.scheduler = scheduler; _this.errorInstance = errorInstance; _this.action = null; _this.scheduleTimeout(); return _this; }
identifier_body
demo.py
from pyh import * list=[[1,'Lucy',25],[2,'Tom',30],[3,'Lily',20]] page = PyH('Test')
page<<div(style="text-align:center")<<h4('Test table') mytab = page << table(border="1",cellpadding="3",cellspacing="0",style="margin:auto") tr1 = mytab << tr(bgcolor="lightgrey") tr1 << th('id') + th('name')+th('age') for i in range(len(list)): tr2 = mytab << tr() for j in range(3): tr2 << td(list[i][j...
random_line_split
demo.py
from pyh import * list=[[1,'Lucy',25],[2,'Tom',30],[3,'Lily',20]] page = PyH('Test') page<<div(style="text-align:center")<<h4('Test table') mytab = page << table(border="1",cellpadding="3",cellspacing="0",style="margin:auto") tr1 = mytab << tr(bgcolor="lightgrey") tr1 << th('id') + th('name')+th('age') for i in range(l...
page.printOut('/Users/miraclewong/github/PythonBasic/PyH/demo.html')
tr2 << td(list[i][j]) if list[i][j]=='Tom': tr2.attributes['bgcolor']='yellow' if list[i][j]=='Lily': tr2[1].attributes['style']='color:red'
conditional_block
tap.py
# -*- test-case-name: twisted.names.test.test_tap -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Domain Name Server """ import os, traceback from twisted.python import usage from twisted.names import dns from twisted.application import internet, service from twisted.names import ser...
(config): ca, cl = _buildResolvers(config) f = server.DNSServerFactory(config.zones, ca, cl, config['verbose']) p = dns.DNSDatagramProtocol(f) f.noisy = 0 ret = service.MultiService() for (klass, arg) in [(internet.TCPServer, f), (internet.UDPServer, p)]: s = klass(config['port'], arg, ...
makeService
identifier_name
tap.py
# -*- test-case-name: twisted.names.test.test_tap -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Domain Name Server """ import os, traceback from twisted.python import usage from twisted.names import dns from twisted.application import internet, service from twisted.names import ser...
return ret
svc.setServiceParent(ret)
conditional_block
tap.py
# -*- test-case-name: twisted.names.test.test_tap -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Domain Name Server """ import os, traceback from twisted.python import usage from twisted.names import dns from twisted.application import internet, service from twisted.names import ser...
def postOptions(self): if self['resolv-conf']: self['recursive'] = True self.svcs = [] self.zones = [] for f in self.zonefiles: try: self.zones.append(authority.PySourceAuthority(f)) except Exception: traceback.p...
"""Increment verbosity level""" self['verbose'] += 1
identifier_body
tap.py
# -*- test-case-name: twisted.names.test.test_tap -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Domain Name Server """ import os, traceback from twisted.python import usage from twisted.names import dns from twisted.application import internet, service from twisted.names import ser...
def opt_bindzone(self, filename): """Specify the filename of a BIND9 syntax zone definition""" if not os.path.exists(filename): raise usage.UsageError(filename + ": No such file") self.bindfiles.append(filename) def opt_secondary(self, ip_domain): """Act as seconda...
"""Specify the filename of a Python syntax zone definition""" if not os.path.exists(filename): raise usage.UsageError(filename + ": No such file") self.zonefiles.append(filename)
random_line_split
register.rs
use super::super::{IrcMsg, numerics}; use super::super::message_types::server; pub type RegisterResult = Result<(), RegisterError>; #[derive(Clone, Debug)] pub struct RegisterError { pub errtype: RegisterErrorType, pub message: IrcMsg, } impl RegisterError { pub fn should_pick_new_nickname(&self) -> bool...
numerics::ERR_ERRONEUSNICKNAME => Some(RegisterErrorType::ErroneousNickname), numerics::ERR_NICKCOLLISION => Some(RegisterErrorType::NicknameCollision), numerics::ERR_RESTRICTED => Some(RegisterErrorType::Restricted), _ => None } } }
match result { numerics::ERR_NONICKNAMEGIVEN => Some(RegisterErrorType::NoNicknameGiven), numerics::ERR_NICKNAMEINUSE => Some(RegisterErrorType::NicknameInUse), numerics::ERR_UNAVAILRESOURCE => Some(RegisterErrorType::UnavailableResource),
random_line_split
register.rs
use super::super::{IrcMsg, numerics}; use super::super::message_types::server; pub type RegisterResult = Result<(), RegisterError>; #[derive(Clone, Debug)] pub struct RegisterError { pub errtype: RegisterErrorType, pub message: IrcMsg, } impl RegisterError { pub fn should_pick_new_nickname(&self) -> bool...
(result: i32) -> bool { RegisterErrorType::from_ord_known(result).is_some() } pub fn from_ord_known(result: i32) -> Option<RegisterErrorType> { match result { numerics::ERR_NONICKNAMEGIVEN => Some(RegisterErrorType::NoNicknameGiven), numerics::ERR_NICKNAMEINUSE => Some(R...
is_known_error
identifier_name
users.ts
/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
{ const [user, created] = await User.findOrCreate({ where: {email: email, group: USER_GROUP_YOUTUBE}, defaults: { name: name, group: USER_GROUP_YOUTUBE, isActive: true, }, }); if (!created) { if (!await user.isActive) { user.isActive = true; } } user.extra = {toke...
identifier_body
users.ts
/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
( user: User, data: Pick<UserSocialAuth, 'provider' | 'socialId'>, ): Promise<[UserSocialAuth, boolean]> { const socialAuthData = { ...data, userId: user.id, }; const [userSocialAuth, created] = await UserSocialAuth.findOrCreate({ where: { userId: socialAuthData.userId, provider: soci...
findOrCreateUserSocialAuth
identifier_name
users.ts
/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
const [user, created] = await User.findOrCreate({ where: {email: email}, defaults: { name: name, group: USER_GROUP_ADMIN, isActive: true, }, }); if (!created) { // We are repurposing an existing user. So ensure they have the correct properties if (!await user.isActive) { ...
{ return; }
conditional_block
users.ts
/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
export async function isFirstUserInitialised() { const count = await User.count({where: {group: USER_GROUP_ADMIN, isActive: true}}); return count > 0; } export async function ensureFirstUser({name, email}: {name: string, email: string}) { if (await isFirstUserInitialised()) { return; } const [user, cre...
}
random_line_split
kmeans.js
define(function (require, exports, module) { var distances = require("./distance"); function KMeans(centroids)
KMeans.prototype.randomCentroids = function(points, k) { var centroids = points.slice(0); // copy centroids.sort(function() { return (Math.round(Math.random()) - 0.5); }); return centroids.slice(0, k); } KMeans.prototype.classify = function(point, distance) { var min = Infinity, index = 0...
{ this.centroids = centroids || []; }
identifier_body
kmeans.js
define(function (require, exports, module) { var distances = require("./distance"); function KMeans(centroids) { this.centroids = centroids || []; } KMeans.prototype.randomCentroids = function(points, k) { var centroids = points.slice(0); // copy centroids.sort(function() { return (Math.round(Math.rand...
var centroid = this.centroids[j]; var newCentroid = new Array(centroid.length); for (var g = 0; g < centroid.length; g++) { var sum = 0; for (var i = 0; i < assigned.length; i++) { sum += assigned[i][g]; } newCentroid[g] = sum ...
{ continue; }
conditional_block
kmeans.js
define(function (require, exports, module) { var distances = require("./distance"); function KMeans(centroids) { this.centroids = centroids || []; } KMeans.prototype.randomCentroids = function(points, k) { var centroids = points.slice(0); // copy centroids.sort(function() { return (Math.round(Math.rand...
module.exports = KMeans; module.exports.kmeans = function(vectors, k) { return (new KMeans()).cluster(vectors, k); } });
random_line_split
kmeans.js
define(function (require, exports, module) { var distances = require("./distance"); function
(centroids) { this.centroids = centroids || []; } KMeans.prototype.randomCentroids = function(points, k) { var centroids = points.slice(0); // copy centroids.sort(function() { return (Math.round(Math.random()) - 0.5); }); return centroids.slice(0, k); } KMeans.prototype.classify = function(point,...
KMeans
identifier_name
enrollmentsNew.js
import Alert from '/imports/ui/alert'; import { Template } from 'meteor/templating'; import { ReactiveVar } from 'meteor/reactive-var'; import Surveys from '/imports/api/surveys/surveys'; import Survey from '/imports/ui/components/surveyForm/Survey'; import { DefaultAdminAccessRoles } from '/imports/config/permissions'...
});
random_line_split
enrollmentsNew.js
import Alert from '/imports/ui/alert'; import { Template } from 'meteor/templating'; import { ReactiveVar } from 'meteor/reactive-var'; import Surveys from '/imports/api/surveys/surveys'; import Survey from '/imports/ui/components/surveyForm/Survey'; import { DefaultAdminAccessRoles } from '/imports/config/permissions'...
.then(({ id, schema, message }) => { Alert.success(message); const query = schema ? { query: { schema } } : {}; Router.go('viewClient', { _id: id }, query); }) .catch(err => Alert.error(err)); } // Redirect to v2017 client version if not selected but exist: if (clie...
{ const { clientVersions } = client; const requiredClient = _.find(clientVersions, ({ schema }) => schema === requiredSchema); if (!requiredClient) { Meteor.callPromise('clients.create', client, requiredSchema, true) .then( ({ clientId, schema }) => ({ id: clientId, s...
conditional_block
enrollmentsNew.js
import Alert from '/imports/ui/alert'; import { Template } from 'meteor/templating'; import { ReactiveVar } from 'meteor/reactive-var'; import Surveys from '/imports/api/surveys/surveys'; import Survey from '/imports/ui/components/surveyForm/Survey'; import { DefaultAdminAccessRoles } from '/imports/config/permissions'...
() { return true; }, component() { return Survey; }, definition() { if (!Template.instance().surveyLoaded.get()) return {}; const survey = Surveys.findOne(this.surveyId); const definition = JSON.parse(survey.definition); return { ...definition, title: definition.title || surv...
isEnrollment
identifier_name
enrollmentsNew.js
import Alert from '/imports/ui/alert'; import { Template } from 'meteor/templating'; import { ReactiveVar } from 'meteor/reactive-var'; import Surveys from '/imports/api/surveys/surveys'; import Survey from '/imports/ui/components/surveyForm/Survey'; import { DefaultAdminAccessRoles } from '/imports/config/permissions'...
, enrollmentInfo() { return this.enrollmentInfo; }, isAdmin() { return Roles.userIsInRole(Meteor.userId(), DefaultAdminAccessRoles); }, });
{ return this.surveyId; }
identifier_body
equal.py
# Copyright 2019 The TensorFlow Authors. 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 applica...
(options): """Make a set of tests to do equal.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64, tf.string], "input_shape_pair": [([], []), ([1, 1, 1, 3], [1, 1, 1, 3]), ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]), ([5, 5...
make_equal_tests
identifier_name
equal.py
# Copyright 2019 The TensorFlow Authors. 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 applica...
input_value2 = tf.compat.v1.placeholder( dtype=parameters["input_dtype"], name="input2", shape=parameters["input_shape_pair"][1]) out = tf.equal(input_value1, input_value2) return [input_value1, input_value2], [out] def build_inputs(parameters, sess, inputs, outputs): input_va...
"""Make a set of tests to do equal.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64, tf.string], "input_shape_pair": [([], []), ([1, 1, 1, 3], [1, 1, 1, 3]), ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]), ([5, 5], [1]), ([10...
identifier_body
equal.py
# Copyright 2019 The TensorFlow Authors. 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 applica...
"fully_quantize": [True], }] def build_graph(parameters): """Build the equal op testing graph.""" input_value1 = tf.compat.v1.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape_pair"][0]) input_value2 = tf.compat.v1.placeholder( ...
"input_dtype": [tf.float32], "input_shape_pair": [([1, 1, 1, 3], [1, 1, 1, 3]), ([2, 3, 3], [2, 3])],
random_line_split
jquery.zenpen.url.js
* * Copyright (c) 2013 Deux Huit Huit (http://www.deuxhuithuit.com/) * Licensed under the MIT (http://deuxhuithuit.mit-license.org) * Based on the work of Tim Holman (https://github.com/tholman/zenpen) * Licensed under the Apache License (https://github.com/tholman/zenpen/blob/master/licence.md) */ (functio...
/* * jQuery ZenPen url/link action
random_line_split
jquery.zenpen.url.js
/* * jQuery ZenPen url/link action * * Copyright (c) 2013 Deux Huit Huit (http://www.deuxhuithuit.com/) * Licensed under the MIT (http://deuxhuithuit.mit-license.org) * Based on the work of Tim Holman (https://github.com/tholman/zenpen) * Licensed under the Apache License (https://github.com/tholman/zenpen/b...
} setTimeout(function () { popup.find('input.url-input').focus(); }, 50); } } }; })(jQuery);
{ var width = popup.width(); opts.addClass('url-mode'); var newWidth = /*popup.find('input.url-input').width()*/245 + btn.width(); popup.width(newWidth); // save options if (!!lastSelection && !lastSelection.isCollapsed) { this._options = { btn: btn, popup: p...
conditional_block
reflect.rs
[ 0, 0 ])); Store(bcx, len, GEPi(bcx, scratch.val, [ 0, 1 ])); scratch.val } pub fn c_size_and_align(&mut self, t: ty::t) -> Vec<ValueRef> { let tr = type_of(self.bcx.ccx(), t); let s = machine::llsize_of_real(self.bcx.ccx(), tr); let a = machine::llalign_of_min(self.bc...
ty::ty_str => self.visit("estr_uniq", &[]), _ => { let extra = self.c_mt(&ty::mt { ty: typ, mutbl: ast::MutImmutable, }); self.visit("uniq", extra.as_slice()) ...
{ let extra = Vec::new(); let extra = extra.append(self.c_mt(mt).as_slice()); self.visit("evec_uniq", extra.as_slice()) }
conditional_block
reflect.rs
pub fn c_bool(&mut self, b: bool) -> ValueRef { C_bool(self.bcx.ccx(), b) } pub fn c_slice(&mut self, s: InternedString) -> ValueRef { // We're careful to not use first class aggregates here because that // will kick us off fast isel. (Issue #4352.) let bcx = self.bcx; ...
{ C_uint(self.bcx.ccx(), u) }
identifier_body
reflect.rs
()); self.visit("evec_fixed", extra.as_slice()) } ty::ty_vec(..) | ty::ty_str => fail!("unexpected unsized type"), // Should remove mt from box and uniq. ty::ty_box(typ) => { let extra = self.c_mt(&ty::mt { ty: typ, ...
let modeval = 5u; // "by copy" let extra = vec!(self.c_uint(i),
random_line_split
reflect.rs
// Should rename to vec_*. ty::ty_vec(ref mt, Some(sz)) => { let extra = (vec!(self.c_uint(sz))).append(self.c_size_and_align(t).as_slice()); let extra = extra.append(self.c_mt(mt).as_slice()); self.visit("evec_fixed", extra.as_slice()) } ...
visit_sig
identifier_name
test_reload_button_provider.py
import pytest from cfme.containers.provider import ContainersProvider from utils import testgen, version from cfme.web_ui import toolbar as tb from utils.appliance.implementations.ui import navigate_to pytestmark = [ pytest.mark.uncollectif( lambda: version.current_version() < "5.6"), pytest.mark.use...
according to the @sha. Image Registries are also validated separately. """ navigate_to(provider, 'Details') tb.select('Reload Current Display') provider.validate_stats(ui=True) list_img_from_registry = provider.mgmt.list_image() list_img_from_registry_splitted = [i.id.split( '@...
Projects, Routes, Container Services, Replicators, Pods, Containers, and Nodes. Images are being validated separately, since the total number of images in CFME 5.7 includes all images from the OSE registry as well as the images that are being created from the running pods. The images are...
random_line_split
test_reload_button_provider.py
import pytest from cfme.containers.provider import ContainersProvider from utils import testgen, version from cfme.web_ui import toolbar as tb from utils.appliance.implementations.ui import navigate_to pytestmark = [ pytest.mark.uncollectif( lambda: version.current_version() < "5.6"), pytest.mark.use...
for d in list_img_from_openshift] list_img_from_openshift_parsed = [i[7:].split( '@sha256:')[-1] for i in list_img_from_openshift_splitted] list_img_from_registry_splitted_new = set(list_img_from_registry_splitted) list_img_from_openshift_parsed_new = set(list...
""" This test verifies the data integrity of the fields in the Relationships table after clicking the "reload" button. Fields that are being verified as part of provider.validate.stats(): Projects, Routes, Container Services, Replicators, Pods, Containers, and Nodes. Images are being val...
identifier_body
test_reload_button_provider.py
import pytest from cfme.containers.provider import ContainersProvider from utils import testgen, version from cfme.web_ui import toolbar as tb from utils.appliance.implementations.ui import navigate_to pytestmark = [ pytest.mark.uncollectif( lambda: version.current_version() < "5.6"), pytest.mark.use...
(provider): """ This test verifies the data integrity of the fields in the Relationships table after clicking the "reload" button. Fields that are being verified as part of provider.validate.stats(): Projects, Routes, Container Services, Replicators, Pods, Containers, and Nodes. Imag...
test_reload_button_provider
identifier_name
__init__.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (C) 2007-2018, Raffaele Salmaso <raffaele@salmaso.org> # Copyright (c) 2012 Omoto Kenji # Copyright (c) 2011 Sam Stephenson # Copyright (c) 2011 Josh Peek # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and a...
(name, runtime): '''Register a JavaScript runtime.''' _runtimes[name] = runtime def get(name=None): """ Return a appropriate JavaScript runtime. If name is specified, return the runtime. """ if name is None: return _auto_detect() try: runtime = runtimes()[name] exc...
register
identifier_name
__init__.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (C) 2007-2018, Raffaele Salmaso <raffaele@salmaso.org> # Copyright (c) 2012 Omoto Kenji # Copyright (c) 2011 Sam Stephenson # Copyright (c) 2011 Josh Peek # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and a...
runner_source=r"""(function(program, execJS) { execJS(program) })(function() { return eval(#{encoded_source}); }, function(program) { #{json2_source} var output, print = function(string) { string = string.replace(/[^\x00-\x7f]/g, function(ch){ return '\\u' + ('0000' + ch.charCodeAt(0).toString(16))....
encoding="ascii",
random_line_split
__init__.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (C) 2007-2018, Raffaele Salmaso <raffaele@salmaso.org> # Copyright (c) 2012 Omoto Kenji # Copyright (c) 2011 Sam Stephenson # Copyright (c) 2011 Josh Peek # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and a...
_runtimes['JavaScriptCore'] = Runtime( name="JavaScriptCore", command=["/System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc"], runner_source=r"""(function(program, execJS) { execJS(program) })(function() { return eval(#{encoded_source}); }, function(program) { var output; t...
break
conditional_block
__init__.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (C) 2007-2018, Raffaele Salmaso <raffaele@salmaso.org> # Copyright (c) 2012 Omoto Kenji # Copyright (c) 2011 Sam Stephenson # Copyright (c) 2011 Josh Peek # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and a...
def get(name=None): """ Return a appropriate JavaScript runtime. If name is specified, return the runtime. """ if name is None: return _auto_detect() try: runtime = runtimes()[name] except KeyError: raise RuntimeUnavailable("{name} runtime is not defined".format(n...
'''Register a JavaScript runtime.''' _runtimes[name] = runtime
identifier_body
counter.py
#!/usr/bin/env python # Copyright (c) 2010 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import time output = sys.argv[1] persistoutput = "%s.persist" % sys.argv[1] count = 0 try: count = open(persist...
sys.exit(0)
open(output, 'w').write('%d' % (count)) # Sleep so the next run changes the file time sufficiently to make the build # detect the file as changed. time.sleep(1)
conditional_block
counter.py
#!/usr/bin/env python # Copyright (c) 2010 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import time output = sys.argv[1] persistoutput = "%s.persist" % sys.argv[1] count = 0 try: count = open(persist...
# Save the count in a file that is undeclared, and thus hidden, to gyp. We need # to do this because, prior to running commands, some build systems deletes # any declared outputs, so we would lose our count if we just wrote to the # given output file. open(persistoutput, 'w').write('%d' % (count)) # Only write...
except: pass
random_line_split
unlockRetroSurveyForUser.js
import {GraphQLNonNull, GraphQLID} from 'graphql' import {unlockRetroSurveyForUser} from 'src/server/actions/retroSurveyLockUnlock' import userCan from 'src/common/util/userCan' import {Project} from 'src/server/services/dataService/models' import {LGNotAuthorizedError} from 'src/server/util/error' import {ProjectSumm...
await unlockRetroSurveyForUser(memberId, projectId) return { project: await Project.get(projectId) } } }
{ throw new LGNotAuthorizedError() }
conditional_block
unlockRetroSurveyForUser.js
import {GraphQLNonNull, GraphQLID} from 'graphql' import {unlockRetroSurveyForUser} from 'src/server/actions/retroSurveyLockUnlock' import userCan from 'src/common/util/userCan' import {Project} from 'src/server/services/dataService/models' import {LGNotAuthorizedError} from 'src/server/util/error' import {ProjectSumm...
}
{ if (!userCan(currentUser, 'lockAndUnlockSurveys')) { throw new LGNotAuthorizedError() } await unlockRetroSurveyForUser(memberId, projectId) return { project: await Project.get(projectId) } }
identifier_body
unlockRetroSurveyForUser.js
import {GraphQLNonNull, GraphQLID} from 'graphql' import {unlockRetroSurveyForUser} from 'src/server/actions/retroSurveyLockUnlock' import userCan from 'src/common/util/userCan' import {Project} from 'src/server/services/dataService/models' import {LGNotAuthorizedError} from 'src/server/util/error'
import {ProjectSummary} from 'src/server/graphql/schemas' export default { type: ProjectSummary, args: { memberId: { type: new GraphQLNonNull(GraphQLID), description: 'The memberId of the member whose survey should be unlocked', }, projectId: { type: new GraphQLNonNull(GraphQLID), ...
random_line_split
unlockRetroSurveyForUser.js
import {GraphQLNonNull, GraphQLID} from 'graphql' import {unlockRetroSurveyForUser} from 'src/server/actions/retroSurveyLockUnlock' import userCan from 'src/common/util/userCan' import {Project} from 'src/server/services/dataService/models' import {LGNotAuthorizedError} from 'src/server/util/error' import {ProjectSumm...
(source, {memberId, projectId}, {rootValue: {currentUser}}) { if (!userCan(currentUser, 'lockAndUnlockSurveys')) { throw new LGNotAuthorizedError() } await unlockRetroSurveyForUser(memberId, projectId) return { project: await Project.get(projectId) } } }
resolve
identifier_name
DistributedMintBattleAI.py
from toontown.toonbase import ToontownGlobals from toontown.coghq import DistributedLevelBattleAI from direct.directnotify import DirectNotifyGlobal from direct.fsm import State from direct.fsm import ClassicFSM, State from toontown.battle.BattleBase import * import CogDisguiseGlobals from toontown.toonbase.ToontownBat...
DistributedLevelBattleAI.DistributedLevelBattleAI.enterResume(self) if self.bossBattle and self.bossDefeated: self.battleMgr.level.b_setDefeated()
identifier_body
DistributedMintBattleAI.py
from toontown.toonbase import ToontownGlobals from toontown.coghq import DistributedLevelBattleAI from direct.directnotify import DirectNotifyGlobal from direct.fsm import State from direct.fsm import ClassicFSM, State from toontown.battle.BattleBase import * import CogDisguiseGlobals from toontown.toonbase.ToontownBat...
self.battleMgr.level.b_setDefeated()
conditional_block
DistributedMintBattleAI.py
from toontown.toonbase import ToontownGlobals from toontown.coghq import DistributedLevelBattleAI from direct.directnotify import DirectNotifyGlobal from direct.fsm import State from direct.fsm import ClassicFSM, State from toontown.battle.BattleBase import * import CogDisguiseGlobals from toontown.toonbase.ToontownBat...
(self, air, battleMgr, pos, suit, toonId, zoneId, level, battleCellId, roundCallback = None, finishCallback = None, maxSuits = 4): DistributedLevelBattleAI.DistributedLevelBattleAI.__init__(self, air, battleMgr, pos, suit, toonId, zoneId, level, battleCellId, 'MintReward', roundCallback, finishCallback, maxSuit...
__init__
identifier_name
DistributedMintBattleAI.py
from toontown.toonbase import ToontownGlobals from toontown.coghq import DistributedLevelBattleAI from direct.directnotify import DirectNotifyGlobal from direct.fsm import State from direct.fsm import ClassicFSM, State from toontown.battle.BattleBase import * import CogDisguiseGlobals from toontown.toonbase.ToontownBat...
self.resetResponses() self.assignRewards() self.bossDefeated = 1 self.level.setVictors(self.activeToons[:]) self.timer.startCallback(BUILDING_REWARD_TIMEOUT, self.serverRewardDone) return None def exitMintReward(self): return None def enterResume(self): ...
self.notify.debug('toon %d not helpful list, skipping merits' % toon.doId) def enterMintReward(self): self.joinableFsm.request('Unjoinable') self.runableFsm.request('Unrunable')
random_line_split
sv.js
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license
*/ CKEDITOR.plugins.setLang( 'toolbar', 'sv', { toolbarCollapse: 'Dölj verktygsfält', toolbarExpand: 'Visa verktygsfält', toolbarGroups: { document: 'Dokument', clipboard: 'Urklipp/ångra', editing: 'Redigering', forms: 'Formulär', basicstyles: 'Basstilar', paragraph: 'Paragraf', links: 'Länkar', inse...
random_line_split
Upload.d.ts
/// <reference types="react" /> import React from 'react'; import Dragger from './Dragger'; import { UploadProps } from './interface'; export interface UploadContext { antLocale?: { Upload?: any; }; } export { UploadProps }; export default class
extends React.Component<UploadProps, any> { static Dragger: typeof Dragger; static defaultProps: { prefixCls: string; type: string; multiple: boolean; action: string; data: {}; accept: string; beforeUpload: () => boolean; showUploadList: boolean; ...
Upload
identifier_name
Upload.d.ts
/// <reference types="react" /> import React from 'react'; import Dragger from './Dragger'; import { UploadProps } from './interface'; export interface UploadContext { antLocale?: { Upload?: any;
export { UploadProps }; export default class Upload extends React.Component<UploadProps, any> { static Dragger: typeof Dragger; static defaultProps: { prefixCls: string; type: string; multiple: boolean; action: string; data: {}; accept: string; beforeUploa...
}; }
random_line_split
operators.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2009-2010, Nicolas Clairon # 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 abov...
return False
if value == op and isinstance(value, type(op)): return True
conditional_block
operators.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2009-2010, Nicolas Clairon # 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 abov...
(self, *args): super(IS, self).__init__(*args) def __str__(self): representation = ' or %s ' % self.repr return '<is '+representation.join([repr(i) for i in self._operands]) + '>' def validate(self, value): if value in self._operands: for op in self._operands: ...
__init__
identifier_name
operators.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2009-2010, Nicolas Clairon # 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 abov...
class OR(SchemaOperator): repr = 'or' def __init__(self, *args): super(OR, self).__init__(*args) def __str__(self): repr = ' %s ' % self.repr return '<'+repr.join([i.__name__ for i in self._operands]) + '>' def validate(self, value): return isinstance(value, tuple(sel...
return type(self) == type(other) and self._operands == other._operands def validate(self, value): raise NotImplementedError
random_line_split
operators.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2009-2010, Nicolas Clairon # 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 abov...
class OR(SchemaOperator): repr = 'or' def __init__(self, *args): super(OR, self).__init__(*args) def __str__(self): repr = ' %s ' % self.repr return '<'+repr.join([i.__name__ for i in self._operands]) + '>' def validate(self, value): return isinstance(value, tuple(s...
repr = None def __init__(self, *args): assert self.repr is not None self._operands = list(args) def __repr__(self): return str(self) def __iter__(self): for operand in self._operands: yield operand def __eq__(self, other): return type(self) == type...
identifier_body
listener.rs
use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::RwLock; use apm::event::{CommandStarted, CommandResult}; use Client; use error::Result; pub type StartHook = fn(Client, &CommandStarted); pub type CompletionHook = fn(Client, &CommandResult); pub struct Listener { no_s...
pub fn new() -> Listener { Listener { no_start_hooks: AtomicBool::new(true), no_completion_hooks: AtomicBool::new(true), start_hooks: RwLock::new(Vec::new()), completion_hooks: RwLock::new(Vec::new()), } } pub fn add_start_hook(&self, hook: St...
start_hooks: RwLock<Vec<StartHook>>, completion_hooks: RwLock<Vec<CompletionHook>>, } impl Listener {
random_line_split
listener.rs
use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::RwLock; use apm::event::{CommandStarted, CommandResult}; use Client; use error::Result; pub type StartHook = fn(Client, &CommandStarted); pub type CompletionHook = fn(Client, &CommandResult); pub struct Listener { no_s...
let guard = self.start_hooks.read()?; for hook in guard.deref().iter() { hook(client.clone(), started); } Ok(()) } pub fn run_completion_hooks(&self, client: Client, result: &CommandResult) -> Result<()> { if self.no_completion_hooks.load(Ordering::SeqCst...
{ return Ok(()); }
conditional_block
listener.rs
use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::RwLock; use apm::event::{CommandStarted, CommandResult}; use Client; use error::Result; pub type StartHook = fn(Client, &CommandStarted); pub type CompletionHook = fn(Client, &CommandResult); pub struct Listener { no_s...
(&self, hook: CompletionHook) -> Result<()> { let mut guard = self.completion_hooks.write()?; self.no_completion_hooks.store(false, Ordering::SeqCst); Ok(guard.deref_mut().push(hook)) } pub fn run_start_hooks(&self, client: Client, started: &CommandStarted) -> Result<()> { if se...
add_completion_hook
identifier_name
lib.rs
//! The operational library makes it easy to implement monads with tricky control flow. //! //! This is very useful for: writing web applications in a sequential style, //! programming games with a uniform interface for human and AI players and easy replay, //! implementing fast parser monads, designing monadic DSLs, e...
/// The case `Pure(a)` means that the program contains no instructions and just returns the result `a`. Pure(Box<A>), /// The case `Then(instr, k)` means that the first instruction is `instr` and the remaining program is given by the kleisli arrow `k`. Then(Box<I>, Kleisli<'a, I, I::Return, A>) } impl<...
/// - `A` is the return type of the program. pub enum Program<'a, I: Instr, A> {
random_line_split
lib.rs
//! The operational library makes it easy to implement monads with tricky control flow. //! //! This is very useful for: writing web applications in a sequential style, //! programming games with a uniform interface for human and AI players and easy replay, //! implementing fast parser monads, designing monadic DSLs, e...
{ Program::Pure(Box::new(a)) }
identifier_body
lib.rs
//! The operational library makes it easy to implement monads with tricky control flow. //! //! This is very useful for: writing web applications in a sequential style, //! programming games with a uniform interface for human and AI players and easy replay, //! implementing fast parser monads, designing monadic DSLs, e...
<'a, I: 'a + Instr, A>(a: A) -> Program<'a, I, A> { Program::Pure(Box::new(a)) }
point
identifier_name
todo-section.js
const {ul, li, i, button} = require('dom-gen') const {on, component} = $.cc /** * TaskSection component. */
* @param {jQuery} elem */ constructor (elem) { this.tasks = elem.data('tasks') this.elem = elem } appendTaskList (elem) { return ul(this.tasks.map(task => li(this.icon(), ' ', task.title))).appendTo(elem) } } @component class DoneSection extends TaskSection { constructor (elem) { super...
class TaskSection { /**
random_line_split
todo-section.js
const {ul, li, i, button} = require('dom-gen') const {on, component} = $.cc /** * TaskSection component. */ class TaskSection { /** * @param {jQuery} elem */ constructor (elem) { this.tasks = elem.data('tasks') this.elem = elem } appendTaskList (elem) { return ul(this.tasks.map(task => li...
(elem) { button(i().addClass('fa fa-check-square-o'), ' ', 'Show dones').appendTo(elem) } @on('click').at('button') onButtonClick () { this.elem.find('ul').toggleClass('task-list-hidden') } icon () { return i().addClass('fa fa-check-square-o') } } @component class TodoSection extends TaskSec...
appendShowMoreBtn
identifier_name
todo-section.js
const {ul, li, i, button} = require('dom-gen') const {on, component} = $.cc /** * TaskSection component. */ class TaskSection { /** * @param {jQuery} elem */ constructor (elem) { this.tasks = elem.data('tasks') this.elem = elem } appendTaskList (elem) { return ul(this.tasks.map(task => li...
} appendShowMoreBtn (elem) { button(i().addClass('fa fa-check-square-o'), ' ', 'Show dones').appendTo(elem) } @on('click').at('button') onButtonClick () { this.elem.find('ul').toggleClass('task-list-hidden') } icon () { return i().addClass('fa fa-check-square-o') } } @component class To...
{ this.appendShowMoreBtn(elem) this.appendTaskList(elem).addClass('task-list task-list-hidden gray-out') }
conditional_block
todo-section.js
const {ul, li, i, button} = require('dom-gen') const {on, component} = $.cc /** * TaskSection component. */ class TaskSection { /** * @param {jQuery} elem */ constructor (elem) { this.tasks = elem.data('tasks') this.elem = elem } appendTaskList (elem)
} @component class DoneSection extends TaskSection { constructor (elem) { super(elem) if (this.tasks.length > 0) { this.appendShowMoreBtn(elem) this.appendTaskList(elem).addClass('task-list task-list-hidden gray-out') } } appendShowMoreBtn (elem) { button(i().addClass('fa fa-check-...
{ return ul(this.tasks.map(task => li(this.icon(), ' ', task.title))).appendTo(elem) }
identifier_body
compatibility.py
# -*- coding: utf-8 -*- import sys import django from django.utils import six try: from django.utils.text import truncate_words except ImportError: # django >=1.5 from django.utils.text import Truncator from django.utils.functional import allow_lazy def truncate_words(s, num, end_text='...'): ...
return path # copied from django-cms (for compatibility with Django 1.4) try: from django.utils.encoding import force_unicode def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. ...
return path.decode(fs_encoding)
conditional_block
compatibility.py
# -*- coding: utf-8 -*- import sys import django from django.utils import six try: from django.utils.text import truncate_words except ImportError: # django >=1.5 from django.utils.text import Truncator from django.utils.functional import allow_lazy def truncate_words(s, num, end_text='...'): ...
truncate_words = allow_lazy(truncate_words, six.text_type) DJANGO_1_4 = django.VERSION < (1, 5) DJANGO_1_5 = django.VERSION < (1, 6) DJANGO_1_6 = django.VERSION < (1, 7) DJANGO_1_7 = django.VERSION < (1, 8) DJANGO_1_8 = django.VERSION < (1, 9) if not six.PY3: fs_encoding = sys.getfilesystemencoding() or sys...
truncate = end_text and ' %s' % end_text or '' return Truncator(s).words(num, truncate=truncate)
identifier_body
compatibility.py
# -*- coding: utf-8 -*- import sys import django from django.utils import six try: from django.utils.text import truncate_words except ImportError: # django >=1.5 from django.utils.text import Truncator from django.utils.functional import allow_lazy def truncate_words(s, num, end_text='...'): ...
return '%s.%s' % (opts.app_label, opts.get_delete_permission())
random_line_split
compatibility.py
# -*- coding: utf-8 -*- import sys import django from django.utils import six try: from django.utils.text import truncate_words except ImportError: # django >=1.5 from django.utils.text import Truncator from django.utils.functional import allow_lazy def truncate_words(s, num, end_text='...'): ...
(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ klass.__unic...
python_2_unicode_compatible
identifier_name
enu.py
""" Copyright (C) 2017 Open Source Robotics Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to...
(self, e, n, u): self.e = e self.n = n self.u = u def __eq__(self, other): return self.e == other.e and self.n == other.n and self.u == other.u def __hash__(self): return hash((self.e, self.n, self.u)) def to_ecef(self, origin): # this doesn't work at the p...
__init__
identifier_name
enu.py
""" Copyright (C) 2017 Open Source Robotics Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to...
def __eq__(self, other): return self.e == other.e and self.n == other.n and self.u == other.u def __hash__(self): return hash((self.e, self.n, self.u)) def to_ecef(self, origin): # this doesn't work at the poles because longitude is not uniquely defined there sin_lon = or...
self.e = e self.n = n self.u = u
identifier_body
enu.py
""" Copyright (C) 2017 Open Source Robotics Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to...
def __hash__(self): return hash((self.e, self.n, self.u)) def to_ecef(self, origin): # this doesn't work at the poles because longitude is not uniquely defined there sin_lon = origin._sin_lon() sin_lat = origin._sin_lat() cos_lon = origin._cos_lon() cos_lat = ori...
random_line_split
paint_listener.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use LayerId; use LayerProperties; use layers::layers::{BufferRequest, LayerBufferSet}; use layers::platform::surfa...
/// Informs the compositor of the layers for the given pipeline. The compositor responds by /// creating and/or destroying paint layers as necessary. fn initialize_layers_for_pipeline(&mut self, pipeline_id: PipelineId, properties:...
fn native_display(&mut self) -> Option<NativeDisplay>;
random_line_split