file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
main.controller.js | import {Task} from '../components/tasks/tasks.service.js';
export class MainController {
constructor ($interval, $log, tasksService, speechService) {
'ngInject';
const vm = this,
currentTime = getPomodoroTime();
Object.assign(vm, {
// timer
timeLeft: formatTime(currentTime),
currentTime,
// tasks
tasks: tasksService.getTasks(),
newTask: Task(),
hasTasks(){ return this.tasks.length > 0; },
filterTerm: '',
// services
$interval,
$log,
tasksService,
speechService
});
// angular and getters don't seem to work
// very well together
vm.activeTask = this.tasks.find(t => t.isActive);
}
addNewTask(){
this.tasks.push(this.newTask);
if (this.tasks.length === 1) this.setTaskAsActive(this.newTask);
this.tasksService.saveTask(this.newTask);
this.newTask = Task();
}
removeTask(task){
const index = this.tasks.indexOf(task);
if (index !== -1){
if (task.isActive) this.setNextTaskAsActive(index);
this.tasks.splice(index,1);
this.tasksService.removeTask(task);
}
}
archiveTask(task){
const index = this.tasks.indexOf(task);
if (index !== -1){
let [taskToArchive] = this.tasks.splice(index,1);
this.tasksService.archiveTask(taskToArchive);
}
}
setNextTaskAsActive(index){
if (this.tasks.length > index + 1) this.setTaskAsActive(this.tasks[index+1]);
else if (index > 0) this.setTaskAsActive(this.tasks[index-1]);
}
setTaskAsActive(task){
const currentActiveTask = this.tasks.find(t => t.isActive);
if (currentActiveTask) currentActiveTask.isActive = false;
task.isActive = true;
this.activeTask = task;
}
startPomodoro(){
if (this.performingTask) throw new Error("Can't start a new pomodoro while one is already running");
this.performingTask = true;
this.setTimerInterval(getPomodoroTime());
this.speechService.say('ring ring ring start pomodoro now! Time to kick some ass!');
}
cancelPomodoro(){
this.stopPomodoro();
this.resetPomodoroTimer();
}
advanceTimer(){
this.$log.debug('advancing timer 1 second');
this.currentTime -= 1;
if (this.currentTime === 0) {
if (this.performingTask) this.completePomodoro();
else this.completeRest();
}
else this.timeLeft = formatTime(this.currentTime);
}
stopPomodoro() |
completePomodoro(){
this.activeTask.workedPomodoros++;
this.stopPomodoro();
this.startRest();
}
startRest(){
this.resting = true;
this.setupRestTime();
this.setTimerInterval(getRestTime(this.activeTask));
}
setTimerInterval(seconds){
//console.log('create interval');
this.cleanInterval(); // make sure we release all intervals
this.timerInterval = this.$interval(this.advanceTimer.bind(this), 1000, seconds);
}
completeRest(){
this.cleanInterval();
this.resting = false;
this.resetPomodoroTimer();
}
cleanInterval(){
if (this.timerInterval) {
//console.log('stopping interval');
this.$interval.cancel(this.timerInterval);
this.timerInterval = null;
}
}
resetPomodoroTimer(){
this.setTime(getPomodoroTime());
}
setupRestTime(){
this.setTime(getRestTime(this.activeTask));
}
setTime(time){
this.currentTime = time;
this.timeLeft = formatTime(this.currentTime);
}
}
function getPomodoroTime(){
return 25*60;
}
function getRestTime(activeTask){
if (activeTask.workedPomodoros % 4 === 0) return 20*60;
return 5*60;
}
function formatTime(time){
const minutesLeft = Number.parseInt(time/60),
secondsLeft = Math.round((time/60 - minutesLeft) * 60),
formattedMinutesLeft = formatDigits(minutesLeft),
formattedSecondsLeft = formatDigits(secondsLeft);
return `${formattedMinutesLeft}:${formattedSecondsLeft}`
}
function formatDigits(digits){
return digits < 10 ? "0" + digits : digits;
}
| {
this.performingTask = false;
this.cleanInterval();
this.speechService.say('Stop! Time to rest and reflect!');
} | identifier_body |
main.controller.js | import {Task} from '../components/tasks/tasks.service.js';
export class MainController {
| ($interval, $log, tasksService, speechService) {
'ngInject';
const vm = this,
currentTime = getPomodoroTime();
Object.assign(vm, {
// timer
timeLeft: formatTime(currentTime),
currentTime,
// tasks
tasks: tasksService.getTasks(),
newTask: Task(),
hasTasks(){ return this.tasks.length > 0; },
filterTerm: '',
// services
$interval,
$log,
tasksService,
speechService
});
// angular and getters don't seem to work
// very well together
vm.activeTask = this.tasks.find(t => t.isActive);
}
addNewTask(){
this.tasks.push(this.newTask);
if (this.tasks.length === 1) this.setTaskAsActive(this.newTask);
this.tasksService.saveTask(this.newTask);
this.newTask = Task();
}
removeTask(task){
const index = this.tasks.indexOf(task);
if (index !== -1){
if (task.isActive) this.setNextTaskAsActive(index);
this.tasks.splice(index,1);
this.tasksService.removeTask(task);
}
}
archiveTask(task){
const index = this.tasks.indexOf(task);
if (index !== -1){
let [taskToArchive] = this.tasks.splice(index,1);
this.tasksService.archiveTask(taskToArchive);
}
}
setNextTaskAsActive(index){
if (this.tasks.length > index + 1) this.setTaskAsActive(this.tasks[index+1]);
else if (index > 0) this.setTaskAsActive(this.tasks[index-1]);
}
setTaskAsActive(task){
const currentActiveTask = this.tasks.find(t => t.isActive);
if (currentActiveTask) currentActiveTask.isActive = false;
task.isActive = true;
this.activeTask = task;
}
startPomodoro(){
if (this.performingTask) throw new Error("Can't start a new pomodoro while one is already running");
this.performingTask = true;
this.setTimerInterval(getPomodoroTime());
this.speechService.say('ring ring ring start pomodoro now! Time to kick some ass!');
}
cancelPomodoro(){
this.stopPomodoro();
this.resetPomodoroTimer();
}
advanceTimer(){
this.$log.debug('advancing timer 1 second');
this.currentTime -= 1;
if (this.currentTime === 0) {
if (this.performingTask) this.completePomodoro();
else this.completeRest();
}
else this.timeLeft = formatTime(this.currentTime);
}
stopPomodoro(){
this.performingTask = false;
this.cleanInterval();
this.speechService.say('Stop! Time to rest and reflect!');
}
completePomodoro(){
this.activeTask.workedPomodoros++;
this.stopPomodoro();
this.startRest();
}
startRest(){
this.resting = true;
this.setupRestTime();
this.setTimerInterval(getRestTime(this.activeTask));
}
setTimerInterval(seconds){
//console.log('create interval');
this.cleanInterval(); // make sure we release all intervals
this.timerInterval = this.$interval(this.advanceTimer.bind(this), 1000, seconds);
}
completeRest(){
this.cleanInterval();
this.resting = false;
this.resetPomodoroTimer();
}
cleanInterval(){
if (this.timerInterval) {
//console.log('stopping interval');
this.$interval.cancel(this.timerInterval);
this.timerInterval = null;
}
}
resetPomodoroTimer(){
this.setTime(getPomodoroTime());
}
setupRestTime(){
this.setTime(getRestTime(this.activeTask));
}
setTime(time){
this.currentTime = time;
this.timeLeft = formatTime(this.currentTime);
}
}
function getPomodoroTime(){
return 25*60;
}
function getRestTime(activeTask){
if (activeTask.workedPomodoros % 4 === 0) return 20*60;
return 5*60;
}
function formatTime(time){
const minutesLeft = Number.parseInt(time/60),
secondsLeft = Math.round((time/60 - minutesLeft) * 60),
formattedMinutesLeft = formatDigits(minutesLeft),
formattedSecondsLeft = formatDigits(secondsLeft);
return `${formattedMinutesLeft}:${formattedSecondsLeft}`
}
function formatDigits(digits){
return digits < 10 ? "0" + digits : digits;
}
| constructor | identifier_name |
main.controller.js | import {Task} from '../components/tasks/tasks.service.js';
export class MainController {
constructor ($interval, $log, tasksService, speechService) {
'ngInject';
const vm = this,
currentTime = getPomodoroTime();
Object.assign(vm, {
// timer
timeLeft: formatTime(currentTime),
currentTime,
// tasks
tasks: tasksService.getTasks(),
newTask: Task(),
hasTasks(){ return this.tasks.length > 0; },
filterTerm: '',
// services
$interval,
$log,
tasksService,
speechService
});
// angular and getters don't seem to work
// very well together
vm.activeTask = this.tasks.find(t => t.isActive);
}
addNewTask(){
this.tasks.push(this.newTask);
if (this.tasks.length === 1) this.setTaskAsActive(this.newTask);
this.tasksService.saveTask(this.newTask);
this.newTask = Task();
}
removeTask(task){
const index = this.tasks.indexOf(task);
if (index !== -1){
if (task.isActive) this.setNextTaskAsActive(index);
this.tasks.splice(index,1);
this.tasksService.removeTask(task);
}
}
archiveTask(task){
const index = this.tasks.indexOf(task);
if (index !== -1){
let [taskToArchive] = this.tasks.splice(index,1);
this.tasksService.archiveTask(taskToArchive);
}
}
setNextTaskAsActive(index){
if (this.tasks.length > index + 1) this.setTaskAsActive(this.tasks[index+1]);
else if (index > 0) this.setTaskAsActive(this.tasks[index-1]);
}
setTaskAsActive(task){
const currentActiveTask = this.tasks.find(t => t.isActive);
if (currentActiveTask) currentActiveTask.isActive = false;
task.isActive = true;
this.activeTask = task;
}
startPomodoro(){
if (this.performingTask) throw new Error("Can't start a new pomodoro while one is already running");
this.performingTask = true;
this.setTimerInterval(getPomodoroTime());
this.speechService.say('ring ring ring start pomodoro now! Time to kick some ass!');
}
cancelPomodoro(){
this.stopPomodoro();
this.resetPomodoroTimer();
}
advanceTimer(){
this.$log.debug('advancing timer 1 second');
this.currentTime -= 1;
if (this.currentTime === 0) {
if (this.performingTask) this.completePomodoro();
else this.completeRest();
}
else this.timeLeft = formatTime(this.currentTime);
}
stopPomodoro(){
this.performingTask = false;
this.cleanInterval();
this.speechService.say('Stop! Time to rest and reflect!');
}
completePomodoro(){
this.activeTask.workedPomodoros++;
this.stopPomodoro();
this.startRest();
}
startRest(){
this.resting = true;
this.setupRestTime();
this.setTimerInterval(getRestTime(this.activeTask));
}
setTimerInterval(seconds){
//console.log('create interval');
this.cleanInterval(); // make sure we release all intervals
this.timerInterval = this.$interval(this.advanceTimer.bind(this), 1000, seconds);
}
completeRest(){
this.cleanInterval();
this.resting = false;
this.resetPomodoroTimer();
}
cleanInterval(){
if (this.timerInterval) {
//console.log('stopping interval');
this.$interval.cancel(this.timerInterval);
this.timerInterval = null;
}
}
resetPomodoroTimer(){
this.setTime(getPomodoroTime());
} | }
setTime(time){
this.currentTime = time;
this.timeLeft = formatTime(this.currentTime);
}
}
function getPomodoroTime(){
return 25*60;
}
function getRestTime(activeTask){
if (activeTask.workedPomodoros % 4 === 0) return 20*60;
return 5*60;
}
function formatTime(time){
const minutesLeft = Number.parseInt(time/60),
secondsLeft = Math.round((time/60 - minutesLeft) * 60),
formattedMinutesLeft = formatDigits(minutesLeft),
formattedSecondsLeft = formatDigits(secondsLeft);
return `${formattedMinutesLeft}:${formattedSecondsLeft}`
}
function formatDigits(digits){
return digits < 10 ? "0" + digits : digits;
} |
setupRestTime(){
this.setTime(getRestTime(this.activeTask)); | random_line_split |
Overview.js | /*
* catberry-homepage
*
* Copyright (c) 2015 Denis Rechkunov and project contributors.
*
* catberry-homepage's license follows:
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | * FITNESS FOR A PARTICULAR PURPOSE AND 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.
*
* This license applies to all parts of catberry-homepage that are not
* externally maintained libraries.
*/
'use strict';
module.exports = Overview;
var util = require('util'),
StaticStoreBase = require('../../lib/StaticStoreBase');
util.inherits(Overview, StaticStoreBase);
/*
* This is a Catberry Store file.
* More details can be found here
* https://github.com/catberry/catberry/blob/master/docs/index.md#stores
*/
/**
* Creates new instance of the "static/Quotes" store.
* @constructor
*/
function Overview() {
StaticStoreBase.call(this);
}
Overview.prototype.filename = 'github/overview'; | random_line_split | |
Overview.js | /*
* catberry-homepage
*
* Copyright (c) 2015 Denis Rechkunov and project contributors.
*
* catberry-homepage's license follows:
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND 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.
*
* This license applies to all parts of catberry-homepage that are not
* externally maintained libraries.
*/
'use strict';
module.exports = Overview;
var util = require('util'),
StaticStoreBase = require('../../lib/StaticStoreBase');
util.inherits(Overview, StaticStoreBase);
/*
* This is a Catberry Store file.
* More details can be found here
* https://github.com/catberry/catberry/blob/master/docs/index.md#stores
*/
/**
* Creates new instance of the "static/Quotes" store.
* @constructor
*/
function Overview() |
Overview.prototype.filename = 'github/overview';
| {
StaticStoreBase.call(this);
} | identifier_body |
Overview.js | /*
* catberry-homepage
*
* Copyright (c) 2015 Denis Rechkunov and project contributors.
*
* catberry-homepage's license follows:
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND 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.
*
* This license applies to all parts of catberry-homepage that are not
* externally maintained libraries.
*/
'use strict';
module.exports = Overview;
var util = require('util'),
StaticStoreBase = require('../../lib/StaticStoreBase');
util.inherits(Overview, StaticStoreBase);
/*
* This is a Catberry Store file.
* More details can be found here
* https://github.com/catberry/catberry/blob/master/docs/index.md#stores
*/
/**
* Creates new instance of the "static/Quotes" store.
* @constructor
*/
function | () {
StaticStoreBase.call(this);
}
Overview.prototype.filename = 'github/overview';
| Overview | identifier_name |
bluetigers.py | # coding=utf-8
# Author: raver2046 <raver2046@gmail.com>
#
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage 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.
#
# SickRage is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. | from requests.utils import dict_from_cookiejar
import traceback
from sickbeard import logger, tvcache
from sickbeard.bs4_parser import BS4Parser
from sickrage.providers.torrent.TorrentProvider import TorrentProvider
class BlueTigersProvider(TorrentProvider): # pylint: disable=too-many-instance-attributes
def __init__(self):
TorrentProvider.__init__(self, "BLUETIGERS")
self.username = None
self.password = None
self.ratio = None
self.token = None
self.cache = tvcache.TVCache(self, min_time=10) # Only poll BLUETIGERS every 10 minutes max
self.urls = {
'base_url': 'https://www.bluetigers.ca/',
'search': 'https://www.bluetigers.ca/torrents-search.php',
'login': 'https://www.bluetigers.ca/account-login.php',
'download': 'https://www.bluetigers.ca/torrents-details.php?id=%s&hit=1',
}
self.search_params = {
"c16": 1, "c10": 1, "c130": 1, "c131": 1, "c17": 1, "c18": 1, "c19": 1
}
self.url = self.urls['base_url']
def login(self):
if any(dict_from_cookiejar(self.session.cookies).values()):
return True
login_params = {
'username': self.username,
'password': self.password,
'take_login': '1'
}
response = self.get_url(self.urls['login'], post_data=login_params, timeout=30)
if not response:
check_login = self.get_url(self.urls['base_url'], timeout=30)
if re.search('account-logout.php', check_login):
return True
else:
logger.log(u"Unable to connect to provider", logger.WARNING)
return False
if re.search('account-login.php', response):
logger.log(u"Invalid username or password. Check your settings", logger.WARNING)
return False
return True
def search(self, search_strings, age=0, ep_obj=None): # pylint: disable=too-many-locals
results = []
if not self.login():
return results
for mode in search_strings:
items = []
logger.log(u"Search Mode: %s" % mode, logger.DEBUG)
for search_string in search_strings[mode]:
if mode != 'RSS':
logger.log(u"Search string: {search}".format(search=search_string.decode('utf-8')),
logger.DEBUG)
self.search_params['search'] = search_string
data = self.get_url(self.urls['search'], params=self.search_params)
if not data:
continue
try:
with BS4Parser(data, 'html5lib') as html:
result_linkz = html.findAll('a', href=re.compile("torrents-details"))
if not result_linkz:
logger.log(u"Data returned from provider do not contains any torrent", logger.DEBUG)
continue
if result_linkz:
for link in result_linkz:
title = link.text
download_url = self.urls['base_url'] + link['href']
download_url = download_url.replace("torrents-details", "download")
# FIXME
size = -1
seeders = 1
leechers = 0
if not title or not download_url:
continue
# Filter unseeded torrent
# if seeders < self.minseed or leechers < self.minleech:
# if mode != 'RSS':
# logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG)
# continue
item = title, download_url, size, seeders, leechers
if mode != 'RSS':
logger.log(u"Found result: %s " % title, logger.DEBUG)
items.append(item)
except Exception:
logger.log(u"Failed parsing provider. Traceback: %s" % traceback.format_exc(), logger.ERROR)
# For each search mode sort all the items by seeders if available
items.sort(key=lambda tup: tup[3], reverse=True)
results += items
return results
def seed_ratio(self):
return self.ratio
provider = BlueTigersProvider() | #
# You should have received a copy of the GNU General Public License
# along with SickRage. If not, see <http://www.gnu.org/licenses/>.
import re | random_line_split |
bluetigers.py | # coding=utf-8
# Author: raver2046 <raver2046@gmail.com>
#
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage 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.
#
# SickRage is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SickRage. If not, see <http://www.gnu.org/licenses/>.
import re
from requests.utils import dict_from_cookiejar
import traceback
from sickbeard import logger, tvcache
from sickbeard.bs4_parser import BS4Parser
from sickrage.providers.torrent.TorrentProvider import TorrentProvider
class BlueTigersProvider(TorrentProvider): # pylint: disable=too-many-instance-attributes
def __init__(self):
TorrentProvider.__init__(self, "BLUETIGERS")
self.username = None
self.password = None
self.ratio = None
self.token = None
self.cache = tvcache.TVCache(self, min_time=10) # Only poll BLUETIGERS every 10 minutes max
self.urls = {
'base_url': 'https://www.bluetigers.ca/',
'search': 'https://www.bluetigers.ca/torrents-search.php',
'login': 'https://www.bluetigers.ca/account-login.php',
'download': 'https://www.bluetigers.ca/torrents-details.php?id=%s&hit=1',
}
self.search_params = {
"c16": 1, "c10": 1, "c130": 1, "c131": 1, "c17": 1, "c18": 1, "c19": 1
}
self.url = self.urls['base_url']
def login(self):
if any(dict_from_cookiejar(self.session.cookies).values()):
return True
login_params = {
'username': self.username,
'password': self.password,
'take_login': '1'
}
response = self.get_url(self.urls['login'], post_data=login_params, timeout=30)
if not response:
check_login = self.get_url(self.urls['base_url'], timeout=30)
if re.search('account-logout.php', check_login):
return True
else:
logger.log(u"Unable to connect to provider", logger.WARNING)
return False
if re.search('account-login.php', response):
logger.log(u"Invalid username or password. Check your settings", logger.WARNING)
return False
return True
def search(self, search_strings, age=0, ep_obj=None): # pylint: disable=too-many-locals
results = []
if not self.login():
return results
for mode in search_strings:
items = []
logger.log(u"Search Mode: %s" % mode, logger.DEBUG)
for search_string in search_strings[mode]:
if mode != 'RSS':
logger.log(u"Search string: {search}".format(search=search_string.decode('utf-8')),
logger.DEBUG)
self.search_params['search'] = search_string
data = self.get_url(self.urls['search'], params=self.search_params)
if not data:
continue
try:
with BS4Parser(data, 'html5lib') as html:
result_linkz = html.findAll('a', href=re.compile("torrents-details"))
if not result_linkz:
logger.log(u"Data returned from provider do not contains any torrent", logger.DEBUG)
continue
if result_linkz:
for link in result_linkz:
|
except Exception:
logger.log(u"Failed parsing provider. Traceback: %s" % traceback.format_exc(), logger.ERROR)
# For each search mode sort all the items by seeders if available
items.sort(key=lambda tup: tup[3], reverse=True)
results += items
return results
def seed_ratio(self):
return self.ratio
provider = BlueTigersProvider()
| title = link.text
download_url = self.urls['base_url'] + link['href']
download_url = download_url.replace("torrents-details", "download")
# FIXME
size = -1
seeders = 1
leechers = 0
if not title or not download_url:
continue
# Filter unseeded torrent
# if seeders < self.minseed or leechers < self.minleech:
# if mode != 'RSS':
# logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG)
# continue
item = title, download_url, size, seeders, leechers
if mode != 'RSS':
logger.log(u"Found result: %s " % title, logger.DEBUG)
items.append(item) | conditional_block |
bluetigers.py | # coding=utf-8
# Author: raver2046 <raver2046@gmail.com>
#
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage 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.
#
# SickRage is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SickRage. If not, see <http://www.gnu.org/licenses/>.
import re
from requests.utils import dict_from_cookiejar
import traceback
from sickbeard import logger, tvcache
from sickbeard.bs4_parser import BS4Parser
from sickrage.providers.torrent.TorrentProvider import TorrentProvider
class BlueTigersProvider(TorrentProvider): # pylint: disable=too-many-instance-attributes
def __init__(self):
|
def login(self):
if any(dict_from_cookiejar(self.session.cookies).values()):
return True
login_params = {
'username': self.username,
'password': self.password,
'take_login': '1'
}
response = self.get_url(self.urls['login'], post_data=login_params, timeout=30)
if not response:
check_login = self.get_url(self.urls['base_url'], timeout=30)
if re.search('account-logout.php', check_login):
return True
else:
logger.log(u"Unable to connect to provider", logger.WARNING)
return False
if re.search('account-login.php', response):
logger.log(u"Invalid username or password. Check your settings", logger.WARNING)
return False
return True
def search(self, search_strings, age=0, ep_obj=None): # pylint: disable=too-many-locals
results = []
if not self.login():
return results
for mode in search_strings:
items = []
logger.log(u"Search Mode: %s" % mode, logger.DEBUG)
for search_string in search_strings[mode]:
if mode != 'RSS':
logger.log(u"Search string: {search}".format(search=search_string.decode('utf-8')),
logger.DEBUG)
self.search_params['search'] = search_string
data = self.get_url(self.urls['search'], params=self.search_params)
if not data:
continue
try:
with BS4Parser(data, 'html5lib') as html:
result_linkz = html.findAll('a', href=re.compile("torrents-details"))
if not result_linkz:
logger.log(u"Data returned from provider do not contains any torrent", logger.DEBUG)
continue
if result_linkz:
for link in result_linkz:
title = link.text
download_url = self.urls['base_url'] + link['href']
download_url = download_url.replace("torrents-details", "download")
# FIXME
size = -1
seeders = 1
leechers = 0
if not title or not download_url:
continue
# Filter unseeded torrent
# if seeders < self.minseed or leechers < self.minleech:
# if mode != 'RSS':
# logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG)
# continue
item = title, download_url, size, seeders, leechers
if mode != 'RSS':
logger.log(u"Found result: %s " % title, logger.DEBUG)
items.append(item)
except Exception:
logger.log(u"Failed parsing provider. Traceback: %s" % traceback.format_exc(), logger.ERROR)
# For each search mode sort all the items by seeders if available
items.sort(key=lambda tup: tup[3], reverse=True)
results += items
return results
def seed_ratio(self):
return self.ratio
provider = BlueTigersProvider()
| TorrentProvider.__init__(self, "BLUETIGERS")
self.username = None
self.password = None
self.ratio = None
self.token = None
self.cache = tvcache.TVCache(self, min_time=10) # Only poll BLUETIGERS every 10 minutes max
self.urls = {
'base_url': 'https://www.bluetigers.ca/',
'search': 'https://www.bluetigers.ca/torrents-search.php',
'login': 'https://www.bluetigers.ca/account-login.php',
'download': 'https://www.bluetigers.ca/torrents-details.php?id=%s&hit=1',
}
self.search_params = {
"c16": 1, "c10": 1, "c130": 1, "c131": 1, "c17": 1, "c18": 1, "c19": 1
}
self.url = self.urls['base_url'] | identifier_body |
bluetigers.py | # coding=utf-8
# Author: raver2046 <raver2046@gmail.com>
#
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage 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.
#
# SickRage is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SickRage. If not, see <http://www.gnu.org/licenses/>.
import re
from requests.utils import dict_from_cookiejar
import traceback
from sickbeard import logger, tvcache
from sickbeard.bs4_parser import BS4Parser
from sickrage.providers.torrent.TorrentProvider import TorrentProvider
class BlueTigersProvider(TorrentProvider): # pylint: disable=too-many-instance-attributes
def __init__(self):
TorrentProvider.__init__(self, "BLUETIGERS")
self.username = None
self.password = None
self.ratio = None
self.token = None
self.cache = tvcache.TVCache(self, min_time=10) # Only poll BLUETIGERS every 10 minutes max
self.urls = {
'base_url': 'https://www.bluetigers.ca/',
'search': 'https://www.bluetigers.ca/torrents-search.php',
'login': 'https://www.bluetigers.ca/account-login.php',
'download': 'https://www.bluetigers.ca/torrents-details.php?id=%s&hit=1',
}
self.search_params = {
"c16": 1, "c10": 1, "c130": 1, "c131": 1, "c17": 1, "c18": 1, "c19": 1
}
self.url = self.urls['base_url']
def login(self):
if any(dict_from_cookiejar(self.session.cookies).values()):
return True
login_params = {
'username': self.username,
'password': self.password,
'take_login': '1'
}
response = self.get_url(self.urls['login'], post_data=login_params, timeout=30)
if not response:
check_login = self.get_url(self.urls['base_url'], timeout=30)
if re.search('account-logout.php', check_login):
return True
else:
logger.log(u"Unable to connect to provider", logger.WARNING)
return False
if re.search('account-login.php', response):
logger.log(u"Invalid username or password. Check your settings", logger.WARNING)
return False
return True
def search(self, search_strings, age=0, ep_obj=None): # pylint: disable=too-many-locals
results = []
if not self.login():
return results
for mode in search_strings:
items = []
logger.log(u"Search Mode: %s" % mode, logger.DEBUG)
for search_string in search_strings[mode]:
if mode != 'RSS':
logger.log(u"Search string: {search}".format(search=search_string.decode('utf-8')),
logger.DEBUG)
self.search_params['search'] = search_string
data = self.get_url(self.urls['search'], params=self.search_params)
if not data:
continue
try:
with BS4Parser(data, 'html5lib') as html:
result_linkz = html.findAll('a', href=re.compile("torrents-details"))
if not result_linkz:
logger.log(u"Data returned from provider do not contains any torrent", logger.DEBUG)
continue
if result_linkz:
for link in result_linkz:
title = link.text
download_url = self.urls['base_url'] + link['href']
download_url = download_url.replace("torrents-details", "download")
# FIXME
size = -1
seeders = 1
leechers = 0
if not title or not download_url:
continue
# Filter unseeded torrent
# if seeders < self.minseed or leechers < self.minleech:
# if mode != 'RSS':
# logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG)
# continue
item = title, download_url, size, seeders, leechers
if mode != 'RSS':
logger.log(u"Found result: %s " % title, logger.DEBUG)
items.append(item)
except Exception:
logger.log(u"Failed parsing provider. Traceback: %s" % traceback.format_exc(), logger.ERROR)
# For each search mode sort all the items by seeders if available
items.sort(key=lambda tup: tup[3], reverse=True)
results += items
return results
def | (self):
return self.ratio
provider = BlueTigersProvider()
| seed_ratio | identifier_name |
poisonpentametron.js | 'use strict';
var fs = require('fs-extra')
, async = require('async')
, nconf = require('nconf');
var config = nconf.file('./conf/pp.' + (process.env.NODE_ENV || 'development') + '.json').load();
require('date-utils');
var pp = {};
pp.poetry = "";
pp.poetryPlain = "";
pp.rawPoetry = [];
pp.cleanPoetry = [];
pp.checkSum = 0;
pp.isFeedFresh = function(cb) {
// checks if conf.Feed is older than conf.maxAgeInMinutes
console.log('\tisFeedFresh checking how old feed is');
console.log(config.feed);
fs.stat(config.feed, function(err, stats) {
if (err) {
if (err.errno === 34) {
console.error('\tisFeedFresh error: Feed not found!');
cb(new Error('Feed not found!'));
} else {
console.error('\tisFeedFresh Unhandled error: %s', JSON.stringify(err, null, 4));
cb(err);
}
} else |
});
};
function start(cb) {
console.log('start');
return cb(null, config.url);
}
var downloadFeed = require('./download.js').downloadFeed
, parseTweets = require('./parseTweets.js').parseTweets
, saveFile = require('./archiveFile.js').saveFile
, saveAndArchiveFile = require('./archiveFile.js').saveAndArchiveFile
, cleanText = require('./sanitiseTweets.js').cleanText
, createMatrix = require('./createMatrix.js').createMatrix
, createPlainText = require('./createPlainText.js').createPlainText;
function finished(d, cb) { // mock cleanText
console.log('finished d: %s', typeof d);
cb(null);
}
pp.updateFeed = function(cb) {
var waterfall = [start, downloadFeed, saveAndArchiveFile, parseTweets, saveAndArchiveFile, cleanText, saveAndArchiveFile,
//FIXME: refactor
function glue(data, cb) {
createMatrix(data, function(err, file, data2, encoding) {
if (err) {
return cb(err);
}
saveFile(file, data2, encoding, function(meh) {
console.log('created banner: %s', typeof meh);
createPlainText(data, function(err, file, data3, encoding) {
saveFile(file, data3, encoding, function(meh) {
console.log('created plain: %s', typeof meh);
cb(null, meh); // :(
}); // saveFileInner
}); // createPlainText
}); // saveFile outer
}); // createMatrix
},finished];
console.log('\tstart time: %s', new Date());
async.waterfall(waterfall, function finished(err) {
if (err) {
// 500
console.log('\tupdateFeed error: %s', JSON.stringify(err, null, 4));
cb(err);
} else {
console.log('\tupdateFeed completed successfully!');
console.log('\tend time: %s', new Date());
cb(null);
}
});
};
pp.ok = function() { return true; };
module.exports = pp;
| {
var feed = new Date(stats.mtime)
, now = new Date()
, delta = feed.getMinutesBetween(now);
console.log('\tisFeedFresh stats:\n\t\t%s\n\t\tnow %s\n\t\tdelta (min) %s\n\t\tthreshold (min) %s', feed, now, delta, config.maxAgeInMinutes);
cb(null, delta < config.maxAgeInMinutes);
} | conditional_block |
poisonpentametron.js | 'use strict';
var fs = require('fs-extra')
, async = require('async')
, nconf = require('nconf');
var config = nconf.file('./conf/pp.' + (process.env.NODE_ENV || 'development') + '.json').load();
require('date-utils');
var pp = {};
pp.poetry = "";
pp.poetryPlain = "";
pp.rawPoetry = [];
pp.cleanPoetry = [];
pp.checkSum = 0;
pp.isFeedFresh = function(cb) {
// checks if conf.Feed is older than conf.maxAgeInMinutes
console.log('\tisFeedFresh checking how old feed is');
console.log(config.feed);
fs.stat(config.feed, function(err, stats) {
if (err) {
if (err.errno === 34) {
console.error('\tisFeedFresh error: Feed not found!');
cb(new Error('Feed not found!'));
} else {
console.error('\tisFeedFresh Unhandled error: %s', JSON.stringify(err, null, 4));
cb(err);
}
} else {
var feed = new Date(stats.mtime)
, now = new Date()
, delta = feed.getMinutesBetween(now);
console.log('\tisFeedFresh stats:\n\t\t%s\n\t\tnow %s\n\t\tdelta (min) %s\n\t\tthreshold (min) %s', feed, now, delta, config.maxAgeInMinutes);
cb(null, delta < config.maxAgeInMinutes);
}
});
};
function | (cb) {
console.log('start');
return cb(null, config.url);
}
var downloadFeed = require('./download.js').downloadFeed
, parseTweets = require('./parseTweets.js').parseTweets
, saveFile = require('./archiveFile.js').saveFile
, saveAndArchiveFile = require('./archiveFile.js').saveAndArchiveFile
, cleanText = require('./sanitiseTweets.js').cleanText
, createMatrix = require('./createMatrix.js').createMatrix
, createPlainText = require('./createPlainText.js').createPlainText;
function finished(d, cb) { // mock cleanText
console.log('finished d: %s', typeof d);
cb(null);
}
pp.updateFeed = function(cb) {
var waterfall = [start, downloadFeed, saveAndArchiveFile, parseTweets, saveAndArchiveFile, cleanText, saveAndArchiveFile,
//FIXME: refactor
function glue(data, cb) {
createMatrix(data, function(err, file, data2, encoding) {
if (err) {
return cb(err);
}
saveFile(file, data2, encoding, function(meh) {
console.log('created banner: %s', typeof meh);
createPlainText(data, function(err, file, data3, encoding) {
saveFile(file, data3, encoding, function(meh) {
console.log('created plain: %s', typeof meh);
cb(null, meh); // :(
}); // saveFileInner
}); // createPlainText
}); // saveFile outer
}); // createMatrix
},finished];
console.log('\tstart time: %s', new Date());
async.waterfall(waterfall, function finished(err) {
if (err) {
// 500
console.log('\tupdateFeed error: %s', JSON.stringify(err, null, 4));
cb(err);
} else {
console.log('\tupdateFeed completed successfully!');
console.log('\tend time: %s', new Date());
cb(null);
}
});
};
pp.ok = function() { return true; };
module.exports = pp;
| start | identifier_name |
poisonpentametron.js | 'use strict';
var fs = require('fs-extra')
, async = require('async')
, nconf = require('nconf');
var config = nconf.file('./conf/pp.' + (process.env.NODE_ENV || 'development') + '.json').load();
require('date-utils');
var pp = {};
pp.poetry = "";
pp.poetryPlain = "";
pp.rawPoetry = [];
pp.cleanPoetry = [];
pp.checkSum = 0;
pp.isFeedFresh = function(cb) {
// checks if conf.Feed is older than conf.maxAgeInMinutes
console.log('\tisFeedFresh checking how old feed is');
console.log(config.feed);
fs.stat(config.feed, function(err, stats) {
if (err) {
if (err.errno === 34) {
console.error('\tisFeedFresh error: Feed not found!');
cb(new Error('Feed not found!'));
} else {
console.error('\tisFeedFresh Unhandled error: %s', JSON.stringify(err, null, 4));
cb(err);
}
} else {
var feed = new Date(stats.mtime)
, now = new Date()
, delta = feed.getMinutesBetween(now);
console.log('\tisFeedFresh stats:\n\t\t%s\n\t\tnow %s\n\t\tdelta (min) %s\n\t\tthreshold (min) %s', feed, now, delta, config.maxAgeInMinutes);
cb(null, delta < config.maxAgeInMinutes);
}
});
};
function start(cb) |
var downloadFeed = require('./download.js').downloadFeed
, parseTweets = require('./parseTweets.js').parseTweets
, saveFile = require('./archiveFile.js').saveFile
, saveAndArchiveFile = require('./archiveFile.js').saveAndArchiveFile
, cleanText = require('./sanitiseTweets.js').cleanText
, createMatrix = require('./createMatrix.js').createMatrix
, createPlainText = require('./createPlainText.js').createPlainText;
function finished(d, cb) { // mock cleanText
console.log('finished d: %s', typeof d);
cb(null);
}
pp.updateFeed = function(cb) {
var waterfall = [start, downloadFeed, saveAndArchiveFile, parseTweets, saveAndArchiveFile, cleanText, saveAndArchiveFile,
//FIXME: refactor
function glue(data, cb) {
createMatrix(data, function(err, file, data2, encoding) {
if (err) {
return cb(err);
}
saveFile(file, data2, encoding, function(meh) {
console.log('created banner: %s', typeof meh);
createPlainText(data, function(err, file, data3, encoding) {
saveFile(file, data3, encoding, function(meh) {
console.log('created plain: %s', typeof meh);
cb(null, meh); // :(
}); // saveFileInner
}); // createPlainText
}); // saveFile outer
}); // createMatrix
},finished];
console.log('\tstart time: %s', new Date());
async.waterfall(waterfall, function finished(err) {
if (err) {
// 500
console.log('\tupdateFeed error: %s', JSON.stringify(err, null, 4));
cb(err);
} else {
console.log('\tupdateFeed completed successfully!');
console.log('\tend time: %s', new Date());
cb(null);
}
});
};
pp.ok = function() { return true; };
module.exports = pp;
| {
console.log('start');
return cb(null, config.url);
} | identifier_body |
poisonpentametron.js | 'use strict';
var fs = require('fs-extra')
, async = require('async')
, nconf = require('nconf');
var config = nconf.file('./conf/pp.' + (process.env.NODE_ENV || 'development') + '.json').load();
require('date-utils');
var pp = {};
pp.poetry = "";
pp.poetryPlain = "";
pp.rawPoetry = [];
pp.cleanPoetry = [];
pp.checkSum = 0;
pp.isFeedFresh = function(cb) {
// checks if conf.Feed is older than conf.maxAgeInMinutes
console.log('\tisFeedFresh checking how old feed is');
console.log(config.feed);
fs.stat(config.feed, function(err, stats) {
if (err) {
if (err.errno === 34) {
console.error('\tisFeedFresh error: Feed not found!');
cb(new Error('Feed not found!'));
} else {
console.error('\tisFeedFresh Unhandled error: %s', JSON.stringify(err, null, 4));
cb(err);
}
} else {
var feed = new Date(stats.mtime)
, now = new Date()
, delta = feed.getMinutesBetween(now);
console.log('\tisFeedFresh stats:\n\t\t%s\n\t\tnow %s\n\t\tdelta (min) %s\n\t\tthreshold (min) %s', feed, now, delta, config.maxAgeInMinutes);
cb(null, delta < config.maxAgeInMinutes);
}
});
};
function start(cb) {
console.log('start');
return cb(null, config.url);
}
var downloadFeed = require('./download.js').downloadFeed
, parseTweets = require('./parseTweets.js').parseTweets
, saveFile = require('./archiveFile.js').saveFile
, saveAndArchiveFile = require('./archiveFile.js').saveAndArchiveFile |
function finished(d, cb) { // mock cleanText
console.log('finished d: %s', typeof d);
cb(null);
}
pp.updateFeed = function(cb) {
var waterfall = [start, downloadFeed, saveAndArchiveFile, parseTweets, saveAndArchiveFile, cleanText, saveAndArchiveFile,
//FIXME: refactor
function glue(data, cb) {
createMatrix(data, function(err, file, data2, encoding) {
if (err) {
return cb(err);
}
saveFile(file, data2, encoding, function(meh) {
console.log('created banner: %s', typeof meh);
createPlainText(data, function(err, file, data3, encoding) {
saveFile(file, data3, encoding, function(meh) {
console.log('created plain: %s', typeof meh);
cb(null, meh); // :(
}); // saveFileInner
}); // createPlainText
}); // saveFile outer
}); // createMatrix
},finished];
console.log('\tstart time: %s', new Date());
async.waterfall(waterfall, function finished(err) {
if (err) {
// 500
console.log('\tupdateFeed error: %s', JSON.stringify(err, null, 4));
cb(err);
} else {
console.log('\tupdateFeed completed successfully!');
console.log('\tend time: %s', new Date());
cb(null);
}
});
};
pp.ok = function() { return true; };
module.exports = pp; | , cleanText = require('./sanitiseTweets.js').cleanText
, createMatrix = require('./createMatrix.js').createMatrix
, createPlainText = require('./createPlainText.js').createPlainText; | random_line_split |
window_wall_ratio_east_SDH_by_building_age_lookup.py | # coding: utf8
# OeQ autogenerated lookup function for 'Window/Wall Ratio East in correlation to year of construction, based on the source data of the survey for the "German Building Typology developed by the "Institut für Wohnen und Umwelt", Darmstadt/Germany, 2011-2013'
import math
import numpy as np
import oeqLookuptable as oeq
def get(*xin):
l_lookup = oeq.lookuptable(
[
1849,0,
1850,0,
1851,0,
1852,0,
1853,0,
1854,0,
1855,0,
1856,0,
1857,0,
1858,0,
1859,0,
1860,0,
1861,0,
1862,0,
1863,0,
1864,0,
1865,0,
1866,0,
1867,0,
1868,0,
1869,0,
1870,0,
1871,0,
1872,0,
1873,0,
1874,0,
1875,0,
1876,0,
1877,0,
1878,0,
1879,0,
1880,0,
1881,0,
1882,0,
1883,0,
1884,0,
1885,0,
1886,0,
1887,0,
1888,0,
1889,0,
1890,0,
1891,0,
1892,0,
1893,0,
1894,0,
1895,0,
1896,0,
1897,0,
1898,0,
1899,0,
1900,0,
1901,0,
1902,0,
1903,0,
1904,0,
1905,0,
1906,0,
1907,0,
1908,0,
1909,0,
1910,0,
1911,0,
1912,0,
1913,0,
1914,0,
1915,0,
1916,0,
1917,0,
1918,0, | 1922,0,
1923,0,
1924,0,
1925,0,
1926,0,
1927,0,
1928,0,
1929,0,
1930,0,
1931,0,
1932,0,
1933,0,
1934,0,
1935,0,
1936,0,
1937,0,
1938,0,
1939,0,
1940,0,
1941,0,
1942,0,
1943,0,
1944,0,
1945,0,
1946,0,
1947,0,
1948,0,
1949,0,
1950,0,
1951,0,
1952,0,
1953,0,
1954,0,
1955,0,
1956,0,
1957,0,
1958,0.001,
1959,0.002,
1960,0.002,
1961,0,
1962,0,
1963,0,
1964,0,
1965,0,
1966,0.019,
1967,0.046,
1968,0.077,
1969,0.11,
1970,0.141,
1971,0.169,
1972,0.195,
1973,0.22,
1974,0.22,
1975,0.22,
1976,0.22,
1977,0.22,
1978,0.161,
1979,0.089,
1980,0.028,
1981,0,
1982,0.019,
1983,0.07,
1984,0.131,
1985,0.18,
1986,0.2,
1987,0.199,
1988,0.188,
1989,0.18,
1990,0.184,
1991,0.192,
1992,0.195,
1993,0.18,
1994,0.142,
1995,0.09,
1996,0.038,
1997,0,
1998,0,
1999,0,
2000,0.007,
2001,0.025,
2002,0.038,
2003,0.045,
2004,0.049,
2005,0.05,
2006,0.05,
2007,0.051,
2008,0.05,
2009,0.05,
2010,0.05,
2011,0.05,
2012,0.05,
2013,0.05,
2014,0.05,
2015,0.05,
2016,0.05,
2017,0.05,
2018,0.05,
2019,0.05,
2020,0.05,
2021,0.05])
return(l_lookup.lookup(xin)) | 1919,0,
1920,0,
1921,0, | random_line_split |
window_wall_ratio_east_SDH_by_building_age_lookup.py | # coding: utf8
# OeQ autogenerated lookup function for 'Window/Wall Ratio East in correlation to year of construction, based on the source data of the survey for the "German Building Typology developed by the "Institut für Wohnen und Umwelt", Darmstadt/Germany, 2011-2013'
import math
import numpy as np
import oeqLookuptable as oeq
def g | *xin):
l_lookup = oeq.lookuptable(
[
1849,0,
1850,0,
1851,0,
1852,0,
1853,0,
1854,0,
1855,0,
1856,0,
1857,0,
1858,0,
1859,0,
1860,0,
1861,0,
1862,0,
1863,0,
1864,0,
1865,0,
1866,0,
1867,0,
1868,0,
1869,0,
1870,0,
1871,0,
1872,0,
1873,0,
1874,0,
1875,0,
1876,0,
1877,0,
1878,0,
1879,0,
1880,0,
1881,0,
1882,0,
1883,0,
1884,0,
1885,0,
1886,0,
1887,0,
1888,0,
1889,0,
1890,0,
1891,0,
1892,0,
1893,0,
1894,0,
1895,0,
1896,0,
1897,0,
1898,0,
1899,0,
1900,0,
1901,0,
1902,0,
1903,0,
1904,0,
1905,0,
1906,0,
1907,0,
1908,0,
1909,0,
1910,0,
1911,0,
1912,0,
1913,0,
1914,0,
1915,0,
1916,0,
1917,0,
1918,0,
1919,0,
1920,0,
1921,0,
1922,0,
1923,0,
1924,0,
1925,0,
1926,0,
1927,0,
1928,0,
1929,0,
1930,0,
1931,0,
1932,0,
1933,0,
1934,0,
1935,0,
1936,0,
1937,0,
1938,0,
1939,0,
1940,0,
1941,0,
1942,0,
1943,0,
1944,0,
1945,0,
1946,0,
1947,0,
1948,0,
1949,0,
1950,0,
1951,0,
1952,0,
1953,0,
1954,0,
1955,0,
1956,0,
1957,0,
1958,0.001,
1959,0.002,
1960,0.002,
1961,0,
1962,0,
1963,0,
1964,0,
1965,0,
1966,0.019,
1967,0.046,
1968,0.077,
1969,0.11,
1970,0.141,
1971,0.169,
1972,0.195,
1973,0.22,
1974,0.22,
1975,0.22,
1976,0.22,
1977,0.22,
1978,0.161,
1979,0.089,
1980,0.028,
1981,0,
1982,0.019,
1983,0.07,
1984,0.131,
1985,0.18,
1986,0.2,
1987,0.199,
1988,0.188,
1989,0.18,
1990,0.184,
1991,0.192,
1992,0.195,
1993,0.18,
1994,0.142,
1995,0.09,
1996,0.038,
1997,0,
1998,0,
1999,0,
2000,0.007,
2001,0.025,
2002,0.038,
2003,0.045,
2004,0.049,
2005,0.05,
2006,0.05,
2007,0.051,
2008,0.05,
2009,0.05,
2010,0.05,
2011,0.05,
2012,0.05,
2013,0.05,
2014,0.05,
2015,0.05,
2016,0.05,
2017,0.05,
2018,0.05,
2019,0.05,
2020,0.05,
2021,0.05])
return(l_lookup.lookup(xin))
| et( | identifier_name |
window_wall_ratio_east_SDH_by_building_age_lookup.py | # coding: utf8
# OeQ autogenerated lookup function for 'Window/Wall Ratio East in correlation to year of construction, based on the source data of the survey for the "German Building Typology developed by the "Institut für Wohnen und Umwelt", Darmstadt/Germany, 2011-2013'
import math
import numpy as np
import oeqLookuptable as oeq
def get(*xin):
l | _lookup = oeq.lookuptable(
[
1849,0,
1850,0,
1851,0,
1852,0,
1853,0,
1854,0,
1855,0,
1856,0,
1857,0,
1858,0,
1859,0,
1860,0,
1861,0,
1862,0,
1863,0,
1864,0,
1865,0,
1866,0,
1867,0,
1868,0,
1869,0,
1870,0,
1871,0,
1872,0,
1873,0,
1874,0,
1875,0,
1876,0,
1877,0,
1878,0,
1879,0,
1880,0,
1881,0,
1882,0,
1883,0,
1884,0,
1885,0,
1886,0,
1887,0,
1888,0,
1889,0,
1890,0,
1891,0,
1892,0,
1893,0,
1894,0,
1895,0,
1896,0,
1897,0,
1898,0,
1899,0,
1900,0,
1901,0,
1902,0,
1903,0,
1904,0,
1905,0,
1906,0,
1907,0,
1908,0,
1909,0,
1910,0,
1911,0,
1912,0,
1913,0,
1914,0,
1915,0,
1916,0,
1917,0,
1918,0,
1919,0,
1920,0,
1921,0,
1922,0,
1923,0,
1924,0,
1925,0,
1926,0,
1927,0,
1928,0,
1929,0,
1930,0,
1931,0,
1932,0,
1933,0,
1934,0,
1935,0,
1936,0,
1937,0,
1938,0,
1939,0,
1940,0,
1941,0,
1942,0,
1943,0,
1944,0,
1945,0,
1946,0,
1947,0,
1948,0,
1949,0,
1950,0,
1951,0,
1952,0,
1953,0,
1954,0,
1955,0,
1956,0,
1957,0,
1958,0.001,
1959,0.002,
1960,0.002,
1961,0,
1962,0,
1963,0,
1964,0,
1965,0,
1966,0.019,
1967,0.046,
1968,0.077,
1969,0.11,
1970,0.141,
1971,0.169,
1972,0.195,
1973,0.22,
1974,0.22,
1975,0.22,
1976,0.22,
1977,0.22,
1978,0.161,
1979,0.089,
1980,0.028,
1981,0,
1982,0.019,
1983,0.07,
1984,0.131,
1985,0.18,
1986,0.2,
1987,0.199,
1988,0.188,
1989,0.18,
1990,0.184,
1991,0.192,
1992,0.195,
1993,0.18,
1994,0.142,
1995,0.09,
1996,0.038,
1997,0,
1998,0,
1999,0,
2000,0.007,
2001,0.025,
2002,0.038,
2003,0.045,
2004,0.049,
2005,0.05,
2006,0.05,
2007,0.051,
2008,0.05,
2009,0.05,
2010,0.05,
2011,0.05,
2012,0.05,
2013,0.05,
2014,0.05,
2015,0.05,
2016,0.05,
2017,0.05,
2018,0.05,
2019,0.05,
2020,0.05,
2021,0.05])
return(l_lookup.lookup(xin))
| identifier_body | |
pipeline_hazard01.py | #The pipeline may not work correctly if there is both read and write access to the same memory 'xs0'
from polyphony import testbench
from polyphony import pipelined
def pipeline_hazard01(xs0, xs1, xs2):
for i in pipelined(range(len(xs0) - 1)):
xs1[i] = xs0[i]
xs0[i + 1] = xs2[i]
@testbench
def test():
|
test()
| data0 = [1, 2, 3]
data1 = [0, 0, 0]
data2 = [1, 2, 1]
pipeline_hazard01(data0, data1, data2)
assert 1 == data0[0]
assert 1 == data0[1]
assert 2 == data0[2]
assert 1 == data1[0]
assert 1 == data1[1]
assert 0 == data1[2] | identifier_body |
pipeline_hazard01.py | #The pipeline may not work correctly if there is both read and write access to the same memory 'xs0'
from polyphony import testbench
from polyphony import pipelined
def pipeline_hazard01(xs0, xs1, xs2):
for i in pipelined(range(len(xs0) - 1)):
xs1[i] = xs0[i]
xs0[i + 1] = xs2[i] |
@testbench
def test():
data0 = [1, 2, 3]
data1 = [0, 0, 0]
data2 = [1, 2, 1]
pipeline_hazard01(data0, data1, data2)
assert 1 == data0[0]
assert 1 == data0[1]
assert 2 == data0[2]
assert 1 == data1[0]
assert 1 == data1[1]
assert 0 == data1[2]
test() | random_line_split | |
pipeline_hazard01.py | #The pipeline may not work correctly if there is both read and write access to the same memory 'xs0'
from polyphony import testbench
from polyphony import pipelined
def pipeline_hazard01(xs0, xs1, xs2):
for i in pipelined(range(len(xs0) - 1)):
|
@testbench
def test():
data0 = [1, 2, 3]
data1 = [0, 0, 0]
data2 = [1, 2, 1]
pipeline_hazard01(data0, data1, data2)
assert 1 == data0[0]
assert 1 == data0[1]
assert 2 == data0[2]
assert 1 == data1[0]
assert 1 == data1[1]
assert 0 == data1[2]
test()
| xs1[i] = xs0[i]
xs0[i + 1] = xs2[i] | conditional_block |
pipeline_hazard01.py | #The pipeline may not work correctly if there is both read and write access to the same memory 'xs0'
from polyphony import testbench
from polyphony import pipelined
def | (xs0, xs1, xs2):
for i in pipelined(range(len(xs0) - 1)):
xs1[i] = xs0[i]
xs0[i + 1] = xs2[i]
@testbench
def test():
data0 = [1, 2, 3]
data1 = [0, 0, 0]
data2 = [1, 2, 1]
pipeline_hazard01(data0, data1, data2)
assert 1 == data0[0]
assert 1 == data0[1]
assert 2 == data0[2]
assert 1 == data1[0]
assert 1 == data1[1]
assert 0 == data1[2]
test()
| pipeline_hazard01 | identifier_name |
cstring.rs | use libc::c_char;
use std::ffi::CStr;
use std::str::Utf8Error;
use std::ffi::CString;
pub struct CStringUtils {}
impl CStringUtils {
pub fn c_str_to_string(cstr: *const c_char) -> Result<Option<String>, Utf8Error> {
if cstr.is_null() {
return Ok(None);
}
unsafe {
match CStr::from_ptr(cstr).to_str() {
Ok(str) => Ok(Some(str.to_string())),
Err(err) => Err(err)
}
}
}
pub fn c_str_to_str<'a>(cstr: *const c_char) -> Result<Option<&'a str>, Utf8Error> {
if cstr.is_null() {
return Ok(None);
}
unsafe {
match CStr::from_ptr(cstr).to_str() {
Ok(s) => Ok(Some(s)),
Err(err) => Err(err)
}
}
}
pub fn string_to_cstring(s: String) -> CString {
CString::new(s).unwrap() | }
//TODO DOCUMENT WHAT THIS DOES
macro_rules! check_useful_c_str {
($x:ident, $e:expr) => {
let $x = match CStringUtils::c_str_to_string($x) {
Ok(Some(val)) => val,
_ => return VcxError::from_msg($e, "Invalid pointer has been passed").into()
};
if $x.is_empty() {
return VcxError::from_msg($e, "Empty string has been passed").into()
}
}
}
macro_rules! check_useful_opt_c_str {
($x:ident, $e:expr) => {
let $x = match CStringUtils::c_str_to_string($x) {
Ok(opt_val) => opt_val,
Err(_) => return VcxError::from_msg($e, "Invalid pointer has been passed").into()
};
}
}
/// Vector helpers
macro_rules! check_useful_c_byte_array {
($ptr:ident, $len:expr, $err1:expr, $err2:expr) => {
if $ptr.is_null() {
return VcxError::from_msg($err1, "Invalid pointer has been passed").into()
}
if $len <= 0 {
return VcxError::from_msg($err2, "Array length must be greater than 0").into()
}
let $ptr = unsafe { $crate::std::slice::from_raw_parts($ptr, $len as usize) };
let $ptr = $ptr.to_vec();
}
}
//Returnable pointer is valid only before first vector modification
pub fn vec_to_pointer(v: &Vec<u8>) -> (*const u8, u32) {
let len = v.len() as u32;
(v.as_ptr() as *const u8, len)
} | } | random_line_split |
cstring.rs | use libc::c_char;
use std::ffi::CStr;
use std::str::Utf8Error;
use std::ffi::CString;
pub struct CStringUtils {}
impl CStringUtils {
pub fn c_str_to_string(cstr: *const c_char) -> Result<Option<String>, Utf8Error> {
if cstr.is_null() {
return Ok(None);
}
unsafe {
match CStr::from_ptr(cstr).to_str() {
Ok(str) => Ok(Some(str.to_string())),
Err(err) => Err(err)
}
}
}
pub fn c_str_to_str<'a>(cstr: *const c_char) -> Result<Option<&'a str>, Utf8Error> {
if cstr.is_null() {
return Ok(None);
}
unsafe {
match CStr::from_ptr(cstr).to_str() {
Ok(s) => Ok(Some(s)),
Err(err) => Err(err)
}
}
}
pub fn string_to_cstring(s: String) -> CString {
CString::new(s).unwrap()
}
}
//TODO DOCUMENT WHAT THIS DOES
macro_rules! check_useful_c_str {
($x:ident, $e:expr) => {
let $x = match CStringUtils::c_str_to_string($x) {
Ok(Some(val)) => val,
_ => return VcxError::from_msg($e, "Invalid pointer has been passed").into()
};
if $x.is_empty() {
return VcxError::from_msg($e, "Empty string has been passed").into()
}
}
}
macro_rules! check_useful_opt_c_str {
($x:ident, $e:expr) => {
let $x = match CStringUtils::c_str_to_string($x) {
Ok(opt_val) => opt_val,
Err(_) => return VcxError::from_msg($e, "Invalid pointer has been passed").into()
};
}
}
/// Vector helpers
macro_rules! check_useful_c_byte_array {
($ptr:ident, $len:expr, $err1:expr, $err2:expr) => {
if $ptr.is_null() {
return VcxError::from_msg($err1, "Invalid pointer has been passed").into()
}
if $len <= 0 {
return VcxError::from_msg($err2, "Array length must be greater than 0").into()
}
let $ptr = unsafe { $crate::std::slice::from_raw_parts($ptr, $len as usize) };
let $ptr = $ptr.to_vec();
}
}
//Returnable pointer is valid only before first vector modification
pub fn vec_to_pointer(v: &Vec<u8>) -> (*const u8, u32) | {
let len = v.len() as u32;
(v.as_ptr() as *const u8, len)
} | identifier_body | |
cstring.rs | use libc::c_char;
use std::ffi::CStr;
use std::str::Utf8Error;
use std::ffi::CString;
pub struct CStringUtils {}
impl CStringUtils {
pub fn c_str_to_string(cstr: *const c_char) -> Result<Option<String>, Utf8Error> {
if cstr.is_null() {
return Ok(None);
}
unsafe {
match CStr::from_ptr(cstr).to_str() {
Ok(str) => Ok(Some(str.to_string())),
Err(err) => Err(err)
}
}
}
pub fn c_str_to_str<'a>(cstr: *const c_char) -> Result<Option<&'a str>, Utf8Error> {
if cstr.is_null() {
return Ok(None);
}
unsafe {
match CStr::from_ptr(cstr).to_str() {
Ok(s) => Ok(Some(s)),
Err(err) => Err(err)
}
}
}
pub fn | (s: String) -> CString {
CString::new(s).unwrap()
}
}
//TODO DOCUMENT WHAT THIS DOES
macro_rules! check_useful_c_str {
($x:ident, $e:expr) => {
let $x = match CStringUtils::c_str_to_string($x) {
Ok(Some(val)) => val,
_ => return VcxError::from_msg($e, "Invalid pointer has been passed").into()
};
if $x.is_empty() {
return VcxError::from_msg($e, "Empty string has been passed").into()
}
}
}
macro_rules! check_useful_opt_c_str {
($x:ident, $e:expr) => {
let $x = match CStringUtils::c_str_to_string($x) {
Ok(opt_val) => opt_val,
Err(_) => return VcxError::from_msg($e, "Invalid pointer has been passed").into()
};
}
}
/// Vector helpers
macro_rules! check_useful_c_byte_array {
($ptr:ident, $len:expr, $err1:expr, $err2:expr) => {
if $ptr.is_null() {
return VcxError::from_msg($err1, "Invalid pointer has been passed").into()
}
if $len <= 0 {
return VcxError::from_msg($err2, "Array length must be greater than 0").into()
}
let $ptr = unsafe { $crate::std::slice::from_raw_parts($ptr, $len as usize) };
let $ptr = $ptr.to_vec();
}
}
//Returnable pointer is valid only before first vector modification
pub fn vec_to_pointer(v: &Vec<u8>) -> (*const u8, u32) {
let len = v.len() as u32;
(v.as_ptr() as *const u8, len)
}
| string_to_cstring | identifier_name |
forward_ref.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ForwardRefFn, Inject, ReflectiveInjector, forwardRef, resolveForwardRef} from '@angular/core';
// #docregion forward_ref_fn
var ref = forwardRef(() => Lock);
// #enddocregion
// #docregion forward_ref
class Door {
lock: Lock;
| (@Inject(forwardRef(() => Lock)) lock: Lock) { this.lock = lock; }
}
// Only at this point Lock is defined.
class Lock {}
var injector = ReflectiveInjector.resolveAndCreate([Door, Lock]);
var door = injector.get(Door);
expect(door instanceof Door).toBe(true);
expect(door.lock instanceof Lock).toBe(true);
// #enddocregion
// #docregion resolve_forward_ref
ref = forwardRef(() => 'refValue');
expect(resolveForwardRef(ref)).toEqual('refValue');
expect(resolveForwardRef('regularValue')).toEqual('regularValue');
// #enddocregion
| constructor | identifier_name |
forward_ref.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ForwardRefFn, Inject, ReflectiveInjector, forwardRef, resolveForwardRef} from '@angular/core';
// #docregion forward_ref_fn
var ref = forwardRef(() => Lock); |
// #docregion forward_ref
class Door {
lock: Lock;
constructor(@Inject(forwardRef(() => Lock)) lock: Lock) { this.lock = lock; }
}
// Only at this point Lock is defined.
class Lock {}
var injector = ReflectiveInjector.resolveAndCreate([Door, Lock]);
var door = injector.get(Door);
expect(door instanceof Door).toBe(true);
expect(door.lock instanceof Lock).toBe(true);
// #enddocregion
// #docregion resolve_forward_ref
ref = forwardRef(() => 'refValue');
expect(resolveForwardRef(ref)).toEqual('refValue');
expect(resolveForwardRef('regularValue')).toEqual('regularValue');
// #enddocregion | // #enddocregion | random_line_split |
gdpr.js | var pause = undefined;
var play = undefined;
var audio = undefined;
var tapesound = undefined;
// var staticsound = undefined;
function endstatic()
{
document.body.style.backgroundImage = "none";
document.body.style.backgroundColor = "white";
//staticsound.pause();
}
function | ()
{
audio.play();
}
function startstyle()
{
rude.style.display = "none";
curvebox.style.display = "none";
spun.style.display = null;
cover.classList.add("wrapper");
}
function startsound()
{
tapesound.play();
}
function delayedlaw()
{
lawbreaker.style.display = null;
}
function onplay(e)
{
var curvebox = document.getElementById("curvebox");
var rude = document.getElementById("rude");
var spun = document.getElementById("spun");
var cover = document.getElementById("cover");
var lawbreaker = document.getElementById("lawbreaker");
curvebox.classList.add("getmeinofhere");
rude.classList.add("getmeoutofhere");
rude.style.display = null;
setTimeout(startmusic, 1600);
setTimeout(startstyle, 2000);
setTimeout(delayedlaw, 4800);
setTimeout(endstatic, 2000);
}
function reset()
{
audio.currentTime = 0;
audio.pause();
tapesound.currentTime = 0;
tapesound.pause();
// staticsound.play();
var string = "/img/tiled static.gif";
document.body.style.backgroundImage = "url('" + string + "')";
document.body.style.backgroundColor = "white";
}
window.onload = function()
{
var button = document.getElementById("OHGODWORK");
button.onclick = onplay;
console.log("load successed");
tapesound = document.createElement("audio");
tapesound.src = "/tapefeed.mp3";
tapesound.pause();
audio = document.createElement("audio");
audio.src = " https://oman.imjake.me/LawBreaker.mp3 ";
audio.pause();
audio.addEventListener('ended',function(){
reset();
},false);
}
| startmusic | identifier_name |
gdpr.js | var pause = undefined;
var play = undefined;
var audio = undefined;
var tapesound = undefined;
// var staticsound = undefined;
function endstatic()
{
document.body.style.backgroundImage = "none";
document.body.style.backgroundColor = "white";
//staticsound.pause();
}
function startmusic()
{
audio.play();
}
function startstyle()
{
rude.style.display = "none";
curvebox.style.display = "none";
spun.style.display = null;
cover.classList.add("wrapper");
}
function startsound()
|
function delayedlaw()
{
lawbreaker.style.display = null;
}
function onplay(e)
{
var curvebox = document.getElementById("curvebox");
var rude = document.getElementById("rude");
var spun = document.getElementById("spun");
var cover = document.getElementById("cover");
var lawbreaker = document.getElementById("lawbreaker");
curvebox.classList.add("getmeinofhere");
rude.classList.add("getmeoutofhere");
rude.style.display = null;
setTimeout(startmusic, 1600);
setTimeout(startstyle, 2000);
setTimeout(delayedlaw, 4800);
setTimeout(endstatic, 2000);
}
function reset()
{
audio.currentTime = 0;
audio.pause();
tapesound.currentTime = 0;
tapesound.pause();
// staticsound.play();
var string = "/img/tiled static.gif";
document.body.style.backgroundImage = "url('" + string + "')";
document.body.style.backgroundColor = "white";
}
window.onload = function()
{
var button = document.getElementById("OHGODWORK");
button.onclick = onplay;
console.log("load successed");
tapesound = document.createElement("audio");
tapesound.src = "/tapefeed.mp3";
tapesound.pause();
audio = document.createElement("audio");
audio.src = " https://oman.imjake.me/LawBreaker.mp3 ";
audio.pause();
audio.addEventListener('ended',function(){
reset();
},false);
}
| {
tapesound.play();
} | identifier_body |
gdpr.js | var pause = undefined;
var play = undefined;
var audio = undefined;
var tapesound = undefined;
// var staticsound = undefined;
function endstatic()
{
document.body.style.backgroundImage = "none";
document.body.style.backgroundColor = "white";
//staticsound.pause();
}
function startmusic()
{
audio.play();
}
function startstyle()
{
rude.style.display = "none";
curvebox.style.display = "none";
spun.style.display = null;
cover.classList.add("wrapper");
}
function startsound()
{
tapesound.play();
}
function delayedlaw()
{
lawbreaker.style.display = null;
}
function onplay(e)
{
var curvebox = document.getElementById("curvebox");
var rude = document.getElementById("rude");
var spun = document.getElementById("spun");
var cover = document.getElementById("cover");
var lawbreaker = document.getElementById("lawbreaker");
curvebox.classList.add("getmeinofhere");
rude.classList.add("getmeoutofhere");
rude.style.display = null;
setTimeout(startmusic, 1600);
setTimeout(startstyle, 2000);
setTimeout(delayedlaw, 4800);
setTimeout(endstatic, 2000);
}
function reset()
{
audio.currentTime = 0;
audio.pause();
tapesound.currentTime = 0;
tapesound.pause();
// staticsound.play();
var string = "/img/tiled static.gif";
document.body.style.backgroundImage = "url('" + string + "')";
document.body.style.backgroundColor = "white";
}
window.onload = function() | tapesound = document.createElement("audio");
tapesound.src = "/tapefeed.mp3";
tapesound.pause();
audio = document.createElement("audio");
audio.src = " https://oman.imjake.me/LawBreaker.mp3 ";
audio.pause();
audio.addEventListener('ended',function(){
reset();
},false);
} | {
var button = document.getElementById("OHGODWORK");
button.onclick = onplay;
console.log("load successed"); | random_line_split |
connection_status.rs | use crate::{
auth::{Credentials, SASLMechanism},
Connection, ConnectionProperties, PromiseResolver,
};
use parking_lot::Mutex;
use std::{fmt, sync::Arc};
#[derive(Clone, Default)]
pub struct ConnectionStatus(Arc<Mutex<Inner>>);
impl ConnectionStatus {
pub fn state(&self) -> ConnectionState {
self.0.lock().state.clone()
}
pub(crate) fn set_state(&self, state: ConnectionState) {
self.0.lock().state = state;
}
pub(crate) fn connection_step(&self) -> Option<ConnectionStep> {
self.0.lock().connection_step.take()
}
pub(crate) fn set_connection_step(&self, connection_step: ConnectionStep) {
self.0.lock().connection_step = Some(connection_step);
}
pub(crate) fn connection_resolver(&self) -> Option<PromiseResolver<Connection>> {
let resolver = self.0.lock().connection_resolver();
// We carry the Connection here to drop the lock() above before dropping the Connection
resolver.map(|(resolver, _connection)| resolver)
}
pub fn vhost(&self) -> String {
self.0.lock().vhost.clone()
}
pub(crate) fn set_vhost(&self, vhost: &str) {
self.0.lock().vhost = vhost.into();
}
pub fn username(&self) -> String {
self.0.lock().username.clone()
}
pub(crate) fn set_username(&self, username: &str) {
self.0.lock().username = username.into();
}
pub(crate) fn block(&self) {
self.0.lock().blocked = true;
}
pub(crate) fn unblock(&self) {
self.0.lock().blocked = false;
}
pub fn blocked(&self) -> bool {
self.0.lock().blocked
}
pub fn connected(&self) -> bool {
self.0.lock().state == ConnectionState::Connected
}
pub fn closing(&self) -> bool {
self.0.lock().state == ConnectionState::Closing
}
pub fn closed(&self) -> bool {
self.0.lock().state == ConnectionState::Closed
}
pub fn errored(&self) -> bool {
self.0.lock().state == ConnectionState::Error
} | [ConnectionState::Connecting, ConnectionState::Connected].contains(&self.0.lock().state)
}
}
pub(crate) enum ConnectionStep {
ProtocolHeader(
PromiseResolver<Connection>,
Connection,
Credentials,
SASLMechanism,
ConnectionProperties,
),
StartOk(PromiseResolver<Connection>, Connection, Credentials),
Open(PromiseResolver<Connection>),
}
#[derive(Clone, Debug, PartialEq)]
pub enum ConnectionState {
Initial,
Connecting,
Connected,
Closing,
Closed,
Error,
}
impl Default for ConnectionState {
fn default() -> Self {
ConnectionState::Initial
}
}
impl fmt::Debug for ConnectionStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut debug = f.debug_struct("ConnectionStatus");
if let Some(inner) = self.0.try_lock() {
debug
.field("state", &inner.state)
.field("vhost", &inner.vhost)
.field("username", &inner.username)
.field("blocked", &inner.blocked);
}
debug.finish()
}
}
struct Inner {
connection_step: Option<ConnectionStep>,
state: ConnectionState,
vhost: String,
username: String,
blocked: bool,
}
impl Default for Inner {
fn default() -> Self {
Self {
connection_step: None,
state: ConnectionState::default(),
vhost: "/".into(),
username: "guest".into(),
blocked: false,
}
}
}
impl Inner {
fn connection_resolver(&mut self) -> Option<(PromiseResolver<Connection>, Option<Connection>)> {
if let ConnectionState::Connecting = self.state {
self.connection_step
.take()
.map(|connection_step| match connection_step {
ConnectionStep::ProtocolHeader(resolver, connection, ..) => {
(resolver, Some(connection))
}
ConnectionStep::StartOk(resolver, connection, ..) => {
(resolver, Some(connection))
}
ConnectionStep::Open(resolver, ..) => (resolver, None),
})
} else {
None
}
}
} |
pub(crate) fn auto_close(&self) -> bool { | random_line_split |
connection_status.rs | use crate::{
auth::{Credentials, SASLMechanism},
Connection, ConnectionProperties, PromiseResolver,
};
use parking_lot::Mutex;
use std::{fmt, sync::Arc};
#[derive(Clone, Default)]
pub struct ConnectionStatus(Arc<Mutex<Inner>>);
impl ConnectionStatus {
pub fn state(&self) -> ConnectionState {
self.0.lock().state.clone()
}
pub(crate) fn set_state(&self, state: ConnectionState) {
self.0.lock().state = state;
}
pub(crate) fn connection_step(&self) -> Option<ConnectionStep> {
self.0.lock().connection_step.take()
}
pub(crate) fn set_connection_step(&self, connection_step: ConnectionStep) {
self.0.lock().connection_step = Some(connection_step);
}
pub(crate) fn connection_resolver(&self) -> Option<PromiseResolver<Connection>> {
let resolver = self.0.lock().connection_resolver();
// We carry the Connection here to drop the lock() above before dropping the Connection
resolver.map(|(resolver, _connection)| resolver)
}
pub fn vhost(&self) -> String {
self.0.lock().vhost.clone()
}
pub(crate) fn set_vhost(&self, vhost: &str) {
self.0.lock().vhost = vhost.into();
}
pub fn username(&self) -> String {
self.0.lock().username.clone()
}
pub(crate) fn set_username(&self, username: &str) {
self.0.lock().username = username.into();
}
pub(crate) fn block(&self) {
self.0.lock().blocked = true;
}
pub(crate) fn unblock(&self) {
self.0.lock().blocked = false;
}
pub fn blocked(&self) -> bool {
self.0.lock().blocked
}
pub fn connected(&self) -> bool {
self.0.lock().state == ConnectionState::Connected
}
pub fn closing(&self) -> bool {
self.0.lock().state == ConnectionState::Closing
}
pub fn closed(&self) -> bool {
self.0.lock().state == ConnectionState::Closed
}
pub fn | (&self) -> bool {
self.0.lock().state == ConnectionState::Error
}
pub(crate) fn auto_close(&self) -> bool {
[ConnectionState::Connecting, ConnectionState::Connected].contains(&self.0.lock().state)
}
}
pub(crate) enum ConnectionStep {
ProtocolHeader(
PromiseResolver<Connection>,
Connection,
Credentials,
SASLMechanism,
ConnectionProperties,
),
StartOk(PromiseResolver<Connection>, Connection, Credentials),
Open(PromiseResolver<Connection>),
}
#[derive(Clone, Debug, PartialEq)]
pub enum ConnectionState {
Initial,
Connecting,
Connected,
Closing,
Closed,
Error,
}
impl Default for ConnectionState {
fn default() -> Self {
ConnectionState::Initial
}
}
impl fmt::Debug for ConnectionStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut debug = f.debug_struct("ConnectionStatus");
if let Some(inner) = self.0.try_lock() {
debug
.field("state", &inner.state)
.field("vhost", &inner.vhost)
.field("username", &inner.username)
.field("blocked", &inner.blocked);
}
debug.finish()
}
}
struct Inner {
connection_step: Option<ConnectionStep>,
state: ConnectionState,
vhost: String,
username: String,
blocked: bool,
}
impl Default for Inner {
fn default() -> Self {
Self {
connection_step: None,
state: ConnectionState::default(),
vhost: "/".into(),
username: "guest".into(),
blocked: false,
}
}
}
impl Inner {
fn connection_resolver(&mut self) -> Option<(PromiseResolver<Connection>, Option<Connection>)> {
if let ConnectionState::Connecting = self.state {
self.connection_step
.take()
.map(|connection_step| match connection_step {
ConnectionStep::ProtocolHeader(resolver, connection, ..) => {
(resolver, Some(connection))
}
ConnectionStep::StartOk(resolver, connection, ..) => {
(resolver, Some(connection))
}
ConnectionStep::Open(resolver, ..) => (resolver, None),
})
} else {
None
}
}
}
| errored | identifier_name |
connection_status.rs | use crate::{
auth::{Credentials, SASLMechanism},
Connection, ConnectionProperties, PromiseResolver,
};
use parking_lot::Mutex;
use std::{fmt, sync::Arc};
#[derive(Clone, Default)]
pub struct ConnectionStatus(Arc<Mutex<Inner>>);
impl ConnectionStatus {
pub fn state(&self) -> ConnectionState {
self.0.lock().state.clone()
}
pub(crate) fn set_state(&self, state: ConnectionState) {
self.0.lock().state = state;
}
pub(crate) fn connection_step(&self) -> Option<ConnectionStep> {
self.0.lock().connection_step.take()
}
pub(crate) fn set_connection_step(&self, connection_step: ConnectionStep) {
self.0.lock().connection_step = Some(connection_step);
}
pub(crate) fn connection_resolver(&self) -> Option<PromiseResolver<Connection>> {
let resolver = self.0.lock().connection_resolver();
// We carry the Connection here to drop the lock() above before dropping the Connection
resolver.map(|(resolver, _connection)| resolver)
}
pub fn vhost(&self) -> String {
self.0.lock().vhost.clone()
}
pub(crate) fn set_vhost(&self, vhost: &str) {
self.0.lock().vhost = vhost.into();
}
pub fn username(&self) -> String {
self.0.lock().username.clone()
}
pub(crate) fn set_username(&self, username: &str) {
self.0.lock().username = username.into();
}
pub(crate) fn block(&self) {
self.0.lock().blocked = true;
}
pub(crate) fn unblock(&self) {
self.0.lock().blocked = false;
}
pub fn blocked(&self) -> bool {
self.0.lock().blocked
}
pub fn connected(&self) -> bool {
self.0.lock().state == ConnectionState::Connected
}
pub fn closing(&self) -> bool {
self.0.lock().state == ConnectionState::Closing
}
pub fn closed(&self) -> bool {
self.0.lock().state == ConnectionState::Closed
}
pub fn errored(&self) -> bool {
self.0.lock().state == ConnectionState::Error
}
pub(crate) fn auto_close(&self) -> bool {
[ConnectionState::Connecting, ConnectionState::Connected].contains(&self.0.lock().state)
}
}
pub(crate) enum ConnectionStep {
ProtocolHeader(
PromiseResolver<Connection>,
Connection,
Credentials,
SASLMechanism,
ConnectionProperties,
),
StartOk(PromiseResolver<Connection>, Connection, Credentials),
Open(PromiseResolver<Connection>),
}
#[derive(Clone, Debug, PartialEq)]
pub enum ConnectionState {
Initial,
Connecting,
Connected,
Closing,
Closed,
Error,
}
impl Default for ConnectionState {
fn default() -> Self {
ConnectionState::Initial
}
}
impl fmt::Debug for ConnectionStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result |
}
struct Inner {
connection_step: Option<ConnectionStep>,
state: ConnectionState,
vhost: String,
username: String,
blocked: bool,
}
impl Default for Inner {
fn default() -> Self {
Self {
connection_step: None,
state: ConnectionState::default(),
vhost: "/".into(),
username: "guest".into(),
blocked: false,
}
}
}
impl Inner {
fn connection_resolver(&mut self) -> Option<(PromiseResolver<Connection>, Option<Connection>)> {
if let ConnectionState::Connecting = self.state {
self.connection_step
.take()
.map(|connection_step| match connection_step {
ConnectionStep::ProtocolHeader(resolver, connection, ..) => {
(resolver, Some(connection))
}
ConnectionStep::StartOk(resolver, connection, ..) => {
(resolver, Some(connection))
}
ConnectionStep::Open(resolver, ..) => (resolver, None),
})
} else {
None
}
}
}
| {
let mut debug = f.debug_struct("ConnectionStatus");
if let Some(inner) = self.0.try_lock() {
debug
.field("state", &inner.state)
.field("vhost", &inner.vhost)
.field("username", &inner.username)
.field("blocked", &inner.blocked);
}
debug.finish()
} | identifier_body |
jquery.waituntilexists.js | ;(function ($, window) {
var intervals = {};
var removeListener = function(selector) {
if (intervals[selector]) {
window.clearInterval(intervals[selector]);
intervals[selector] = null;
}
};
var found = 'waitUntilExists.found';
/**
* @function
* @property {object} jQuery plugin which runs handler function once specified
* element is inserted into the DOM
* @param {function|string} handler
* A function to execute at the time when the element is inserted or
* string "remove" to remove the listener from the given selector
* @param {bool} shouldRunHandlerOnce
* Optional: if true, handler is unbound after its first invocation
* @example jQuery(selector).waitUntilExists(function);
*/
$.fn.waitUntilExists = function(handler, shouldRunHandlerOnce, isChild) {
var selector = this.selector;
var $this = $(selector);
var $elements = $this.not(function() { return $(this).data(found); });
if (handler === 'remove') {
// Hijack and remove interval immediately if the code requests
removeListener(selector);
}
else |
return $this;
};
}(jQuery, window)); | {
// Run the handler on all found elements and mark as found
$elements.each(handler).data(found, true);
if (shouldRunHandlerOnce && $this.length) {
// Element was found, implying the handler already ran for all
// matched elements
removeListener(selector);
}
else if (!isChild) {
// If this is a recurring search or if the target has not yet been
// found, create an interval to continue searching for the target
intervals[selector] = window.setInterval(function () {
$this.waitUntilExists(handler, shouldRunHandlerOnce, true);
}, 500);
}
} | conditional_block |
jquery.waituntilexists.js | ;(function ($, window) {
var intervals = {};
var removeListener = function(selector) {
if (intervals[selector]) {
window.clearInterval(intervals[selector]);
intervals[selector] = null;
}
};
var found = 'waitUntilExists.found';
/**
* @function
* @property {object} jQuery plugin which runs handler function once specified
* element is inserted into the DOM
* @param {function|string} handler
* A function to execute at the time when the element is inserted or
* string "remove" to remove the listener from the given selector
* @param {bool} shouldRunHandlerOnce
* Optional: if true, handler is unbound after its first invocation
* @example jQuery(selector).waitUntilExists(function);
*/
$.fn.waitUntilExists = function(handler, shouldRunHandlerOnce, isChild) {
var selector = this.selector;
var $this = $(selector);
var $elements = $this.not(function() { return $(this).data(found); });
if (handler === 'remove') {
// Hijack and remove interval immediately if the code requests
removeListener(selector);
}
else {
// Run the handler on all found elements and mark as found
$elements.each(handler).data(found, true);
if (shouldRunHandlerOnce && $this.length) {
// Element was found, implying the handler already ran for all
// matched elements
removeListener(selector);
}
else if (!isChild) {
// If this is a recurring search or if the target has not yet been
// found, create an interval to continue searching for the target
intervals[selector] = window.setInterval(function () {
$this.waitUntilExists(handler, shouldRunHandlerOnce, true);
}, 500);
}
}
return $this; | }(jQuery, window)); | };
| random_line_split |
ToLong-001.js | /* ***** BEGIN LICENSE BLOCK *****
*
* Copyright (C) 1998 Netscape Communications Corporation.
* Copyright (C) 2010 Apple Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
* ***** END LICENSE BLOCK ***** */
gTestfile = 'ToLong-001.js';
/**
* Preferred Argument Conversion.
*
* Passing a JavaScript boolean to a Java method should prefer to call
* a Java method of the same name that expects a Java boolean.
*
*/
var SECTION = "Preferred argument conversion: JavaScript Object to Long";
var VERSION = "1_4";
var TITLE = "LiveConnect 3.0 JavaScript to Java Data Type Conversion " +
SECTION;
startTest();
var TEST_CLASS = applet.createQAObject("com.netscape.javascript.qa.lc3.jsobject.JSObject_006");
function MyObject( value ) {
this.value = value;
this.valueOf = new Function( "return this.value" );
}
function | () {
return;
}
MyFunction.valueOf = new Function( "return 6060842" );
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new String() ) +''",
"'LONG'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new Boolean() ) +''",
"'LONG'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new Number() ) +''",
"'LONG'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new Date(0) ) +''",
"'LONG'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new MyObject(999) ) +''",
"'LONG'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( MyFunction ) +''",
"'LONG'");
| MyFunction | identifier_name |
ToLong-001.js | /* ***** BEGIN LICENSE BLOCK *****
*
* Copyright (C) 1998 Netscape Communications Corporation.
* Copyright (C) 2010 Apple Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
* ***** END LICENSE BLOCK ***** */
gTestfile = 'ToLong-001.js';
/**
* Preferred Argument Conversion.
*
* Passing a JavaScript boolean to a Java method should prefer to call
* a Java method of the same name that expects a Java boolean.
*
*/
var SECTION = "Preferred argument conversion: JavaScript Object to Long";
var VERSION = "1_4";
var TITLE = "LiveConnect 3.0 JavaScript to Java Data Type Conversion " +
SECTION;
startTest();
var TEST_CLASS = applet.createQAObject("com.netscape.javascript.qa.lc3.jsobject.JSObject_006");
function MyObject( value ) {
this.value = value;
this.valueOf = new Function( "return this.value" );
}
function MyFunction() |
MyFunction.valueOf = new Function( "return 6060842" );
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new String() ) +''",
"'LONG'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new Boolean() ) +''",
"'LONG'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new Number() ) +''",
"'LONG'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new Date(0) ) +''",
"'LONG'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new MyObject(999) ) +''",
"'LONG'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( MyFunction ) +''",
"'LONG'");
| {
return;
} | identifier_body |
ToLong-001.js | /* ***** BEGIN LICENSE BLOCK *****
*
* Copyright (C) 1998 Netscape Communications Corporation.
* Copyright (C) 2010 Apple Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
* ***** END LICENSE BLOCK ***** */ | /**
* Preferred Argument Conversion.
*
* Passing a JavaScript boolean to a Java method should prefer to call
* a Java method of the same name that expects a Java boolean.
*
*/
var SECTION = "Preferred argument conversion: JavaScript Object to Long";
var VERSION = "1_4";
var TITLE = "LiveConnect 3.0 JavaScript to Java Data Type Conversion " +
SECTION;
startTest();
var TEST_CLASS = applet.createQAObject("com.netscape.javascript.qa.lc3.jsobject.JSObject_006");
function MyObject( value ) {
this.value = value;
this.valueOf = new Function( "return this.value" );
}
function MyFunction() {
return;
}
MyFunction.valueOf = new Function( "return 6060842" );
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new String() ) +''",
"'LONG'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new Boolean() ) +''",
"'LONG'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new Number() ) +''",
"'LONG'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new Date(0) ) +''",
"'LONG'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( new MyObject(999) ) +''",
"'LONG'");
shouldBeWithErrorCheck(
"TEST_CLASS.ambiguous( MyFunction ) +''",
"'LONG'"); |
gTestfile = 'ToLong-001.js';
| random_line_split |
dice.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import string
import random
# Simple recursive descent parser for dice rolls, e.g. '3d6+1d8+4'.
#
# roll := die {('+' | '-') die} ('+' | '-') modifier
# die := number 'd' number
# modifier := number
class StringBuf(object):
def __init__(self, s):
self.s = s
self.pos = 0
def peek(self):
return self.s[self.pos]
def getc(self):
c = self.peek()
self.pos += 1
return c
def ungetc(self):
self.pos -= 1
def tell(self):
|
class Symbol(object):
NUMBER = 0
D = 1
PLUS = 2
MINUS = 3
def __init__(self, type_, pos, value)
def next_symbol(s):
c = s.getc()
while c in string.whitespace:
c = s.getc()
if c in string.digits:
# start of a number
literal = c
c = s.getc()
while c in string.digits:
literal += c
c = s.getc()
s.ungetc()
sym = (Symbol.NUMBER,
elif c == 'd':
# die indicator
pass
elif c == '+':
# plus sign
pass
elif c == '-':
# minus sign
pass
else:
# unrecognized input
raise ValueError('Syntax error at position ' + s.tell())
return ()
| return self.pos | identifier_body |
dice.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import string
import random
# Simple recursive descent parser for dice rolls, e.g. '3d6+1d8+4'.
#
# roll := die {('+' | '-') die} ('+' | '-') modifier
# die := number 'd' number | self.pos = 0
def peek(self):
return self.s[self.pos]
def getc(self):
c = self.peek()
self.pos += 1
return c
def ungetc(self):
self.pos -= 1
def tell(self):
return self.pos
class Symbol(object):
NUMBER = 0
D = 1
PLUS = 2
MINUS = 3
def __init__(self, type_, pos, value)
def next_symbol(s):
c = s.getc()
while c in string.whitespace:
c = s.getc()
if c in string.digits:
# start of a number
literal = c
c = s.getc()
while c in string.digits:
literal += c
c = s.getc()
s.ungetc()
sym = (Symbol.NUMBER,
elif c == 'd':
# die indicator
pass
elif c == '+':
# plus sign
pass
elif c == '-':
# minus sign
pass
else:
# unrecognized input
raise ValueError('Syntax error at position ' + s.tell())
return () | # modifier := number
class StringBuf(object):
def __init__(self, s):
self.s = s | random_line_split |
dice.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import string
import random
# Simple recursive descent parser for dice rolls, e.g. '3d6+1d8+4'.
#
# roll := die {('+' | '-') die} ('+' | '-') modifier
# die := number 'd' number
# modifier := number
class | (object):
def __init__(self, s):
self.s = s
self.pos = 0
def peek(self):
return self.s[self.pos]
def getc(self):
c = self.peek()
self.pos += 1
return c
def ungetc(self):
self.pos -= 1
def tell(self):
return self.pos
class Symbol(object):
NUMBER = 0
D = 1
PLUS = 2
MINUS = 3
def __init__(self, type_, pos, value)
def next_symbol(s):
c = s.getc()
while c in string.whitespace:
c = s.getc()
if c in string.digits:
# start of a number
literal = c
c = s.getc()
while c in string.digits:
literal += c
c = s.getc()
s.ungetc()
sym = (Symbol.NUMBER,
elif c == 'd':
# die indicator
pass
elif c == '+':
# plus sign
pass
elif c == '-':
# minus sign
pass
else:
# unrecognized input
raise ValueError('Syntax error at position ' + s.tell())
return ()
| StringBuf | identifier_name |
dice.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import string
import random
# Simple recursive descent parser for dice rolls, e.g. '3d6+1d8+4'.
#
# roll := die {('+' | '-') die} ('+' | '-') modifier
# die := number 'd' number
# modifier := number
class StringBuf(object):
def __init__(self, s):
self.s = s
self.pos = 0
def peek(self):
return self.s[self.pos]
def getc(self):
c = self.peek()
self.pos += 1
return c
def ungetc(self):
self.pos -= 1
def tell(self):
return self.pos
class Symbol(object):
NUMBER = 0
D = 1
PLUS = 2
MINUS = 3
def __init__(self, type_, pos, value)
def next_symbol(s):
c = s.getc()
while c in string.whitespace:
c = s.getc()
if c in string.digits:
# start of a number
literal = c
c = s.getc()
while c in string.digits:
literal += c
c = s.getc()
s.ungetc()
sym = (Symbol.NUMBER,
elif c == 'd':
# die indicator
pass
elif c == '+':
# plus sign
pass
elif c == '-':
# minus sign
pass
else:
# unrecognized input
|
return ()
| raise ValueError('Syntax error at position ' + s.tell()) | conditional_block |
time.rs | //! Time support
use std::cmp::Ordering;
use std::ops::{Add, Sub};
use std::ptr;
use libc::timespec as c_timespec;
use libc::{c_int, c_long, time_t};
use remacs_lib::current_timespec;
use remacs_macros::lisp_fn;
use crate::{
lisp::LispObject,
numbers::MOST_NEGATIVE_FIXNUM,
remacs_sys::{lisp_time, EmacsDouble, EmacsInt},
};
const LO_TIME_BITS: i32 = 16;
pub type LispTime = lisp_time;
impl LispTime {
pub fn into_vec(self, nelem: usize) -> Vec<EmacsInt> {
let mut v = Vec::with_capacity(nelem);
if nelem >= 2 {
v.push(self.hi);
v.push(self.lo.into());
}
if nelem >= 3 {
v.push(self.us.into());
}
if nelem > 3 {
v.push(self.ps.into());
}
v
}
}
impl PartialEq for LispTime {
fn eq(&self, other: &Self) -> bool {
self.hi == other.hi && self.lo == other.lo && self.us == other.us && self.ps == other.ps
}
}
impl Eq for LispTime {}
impl PartialOrd for LispTime {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for LispTime {
fn cmp(&self, other: &Self) -> Ordering {
self.hi
.cmp(&other.hi)
.then_with(|| self.lo.cmp(&other.lo))
.then_with(|| self.us.cmp(&other.us))
.then_with(|| self.ps.cmp(&other.ps))
}
}
#[allow(clippy::suspicious_arithmetic_impl)]
impl Add for LispTime {
type Output = Self;
fn add(self, other: Self) -> Self {
let mut hi = self.hi + other.hi;
let mut lo = self.lo + other.lo;
let mut us = self.us + other.us;
let mut ps = self.ps + other.ps;
if ps >= 1_000_000 {
us += 1;
ps -= 1_000_000;
}
if us >= 1_000_000 {
lo += 1;
us -= 1_000_000;
}
if lo >= 1 << LO_TIME_BITS {
hi += 1;
lo -= 1 << LO_TIME_BITS;
}
Self { hi, lo, us, ps }
}
}
#[allow(clippy::suspicious_arithmetic_impl)]
impl Sub for LispTime {
type Output = Self;
fn sub(self, other: Self) -> Self {
let mut hi = self.hi - other.hi;
let mut lo = self.lo - other.lo;
let mut us = self.us - other.us;
let mut ps = self.ps - other.ps;
if ps < 0 {
us -= 1;
ps += 1_000_000;
}
if us < 0 {
lo -= 1;
us += 1_000_000;
}
if hi < 0 {
hi -= 1;
lo += 1 << LO_TIME_BITS;
}
Self { hi, lo, us, ps }
}
}
/// Return the upper part of the time T (everything but the bottom 16 bits).
#[no_mangle]
pub extern "C" fn hi_time(t: time_t) -> EmacsInt {
let hi = t >> LO_TIME_BITS;
if LispObject::fixnum_overflow(hi) {
time_overflow();
}
hi
}
/// Return the bottom bits of the time T.
#[no_mangle]
pub extern "C" fn lo_time(t: time_t) -> i32 {
(t & ((1 << LO_TIME_BITS) - 1)) as i32
}
/// Make a Lisp list that represents the Emacs time T. T may be an
/// invalid time, with a slightly negative `tv_nsec` value such as
/// `UNKNOWN_MODTIME_NSECS`; in that case, the Lisp list contains a
/// correspondingly negative picosecond count.
#[no_mangle]
pub extern "C" fn make_lisp_time(t: c_timespec) -> LispObject {
make_lisp_time_1(t)
}
fn make_lisp_time_1(t: c_timespec) -> LispObject {
let s = t.tv_sec;
let ns = t.tv_nsec;
list!(hi_time(s), lo_time(s), ns / 1_000, ns % 1_000 * 1_000)
}
/// Decode a Lisp list `SPECIFIED_TIME` that represents a time.
/// Set `*PHIGH`, `*PLOW`, `*PUSEC`, `*PPSEC` to its parts; do not check their values.
/// Return 2, 3, or 4 to indicate the effective length of `SPECIFIED_TIME`
/// if successful, 0 if unsuccessful.
#[no_mangle]
pub unsafe extern "C" fn disassemble_lisp_time(
specified_time: LispObject,
phigh: *mut LispObject,
plow: *mut LispObject,
pusec: *mut LispObject,
ppsec: *mut LispObject,
) -> c_int {
let specified_time = specified_time;
let mut high = LispObject::from(0);
let mut low = specified_time;
let mut usec = LispObject::from(0);
let mut psec = LispObject::from(0);
let mut len = 4;
if let Some((car, cdr)) = specified_time.into() {
high = car;
low = cdr;
if let Some((a, low_tail)) = cdr.into() {
low = a;
if let Some((a, low_tail)) = low_tail.into() {
usec = a;
if let Some((a, _)) = low_tail.into() {
psec = a;
} else {
len = 3;
}
} else if low_tail.is_not_nil() {
usec = low_tail;
len = 3;
} else {
len = 2;
}
} else {
len = 2;
}
// When combining components, require LOW to be an integer,
// as otherwise it would be a pain to add up times.
if !low.is_fixnum() {
return 0;
}
} else if specified_time.is_fixnum() {
len = 2;
}
*phigh = high;
*plow = low;
*pusec = usec;
*ppsec = psec;
len
}
/// From the time components HIGH, LOW, USEC and PSEC taken from a Lisp
/// list, generate the corresponding time value.
/// If LOW is floating point, the other components should be zero.
///
/// If RESULT is not null, store into *RESULT the converted time.
/// If *DRESULT is not null, store into *DRESULT the number of
/// seconds since the start of the POSIX Epoch.
///
/// Return 1 if successful, 0 if the components are of the
/// wrong type, and -1 if the time is out of range.
#[no_mangle]
pub unsafe extern "C" fn decode_time_components(
high: LispObject,
low: LispObject,
usec: LispObject,
psec: LispObject,
result: *mut lisp_time,
dresult: *mut f64,
) -> c_int {
let high = high;
let usec = usec;
let psec = psec;
if !(high.is_fixnum() && usec.is_fixnum() && psec.is_fixnum()) {
return 0;
}
let low = low;
if !low.is_fixnum() {
if let Some(t) = low.as_float() {
if !(result.is_null() || decode_float_time(t, result)) {
return -1;
}
if !dresult.is_null() {
*dresult = t;
}
return 1;
} else if low.is_nil() {
let now = current_timespec();
if !result.is_null() {
(*result).hi = hi_time(now.tv_sec);
(*result).lo = lo_time(now.tv_sec);
(*result).us = (now.tv_nsec / 1000) as c_int;
(*result).ps = (now.tv_nsec % 1000 * 1000) as c_int;
}
if !dresult.is_null() {
*dresult = (now.tv_sec as f64) + (now.tv_nsec as f64) / 1e9;
}
return 1;
} else {
return 0;
}
}
let mut hi = high.as_fixnum().unwrap();
let mut lo = low.as_fixnum().unwrap();
let mut us = usec.as_fixnum().unwrap();
let mut ps = psec.as_fixnum().unwrap();
// Normalize out-of-range lower-order components by carrying
// each overflow into the next higher-order component.
if ps % 1_000_000 < 0 {
us += ps / 1_000_000 - 1;
}
if us % 1_000_000 < 0 {
lo += us / 1_000_000 - 1;
}
hi += lo >> LO_TIME_BITS;
if ps % 1_000_000 < 0 {
ps = ps % 1_000_000 + 1_000_000;
} else {
ps %= 1_000_000;
}
if us % 1_000_000 < 0 {
us = us % 1_000_000 + 1_000_000;
} else {
us %= 1_000_000;
}
lo &= (1 << LO_TIME_BITS) - 1;
if !result.is_null() {
if LispObject::fixnum_overflow(hi) {
return -1;
}
(*result).hi = hi;
(*result).lo = lo as c_int;
(*result).us = us as c_int;
(*result).ps = ps as c_int;
}
if !dresult.is_null() {
let dhi = hi as f64;
*dresult =
(us as f64 * 1e6 + ps as f64) / 1e12 + (lo as f64) + dhi * f64::from(1 << LO_TIME_BITS);
}
1
}
/// Convert T into an Emacs time *RESULT, truncating toward minus infinity.
/// Return true if T is in range, false otherwise.
unsafe fn decode_float_time(t: f64, result: *mut lisp_time) -> bool {
let lo_multiplier = f64::from(1 << LO_TIME_BITS);
let emacs_time_min = MOST_NEGATIVE_FIXNUM as f64 * lo_multiplier;
if !(emacs_time_min <= t && t < -emacs_time_min) {
return false;
}
let small_t = t / lo_multiplier;
let mut hi = small_t as EmacsInt;
let t_sans_hi = t - (hi as f64) * lo_multiplier;
let mut lo = t_sans_hi as c_int;
let fracps = (t_sans_hi - f64::from(lo)) * 1e12;
let mut us = (fracps / 1e6) as c_int;
let mut ps = (fracps - f64::from(us) * 1e6) as c_int;
if ps < 0 {
us -= 1;
ps += 1_000_000;
}
if us < 0 {
lo -= 1;
us += 1_000_000;
}
if lo < 0 {
hi -= 1;
lo += 1 << LO_TIME_BITS;
}
(*result).hi = hi;
(*result).lo = lo;
(*result).us = us;
(*result).ps = ps;
true
}
#[no_mangle]
pub extern "C" fn lisp_to_timespec(t: lisp_time) -> c_timespec {
if t.hi < (1 >> LO_TIME_BITS) {
return c_timespec {
tv_sec: 0,
tv_nsec: -1,
};
}
let s = (t.hi << LO_TIME_BITS) + time_t::from(t.lo);
let ns = t.us * 1000 + t.ps / 1000;
c_timespec {
tv_sec: s,
tv_nsec: c_long::from(ns),
}
}
/// Decode a Lisp list `SPECIFIED_TIME` that represents a time.
/// Store its effective length into `*PLEN`.
/// If `SPECIFIED_TIME` is nil, use the current time.
/// Signal an error if `SPECIFIED_TIME` does not represent a time.
#[no_mangle]
pub unsafe extern "C" fn lisp_time_struct(
specified_time: LispObject,
plen: *mut c_int,
) -> lisp_time {
let mut high = LispObject::from_C(0);
let mut low = LispObject::from_C(0);
let mut usec = LispObject::from_C(0);
let mut psec = LispObject::from_C(0);
let len = { disassemble_lisp_time(specified_time, &mut high, &mut low, &mut usec, &mut psec) };
if len == 0 {
invalid_time();
}
let mut t: lisp_time = Default::default();
let val = decode_time_components(high, low, usec, psec, &mut t, ptr::null_mut());
check_time_validity(val);
if !plen.is_null() {
*plen = len;
}
t
}
/// Check a return value compatible with that of `decode_time_components`.
fn | (validity: i32) {
if validity <= 0 {
if validity < 0 {
time_overflow();
} else {
invalid_time();
}
}
}
fn invalid_time() -> ! {
error!("Invalid time specification");
}
/// Report that a time value is out of range for Emacs.
pub fn time_overflow() -> ! {
error!("Specified time is not representable");
}
/// Return the current time, as the number of seconds since 1970-01-01 00:00:00.
/// The time is returned as a list of integers (HIGH LOW USEC PSEC).
/// HIGH has the most significant bits of the seconds, while LOW has the
/// least significant 16 bits. USEC and PSEC are the microsecond and
/// picosecond counts.
#[lisp_fn]
pub fn current_time() -> LispObject {
make_lisp_time_1(current_timespec())
}
/// Return the current time, as a float number of seconds since the
/// epoch. If TIME is given, it is the time to convert to float
/// instead of the current time. The argument should have the form
/// (HIGH LOW) or (HIGH LOW USEC) or (HIGH LOW USEC PSEC). Thus, you
/// can use times from `current-time' and from `file-attributes'.
/// TIME can also have the form (HIGH . LOW), but this is considered
/// obsolete.
///
/// WARNING: Since the result is floating point, it may not be exact.
/// If precise time stamps are required, use either `current-time',
/// or (if you need time as a string) `format-time-string'.
#[lisp_fn(min = "0")]
pub fn float_time(time: LispObject) -> EmacsDouble {
let mut high = LispObject::from_C(0);
let mut low = LispObject::from_C(0);
let mut usec = LispObject::from_C(0);
let mut psec = LispObject::from_C(0);
let mut t = 0.0;
if unsafe {
disassemble_lisp_time(time, &mut high, &mut low, &mut usec, &mut psec) == 0
|| decode_time_components(high, low, usec, psec, ptr::null_mut(), &mut t) == 0
} {
invalid_time();
}
t
}
include!(concat!(env!("OUT_DIR"), "/time_exports.rs"));
| check_time_validity | identifier_name |
time.rs | //! Time support
use std::cmp::Ordering;
use std::ops::{Add, Sub};
use std::ptr;
use libc::timespec as c_timespec;
use libc::{c_int, c_long, time_t};
use remacs_lib::current_timespec;
use remacs_macros::lisp_fn;
use crate::{
lisp::LispObject,
numbers::MOST_NEGATIVE_FIXNUM,
remacs_sys::{lisp_time, EmacsDouble, EmacsInt},
};
const LO_TIME_BITS: i32 = 16;
pub type LispTime = lisp_time;
impl LispTime {
pub fn into_vec(self, nelem: usize) -> Vec<EmacsInt> {
let mut v = Vec::with_capacity(nelem);
if nelem >= 2 {
v.push(self.hi);
v.push(self.lo.into());
}
if nelem >= 3 {
v.push(self.us.into());
}
if nelem > 3 {
v.push(self.ps.into());
}
v
}
}
impl PartialEq for LispTime {
fn eq(&self, other: &Self) -> bool {
self.hi == other.hi && self.lo == other.lo && self.us == other.us && self.ps == other.ps
}
}
impl Eq for LispTime {}
impl PartialOrd for LispTime {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for LispTime {
fn cmp(&self, other: &Self) -> Ordering {
self.hi
.cmp(&other.hi)
.then_with(|| self.lo.cmp(&other.lo))
.then_with(|| self.us.cmp(&other.us))
.then_with(|| self.ps.cmp(&other.ps))
}
}
#[allow(clippy::suspicious_arithmetic_impl)]
impl Add for LispTime {
type Output = Self;
fn add(self, other: Self) -> Self {
let mut hi = self.hi + other.hi;
let mut lo = self.lo + other.lo;
let mut us = self.us + other.us;
let mut ps = self.ps + other.ps;
if ps >= 1_000_000 {
us += 1;
ps -= 1_000_000;
}
if us >= 1_000_000 {
lo += 1;
us -= 1_000_000;
}
if lo >= 1 << LO_TIME_BITS {
hi += 1;
lo -= 1 << LO_TIME_BITS;
}
Self { hi, lo, us, ps }
}
}
#[allow(clippy::suspicious_arithmetic_impl)]
impl Sub for LispTime {
type Output = Self;
fn sub(self, other: Self) -> Self {
let mut hi = self.hi - other.hi;
let mut lo = self.lo - other.lo;
let mut us = self.us - other.us;
let mut ps = self.ps - other.ps;
if ps < 0 {
us -= 1;
ps += 1_000_000;
}
if us < 0 {
lo -= 1;
us += 1_000_000;
}
if hi < 0 {
hi -= 1;
lo += 1 << LO_TIME_BITS;
}
Self { hi, lo, us, ps }
}
}
/// Return the upper part of the time T (everything but the bottom 16 bits).
#[no_mangle]
pub extern "C" fn hi_time(t: time_t) -> EmacsInt {
let hi = t >> LO_TIME_BITS;
if LispObject::fixnum_overflow(hi) {
time_overflow();
}
hi
}
/// Return the bottom bits of the time T.
#[no_mangle]
pub extern "C" fn lo_time(t: time_t) -> i32 {
(t & ((1 << LO_TIME_BITS) - 1)) as i32
}
| /// `UNKNOWN_MODTIME_NSECS`; in that case, the Lisp list contains a
/// correspondingly negative picosecond count.
#[no_mangle]
pub extern "C" fn make_lisp_time(t: c_timespec) -> LispObject {
make_lisp_time_1(t)
}
fn make_lisp_time_1(t: c_timespec) -> LispObject {
let s = t.tv_sec;
let ns = t.tv_nsec;
list!(hi_time(s), lo_time(s), ns / 1_000, ns % 1_000 * 1_000)
}
/// Decode a Lisp list `SPECIFIED_TIME` that represents a time.
/// Set `*PHIGH`, `*PLOW`, `*PUSEC`, `*PPSEC` to its parts; do not check their values.
/// Return 2, 3, or 4 to indicate the effective length of `SPECIFIED_TIME`
/// if successful, 0 if unsuccessful.
#[no_mangle]
pub unsafe extern "C" fn disassemble_lisp_time(
specified_time: LispObject,
phigh: *mut LispObject,
plow: *mut LispObject,
pusec: *mut LispObject,
ppsec: *mut LispObject,
) -> c_int {
let specified_time = specified_time;
let mut high = LispObject::from(0);
let mut low = specified_time;
let mut usec = LispObject::from(0);
let mut psec = LispObject::from(0);
let mut len = 4;
if let Some((car, cdr)) = specified_time.into() {
high = car;
low = cdr;
if let Some((a, low_tail)) = cdr.into() {
low = a;
if let Some((a, low_tail)) = low_tail.into() {
usec = a;
if let Some((a, _)) = low_tail.into() {
psec = a;
} else {
len = 3;
}
} else if low_tail.is_not_nil() {
usec = low_tail;
len = 3;
} else {
len = 2;
}
} else {
len = 2;
}
// When combining components, require LOW to be an integer,
// as otherwise it would be a pain to add up times.
if !low.is_fixnum() {
return 0;
}
} else if specified_time.is_fixnum() {
len = 2;
}
*phigh = high;
*plow = low;
*pusec = usec;
*ppsec = psec;
len
}
/// From the time components HIGH, LOW, USEC and PSEC taken from a Lisp
/// list, generate the corresponding time value.
/// If LOW is floating point, the other components should be zero.
///
/// If RESULT is not null, store into *RESULT the converted time.
/// If *DRESULT is not null, store into *DRESULT the number of
/// seconds since the start of the POSIX Epoch.
///
/// Return 1 if successful, 0 if the components are of the
/// wrong type, and -1 if the time is out of range.
#[no_mangle]
pub unsafe extern "C" fn decode_time_components(
high: LispObject,
low: LispObject,
usec: LispObject,
psec: LispObject,
result: *mut lisp_time,
dresult: *mut f64,
) -> c_int {
let high = high;
let usec = usec;
let psec = psec;
if !(high.is_fixnum() && usec.is_fixnum() && psec.is_fixnum()) {
return 0;
}
let low = low;
if !low.is_fixnum() {
if let Some(t) = low.as_float() {
if !(result.is_null() || decode_float_time(t, result)) {
return -1;
}
if !dresult.is_null() {
*dresult = t;
}
return 1;
} else if low.is_nil() {
let now = current_timespec();
if !result.is_null() {
(*result).hi = hi_time(now.tv_sec);
(*result).lo = lo_time(now.tv_sec);
(*result).us = (now.tv_nsec / 1000) as c_int;
(*result).ps = (now.tv_nsec % 1000 * 1000) as c_int;
}
if !dresult.is_null() {
*dresult = (now.tv_sec as f64) + (now.tv_nsec as f64) / 1e9;
}
return 1;
} else {
return 0;
}
}
let mut hi = high.as_fixnum().unwrap();
let mut lo = low.as_fixnum().unwrap();
let mut us = usec.as_fixnum().unwrap();
let mut ps = psec.as_fixnum().unwrap();
// Normalize out-of-range lower-order components by carrying
// each overflow into the next higher-order component.
if ps % 1_000_000 < 0 {
us += ps / 1_000_000 - 1;
}
if us % 1_000_000 < 0 {
lo += us / 1_000_000 - 1;
}
hi += lo >> LO_TIME_BITS;
if ps % 1_000_000 < 0 {
ps = ps % 1_000_000 + 1_000_000;
} else {
ps %= 1_000_000;
}
if us % 1_000_000 < 0 {
us = us % 1_000_000 + 1_000_000;
} else {
us %= 1_000_000;
}
lo &= (1 << LO_TIME_BITS) - 1;
if !result.is_null() {
if LispObject::fixnum_overflow(hi) {
return -1;
}
(*result).hi = hi;
(*result).lo = lo as c_int;
(*result).us = us as c_int;
(*result).ps = ps as c_int;
}
if !dresult.is_null() {
let dhi = hi as f64;
*dresult =
(us as f64 * 1e6 + ps as f64) / 1e12 + (lo as f64) + dhi * f64::from(1 << LO_TIME_BITS);
}
1
}
/// Convert T into an Emacs time *RESULT, truncating toward minus infinity.
/// Return true if T is in range, false otherwise.
unsafe fn decode_float_time(t: f64, result: *mut lisp_time) -> bool {
let lo_multiplier = f64::from(1 << LO_TIME_BITS);
let emacs_time_min = MOST_NEGATIVE_FIXNUM as f64 * lo_multiplier;
if !(emacs_time_min <= t && t < -emacs_time_min) {
return false;
}
let small_t = t / lo_multiplier;
let mut hi = small_t as EmacsInt;
let t_sans_hi = t - (hi as f64) * lo_multiplier;
let mut lo = t_sans_hi as c_int;
let fracps = (t_sans_hi - f64::from(lo)) * 1e12;
let mut us = (fracps / 1e6) as c_int;
let mut ps = (fracps - f64::from(us) * 1e6) as c_int;
if ps < 0 {
us -= 1;
ps += 1_000_000;
}
if us < 0 {
lo -= 1;
us += 1_000_000;
}
if lo < 0 {
hi -= 1;
lo += 1 << LO_TIME_BITS;
}
(*result).hi = hi;
(*result).lo = lo;
(*result).us = us;
(*result).ps = ps;
true
}
#[no_mangle]
pub extern "C" fn lisp_to_timespec(t: lisp_time) -> c_timespec {
if t.hi < (1 >> LO_TIME_BITS) {
return c_timespec {
tv_sec: 0,
tv_nsec: -1,
};
}
let s = (t.hi << LO_TIME_BITS) + time_t::from(t.lo);
let ns = t.us * 1000 + t.ps / 1000;
c_timespec {
tv_sec: s,
tv_nsec: c_long::from(ns),
}
}
/// Decode a Lisp list `SPECIFIED_TIME` that represents a time.
/// Store its effective length into `*PLEN`.
/// If `SPECIFIED_TIME` is nil, use the current time.
/// Signal an error if `SPECIFIED_TIME` does not represent a time.
#[no_mangle]
pub unsafe extern "C" fn lisp_time_struct(
specified_time: LispObject,
plen: *mut c_int,
) -> lisp_time {
let mut high = LispObject::from_C(0);
let mut low = LispObject::from_C(0);
let mut usec = LispObject::from_C(0);
let mut psec = LispObject::from_C(0);
let len = { disassemble_lisp_time(specified_time, &mut high, &mut low, &mut usec, &mut psec) };
if len == 0 {
invalid_time();
}
let mut t: lisp_time = Default::default();
let val = decode_time_components(high, low, usec, psec, &mut t, ptr::null_mut());
check_time_validity(val);
if !plen.is_null() {
*plen = len;
}
t
}
/// Check a return value compatible with that of `decode_time_components`.
fn check_time_validity(validity: i32) {
if validity <= 0 {
if validity < 0 {
time_overflow();
} else {
invalid_time();
}
}
}
fn invalid_time() -> ! {
error!("Invalid time specification");
}
/// Report that a time value is out of range for Emacs.
pub fn time_overflow() -> ! {
error!("Specified time is not representable");
}
/// Return the current time, as the number of seconds since 1970-01-01 00:00:00.
/// The time is returned as a list of integers (HIGH LOW USEC PSEC).
/// HIGH has the most significant bits of the seconds, while LOW has the
/// least significant 16 bits. USEC and PSEC are the microsecond and
/// picosecond counts.
#[lisp_fn]
pub fn current_time() -> LispObject {
make_lisp_time_1(current_timespec())
}
/// Return the current time, as a float number of seconds since the
/// epoch. If TIME is given, it is the time to convert to float
/// instead of the current time. The argument should have the form
/// (HIGH LOW) or (HIGH LOW USEC) or (HIGH LOW USEC PSEC). Thus, you
/// can use times from `current-time' and from `file-attributes'.
/// TIME can also have the form (HIGH . LOW), but this is considered
/// obsolete.
///
/// WARNING: Since the result is floating point, it may not be exact.
/// If precise time stamps are required, use either `current-time',
/// or (if you need time as a string) `format-time-string'.
#[lisp_fn(min = "0")]
pub fn float_time(time: LispObject) -> EmacsDouble {
let mut high = LispObject::from_C(0);
let mut low = LispObject::from_C(0);
let mut usec = LispObject::from_C(0);
let mut psec = LispObject::from_C(0);
let mut t = 0.0;
if unsafe {
disassemble_lisp_time(time, &mut high, &mut low, &mut usec, &mut psec) == 0
|| decode_time_components(high, low, usec, psec, ptr::null_mut(), &mut t) == 0
} {
invalid_time();
}
t
}
include!(concat!(env!("OUT_DIR"), "/time_exports.rs")); | /// Make a Lisp list that represents the Emacs time T. T may be an
/// invalid time, with a slightly negative `tv_nsec` value such as | random_line_split |
time.rs | //! Time support
use std::cmp::Ordering;
use std::ops::{Add, Sub};
use std::ptr;
use libc::timespec as c_timespec;
use libc::{c_int, c_long, time_t};
use remacs_lib::current_timespec;
use remacs_macros::lisp_fn;
use crate::{
lisp::LispObject,
numbers::MOST_NEGATIVE_FIXNUM,
remacs_sys::{lisp_time, EmacsDouble, EmacsInt},
};
const LO_TIME_BITS: i32 = 16;
pub type LispTime = lisp_time;
impl LispTime {
pub fn into_vec(self, nelem: usize) -> Vec<EmacsInt> {
let mut v = Vec::with_capacity(nelem);
if nelem >= 2 {
v.push(self.hi);
v.push(self.lo.into());
}
if nelem >= 3 {
v.push(self.us.into());
}
if nelem > 3 {
v.push(self.ps.into());
}
v
}
}
impl PartialEq for LispTime {
fn eq(&self, other: &Self) -> bool {
self.hi == other.hi && self.lo == other.lo && self.us == other.us && self.ps == other.ps
}
}
impl Eq for LispTime {}
impl PartialOrd for LispTime {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for LispTime {
fn cmp(&self, other: &Self) -> Ordering {
self.hi
.cmp(&other.hi)
.then_with(|| self.lo.cmp(&other.lo))
.then_with(|| self.us.cmp(&other.us))
.then_with(|| self.ps.cmp(&other.ps))
}
}
#[allow(clippy::suspicious_arithmetic_impl)]
impl Add for LispTime {
type Output = Self;
fn add(self, other: Self) -> Self {
let mut hi = self.hi + other.hi;
let mut lo = self.lo + other.lo;
let mut us = self.us + other.us;
let mut ps = self.ps + other.ps;
if ps >= 1_000_000 {
us += 1;
ps -= 1_000_000;
}
if us >= 1_000_000 {
lo += 1;
us -= 1_000_000;
}
if lo >= 1 << LO_TIME_BITS {
hi += 1;
lo -= 1 << LO_TIME_BITS;
}
Self { hi, lo, us, ps }
}
}
#[allow(clippy::suspicious_arithmetic_impl)]
impl Sub for LispTime {
type Output = Self;
fn sub(self, other: Self) -> Self {
let mut hi = self.hi - other.hi;
let mut lo = self.lo - other.lo;
let mut us = self.us - other.us;
let mut ps = self.ps - other.ps;
if ps < 0 {
us -= 1;
ps += 1_000_000;
}
if us < 0 {
lo -= 1;
us += 1_000_000;
}
if hi < 0 {
hi -= 1;
lo += 1 << LO_TIME_BITS;
}
Self { hi, lo, us, ps }
}
}
/// Return the upper part of the time T (everything but the bottom 16 bits).
#[no_mangle]
pub extern "C" fn hi_time(t: time_t) -> EmacsInt {
let hi = t >> LO_TIME_BITS;
if LispObject::fixnum_overflow(hi) {
time_overflow();
}
hi
}
/// Return the bottom bits of the time T.
#[no_mangle]
pub extern "C" fn lo_time(t: time_t) -> i32 {
(t & ((1 << LO_TIME_BITS) - 1)) as i32
}
/// Make a Lisp list that represents the Emacs time T. T may be an
/// invalid time, with a slightly negative `tv_nsec` value such as
/// `UNKNOWN_MODTIME_NSECS`; in that case, the Lisp list contains a
/// correspondingly negative picosecond count.
#[no_mangle]
pub extern "C" fn make_lisp_time(t: c_timespec) -> LispObject {
make_lisp_time_1(t)
}
fn make_lisp_time_1(t: c_timespec) -> LispObject {
let s = t.tv_sec;
let ns = t.tv_nsec;
list!(hi_time(s), lo_time(s), ns / 1_000, ns % 1_000 * 1_000)
}
/// Decode a Lisp list `SPECIFIED_TIME` that represents a time.
/// Set `*PHIGH`, `*PLOW`, `*PUSEC`, `*PPSEC` to its parts; do not check their values.
/// Return 2, 3, or 4 to indicate the effective length of `SPECIFIED_TIME`
/// if successful, 0 if unsuccessful.
#[no_mangle]
pub unsafe extern "C" fn disassemble_lisp_time(
specified_time: LispObject,
phigh: *mut LispObject,
plow: *mut LispObject,
pusec: *mut LispObject,
ppsec: *mut LispObject,
) -> c_int {
let specified_time = specified_time;
let mut high = LispObject::from(0);
let mut low = specified_time;
let mut usec = LispObject::from(0);
let mut psec = LispObject::from(0);
let mut len = 4;
if let Some((car, cdr)) = specified_time.into() {
high = car;
low = cdr;
if let Some((a, low_tail)) = cdr.into() {
low = a;
if let Some((a, low_tail)) = low_tail.into() {
usec = a;
if let Some((a, _)) = low_tail.into() {
psec = a;
} else {
len = 3;
}
} else if low_tail.is_not_nil() {
usec = low_tail;
len = 3;
} else {
len = 2;
}
} else {
len = 2;
}
// When combining components, require LOW to be an integer,
// as otherwise it would be a pain to add up times.
if !low.is_fixnum() {
return 0;
}
} else if specified_time.is_fixnum() {
len = 2;
}
*phigh = high;
*plow = low;
*pusec = usec;
*ppsec = psec;
len
}
/// From the time components HIGH, LOW, USEC and PSEC taken from a Lisp
/// list, generate the corresponding time value.
/// If LOW is floating point, the other components should be zero.
///
/// If RESULT is not null, store into *RESULT the converted time.
/// If *DRESULT is not null, store into *DRESULT the number of
/// seconds since the start of the POSIX Epoch.
///
/// Return 1 if successful, 0 if the components are of the
/// wrong type, and -1 if the time is out of range.
#[no_mangle]
pub unsafe extern "C" fn decode_time_components(
high: LispObject,
low: LispObject,
usec: LispObject,
psec: LispObject,
result: *mut lisp_time,
dresult: *mut f64,
) -> c_int {
let high = high;
let usec = usec;
let psec = psec;
if !(high.is_fixnum() && usec.is_fixnum() && psec.is_fixnum()) {
return 0;
}
let low = low;
if !low.is_fixnum() {
if let Some(t) = low.as_float() {
if !(result.is_null() || decode_float_time(t, result)) {
return -1;
}
if !dresult.is_null() {
*dresult = t;
}
return 1;
} else if low.is_nil() {
let now = current_timespec();
if !result.is_null() {
(*result).hi = hi_time(now.tv_sec);
(*result).lo = lo_time(now.tv_sec);
(*result).us = (now.tv_nsec / 1000) as c_int;
(*result).ps = (now.tv_nsec % 1000 * 1000) as c_int;
}
if !dresult.is_null() {
*dresult = (now.tv_sec as f64) + (now.tv_nsec as f64) / 1e9;
}
return 1;
} else {
return 0;
}
}
let mut hi = high.as_fixnum().unwrap();
let mut lo = low.as_fixnum().unwrap();
let mut us = usec.as_fixnum().unwrap();
let mut ps = psec.as_fixnum().unwrap();
// Normalize out-of-range lower-order components by carrying
// each overflow into the next higher-order component.
if ps % 1_000_000 < 0 {
us += ps / 1_000_000 - 1;
}
if us % 1_000_000 < 0 {
lo += us / 1_000_000 - 1;
}
hi += lo >> LO_TIME_BITS;
if ps % 1_000_000 < 0 {
ps = ps % 1_000_000 + 1_000_000;
} else {
ps %= 1_000_000;
}
if us % 1_000_000 < 0 {
us = us % 1_000_000 + 1_000_000;
} else {
us %= 1_000_000;
}
lo &= (1 << LO_TIME_BITS) - 1;
if !result.is_null() {
if LispObject::fixnum_overflow(hi) {
return -1;
}
(*result).hi = hi;
(*result).lo = lo as c_int;
(*result).us = us as c_int;
(*result).ps = ps as c_int;
}
if !dresult.is_null() {
let dhi = hi as f64;
*dresult =
(us as f64 * 1e6 + ps as f64) / 1e12 + (lo as f64) + dhi * f64::from(1 << LO_TIME_BITS);
}
1
}
/// Convert T into an Emacs time *RESULT, truncating toward minus infinity.
/// Return true if T is in range, false otherwise.
unsafe fn decode_float_time(t: f64, result: *mut lisp_time) -> bool |
#[no_mangle]
pub extern "C" fn lisp_to_timespec(t: lisp_time) -> c_timespec {
if t.hi < (1 >> LO_TIME_BITS) {
return c_timespec {
tv_sec: 0,
tv_nsec: -1,
};
}
let s = (t.hi << LO_TIME_BITS) + time_t::from(t.lo);
let ns = t.us * 1000 + t.ps / 1000;
c_timespec {
tv_sec: s,
tv_nsec: c_long::from(ns),
}
}
/// Decode a Lisp list `SPECIFIED_TIME` that represents a time.
/// Store its effective length into `*PLEN`.
/// If `SPECIFIED_TIME` is nil, use the current time.
/// Signal an error if `SPECIFIED_TIME` does not represent a time.
#[no_mangle]
pub unsafe extern "C" fn lisp_time_struct(
specified_time: LispObject,
plen: *mut c_int,
) -> lisp_time {
let mut high = LispObject::from_C(0);
let mut low = LispObject::from_C(0);
let mut usec = LispObject::from_C(0);
let mut psec = LispObject::from_C(0);
let len = { disassemble_lisp_time(specified_time, &mut high, &mut low, &mut usec, &mut psec) };
if len == 0 {
invalid_time();
}
let mut t: lisp_time = Default::default();
let val = decode_time_components(high, low, usec, psec, &mut t, ptr::null_mut());
check_time_validity(val);
if !plen.is_null() {
*plen = len;
}
t
}
/// Check a return value compatible with that of `decode_time_components`.
fn check_time_validity(validity: i32) {
if validity <= 0 {
if validity < 0 {
time_overflow();
} else {
invalid_time();
}
}
}
fn invalid_time() -> ! {
error!("Invalid time specification");
}
/// Report that a time value is out of range for Emacs.
pub fn time_overflow() -> ! {
error!("Specified time is not representable");
}
/// Return the current time, as the number of seconds since 1970-01-01 00:00:00.
/// The time is returned as a list of integers (HIGH LOW USEC PSEC).
/// HIGH has the most significant bits of the seconds, while LOW has the
/// least significant 16 bits. USEC and PSEC are the microsecond and
/// picosecond counts.
#[lisp_fn]
pub fn current_time() -> LispObject {
make_lisp_time_1(current_timespec())
}
/// Return the current time, as a float number of seconds since the
/// epoch. If TIME is given, it is the time to convert to float
/// instead of the current time. The argument should have the form
/// (HIGH LOW) or (HIGH LOW USEC) or (HIGH LOW USEC PSEC). Thus, you
/// can use times from `current-time' and from `file-attributes'.
/// TIME can also have the form (HIGH . LOW), but this is considered
/// obsolete.
///
/// WARNING: Since the result is floating point, it may not be exact.
/// If precise time stamps are required, use either `current-time',
/// or (if you need time as a string) `format-time-string'.
#[lisp_fn(min = "0")]
pub fn float_time(time: LispObject) -> EmacsDouble {
let mut high = LispObject::from_C(0);
let mut low = LispObject::from_C(0);
let mut usec = LispObject::from_C(0);
let mut psec = LispObject::from_C(0);
let mut t = 0.0;
if unsafe {
disassemble_lisp_time(time, &mut high, &mut low, &mut usec, &mut psec) == 0
|| decode_time_components(high, low, usec, psec, ptr::null_mut(), &mut t) == 0
} {
invalid_time();
}
t
}
include!(concat!(env!("OUT_DIR"), "/time_exports.rs"));
| {
let lo_multiplier = f64::from(1 << LO_TIME_BITS);
let emacs_time_min = MOST_NEGATIVE_FIXNUM as f64 * lo_multiplier;
if !(emacs_time_min <= t && t < -emacs_time_min) {
return false;
}
let small_t = t / lo_multiplier;
let mut hi = small_t as EmacsInt;
let t_sans_hi = t - (hi as f64) * lo_multiplier;
let mut lo = t_sans_hi as c_int;
let fracps = (t_sans_hi - f64::from(lo)) * 1e12;
let mut us = (fracps / 1e6) as c_int;
let mut ps = (fracps - f64::from(us) * 1e6) as c_int;
if ps < 0 {
us -= 1;
ps += 1_000_000;
}
if us < 0 {
lo -= 1;
us += 1_000_000;
}
if lo < 0 {
hi -= 1;
lo += 1 << LO_TIME_BITS;
}
(*result).hi = hi;
(*result).lo = lo;
(*result).us = us;
(*result).ps = ps;
true
} | identifier_body |
time.rs | //! Time support
use std::cmp::Ordering;
use std::ops::{Add, Sub};
use std::ptr;
use libc::timespec as c_timespec;
use libc::{c_int, c_long, time_t};
use remacs_lib::current_timespec;
use remacs_macros::lisp_fn;
use crate::{
lisp::LispObject,
numbers::MOST_NEGATIVE_FIXNUM,
remacs_sys::{lisp_time, EmacsDouble, EmacsInt},
};
const LO_TIME_BITS: i32 = 16;
pub type LispTime = lisp_time;
impl LispTime {
pub fn into_vec(self, nelem: usize) -> Vec<EmacsInt> {
let mut v = Vec::with_capacity(nelem);
if nelem >= 2 {
v.push(self.hi);
v.push(self.lo.into());
}
if nelem >= 3 {
v.push(self.us.into());
}
if nelem > 3 {
v.push(self.ps.into());
}
v
}
}
impl PartialEq for LispTime {
fn eq(&self, other: &Self) -> bool {
self.hi == other.hi && self.lo == other.lo && self.us == other.us && self.ps == other.ps
}
}
impl Eq for LispTime {}
impl PartialOrd for LispTime {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for LispTime {
fn cmp(&self, other: &Self) -> Ordering {
self.hi
.cmp(&other.hi)
.then_with(|| self.lo.cmp(&other.lo))
.then_with(|| self.us.cmp(&other.us))
.then_with(|| self.ps.cmp(&other.ps))
}
}
#[allow(clippy::suspicious_arithmetic_impl)]
impl Add for LispTime {
type Output = Self;
fn add(self, other: Self) -> Self {
let mut hi = self.hi + other.hi;
let mut lo = self.lo + other.lo;
let mut us = self.us + other.us;
let mut ps = self.ps + other.ps;
if ps >= 1_000_000 {
us += 1;
ps -= 1_000_000;
}
if us >= 1_000_000 {
lo += 1;
us -= 1_000_000;
}
if lo >= 1 << LO_TIME_BITS {
hi += 1;
lo -= 1 << LO_TIME_BITS;
}
Self { hi, lo, us, ps }
}
}
#[allow(clippy::suspicious_arithmetic_impl)]
impl Sub for LispTime {
type Output = Self;
fn sub(self, other: Self) -> Self {
let mut hi = self.hi - other.hi;
let mut lo = self.lo - other.lo;
let mut us = self.us - other.us;
let mut ps = self.ps - other.ps;
if ps < 0 {
us -= 1;
ps += 1_000_000;
}
if us < 0 {
lo -= 1;
us += 1_000_000;
}
if hi < 0 {
hi -= 1;
lo += 1 << LO_TIME_BITS;
}
Self { hi, lo, us, ps }
}
}
/// Return the upper part of the time T (everything but the bottom 16 bits).
#[no_mangle]
pub extern "C" fn hi_time(t: time_t) -> EmacsInt {
let hi = t >> LO_TIME_BITS;
if LispObject::fixnum_overflow(hi) {
time_overflow();
}
hi
}
/// Return the bottom bits of the time T.
#[no_mangle]
pub extern "C" fn lo_time(t: time_t) -> i32 {
(t & ((1 << LO_TIME_BITS) - 1)) as i32
}
/// Make a Lisp list that represents the Emacs time T. T may be an
/// invalid time, with a slightly negative `tv_nsec` value such as
/// `UNKNOWN_MODTIME_NSECS`; in that case, the Lisp list contains a
/// correspondingly negative picosecond count.
#[no_mangle]
pub extern "C" fn make_lisp_time(t: c_timespec) -> LispObject {
make_lisp_time_1(t)
}
fn make_lisp_time_1(t: c_timespec) -> LispObject {
let s = t.tv_sec;
let ns = t.tv_nsec;
list!(hi_time(s), lo_time(s), ns / 1_000, ns % 1_000 * 1_000)
}
/// Decode a Lisp list `SPECIFIED_TIME` that represents a time.
/// Set `*PHIGH`, `*PLOW`, `*PUSEC`, `*PPSEC` to its parts; do not check their values.
/// Return 2, 3, or 4 to indicate the effective length of `SPECIFIED_TIME`
/// if successful, 0 if unsuccessful.
#[no_mangle]
pub unsafe extern "C" fn disassemble_lisp_time(
specified_time: LispObject,
phigh: *mut LispObject,
plow: *mut LispObject,
pusec: *mut LispObject,
ppsec: *mut LispObject,
) -> c_int {
let specified_time = specified_time;
let mut high = LispObject::from(0);
let mut low = specified_time;
let mut usec = LispObject::from(0);
let mut psec = LispObject::from(0);
let mut len = 4;
if let Some((car, cdr)) = specified_time.into() {
high = car;
low = cdr;
if let Some((a, low_tail)) = cdr.into() {
low = a;
if let Some((a, low_tail)) = low_tail.into() {
usec = a;
if let Some((a, _)) = low_tail.into() {
psec = a;
} else {
len = 3;
}
} else if low_tail.is_not_nil() {
usec = low_tail;
len = 3;
} else {
len = 2;
}
} else {
len = 2;
}
// When combining components, require LOW to be an integer,
// as otherwise it would be a pain to add up times.
if !low.is_fixnum() {
return 0;
}
} else if specified_time.is_fixnum() {
len = 2;
}
*phigh = high;
*plow = low;
*pusec = usec;
*ppsec = psec;
len
}
/// From the time components HIGH, LOW, USEC and PSEC taken from a Lisp
/// list, generate the corresponding time value.
/// If LOW is floating point, the other components should be zero.
///
/// If RESULT is not null, store into *RESULT the converted time.
/// If *DRESULT is not null, store into *DRESULT the number of
/// seconds since the start of the POSIX Epoch.
///
/// Return 1 if successful, 0 if the components are of the
/// wrong type, and -1 if the time is out of range.
#[no_mangle]
pub unsafe extern "C" fn decode_time_components(
high: LispObject,
low: LispObject,
usec: LispObject,
psec: LispObject,
result: *mut lisp_time,
dresult: *mut f64,
) -> c_int {
let high = high;
let usec = usec;
let psec = psec;
if !(high.is_fixnum() && usec.is_fixnum() && psec.is_fixnum()) {
return 0;
}
let low = low;
if !low.is_fixnum() {
if let Some(t) = low.as_float() {
if !(result.is_null() || decode_float_time(t, result)) |
if !dresult.is_null() {
*dresult = t;
}
return 1;
} else if low.is_nil() {
let now = current_timespec();
if !result.is_null() {
(*result).hi = hi_time(now.tv_sec);
(*result).lo = lo_time(now.tv_sec);
(*result).us = (now.tv_nsec / 1000) as c_int;
(*result).ps = (now.tv_nsec % 1000 * 1000) as c_int;
}
if !dresult.is_null() {
*dresult = (now.tv_sec as f64) + (now.tv_nsec as f64) / 1e9;
}
return 1;
} else {
return 0;
}
}
let mut hi = high.as_fixnum().unwrap();
let mut lo = low.as_fixnum().unwrap();
let mut us = usec.as_fixnum().unwrap();
let mut ps = psec.as_fixnum().unwrap();
// Normalize out-of-range lower-order components by carrying
// each overflow into the next higher-order component.
if ps % 1_000_000 < 0 {
us += ps / 1_000_000 - 1;
}
if us % 1_000_000 < 0 {
lo += us / 1_000_000 - 1;
}
hi += lo >> LO_TIME_BITS;
if ps % 1_000_000 < 0 {
ps = ps % 1_000_000 + 1_000_000;
} else {
ps %= 1_000_000;
}
if us % 1_000_000 < 0 {
us = us % 1_000_000 + 1_000_000;
} else {
us %= 1_000_000;
}
lo &= (1 << LO_TIME_BITS) - 1;
if !result.is_null() {
if LispObject::fixnum_overflow(hi) {
return -1;
}
(*result).hi = hi;
(*result).lo = lo as c_int;
(*result).us = us as c_int;
(*result).ps = ps as c_int;
}
if !dresult.is_null() {
let dhi = hi as f64;
*dresult =
(us as f64 * 1e6 + ps as f64) / 1e12 + (lo as f64) + dhi * f64::from(1 << LO_TIME_BITS);
}
1
}
/// Convert T into an Emacs time *RESULT, truncating toward minus infinity.
/// Return true if T is in range, false otherwise.
unsafe fn decode_float_time(t: f64, result: *mut lisp_time) -> bool {
let lo_multiplier = f64::from(1 << LO_TIME_BITS);
let emacs_time_min = MOST_NEGATIVE_FIXNUM as f64 * lo_multiplier;
if !(emacs_time_min <= t && t < -emacs_time_min) {
return false;
}
let small_t = t / lo_multiplier;
let mut hi = small_t as EmacsInt;
let t_sans_hi = t - (hi as f64) * lo_multiplier;
let mut lo = t_sans_hi as c_int;
let fracps = (t_sans_hi - f64::from(lo)) * 1e12;
let mut us = (fracps / 1e6) as c_int;
let mut ps = (fracps - f64::from(us) * 1e6) as c_int;
if ps < 0 {
us -= 1;
ps += 1_000_000;
}
if us < 0 {
lo -= 1;
us += 1_000_000;
}
if lo < 0 {
hi -= 1;
lo += 1 << LO_TIME_BITS;
}
(*result).hi = hi;
(*result).lo = lo;
(*result).us = us;
(*result).ps = ps;
true
}
#[no_mangle]
pub extern "C" fn lisp_to_timespec(t: lisp_time) -> c_timespec {
if t.hi < (1 >> LO_TIME_BITS) {
return c_timespec {
tv_sec: 0,
tv_nsec: -1,
};
}
let s = (t.hi << LO_TIME_BITS) + time_t::from(t.lo);
let ns = t.us * 1000 + t.ps / 1000;
c_timespec {
tv_sec: s,
tv_nsec: c_long::from(ns),
}
}
/// Decode a Lisp list `SPECIFIED_TIME` that represents a time.
/// Store its effective length into `*PLEN`.
/// If `SPECIFIED_TIME` is nil, use the current time.
/// Signal an error if `SPECIFIED_TIME` does not represent a time.
#[no_mangle]
pub unsafe extern "C" fn lisp_time_struct(
specified_time: LispObject,
plen: *mut c_int,
) -> lisp_time {
let mut high = LispObject::from_C(0);
let mut low = LispObject::from_C(0);
let mut usec = LispObject::from_C(0);
let mut psec = LispObject::from_C(0);
let len = { disassemble_lisp_time(specified_time, &mut high, &mut low, &mut usec, &mut psec) };
if len == 0 {
invalid_time();
}
let mut t: lisp_time = Default::default();
let val = decode_time_components(high, low, usec, psec, &mut t, ptr::null_mut());
check_time_validity(val);
if !plen.is_null() {
*plen = len;
}
t
}
/// Check a return value compatible with that of `decode_time_components`.
fn check_time_validity(validity: i32) {
if validity <= 0 {
if validity < 0 {
time_overflow();
} else {
invalid_time();
}
}
}
fn invalid_time() -> ! {
error!("Invalid time specification");
}
/// Report that a time value is out of range for Emacs.
pub fn time_overflow() -> ! {
error!("Specified time is not representable");
}
/// Return the current time, as the number of seconds since 1970-01-01 00:00:00.
/// The time is returned as a list of integers (HIGH LOW USEC PSEC).
/// HIGH has the most significant bits of the seconds, while LOW has the
/// least significant 16 bits. USEC and PSEC are the microsecond and
/// picosecond counts.
#[lisp_fn]
pub fn current_time() -> LispObject {
make_lisp_time_1(current_timespec())
}
/// Return the current time, as a float number of seconds since the
/// epoch. If TIME is given, it is the time to convert to float
/// instead of the current time. The argument should have the form
/// (HIGH LOW) or (HIGH LOW USEC) or (HIGH LOW USEC PSEC). Thus, you
/// can use times from `current-time' and from `file-attributes'.
/// TIME can also have the form (HIGH . LOW), but this is considered
/// obsolete.
///
/// WARNING: Since the result is floating point, it may not be exact.
/// If precise time stamps are required, use either `current-time',
/// or (if you need time as a string) `format-time-string'.
#[lisp_fn(min = "0")]
pub fn float_time(time: LispObject) -> EmacsDouble {
let mut high = LispObject::from_C(0);
let mut low = LispObject::from_C(0);
let mut usec = LispObject::from_C(0);
let mut psec = LispObject::from_C(0);
let mut t = 0.0;
if unsafe {
disassemble_lisp_time(time, &mut high, &mut low, &mut usec, &mut psec) == 0
|| decode_time_components(high, low, usec, psec, ptr::null_mut(), &mut t) == 0
} {
invalid_time();
}
t
}
include!(concat!(env!("OUT_DIR"), "/time_exports.rs"));
| {
return -1;
} | conditional_block |
macro_crate_test.rs | // Copyright 2013-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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// force-host
#![feature(globs, plugin_registrar, macro_rules, quote)]
extern crate syntax;
extern crate rustc;
use syntax::ast::{TokenTree, Item, MetaItem};
use syntax::codemap::Span;
use syntax::ext::base::*;
use syntax::parse::token;
use syntax::parse;
use rustc::plugin::Registry;
use std::gc::{Gc, GC};
#[macro_export]
macro_rules! exported_macro (() => (2i))
macro_rules! unexported_macro (() => (3i))
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("make_a_1", expand_make_a_1);
reg.register_macro("forged_ident", expand_forged_ident);
reg.register_macro("identity", expand_identity);
reg.register_syntax_extension(
token::intern("into_foo"),
ItemModifier(expand_into_foo));
}
fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
-> Box<MacResult+'static> {
if !tts.is_empty() {
cx.span_fatal(sp, "make_a_1 takes no arguments");
}
MacExpr::new(quote_expr!(cx, 1i))
}
// See Issue #15750
fn expand_identity(cx: &mut ExtCtxt, _span: Span, tts: &[TokenTree])
-> Box<MacResult+'static> {
// Parse an expression and emit it unchanged.
let mut parser = parse::new_parser_from_tts(cx.parse_sess(),
cx.cfg(), Vec::from_slice(tts));
let expr = parser.parse_expr();
MacExpr::new(quote_expr!(&mut *cx, $expr))
}
fn | (cx: &mut ExtCtxt, sp: Span, attr: Gc<MetaItem>, it: Gc<Item>)
-> Gc<Item> {
box(GC) Item {
attrs: it.attrs.clone(),
..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone()
}
}
fn expand_forged_ident(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult+'static> {
use syntax::ext::quote::rt::*;
if !tts.is_empty() {
cx.span_fatal(sp, "forged_ident takes no arguments");
}
// Most of this is modelled after the expansion of the `quote_expr!`
// macro ...
let parse_sess = cx.parse_sess();
let cfg = cx.cfg();
// ... except this is where we inject a forged identifier,
// and deliberately do not call `cx.parse_tts_with_hygiene`
// (because we are testing that this will be *rejected*
// by the default parser).
let expr = {
let tt = cx.parse_tts("\x00name_2,ctxt_0\x00".to_string());
let mut parser = new_parser_from_tts(parse_sess, cfg, tt);
parser.parse_expr()
};
MacExpr::new(expr)
}
pub fn foo() {}
| expand_into_foo | identifier_name |
macro_crate_test.rs | // Copyright 2013-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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms. |
// force-host
#![feature(globs, plugin_registrar, macro_rules, quote)]
extern crate syntax;
extern crate rustc;
use syntax::ast::{TokenTree, Item, MetaItem};
use syntax::codemap::Span;
use syntax::ext::base::*;
use syntax::parse::token;
use syntax::parse;
use rustc::plugin::Registry;
use std::gc::{Gc, GC};
#[macro_export]
macro_rules! exported_macro (() => (2i))
macro_rules! unexported_macro (() => (3i))
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("make_a_1", expand_make_a_1);
reg.register_macro("forged_ident", expand_forged_ident);
reg.register_macro("identity", expand_identity);
reg.register_syntax_extension(
token::intern("into_foo"),
ItemModifier(expand_into_foo));
}
fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
-> Box<MacResult+'static> {
if !tts.is_empty() {
cx.span_fatal(sp, "make_a_1 takes no arguments");
}
MacExpr::new(quote_expr!(cx, 1i))
}
// See Issue #15750
fn expand_identity(cx: &mut ExtCtxt, _span: Span, tts: &[TokenTree])
-> Box<MacResult+'static> {
// Parse an expression and emit it unchanged.
let mut parser = parse::new_parser_from_tts(cx.parse_sess(),
cx.cfg(), Vec::from_slice(tts));
let expr = parser.parse_expr();
MacExpr::new(quote_expr!(&mut *cx, $expr))
}
fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: Gc<MetaItem>, it: Gc<Item>)
-> Gc<Item> {
box(GC) Item {
attrs: it.attrs.clone(),
..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone()
}
}
fn expand_forged_ident(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult+'static> {
use syntax::ext::quote::rt::*;
if !tts.is_empty() {
cx.span_fatal(sp, "forged_ident takes no arguments");
}
// Most of this is modelled after the expansion of the `quote_expr!`
// macro ...
let parse_sess = cx.parse_sess();
let cfg = cx.cfg();
// ... except this is where we inject a forged identifier,
// and deliberately do not call `cx.parse_tts_with_hygiene`
// (because we are testing that this will be *rejected*
// by the default parser).
let expr = {
let tt = cx.parse_tts("\x00name_2,ctxt_0\x00".to_string());
let mut parser = new_parser_from_tts(parse_sess, cfg, tt);
parser.parse_expr()
};
MacExpr::new(expr)
}
pub fn foo() {} | random_line_split | |
macro_crate_test.rs | // Copyright 2013-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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// force-host
#![feature(globs, plugin_registrar, macro_rules, quote)]
extern crate syntax;
extern crate rustc;
use syntax::ast::{TokenTree, Item, MetaItem};
use syntax::codemap::Span;
use syntax::ext::base::*;
use syntax::parse::token;
use syntax::parse;
use rustc::plugin::Registry;
use std::gc::{Gc, GC};
#[macro_export]
macro_rules! exported_macro (() => (2i))
macro_rules! unexported_macro (() => (3i))
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("make_a_1", expand_make_a_1);
reg.register_macro("forged_ident", expand_forged_ident);
reg.register_macro("identity", expand_identity);
reg.register_syntax_extension(
token::intern("into_foo"),
ItemModifier(expand_into_foo));
}
fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
-> Box<MacResult+'static> {
if !tts.is_empty() |
MacExpr::new(quote_expr!(cx, 1i))
}
// See Issue #15750
fn expand_identity(cx: &mut ExtCtxt, _span: Span, tts: &[TokenTree])
-> Box<MacResult+'static> {
// Parse an expression and emit it unchanged.
let mut parser = parse::new_parser_from_tts(cx.parse_sess(),
cx.cfg(), Vec::from_slice(tts));
let expr = parser.parse_expr();
MacExpr::new(quote_expr!(&mut *cx, $expr))
}
fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: Gc<MetaItem>, it: Gc<Item>)
-> Gc<Item> {
box(GC) Item {
attrs: it.attrs.clone(),
..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone()
}
}
fn expand_forged_ident(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult+'static> {
use syntax::ext::quote::rt::*;
if !tts.is_empty() {
cx.span_fatal(sp, "forged_ident takes no arguments");
}
// Most of this is modelled after the expansion of the `quote_expr!`
// macro ...
let parse_sess = cx.parse_sess();
let cfg = cx.cfg();
// ... except this is where we inject a forged identifier,
// and deliberately do not call `cx.parse_tts_with_hygiene`
// (because we are testing that this will be *rejected*
// by the default parser).
let expr = {
let tt = cx.parse_tts("\x00name_2,ctxt_0\x00".to_string());
let mut parser = new_parser_from_tts(parse_sess, cfg, tt);
parser.parse_expr()
};
MacExpr::new(expr)
}
pub fn foo() {}
| {
cx.span_fatal(sp, "make_a_1 takes no arguments");
} | conditional_block |
macro_crate_test.rs | // Copyright 2013-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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// force-host
#![feature(globs, plugin_registrar, macro_rules, quote)]
extern crate syntax;
extern crate rustc;
use syntax::ast::{TokenTree, Item, MetaItem};
use syntax::codemap::Span;
use syntax::ext::base::*;
use syntax::parse::token;
use syntax::parse;
use rustc::plugin::Registry;
use std::gc::{Gc, GC};
#[macro_export]
macro_rules! exported_macro (() => (2i))
macro_rules! unexported_macro (() => (3i))
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("make_a_1", expand_make_a_1);
reg.register_macro("forged_ident", expand_forged_ident);
reg.register_macro("identity", expand_identity);
reg.register_syntax_extension(
token::intern("into_foo"),
ItemModifier(expand_into_foo));
}
fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
-> Box<MacResult+'static> |
// See Issue #15750
fn expand_identity(cx: &mut ExtCtxt, _span: Span, tts: &[TokenTree])
-> Box<MacResult+'static> {
// Parse an expression and emit it unchanged.
let mut parser = parse::new_parser_from_tts(cx.parse_sess(),
cx.cfg(), Vec::from_slice(tts));
let expr = parser.parse_expr();
MacExpr::new(quote_expr!(&mut *cx, $expr))
}
fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: Gc<MetaItem>, it: Gc<Item>)
-> Gc<Item> {
box(GC) Item {
attrs: it.attrs.clone(),
..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone()
}
}
fn expand_forged_ident(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult+'static> {
use syntax::ext::quote::rt::*;
if !tts.is_empty() {
cx.span_fatal(sp, "forged_ident takes no arguments");
}
// Most of this is modelled after the expansion of the `quote_expr!`
// macro ...
let parse_sess = cx.parse_sess();
let cfg = cx.cfg();
// ... except this is where we inject a forged identifier,
// and deliberately do not call `cx.parse_tts_with_hygiene`
// (because we are testing that this will be *rejected*
// by the default parser).
let expr = {
let tt = cx.parse_tts("\x00name_2,ctxt_0\x00".to_string());
let mut parser = new_parser_from_tts(parse_sess, cfg, tt);
parser.parse_expr()
};
MacExpr::new(expr)
}
pub fn foo() {}
| {
if !tts.is_empty() {
cx.span_fatal(sp, "make_a_1 takes no arguments");
}
MacExpr::new(quote_expr!(cx, 1i))
} | identifier_body |
array_simp_2.py | t = int(raw_input())
MOD = 10**9 + 7
def modexp(a,b):
res = 1
while b:
if b&1:
res *= a
res %= MOD
a = (a*a)%MOD
b /= 2
return res
fn = [1 for _ in xrange(100001)]
ifn = [1 for _ in xrange(100001)]
for i in range(1,100000):
fn[i] = fn[i-1] * i
fn[i] %= MOD
ifn[i] = modexp(fn[i],MOD-2)
def | (n,k):
return fn[n] * ifn[k] * ifn[n-k]
for ti in range(t):
n = int(raw_input())
a = map(int,raw_input().split())
ans = 0
for i in range(n):
if i%2==0:
ans += nCr(n-1,i)%MOD * a[i]%MOD
else:
ans -= nCr(n-1,i)%MOD * a[i]%MOD
ans %= MOD
print ans | nCr | identifier_name |
array_simp_2.py | t = int(raw_input())
MOD = 10**9 + 7
def modexp(a,b):
res = 1
while b:
if b&1:
res *= a
res %= MOD
a = (a*a)%MOD
b /= 2
return res
fn = [1 for _ in xrange(100001)]
ifn = [1 for _ in xrange(100001)]
for i in range(1,100000):
fn[i] = fn[i-1] * i
fn[i] %= MOD
ifn[i] = modexp(fn[i],MOD-2)
def nCr(n,k):
return fn[n] * ifn[k] * ifn[n-k]
for ti in range(t):
n = int(raw_input())
a = map(int,raw_input().split())
ans = 0
for i in range(n):
if i%2==0:
ans += nCr(n-1,i)%MOD * a[i]%MOD
else:
|
ans %= MOD
print ans | ans -= nCr(n-1,i)%MOD * a[i]%MOD | conditional_block |
array_simp_2.py | t = int(raw_input())
MOD = 10**9 + 7
def modexp(a,b):
res = 1
while b:
if b&1:
res *= a
res %= MOD
a = (a*a)%MOD
b /= 2
return res
fn = [1 for _ in xrange(100001)]
ifn = [1 for _ in xrange(100001)]
for i in range(1,100000):
fn[i] = fn[i-1] * i
fn[i] %= MOD
ifn[i] = modexp(fn[i],MOD-2) | ans = 0
for i in range(n):
if i%2==0:
ans += nCr(n-1,i)%MOD * a[i]%MOD
else:
ans -= nCr(n-1,i)%MOD * a[i]%MOD
ans %= MOD
print ans | def nCr(n,k):
return fn[n] * ifn[k] * ifn[n-k]
for ti in range(t):
n = int(raw_input())
a = map(int,raw_input().split()) | random_line_split |
array_simp_2.py | t = int(raw_input())
MOD = 10**9 + 7
def modexp(a,b):
|
fn = [1 for _ in xrange(100001)]
ifn = [1 for _ in xrange(100001)]
for i in range(1,100000):
fn[i] = fn[i-1] * i
fn[i] %= MOD
ifn[i] = modexp(fn[i],MOD-2)
def nCr(n,k):
return fn[n] * ifn[k] * ifn[n-k]
for ti in range(t):
n = int(raw_input())
a = map(int,raw_input().split())
ans = 0
for i in range(n):
if i%2==0:
ans += nCr(n-1,i)%MOD * a[i]%MOD
else:
ans -= nCr(n-1,i)%MOD * a[i]%MOD
ans %= MOD
print ans | res = 1
while b:
if b&1:
res *= a
res %= MOD
a = (a*a)%MOD
b /= 2
return res | identifier_body |
index.tsx | /// <reference path="../typings/index.d.ts" />
import * as injectTapEventPlugin from 'react-tap-event-plugin';
import animationFrame from './util/animationFrame';
injectTapEventPlugin();
animationFrame();
interface CustomerElement extends Element{
blur?: ()=>{}
}
function | (e) {
if(e.target.tagName == "INPUT" || e.target.tagName == 'TEXTAREA') {
return;
}
var activeElement = document.activeElement as CustomerElement;
if(activeElement.tagName == "INPUT" || activeElement.tagName == "TEXTAREA") {
activeElement.blur && activeElement.blur();
}
}
document.addEventListener('touchstart', blurActiveInput, false)
export {colors} from './styles/colors';
export {default as Alert} from './Alert';
export {default as Button} from './Button';
export {default as Icon} from './Icon';
export {default as Line} from './Line';
export {default as Tabs} from './Tabs';
export {default as Tab} from './Tabs/Tab';
export {default as TabBar} from './TabBar/TabBar';
export {default as TabBarItem} from './TabBar/TabBarItem';
export {default as SegmentedControl} from './SegmentedControl';
export {default as LinearProgress} from './LinearProgress';
export {default as CircleProgress} from './CircleProgress';
export {default as Carousel} from './Carousel';
export {default as Badge} from './Badge';
export {default as Toast} from './Toast';
export {default as Card} from './Card';
export {default as Switch} from './Switch';
export {default as Checkbox} from './Checkbox';
export {default as Radio} from './Radio';
export {default as RadioGroup} from './Radio/RadioGroup';
export {default as Ellipsis} from './Ellipsis';
export {default as Table} from './Table';
export {default as Arrow} from './Arrow';
export {default as Slider} from './Slider';
export {default as Popup} from './Popup';
export {default as Panel} from './Panel';
export {default as InputItem} from './InputItem';
export {default as TextareaItem} from './TextareaItem';
export {default as Dialog} from './Dialog';
export {createDialog} from './Dialog';
export {default as ScrollerView} from './ScrollerView';
//TODO: 优先级按照如下顺序
//export {default as NavBar} from './NavBar';
//export {default as SearchBar} from './SearchBar';
//export {default as Picker} from './Picker';
//export {default as DatePicker} from './DatePicker'; ios and 安卓两种 参考material-ui & andt-mobile & mint-ui | blurActiveInput | identifier_name |
index.tsx | /// <reference path="../typings/index.d.ts" />
import * as injectTapEventPlugin from 'react-tap-event-plugin';
import animationFrame from './util/animationFrame';
injectTapEventPlugin();
animationFrame();
interface CustomerElement extends Element{
blur?: ()=>{}
}
function blurActiveInput(e) {
if(e.target.tagName == "INPUT" || e.target.tagName == 'TEXTAREA') |
var activeElement = document.activeElement as CustomerElement;
if(activeElement.tagName == "INPUT" || activeElement.tagName == "TEXTAREA") {
activeElement.blur && activeElement.blur();
}
}
document.addEventListener('touchstart', blurActiveInput, false)
export {colors} from './styles/colors';
export {default as Alert} from './Alert';
export {default as Button} from './Button';
export {default as Icon} from './Icon';
export {default as Line} from './Line';
export {default as Tabs} from './Tabs';
export {default as Tab} from './Tabs/Tab';
export {default as TabBar} from './TabBar/TabBar';
export {default as TabBarItem} from './TabBar/TabBarItem';
export {default as SegmentedControl} from './SegmentedControl';
export {default as LinearProgress} from './LinearProgress';
export {default as CircleProgress} from './CircleProgress';
export {default as Carousel} from './Carousel';
export {default as Badge} from './Badge';
export {default as Toast} from './Toast';
export {default as Card} from './Card';
export {default as Switch} from './Switch';
export {default as Checkbox} from './Checkbox';
export {default as Radio} from './Radio';
export {default as RadioGroup} from './Radio/RadioGroup';
export {default as Ellipsis} from './Ellipsis';
export {default as Table} from './Table';
export {default as Arrow} from './Arrow';
export {default as Slider} from './Slider';
export {default as Popup} from './Popup';
export {default as Panel} from './Panel';
export {default as InputItem} from './InputItem';
export {default as TextareaItem} from './TextareaItem';
export {default as Dialog} from './Dialog';
export {createDialog} from './Dialog';
export {default as ScrollerView} from './ScrollerView';
//TODO: 优先级按照如下顺序
//export {default as NavBar} from './NavBar';
//export {default as SearchBar} from './SearchBar';
//export {default as Picker} from './Picker';
//export {default as DatePicker} from './DatePicker'; ios and 安卓两种 参考material-ui & andt-mobile & mint-ui | {
return;
} | conditional_block |
index.tsx | /// <reference path="../typings/index.d.ts" />
import * as injectTapEventPlugin from 'react-tap-event-plugin';
import animationFrame from './util/animationFrame';
injectTapEventPlugin();
animationFrame();
interface CustomerElement extends Element{
blur?: ()=>{}
}
function blurActiveInput(e) {
if(e.target.tagName == "INPUT" || e.target.tagName == 'TEXTAREA') {
return;
}
var activeElement = document.activeElement as CustomerElement;
if(activeElement.tagName == "INPUT" || activeElement.tagName == "TEXTAREA") {
activeElement.blur && activeElement.blur();
}
}
document.addEventListener('touchstart', blurActiveInput, false)
export {colors} from './styles/colors';
export {default as Alert} from './Alert';
export {default as Button} from './Button';
export {default as Icon} from './Icon';
export {default as Line} from './Line';
export {default as Tabs} from './Tabs';
export {default as Tab} from './Tabs/Tab';
export {default as TabBar} from './TabBar/TabBar';
export {default as TabBarItem} from './TabBar/TabBarItem';
export {default as SegmentedControl} from './SegmentedControl';
export {default as LinearProgress} from './LinearProgress';
export {default as CircleProgress} from './CircleProgress';
export {default as Carousel} from './Carousel'; | export {default as Toast} from './Toast';
export {default as Card} from './Card';
export {default as Switch} from './Switch';
export {default as Checkbox} from './Checkbox';
export {default as Radio} from './Radio';
export {default as RadioGroup} from './Radio/RadioGroup';
export {default as Ellipsis} from './Ellipsis';
export {default as Table} from './Table';
export {default as Arrow} from './Arrow';
export {default as Slider} from './Slider';
export {default as Popup} from './Popup';
export {default as Panel} from './Panel';
export {default as InputItem} from './InputItem';
export {default as TextareaItem} from './TextareaItem';
export {default as Dialog} from './Dialog';
export {createDialog} from './Dialog';
export {default as ScrollerView} from './ScrollerView';
//TODO: 优先级按照如下顺序
//export {default as NavBar} from './NavBar';
//export {default as SearchBar} from './SearchBar';
//export {default as Picker} from './Picker';
//export {default as DatePicker} from './DatePicker'; ios and 安卓两种 参考material-ui & andt-mobile & mint-ui | export {default as Badge} from './Badge'; | random_line_split |
index.tsx | /// <reference path="../typings/index.d.ts" />
import * as injectTapEventPlugin from 'react-tap-event-plugin';
import animationFrame from './util/animationFrame';
injectTapEventPlugin();
animationFrame();
interface CustomerElement extends Element{
blur?: ()=>{}
}
function blurActiveInput(e) |
document.addEventListener('touchstart', blurActiveInput, false)
export {colors} from './styles/colors';
export {default as Alert} from './Alert';
export {default as Button} from './Button';
export {default as Icon} from './Icon';
export {default as Line} from './Line';
export {default as Tabs} from './Tabs';
export {default as Tab} from './Tabs/Tab';
export {default as TabBar} from './TabBar/TabBar';
export {default as TabBarItem} from './TabBar/TabBarItem';
export {default as SegmentedControl} from './SegmentedControl';
export {default as LinearProgress} from './LinearProgress';
export {default as CircleProgress} from './CircleProgress';
export {default as Carousel} from './Carousel';
export {default as Badge} from './Badge';
export {default as Toast} from './Toast';
export {default as Card} from './Card';
export {default as Switch} from './Switch';
export {default as Checkbox} from './Checkbox';
export {default as Radio} from './Radio';
export {default as RadioGroup} from './Radio/RadioGroup';
export {default as Ellipsis} from './Ellipsis';
export {default as Table} from './Table';
export {default as Arrow} from './Arrow';
export {default as Slider} from './Slider';
export {default as Popup} from './Popup';
export {default as Panel} from './Panel';
export {default as InputItem} from './InputItem';
export {default as TextareaItem} from './TextareaItem';
export {default as Dialog} from './Dialog';
export {createDialog} from './Dialog';
export {default as ScrollerView} from './ScrollerView';
//TODO: 优先级按照如下顺序
//export {default as NavBar} from './NavBar';
//export {default as SearchBar} from './SearchBar';
//export {default as Picker} from './Picker';
//export {default as DatePicker} from './DatePicker'; ios and 安卓两种 参考material-ui & andt-mobile & mint-ui | {
if(e.target.tagName == "INPUT" || e.target.tagName == 'TEXTAREA') {
return;
}
var activeElement = document.activeElement as CustomerElement;
if(activeElement.tagName == "INPUT" || activeElement.tagName == "TEXTAREA") {
activeElement.blur && activeElement.blur();
}
} | identifier_body |
docs.js | var Document = require('pelias-model').Document;
var docs = {};
docs.named = new Document('item1',1);
docs.named.setName('default','poi1');
docs.unnamed = new Document('item2',2); // no name
docs.unnamedWithAddress = new Document('item3',3);
docs.unnamedWithAddress.setCentroid({lat:3,lon:3});
docs.unnamedWithAddress.address = {
number: '10', street: 'Mapzen pl'
};
docs.namedWithAddress = new Document('item4',4);
docs.namedWithAddress.setName('default','poi4');
docs.namedWithAddress.setCentroid({lat:4,lon:4});
docs.namedWithAddress.address = {
number: '11', street: 'Sesame st'
};
docs.invalidId = new Document('item5',5);
docs.invalidId._meta.id = undefined; // unset the id
docs.invalidId.setCentroid({lat:5,lon:5});
docs.invalidId.address = {
number: '12', street: 'Old st'
};
docs.completeDoc = new Document('item6',6);
docs.completeDoc.address = {
number: '13', street: 'Goldsmiths row', test: 'prop'
};
docs.completeDoc
.setName('default','item6')
.setName('alt','item six')
.setCentroid({lat:6,lon:6})
.setAlpha3('FOO')
.setAdmin('admin0','country')
.setAdmin('admin1','state')
.setAdmin('admin1_abbr','STA')
.setAdmin('admin2','city')
.setAdmin('local_admin','borough') | .setAdmin('locality','town')
.setAdmin('neighborhood','hood')
.setMeta('foo','bar')
.setMeta('bing','bang');
docs.osmNode1 = new Document('item7',7)
.setName('osmnode','node7')
.setCentroid({lat:7,lon:7});
docs.osmWay1 = new Document('osmway',8)
.setName('osmway','way8')
.setMeta('nodes', [
{ lat: 10, lon: 10 },
{ lat: 06, lon: 10 },
{ lat: 06, lon: 06 },
{ lat: 10, lon: 06 }
]);
docs.osmRelation1 = new Document('item9',9)
.setName('osmrelation','relation9')
.setCentroid({lat:9,lon:9});
// ref: https://github.com/pelias/openstreetmap/issues/21
docs.semicolonStreetNumbers = new Document('item10',10);
docs.semicolonStreetNumbers.setName('default','poi10');
docs.semicolonStreetNumbers.setCentroid({lat:10,lon:10});
docs.semicolonStreetNumbers.address = {
number: '1; 2 ;3', street: 'Pennine Road'
};
// has no 'nodes' and a preset centroid
docs.osmWay2 = new Document('osmway',11)
.setName('osmway','way11')
.setCentroid({lat:11,lon:11});
module.exports = docs; | random_line_split | |
CodeEditor.tsx | import * as React from 'react'
import * as Codemirror from 'react-codemirror'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/mdn-like.css'
import './CodeEditor.css'
| onChange?: (...args: any[]) => any
}
export default class CodeEditor extends React.Component<P> {
static defaultProps = {
value: '',
onChange: (e: any) => e,
}
state = {
value: this.props.value,
}
componentWillReceiveProps(nextProps: any) {
this.setState({
value: nextProps.value,
})
}
updateCode = (newCode: string) => {
this.props.onChange!(newCode)
}
render() {
return (
<Codemirror
value={this.state.value}
onChange={this.updateCode}
options={{
mode: 'javascript',
theme: 'mdn-like',
indentUnit: 2,
tabSize: 2,
lineNumbers: true,
extraKeys: {
Tab: (cm: any) => {
const spacesPerTab = cm.getOption('indentUnit')
const spacesToInsert =
spacesPerTab - (cm.doc.getCursor('start').ch % spacesPerTab)
const spaces = ' '.repeat(spacesToInsert)
cm.replaceSelection(spaces, 'end', '+input')
},
},
}}
/>
)
}
} | interface P {
value?: string | random_line_split |
CodeEditor.tsx | import * as React from 'react'
import * as Codemirror from 'react-codemirror'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/mdn-like.css'
import './CodeEditor.css'
interface P {
value?: string
onChange?: (...args: any[]) => any
}
export default class CodeEditor extends React.Component<P> {
static defaultProps = {
value: '',
onChange: (e: any) => e,
}
state = {
value: this.props.value,
}
| (nextProps: any) {
this.setState({
value: nextProps.value,
})
}
updateCode = (newCode: string) => {
this.props.onChange!(newCode)
}
render() {
return (
<Codemirror
value={this.state.value}
onChange={this.updateCode}
options={{
mode: 'javascript',
theme: 'mdn-like',
indentUnit: 2,
tabSize: 2,
lineNumbers: true,
extraKeys: {
Tab: (cm: any) => {
const spacesPerTab = cm.getOption('indentUnit')
const spacesToInsert =
spacesPerTab - (cm.doc.getCursor('start').ch % spacesPerTab)
const spaces = ' '.repeat(spacesToInsert)
cm.replaceSelection(spaces, 'end', '+input')
},
},
}}
/>
)
}
}
| componentWillReceiveProps | identifier_name |
CodeEditor.tsx | import * as React from 'react'
import * as Codemirror from 'react-codemirror'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/mdn-like.css'
import './CodeEditor.css'
interface P {
value?: string
onChange?: (...args: any[]) => any
}
export default class CodeEditor extends React.Component<P> {
static defaultProps = {
value: '',
onChange: (e: any) => e,
}
state = {
value: this.props.value,
}
componentWillReceiveProps(nextProps: any) |
updateCode = (newCode: string) => {
this.props.onChange!(newCode)
}
render() {
return (
<Codemirror
value={this.state.value}
onChange={this.updateCode}
options={{
mode: 'javascript',
theme: 'mdn-like',
indentUnit: 2,
tabSize: 2,
lineNumbers: true,
extraKeys: {
Tab: (cm: any) => {
const spacesPerTab = cm.getOption('indentUnit')
const spacesToInsert =
spacesPerTab - (cm.doc.getCursor('start').ch % spacesPerTab)
const spaces = ' '.repeat(spacesToInsert)
cm.replaceSelection(spaces, 'end', '+input')
},
},
}}
/>
)
}
}
| {
this.setState({
value: nextProps.value,
})
} | identifier_body |
event-logging-strategy-test.ts | import Coordinator, {
EventLoggingStrategy
} from '../../src/index';
import {
Source,
Transform,
TransformBuilder,
buildTransform
} from '@orbit/data';
import '../test-helper';
declare const RSVP: any;
const { all } = RSVP;
const { module, test } = QUnit;
module('EventLoggingStrategy', function(hooks) {
const t = new TransformBuilder();
const tA = buildTransform([t.addRecord({ type: 'planet', id: 'a', attributes: { name: 'a' } })], null, 'a');
const tB = buildTransform([t.addRecord({ type: 'planet', id: 'b', attributes: { name: 'b' } })], null, 'b');
const tC = buildTransform([t.addRecord({ type: 'planet', id: 'c', attributes: { name: 'c' } })], null, 'c');
let eventLoggingStrategy;
test('can be instantiated', function(assert) {
eventLoggingStrategy = new EventLoggingStrategy();
assert.ok(eventLoggingStrategy);
});
test('can be added to a coordinator', function(assert) {
let coordinator = new Coordinator();
eventLoggingStrategy = new EventLoggingStrategy();
coordinator.addStrategy(eventLoggingStrategy);
assert.strictEqual(coordinator.getStrategy('event-logging'), eventLoggingStrategy);
});
test('for basic sources, installs `transform` listeners on activatation and removes them on deactivation', function(assert) {
assert.expect(6);
class MySource extends Source {}
let s1 = new MySource({ name: 's1' });
let s2 = new MySource({ name: 's2' });
eventLoggingStrategy = new EventLoggingStrategy();
let coordinator = new Coordinator({ sources: [ s1, s2 ], strategies: [ eventLoggingStrategy ]});
assert.equal(s1.listeners('transform').length, 0);
assert.equal(s2.listeners('transform').length, 0);
return coordinator.activate()
.then(() => {
assert.equal(s1.listeners('transform').length, 1);
assert.equal(s2.listeners('transform').length, 1);
return coordinator.deactivate();
})
.then(() => {
assert.equal(s1.listeners('transform').length, 0);
assert.equal(s2.listeners('transform').length, 0);
}); |
// TODO:
// * test `interfaces` option
// * test adding sources that support different interfaces to ensure they're inspected properly
}); | }); | random_line_split |
event-logging-strategy-test.ts | import Coordinator, {
EventLoggingStrategy
} from '../../src/index';
import {
Source,
Transform,
TransformBuilder,
buildTransform
} from '@orbit/data';
import '../test-helper';
declare const RSVP: any;
const { all } = RSVP;
const { module, test } = QUnit;
module('EventLoggingStrategy', function(hooks) {
const t = new TransformBuilder();
const tA = buildTransform([t.addRecord({ type: 'planet', id: 'a', attributes: { name: 'a' } })], null, 'a');
const tB = buildTransform([t.addRecord({ type: 'planet', id: 'b', attributes: { name: 'b' } })], null, 'b');
const tC = buildTransform([t.addRecord({ type: 'planet', id: 'c', attributes: { name: 'c' } })], null, 'c');
let eventLoggingStrategy;
test('can be instantiated', function(assert) {
eventLoggingStrategy = new EventLoggingStrategy();
assert.ok(eventLoggingStrategy);
});
test('can be added to a coordinator', function(assert) {
let coordinator = new Coordinator();
eventLoggingStrategy = new EventLoggingStrategy();
coordinator.addStrategy(eventLoggingStrategy);
assert.strictEqual(coordinator.getStrategy('event-logging'), eventLoggingStrategy);
});
test('for basic sources, installs `transform` listeners on activatation and removes them on deactivation', function(assert) {
assert.expect(6);
class | extends Source {}
let s1 = new MySource({ name: 's1' });
let s2 = new MySource({ name: 's2' });
eventLoggingStrategy = new EventLoggingStrategy();
let coordinator = new Coordinator({ sources: [ s1, s2 ], strategies: [ eventLoggingStrategy ]});
assert.equal(s1.listeners('transform').length, 0);
assert.equal(s2.listeners('transform').length, 0);
return coordinator.activate()
.then(() => {
assert.equal(s1.listeners('transform').length, 1);
assert.equal(s2.listeners('transform').length, 1);
return coordinator.deactivate();
})
.then(() => {
assert.equal(s1.listeners('transform').length, 0);
assert.equal(s2.listeners('transform').length, 0);
});
});
// TODO:
// * test `interfaces` option
// * test adding sources that support different interfaces to ensure they're inspected properly
});
| MySource | identifier_name |
listdir.rs | // Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Helpers for reading directory structures from the local filesystem.
use std::fs;
use std::path::PathBuf;
use std::sync::mpsc;
use threadpool;
pub trait PathHandler<D> {
fn handle_path(&self, D, PathBuf) -> Option<D>;
}
pub fn iterate_recursively<P: 'static + Send + Clone, W: 'static + PathHandler<P> + Send + Clone>
(root: (PathBuf, P), worker: &mut W)
{
let threads = 10;
let (push_ch, work_ch) = mpsc::sync_channel(threads);
let pool = threadpool::ThreadPool::new(threads);
// Insert the first task into the queue:
push_ch.send(Some(root)).unwrap();
let mut running_workers = 0 as i32;
// Master thread:
loop {
match work_ch.recv() {
Err(_) => unreachable!(),
Ok(None) => {
// A worker has completed a task.
// We are done when no more workers are active (i.e. all tasks are done):
running_workers -= 1;
if running_workers == 0 {
break
}
},
Ok(Some((root, payload))) => {
// Execute the task in a pool thread:
running_workers += 1;
let _worker = worker.clone();
let _push_ch = push_ch.clone();
pool.execute(move|| {
let res = fs::read_dir(&root);
if res.is_ok() {
for entry in res.unwrap() {
if entry.is_ok() {
let entry = entry.unwrap();
let file = entry.path();
let path = PathBuf::from(file.to_str().unwrap());
let dir_opt = _worker.handle_path(payload.clone(), path);
if dir_opt.is_some() {
_push_ch.send(Some((file.clone(), dir_opt.unwrap()))).unwrap();
}
}
}
}
// Count this pool thread as idle:
_push_ch.send(None).unwrap();
});
}
}
}
}
struct PrintPathHandler;
impl Clone for PrintPathHandler {
fn clone(&self) -> PrintPathHandler { PrintPathHandler }
}
impl PathHandler<()> for PrintPathHandler {
fn handle_path(&self, _: (), path: PathBuf) -> Option<()> |
}
| {
println!("{}", path.display());
match fs::metadata(&path) {
Ok(ref m) if m.is_dir() => Some(()),
_ => None,
}
} | identifier_body |
listdir.rs | // Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Helpers for reading directory structures from the local filesystem.
use std::fs;
use std::path::PathBuf;
use std::sync::mpsc; | use threadpool;
pub trait PathHandler<D> {
fn handle_path(&self, D, PathBuf) -> Option<D>;
}
pub fn iterate_recursively<P: 'static + Send + Clone, W: 'static + PathHandler<P> + Send + Clone>
(root: (PathBuf, P), worker: &mut W)
{
let threads = 10;
let (push_ch, work_ch) = mpsc::sync_channel(threads);
let pool = threadpool::ThreadPool::new(threads);
// Insert the first task into the queue:
push_ch.send(Some(root)).unwrap();
let mut running_workers = 0 as i32;
// Master thread:
loop {
match work_ch.recv() {
Err(_) => unreachable!(),
Ok(None) => {
// A worker has completed a task.
// We are done when no more workers are active (i.e. all tasks are done):
running_workers -= 1;
if running_workers == 0 {
break
}
},
Ok(Some((root, payload))) => {
// Execute the task in a pool thread:
running_workers += 1;
let _worker = worker.clone();
let _push_ch = push_ch.clone();
pool.execute(move|| {
let res = fs::read_dir(&root);
if res.is_ok() {
for entry in res.unwrap() {
if entry.is_ok() {
let entry = entry.unwrap();
let file = entry.path();
let path = PathBuf::from(file.to_str().unwrap());
let dir_opt = _worker.handle_path(payload.clone(), path);
if dir_opt.is_some() {
_push_ch.send(Some((file.clone(), dir_opt.unwrap()))).unwrap();
}
}
}
}
// Count this pool thread as idle:
_push_ch.send(None).unwrap();
});
}
}
}
}
struct PrintPathHandler;
impl Clone for PrintPathHandler {
fn clone(&self) -> PrintPathHandler { PrintPathHandler }
}
impl PathHandler<()> for PrintPathHandler {
fn handle_path(&self, _: (), path: PathBuf) -> Option<()> {
println!("{}", path.display());
match fs::metadata(&path) {
Ok(ref m) if m.is_dir() => Some(()),
_ => None,
}
}
} | random_line_split | |
listdir.rs | // Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Helpers for reading directory structures from the local filesystem.
use std::fs;
use std::path::PathBuf;
use std::sync::mpsc;
use threadpool;
pub trait PathHandler<D> {
fn handle_path(&self, D, PathBuf) -> Option<D>;
}
pub fn | <P: 'static + Send + Clone, W: 'static + PathHandler<P> + Send + Clone>
(root: (PathBuf, P), worker: &mut W)
{
let threads = 10;
let (push_ch, work_ch) = mpsc::sync_channel(threads);
let pool = threadpool::ThreadPool::new(threads);
// Insert the first task into the queue:
push_ch.send(Some(root)).unwrap();
let mut running_workers = 0 as i32;
// Master thread:
loop {
match work_ch.recv() {
Err(_) => unreachable!(),
Ok(None) => {
// A worker has completed a task.
// We are done when no more workers are active (i.e. all tasks are done):
running_workers -= 1;
if running_workers == 0 {
break
}
},
Ok(Some((root, payload))) => {
// Execute the task in a pool thread:
running_workers += 1;
let _worker = worker.clone();
let _push_ch = push_ch.clone();
pool.execute(move|| {
let res = fs::read_dir(&root);
if res.is_ok() {
for entry in res.unwrap() {
if entry.is_ok() {
let entry = entry.unwrap();
let file = entry.path();
let path = PathBuf::from(file.to_str().unwrap());
let dir_opt = _worker.handle_path(payload.clone(), path);
if dir_opt.is_some() {
_push_ch.send(Some((file.clone(), dir_opt.unwrap()))).unwrap();
}
}
}
}
// Count this pool thread as idle:
_push_ch.send(None).unwrap();
});
}
}
}
}
struct PrintPathHandler;
impl Clone for PrintPathHandler {
fn clone(&self) -> PrintPathHandler { PrintPathHandler }
}
impl PathHandler<()> for PrintPathHandler {
fn handle_path(&self, _: (), path: PathBuf) -> Option<()> {
println!("{}", path.display());
match fs::metadata(&path) {
Ok(ref m) if m.is_dir() => Some(()),
_ => None,
}
}
}
| iterate_recursively | identifier_name |
error_handler.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {getDebugContext, getErrorLogger, getOriginalError} from './errors';
/**
* Provides a hook for centralized exception handling.
*
* The default implementation of `ErrorHandler` prints error messages to the `console`. To
* intercept error handling, write a custom exception handler that replaces this default as
* appropriate for your app.
*
* @usageNotes
* ### Example
*
* ```
* class MyErrorHandler implements ErrorHandler {
* handleError(error) {
* // do something with the exception
* }
* }
*
* @NgModule({
* providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
* })
* class MyModule {}
* ```
*
* @publicApi
*/
export class ErrorHandler {
/**
* @internal
*/
_console: Console = console;
handleError(error: any): void {
const originalError = this._findOriginalError(error);
const context = this._findContext(error);
// Note: Browser consoles show the place from where console.error was called.
// We can use this to give users additional information about the error.
const errorLogger = getErrorLogger(error);
errorLogger(this._console, `ERROR`, error);
if (originalError) {
errorLogger(this._console, `ORIGINAL ERROR`, originalError);
}
if (context) |
}
/** @internal */
_findContext(error: any): any {
if (error) {
return getDebugContext(error) ? getDebugContext(error) :
this._findContext(getOriginalError(error));
}
return null;
}
/** @internal */
_findOriginalError(error: Error): any {
let e = getOriginalError(error);
while (e && getOriginalError(e)) {
e = getOriginalError(e);
}
return e;
}
}
| {
errorLogger(this._console, 'ERROR CONTEXT', context);
} | conditional_block |
error_handler.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {getDebugContext, getErrorLogger, getOriginalError} from './errors';
/**
* Provides a hook for centralized exception handling.
*
* The default implementation of `ErrorHandler` prints error messages to the `console`. To
* intercept error handling, write a custom exception handler that replaces this default as
* appropriate for your app.
*
* @usageNotes
* ### Example
*
* ```
* class MyErrorHandler implements ErrorHandler {
* handleError(error) {
* // do something with the exception
* }
* }
*
* @NgModule({
* providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
* })
* class MyModule {}
* ```
*
* @publicApi
*/
export class ErrorHandler {
/**
* @internal
*/
_console: Console = console;
handleError(error: any): void {
const originalError = this._findOriginalError(error);
const context = this._findContext(error);
// Note: Browser consoles show the place from where console.error was called.
// We can use this to give users additional information about the error.
const errorLogger = getErrorLogger(error);
errorLogger(this._console, `ERROR`, error);
if (originalError) {
errorLogger(this._console, `ORIGINAL ERROR`, originalError);
}
if (context) {
errorLogger(this._console, 'ERROR CONTEXT', context);
}
}
/** @internal */
| (error: any): any {
if (error) {
return getDebugContext(error) ? getDebugContext(error) :
this._findContext(getOriginalError(error));
}
return null;
}
/** @internal */
_findOriginalError(error: Error): any {
let e = getOriginalError(error);
while (e && getOriginalError(e)) {
e = getOriginalError(e);
}
return e;
}
}
| _findContext | identifier_name |
error_handler.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {getDebugContext, getErrorLogger, getOriginalError} from './errors';
/**
* Provides a hook for centralized exception handling.
*
* The default implementation of `ErrorHandler` prints error messages to the `console`. To
* intercept error handling, write a custom exception handler that replaces this default as
* appropriate for your app.
*
* @usageNotes
* ### Example
*
* ```
* class MyErrorHandler implements ErrorHandler {
* handleError(error) {
* // do something with the exception
* }
* }
*
* @NgModule({
* providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
* })
* class MyModule {}
* ```
*
* @publicApi
*/
export class ErrorHandler {
/**
* @internal
*/
_console: Console = console;
handleError(error: any): void {
const originalError = this._findOriginalError(error);
const context = this._findContext(error);
// Note: Browser consoles show the place from where console.error was called.
// We can use this to give users additional information about the error.
const errorLogger = getErrorLogger(error);
errorLogger(this._console, `ERROR`, error);
if (originalError) {
errorLogger(this._console, `ORIGINAL ERROR`, originalError);
}
if (context) {
errorLogger(this._console, 'ERROR CONTEXT', context);
}
}
/** @internal */
_findContext(error: any): any |
/** @internal */
_findOriginalError(error: Error): any {
let e = getOriginalError(error);
while (e && getOriginalError(e)) {
e = getOriginalError(e);
}
return e;
}
}
| {
if (error) {
return getDebugContext(error) ? getDebugContext(error) :
this._findContext(getOriginalError(error));
}
return null;
} | identifier_body |
error_handler.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {getDebugContext, getErrorLogger, getOriginalError} from './errors';
/**
* Provides a hook for centralized exception handling.
*
* The default implementation of `ErrorHandler` prints error messages to the `console`. To
* intercept error handling, write a custom exception handler that replaces this default as
* appropriate for your app.
*
* @usageNotes
* ### Example
* | * handleError(error) {
* // do something with the exception
* }
* }
*
* @NgModule({
* providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
* })
* class MyModule {}
* ```
*
* @publicApi
*/
export class ErrorHandler {
/**
* @internal
*/
_console: Console = console;
handleError(error: any): void {
const originalError = this._findOriginalError(error);
const context = this._findContext(error);
// Note: Browser consoles show the place from where console.error was called.
// We can use this to give users additional information about the error.
const errorLogger = getErrorLogger(error);
errorLogger(this._console, `ERROR`, error);
if (originalError) {
errorLogger(this._console, `ORIGINAL ERROR`, originalError);
}
if (context) {
errorLogger(this._console, 'ERROR CONTEXT', context);
}
}
/** @internal */
_findContext(error: any): any {
if (error) {
return getDebugContext(error) ? getDebugContext(error) :
this._findContext(getOriginalError(error));
}
return null;
}
/** @internal */
_findOriginalError(error: Error): any {
let e = getOriginalError(error);
while (e && getOriginalError(e)) {
e = getOriginalError(e);
}
return e;
}
} | * ```
* class MyErrorHandler implements ErrorHandler { | random_line_split |
convert_engine.py | from __future__ import unicode_literals, with_statement
import re
import os
import subprocess
from collections import OrderedDict
from django.utils.encoding import smart_str
from django.core.files.temp import NamedTemporaryFile
from sorl.thumbnail.base import EXTENSIONS
from sorl.thumbnail.compat import b
from sorl.thumbnail.conf import settings
from sorl.thumbnail.engines.base import EngineBase
size_re = re.compile(r'^(?:.+) (?:[A-Z]+) (?P<x>\d+)x(?P<y>\d+)')
class Engine(EngineBase):
"""
Image object is a dict with source path, options and size
"""
def write(self, image, options, thumbnail):
"""
Writes the thumbnail image
"""
if options['format'] == 'JPEG' and options.get(
'progressive', settings.THUMBNAIL_PROGRESSIVE):
image['options']['interlace'] = 'line'
image['options']['quality'] = options['quality']
args = settings.THUMBNAIL_CONVERT.split(' ')
args.append(image['source'] + '[0]')
for k in image['options']:
v = image['options'][k]
args.append('-%s' % k)
if v is not None:
args.append('%s' % v)
flatten = "on"
if 'flatten' in options:
flatten = options['flatten']
if settings.THUMBNAIL_FLATTEN and not flatten == "off":
args.append('-flatten')
suffix = '.%s' % EXTENSIONS[options['format']]
with NamedTemporaryFile(suffix=suffix, mode='rb') as fp: | args = map(smart_str, args)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
out, err = p.communicate()
if err:
raise Exception(err)
thumbnail.write(fp.read())
def cleanup(self, image):
os.remove(image['source']) # we should not need this now
def get_image(self, source):
"""
Returns the backend image objects from a ImageFile instance
"""
with NamedTemporaryFile(mode='wb', delete=False) as fp:
fp.write(source.read())
return {'source': fp.name, 'options': OrderedDict(), 'size': None}
def get_image_size(self, image):
"""
Returns the image width and height as a tuple
"""
if image['size'] is None:
args = settings.THUMBNAIL_IDENTIFY.split(' ')
args.append(image['source'])
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
m = size_re.match(str(p.stdout.read()))
image['size'] = int(m.group('x')), int(m.group('y'))
return image['size']
def is_valid_image(self, raw_data):
"""
This is not very good for imagemagick because it will say anything is
valid that it can use as input.
"""
with NamedTemporaryFile(mode='wb') as fp:
fp.write(raw_data)
fp.flush()
args = settings.THUMBNAIL_IDENTIFY.split(' ')
args.append(fp.name)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
retcode = p.wait()
return retcode == 0
def _orientation(self, image):
# return image
# XXX need to get the dimensions right after a transpose.
if settings.THUMBNAIL_CONVERT.endswith('gm convert'):
args = settings.THUMBNAIL_IDENTIFY.split()
args.extend(['-format', '%[exif:orientation]', image['source']])
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
result = p.stdout.read().strip()
if result and result != b('unknown'):
result = int(result)
options = image['options']
if result == 2:
options['flop'] = None
elif result == 3:
options['rotate'] = '180'
elif result == 4:
options['flip'] = None
elif result == 5:
options['rotate'] = '90'
options['flop'] = None
elif result == 6:
options['rotate'] = '90'
elif result == 7:
options['rotate'] = '-90'
options['flop'] = None
elif result == 8:
options['rotate'] = '-90'
else:
# ImageMagick also corrects the orientation exif data for
# destination
image['options']['auto-orient'] = None
return image
def _flip_dimensions(self, image):
if settings.THUMBNAIL_CONVERT.endswith('gm convert'):
args = settings.THUMBNAIL_IDENTIFY.split()
args.extend(['-format', '%[exif:orientation]', image['source']])
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
result = p.stdout.read().strip()
return result != 'unknown' and int(result) in [5, 6, 7, 8]
else:
return False
def _colorspace(self, image, colorspace):
"""
`Valid colorspaces
<http://www.graphicsmagick.org/GraphicsMagick.html#details-colorspace>`_.
Backends need to implement the following::
RGB, GRAY
"""
image['options']['colorspace'] = colorspace
return image
def _crop(self, image, width, height, x_offset, y_offset):
"""
Crops the image
"""
image['options']['crop'] = '%sx%s+%s+%s' % (width, height, x_offset, y_offset)
image['size'] = (width, height) # update image size
return image
def _scale(self, image, width, height):
"""
Does the resizing of the image
"""
image['options']['scale'] = '%sx%s!' % (width, height)
image['size'] = (width, height) # update image size
return image
def _padding(self, image, geometry, options):
"""
Pads the image
"""
# The order is important. The gravity option should come before extent.
image['options']['background'] = options.get('padding_color')
image['options']['gravity'] = 'center'
image['options']['extent'] = '%sx%s' % (geometry[0], geometry[1])
return image | args.append(fp.name) | random_line_split |
convert_engine.py | from __future__ import unicode_literals, with_statement
import re
import os
import subprocess
from collections import OrderedDict
from django.utils.encoding import smart_str
from django.core.files.temp import NamedTemporaryFile
from sorl.thumbnail.base import EXTENSIONS
from sorl.thumbnail.compat import b
from sorl.thumbnail.conf import settings
from sorl.thumbnail.engines.base import EngineBase
size_re = re.compile(r'^(?:.+) (?:[A-Z]+) (?P<x>\d+)x(?P<y>\d+)')
class Engine(EngineBase):
"""
Image object is a dict with source path, options and size
"""
def write(self, image, options, thumbnail):
"""
Writes the thumbnail image
"""
if options['format'] == 'JPEG' and options.get(
'progressive', settings.THUMBNAIL_PROGRESSIVE):
image['options']['interlace'] = 'line'
image['options']['quality'] = options['quality']
args = settings.THUMBNAIL_CONVERT.split(' ')
args.append(image['source'] + '[0]')
for k in image['options']:
v = image['options'][k]
args.append('-%s' % k)
if v is not None:
args.append('%s' % v)
flatten = "on"
if 'flatten' in options:
flatten = options['flatten']
if settings.THUMBNAIL_FLATTEN and not flatten == "off":
|
suffix = '.%s' % EXTENSIONS[options['format']]
with NamedTemporaryFile(suffix=suffix, mode='rb') as fp:
args.append(fp.name)
args = map(smart_str, args)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
out, err = p.communicate()
if err:
raise Exception(err)
thumbnail.write(fp.read())
def cleanup(self, image):
os.remove(image['source']) # we should not need this now
def get_image(self, source):
"""
Returns the backend image objects from a ImageFile instance
"""
with NamedTemporaryFile(mode='wb', delete=False) as fp:
fp.write(source.read())
return {'source': fp.name, 'options': OrderedDict(), 'size': None}
def get_image_size(self, image):
"""
Returns the image width and height as a tuple
"""
if image['size'] is None:
args = settings.THUMBNAIL_IDENTIFY.split(' ')
args.append(image['source'])
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
m = size_re.match(str(p.stdout.read()))
image['size'] = int(m.group('x')), int(m.group('y'))
return image['size']
def is_valid_image(self, raw_data):
"""
This is not very good for imagemagick because it will say anything is
valid that it can use as input.
"""
with NamedTemporaryFile(mode='wb') as fp:
fp.write(raw_data)
fp.flush()
args = settings.THUMBNAIL_IDENTIFY.split(' ')
args.append(fp.name)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
retcode = p.wait()
return retcode == 0
def _orientation(self, image):
# return image
# XXX need to get the dimensions right after a transpose.
if settings.THUMBNAIL_CONVERT.endswith('gm convert'):
args = settings.THUMBNAIL_IDENTIFY.split()
args.extend(['-format', '%[exif:orientation]', image['source']])
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
result = p.stdout.read().strip()
if result and result != b('unknown'):
result = int(result)
options = image['options']
if result == 2:
options['flop'] = None
elif result == 3:
options['rotate'] = '180'
elif result == 4:
options['flip'] = None
elif result == 5:
options['rotate'] = '90'
options['flop'] = None
elif result == 6:
options['rotate'] = '90'
elif result == 7:
options['rotate'] = '-90'
options['flop'] = None
elif result == 8:
options['rotate'] = '-90'
else:
# ImageMagick also corrects the orientation exif data for
# destination
image['options']['auto-orient'] = None
return image
def _flip_dimensions(self, image):
if settings.THUMBNAIL_CONVERT.endswith('gm convert'):
args = settings.THUMBNAIL_IDENTIFY.split()
args.extend(['-format', '%[exif:orientation]', image['source']])
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
result = p.stdout.read().strip()
return result != 'unknown' and int(result) in [5, 6, 7, 8]
else:
return False
def _colorspace(self, image, colorspace):
"""
`Valid colorspaces
<http://www.graphicsmagick.org/GraphicsMagick.html#details-colorspace>`_.
Backends need to implement the following::
RGB, GRAY
"""
image['options']['colorspace'] = colorspace
return image
def _crop(self, image, width, height, x_offset, y_offset):
"""
Crops the image
"""
image['options']['crop'] = '%sx%s+%s+%s' % (width, height, x_offset, y_offset)
image['size'] = (width, height) # update image size
return image
def _scale(self, image, width, height):
"""
Does the resizing of the image
"""
image['options']['scale'] = '%sx%s!' % (width, height)
image['size'] = (width, height) # update image size
return image
def _padding(self, image, geometry, options):
"""
Pads the image
"""
# The order is important. The gravity option should come before extent.
image['options']['background'] = options.get('padding_color')
image['options']['gravity'] = 'center'
image['options']['extent'] = '%sx%s' % (geometry[0], geometry[1])
return image
| args.append('-flatten') | conditional_block |
convert_engine.py | from __future__ import unicode_literals, with_statement
import re
import os
import subprocess
from collections import OrderedDict
from django.utils.encoding import smart_str
from django.core.files.temp import NamedTemporaryFile
from sorl.thumbnail.base import EXTENSIONS
from sorl.thumbnail.compat import b
from sorl.thumbnail.conf import settings
from sorl.thumbnail.engines.base import EngineBase
size_re = re.compile(r'^(?:.+) (?:[A-Z]+) (?P<x>\d+)x(?P<y>\d+)')
class Engine(EngineBase):
"""
Image object is a dict with source path, options and size
"""
def write(self, image, options, thumbnail):
"""
Writes the thumbnail image
"""
if options['format'] == 'JPEG' and options.get(
'progressive', settings.THUMBNAIL_PROGRESSIVE):
image['options']['interlace'] = 'line'
image['options']['quality'] = options['quality']
args = settings.THUMBNAIL_CONVERT.split(' ')
args.append(image['source'] + '[0]')
for k in image['options']:
v = image['options'][k]
args.append('-%s' % k)
if v is not None:
args.append('%s' % v)
flatten = "on"
if 'flatten' in options:
flatten = options['flatten']
if settings.THUMBNAIL_FLATTEN and not flatten == "off":
args.append('-flatten')
suffix = '.%s' % EXTENSIONS[options['format']]
with NamedTemporaryFile(suffix=suffix, mode='rb') as fp:
args.append(fp.name)
args = map(smart_str, args)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
out, err = p.communicate()
if err:
raise Exception(err)
thumbnail.write(fp.read())
def cleanup(self, image):
os.remove(image['source']) # we should not need this now
def get_image(self, source):
"""
Returns the backend image objects from a ImageFile instance
"""
with NamedTemporaryFile(mode='wb', delete=False) as fp:
fp.write(source.read())
return {'source': fp.name, 'options': OrderedDict(), 'size': None}
def get_image_size(self, image):
"""
Returns the image width and height as a tuple
"""
if image['size'] is None:
args = settings.THUMBNAIL_IDENTIFY.split(' ')
args.append(image['source'])
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
m = size_re.match(str(p.stdout.read()))
image['size'] = int(m.group('x')), int(m.group('y'))
return image['size']
def is_valid_image(self, raw_data):
"""
This is not very good for imagemagick because it will say anything is
valid that it can use as input.
"""
with NamedTemporaryFile(mode='wb') as fp:
fp.write(raw_data)
fp.flush()
args = settings.THUMBNAIL_IDENTIFY.split(' ')
args.append(fp.name)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
retcode = p.wait()
return retcode == 0
def _orientation(self, image):
# return image
# XXX need to get the dimensions right after a transpose.
if settings.THUMBNAIL_CONVERT.endswith('gm convert'):
args = settings.THUMBNAIL_IDENTIFY.split()
args.extend(['-format', '%[exif:orientation]', image['source']])
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
result = p.stdout.read().strip()
if result and result != b('unknown'):
result = int(result)
options = image['options']
if result == 2:
options['flop'] = None
elif result == 3:
options['rotate'] = '180'
elif result == 4:
options['flip'] = None
elif result == 5:
options['rotate'] = '90'
options['flop'] = None
elif result == 6:
options['rotate'] = '90'
elif result == 7:
options['rotate'] = '-90'
options['flop'] = None
elif result == 8:
options['rotate'] = '-90'
else:
# ImageMagick also corrects the orientation exif data for
# destination
image['options']['auto-orient'] = None
return image
def _flip_dimensions(self, image):
if settings.THUMBNAIL_CONVERT.endswith('gm convert'):
args = settings.THUMBNAIL_IDENTIFY.split()
args.extend(['-format', '%[exif:orientation]', image['source']])
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
result = p.stdout.read().strip()
return result != 'unknown' and int(result) in [5, 6, 7, 8]
else:
return False
def _colorspace(self, image, colorspace):
"""
`Valid colorspaces
<http://www.graphicsmagick.org/GraphicsMagick.html#details-colorspace>`_.
Backends need to implement the following::
RGB, GRAY
"""
image['options']['colorspace'] = colorspace
return image
def _crop(self, image, width, height, x_offset, y_offset):
"""
Crops the image
"""
image['options']['crop'] = '%sx%s+%s+%s' % (width, height, x_offset, y_offset)
image['size'] = (width, height) # update image size
return image
def _scale(self, image, width, height):
"""
Does the resizing of the image
"""
image['options']['scale'] = '%sx%s!' % (width, height)
image['size'] = (width, height) # update image size
return image
def | (self, image, geometry, options):
"""
Pads the image
"""
# The order is important. The gravity option should come before extent.
image['options']['background'] = options.get('padding_color')
image['options']['gravity'] = 'center'
image['options']['extent'] = '%sx%s' % (geometry[0], geometry[1])
return image
| _padding | identifier_name |
convert_engine.py | from __future__ import unicode_literals, with_statement
import re
import os
import subprocess
from collections import OrderedDict
from django.utils.encoding import smart_str
from django.core.files.temp import NamedTemporaryFile
from sorl.thumbnail.base import EXTENSIONS
from sorl.thumbnail.compat import b
from sorl.thumbnail.conf import settings
from sorl.thumbnail.engines.base import EngineBase
size_re = re.compile(r'^(?:.+) (?:[A-Z]+) (?P<x>\d+)x(?P<y>\d+)')
class Engine(EngineBase):
| """
Image object is a dict with source path, options and size
"""
def write(self, image, options, thumbnail):
"""
Writes the thumbnail image
"""
if options['format'] == 'JPEG' and options.get(
'progressive', settings.THUMBNAIL_PROGRESSIVE):
image['options']['interlace'] = 'line'
image['options']['quality'] = options['quality']
args = settings.THUMBNAIL_CONVERT.split(' ')
args.append(image['source'] + '[0]')
for k in image['options']:
v = image['options'][k]
args.append('-%s' % k)
if v is not None:
args.append('%s' % v)
flatten = "on"
if 'flatten' in options:
flatten = options['flatten']
if settings.THUMBNAIL_FLATTEN and not flatten == "off":
args.append('-flatten')
suffix = '.%s' % EXTENSIONS[options['format']]
with NamedTemporaryFile(suffix=suffix, mode='rb') as fp:
args.append(fp.name)
args = map(smart_str, args)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
out, err = p.communicate()
if err:
raise Exception(err)
thumbnail.write(fp.read())
def cleanup(self, image):
os.remove(image['source']) # we should not need this now
def get_image(self, source):
"""
Returns the backend image objects from a ImageFile instance
"""
with NamedTemporaryFile(mode='wb', delete=False) as fp:
fp.write(source.read())
return {'source': fp.name, 'options': OrderedDict(), 'size': None}
def get_image_size(self, image):
"""
Returns the image width and height as a tuple
"""
if image['size'] is None:
args = settings.THUMBNAIL_IDENTIFY.split(' ')
args.append(image['source'])
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
m = size_re.match(str(p.stdout.read()))
image['size'] = int(m.group('x')), int(m.group('y'))
return image['size']
def is_valid_image(self, raw_data):
"""
This is not very good for imagemagick because it will say anything is
valid that it can use as input.
"""
with NamedTemporaryFile(mode='wb') as fp:
fp.write(raw_data)
fp.flush()
args = settings.THUMBNAIL_IDENTIFY.split(' ')
args.append(fp.name)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
retcode = p.wait()
return retcode == 0
def _orientation(self, image):
# return image
# XXX need to get the dimensions right after a transpose.
if settings.THUMBNAIL_CONVERT.endswith('gm convert'):
args = settings.THUMBNAIL_IDENTIFY.split()
args.extend(['-format', '%[exif:orientation]', image['source']])
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
result = p.stdout.read().strip()
if result and result != b('unknown'):
result = int(result)
options = image['options']
if result == 2:
options['flop'] = None
elif result == 3:
options['rotate'] = '180'
elif result == 4:
options['flip'] = None
elif result == 5:
options['rotate'] = '90'
options['flop'] = None
elif result == 6:
options['rotate'] = '90'
elif result == 7:
options['rotate'] = '-90'
options['flop'] = None
elif result == 8:
options['rotate'] = '-90'
else:
# ImageMagick also corrects the orientation exif data for
# destination
image['options']['auto-orient'] = None
return image
def _flip_dimensions(self, image):
if settings.THUMBNAIL_CONVERT.endswith('gm convert'):
args = settings.THUMBNAIL_IDENTIFY.split()
args.extend(['-format', '%[exif:orientation]', image['source']])
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
result = p.stdout.read().strip()
return result != 'unknown' and int(result) in [5, 6, 7, 8]
else:
return False
def _colorspace(self, image, colorspace):
"""
`Valid colorspaces
<http://www.graphicsmagick.org/GraphicsMagick.html#details-colorspace>`_.
Backends need to implement the following::
RGB, GRAY
"""
image['options']['colorspace'] = colorspace
return image
def _crop(self, image, width, height, x_offset, y_offset):
"""
Crops the image
"""
image['options']['crop'] = '%sx%s+%s+%s' % (width, height, x_offset, y_offset)
image['size'] = (width, height) # update image size
return image
def _scale(self, image, width, height):
"""
Does the resizing of the image
"""
image['options']['scale'] = '%sx%s!' % (width, height)
image['size'] = (width, height) # update image size
return image
def _padding(self, image, geometry, options):
"""
Pads the image
"""
# The order is important. The gravity option should come before extent.
image['options']['background'] = options.get('padding_color')
image['options']['gravity'] = 'center'
image['options']['extent'] = '%sx%s' % (geometry[0], geometry[1])
return image | identifier_body | |
common-driver.js | var webdriver = require('selenium-webdriver');
var By = webdriver.By;
var SauceLabs = require("saucelabs");
var fs = require("fs");
var until = webdriver.until;
module.exports = {
failIfTrue: function(done, failMessage) {
return function(result) {
if(result) done(failMessage);
}
},
failIfFalse: function(done, failMessage) {
return function(result) {
if(!result) done(failMessage);
}
},
failed: function(done, failMessage) {
return function(reason) {
done(reason + "::" + failMessage);
}
},
failuresOccured: function() {
return jasmine.getEnv().currentSpec.results_.failedCount > 0;
},
|
if (this.saucelabs.username != null) {
var spec = jasmine.getEnv().currentSpec;
this.updateJob(driver, {passed: spec.results_.totalCount == spec.results_.passedCount})()
.then(driver.quit())
.then(function() { console.log("Setting test status"); })
.then(done);
} else {
driver.quit();
done();
}
},
updateJob: function(driver, options) {
if (this.saucelabs.username == null)
{
return function() {}; // No op. Assume running locally.
}
return function() {
return new Promise(function(resolve, reject) {
this.saucelabs.updateJob(driver.sessionID, options, resolve);
});
};
},
updateDriverSessionId: function(driver) {
return function(session) {
driver.sessionID = session.id_;
}
},
setupDriver: function(sauceUsername, sauceKey, extensionUrl, octopusUrl, octopusPassword, testIdFilename, octopusVersion, bluefinVersion, done) {
saucelabs = new SauceLabs({
username: sauceUsername,
password: sauceKey
});
var result = new webdriver.Builder().
withCapabilities({
'name': 'Spec run in node',
'build': bluefinVersion + "-" + octopusVersion,
'browserName': 'chrome',
'platform': 'Windows 10',
'version': '43.0',
'username': sauceUsername,
'accessKey': sauceKey,
'prerun': {
'executable': 'https://gist.githubusercontent.com/davidroberts63/b7c01e7aa945cde9064aca04e947288a/raw/GetExtension.bat',
'args': [ extensionUrl ]
},
"chromeOptions": {
"args": [
"--load-extension=C:\\bluefin-extension",
"start-maximized",
"disable-webgl",
"blacklist-webgl",
"blacklist-accelerated-compositing",
"disable-accelerated-2d-canvas",
"disable-accelerated-compositing",
"disable-accelerated-layers",
"disable-accelerated-plugins",
"disable-accelerated-video",
"disable-accelerated-video-decode",
"disable-gpu",
"disable-infobars",
"test-type"
]
},
});
// Run against SauceLabs or just run locally.
if(sauceUsername != null) {
result = result.usingServer("http://" + sauceUsername + ":" + sauceKey + "@ondemand.saucelabs.com:80/wd/hub");
}
result = result.build();
var spec = jasmine.getEnv().currentSpec;
result.getSession()
.then(this.updateDriverSessionId(result))
.then(this.updateJob(result, {name: spec.suite.description + ' ' + spec.description}))
.then(this.outputTestIdentifier(testIdFilename, result, spec.suite.description + " " + spec.description))
.then(this.closeOptionsTab(result))
.then(this.login(result, octopusUrl, octopusPassword, done))
.then(done);
return result;
},
outputTestIdentifier: function(filename, driver, name) {
return function() {
return new Promise(function(resolve, reject) {
fs.appendFile(filename, driver.sessionID + "~" + name + "\n", "utf8", resolve);
});
}
},
closeOptionsTab: function(driver) {
return function() {
return driver.getAllWindowHandles().then(function(handles) {
driver.switchTo().window(handles[1]);
driver.findElement(By.id("analytics")).click();
driver.findElement(By.id("save")).click();
driver.close();
driver.switchTo().window(handles[0]);
driver.navigate().refresh();
});
}
},
login: function(driver, url, password, done) {
var tests = this;
return function() {
driver.get(url);
driver.wait(until.elementLocated(By.id("inputUsername")), 3000, "Didn't get the login page.").thenCatch(done);
driver.findElement(By.id("inputUsername")).sendKeys("JoeAdministrator");
driver.findElement(By.id("inputPassword")).sendKeys(password);
driver.findElement(By.css("button.btn.btn-success[type='submit']")).click();
return driver.sleep(3000).then();
}
}
}; | saucelabs: {},
setTestStatus: function(driver, done) {
driver.controlFlow().reset(); // Discontinue any further driver actions that may have been defined. | random_line_split |
common-driver.js | var webdriver = require('selenium-webdriver');
var By = webdriver.By;
var SauceLabs = require("saucelabs");
var fs = require("fs");
var until = webdriver.until;
module.exports = {
failIfTrue: function(done, failMessage) {
return function(result) {
if(result) done(failMessage);
}
},
failIfFalse: function(done, failMessage) {
return function(result) {
if(!result) done(failMessage);
}
},
failed: function(done, failMessage) {
return function(reason) {
done(reason + "::" + failMessage);
}
},
failuresOccured: function() {
return jasmine.getEnv().currentSpec.results_.failedCount > 0;
},
saucelabs: {},
setTestStatus: function(driver, done) {
driver.controlFlow().reset(); // Discontinue any further driver actions that may have been defined.
if (this.saucelabs.username != null) | else {
driver.quit();
done();
}
},
updateJob: function(driver, options) {
if (this.saucelabs.username == null)
{
return function() {}; // No op. Assume running locally.
}
return function() {
return new Promise(function(resolve, reject) {
this.saucelabs.updateJob(driver.sessionID, options, resolve);
});
};
},
updateDriverSessionId: function(driver) {
return function(session) {
driver.sessionID = session.id_;
}
},
setupDriver: function(sauceUsername, sauceKey, extensionUrl, octopusUrl, octopusPassword, testIdFilename, octopusVersion, bluefinVersion, done) {
saucelabs = new SauceLabs({
username: sauceUsername,
password: sauceKey
});
var result = new webdriver.Builder().
withCapabilities({
'name': 'Spec run in node',
'build': bluefinVersion + "-" + octopusVersion,
'browserName': 'chrome',
'platform': 'Windows 10',
'version': '43.0',
'username': sauceUsername,
'accessKey': sauceKey,
'prerun': {
'executable': 'https://gist.githubusercontent.com/davidroberts63/b7c01e7aa945cde9064aca04e947288a/raw/GetExtension.bat',
'args': [ extensionUrl ]
},
"chromeOptions": {
"args": [
"--load-extension=C:\\bluefin-extension",
"start-maximized",
"disable-webgl",
"blacklist-webgl",
"blacklist-accelerated-compositing",
"disable-accelerated-2d-canvas",
"disable-accelerated-compositing",
"disable-accelerated-layers",
"disable-accelerated-plugins",
"disable-accelerated-video",
"disable-accelerated-video-decode",
"disable-gpu",
"disable-infobars",
"test-type"
]
},
});
// Run against SauceLabs or just run locally.
if(sauceUsername != null) {
result = result.usingServer("http://" + sauceUsername + ":" + sauceKey + "@ondemand.saucelabs.com:80/wd/hub");
}
result = result.build();
var spec = jasmine.getEnv().currentSpec;
result.getSession()
.then(this.updateDriverSessionId(result))
.then(this.updateJob(result, {name: spec.suite.description + ' ' + spec.description}))
.then(this.outputTestIdentifier(testIdFilename, result, spec.suite.description + " " + spec.description))
.then(this.closeOptionsTab(result))
.then(this.login(result, octopusUrl, octopusPassword, done))
.then(done);
return result;
},
outputTestIdentifier: function(filename, driver, name) {
return function() {
return new Promise(function(resolve, reject) {
fs.appendFile(filename, driver.sessionID + "~" + name + "\n", "utf8", resolve);
});
}
},
closeOptionsTab: function(driver) {
return function() {
return driver.getAllWindowHandles().then(function(handles) {
driver.switchTo().window(handles[1]);
driver.findElement(By.id("analytics")).click();
driver.findElement(By.id("save")).click();
driver.close();
driver.switchTo().window(handles[0]);
driver.navigate().refresh();
});
}
},
login: function(driver, url, password, done) {
var tests = this;
return function() {
driver.get(url);
driver.wait(until.elementLocated(By.id("inputUsername")), 3000, "Didn't get the login page.").thenCatch(done);
driver.findElement(By.id("inputUsername")).sendKeys("JoeAdministrator");
driver.findElement(By.id("inputPassword")).sendKeys(password);
driver.findElement(By.css("button.btn.btn-success[type='submit']")).click();
return driver.sleep(3000).then();
}
}
}; | {
var spec = jasmine.getEnv().currentSpec;
this.updateJob(driver, {passed: spec.results_.totalCount == spec.results_.passedCount})()
.then(driver.quit())
.then(function() { console.log("Setting test status"); })
.then(done);
} | conditional_block |
test_calc.py | import pytest
from calc import INTEGER, EOF, PLUS, Calc, CalcError
def test_calc_raises_error_on_invalid_tokens():
"""
Test that invalid tokens cause a ``CalcError`` and that the exception stack
trace contains useful information.
"""
input_text = "lumberjack" # Now with 100% more Monty Python references.
calc = Calc(text=input_text)
with pytest.raises(CalcError) as err:
calc.parse()
assert "Invalid token at position 0" in str(err.value)
def test_calc_raises_error_on_unexepected_syntax():
"""
Test that unexpected syntax causes a ``CalcError`` and that the exception
stack trace contains useful information.
"""
input_text = "+"
calc = Calc(text=input_text)
with pytest.raises(CalcError) as err:
calc.parse()
assert "Expected INTEGER at position 1, found PLUS" in str(err.value)
def test_calc_finds_eof_token_at_end_of_line():
"""
Test that, upon finding an end of line, a :class:`Calc` correctly tokenizes
an EOF :class:`Token`.
"""
input_text = ""
calc = Calc(text=input_text)
assert calc._next_token().type == EOF
def test_calc_finds_eof_token_after_int():
"""
Test that after consuming a solitary an INTEGER :class:`Token` a
:class:`Calc` will correctly tokenize an EOF :class:`Token`.
"""
input_text = "1"
calc = Calc(text=input_text)
token = calc._next_token()
assert token.type == INTEGER
assert token.value == 1
assert calc._next_token().type == EOF
def test_calc_can_consume_valid_token():
"""Test that a :class:`Calc` can consume a valid :class:`Token`."""
input_text = "1+1"
calc = Calc(text=input_text)
# Note: Since _next_token advances position one cannot simply
# >>> calc.current_token = Token(INTEGER, 1)
# The _next_token method MUST be called or this test will fail.
calc.current_token = calc._next_token()
calc._consume_token(INTEGER)
assert calc.current_token.type == PLUS
def test_parse_supports_addition():
"""Test that a :class:`Calc` can correctly parse the addition operation."""
# Note: This function name was briefly duplicated and therefore didn't run.
input_text = "1+1"
calc = Calc(text=input_text)
assert calc.parse() == 2
def test_parse_sets_eof():
"""
Test that successfully parsing an arithmetic expression sets the
``current_token`` attribute of a :class:`Calc` to EOF.
"""
input_text = "1+1"
calc = Calc(text=input_text)
calc.parse()
assert calc.current_token.type == EOF
def | ():
"""
Test that attempting to parse an invalid expression allows a ``CalcError``
to propagate correctly.
"""
input_text = "+1"
calc = Calc(text=input_text)
with pytest.raises(CalcError):
calc.parse()
| test_parse_raises_error_on_invalid_expression | identifier_name |
test_calc.py | import pytest
from calc import INTEGER, EOF, PLUS, Calc, CalcError
def test_calc_raises_error_on_invalid_tokens():
"""
Test that invalid tokens cause a ``CalcError`` and that the exception stack
trace contains useful information.
"""
input_text = "lumberjack" # Now with 100% more Monty Python references.
calc = Calc(text=input_text)
with pytest.raises(CalcError) as err:
calc.parse()
assert "Invalid token at position 0" in str(err.value)
def test_calc_raises_error_on_unexepected_syntax():
"""
Test that unexpected syntax causes a ``CalcError`` and that the exception
stack trace contains useful information.
"""
input_text = "+"
calc = Calc(text=input_text)
with pytest.raises(CalcError) as err:
calc.parse()
assert "Expected INTEGER at position 1, found PLUS" in str(err.value)
def test_calc_finds_eof_token_at_end_of_line():
"""
Test that, upon finding an end of line, a :class:`Calc` correctly tokenizes
an EOF :class:`Token`.
"""
input_text = ""
calc = Calc(text=input_text)
assert calc._next_token().type == EOF
def test_calc_finds_eof_token_after_int():
"""
Test that after consuming a solitary an INTEGER :class:`Token` a
:class:`Calc` will correctly tokenize an EOF :class:`Token`.
"""
input_text = "1"
calc = Calc(text=input_text)
token = calc._next_token()
assert token.type == INTEGER
assert token.value == 1
assert calc._next_token().type == EOF
def test_calc_can_consume_valid_token():
"""Test that a :class:`Calc` can consume a valid :class:`Token`."""
input_text = "1+1"
calc = Calc(text=input_text)
# Note: Since _next_token advances position one cannot simply
# >>> calc.current_token = Token(INTEGER, 1)
# The _next_token method MUST be called or this test will fail.
calc.current_token = calc._next_token()
calc._consume_token(INTEGER)
assert calc.current_token.type == PLUS
def test_parse_supports_addition():
"""Test that a :class:`Calc` can correctly parse the addition operation."""
# Note: This function name was briefly duplicated and therefore didn't run.
input_text = "1+1"
calc = Calc(text=input_text)
assert calc.parse() == 2
def test_parse_sets_eof():
"""
Test that successfully parsing an arithmetic expression sets the
``current_token`` attribute of a :class:`Calc` to EOF.
""" | input_text = "1+1"
calc = Calc(text=input_text)
calc.parse()
assert calc.current_token.type == EOF
def test_parse_raises_error_on_invalid_expression():
"""
Test that attempting to parse an invalid expression allows a ``CalcError``
to propagate correctly.
"""
input_text = "+1"
calc = Calc(text=input_text)
with pytest.raises(CalcError):
calc.parse() | random_line_split | |
test_calc.py | import pytest
from calc import INTEGER, EOF, PLUS, Calc, CalcError
def test_calc_raises_error_on_invalid_tokens():
"""
Test that invalid tokens cause a ``CalcError`` and that the exception stack
trace contains useful information.
"""
input_text = "lumberjack" # Now with 100% more Monty Python references.
calc = Calc(text=input_text)
with pytest.raises(CalcError) as err:
calc.parse()
assert "Invalid token at position 0" in str(err.value)
def test_calc_raises_error_on_unexepected_syntax():
"""
Test that unexpected syntax causes a ``CalcError`` and that the exception
stack trace contains useful information.
"""
input_text = "+"
calc = Calc(text=input_text)
with pytest.raises(CalcError) as err:
calc.parse()
assert "Expected INTEGER at position 1, found PLUS" in str(err.value)
def test_calc_finds_eof_token_at_end_of_line():
"""
Test that, upon finding an end of line, a :class:`Calc` correctly tokenizes
an EOF :class:`Token`.
"""
input_text = ""
calc = Calc(text=input_text)
assert calc._next_token().type == EOF
def test_calc_finds_eof_token_after_int():
|
def test_calc_can_consume_valid_token():
"""Test that a :class:`Calc` can consume a valid :class:`Token`."""
input_text = "1+1"
calc = Calc(text=input_text)
# Note: Since _next_token advances position one cannot simply
# >>> calc.current_token = Token(INTEGER, 1)
# The _next_token method MUST be called or this test will fail.
calc.current_token = calc._next_token()
calc._consume_token(INTEGER)
assert calc.current_token.type == PLUS
def test_parse_supports_addition():
"""Test that a :class:`Calc` can correctly parse the addition operation."""
# Note: This function name was briefly duplicated and therefore didn't run.
input_text = "1+1"
calc = Calc(text=input_text)
assert calc.parse() == 2
def test_parse_sets_eof():
"""
Test that successfully parsing an arithmetic expression sets the
``current_token`` attribute of a :class:`Calc` to EOF.
"""
input_text = "1+1"
calc = Calc(text=input_text)
calc.parse()
assert calc.current_token.type == EOF
def test_parse_raises_error_on_invalid_expression():
"""
Test that attempting to parse an invalid expression allows a ``CalcError``
to propagate correctly.
"""
input_text = "+1"
calc = Calc(text=input_text)
with pytest.raises(CalcError):
calc.parse()
| """
Test that after consuming a solitary an INTEGER :class:`Token` a
:class:`Calc` will correctly tokenize an EOF :class:`Token`.
"""
input_text = "1"
calc = Calc(text=input_text)
token = calc._next_token()
assert token.type == INTEGER
assert token.value == 1
assert calc._next_token().type == EOF | identifier_body |
reducers011.js | /**
* Copyright 2020 The Google Earth Engine Community Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and | /**
* @fileoverview Earth Engine Developer's Guide examples
* from 'Reducers - Image reduce' section
*/
// [START earthengine__reducers011__image_reduce]
// Load an image and select some bands of interest.
var image = ee.Image('LANDSAT/LC08/C01/T1/LC08_044034_20140318')
.select(['B4', 'B3', 'B2']);
// Reduce the image to get a one-band maximum value image.
var maxValue = image.reduce(ee.Reducer.max());
// Display the result.
Map.centerObject(image, 10);
Map.addLayer(maxValue, {max: 13000}, 'Maximum value image');
// [END earthengine__reducers011__image_reduce] | * limitations under the License.
*/
| random_line_split |
struct-pattern-matching-with-methods.rs | // edition:2021
//check-pass
#![warn(unused)]
#![allow(dead_code)]
#![feature(rustc_attrs)]
#[derive(Debug, Clone, Copy)]
enum PointType {
TwoD { x: u32, y: u32 },
ThreeD{ x: u32, y: u32, z: u32 }
}
// Testing struct patterns
struct Points {
points: Vec<PointType>,
}
impl Points {
pub fn test1(&mut self) -> Vec<usize> {
(0..self.points.len())
.filter_map(|i| {
let idx = i as usize;
match self.test2(idx) {
PointType::TwoD { .. } => Some(i),
PointType::ThreeD { .. } => None,
}
})
.collect()
}
pub fn test2(&mut self, i: usize) -> PointType {
self.points[i]
}
}
fn main() {
let mut points = Points {
points: Vec::<PointType>::new()
};
points.points.push(PointType::ThreeD { x:0, y:0, z:0 });
points.points.push(PointType::TwoD{ x:0, y:0 });
points.points.push(PointType::ThreeD{ x:0, y:0, z:0 }); | points.points.push(PointType::TwoD{ x:0, y:0 });
println!("{:?}", points.test1());
println!("{:?}", points.points);
} | random_line_split | |
struct-pattern-matching-with-methods.rs | // edition:2021
//check-pass
#![warn(unused)]
#![allow(dead_code)]
#![feature(rustc_attrs)]
#[derive(Debug, Clone, Copy)]
enum PointType {
TwoD { x: u32, y: u32 },
ThreeD{ x: u32, y: u32, z: u32 }
}
// Testing struct patterns
struct Points {
points: Vec<PointType>,
}
impl Points {
pub fn test1(&mut self) -> Vec<usize> {
(0..self.points.len())
.filter_map(|i| {
let idx = i as usize;
match self.test2(idx) {
PointType::TwoD { .. } => Some(i),
PointType::ThreeD { .. } => None,
}
})
.collect()
}
pub fn test2(&mut self, i: usize) -> PointType {
self.points[i]
}
}
fn | () {
let mut points = Points {
points: Vec::<PointType>::new()
};
points.points.push(PointType::ThreeD { x:0, y:0, z:0 });
points.points.push(PointType::TwoD{ x:0, y:0 });
points.points.push(PointType::ThreeD{ x:0, y:0, z:0 });
points.points.push(PointType::TwoD{ x:0, y:0 });
println!("{:?}", points.test1());
println!("{:?}", points.points);
}
| main | identifier_name |
struct-pattern-matching-with-methods.rs | // edition:2021
//check-pass
#![warn(unused)]
#![allow(dead_code)]
#![feature(rustc_attrs)]
#[derive(Debug, Clone, Copy)]
enum PointType {
TwoD { x: u32, y: u32 },
ThreeD{ x: u32, y: u32, z: u32 }
}
// Testing struct patterns
struct Points {
points: Vec<PointType>,
}
impl Points {
pub fn test1(&mut self) -> Vec<usize> {
(0..self.points.len())
.filter_map(|i| {
let idx = i as usize;
match self.test2(idx) {
PointType::TwoD { .. } => Some(i),
PointType::ThreeD { .. } => None,
}
})
.collect()
}
pub fn test2(&mut self, i: usize) -> PointType {
self.points[i]
}
}
fn main() | {
let mut points = Points {
points: Vec::<PointType>::new()
};
points.points.push(PointType::ThreeD { x:0, y:0, z:0 });
points.points.push(PointType::TwoD{ x:0, y:0 });
points.points.push(PointType::ThreeD{ x:0, y:0, z:0 });
points.points.push(PointType::TwoD{ x:0, y:0 });
println!("{:?}", points.test1());
println!("{:?}", points.points);
} | identifier_body | |
function_expression-out.js | var a = function() {
return 'b';
};
b = function doB(q, wer, ty) {
var c = function(n) {
return function() {
return q +
wer - ty;
}
}
return c
}
this.foo = {
bar: function() {
var r = function() {
re(); draw();
return log('foo') + 'bar';
};
},
ipsum: function(amet) {
return function() {
amet()
}
}
};
var noop = function() {};
var add = function(a, b) {
return a + b;
}
call(function(a) {
b();
});
// issue #36
var obj = {
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
}
};
// issue #134 |
// issue #143
if (!this._pollReceive) {
this._pollReceive = nn.PollReceiveSocket(this.binding, function(events) {
if (events) this._receive();
}.bind(this));
}
// issue #283
var foo = function foo() {
bar()
}
var foo = function() {
bar()
}
// default params (#285)
var defaultParams = function defaults(z, x = 1, y = 2) {
return z + x + y;
}
// issue #350
var foo = function*() {
yield '123';
yield '456';
};
var foo = function*() {
yield '123';
yield '456';
}; | var foo = new MyConstructor(function otherFunction() {}); | random_line_split |
env.rs | // Copyright 2013 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Runtime environment settings
use from_str::from_str;
use option::{Some, None, Expect};
use os;
// Note that these are all accessed without any synchronization.
// They are expected to be initialized once then left alone.
static mut MIN_STACK: uint = 2 * 1024 * 1024;
/// This default corresponds to 20M of cache per scheduler (at the default size).
static mut MAX_CACHED_STACKS: uint = 10;
static mut DEBUG_BORROW: bool = false;
pub fn init() {
unsafe {
match os::getenv("RUST_MIN_STACK") {
Some(s) => match from_str(s) {
Some(i) => MIN_STACK = i,
None => ()
},
None => ()
}
match os::getenv("RUST_MAX_CACHED_STACKS") {
Some(max) => MAX_CACHED_STACKS = from_str(max).expect("expected positive integer in \
RUST_MAX_CACHED_STACKS"),
None => ()
}
match os::getenv("RUST_DEBUG_BORROW") {
Some(_) => DEBUG_BORROW = true,
None => ()
}
}
}
pub fn min_stack() -> uint |
pub fn max_cached_stacks() -> uint {
unsafe { MAX_CACHED_STACKS }
}
pub fn debug_borrow() -> bool {
unsafe { DEBUG_BORROW }
}
| {
unsafe { MIN_STACK }
} | identifier_body |
env.rs | // Copyright 2013 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Runtime environment settings
use from_str::from_str;
use option::{Some, None, Expect};
use os;
// Note that these are all accessed without any synchronization.
// They are expected to be initialized once then left alone.
static mut MIN_STACK: uint = 2 * 1024 * 1024;
/// This default corresponds to 20M of cache per scheduler (at the default size).
static mut MAX_CACHED_STACKS: uint = 10;
static mut DEBUG_BORROW: bool = false;
pub fn init() {
unsafe {
match os::getenv("RUST_MIN_STACK") {
Some(s) => match from_str(s) {
Some(i) => MIN_STACK = i,
None => ()
},
None => ()
}
match os::getenv("RUST_MAX_CACHED_STACKS") {
Some(max) => MAX_CACHED_STACKS = from_str(max).expect("expected positive integer in \
RUST_MAX_CACHED_STACKS"),
None => ()
}
match os::getenv("RUST_DEBUG_BORROW") {
Some(_) => DEBUG_BORROW = true, | None => ()
}
}
}
pub fn min_stack() -> uint {
unsafe { MIN_STACK }
}
pub fn max_cached_stacks() -> uint {
unsafe { MAX_CACHED_STACKS }
}
pub fn debug_borrow() -> bool {
unsafe { DEBUG_BORROW }
} | random_line_split | |
env.rs | // Copyright 2013 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Runtime environment settings
use from_str::from_str;
use option::{Some, None, Expect};
use os;
// Note that these are all accessed without any synchronization.
// They are expected to be initialized once then left alone.
static mut MIN_STACK: uint = 2 * 1024 * 1024;
/// This default corresponds to 20M of cache per scheduler (at the default size).
static mut MAX_CACHED_STACKS: uint = 10;
static mut DEBUG_BORROW: bool = false;
pub fn | () {
unsafe {
match os::getenv("RUST_MIN_STACK") {
Some(s) => match from_str(s) {
Some(i) => MIN_STACK = i,
None => ()
},
None => ()
}
match os::getenv("RUST_MAX_CACHED_STACKS") {
Some(max) => MAX_CACHED_STACKS = from_str(max).expect("expected positive integer in \
RUST_MAX_CACHED_STACKS"),
None => ()
}
match os::getenv("RUST_DEBUG_BORROW") {
Some(_) => DEBUG_BORROW = true,
None => ()
}
}
}
pub fn min_stack() -> uint {
unsafe { MIN_STACK }
}
pub fn max_cached_stacks() -> uint {
unsafe { MAX_CACHED_STACKS }
}
pub fn debug_borrow() -> bool {
unsafe { DEBUG_BORROW }
}
| init | identifier_name |
menu.component.ts | import * as moment from 'moment';
import { cloneDeep } from 'lodash';
import { IScope, IComponentOptions, IOnChangesObject } from 'angular';
import { RouterWrapper } from '../../../app/core';
import { IMenu, MenuService } from '../../models/menu';
import { IOrder, OrderService } from '../../models/order';
import { ILineItem, LineItemService } from '../../models/line-item';
import { ProductTypeUrls } from '../../models/product';
import { PriceService } from '../../models/price';
// internal types --------------------------------------------------------------
interface ITriggerOrderPlaceEvent {
(arg: { order: IOrder }): void;
}
export class MenuController {
// bindings ------------------------------------------------------------------
// input
menu: IMenu;
// output
triggerOrderPlaceEvent: ITriggerOrderPlaceEvent;
// internal
order: IOrder;
lineItemsAvailable: ILineItem[];
size: string;
private lineItemsAddedToOrder = false;
private customLunch: boolean;
private selectedLineItems: ILineItem[];
constructor(
private $scope: IScope,
private router: RouterWrapper,
private lOrderService: OrderService,
private lLineItemService: LineItemService,
private lPriceService: PriceService,
private lMenuService: MenuService
) {
'ngInject';
}
// dom event handlers --------------------------------------------------------
addToOrder(): void {
this.order = this.lOrderService.setLineItems(this.selectedLineItems, this.order);
this.lineItemsAddedToOrder = true;
this.triggerOrderPlaceEvent({order: this.order});
}
orderAgain(): void {
this.init();
this.lineItemsAddedToOrder = false;
}
goToBasket(): void {
this.router.navigate(['/basket']);
}
onCustomizeLunch(): void {
this.toggleCustomLunch();
}
onLineItemToggled(inputItem: ILineItem, checked: boolean): void {
let item = this.lLineItemService.setSizeFor(inputItem, this.size);
if (checked) {
this.selectedLineItems = this.lLineItemService.addItemTo(this.selectedLineItems, item);
} else |
}
// view helpers --------------------------------------------------------------
isOrdered(): boolean {
return this.lineItemsAddedToOrder;
}
timeBeforeOrderImpossible(): string {
return moment(this.menu.date).fromNow();
}
isCustomLunch(): boolean {
return this.customLunch;
}
isPredefinedLunch(): boolean {
return !this.isCustomLunch();
}
orderButtonText(): string {
return this.isCustomLunch() ? 'Беру свой' : 'Беру готовый';
}
customizeLunchButtonText(): string {
return this.isCustomLunch() ? 'Вернуть готовый' : 'Собрать свой';
}
productTypeToIconUrl(type: string): string {
return ProductTypeUrls[type];
}
calcPrice(): number {
return this.lPriceService.calcPriceForAll(this.selectedLineItems, this.menu.date);
}
getCoverOf(menu: IMenu): string {
return this.lMenuService.getCoverOf(menu);
}
// private init --------------------------------------------------------------
$onChanges(changes: IOnChangesObject) {
if (changes['menu']) { // tslint:disable-line:no-string-literal
this.onInputMenuChanged(this.menu);
}
}
private init(): void {
this.initOrder();
this.initSize();
this.initLunchCustomization();
}
private initOrder(): void {
this.order = this.lOrderService.createOrderByDate(this.menu.date);
this.lineItemsAvailable = this.createPredefinedLineItems();
this.selectedLineItems = this.createPredefinedLineItems();
}
private initSize(): void {
this.size = 'medium';
this.$scope.$watch(() => this.size, this.onSizeChanged.bind(this));
}
private initLunchCustomization(): void {
this.customLunch = false;
}
// private helpers -----------------------------------------------------------
private createPredefinedLineItems(): ILineItem[] {
return this.lLineItemService.createLineItemsBy(this.menu.products);
}
// private event handlers ----------------------------------------------------
private onInputMenuChanged(menu: IMenu) {
this.menu = cloneDeep(menu);
this.init();
}
private toggleCustomLunch(): void {
this.customLunch = !this.customLunch;
if (this.customLunch) {
this.selectedLineItems = [];
} else {
this.selectedLineItems = this.createPredefinedLineItems();
this.selectedLineItems = this.lLineItemService.setSizeForAll(this.selectedLineItems, this.size);
}
}
private onSizeChanged(size: string): void {
this.size = size;
this.selectedLineItems = this.lLineItemService.setSizeForAll(this.selectedLineItems, size);
}
}
// component definition --------------------------------------------------------
export const MenuComponent: IComponentOptions = {
template: require('./menu.html'),
controller: MenuController,
controllerAs: 'vm',
bindings: {
menu: '<',
triggerOrderPlaceEvent: '&onOrderPlaced'
}
};
| {
this.selectedLineItems = this.lLineItemService.removeItemFrom(this.selectedLineItems, item);
} | conditional_block |
menu.component.ts | import * as moment from 'moment';
import { cloneDeep } from 'lodash';
import { IScope, IComponentOptions, IOnChangesObject } from 'angular';
import { RouterWrapper } from '../../../app/core';
import { IMenu, MenuService } from '../../models/menu';
import { IOrder, OrderService } from '../../models/order';
import { ILineItem, LineItemService } from '../../models/line-item';
import { ProductTypeUrls } from '../../models/product';
import { PriceService } from '../../models/price';
// internal types --------------------------------------------------------------
interface ITriggerOrderPlaceEvent {
(arg: { order: IOrder }): void;
}
export class MenuController {
// bindings ------------------------------------------------------------------
// input
menu: IMenu;
// output
triggerOrderPlaceEvent: ITriggerOrderPlaceEvent;
// internal
order: IOrder;
lineItemsAvailable: ILineItem[];
size: string;
private lineItemsAddedToOrder = false;
private customLunch: boolean;
private selectedLineItems: ILineItem[];
constructor(
private $scope: IScope,
private router: RouterWrapper,
private lOrderService: OrderService,
private lLineItemService: LineItemService,
private lPriceService: PriceService,
private lMenuService: MenuService
) {
'ngInject';
}
// dom event handlers --------------------------------------------------------
addToOrder(): void { | this.triggerOrderPlaceEvent({order: this.order});
}
orderAgain(): void {
this.init();
this.lineItemsAddedToOrder = false;
}
goToBasket(): void {
this.router.navigate(['/basket']);
}
onCustomizeLunch(): void {
this.toggleCustomLunch();
}
onLineItemToggled(inputItem: ILineItem, checked: boolean): void {
let item = this.lLineItemService.setSizeFor(inputItem, this.size);
if (checked) {
this.selectedLineItems = this.lLineItemService.addItemTo(this.selectedLineItems, item);
} else {
this.selectedLineItems = this.lLineItemService.removeItemFrom(this.selectedLineItems, item);
}
}
// view helpers --------------------------------------------------------------
isOrdered(): boolean {
return this.lineItemsAddedToOrder;
}
timeBeforeOrderImpossible(): string {
return moment(this.menu.date).fromNow();
}
isCustomLunch(): boolean {
return this.customLunch;
}
isPredefinedLunch(): boolean {
return !this.isCustomLunch();
}
orderButtonText(): string {
return this.isCustomLunch() ? 'Беру свой' : 'Беру готовый';
}
customizeLunchButtonText(): string {
return this.isCustomLunch() ? 'Вернуть готовый' : 'Собрать свой';
}
productTypeToIconUrl(type: string): string {
return ProductTypeUrls[type];
}
calcPrice(): number {
return this.lPriceService.calcPriceForAll(this.selectedLineItems, this.menu.date);
}
getCoverOf(menu: IMenu): string {
return this.lMenuService.getCoverOf(menu);
}
// private init --------------------------------------------------------------
$onChanges(changes: IOnChangesObject) {
if (changes['menu']) { // tslint:disable-line:no-string-literal
this.onInputMenuChanged(this.menu);
}
}
private init(): void {
this.initOrder();
this.initSize();
this.initLunchCustomization();
}
private initOrder(): void {
this.order = this.lOrderService.createOrderByDate(this.menu.date);
this.lineItemsAvailable = this.createPredefinedLineItems();
this.selectedLineItems = this.createPredefinedLineItems();
}
private initSize(): void {
this.size = 'medium';
this.$scope.$watch(() => this.size, this.onSizeChanged.bind(this));
}
private initLunchCustomization(): void {
this.customLunch = false;
}
// private helpers -----------------------------------------------------------
private createPredefinedLineItems(): ILineItem[] {
return this.lLineItemService.createLineItemsBy(this.menu.products);
}
// private event handlers ----------------------------------------------------
private onInputMenuChanged(menu: IMenu) {
this.menu = cloneDeep(menu);
this.init();
}
private toggleCustomLunch(): void {
this.customLunch = !this.customLunch;
if (this.customLunch) {
this.selectedLineItems = [];
} else {
this.selectedLineItems = this.createPredefinedLineItems();
this.selectedLineItems = this.lLineItemService.setSizeForAll(this.selectedLineItems, this.size);
}
}
private onSizeChanged(size: string): void {
this.size = size;
this.selectedLineItems = this.lLineItemService.setSizeForAll(this.selectedLineItems, size);
}
}
// component definition --------------------------------------------------------
export const MenuComponent: IComponentOptions = {
template: require('./menu.html'),
controller: MenuController,
controllerAs: 'vm',
bindings: {
menu: '<',
triggerOrderPlaceEvent: '&onOrderPlaced'
}
}; | this.order = this.lOrderService.setLineItems(this.selectedLineItems, this.order);
this.lineItemsAddedToOrder = true;
| random_line_split |
menu.component.ts | import * as moment from 'moment';
import { cloneDeep } from 'lodash';
import { IScope, IComponentOptions, IOnChangesObject } from 'angular';
import { RouterWrapper } from '../../../app/core';
import { IMenu, MenuService } from '../../models/menu';
import { IOrder, OrderService } from '../../models/order';
import { ILineItem, LineItemService } from '../../models/line-item';
import { ProductTypeUrls } from '../../models/product';
import { PriceService } from '../../models/price';
// internal types --------------------------------------------------------------
interface ITriggerOrderPlaceEvent {
(arg: { order: IOrder }): void;
}
export class MenuController {
// bindings ------------------------------------------------------------------
// input
menu: IMenu;
// output
triggerOrderPlaceEvent: ITriggerOrderPlaceEvent;
// internal
order: IOrder;
lineItemsAvailable: ILineItem[];
size: string;
private lineItemsAddedToOrder = false;
private customLunch: boolean;
private selectedLineItems: ILineItem[];
constructor(
private $scope: IScope,
private router: RouterWrapper,
private lOrderService: OrderService,
private lLineItemService: LineItemService,
private lPriceService: PriceService,
private lMenuService: MenuService
) {
'ngInject';
}
// dom event handlers --------------------------------------------------------
addToOrder(): void {
this.order = this.lOrderService.setLineItems(this.selectedLineItems, this.order);
this.lineItemsAddedToOrder = true;
this.triggerOrderPlaceEvent({order: this.order});
}
orderAgain(): void {
this.init();
this.lineItemsAddedToOrder = false;
}
goToBasket(): void {
this.router.navigate(['/basket']);
}
onCustomizeLunch(): void {
this.toggleCustomLunch();
}
onLineItemToggled(inputItem: ILineItem, checked: boolean): void {
let item = this.lLineItemService.setSizeFor(inputItem, this.size);
if (checked) {
this.selectedLineItems = this.lLineItemService.addItemTo(this.selectedLineItems, item);
} else {
this.selectedLineItems = this.lLineItemService.removeItemFrom(this.selectedLineItems, item);
}
}
// view helpers --------------------------------------------------------------
isOrdered(): boolean {
return this.lineItemsAddedToOrder;
}
timeBeforeOrderImpossible(): string {
return moment(this.menu.date).fromNow();
}
isCustomLunch(): boolean {
return this.customLunch;
}
isPredefinedLunch(): boolean {
return !this.isCustomLunch();
}
orderButtonText(): string {
return this.isCustomLunch() ? 'Беру свой' : 'Беру готовый';
}
customizeLunchButtonText(): string {
return this.isCustomLunch() ? 'Вернуть готовый' : 'Собрать свой';
}
productTypeToIconUrl(type: string): string {
return ProductTypeUrls[type];
}
calcPrice(): number {
return this.lPriceService.calcPriceForAll(this.selectedLineItems, this.menu.date);
}
getCoverOf(menu: IMenu): string {
return this.lMenuService.getCoverOf(menu);
}
// private init --------------------------------------------------------------
$onChanges(changes: IOnChangesObject) {
| s['menu']) { // tslint:disable-line:no-string-literal
this.onInputMenuChanged(this.menu);
}
}
private init(): void {
this.initOrder();
this.initSize();
this.initLunchCustomization();
}
private initOrder(): void {
this.order = this.lOrderService.createOrderByDate(this.menu.date);
this.lineItemsAvailable = this.createPredefinedLineItems();
this.selectedLineItems = this.createPredefinedLineItems();
}
private initSize(): void {
this.size = 'medium';
this.$scope.$watch(() => this.size, this.onSizeChanged.bind(this));
}
private initLunchCustomization(): void {
this.customLunch = false;
}
// private helpers -----------------------------------------------------------
private createPredefinedLineItems(): ILineItem[] {
return this.lLineItemService.createLineItemsBy(this.menu.products);
}
// private event handlers ----------------------------------------------------
private onInputMenuChanged(menu: IMenu) {
this.menu = cloneDeep(menu);
this.init();
}
private toggleCustomLunch(): void {
this.customLunch = !this.customLunch;
if (this.customLunch) {
this.selectedLineItems = [];
} else {
this.selectedLineItems = this.createPredefinedLineItems();
this.selectedLineItems = this.lLineItemService.setSizeForAll(this.selectedLineItems, this.size);
}
}
private onSizeChanged(size: string): void {
this.size = size;
this.selectedLineItems = this.lLineItemService.setSizeForAll(this.selectedLineItems, size);
}
}
// component definition --------------------------------------------------------
export const MenuComponent: IComponentOptions = {
template: require('./menu.html'),
controller: MenuController,
controllerAs: 'vm',
bindings: {
menu: '<',
triggerOrderPlaceEvent: '&onOrderPlaced'
}
};
| if (change | identifier_name |
menu.component.ts | import * as moment from 'moment';
import { cloneDeep } from 'lodash';
import { IScope, IComponentOptions, IOnChangesObject } from 'angular';
import { RouterWrapper } from '../../../app/core';
import { IMenu, MenuService } from '../../models/menu';
import { IOrder, OrderService } from '../../models/order';
import { ILineItem, LineItemService } from '../../models/line-item';
import { ProductTypeUrls } from '../../models/product';
import { PriceService } from '../../models/price';
// internal types --------------------------------------------------------------
interface ITriggerOrderPlaceEvent {
(arg: { order: IOrder }): void;
}
export class MenuController {
// bindings ------------------------------------------------------------------
// input
menu: IMenu;
// output
triggerOrderPlaceEvent: ITriggerOrderPlaceEvent;
// internal
order: IOrder;
lineItemsAvailable: ILineItem[];
size: string;
private lineItemsAddedToOrder = false;
private customLunch: boolean;
private selectedLineItems: ILineItem[];
constructor(
private $scope: IScope,
private router: RouterWrapper,
private lOrderService: OrderService,
private lLineItemService: LineItemService,
private lPriceService: PriceService,
private lMenuService: MenuService
) {
'ngInject';
}
// dom event handlers --------------------------------------------------------
addToOrder(): void {
this.order = this.lOrderService.setLineItems(this.selectedLineItems, this.order);
this.lineItemsAddedToOrder = true;
this.triggerOrderPlaceEvent({order: this.order});
}
orderAgain(): void {
this.init();
this.lineItemsAddedToOrder = false;
}
goToBasket(): void {
this.router.navigate(['/basket']);
}
onCustomizeLunch(): void {
this.toggleCustomLunch();
}
onLineItemToggled(inputItem: ILineItem, checked: boolean): void |
// view helpers --------------------------------------------------------------
isOrdered(): boolean {
return this.lineItemsAddedToOrder;
}
timeBeforeOrderImpossible(): string {
return moment(this.menu.date).fromNow();
}
isCustomLunch(): boolean {
return this.customLunch;
}
isPredefinedLunch(): boolean {
return !this.isCustomLunch();
}
orderButtonText(): string {
return this.isCustomLunch() ? 'Беру свой' : 'Беру готовый';
}
customizeLunchButtonText(): string {
return this.isCustomLunch() ? 'Вернуть готовый' : 'Собрать свой';
}
productTypeToIconUrl(type: string): string {
return ProductTypeUrls[type];
}
calcPrice(): number {
return this.lPriceService.calcPriceForAll(this.selectedLineItems, this.menu.date);
}
getCoverOf(menu: IMenu): string {
return this.lMenuService.getCoverOf(menu);
}
// private init --------------------------------------------------------------
$onChanges(changes: IOnChangesObject) {
if (changes['menu']) { // tslint:disable-line:no-string-literal
this.onInputMenuChanged(this.menu);
}
}
private init(): void {
this.initOrder();
this.initSize();
this.initLunchCustomization();
}
private initOrder(): void {
this.order = this.lOrderService.createOrderByDate(this.menu.date);
this.lineItemsAvailable = this.createPredefinedLineItems();
this.selectedLineItems = this.createPredefinedLineItems();
}
private initSize(): void {
this.size = 'medium';
this.$scope.$watch(() => this.size, this.onSizeChanged.bind(this));
}
private initLunchCustomization(): void {
this.customLunch = false;
}
// private helpers -----------------------------------------------------------
private createPredefinedLineItems(): ILineItem[] {
return this.lLineItemService.createLineItemsBy(this.menu.products);
}
// private event handlers ----------------------------------------------------
private onInputMenuChanged(menu: IMenu) {
this.menu = cloneDeep(menu);
this.init();
}
private toggleCustomLunch(): void {
this.customLunch = !this.customLunch;
if (this.customLunch) {
this.selectedLineItems = [];
} else {
this.selectedLineItems = this.createPredefinedLineItems();
this.selectedLineItems = this.lLineItemService.setSizeForAll(this.selectedLineItems, this.size);
}
}
private onSizeChanged(size: string): void {
this.size = size;
this.selectedLineItems = this.lLineItemService.setSizeForAll(this.selectedLineItems, size);
}
}
// component definition --------------------------------------------------------
export const MenuComponent: IComponentOptions = {
template: require('./menu.html'),
controller: MenuController,
controllerAs: 'vm',
bindings: {
menu: '<',
triggerOrderPlaceEvent: '&onOrderPlaced'
}
};
| {
let item = this.lLineItemService.setSizeFor(inputItem, this.size);
if (checked) {
this.selectedLineItems = this.lLineItemService.addItemTo(this.selectedLineItems, item);
} else {
this.selectedLineItems = this.lLineItemService.removeItemFrom(this.selectedLineItems, item);
}
} | identifier_body |
issue-49973.rs | // 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
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#[derive(Debug)]
#[repr(i32)]
enum | {
Min = -2147483648i32,
_Max = 2147483647i32,
}
fn main() {
assert_eq!(Some(E::Min).unwrap() as i32, -2147483648i32);
}
| E | identifier_name |
issue-49973.rs | // 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
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#[derive(Debug)]
#[repr(i32)]
enum E {
Min = -2147483648i32,
_Max = 2147483647i32,
}
fn main() { | assert_eq!(Some(E::Min).unwrap() as i32, -2147483648i32);
} | random_line_split | |
issue-49973.rs | // 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
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#[derive(Debug)]
#[repr(i32)]
enum E {
Min = -2147483648i32,
_Max = 2147483647i32,
}
fn main() | {
assert_eq!(Some(E::Min).unwrap() as i32, -2147483648i32);
} | identifier_body | |
unboxed-closure-sugar-region.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test interaction between unboxed closure sugar and region
// parameters (should be exactly as if angle brackets were used
// and regions omitted).
#![feature(default_type_params)]
#![allow(dead_code)]
use std::kinds::marker;
struct Foo<'a,T,U> {
t: T,
u: U,
m: marker::InvariantLifetime<'a>
}
trait Eq<X> { } | fn same_type<A,B:Eq<A>>(a: A, b: B) { }
fn test<'a,'b>() {
// Parens are equivalent to omitting default in angle.
eq::< Foo<(int,),()>, Foo(int) >();
// Here we specify 'static explicitly in angle-bracket version.
// Parenthesized winds up getting inferred.
eq::< Foo<'static, (int,),()>, Foo(int) >();
}
fn test2(x: Foo<(int,),()>, y: Foo(int)) {
// Here, the omitted lifetimes are expanded to distinct things.
same_type(x, y) //~ ERROR cannot infer
}
fn main() { } | impl<X> Eq<X> for X { }
fn eq<A,B:Eq<A>>() { } | random_line_split |
unboxed-closure-sugar-region.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test interaction between unboxed closure sugar and region
// parameters (should be exactly as if angle brackets were used
// and regions omitted).
#![feature(default_type_params)]
#![allow(dead_code)]
use std::kinds::marker;
struct Foo<'a,T,U> {
t: T,
u: U,
m: marker::InvariantLifetime<'a>
}
trait Eq<X> { }
impl<X> Eq<X> for X { }
fn eq<A,B:Eq<A>>() { }
fn same_type<A,B:Eq<A>>(a: A, b: B) |
fn test<'a,'b>() {
// Parens are equivalent to omitting default in angle.
eq::< Foo<(int,),()>, Foo(int) >();
// Here we specify 'static explicitly in angle-bracket version.
// Parenthesized winds up getting inferred.
eq::< Foo<'static, (int,),()>, Foo(int) >();
}
fn test2(x: Foo<(int,),()>, y: Foo(int)) {
// Here, the omitted lifetimes are expanded to distinct things.
same_type(x, y) //~ ERROR cannot infer
}
fn main() { }
| { } | identifier_body |
unboxed-closure-sugar-region.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test interaction between unboxed closure sugar and region
// parameters (should be exactly as if angle brackets were used
// and regions omitted).
#![feature(default_type_params)]
#![allow(dead_code)]
use std::kinds::marker;
struct Foo<'a,T,U> {
t: T,
u: U,
m: marker::InvariantLifetime<'a>
}
trait Eq<X> { }
impl<X> Eq<X> for X { }
fn eq<A,B:Eq<A>>() { }
fn same_type<A,B:Eq<A>>(a: A, b: B) { }
fn | <'a,'b>() {
// Parens are equivalent to omitting default in angle.
eq::< Foo<(int,),()>, Foo(int) >();
// Here we specify 'static explicitly in angle-bracket version.
// Parenthesized winds up getting inferred.
eq::< Foo<'static, (int,),()>, Foo(int) >();
}
fn test2(x: Foo<(int,),()>, y: Foo(int)) {
// Here, the omitted lifetimes are expanded to distinct things.
same_type(x, y) //~ ERROR cannot infer
}
fn main() { }
| test | identifier_name |
slave.js | 'use strict';
// not using ES6 import/export syntax, since we need to require() in a handler
// what the ES6 syntax does not permit
var vm = require('vm');
var errorCatcherInPlace = false;
var messageHandler = function messageHandler() {
console.error('No thread logic initialized.'); // eslint-disable-line no-console
};
function setupErrorCatcher() {
if (errorCatcherInPlace) {
return;
}
process.on('uncaughtException', function (error) {
process.send({
error: { message: error.message, stack: error.stack }
});
});
errorCatcherInPlace = true;
}
function runAsSandboxedModule(code) {
var sandbox = {
Buffer: Buffer,
console: console,
clearInterval: clearInterval,
clearTimeout: clearTimeout,
module: { exports: null },
require: require,
setInterval: setInterval,
setTimeout: setTimeout
};
vm.runInNewContext(code, sandbox);
return sandbox.module.exports;
}
function messageHandlerDone() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
process.send({ response: args });
}
messageHandlerDone.transfer = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
args.pop(); // ignore last parameter, since it's only useful for browser code
messageHandlerDone.apply(undefined, args);
};
function messageHandlerProgress(progress) {
process.send({ progress: progress });
}
process.on('message', function (data) {
if (data.initByScript) {
messageHandler = require(data.script);
}
if (data.initByMethod) |
if (data.doRun) {
// it's a good idea to wait until first thread logic run to set this up,
// so initialization errors will be printed to console
setupErrorCatcher();
messageHandler(data.param, messageHandlerDone, messageHandlerProgress);
}
});
//# sourceMappingURL=slave.js.map
| {
messageHandler = runAsSandboxedModule('module.exports = ' + data.method);
} | conditional_block |
slave.js | 'use strict';
// not using ES6 import/export syntax, since we need to require() in a handler | // what the ES6 syntax does not permit
var vm = require('vm');
var errorCatcherInPlace = false;
var messageHandler = function messageHandler() {
console.error('No thread logic initialized.'); // eslint-disable-line no-console
};
function setupErrorCatcher() {
if (errorCatcherInPlace) {
return;
}
process.on('uncaughtException', function (error) {
process.send({
error: { message: error.message, stack: error.stack }
});
});
errorCatcherInPlace = true;
}
function runAsSandboxedModule(code) {
var sandbox = {
Buffer: Buffer,
console: console,
clearInterval: clearInterval,
clearTimeout: clearTimeout,
module: { exports: null },
require: require,
setInterval: setInterval,
setTimeout: setTimeout
};
vm.runInNewContext(code, sandbox);
return sandbox.module.exports;
}
function messageHandlerDone() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
process.send({ response: args });
}
messageHandlerDone.transfer = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
args.pop(); // ignore last parameter, since it's only useful for browser code
messageHandlerDone.apply(undefined, args);
};
function messageHandlerProgress(progress) {
process.send({ progress: progress });
}
process.on('message', function (data) {
if (data.initByScript) {
messageHandler = require(data.script);
}
if (data.initByMethod) {
messageHandler = runAsSandboxedModule('module.exports = ' + data.method);
}
if (data.doRun) {
// it's a good idea to wait until first thread logic run to set this up,
// so initialization errors will be printed to console
setupErrorCatcher();
messageHandler(data.param, messageHandlerDone, messageHandlerProgress);
}
});
//# sourceMappingURL=slave.js.map | random_line_split | |
slave.js | 'use strict';
// not using ES6 import/export syntax, since we need to require() in a handler
// what the ES6 syntax does not permit
var vm = require('vm');
var errorCatcherInPlace = false;
var messageHandler = function messageHandler() {
console.error('No thread logic initialized.'); // eslint-disable-line no-console
};
function setupErrorCatcher() |
function runAsSandboxedModule(code) {
var sandbox = {
Buffer: Buffer,
console: console,
clearInterval: clearInterval,
clearTimeout: clearTimeout,
module: { exports: null },
require: require,
setInterval: setInterval,
setTimeout: setTimeout
};
vm.runInNewContext(code, sandbox);
return sandbox.module.exports;
}
function messageHandlerDone() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
process.send({ response: args });
}
messageHandlerDone.transfer = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
args.pop(); // ignore last parameter, since it's only useful for browser code
messageHandlerDone.apply(undefined, args);
};
function messageHandlerProgress(progress) {
process.send({ progress: progress });
}
process.on('message', function (data) {
if (data.initByScript) {
messageHandler = require(data.script);
}
if (data.initByMethod) {
messageHandler = runAsSandboxedModule('module.exports = ' + data.method);
}
if (data.doRun) {
// it's a good idea to wait until first thread logic run to set this up,
// so initialization errors will be printed to console
setupErrorCatcher();
messageHandler(data.param, messageHandlerDone, messageHandlerProgress);
}
});
//# sourceMappingURL=slave.js.map
| {
if (errorCatcherInPlace) {
return;
}
process.on('uncaughtException', function (error) {
process.send({
error: { message: error.message, stack: error.stack }
});
});
errorCatcherInPlace = true;
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.