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 |
---|---|---|---|---|
setup.py
|
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
# =============================================================================
"""Cloud TPU profiler package."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from setuptools import setup
_VERSION = '1.7.0'
CONSOLE_SCRIPTS = [
'capture_tpu_profile=cloud_tpu_profiler.main:run_main',
]
setup(
name='cloud_tpu_profiler',
|
long_description='Tools for capture TPU profile',
url='https://www.tensorflow.org/tfrc/',
author='Google Inc.',
author_email='[email protected]',
packages=['cloud_tpu_profiler'],
package_data={
'cloud_tpu_profiler': ['data/*'],
},
entry_points={
'console_scripts': CONSOLE_SCRIPTS,
},
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
],
license='Apache 2.0',
keywords='tensorflow performance tpu',
)
|
version=_VERSION.replace('-', ''),
description='Trace and profile Cloud TPU performance',
|
random_line_split
|
test_dep_graph.py
|
from __future__ import unicode_literals
from rbpkg.package_manager.dep_graph import DependencyGraph
from rbpkg.testing.testcases import TestCase
class DependencyGraphTests(TestCase):
"""Unit tests for rbpkg.package_manager.dep_graph.DependencyGraph."""
def test_iter_sorted_simple(self):
"""Testing DependencyGraph.iter_sorted in simple case"""
graph = DependencyGraph()
graph.add(3, [2])
graph.add(2, [1])
graph.add(1, [])
self.assertEqual(list(graph.iter_sorted()), [1, 2, 3])
def test_iter_sorted_complex(self):
"""Testing DependencyGraph.iter_sorted with complex dependencies"""
graph = DependencyGraph()
graph.add(5, [9])
graph.add(12, [9, 6, 15])
graph.add(15, [9, 2])
graph.add(9, [14, 20])
graph.add(6, [14, 2])
|
self.assertEqual(list(graph.iter_sorted()),
[14, 20, 9, 5, 2, 6, 15, 12])
def test_iter_sorted_circular_ref(self):
"""Testing DependencyGraph.iter_sorted with circular reference"""
graph = DependencyGraph()
graph.add(1, [2])
graph.add(2, [1])
self.assertEqual(list(graph.iter_sorted()), [2, 1])
|
random_line_split
|
|
test_dep_graph.py
|
from __future__ import unicode_literals
from rbpkg.package_manager.dep_graph import DependencyGraph
from rbpkg.testing.testcases import TestCase
class DependencyGraphTests(TestCase):
"""Unit tests for rbpkg.package_manager.dep_graph.DependencyGraph."""
def test_iter_sorted_simple(self):
|
def test_iter_sorted_complex(self):
"""Testing DependencyGraph.iter_sorted with complex dependencies"""
graph = DependencyGraph()
graph.add(5, [9])
graph.add(12, [9, 6, 15])
graph.add(15, [9, 2])
graph.add(9, [14, 20])
graph.add(6, [14, 2])
self.assertEqual(list(graph.iter_sorted()),
[14, 20, 9, 5, 2, 6, 15, 12])
def test_iter_sorted_circular_ref(self):
"""Testing DependencyGraph.iter_sorted with circular reference"""
graph = DependencyGraph()
graph.add(1, [2])
graph.add(2, [1])
self.assertEqual(list(graph.iter_sorted()), [2, 1])
|
"""Testing DependencyGraph.iter_sorted in simple case"""
graph = DependencyGraph()
graph.add(3, [2])
graph.add(2, [1])
graph.add(1, [])
self.assertEqual(list(graph.iter_sorted()), [1, 2, 3])
|
identifier_body
|
test_dep_graph.py
|
from __future__ import unicode_literals
from rbpkg.package_manager.dep_graph import DependencyGraph
from rbpkg.testing.testcases import TestCase
class DependencyGraphTests(TestCase):
"""Unit tests for rbpkg.package_manager.dep_graph.DependencyGraph."""
def
|
(self):
"""Testing DependencyGraph.iter_sorted in simple case"""
graph = DependencyGraph()
graph.add(3, [2])
graph.add(2, [1])
graph.add(1, [])
self.assertEqual(list(graph.iter_sorted()), [1, 2, 3])
def test_iter_sorted_complex(self):
"""Testing DependencyGraph.iter_sorted with complex dependencies"""
graph = DependencyGraph()
graph.add(5, [9])
graph.add(12, [9, 6, 15])
graph.add(15, [9, 2])
graph.add(9, [14, 20])
graph.add(6, [14, 2])
self.assertEqual(list(graph.iter_sorted()),
[14, 20, 9, 5, 2, 6, 15, 12])
def test_iter_sorted_circular_ref(self):
"""Testing DependencyGraph.iter_sorted with circular reference"""
graph = DependencyGraph()
graph.add(1, [2])
graph.add(2, [1])
self.assertEqual(list(graph.iter_sorted()), [2, 1])
|
test_iter_sorted_simple
|
identifier_name
|
idb-helper.js
|
let db;
let idb_helper;
module.exports = idb_helper = {
set_graphene_db: database => {
db = database;
},
trx_readwrite: object_stores => {
return db.transaction(
[object_stores], "readwrite"
);
},
on_request_end: (request) => {
//return request => {
return new Promise((resolve, reject) => {
request.onsuccess = new ChainEvent(
request.onsuccess, resolve, request).event;
request.onerror = new ChainEvent(
request.onerror, reject, request).event;
});
//}(request)
},
on_transaction_end: (transaction) => {
return new Promise((resolve, reject) => {
transaction.oncomplete = new ChainEvent(
transaction.oncomplete, resolve).event;
transaction.onabort = new ChainEvent(
transaction.onabort, reject).event;
});
},
/** Chain an add event. Provide the @param store and @param object and
this method gives you convenient hooks into the database events.
@param event_callback (within active transaction)
@return Promise (resolves or rejects outside of the transaction)
*/
add: (store, object, event_callback) => {
return function(object, event_callback) {
let request = store.add(object);
let event_promise = null;
if(event_callback)
request.onsuccess = new ChainEvent(
request.onsuccess, event => {
event_promise = event_callback(event);
}).event;
let request_promise = idb_helper.on_request_end(request).then( event => {
//DEBUG console.log('... object',object,'result',event.target.result,'event',event)
if ( event.target.result != void 0) {
//todo does event provide the keyPath name? (instead of id)
object.id = event.target.result;
}
return [ object, event ];
});
if(event_promise)
return Promise.all([event_promise, request_promise]);
return request_promise;
}(object, event_callback); //copy let references for callbacks
},
/** callback may return <b>false</b> to indicate that iteration should stop */
cursor: (store_name, callback, transaction) => {
return new Promise((resolve, reject)=>{
if( ! transaction) {
transaction = db.transaction(
[store_name], "readonly"
);
transaction.onerror = error => {
console.error("ERROR idb_helper.cursor transaction", error);
reject(error);
};
}
let store = transaction.objectStore(store_name);
let request = store.openCursor();
request.onsuccess = e => {
let cursor = e.target.result;
let ret = callback(cursor, e);
if(ret === false) resolve();
if(!cursor) resolve(ret);
};
request.onerror = (e) => {
let error = {
error: e.target.error.message,
data: e
};
console.log("ERROR idb_helper.cursor request", error);
reject(error);
};
}).then();
},
autoIncrement_unique: (db, table_name, unique_index) => {
return db.createObjectStore(
table_name, { keyPath: "id", autoIncrement: true }
).createIndex(
"by_"+unique_index, unique_index, { unique: true }
);
}
};
class
|
{
constructor(existing_on_event, callback, request) {
this.event = (event)=> {
if(event.target.error)
console.error("---- transaction error ---->", event.target.error);
//event.request = request
callback(event);
if(existing_on_event) existing_on_event(event);
};
}
}
|
ChainEvent
|
identifier_name
|
idb-helper.js
|
let db;
let idb_helper;
module.exports = idb_helper = {
set_graphene_db: database => {
db = database;
},
trx_readwrite: object_stores => {
return db.transaction(
[object_stores], "readwrite"
);
},
on_request_end: (request) => {
//return request => {
return new Promise((resolve, reject) => {
request.onsuccess = new ChainEvent(
request.onsuccess, resolve, request).event;
request.onerror = new ChainEvent(
request.onerror, reject, request).event;
});
//}(request)
},
on_transaction_end: (transaction) => {
return new Promise((resolve, reject) => {
transaction.oncomplete = new ChainEvent(
transaction.oncomplete, resolve).event;
transaction.onabort = new ChainEvent(
transaction.onabort, reject).event;
});
},
/** Chain an add event. Provide the @param store and @param object and
this method gives you convenient hooks into the database events.
@param event_callback (within active transaction)
@return Promise (resolves or rejects outside of the transaction)
*/
add: (store, object, event_callback) => {
return function(object, event_callback) {
let request = store.add(object);
let event_promise = null;
if(event_callback)
request.onsuccess = new ChainEvent(
request.onsuccess, event => {
event_promise = event_callback(event);
}).event;
let request_promise = idb_helper.on_request_end(request).then( event => {
//DEBUG console.log('... object',object,'result',event.target.result,'event',event)
if ( event.target.result != void 0) {
//todo does event provide the keyPath name? (instead of id)
object.id = event.target.result;
}
return [ object, event ];
});
if(event_promise)
return Promise.all([event_promise, request_promise]);
return request_promise;
}(object, event_callback); //copy let references for callbacks
},
/** callback may return <b>false</b> to indicate that iteration should stop */
cursor: (store_name, callback, transaction) => {
return new Promise((resolve, reject)=>{
if( ! transaction) {
transaction = db.transaction(
[store_name], "readonly"
);
transaction.onerror = error => {
console.error("ERROR idb_helper.cursor transaction", error);
reject(error);
};
}
let store = transaction.objectStore(store_name);
let request = store.openCursor();
request.onsuccess = e => {
let cursor = e.target.result;
let ret = callback(cursor, e);
if(ret === false) resolve();
if(!cursor) resolve(ret);
};
request.onerror = (e) => {
let error = {
error: e.target.error.message,
data: e
};
console.log("ERROR idb_helper.cursor request", error);
reject(error);
};
}).then();
},
|
return db.createObjectStore(
table_name, { keyPath: "id", autoIncrement: true }
).createIndex(
"by_"+unique_index, unique_index, { unique: true }
);
}
};
class ChainEvent {
constructor(existing_on_event, callback, request) {
this.event = (event)=> {
if(event.target.error)
console.error("---- transaction error ---->", event.target.error);
//event.request = request
callback(event);
if(existing_on_event) existing_on_event(event);
};
}
}
|
autoIncrement_unique: (db, table_name, unique_index) => {
|
random_line_split
|
ip_ban.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright 2013 Joe Harris
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.
'''
'''
Trivial example of how to ban an IP. See:
http://www.cloudflare.com/docs/client-api.html#s4.7
'''
import os, sys
# make sure our local copy of txcloudflare is in sys.path
PATH_TO_TXCF = '../txcloudflare/'
try:
import txcloudflare
except ImportError:
txcfpath = os.path.dirname(os.path.realpath(PATH_TO_TXCF))
if txcfpath not in sys.path:
|
from twisted.internet import reactor
import txcloudflare
def got_response(response):
'''
'response' is a txcloudflare.response.Response() instance.
'''
print '< got a response (done)'
print '< ip: {0}'.format(response.data.get('ip', ''))
print '< action: {0}'.format(response.data.get('action', ''))
reactor.stop()
def got_error(error):
'''
'error' is a twisted.python.failure.Failure() instance wrapping one of
the exceptions in txcloudflare.errors. The exceptions return the
CloudFlare error code, a plain text string and a response object
(txcloudflare.response.Response). The response object has a 'request'
parameter if you need to look at the reques that generated the error.
'''
print '< error'
print error.printTraceback()
reactor.stop()
email_address = os.environ.get('TXCFEMAIL', '')
api_token = os.environ.get('TXCFAPI', '')
if __name__ == '__main__':
ip = '8.8.8.8'
print '> banning IP: {0}'.format(ip)
cloudflare = txcloudflare.client_api(email_address, api_token)
cloudflare.ban(ip=ip).addCallback(got_response).addErrback(got_error)
reactor.run()
'''
EOF
'''
|
sys.path.insert(0, txcfpath)
|
conditional_block
|
ip_ban.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright 2013 Joe Harris
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.
'''
'''
Trivial example of how to ban an IP. See:
http://www.cloudflare.com/docs/client-api.html#s4.7
'''
import os, sys
# make sure our local copy of txcloudflare is in sys.path
PATH_TO_TXCF = '../txcloudflare/'
try:
import txcloudflare
except ImportError:
txcfpath = os.path.dirname(os.path.realpath(PATH_TO_TXCF))
if txcfpath not in sys.path:
sys.path.insert(0, txcfpath)
from twisted.internet import reactor
import txcloudflare
def got_response(response):
'''
'response' is a txcloudflare.response.Response() instance.
'''
print '< got a response (done)'
print '< ip: {0}'.format(response.data.get('ip', ''))
print '< action: {0}'.format(response.data.get('action', ''))
reactor.stop()
def
|
(error):
'''
'error' is a twisted.python.failure.Failure() instance wrapping one of
the exceptions in txcloudflare.errors. The exceptions return the
CloudFlare error code, a plain text string and a response object
(txcloudflare.response.Response). The response object has a 'request'
parameter if you need to look at the reques that generated the error.
'''
print '< error'
print error.printTraceback()
reactor.stop()
email_address = os.environ.get('TXCFEMAIL', '')
api_token = os.environ.get('TXCFAPI', '')
if __name__ == '__main__':
ip = '8.8.8.8'
print '> banning IP: {0}'.format(ip)
cloudflare = txcloudflare.client_api(email_address, api_token)
cloudflare.ban(ip=ip).addCallback(got_response).addErrback(got_error)
reactor.run()
'''
EOF
'''
|
got_error
|
identifier_name
|
ip_ban.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright 2013 Joe Harris
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.
'''
'''
Trivial example of how to ban an IP. See:
http://www.cloudflare.com/docs/client-api.html#s4.7
'''
import os, sys
# make sure our local copy of txcloudflare is in sys.path
PATH_TO_TXCF = '../txcloudflare/'
try:
import txcloudflare
except ImportError:
txcfpath = os.path.dirname(os.path.realpath(PATH_TO_TXCF))
if txcfpath not in sys.path:
sys.path.insert(0, txcfpath)
from twisted.internet import reactor
import txcloudflare
def got_response(response):
|
def got_error(error):
'''
'error' is a twisted.python.failure.Failure() instance wrapping one of
the exceptions in txcloudflare.errors. The exceptions return the
CloudFlare error code, a plain text string and a response object
(txcloudflare.response.Response). The response object has a 'request'
parameter if you need to look at the reques that generated the error.
'''
print '< error'
print error.printTraceback()
reactor.stop()
email_address = os.environ.get('TXCFEMAIL', '')
api_token = os.environ.get('TXCFAPI', '')
if __name__ == '__main__':
ip = '8.8.8.8'
print '> banning IP: {0}'.format(ip)
cloudflare = txcloudflare.client_api(email_address, api_token)
cloudflare.ban(ip=ip).addCallback(got_response).addErrback(got_error)
reactor.run()
'''
EOF
'''
|
'''
'response' is a txcloudflare.response.Response() instance.
'''
print '< got a response (done)'
print '< ip: {0}'.format(response.data.get('ip', ''))
print '< action: {0}'.format(response.data.get('action', ''))
reactor.stop()
|
identifier_body
|
ip_ban.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright 2013 Joe Harris
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.
'''
'''
Trivial example of how to ban an IP. See:
http://www.cloudflare.com/docs/client-api.html#s4.7
'''
import os, sys
# make sure our local copy of txcloudflare is in sys.path
PATH_TO_TXCF = '../txcloudflare/'
try:
import txcloudflare
except ImportError:
txcfpath = os.path.dirname(os.path.realpath(PATH_TO_TXCF))
if txcfpath not in sys.path:
sys.path.insert(0, txcfpath)
from twisted.internet import reactor
import txcloudflare
def got_response(response):
'''
'response' is a txcloudflare.response.Response() instance.
'''
print '< got a response (done)'
print '< ip: {0}'.format(response.data.get('ip', ''))
print '< action: {0}'.format(response.data.get('action', ''))
reactor.stop()
def got_error(error):
'''
'error' is a twisted.python.failure.Failure() instance wrapping one of
the exceptions in txcloudflare.errors. The exceptions return the
CloudFlare error code, a plain text string and a response object
(txcloudflare.response.Response). The response object has a 'request'
parameter if you need to look at the reques that generated the error.
'''
print '< error'
print error.printTraceback()
reactor.stop()
email_address = os.environ.get('TXCFEMAIL', '')
api_token = os.environ.get('TXCFAPI', '')
if __name__ == '__main__':
ip = '8.8.8.8'
print '> banning IP: {0}'.format(ip)
cloudflare = txcloudflare.client_api(email_address, api_token)
cloudflare.ban(ip=ip).addCallback(got_response).addErrback(got_error)
reactor.run()
'''
|
EOF
'''
|
random_line_split
|
|
api_request_builder.ts
|
/*
* Copyright 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or 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.
*/
import {CaseInsensitiveMap} from "helpers/collections";
import _ from "lodash";
import m from "mithril";
export enum ApiVersion { latest, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10}
export interface ObjectWithEtag<T> {
etag: string;
object: T;
}
export interface SuccessResponse<T> {
body: T;
}
export interface ErrorResponse {
message: string; //more fields can be added if needed
body?: string;
data?: object;
}
export class ApiResult<T> {
private readonly successResponse?: SuccessResponse<T>;
private readonly errorResponse?: ErrorResponse;
private readonly statusCode: number;
private readonly headers: Map<string, string>;
private constructor(successResponse: SuccessResponse<T> | undefined,
errorResponse: ErrorResponse | undefined,
statusCode: number,
headers: Map<string, string>) {
this.successResponse = successResponse;
this.errorResponse = errorResponse;
this.statusCode = statusCode;
this.headers = headers;
}
static from(xhr: XMLHttpRequest) {
return this.parseResponse(xhr);
}
static success(body: string, statusCode: number, headers: Map<string, string>) {
return new ApiResult<string>({body}, undefined, statusCode, headers);
}
static accepted(body: string, statusCode: number, headers: Map<string, string>) {
return new ApiResult<string>({body}, undefined, statusCode, headers);
}
static error(body: string, message: string, statusCode: number, headers: Map<string, string>) {
return new ApiResult<string>(undefined, {body, message}, statusCode, headers);
}
getStatusCode(): number {
if (this.statusCode) {
|
header(name: string) {
return this.headers.get(name);
}
getEtag(): string | null {
return this.header("etag") || null;
}
getRedirectUrl(): string {
return this.header("Location") || "";
}
getRetryAfterIntervalInMillis(): number {
return Number(this.header("retry-after") || 0) * 1000;
}
map<U>(func: (x: T) => U): ApiResult<U> {
if (this.successResponse) {
const transformedBody = func(this.successResponse.body);
return new ApiResult<U>({body: transformedBody}, this.errorResponse, this.statusCode, this.headers);
} else {
return new ApiResult<U>(this.successResponse, this.errorResponse, this.statusCode, this.headers);
}
}
do(onSuccess: (successResponse: SuccessResponse<T>) => any, onError: (errorResponse: ErrorResponse) => any = () => { /* donothing */}) {
if (this.successResponse) {
return onSuccess(this.successResponse);
} else if (this.errorResponse) {
return onError(this.errorResponse);
}
}
unwrap() {
if (this.successResponse) {
return this.successResponse;
} else {
if (this.errorResponse!.body) {
try {
return JSON.parse(this.errorResponse!.body);
} catch (e) {
//may be parse of the json failed, return the string response as is..
return this.errorResponse!.body;
}
}
return this.errorResponse;
}
}
getOrThrow() {
if (this.successResponse) {
return this.successResponse.body;
} else if (this.errorResponse) {
throw new Error(JSON.parse(this.errorResponse.body!).message);
} else {
throw new Error();
}
}
private static parseResponse(xhr: XMLHttpRequest): ApiResult<string> {
const headers = allHeaders(xhr);
switch (xhr.status) {
case 200:
case 201:
return ApiResult.success(xhr.responseText, xhr.status, headers);
case 202:
return ApiResult.accepted(xhr.responseText, xhr.status, headers);
case 422:
case 503:
return ApiResult.error(xhr.responseText, parseMessage(xhr), xhr.status, headers);
}
return ApiResult.error(xhr.responseText,
`There was an unknown error performing the operation. Possible reason (${xhr.statusText})`,
xhr.status, headers);
}
}
function allHeaders(xhr: XMLHttpRequest): Map<string, string> {
const payload = xhr.getAllResponseHeaders();
const headers = new CaseInsensitiveMap<string>();
for (const line of payload.trim().split(/[\r\n]+/)) {
const parts = line.split(": ");
headers.set(parts.shift()!, parts.join(": "));
}
return headers;
}
function parseMessage(xhr: XMLHttpRequest) {
if (xhr.response.data && xhr.response.data.message) {
return xhr.response.data.message;
}
return `There was an unknown error performing the operation. Possible reason (${xhr.statusText})`;
}
interface Headers {
[key: string]: string;
}
export interface RequestOptions {
etag?: string;
payload: any;
headers?: Headers;
xhrHandle?: (xhr: XMLHttpRequest) => void; //A reference to the underlying XHR object, which can be used to abort the request
}
export class ApiRequestBuilder {
static GET(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "GET", apiVersion, options);
}
static PUT(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "PUT", apiVersion, options);
}
static POST(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "POST", apiVersion, options);
}
static PATCH(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "PATCH", apiVersion, options);
}
static DELETE(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "DELETE", apiVersion, options);
}
static versionHeader(version: ApiVersion): string {
if (version === ApiVersion.latest) {
return `application/vnd.go.cd+json`;
} else {
return `application/vnd.go.cd.${ApiVersion[version]}+json`;
}
}
private static makeRequest(url: string,
method: string,
apiVersion?: ApiVersion,
options?: Partial<RequestOptions>): Promise<ApiResult<string>> {
const headers = this.buildHeaders(method, apiVersion, options);
let payload: any;
if (options && options.payload) {
payload = options.payload;
}
return m.request<XMLHttpRequest>({
url,
method,
headers,
body: payload,
extract: _.identity,
deserialize: _.identity,
config: (xhr) => {
if (options && options.xhrHandle) {
options.xhrHandle(xhr);
}
}
}).then((xhr: XMLHttpRequest) => {
return ApiResult.from(xhr);
}).catch((reason) => {
const unknownError = "There was an unknown error performing the operation.";
try {
return ApiResult.error(reason.responseText,
JSON.parse(reason.message).message || unknownError,
reason.status,
new Map());
} catch {
return ApiResult.error(reason.responseText, unknownError, reason.status, new Map());
}
});
}
private static buildHeaders(method: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
let headers: Headers = {};
if (options && options.headers) {
headers = _.assign({}, options.headers);
}
if (apiVersion !== undefined) {
headers.Accept = this.versionHeader(apiVersion as ApiVersion);
headers["X-Requested-With"] = "XMLHttpRequest";
}
if (options && !_.isEmpty(options.etag)) {
headers[this.etagHeaderName(method)] = options.etag as string;
}
if ((!options || !options.payload) && ApiRequestBuilder.isAnUpdate(method)) {
headers["X-GoCD-Confirm"] = "true";
}
return headers;
}
private static isAnUpdate(method: string) {
const updateMethods = ["PUT", "POST", "DELETE", "PATCH"];
return updateMethods.includes(method.toUpperCase());
}
private static etagHeaderName(method: string) {
return method.toLowerCase() === "get" || method.toLowerCase() === "head" ? "If-None-Match" : "If-Match";
}
}
|
return this.statusCode;
}
return -1;
}
|
random_line_split
|
api_request_builder.ts
|
/*
* Copyright 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or 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.
*/
import {CaseInsensitiveMap} from "helpers/collections";
import _ from "lodash";
import m from "mithril";
export enum ApiVersion { latest, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10}
export interface ObjectWithEtag<T> {
etag: string;
object: T;
}
export interface SuccessResponse<T> {
body: T;
}
export interface ErrorResponse {
message: string; //more fields can be added if needed
body?: string;
data?: object;
}
export class ApiResult<T> {
private readonly successResponse?: SuccessResponse<T>;
private readonly errorResponse?: ErrorResponse;
private readonly statusCode: number;
private readonly headers: Map<string, string>;
private
|
(successResponse: SuccessResponse<T> | undefined,
errorResponse: ErrorResponse | undefined,
statusCode: number,
headers: Map<string, string>) {
this.successResponse = successResponse;
this.errorResponse = errorResponse;
this.statusCode = statusCode;
this.headers = headers;
}
static from(xhr: XMLHttpRequest) {
return this.parseResponse(xhr);
}
static success(body: string, statusCode: number, headers: Map<string, string>) {
return new ApiResult<string>({body}, undefined, statusCode, headers);
}
static accepted(body: string, statusCode: number, headers: Map<string, string>) {
return new ApiResult<string>({body}, undefined, statusCode, headers);
}
static error(body: string, message: string, statusCode: number, headers: Map<string, string>) {
return new ApiResult<string>(undefined, {body, message}, statusCode, headers);
}
getStatusCode(): number {
if (this.statusCode) {
return this.statusCode;
}
return -1;
}
header(name: string) {
return this.headers.get(name);
}
getEtag(): string | null {
return this.header("etag") || null;
}
getRedirectUrl(): string {
return this.header("Location") || "";
}
getRetryAfterIntervalInMillis(): number {
return Number(this.header("retry-after") || 0) * 1000;
}
map<U>(func: (x: T) => U): ApiResult<U> {
if (this.successResponse) {
const transformedBody = func(this.successResponse.body);
return new ApiResult<U>({body: transformedBody}, this.errorResponse, this.statusCode, this.headers);
} else {
return new ApiResult<U>(this.successResponse, this.errorResponse, this.statusCode, this.headers);
}
}
do(onSuccess: (successResponse: SuccessResponse<T>) => any, onError: (errorResponse: ErrorResponse) => any = () => { /* donothing */}) {
if (this.successResponse) {
return onSuccess(this.successResponse);
} else if (this.errorResponse) {
return onError(this.errorResponse);
}
}
unwrap() {
if (this.successResponse) {
return this.successResponse;
} else {
if (this.errorResponse!.body) {
try {
return JSON.parse(this.errorResponse!.body);
} catch (e) {
//may be parse of the json failed, return the string response as is..
return this.errorResponse!.body;
}
}
return this.errorResponse;
}
}
getOrThrow() {
if (this.successResponse) {
return this.successResponse.body;
} else if (this.errorResponse) {
throw new Error(JSON.parse(this.errorResponse.body!).message);
} else {
throw new Error();
}
}
private static parseResponse(xhr: XMLHttpRequest): ApiResult<string> {
const headers = allHeaders(xhr);
switch (xhr.status) {
case 200:
case 201:
return ApiResult.success(xhr.responseText, xhr.status, headers);
case 202:
return ApiResult.accepted(xhr.responseText, xhr.status, headers);
case 422:
case 503:
return ApiResult.error(xhr.responseText, parseMessage(xhr), xhr.status, headers);
}
return ApiResult.error(xhr.responseText,
`There was an unknown error performing the operation. Possible reason (${xhr.statusText})`,
xhr.status, headers);
}
}
function allHeaders(xhr: XMLHttpRequest): Map<string, string> {
const payload = xhr.getAllResponseHeaders();
const headers = new CaseInsensitiveMap<string>();
for (const line of payload.trim().split(/[\r\n]+/)) {
const parts = line.split(": ");
headers.set(parts.shift()!, parts.join(": "));
}
return headers;
}
function parseMessage(xhr: XMLHttpRequest) {
if (xhr.response.data && xhr.response.data.message) {
return xhr.response.data.message;
}
return `There was an unknown error performing the operation. Possible reason (${xhr.statusText})`;
}
interface Headers {
[key: string]: string;
}
export interface RequestOptions {
etag?: string;
payload: any;
headers?: Headers;
xhrHandle?: (xhr: XMLHttpRequest) => void; //A reference to the underlying XHR object, which can be used to abort the request
}
export class ApiRequestBuilder {
static GET(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "GET", apiVersion, options);
}
static PUT(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "PUT", apiVersion, options);
}
static POST(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "POST", apiVersion, options);
}
static PATCH(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "PATCH", apiVersion, options);
}
static DELETE(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "DELETE", apiVersion, options);
}
static versionHeader(version: ApiVersion): string {
if (version === ApiVersion.latest) {
return `application/vnd.go.cd+json`;
} else {
return `application/vnd.go.cd.${ApiVersion[version]}+json`;
}
}
private static makeRequest(url: string,
method: string,
apiVersion?: ApiVersion,
options?: Partial<RequestOptions>): Promise<ApiResult<string>> {
const headers = this.buildHeaders(method, apiVersion, options);
let payload: any;
if (options && options.payload) {
payload = options.payload;
}
return m.request<XMLHttpRequest>({
url,
method,
headers,
body: payload,
extract: _.identity,
deserialize: _.identity,
config: (xhr) => {
if (options && options.xhrHandle) {
options.xhrHandle(xhr);
}
}
}).then((xhr: XMLHttpRequest) => {
return ApiResult.from(xhr);
}).catch((reason) => {
const unknownError = "There was an unknown error performing the operation.";
try {
return ApiResult.error(reason.responseText,
JSON.parse(reason.message).message || unknownError,
reason.status,
new Map());
} catch {
return ApiResult.error(reason.responseText, unknownError, reason.status, new Map());
}
});
}
private static buildHeaders(method: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
let headers: Headers = {};
if (options && options.headers) {
headers = _.assign({}, options.headers);
}
if (apiVersion !== undefined) {
headers.Accept = this.versionHeader(apiVersion as ApiVersion);
headers["X-Requested-With"] = "XMLHttpRequest";
}
if (options && !_.isEmpty(options.etag)) {
headers[this.etagHeaderName(method)] = options.etag as string;
}
if ((!options || !options.payload) && ApiRequestBuilder.isAnUpdate(method)) {
headers["X-GoCD-Confirm"] = "true";
}
return headers;
}
private static isAnUpdate(method: string) {
const updateMethods = ["PUT", "POST", "DELETE", "PATCH"];
return updateMethods.includes(method.toUpperCase());
}
private static etagHeaderName(method: string) {
return method.toLowerCase() === "get" || method.toLowerCase() === "head" ? "If-None-Match" : "If-Match";
}
}
|
constructor
|
identifier_name
|
api_request_builder.ts
|
/*
* Copyright 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or 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.
*/
import {CaseInsensitiveMap} from "helpers/collections";
import _ from "lodash";
import m from "mithril";
export enum ApiVersion { latest, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10}
export interface ObjectWithEtag<T> {
etag: string;
object: T;
}
export interface SuccessResponse<T> {
body: T;
}
export interface ErrorResponse {
message: string; //more fields can be added if needed
body?: string;
data?: object;
}
export class ApiResult<T> {
private readonly successResponse?: SuccessResponse<T>;
private readonly errorResponse?: ErrorResponse;
private readonly statusCode: number;
private readonly headers: Map<string, string>;
private constructor(successResponse: SuccessResponse<T> | undefined,
errorResponse: ErrorResponse | undefined,
statusCode: number,
headers: Map<string, string>) {
this.successResponse = successResponse;
this.errorResponse = errorResponse;
this.statusCode = statusCode;
this.headers = headers;
}
static from(xhr: XMLHttpRequest) {
return this.parseResponse(xhr);
}
static success(body: string, statusCode: number, headers: Map<string, string>) {
return new ApiResult<string>({body}, undefined, statusCode, headers);
}
static accepted(body: string, statusCode: number, headers: Map<string, string>) {
return new ApiResult<string>({body}, undefined, statusCode, headers);
}
static error(body: string, message: string, statusCode: number, headers: Map<string, string>) {
return new ApiResult<string>(undefined, {body, message}, statusCode, headers);
}
getStatusCode(): number {
if (this.statusCode) {
return this.statusCode;
}
return -1;
}
header(name: string) {
return this.headers.get(name);
}
getEtag(): string | null {
return this.header("etag") || null;
}
getRedirectUrl(): string {
return this.header("Location") || "";
}
getRetryAfterIntervalInMillis(): number {
return Number(this.header("retry-after") || 0) * 1000;
}
map<U>(func: (x: T) => U): ApiResult<U> {
if (this.successResponse) {
const transformedBody = func(this.successResponse.body);
return new ApiResult<U>({body: transformedBody}, this.errorResponse, this.statusCode, this.headers);
} else {
return new ApiResult<U>(this.successResponse, this.errorResponse, this.statusCode, this.headers);
}
}
do(onSuccess: (successResponse: SuccessResponse<T>) => any, onError: (errorResponse: ErrorResponse) => any = () => { /* donothing */}) {
if (this.successResponse) {
return onSuccess(this.successResponse);
} else if (this.errorResponse) {
return onError(this.errorResponse);
}
}
unwrap() {
if (this.successResponse) {
return this.successResponse;
} else {
if (this.errorResponse!.body) {
try {
return JSON.parse(this.errorResponse!.body);
} catch (e) {
//may be parse of the json failed, return the string response as is..
return this.errorResponse!.body;
}
}
return this.errorResponse;
}
}
getOrThrow() {
if (this.successResponse) {
return this.successResponse.body;
} else if (this.errorResponse) {
throw new Error(JSON.parse(this.errorResponse.body!).message);
} else {
throw new Error();
}
}
private static parseResponse(xhr: XMLHttpRequest): ApiResult<string> {
const headers = allHeaders(xhr);
switch (xhr.status) {
case 200:
case 201:
return ApiResult.success(xhr.responseText, xhr.status, headers);
case 202:
return ApiResult.accepted(xhr.responseText, xhr.status, headers);
case 422:
case 503:
return ApiResult.error(xhr.responseText, parseMessage(xhr), xhr.status, headers);
}
return ApiResult.error(xhr.responseText,
`There was an unknown error performing the operation. Possible reason (${xhr.statusText})`,
xhr.status, headers);
}
}
function allHeaders(xhr: XMLHttpRequest): Map<string, string> {
const payload = xhr.getAllResponseHeaders();
const headers = new CaseInsensitiveMap<string>();
for (const line of payload.trim().split(/[\r\n]+/)) {
const parts = line.split(": ");
headers.set(parts.shift()!, parts.join(": "));
}
return headers;
}
function parseMessage(xhr: XMLHttpRequest) {
if (xhr.response.data && xhr.response.data.message) {
return xhr.response.data.message;
}
return `There was an unknown error performing the operation. Possible reason (${xhr.statusText})`;
}
interface Headers {
[key: string]: string;
}
export interface RequestOptions {
etag?: string;
payload: any;
headers?: Headers;
xhrHandle?: (xhr: XMLHttpRequest) => void; //A reference to the underlying XHR object, which can be used to abort the request
}
export class ApiRequestBuilder {
static GET(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "GET", apiVersion, options);
}
static PUT(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "PUT", apiVersion, options);
}
static POST(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "POST", apiVersion, options);
}
static PATCH(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "PATCH", apiVersion, options);
}
static DELETE(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "DELETE", apiVersion, options);
}
static versionHeader(version: ApiVersion): string {
if (version === ApiVersion.latest)
|
else {
return `application/vnd.go.cd.${ApiVersion[version]}+json`;
}
}
private static makeRequest(url: string,
method: string,
apiVersion?: ApiVersion,
options?: Partial<RequestOptions>): Promise<ApiResult<string>> {
const headers = this.buildHeaders(method, apiVersion, options);
let payload: any;
if (options && options.payload) {
payload = options.payload;
}
return m.request<XMLHttpRequest>({
url,
method,
headers,
body: payload,
extract: _.identity,
deserialize: _.identity,
config: (xhr) => {
if (options && options.xhrHandle) {
options.xhrHandle(xhr);
}
}
}).then((xhr: XMLHttpRequest) => {
return ApiResult.from(xhr);
}).catch((reason) => {
const unknownError = "There was an unknown error performing the operation.";
try {
return ApiResult.error(reason.responseText,
JSON.parse(reason.message).message || unknownError,
reason.status,
new Map());
} catch {
return ApiResult.error(reason.responseText, unknownError, reason.status, new Map());
}
});
}
private static buildHeaders(method: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
let headers: Headers = {};
if (options && options.headers) {
headers = _.assign({}, options.headers);
}
if (apiVersion !== undefined) {
headers.Accept = this.versionHeader(apiVersion as ApiVersion);
headers["X-Requested-With"] = "XMLHttpRequest";
}
if (options && !_.isEmpty(options.etag)) {
headers[this.etagHeaderName(method)] = options.etag as string;
}
if ((!options || !options.payload) && ApiRequestBuilder.isAnUpdate(method)) {
headers["X-GoCD-Confirm"] = "true";
}
return headers;
}
private static isAnUpdate(method: string) {
const updateMethods = ["PUT", "POST", "DELETE", "PATCH"];
return updateMethods.includes(method.toUpperCase());
}
private static etagHeaderName(method: string) {
return method.toLowerCase() === "get" || method.toLowerCase() === "head" ? "If-None-Match" : "If-Match";
}
}
|
{
return `application/vnd.go.cd+json`;
}
|
conditional_block
|
api_request_builder.ts
|
/*
* Copyright 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or 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.
*/
import {CaseInsensitiveMap} from "helpers/collections";
import _ from "lodash";
import m from "mithril";
export enum ApiVersion { latest, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10}
export interface ObjectWithEtag<T> {
etag: string;
object: T;
}
export interface SuccessResponse<T> {
body: T;
}
export interface ErrorResponse {
message: string; //more fields can be added if needed
body?: string;
data?: object;
}
export class ApiResult<T> {
private readonly successResponse?: SuccessResponse<T>;
private readonly errorResponse?: ErrorResponse;
private readonly statusCode: number;
private readonly headers: Map<string, string>;
private constructor(successResponse: SuccessResponse<T> | undefined,
errorResponse: ErrorResponse | undefined,
statusCode: number,
headers: Map<string, string>) {
this.successResponse = successResponse;
this.errorResponse = errorResponse;
this.statusCode = statusCode;
this.headers = headers;
}
static from(xhr: XMLHttpRequest) {
return this.parseResponse(xhr);
}
static success(body: string, statusCode: number, headers: Map<string, string>) {
return new ApiResult<string>({body}, undefined, statusCode, headers);
}
static accepted(body: string, statusCode: number, headers: Map<string, string>) {
return new ApiResult<string>({body}, undefined, statusCode, headers);
}
static error(body: string, message: string, statusCode: number, headers: Map<string, string>) {
return new ApiResult<string>(undefined, {body, message}, statusCode, headers);
}
getStatusCode(): number {
if (this.statusCode) {
return this.statusCode;
}
return -1;
}
header(name: string) {
return this.headers.get(name);
}
getEtag(): string | null {
return this.header("etag") || null;
}
getRedirectUrl(): string {
return this.header("Location") || "";
}
getRetryAfterIntervalInMillis(): number
|
map<U>(func: (x: T) => U): ApiResult<U> {
if (this.successResponse) {
const transformedBody = func(this.successResponse.body);
return new ApiResult<U>({body: transformedBody}, this.errorResponse, this.statusCode, this.headers);
} else {
return new ApiResult<U>(this.successResponse, this.errorResponse, this.statusCode, this.headers);
}
}
do(onSuccess: (successResponse: SuccessResponse<T>) => any, onError: (errorResponse: ErrorResponse) => any = () => { /* donothing */}) {
if (this.successResponse) {
return onSuccess(this.successResponse);
} else if (this.errorResponse) {
return onError(this.errorResponse);
}
}
unwrap() {
if (this.successResponse) {
return this.successResponse;
} else {
if (this.errorResponse!.body) {
try {
return JSON.parse(this.errorResponse!.body);
} catch (e) {
//may be parse of the json failed, return the string response as is..
return this.errorResponse!.body;
}
}
return this.errorResponse;
}
}
getOrThrow() {
if (this.successResponse) {
return this.successResponse.body;
} else if (this.errorResponse) {
throw new Error(JSON.parse(this.errorResponse.body!).message);
} else {
throw new Error();
}
}
private static parseResponse(xhr: XMLHttpRequest): ApiResult<string> {
const headers = allHeaders(xhr);
switch (xhr.status) {
case 200:
case 201:
return ApiResult.success(xhr.responseText, xhr.status, headers);
case 202:
return ApiResult.accepted(xhr.responseText, xhr.status, headers);
case 422:
case 503:
return ApiResult.error(xhr.responseText, parseMessage(xhr), xhr.status, headers);
}
return ApiResult.error(xhr.responseText,
`There was an unknown error performing the operation. Possible reason (${xhr.statusText})`,
xhr.status, headers);
}
}
function allHeaders(xhr: XMLHttpRequest): Map<string, string> {
const payload = xhr.getAllResponseHeaders();
const headers = new CaseInsensitiveMap<string>();
for (const line of payload.trim().split(/[\r\n]+/)) {
const parts = line.split(": ");
headers.set(parts.shift()!, parts.join(": "));
}
return headers;
}
function parseMessage(xhr: XMLHttpRequest) {
if (xhr.response.data && xhr.response.data.message) {
return xhr.response.data.message;
}
return `There was an unknown error performing the operation. Possible reason (${xhr.statusText})`;
}
interface Headers {
[key: string]: string;
}
export interface RequestOptions {
etag?: string;
payload: any;
headers?: Headers;
xhrHandle?: (xhr: XMLHttpRequest) => void; //A reference to the underlying XHR object, which can be used to abort the request
}
export class ApiRequestBuilder {
static GET(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "GET", apiVersion, options);
}
static PUT(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "PUT", apiVersion, options);
}
static POST(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "POST", apiVersion, options);
}
static PATCH(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "PATCH", apiVersion, options);
}
static DELETE(url: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
return this.makeRequest(url, "DELETE", apiVersion, options);
}
static versionHeader(version: ApiVersion): string {
if (version === ApiVersion.latest) {
return `application/vnd.go.cd+json`;
} else {
return `application/vnd.go.cd.${ApiVersion[version]}+json`;
}
}
private static makeRequest(url: string,
method: string,
apiVersion?: ApiVersion,
options?: Partial<RequestOptions>): Promise<ApiResult<string>> {
const headers = this.buildHeaders(method, apiVersion, options);
let payload: any;
if (options && options.payload) {
payload = options.payload;
}
return m.request<XMLHttpRequest>({
url,
method,
headers,
body: payload,
extract: _.identity,
deserialize: _.identity,
config: (xhr) => {
if (options && options.xhrHandle) {
options.xhrHandle(xhr);
}
}
}).then((xhr: XMLHttpRequest) => {
return ApiResult.from(xhr);
}).catch((reason) => {
const unknownError = "There was an unknown error performing the operation.";
try {
return ApiResult.error(reason.responseText,
JSON.parse(reason.message).message || unknownError,
reason.status,
new Map());
} catch {
return ApiResult.error(reason.responseText, unknownError, reason.status, new Map());
}
});
}
private static buildHeaders(method: string, apiVersion?: ApiVersion, options?: Partial<RequestOptions>) {
let headers: Headers = {};
if (options && options.headers) {
headers = _.assign({}, options.headers);
}
if (apiVersion !== undefined) {
headers.Accept = this.versionHeader(apiVersion as ApiVersion);
headers["X-Requested-With"] = "XMLHttpRequest";
}
if (options && !_.isEmpty(options.etag)) {
headers[this.etagHeaderName(method)] = options.etag as string;
}
if ((!options || !options.payload) && ApiRequestBuilder.isAnUpdate(method)) {
headers["X-GoCD-Confirm"] = "true";
}
return headers;
}
private static isAnUpdate(method: string) {
const updateMethods = ["PUT", "POST", "DELETE", "PATCH"];
return updateMethods.includes(method.toUpperCase());
}
private static etagHeaderName(method: string) {
return method.toLowerCase() === "get" || method.toLowerCase() === "head" ? "If-None-Match" : "If-Match";
}
}
|
{
return Number(this.header("retry-after") || 0) * 1000;
}
|
identifier_body
|
app.min.js
|
(function() {
var MainView, stripTags,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor()
|
ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
stripTags = function(input, allowed) {
var commentsAndPhpTags, tags;
allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1) {
if (allowed.indexOf('<' + $1.toLowerCase() + '>') > -1) {
return $0;
} else {
return '';
}
});
};
KD.enableLogs;
MainView = (function(superClass) {
extend(MainView, superClass);
function MainView() {
MainView.__super__.constructor.apply(this, arguments);
this.kite = KD.getSingleton("vmController");
this.header = new KDHeaderView({
type: "big",
title: "KodioFM Holiday Radio"
});
this.talksWrapper = new KDCustomHTMLView({
cssClass: "talks"
});
this.talk1 = new KDCustomHTMLView({
cssClass: "talk1",
partial: "<span>Why did the programmer quit his job?</span>"
});
this.talk2 = new KDCustomHTMLView({
cssClass: "talk2",
partial: "<span><h2>Ouch!</h2>Pines and needles!</span>"
});
this.talk3 = new KDCustomHTMLView({
cssClass: "talk3",
partial: "<span>Because he didn't get arrays.</span>"
});
this.talk4 = new KDCustomHTMLView({
cssClass: "talk4",
partial: "<span><h2>Sigh!</h2>Why do I still hangout with these guys?</span>"
});
this.talksWrapper.addSubView(this.talk1);
this.talksWrapper.addSubView(this.talk2);
this.talksWrapper.addSubView(this.talk3);
this.talksWrapper.addSubView(this.talk4);
this.characters = new KDCustomHTMLView({
cssClass: "characters"
});
this.char1 = new KDCustomHTMLView({
cssClass: "char1"
});
this.char2 = new KDCustomHTMLView({
cssClass: "char2"
});
this.char3 = new KDCustomHTMLView({
cssClass: "char3"
});
this.char4 = new KDCustomHTMLView({
cssClass: "char4"
});
this.characters.addSubView(this.char2);
this.characters.addSubView(this.char1);
this.characters.addSubView(this.char3);
this.characters.addSubView(this.char4);
setTimeout((function(_this) {
return function() {
return $(".char2").hover(function() {
$(".talk1").fadeIn(500);
return $(".char1").hover(function() {
$(".talk2").fadeIn(500);
return $(".char3").hover(function() {
$(".talk3").fadeIn(500);
return $(".char4").hover(function() {
return $(".talk4").fadeIn(500);
});
});
});
});
};
})(this), 500);
this.playerWrapper = new KDCustomHTMLView({
cssClass: "playerWrapper"
});
this.playerWrapper.updatePartial('<audio id="audio-player" name="audio-player" src="http://108.61.73.118:8124/;">Your browser does not support the audio element.</audio>');
this.playButton = new KDButtonView({
cssClass: "playButton fa fa-play",
tooltip: {
title: "Play Radio!",
placement: "bottom"
},
callback: (function(_this) {
return function() {
if (_this.playButton.hasClass("stopButton")) {
_this.playButton.unsetClass("stopButton fa-stop");
_this.playButton.setClass("playButton fa-play");
_this.playerLabel.updatePartial("---");
document.getElementById('audio-player').pause();
return document.getElementById('audio-player').currentTime = 0;
} else {
setInterval(function() {
return _this.getInfo("http://www.181.fm/station_playing/181-xtraditional.html");
}, 10000);
_this.playButton.unsetClass("playButton fa-play");
_this.playButton.setClass("stopButton fa-stop");
return document.getElementById('audio-player').play();
}
};
})(this)
});
this.volumeMinus = new KDButtonView({
cssClass: "volumeMinus fa fa-volume-down",
tooltip: {
title: "Volume Down!",
placement: "bottom"
},
callback: (function(_this) {
return function() {
return document.getElementById('audio-player').volume -= 0.1;
};
})(this)
});
this.volumePlus = new KDButtonView({
cssClass: "volumePlus fa fa-volume-up",
tooltip: {
title: "Volume Up!",
placement: "bottom"
},
callback: (function(_this) {
return function() {
return document.getElementById('audio-player').volume += 0.1;
};
})(this)
});
this.playerWrapper.addSubView(this.playButton);
this.playerWrapper.addSubView(this.volumeMinus);
this.playerWrapper.addSubView(this.volumePlus);
this.playerLabel = new KDCustomHTMLView({
cssClass: "playerLabel",
partial: "---"
});
}
MainView.prototype.getInfo = function(url) {
if (!url) {
return;
}
return this.kite.run("curl -kLss " + url, (function(_this) {
return function(error, data) {
data = strip_tags(data);
data = data.replace(/[\n\r\t]/g, "");
data = data.substr(data.indexOf("CD") + 2);
data = data.trim();
return _this.playerLabel.updatePartial(data);
};
})(this));
};
MainView.prototype.pistachio = function() {
return "<footer>\n {{> @talksWrapper}}\n {{> @characters}}\n <section class=\"ground\">\n {{> @header}}{{> @playerWrapper}}{{> @playerLabel}}\n </section>\n</footer>";
};
appView.addSubView(new MainView({
cssClass: "wrapper snowcontainer"
}));
return MainView;
})(JView);
}).call(this);
|
{ this.constructor = child; }
|
identifier_body
|
app.min.js
|
(function() {
var MainView, stripTags,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function
|
() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
stripTags = function(input, allowed) {
var commentsAndPhpTags, tags;
allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1) {
if (allowed.indexOf('<' + $1.toLowerCase() + '>') > -1) {
return $0;
} else {
return '';
}
});
};
KD.enableLogs;
MainView = (function(superClass) {
extend(MainView, superClass);
function MainView() {
MainView.__super__.constructor.apply(this, arguments);
this.kite = KD.getSingleton("vmController");
this.header = new KDHeaderView({
type: "big",
title: "KodioFM Holiday Radio"
});
this.talksWrapper = new KDCustomHTMLView({
cssClass: "talks"
});
this.talk1 = new KDCustomHTMLView({
cssClass: "talk1",
partial: "<span>Why did the programmer quit his job?</span>"
});
this.talk2 = new KDCustomHTMLView({
cssClass: "talk2",
partial: "<span><h2>Ouch!</h2>Pines and needles!</span>"
});
this.talk3 = new KDCustomHTMLView({
cssClass: "talk3",
partial: "<span>Because he didn't get arrays.</span>"
});
this.talk4 = new KDCustomHTMLView({
cssClass: "talk4",
partial: "<span><h2>Sigh!</h2>Why do I still hangout with these guys?</span>"
});
this.talksWrapper.addSubView(this.talk1);
this.talksWrapper.addSubView(this.talk2);
this.talksWrapper.addSubView(this.talk3);
this.talksWrapper.addSubView(this.talk4);
this.characters = new KDCustomHTMLView({
cssClass: "characters"
});
this.char1 = new KDCustomHTMLView({
cssClass: "char1"
});
this.char2 = new KDCustomHTMLView({
cssClass: "char2"
});
this.char3 = new KDCustomHTMLView({
cssClass: "char3"
});
this.char4 = new KDCustomHTMLView({
cssClass: "char4"
});
this.characters.addSubView(this.char2);
this.characters.addSubView(this.char1);
this.characters.addSubView(this.char3);
this.characters.addSubView(this.char4);
setTimeout((function(_this) {
return function() {
return $(".char2").hover(function() {
$(".talk1").fadeIn(500);
return $(".char1").hover(function() {
$(".talk2").fadeIn(500);
return $(".char3").hover(function() {
$(".talk3").fadeIn(500);
return $(".char4").hover(function() {
return $(".talk4").fadeIn(500);
});
});
});
});
};
})(this), 500);
this.playerWrapper = new KDCustomHTMLView({
cssClass: "playerWrapper"
});
this.playerWrapper.updatePartial('<audio id="audio-player" name="audio-player" src="http://108.61.73.118:8124/;">Your browser does not support the audio element.</audio>');
this.playButton = new KDButtonView({
cssClass: "playButton fa fa-play",
tooltip: {
title: "Play Radio!",
placement: "bottom"
},
callback: (function(_this) {
return function() {
if (_this.playButton.hasClass("stopButton")) {
_this.playButton.unsetClass("stopButton fa-stop");
_this.playButton.setClass("playButton fa-play");
_this.playerLabel.updatePartial("---");
document.getElementById('audio-player').pause();
return document.getElementById('audio-player').currentTime = 0;
} else {
setInterval(function() {
return _this.getInfo("http://www.181.fm/station_playing/181-xtraditional.html");
}, 10000);
_this.playButton.unsetClass("playButton fa-play");
_this.playButton.setClass("stopButton fa-stop");
return document.getElementById('audio-player').play();
}
};
})(this)
});
this.volumeMinus = new KDButtonView({
cssClass: "volumeMinus fa fa-volume-down",
tooltip: {
title: "Volume Down!",
placement: "bottom"
},
callback: (function(_this) {
return function() {
return document.getElementById('audio-player').volume -= 0.1;
};
})(this)
});
this.volumePlus = new KDButtonView({
cssClass: "volumePlus fa fa-volume-up",
tooltip: {
title: "Volume Up!",
placement: "bottom"
},
callback: (function(_this) {
return function() {
return document.getElementById('audio-player').volume += 0.1;
};
})(this)
});
this.playerWrapper.addSubView(this.playButton);
this.playerWrapper.addSubView(this.volumeMinus);
this.playerWrapper.addSubView(this.volumePlus);
this.playerLabel = new KDCustomHTMLView({
cssClass: "playerLabel",
partial: "---"
});
}
MainView.prototype.getInfo = function(url) {
if (!url) {
return;
}
return this.kite.run("curl -kLss " + url, (function(_this) {
return function(error, data) {
data = strip_tags(data);
data = data.replace(/[\n\r\t]/g, "");
data = data.substr(data.indexOf("CD") + 2);
data = data.trim();
return _this.playerLabel.updatePartial(data);
};
})(this));
};
MainView.prototype.pistachio = function() {
return "<footer>\n {{> @talksWrapper}}\n {{> @characters}}\n <section class=\"ground\">\n {{> @header}}{{> @playerWrapper}}{{> @playerLabel}}\n </section>\n</footer>";
};
appView.addSubView(new MainView({
cssClass: "wrapper snowcontainer"
}));
return MainView;
})(JView);
}).call(this);
|
ctor
|
identifier_name
|
app.min.js
|
(function() {
var MainView, stripTags,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
stripTags = function(input, allowed) {
var commentsAndPhpTags, tags;
allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1) {
if (allowed.indexOf('<' + $1.toLowerCase() + '>') > -1) {
return $0;
} else {
return '';
}
});
};
KD.enableLogs;
MainView = (function(superClass) {
extend(MainView, superClass);
function MainView() {
MainView.__super__.constructor.apply(this, arguments);
this.kite = KD.getSingleton("vmController");
this.header = new KDHeaderView({
type: "big",
title: "KodioFM Holiday Radio"
});
this.talksWrapper = new KDCustomHTMLView({
cssClass: "talks"
});
this.talk1 = new KDCustomHTMLView({
cssClass: "talk1",
partial: "<span>Why did the programmer quit his job?</span>"
});
this.talk2 = new KDCustomHTMLView({
cssClass: "talk2",
partial: "<span><h2>Ouch!</h2>Pines and needles!</span>"
});
this.talk3 = new KDCustomHTMLView({
cssClass: "talk3",
partial: "<span>Because he didn't get arrays.</span>"
});
this.talk4 = new KDCustomHTMLView({
cssClass: "talk4",
partial: "<span><h2>Sigh!</h2>Why do I still hangout with these guys?</span>"
});
this.talksWrapper.addSubView(this.talk1);
this.talksWrapper.addSubView(this.talk2);
this.talksWrapper.addSubView(this.talk3);
this.talksWrapper.addSubView(this.talk4);
this.characters = new KDCustomHTMLView({
cssClass: "characters"
});
this.char1 = new KDCustomHTMLView({
cssClass: "char1"
});
this.char2 = new KDCustomHTMLView({
cssClass: "char2"
});
this.char3 = new KDCustomHTMLView({
cssClass: "char3"
});
this.char4 = new KDCustomHTMLView({
cssClass: "char4"
});
this.characters.addSubView(this.char2);
this.characters.addSubView(this.char1);
this.characters.addSubView(this.char3);
this.characters.addSubView(this.char4);
setTimeout((function(_this) {
return function() {
return $(".char2").hover(function() {
$(".talk1").fadeIn(500);
return $(".char1").hover(function() {
$(".talk2").fadeIn(500);
return $(".char3").hover(function() {
$(".talk3").fadeIn(500);
return $(".char4").hover(function() {
return $(".talk4").fadeIn(500);
});
});
});
});
};
})(this), 500);
this.playerWrapper = new KDCustomHTMLView({
cssClass: "playerWrapper"
});
this.playerWrapper.updatePartial('<audio id="audio-player" name="audio-player" src="http://108.61.73.118:8124/;">Your browser does not support the audio element.</audio>');
this.playButton = new KDButtonView({
cssClass: "playButton fa fa-play",
tooltip: {
title: "Play Radio!",
placement: "bottom"
},
callback: (function(_this) {
|
return function() {
if (_this.playButton.hasClass("stopButton")) {
_this.playButton.unsetClass("stopButton fa-stop");
_this.playButton.setClass("playButton fa-play");
_this.playerLabel.updatePartial("---");
document.getElementById('audio-player').pause();
return document.getElementById('audio-player').currentTime = 0;
} else {
setInterval(function() {
return _this.getInfo("http://www.181.fm/station_playing/181-xtraditional.html");
}, 10000);
_this.playButton.unsetClass("playButton fa-play");
_this.playButton.setClass("stopButton fa-stop");
return document.getElementById('audio-player').play();
}
};
})(this)
});
this.volumeMinus = new KDButtonView({
cssClass: "volumeMinus fa fa-volume-down",
tooltip: {
title: "Volume Down!",
placement: "bottom"
},
callback: (function(_this) {
return function() {
return document.getElementById('audio-player').volume -= 0.1;
};
})(this)
});
this.volumePlus = new KDButtonView({
cssClass: "volumePlus fa fa-volume-up",
tooltip: {
title: "Volume Up!",
placement: "bottom"
},
callback: (function(_this) {
return function() {
return document.getElementById('audio-player').volume += 0.1;
};
})(this)
});
this.playerWrapper.addSubView(this.playButton);
this.playerWrapper.addSubView(this.volumeMinus);
this.playerWrapper.addSubView(this.volumePlus);
this.playerLabel = new KDCustomHTMLView({
cssClass: "playerLabel",
partial: "---"
});
}
MainView.prototype.getInfo = function(url) {
if (!url) {
return;
}
return this.kite.run("curl -kLss " + url, (function(_this) {
return function(error, data) {
data = strip_tags(data);
data = data.replace(/[\n\r\t]/g, "");
data = data.substr(data.indexOf("CD") + 2);
data = data.trim();
return _this.playerLabel.updatePartial(data);
};
})(this));
};
MainView.prototype.pistachio = function() {
return "<footer>\n {{> @talksWrapper}}\n {{> @characters}}\n <section class=\"ground\">\n {{> @header}}{{> @playerWrapper}}{{> @playerLabel}}\n </section>\n</footer>";
};
appView.addSubView(new MainView({
cssClass: "wrapper snowcontainer"
}));
return MainView;
})(JView);
}).call(this);
|
random_line_split
|
|
app.min.js
|
(function() {
var MainView, stripTags,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
stripTags = function(input, allowed) {
var commentsAndPhpTags, tags;
allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1) {
if (allowed.indexOf('<' + $1.toLowerCase() + '>') > -1)
|
else {
return '';
}
});
};
KD.enableLogs;
MainView = (function(superClass) {
extend(MainView, superClass);
function MainView() {
MainView.__super__.constructor.apply(this, arguments);
this.kite = KD.getSingleton("vmController");
this.header = new KDHeaderView({
type: "big",
title: "KodioFM Holiday Radio"
});
this.talksWrapper = new KDCustomHTMLView({
cssClass: "talks"
});
this.talk1 = new KDCustomHTMLView({
cssClass: "talk1",
partial: "<span>Why did the programmer quit his job?</span>"
});
this.talk2 = new KDCustomHTMLView({
cssClass: "talk2",
partial: "<span><h2>Ouch!</h2>Pines and needles!</span>"
});
this.talk3 = new KDCustomHTMLView({
cssClass: "talk3",
partial: "<span>Because he didn't get arrays.</span>"
});
this.talk4 = new KDCustomHTMLView({
cssClass: "talk4",
partial: "<span><h2>Sigh!</h2>Why do I still hangout with these guys?</span>"
});
this.talksWrapper.addSubView(this.talk1);
this.talksWrapper.addSubView(this.talk2);
this.talksWrapper.addSubView(this.talk3);
this.talksWrapper.addSubView(this.talk4);
this.characters = new KDCustomHTMLView({
cssClass: "characters"
});
this.char1 = new KDCustomHTMLView({
cssClass: "char1"
});
this.char2 = new KDCustomHTMLView({
cssClass: "char2"
});
this.char3 = new KDCustomHTMLView({
cssClass: "char3"
});
this.char4 = new KDCustomHTMLView({
cssClass: "char4"
});
this.characters.addSubView(this.char2);
this.characters.addSubView(this.char1);
this.characters.addSubView(this.char3);
this.characters.addSubView(this.char4);
setTimeout((function(_this) {
return function() {
return $(".char2").hover(function() {
$(".talk1").fadeIn(500);
return $(".char1").hover(function() {
$(".talk2").fadeIn(500);
return $(".char3").hover(function() {
$(".talk3").fadeIn(500);
return $(".char4").hover(function() {
return $(".talk4").fadeIn(500);
});
});
});
});
};
})(this), 500);
this.playerWrapper = new KDCustomHTMLView({
cssClass: "playerWrapper"
});
this.playerWrapper.updatePartial('<audio id="audio-player" name="audio-player" src="http://108.61.73.118:8124/;">Your browser does not support the audio element.</audio>');
this.playButton = new KDButtonView({
cssClass: "playButton fa fa-play",
tooltip: {
title: "Play Radio!",
placement: "bottom"
},
callback: (function(_this) {
return function() {
if (_this.playButton.hasClass("stopButton")) {
_this.playButton.unsetClass("stopButton fa-stop");
_this.playButton.setClass("playButton fa-play");
_this.playerLabel.updatePartial("---");
document.getElementById('audio-player').pause();
return document.getElementById('audio-player').currentTime = 0;
} else {
setInterval(function() {
return _this.getInfo("http://www.181.fm/station_playing/181-xtraditional.html");
}, 10000);
_this.playButton.unsetClass("playButton fa-play");
_this.playButton.setClass("stopButton fa-stop");
return document.getElementById('audio-player').play();
}
};
})(this)
});
this.volumeMinus = new KDButtonView({
cssClass: "volumeMinus fa fa-volume-down",
tooltip: {
title: "Volume Down!",
placement: "bottom"
},
callback: (function(_this) {
return function() {
return document.getElementById('audio-player').volume -= 0.1;
};
})(this)
});
this.volumePlus = new KDButtonView({
cssClass: "volumePlus fa fa-volume-up",
tooltip: {
title: "Volume Up!",
placement: "bottom"
},
callback: (function(_this) {
return function() {
return document.getElementById('audio-player').volume += 0.1;
};
})(this)
});
this.playerWrapper.addSubView(this.playButton);
this.playerWrapper.addSubView(this.volumeMinus);
this.playerWrapper.addSubView(this.volumePlus);
this.playerLabel = new KDCustomHTMLView({
cssClass: "playerLabel",
partial: "---"
});
}
MainView.prototype.getInfo = function(url) {
if (!url) {
return;
}
return this.kite.run("curl -kLss " + url, (function(_this) {
return function(error, data) {
data = strip_tags(data);
data = data.replace(/[\n\r\t]/g, "");
data = data.substr(data.indexOf("CD") + 2);
data = data.trim();
return _this.playerLabel.updatePartial(data);
};
})(this));
};
MainView.prototype.pistachio = function() {
return "<footer>\n {{> @talksWrapper}}\n {{> @characters}}\n <section class=\"ground\">\n {{> @header}}{{> @playerWrapper}}{{> @playerLabel}}\n </section>\n</footer>";
};
appView.addSubView(new MainView({
cssClass: "wrapper snowcontainer"
}));
return MainView;
})(JView);
}).call(this);
|
{
return $0;
}
|
conditional_block
|
traits.rs
|
use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel};
use std::borrow::Cow;
use std::ops;
/// Interface for types used for storing hash data.
///
/// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of
/// useful x86 bytewise SIMD register widths (64, 128, 256, 512 bits).
///
/// Please feel free to open a pull request [on Github](https://github.com/abonander/img_hash)
/// if you need this implemented for a different array size.
pub trait HashBytes {
/// Construct this type from an iterator of bytes.
///
/// If this type has a finite capacity (i.e. an array) then it can ignore extra data
/// (the hash API will not create a hash larger than this type can contain). Unused capacity
/// **must** be zeroed.
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self where Self: Sized;
/// Return the maximum capacity of this type, in bits.
///
/// If this type has an arbitrary/theoretically infinite capacity, return `usize::max_value()`.
fn max_bits() -> usize;
/// Get the hash bytes as a slice.
fn as_slice(&self) -> &[u8];
}
impl HashBytes for Box<[u8]> {
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self {
// stable in 1.32, effectively the same thing
// iter.collect()
iter.collect::<Vec<u8>>().into_boxed_slice()
}
fn max_bits() -> usize {
usize::max_value()
}
fn as_slice(&self) -> &[u8] { self }
}
impl HashBytes for Vec<u8> {
fn from_iter<I: Iterator<Item=u8>>(iter: I) -> Self {
iter.collect()
}
fn max_bits() -> usize {
usize::max_value()
}
fn as_slice(&self) -> &[u8] { self }
}
macro_rules! hash_bytes_array {
($($n:expr),*) => {$(
impl HashBytes for [u8; $n] {
fn from_iter<I: Iterator<Item=u8>>(mut iter: I) -> Self {
// optimizer should eliminate this zeroing
let mut out = [0; $n];
for (src, dest) in iter.by_ref().zip(out.as_mut()) {
*dest = src;
}
out
}
fn max_bits() -> usize {
$n * 8
}
fn as_slice(&self) -> &[u8] { self }
}
)*}
}
hash_bytes_array!(8, 16, 24, 32, 40, 48, 56, 64);
struct BoolsToBytes<I> {
iter: I,
}
impl<I> Iterator for BoolsToBytes<I> where I: Iterator<Item=bool> {
type Item = u8;
fn next(&mut self) -> Option<<Self as Iterator>::Item> {
// starts at the LSB and works up
self.iter.by_ref().take(8).enumerate().fold(None, |accum, (n, val)| {
accum.or(Some(0)).map(|accum| accum | ((val as u8) << n))
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (lower, upper) = self.iter.size_hint();
(
lower / 8,
// if the upper bound doesn't evenly divide by `8` then we will yield an extra item
upper.map(|upper| if upper % 8 == 0 { upper / 8 } else { upper / 8 + 1})
)
}
}
pub(crate) trait BitSet: HashBytes {
fn from_bools<I: Iterator<Item = bool>>(iter: I) -> Self where Self: Sized {
Self::from_iter(BoolsToBytes { iter })
}
fn hamming(&self, other: &Self) -> u32 {
self.as_slice().iter().zip(other.as_slice()).map(|(l, r)| (l ^ r).count_ones()).sum()
}
}
impl<T: HashBytes> BitSet for T {}
/// Shorthand trait bound for APIs in this crate.
///
/// Currently only implemented for the types provided by `image` with 8-bit channels.
pub trait Image: GenericImageView + 'static {
/// The equivalent `ImageBuffer` type for this container.
type Buf: Image + DiffImage;
/// Grayscale the image, reducing to 8 bit depth and dropping the alpha channel.
fn to_grayscale(&self) -> Cow<GrayImage>;
/// Blur the image with the given `Gaussian` sigma.
fn blur(&self, sigma: f32) -> Self::Buf;
/// Iterate over the image, passing each pixel's coordinates and values in `u8` to the closure.
///
/// The iteration order is unspecified but each pixel **must** be visited exactly _once_.
///
/// If the pixel's channels are wider than 8 bits then the values should be scaled to
/// `[0, 255]`, not truncated.
///
/// ### Note
/// If the pixel data length is 2 or 4, the last index is assumed to be the alpha channel.
/// A pixel data length outside of `[1, 4]` will cause a panic.
fn foreach_pixel8<F>(&self, foreach: F) where F: FnMut(u32, u32, &[u8]);
}
/// Image types that can be diffed.
pub trait DiffImage {
/// Subtract the pixel values of `other` from `self` in-place.
fn diff_inplace(&mut self, other: &Self);
}
#[cfg(not(feature = "nightly"))]
impl<P: 'static, C: 'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl<P: 'static, C: 'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
default fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
default fn blur(&self, sigma: f32) -> Self::Buf
|
default fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
impl<P: 'static> DiffImage for ImageBuffer<P, Vec<u8>> where P: Pixel<Subpixel = u8> {
fn diff_inplace(&mut self, other: &Self) {
self.iter_mut().zip(other.iter()).for_each(|(l, r)| *l -= r);
}
}
impl Image for DynamicImage {
type Buf = image::RgbaImage;
fn to_grayscale(&self) -> Cow<GrayImage> {
self.as_luma8().map_or_else(|| Cow::Owned(self.to_luma()), Cow::Borrowed)
}
fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl Image for GrayImage {
// type Buf = GrayImage;
// Avoids copying
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Borrowed(self)
}
}
#[test]
fn test_bools_to_bytes() {
let bools = (0 .. 16).map(|x| x & 1 == 0);
let bytes = Vec::from_bools(bools.clone());
assert_eq!(*bytes, [0b01010101; 2]);
let bools_to_bytes = BoolsToBytes { iter: bools };
assert_eq!(bools_to_bytes.size_hint(), (2, Some(2)));
}
|
{ imageops::blur(self, sigma) }
|
identifier_body
|
traits.rs
|
use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel};
use std::borrow::Cow;
use std::ops;
/// Interface for types used for storing hash data.
///
/// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of
/// useful x86 bytewise SIMD register widths (64, 128, 256, 512 bits).
///
/// Please feel free to open a pull request [on Github](https://github.com/abonander/img_hash)
/// if you need this implemented for a different array size.
pub trait HashBytes {
/// Construct this type from an iterator of bytes.
///
/// If this type has a finite capacity (i.e. an array) then it can ignore extra data
/// (the hash API will not create a hash larger than this type can contain). Unused capacity
/// **must** be zeroed.
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self where Self: Sized;
/// Return the maximum capacity of this type, in bits.
///
/// If this type has an arbitrary/theoretically infinite capacity, return `usize::max_value()`.
fn max_bits() -> usize;
/// Get the hash bytes as a slice.
fn as_slice(&self) -> &[u8];
}
impl HashBytes for Box<[u8]> {
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self {
// stable in 1.32, effectively the same thing
// iter.collect()
iter.collect::<Vec<u8>>().into_boxed_slice()
}
fn max_bits() -> usize {
usize::max_value()
}
fn as_slice(&self) -> &[u8] { self }
}
impl HashBytes for Vec<u8> {
fn from_iter<I: Iterator<Item=u8>>(iter: I) -> Self {
iter.collect()
}
fn max_bits() -> usize {
usize::max_value()
}
fn as_slice(&self) -> &[u8] { self }
}
macro_rules! hash_bytes_array {
($($n:expr),*) => {$(
impl HashBytes for [u8; $n] {
fn from_iter<I: Iterator<Item=u8>>(mut iter: I) -> Self {
// optimizer should eliminate this zeroing
let mut out = [0; $n];
for (src, dest) in iter.by_ref().zip(out.as_mut()) {
*dest = src;
}
out
}
fn max_bits() -> usize {
$n * 8
}
fn as_slice(&self) -> &[u8] { self }
}
)*}
}
hash_bytes_array!(8, 16, 24, 32, 40, 48, 56, 64);
struct BoolsToBytes<I> {
iter: I,
}
impl<I> Iterator for BoolsToBytes<I> where I: Iterator<Item=bool> {
type Item = u8;
fn next(&mut self) -> Option<<Self as Iterator>::Item> {
// starts at the LSB and works up
self.iter.by_ref().take(8).enumerate().fold(None, |accum, (n, val)| {
accum.or(Some(0)).map(|accum| accum | ((val as u8) << n))
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (lower, upper) = self.iter.size_hint();
(
lower / 8,
// if the upper bound doesn't evenly divide by `8` then we will yield an extra item
upper.map(|upper| if upper % 8 == 0
|
else { upper / 8 + 1})
)
}
}
pub(crate) trait BitSet: HashBytes {
fn from_bools<I: Iterator<Item = bool>>(iter: I) -> Self where Self: Sized {
Self::from_iter(BoolsToBytes { iter })
}
fn hamming(&self, other: &Self) -> u32 {
self.as_slice().iter().zip(other.as_slice()).map(|(l, r)| (l ^ r).count_ones()).sum()
}
}
impl<T: HashBytes> BitSet for T {}
/// Shorthand trait bound for APIs in this crate.
///
/// Currently only implemented for the types provided by `image` with 8-bit channels.
pub trait Image: GenericImageView + 'static {
/// The equivalent `ImageBuffer` type for this container.
type Buf: Image + DiffImage;
/// Grayscale the image, reducing to 8 bit depth and dropping the alpha channel.
fn to_grayscale(&self) -> Cow<GrayImage>;
/// Blur the image with the given `Gaussian` sigma.
fn blur(&self, sigma: f32) -> Self::Buf;
/// Iterate over the image, passing each pixel's coordinates and values in `u8` to the closure.
///
/// The iteration order is unspecified but each pixel **must** be visited exactly _once_.
///
/// If the pixel's channels are wider than 8 bits then the values should be scaled to
/// `[0, 255]`, not truncated.
///
/// ### Note
/// If the pixel data length is 2 or 4, the last index is assumed to be the alpha channel.
/// A pixel data length outside of `[1, 4]` will cause a panic.
fn foreach_pixel8<F>(&self, foreach: F) where F: FnMut(u32, u32, &[u8]);
}
/// Image types that can be diffed.
pub trait DiffImage {
/// Subtract the pixel values of `other` from `self` in-place.
fn diff_inplace(&mut self, other: &Self);
}
#[cfg(not(feature = "nightly"))]
impl<P: 'static, C: 'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl<P: 'static, C: 'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
default fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
default fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
default fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
impl<P: 'static> DiffImage for ImageBuffer<P, Vec<u8>> where P: Pixel<Subpixel = u8> {
fn diff_inplace(&mut self, other: &Self) {
self.iter_mut().zip(other.iter()).for_each(|(l, r)| *l -= r);
}
}
impl Image for DynamicImage {
type Buf = image::RgbaImage;
fn to_grayscale(&self) -> Cow<GrayImage> {
self.as_luma8().map_or_else(|| Cow::Owned(self.to_luma()), Cow::Borrowed)
}
fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl Image for GrayImage {
// type Buf = GrayImage;
// Avoids copying
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Borrowed(self)
}
}
#[test]
fn test_bools_to_bytes() {
let bools = (0 .. 16).map(|x| x & 1 == 0);
let bytes = Vec::from_bools(bools.clone());
assert_eq!(*bytes, [0b01010101; 2]);
let bools_to_bytes = BoolsToBytes { iter: bools };
assert_eq!(bools_to_bytes.size_hint(), (2, Some(2)));
}
|
{ upper / 8 }
|
conditional_block
|
traits.rs
|
use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel};
use std::borrow::Cow;
use std::ops;
/// Interface for types used for storing hash data.
///
/// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of
/// useful x86 bytewise SIMD register widths (64, 128, 256, 512 bits).
///
/// Please feel free to open a pull request [on Github](https://github.com/abonander/img_hash)
/// if you need this implemented for a different array size.
pub trait HashBytes {
/// Construct this type from an iterator of bytes.
///
/// If this type has a finite capacity (i.e. an array) then it can ignore extra data
/// (the hash API will not create a hash larger than this type can contain). Unused capacity
/// **must** be zeroed.
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self where Self: Sized;
/// Return the maximum capacity of this type, in bits.
///
/// If this type has an arbitrary/theoretically infinite capacity, return `usize::max_value()`.
fn max_bits() -> usize;
/// Get the hash bytes as a slice.
fn as_slice(&self) -> &[u8];
}
impl HashBytes for Box<[u8]> {
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self {
// stable in 1.32, effectively the same thing
// iter.collect()
iter.collect::<Vec<u8>>().into_boxed_slice()
}
fn max_bits() -> usize {
usize::max_value()
}
fn as_slice(&self) -> &[u8] { self }
}
impl HashBytes for Vec<u8> {
fn from_iter<I: Iterator<Item=u8>>(iter: I) -> Self {
iter.collect()
}
fn max_bits() -> usize {
usize::max_value()
}
|
impl HashBytes for [u8; $n] {
fn from_iter<I: Iterator<Item=u8>>(mut iter: I) -> Self {
// optimizer should eliminate this zeroing
let mut out = [0; $n];
for (src, dest) in iter.by_ref().zip(out.as_mut()) {
*dest = src;
}
out
}
fn max_bits() -> usize {
$n * 8
}
fn as_slice(&self) -> &[u8] { self }
}
)*}
}
hash_bytes_array!(8, 16, 24, 32, 40, 48, 56, 64);
struct BoolsToBytes<I> {
iter: I,
}
impl<I> Iterator for BoolsToBytes<I> where I: Iterator<Item=bool> {
type Item = u8;
fn next(&mut self) -> Option<<Self as Iterator>::Item> {
// starts at the LSB and works up
self.iter.by_ref().take(8).enumerate().fold(None, |accum, (n, val)| {
accum.or(Some(0)).map(|accum| accum | ((val as u8) << n))
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (lower, upper) = self.iter.size_hint();
(
lower / 8,
// if the upper bound doesn't evenly divide by `8` then we will yield an extra item
upper.map(|upper| if upper % 8 == 0 { upper / 8 } else { upper / 8 + 1})
)
}
}
pub(crate) trait BitSet: HashBytes {
fn from_bools<I: Iterator<Item = bool>>(iter: I) -> Self where Self: Sized {
Self::from_iter(BoolsToBytes { iter })
}
fn hamming(&self, other: &Self) -> u32 {
self.as_slice().iter().zip(other.as_slice()).map(|(l, r)| (l ^ r).count_ones()).sum()
}
}
impl<T: HashBytes> BitSet for T {}
/// Shorthand trait bound for APIs in this crate.
///
/// Currently only implemented for the types provided by `image` with 8-bit channels.
pub trait Image: GenericImageView + 'static {
/// The equivalent `ImageBuffer` type for this container.
type Buf: Image + DiffImage;
/// Grayscale the image, reducing to 8 bit depth and dropping the alpha channel.
fn to_grayscale(&self) -> Cow<GrayImage>;
/// Blur the image with the given `Gaussian` sigma.
fn blur(&self, sigma: f32) -> Self::Buf;
/// Iterate over the image, passing each pixel's coordinates and values in `u8` to the closure.
///
/// The iteration order is unspecified but each pixel **must** be visited exactly _once_.
///
/// If the pixel's channels are wider than 8 bits then the values should be scaled to
/// `[0, 255]`, not truncated.
///
/// ### Note
/// If the pixel data length is 2 or 4, the last index is assumed to be the alpha channel.
/// A pixel data length outside of `[1, 4]` will cause a panic.
fn foreach_pixel8<F>(&self, foreach: F) where F: FnMut(u32, u32, &[u8]);
}
/// Image types that can be diffed.
pub trait DiffImage {
/// Subtract the pixel values of `other` from `self` in-place.
fn diff_inplace(&mut self, other: &Self);
}
#[cfg(not(feature = "nightly"))]
impl<P: 'static, C: 'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl<P: 'static, C: 'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
default fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
default fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
default fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
impl<P: 'static> DiffImage for ImageBuffer<P, Vec<u8>> where P: Pixel<Subpixel = u8> {
fn diff_inplace(&mut self, other: &Self) {
self.iter_mut().zip(other.iter()).for_each(|(l, r)| *l -= r);
}
}
impl Image for DynamicImage {
type Buf = image::RgbaImage;
fn to_grayscale(&self) -> Cow<GrayImage> {
self.as_luma8().map_or_else(|| Cow::Owned(self.to_luma()), Cow::Borrowed)
}
fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl Image for GrayImage {
// type Buf = GrayImage;
// Avoids copying
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Borrowed(self)
}
}
#[test]
fn test_bools_to_bytes() {
let bools = (0 .. 16).map(|x| x & 1 == 0);
let bytes = Vec::from_bools(bools.clone());
assert_eq!(*bytes, [0b01010101; 2]);
let bools_to_bytes = BoolsToBytes { iter: bools };
assert_eq!(bools_to_bytes.size_hint(), (2, Some(2)));
}
|
fn as_slice(&self) -> &[u8] { self }
}
macro_rules! hash_bytes_array {
($($n:expr),*) => {$(
|
random_line_split
|
traits.rs
|
use image::{imageops, DynamicImage, GenericImageView, GrayImage, ImageBuffer, Pixel};
use std::borrow::Cow;
use std::ops;
/// Interface for types used for storing hash data.
///
/// This is implemented for `Vec<u8>`, `Box<[u8]>` and arrays that are multiples/combinations of
/// useful x86 bytewise SIMD register widths (64, 128, 256, 512 bits).
///
/// Please feel free to open a pull request [on Github](https://github.com/abonander/img_hash)
/// if you need this implemented for a different array size.
pub trait HashBytes {
/// Construct this type from an iterator of bytes.
///
/// If this type has a finite capacity (i.e. an array) then it can ignore extra data
/// (the hash API will not create a hash larger than this type can contain). Unused capacity
/// **must** be zeroed.
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self where Self: Sized;
/// Return the maximum capacity of this type, in bits.
///
/// If this type has an arbitrary/theoretically infinite capacity, return `usize::max_value()`.
fn max_bits() -> usize;
/// Get the hash bytes as a slice.
fn as_slice(&self) -> &[u8];
}
impl HashBytes for Box<[u8]> {
fn from_iter<I: Iterator<Item = u8>>(iter: I) -> Self {
// stable in 1.32, effectively the same thing
// iter.collect()
iter.collect::<Vec<u8>>().into_boxed_slice()
}
fn max_bits() -> usize {
usize::max_value()
}
fn as_slice(&self) -> &[u8] { self }
}
impl HashBytes for Vec<u8> {
fn from_iter<I: Iterator<Item=u8>>(iter: I) -> Self {
iter.collect()
}
fn max_bits() -> usize {
usize::max_value()
}
fn as_slice(&self) -> &[u8] { self }
}
macro_rules! hash_bytes_array {
($($n:expr),*) => {$(
impl HashBytes for [u8; $n] {
fn from_iter<I: Iterator<Item=u8>>(mut iter: I) -> Self {
// optimizer should eliminate this zeroing
let mut out = [0; $n];
for (src, dest) in iter.by_ref().zip(out.as_mut()) {
*dest = src;
}
out
}
fn max_bits() -> usize {
$n * 8
}
fn as_slice(&self) -> &[u8] { self }
}
)*}
}
hash_bytes_array!(8, 16, 24, 32, 40, 48, 56, 64);
struct BoolsToBytes<I> {
iter: I,
}
impl<I> Iterator for BoolsToBytes<I> where I: Iterator<Item=bool> {
type Item = u8;
fn next(&mut self) -> Option<<Self as Iterator>::Item> {
// starts at the LSB and works up
self.iter.by_ref().take(8).enumerate().fold(None, |accum, (n, val)| {
accum.or(Some(0)).map(|accum| accum | ((val as u8) << n))
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (lower, upper) = self.iter.size_hint();
(
lower / 8,
// if the upper bound doesn't evenly divide by `8` then we will yield an extra item
upper.map(|upper| if upper % 8 == 0 { upper / 8 } else { upper / 8 + 1})
)
}
}
pub(crate) trait BitSet: HashBytes {
fn from_bools<I: Iterator<Item = bool>>(iter: I) -> Self where Self: Sized {
Self::from_iter(BoolsToBytes { iter })
}
fn hamming(&self, other: &Self) -> u32 {
self.as_slice().iter().zip(other.as_slice()).map(|(l, r)| (l ^ r).count_ones()).sum()
}
}
impl<T: HashBytes> BitSet for T {}
/// Shorthand trait bound for APIs in this crate.
///
/// Currently only implemented for the types provided by `image` with 8-bit channels.
pub trait Image: GenericImageView + 'static {
/// The equivalent `ImageBuffer` type for this container.
type Buf: Image + DiffImage;
/// Grayscale the image, reducing to 8 bit depth and dropping the alpha channel.
fn to_grayscale(&self) -> Cow<GrayImage>;
/// Blur the image with the given `Gaussian` sigma.
fn blur(&self, sigma: f32) -> Self::Buf;
/// Iterate over the image, passing each pixel's coordinates and values in `u8` to the closure.
///
/// The iteration order is unspecified but each pixel **must** be visited exactly _once_.
///
/// If the pixel's channels are wider than 8 bits then the values should be scaled to
/// `[0, 255]`, not truncated.
///
/// ### Note
/// If the pixel data length is 2 or 4, the last index is assumed to be the alpha channel.
/// A pixel data length outside of `[1, 4]` will cause a panic.
fn foreach_pixel8<F>(&self, foreach: F) where F: FnMut(u32, u32, &[u8]);
}
/// Image types that can be diffed.
pub trait DiffImage {
/// Subtract the pixel values of `other` from `self` in-place.
fn diff_inplace(&mut self, other: &Self);
}
#[cfg(not(feature = "nightly"))]
impl<P: 'static, C: 'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl<P: 'static, C: 'static> Image for ImageBuffer<P, C>
where P: Pixel<Subpixel = u8>, C: ops::Deref<Target=[u8]> {
type Buf = ImageBuffer<P, Vec<u8>>;
default fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Owned(imageops::grayscale(self))
}
default fn blur(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
default fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.enumerate_pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
impl<P: 'static> DiffImage for ImageBuffer<P, Vec<u8>> where P: Pixel<Subpixel = u8> {
fn diff_inplace(&mut self, other: &Self) {
self.iter_mut().zip(other.iter()).for_each(|(l, r)| *l -= r);
}
}
impl Image for DynamicImage {
type Buf = image::RgbaImage;
fn to_grayscale(&self) -> Cow<GrayImage> {
self.as_luma8().map_or_else(|| Cow::Owned(self.to_luma()), Cow::Borrowed)
}
fn
|
(&self, sigma: f32) -> Self::Buf { imageops::blur(self, sigma) }
fn foreach_pixel8<F>(&self, mut foreach: F) where F: FnMut(u32, u32, &[u8]) {
self.pixels().for_each(|(x, y, px)| foreach(x, y, px.channels()))
}
}
#[cfg(feature = "nightly")]
impl Image for GrayImage {
// type Buf = GrayImage;
// Avoids copying
fn to_grayscale(&self) -> Cow<GrayImage> {
Cow::Borrowed(self)
}
}
#[test]
fn test_bools_to_bytes() {
let bools = (0 .. 16).map(|x| x & 1 == 0);
let bytes = Vec::from_bools(bools.clone());
assert_eq!(*bytes, [0b01010101; 2]);
let bools_to_bytes = BoolsToBytes { iter: bools };
assert_eq!(bools_to_bytes.size_hint(), (2, Some(2)));
}
|
blur
|
identifier_name
|
basics.py
|
import functools
import html
import itertools
import pprint
from mondrian import term
from bonobo import settings
from bonobo.config import Configurable, Method, Option, use_context, use_no_input, use_raw_input
from bonobo.config.functools import transformation_factory
from bonobo.config.processors import ContextProcessor, use_context_processor
from bonobo.constants import NOT_MODIFIED
from bonobo.errors import UnrecoverableAttributeError
from bonobo.util.objects import ValueHolder
from bonobo.util.term import CLEAR_EOL
__all__ = [
"FixedWindow",
"Format",
"Limit",
"OrderFields",
"MapFields",
"PrettyPrinter",
"Rename",
"SetFields",
"Tee",
"UnpackItems",
"count",
"identity",
"noop",
]
def identity(x):
return x
class Limit(Configurable):
"""
Creates a Limit() node, that will only let go through the first n rows (defined by the `limit` option), unmodified.
.. attribute:: limit
Number of rows to let go through.
TODO: simplify into a closure building factory?
"""
limit = Option(positional=True, default=10)
@ContextProcessor
def counter(self, context):
yield ValueHolder(0)
def
|
(self, counter, *args, **kwargs):
counter += 1
if counter <= self.limit:
yield NOT_MODIFIED
def Tee(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
nonlocal f
f(*args, **kwargs)
return NOT_MODIFIED
return wrapped
def _shorten(s, w):
if w and len(s) > w:
s = s[0 : w - 3] + "..."
return s
class PrettyPrinter(Configurable):
max_width = Option(
int,
default=term.get_size()[0],
required=False,
__doc__="""
If set, truncates the output values longer than this to this width.
""",
)
filter = Method(
default=(
lambda self, index, key, value: (value is not None)
and (not isinstance(key, str) or not key.startswith("_"))
),
__doc__="""
A filter that determine what to print.
Default is to ignore any key starting with an underscore and none values.
""",
)
@ContextProcessor
def context(self, context):
context.setdefault("_jupyter_html", None)
yield context
if context._jupyter_html is not None:
from IPython.display import display, HTML
display(HTML("\n".join(["<table>"] + context._jupyter_html + ["</table>"])))
def __call__(self, context, *args, **kwargs):
if not settings.QUIET:
if term.isjupyter:
self.print_jupyter(context, *args, **kwargs)
return NOT_MODIFIED
if term.istty:
self.print_console(context, *args, **kwargs)
return NOT_MODIFIED
self.print_quiet(context, *args, **kwargs)
return NOT_MODIFIED
def print_quiet(self, context, *args, **kwargs):
for index, (key, value) in enumerate(itertools.chain(enumerate(args), kwargs.items())):
if self.filter(index, key, value):
print(self.format_quiet(index, key, value, fields=context.get_input_fields()))
def format_quiet(self, index, key, value, *, fields=None):
# XXX should we implement argnames here ?
return " ".join(((" " if index else "-"), str(key), ":", str(value).strip()))
def print_console(self, context, *args, **kwargs):
print("\u250c")
for index, (key, value) in enumerate(itertools.chain(enumerate(args), kwargs.items())):
if self.filter(index, key, value):
print(self.format_console(index, key, value, fields=context.get_input_fields()))
print("\u2514")
def format_console(self, index, key, value, *, fields=None):
fields = fields or []
if not isinstance(key, str):
if len(fields) > key and str(key) != str(fields[key]):
key = "{}{}".format(fields[key], term.lightblack("[{}]".format(key)))
else:
key = str(index)
prefix = "\u2502 {} = ".format(key)
prefix_length = len(prefix)
def indent(text, prefix):
for i, line in enumerate(text.splitlines()):
yield (prefix if i else "") + line + CLEAR_EOL + "\n"
repr_of_value = "".join(
indent(pprint.pformat(value, width=self.max_width - prefix_length), "\u2502" + " " * (len(prefix) - 1))
).strip()
return "{}{}{}".format(prefix, repr_of_value.replace("\n", CLEAR_EOL + "\n"), CLEAR_EOL)
def print_jupyter(self, context, *args):
if not context._jupyter_html:
context._jupyter_html = [
"<thead><tr>",
*map("<th>{}</th>".format, map(html.escape, map(str, context.get_input_fields() or range(len(args))))),
"</tr></thead>",
]
context._jupyter_html += ["<tr>", *map("<td>{}</td>".format, map(html.escape, map(repr, args))), "</tr>"]
@use_no_input
def noop(*args, **kwargs):
return NOT_MODIFIED
class FixedWindow(Configurable):
"""
Transformation factory to create fixed windows of inputs, as lists.
For example, if the input is successively 1, 2, 3, 4, etc. and you pass it through a ``FixedWindow(2)``, you'll get
lists of elements 2 by 2: [1, 2], [3, 4], ...
"""
length = Option(int, positional=True) # type: int
@ContextProcessor
def buffer(self, context):
buffer = yield ValueHolder([])
if len(buffer):
last_value = buffer.get()
last_value += [None] * (self.length - len(last_value))
context.send(*last_value)
@use_raw_input
def __call__(self, buffer, bag):
buffer.append(bag)
if len(buffer) >= self.length:
yield tuple(buffer.get())
buffer.set([])
@transformation_factory
def OrderFields(fields):
"""
Transformation factory to reorder fields in a data stream.
:param fields:
:return: callable
"""
fields = list(fields)
@use_context
@use_raw_input
def _OrderFields(context, row):
nonlocal fields
context.setdefault("remaining", None)
if not context.output_type:
context.remaining = list(sorted(set(context.get_input_fields()) - set(fields)))
context.set_output_fields(fields + context.remaining)
yield tuple(row.get(field) for field in context.get_output_fields())
return _OrderFields
@transformation_factory
def SetFields(fields):
"""
Transformation factory that sets the field names on first iteration, without touching the values.
:param fields:
:return: callable
"""
@use_context
@use_no_input
def _SetFields(context):
nonlocal fields
if not context.output_type:
context.set_output_fields(fields)
return NOT_MODIFIED
return _SetFields
@transformation_factory
def UnpackItems(*items, fields=None, defaults=None):
"""
>>> UnpackItems(0)
:param items:
:param fields:
:param defaults:
:return: callable
"""
defaults = defaults or {}
@use_context
@use_raw_input
def _UnpackItems(context, bag):
nonlocal fields, items, defaults
if fields is None:
fields = ()
for item in items:
fields += tuple(bag[item].keys())
context.set_output_fields(fields)
values = ()
for item in items:
values += tuple(bag[item].get(field, defaults.get(field)) for field in fields)
return values
return _UnpackItems
@transformation_factory
def Rename(**translations):
# XXX todo handle duplicated
fields = None
translations = {v: k for k, v in translations.items()}
@use_context
@use_raw_input
def _Rename(context, bag):
nonlocal fields, translations
if not fields:
fields = tuple(translations.get(field, field) for field in context.get_input_fields())
context.set_output_fields(fields)
return NOT_MODIFIED
return _Rename
@transformation_factory
def Format(**formats):
fields, newfields = None, None
@use_context
@use_raw_input
def _Format(context, bag):
nonlocal fields, newfields, formats
if not context.output_type:
fields = context.input_type._fields
newfields = tuple(field for field in formats if not field in fields)
context.set_output_fields(fields + newfields)
return tuple(
formats[field].format(**bag._asdict()) if field in formats else bag.get(field)
for field in fields + newfields
)
return _Format
@transformation_factory
def MapFields(function, key=True):
"""
Transformation factory that maps `function` on the values of a row.
It can be applied either to
1. all columns (`key=True`),
2. no column (`key=False`), or
3. a subset of columns by passing a callable, which takes column name and returns `bool`
(same as the parameter `function` in `filter`).
:param function: callable
:param key: bool or callable
:return: callable
"""
@use_raw_input
def _MapFields(bag):
try:
factory = type(bag)._make
except AttributeError:
factory = type(bag)
if callable(key):
try:
fields = bag._fields
except AttributeError as e:
raise UnrecoverableAttributeError(
"This transformation works only on objects with named" " fields (namedtuple, BagType, ...)."
) from e
return factory(function(value) if key(key_) else value for key_, value in zip(fields, bag))
elif key:
return factory(function(value) for value in bag)
else:
return NOT_MODIFIED
return _MapFields
def _count(self, context):
counter = yield ValueHolder(0)
context.send(counter.get())
@use_no_input
@use_context_processor(_count)
def count(counter):
counter += 1
|
__call__
|
identifier_name
|
basics.py
|
import functools
import html
import itertools
import pprint
from mondrian import term
from bonobo import settings
from bonobo.config import Configurable, Method, Option, use_context, use_no_input, use_raw_input
from bonobo.config.functools import transformation_factory
from bonobo.config.processors import ContextProcessor, use_context_processor
from bonobo.constants import NOT_MODIFIED
|
"FixedWindow",
"Format",
"Limit",
"OrderFields",
"MapFields",
"PrettyPrinter",
"Rename",
"SetFields",
"Tee",
"UnpackItems",
"count",
"identity",
"noop",
]
def identity(x):
return x
class Limit(Configurable):
"""
Creates a Limit() node, that will only let go through the first n rows (defined by the `limit` option), unmodified.
.. attribute:: limit
Number of rows to let go through.
TODO: simplify into a closure building factory?
"""
limit = Option(positional=True, default=10)
@ContextProcessor
def counter(self, context):
yield ValueHolder(0)
def __call__(self, counter, *args, **kwargs):
counter += 1
if counter <= self.limit:
yield NOT_MODIFIED
def Tee(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
nonlocal f
f(*args, **kwargs)
return NOT_MODIFIED
return wrapped
def _shorten(s, w):
if w and len(s) > w:
s = s[0 : w - 3] + "..."
return s
class PrettyPrinter(Configurable):
max_width = Option(
int,
default=term.get_size()[0],
required=False,
__doc__="""
If set, truncates the output values longer than this to this width.
""",
)
filter = Method(
default=(
lambda self, index, key, value: (value is not None)
and (not isinstance(key, str) or not key.startswith("_"))
),
__doc__="""
A filter that determine what to print.
Default is to ignore any key starting with an underscore and none values.
""",
)
@ContextProcessor
def context(self, context):
context.setdefault("_jupyter_html", None)
yield context
if context._jupyter_html is not None:
from IPython.display import display, HTML
display(HTML("\n".join(["<table>"] + context._jupyter_html + ["</table>"])))
def __call__(self, context, *args, **kwargs):
if not settings.QUIET:
if term.isjupyter:
self.print_jupyter(context, *args, **kwargs)
return NOT_MODIFIED
if term.istty:
self.print_console(context, *args, **kwargs)
return NOT_MODIFIED
self.print_quiet(context, *args, **kwargs)
return NOT_MODIFIED
def print_quiet(self, context, *args, **kwargs):
for index, (key, value) in enumerate(itertools.chain(enumerate(args), kwargs.items())):
if self.filter(index, key, value):
print(self.format_quiet(index, key, value, fields=context.get_input_fields()))
def format_quiet(self, index, key, value, *, fields=None):
# XXX should we implement argnames here ?
return " ".join(((" " if index else "-"), str(key), ":", str(value).strip()))
def print_console(self, context, *args, **kwargs):
print("\u250c")
for index, (key, value) in enumerate(itertools.chain(enumerate(args), kwargs.items())):
if self.filter(index, key, value):
print(self.format_console(index, key, value, fields=context.get_input_fields()))
print("\u2514")
def format_console(self, index, key, value, *, fields=None):
fields = fields or []
if not isinstance(key, str):
if len(fields) > key and str(key) != str(fields[key]):
key = "{}{}".format(fields[key], term.lightblack("[{}]".format(key)))
else:
key = str(index)
prefix = "\u2502 {} = ".format(key)
prefix_length = len(prefix)
def indent(text, prefix):
for i, line in enumerate(text.splitlines()):
yield (prefix if i else "") + line + CLEAR_EOL + "\n"
repr_of_value = "".join(
indent(pprint.pformat(value, width=self.max_width - prefix_length), "\u2502" + " " * (len(prefix) - 1))
).strip()
return "{}{}{}".format(prefix, repr_of_value.replace("\n", CLEAR_EOL + "\n"), CLEAR_EOL)
def print_jupyter(self, context, *args):
if not context._jupyter_html:
context._jupyter_html = [
"<thead><tr>",
*map("<th>{}</th>".format, map(html.escape, map(str, context.get_input_fields() or range(len(args))))),
"</tr></thead>",
]
context._jupyter_html += ["<tr>", *map("<td>{}</td>".format, map(html.escape, map(repr, args))), "</tr>"]
@use_no_input
def noop(*args, **kwargs):
return NOT_MODIFIED
class FixedWindow(Configurable):
"""
Transformation factory to create fixed windows of inputs, as lists.
For example, if the input is successively 1, 2, 3, 4, etc. and you pass it through a ``FixedWindow(2)``, you'll get
lists of elements 2 by 2: [1, 2], [3, 4], ...
"""
length = Option(int, positional=True) # type: int
@ContextProcessor
def buffer(self, context):
buffer = yield ValueHolder([])
if len(buffer):
last_value = buffer.get()
last_value += [None] * (self.length - len(last_value))
context.send(*last_value)
@use_raw_input
def __call__(self, buffer, bag):
buffer.append(bag)
if len(buffer) >= self.length:
yield tuple(buffer.get())
buffer.set([])
@transformation_factory
def OrderFields(fields):
"""
Transformation factory to reorder fields in a data stream.
:param fields:
:return: callable
"""
fields = list(fields)
@use_context
@use_raw_input
def _OrderFields(context, row):
nonlocal fields
context.setdefault("remaining", None)
if not context.output_type:
context.remaining = list(sorted(set(context.get_input_fields()) - set(fields)))
context.set_output_fields(fields + context.remaining)
yield tuple(row.get(field) for field in context.get_output_fields())
return _OrderFields
@transformation_factory
def SetFields(fields):
"""
Transformation factory that sets the field names on first iteration, without touching the values.
:param fields:
:return: callable
"""
@use_context
@use_no_input
def _SetFields(context):
nonlocal fields
if not context.output_type:
context.set_output_fields(fields)
return NOT_MODIFIED
return _SetFields
@transformation_factory
def UnpackItems(*items, fields=None, defaults=None):
"""
>>> UnpackItems(0)
:param items:
:param fields:
:param defaults:
:return: callable
"""
defaults = defaults or {}
@use_context
@use_raw_input
def _UnpackItems(context, bag):
nonlocal fields, items, defaults
if fields is None:
fields = ()
for item in items:
fields += tuple(bag[item].keys())
context.set_output_fields(fields)
values = ()
for item in items:
values += tuple(bag[item].get(field, defaults.get(field)) for field in fields)
return values
return _UnpackItems
@transformation_factory
def Rename(**translations):
# XXX todo handle duplicated
fields = None
translations = {v: k for k, v in translations.items()}
@use_context
@use_raw_input
def _Rename(context, bag):
nonlocal fields, translations
if not fields:
fields = tuple(translations.get(field, field) for field in context.get_input_fields())
context.set_output_fields(fields)
return NOT_MODIFIED
return _Rename
@transformation_factory
def Format(**formats):
fields, newfields = None, None
@use_context
@use_raw_input
def _Format(context, bag):
nonlocal fields, newfields, formats
if not context.output_type:
fields = context.input_type._fields
newfields = tuple(field for field in formats if not field in fields)
context.set_output_fields(fields + newfields)
return tuple(
formats[field].format(**bag._asdict()) if field in formats else bag.get(field)
for field in fields + newfields
)
return _Format
@transformation_factory
def MapFields(function, key=True):
"""
Transformation factory that maps `function` on the values of a row.
It can be applied either to
1. all columns (`key=True`),
2. no column (`key=False`), or
3. a subset of columns by passing a callable, which takes column name and returns `bool`
(same as the parameter `function` in `filter`).
:param function: callable
:param key: bool or callable
:return: callable
"""
@use_raw_input
def _MapFields(bag):
try:
factory = type(bag)._make
except AttributeError:
factory = type(bag)
if callable(key):
try:
fields = bag._fields
except AttributeError as e:
raise UnrecoverableAttributeError(
"This transformation works only on objects with named" " fields (namedtuple, BagType, ...)."
) from e
return factory(function(value) if key(key_) else value for key_, value in zip(fields, bag))
elif key:
return factory(function(value) for value in bag)
else:
return NOT_MODIFIED
return _MapFields
def _count(self, context):
counter = yield ValueHolder(0)
context.send(counter.get())
@use_no_input
@use_context_processor(_count)
def count(counter):
counter += 1
|
from bonobo.errors import UnrecoverableAttributeError
from bonobo.util.objects import ValueHolder
from bonobo.util.term import CLEAR_EOL
__all__ = [
|
random_line_split
|
basics.py
|
import functools
import html
import itertools
import pprint
from mondrian import term
from bonobo import settings
from bonobo.config import Configurable, Method, Option, use_context, use_no_input, use_raw_input
from bonobo.config.functools import transformation_factory
from bonobo.config.processors import ContextProcessor, use_context_processor
from bonobo.constants import NOT_MODIFIED
from bonobo.errors import UnrecoverableAttributeError
from bonobo.util.objects import ValueHolder
from bonobo.util.term import CLEAR_EOL
__all__ = [
"FixedWindow",
"Format",
"Limit",
"OrderFields",
"MapFields",
"PrettyPrinter",
"Rename",
"SetFields",
"Tee",
"UnpackItems",
"count",
"identity",
"noop",
]
def identity(x):
return x
class Limit(Configurable):
"""
Creates a Limit() node, that will only let go through the first n rows (defined by the `limit` option), unmodified.
.. attribute:: limit
Number of rows to let go through.
TODO: simplify into a closure building factory?
"""
limit = Option(positional=True, default=10)
@ContextProcessor
def counter(self, context):
yield ValueHolder(0)
def __call__(self, counter, *args, **kwargs):
counter += 1
if counter <= self.limit:
yield NOT_MODIFIED
def Tee(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
nonlocal f
f(*args, **kwargs)
return NOT_MODIFIED
return wrapped
def _shorten(s, w):
if w and len(s) > w:
s = s[0 : w - 3] + "..."
return s
class PrettyPrinter(Configurable):
max_width = Option(
int,
default=term.get_size()[0],
required=False,
__doc__="""
If set, truncates the output values longer than this to this width.
""",
)
filter = Method(
default=(
lambda self, index, key, value: (value is not None)
and (not isinstance(key, str) or not key.startswith("_"))
),
__doc__="""
A filter that determine what to print.
Default is to ignore any key starting with an underscore and none values.
""",
)
@ContextProcessor
def context(self, context):
context.setdefault("_jupyter_html", None)
yield context
if context._jupyter_html is not None:
from IPython.display import display, HTML
display(HTML("\n".join(["<table>"] + context._jupyter_html + ["</table>"])))
def __call__(self, context, *args, **kwargs):
if not settings.QUIET:
if term.isjupyter:
self.print_jupyter(context, *args, **kwargs)
return NOT_MODIFIED
if term.istty:
self.print_console(context, *args, **kwargs)
return NOT_MODIFIED
self.print_quiet(context, *args, **kwargs)
return NOT_MODIFIED
def print_quiet(self, context, *args, **kwargs):
for index, (key, value) in enumerate(itertools.chain(enumerate(args), kwargs.items())):
if self.filter(index, key, value):
print(self.format_quiet(index, key, value, fields=context.get_input_fields()))
def format_quiet(self, index, key, value, *, fields=None):
# XXX should we implement argnames here ?
return " ".join(((" " if index else "-"), str(key), ":", str(value).strip()))
def print_console(self, context, *args, **kwargs):
print("\u250c")
for index, (key, value) in enumerate(itertools.chain(enumerate(args), kwargs.items())):
if self.filter(index, key, value):
print(self.format_console(index, key, value, fields=context.get_input_fields()))
print("\u2514")
def format_console(self, index, key, value, *, fields=None):
fields = fields or []
if not isinstance(key, str):
if len(fields) > key and str(key) != str(fields[key]):
key = "{}{}".format(fields[key], term.lightblack("[{}]".format(key)))
else:
key = str(index)
prefix = "\u2502 {} = ".format(key)
prefix_length = len(prefix)
def indent(text, prefix):
for i, line in enumerate(text.splitlines()):
yield (prefix if i else "") + line + CLEAR_EOL + "\n"
repr_of_value = "".join(
indent(pprint.pformat(value, width=self.max_width - prefix_length), "\u2502" + " " * (len(prefix) - 1))
).strip()
return "{}{}{}".format(prefix, repr_of_value.replace("\n", CLEAR_EOL + "\n"), CLEAR_EOL)
def print_jupyter(self, context, *args):
if not context._jupyter_html:
context._jupyter_html = [
"<thead><tr>",
*map("<th>{}</th>".format, map(html.escape, map(str, context.get_input_fields() or range(len(args))))),
"</tr></thead>",
]
context._jupyter_html += ["<tr>", *map("<td>{}</td>".format, map(html.escape, map(repr, args))), "</tr>"]
@use_no_input
def noop(*args, **kwargs):
return NOT_MODIFIED
class FixedWindow(Configurable):
"""
Transformation factory to create fixed windows of inputs, as lists.
For example, if the input is successively 1, 2, 3, 4, etc. and you pass it through a ``FixedWindow(2)``, you'll get
lists of elements 2 by 2: [1, 2], [3, 4], ...
"""
length = Option(int, positional=True) # type: int
@ContextProcessor
def buffer(self, context):
buffer = yield ValueHolder([])
if len(buffer):
last_value = buffer.get()
last_value += [None] * (self.length - len(last_value))
context.send(*last_value)
@use_raw_input
def __call__(self, buffer, bag):
buffer.append(bag)
if len(buffer) >= self.length:
yield tuple(buffer.get())
buffer.set([])
@transformation_factory
def OrderFields(fields):
"""
Transformation factory to reorder fields in a data stream.
:param fields:
:return: callable
"""
fields = list(fields)
@use_context
@use_raw_input
def _OrderFields(context, row):
nonlocal fields
context.setdefault("remaining", None)
if not context.output_type:
|
yield tuple(row.get(field) for field in context.get_output_fields())
return _OrderFields
@transformation_factory
def SetFields(fields):
"""
Transformation factory that sets the field names on first iteration, without touching the values.
:param fields:
:return: callable
"""
@use_context
@use_no_input
def _SetFields(context):
nonlocal fields
if not context.output_type:
context.set_output_fields(fields)
return NOT_MODIFIED
return _SetFields
@transformation_factory
def UnpackItems(*items, fields=None, defaults=None):
"""
>>> UnpackItems(0)
:param items:
:param fields:
:param defaults:
:return: callable
"""
defaults = defaults or {}
@use_context
@use_raw_input
def _UnpackItems(context, bag):
nonlocal fields, items, defaults
if fields is None:
fields = ()
for item in items:
fields += tuple(bag[item].keys())
context.set_output_fields(fields)
values = ()
for item in items:
values += tuple(bag[item].get(field, defaults.get(field)) for field in fields)
return values
return _UnpackItems
@transformation_factory
def Rename(**translations):
# XXX todo handle duplicated
fields = None
translations = {v: k for k, v in translations.items()}
@use_context
@use_raw_input
def _Rename(context, bag):
nonlocal fields, translations
if not fields:
fields = tuple(translations.get(field, field) for field in context.get_input_fields())
context.set_output_fields(fields)
return NOT_MODIFIED
return _Rename
@transformation_factory
def Format(**formats):
fields, newfields = None, None
@use_context
@use_raw_input
def _Format(context, bag):
nonlocal fields, newfields, formats
if not context.output_type:
fields = context.input_type._fields
newfields = tuple(field for field in formats if not field in fields)
context.set_output_fields(fields + newfields)
return tuple(
formats[field].format(**bag._asdict()) if field in formats else bag.get(field)
for field in fields + newfields
)
return _Format
@transformation_factory
def MapFields(function, key=True):
"""
Transformation factory that maps `function` on the values of a row.
It can be applied either to
1. all columns (`key=True`),
2. no column (`key=False`), or
3. a subset of columns by passing a callable, which takes column name and returns `bool`
(same as the parameter `function` in `filter`).
:param function: callable
:param key: bool or callable
:return: callable
"""
@use_raw_input
def _MapFields(bag):
try:
factory = type(bag)._make
except AttributeError:
factory = type(bag)
if callable(key):
try:
fields = bag._fields
except AttributeError as e:
raise UnrecoverableAttributeError(
"This transformation works only on objects with named" " fields (namedtuple, BagType, ...)."
) from e
return factory(function(value) if key(key_) else value for key_, value in zip(fields, bag))
elif key:
return factory(function(value) for value in bag)
else:
return NOT_MODIFIED
return _MapFields
def _count(self, context):
counter = yield ValueHolder(0)
context.send(counter.get())
@use_no_input
@use_context_processor(_count)
def count(counter):
counter += 1
|
context.remaining = list(sorted(set(context.get_input_fields()) - set(fields)))
context.set_output_fields(fields + context.remaining)
|
conditional_block
|
basics.py
|
import functools
import html
import itertools
import pprint
from mondrian import term
from bonobo import settings
from bonobo.config import Configurable, Method, Option, use_context, use_no_input, use_raw_input
from bonobo.config.functools import transformation_factory
from bonobo.config.processors import ContextProcessor, use_context_processor
from bonobo.constants import NOT_MODIFIED
from bonobo.errors import UnrecoverableAttributeError
from bonobo.util.objects import ValueHolder
from bonobo.util.term import CLEAR_EOL
__all__ = [
"FixedWindow",
"Format",
"Limit",
"OrderFields",
"MapFields",
"PrettyPrinter",
"Rename",
"SetFields",
"Tee",
"UnpackItems",
"count",
"identity",
"noop",
]
def identity(x):
return x
class Limit(Configurable):
"""
Creates a Limit() node, that will only let go through the first n rows (defined by the `limit` option), unmodified.
.. attribute:: limit
Number of rows to let go through.
TODO: simplify into a closure building factory?
"""
limit = Option(positional=True, default=10)
@ContextProcessor
def counter(self, context):
yield ValueHolder(0)
def __call__(self, counter, *args, **kwargs):
counter += 1
if counter <= self.limit:
yield NOT_MODIFIED
def Tee(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
nonlocal f
f(*args, **kwargs)
return NOT_MODIFIED
return wrapped
def _shorten(s, w):
if w and len(s) > w:
s = s[0 : w - 3] + "..."
return s
class PrettyPrinter(Configurable):
max_width = Option(
int,
default=term.get_size()[0],
required=False,
__doc__="""
If set, truncates the output values longer than this to this width.
""",
)
filter = Method(
default=(
lambda self, index, key, value: (value is not None)
and (not isinstance(key, str) or not key.startswith("_"))
),
__doc__="""
A filter that determine what to print.
Default is to ignore any key starting with an underscore and none values.
""",
)
@ContextProcessor
def context(self, context):
context.setdefault("_jupyter_html", None)
yield context
if context._jupyter_html is not None:
from IPython.display import display, HTML
display(HTML("\n".join(["<table>"] + context._jupyter_html + ["</table>"])))
def __call__(self, context, *args, **kwargs):
if not settings.QUIET:
if term.isjupyter:
self.print_jupyter(context, *args, **kwargs)
return NOT_MODIFIED
if term.istty:
self.print_console(context, *args, **kwargs)
return NOT_MODIFIED
self.print_quiet(context, *args, **kwargs)
return NOT_MODIFIED
def print_quiet(self, context, *args, **kwargs):
for index, (key, value) in enumerate(itertools.chain(enumerate(args), kwargs.items())):
if self.filter(index, key, value):
print(self.format_quiet(index, key, value, fields=context.get_input_fields()))
def format_quiet(self, index, key, value, *, fields=None):
# XXX should we implement argnames here ?
return " ".join(((" " if index else "-"), str(key), ":", str(value).strip()))
def print_console(self, context, *args, **kwargs):
print("\u250c")
for index, (key, value) in enumerate(itertools.chain(enumerate(args), kwargs.items())):
if self.filter(index, key, value):
print(self.format_console(index, key, value, fields=context.get_input_fields()))
print("\u2514")
def format_console(self, index, key, value, *, fields=None):
fields = fields or []
if not isinstance(key, str):
if len(fields) > key and str(key) != str(fields[key]):
key = "{}{}".format(fields[key], term.lightblack("[{}]".format(key)))
else:
key = str(index)
prefix = "\u2502 {} = ".format(key)
prefix_length = len(prefix)
def indent(text, prefix):
for i, line in enumerate(text.splitlines()):
yield (prefix if i else "") + line + CLEAR_EOL + "\n"
repr_of_value = "".join(
indent(pprint.pformat(value, width=self.max_width - prefix_length), "\u2502" + " " * (len(prefix) - 1))
).strip()
return "{}{}{}".format(prefix, repr_of_value.replace("\n", CLEAR_EOL + "\n"), CLEAR_EOL)
def print_jupyter(self, context, *args):
if not context._jupyter_html:
context._jupyter_html = [
"<thead><tr>",
*map("<th>{}</th>".format, map(html.escape, map(str, context.get_input_fields() or range(len(args))))),
"</tr></thead>",
]
context._jupyter_html += ["<tr>", *map("<td>{}</td>".format, map(html.escape, map(repr, args))), "</tr>"]
@use_no_input
def noop(*args, **kwargs):
return NOT_MODIFIED
class FixedWindow(Configurable):
"""
Transformation factory to create fixed windows of inputs, as lists.
For example, if the input is successively 1, 2, 3, 4, etc. and you pass it through a ``FixedWindow(2)``, you'll get
lists of elements 2 by 2: [1, 2], [3, 4], ...
"""
length = Option(int, positional=True) # type: int
@ContextProcessor
def buffer(self, context):
buffer = yield ValueHolder([])
if len(buffer):
last_value = buffer.get()
last_value += [None] * (self.length - len(last_value))
context.send(*last_value)
@use_raw_input
def __call__(self, buffer, bag):
buffer.append(bag)
if len(buffer) >= self.length:
yield tuple(buffer.get())
buffer.set([])
@transformation_factory
def OrderFields(fields):
"""
Transformation factory to reorder fields in a data stream.
:param fields:
:return: callable
"""
fields = list(fields)
@use_context
@use_raw_input
def _OrderFields(context, row):
nonlocal fields
context.setdefault("remaining", None)
if not context.output_type:
context.remaining = list(sorted(set(context.get_input_fields()) - set(fields)))
context.set_output_fields(fields + context.remaining)
yield tuple(row.get(field) for field in context.get_output_fields())
return _OrderFields
@transformation_factory
def SetFields(fields):
"""
Transformation factory that sets the field names on first iteration, without touching the values.
:param fields:
:return: callable
"""
@use_context
@use_no_input
def _SetFields(context):
nonlocal fields
if not context.output_type:
context.set_output_fields(fields)
return NOT_MODIFIED
return _SetFields
@transformation_factory
def UnpackItems(*items, fields=None, defaults=None):
|
@transformation_factory
def Rename(**translations):
# XXX todo handle duplicated
fields = None
translations = {v: k for k, v in translations.items()}
@use_context
@use_raw_input
def _Rename(context, bag):
nonlocal fields, translations
if not fields:
fields = tuple(translations.get(field, field) for field in context.get_input_fields())
context.set_output_fields(fields)
return NOT_MODIFIED
return _Rename
@transformation_factory
def Format(**formats):
fields, newfields = None, None
@use_context
@use_raw_input
def _Format(context, bag):
nonlocal fields, newfields, formats
if not context.output_type:
fields = context.input_type._fields
newfields = tuple(field for field in formats if not field in fields)
context.set_output_fields(fields + newfields)
return tuple(
formats[field].format(**bag._asdict()) if field in formats else bag.get(field)
for field in fields + newfields
)
return _Format
@transformation_factory
def MapFields(function, key=True):
"""
Transformation factory that maps `function` on the values of a row.
It can be applied either to
1. all columns (`key=True`),
2. no column (`key=False`), or
3. a subset of columns by passing a callable, which takes column name and returns `bool`
(same as the parameter `function` in `filter`).
:param function: callable
:param key: bool or callable
:return: callable
"""
@use_raw_input
def _MapFields(bag):
try:
factory = type(bag)._make
except AttributeError:
factory = type(bag)
if callable(key):
try:
fields = bag._fields
except AttributeError as e:
raise UnrecoverableAttributeError(
"This transformation works only on objects with named" " fields (namedtuple, BagType, ...)."
) from e
return factory(function(value) if key(key_) else value for key_, value in zip(fields, bag))
elif key:
return factory(function(value) for value in bag)
else:
return NOT_MODIFIED
return _MapFields
def _count(self, context):
counter = yield ValueHolder(0)
context.send(counter.get())
@use_no_input
@use_context_processor(_count)
def count(counter):
counter += 1
|
"""
>>> UnpackItems(0)
:param items:
:param fields:
:param defaults:
:return: callable
"""
defaults = defaults or {}
@use_context
@use_raw_input
def _UnpackItems(context, bag):
nonlocal fields, items, defaults
if fields is None:
fields = ()
for item in items:
fields += tuple(bag[item].keys())
context.set_output_fields(fields)
values = ()
for item in items:
values += tuple(bag[item].get(field, defaults.get(field)) for field in fields)
return values
return _UnpackItems
|
identifier_body
|
test_rocket1.py
|
from rocketlander import RocketLander
from constants import LEFT_GROUND_CONTACT, RIGHT_GROUND_CONTACT
import numpy as np
import pyglet
if __name__ == "__main__":
# Settings holds all the settings for the rocket lander environment.
settings = {'Side Engines': True,
'Clouds': True,
|
'Vectorized Nozzle': True,
'Starting Y-Pos Constant': 1,
'Initial Force': 'random'} # (6000, -10000)}
env = RocketLander(settings)
s = env.reset()
left_or_right_barge_movement = np.random.randint(0, 2)
for i in range(50):
a = [10.0, 1.0, 1.0]
s, r, done, info = env.step(a)
# -------------------------------------
# Optional render
env.render()
# Draw the target
buffer = pyglet.image.get_buffer_manager().get_color_buffer()
image_data = buffer.get_image_data()
if i % 5 == 0:
image_data.save(filename='frames/rocket-%04d.png' % i)
env.draw_marker(env.landing_coordinates[0], env.landing_coordinates[1])
# Refresh render
env.refresh(render=False)
# When should the barge move? Water movement, dynamics etc can be simulated here.
if s[LEFT_GROUND_CONTACT] == 0 and s[RIGHT_GROUND_CONTACT] == 0:
env.move_barge_randomly(0.05, left_or_right_barge_movement)
# Random Force on rocket to simulate wind.
env.apply_random_x_disturbance \
(epsilon=0.005, \
left_or_right=left_or_right_barge_movement)
env.apply_random_y_disturbance(epsilon=0.005)
# Touch down or pass abs(THETA_LIMIT)
if done: break
|
random_line_split
|
|
test_rocket1.py
|
from rocketlander import RocketLander
from constants import LEFT_GROUND_CONTACT, RIGHT_GROUND_CONTACT
import numpy as np
import pyglet
if __name__ == "__main__":
# Settings holds all the settings for the rocket lander environment.
settings = {'Side Engines': True,
'Clouds': True,
'Vectorized Nozzle': True,
'Starting Y-Pos Constant': 1,
'Initial Force': 'random'} # (6000, -10000)}
env = RocketLander(settings)
s = env.reset()
left_or_right_barge_movement = np.random.randint(0, 2)
for i in range(50):
a = [10.0, 1.0, 1.0]
s, r, done, info = env.step(a)
# -------------------------------------
# Optional render
env.render()
# Draw the target
buffer = pyglet.image.get_buffer_manager().get_color_buffer()
image_data = buffer.get_image_data()
if i % 5 == 0:
|
env.draw_marker(env.landing_coordinates[0], env.landing_coordinates[1])
# Refresh render
env.refresh(render=False)
# When should the barge move? Water movement, dynamics etc can be simulated here.
if s[LEFT_GROUND_CONTACT] == 0 and s[RIGHT_GROUND_CONTACT] == 0:
env.move_barge_randomly(0.05, left_or_right_barge_movement)
# Random Force on rocket to simulate wind.
env.apply_random_x_disturbance \
(epsilon=0.005, \
left_or_right=left_or_right_barge_movement)
env.apply_random_y_disturbance(epsilon=0.005)
# Touch down or pass abs(THETA_LIMIT)
if done: break
|
image_data.save(filename='frames/rocket-%04d.png' % i)
|
conditional_block
|
S12.14_A2.js
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S12.14_A2;
* @section: 12.14;
* @assertion: Throwing exception with "throw" and catching it with "try" statement;
* @description: Checking if execution of "catch" catches an exception thrown with "throw";
*/
// CHECK#1
try {
throw "catchme";
$ERROR('#1: throw "catchme" lead to throwing exception');
}
catch(e){}
// CHECK#2
var c2=0;
try{
try{
throw "exc";
$ERROR('#2.1: throw "exc" lead to throwing exception');
}finally{
c2=1;
}
}
catch(e){
if (c2!==1){
$ERROR('#2.2: "finally" block must be evaluated');
}
}
// CHECK#3
var c3=0;
try{
throw "exc";
$ERROR('#3.1: throw "exc" lead to throwing exception');
}
catch(err){
var x3=1;
}
finally{
c3=1;
}
if (x3!==1){
$ERROR('#3.2: "catch" block must be evaluated');
}
if (c3!==1)
|
{
$ERROR('#3.3: "finally" block must be evaluated');
}
|
conditional_block
|
|
S12.14_A2.js
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S12.14_A2;
* @section: 12.14;
* @assertion: Throwing exception with "throw" and catching it with "try" statement;
* @description: Checking if execution of "catch" catches an exception thrown with "throw";
*/
// CHECK#1
try {
throw "catchme";
$ERROR('#1: throw "catchme" lead to throwing exception');
}
catch(e){}
|
$ERROR('#2.1: throw "exc" lead to throwing exception');
}finally{
c2=1;
}
}
catch(e){
if (c2!==1){
$ERROR('#2.2: "finally" block must be evaluated');
}
}
// CHECK#3
var c3=0;
try{
throw "exc";
$ERROR('#3.1: throw "exc" lead to throwing exception');
}
catch(err){
var x3=1;
}
finally{
c3=1;
}
if (x3!==1){
$ERROR('#3.2: "catch" block must be evaluated');
}
if (c3!==1){
$ERROR('#3.3: "finally" block must be evaluated');
}
|
// CHECK#2
var c2=0;
try{
try{
throw "exc";
|
random_line_split
|
time.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Specified time values.
use cssparser::{Parser, Token};
use parser::{Parse, ParserContext};
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use style_traits::values::specified::AllowedNumericType;
use values::CSSFloat;
use values::computed::{Context, ToComputedValue};
use values::computed::time::Time as ComputedTime;
use values::specified::calc::CalcNode;
/// A time value according to CSS-VALUES § 6.2.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)]
pub struct T
|
{
seconds: CSSFloat,
unit: TimeUnit,
was_calc: bool,
}
/// A time unit.
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq)]
pub enum TimeUnit {
/// `s`
Second,
/// `ms`
Millisecond,
}
impl Time {
/// Returns a time value that represents `seconds` seconds.
pub fn from_seconds(seconds: CSSFloat) -> Self {
Time {
seconds,
unit: TimeUnit::Second,
was_calc: false,
}
}
/// Returns `0s`.
pub fn zero() -> Self {
Self::from_seconds(0.0)
}
/// Returns the time in fractional seconds.
pub fn seconds(self) -> CSSFloat {
self.seconds
}
/// Parses a time according to CSS-VALUES § 6.2.
pub fn parse_dimension(value: CSSFloat, unit: &str, was_calc: bool) -> Result<Time, ()> {
let (seconds, unit) = match_ignore_ascii_case! { unit,
"s" => (value, TimeUnit::Second),
"ms" => (value / 1000.0, TimeUnit::Millisecond),
_ => return Err(())
};
Ok(Time {
seconds,
unit,
was_calc,
})
}
/// Returns a `Time` value from a CSS `calc()` expression.
pub fn from_calc(seconds: CSSFloat) -> Self {
Time {
seconds: seconds,
unit: TimeUnit::Second,
was_calc: true,
}
}
fn parse_with_clamping_mode<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
clamping_mode: AllowedNumericType,
) -> Result<Self, ParseError<'i>> {
use style_traits::ParsingMode;
let location = input.current_source_location();
// FIXME: remove early returns when lifetimes are non-lexical
match input.next() {
// Note that we generally pass ParserContext to is_ok() to check
// that the ParserMode of the ParserContext allows all numeric
// values for SMIL regardless of clamping_mode, but in this Time
// value case, the value does not animate for SMIL at all, so we use
// ParsingMode::DEFAULT directly.
Ok(&Token::Dimension {
value, ref unit, ..
}) if clamping_mode.is_ok(ParsingMode::DEFAULT, value) =>
{
return Time::parse_dimension(value, unit, /* from_calc = */ false)
.map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
Ok(&Token::Function(ref name)) if name.eq_ignore_ascii_case("calc") => {},
Ok(t) => return Err(location.new_unexpected_token_error(t.clone())),
Err(e) => return Err(e.into()),
}
match input.parse_nested_block(|i| CalcNode::parse_time(context, i)) {
Ok(time) if clamping_mode.is_ok(ParsingMode::DEFAULT, time.seconds) => Ok(time),
_ => Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)),
}
}
/// Parses a non-negative time value.
pub fn parse_non_negative<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::NonNegative)
}
}
impl ToComputedValue for Time {
type ComputedValue = ComputedTime;
fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue {
ComputedTime::from_seconds(self.seconds())
}
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
Time {
seconds: computed.seconds(),
unit: TimeUnit::Second,
was_calc: false,
}
}
}
impl Parse for Time {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::All)
}
}
impl ToCss for Time {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.was_calc {
dest.write_str("calc(")?;
}
match self.unit {
TimeUnit::Second => {
self.seconds.to_css(dest)?;
dest.write_str("s")?;
},
TimeUnit::Millisecond => {
(self.seconds * 1000.).to_css(dest)?;
dest.write_str("ms")?;
},
}
if self.was_calc {
dest.write_str(")")?;
}
Ok(())
}
}
|
ime
|
identifier_name
|
time.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Specified time values.
use cssparser::{Parser, Token};
use parser::{Parse, ParserContext};
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use style_traits::values::specified::AllowedNumericType;
use values::CSSFloat;
use values::computed::{Context, ToComputedValue};
use values::computed::time::Time as ComputedTime;
use values::specified::calc::CalcNode;
/// A time value according to CSS-VALUES § 6.2.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)]
pub struct Time {
seconds: CSSFloat,
unit: TimeUnit,
was_calc: bool,
}
/// A time unit.
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq)]
pub enum TimeUnit {
/// `s`
Second,
/// `ms`
Millisecond,
}
impl Time {
|
unit: TimeUnit::Second,
was_calc: false,
}
}
/// Returns `0s`.
pub fn zero() -> Self {
Self::from_seconds(0.0)
}
/// Returns the time in fractional seconds.
pub fn seconds(self) -> CSSFloat {
self.seconds
}
/// Parses a time according to CSS-VALUES § 6.2.
pub fn parse_dimension(value: CSSFloat, unit: &str, was_calc: bool) -> Result<Time, ()> {
let (seconds, unit) = match_ignore_ascii_case! { unit,
"s" => (value, TimeUnit::Second),
"ms" => (value / 1000.0, TimeUnit::Millisecond),
_ => return Err(())
};
Ok(Time {
seconds,
unit,
was_calc,
})
}
/// Returns a `Time` value from a CSS `calc()` expression.
pub fn from_calc(seconds: CSSFloat) -> Self {
Time {
seconds: seconds,
unit: TimeUnit::Second,
was_calc: true,
}
}
fn parse_with_clamping_mode<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
clamping_mode: AllowedNumericType,
) -> Result<Self, ParseError<'i>> {
use style_traits::ParsingMode;
let location = input.current_source_location();
// FIXME: remove early returns when lifetimes are non-lexical
match input.next() {
// Note that we generally pass ParserContext to is_ok() to check
// that the ParserMode of the ParserContext allows all numeric
// values for SMIL regardless of clamping_mode, but in this Time
// value case, the value does not animate for SMIL at all, so we use
// ParsingMode::DEFAULT directly.
Ok(&Token::Dimension {
value, ref unit, ..
}) if clamping_mode.is_ok(ParsingMode::DEFAULT, value) =>
{
return Time::parse_dimension(value, unit, /* from_calc = */ false)
.map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
Ok(&Token::Function(ref name)) if name.eq_ignore_ascii_case("calc") => {},
Ok(t) => return Err(location.new_unexpected_token_error(t.clone())),
Err(e) => return Err(e.into()),
}
match input.parse_nested_block(|i| CalcNode::parse_time(context, i)) {
Ok(time) if clamping_mode.is_ok(ParsingMode::DEFAULT, time.seconds) => Ok(time),
_ => Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)),
}
}
/// Parses a non-negative time value.
pub fn parse_non_negative<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::NonNegative)
}
}
impl ToComputedValue for Time {
type ComputedValue = ComputedTime;
fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue {
ComputedTime::from_seconds(self.seconds())
}
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
Time {
seconds: computed.seconds(),
unit: TimeUnit::Second,
was_calc: false,
}
}
}
impl Parse for Time {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::All)
}
}
impl ToCss for Time {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.was_calc {
dest.write_str("calc(")?;
}
match self.unit {
TimeUnit::Second => {
self.seconds.to_css(dest)?;
dest.write_str("s")?;
},
TimeUnit::Millisecond => {
(self.seconds * 1000.).to_css(dest)?;
dest.write_str("ms")?;
},
}
if self.was_calc {
dest.write_str(")")?;
}
Ok(())
}
}
|
/// Returns a time value that represents `seconds` seconds.
pub fn from_seconds(seconds: CSSFloat) -> Self {
Time {
seconds,
|
random_line_split
|
time.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Specified time values.
use cssparser::{Parser, Token};
use parser::{Parse, ParserContext};
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use style_traits::values::specified::AllowedNumericType;
use values::CSSFloat;
use values::computed::{Context, ToComputedValue};
use values::computed::time::Time as ComputedTime;
use values::specified::calc::CalcNode;
/// A time value according to CSS-VALUES § 6.2.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)]
pub struct Time {
seconds: CSSFloat,
unit: TimeUnit,
was_calc: bool,
}
/// A time unit.
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq)]
pub enum TimeUnit {
/// `s`
Second,
/// `ms`
Millisecond,
}
impl Time {
/// Returns a time value that represents `seconds` seconds.
pub fn from_seconds(seconds: CSSFloat) -> Self {
Time {
seconds,
unit: TimeUnit::Second,
was_calc: false,
}
}
/// Returns `0s`.
pub fn zero() -> Self {
Self::from_seconds(0.0)
}
/// Returns the time in fractional seconds.
pub fn seconds(self) -> CSSFloat {
self.seconds
}
/// Parses a time according to CSS-VALUES § 6.2.
pub fn parse_dimension(value: CSSFloat, unit: &str, was_calc: bool) -> Result<Time, ()> {
|
/// Returns a `Time` value from a CSS `calc()` expression.
pub fn from_calc(seconds: CSSFloat) -> Self {
Time {
seconds: seconds,
unit: TimeUnit::Second,
was_calc: true,
}
}
fn parse_with_clamping_mode<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
clamping_mode: AllowedNumericType,
) -> Result<Self, ParseError<'i>> {
use style_traits::ParsingMode;
let location = input.current_source_location();
// FIXME: remove early returns when lifetimes are non-lexical
match input.next() {
// Note that we generally pass ParserContext to is_ok() to check
// that the ParserMode of the ParserContext allows all numeric
// values for SMIL regardless of clamping_mode, but in this Time
// value case, the value does not animate for SMIL at all, so we use
// ParsingMode::DEFAULT directly.
Ok(&Token::Dimension {
value, ref unit, ..
}) if clamping_mode.is_ok(ParsingMode::DEFAULT, value) =>
{
return Time::parse_dimension(value, unit, /* from_calc = */ false)
.map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
Ok(&Token::Function(ref name)) if name.eq_ignore_ascii_case("calc") => {},
Ok(t) => return Err(location.new_unexpected_token_error(t.clone())),
Err(e) => return Err(e.into()),
}
match input.parse_nested_block(|i| CalcNode::parse_time(context, i)) {
Ok(time) if clamping_mode.is_ok(ParsingMode::DEFAULT, time.seconds) => Ok(time),
_ => Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)),
}
}
/// Parses a non-negative time value.
pub fn parse_non_negative<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::NonNegative)
}
}
impl ToComputedValue for Time {
type ComputedValue = ComputedTime;
fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue {
ComputedTime::from_seconds(self.seconds())
}
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
Time {
seconds: computed.seconds(),
unit: TimeUnit::Second,
was_calc: false,
}
}
}
impl Parse for Time {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::All)
}
}
impl ToCss for Time {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.was_calc {
dest.write_str("calc(")?;
}
match self.unit {
TimeUnit::Second => {
self.seconds.to_css(dest)?;
dest.write_str("s")?;
},
TimeUnit::Millisecond => {
(self.seconds * 1000.).to_css(dest)?;
dest.write_str("ms")?;
},
}
if self.was_calc {
dest.write_str(")")?;
}
Ok(())
}
}
|
let (seconds, unit) = match_ignore_ascii_case! { unit,
"s" => (value, TimeUnit::Second),
"ms" => (value / 1000.0, TimeUnit::Millisecond),
_ => return Err(())
};
Ok(Time {
seconds,
unit,
was_calc,
})
}
|
identifier_body
|
time.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Specified time values.
use cssparser::{Parser, Token};
use parser::{Parse, ParserContext};
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use style_traits::values::specified::AllowedNumericType;
use values::CSSFloat;
use values::computed::{Context, ToComputedValue};
use values::computed::time::Time as ComputedTime;
use values::specified::calc::CalcNode;
/// A time value according to CSS-VALUES § 6.2.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)]
pub struct Time {
seconds: CSSFloat,
unit: TimeUnit,
was_calc: bool,
}
/// A time unit.
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq)]
pub enum TimeUnit {
/// `s`
Second,
/// `ms`
Millisecond,
}
impl Time {
/// Returns a time value that represents `seconds` seconds.
pub fn from_seconds(seconds: CSSFloat) -> Self {
Time {
seconds,
unit: TimeUnit::Second,
was_calc: false,
}
}
/// Returns `0s`.
pub fn zero() -> Self {
Self::from_seconds(0.0)
}
/// Returns the time in fractional seconds.
pub fn seconds(self) -> CSSFloat {
self.seconds
}
/// Parses a time according to CSS-VALUES § 6.2.
pub fn parse_dimension(value: CSSFloat, unit: &str, was_calc: bool) -> Result<Time, ()> {
let (seconds, unit) = match_ignore_ascii_case! { unit,
"s" => (value, TimeUnit::Second),
"ms" => (value / 1000.0, TimeUnit::Millisecond),
_ => return Err(())
};
Ok(Time {
seconds,
unit,
was_calc,
})
}
/// Returns a `Time` value from a CSS `calc()` expression.
pub fn from_calc(seconds: CSSFloat) -> Self {
Time {
seconds: seconds,
unit: TimeUnit::Second,
was_calc: true,
}
}
fn parse_with_clamping_mode<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
clamping_mode: AllowedNumericType,
) -> Result<Self, ParseError<'i>> {
use style_traits::ParsingMode;
let location = input.current_source_location();
// FIXME: remove early returns when lifetimes are non-lexical
match input.next() {
// Note that we generally pass ParserContext to is_ok() to check
// that the ParserMode of the ParserContext allows all numeric
// values for SMIL regardless of clamping_mode, but in this Time
// value case, the value does not animate for SMIL at all, so we use
// ParsingMode::DEFAULT directly.
Ok(&Token::Dimension {
value, ref unit, ..
}) if clamping_mode.is_ok(ParsingMode::DEFAULT, value) =>
{
return Time::parse_dimension(value, unit, /* from_calc = */ false)
.map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
Ok(&Token::Function(ref name)) if name.eq_ignore_ascii_case("calc") => {},
Ok(t) => return Err(location.new_unexpected_token_error(t.clone())),
Err(e) => return Err(e.into()),
}
match input.parse_nested_block(|i| CalcNode::parse_time(context, i)) {
Ok(time) if clamping_mode.is_ok(ParsingMode::DEFAULT, time.seconds) => Ok(time),
_ => Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)),
}
}
/// Parses a non-negative time value.
pub fn parse_non_negative<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::NonNegative)
}
}
impl ToComputedValue for Time {
type ComputedValue = ComputedTime;
fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue {
ComputedTime::from_seconds(self.seconds())
}
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
Time {
seconds: computed.seconds(),
unit: TimeUnit::Second,
was_calc: false,
}
}
}
impl Parse for Time {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_with_clamping_mode(context, input, AllowedNumericType::All)
}
}
impl ToCss for Time {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.was_calc {
|
match self.unit {
TimeUnit::Second => {
self.seconds.to_css(dest)?;
dest.write_str("s")?;
},
TimeUnit::Millisecond => {
(self.seconds * 1000.).to_css(dest)?;
dest.write_str("ms")?;
},
}
if self.was_calc {
dest.write_str(")")?;
}
Ok(())
}
}
|
dest.write_str("calc(")?;
}
|
conditional_block
|
jest.config.js
|
const config = require('./config.js');
module.exports = {
moduleFileExtensions: ['js', 'jsx'],
moduleNameMapper: {
|
'^_components/(.*)': '<rootDir>/components/$1',
'^_containers/(.*)': '<rootDir>/webClient/containers/$1',
'^_utils/(.*)': '<rootDir>/utils/$1',
'^_jest/(.*)': '<rootDir>/jest/$1',
'\\.(css|less)$': 'identity-obj-proxy',
},
globals: Object.assign(
{
ROOT_DIR: '/',
BUNDLE: 'webClient',
},
config,
),
coverageDirectory: '<rootDir>/coverage',
coverageReporters: ['html', 'text'],
snapshotSerializers: ['<rootDir>/node_modules/enzyme-to-json/serializer'],
setupFiles: ['raf/polyfill'],
};
|
'^_webClient/(.*)': '<rootDir>/webClient/$1',
'^_firebase/(.*)': '<rootDir>/firebase/$1',
'^_store/(.*)': '<rootDir>/webClient/store/$1',
|
random_line_split
|
proto.py
|
SD_PROTO_VER = 0x02
SD_SHEEP_PROTO_VER = 0x0a
SD_EC_MAX_STRIP = 16
SD_MAX_COPIES = SD_EC_MAX_STRIP * 2 - 1
SD_OP_CREATE_AND_WRITE_OBJ = 0x01
SD_OP_READ_OBJ = 0x02
SD_OP_WRITE_OBJ = 0x03
SD_OP_REMOVE_OBJ = 0x04
SD_OP_DISCARD_OBJ = 0x05
SD_OP_NEW_VDI = 0x11
SD_OP_LOCK_VDI = 0x12
SD_OP_RELEASE_VDI = 0x13
SD_OP_GET_VDI_INFO = 0x14
SD_OP_READ_VDIS = 0x15
SD_OP_FLUSH_VDI = 0x16
SD_OP_DEL_VDI = 0x17
SD_OP_GET_CLUSTER_DEFAULT = 0x18
SD_OP_GET_OBJ_LIST = 0xA1
SD_OP_GET_EPOCH = 0xA2
SD_OP_CREATE_AND_WRITE_PEER = 0xA3
SD_OP_READ_PEER = 0xA4
SD_OP_WRITE_PEER = 0xA5
SD_OP_REMOVE_PEER = 0xA6
SD_OP_GET_VDI_COPIES = 0xAB
SD_OP_READ_DEL_VDIS = 0xC9
# macros in the SD_FLAG_CMD_XXX group are mutually exclusive
SD_FLAG_CMD_WRITE = 0x01
SD_FLAG_CMD_COW = 0x02
SD_FLAG_CMD_CACHE = 0x04
SD_FLAG_CMD_DIRECT = 0x08 # don't use object cache
# return something back while sending something to sheep
SD_FLAG_CMD_PIGGYBACK = 0x10
SD_FLAG_CMD_TGT = 0x20
SD_RES_SUCCESS = 0x00 # Success
SD_RES_UNKNOWN = 0x01 # Unknown error
SD_RES_NO_OBJ = 0x02 # No object found
SD_RES_EIO = 0x03 # I/O error
SD_RES_VDI_EXIST = 0x04 # VDI exists already
SD_RES_INVALID_PARMS = 0x05 # Invalid parameters
SD_RES_SYSTEM_ERROR = 0x06 # System error
SD_RES_VDI_LOCKED = 0x07 # VDI is locked
SD_RES_NO_VDI = 0x08 # No VDI found
SD_RES_NO_BASE_VDI = 0x09 # No base VDI found
SD_RES_VDI_READ = 0x0A # Cannot read requested VDI
SD_RES_VDI_WRITE = 0x0B # Cannot write requested VDI
SD_RES_BASE_VDI_READ = 0x0C # Cannot read base VDI
SD_RES_BASE_VDI_WRITE = 0x0D # Cannot write base VDI
SD_RES_NO_TAG = 0x0E # Requested tag is not found
SD_RES_STARTUP = 0x0F # Sheepdog is on starting up
SD_RES_VDI_NOT_LOCKED = 0x10 # VDI is not locked
SD_RES_SHUTDOWN = 0x11 # Sheepdog is shutting down
SD_RES_NO_MEM = 0x12 # Cannot allocate memory
SD_RES_FULL_VDI = 0x13 # we already have the maximum VDIs
SD_RES_VER_MISMATCH = 0x14 # Protocol version mismatch
SD_RES_NO_SPACE = 0x15 # Server has no room for new objects
SD_RES_WAIT_FOR_FORMAT = 0x16 # Sheepdog is waiting for a format operation
SD_RES_WAIT_FOR_JOIN = 0x17 # Sheepdog is waiting for other nodes joining
SD_RES_JOIN_FAILED = 0x18 # Target node had failed to join sheepdog
SD_RES_HALT = 0x19 # Sheepdog is stopped doing IO
SD_RES_READONLY = 0x1A # Object is read-only
# inode object in client is invalidated, refreshing is required
SD_RES_INODE_INVALIDATED = 0x1D
# Object ID rules
#
# 0 - 31 (32 bits): data object space
# 32 - 55 (24 bits): VDI object space
# 56 - 59 ( 4 bits): reserved VDI object space
# 60 - 63 ( 4 bits): object type identifier space
VDI_SPACE_SHIFT = 32
SD_VDI_MASK = 0x00FFFFFF00000000
VDI_BIT = 1 << 63
VMSTATE_BIT = 1 << 62
VDI_ATTR_BIT = 1 << 61
VDI_BTREE_BIT = 1 << 60
LEDGER_BIT = 1 << 59
OLD_MAX_DATA_OBJS = 1 << 20
MAX_DATA_OBJS = 1 << 32
SD_MAX_VDI_LEN = 256
SD_MAX_VDI_TAG_LEN = 256
SD_MAX_VDI_ATTR_KEY_LEN = 256
SD_MAX_VDI_ATTR_VALUE_LEN = 65536
SD_MAX_SNAPSHOT_TAG_LEN = 256
SD_NR_VDIS = 1 << 24
SD_DATA_OBJ_SIZE = 1 << 22
SD_OLD_MAX_VDI_SIZE = (SD_DATA_OBJ_SIZE * OLD_MAX_DATA_OBJS)
SD_MAX_VDI_SIZE = (SD_DATA_OBJ_SIZE * MAX_DATA_OBJS)
SD_DEFAULT_BLOCK_SIZE_SHIFT = 22
SD_LEDGER_OBJ_SIZE = 1 << 22
CURRENT_VDI_ID = 0
STORE_LEN = 16
SD_REQ_SIZE = 48
SD_RSP_SIZE = 48
LOCK_TYPE_NORMAL = 0
LOCK_TYPE_SHARED = 1 # for iSCSI multipath
def vid_to_vdi_oid(vid):
|
return VDI_BIT | vid << VDI_SPACE_SHIFT
|
identifier_body
|
|
proto.py
|
SD_PROTO_VER = 0x02
SD_SHEEP_PROTO_VER = 0x0a
SD_EC_MAX_STRIP = 16
SD_MAX_COPIES = SD_EC_MAX_STRIP * 2 - 1
SD_OP_CREATE_AND_WRITE_OBJ = 0x01
SD_OP_READ_OBJ = 0x02
SD_OP_WRITE_OBJ = 0x03
SD_OP_REMOVE_OBJ = 0x04
SD_OP_DISCARD_OBJ = 0x05
SD_OP_NEW_VDI = 0x11
SD_OP_LOCK_VDI = 0x12
SD_OP_RELEASE_VDI = 0x13
SD_OP_GET_VDI_INFO = 0x14
SD_OP_READ_VDIS = 0x15
SD_OP_FLUSH_VDI = 0x16
SD_OP_DEL_VDI = 0x17
SD_OP_GET_CLUSTER_DEFAULT = 0x18
SD_OP_GET_OBJ_LIST = 0xA1
SD_OP_GET_EPOCH = 0xA2
SD_OP_CREATE_AND_WRITE_PEER = 0xA3
SD_OP_READ_PEER = 0xA4
SD_OP_WRITE_PEER = 0xA5
SD_OP_REMOVE_PEER = 0xA6
SD_OP_GET_VDI_COPIES = 0xAB
SD_OP_READ_DEL_VDIS = 0xC9
# macros in the SD_FLAG_CMD_XXX group are mutually exclusive
SD_FLAG_CMD_WRITE = 0x01
SD_FLAG_CMD_COW = 0x02
SD_FLAG_CMD_CACHE = 0x04
SD_FLAG_CMD_DIRECT = 0x08 # don't use object cache
# return something back while sending something to sheep
SD_FLAG_CMD_PIGGYBACK = 0x10
SD_FLAG_CMD_TGT = 0x20
SD_RES_SUCCESS = 0x00 # Success
SD_RES_UNKNOWN = 0x01 # Unknown error
SD_RES_NO_OBJ = 0x02 # No object found
SD_RES_EIO = 0x03 # I/O error
SD_RES_VDI_EXIST = 0x04 # VDI exists already
SD_RES_INVALID_PARMS = 0x05 # Invalid parameters
SD_RES_SYSTEM_ERROR = 0x06 # System error
SD_RES_VDI_LOCKED = 0x07 # VDI is locked
SD_RES_NO_VDI = 0x08 # No VDI found
SD_RES_NO_BASE_VDI = 0x09 # No base VDI found
SD_RES_VDI_READ = 0x0A # Cannot read requested VDI
SD_RES_VDI_WRITE = 0x0B # Cannot write requested VDI
SD_RES_BASE_VDI_READ = 0x0C # Cannot read base VDI
SD_RES_BASE_VDI_WRITE = 0x0D # Cannot write base VDI
SD_RES_NO_TAG = 0x0E # Requested tag is not found
SD_RES_STARTUP = 0x0F # Sheepdog is on starting up
SD_RES_VDI_NOT_LOCKED = 0x10 # VDI is not locked
SD_RES_SHUTDOWN = 0x11 # Sheepdog is shutting down
SD_RES_NO_MEM = 0x12 # Cannot allocate memory
SD_RES_FULL_VDI = 0x13 # we already have the maximum VDIs
SD_RES_VER_MISMATCH = 0x14 # Protocol version mismatch
SD_RES_NO_SPACE = 0x15 # Server has no room for new objects
SD_RES_WAIT_FOR_FORMAT = 0x16 # Sheepdog is waiting for a format operation
SD_RES_WAIT_FOR_JOIN = 0x17 # Sheepdog is waiting for other nodes joining
SD_RES_JOIN_FAILED = 0x18 # Target node had failed to join sheepdog
SD_RES_HALT = 0x19 # Sheepdog is stopped doing IO
SD_RES_READONLY = 0x1A # Object is read-only
# inode object in client is invalidated, refreshing is required
SD_RES_INODE_INVALIDATED = 0x1D
# Object ID rules
#
# 0 - 31 (32 bits): data object space
# 32 - 55 (24 bits): VDI object space
# 56 - 59 ( 4 bits): reserved VDI object space
# 60 - 63 ( 4 bits): object type identifier space
VDI_SPACE_SHIFT = 32
SD_VDI_MASK = 0x00FFFFFF00000000
VDI_BIT = 1 << 63
VMSTATE_BIT = 1 << 62
VDI_ATTR_BIT = 1 << 61
VDI_BTREE_BIT = 1 << 60
LEDGER_BIT = 1 << 59
OLD_MAX_DATA_OBJS = 1 << 20
MAX_DATA_OBJS = 1 << 32
SD_MAX_VDI_LEN = 256
SD_MAX_VDI_TAG_LEN = 256
SD_MAX_VDI_ATTR_KEY_LEN = 256
SD_MAX_VDI_ATTR_VALUE_LEN = 65536
SD_MAX_SNAPSHOT_TAG_LEN = 256
SD_NR_VDIS = 1 << 24
SD_DATA_OBJ_SIZE = 1 << 22
SD_OLD_MAX_VDI_SIZE = (SD_DATA_OBJ_SIZE * OLD_MAX_DATA_OBJS)
SD_MAX_VDI_SIZE = (SD_DATA_OBJ_SIZE * MAX_DATA_OBJS)
SD_DEFAULT_BLOCK_SIZE_SHIFT = 22
SD_LEDGER_OBJ_SIZE = 1 << 22
CURRENT_VDI_ID = 0
STORE_LEN = 16
SD_REQ_SIZE = 48
SD_RSP_SIZE = 48
LOCK_TYPE_NORMAL = 0
LOCK_TYPE_SHARED = 1 # for iSCSI multipath
def
|
(vid):
return VDI_BIT | vid << VDI_SPACE_SHIFT
|
vid_to_vdi_oid
|
identifier_name
|
proto.py
|
SD_PROTO_VER = 0x02
SD_SHEEP_PROTO_VER = 0x0a
SD_EC_MAX_STRIP = 16
SD_MAX_COPIES = SD_EC_MAX_STRIP * 2 - 1
SD_OP_CREATE_AND_WRITE_OBJ = 0x01
SD_OP_READ_OBJ = 0x02
SD_OP_WRITE_OBJ = 0x03
SD_OP_REMOVE_OBJ = 0x04
SD_OP_DISCARD_OBJ = 0x05
SD_OP_NEW_VDI = 0x11
SD_OP_LOCK_VDI = 0x12
SD_OP_RELEASE_VDI = 0x13
SD_OP_GET_VDI_INFO = 0x14
SD_OP_READ_VDIS = 0x15
SD_OP_FLUSH_VDI = 0x16
SD_OP_DEL_VDI = 0x17
SD_OP_GET_CLUSTER_DEFAULT = 0x18
SD_OP_GET_OBJ_LIST = 0xA1
SD_OP_GET_EPOCH = 0xA2
SD_OP_CREATE_AND_WRITE_PEER = 0xA3
SD_OP_READ_PEER = 0xA4
SD_OP_WRITE_PEER = 0xA5
SD_OP_REMOVE_PEER = 0xA6
SD_OP_GET_VDI_COPIES = 0xAB
SD_OP_READ_DEL_VDIS = 0xC9
# macros in the SD_FLAG_CMD_XXX group are mutually exclusive
SD_FLAG_CMD_WRITE = 0x01
SD_FLAG_CMD_COW = 0x02
SD_FLAG_CMD_CACHE = 0x04
SD_FLAG_CMD_DIRECT = 0x08 # don't use object cache
# return something back while sending something to sheep
SD_FLAG_CMD_PIGGYBACK = 0x10
SD_FLAG_CMD_TGT = 0x20
SD_RES_SUCCESS = 0x00 # Success
SD_RES_UNKNOWN = 0x01 # Unknown error
SD_RES_NO_OBJ = 0x02 # No object found
SD_RES_EIO = 0x03 # I/O error
SD_RES_VDI_EXIST = 0x04 # VDI exists already
SD_RES_INVALID_PARMS = 0x05 # Invalid parameters
SD_RES_SYSTEM_ERROR = 0x06 # System error
SD_RES_VDI_LOCKED = 0x07 # VDI is locked
SD_RES_NO_VDI = 0x08 # No VDI found
SD_RES_NO_BASE_VDI = 0x09 # No base VDI found
SD_RES_VDI_READ = 0x0A # Cannot read requested VDI
SD_RES_VDI_WRITE = 0x0B # Cannot write requested VDI
SD_RES_BASE_VDI_READ = 0x0C # Cannot read base VDI
SD_RES_BASE_VDI_WRITE = 0x0D # Cannot write base VDI
SD_RES_NO_TAG = 0x0E # Requested tag is not found
SD_RES_STARTUP = 0x0F # Sheepdog is on starting up
SD_RES_VDI_NOT_LOCKED = 0x10 # VDI is not locked
SD_RES_SHUTDOWN = 0x11 # Sheepdog is shutting down
SD_RES_NO_MEM = 0x12 # Cannot allocate memory
SD_RES_FULL_VDI = 0x13 # we already have the maximum VDIs
SD_RES_VER_MISMATCH = 0x14 # Protocol version mismatch
SD_RES_NO_SPACE = 0x15 # Server has no room for new objects
SD_RES_WAIT_FOR_FORMAT = 0x16 # Sheepdog is waiting for a format operation
SD_RES_WAIT_FOR_JOIN = 0x17 # Sheepdog is waiting for other nodes joining
SD_RES_JOIN_FAILED = 0x18 # Target node had failed to join sheepdog
SD_RES_HALT = 0x19 # Sheepdog is stopped doing IO
SD_RES_READONLY = 0x1A # Object is read-only
# inode object in client is invalidated, refreshing is required
SD_RES_INODE_INVALIDATED = 0x1D
# Object ID rules
#
# 0 - 31 (32 bits): data object space
# 32 - 55 (24 bits): VDI object space
# 56 - 59 ( 4 bits): reserved VDI object space
# 60 - 63 ( 4 bits): object type identifier space
VDI_SPACE_SHIFT = 32
SD_VDI_MASK = 0x00FFFFFF00000000
VDI_BIT = 1 << 63
VMSTATE_BIT = 1 << 62
VDI_ATTR_BIT = 1 << 61
VDI_BTREE_BIT = 1 << 60
LEDGER_BIT = 1 << 59
OLD_MAX_DATA_OBJS = 1 << 20
MAX_DATA_OBJS = 1 << 32
SD_MAX_VDI_LEN = 256
SD_MAX_VDI_TAG_LEN = 256
SD_MAX_VDI_ATTR_KEY_LEN = 256
SD_MAX_VDI_ATTR_VALUE_LEN = 65536
|
SD_OLD_MAX_VDI_SIZE = (SD_DATA_OBJ_SIZE * OLD_MAX_DATA_OBJS)
SD_MAX_VDI_SIZE = (SD_DATA_OBJ_SIZE * MAX_DATA_OBJS)
SD_DEFAULT_BLOCK_SIZE_SHIFT = 22
SD_LEDGER_OBJ_SIZE = 1 << 22
CURRENT_VDI_ID = 0
STORE_LEN = 16
SD_REQ_SIZE = 48
SD_RSP_SIZE = 48
LOCK_TYPE_NORMAL = 0
LOCK_TYPE_SHARED = 1 # for iSCSI multipath
def vid_to_vdi_oid(vid):
return VDI_BIT | vid << VDI_SPACE_SHIFT
|
SD_MAX_SNAPSHOT_TAG_LEN = 256
SD_NR_VDIS = 1 << 24
SD_DATA_OBJ_SIZE = 1 << 22
|
random_line_split
|
main.rs
|
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
// ANCHOR: here
use std::thread;
use std::time::Duration;
// --snip--
// ANCHOR_END: here
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
}
}
// ANCHOR: here
fn handle_connection(mut stream: TcpStream) {
// --snip--
// ANCHOR_END: here
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
// ANCHOR: here
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK", "hello.html")
} else if buffer.starts_with(sleep)
|
else {
("HTTP/1.1 404 NOT FOUND", "404.html")
};
// --snip--
// ANCHOR_END: here
let contents = fs::read_to_string(filename).unwrap();
let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n{}",
status_line,
contents.len(),
contents
);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
// ANCHOR: here
}
// ANCHOR_END: here
|
{
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
}
|
conditional_block
|
main.rs
|
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
// ANCHOR: here
use std::thread;
use std::time::Duration;
// --snip--
// ANCHOR_END: here
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
}
}
// ANCHOR: here
fn handle_connection(mut stream: TcpStream) {
// --snip--
// ANCHOR_END: here
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
// ANCHOR: here
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK", "hello.html")
} else if buffer.starts_with(sleep) {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND", "404.html")
};
// --snip--
|
// ANCHOR_END: here
let contents = fs::read_to_string(filename).unwrap();
let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n{}",
status_line,
contents.len(),
contents
);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
// ANCHOR: here
}
// ANCHOR_END: here
|
random_line_split
|
|
main.rs
|
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
// ANCHOR: here
use std::thread;
use std::time::Duration;
// --snip--
// ANCHOR_END: here
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
}
}
// ANCHOR: here
fn handle_connection(mut stream: TcpStream)
|
// ANCHOR_END: here
|
{
// --snip--
// ANCHOR_END: here
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
// ANCHOR: here
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK", "hello.html")
} else if buffer.starts_with(sleep) {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND", "404.html")
};
// --snip--
// ANCHOR_END: here
let contents = fs::read_to_string(filename).unwrap();
let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n{}",
status_line,
contents.len(),
contents
);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
// ANCHOR: here
}
|
identifier_body
|
main.rs
|
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
// ANCHOR: here
use std::thread;
use std::time::Duration;
// --snip--
// ANCHOR_END: here
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
}
}
// ANCHOR: here
fn
|
(mut stream: TcpStream) {
// --snip--
// ANCHOR_END: here
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
// ANCHOR: here
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK", "hello.html")
} else if buffer.starts_with(sleep) {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND", "404.html")
};
// --snip--
// ANCHOR_END: here
let contents = fs::read_to_string(filename).unwrap();
let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n{}",
status_line,
contents.len(),
contents
);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
// ANCHOR: here
}
// ANCHOR_END: here
|
handle_connection
|
identifier_name
|
setup.py
|
import versioneer
import os
|
with open('requirements-optional.txt') as f:
optionals = f.read().splitlines()
reqs = []
for ir in required:
if ir[0:3] == 'git':
name = ir.split('/')[-1]
reqs += ['%s @ %s@master' % (name, ir)]
else:
reqs += [ir]
opt_reqs = []
extras_require = {}
for ir in optionals:
# For conditionals like pytest=2.1; python == 3.6
if ';' in ir:
entries = ir.split(';')
extras_require[entries[1]] = entries[0]
# Git repos, install master
if ir[0:3] == 'git':
name = ir.split('/')[-1]
opt_reqs += ['%s @ %s@master' % (name, ir)]
else:
opt_reqs += [ir]
extras_require['extras'] = opt_reqs
# If interested in benchmarking devito, we need the `examples` too
exclude = ['docs', 'tests']
try:
if not bool(int(os.environ.get('DEVITO_BENCHMARKS', 0))):
exclude += ['examples']
except (TypeError, ValueError):
exclude += ['examples']
setup(name='devito',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description="Finite Difference DSL for symbolic computation.",
long_description="""Devito is a new tool for performing
optimised Finite Difference (FD) computation from high-level
symbolic problem definitions. Devito performs automated code
generation and Just-In-time (JIT) compilation based on symbolic
equations defined in SymPy to create and execute highly
optimised Finite Difference kernels on multiple computer
platforms.""",
url='http://www.devitoproject.org',
author="Imperial College London",
author_email='[email protected]',
license='MIT',
packages=find_packages(exclude=exclude),
install_requires=reqs,
extras_require=extras_require,
test_suite='tests')
|
from setuptools import setup, find_packages
with open('requirements.txt') as f:
required = f.read().splitlines()
|
random_line_split
|
setup.py
|
import versioneer
import os
from setuptools import setup, find_packages
with open('requirements.txt') as f:
required = f.read().splitlines()
with open('requirements-optional.txt') as f:
optionals = f.read().splitlines()
reqs = []
for ir in required:
if ir[0:3] == 'git':
name = ir.split('/')[-1]
reqs += ['%s @ %s@master' % (name, ir)]
else:
reqs += [ir]
opt_reqs = []
extras_require = {}
for ir in optionals:
# For conditionals like pytest=2.1; python == 3.6
if ';' in ir:
entries = ir.split(';')
extras_require[entries[1]] = entries[0]
# Git repos, install master
if ir[0:3] == 'git':
name = ir.split('/')[-1]
opt_reqs += ['%s @ %s@master' % (name, ir)]
else:
|
extras_require['extras'] = opt_reqs
# If interested in benchmarking devito, we need the `examples` too
exclude = ['docs', 'tests']
try:
if not bool(int(os.environ.get('DEVITO_BENCHMARKS', 0))):
exclude += ['examples']
except (TypeError, ValueError):
exclude += ['examples']
setup(name='devito',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description="Finite Difference DSL for symbolic computation.",
long_description="""Devito is a new tool for performing
optimised Finite Difference (FD) computation from high-level
symbolic problem definitions. Devito performs automated code
generation and Just-In-time (JIT) compilation based on symbolic
equations defined in SymPy to create and execute highly
optimised Finite Difference kernels on multiple computer
platforms.""",
url='http://www.devitoproject.org',
author="Imperial College London",
author_email='[email protected]',
license='MIT',
packages=find_packages(exclude=exclude),
install_requires=reqs,
extras_require=extras_require,
test_suite='tests')
|
opt_reqs += [ir]
|
conditional_block
|
admin_crud_spec.ts
|
/*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or 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.
*/
import {ApiResult} from "helpers/api_request_builder";
|
describe("admin crud", () => {
beforeEach(() => jasmine.Ajax.install());
afterEach(() => jasmine.Ajax.uninstall());
describe("bulkUpdate", () => {
const API_SYSTEM_ADMINS_PATH = "/go/api/admin/security/system_admins";
it("should make a patch request", (done) => {
const bulkUpdateSystemAdmins = {
operations: {
users: {
add: ["bob", "alice"]
}
}
};
jasmine.Ajax.stubRequest(API_SYSTEM_ADMINS_PATH, JSON.stringify(bulkUpdateSystemAdmins), "PATCH")
.andReturn({
status: 200,
responseHeaders: {
"Content-Type": "application/vnd.go.cd.v2+json; charset=utf-8",
"ETag": "some-etag"
},
responseText: JSON.stringify(
bulkUpdateSystemAdmins)
});
const onResponse = jasmine.createSpy().and.callFake((response: ApiResult<any>) => {
done();
});
AdminsCRUD.bulkUpdate(bulkUpdateSystemAdmins).then(onResponse);
const request = jasmine.Ajax.requests.mostRecent();
expect(request.url).toEqual(API_SYSTEM_ADMINS_PATH);
expect(request.method).toEqual("PATCH");
expect(request.requestHeaders.Accept).toEqual("application/vnd.go.cd.v2+json");
expect(request.requestHeaders["Content-Type"]).toEqual("application/json; charset=utf-8");
});
});
});
|
import {AdminsCRUD} from "models/admins/admin_crud";
|
random_line_split
|
fastclick.js
|
/**
* @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
*
* @version 1.0.2
* @codingstandard ftlabs-jsv2
* @copyright The Financial Times Limited [All Rights Reserved]
* @license MIT License (see LICENSE.txt)
*/
/*jslint browser:true, node:true*/
/*global define, Event, Node*/
/**
* Instantiate fast-clicking listeners on the specified layer.
*
* @constructor
* @param {Element} layer The layer to listen on
* @param {Object} options The options to override the defaults
*/
function FastClick(layer, options) {
'use strict';
var oldOnClick;
options = options || {};
/**
* Whether a click is currently being tracked.
*
* @type boolean
*/
this.trackingClick = false;
/**
* Timestamp for when click tracking started.
*
* @type number
*/
this.trackingClickStart = 0;
/**
* The element being tracked for a click.
*
* @type EventTarget
*/
this.targetElement = null;
/**
* X-coordinate of touch start event.
*
* @type number
*/
this.touchStartX = 0;
/**
* Y-coordinate of touch start event.
*
* @type number
*/
this.touchStartY = 0;
/**
* ID of the last touch, retrieved from Touch.identifier.
*
* @type number
*/
this.lastTouchIdentifier = 0;
/**
* Touchmove boundary, beyond which a click will be cancelled.
*
* @type number
*/
this.touchBoundary = options.touchBoundary || 10;
/**
* The FastClick layer.
*
* @type Element
*/
this.layer = layer;
/**
* The minimum time between tap(touchstart and touchend) events
*
* @type number
*/
this.tapDelay = options.tapDelay || 200;
if (FastClick.notNeeded(layer)) {
return;
}
// Some old versions of Android don't have Function.prototype.bind
function bind(method, context) {
return function() { return method.apply(context, arguments); };
}
var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
var context = this;
for (var i = 0, l = methods.length; i < l; i++) {
context[methods[i]] = bind(context[methods[i]], context);
}
// Set up event handlers as required
if (deviceIsAndroid) {
layer.addEventListener('mouseover', this.onMouse, true);
layer.addEventListener('mousedown', this.onMouse, true);
layer.addEventListener('mouseup', this.onMouse, true);
}
layer.addEventListener('click', this.onClick, true);
layer.addEventListener('touchstart', this.onTouchStart, false);
layer.addEventListener('touchmove', this.onTouchMove, false);
layer.addEventListener('touchend', this.onTouchEnd, false);
layer.addEventListener('touchcancel', this.onTouchCancel, false);
// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
// layer when they are cancelled.
if (!Event.prototype.stopImmediatePropagation) {
layer.removeEventListener = function(type, callback, capture) {
var rmv = Node.prototype.removeEventListener;
if (type === 'click') {
rmv.call(layer, type, callback.hijacked || callback, capture);
} else {
rmv.call(layer, type, callback, capture);
}
};
layer.addEventListener = function(type, callback, capture) {
var adv = Node.prototype.addEventListener;
if (type === 'click') {
adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
if (!event.propagationStopped) {
callback(event);
}
}), capture);
} else {
adv.call(layer, type, callback, capture);
}
};
}
// If a handler is already declared in the element's onclick attribute, it will be fired before
// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
// adding it as listener.
if (typeof layer.onclick === 'function') {
// Android browser on at least 3.2 requires a new reference to the function in layer.onclick
// - the old one won't work if passed to addEventListener directly.
oldOnClick = layer.onclick;
layer.addEventListener('click', function(event) {
oldOnClick(event);
}, false);
layer.onclick = null;
}
}
/**
* Android requires exceptions.
*
* @type boolean
*/
var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0;
/**
* iOS requires exceptions.
*
* @type boolean
*/
var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent);
/**
* iOS 4 requires an exception for select elements.
*
* @type boolean
*/
var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);
/**
* iOS 6.0(+?) requires the target element to be manually derived
*
* @type boolean
*/
var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS ([6-9]|\d{2})_\d/).test(navigator.userAgent);
/**
* Determine whether a given element requires a native click.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element needs a native click
*/
FastClick.prototype.needsClick = function(target) {
'use strict';
switch (target.nodeName.toLowerCase()) {
// Don't send a synthetic click to disabled inputs (issue #62)
case 'button':
case 'select':
case 'textarea':
if (target.disabled) {
return true;
}
break;
case 'input':
// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
if ((deviceIsIOS && target.type === 'file') || target.disabled) {
return true;
}
break;
case 'label':
case 'video':
return true;
}
return (/\bneedsclick\b/).test(target.className);
};
/**
* Determine whether a given element requires a call to focus to simulate click into element.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
*/
FastClick.prototype.needsFocus = function(target) {
'use strict';
switch (target.nodeName.toLowerCase()) {
case 'textarea':
return true;
case 'select':
return !deviceIsAndroid;
case 'input':
switch (target.type) {
case 'button':
case 'checkbox':
case 'file':
case 'image':
case 'radio':
case 'submit':
return false;
}
// No point in attempting to focus disabled inputs
return !target.disabled && !target.readOnly;
default:
return (/\bneedsfocus\b/).test(target.className);
}
};
/**
* Send a click event to the specified element.
*
* @param {EventTarget|Element} targetElement
* @param {Event} event
*/
FastClick.prototype.sendClick = function(targetElement, event) {
'use strict';
var clickEvent, touch;
// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
if (document.activeElement && document.activeElement !== targetElement) {
document.activeElement.blur();
}
touch = event.changedTouches[0];
// Synthesise a click event, with an extra attribute so it can be tracked
clickEvent = document.createEvent('MouseEvents');
clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
clickEvent.forwardedTouchEvent = true;
targetElement.dispatchEvent(clickEvent);
};
FastClick.prototype.determineEventType = function(targetElement) {
'use strict';
//Issue #159: Android Chrome Select Box does not open with a synthetic click event
if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
return 'mousedown';
}
return 'click';
};
/**
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.focus = function(targetElement) {
'use strict';
var length;
// Issue #160: on iOS 7, some input elements (e.g. date datetime) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time') {
length = targetElement.value.length;
targetElement.setSelectionRange(length, length);
} else {
targetElement.focus();
}
};
/**
* Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
*
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.updateScrollParent = function(targetElement) {
'use strict';
var scrollParent, parentElement;
scrollParent = targetElement.fastClickScrollParent;
// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
// target element was moved to another parent.
if (!scrollParent || !scrollParent.contains(targetElement)) {
parentElement = targetElement;
do {
if (parentElement.scrollHeight > parentElement.offsetHeight) {
scrollParent = parentElement;
targetElement.fastClickScrollParent = parentElement;
break;
}
parentElement = parentElement.parentElement;
} while (parentElement);
}
// Always update the scroll top tracker if possible.
if (scrollParent) {
scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
}
};
/**
* @param {EventTarget} targetElement
* @returns {Element|EventTarget}
*/
FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
'use strict';
// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
if (eventTarget.nodeType === Node.TEXT_NODE) {
return eventTarget.parentNode;
}
return eventTarget;
};
/**
* On touch start, record the position and scroll offset.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchStart = function(event) {
'use strict';
var targetElement, touch, selection;
// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
if (event.targetTouches.length > 1) {
return true;
}
targetElement = this.getTargetElementFromEventTarget(event.target);
touch = event.targetTouches[0];
if (deviceIsIOS) {
// Only trusted events will deselect text on iOS (issue #49)
selection = window.getSelection();
if (selection.rangeCount && !selection.isCollapsed) {
return true;
}
if (!deviceIsIOS4) {
|
// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
// with the same identifier as the touch event that previously triggered the click that triggered the alert.
// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
if (touch.identifier === this.lastTouchIdentifier) {
event.preventDefault();
return false;
}
this.lastTouchIdentifier = touch.identifier;
// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
// 1) the user does a fling scroll on the scrollable layer
// 2) the user stops the fling scroll with another tap
// then the event.target of the last 'touchend' event will be the element that was under the user's finger
// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
this.updateScrollParent(targetElement);
}
}
this.trackingClick = true;
this.trackingClickStart = event.timeStamp;
this.targetElement = targetElement;
this.touchStartX = touch.pageX;
this.touchStartY = touch.pageY;
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
event.preventDefault();
}
return true;
};
/**
* Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.touchHasMoved = function(event) {
'use strict';
var touch = event.changedTouches[0], boundary = this.touchBoundary;
if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
return true;
}
return false;
};
/**
* Update the last position.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchMove = function(event) {
'use strict';
if (!this.trackingClick) {
return true;
}
// If the touch has moved, cancel the click tracking
if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
this.trackingClick = false;
this.targetElement = null;
}
return true;
};
/**
* Attempt to find the labelled control for the given label element.
*
* @param {EventTarget|HTMLLabelElement} labelElement
* @returns {Element|null}
*/
FastClick.prototype.findControl = function(labelElement) {
'use strict';
// Fast path for newer browsers supporting the HTML5 control attribute
if (labelElement.control !== undefined) {
return labelElement.control;
}
// All browsers under test that support touch events also support the HTML5 htmlFor attribute
if (labelElement.htmlFor) {
return document.getElementById(labelElement.htmlFor);
}
// If no for attribute exists, attempt to retrieve the first labellable descendant element
// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
};
/**
* On touch end, determine whether to send a click event at once.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchEnd = function(event) {
'use strict';
var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
if (!this.trackingClick) {
return true;
}
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
this.cancelNextClick = true;
return true;
}
// Reset to prevent wrong click cancel on input (issue #156).
this.cancelNextClick = false;
this.lastClickTime = event.timeStamp;
trackingClickStart = this.trackingClickStart;
this.trackingClick = false;
this.trackingClickStart = 0;
// On some iOS devices, the targetElement supplied with the event is invalid if the layer
// is performing a transition or scroll, and has to be re-detected manually. Note that
// for this to function correctly, it must be called *after* the event target is checked!
// See issue #57; also filed as rdar://13048589 .
if (deviceIsIOSWithBadTarget) {
touch = event.changedTouches[0];
// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
}
targetTagName = targetElement.tagName.toLowerCase();
if (targetTagName === 'label') {
forElement = this.findControl(targetElement);
if (forElement) {
this.focus(targetElement);
if (deviceIsAndroid) {
return false;
}
targetElement = forElement;
}
} else if (this.needsFocus(targetElement)) {
// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
this.targetElement = null;
return false;
}
this.focus(targetElement);
this.sendClick(targetElement, event);
// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
// Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
if (!deviceIsIOS || targetTagName !== 'select') {
this.targetElement = null;
event.preventDefault();
}
return false;
}
if (deviceIsIOS && !deviceIsIOS4) {
// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
scrollParent = targetElement.fastClickScrollParent;
if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
return true;
}
}
// Prevent the actual click from going though - unless the target node is marked as requiring
// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
if (!this.needsClick(targetElement)) {
event.preventDefault();
this.sendClick(targetElement, event);
}
return false;
};
/**
* On touch cancel, stop tracking the click.
*
* @returns {void}
*/
FastClick.prototype.onTouchCancel = function() {
'use strict';
this.trackingClick = false;
this.targetElement = null;
};
/**
* Determine mouse events which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onMouse = function(event) {
'use strict';
// If a target element was never set (because a touch event was never fired) allow the event
if (!this.targetElement) {
return true;
}
if (event.forwardedTouchEvent) {
return true;
}
// Programmatically generated events targeting a specific element should be permitted
if (!event.cancelable) {
return true;
}
// Derive and check the target element to see whether the mouse event needs to be permitted;
// unless explicitly enabled, prevent non-touch click events from triggering actions,
// to prevent ghost/doubleclicks.
if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
// Prevent any user-added listeners declared on FastClick element from being fired.
if (event.stopImmediatePropagation) {
event.stopImmediatePropagation();
} else {
// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
event.propagationStopped = true;
}
// Cancel the event
event.stopPropagation();
event.preventDefault();
return false;
}
// If the mouse event is permitted, return true for the action to go through.
return true;
};
/**
* On actual clicks, determine whether this is a touch-generated click, a click action occurring
* naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
* an actual click which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onClick = function(event) {
'use strict';
var permitted;
// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
if (this.trackingClick) {
this.targetElement = null;
this.trackingClick = false;
return true;
}
// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
if (event.target.type === 'submit' && event.detail === 0) {
return true;
}
permitted = this.onMouse(event);
// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
if (!permitted) {
this.targetElement = null;
}
// If clicks are permitted, return true for the action to go through.
return permitted;
};
/**
* Remove all FastClick's event listeners.
*
* @returns {void}
*/
FastClick.prototype.destroy = function() {
'use strict';
var layer = this.layer;
if (deviceIsAndroid) {
layer.removeEventListener('mouseover', this.onMouse, true);
layer.removeEventListener('mousedown', this.onMouse, true);
layer.removeEventListener('mouseup', this.onMouse, true);
}
layer.removeEventListener('click', this.onClick, true);
layer.removeEventListener('touchstart', this.onTouchStart, false);
layer.removeEventListener('touchmove', this.onTouchMove, false);
layer.removeEventListener('touchend', this.onTouchEnd, false);
layer.removeEventListener('touchcancel', this.onTouchCancel, false);
};
/**
* Check whether FastClick is needed.
*
* @param {Element} layer The layer to listen on
*/
FastClick.notNeeded = function(layer) {
'use strict';
var metaViewport;
var chromeVersion;
// Devices that don't support touch don't need FastClick
if (typeof window.ontouchstart === 'undefined') {
return true;
}
// Chrome version - zero for other browsers
chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
if (chromeVersion) {
if (deviceIsAndroid) {
metaViewport = document.querySelector('meta[name=viewport]');
if (metaViewport) {
// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
return true;
}
// Chrome 32 and above with width=device-width or less don't need FastClick
if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
return true;
}
}
// Chrome desktop doesn't need FastClick (issue #15)
} else {
return true;
}
}
// IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97)
if (layer.style.msTouchAction === 'none') {
return true;
}
return false;
};
/**
* Factory method for creating a FastClick object
*
* @param {Element} layer The layer to listen on
* @param {Object} options The options to override the defaults
*/
FastClick.attach = function(layer, options) {
'use strict';
return new FastClick(layer, options);
};
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// AMD. Register as an anonymous module.
define(function() {
'use strict';
return FastClick;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = FastClick.attach;
module.exports.FastClick = FastClick;
} else {
window.FastClick = FastClick;
}
|
random_line_split
|
|
fastclick.js
|
/**
* @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
*
* @version 1.0.2
* @codingstandard ftlabs-jsv2
* @copyright The Financial Times Limited [All Rights Reserved]
* @license MIT License (see LICENSE.txt)
*/
/*jslint browser:true, node:true*/
/*global define, Event, Node*/
/**
* Instantiate fast-clicking listeners on the specified layer.
*
* @constructor
* @param {Element} layer The layer to listen on
* @param {Object} options The options to override the defaults
*/
function FastClick(layer, options) {
'use strict';
var oldOnClick;
options = options || {};
/**
* Whether a click is currently being tracked.
*
* @type boolean
*/
this.trackingClick = false;
/**
* Timestamp for when click tracking started.
*
* @type number
*/
this.trackingClickStart = 0;
/**
* The element being tracked for a click.
*
* @type EventTarget
*/
this.targetElement = null;
/**
* X-coordinate of touch start event.
*
* @type number
*/
this.touchStartX = 0;
/**
* Y-coordinate of touch start event.
*
* @type number
*/
this.touchStartY = 0;
/**
* ID of the last touch, retrieved from Touch.identifier.
*
* @type number
*/
this.lastTouchIdentifier = 0;
/**
* Touchmove boundary, beyond which a click will be cancelled.
*
* @type number
*/
this.touchBoundary = options.touchBoundary || 10;
/**
* The FastClick layer.
*
* @type Element
*/
this.layer = layer;
/**
* The minimum time between tap(touchstart and touchend) events
*
* @type number
*/
this.tapDelay = options.tapDelay || 200;
if (FastClick.notNeeded(layer)) {
return;
}
// Some old versions of Android don't have Function.prototype.bind
function bind(method, context) {
return function() { return method.apply(context, arguments); };
}
var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
var context = this;
for (var i = 0, l = methods.length; i < l; i++) {
context[methods[i]] = bind(context[methods[i]], context);
}
// Set up event handlers as required
if (deviceIsAndroid) {
layer.addEventListener('mouseover', this.onMouse, true);
layer.addEventListener('mousedown', this.onMouse, true);
layer.addEventListener('mouseup', this.onMouse, true);
}
layer.addEventListener('click', this.onClick, true);
layer.addEventListener('touchstart', this.onTouchStart, false);
layer.addEventListener('touchmove', this.onTouchMove, false);
layer.addEventListener('touchend', this.onTouchEnd, false);
layer.addEventListener('touchcancel', this.onTouchCancel, false);
// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
// layer when they are cancelled.
if (!Event.prototype.stopImmediatePropagation) {
layer.removeEventListener = function(type, callback, capture) {
var rmv = Node.prototype.removeEventListener;
if (type === 'click') {
rmv.call(layer, type, callback.hijacked || callback, capture);
} else {
rmv.call(layer, type, callback, capture);
}
};
layer.addEventListener = function(type, callback, capture) {
var adv = Node.prototype.addEventListener;
if (type === 'click') {
adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
if (!event.propagationStopped) {
callback(event);
}
}), capture);
} else {
adv.call(layer, type, callback, capture);
}
};
}
// If a handler is already declared in the element's onclick attribute, it will be fired before
// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
// adding it as listener.
if (typeof layer.onclick === 'function') {
// Android browser on at least 3.2 requires a new reference to the function in layer.onclick
// - the old one won't work if passed to addEventListener directly.
oldOnClick = layer.onclick;
layer.addEventListener('click', function(event) {
oldOnClick(event);
}, false);
layer.onclick = null;
}
}
/**
* Android requires exceptions.
*
* @type boolean
*/
var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0;
/**
* iOS requires exceptions.
*
* @type boolean
*/
var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent);
/**
* iOS 4 requires an exception for select elements.
*
* @type boolean
*/
var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);
/**
* iOS 6.0(+?) requires the target element to be manually derived
*
* @type boolean
*/
var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS ([6-9]|\d{2})_\d/).test(navigator.userAgent);
/**
* Determine whether a given element requires a native click.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element needs a native click
*/
FastClick.prototype.needsClick = function(target) {
'use strict';
switch (target.nodeName.toLowerCase()) {
// Don't send a synthetic click to disabled inputs (issue #62)
case 'button':
case 'select':
case 'textarea':
if (target.disabled) {
return true;
}
break;
case 'input':
// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
if ((deviceIsIOS && target.type === 'file') || target.disabled) {
return true;
}
break;
case 'label':
case 'video':
return true;
}
return (/\bneedsclick\b/).test(target.className);
};
/**
* Determine whether a given element requires a call to focus to simulate click into element.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
*/
FastClick.prototype.needsFocus = function(target) {
'use strict';
switch (target.nodeName.toLowerCase()) {
case 'textarea':
return true;
case 'select':
return !deviceIsAndroid;
case 'input':
switch (target.type) {
case 'button':
case 'checkbox':
case 'file':
case 'image':
case 'radio':
case 'submit':
return false;
}
// No point in attempting to focus disabled inputs
return !target.disabled && !target.readOnly;
default:
return (/\bneedsfocus\b/).test(target.className);
}
};
/**
* Send a click event to the specified element.
*
* @param {EventTarget|Element} targetElement
* @param {Event} event
*/
FastClick.prototype.sendClick = function(targetElement, event) {
'use strict';
var clickEvent, touch;
// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
if (document.activeElement && document.activeElement !== targetElement) {
document.activeElement.blur();
}
touch = event.changedTouches[0];
// Synthesise a click event, with an extra attribute so it can be tracked
clickEvent = document.createEvent('MouseEvents');
clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
clickEvent.forwardedTouchEvent = true;
targetElement.dispatchEvent(clickEvent);
};
FastClick.prototype.determineEventType = function(targetElement) {
'use strict';
//Issue #159: Android Chrome Select Box does not open with a synthetic click event
if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
return 'mousedown';
}
return 'click';
};
/**
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.focus = function(targetElement) {
'use strict';
var length;
// Issue #160: on iOS 7, some input elements (e.g. date datetime) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time') {
length = targetElement.value.length;
targetElement.setSelectionRange(length, length);
} else {
targetElement.focus();
}
};
/**
* Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
*
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.updateScrollParent = function(targetElement) {
'use strict';
var scrollParent, parentElement;
scrollParent = targetElement.fastClickScrollParent;
// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
// target element was moved to another parent.
if (!scrollParent || !scrollParent.contains(targetElement)) {
parentElement = targetElement;
do {
if (parentElement.scrollHeight > parentElement.offsetHeight) {
scrollParent = parentElement;
targetElement.fastClickScrollParent = parentElement;
break;
}
parentElement = parentElement.parentElement;
} while (parentElement);
}
// Always update the scroll top tracker if possible.
if (scrollParent) {
scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
}
};
/**
* @param {EventTarget} targetElement
* @returns {Element|EventTarget}
*/
FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
'use strict';
// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
if (eventTarget.nodeType === Node.TEXT_NODE) {
return eventTarget.parentNode;
}
return eventTarget;
};
/**
* On touch start, record the position and scroll offset.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchStart = function(event) {
'use strict';
var targetElement, touch, selection;
// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
if (event.targetTouches.length > 1) {
return true;
}
targetElement = this.getTargetElementFromEventTarget(event.target);
touch = event.targetTouches[0];
if (deviceIsIOS) {
// Only trusted events will deselect text on iOS (issue #49)
selection = window.getSelection();
if (selection.rangeCount && !selection.isCollapsed) {
return true;
}
if (!deviceIsIOS4) {
// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
// with the same identifier as the touch event that previously triggered the click that triggered the alert.
// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
if (touch.identifier === this.lastTouchIdentifier)
|
this.lastTouchIdentifier = touch.identifier;
// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
// 1) the user does a fling scroll on the scrollable layer
// 2) the user stops the fling scroll with another tap
// then the event.target of the last 'touchend' event will be the element that was under the user's finger
// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
this.updateScrollParent(targetElement);
}
}
this.trackingClick = true;
this.trackingClickStart = event.timeStamp;
this.targetElement = targetElement;
this.touchStartX = touch.pageX;
this.touchStartY = touch.pageY;
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
event.preventDefault();
}
return true;
};
/**
* Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.touchHasMoved = function(event) {
'use strict';
var touch = event.changedTouches[0], boundary = this.touchBoundary;
if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
return true;
}
return false;
};
/**
* Update the last position.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchMove = function(event) {
'use strict';
if (!this.trackingClick) {
return true;
}
// If the touch has moved, cancel the click tracking
if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
this.trackingClick = false;
this.targetElement = null;
}
return true;
};
/**
* Attempt to find the labelled control for the given label element.
*
* @param {EventTarget|HTMLLabelElement} labelElement
* @returns {Element|null}
*/
FastClick.prototype.findControl = function(labelElement) {
'use strict';
// Fast path for newer browsers supporting the HTML5 control attribute
if (labelElement.control !== undefined) {
return labelElement.control;
}
// All browsers under test that support touch events also support the HTML5 htmlFor attribute
if (labelElement.htmlFor) {
return document.getElementById(labelElement.htmlFor);
}
// If no for attribute exists, attempt to retrieve the first labellable descendant element
// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
};
/**
* On touch end, determine whether to send a click event at once.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchEnd = function(event) {
'use strict';
var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
if (!this.trackingClick) {
return true;
}
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
this.cancelNextClick = true;
return true;
}
// Reset to prevent wrong click cancel on input (issue #156).
this.cancelNextClick = false;
this.lastClickTime = event.timeStamp;
trackingClickStart = this.trackingClickStart;
this.trackingClick = false;
this.trackingClickStart = 0;
// On some iOS devices, the targetElement supplied with the event is invalid if the layer
// is performing a transition or scroll, and has to be re-detected manually. Note that
// for this to function correctly, it must be called *after* the event target is checked!
// See issue #57; also filed as rdar://13048589 .
if (deviceIsIOSWithBadTarget) {
touch = event.changedTouches[0];
// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
}
targetTagName = targetElement.tagName.toLowerCase();
if (targetTagName === 'label') {
forElement = this.findControl(targetElement);
if (forElement) {
this.focus(targetElement);
if (deviceIsAndroid) {
return false;
}
targetElement = forElement;
}
} else if (this.needsFocus(targetElement)) {
// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
this.targetElement = null;
return false;
}
this.focus(targetElement);
this.sendClick(targetElement, event);
// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
// Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
if (!deviceIsIOS || targetTagName !== 'select') {
this.targetElement = null;
event.preventDefault();
}
return false;
}
if (deviceIsIOS && !deviceIsIOS4) {
// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
scrollParent = targetElement.fastClickScrollParent;
if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
return true;
}
}
// Prevent the actual click from going though - unless the target node is marked as requiring
// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
if (!this.needsClick(targetElement)) {
event.preventDefault();
this.sendClick(targetElement, event);
}
return false;
};
/**
* On touch cancel, stop tracking the click.
*
* @returns {void}
*/
FastClick.prototype.onTouchCancel = function() {
'use strict';
this.trackingClick = false;
this.targetElement = null;
};
/**
* Determine mouse events which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onMouse = function(event) {
'use strict';
// If a target element was never set (because a touch event was never fired) allow the event
if (!this.targetElement) {
return true;
}
if (event.forwardedTouchEvent) {
return true;
}
// Programmatically generated events targeting a specific element should be permitted
if (!event.cancelable) {
return true;
}
// Derive and check the target element to see whether the mouse event needs to be permitted;
// unless explicitly enabled, prevent non-touch click events from triggering actions,
// to prevent ghost/doubleclicks.
if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
// Prevent any user-added listeners declared on FastClick element from being fired.
if (event.stopImmediatePropagation) {
event.stopImmediatePropagation();
} else {
// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
event.propagationStopped = true;
}
// Cancel the event
event.stopPropagation();
event.preventDefault();
return false;
}
// If the mouse event is permitted, return true for the action to go through.
return true;
};
/**
* On actual clicks, determine whether this is a touch-generated click, a click action occurring
* naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
* an actual click which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onClick = function(event) {
'use strict';
var permitted;
// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
if (this.trackingClick) {
this.targetElement = null;
this.trackingClick = false;
return true;
}
// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
if (event.target.type === 'submit' && event.detail === 0) {
return true;
}
permitted = this.onMouse(event);
// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
if (!permitted) {
this.targetElement = null;
}
// If clicks are permitted, return true for the action to go through.
return permitted;
};
/**
* Remove all FastClick's event listeners.
*
* @returns {void}
*/
FastClick.prototype.destroy = function() {
'use strict';
var layer = this.layer;
if (deviceIsAndroid) {
layer.removeEventListener('mouseover', this.onMouse, true);
layer.removeEventListener('mousedown', this.onMouse, true);
layer.removeEventListener('mouseup', this.onMouse, true);
}
layer.removeEventListener('click', this.onClick, true);
layer.removeEventListener('touchstart', this.onTouchStart, false);
layer.removeEventListener('touchmove', this.onTouchMove, false);
layer.removeEventListener('touchend', this.onTouchEnd, false);
layer.removeEventListener('touchcancel', this.onTouchCancel, false);
};
/**
* Check whether FastClick is needed.
*
* @param {Element} layer The layer to listen on
*/
FastClick.notNeeded = function(layer) {
'use strict';
var metaViewport;
var chromeVersion;
// Devices that don't support touch don't need FastClick
if (typeof window.ontouchstart === 'undefined') {
return true;
}
// Chrome version - zero for other browsers
chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
if (chromeVersion) {
if (deviceIsAndroid) {
metaViewport = document.querySelector('meta[name=viewport]');
if (metaViewport) {
// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
return true;
}
// Chrome 32 and above with width=device-width or less don't need FastClick
if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
return true;
}
}
// Chrome desktop doesn't need FastClick (issue #15)
} else {
return true;
}
}
// IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97)
if (layer.style.msTouchAction === 'none') {
return true;
}
return false;
};
/**
* Factory method for creating a FastClick object
*
* @param {Element} layer The layer to listen on
* @param {Object} options The options to override the defaults
*/
FastClick.attach = function(layer, options) {
'use strict';
return new FastClick(layer, options);
};
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// AMD. Register as an anonymous module.
define(function() {
'use strict';
return FastClick;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = FastClick.attach;
module.exports.FastClick = FastClick;
} else {
window.FastClick = FastClick;
}
|
{
event.preventDefault();
return false;
}
|
conditional_block
|
fastclick.js
|
/**
* @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
*
* @version 1.0.2
* @codingstandard ftlabs-jsv2
* @copyright The Financial Times Limited [All Rights Reserved]
* @license MIT License (see LICENSE.txt)
*/
/*jslint browser:true, node:true*/
/*global define, Event, Node*/
/**
* Instantiate fast-clicking listeners on the specified layer.
*
* @constructor
* @param {Element} layer The layer to listen on
* @param {Object} options The options to override the defaults
*/
function FastClick(layer, options)
|
/**
* Android requires exceptions.
*
* @type boolean
*/
var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0;
/**
* iOS requires exceptions.
*
* @type boolean
*/
var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent);
/**
* iOS 4 requires an exception for select elements.
*
* @type boolean
*/
var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);
/**
* iOS 6.0(+?) requires the target element to be manually derived
*
* @type boolean
*/
var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS ([6-9]|\d{2})_\d/).test(navigator.userAgent);
/**
* Determine whether a given element requires a native click.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element needs a native click
*/
FastClick.prototype.needsClick = function(target) {
'use strict';
switch (target.nodeName.toLowerCase()) {
// Don't send a synthetic click to disabled inputs (issue #62)
case 'button':
case 'select':
case 'textarea':
if (target.disabled) {
return true;
}
break;
case 'input':
// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
if ((deviceIsIOS && target.type === 'file') || target.disabled) {
return true;
}
break;
case 'label':
case 'video':
return true;
}
return (/\bneedsclick\b/).test(target.className);
};
/**
* Determine whether a given element requires a call to focus to simulate click into element.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
*/
FastClick.prototype.needsFocus = function(target) {
'use strict';
switch (target.nodeName.toLowerCase()) {
case 'textarea':
return true;
case 'select':
return !deviceIsAndroid;
case 'input':
switch (target.type) {
case 'button':
case 'checkbox':
case 'file':
case 'image':
case 'radio':
case 'submit':
return false;
}
// No point in attempting to focus disabled inputs
return !target.disabled && !target.readOnly;
default:
return (/\bneedsfocus\b/).test(target.className);
}
};
/**
* Send a click event to the specified element.
*
* @param {EventTarget|Element} targetElement
* @param {Event} event
*/
FastClick.prototype.sendClick = function(targetElement, event) {
'use strict';
var clickEvent, touch;
// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
if (document.activeElement && document.activeElement !== targetElement) {
document.activeElement.blur();
}
touch = event.changedTouches[0];
// Synthesise a click event, with an extra attribute so it can be tracked
clickEvent = document.createEvent('MouseEvents');
clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
clickEvent.forwardedTouchEvent = true;
targetElement.dispatchEvent(clickEvent);
};
FastClick.prototype.determineEventType = function(targetElement) {
'use strict';
//Issue #159: Android Chrome Select Box does not open with a synthetic click event
if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
return 'mousedown';
}
return 'click';
};
/**
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.focus = function(targetElement) {
'use strict';
var length;
// Issue #160: on iOS 7, some input elements (e.g. date datetime) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time') {
length = targetElement.value.length;
targetElement.setSelectionRange(length, length);
} else {
targetElement.focus();
}
};
/**
* Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
*
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.updateScrollParent = function(targetElement) {
'use strict';
var scrollParent, parentElement;
scrollParent = targetElement.fastClickScrollParent;
// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
// target element was moved to another parent.
if (!scrollParent || !scrollParent.contains(targetElement)) {
parentElement = targetElement;
do {
if (parentElement.scrollHeight > parentElement.offsetHeight) {
scrollParent = parentElement;
targetElement.fastClickScrollParent = parentElement;
break;
}
parentElement = parentElement.parentElement;
} while (parentElement);
}
// Always update the scroll top tracker if possible.
if (scrollParent) {
scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
}
};
/**
* @param {EventTarget} targetElement
* @returns {Element|EventTarget}
*/
FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
'use strict';
// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
if (eventTarget.nodeType === Node.TEXT_NODE) {
return eventTarget.parentNode;
}
return eventTarget;
};
/**
* On touch start, record the position and scroll offset.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchStart = function(event) {
'use strict';
var targetElement, touch, selection;
// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
if (event.targetTouches.length > 1) {
return true;
}
targetElement = this.getTargetElementFromEventTarget(event.target);
touch = event.targetTouches[0];
if (deviceIsIOS) {
// Only trusted events will deselect text on iOS (issue #49)
selection = window.getSelection();
if (selection.rangeCount && !selection.isCollapsed) {
return true;
}
if (!deviceIsIOS4) {
// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
// with the same identifier as the touch event that previously triggered the click that triggered the alert.
// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
if (touch.identifier === this.lastTouchIdentifier) {
event.preventDefault();
return false;
}
this.lastTouchIdentifier = touch.identifier;
// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
// 1) the user does a fling scroll on the scrollable layer
// 2) the user stops the fling scroll with another tap
// then the event.target of the last 'touchend' event will be the element that was under the user's finger
// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
this.updateScrollParent(targetElement);
}
}
this.trackingClick = true;
this.trackingClickStart = event.timeStamp;
this.targetElement = targetElement;
this.touchStartX = touch.pageX;
this.touchStartY = touch.pageY;
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
event.preventDefault();
}
return true;
};
/**
* Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.touchHasMoved = function(event) {
'use strict';
var touch = event.changedTouches[0], boundary = this.touchBoundary;
if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
return true;
}
return false;
};
/**
* Update the last position.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchMove = function(event) {
'use strict';
if (!this.trackingClick) {
return true;
}
// If the touch has moved, cancel the click tracking
if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
this.trackingClick = false;
this.targetElement = null;
}
return true;
};
/**
* Attempt to find the labelled control for the given label element.
*
* @param {EventTarget|HTMLLabelElement} labelElement
* @returns {Element|null}
*/
FastClick.prototype.findControl = function(labelElement) {
'use strict';
// Fast path for newer browsers supporting the HTML5 control attribute
if (labelElement.control !== undefined) {
return labelElement.control;
}
// All browsers under test that support touch events also support the HTML5 htmlFor attribute
if (labelElement.htmlFor) {
return document.getElementById(labelElement.htmlFor);
}
// If no for attribute exists, attempt to retrieve the first labellable descendant element
// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
};
/**
* On touch end, determine whether to send a click event at once.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchEnd = function(event) {
'use strict';
var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
if (!this.trackingClick) {
return true;
}
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
this.cancelNextClick = true;
return true;
}
// Reset to prevent wrong click cancel on input (issue #156).
this.cancelNextClick = false;
this.lastClickTime = event.timeStamp;
trackingClickStart = this.trackingClickStart;
this.trackingClick = false;
this.trackingClickStart = 0;
// On some iOS devices, the targetElement supplied with the event is invalid if the layer
// is performing a transition or scroll, and has to be re-detected manually. Note that
// for this to function correctly, it must be called *after* the event target is checked!
// See issue #57; also filed as rdar://13048589 .
if (deviceIsIOSWithBadTarget) {
touch = event.changedTouches[0];
// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
}
targetTagName = targetElement.tagName.toLowerCase();
if (targetTagName === 'label') {
forElement = this.findControl(targetElement);
if (forElement) {
this.focus(targetElement);
if (deviceIsAndroid) {
return false;
}
targetElement = forElement;
}
} else if (this.needsFocus(targetElement)) {
// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
this.targetElement = null;
return false;
}
this.focus(targetElement);
this.sendClick(targetElement, event);
// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
// Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
if (!deviceIsIOS || targetTagName !== 'select') {
this.targetElement = null;
event.preventDefault();
}
return false;
}
if (deviceIsIOS && !deviceIsIOS4) {
// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
scrollParent = targetElement.fastClickScrollParent;
if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
return true;
}
}
// Prevent the actual click from going though - unless the target node is marked as requiring
// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
if (!this.needsClick(targetElement)) {
event.preventDefault();
this.sendClick(targetElement, event);
}
return false;
};
/**
* On touch cancel, stop tracking the click.
*
* @returns {void}
*/
FastClick.prototype.onTouchCancel = function() {
'use strict';
this.trackingClick = false;
this.targetElement = null;
};
/**
* Determine mouse events which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onMouse = function(event) {
'use strict';
// If a target element was never set (because a touch event was never fired) allow the event
if (!this.targetElement) {
return true;
}
if (event.forwardedTouchEvent) {
return true;
}
// Programmatically generated events targeting a specific element should be permitted
if (!event.cancelable) {
return true;
}
// Derive and check the target element to see whether the mouse event needs to be permitted;
// unless explicitly enabled, prevent non-touch click events from triggering actions,
// to prevent ghost/doubleclicks.
if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
// Prevent any user-added listeners declared on FastClick element from being fired.
if (event.stopImmediatePropagation) {
event.stopImmediatePropagation();
} else {
// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
event.propagationStopped = true;
}
// Cancel the event
event.stopPropagation();
event.preventDefault();
return false;
}
// If the mouse event is permitted, return true for the action to go through.
return true;
};
/**
* On actual clicks, determine whether this is a touch-generated click, a click action occurring
* naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
* an actual click which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onClick = function(event) {
'use strict';
var permitted;
// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
if (this.trackingClick) {
this.targetElement = null;
this.trackingClick = false;
return true;
}
// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
if (event.target.type === 'submit' && event.detail === 0) {
return true;
}
permitted = this.onMouse(event);
// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
if (!permitted) {
this.targetElement = null;
}
// If clicks are permitted, return true for the action to go through.
return permitted;
};
/**
* Remove all FastClick's event listeners.
*
* @returns {void}
*/
FastClick.prototype.destroy = function() {
'use strict';
var layer = this.layer;
if (deviceIsAndroid) {
layer.removeEventListener('mouseover', this.onMouse, true);
layer.removeEventListener('mousedown', this.onMouse, true);
layer.removeEventListener('mouseup', this.onMouse, true);
}
layer.removeEventListener('click', this.onClick, true);
layer.removeEventListener('touchstart', this.onTouchStart, false);
layer.removeEventListener('touchmove', this.onTouchMove, false);
layer.removeEventListener('touchend', this.onTouchEnd, false);
layer.removeEventListener('touchcancel', this.onTouchCancel, false);
};
/**
* Check whether FastClick is needed.
*
* @param {Element} layer The layer to listen on
*/
FastClick.notNeeded = function(layer) {
'use strict';
var metaViewport;
var chromeVersion;
// Devices that don't support touch don't need FastClick
if (typeof window.ontouchstart === 'undefined') {
return true;
}
// Chrome version - zero for other browsers
chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
if (chromeVersion) {
if (deviceIsAndroid) {
metaViewport = document.querySelector('meta[name=viewport]');
if (metaViewport) {
// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
return true;
}
// Chrome 32 and above with width=device-width or less don't need FastClick
if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
return true;
}
}
// Chrome desktop doesn't need FastClick (issue #15)
} else {
return true;
}
}
// IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97)
if (layer.style.msTouchAction === 'none') {
return true;
}
return false;
};
/**
* Factory method for creating a FastClick object
*
* @param {Element} layer The layer to listen on
* @param {Object} options The options to override the defaults
*/
FastClick.attach = function(layer, options) {
'use strict';
return new FastClick(layer, options);
};
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// AMD. Register as an anonymous module.
define(function() {
'use strict';
return FastClick;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = FastClick.attach;
module.exports.FastClick = FastClick;
} else {
window.FastClick = FastClick;
}
|
{
'use strict';
var oldOnClick;
options = options || {};
/**
* Whether a click is currently being tracked.
*
* @type boolean
*/
this.trackingClick = false;
/**
* Timestamp for when click tracking started.
*
* @type number
*/
this.trackingClickStart = 0;
/**
* The element being tracked for a click.
*
* @type EventTarget
*/
this.targetElement = null;
/**
* X-coordinate of touch start event.
*
* @type number
*/
this.touchStartX = 0;
/**
* Y-coordinate of touch start event.
*
* @type number
*/
this.touchStartY = 0;
/**
* ID of the last touch, retrieved from Touch.identifier.
*
* @type number
*/
this.lastTouchIdentifier = 0;
/**
* Touchmove boundary, beyond which a click will be cancelled.
*
* @type number
*/
this.touchBoundary = options.touchBoundary || 10;
/**
* The FastClick layer.
*
* @type Element
*/
this.layer = layer;
/**
* The minimum time between tap(touchstart and touchend) events
*
* @type number
*/
this.tapDelay = options.tapDelay || 200;
if (FastClick.notNeeded(layer)) {
return;
}
// Some old versions of Android don't have Function.prototype.bind
function bind(method, context) {
return function() { return method.apply(context, arguments); };
}
var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
var context = this;
for (var i = 0, l = methods.length; i < l; i++) {
context[methods[i]] = bind(context[methods[i]], context);
}
// Set up event handlers as required
if (deviceIsAndroid) {
layer.addEventListener('mouseover', this.onMouse, true);
layer.addEventListener('mousedown', this.onMouse, true);
layer.addEventListener('mouseup', this.onMouse, true);
}
layer.addEventListener('click', this.onClick, true);
layer.addEventListener('touchstart', this.onTouchStart, false);
layer.addEventListener('touchmove', this.onTouchMove, false);
layer.addEventListener('touchend', this.onTouchEnd, false);
layer.addEventListener('touchcancel', this.onTouchCancel, false);
// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
// layer when they are cancelled.
if (!Event.prototype.stopImmediatePropagation) {
layer.removeEventListener = function(type, callback, capture) {
var rmv = Node.prototype.removeEventListener;
if (type === 'click') {
rmv.call(layer, type, callback.hijacked || callback, capture);
} else {
rmv.call(layer, type, callback, capture);
}
};
layer.addEventListener = function(type, callback, capture) {
var adv = Node.prototype.addEventListener;
if (type === 'click') {
adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
if (!event.propagationStopped) {
callback(event);
}
}), capture);
} else {
adv.call(layer, type, callback, capture);
}
};
}
// If a handler is already declared in the element's onclick attribute, it will be fired before
// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
// adding it as listener.
if (typeof layer.onclick === 'function') {
// Android browser on at least 3.2 requires a new reference to the function in layer.onclick
// - the old one won't work if passed to addEventListener directly.
oldOnClick = layer.onclick;
layer.addEventListener('click', function(event) {
oldOnClick(event);
}, false);
layer.onclick = null;
}
}
|
identifier_body
|
fastclick.js
|
/**
* @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
*
* @version 1.0.2
* @codingstandard ftlabs-jsv2
* @copyright The Financial Times Limited [All Rights Reserved]
* @license MIT License (see LICENSE.txt)
*/
/*jslint browser:true, node:true*/
/*global define, Event, Node*/
/**
* Instantiate fast-clicking listeners on the specified layer.
*
* @constructor
* @param {Element} layer The layer to listen on
* @param {Object} options The options to override the defaults
*/
function FastClick(layer, options) {
'use strict';
var oldOnClick;
options = options || {};
/**
* Whether a click is currently being tracked.
*
* @type boolean
*/
this.trackingClick = false;
/**
* Timestamp for when click tracking started.
*
* @type number
*/
this.trackingClickStart = 0;
/**
* The element being tracked for a click.
*
* @type EventTarget
*/
this.targetElement = null;
/**
* X-coordinate of touch start event.
*
* @type number
*/
this.touchStartX = 0;
/**
* Y-coordinate of touch start event.
*
* @type number
*/
this.touchStartY = 0;
/**
* ID of the last touch, retrieved from Touch.identifier.
*
* @type number
*/
this.lastTouchIdentifier = 0;
/**
* Touchmove boundary, beyond which a click will be cancelled.
*
* @type number
*/
this.touchBoundary = options.touchBoundary || 10;
/**
* The FastClick layer.
*
* @type Element
*/
this.layer = layer;
/**
* The minimum time between tap(touchstart and touchend) events
*
* @type number
*/
this.tapDelay = options.tapDelay || 200;
if (FastClick.notNeeded(layer)) {
return;
}
// Some old versions of Android don't have Function.prototype.bind
function
|
(method, context) {
return function() { return method.apply(context, arguments); };
}
var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
var context = this;
for (var i = 0, l = methods.length; i < l; i++) {
context[methods[i]] = bind(context[methods[i]], context);
}
// Set up event handlers as required
if (deviceIsAndroid) {
layer.addEventListener('mouseover', this.onMouse, true);
layer.addEventListener('mousedown', this.onMouse, true);
layer.addEventListener('mouseup', this.onMouse, true);
}
layer.addEventListener('click', this.onClick, true);
layer.addEventListener('touchstart', this.onTouchStart, false);
layer.addEventListener('touchmove', this.onTouchMove, false);
layer.addEventListener('touchend', this.onTouchEnd, false);
layer.addEventListener('touchcancel', this.onTouchCancel, false);
// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
// layer when they are cancelled.
if (!Event.prototype.stopImmediatePropagation) {
layer.removeEventListener = function(type, callback, capture) {
var rmv = Node.prototype.removeEventListener;
if (type === 'click') {
rmv.call(layer, type, callback.hijacked || callback, capture);
} else {
rmv.call(layer, type, callback, capture);
}
};
layer.addEventListener = function(type, callback, capture) {
var adv = Node.prototype.addEventListener;
if (type === 'click') {
adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
if (!event.propagationStopped) {
callback(event);
}
}), capture);
} else {
adv.call(layer, type, callback, capture);
}
};
}
// If a handler is already declared in the element's onclick attribute, it will be fired before
// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
// adding it as listener.
if (typeof layer.onclick === 'function') {
// Android browser on at least 3.2 requires a new reference to the function in layer.onclick
// - the old one won't work if passed to addEventListener directly.
oldOnClick = layer.onclick;
layer.addEventListener('click', function(event) {
oldOnClick(event);
}, false);
layer.onclick = null;
}
}
/**
* Android requires exceptions.
*
* @type boolean
*/
var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0;
/**
* iOS requires exceptions.
*
* @type boolean
*/
var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent);
/**
* iOS 4 requires an exception for select elements.
*
* @type boolean
*/
var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);
/**
* iOS 6.0(+?) requires the target element to be manually derived
*
* @type boolean
*/
var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS ([6-9]|\d{2})_\d/).test(navigator.userAgent);
/**
* Determine whether a given element requires a native click.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element needs a native click
*/
FastClick.prototype.needsClick = function(target) {
'use strict';
switch (target.nodeName.toLowerCase()) {
// Don't send a synthetic click to disabled inputs (issue #62)
case 'button':
case 'select':
case 'textarea':
if (target.disabled) {
return true;
}
break;
case 'input':
// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
if ((deviceIsIOS && target.type === 'file') || target.disabled) {
return true;
}
break;
case 'label':
case 'video':
return true;
}
return (/\bneedsclick\b/).test(target.className);
};
/**
* Determine whether a given element requires a call to focus to simulate click into element.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
*/
FastClick.prototype.needsFocus = function(target) {
'use strict';
switch (target.nodeName.toLowerCase()) {
case 'textarea':
return true;
case 'select':
return !deviceIsAndroid;
case 'input':
switch (target.type) {
case 'button':
case 'checkbox':
case 'file':
case 'image':
case 'radio':
case 'submit':
return false;
}
// No point in attempting to focus disabled inputs
return !target.disabled && !target.readOnly;
default:
return (/\bneedsfocus\b/).test(target.className);
}
};
/**
* Send a click event to the specified element.
*
* @param {EventTarget|Element} targetElement
* @param {Event} event
*/
FastClick.prototype.sendClick = function(targetElement, event) {
'use strict';
var clickEvent, touch;
// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
if (document.activeElement && document.activeElement !== targetElement) {
document.activeElement.blur();
}
touch = event.changedTouches[0];
// Synthesise a click event, with an extra attribute so it can be tracked
clickEvent = document.createEvent('MouseEvents');
clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
clickEvent.forwardedTouchEvent = true;
targetElement.dispatchEvent(clickEvent);
};
FastClick.prototype.determineEventType = function(targetElement) {
'use strict';
//Issue #159: Android Chrome Select Box does not open with a synthetic click event
if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
return 'mousedown';
}
return 'click';
};
/**
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.focus = function(targetElement) {
'use strict';
var length;
// Issue #160: on iOS 7, some input elements (e.g. date datetime) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time') {
length = targetElement.value.length;
targetElement.setSelectionRange(length, length);
} else {
targetElement.focus();
}
};
/**
* Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
*
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.updateScrollParent = function(targetElement) {
'use strict';
var scrollParent, parentElement;
scrollParent = targetElement.fastClickScrollParent;
// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
// target element was moved to another parent.
if (!scrollParent || !scrollParent.contains(targetElement)) {
parentElement = targetElement;
do {
if (parentElement.scrollHeight > parentElement.offsetHeight) {
scrollParent = parentElement;
targetElement.fastClickScrollParent = parentElement;
break;
}
parentElement = parentElement.parentElement;
} while (parentElement);
}
// Always update the scroll top tracker if possible.
if (scrollParent) {
scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
}
};
/**
* @param {EventTarget} targetElement
* @returns {Element|EventTarget}
*/
FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
'use strict';
// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
if (eventTarget.nodeType === Node.TEXT_NODE) {
return eventTarget.parentNode;
}
return eventTarget;
};
/**
* On touch start, record the position and scroll offset.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchStart = function(event) {
'use strict';
var targetElement, touch, selection;
// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
if (event.targetTouches.length > 1) {
return true;
}
targetElement = this.getTargetElementFromEventTarget(event.target);
touch = event.targetTouches[0];
if (deviceIsIOS) {
// Only trusted events will deselect text on iOS (issue #49)
selection = window.getSelection();
if (selection.rangeCount && !selection.isCollapsed) {
return true;
}
if (!deviceIsIOS4) {
// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
// with the same identifier as the touch event that previously triggered the click that triggered the alert.
// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
if (touch.identifier === this.lastTouchIdentifier) {
event.preventDefault();
return false;
}
this.lastTouchIdentifier = touch.identifier;
// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
// 1) the user does a fling scroll on the scrollable layer
// 2) the user stops the fling scroll with another tap
// then the event.target of the last 'touchend' event will be the element that was under the user's finger
// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
this.updateScrollParent(targetElement);
}
}
this.trackingClick = true;
this.trackingClickStart = event.timeStamp;
this.targetElement = targetElement;
this.touchStartX = touch.pageX;
this.touchStartY = touch.pageY;
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
event.preventDefault();
}
return true;
};
/**
* Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.touchHasMoved = function(event) {
'use strict';
var touch = event.changedTouches[0], boundary = this.touchBoundary;
if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
return true;
}
return false;
};
/**
* Update the last position.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchMove = function(event) {
'use strict';
if (!this.trackingClick) {
return true;
}
// If the touch has moved, cancel the click tracking
if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
this.trackingClick = false;
this.targetElement = null;
}
return true;
};
/**
* Attempt to find the labelled control for the given label element.
*
* @param {EventTarget|HTMLLabelElement} labelElement
* @returns {Element|null}
*/
FastClick.prototype.findControl = function(labelElement) {
'use strict';
// Fast path for newer browsers supporting the HTML5 control attribute
if (labelElement.control !== undefined) {
return labelElement.control;
}
// All browsers under test that support touch events also support the HTML5 htmlFor attribute
if (labelElement.htmlFor) {
return document.getElementById(labelElement.htmlFor);
}
// If no for attribute exists, attempt to retrieve the first labellable descendant element
// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
};
/**
* On touch end, determine whether to send a click event at once.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchEnd = function(event) {
'use strict';
var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
if (!this.trackingClick) {
return true;
}
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
this.cancelNextClick = true;
return true;
}
// Reset to prevent wrong click cancel on input (issue #156).
this.cancelNextClick = false;
this.lastClickTime = event.timeStamp;
trackingClickStart = this.trackingClickStart;
this.trackingClick = false;
this.trackingClickStart = 0;
// On some iOS devices, the targetElement supplied with the event is invalid if the layer
// is performing a transition or scroll, and has to be re-detected manually. Note that
// for this to function correctly, it must be called *after* the event target is checked!
// See issue #57; also filed as rdar://13048589 .
if (deviceIsIOSWithBadTarget) {
touch = event.changedTouches[0];
// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
}
targetTagName = targetElement.tagName.toLowerCase();
if (targetTagName === 'label') {
forElement = this.findControl(targetElement);
if (forElement) {
this.focus(targetElement);
if (deviceIsAndroid) {
return false;
}
targetElement = forElement;
}
} else if (this.needsFocus(targetElement)) {
// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
this.targetElement = null;
return false;
}
this.focus(targetElement);
this.sendClick(targetElement, event);
// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
// Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
if (!deviceIsIOS || targetTagName !== 'select') {
this.targetElement = null;
event.preventDefault();
}
return false;
}
if (deviceIsIOS && !deviceIsIOS4) {
// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
scrollParent = targetElement.fastClickScrollParent;
if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
return true;
}
}
// Prevent the actual click from going though - unless the target node is marked as requiring
// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
if (!this.needsClick(targetElement)) {
event.preventDefault();
this.sendClick(targetElement, event);
}
return false;
};
/**
* On touch cancel, stop tracking the click.
*
* @returns {void}
*/
FastClick.prototype.onTouchCancel = function() {
'use strict';
this.trackingClick = false;
this.targetElement = null;
};
/**
* Determine mouse events which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onMouse = function(event) {
'use strict';
// If a target element was never set (because a touch event was never fired) allow the event
if (!this.targetElement) {
return true;
}
if (event.forwardedTouchEvent) {
return true;
}
// Programmatically generated events targeting a specific element should be permitted
if (!event.cancelable) {
return true;
}
// Derive and check the target element to see whether the mouse event needs to be permitted;
// unless explicitly enabled, prevent non-touch click events from triggering actions,
// to prevent ghost/doubleclicks.
if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
// Prevent any user-added listeners declared on FastClick element from being fired.
if (event.stopImmediatePropagation) {
event.stopImmediatePropagation();
} else {
// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
event.propagationStopped = true;
}
// Cancel the event
event.stopPropagation();
event.preventDefault();
return false;
}
// If the mouse event is permitted, return true for the action to go through.
return true;
};
/**
* On actual clicks, determine whether this is a touch-generated click, a click action occurring
* naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
* an actual click which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onClick = function(event) {
'use strict';
var permitted;
// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
if (this.trackingClick) {
this.targetElement = null;
this.trackingClick = false;
return true;
}
// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
if (event.target.type === 'submit' && event.detail === 0) {
return true;
}
permitted = this.onMouse(event);
// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
if (!permitted) {
this.targetElement = null;
}
// If clicks are permitted, return true for the action to go through.
return permitted;
};
/**
* Remove all FastClick's event listeners.
*
* @returns {void}
*/
FastClick.prototype.destroy = function() {
'use strict';
var layer = this.layer;
if (deviceIsAndroid) {
layer.removeEventListener('mouseover', this.onMouse, true);
layer.removeEventListener('mousedown', this.onMouse, true);
layer.removeEventListener('mouseup', this.onMouse, true);
}
layer.removeEventListener('click', this.onClick, true);
layer.removeEventListener('touchstart', this.onTouchStart, false);
layer.removeEventListener('touchmove', this.onTouchMove, false);
layer.removeEventListener('touchend', this.onTouchEnd, false);
layer.removeEventListener('touchcancel', this.onTouchCancel, false);
};
/**
* Check whether FastClick is needed.
*
* @param {Element} layer The layer to listen on
*/
FastClick.notNeeded = function(layer) {
'use strict';
var metaViewport;
var chromeVersion;
// Devices that don't support touch don't need FastClick
if (typeof window.ontouchstart === 'undefined') {
return true;
}
// Chrome version - zero for other browsers
chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
if (chromeVersion) {
if (deviceIsAndroid) {
metaViewport = document.querySelector('meta[name=viewport]');
if (metaViewport) {
// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
return true;
}
// Chrome 32 and above with width=device-width or less don't need FastClick
if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
return true;
}
}
// Chrome desktop doesn't need FastClick (issue #15)
} else {
return true;
}
}
// IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97)
if (layer.style.msTouchAction === 'none') {
return true;
}
return false;
};
/**
* Factory method for creating a FastClick object
*
* @param {Element} layer The layer to listen on
* @param {Object} options The options to override the defaults
*/
FastClick.attach = function(layer, options) {
'use strict';
return new FastClick(layer, options);
};
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// AMD. Register as an anonymous module.
define(function() {
'use strict';
return FastClick;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = FastClick.attach;
module.exports.FastClick = FastClick;
} else {
window.FastClick = FastClick;
}
|
bind
|
identifier_name
|
command.rs
|
// Copyright 2014 The Gfx-rs Developers.
//
// 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.
//! Command Buffer device interface
use std::ops::Deref;
use std::collections::hash_set::{self, HashSet};
use {Resources, IndexType, InstanceCount, VertexCount,
SubmissionResult, SubmissionError};
use {state, target, pso, shade, texture, handle};
/// A universal clear color supporting integet formats
/// as well as the standard floating-point.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum ClearColor {
/// Standard floating-point vec4 color
Float([f32; 4]),
/// Integer vector to clear ivec4 targets.
Int([i32; 4]),
/// Unsigned int vector to clear uvec4 targets.
Uint([u32; 4]),
}
/// Optional instance parameters: (instance count, buffer offset)
pub type InstanceParams = (InstanceCount, VertexCount);
/// An interface of the abstract command buffer. It collects commands in an
/// efficient API-specific manner, to be ready for execution on the device.
#[allow(missing_docs)]
pub trait Buffer<R: Resources>: Send {
/// Reset the command buffer contents, retain the allocated storage
fn reset(&mut self);
/// Bind a pipeline state object
fn bind_pipeline_state(&mut self, R::PipelineStateObject);
/// Bind a complete set of vertex buffers
fn bind_vertex_buffers(&mut self, pso::VertexBufferSet<R>);
/// Bind a complete set of constant buffers
fn bind_constant_buffers(&mut self, &[pso::ConstantBufferParam<R>]);
/// Bind a global constant
fn bind_global_constant(&mut self, shade::Location, shade::UniformValue);
/// Bind a complete set of shader resource views
fn bind_resource_views(&mut self, &[pso::ResourceViewParam<R>]);
/// Bind a complete set of unordered access views
fn bind_unordered_views(&mut self, &[pso::UnorderedViewParam<R>]);
/// Bind a complete set of samplers
fn bind_samplers(&mut self, &[pso::SamplerParam<R>]);
/// Bind a complete set of pixel targets, including multiple
/// colors views and an optional depth/stencil view.
fn bind_pixel_targets(&mut self, pso::PixelTargetSet<R>);
/// Bind an index buffer
fn bind_index(&mut self, R::Buffer, IndexType);
/// Set scissor rectangle
fn set_scissor(&mut self, target::Rect);
/// Set reference values for the blending and stencil front/back
fn set_ref_values(&mut self, state::RefValues);
/// Copy part of a buffer to another
fn copy_buffer(&mut self, src: R::Buffer, dst: R::Buffer,
src_offset_bytes: usize, dst_offset_bytes: usize,
size_bytes: usize);
/// Copy part of a buffer to a texture
fn copy_buffer_to_texture(&mut self,
src: R::Buffer, src_offset_bytes: usize,
dst: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo);
/// Copy part of a texture to a buffer
fn copy_texture_to_buffer(&mut self,
src: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo,
dst: R::Buffer, dst_offset_bytes: usize);
/// Update a vertex/index/uniform buffer
fn update_buffer(&mut self, R::Buffer, data: &[u8], offset: usize);
/// Update a texture
fn update_texture(&mut self, R::Texture, texture::Kind, Option<texture::CubeFace>,
data: &[u8], texture::RawImageInfo);
fn generate_mipmap(&mut self, R::ShaderResourceView);
/// Clear color target
fn clear_color(&mut self, R::RenderTargetView, ClearColor);
fn clear_depth_stencil(&mut self, R::DepthStencilView,
Option<target::Depth>, Option<target::Stencil>);
/// Draw a primitive
fn call_draw(&mut self, VertexCount, VertexCount, Option<InstanceParams>);
/// Draw a primitive with index buffer
fn call_draw_indexed(&mut self, VertexCount, VertexCount, VertexCount, Option<InstanceParams>);
}
macro_rules! impl_clear {
{ $( $ty:ty = $sub:ident[$a:expr, $b:expr, $c:expr, $d:expr], )* } => {
$(
impl From<$ty> for ClearColor {
fn from(v: $ty) -> ClearColor {
ClearColor::$sub([v[$a], v[$b], v[$c], v[$d]])
}
}
)*
}
}
impl_clear! {
[f32; 4] = Float[0, 1, 2, 3],
[f32; 3] = Float[0, 1, 2, 0],
[f32; 2] = Float[0, 1, 0, 0],
[i32; 4] = Int [0, 1, 2, 3],
[i32; 3] = Int [0, 1, 2, 0],
[i32; 2] = Int [0, 1, 0, 0],
[u32; 4] = Uint [0, 1, 2, 3],
[u32; 3] = Uint [0, 1, 2, 0],
[u32; 2] = Uint [0, 1, 0, 0],
}
impl From<f32> for ClearColor {
fn from(v: f32) -> ClearColor {
ClearColor::Float([v, 0.0, 0.0, 0.0])
}
}
impl From<i32> for ClearColor {
fn from(v: i32) -> ClearColor {
ClearColor::Int([v, 0, 0, 0])
}
}
impl From<u32> for ClearColor {
fn from(v: u32) -> ClearColor {
ClearColor::Uint([v, 0, 0, 0])
}
}
/// Informations about what is accessed by a bunch of commands.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccessInfo<R: Resources> {
mapped_reads: HashSet<handle::RawBuffer<R>>,
mapped_writes: HashSet<handle::RawBuffer<R>>,
}
impl<R: Resources> AccessInfo<R> {
/// Creates empty access informations
pub fn new() -> Self {
AccessInfo {
mapped_reads: HashSet::new(),
mapped_writes: HashSet::new(),
}
}
/// Clear access informations
pub fn clear(&mut self) {
self.mapped_reads.clear();
self.mapped_writes.clear();
}
/// Register a buffer read access
pub fn buffer_read(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_reads.insert(buffer.clone());
}
}
/// Register a buffer write access
pub fn buffer_write(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped()
|
}
/// Returns the mapped buffers that The GPU will read from
pub fn mapped_reads(&self) -> AccessInfoBuffers<R> {
self.mapped_reads.iter()
}
/// Returns the mapped buffers that The GPU will write to
pub fn mapped_writes(&self) -> AccessInfoBuffers<R> {
self.mapped_writes.iter()
}
/// Is there any mapped buffer reads ?
pub fn has_mapped_reads(&self) -> bool {
!self.mapped_reads.is_empty()
}
/// Is there any mapped buffer writes ?
pub fn has_mapped_writes(&self) -> bool {
!self.mapped_writes.is_empty()
}
/// Takes all the accesses necessary for submission
pub fn take_accesses(&self) -> SubmissionResult<AccessGuard<R>> {
for buffer in self.mapped_reads().chain(self.mapped_writes()) {
unsafe {
if !buffer.mapping().unwrap().take_access() {
return Err(SubmissionError::AccessOverlap);
}
}
}
Ok(AccessGuard { inner: self })
}
}
#[allow(missing_docs)]
pub type AccessInfoBuffers<'a, R> = hash_set::Iter<'a, handle::RawBuffer<R>>;
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuard<'a, R: Resources> {
inner: &'a AccessInfo<R>,
}
#[allow(missing_docs)]
impl<'a, R: Resources> AccessGuard<'a, R> {
/// Returns the mapped buffers that The GPU will read from,
/// with exclusive acces to their mapping
pub fn access_mapped_reads(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_reads()
}
}
/// Returns the mapped buffers that The GPU will write to,
/// with exclusive acces to their mapping
pub fn access_mapped_writes(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_writes()
}
}
pub fn access_mapped(&mut self) -> AccessGuardBuffersChain<R> {
AccessGuardBuffersChain {
fst: self.inner.mapped_reads(),
snd: self.inner.mapped_writes(),
}
}
}
impl<'a, R: Resources> Deref for AccessGuard<'a, R> {
type Target = AccessInfo<R>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<'a, R: Resources> Drop for AccessGuard<'a, R> {
fn drop(&mut self) {
for buffer in self.inner.mapped_reads().chain(self.inner.mapped_writes()) {
unsafe {
buffer.mapping().unwrap().release_access();
}
}
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffers<'a, R: Resources> {
buffers: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffers<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.buffers.next().map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffersChain<'a, R: Resources> {
fst: AccessInfoBuffers<'a, R>,
snd: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffersChain<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.fst.next().or_else(|| self.snd.next())
.map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
}
|
{
self.mapped_writes.insert(buffer.clone());
}
|
conditional_block
|
command.rs
|
// Copyright 2014 The Gfx-rs Developers.
//
// 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.
//! Command Buffer device interface
use std::ops::Deref;
use std::collections::hash_set::{self, HashSet};
use {Resources, IndexType, InstanceCount, VertexCount,
SubmissionResult, SubmissionError};
use {state, target, pso, shade, texture, handle};
/// A universal clear color supporting integet formats
/// as well as the standard floating-point.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum ClearColor {
/// Standard floating-point vec4 color
Float([f32; 4]),
/// Integer vector to clear ivec4 targets.
Int([i32; 4]),
/// Unsigned int vector to clear uvec4 targets.
Uint([u32; 4]),
}
/// Optional instance parameters: (instance count, buffer offset)
pub type InstanceParams = (InstanceCount, VertexCount);
/// An interface of the abstract command buffer. It collects commands in an
/// efficient API-specific manner, to be ready for execution on the device.
#[allow(missing_docs)]
pub trait Buffer<R: Resources>: Send {
/// Reset the command buffer contents, retain the allocated storage
fn reset(&mut self);
/// Bind a pipeline state object
fn bind_pipeline_state(&mut self, R::PipelineStateObject);
/// Bind a complete set of vertex buffers
fn bind_vertex_buffers(&mut self, pso::VertexBufferSet<R>);
/// Bind a complete set of constant buffers
fn bind_constant_buffers(&mut self, &[pso::ConstantBufferParam<R>]);
/// Bind a global constant
fn bind_global_constant(&mut self, shade::Location, shade::UniformValue);
/// Bind a complete set of shader resource views
fn bind_resource_views(&mut self, &[pso::ResourceViewParam<R>]);
/// Bind a complete set of unordered access views
fn bind_unordered_views(&mut self, &[pso::UnorderedViewParam<R>]);
/// Bind a complete set of samplers
fn bind_samplers(&mut self, &[pso::SamplerParam<R>]);
/// Bind a complete set of pixel targets, including multiple
/// colors views and an optional depth/stencil view.
fn bind_pixel_targets(&mut self, pso::PixelTargetSet<R>);
/// Bind an index buffer
fn bind_index(&mut self, R::Buffer, IndexType);
/// Set scissor rectangle
fn set_scissor(&mut self, target::Rect);
/// Set reference values for the blending and stencil front/back
fn set_ref_values(&mut self, state::RefValues);
/// Copy part of a buffer to another
fn copy_buffer(&mut self, src: R::Buffer, dst: R::Buffer,
src_offset_bytes: usize, dst_offset_bytes: usize,
size_bytes: usize);
/// Copy part of a buffer to a texture
fn copy_buffer_to_texture(&mut self,
src: R::Buffer, src_offset_bytes: usize,
dst: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo);
/// Copy part of a texture to a buffer
fn copy_texture_to_buffer(&mut self,
src: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo,
dst: R::Buffer, dst_offset_bytes: usize);
/// Update a vertex/index/uniform buffer
fn update_buffer(&mut self, R::Buffer, data: &[u8], offset: usize);
/// Update a texture
fn update_texture(&mut self, R::Texture, texture::Kind, Option<texture::CubeFace>,
data: &[u8], texture::RawImageInfo);
|
fn generate_mipmap(&mut self, R::ShaderResourceView);
/// Clear color target
fn clear_color(&mut self, R::RenderTargetView, ClearColor);
fn clear_depth_stencil(&mut self, R::DepthStencilView,
Option<target::Depth>, Option<target::Stencil>);
/// Draw a primitive
fn call_draw(&mut self, VertexCount, VertexCount, Option<InstanceParams>);
/// Draw a primitive with index buffer
fn call_draw_indexed(&mut self, VertexCount, VertexCount, VertexCount, Option<InstanceParams>);
}
macro_rules! impl_clear {
{ $( $ty:ty = $sub:ident[$a:expr, $b:expr, $c:expr, $d:expr], )* } => {
$(
impl From<$ty> for ClearColor {
fn from(v: $ty) -> ClearColor {
ClearColor::$sub([v[$a], v[$b], v[$c], v[$d]])
}
}
)*
}
}
impl_clear! {
[f32; 4] = Float[0, 1, 2, 3],
[f32; 3] = Float[0, 1, 2, 0],
[f32; 2] = Float[0, 1, 0, 0],
[i32; 4] = Int [0, 1, 2, 3],
[i32; 3] = Int [0, 1, 2, 0],
[i32; 2] = Int [0, 1, 0, 0],
[u32; 4] = Uint [0, 1, 2, 3],
[u32; 3] = Uint [0, 1, 2, 0],
[u32; 2] = Uint [0, 1, 0, 0],
}
impl From<f32> for ClearColor {
fn from(v: f32) -> ClearColor {
ClearColor::Float([v, 0.0, 0.0, 0.0])
}
}
impl From<i32> for ClearColor {
fn from(v: i32) -> ClearColor {
ClearColor::Int([v, 0, 0, 0])
}
}
impl From<u32> for ClearColor {
fn from(v: u32) -> ClearColor {
ClearColor::Uint([v, 0, 0, 0])
}
}
/// Informations about what is accessed by a bunch of commands.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccessInfo<R: Resources> {
mapped_reads: HashSet<handle::RawBuffer<R>>,
mapped_writes: HashSet<handle::RawBuffer<R>>,
}
impl<R: Resources> AccessInfo<R> {
/// Creates empty access informations
pub fn new() -> Self {
AccessInfo {
mapped_reads: HashSet::new(),
mapped_writes: HashSet::new(),
}
}
/// Clear access informations
pub fn clear(&mut self) {
self.mapped_reads.clear();
self.mapped_writes.clear();
}
/// Register a buffer read access
pub fn buffer_read(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_reads.insert(buffer.clone());
}
}
/// Register a buffer write access
pub fn buffer_write(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_writes.insert(buffer.clone());
}
}
/// Returns the mapped buffers that The GPU will read from
pub fn mapped_reads(&self) -> AccessInfoBuffers<R> {
self.mapped_reads.iter()
}
/// Returns the mapped buffers that The GPU will write to
pub fn mapped_writes(&self) -> AccessInfoBuffers<R> {
self.mapped_writes.iter()
}
/// Is there any mapped buffer reads ?
pub fn has_mapped_reads(&self) -> bool {
!self.mapped_reads.is_empty()
}
/// Is there any mapped buffer writes ?
pub fn has_mapped_writes(&self) -> bool {
!self.mapped_writes.is_empty()
}
/// Takes all the accesses necessary for submission
pub fn take_accesses(&self) -> SubmissionResult<AccessGuard<R>> {
for buffer in self.mapped_reads().chain(self.mapped_writes()) {
unsafe {
if !buffer.mapping().unwrap().take_access() {
return Err(SubmissionError::AccessOverlap);
}
}
}
Ok(AccessGuard { inner: self })
}
}
#[allow(missing_docs)]
pub type AccessInfoBuffers<'a, R> = hash_set::Iter<'a, handle::RawBuffer<R>>;
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuard<'a, R: Resources> {
inner: &'a AccessInfo<R>,
}
#[allow(missing_docs)]
impl<'a, R: Resources> AccessGuard<'a, R> {
/// Returns the mapped buffers that The GPU will read from,
/// with exclusive acces to their mapping
pub fn access_mapped_reads(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_reads()
}
}
/// Returns the mapped buffers that The GPU will write to,
/// with exclusive acces to their mapping
pub fn access_mapped_writes(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_writes()
}
}
pub fn access_mapped(&mut self) -> AccessGuardBuffersChain<R> {
AccessGuardBuffersChain {
fst: self.inner.mapped_reads(),
snd: self.inner.mapped_writes(),
}
}
}
impl<'a, R: Resources> Deref for AccessGuard<'a, R> {
type Target = AccessInfo<R>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<'a, R: Resources> Drop for AccessGuard<'a, R> {
fn drop(&mut self) {
for buffer in self.inner.mapped_reads().chain(self.inner.mapped_writes()) {
unsafe {
buffer.mapping().unwrap().release_access();
}
}
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffers<'a, R: Resources> {
buffers: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffers<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.buffers.next().map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffersChain<'a, R: Resources> {
fst: AccessInfoBuffers<'a, R>,
snd: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffersChain<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.fst.next().or_else(|| self.snd.next())
.map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
}
|
random_line_split
|
|
command.rs
|
// Copyright 2014 The Gfx-rs Developers.
//
// 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.
//! Command Buffer device interface
use std::ops::Deref;
use std::collections::hash_set::{self, HashSet};
use {Resources, IndexType, InstanceCount, VertexCount,
SubmissionResult, SubmissionError};
use {state, target, pso, shade, texture, handle};
/// A universal clear color supporting integet formats
/// as well as the standard floating-point.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum ClearColor {
/// Standard floating-point vec4 color
Float([f32; 4]),
/// Integer vector to clear ivec4 targets.
Int([i32; 4]),
/// Unsigned int vector to clear uvec4 targets.
Uint([u32; 4]),
}
/// Optional instance parameters: (instance count, buffer offset)
pub type InstanceParams = (InstanceCount, VertexCount);
/// An interface of the abstract command buffer. It collects commands in an
/// efficient API-specific manner, to be ready for execution on the device.
#[allow(missing_docs)]
pub trait Buffer<R: Resources>: Send {
/// Reset the command buffer contents, retain the allocated storage
fn reset(&mut self);
/// Bind a pipeline state object
fn bind_pipeline_state(&mut self, R::PipelineStateObject);
/// Bind a complete set of vertex buffers
fn bind_vertex_buffers(&mut self, pso::VertexBufferSet<R>);
/// Bind a complete set of constant buffers
fn bind_constant_buffers(&mut self, &[pso::ConstantBufferParam<R>]);
/// Bind a global constant
fn bind_global_constant(&mut self, shade::Location, shade::UniformValue);
/// Bind a complete set of shader resource views
fn bind_resource_views(&mut self, &[pso::ResourceViewParam<R>]);
/// Bind a complete set of unordered access views
fn bind_unordered_views(&mut self, &[pso::UnorderedViewParam<R>]);
/// Bind a complete set of samplers
fn bind_samplers(&mut self, &[pso::SamplerParam<R>]);
/// Bind a complete set of pixel targets, including multiple
/// colors views and an optional depth/stencil view.
fn bind_pixel_targets(&mut self, pso::PixelTargetSet<R>);
/// Bind an index buffer
fn bind_index(&mut self, R::Buffer, IndexType);
/// Set scissor rectangle
fn set_scissor(&mut self, target::Rect);
/// Set reference values for the blending and stencil front/back
fn set_ref_values(&mut self, state::RefValues);
/// Copy part of a buffer to another
fn copy_buffer(&mut self, src: R::Buffer, dst: R::Buffer,
src_offset_bytes: usize, dst_offset_bytes: usize,
size_bytes: usize);
/// Copy part of a buffer to a texture
fn copy_buffer_to_texture(&mut self,
src: R::Buffer, src_offset_bytes: usize,
dst: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo);
/// Copy part of a texture to a buffer
fn copy_texture_to_buffer(&mut self,
src: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo,
dst: R::Buffer, dst_offset_bytes: usize);
/// Update a vertex/index/uniform buffer
fn update_buffer(&mut self, R::Buffer, data: &[u8], offset: usize);
/// Update a texture
fn update_texture(&mut self, R::Texture, texture::Kind, Option<texture::CubeFace>,
data: &[u8], texture::RawImageInfo);
fn generate_mipmap(&mut self, R::ShaderResourceView);
/// Clear color target
fn clear_color(&mut self, R::RenderTargetView, ClearColor);
fn clear_depth_stencil(&mut self, R::DepthStencilView,
Option<target::Depth>, Option<target::Stencil>);
/// Draw a primitive
fn call_draw(&mut self, VertexCount, VertexCount, Option<InstanceParams>);
/// Draw a primitive with index buffer
fn call_draw_indexed(&mut self, VertexCount, VertexCount, VertexCount, Option<InstanceParams>);
}
macro_rules! impl_clear {
{ $( $ty:ty = $sub:ident[$a:expr, $b:expr, $c:expr, $d:expr], )* } => {
$(
impl From<$ty> for ClearColor {
fn from(v: $ty) -> ClearColor {
ClearColor::$sub([v[$a], v[$b], v[$c], v[$d]])
}
}
)*
}
}
impl_clear! {
[f32; 4] = Float[0, 1, 2, 3],
[f32; 3] = Float[0, 1, 2, 0],
[f32; 2] = Float[0, 1, 0, 0],
[i32; 4] = Int [0, 1, 2, 3],
[i32; 3] = Int [0, 1, 2, 0],
[i32; 2] = Int [0, 1, 0, 0],
[u32; 4] = Uint [0, 1, 2, 3],
[u32; 3] = Uint [0, 1, 2, 0],
[u32; 2] = Uint [0, 1, 0, 0],
}
impl From<f32> for ClearColor {
fn from(v: f32) -> ClearColor {
ClearColor::Float([v, 0.0, 0.0, 0.0])
}
}
impl From<i32> for ClearColor {
fn from(v: i32) -> ClearColor {
ClearColor::Int([v, 0, 0, 0])
}
}
impl From<u32> for ClearColor {
fn from(v: u32) -> ClearColor {
ClearColor::Uint([v, 0, 0, 0])
}
}
/// Informations about what is accessed by a bunch of commands.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccessInfo<R: Resources> {
mapped_reads: HashSet<handle::RawBuffer<R>>,
mapped_writes: HashSet<handle::RawBuffer<R>>,
}
impl<R: Resources> AccessInfo<R> {
/// Creates empty access informations
pub fn new() -> Self {
AccessInfo {
mapped_reads: HashSet::new(),
mapped_writes: HashSet::new(),
}
}
/// Clear access informations
pub fn clear(&mut self) {
self.mapped_reads.clear();
self.mapped_writes.clear();
}
/// Register a buffer read access
pub fn buffer_read(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_reads.insert(buffer.clone());
}
}
/// Register a buffer write access
pub fn buffer_write(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_writes.insert(buffer.clone());
}
}
/// Returns the mapped buffers that The GPU will read from
pub fn mapped_reads(&self) -> AccessInfoBuffers<R>
|
/// Returns the mapped buffers that The GPU will write to
pub fn mapped_writes(&self) -> AccessInfoBuffers<R> {
self.mapped_writes.iter()
}
/// Is there any mapped buffer reads ?
pub fn has_mapped_reads(&self) -> bool {
!self.mapped_reads.is_empty()
}
/// Is there any mapped buffer writes ?
pub fn has_mapped_writes(&self) -> bool {
!self.mapped_writes.is_empty()
}
/// Takes all the accesses necessary for submission
pub fn take_accesses(&self) -> SubmissionResult<AccessGuard<R>> {
for buffer in self.mapped_reads().chain(self.mapped_writes()) {
unsafe {
if !buffer.mapping().unwrap().take_access() {
return Err(SubmissionError::AccessOverlap);
}
}
}
Ok(AccessGuard { inner: self })
}
}
#[allow(missing_docs)]
pub type AccessInfoBuffers<'a, R> = hash_set::Iter<'a, handle::RawBuffer<R>>;
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuard<'a, R: Resources> {
inner: &'a AccessInfo<R>,
}
#[allow(missing_docs)]
impl<'a, R: Resources> AccessGuard<'a, R> {
/// Returns the mapped buffers that The GPU will read from,
/// with exclusive acces to their mapping
pub fn access_mapped_reads(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_reads()
}
}
/// Returns the mapped buffers that The GPU will write to,
/// with exclusive acces to their mapping
pub fn access_mapped_writes(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_writes()
}
}
pub fn access_mapped(&mut self) -> AccessGuardBuffersChain<R> {
AccessGuardBuffersChain {
fst: self.inner.mapped_reads(),
snd: self.inner.mapped_writes(),
}
}
}
impl<'a, R: Resources> Deref for AccessGuard<'a, R> {
type Target = AccessInfo<R>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<'a, R: Resources> Drop for AccessGuard<'a, R> {
fn drop(&mut self) {
for buffer in self.inner.mapped_reads().chain(self.inner.mapped_writes()) {
unsafe {
buffer.mapping().unwrap().release_access();
}
}
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffers<'a, R: Resources> {
buffers: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffers<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.buffers.next().map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffersChain<'a, R: Resources> {
fst: AccessInfoBuffers<'a, R>,
snd: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffersChain<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.fst.next().or_else(|| self.snd.next())
.map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
}
|
{
self.mapped_reads.iter()
}
|
identifier_body
|
command.rs
|
// Copyright 2014 The Gfx-rs Developers.
//
// 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.
//! Command Buffer device interface
use std::ops::Deref;
use std::collections::hash_set::{self, HashSet};
use {Resources, IndexType, InstanceCount, VertexCount,
SubmissionResult, SubmissionError};
use {state, target, pso, shade, texture, handle};
/// A universal clear color supporting integet formats
/// as well as the standard floating-point.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum ClearColor {
/// Standard floating-point vec4 color
Float([f32; 4]),
/// Integer vector to clear ivec4 targets.
Int([i32; 4]),
/// Unsigned int vector to clear uvec4 targets.
Uint([u32; 4]),
}
/// Optional instance parameters: (instance count, buffer offset)
pub type InstanceParams = (InstanceCount, VertexCount);
/// An interface of the abstract command buffer. It collects commands in an
/// efficient API-specific manner, to be ready for execution on the device.
#[allow(missing_docs)]
pub trait Buffer<R: Resources>: Send {
/// Reset the command buffer contents, retain the allocated storage
fn reset(&mut self);
/// Bind a pipeline state object
fn bind_pipeline_state(&mut self, R::PipelineStateObject);
/// Bind a complete set of vertex buffers
fn bind_vertex_buffers(&mut self, pso::VertexBufferSet<R>);
/// Bind a complete set of constant buffers
fn bind_constant_buffers(&mut self, &[pso::ConstantBufferParam<R>]);
/// Bind a global constant
fn bind_global_constant(&mut self, shade::Location, shade::UniformValue);
/// Bind a complete set of shader resource views
fn bind_resource_views(&mut self, &[pso::ResourceViewParam<R>]);
/// Bind a complete set of unordered access views
fn bind_unordered_views(&mut self, &[pso::UnorderedViewParam<R>]);
/// Bind a complete set of samplers
fn bind_samplers(&mut self, &[pso::SamplerParam<R>]);
/// Bind a complete set of pixel targets, including multiple
/// colors views and an optional depth/stencil view.
fn bind_pixel_targets(&mut self, pso::PixelTargetSet<R>);
/// Bind an index buffer
fn bind_index(&mut self, R::Buffer, IndexType);
/// Set scissor rectangle
fn set_scissor(&mut self, target::Rect);
/// Set reference values for the blending and stencil front/back
fn set_ref_values(&mut self, state::RefValues);
/// Copy part of a buffer to another
fn copy_buffer(&mut self, src: R::Buffer, dst: R::Buffer,
src_offset_bytes: usize, dst_offset_bytes: usize,
size_bytes: usize);
/// Copy part of a buffer to a texture
fn copy_buffer_to_texture(&mut self,
src: R::Buffer, src_offset_bytes: usize,
dst: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo);
/// Copy part of a texture to a buffer
fn copy_texture_to_buffer(&mut self,
src: R::Texture, texture::Kind,
Option<texture::CubeFace>, texture::RawImageInfo,
dst: R::Buffer, dst_offset_bytes: usize);
/// Update a vertex/index/uniform buffer
fn update_buffer(&mut self, R::Buffer, data: &[u8], offset: usize);
/// Update a texture
fn update_texture(&mut self, R::Texture, texture::Kind, Option<texture::CubeFace>,
data: &[u8], texture::RawImageInfo);
fn generate_mipmap(&mut self, R::ShaderResourceView);
/// Clear color target
fn clear_color(&mut self, R::RenderTargetView, ClearColor);
fn clear_depth_stencil(&mut self, R::DepthStencilView,
Option<target::Depth>, Option<target::Stencil>);
/// Draw a primitive
fn call_draw(&mut self, VertexCount, VertexCount, Option<InstanceParams>);
/// Draw a primitive with index buffer
fn call_draw_indexed(&mut self, VertexCount, VertexCount, VertexCount, Option<InstanceParams>);
}
macro_rules! impl_clear {
{ $( $ty:ty = $sub:ident[$a:expr, $b:expr, $c:expr, $d:expr], )* } => {
$(
impl From<$ty> for ClearColor {
fn from(v: $ty) -> ClearColor {
ClearColor::$sub([v[$a], v[$b], v[$c], v[$d]])
}
}
)*
}
}
impl_clear! {
[f32; 4] = Float[0, 1, 2, 3],
[f32; 3] = Float[0, 1, 2, 0],
[f32; 2] = Float[0, 1, 0, 0],
[i32; 4] = Int [0, 1, 2, 3],
[i32; 3] = Int [0, 1, 2, 0],
[i32; 2] = Int [0, 1, 0, 0],
[u32; 4] = Uint [0, 1, 2, 3],
[u32; 3] = Uint [0, 1, 2, 0],
[u32; 2] = Uint [0, 1, 0, 0],
}
impl From<f32> for ClearColor {
fn from(v: f32) -> ClearColor {
ClearColor::Float([v, 0.0, 0.0, 0.0])
}
}
impl From<i32> for ClearColor {
fn from(v: i32) -> ClearColor {
ClearColor::Int([v, 0, 0, 0])
}
}
impl From<u32> for ClearColor {
fn from(v: u32) -> ClearColor {
ClearColor::Uint([v, 0, 0, 0])
}
}
/// Informations about what is accessed by a bunch of commands.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccessInfo<R: Resources> {
mapped_reads: HashSet<handle::RawBuffer<R>>,
mapped_writes: HashSet<handle::RawBuffer<R>>,
}
impl<R: Resources> AccessInfo<R> {
/// Creates empty access informations
pub fn new() -> Self {
AccessInfo {
mapped_reads: HashSet::new(),
mapped_writes: HashSet::new(),
}
}
/// Clear access informations
pub fn clear(&mut self) {
self.mapped_reads.clear();
self.mapped_writes.clear();
}
/// Register a buffer read access
pub fn buffer_read(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_reads.insert(buffer.clone());
}
}
/// Register a buffer write access
pub fn buffer_write(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_writes.insert(buffer.clone());
}
}
/// Returns the mapped buffers that The GPU will read from
pub fn mapped_reads(&self) -> AccessInfoBuffers<R> {
self.mapped_reads.iter()
}
/// Returns the mapped buffers that The GPU will write to
pub fn mapped_writes(&self) -> AccessInfoBuffers<R> {
self.mapped_writes.iter()
}
/// Is there any mapped buffer reads ?
pub fn has_mapped_reads(&self) -> bool {
!self.mapped_reads.is_empty()
}
/// Is there any mapped buffer writes ?
pub fn
|
(&self) -> bool {
!self.mapped_writes.is_empty()
}
/// Takes all the accesses necessary for submission
pub fn take_accesses(&self) -> SubmissionResult<AccessGuard<R>> {
for buffer in self.mapped_reads().chain(self.mapped_writes()) {
unsafe {
if !buffer.mapping().unwrap().take_access() {
return Err(SubmissionError::AccessOverlap);
}
}
}
Ok(AccessGuard { inner: self })
}
}
#[allow(missing_docs)]
pub type AccessInfoBuffers<'a, R> = hash_set::Iter<'a, handle::RawBuffer<R>>;
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuard<'a, R: Resources> {
inner: &'a AccessInfo<R>,
}
#[allow(missing_docs)]
impl<'a, R: Resources> AccessGuard<'a, R> {
/// Returns the mapped buffers that The GPU will read from,
/// with exclusive acces to their mapping
pub fn access_mapped_reads(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_reads()
}
}
/// Returns the mapped buffers that The GPU will write to,
/// with exclusive acces to their mapping
pub fn access_mapped_writes(&mut self) -> AccessGuardBuffers<R> {
AccessGuardBuffers {
buffers: self.inner.mapped_writes()
}
}
pub fn access_mapped(&mut self) -> AccessGuardBuffersChain<R> {
AccessGuardBuffersChain {
fst: self.inner.mapped_reads(),
snd: self.inner.mapped_writes(),
}
}
}
impl<'a, R: Resources> Deref for AccessGuard<'a, R> {
type Target = AccessInfo<R>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<'a, R: Resources> Drop for AccessGuard<'a, R> {
fn drop(&mut self) {
for buffer in self.inner.mapped_reads().chain(self.inner.mapped_writes()) {
unsafe {
buffer.mapping().unwrap().release_access();
}
}
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffers<'a, R: Resources> {
buffers: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffers<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.buffers.next().map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct AccessGuardBuffersChain<'a, R: Resources> {
fst: AccessInfoBuffers<'a, R>,
snd: AccessInfoBuffers<'a, R>
}
impl<'a, R: Resources> Iterator for AccessGuardBuffersChain<'a, R> {
type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping);
fn next(&mut self) -> Option<Self::Item> {
self.fst.next().or_else(|| self.snd.next())
.map(|buffer| unsafe {
(buffer, buffer.mapping().unwrap().use_access())
})
}
}
|
has_mapped_writes
|
identifier_name
|
app.py
|
from flask import Flask
app = Flask(__name__)
from media import Movie
from flask import render_template
import re
@app.route('/')
def
|
():
'''View function for index page.'''
toy_story = Movie(title = "Toy Story 3", trailer_youtube_url ="https://www.youtube.com/watch?v=QW0sjQFpXTU",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMTgxOTY4Mjc0MF5BMl5BanBnXkFtZTcwNTA4MDQyMw@@._V1_UY268_CR3,0,182,268_AL_.jpg",
storyline='''Andy's toys get mistakenly delivered to a day care centre.
Woody convinces the other toys that they weren't dumped and leads them on an expedition back
home.''')
pulp_fiction = Movie(title = "Pulp Fiction ", trailer_youtube_url ="https://www.youtube.com/watch?v=s7EdQ4FqbhY",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMTkxMTA5OTAzMl5BMl5BanBnXkFtZTgwNjA5MDc3NjE@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''The lives of two mob hit men, a boxer, a gangster's wife, and a pair of diner bandits
intertwine in four tales of violence and redemption''')
shawshank = Movie(title = "The Shawshank Redemption", trailer_youtube_url ="https://www.youtube.com/watch?v=KtwXlIwozog",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''Two imprisoned men bond over a number of years, finding solace
and eventual redemption through acts of common decency.''')
godfather = Movie(title = "The Godfather ", trailer_youtube_url ="https://www.youtube.com/watch?v=sY1S34973zA",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMjEyMjcyNDI4MF5BMl5BanBnXkFtZTcwMDA5Mzg3OA@@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.''')
dark_knight = Movie(title = "The Dark Knight ", trailer_youtube_url ="https://www.youtube.com/watch?v=EXeTwQWrcwY",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''Set within a year after the events of Batman Begins, Batman, Lieutenant James Gordon, and new district attorney Harvey Dent successfully begin to round up the criminals''')
movies=[toy_story,pulp_fiction,dark_knight,godfather,shawshank]
# Replace `Youtube URL` with just `Youtube video ID`
for movie in movies:
youtube_id_match = re.search(r'(?<=v=)[^&#]+', movie.trailer_youtube_url)
youtube_id_match = youtube_id_match or re.search(r'(?<=be/)[^&#]+', movie.trailer_youtube_url)
trailer_youtube_id = (youtube_id_match.group(0) if youtube_id_match else None)
movie.trailer_youtube_url = trailer_youtube_id
return render_template('index.html',
data=movies)
if __name__ == '__main__':
app.run(debug=True)
|
index
|
identifier_name
|
app.py
|
from flask import Flask
app = Flask(__name__)
from media import Movie
from flask import render_template
import re
@app.route('/')
def index():
'''View function for index page.'''
toy_story = Movie(title = "Toy Story 3", trailer_youtube_url ="https://www.youtube.com/watch?v=QW0sjQFpXTU",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMTgxOTY4Mjc0MF5BMl5BanBnXkFtZTcwNTA4MDQyMw@@._V1_UY268_CR3,0,182,268_AL_.jpg",
storyline='''Andy's toys get mistakenly delivered to a day care centre.
Woody convinces the other toys that they weren't dumped and leads them on an expedition back
home.''')
pulp_fiction = Movie(title = "Pulp Fiction ", trailer_youtube_url ="https://www.youtube.com/watch?v=s7EdQ4FqbhY",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMTkxMTA5OTAzMl5BMl5BanBnXkFtZTgwNjA5MDc3NjE@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''The lives of two mob hit men, a boxer, a gangster's wife, and a pair of diner bandits
intertwine in four tales of violence and redemption''')
shawshank = Movie(title = "The Shawshank Redemption", trailer_youtube_url ="https://www.youtube.com/watch?v=KtwXlIwozog",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''Two imprisoned men bond over a number of years, finding solace
and eventual redemption through acts of common decency.''')
godfather = Movie(title = "The Godfather ", trailer_youtube_url ="https://www.youtube.com/watch?v=sY1S34973zA",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMjEyMjcyNDI4MF5BMl5BanBnXkFtZTcwMDA5Mzg3OA@@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.''')
dark_knight = Movie(title = "The Dark Knight ", trailer_youtube_url ="https://www.youtube.com/watch?v=EXeTwQWrcwY",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''Set within a year after the events of Batman Begins, Batman, Lieutenant James Gordon, and new district attorney Harvey Dent successfully begin to round up the criminals''')
movies=[toy_story,pulp_fiction,dark_knight,godfather,shawshank]
# Replace `Youtube URL` with just `Youtube video ID`
for movie in movies:
|
return render_template('index.html',
data=movies)
if __name__ == '__main__':
app.run(debug=True)
|
youtube_id_match = re.search(r'(?<=v=)[^&#]+', movie.trailer_youtube_url)
youtube_id_match = youtube_id_match or re.search(r'(?<=be/)[^&#]+', movie.trailer_youtube_url)
trailer_youtube_id = (youtube_id_match.group(0) if youtube_id_match else None)
movie.trailer_youtube_url = trailer_youtube_id
|
conditional_block
|
app.py
|
from flask import Flask
app = Flask(__name__)
from media import Movie
from flask import render_template
import re
@app.route('/')
def index():
'''View function for index page.'''
|
storyline='''Andy's toys get mistakenly delivered to a day care centre.
Woody convinces the other toys that they weren't dumped and leads them on an expedition back
home.''')
pulp_fiction = Movie(title = "Pulp Fiction ", trailer_youtube_url ="https://www.youtube.com/watch?v=s7EdQ4FqbhY",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMTkxMTA5OTAzMl5BMl5BanBnXkFtZTgwNjA5MDc3NjE@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''The lives of two mob hit men, a boxer, a gangster's wife, and a pair of diner bandits
intertwine in four tales of violence and redemption''')
shawshank = Movie(title = "The Shawshank Redemption", trailer_youtube_url ="https://www.youtube.com/watch?v=KtwXlIwozog",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''Two imprisoned men bond over a number of years, finding solace
and eventual redemption through acts of common decency.''')
godfather = Movie(title = "The Godfather ", trailer_youtube_url ="https://www.youtube.com/watch?v=sY1S34973zA",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMjEyMjcyNDI4MF5BMl5BanBnXkFtZTcwMDA5Mzg3OA@@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.''')
dark_knight = Movie(title = "The Dark Knight ", trailer_youtube_url ="https://www.youtube.com/watch?v=EXeTwQWrcwY",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''Set within a year after the events of Batman Begins, Batman, Lieutenant James Gordon, and new district attorney Harvey Dent successfully begin to round up the criminals''')
movies=[toy_story,pulp_fiction,dark_knight,godfather,shawshank]
# Replace `Youtube URL` with just `Youtube video ID`
for movie in movies:
youtube_id_match = re.search(r'(?<=v=)[^&#]+', movie.trailer_youtube_url)
youtube_id_match = youtube_id_match or re.search(r'(?<=be/)[^&#]+', movie.trailer_youtube_url)
trailer_youtube_id = (youtube_id_match.group(0) if youtube_id_match else None)
movie.trailer_youtube_url = trailer_youtube_id
return render_template('index.html',
data=movies)
if __name__ == '__main__':
app.run(debug=True)
|
toy_story = Movie(title = "Toy Story 3", trailer_youtube_url ="https://www.youtube.com/watch?v=QW0sjQFpXTU",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMTgxOTY4Mjc0MF5BMl5BanBnXkFtZTcwNTA4MDQyMw@@._V1_UY268_CR3,0,182,268_AL_.jpg",
|
random_line_split
|
app.py
|
from flask import Flask
app = Flask(__name__)
from media import Movie
from flask import render_template
import re
@app.route('/')
def index():
|
if __name__ == '__main__':
app.run(debug=True)
|
'''View function for index page.'''
toy_story = Movie(title = "Toy Story 3", trailer_youtube_url ="https://www.youtube.com/watch?v=QW0sjQFpXTU",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMTgxOTY4Mjc0MF5BMl5BanBnXkFtZTcwNTA4MDQyMw@@._V1_UY268_CR3,0,182,268_AL_.jpg",
storyline='''Andy's toys get mistakenly delivered to a day care centre.
Woody convinces the other toys that they weren't dumped and leads them on an expedition back
home.''')
pulp_fiction = Movie(title = "Pulp Fiction ", trailer_youtube_url ="https://www.youtube.com/watch?v=s7EdQ4FqbhY",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMTkxMTA5OTAzMl5BMl5BanBnXkFtZTgwNjA5MDc3NjE@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''The lives of two mob hit men, a boxer, a gangster's wife, and a pair of diner bandits
intertwine in four tales of violence and redemption''')
shawshank = Movie(title = "The Shawshank Redemption", trailer_youtube_url ="https://www.youtube.com/watch?v=KtwXlIwozog",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''Two imprisoned men bond over a number of years, finding solace
and eventual redemption through acts of common decency.''')
godfather = Movie(title = "The Godfather ", trailer_youtube_url ="https://www.youtube.com/watch?v=sY1S34973zA",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMjEyMjcyNDI4MF5BMl5BanBnXkFtZTcwMDA5Mzg3OA@@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.''')
dark_knight = Movie(title = "The Dark Knight ", trailer_youtube_url ="https://www.youtube.com/watch?v=EXeTwQWrcwY",
poster_image_url="https://images-na.ssl-images-amazon.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_UX182_CR0,0,182,268_AL_.jpg",
storyline='''Set within a year after the events of Batman Begins, Batman, Lieutenant James Gordon, and new district attorney Harvey Dent successfully begin to round up the criminals''')
movies=[toy_story,pulp_fiction,dark_knight,godfather,shawshank]
# Replace `Youtube URL` with just `Youtube video ID`
for movie in movies:
youtube_id_match = re.search(r'(?<=v=)[^&#]+', movie.trailer_youtube_url)
youtube_id_match = youtube_id_match or re.search(r'(?<=be/)[^&#]+', movie.trailer_youtube_url)
trailer_youtube_id = (youtube_id_match.group(0) if youtube_id_match else None)
movie.trailer_youtube_url = trailer_youtube_id
return render_template('index.html',
data=movies)
|
identifier_body
|
settings.py
|
# Django settings for imageuploads project.
import os
PROJECT_DIR = os.path.dirname(__file__)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '[email protected]'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
MEDIA_ROOT = os.path.join(PROJECT_DIR, "media")
STATIC_ROOT = os.path.join(PROJECT_DIR, "static")
MEDIA_URL = "/media/"
STATIC_URL = "/static/"
# Additional locations of static files
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, "site_static"),
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'qomeppi59pg-(^lh7o@seb!-9d(yr@5n^=*y9w&(=!yd2p7&e^'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'imageuploads.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'imageuploads.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, "templates"),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'crispy_forms',
'ajaxuploader',
'images',
)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
CRISPY_TEMPLATE_PACK = 'bootstrap3'
|
pass
|
try:
execfile(os.path.join(os.path.dirname(__file__), "local_settings.py"))
except IOError:
|
random_line_split
|
oauth.ts
|
import crypto from "crypto";
import oauth from "oauth-sign";
import { URL } from "url";
import { Credentials } from "./credentials";
// Object.fromEntries
const objectFromEntries = (
entries: IterableIterator<[string, string]>
): { [key: string]: string } => {
const o = Object.create(null);
for (const [k, v] of entries) {
o[k] = v;
}
return o;
};
const oauthAuthorizationHeader = (
urlString: string,
method: string,
oauthKeys: Credentials
): string => {
const nonce = crypto.randomBytes(16).toString("hex");
const signatureMethod = "HMAC-SHA1";
const timestamp = Math.floor(Date.now() / 1000).toString();
const oauthSortedParams: [string, string][] = [
["oauth_consumer_key", oauthKeys.consumerKey],
["oauth_nonce", nonce],
["oauth_signature_method", signatureMethod],
["oauth_timestamp", timestamp],
["oauth_token", oauthKeys.accessToken],
["oauth_version", "1.0"],
];
const urlObject = new URL(urlString);
for (const [name, value] of oauthSortedParams) {
urlObject.searchParams.append(name, value);
}
const params = [
...oauthSortedParams,
[
|
urlObject.protocol + "//" + urlObject.host + urlObject.pathname,
objectFromEntries(urlObject.searchParams.entries()),
oauthKeys.consumerSecret,
oauthKeys.accessTokenSecret
),
],
]
.map(([name, value]) => `${name}="${oauth.rfc3986(value)}"`)
.join(",");
return `OAuth ${params}`;
};
export { oauthAuthorizationHeader };
|
"oauth_signature",
oauth.sign(
signatureMethod,
method,
|
random_line_split
|
issue.py
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import json
from frappe import _
from frappe import utils
from frappe.model.document import Document
from frappe.utils import now, time_diff_in_hours, now_datetime, getdate, get_weekdays, add_to_date, today, get_time, get_datetime
from datetime import datetime, timedelta
from frappe.model.mapper import get_mapped_doc
from frappe.utils.user import is_website_user
from erpnext.support.doctype.service_level_agreement.service_level_agreement import get_active_service_level_agreement_for
from frappe.email.inbox import link_communication_to_document
sender_field = "raised_by"
class Issue(Document):
def get_feed(self):
return "{0}: {1}".format(_(self.status), self.subject)
def validate(self):
if self.is_new() and self.via_customer_portal:
self.flags.create_communication = True
if not self.raised_by:
self.raised_by = frappe.session.user
self.change_service_level_agreement_and_priority()
self.update_status()
self.set_lead_contact(self.raised_by)
def on_update(self):
# Add a communication in the issue timeline
if self.flags.create_communication and self.via_customer_portal:
self.create_communication()
self.flags.communication_created = None
def set_lead_contact(self, email_id):
import email.utils
email_id = email.utils.parseaddr(email_id)[1]
if email_id:
if not self.lead:
self.lead = frappe.db.get_value("Lead", {"email_id": email_id})
if not self.contact and not self.customer:
self.contact = frappe.db.get_value("Contact", {"email_id": email_id})
if self.contact:
contact = frappe.get_doc('Contact', self.contact)
self.customer = contact.get_link_for('Customer')
if not self.company:
self.company = frappe.db.get_value("Lead", self.lead, "company") or \
frappe.db.get_default("Company")
def update_status(self):
status = frappe.db.get_value("Issue", self.name, "status")
if self.status!="Open" and status =="Open" and not self.first_responded_on:
self.first_responded_on = frappe.flags.current_time or now_datetime()
if self.status=="Closed" and status !="Closed":
self.resolution_date = frappe.flags.current_time or now_datetime()
if frappe.db.get_value("Issue", self.name, "agreement_fulfilled") == "Ongoing":
set_service_level_agreement_variance(issue=self.name)
self.update_agreement_status()
if self.status=="Open" and status !="Open":
# if no date, it should be set as None and not a blank string "", as per mysql strict config
self.resolution_date = None
def update_agreement_status(self):
if self.service_level_agreement and self.agreement_fulfilled == "Ongoing":
if frappe.db.get_value("Issue", self.name, "response_by_variance") < 0 or \
frappe.db.get_value("Issue", self.name, "resolution_by_variance") < 0:
self.agreement_fulfilled = "Failed"
else:
self.agreement_fulfilled = "Fulfilled"
def update_agreement_fulfilled_on_custom_status(self):
"""
Update Agreement Fulfilled status using Custom Scripts for Custom Issue Status
"""
if not self.first_responded_on: # first_responded_on set when first reply is sent to customer
self.response_by_variance = round(time_diff_in_hours(self.response_by, now_datetime()), 2)
if not self.resolution_date: # resolution_date set when issue has been closed
self.resolution_by_variance = round(time_diff_in_hours(self.resolution_by, now_datetime()), 2)
self.agreement_fulfilled = "Fulfilled" if self.response_by_variance > 0 and self.resolution_by_variance > 0 else "Failed"
def
|
(self):
communication = frappe.new_doc("Communication")
communication.update({
"communication_type": "Communication",
"communication_medium": "Email",
"sent_or_received": "Received",
"email_status": "Open",
"subject": self.subject,
"sender": self.raised_by,
"content": self.description,
"status": "Linked",
"reference_doctype": "Issue",
"reference_name": self.name
})
communication.ignore_permissions = True
communication.ignore_mandatory = True
communication.save()
def split_issue(self, subject, communication_id):
# Bug: Pressing enter doesn't send subject
from copy import deepcopy
replicated_issue = deepcopy(self)
replicated_issue.subject = subject
replicated_issue.issue_split_from = self.name
replicated_issue.mins_to_first_response = 0
replicated_issue.first_responded_on = None
replicated_issue.creation = now_datetime()
# Reset SLA
if replicated_issue.service_level_agreement:
replicated_issue.service_level_agreement_creation = now_datetime()
replicated_issue.service_level_agreement = None
replicated_issue.agreement_fulfilled = "Ongoing"
replicated_issue.response_by = None
replicated_issue.response_by_variance = None
replicated_issue.resolution_by = None
replicated_issue.resolution_by_variance = None
frappe.get_doc(replicated_issue).insert()
# Replicate linked Communications
# TODO: get all communications in timeline before this, and modify them to append them to new doc
comm_to_split_from = frappe.get_doc("Communication", communication_id)
communications = frappe.get_all("Communication",
filters={"reference_doctype": "Issue",
"reference_name": comm_to_split_from.reference_name,
"creation": ('>=', comm_to_split_from.creation)})
for communication in communications:
doc = frappe.get_doc("Communication", communication.name)
doc.reference_name = replicated_issue.name
doc.save(ignore_permissions=True)
frappe.get_doc({
"doctype": "Comment",
"comment_type": "Info",
"reference_doctype": "Issue",
"reference_name": replicated_issue.name,
"content": " - Split the Issue from <a href='#Form/Issue/{0}'>{1}</a>".format(self.name, frappe.bold(self.name)),
}).insert(ignore_permissions=True)
return replicated_issue.name
def before_insert(self):
if frappe.db.get_single_value("Support Settings", "track_service_level_agreement"):
self.set_response_and_resolution_time()
def set_response_and_resolution_time(self, priority=None, service_level_agreement=None):
service_level_agreement = get_active_service_level_agreement_for(priority=priority,
customer=self.customer, service_level_agreement=service_level_agreement)
if not service_level_agreement:
if frappe.db.get_value("Issue", self.name, "service_level_agreement"):
frappe.throw(_("Couldn't Set Service Level Agreement {0}.").format(self.service_level_agreement))
return
if (service_level_agreement.customer and self.customer) and not (service_level_agreement.customer == self.customer):
frappe.throw(_("This Service Level Agreement is specific to Customer {0}").format(service_level_agreement.customer))
self.service_level_agreement = service_level_agreement.name
self.priority = service_level_agreement.default_priority if not priority else priority
service_level_agreement = frappe.get_doc("Service Level Agreement", service_level_agreement.name)
priority = service_level_agreement.get_service_level_agreement_priority(self.priority)
priority.update({
"support_and_resolution": service_level_agreement.support_and_resolution,
"holiday_list": service_level_agreement.holiday_list
})
if not self.creation:
self.creation = now_datetime()
self.service_level_agreement_creation = now_datetime()
start_date_time = get_datetime(self.service_level_agreement_creation)
self.response_by = get_expected_time_for(parameter='response', service_level=priority, start_date_time=start_date_time)
self.resolution_by = get_expected_time_for(parameter='resolution', service_level=priority, start_date_time=start_date_time)
self.response_by_variance = round(time_diff_in_hours(self.response_by, now_datetime()))
self.resolution_by_variance = round(time_diff_in_hours(self.resolution_by, now_datetime()))
def change_service_level_agreement_and_priority(self):
if self.service_level_agreement and frappe.db.exists("Issue", self.name) and \
frappe.db.get_single_value("Support Settings", "track_service_level_agreement"):
if not self.priority == frappe.db.get_value("Issue", self.name, "priority"):
self.set_response_and_resolution_time(priority=self.priority, service_level_agreement=self.service_level_agreement)
frappe.msgprint(_("Priority has been changed to {0}.").format(self.priority))
if not self.service_level_agreement == frappe.db.get_value("Issue", self.name, "service_level_agreement"):
self.set_response_and_resolution_time(priority=self.priority, service_level_agreement=self.service_level_agreement)
frappe.msgprint(_("Service Level Agreement has been changed to {0}.").format(self.service_level_agreement))
def reset_service_level_agreement(self, reason, user):
if not frappe.db.get_single_value("Support Settings", "allow_resetting_service_level_agreement"):
frappe.throw(_("Allow Resetting Service Level Agreement from Support Settings."))
frappe.get_doc({
"doctype": "Comment",
"comment_type": "Info",
"reference_doctype": self.doctype,
"reference_name": self.name,
"comment_email": user,
"content": " resetted Service Level Agreement - {0}".format(_(reason)),
}).insert(ignore_permissions=True)
self.service_level_agreement_creation = now_datetime()
self.set_response_and_resolution_time(priority=self.priority, service_level_agreement=self.service_level_agreement)
self.agreement_fulfilled = "Ongoing"
self.save()
def get_expected_time_for(parameter, service_level, start_date_time):
current_date_time = start_date_time
expected_time = current_date_time
start_time = None
end_time = None
# lets assume response time is in days by default
if parameter == 'response':
allotted_days = service_level.get("response_time")
time_period = service_level.get("response_time_period")
elif parameter == 'resolution':
allotted_days = service_level.get("resolution_time")
time_period = service_level.get("resolution_time_period")
else:
frappe.throw(_("{0} parameter is invalid").format(parameter))
allotted_hours = 0
if time_period == 'Hour':
allotted_hours = allotted_days
allotted_days = 0
elif time_period == 'Week':
allotted_days *= 7
expected_time_is_set = 1 if allotted_days == 0 and time_period in ['Day', 'Week'] else 0
support_days = {}
for service in service_level.get("support_and_resolution"):
support_days[service.workday] = frappe._dict({
'start_time': service.start_time,
'end_time': service.end_time,
})
holidays = get_holidays(service_level.get("holiday_list"))
weekdays = get_weekdays()
while not expected_time_is_set:
current_weekday = weekdays[current_date_time.weekday()]
if not is_holiday(current_date_time, holidays) and current_weekday in support_days:
start_time = current_date_time - datetime(current_date_time.year, current_date_time.month, current_date_time.day) \
if getdate(current_date_time) == getdate(start_date_time) and get_time_in_timedelta(current_date_time.time()) > support_days[current_weekday].start_time \
else support_days[current_weekday].start_time
end_time = support_days[current_weekday].end_time
time_left_today = time_diff_in_hours(end_time, start_time)
# no time left for support today
if time_left_today < 0: pass
elif time_period == 'Hour':
if time_left_today >= allotted_hours:
expected_time = datetime.combine(getdate(current_date_time), get_time(start_time))
expected_time = add_to_date(expected_time, hours=allotted_hours)
expected_time_is_set = 1
else:
allotted_hours = allotted_hours - time_left_today
else:
allotted_days -= 1
expected_time_is_set = allotted_days <= 0
if not expected_time_is_set:
current_date_time = add_to_date(current_date_time, days=1)
if end_time and time_period != 'Hour':
current_date_time = datetime.combine(getdate(current_date_time), get_time(end_time))
else:
current_date_time = expected_time
return current_date_time
def set_service_level_agreement_variance(issue=None):
current_time = frappe.flags.current_time or now_datetime()
filters = {"status": "Open", "agreement_fulfilled": "Ongoing"}
if issue:
filters = {"name": issue}
for issue in frappe.get_list("Issue", filters=filters):
doc = frappe.get_doc("Issue", issue.name)
if not doc.first_responded_on: # first_responded_on set when first reply is sent to customer
variance = round(time_diff_in_hours(doc.response_by, current_time), 2)
frappe.db.set_value(dt="Issue", dn=doc.name, field="response_by_variance", val=variance, update_modified=False)
if variance < 0:
frappe.db.set_value(dt="Issue", dn=doc.name, field="agreement_fulfilled", val="Failed", update_modified=False)
if not doc.resolution_date: # resolution_date set when issue has been closed
variance = round(time_diff_in_hours(doc.resolution_by, current_time), 2)
frappe.db.set_value(dt="Issue", dn=doc.name, field="resolution_by_variance", val=variance, update_modified=False)
if variance < 0:
frappe.db.set_value(dt="Issue", dn=doc.name, field="agreement_fulfilled", val="Failed", update_modified=False)
def get_list_context(context=None):
return {
"title": _("Issues"),
"get_list": get_issue_list,
"row_template": "templates/includes/issue_row.html",
"show_sidebar": True,
"show_search": True,
'no_breadcrumbs': True
}
def get_issue_list(doctype, txt, filters, limit_start, limit_page_length=20, order_by=None):
from frappe.www.list import get_list
user = frappe.session.user
contact = frappe.db.get_value('Contact', {'user': user}, 'name')
customer = None
if contact:
contact_doc = frappe.get_doc('Contact', contact)
customer = contact_doc.get_link_for('Customer')
ignore_permissions = False
if is_website_user():
if not filters: filters = []
filters.append(("Issue", "customer", "=", customer)) if customer else filters.append(("Issue", "raised_by", "=", user))
ignore_permissions = True
return get_list(doctype, txt, filters, limit_start, limit_page_length, ignore_permissions=ignore_permissions)
@frappe.whitelist()
def set_multiple_status(names, status):
names = json.loads(names)
for name in names:
set_status(name, status)
@frappe.whitelist()
def set_status(name, status):
st = frappe.get_doc("Issue", name)
st.status = status
st.save()
def auto_close_tickets():
"""Auto-close replied support tickets after 7 days"""
auto_close_after_days = frappe.db.get_value("Support Settings", "Support Settings", "close_issue_after_days") or 7
issues = frappe.db.sql(""" select name from tabIssue where status='Replied' and
modified<DATE_SUB(CURDATE(), INTERVAL %s DAY) """, (auto_close_after_days), as_dict=True)
for issue in issues:
doc = frappe.get_doc("Issue", issue.get("name"))
doc.status = "Closed"
doc.flags.ignore_permissions = True
doc.flags.ignore_mandatory = True
doc.save()
def has_website_permission(doc, ptype, user, verbose=False):
from erpnext.controllers.website_list_for_contact import has_website_permission
permission_based_on_customer = has_website_permission(doc, ptype, user, verbose)
return permission_based_on_customer or doc.raised_by==user
def update_issue(contact, method):
"""Called when Contact is deleted"""
frappe.db.sql("""UPDATE `tabIssue` set contact='' where contact=%s""", contact.name)
def get_holidays(holiday_list_name):
holiday_list = frappe.get_cached_doc("Holiday List", holiday_list_name)
holidays = [holiday.holiday_date for holiday in holiday_list.holidays]
return holidays
def is_holiday(date, holidays):
return getdate(date) in holidays
@frappe.whitelist()
def make_task(source_name, target_doc=None):
return get_mapped_doc("Issue", source_name, {
"Issue": {
"doctype": "Task"
}
}, target_doc)
@frappe.whitelist()
def make_issue_from_communication(communication, ignore_communication_links=False):
""" raise a issue from email """
doc = frappe.get_doc("Communication", communication)
issue = frappe.get_doc({
"doctype": "Issue",
"subject": doc.subject,
"communication_medium": doc.communication_medium,
"raised_by": doc.sender or "",
"raised_by_phone": doc.phone_no or ""
}).insert(ignore_permissions=True)
link_communication_to_document(doc, "Issue", issue.name, ignore_communication_links)
return issue.name
def get_time_in_timedelta(time):
"""
Converts datetime.time(10, 36, 55, 961454) to datetime.timedelta(seconds=38215)
"""
import datetime
return datetime.timedelta(hours=time.hour, minutes=time.minute, seconds=time.second)
|
create_communication
|
identifier_name
|
issue.py
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import json
from frappe import _
from frappe import utils
from frappe.model.document import Document
from frappe.utils import now, time_diff_in_hours, now_datetime, getdate, get_weekdays, add_to_date, today, get_time, get_datetime
from datetime import datetime, timedelta
from frappe.model.mapper import get_mapped_doc
from frappe.utils.user import is_website_user
from erpnext.support.doctype.service_level_agreement.service_level_agreement import get_active_service_level_agreement_for
from frappe.email.inbox import link_communication_to_document
sender_field = "raised_by"
class Issue(Document):
def get_feed(self):
return "{0}: {1}".format(_(self.status), self.subject)
def validate(self):
if self.is_new() and self.via_customer_portal:
self.flags.create_communication = True
if not self.raised_by:
self.raised_by = frappe.session.user
self.change_service_level_agreement_and_priority()
self.update_status()
self.set_lead_contact(self.raised_by)
def on_update(self):
# Add a communication in the issue timeline
if self.flags.create_communication and self.via_customer_portal:
self.create_communication()
self.flags.communication_created = None
def set_lead_contact(self, email_id):
import email.utils
email_id = email.utils.parseaddr(email_id)[1]
if email_id:
if not self.lead:
self.lead = frappe.db.get_value("Lead", {"email_id": email_id})
if not self.contact and not self.customer:
self.contact = frappe.db.get_value("Contact", {"email_id": email_id})
if self.contact:
contact = frappe.get_doc('Contact', self.contact)
self.customer = contact.get_link_for('Customer')
if not self.company:
self.company = frappe.db.get_value("Lead", self.lead, "company") or \
frappe.db.get_default("Company")
def update_status(self):
status = frappe.db.get_value("Issue", self.name, "status")
if self.status!="Open" and status =="Open" and not self.first_responded_on:
self.first_responded_on = frappe.flags.current_time or now_datetime()
if self.status=="Closed" and status !="Closed":
self.resolution_date = frappe.flags.current_time or now_datetime()
if frappe.db.get_value("Issue", self.name, "agreement_fulfilled") == "Ongoing":
set_service_level_agreement_variance(issue=self.name)
self.update_agreement_status()
if self.status=="Open" and status !="Open":
# if no date, it should be set as None and not a blank string "", as per mysql strict config
self.resolution_date = None
def update_agreement_status(self):
if self.service_level_agreement and self.agreement_fulfilled == "Ongoing":
if frappe.db.get_value("Issue", self.name, "response_by_variance") < 0 or \
frappe.db.get_value("Issue", self.name, "resolution_by_variance") < 0:
self.agreement_fulfilled = "Failed"
else:
self.agreement_fulfilled = "Fulfilled"
def update_agreement_fulfilled_on_custom_status(self):
"""
Update Agreement Fulfilled status using Custom Scripts for Custom Issue Status
"""
if not self.first_responded_on: # first_responded_on set when first reply is sent to customer
self.response_by_variance = round(time_diff_in_hours(self.response_by, now_datetime()), 2)
if not self.resolution_date: # resolution_date set when issue has been closed
self.resolution_by_variance = round(time_diff_in_hours(self.resolution_by, now_datetime()), 2)
self.agreement_fulfilled = "Fulfilled" if self.response_by_variance > 0 and self.resolution_by_variance > 0 else "Failed"
def create_communication(self):
communication = frappe.new_doc("Communication")
communication.update({
"communication_type": "Communication",
"communication_medium": "Email",
"sent_or_received": "Received",
"email_status": "Open",
"subject": self.subject,
"sender": self.raised_by,
"content": self.description,
"status": "Linked",
"reference_doctype": "Issue",
"reference_name": self.name
})
communication.ignore_permissions = True
communication.ignore_mandatory = True
communication.save()
def split_issue(self, subject, communication_id):
# Bug: Pressing enter doesn't send subject
from copy import deepcopy
replicated_issue = deepcopy(self)
replicated_issue.subject = subject
replicated_issue.issue_split_from = self.name
replicated_issue.mins_to_first_response = 0
replicated_issue.first_responded_on = None
replicated_issue.creation = now_datetime()
# Reset SLA
if replicated_issue.service_level_agreement:
replicated_issue.service_level_agreement_creation = now_datetime()
replicated_issue.service_level_agreement = None
replicated_issue.agreement_fulfilled = "Ongoing"
replicated_issue.response_by = None
replicated_issue.response_by_variance = None
replicated_issue.resolution_by = None
replicated_issue.resolution_by_variance = None
frappe.get_doc(replicated_issue).insert()
# Replicate linked Communications
# TODO: get all communications in timeline before this, and modify them to append them to new doc
comm_to_split_from = frappe.get_doc("Communication", communication_id)
communications = frappe.get_all("Communication",
filters={"reference_doctype": "Issue",
"reference_name": comm_to_split_from.reference_name,
"creation": ('>=', comm_to_split_from.creation)})
for communication in communications:
doc = frappe.get_doc("Communication", communication.name)
doc.reference_name = replicated_issue.name
doc.save(ignore_permissions=True)
frappe.get_doc({
"doctype": "Comment",
"comment_type": "Info",
"reference_doctype": "Issue",
"reference_name": replicated_issue.name,
"content": " - Split the Issue from <a href='#Form/Issue/{0}'>{1}</a>".format(self.name, frappe.bold(self.name)),
}).insert(ignore_permissions=True)
return replicated_issue.name
def before_insert(self):
if frappe.db.get_single_value("Support Settings", "track_service_level_agreement"):
self.set_response_and_resolution_time()
def set_response_and_resolution_time(self, priority=None, service_level_agreement=None):
|
def change_service_level_agreement_and_priority(self):
if self.service_level_agreement and frappe.db.exists("Issue", self.name) and \
frappe.db.get_single_value("Support Settings", "track_service_level_agreement"):
if not self.priority == frappe.db.get_value("Issue", self.name, "priority"):
self.set_response_and_resolution_time(priority=self.priority, service_level_agreement=self.service_level_agreement)
frappe.msgprint(_("Priority has been changed to {0}.").format(self.priority))
if not self.service_level_agreement == frappe.db.get_value("Issue", self.name, "service_level_agreement"):
self.set_response_and_resolution_time(priority=self.priority, service_level_agreement=self.service_level_agreement)
frappe.msgprint(_("Service Level Agreement has been changed to {0}.").format(self.service_level_agreement))
def reset_service_level_agreement(self, reason, user):
if not frappe.db.get_single_value("Support Settings", "allow_resetting_service_level_agreement"):
frappe.throw(_("Allow Resetting Service Level Agreement from Support Settings."))
frappe.get_doc({
"doctype": "Comment",
"comment_type": "Info",
"reference_doctype": self.doctype,
"reference_name": self.name,
"comment_email": user,
"content": " resetted Service Level Agreement - {0}".format(_(reason)),
}).insert(ignore_permissions=True)
self.service_level_agreement_creation = now_datetime()
self.set_response_and_resolution_time(priority=self.priority, service_level_agreement=self.service_level_agreement)
self.agreement_fulfilled = "Ongoing"
self.save()
def get_expected_time_for(parameter, service_level, start_date_time):
current_date_time = start_date_time
expected_time = current_date_time
start_time = None
end_time = None
# lets assume response time is in days by default
if parameter == 'response':
allotted_days = service_level.get("response_time")
time_period = service_level.get("response_time_period")
elif parameter == 'resolution':
allotted_days = service_level.get("resolution_time")
time_period = service_level.get("resolution_time_period")
else:
frappe.throw(_("{0} parameter is invalid").format(parameter))
allotted_hours = 0
if time_period == 'Hour':
allotted_hours = allotted_days
allotted_days = 0
elif time_period == 'Week':
allotted_days *= 7
expected_time_is_set = 1 if allotted_days == 0 and time_period in ['Day', 'Week'] else 0
support_days = {}
for service in service_level.get("support_and_resolution"):
support_days[service.workday] = frappe._dict({
'start_time': service.start_time,
'end_time': service.end_time,
})
holidays = get_holidays(service_level.get("holiday_list"))
weekdays = get_weekdays()
while not expected_time_is_set:
current_weekday = weekdays[current_date_time.weekday()]
if not is_holiday(current_date_time, holidays) and current_weekday in support_days:
start_time = current_date_time - datetime(current_date_time.year, current_date_time.month, current_date_time.day) \
if getdate(current_date_time) == getdate(start_date_time) and get_time_in_timedelta(current_date_time.time()) > support_days[current_weekday].start_time \
else support_days[current_weekday].start_time
end_time = support_days[current_weekday].end_time
time_left_today = time_diff_in_hours(end_time, start_time)
# no time left for support today
if time_left_today < 0: pass
elif time_period == 'Hour':
if time_left_today >= allotted_hours:
expected_time = datetime.combine(getdate(current_date_time), get_time(start_time))
expected_time = add_to_date(expected_time, hours=allotted_hours)
expected_time_is_set = 1
else:
allotted_hours = allotted_hours - time_left_today
else:
allotted_days -= 1
expected_time_is_set = allotted_days <= 0
if not expected_time_is_set:
current_date_time = add_to_date(current_date_time, days=1)
if end_time and time_period != 'Hour':
current_date_time = datetime.combine(getdate(current_date_time), get_time(end_time))
else:
current_date_time = expected_time
return current_date_time
def set_service_level_agreement_variance(issue=None):
current_time = frappe.flags.current_time or now_datetime()
filters = {"status": "Open", "agreement_fulfilled": "Ongoing"}
if issue:
filters = {"name": issue}
for issue in frappe.get_list("Issue", filters=filters):
doc = frappe.get_doc("Issue", issue.name)
if not doc.first_responded_on: # first_responded_on set when first reply is sent to customer
variance = round(time_diff_in_hours(doc.response_by, current_time), 2)
frappe.db.set_value(dt="Issue", dn=doc.name, field="response_by_variance", val=variance, update_modified=False)
if variance < 0:
frappe.db.set_value(dt="Issue", dn=doc.name, field="agreement_fulfilled", val="Failed", update_modified=False)
if not doc.resolution_date: # resolution_date set when issue has been closed
variance = round(time_diff_in_hours(doc.resolution_by, current_time), 2)
frappe.db.set_value(dt="Issue", dn=doc.name, field="resolution_by_variance", val=variance, update_modified=False)
if variance < 0:
frappe.db.set_value(dt="Issue", dn=doc.name, field="agreement_fulfilled", val="Failed", update_modified=False)
def get_list_context(context=None):
return {
"title": _("Issues"),
"get_list": get_issue_list,
"row_template": "templates/includes/issue_row.html",
"show_sidebar": True,
"show_search": True,
'no_breadcrumbs': True
}
def get_issue_list(doctype, txt, filters, limit_start, limit_page_length=20, order_by=None):
from frappe.www.list import get_list
user = frappe.session.user
contact = frappe.db.get_value('Contact', {'user': user}, 'name')
customer = None
if contact:
contact_doc = frappe.get_doc('Contact', contact)
customer = contact_doc.get_link_for('Customer')
ignore_permissions = False
if is_website_user():
if not filters: filters = []
filters.append(("Issue", "customer", "=", customer)) if customer else filters.append(("Issue", "raised_by", "=", user))
ignore_permissions = True
return get_list(doctype, txt, filters, limit_start, limit_page_length, ignore_permissions=ignore_permissions)
@frappe.whitelist()
def set_multiple_status(names, status):
names = json.loads(names)
for name in names:
set_status(name, status)
@frappe.whitelist()
def set_status(name, status):
st = frappe.get_doc("Issue", name)
st.status = status
st.save()
def auto_close_tickets():
"""Auto-close replied support tickets after 7 days"""
auto_close_after_days = frappe.db.get_value("Support Settings", "Support Settings", "close_issue_after_days") or 7
issues = frappe.db.sql(""" select name from tabIssue where status='Replied' and
modified<DATE_SUB(CURDATE(), INTERVAL %s DAY) """, (auto_close_after_days), as_dict=True)
for issue in issues:
doc = frappe.get_doc("Issue", issue.get("name"))
doc.status = "Closed"
doc.flags.ignore_permissions = True
doc.flags.ignore_mandatory = True
doc.save()
def has_website_permission(doc, ptype, user, verbose=False):
from erpnext.controllers.website_list_for_contact import has_website_permission
permission_based_on_customer = has_website_permission(doc, ptype, user, verbose)
return permission_based_on_customer or doc.raised_by==user
def update_issue(contact, method):
"""Called when Contact is deleted"""
frappe.db.sql("""UPDATE `tabIssue` set contact='' where contact=%s""", contact.name)
def get_holidays(holiday_list_name):
holiday_list = frappe.get_cached_doc("Holiday List", holiday_list_name)
holidays = [holiday.holiday_date for holiday in holiday_list.holidays]
return holidays
def is_holiday(date, holidays):
return getdate(date) in holidays
@frappe.whitelist()
def make_task(source_name, target_doc=None):
return get_mapped_doc("Issue", source_name, {
"Issue": {
"doctype": "Task"
}
}, target_doc)
@frappe.whitelist()
def make_issue_from_communication(communication, ignore_communication_links=False):
""" raise a issue from email """
doc = frappe.get_doc("Communication", communication)
issue = frappe.get_doc({
"doctype": "Issue",
"subject": doc.subject,
"communication_medium": doc.communication_medium,
"raised_by": doc.sender or "",
"raised_by_phone": doc.phone_no or ""
}).insert(ignore_permissions=True)
link_communication_to_document(doc, "Issue", issue.name, ignore_communication_links)
return issue.name
def get_time_in_timedelta(time):
"""
Converts datetime.time(10, 36, 55, 961454) to datetime.timedelta(seconds=38215)
"""
import datetime
return datetime.timedelta(hours=time.hour, minutes=time.minute, seconds=time.second)
|
service_level_agreement = get_active_service_level_agreement_for(priority=priority,
customer=self.customer, service_level_agreement=service_level_agreement)
if not service_level_agreement:
if frappe.db.get_value("Issue", self.name, "service_level_agreement"):
frappe.throw(_("Couldn't Set Service Level Agreement {0}.").format(self.service_level_agreement))
return
if (service_level_agreement.customer and self.customer) and not (service_level_agreement.customer == self.customer):
frappe.throw(_("This Service Level Agreement is specific to Customer {0}").format(service_level_agreement.customer))
self.service_level_agreement = service_level_agreement.name
self.priority = service_level_agreement.default_priority if not priority else priority
service_level_agreement = frappe.get_doc("Service Level Agreement", service_level_agreement.name)
priority = service_level_agreement.get_service_level_agreement_priority(self.priority)
priority.update({
"support_and_resolution": service_level_agreement.support_and_resolution,
"holiday_list": service_level_agreement.holiday_list
})
if not self.creation:
self.creation = now_datetime()
self.service_level_agreement_creation = now_datetime()
start_date_time = get_datetime(self.service_level_agreement_creation)
self.response_by = get_expected_time_for(parameter='response', service_level=priority, start_date_time=start_date_time)
self.resolution_by = get_expected_time_for(parameter='resolution', service_level=priority, start_date_time=start_date_time)
self.response_by_variance = round(time_diff_in_hours(self.response_by, now_datetime()))
self.resolution_by_variance = round(time_diff_in_hours(self.resolution_by, now_datetime()))
|
identifier_body
|
issue.py
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import json
from frappe import _
from frappe import utils
from frappe.model.document import Document
from frappe.utils import now, time_diff_in_hours, now_datetime, getdate, get_weekdays, add_to_date, today, get_time, get_datetime
from datetime import datetime, timedelta
from frappe.model.mapper import get_mapped_doc
from frappe.utils.user import is_website_user
from erpnext.support.doctype.service_level_agreement.service_level_agreement import get_active_service_level_agreement_for
from frappe.email.inbox import link_communication_to_document
sender_field = "raised_by"
class Issue(Document):
def get_feed(self):
return "{0}: {1}".format(_(self.status), self.subject)
def validate(self):
if self.is_new() and self.via_customer_portal:
self.flags.create_communication = True
if not self.raised_by:
self.raised_by = frappe.session.user
self.change_service_level_agreement_and_priority()
self.update_status()
self.set_lead_contact(self.raised_by)
def on_update(self):
# Add a communication in the issue timeline
if self.flags.create_communication and self.via_customer_portal:
self.create_communication()
self.flags.communication_created = None
def set_lead_contact(self, email_id):
import email.utils
email_id = email.utils.parseaddr(email_id)[1]
if email_id:
if not self.lead:
self.lead = frappe.db.get_value("Lead", {"email_id": email_id})
if not self.contact and not self.customer:
self.contact = frappe.db.get_value("Contact", {"email_id": email_id})
if self.contact:
contact = frappe.get_doc('Contact', self.contact)
self.customer = contact.get_link_for('Customer')
if not self.company:
self.company = frappe.db.get_value("Lead", self.lead, "company") or \
frappe.db.get_default("Company")
def update_status(self):
status = frappe.db.get_value("Issue", self.name, "status")
if self.status!="Open" and status =="Open" and not self.first_responded_on:
self.first_responded_on = frappe.flags.current_time or now_datetime()
if self.status=="Closed" and status !="Closed":
self.resolution_date = frappe.flags.current_time or now_datetime()
if frappe.db.get_value("Issue", self.name, "agreement_fulfilled") == "Ongoing":
set_service_level_agreement_variance(issue=self.name)
self.update_agreement_status()
if self.status=="Open" and status !="Open":
# if no date, it should be set as None and not a blank string "", as per mysql strict config
self.resolution_date = None
def update_agreement_status(self):
if self.service_level_agreement and self.agreement_fulfilled == "Ongoing":
if frappe.db.get_value("Issue", self.name, "response_by_variance") < 0 or \
frappe.db.get_value("Issue", self.name, "resolution_by_variance") < 0:
self.agreement_fulfilled = "Failed"
else:
self.agreement_fulfilled = "Fulfilled"
def update_agreement_fulfilled_on_custom_status(self):
"""
Update Agreement Fulfilled status using Custom Scripts for Custom Issue Status
"""
if not self.first_responded_on: # first_responded_on set when first reply is sent to customer
self.response_by_variance = round(time_diff_in_hours(self.response_by, now_datetime()), 2)
if not self.resolution_date: # resolution_date set when issue has been closed
self.resolution_by_variance = round(time_diff_in_hours(self.resolution_by, now_datetime()), 2)
self.agreement_fulfilled = "Fulfilled" if self.response_by_variance > 0 and self.resolution_by_variance > 0 else "Failed"
def create_communication(self):
communication = frappe.new_doc("Communication")
communication.update({
"communication_type": "Communication",
"communication_medium": "Email",
"sent_or_received": "Received",
"email_status": "Open",
"subject": self.subject,
"sender": self.raised_by,
"content": self.description,
"status": "Linked",
"reference_doctype": "Issue",
"reference_name": self.name
})
communication.ignore_permissions = True
communication.ignore_mandatory = True
communication.save()
def split_issue(self, subject, communication_id):
# Bug: Pressing enter doesn't send subject
from copy import deepcopy
replicated_issue = deepcopy(self)
replicated_issue.subject = subject
replicated_issue.issue_split_from = self.name
replicated_issue.mins_to_first_response = 0
replicated_issue.first_responded_on = None
replicated_issue.creation = now_datetime()
# Reset SLA
if replicated_issue.service_level_agreement:
replicated_issue.service_level_agreement_creation = now_datetime()
replicated_issue.service_level_agreement = None
replicated_issue.agreement_fulfilled = "Ongoing"
replicated_issue.response_by = None
replicated_issue.response_by_variance = None
replicated_issue.resolution_by = None
replicated_issue.resolution_by_variance = None
frappe.get_doc(replicated_issue).insert()
# Replicate linked Communications
# TODO: get all communications in timeline before this, and modify them to append them to new doc
comm_to_split_from = frappe.get_doc("Communication", communication_id)
communications = frappe.get_all("Communication",
filters={"reference_doctype": "Issue",
"reference_name": comm_to_split_from.reference_name,
"creation": ('>=', comm_to_split_from.creation)})
|
doc.reference_name = replicated_issue.name
doc.save(ignore_permissions=True)
frappe.get_doc({
"doctype": "Comment",
"comment_type": "Info",
"reference_doctype": "Issue",
"reference_name": replicated_issue.name,
"content": " - Split the Issue from <a href='#Form/Issue/{0}'>{1}</a>".format(self.name, frappe.bold(self.name)),
}).insert(ignore_permissions=True)
return replicated_issue.name
def before_insert(self):
if frappe.db.get_single_value("Support Settings", "track_service_level_agreement"):
self.set_response_and_resolution_time()
def set_response_and_resolution_time(self, priority=None, service_level_agreement=None):
service_level_agreement = get_active_service_level_agreement_for(priority=priority,
customer=self.customer, service_level_agreement=service_level_agreement)
if not service_level_agreement:
if frappe.db.get_value("Issue", self.name, "service_level_agreement"):
frappe.throw(_("Couldn't Set Service Level Agreement {0}.").format(self.service_level_agreement))
return
if (service_level_agreement.customer and self.customer) and not (service_level_agreement.customer == self.customer):
frappe.throw(_("This Service Level Agreement is specific to Customer {0}").format(service_level_agreement.customer))
self.service_level_agreement = service_level_agreement.name
self.priority = service_level_agreement.default_priority if not priority else priority
service_level_agreement = frappe.get_doc("Service Level Agreement", service_level_agreement.name)
priority = service_level_agreement.get_service_level_agreement_priority(self.priority)
priority.update({
"support_and_resolution": service_level_agreement.support_and_resolution,
"holiday_list": service_level_agreement.holiday_list
})
if not self.creation:
self.creation = now_datetime()
self.service_level_agreement_creation = now_datetime()
start_date_time = get_datetime(self.service_level_agreement_creation)
self.response_by = get_expected_time_for(parameter='response', service_level=priority, start_date_time=start_date_time)
self.resolution_by = get_expected_time_for(parameter='resolution', service_level=priority, start_date_time=start_date_time)
self.response_by_variance = round(time_diff_in_hours(self.response_by, now_datetime()))
self.resolution_by_variance = round(time_diff_in_hours(self.resolution_by, now_datetime()))
def change_service_level_agreement_and_priority(self):
if self.service_level_agreement and frappe.db.exists("Issue", self.name) and \
frappe.db.get_single_value("Support Settings", "track_service_level_agreement"):
if not self.priority == frappe.db.get_value("Issue", self.name, "priority"):
self.set_response_and_resolution_time(priority=self.priority, service_level_agreement=self.service_level_agreement)
frappe.msgprint(_("Priority has been changed to {0}.").format(self.priority))
if not self.service_level_agreement == frappe.db.get_value("Issue", self.name, "service_level_agreement"):
self.set_response_and_resolution_time(priority=self.priority, service_level_agreement=self.service_level_agreement)
frappe.msgprint(_("Service Level Agreement has been changed to {0}.").format(self.service_level_agreement))
def reset_service_level_agreement(self, reason, user):
if not frappe.db.get_single_value("Support Settings", "allow_resetting_service_level_agreement"):
frappe.throw(_("Allow Resetting Service Level Agreement from Support Settings."))
frappe.get_doc({
"doctype": "Comment",
"comment_type": "Info",
"reference_doctype": self.doctype,
"reference_name": self.name,
"comment_email": user,
"content": " resetted Service Level Agreement - {0}".format(_(reason)),
}).insert(ignore_permissions=True)
self.service_level_agreement_creation = now_datetime()
self.set_response_and_resolution_time(priority=self.priority, service_level_agreement=self.service_level_agreement)
self.agreement_fulfilled = "Ongoing"
self.save()
def get_expected_time_for(parameter, service_level, start_date_time):
current_date_time = start_date_time
expected_time = current_date_time
start_time = None
end_time = None
# lets assume response time is in days by default
if parameter == 'response':
allotted_days = service_level.get("response_time")
time_period = service_level.get("response_time_period")
elif parameter == 'resolution':
allotted_days = service_level.get("resolution_time")
time_period = service_level.get("resolution_time_period")
else:
frappe.throw(_("{0} parameter is invalid").format(parameter))
allotted_hours = 0
if time_period == 'Hour':
allotted_hours = allotted_days
allotted_days = 0
elif time_period == 'Week':
allotted_days *= 7
expected_time_is_set = 1 if allotted_days == 0 and time_period in ['Day', 'Week'] else 0
support_days = {}
for service in service_level.get("support_and_resolution"):
support_days[service.workday] = frappe._dict({
'start_time': service.start_time,
'end_time': service.end_time,
})
holidays = get_holidays(service_level.get("holiday_list"))
weekdays = get_weekdays()
while not expected_time_is_set:
current_weekday = weekdays[current_date_time.weekday()]
if not is_holiday(current_date_time, holidays) and current_weekday in support_days:
start_time = current_date_time - datetime(current_date_time.year, current_date_time.month, current_date_time.day) \
if getdate(current_date_time) == getdate(start_date_time) and get_time_in_timedelta(current_date_time.time()) > support_days[current_weekday].start_time \
else support_days[current_weekday].start_time
end_time = support_days[current_weekday].end_time
time_left_today = time_diff_in_hours(end_time, start_time)
# no time left for support today
if time_left_today < 0: pass
elif time_period == 'Hour':
if time_left_today >= allotted_hours:
expected_time = datetime.combine(getdate(current_date_time), get_time(start_time))
expected_time = add_to_date(expected_time, hours=allotted_hours)
expected_time_is_set = 1
else:
allotted_hours = allotted_hours - time_left_today
else:
allotted_days -= 1
expected_time_is_set = allotted_days <= 0
if not expected_time_is_set:
current_date_time = add_to_date(current_date_time, days=1)
if end_time and time_period != 'Hour':
current_date_time = datetime.combine(getdate(current_date_time), get_time(end_time))
else:
current_date_time = expected_time
return current_date_time
def set_service_level_agreement_variance(issue=None):
current_time = frappe.flags.current_time or now_datetime()
filters = {"status": "Open", "agreement_fulfilled": "Ongoing"}
if issue:
filters = {"name": issue}
for issue in frappe.get_list("Issue", filters=filters):
doc = frappe.get_doc("Issue", issue.name)
if not doc.first_responded_on: # first_responded_on set when first reply is sent to customer
variance = round(time_diff_in_hours(doc.response_by, current_time), 2)
frappe.db.set_value(dt="Issue", dn=doc.name, field="response_by_variance", val=variance, update_modified=False)
if variance < 0:
frappe.db.set_value(dt="Issue", dn=doc.name, field="agreement_fulfilled", val="Failed", update_modified=False)
if not doc.resolution_date: # resolution_date set when issue has been closed
variance = round(time_diff_in_hours(doc.resolution_by, current_time), 2)
frappe.db.set_value(dt="Issue", dn=doc.name, field="resolution_by_variance", val=variance, update_modified=False)
if variance < 0:
frappe.db.set_value(dt="Issue", dn=doc.name, field="agreement_fulfilled", val="Failed", update_modified=False)
def get_list_context(context=None):
return {
"title": _("Issues"),
"get_list": get_issue_list,
"row_template": "templates/includes/issue_row.html",
"show_sidebar": True,
"show_search": True,
'no_breadcrumbs': True
}
def get_issue_list(doctype, txt, filters, limit_start, limit_page_length=20, order_by=None):
from frappe.www.list import get_list
user = frappe.session.user
contact = frappe.db.get_value('Contact', {'user': user}, 'name')
customer = None
if contact:
contact_doc = frappe.get_doc('Contact', contact)
customer = contact_doc.get_link_for('Customer')
ignore_permissions = False
if is_website_user():
if not filters: filters = []
filters.append(("Issue", "customer", "=", customer)) if customer else filters.append(("Issue", "raised_by", "=", user))
ignore_permissions = True
return get_list(doctype, txt, filters, limit_start, limit_page_length, ignore_permissions=ignore_permissions)
@frappe.whitelist()
def set_multiple_status(names, status):
names = json.loads(names)
for name in names:
set_status(name, status)
@frappe.whitelist()
def set_status(name, status):
st = frappe.get_doc("Issue", name)
st.status = status
st.save()
def auto_close_tickets():
"""Auto-close replied support tickets after 7 days"""
auto_close_after_days = frappe.db.get_value("Support Settings", "Support Settings", "close_issue_after_days") or 7
issues = frappe.db.sql(""" select name from tabIssue where status='Replied' and
modified<DATE_SUB(CURDATE(), INTERVAL %s DAY) """, (auto_close_after_days), as_dict=True)
for issue in issues:
doc = frappe.get_doc("Issue", issue.get("name"))
doc.status = "Closed"
doc.flags.ignore_permissions = True
doc.flags.ignore_mandatory = True
doc.save()
def has_website_permission(doc, ptype, user, verbose=False):
from erpnext.controllers.website_list_for_contact import has_website_permission
permission_based_on_customer = has_website_permission(doc, ptype, user, verbose)
return permission_based_on_customer or doc.raised_by==user
def update_issue(contact, method):
"""Called when Contact is deleted"""
frappe.db.sql("""UPDATE `tabIssue` set contact='' where contact=%s""", contact.name)
def get_holidays(holiday_list_name):
holiday_list = frappe.get_cached_doc("Holiday List", holiday_list_name)
holidays = [holiday.holiday_date for holiday in holiday_list.holidays]
return holidays
def is_holiday(date, holidays):
return getdate(date) in holidays
@frappe.whitelist()
def make_task(source_name, target_doc=None):
return get_mapped_doc("Issue", source_name, {
"Issue": {
"doctype": "Task"
}
}, target_doc)
@frappe.whitelist()
def make_issue_from_communication(communication, ignore_communication_links=False):
""" raise a issue from email """
doc = frappe.get_doc("Communication", communication)
issue = frappe.get_doc({
"doctype": "Issue",
"subject": doc.subject,
"communication_medium": doc.communication_medium,
"raised_by": doc.sender or "",
"raised_by_phone": doc.phone_no or ""
}).insert(ignore_permissions=True)
link_communication_to_document(doc, "Issue", issue.name, ignore_communication_links)
return issue.name
def get_time_in_timedelta(time):
"""
Converts datetime.time(10, 36, 55, 961454) to datetime.timedelta(seconds=38215)
"""
import datetime
return datetime.timedelta(hours=time.hour, minutes=time.minute, seconds=time.second)
|
for communication in communications:
doc = frappe.get_doc("Communication", communication.name)
|
random_line_split
|
issue.py
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import json
from frappe import _
from frappe import utils
from frappe.model.document import Document
from frappe.utils import now, time_diff_in_hours, now_datetime, getdate, get_weekdays, add_to_date, today, get_time, get_datetime
from datetime import datetime, timedelta
from frappe.model.mapper import get_mapped_doc
from frappe.utils.user import is_website_user
from erpnext.support.doctype.service_level_agreement.service_level_agreement import get_active_service_level_agreement_for
from frappe.email.inbox import link_communication_to_document
sender_field = "raised_by"
class Issue(Document):
def get_feed(self):
return "{0}: {1}".format(_(self.status), self.subject)
def validate(self):
if self.is_new() and self.via_customer_portal:
self.flags.create_communication = True
if not self.raised_by:
self.raised_by = frappe.session.user
self.change_service_level_agreement_and_priority()
self.update_status()
self.set_lead_contact(self.raised_by)
def on_update(self):
# Add a communication in the issue timeline
if self.flags.create_communication and self.via_customer_portal:
self.create_communication()
self.flags.communication_created = None
def set_lead_contact(self, email_id):
import email.utils
email_id = email.utils.parseaddr(email_id)[1]
if email_id:
if not self.lead:
self.lead = frappe.db.get_value("Lead", {"email_id": email_id})
if not self.contact and not self.customer:
self.contact = frappe.db.get_value("Contact", {"email_id": email_id})
if self.contact:
contact = frappe.get_doc('Contact', self.contact)
self.customer = contact.get_link_for('Customer')
if not self.company:
self.company = frappe.db.get_value("Lead", self.lead, "company") or \
frappe.db.get_default("Company")
def update_status(self):
status = frappe.db.get_value("Issue", self.name, "status")
if self.status!="Open" and status =="Open" and not self.first_responded_on:
self.first_responded_on = frappe.flags.current_time or now_datetime()
if self.status=="Closed" and status !="Closed":
self.resolution_date = frappe.flags.current_time or now_datetime()
if frappe.db.get_value("Issue", self.name, "agreement_fulfilled") == "Ongoing":
set_service_level_agreement_variance(issue=self.name)
self.update_agreement_status()
if self.status=="Open" and status !="Open":
# if no date, it should be set as None and not a blank string "", as per mysql strict config
self.resolution_date = None
def update_agreement_status(self):
if self.service_level_agreement and self.agreement_fulfilled == "Ongoing":
if frappe.db.get_value("Issue", self.name, "response_by_variance") < 0 or \
frappe.db.get_value("Issue", self.name, "resolution_by_variance") < 0:
self.agreement_fulfilled = "Failed"
else:
self.agreement_fulfilled = "Fulfilled"
def update_agreement_fulfilled_on_custom_status(self):
"""
Update Agreement Fulfilled status using Custom Scripts for Custom Issue Status
"""
if not self.first_responded_on: # first_responded_on set when first reply is sent to customer
self.response_by_variance = round(time_diff_in_hours(self.response_by, now_datetime()), 2)
if not self.resolution_date: # resolution_date set when issue has been closed
self.resolution_by_variance = round(time_diff_in_hours(self.resolution_by, now_datetime()), 2)
self.agreement_fulfilled = "Fulfilled" if self.response_by_variance > 0 and self.resolution_by_variance > 0 else "Failed"
def create_communication(self):
communication = frappe.new_doc("Communication")
communication.update({
"communication_type": "Communication",
"communication_medium": "Email",
"sent_or_received": "Received",
"email_status": "Open",
"subject": self.subject,
"sender": self.raised_by,
"content": self.description,
"status": "Linked",
"reference_doctype": "Issue",
"reference_name": self.name
})
communication.ignore_permissions = True
communication.ignore_mandatory = True
communication.save()
def split_issue(self, subject, communication_id):
# Bug: Pressing enter doesn't send subject
from copy import deepcopy
replicated_issue = deepcopy(self)
replicated_issue.subject = subject
replicated_issue.issue_split_from = self.name
replicated_issue.mins_to_first_response = 0
replicated_issue.first_responded_on = None
replicated_issue.creation = now_datetime()
# Reset SLA
if replicated_issue.service_level_agreement:
replicated_issue.service_level_agreement_creation = now_datetime()
replicated_issue.service_level_agreement = None
replicated_issue.agreement_fulfilled = "Ongoing"
replicated_issue.response_by = None
replicated_issue.response_by_variance = None
replicated_issue.resolution_by = None
replicated_issue.resolution_by_variance = None
frappe.get_doc(replicated_issue).insert()
# Replicate linked Communications
# TODO: get all communications in timeline before this, and modify them to append them to new doc
comm_to_split_from = frappe.get_doc("Communication", communication_id)
communications = frappe.get_all("Communication",
filters={"reference_doctype": "Issue",
"reference_name": comm_to_split_from.reference_name,
"creation": ('>=', comm_to_split_from.creation)})
for communication in communications:
doc = frappe.get_doc("Communication", communication.name)
doc.reference_name = replicated_issue.name
doc.save(ignore_permissions=True)
frappe.get_doc({
"doctype": "Comment",
"comment_type": "Info",
"reference_doctype": "Issue",
"reference_name": replicated_issue.name,
"content": " - Split the Issue from <a href='#Form/Issue/{0}'>{1}</a>".format(self.name, frappe.bold(self.name)),
}).insert(ignore_permissions=True)
return replicated_issue.name
def before_insert(self):
if frappe.db.get_single_value("Support Settings", "track_service_level_agreement"):
self.set_response_and_resolution_time()
def set_response_and_resolution_time(self, priority=None, service_level_agreement=None):
service_level_agreement = get_active_service_level_agreement_for(priority=priority,
customer=self.customer, service_level_agreement=service_level_agreement)
if not service_level_agreement:
if frappe.db.get_value("Issue", self.name, "service_level_agreement"):
frappe.throw(_("Couldn't Set Service Level Agreement {0}.").format(self.service_level_agreement))
return
if (service_level_agreement.customer and self.customer) and not (service_level_agreement.customer == self.customer):
frappe.throw(_("This Service Level Agreement is specific to Customer {0}").format(service_level_agreement.customer))
self.service_level_agreement = service_level_agreement.name
self.priority = service_level_agreement.default_priority if not priority else priority
service_level_agreement = frappe.get_doc("Service Level Agreement", service_level_agreement.name)
priority = service_level_agreement.get_service_level_agreement_priority(self.priority)
priority.update({
"support_and_resolution": service_level_agreement.support_and_resolution,
"holiday_list": service_level_agreement.holiday_list
})
if not self.creation:
self.creation = now_datetime()
self.service_level_agreement_creation = now_datetime()
start_date_time = get_datetime(self.service_level_agreement_creation)
self.response_by = get_expected_time_for(parameter='response', service_level=priority, start_date_time=start_date_time)
self.resolution_by = get_expected_time_for(parameter='resolution', service_level=priority, start_date_time=start_date_time)
self.response_by_variance = round(time_diff_in_hours(self.response_by, now_datetime()))
self.resolution_by_variance = round(time_diff_in_hours(self.resolution_by, now_datetime()))
def change_service_level_agreement_and_priority(self):
if self.service_level_agreement and frappe.db.exists("Issue", self.name) and \
frappe.db.get_single_value("Support Settings", "track_service_level_agreement"):
if not self.priority == frappe.db.get_value("Issue", self.name, "priority"):
self.set_response_and_resolution_time(priority=self.priority, service_level_agreement=self.service_level_agreement)
frappe.msgprint(_("Priority has been changed to {0}.").format(self.priority))
if not self.service_level_agreement == frappe.db.get_value("Issue", self.name, "service_level_agreement"):
self.set_response_and_resolution_time(priority=self.priority, service_level_agreement=self.service_level_agreement)
frappe.msgprint(_("Service Level Agreement has been changed to {0}.").format(self.service_level_agreement))
def reset_service_level_agreement(self, reason, user):
if not frappe.db.get_single_value("Support Settings", "allow_resetting_service_level_agreement"):
frappe.throw(_("Allow Resetting Service Level Agreement from Support Settings."))
frappe.get_doc({
"doctype": "Comment",
"comment_type": "Info",
"reference_doctype": self.doctype,
"reference_name": self.name,
"comment_email": user,
"content": " resetted Service Level Agreement - {0}".format(_(reason)),
}).insert(ignore_permissions=True)
self.service_level_agreement_creation = now_datetime()
self.set_response_and_resolution_time(priority=self.priority, service_level_agreement=self.service_level_agreement)
self.agreement_fulfilled = "Ongoing"
self.save()
def get_expected_time_for(parameter, service_level, start_date_time):
current_date_time = start_date_time
expected_time = current_date_time
start_time = None
end_time = None
# lets assume response time is in days by default
if parameter == 'response':
allotted_days = service_level.get("response_time")
time_period = service_level.get("response_time_period")
elif parameter == 'resolution':
allotted_days = service_level.get("resolution_time")
time_period = service_level.get("resolution_time_period")
else:
frappe.throw(_("{0} parameter is invalid").format(parameter))
allotted_hours = 0
if time_period == 'Hour':
allotted_hours = allotted_days
allotted_days = 0
elif time_period == 'Week':
allotted_days *= 7
expected_time_is_set = 1 if allotted_days == 0 and time_period in ['Day', 'Week'] else 0
support_days = {}
for service in service_level.get("support_and_resolution"):
support_days[service.workday] = frappe._dict({
'start_time': service.start_time,
'end_time': service.end_time,
})
holidays = get_holidays(service_level.get("holiday_list"))
weekdays = get_weekdays()
while not expected_time_is_set:
current_weekday = weekdays[current_date_time.weekday()]
if not is_holiday(current_date_time, holidays) and current_weekday in support_days:
start_time = current_date_time - datetime(current_date_time.year, current_date_time.month, current_date_time.day) \
if getdate(current_date_time) == getdate(start_date_time) and get_time_in_timedelta(current_date_time.time()) > support_days[current_weekday].start_time \
else support_days[current_weekday].start_time
end_time = support_days[current_weekday].end_time
time_left_today = time_diff_in_hours(end_time, start_time)
# no time left for support today
if time_left_today < 0: pass
elif time_period == 'Hour':
if time_left_today >= allotted_hours:
expected_time = datetime.combine(getdate(current_date_time), get_time(start_time))
expected_time = add_to_date(expected_time, hours=allotted_hours)
expected_time_is_set = 1
else:
allotted_hours = allotted_hours - time_left_today
else:
allotted_days -= 1
expected_time_is_set = allotted_days <= 0
if not expected_time_is_set:
current_date_time = add_to_date(current_date_time, days=1)
if end_time and time_period != 'Hour':
current_date_time = datetime.combine(getdate(current_date_time), get_time(end_time))
else:
current_date_time = expected_time
return current_date_time
def set_service_level_agreement_variance(issue=None):
current_time = frappe.flags.current_time or now_datetime()
filters = {"status": "Open", "agreement_fulfilled": "Ongoing"}
if issue:
filters = {"name": issue}
for issue in frappe.get_list("Issue", filters=filters):
doc = frappe.get_doc("Issue", issue.name)
if not doc.first_responded_on: # first_responded_on set when first reply is sent to customer
variance = round(time_diff_in_hours(doc.response_by, current_time), 2)
frappe.db.set_value(dt="Issue", dn=doc.name, field="response_by_variance", val=variance, update_modified=False)
if variance < 0:
frappe.db.set_value(dt="Issue", dn=doc.name, field="agreement_fulfilled", val="Failed", update_modified=False)
if not doc.resolution_date: # resolution_date set when issue has been closed
variance = round(time_diff_in_hours(doc.resolution_by, current_time), 2)
frappe.db.set_value(dt="Issue", dn=doc.name, field="resolution_by_variance", val=variance, update_modified=False)
if variance < 0:
frappe.db.set_value(dt="Issue", dn=doc.name, field="agreement_fulfilled", val="Failed", update_modified=False)
def get_list_context(context=None):
return {
"title": _("Issues"),
"get_list": get_issue_list,
"row_template": "templates/includes/issue_row.html",
"show_sidebar": True,
"show_search": True,
'no_breadcrumbs': True
}
def get_issue_list(doctype, txt, filters, limit_start, limit_page_length=20, order_by=None):
from frappe.www.list import get_list
user = frappe.session.user
contact = frappe.db.get_value('Contact', {'user': user}, 'name')
customer = None
if contact:
contact_doc = frappe.get_doc('Contact', contact)
customer = contact_doc.get_link_for('Customer')
ignore_permissions = False
if is_website_user():
if not filters:
|
filters.append(("Issue", "customer", "=", customer)) if customer else filters.append(("Issue", "raised_by", "=", user))
ignore_permissions = True
return get_list(doctype, txt, filters, limit_start, limit_page_length, ignore_permissions=ignore_permissions)
@frappe.whitelist()
def set_multiple_status(names, status):
names = json.loads(names)
for name in names:
set_status(name, status)
@frappe.whitelist()
def set_status(name, status):
st = frappe.get_doc("Issue", name)
st.status = status
st.save()
def auto_close_tickets():
"""Auto-close replied support tickets after 7 days"""
auto_close_after_days = frappe.db.get_value("Support Settings", "Support Settings", "close_issue_after_days") or 7
issues = frappe.db.sql(""" select name from tabIssue where status='Replied' and
modified<DATE_SUB(CURDATE(), INTERVAL %s DAY) """, (auto_close_after_days), as_dict=True)
for issue in issues:
doc = frappe.get_doc("Issue", issue.get("name"))
doc.status = "Closed"
doc.flags.ignore_permissions = True
doc.flags.ignore_mandatory = True
doc.save()
def has_website_permission(doc, ptype, user, verbose=False):
from erpnext.controllers.website_list_for_contact import has_website_permission
permission_based_on_customer = has_website_permission(doc, ptype, user, verbose)
return permission_based_on_customer or doc.raised_by==user
def update_issue(contact, method):
"""Called when Contact is deleted"""
frappe.db.sql("""UPDATE `tabIssue` set contact='' where contact=%s""", contact.name)
def get_holidays(holiday_list_name):
holiday_list = frappe.get_cached_doc("Holiday List", holiday_list_name)
holidays = [holiday.holiday_date for holiday in holiday_list.holidays]
return holidays
def is_holiday(date, holidays):
return getdate(date) in holidays
@frappe.whitelist()
def make_task(source_name, target_doc=None):
return get_mapped_doc("Issue", source_name, {
"Issue": {
"doctype": "Task"
}
}, target_doc)
@frappe.whitelist()
def make_issue_from_communication(communication, ignore_communication_links=False):
""" raise a issue from email """
doc = frappe.get_doc("Communication", communication)
issue = frappe.get_doc({
"doctype": "Issue",
"subject": doc.subject,
"communication_medium": doc.communication_medium,
"raised_by": doc.sender or "",
"raised_by_phone": doc.phone_no or ""
}).insert(ignore_permissions=True)
link_communication_to_document(doc, "Issue", issue.name, ignore_communication_links)
return issue.name
def get_time_in_timedelta(time):
"""
Converts datetime.time(10, 36, 55, 961454) to datetime.timedelta(seconds=38215)
"""
import datetime
return datetime.timedelta(hours=time.hour, minutes=time.minute, seconds=time.second)
|
filters = []
|
conditional_block
|
IonPrettyTextWriter.ts
|
/*!
* Copyright 2012 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
import { CharCodes } from "./IonText";
import { State, TextWriter } from "./IonTextWriter";
import { IonType } from "./IonType";
import { IonTypes } from "./IonTypes";
import { Writeable } from "./IonWriteable";
type Serializer<T> = (value: T) => void;
/*
* This class and functionality carry no guarantees of correctness or support.
* Do not rely on this functionality for more than front end formatting.
*/
export class PrettyTextWriter extends TextWriter {
private indentCount: number = 0;
constructor(writeable: Writeable, private readonly indentSize: number = 2) {
super(writeable);
}
writeFieldName(fieldName: string): void {
if (this.currentContainer.containerType !== IonTypes.STRUCT) {
throw new Error("Cannot write field name outside of a struct");
}
if (this.currentContainer.state !== State.STRUCT_FIELD) {
throw new Error("Expecting a struct value");
}
if (!this.currentContainer.clean) {
this.writeable.writeByte(CharCodes.COMMA);
this.writePrettyNewLine(0);
}
this.writePrettyIndent(0);
this.writeSymbolToken(fieldName);
this.writeable.writeByte(CharCodes.COLON);
this.writeable.writeByte(CharCodes.SPACE);
this.currentContainer.state = State.VALUE;
}
writeNull(type: IonType): void {
if (type === undefined || type === null) {
type = IonTypes.NULL;
}
this.handleSeparator();
this.writePrettyValue();
this.writeAnnotations();
this._writeNull(type);
if (this.currentContainer.containerType === IonTypes.STRUCT) {
this.currentContainer.state = State.STRUCT_FIELD;
}
}
stepOut(): void {
const currentContainer = this.containerContext.pop();
if (!currentContainer || !currentContainer.containerType) {
throw new Error("Can't step out when not in a container");
} else if (
currentContainer.containerType === IonTypes.STRUCT &&
currentContainer.state === State.VALUE
) {
throw new Error("Expecting a struct value");
}
if (!currentContainer.clean) {
this.writePrettyNewLine(0);
}
this.writePrettyIndent(-1);
switch (currentContainer.containerType) {
case IonTypes.LIST:
this.writeable.writeByte(CharCodes.RIGHT_BRACKET);
break;
case IonTypes.SEXP:
this.writeable.writeByte(CharCodes.RIGHT_PARENTHESIS);
break;
case IonTypes.STRUCT:
this.writeable.writeByte(CharCodes.RIGHT_BRACE);
break;
default:
throw new Error("Unexpected container type");
}
}
_serializeValue<T>(type: IonType, value: T, serialize: Serializer<T>) {
if (this.currentContainer.state === State.STRUCT_FIELD) {
throw new Error("Expecting a struct field");
}
if (value === null) {
this.writeNull(type);
return;
}
this.handleSeparator();
this.writePrettyValue();
this.writeAnnotations();
serialize(value);
if (this.currentContainer.containerType === IonTypes.STRUCT) {
this.currentContainer.state = State.STRUCT_FIELD;
}
}
writeContainer(type: IonType, openingCharacter: number): void {
if (
this.currentContainer.containerType === IonTypes.STRUCT &&
this.currentContainer.state === State.VALUE
) {
this.currentContainer.state = State.STRUCT_FIELD;
}
this.handleSeparator();
this.writePrettyValue();
this.writeAnnotations();
this.writeable.writeByte(openingCharacter);
this.writePrettyNewLine(1);
this._stepIn(type);
}
handleSeparator(): void {
if (this.depth() === 0) {
if (this.currentContainer.clean) {
this.currentContainer.clean = false;
} else {
this.writeable.writeByte(CharCodes.LINE_FEED);
}
} else {
if (this.currentContainer.clean) {
this.currentContainer.clean = false;
} else {
switch (this.currentContainer.containerType) {
case IonTypes.LIST:
this.writeable.writeByte(CharCodes.COMMA);
this.writePrettyNewLine(0);
break;
case IonTypes.SEXP:
this.writeable.writeByte(CharCodes.SPACE);
this.writePrettyNewLine(0);
break;
default:
// no op
}
}
}
}
private writePrettyValue(): void {
if (
this.depth() > 0 &&
this.currentContainer.containerType &&
this.currentContainer.containerType !== IonTypes.STRUCT
) {
this.writePrettyIndent(0);
}
}
private writePrettyNewLine(incrementValue: number): void {
this.indentCount = this.indentCount + incrementValue;
if (this.indentSize && this.indentSize > 0) {
this.writeable.writeByte(CharCodes.LINE_FEED);
}
}
private
|
(incrementValue: number): void {
this.indentCount = this.indentCount + incrementValue;
if (this.indentSize && this.indentSize > 0) {
for (let i = 0; i < this.indentCount * this.indentSize; i++) {
this.writeable.writeByte(CharCodes.SPACE);
}
}
}
}
|
writePrettyIndent
|
identifier_name
|
IonPrettyTextWriter.ts
|
/*!
* Copyright 2012 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
import { CharCodes } from "./IonText";
import { State, TextWriter } from "./IonTextWriter";
import { IonType } from "./IonType";
import { IonTypes } from "./IonTypes";
import { Writeable } from "./IonWriteable";
type Serializer<T> = (value: T) => void;
/*
* This class and functionality carry no guarantees of correctness or support.
* Do not rely on this functionality for more than front end formatting.
*/
export class PrettyTextWriter extends TextWriter {
private indentCount: number = 0;
constructor(writeable: Writeable, private readonly indentSize: number = 2) {
super(writeable);
}
writeFieldName(fieldName: string): void {
if (this.currentContainer.containerType !== IonTypes.STRUCT) {
throw new Error("Cannot write field name outside of a struct");
}
if (this.currentContainer.state !== State.STRUCT_FIELD) {
throw new Error("Expecting a struct value");
}
if (!this.currentContainer.clean) {
this.writeable.writeByte(CharCodes.COMMA);
this.writePrettyNewLine(0);
}
this.writePrettyIndent(0);
this.writeSymbolToken(fieldName);
this.writeable.writeByte(CharCodes.COLON);
this.writeable.writeByte(CharCodes.SPACE);
this.currentContainer.state = State.VALUE;
}
writeNull(type: IonType): void
|
stepOut(): void {
const currentContainer = this.containerContext.pop();
if (!currentContainer || !currentContainer.containerType) {
throw new Error("Can't step out when not in a container");
} else if (
currentContainer.containerType === IonTypes.STRUCT &&
currentContainer.state === State.VALUE
) {
throw new Error("Expecting a struct value");
}
if (!currentContainer.clean) {
this.writePrettyNewLine(0);
}
this.writePrettyIndent(-1);
switch (currentContainer.containerType) {
case IonTypes.LIST:
this.writeable.writeByte(CharCodes.RIGHT_BRACKET);
break;
case IonTypes.SEXP:
this.writeable.writeByte(CharCodes.RIGHT_PARENTHESIS);
break;
case IonTypes.STRUCT:
this.writeable.writeByte(CharCodes.RIGHT_BRACE);
break;
default:
throw new Error("Unexpected container type");
}
}
_serializeValue<T>(type: IonType, value: T, serialize: Serializer<T>) {
if (this.currentContainer.state === State.STRUCT_FIELD) {
throw new Error("Expecting a struct field");
}
if (value === null) {
this.writeNull(type);
return;
}
this.handleSeparator();
this.writePrettyValue();
this.writeAnnotations();
serialize(value);
if (this.currentContainer.containerType === IonTypes.STRUCT) {
this.currentContainer.state = State.STRUCT_FIELD;
}
}
writeContainer(type: IonType, openingCharacter: number): void {
if (
this.currentContainer.containerType === IonTypes.STRUCT &&
this.currentContainer.state === State.VALUE
) {
this.currentContainer.state = State.STRUCT_FIELD;
}
this.handleSeparator();
this.writePrettyValue();
this.writeAnnotations();
this.writeable.writeByte(openingCharacter);
this.writePrettyNewLine(1);
this._stepIn(type);
}
handleSeparator(): void {
if (this.depth() === 0) {
if (this.currentContainer.clean) {
this.currentContainer.clean = false;
} else {
this.writeable.writeByte(CharCodes.LINE_FEED);
}
} else {
if (this.currentContainer.clean) {
this.currentContainer.clean = false;
} else {
switch (this.currentContainer.containerType) {
case IonTypes.LIST:
this.writeable.writeByte(CharCodes.COMMA);
this.writePrettyNewLine(0);
break;
case IonTypes.SEXP:
this.writeable.writeByte(CharCodes.SPACE);
this.writePrettyNewLine(0);
break;
default:
// no op
}
}
}
}
private writePrettyValue(): void {
if (
this.depth() > 0 &&
this.currentContainer.containerType &&
this.currentContainer.containerType !== IonTypes.STRUCT
) {
this.writePrettyIndent(0);
}
}
private writePrettyNewLine(incrementValue: number): void {
this.indentCount = this.indentCount + incrementValue;
if (this.indentSize && this.indentSize > 0) {
this.writeable.writeByte(CharCodes.LINE_FEED);
}
}
private writePrettyIndent(incrementValue: number): void {
this.indentCount = this.indentCount + incrementValue;
if (this.indentSize && this.indentSize > 0) {
for (let i = 0; i < this.indentCount * this.indentSize; i++) {
this.writeable.writeByte(CharCodes.SPACE);
}
}
}
}
|
{
if (type === undefined || type === null) {
type = IonTypes.NULL;
}
this.handleSeparator();
this.writePrettyValue();
this.writeAnnotations();
this._writeNull(type);
if (this.currentContainer.containerType === IonTypes.STRUCT) {
this.currentContainer.state = State.STRUCT_FIELD;
}
}
|
identifier_body
|
IonPrettyTextWriter.ts
|
/*!
* Copyright 2012 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
import { CharCodes } from "./IonText";
import { State, TextWriter } from "./IonTextWriter";
import { IonType } from "./IonType";
import { IonTypes } from "./IonTypes";
import { Writeable } from "./IonWriteable";
type Serializer<T> = (value: T) => void;
/*
* This class and functionality carry no guarantees of correctness or support.
* Do not rely on this functionality for more than front end formatting.
*/
export class PrettyTextWriter extends TextWriter {
private indentCount: number = 0;
constructor(writeable: Writeable, private readonly indentSize: number = 2) {
super(writeable);
}
writeFieldName(fieldName: string): void {
if (this.currentContainer.containerType !== IonTypes.STRUCT) {
throw new Error("Cannot write field name outside of a struct");
}
if (this.currentContainer.state !== State.STRUCT_FIELD) {
throw new Error("Expecting a struct value");
}
if (!this.currentContainer.clean) {
this.writeable.writeByte(CharCodes.COMMA);
this.writePrettyNewLine(0);
}
|
this.writeSymbolToken(fieldName);
this.writeable.writeByte(CharCodes.COLON);
this.writeable.writeByte(CharCodes.SPACE);
this.currentContainer.state = State.VALUE;
}
writeNull(type: IonType): void {
if (type === undefined || type === null) {
type = IonTypes.NULL;
}
this.handleSeparator();
this.writePrettyValue();
this.writeAnnotations();
this._writeNull(type);
if (this.currentContainer.containerType === IonTypes.STRUCT) {
this.currentContainer.state = State.STRUCT_FIELD;
}
}
stepOut(): void {
const currentContainer = this.containerContext.pop();
if (!currentContainer || !currentContainer.containerType) {
throw new Error("Can't step out when not in a container");
} else if (
currentContainer.containerType === IonTypes.STRUCT &&
currentContainer.state === State.VALUE
) {
throw new Error("Expecting a struct value");
}
if (!currentContainer.clean) {
this.writePrettyNewLine(0);
}
this.writePrettyIndent(-1);
switch (currentContainer.containerType) {
case IonTypes.LIST:
this.writeable.writeByte(CharCodes.RIGHT_BRACKET);
break;
case IonTypes.SEXP:
this.writeable.writeByte(CharCodes.RIGHT_PARENTHESIS);
break;
case IonTypes.STRUCT:
this.writeable.writeByte(CharCodes.RIGHT_BRACE);
break;
default:
throw new Error("Unexpected container type");
}
}
_serializeValue<T>(type: IonType, value: T, serialize: Serializer<T>) {
if (this.currentContainer.state === State.STRUCT_FIELD) {
throw new Error("Expecting a struct field");
}
if (value === null) {
this.writeNull(type);
return;
}
this.handleSeparator();
this.writePrettyValue();
this.writeAnnotations();
serialize(value);
if (this.currentContainer.containerType === IonTypes.STRUCT) {
this.currentContainer.state = State.STRUCT_FIELD;
}
}
writeContainer(type: IonType, openingCharacter: number): void {
if (
this.currentContainer.containerType === IonTypes.STRUCT &&
this.currentContainer.state === State.VALUE
) {
this.currentContainer.state = State.STRUCT_FIELD;
}
this.handleSeparator();
this.writePrettyValue();
this.writeAnnotations();
this.writeable.writeByte(openingCharacter);
this.writePrettyNewLine(1);
this._stepIn(type);
}
handleSeparator(): void {
if (this.depth() === 0) {
if (this.currentContainer.clean) {
this.currentContainer.clean = false;
} else {
this.writeable.writeByte(CharCodes.LINE_FEED);
}
} else {
if (this.currentContainer.clean) {
this.currentContainer.clean = false;
} else {
switch (this.currentContainer.containerType) {
case IonTypes.LIST:
this.writeable.writeByte(CharCodes.COMMA);
this.writePrettyNewLine(0);
break;
case IonTypes.SEXP:
this.writeable.writeByte(CharCodes.SPACE);
this.writePrettyNewLine(0);
break;
default:
// no op
}
}
}
}
private writePrettyValue(): void {
if (
this.depth() > 0 &&
this.currentContainer.containerType &&
this.currentContainer.containerType !== IonTypes.STRUCT
) {
this.writePrettyIndent(0);
}
}
private writePrettyNewLine(incrementValue: number): void {
this.indentCount = this.indentCount + incrementValue;
if (this.indentSize && this.indentSize > 0) {
this.writeable.writeByte(CharCodes.LINE_FEED);
}
}
private writePrettyIndent(incrementValue: number): void {
this.indentCount = this.indentCount + incrementValue;
if (this.indentSize && this.indentSize > 0) {
for (let i = 0; i < this.indentCount * this.indentSize; i++) {
this.writeable.writeByte(CharCodes.SPACE);
}
}
}
}
|
this.writePrettyIndent(0);
|
random_line_split
|
item.py
|
#!/usr/bin/env python3
# Copyright (c) 2008-9 Qtrac Ltd. All rights reserved.
# This program or module 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 2 of the License, or
# version 3 of the License, or (at your option) any later version. It is
# provided for educational purposes and 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.
"""Provides the Item example classes.
"""
class Item(object):
def __init__(self, artist, title, year=None):
self.__artist = artist
self.__title = title
self.__year = year
def artist(self):
return self.__artist
def setArtist(self, artist):
self.__artist = artist
def title(self):
return self.__title
def setTitle(self, title):
self.__title = title
def year(self):
|
def setYear(self, year):
self.__year = year
def __str__(self):
year = ""
if self.__year is not None:
year = " in {0}".format(self.__year)
return "{0} by {1}{2}".format(self.__title, self.__artist, year)
class Painting(Item):
def __init__(self, artist, title, year=None):
super(Painting, self).__init__(artist, title, year)
class Sculpture(Item):
def __init__(self, artist, title, year=None, material=None):
super(Sculpture, self).__init__(artist, title, year)
self.__material = material
def material(self):
return self.__material
def setMaterial(self, material):
self.__material = material
def __str__(self):
materialString = ""
if self.__material is not None:
materialString = " ({0})".format(self.__material)
return "{0}{1}".format(super(Sculpture, self).__str__(),
materialString)
class Dimension(object):
def __init__(self, width, height, depth=None):
self.__width = width
self.__height = height
self.__depth = depth
def width(self):
return self.__width
def setWidth(self, width):
self.__width = width
def height(self):
return self.__height
def setHeight(self, height):
self.__height = height
def depth(self):
return self.__depth
def setDepth(self, depth):
self.__depth = depth
def area(self):
raise NotImplemented
def volume(self):
raise NotImplemented
if __name__ == "__main__":
items = []
items.append(Painting("Cecil Collins", "The Poet", 1941))
items.append(Painting("Cecil Collins", "The Sleeping Fool", 1943))
items.append(Painting("Edvard Munch", "The Scream", 1893))
items.append(Painting("Edvard Munch", "The Sick Child", 1896))
items.append(Painting("Edvard Munch", "The Dance of Life", 1900))
items.append(Sculpture("Auguste Rodin", "Eternal Springtime", 1917,
"plaster"))
items.append(Sculpture("Auguste Rodin", "Naked Balzac", 1917,
"plaster"))
items.append(Sculpture("Auguste Rodin", "The Secret", 1925,
"bronze"))
uniquematerials = set()
for item in items:
print(item)
if hasattr(item, "material"):
uniquematerials.add(item.material())
print("Sculptures use {0} unique materials".format(
len(uniquematerials)))
|
return self.__year
|
random_line_split
|
item.py
|
#!/usr/bin/env python3
# Copyright (c) 2008-9 Qtrac Ltd. All rights reserved.
# This program or module 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 2 of the License, or
# version 3 of the License, or (at your option) any later version. It is
# provided for educational purposes and 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.
"""Provides the Item example classes.
"""
class Item(object):
def __init__(self, artist, title, year=None):
self.__artist = artist
self.__title = title
self.__year = year
def artist(self):
return self.__artist
def setArtist(self, artist):
self.__artist = artist
def title(self):
return self.__title
def setTitle(self, title):
self.__title = title
def year(self):
return self.__year
def setYear(self, year):
self.__year = year
def __str__(self):
year = ""
if self.__year is not None:
year = " in {0}".format(self.__year)
return "{0} by {1}{2}".format(self.__title, self.__artist, year)
class Painting(Item):
def __init__(self, artist, title, year=None):
super(Painting, self).__init__(artist, title, year)
class Sculpture(Item):
def __init__(self, artist, title, year=None, material=None):
super(Sculpture, self).__init__(artist, title, year)
self.__material = material
def material(self):
return self.__material
def setMaterial(self, material):
self.__material = material
def __str__(self):
materialString = ""
if self.__material is not None:
materialString = " ({0})".format(self.__material)
return "{0}{1}".format(super(Sculpture, self).__str__(),
materialString)
class Dimension(object):
def __init__(self, width, height, depth=None):
self.__width = width
self.__height = height
self.__depth = depth
def width(self):
return self.__width
def setWidth(self, width):
self.__width = width
def height(self):
return self.__height
def setHeight(self, height):
self.__height = height
def depth(self):
return self.__depth
def setDepth(self, depth):
self.__depth = depth
def area(self):
raise NotImplemented
def volume(self):
raise NotImplemented
if __name__ == "__main__":
items = []
items.append(Painting("Cecil Collins", "The Poet", 1941))
items.append(Painting("Cecil Collins", "The Sleeping Fool", 1943))
items.append(Painting("Edvard Munch", "The Scream", 1893))
items.append(Painting("Edvard Munch", "The Sick Child", 1896))
items.append(Painting("Edvard Munch", "The Dance of Life", 1900))
items.append(Sculpture("Auguste Rodin", "Eternal Springtime", 1917,
"plaster"))
items.append(Sculpture("Auguste Rodin", "Naked Balzac", 1917,
"plaster"))
items.append(Sculpture("Auguste Rodin", "The Secret", 1925,
"bronze"))
uniquematerials = set()
for item in items:
print(item)
if hasattr(item, "material"):
|
print("Sculptures use {0} unique materials".format(
len(uniquematerials)))
|
uniquematerials.add(item.material())
|
conditional_block
|
item.py
|
#!/usr/bin/env python3
# Copyright (c) 2008-9 Qtrac Ltd. All rights reserved.
# This program or module 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 2 of the License, or
# version 3 of the License, or (at your option) any later version. It is
# provided for educational purposes and 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.
"""Provides the Item example classes.
"""
class Item(object):
def __init__(self, artist, title, year=None):
self.__artist = artist
self.__title = title
self.__year = year
def artist(self):
return self.__artist
def setArtist(self, artist):
self.__artist = artist
def title(self):
return self.__title
def setTitle(self, title):
self.__title = title
def year(self):
return self.__year
def setYear(self, year):
self.__year = year
def __str__(self):
year = ""
if self.__year is not None:
year = " in {0}".format(self.__year)
return "{0} by {1}{2}".format(self.__title, self.__artist, year)
class Painting(Item):
def __init__(self, artist, title, year=None):
super(Painting, self).__init__(artist, title, year)
class Sculpture(Item):
def __init__(self, artist, title, year=None, material=None):
super(Sculpture, self).__init__(artist, title, year)
self.__material = material
def material(self):
return self.__material
def setMaterial(self, material):
self.__material = material
def __str__(self):
materialString = ""
if self.__material is not None:
materialString = " ({0})".format(self.__material)
return "{0}{1}".format(super(Sculpture, self).__str__(),
materialString)
class Dimension(object):
def __init__(self, width, height, depth=None):
self.__width = width
self.__height = height
self.__depth = depth
def width(self):
return self.__width
def setWidth(self, width):
self.__width = width
def height(self):
return self.__height
def setHeight(self, height):
self.__height = height
def depth(self):
return self.__depth
def setDepth(self, depth):
self.__depth = depth
def
|
(self):
raise NotImplemented
def volume(self):
raise NotImplemented
if __name__ == "__main__":
items = []
items.append(Painting("Cecil Collins", "The Poet", 1941))
items.append(Painting("Cecil Collins", "The Sleeping Fool", 1943))
items.append(Painting("Edvard Munch", "The Scream", 1893))
items.append(Painting("Edvard Munch", "The Sick Child", 1896))
items.append(Painting("Edvard Munch", "The Dance of Life", 1900))
items.append(Sculpture("Auguste Rodin", "Eternal Springtime", 1917,
"plaster"))
items.append(Sculpture("Auguste Rodin", "Naked Balzac", 1917,
"plaster"))
items.append(Sculpture("Auguste Rodin", "The Secret", 1925,
"bronze"))
uniquematerials = set()
for item in items:
print(item)
if hasattr(item, "material"):
uniquematerials.add(item.material())
print("Sculptures use {0} unique materials".format(
len(uniquematerials)))
|
area
|
identifier_name
|
item.py
|
#!/usr/bin/env python3
# Copyright (c) 2008-9 Qtrac Ltd. All rights reserved.
# This program or module 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 2 of the License, or
# version 3 of the License, or (at your option) any later version. It is
# provided for educational purposes and 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.
"""Provides the Item example classes.
"""
class Item(object):
def __init__(self, artist, title, year=None):
self.__artist = artist
self.__title = title
self.__year = year
def artist(self):
return self.__artist
def setArtist(self, artist):
self.__artist = artist
def title(self):
return self.__title
def setTitle(self, title):
self.__title = title
def year(self):
return self.__year
def setYear(self, year):
self.__year = year
def __str__(self):
year = ""
if self.__year is not None:
year = " in {0}".format(self.__year)
return "{0} by {1}{2}".format(self.__title, self.__artist, year)
class Painting(Item):
def __init__(self, artist, title, year=None):
super(Painting, self).__init__(artist, title, year)
class Sculpture(Item):
|
class Dimension(object):
def __init__(self, width, height, depth=None):
self.__width = width
self.__height = height
self.__depth = depth
def width(self):
return self.__width
def setWidth(self, width):
self.__width = width
def height(self):
return self.__height
def setHeight(self, height):
self.__height = height
def depth(self):
return self.__depth
def setDepth(self, depth):
self.__depth = depth
def area(self):
raise NotImplemented
def volume(self):
raise NotImplemented
if __name__ == "__main__":
items = []
items.append(Painting("Cecil Collins", "The Poet", 1941))
items.append(Painting("Cecil Collins", "The Sleeping Fool", 1943))
items.append(Painting("Edvard Munch", "The Scream", 1893))
items.append(Painting("Edvard Munch", "The Sick Child", 1896))
items.append(Painting("Edvard Munch", "The Dance of Life", 1900))
items.append(Sculpture("Auguste Rodin", "Eternal Springtime", 1917,
"plaster"))
items.append(Sculpture("Auguste Rodin", "Naked Balzac", 1917,
"plaster"))
items.append(Sculpture("Auguste Rodin", "The Secret", 1925,
"bronze"))
uniquematerials = set()
for item in items:
print(item)
if hasattr(item, "material"):
uniquematerials.add(item.material())
print("Sculptures use {0} unique materials".format(
len(uniquematerials)))
|
def __init__(self, artist, title, year=None, material=None):
super(Sculpture, self).__init__(artist, title, year)
self.__material = material
def material(self):
return self.__material
def setMaterial(self, material):
self.__material = material
def __str__(self):
materialString = ""
if self.__material is not None:
materialString = " ({0})".format(self.__material)
return "{0}{1}".format(super(Sculpture, self).__str__(),
materialString)
|
identifier_body
|
unittest.py
|
#!/usr/bin/env python
# ***** BEGIN LICENSE BLOCK *****
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
# ***** END LICENSE BLOCK *****
import os
import re
from mozharness.mozilla.testing.errors import TinderBoxPrintRe
from mozharness.base.log import OutputParser, WARNING, INFO, CRITICAL
from mozharness.mozilla.buildbot import TBPL_WARNING, TBPL_FAILURE, TBPL_RETRY
from mozharness.mozilla.buildbot import TBPL_SUCCESS, TBPL_WORST_LEVEL_TUPLE
SUITE_CATEGORIES = ['mochitest', 'reftest', 'xpcshell']
def tbox_print_summary(pass_count, fail_count, known_fail_count=None,
crashed=False, leaked=False):
emphasize_fail_text = '<em class="testfail">%s</em>'
if pass_count < 0 or fail_count < 0 or \
(known_fail_count is not None and known_fail_count < 0):
summary = emphasize_fail_text % 'T-FAIL'
elif pass_count == 0 and fail_count == 0 and \
(known_fail_count == 0 or known_fail_count is None):
summary = emphasize_fail_text % 'T-FAIL'
else:
str_fail_count = str(fail_count)
if fail_count > 0:
str_fail_count = emphasize_fail_text % str_fail_count
summary = "%d/%s" % (pass_count, str_fail_count)
if known_fail_count is not None:
summary += "/%d" % known_fail_count
# Format the crash status.
if crashed:
summary += " %s" % emphasize_fail_text % "CRASH"
# Format the leak status.
if leaked is not False:
summary += " %s" % emphasize_fail_text % (
(leaked and "LEAK") or "L-FAIL")
return summary
class TestSummaryOutputParserHelper(OutputParser):
def __init__(self, regex=re.compile(r'(passed|failed|todo): (\d+)'), **kwargs):
self.regex = regex
self.failed = 0
self.passed = 0
self.todo = 0
self.last_line = None
super(TestSummaryOutputParserHelper, self).__init__(**kwargs)
def parse_single_line(self, line):
super(TestSummaryOutputParserHelper, self).parse_single_line(line)
self.last_line = line
m = self.regex.search(line)
if m:
try:
setattr(self, m.group(1), int(m.group(2)))
except ValueError:
# ignore bad values
pass
def evaluate_parser(self):
# generate the TinderboxPrint line for TBPL
emphasize_fail_text = '<em class="testfail">%s</em>'
failed = "0"
if self.passed == 0 and self.failed == 0:
self.tsummary = emphasize_fail_text % "T-FAIL"
else:
if self.failed > 0:
failed = emphasize_fail_text % str(self.failed)
self.tsummary = "%d/%s/%d" % (self.passed, failed, self.todo)
def print_summary(self, suite_name):
self.evaluate_parser()
self.info("TinderboxPrint: %s: %s\n" % (suite_name, self.tsummary))
class DesktopUnittestOutputParser(OutputParser):
|
class EmulatorMixin(object):
""" Currently dependent on both TooltoolMixin and TestingMixin)"""
def install_emulator_from_tooltool(self, manifest_path):
dirs = self.query_abs_dirs()
if self.tooltool_fetch(manifest_path, output_dir=dirs['abs_work_dir']):
self.fatal("Unable to download emulator via tooltool!")
unzip = self.query_exe("unzip")
unzip_cmd = [unzip, '-q', os.path.join(dirs['abs_work_dir'], "emulator.zip")]
self.run_command(unzip_cmd, cwd=dirs['abs_emulator_dir'], halt_on_failure=True,
fatal_exit_code=3)
def install_emulator(self):
dirs = self.query_abs_dirs()
self.mkdir_p(dirs['abs_emulator_dir'])
if self.config.get('emulator_url'):
self._download_unzip(self.config['emulator_url'], dirs['abs_emulator_dir'])
elif self.config.get('emulator_manifest'):
manifest_path = self.create_tooltool_manifest(self.config['emulator_manifest'])
self.install_emulator_from_tooltool(manifest_path)
elif self.buildbot_config:
props = self.buildbot_config.get('properties')
url = 'https://hg.mozilla.org/%s/raw-file/%s/b2g/test/emulator.manifest' % (
props['repo_path'], props['revision'])
manifest_path = self.download_file(url,
file_name='tooltool.tt',
parent_dir=dirs['abs_work_dir'])
if not manifest_path:
self.fatal("Can't download emulator manifest from %s" % url)
self.install_emulator_from_tooltool(manifest_path)
else:
self.fatal("Can't get emulator; set emulator_url or emulator_manifest in the config!")
|
"""
A class that extends OutputParser such that it can parse the number of
passed/failed/todo tests from the output.
"""
def __init__(self, suite_category, **kwargs):
# worst_log_level defined already in DesktopUnittestOutputParser
# but is here to make pylint happy
self.worst_log_level = INFO
super(DesktopUnittestOutputParser, self).__init__(**kwargs)
self.summary_suite_re = TinderBoxPrintRe.get('%s_summary' % suite_category, {})
self.harness_error_re = TinderBoxPrintRe['harness_error']['minimum_regex']
self.full_harness_error_re = TinderBoxPrintRe['harness_error']['full_regex']
self.harness_retry_re = TinderBoxPrintRe['harness_error']['retry_regex']
self.fail_count = -1
self.pass_count = -1
# known_fail_count does not exist for some suites
self.known_fail_count = self.summary_suite_re.get('known_fail_group') and -1
self.crashed, self.leaked = False, False
self.tbpl_status = TBPL_SUCCESS
def parse_single_line(self, line):
if self.summary_suite_re:
summary_m = self.summary_suite_re['regex'].match(line) # pass/fail/todo
if summary_m:
message = ' %s' % line
log_level = INFO
# remove all the none values in groups() so this will work
# with all suites including mochitest browser-chrome
summary_match_list = [group for group in summary_m.groups()
if group is not None]
r = summary_match_list[0]
if self.summary_suite_re['pass_group'] in r:
if len(summary_match_list) > 1:
self.pass_count = int(summary_match_list[-1])
else:
# This handles suites that either pass or report
# number of failures. We need to set both
# pass and fail count in the pass case.
self.pass_count = 1
self.fail_count = 0
elif self.summary_suite_re['fail_group'] in r:
self.fail_count = int(summary_match_list[-1])
if self.fail_count > 0:
message += '\n One or more unittests failed.'
log_level = WARNING
# If self.summary_suite_re['known_fail_group'] == None,
# then r should not match it, # so this test is fine as is.
elif self.summary_suite_re['known_fail_group'] in r:
self.known_fail_count = int(summary_match_list[-1])
self.log(message, log_level)
return # skip harness check and base parse_single_line
harness_match = self.harness_error_re.match(line)
if harness_match:
self.warning(' %s' % line)
self.worst_log_level = self.worst_level(WARNING, self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_WARNING, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
full_harness_match = self.full_harness_error_re.match(line)
if full_harness_match:
r = full_harness_match.group(1)
if r == "application crashed":
self.crashed = True
elif r == "missing output line for total leaks!":
self.leaked = None
else:
self.leaked = True
return # skip base parse_single_line
if self.harness_retry_re.search(line):
self.critical(' %s' % line)
self.worst_log_level = self.worst_level(CRITICAL, self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_RETRY, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
return # skip base parse_single_line
super(DesktopUnittestOutputParser, self).parse_single_line(line)
def evaluate_parser(self, return_code, success_codes=None):
success_codes = success_codes or [0]
if self.num_errors: # mozharness ran into a script error
self.tbpl_status = self.worst_level(TBPL_FAILURE, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
# I have to put this outside of parse_single_line because this checks not
# only if fail_count was more then 0 but also if fail_count is still -1
# (no fail summary line was found)
if self.fail_count != 0:
self.worst_log_level = self.worst_level(WARNING, self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_WARNING, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
# Account for the possibility that no test summary was output.
if self.pass_count <= 0 and self.fail_count <= 0 and \
(self.known_fail_count is None or self.known_fail_count <= 0):
self.error('No tests run or test summary not found')
self.worst_log_level = self.worst_level(WARNING,
self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_WARNING,
self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
if return_code not in success_codes:
self.tbpl_status = self.worst_level(TBPL_FAILURE, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
# we can trust in parser.worst_log_level in either case
return (self.tbpl_status, self.worst_log_level)
def append_tinderboxprint_line(self, suite_name):
# We are duplicating a condition (fail_count) from evaluate_parser and
# parse parse_single_line but at little cost since we are not parsing
# the log more then once. I figured this method should stay isolated as
# it is only here for tbpl highlighted summaries and is not part of
# buildbot evaluation or result status IIUC.
summary = tbox_print_summary(self.pass_count,
self.fail_count,
self.known_fail_count,
self.crashed,
self.leaked)
self.info("TinderboxPrint: %s<br/>%s\n" % (suite_name, summary))
|
identifier_body
|
unittest.py
|
#!/usr/bin/env python
# ***** BEGIN LICENSE BLOCK *****
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
# ***** END LICENSE BLOCK *****
import os
|
from mozharness.base.log import OutputParser, WARNING, INFO, CRITICAL
from mozharness.mozilla.buildbot import TBPL_WARNING, TBPL_FAILURE, TBPL_RETRY
from mozharness.mozilla.buildbot import TBPL_SUCCESS, TBPL_WORST_LEVEL_TUPLE
SUITE_CATEGORIES = ['mochitest', 'reftest', 'xpcshell']
def tbox_print_summary(pass_count, fail_count, known_fail_count=None,
crashed=False, leaked=False):
emphasize_fail_text = '<em class="testfail">%s</em>'
if pass_count < 0 or fail_count < 0 or \
(known_fail_count is not None and known_fail_count < 0):
summary = emphasize_fail_text % 'T-FAIL'
elif pass_count == 0 and fail_count == 0 and \
(known_fail_count == 0 or known_fail_count is None):
summary = emphasize_fail_text % 'T-FAIL'
else:
str_fail_count = str(fail_count)
if fail_count > 0:
str_fail_count = emphasize_fail_text % str_fail_count
summary = "%d/%s" % (pass_count, str_fail_count)
if known_fail_count is not None:
summary += "/%d" % known_fail_count
# Format the crash status.
if crashed:
summary += " %s" % emphasize_fail_text % "CRASH"
# Format the leak status.
if leaked is not False:
summary += " %s" % emphasize_fail_text % (
(leaked and "LEAK") or "L-FAIL")
return summary
class TestSummaryOutputParserHelper(OutputParser):
def __init__(self, regex=re.compile(r'(passed|failed|todo): (\d+)'), **kwargs):
self.regex = regex
self.failed = 0
self.passed = 0
self.todo = 0
self.last_line = None
super(TestSummaryOutputParserHelper, self).__init__(**kwargs)
def parse_single_line(self, line):
super(TestSummaryOutputParserHelper, self).parse_single_line(line)
self.last_line = line
m = self.regex.search(line)
if m:
try:
setattr(self, m.group(1), int(m.group(2)))
except ValueError:
# ignore bad values
pass
def evaluate_parser(self):
# generate the TinderboxPrint line for TBPL
emphasize_fail_text = '<em class="testfail">%s</em>'
failed = "0"
if self.passed == 0 and self.failed == 0:
self.tsummary = emphasize_fail_text % "T-FAIL"
else:
if self.failed > 0:
failed = emphasize_fail_text % str(self.failed)
self.tsummary = "%d/%s/%d" % (self.passed, failed, self.todo)
def print_summary(self, suite_name):
self.evaluate_parser()
self.info("TinderboxPrint: %s: %s\n" % (suite_name, self.tsummary))
class DesktopUnittestOutputParser(OutputParser):
"""
A class that extends OutputParser such that it can parse the number of
passed/failed/todo tests from the output.
"""
def __init__(self, suite_category, **kwargs):
# worst_log_level defined already in DesktopUnittestOutputParser
# but is here to make pylint happy
self.worst_log_level = INFO
super(DesktopUnittestOutputParser, self).__init__(**kwargs)
self.summary_suite_re = TinderBoxPrintRe.get('%s_summary' % suite_category, {})
self.harness_error_re = TinderBoxPrintRe['harness_error']['minimum_regex']
self.full_harness_error_re = TinderBoxPrintRe['harness_error']['full_regex']
self.harness_retry_re = TinderBoxPrintRe['harness_error']['retry_regex']
self.fail_count = -1
self.pass_count = -1
# known_fail_count does not exist for some suites
self.known_fail_count = self.summary_suite_re.get('known_fail_group') and -1
self.crashed, self.leaked = False, False
self.tbpl_status = TBPL_SUCCESS
def parse_single_line(self, line):
if self.summary_suite_re:
summary_m = self.summary_suite_re['regex'].match(line) # pass/fail/todo
if summary_m:
message = ' %s' % line
log_level = INFO
# remove all the none values in groups() so this will work
# with all suites including mochitest browser-chrome
summary_match_list = [group for group in summary_m.groups()
if group is not None]
r = summary_match_list[0]
if self.summary_suite_re['pass_group'] in r:
if len(summary_match_list) > 1:
self.pass_count = int(summary_match_list[-1])
else:
# This handles suites that either pass or report
# number of failures. We need to set both
# pass and fail count in the pass case.
self.pass_count = 1
self.fail_count = 0
elif self.summary_suite_re['fail_group'] in r:
self.fail_count = int(summary_match_list[-1])
if self.fail_count > 0:
message += '\n One or more unittests failed.'
log_level = WARNING
# If self.summary_suite_re['known_fail_group'] == None,
# then r should not match it, # so this test is fine as is.
elif self.summary_suite_re['known_fail_group'] in r:
self.known_fail_count = int(summary_match_list[-1])
self.log(message, log_level)
return # skip harness check and base parse_single_line
harness_match = self.harness_error_re.match(line)
if harness_match:
self.warning(' %s' % line)
self.worst_log_level = self.worst_level(WARNING, self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_WARNING, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
full_harness_match = self.full_harness_error_re.match(line)
if full_harness_match:
r = full_harness_match.group(1)
if r == "application crashed":
self.crashed = True
elif r == "missing output line for total leaks!":
self.leaked = None
else:
self.leaked = True
return # skip base parse_single_line
if self.harness_retry_re.search(line):
self.critical(' %s' % line)
self.worst_log_level = self.worst_level(CRITICAL, self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_RETRY, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
return # skip base parse_single_line
super(DesktopUnittestOutputParser, self).parse_single_line(line)
def evaluate_parser(self, return_code, success_codes=None):
success_codes = success_codes or [0]
if self.num_errors: # mozharness ran into a script error
self.tbpl_status = self.worst_level(TBPL_FAILURE, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
# I have to put this outside of parse_single_line because this checks not
# only if fail_count was more then 0 but also if fail_count is still -1
# (no fail summary line was found)
if self.fail_count != 0:
self.worst_log_level = self.worst_level(WARNING, self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_WARNING, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
# Account for the possibility that no test summary was output.
if self.pass_count <= 0 and self.fail_count <= 0 and \
(self.known_fail_count is None or self.known_fail_count <= 0):
self.error('No tests run or test summary not found')
self.worst_log_level = self.worst_level(WARNING,
self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_WARNING,
self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
if return_code not in success_codes:
self.tbpl_status = self.worst_level(TBPL_FAILURE, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
# we can trust in parser.worst_log_level in either case
return (self.tbpl_status, self.worst_log_level)
def append_tinderboxprint_line(self, suite_name):
# We are duplicating a condition (fail_count) from evaluate_parser and
# parse parse_single_line but at little cost since we are not parsing
# the log more then once. I figured this method should stay isolated as
# it is only here for tbpl highlighted summaries and is not part of
# buildbot evaluation or result status IIUC.
summary = tbox_print_summary(self.pass_count,
self.fail_count,
self.known_fail_count,
self.crashed,
self.leaked)
self.info("TinderboxPrint: %s<br/>%s\n" % (suite_name, summary))
class EmulatorMixin(object):
""" Currently dependent on both TooltoolMixin and TestingMixin)"""
def install_emulator_from_tooltool(self, manifest_path):
dirs = self.query_abs_dirs()
if self.tooltool_fetch(manifest_path, output_dir=dirs['abs_work_dir']):
self.fatal("Unable to download emulator via tooltool!")
unzip = self.query_exe("unzip")
unzip_cmd = [unzip, '-q', os.path.join(dirs['abs_work_dir'], "emulator.zip")]
self.run_command(unzip_cmd, cwd=dirs['abs_emulator_dir'], halt_on_failure=True,
fatal_exit_code=3)
def install_emulator(self):
dirs = self.query_abs_dirs()
self.mkdir_p(dirs['abs_emulator_dir'])
if self.config.get('emulator_url'):
self._download_unzip(self.config['emulator_url'], dirs['abs_emulator_dir'])
elif self.config.get('emulator_manifest'):
manifest_path = self.create_tooltool_manifest(self.config['emulator_manifest'])
self.install_emulator_from_tooltool(manifest_path)
elif self.buildbot_config:
props = self.buildbot_config.get('properties')
url = 'https://hg.mozilla.org/%s/raw-file/%s/b2g/test/emulator.manifest' % (
props['repo_path'], props['revision'])
manifest_path = self.download_file(url,
file_name='tooltool.tt',
parent_dir=dirs['abs_work_dir'])
if not manifest_path:
self.fatal("Can't download emulator manifest from %s" % url)
self.install_emulator_from_tooltool(manifest_path)
else:
self.fatal("Can't get emulator; set emulator_url or emulator_manifest in the config!")
|
import re
from mozharness.mozilla.testing.errors import TinderBoxPrintRe
|
random_line_split
|
unittest.py
|
#!/usr/bin/env python
# ***** BEGIN LICENSE BLOCK *****
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
# ***** END LICENSE BLOCK *****
import os
import re
from mozharness.mozilla.testing.errors import TinderBoxPrintRe
from mozharness.base.log import OutputParser, WARNING, INFO, CRITICAL
from mozharness.mozilla.buildbot import TBPL_WARNING, TBPL_FAILURE, TBPL_RETRY
from mozharness.mozilla.buildbot import TBPL_SUCCESS, TBPL_WORST_LEVEL_TUPLE
SUITE_CATEGORIES = ['mochitest', 'reftest', 'xpcshell']
def tbox_print_summary(pass_count, fail_count, known_fail_count=None,
crashed=False, leaked=False):
emphasize_fail_text = '<em class="testfail">%s</em>'
if pass_count < 0 or fail_count < 0 or \
(known_fail_count is not None and known_fail_count < 0):
summary = emphasize_fail_text % 'T-FAIL'
elif pass_count == 0 and fail_count == 0 and \
(known_fail_count == 0 or known_fail_count is None):
summary = emphasize_fail_text % 'T-FAIL'
else:
str_fail_count = str(fail_count)
if fail_count > 0:
str_fail_count = emphasize_fail_text % str_fail_count
summary = "%d/%s" % (pass_count, str_fail_count)
if known_fail_count is not None:
summary += "/%d" % known_fail_count
# Format the crash status.
if crashed:
summary += " %s" % emphasize_fail_text % "CRASH"
# Format the leak status.
if leaked is not False:
summary += " %s" % emphasize_fail_text % (
(leaked and "LEAK") or "L-FAIL")
return summary
class TestSummaryOutputParserHelper(OutputParser):
def __init__(self, regex=re.compile(r'(passed|failed|todo): (\d+)'), **kwargs):
self.regex = regex
self.failed = 0
self.passed = 0
self.todo = 0
self.last_line = None
super(TestSummaryOutputParserHelper, self).__init__(**kwargs)
def parse_single_line(self, line):
super(TestSummaryOutputParserHelper, self).parse_single_line(line)
self.last_line = line
m = self.regex.search(line)
if m:
try:
setattr(self, m.group(1), int(m.group(2)))
except ValueError:
# ignore bad values
pass
def evaluate_parser(self):
# generate the TinderboxPrint line for TBPL
emphasize_fail_text = '<em class="testfail">%s</em>'
failed = "0"
if self.passed == 0 and self.failed == 0:
self.tsummary = emphasize_fail_text % "T-FAIL"
else:
if self.failed > 0:
failed = emphasize_fail_text % str(self.failed)
self.tsummary = "%d/%s/%d" % (self.passed, failed, self.todo)
def print_summary(self, suite_name):
self.evaluate_parser()
self.info("TinderboxPrint: %s: %s\n" % (suite_name, self.tsummary))
class DesktopUnittestOutputParser(OutputParser):
"""
A class that extends OutputParser such that it can parse the number of
passed/failed/todo tests from the output.
"""
def __init__(self, suite_category, **kwargs):
# worst_log_level defined already in DesktopUnittestOutputParser
# but is here to make pylint happy
self.worst_log_level = INFO
super(DesktopUnittestOutputParser, self).__init__(**kwargs)
self.summary_suite_re = TinderBoxPrintRe.get('%s_summary' % suite_category, {})
self.harness_error_re = TinderBoxPrintRe['harness_error']['minimum_regex']
self.full_harness_error_re = TinderBoxPrintRe['harness_error']['full_regex']
self.harness_retry_re = TinderBoxPrintRe['harness_error']['retry_regex']
self.fail_count = -1
self.pass_count = -1
# known_fail_count does not exist for some suites
self.known_fail_count = self.summary_suite_re.get('known_fail_group') and -1
self.crashed, self.leaked = False, False
self.tbpl_status = TBPL_SUCCESS
def parse_single_line(self, line):
if self.summary_suite_re:
summary_m = self.summary_suite_re['regex'].match(line) # pass/fail/todo
if summary_m:
message = ' %s' % line
log_level = INFO
# remove all the none values in groups() so this will work
# with all suites including mochitest browser-chrome
summary_match_list = [group for group in summary_m.groups()
if group is not None]
r = summary_match_list[0]
if self.summary_suite_re['pass_group'] in r:
if len(summary_match_list) > 1:
self.pass_count = int(summary_match_list[-1])
else:
# This handles suites that either pass or report
# number of failures. We need to set both
# pass and fail count in the pass case.
self.pass_count = 1
self.fail_count = 0
elif self.summary_suite_re['fail_group'] in r:
self.fail_count = int(summary_match_list[-1])
if self.fail_count > 0:
message += '\n One or more unittests failed.'
log_level = WARNING
# If self.summary_suite_re['known_fail_group'] == None,
# then r should not match it, # so this test is fine as is.
elif self.summary_suite_re['known_fail_group'] in r:
self.known_fail_count = int(summary_match_list[-1])
self.log(message, log_level)
return # skip harness check and base parse_single_line
harness_match = self.harness_error_re.match(line)
if harness_match:
self.warning(' %s' % line)
self.worst_log_level = self.worst_level(WARNING, self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_WARNING, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
full_harness_match = self.full_harness_error_re.match(line)
if full_harness_match:
r = full_harness_match.group(1)
if r == "application crashed":
self.crashed = True
elif r == "missing output line for total leaks!":
self.leaked = None
else:
self.leaked = True
return # skip base parse_single_line
if self.harness_retry_re.search(line):
self.critical(' %s' % line)
self.worst_log_level = self.worst_level(CRITICAL, self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_RETRY, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
return # skip base parse_single_line
super(DesktopUnittestOutputParser, self).parse_single_line(line)
def evaluate_parser(self, return_code, success_codes=None):
success_codes = success_codes or [0]
if self.num_errors: # mozharness ran into a script error
self.tbpl_status = self.worst_level(TBPL_FAILURE, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
# I have to put this outside of parse_single_line because this checks not
# only if fail_count was more then 0 but also if fail_count is still -1
# (no fail summary line was found)
if self.fail_count != 0:
self.worst_log_level = self.worst_level(WARNING, self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_WARNING, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
# Account for the possibility that no test summary was output.
if self.pass_count <= 0 and self.fail_count <= 0 and \
(self.known_fail_count is None or self.known_fail_count <= 0):
self.error('No tests run or test summary not found')
self.worst_log_level = self.worst_level(WARNING,
self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_WARNING,
self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
if return_code not in success_codes:
self.tbpl_status = self.worst_level(TBPL_FAILURE, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
# we can trust in parser.worst_log_level in either case
return (self.tbpl_status, self.worst_log_level)
def append_tinderboxprint_line(self, suite_name):
# We are duplicating a condition (fail_count) from evaluate_parser and
# parse parse_single_line but at little cost since we are not parsing
# the log more then once. I figured this method should stay isolated as
# it is only here for tbpl highlighted summaries and is not part of
# buildbot evaluation or result status IIUC.
summary = tbox_print_summary(self.pass_count,
self.fail_count,
self.known_fail_count,
self.crashed,
self.leaked)
self.info("TinderboxPrint: %s<br/>%s\n" % (suite_name, summary))
class EmulatorMixin(object):
""" Currently dependent on both TooltoolMixin and TestingMixin)"""
def install_emulator_from_tooltool(self, manifest_path):
dirs = self.query_abs_dirs()
if self.tooltool_fetch(manifest_path, output_dir=dirs['abs_work_dir']):
self.fatal("Unable to download emulator via tooltool!")
unzip = self.query_exe("unzip")
unzip_cmd = [unzip, '-q', os.path.join(dirs['abs_work_dir'], "emulator.zip")]
self.run_command(unzip_cmd, cwd=dirs['abs_emulator_dir'], halt_on_failure=True,
fatal_exit_code=3)
def install_emulator(self):
dirs = self.query_abs_dirs()
self.mkdir_p(dirs['abs_emulator_dir'])
if self.config.get('emulator_url'):
|
elif self.config.get('emulator_manifest'):
manifest_path = self.create_tooltool_manifest(self.config['emulator_manifest'])
self.install_emulator_from_tooltool(manifest_path)
elif self.buildbot_config:
props = self.buildbot_config.get('properties')
url = 'https://hg.mozilla.org/%s/raw-file/%s/b2g/test/emulator.manifest' % (
props['repo_path'], props['revision'])
manifest_path = self.download_file(url,
file_name='tooltool.tt',
parent_dir=dirs['abs_work_dir'])
if not manifest_path:
self.fatal("Can't download emulator manifest from %s" % url)
self.install_emulator_from_tooltool(manifest_path)
else:
self.fatal("Can't get emulator; set emulator_url or emulator_manifest in the config!")
|
self._download_unzip(self.config['emulator_url'], dirs['abs_emulator_dir'])
|
conditional_block
|
unittest.py
|
#!/usr/bin/env python
# ***** BEGIN LICENSE BLOCK *****
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
# ***** END LICENSE BLOCK *****
import os
import re
from mozharness.mozilla.testing.errors import TinderBoxPrintRe
from mozharness.base.log import OutputParser, WARNING, INFO, CRITICAL
from mozharness.mozilla.buildbot import TBPL_WARNING, TBPL_FAILURE, TBPL_RETRY
from mozharness.mozilla.buildbot import TBPL_SUCCESS, TBPL_WORST_LEVEL_TUPLE
SUITE_CATEGORIES = ['mochitest', 'reftest', 'xpcshell']
def tbox_print_summary(pass_count, fail_count, known_fail_count=None,
crashed=False, leaked=False):
emphasize_fail_text = '<em class="testfail">%s</em>'
if pass_count < 0 or fail_count < 0 or \
(known_fail_count is not None and known_fail_count < 0):
summary = emphasize_fail_text % 'T-FAIL'
elif pass_count == 0 and fail_count == 0 and \
(known_fail_count == 0 or known_fail_count is None):
summary = emphasize_fail_text % 'T-FAIL'
else:
str_fail_count = str(fail_count)
if fail_count > 0:
str_fail_count = emphasize_fail_text % str_fail_count
summary = "%d/%s" % (pass_count, str_fail_count)
if known_fail_count is not None:
summary += "/%d" % known_fail_count
# Format the crash status.
if crashed:
summary += " %s" % emphasize_fail_text % "CRASH"
# Format the leak status.
if leaked is not False:
summary += " %s" % emphasize_fail_text % (
(leaked and "LEAK") or "L-FAIL")
return summary
class TestSummaryOutputParserHelper(OutputParser):
def __init__(self, regex=re.compile(r'(passed|failed|todo): (\d+)'), **kwargs):
self.regex = regex
self.failed = 0
self.passed = 0
self.todo = 0
self.last_line = None
super(TestSummaryOutputParserHelper, self).__init__(**kwargs)
def parse_single_line(self, line):
super(TestSummaryOutputParserHelper, self).parse_single_line(line)
self.last_line = line
m = self.regex.search(line)
if m:
try:
setattr(self, m.group(1), int(m.group(2)))
except ValueError:
# ignore bad values
pass
def evaluate_parser(self):
# generate the TinderboxPrint line for TBPL
emphasize_fail_text = '<em class="testfail">%s</em>'
failed = "0"
if self.passed == 0 and self.failed == 0:
self.tsummary = emphasize_fail_text % "T-FAIL"
else:
if self.failed > 0:
failed = emphasize_fail_text % str(self.failed)
self.tsummary = "%d/%s/%d" % (self.passed, failed, self.todo)
def print_summary(self, suite_name):
self.evaluate_parser()
self.info("TinderboxPrint: %s: %s\n" % (suite_name, self.tsummary))
class DesktopUnittestOutputParser(OutputParser):
"""
A class that extends OutputParser such that it can parse the number of
passed/failed/todo tests from the output.
"""
def __init__(self, suite_category, **kwargs):
# worst_log_level defined already in DesktopUnittestOutputParser
# but is here to make pylint happy
self.worst_log_level = INFO
super(DesktopUnittestOutputParser, self).__init__(**kwargs)
self.summary_suite_re = TinderBoxPrintRe.get('%s_summary' % suite_category, {})
self.harness_error_re = TinderBoxPrintRe['harness_error']['minimum_regex']
self.full_harness_error_re = TinderBoxPrintRe['harness_error']['full_regex']
self.harness_retry_re = TinderBoxPrintRe['harness_error']['retry_regex']
self.fail_count = -1
self.pass_count = -1
# known_fail_count does not exist for some suites
self.known_fail_count = self.summary_suite_re.get('known_fail_group') and -1
self.crashed, self.leaked = False, False
self.tbpl_status = TBPL_SUCCESS
def parse_single_line(self, line):
if self.summary_suite_re:
summary_m = self.summary_suite_re['regex'].match(line) # pass/fail/todo
if summary_m:
message = ' %s' % line
log_level = INFO
# remove all the none values in groups() so this will work
# with all suites including mochitest browser-chrome
summary_match_list = [group for group in summary_m.groups()
if group is not None]
r = summary_match_list[0]
if self.summary_suite_re['pass_group'] in r:
if len(summary_match_list) > 1:
self.pass_count = int(summary_match_list[-1])
else:
# This handles suites that either pass or report
# number of failures. We need to set both
# pass and fail count in the pass case.
self.pass_count = 1
self.fail_count = 0
elif self.summary_suite_re['fail_group'] in r:
self.fail_count = int(summary_match_list[-1])
if self.fail_count > 0:
message += '\n One or more unittests failed.'
log_level = WARNING
# If self.summary_suite_re['known_fail_group'] == None,
# then r should not match it, # so this test is fine as is.
elif self.summary_suite_re['known_fail_group'] in r:
self.known_fail_count = int(summary_match_list[-1])
self.log(message, log_level)
return # skip harness check and base parse_single_line
harness_match = self.harness_error_re.match(line)
if harness_match:
self.warning(' %s' % line)
self.worst_log_level = self.worst_level(WARNING, self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_WARNING, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
full_harness_match = self.full_harness_error_re.match(line)
if full_harness_match:
r = full_harness_match.group(1)
if r == "application crashed":
self.crashed = True
elif r == "missing output line for total leaks!":
self.leaked = None
else:
self.leaked = True
return # skip base parse_single_line
if self.harness_retry_re.search(line):
self.critical(' %s' % line)
self.worst_log_level = self.worst_level(CRITICAL, self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_RETRY, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
return # skip base parse_single_line
super(DesktopUnittestOutputParser, self).parse_single_line(line)
def evaluate_parser(self, return_code, success_codes=None):
success_codes = success_codes or [0]
if self.num_errors: # mozharness ran into a script error
self.tbpl_status = self.worst_level(TBPL_FAILURE, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
# I have to put this outside of parse_single_line because this checks not
# only if fail_count was more then 0 but also if fail_count is still -1
# (no fail summary line was found)
if self.fail_count != 0:
self.worst_log_level = self.worst_level(WARNING, self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_WARNING, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
# Account for the possibility that no test summary was output.
if self.pass_count <= 0 and self.fail_count <= 0 and \
(self.known_fail_count is None or self.known_fail_count <= 0):
self.error('No tests run or test summary not found')
self.worst_log_level = self.worst_level(WARNING,
self.worst_log_level)
self.tbpl_status = self.worst_level(TBPL_WARNING,
self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
if return_code not in success_codes:
self.tbpl_status = self.worst_level(TBPL_FAILURE, self.tbpl_status,
levels=TBPL_WORST_LEVEL_TUPLE)
# we can trust in parser.worst_log_level in either case
return (self.tbpl_status, self.worst_log_level)
def
|
(self, suite_name):
# We are duplicating a condition (fail_count) from evaluate_parser and
# parse parse_single_line but at little cost since we are not parsing
# the log more then once. I figured this method should stay isolated as
# it is only here for tbpl highlighted summaries and is not part of
# buildbot evaluation or result status IIUC.
summary = tbox_print_summary(self.pass_count,
self.fail_count,
self.known_fail_count,
self.crashed,
self.leaked)
self.info("TinderboxPrint: %s<br/>%s\n" % (suite_name, summary))
class EmulatorMixin(object):
""" Currently dependent on both TooltoolMixin and TestingMixin)"""
def install_emulator_from_tooltool(self, manifest_path):
dirs = self.query_abs_dirs()
if self.tooltool_fetch(manifest_path, output_dir=dirs['abs_work_dir']):
self.fatal("Unable to download emulator via tooltool!")
unzip = self.query_exe("unzip")
unzip_cmd = [unzip, '-q', os.path.join(dirs['abs_work_dir'], "emulator.zip")]
self.run_command(unzip_cmd, cwd=dirs['abs_emulator_dir'], halt_on_failure=True,
fatal_exit_code=3)
def install_emulator(self):
dirs = self.query_abs_dirs()
self.mkdir_p(dirs['abs_emulator_dir'])
if self.config.get('emulator_url'):
self._download_unzip(self.config['emulator_url'], dirs['abs_emulator_dir'])
elif self.config.get('emulator_manifest'):
manifest_path = self.create_tooltool_manifest(self.config['emulator_manifest'])
self.install_emulator_from_tooltool(manifest_path)
elif self.buildbot_config:
props = self.buildbot_config.get('properties')
url = 'https://hg.mozilla.org/%s/raw-file/%s/b2g/test/emulator.manifest' % (
props['repo_path'], props['revision'])
manifest_path = self.download_file(url,
file_name='tooltool.tt',
parent_dir=dirs['abs_work_dir'])
if not manifest_path:
self.fatal("Can't download emulator manifest from %s" % url)
self.install_emulator_from_tooltool(manifest_path)
else:
self.fatal("Can't get emulator; set emulator_url or emulator_manifest in the config!")
|
append_tinderboxprint_line
|
identifier_name
|
crypto-list.ts
|
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
@IonicPage()
@Component({
selector: 'page-crypto-list',
templateUrl: 'crypto-list.html',
})
export class CryptoListPage {
data = [
{
id: 'bitcoin',
name: 'Bitcoin',
symbol: 'btc',
rank: '1',
price_usd: '13208.8',
percent_change_1h: '1.54'
},
{
id: 'ethereum',
name: 'Ethereum',
symbol: 'eth',
rank: '2',
price_usd: '658.926',
percent_change_1h: '2.42'
},
{
id: 'bitcoin-cash',
name: 'Bitcoin Cash',
symbol: 'bch',
rank: '3',
price_usd: '2758.51',
percent_change_1h: '2.65'
},
{
id: 'ripple',
name: 'Ripple',
symbol: 'xrp',
rank: '4',
price_usd: '1.01963',
percent_change_1h: '0.98'
},
{
id: 'litecoin',
name: 'Litecoin',
|
symbol: 'ltc',
rank: '5',
price_usd: '263.913',
percent_change_1h: '2.21'
}
];
constructor(public navCtrl: NavController, public navParams: NavParams) {}
precision(n,m) {
return parseFloat(n).toFixed(m);
}
evolution(n) {
return n > 0
? '<span>' + parseFloat(n).toFixed(2) + ' <i class="fa fa-caret-up"></i></span>'
: '<span class="red">' + parseFloat(n).toFixed(2) + ' <i class="fa fa-caret-down"></i></span>';
}
}
|
random_line_split
|
|
crypto-list.ts
|
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
@IonicPage()
@Component({
selector: 'page-crypto-list',
templateUrl: 'crypto-list.html',
})
export class CryptoListPage {
data = [
{
id: 'bitcoin',
name: 'Bitcoin',
symbol: 'btc',
rank: '1',
price_usd: '13208.8',
percent_change_1h: '1.54'
},
{
id: 'ethereum',
name: 'Ethereum',
symbol: 'eth',
rank: '2',
price_usd: '658.926',
percent_change_1h: '2.42'
},
{
id: 'bitcoin-cash',
name: 'Bitcoin Cash',
symbol: 'bch',
rank: '3',
price_usd: '2758.51',
percent_change_1h: '2.65'
},
{
id: 'ripple',
name: 'Ripple',
symbol: 'xrp',
rank: '4',
price_usd: '1.01963',
percent_change_1h: '0.98'
},
{
id: 'litecoin',
name: 'Litecoin',
symbol: 'ltc',
rank: '5',
price_usd: '263.913',
percent_change_1h: '2.21'
}
];
constructor(public navCtrl: NavController, public navParams: NavParams) {}
precision(n,m) {
return parseFloat(n).toFixed(m);
}
|
(n) {
return n > 0
? '<span>' + parseFloat(n).toFixed(2) + ' <i class="fa fa-caret-up"></i></span>'
: '<span class="red">' + parseFloat(n).toFixed(2) + ' <i class="fa fa-caret-down"></i></span>';
}
}
|
evolution
|
identifier_name
|
trivial_client.py
|
from __future__ import print_function
import time
import argparse
import grpc
from jaeger_client import Config
from grpc_opentracing import open_tracing_client_interceptor
from grpc_opentracing.grpcext import intercept_channel
import command_line_pb2
def run():
parser = argparse.ArgumentParser()
parser.add_argument(
'--log_payloads',
action='store_true',
help='log request/response objects to open-tracing spans')
args = parser.parse_args()
config = Config(
config={
'sampler': {
'type': 'const',
'param': 1,
|
},
service_name='trivial-client')
tracer = config.initialize_tracer()
tracer_interceptor = open_tracing_client_interceptor(
tracer, log_payloads=args.log_payloads)
channel = grpc.insecure_channel('localhost:50051')
channel = intercept_channel(channel, tracer_interceptor)
stub = command_line_pb2.CommandLineStub(channel)
response = stub.Echo(command_line_pb2.CommandRequest(text='Hello, hello'))
print(response.text)
time.sleep(2)
tracer.close()
time.sleep(2)
if __name__ == '__main__':
run()
|
},
'logging': True,
|
random_line_split
|
trivial_client.py
|
from __future__ import print_function
import time
import argparse
import grpc
from jaeger_client import Config
from grpc_opentracing import open_tracing_client_interceptor
from grpc_opentracing.grpcext import intercept_channel
import command_line_pb2
def
|
():
parser = argparse.ArgumentParser()
parser.add_argument(
'--log_payloads',
action='store_true',
help='log request/response objects to open-tracing spans')
args = parser.parse_args()
config = Config(
config={
'sampler': {
'type': 'const',
'param': 1,
},
'logging': True,
},
service_name='trivial-client')
tracer = config.initialize_tracer()
tracer_interceptor = open_tracing_client_interceptor(
tracer, log_payloads=args.log_payloads)
channel = grpc.insecure_channel('localhost:50051')
channel = intercept_channel(channel, tracer_interceptor)
stub = command_line_pb2.CommandLineStub(channel)
response = stub.Echo(command_line_pb2.CommandRequest(text='Hello, hello'))
print(response.text)
time.sleep(2)
tracer.close()
time.sleep(2)
if __name__ == '__main__':
run()
|
run
|
identifier_name
|
trivial_client.py
|
from __future__ import print_function
import time
import argparse
import grpc
from jaeger_client import Config
from grpc_opentracing import open_tracing_client_interceptor
from grpc_opentracing.grpcext import intercept_channel
import command_line_pb2
def run():
parser = argparse.ArgumentParser()
parser.add_argument(
'--log_payloads',
action='store_true',
help='log request/response objects to open-tracing spans')
args = parser.parse_args()
config = Config(
config={
'sampler': {
'type': 'const',
'param': 1,
},
'logging': True,
},
service_name='trivial-client')
tracer = config.initialize_tracer()
tracer_interceptor = open_tracing_client_interceptor(
tracer, log_payloads=args.log_payloads)
channel = grpc.insecure_channel('localhost:50051')
channel = intercept_channel(channel, tracer_interceptor)
stub = command_line_pb2.CommandLineStub(channel)
response = stub.Echo(command_line_pb2.CommandRequest(text='Hello, hello'))
print(response.text)
time.sleep(2)
tracer.close()
time.sleep(2)
if __name__ == '__main__':
|
run()
|
conditional_block
|
|
trivial_client.py
|
from __future__ import print_function
import time
import argparse
import grpc
from jaeger_client import Config
from grpc_opentracing import open_tracing_client_interceptor
from grpc_opentracing.grpcext import intercept_channel
import command_line_pb2
def run():
|
if __name__ == '__main__':
run()
|
parser = argparse.ArgumentParser()
parser.add_argument(
'--log_payloads',
action='store_true',
help='log request/response objects to open-tracing spans')
args = parser.parse_args()
config = Config(
config={
'sampler': {
'type': 'const',
'param': 1,
},
'logging': True,
},
service_name='trivial-client')
tracer = config.initialize_tracer()
tracer_interceptor = open_tracing_client_interceptor(
tracer, log_payloads=args.log_payloads)
channel = grpc.insecure_channel('localhost:50051')
channel = intercept_channel(channel, tracer_interceptor)
stub = command_line_pb2.CommandLineStub(channel)
response = stub.Echo(command_line_pb2.CommandRequest(text='Hello, hello'))
print(response.text)
time.sleep(2)
tracer.close()
time.sleep(2)
|
identifier_body
|
transmission.rs
|
//! A minimal implementation of rpc client for Tranmission.
use reqwest::header::HeaderValue;
use reqwest::{self, Client, IntoUrl, StatusCode, Url};
use serde_json::Value;
use std::{fmt, result};
pub type Result<T> = result::Result<T, failure::Error>;
|
#[fail(display = "failed to get SessionId from header")]
SessionIdNotFound,
#[fail(display = "unexpected status code: {}", status)]
UnexpectedStatus { status: reqwest::StatusCode },
#[fail(display = "the transmission server responded with an error: {}", error)]
ResponseError { error: String },
}
/// A enum that represents the "ids" field in request body.
#[derive(Debug, Clone, Copy)]
pub enum TorrentSelect<'a> {
Ids(&'a [String]),
All,
}
/// A struct that represents the "delete-local-data" field in request body.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct DeleteLocalData(pub bool);
/// A structure that represents fields for torrent-get request.
///
/// It provides only the minimum required fields.
#[derive(Debug, Clone, Copy, Serialize)]
pub enum ArgGet {
#[serde(rename = "hashString")]
HashString,
#[serde(rename = "status")]
Status,
}
// https://github.com/serde-rs/serde/issues/497
macro_rules! enum_number_de {
($name:ident { $($variant:ident = $value:expr, )* }) => {
#[derive(Debug, Clone, Copy)]
pub enum $name {
$($variant = $value,)*
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
where D: serde::Deserializer<'de>
{
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = $name;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("positive integer")
}
fn visit_u64<E>(self, value: u64) -> result::Result<$name, E>
where E: serde::de::Error
{
match value {
$( $value => Ok($name::$variant), )*
_ => Err(E::custom(
format!("unknown {} value: {}",
stringify!($name), value))),
}
}
}
deserializer.deserialize_u64(Visitor)
}
}
}
}
/// A enum that represents a torrent status.
enum_number_de!(TorrentStatus {
TorrentIsStopped = 0,
QueuedToCheckFiles = 1,
CheckingFiles = 2,
QueuedToDownload = 3,
Downloading = 4,
QueuedToSeed = 5,
Seeding = 6,
});
/// A struct that represents a "torrents" object in response body.
///
/// It provides only the minimum required fields.
#[derive(Debug, Clone, Deserialize)]
pub struct ResponseGet {
#[serde(rename = "hashString")]
pub hash: String,
pub status: TorrentStatus,
}
/// A struct that represents a "arguments" object in response body.
#[derive(Debug, Clone, Deserialize)]
struct ResponseArgument {
#[serde(default)]
torrents: Vec<ResponseGet>,
}
/// A enum that represents a response status.
#[derive(Debug, Clone, Deserialize)]
pub enum ResponseStatus {
#[serde(rename = "success")]
Success,
Error(String),
}
/// A struct that represents a response body.
#[derive(Debug, Clone, Deserialize)]
struct Response {
arguments: ResponseArgument,
result: ResponseStatus,
}
/// RPC username and password.
#[derive(Debug)]
struct User {
name: String,
password: String,
}
/// Torrent client.
#[derive(Debug)]
pub struct Transmission {
url: Url,
user: Option<User>,
sid: HeaderValue,
http_client: Client,
}
macro_rules! requ_json {
($var:ident , $method:tt $(,$argstring:tt : $argname:ident)*) => {
match $var {
TorrentSelect::Ids(vec) => json!({"arguments":{$($argstring:$argname,)* "ids":vec}, "method":$method}),
TorrentSelect::All => json!({"arguments":{$($argstring:$argname,)*}, "method":$method}),
}
}
}
macro_rules! empty_response {
($name:ident, $method:tt $(,$argname:ident : $argtype:ident : $argstring:tt)*) => {
pub fn $name(&self, t: TorrentSelect<'_> $(,$argname:$argtype)*) -> Result<()> {
match self.request(&requ_json!(t,$method $(,$argstring:$argname)*))?.json::<Response>()?.result {
ResponseStatus::Success => Ok(()),
ResponseStatus::Error(error) => Err(TransmissionError::ResponseError{ error }.into()),
}
}
}
}
impl Transmission {
/// Crate new `Transmission` struct.
///
/// Fails if a `url` can not be parsed or if HTTP client fails.
pub fn new<U>(url: U, user: Option<(String, String)>) -> Result<Self>
where
U: IntoUrl,
{
let user = if let Some((n, p)) = user {
Some(User {
name: n,
password: p,
})
} else {
None
};
let url = url.into_url()?;
let http_client = Client::new();
let sid = http_client
.get(url.clone())
.send()?
.headers()
.get("X-Transmission-Session-Id")
.ok_or(TransmissionError::SessionIdNotFound)?
.clone();
Ok(Self {
url,
user,
sid,
http_client,
})
}
pub fn url(&self) -> &str {
self.url.as_str()
}
/// Make a request to the Transmission.
///
/// If the response status is 200, then return a response.
/// If the response status is 409, then try again with a new SID.
/// Otherwise return an error.
fn request(&self, json: &Value) -> Result<reqwest::Response> {
let resp = self
.http_client
.post(self.url.clone())
.json(json)
.header("X-Transmission-Session-Id", self.sid.clone())
.send()?;
match resp.status() {
StatusCode::OK => Ok(resp),
_ => Err(TransmissionError::UnexpectedStatus {
status: resp.status(),
}
.into()),
}
}
/// Start a list of torrents in the Transmission.
empty_response!(start, "torrent-start");
/// Stop a list of torrents in the Transmission.
empty_response!(stop, "torrent-stop");
/// Remove a list of torrents in the Transmission.
empty_response!(remove, "torrent-remove", d:DeleteLocalData:"delete-local-data");
/// Get a list of torrents from the Transmission.
pub fn get(&self, t: TorrentSelect<'_>, f: &[ArgGet]) -> Result<Vec<ResponseGet>> {
let responce = self
.request(&requ_json!(t, "torrent-get", "fields": f))?
.json::<Response>()?;
match responce.result {
ResponseStatus::Success => Ok(responce.arguments.torrents),
ResponseStatus::Error(error) => Err(TransmissionError::ResponseError { error }.into()),
}
}
}
|
#[derive(Debug, Fail)]
enum TransmissionError {
|
random_line_split
|
transmission.rs
|
//! A minimal implementation of rpc client for Tranmission.
use reqwest::header::HeaderValue;
use reqwest::{self, Client, IntoUrl, StatusCode, Url};
use serde_json::Value;
use std::{fmt, result};
pub type Result<T> = result::Result<T, failure::Error>;
#[derive(Debug, Fail)]
enum TransmissionError {
#[fail(display = "failed to get SessionId from header")]
SessionIdNotFound,
#[fail(display = "unexpected status code: {}", status)]
UnexpectedStatus { status: reqwest::StatusCode },
#[fail(display = "the transmission server responded with an error: {}", error)]
ResponseError { error: String },
}
/// A enum that represents the "ids" field in request body.
#[derive(Debug, Clone, Copy)]
pub enum TorrentSelect<'a> {
Ids(&'a [String]),
All,
}
/// A struct that represents the "delete-local-data" field in request body.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct DeleteLocalData(pub bool);
/// A structure that represents fields for torrent-get request.
///
/// It provides only the minimum required fields.
#[derive(Debug, Clone, Copy, Serialize)]
pub enum ArgGet {
#[serde(rename = "hashString")]
HashString,
#[serde(rename = "status")]
Status,
}
// https://github.com/serde-rs/serde/issues/497
macro_rules! enum_number_de {
($name:ident { $($variant:ident = $value:expr, )* }) => {
#[derive(Debug, Clone, Copy)]
pub enum $name {
$($variant = $value,)*
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
where D: serde::Deserializer<'de>
{
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = $name;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("positive integer")
}
fn visit_u64<E>(self, value: u64) -> result::Result<$name, E>
where E: serde::de::Error
{
match value {
$( $value => Ok($name::$variant), )*
_ => Err(E::custom(
format!("unknown {} value: {}",
stringify!($name), value))),
}
}
}
deserializer.deserialize_u64(Visitor)
}
}
}
}
/// A enum that represents a torrent status.
enum_number_de!(TorrentStatus {
TorrentIsStopped = 0,
QueuedToCheckFiles = 1,
CheckingFiles = 2,
QueuedToDownload = 3,
Downloading = 4,
QueuedToSeed = 5,
Seeding = 6,
});
/// A struct that represents a "torrents" object in response body.
///
/// It provides only the minimum required fields.
#[derive(Debug, Clone, Deserialize)]
pub struct ResponseGet {
#[serde(rename = "hashString")]
pub hash: String,
pub status: TorrentStatus,
}
/// A struct that represents a "arguments" object in response body.
#[derive(Debug, Clone, Deserialize)]
struct ResponseArgument {
#[serde(default)]
torrents: Vec<ResponseGet>,
}
/// A enum that represents a response status.
#[derive(Debug, Clone, Deserialize)]
pub enum ResponseStatus {
#[serde(rename = "success")]
Success,
Error(String),
}
/// A struct that represents a response body.
#[derive(Debug, Clone, Deserialize)]
struct Response {
arguments: ResponseArgument,
result: ResponseStatus,
}
/// RPC username and password.
#[derive(Debug)]
struct User {
name: String,
password: String,
}
/// Torrent client.
#[derive(Debug)]
pub struct Transmission {
url: Url,
user: Option<User>,
sid: HeaderValue,
http_client: Client,
}
macro_rules! requ_json {
($var:ident , $method:tt $(,$argstring:tt : $argname:ident)*) => {
match $var {
TorrentSelect::Ids(vec) => json!({"arguments":{$($argstring:$argname,)* "ids":vec}, "method":$method}),
TorrentSelect::All => json!({"arguments":{$($argstring:$argname,)*}, "method":$method}),
}
}
}
macro_rules! empty_response {
($name:ident, $method:tt $(,$argname:ident : $argtype:ident : $argstring:tt)*) => {
pub fn $name(&self, t: TorrentSelect<'_> $(,$argname:$argtype)*) -> Result<()> {
match self.request(&requ_json!(t,$method $(,$argstring:$argname)*))?.json::<Response>()?.result {
ResponseStatus::Success => Ok(()),
ResponseStatus::Error(error) => Err(TransmissionError::ResponseError{ error }.into()),
}
}
}
}
impl Transmission {
/// Crate new `Transmission` struct.
///
/// Fails if a `url` can not be parsed or if HTTP client fails.
pub fn new<U>(url: U, user: Option<(String, String)>) -> Result<Self>
where
U: IntoUrl,
{
let user = if let Some((n, p)) = user {
Some(User {
name: n,
password: p,
})
} else
|
;
let url = url.into_url()?;
let http_client = Client::new();
let sid = http_client
.get(url.clone())
.send()?
.headers()
.get("X-Transmission-Session-Id")
.ok_or(TransmissionError::SessionIdNotFound)?
.clone();
Ok(Self {
url,
user,
sid,
http_client,
})
}
pub fn url(&self) -> &str {
self.url.as_str()
}
/// Make a request to the Transmission.
///
/// If the response status is 200, then return a response.
/// If the response status is 409, then try again with a new SID.
/// Otherwise return an error.
fn request(&self, json: &Value) -> Result<reqwest::Response> {
let resp = self
.http_client
.post(self.url.clone())
.json(json)
.header("X-Transmission-Session-Id", self.sid.clone())
.send()?;
match resp.status() {
StatusCode::OK => Ok(resp),
_ => Err(TransmissionError::UnexpectedStatus {
status: resp.status(),
}
.into()),
}
}
/// Start a list of torrents in the Transmission.
empty_response!(start, "torrent-start");
/// Stop a list of torrents in the Transmission.
empty_response!(stop, "torrent-stop");
/// Remove a list of torrents in the Transmission.
empty_response!(remove, "torrent-remove", d:DeleteLocalData:"delete-local-data");
/// Get a list of torrents from the Transmission.
pub fn get(&self, t: TorrentSelect<'_>, f: &[ArgGet]) -> Result<Vec<ResponseGet>> {
let responce = self
.request(&requ_json!(t, "torrent-get", "fields": f))?
.json::<Response>()?;
match responce.result {
ResponseStatus::Success => Ok(responce.arguments.torrents),
ResponseStatus::Error(error) => Err(TransmissionError::ResponseError { error }.into()),
}
}
}
|
{
None
}
|
conditional_block
|
transmission.rs
|
//! A minimal implementation of rpc client for Tranmission.
use reqwest::header::HeaderValue;
use reqwest::{self, Client, IntoUrl, StatusCode, Url};
use serde_json::Value;
use std::{fmt, result};
pub type Result<T> = result::Result<T, failure::Error>;
#[derive(Debug, Fail)]
enum TransmissionError {
#[fail(display = "failed to get SessionId from header")]
SessionIdNotFound,
#[fail(display = "unexpected status code: {}", status)]
UnexpectedStatus { status: reqwest::StatusCode },
#[fail(display = "the transmission server responded with an error: {}", error)]
ResponseError { error: String },
}
/// A enum that represents the "ids" field in request body.
#[derive(Debug, Clone, Copy)]
pub enum TorrentSelect<'a> {
Ids(&'a [String]),
All,
}
/// A struct that represents the "delete-local-data" field in request body.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct DeleteLocalData(pub bool);
/// A structure that represents fields for torrent-get request.
///
/// It provides only the minimum required fields.
#[derive(Debug, Clone, Copy, Serialize)]
pub enum ArgGet {
#[serde(rename = "hashString")]
HashString,
#[serde(rename = "status")]
Status,
}
// https://github.com/serde-rs/serde/issues/497
macro_rules! enum_number_de {
($name:ident { $($variant:ident = $value:expr, )* }) => {
#[derive(Debug, Clone, Copy)]
pub enum $name {
$($variant = $value,)*
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
where D: serde::Deserializer<'de>
{
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = $name;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("positive integer")
}
fn visit_u64<E>(self, value: u64) -> result::Result<$name, E>
where E: serde::de::Error
{
match value {
$( $value => Ok($name::$variant), )*
_ => Err(E::custom(
format!("unknown {} value: {}",
stringify!($name), value))),
}
}
}
deserializer.deserialize_u64(Visitor)
}
}
}
}
/// A enum that represents a torrent status.
enum_number_de!(TorrentStatus {
TorrentIsStopped = 0,
QueuedToCheckFiles = 1,
CheckingFiles = 2,
QueuedToDownload = 3,
Downloading = 4,
QueuedToSeed = 5,
Seeding = 6,
});
/// A struct that represents a "torrents" object in response body.
///
/// It provides only the minimum required fields.
#[derive(Debug, Clone, Deserialize)]
pub struct ResponseGet {
#[serde(rename = "hashString")]
pub hash: String,
pub status: TorrentStatus,
}
/// A struct that represents a "arguments" object in response body.
#[derive(Debug, Clone, Deserialize)]
struct ResponseArgument {
#[serde(default)]
torrents: Vec<ResponseGet>,
}
/// A enum that represents a response status.
#[derive(Debug, Clone, Deserialize)]
pub enum ResponseStatus {
#[serde(rename = "success")]
Success,
Error(String),
}
/// A struct that represents a response body.
#[derive(Debug, Clone, Deserialize)]
struct Response {
arguments: ResponseArgument,
result: ResponseStatus,
}
/// RPC username and password.
#[derive(Debug)]
struct User {
name: String,
password: String,
}
/// Torrent client.
#[derive(Debug)]
pub struct Transmission {
url: Url,
user: Option<User>,
sid: HeaderValue,
http_client: Client,
}
macro_rules! requ_json {
($var:ident , $method:tt $(,$argstring:tt : $argname:ident)*) => {
match $var {
TorrentSelect::Ids(vec) => json!({"arguments":{$($argstring:$argname,)* "ids":vec}, "method":$method}),
TorrentSelect::All => json!({"arguments":{$($argstring:$argname,)*}, "method":$method}),
}
}
}
macro_rules! empty_response {
($name:ident, $method:tt $(,$argname:ident : $argtype:ident : $argstring:tt)*) => {
pub fn $name(&self, t: TorrentSelect<'_> $(,$argname:$argtype)*) -> Result<()> {
match self.request(&requ_json!(t,$method $(,$argstring:$argname)*))?.json::<Response>()?.result {
ResponseStatus::Success => Ok(()),
ResponseStatus::Error(error) => Err(TransmissionError::ResponseError{ error }.into()),
}
}
}
}
impl Transmission {
/// Crate new `Transmission` struct.
///
/// Fails if a `url` can not be parsed or if HTTP client fails.
pub fn
|
<U>(url: U, user: Option<(String, String)>) -> Result<Self>
where
U: IntoUrl,
{
let user = if let Some((n, p)) = user {
Some(User {
name: n,
password: p,
})
} else {
None
};
let url = url.into_url()?;
let http_client = Client::new();
let sid = http_client
.get(url.clone())
.send()?
.headers()
.get("X-Transmission-Session-Id")
.ok_or(TransmissionError::SessionIdNotFound)?
.clone();
Ok(Self {
url,
user,
sid,
http_client,
})
}
pub fn url(&self) -> &str {
self.url.as_str()
}
/// Make a request to the Transmission.
///
/// If the response status is 200, then return a response.
/// If the response status is 409, then try again with a new SID.
/// Otherwise return an error.
fn request(&self, json: &Value) -> Result<reqwest::Response> {
let resp = self
.http_client
.post(self.url.clone())
.json(json)
.header("X-Transmission-Session-Id", self.sid.clone())
.send()?;
match resp.status() {
StatusCode::OK => Ok(resp),
_ => Err(TransmissionError::UnexpectedStatus {
status: resp.status(),
}
.into()),
}
}
/// Start a list of torrents in the Transmission.
empty_response!(start, "torrent-start");
/// Stop a list of torrents in the Transmission.
empty_response!(stop, "torrent-stop");
/// Remove a list of torrents in the Transmission.
empty_response!(remove, "torrent-remove", d:DeleteLocalData:"delete-local-data");
/// Get a list of torrents from the Transmission.
pub fn get(&self, t: TorrentSelect<'_>, f: &[ArgGet]) -> Result<Vec<ResponseGet>> {
let responce = self
.request(&requ_json!(t, "torrent-get", "fields": f))?
.json::<Response>()?;
match responce.result {
ResponseStatus::Success => Ok(responce.arguments.torrents),
ResponseStatus::Error(error) => Err(TransmissionError::ResponseError { error }.into()),
}
}
}
|
new
|
identifier_name
|
js-let-vs-var.js
|
"use strict";
var a = 1;
let b = 1;
console.log("after global declaration", a, b);
function asdf() {
var a = 2;
let b = 2;
console.log("in method asdf", a, b);
}
console.log("after function declaration", a, b);
asdf();
console.log("after function call", a, b)
if(true) {
var a = 3;
let b = 3;
console.log("in if block", a, b);
}
console.log("after if block", a, b);
console.log("---");
var items = [1,2,3,4]
for (var i = 0; i < items.length; i++)
|
// the same sample with let
for (let i = 0; i < items.length; i++) {
setTimeout(function () {
console.log("logging item with index %d using let, %s: %s", i, items, items[i]);
}, 10);
}
|
{
setTimeout(function () {
console.log("logging item with index %d using var, %s: %s", i, items, items[i]);
}, 10);
}
|
conditional_block
|
js-let-vs-var.js
|
"use strict";
var a = 1;
let b = 1;
console.log("after global declaration", a, b);
function asdf() {
var a = 2;
let b = 2;
console.log("in method asdf", a, b);
}
console.log("after function declaration", a, b);
asdf();
console.log("after function call", a, b)
if(true) {
var a = 3;
let b = 3;
console.log("in if block", a, b);
}
console.log("after if block", a, b);
|
console.log("---");
var items = [1,2,3,4]
for (var i = 0; i < items.length; i++) {
setTimeout(function () {
console.log("logging item with index %d using var, %s: %s", i, items, items[i]);
}, 10);
}
// the same sample with let
for (let i = 0; i < items.length; i++) {
setTimeout(function () {
console.log("logging item with index %d using let, %s: %s", i, items, items[i]);
}, 10);
}
|
random_line_split
|
|
js-let-vs-var.js
|
"use strict";
var a = 1;
let b = 1;
console.log("after global declaration", a, b);
function
|
() {
var a = 2;
let b = 2;
console.log("in method asdf", a, b);
}
console.log("after function declaration", a, b);
asdf();
console.log("after function call", a, b)
if(true) {
var a = 3;
let b = 3;
console.log("in if block", a, b);
}
console.log("after if block", a, b);
console.log("---");
var items = [1,2,3,4]
for (var i = 0; i < items.length; i++) {
setTimeout(function () {
console.log("logging item with index %d using var, %s: %s", i, items, items[i]);
}, 10);
}
// the same sample with let
for (let i = 0; i < items.length; i++) {
setTimeout(function () {
console.log("logging item with index %d using let, %s: %s", i, items, items[i]);
}, 10);
}
|
asdf
|
identifier_name
|
js-let-vs-var.js
|
"use strict";
var a = 1;
let b = 1;
console.log("after global declaration", a, b);
function asdf()
|
console.log("after function declaration", a, b);
asdf();
console.log("after function call", a, b)
if(true) {
var a = 3;
let b = 3;
console.log("in if block", a, b);
}
console.log("after if block", a, b);
console.log("---");
var items = [1,2,3,4]
for (var i = 0; i < items.length; i++) {
setTimeout(function () {
console.log("logging item with index %d using var, %s: %s", i, items, items[i]);
}, 10);
}
// the same sample with let
for (let i = 0; i < items.length; i++) {
setTimeout(function () {
console.log("logging item with index %d using let, %s: %s", i, items, items[i]);
}, 10);
}
|
{
var a = 2;
let b = 2;
console.log("in method asdf", a, b);
}
|
identifier_body
|
SubTitlesComponent.tsx
|
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import CursorDispOffset from '../CursorDispOffset';
import ChatStatusSender from '../../../Contents/Sender/ChatStatusSender';
interface SubTitlesProp {
chat: ChatStatusSender;
offset: CursorDispOffset;
}
/**
* 字幕表示メイン
*/
export default class SubTitlesComponent extends React.Component<SubTitlesProp, any>{
/**
*
*/
public render() {
let m
|
* 字幕表示のスタイル情報
*/
private GetStyle() {
let offset = this.props.offset;
let bottompos = Math.round((offset.clientHeight - offset.dispHeight) / 2);
let sidepos = Math.round((offset.clientWidth - offset.dispWidth) / 2);
let fontsize = Math.round((offset.dispHeight + offset.dispWidth) * 0.03);
let lineheight = Math.ceil(fontsize * 1.4);
return {
bottom: bottompos.toString() + "px",
left: sidepos.toString() + "px",
right: sidepos.toString() + "px",
fontSize: fontsize.toString() + "px",
lineHeight: lineheight.toString() + "px",
};
}
}
|
sg = "";
if (this.props.chat.message) {
msg = this.props.chat.message;
}
if (msg == null || msg.length == 0) {
return (<div></div>);
}
else {
return (
<div id='sbj-cast-subtitles' className='sbj-cast-subtitles' style={this.GetStyle()}>
{msg}
</div>
);
}
}
/**
|
identifier_body
|
SubTitlesComponent.tsx
|
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import CursorDispOffset from '../CursorDispOffset';
import ChatStatusSender from '../../../Contents/Sender/ChatStatusSender';
interface SubTitlesProp {
chat: ChatStatusSender;
offset: CursorDispOffset;
}
/**
* 字幕表示メイン
*/
export default class SubTitlesComponent extends React.Component<SubTitlesProp, any>{
/**
*
*/
public render() {
let msg = "";
if (this.props.chat.message) {
msg = this.props.chat.message;
}
if (msg == null || msg.length == 0) {
return (<div></div>);
}
else {
return (
<div id='sbj-cast-subtitles' className='sbj-cast-subtitles' style={this.GetStyle()}>
{msg}
</div>
);
}
}
/**
* 字幕表示のスタイル情報
*/
private GetStyle() {
let offset = this.props.offset;
let bottompos = Math.round((offset.clientHeight - offset.dispHeight) / 2);
let sidepos = Math.round((offset.clientWidth - offset.dispWidth) / 2);
let fontsize = Math.round((offset.dispHeight + offset.dispWidth) * 0.03);
let lineheight = Math.ceil(fontsize * 1.4);
return {
bottom: bottompos.toString() + "px",
left: sidepos.toString() + "px",
|
right: sidepos.toString() + "px",
fontSize: fontsize.toString() + "px",
lineHeight: lineheight.toString() + "px",
};
}
}
|
random_line_split
|
|
SubTitlesComponent.tsx
|
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import CursorDispOffset from '../CursorDispOffset';
import ChatStatusSender from '../../../Contents/Sender/ChatStatusSender';
interface SubTitlesProp {
chat: ChatStatusSender;
offset: CursorDispOffset;
}
/**
* 字幕表示メイン
*/
export default class SubTitlesComponent extends React.Component<SubTitlesProp, any>{
/**
*
*/
public render() {
let msg = "";
if (this.props.chat.message) {
ms
|
g == null || msg.length == 0) {
return (<div></div>);
}
else {
return (
<div id='sbj-cast-subtitles' className='sbj-cast-subtitles' style={this.GetStyle()}>
{msg}
</div>
);
}
}
/**
* 字幕表示のスタイル情報
*/
private GetStyle() {
let offset = this.props.offset;
let bottompos = Math.round((offset.clientHeight - offset.dispHeight) / 2);
let sidepos = Math.round((offset.clientWidth - offset.dispWidth) / 2);
let fontsize = Math.round((offset.dispHeight + offset.dispWidth) * 0.03);
let lineheight = Math.ceil(fontsize * 1.4);
return {
bottom: bottompos.toString() + "px",
left: sidepos.toString() + "px",
right: sidepos.toString() + "px",
fontSize: fontsize.toString() + "px",
lineHeight: lineheight.toString() + "px",
};
}
}
|
g = this.props.chat.message;
}
if (ms
|
conditional_block
|
SubTitlesComponent.tsx
|
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import CursorDispOffset from '../CursorDispOffset';
import ChatStatusSender from '../../../Contents/Sender/ChatStatusSender';
interface SubTitlesProp {
chat: ChatStatusSender;
offset: CursorDispOffset;
}
/**
* 字幕表示メイン
*/
export default class SubTitlesComponent extends React.Component<SubTitlesProp, any>{
/**
*
*/
public render() {
|
t msg = "";
if (this.props.chat.message) {
msg = this.props.chat.message;
}
if (msg == null || msg.length == 0) {
return (<div></div>);
}
else {
return (
<div id='sbj-cast-subtitles' className='sbj-cast-subtitles' style={this.GetStyle()}>
{msg}
</div>
);
}
}
/**
* 字幕表示のスタイル情報
*/
private GetStyle() {
let offset = this.props.offset;
let bottompos = Math.round((offset.clientHeight - offset.dispHeight) / 2);
let sidepos = Math.round((offset.clientWidth - offset.dispWidth) / 2);
let fontsize = Math.round((offset.dispHeight + offset.dispWidth) * 0.03);
let lineheight = Math.ceil(fontsize * 1.4);
return {
bottom: bottompos.toString() + "px",
left: sidepos.toString() + "px",
right: sidepos.toString() + "px",
fontSize: fontsize.toString() + "px",
lineHeight: lineheight.toString() + "px",
};
}
}
|
le
|
identifier_name
|
brushTypes.js
|
SyntaxHighlighter.autoloader(
'xs ' + MTBrushParams.baseUrl + '/shBrushXSScript.js'
);
// disable double click to select
SyntaxHighlighter.defaults['quick-code'] = false;
// add toolbar related code
//
function selectElementText(el, win) {
win = win || window;
var doc = win.document, sel, range;
if (win.getSelection && doc.createRange) {
sel = win.getSelection();
range = doc.createRange();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
} else if (doc.body.createTextRange) {
range = doc.body.createTextRange();
range.moveToElementText(el);
range.select();
}
}
function
|
() {
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
}
SyntaxHighlighter.config["strings"]["copy"] = "複製程式碼";
SyntaxHighlighter.toolbar["items"]["list"] = ['copy'];
SyntaxHighlighter.toolbar["items"]["copy"] = {
execute: function(highlighter) {
var div = $("#highlighter_" + highlighter.id);
var container = div.find(".container");
if (container) {
selectElementText(container[0]);
var success = false;
try {
// copy text
success = document.execCommand('copy');
}
catch (err) {
success = false;
}
if (success) {
clearSelection();
alert('程式碼已經成功複製到剪貼簿。');
}
else {
alert('請按Ctrl+C來複製程式碼。');
}
}
}
};
SyntaxHighlighter.all();
|
clearSelection
|
identifier_name
|
brushTypes.js
|
SyntaxHighlighter.autoloader(
'xs ' + MTBrushParams.baseUrl + '/shBrushXSScript.js'
);
// disable double click to select
SyntaxHighlighter.defaults['quick-code'] = false;
// add toolbar related code
//
function selectElementText(el, win) {
win = win || window;
var doc = win.document, sel, range;
if (win.getSelection && doc.createRange) {
sel = win.getSelection();
range = doc.createRange();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
} else if (doc.body.createTextRange) {
range = doc.body.createTextRange();
range.moveToElementText(el);
range.select();
}
}
function clearSelection() {
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
}
SyntaxHighlighter.config["strings"]["copy"] = "複製程式碼";
SyntaxHighlighter.toolbar["items"]["list"] = ['copy'];
SyntaxHighlighter.toolbar["items"]["copy"] = {
execute: function(highlighter) {
var div = $("#highlighter_" + highlighter.id);
var container = div.find(".container");
if (container) {
selectElementText(container[0]);
var success = false;
try {
// copy text
success = document.execCommand('copy');
}
catch (err) {
success = false;
}
if (success) {
|
ert('請按Ctrl+C來複製程式碼。');
}
}
}
};
SyntaxHighlighter.all();
|
clearSelection();
alert('程式碼已經成功複製到剪貼簿。');
}
else {
al
|
conditional_block
|
brushTypes.js
|
SyntaxHighlighter.autoloader(
'xs ' + MTBrushParams.baseUrl + '/shBrushXSScript.js'
);
// disable double click to select
SyntaxHighlighter.defaults['quick-code'] = false;
// add toolbar related code
//
function selectElementText(el, win) {
win = win || window;
var doc = win.document, sel, range;
if (win.getSelection && doc.createRange) {
sel = win.getSelection();
range = doc.createRange();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
} else if (doc.body.createTextRange) {
range = doc.body.createTextRange();
range.moveToElementText(el);
range.select();
}
}
function clearSelection()
|
SyntaxHighlighter.config["strings"]["copy"] = "複製程式碼";
SyntaxHighlighter.toolbar["items"]["list"] = ['copy'];
SyntaxHighlighter.toolbar["items"]["copy"] = {
execute: function(highlighter) {
var div = $("#highlighter_" + highlighter.id);
var container = div.find(".container");
if (container) {
selectElementText(container[0]);
var success = false;
try {
// copy text
success = document.execCommand('copy');
}
catch (err) {
success = false;
}
if (success) {
clearSelection();
alert('程式碼已經成功複製到剪貼簿。');
}
else {
alert('請按Ctrl+C來複製程式碼。');
}
}
}
};
SyntaxHighlighter.all();
|
{
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
}
|
identifier_body
|
brushTypes.js
|
SyntaxHighlighter.autoloader(
'xs ' + MTBrushParams.baseUrl + '/shBrushXSScript.js'
);
// disable double click to select
SyntaxHighlighter.defaults['quick-code'] = false;
// add toolbar related code
//
function selectElementText(el, win) {
win = win || window;
|
sel.removeAllRanges();
sel.addRange(range);
} else if (doc.body.createTextRange) {
range = doc.body.createTextRange();
range.moveToElementText(el);
range.select();
}
}
function clearSelection() {
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
}
SyntaxHighlighter.config["strings"]["copy"] = "複製程式碼";
SyntaxHighlighter.toolbar["items"]["list"] = ['copy'];
SyntaxHighlighter.toolbar["items"]["copy"] = {
execute: function(highlighter) {
var div = $("#highlighter_" + highlighter.id);
var container = div.find(".container");
if (container) {
selectElementText(container[0]);
var success = false;
try {
// copy text
success = document.execCommand('copy');
}
catch (err) {
success = false;
}
if (success) {
clearSelection();
alert('程式碼已經成功複製到剪貼簿。');
}
else {
alert('請按Ctrl+C來複製程式碼。');
}
}
}
};
SyntaxHighlighter.all();
|
var doc = win.document, sel, range;
if (win.getSelection && doc.createRange) {
sel = win.getSelection();
range = doc.createRange();
range.selectNodeContents(el);
|
random_line_split
|
game.py
|
# Copyright 2010, 2014 Gerardo Marset <[email protected]>
#
# This file is part of Haxxor Engine.
#
# Haxxor Engine 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.
#
# Haxxor Engine 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 Haxxor Engine. If not, see <http://www.gnu.org/licenses/>.
import os
import time
import json
import tools
from filesystem import File
import cli
import system
import missions
SAVEGAME = "{}.sav"
DOWNLOADS_DIR = "C:\\Descargas"
class
|
(object):
def __init__(self):
self.running = True
print("Bienvenido a Haxxor Engine.")
try:
self.name = "test" if tools.DEBUG else ask_for_name()
except EOFError:
self.running = False
return
self.clear()
if os.path.isfile(SAVEGAME.format(self.name)):
self.load()
print("Juego cargado.")
else:
self.aliases = default_aliases()
self.mission_id = 0
self.system = system.default_local_system()
self.save()
print("Una nueva partida fue creada para {}.".format(self.name))
print("Escribí \"help\" para ver la lista de comandos.")
self.start_mission()
self.cli = cli.CLI(self.system, self)
@property
def valid_hosts(self):
return ["127.0.0.1", "localhost", self.system.ip,
self.mission.system.ip]
def start_mission(self, restart=None):
self.mission = (missions.missions[self.mission_id].
get_prepared_copy(self, restart))
print("Tenés un e-mail. Escribí \"mail\" para verlo.")
def main_loop(self):
while self.running:
ms = time.time()
self.cli.prompt()
if not self.cli.system.is_local:
if self.mission.ip_tracker.update(time.time() - ms,
self.system.ip):
self.telnet_end("Conexión perdida.\nTu IP fue rastreada.",
True)
def load(self):
with open(SAVEGAME.format(self.name), "r") as f:
load_dict = json.loads(f.read())
self.aliases = load_dict["aliases"]
self.mission_id = load_dict["mission_id"]
filesystem = load_dict["filesystem"]
ip = load_dict["ip"]
def recursive_loop(directory):
for name, value in directory.items():
if isinstance(value, dict):
for element in recursive_loop(value):
pass
else:
directory[name] = File(value)
yield name
for element in recursive_loop(filesystem):
pass
self.system = system.System(filesystem, ip, True)
def save(self):
with open(SAVEGAME.format(self.name), "w") as f:
f.write(json.dumps({
"aliases": self.aliases,
"mission_id": self.mission_id,
"filesystem": self.system.filesystem,
"ip": self.system.ip
}, indent=4, default=lambda o: o.id_))
def clear(self):
if os.name == "posix":
os.system("clear")
elif os.name in ("nt", "dos", "ce"):
os.system("cls")
else:
print("\n" * 300)
def telnet_start(self):
self.cli.system = self.mission.system
self.clear()
print(self.mission.asciiart)
if not self.cli.telnet_login():
self.telnet_end()
def telnet_end(self, message="Conexión cerrada.", force_fail=False):
self.cli.system = self.system
self.clear()
print(message)
if force_fail or not self.mission.is_complete():
print("Misión fallida.")
self.start_mission(self.mission)
return
print("Misión superada.")
downloads_dir = self.system.retrieve(tools.
dir_to_dirlist(DOWNLOADS_DIR))
for file_name, file_ in self.mission.downloads:
downloads_dir[file_name] = file_
self.mission_id += 1
self.start_mission()
def default_aliases():
return {
"cd..": "cd ..",
"ls": "dir",
"rm": "del",
"clear": "cls"
}
def ask_for_name():
while True:
name = tools.iinput("¿Cuál es tu nombre? ")
if name == "":
print("Escribí tu nombre.")
continue
if not all(ord(c) < 128 for c in name):
print("Solo se permiten caracteres ASCII.")
continue
if not name.isalnum():
print("Solo se permiten caracteres alfanuméricos.")
continue
break
return name
|
Game
|
identifier_name
|
game.py
|
# Copyright 2010, 2014 Gerardo Marset <[email protected]>
#
# This file is part of Haxxor Engine.
#
# Haxxor Engine 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.
#
# Haxxor Engine 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 Haxxor Engine. If not, see <http://www.gnu.org/licenses/>.
import os
import time
import json
import tools
from filesystem import File
import cli
import system
import missions
SAVEGAME = "{}.sav"
DOWNLOADS_DIR = "C:\\Descargas"
class Game(object):
def __init__(self):
self.running = True
print("Bienvenido a Haxxor Engine.")
try:
self.name = "test" if tools.DEBUG else ask_for_name()
except EOFError:
self.running = False
return
self.clear()
if os.path.isfile(SAVEGAME.format(self.name)):
self.load()
print("Juego cargado.")
else:
self.aliases = default_aliases()
self.mission_id = 0
self.system = system.default_local_system()
self.save()
print("Una nueva partida fue creada para {}.".format(self.name))
print("Escribí \"help\" para ver la lista de comandos.")
self.start_mission()
self.cli = cli.CLI(self.system, self)
@property
def valid_hosts(self):
return ["127.0.0.1", "localhost", self.system.ip,
self.mission.system.ip]
def start_mission(self, restart=None):
self.mission = (missions.missions[self.mission_id].
get_prepared_copy(self, restart))
print("Tenés un e-mail. Escribí \"mail\" para verlo.")
def main_loop(self):
while self.running:
ms = time.time()
self.cli.prompt()
if not self.cli.system.is_local:
if self.mission.ip_tracker.update(time.time() - ms,
self.system.ip):
self.telnet_end("Conexión perdida.\nTu IP fue rastreada.",
True)
def load(self):
with open(SAVEGAME.format(self.name), "r") as f:
load_dict = json.loads(f.read())
self.aliases = load_dict["aliases"]
self.mission_id = load_dict["mission_id"]
filesystem = load_dict["filesystem"]
ip = load_dict["ip"]
def recursive_loop(directory):
for name, value in directory.items():
if i
|
for element in recursive_loop(filesystem):
pass
self.system = system.System(filesystem, ip, True)
def save(self):
with open(SAVEGAME.format(self.name), "w") as f:
f.write(json.dumps({
"aliases": self.aliases,
"mission_id": self.mission_id,
"filesystem": self.system.filesystem,
"ip": self.system.ip
}, indent=4, default=lambda o: o.id_))
def clear(self):
if os.name == "posix":
os.system("clear")
elif os.name in ("nt", "dos", "ce"):
os.system("cls")
else:
print("\n" * 300)
def telnet_start(self):
self.cli.system = self.mission.system
self.clear()
print(self.mission.asciiart)
if not self.cli.telnet_login():
self.telnet_end()
def telnet_end(self, message="Conexión cerrada.", force_fail=False):
self.cli.system = self.system
self.clear()
print(message)
if force_fail or not self.mission.is_complete():
print("Misión fallida.")
self.start_mission(self.mission)
return
print("Misión superada.")
downloads_dir = self.system.retrieve(tools.
dir_to_dirlist(DOWNLOADS_DIR))
for file_name, file_ in self.mission.downloads:
downloads_dir[file_name] = file_
self.mission_id += 1
self.start_mission()
def default_aliases():
return {
"cd..": "cd ..",
"ls": "dir",
"rm": "del",
"clear": "cls"
}
def ask_for_name():
while True:
name = tools.iinput("¿Cuál es tu nombre? ")
if name == "":
print("Escribí tu nombre.")
continue
if not all(ord(c) < 128 for c in name):
print("Solo se permiten caracteres ASCII.")
continue
if not name.isalnum():
print("Solo se permiten caracteres alfanuméricos.")
continue
break
return name
|
sinstance(value, dict):
for element in recursive_loop(value):
pass
else:
directory[name] = File(value)
yield name
|
conditional_block
|
game.py
|
# Copyright 2010, 2014 Gerardo Marset <[email protected]>
#
# This file is part of Haxxor Engine.
#
# Haxxor Engine 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.
#
# Haxxor Engine 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 Haxxor Engine. If not, see <http://www.gnu.org/licenses/>.
import os
import time
import json
import tools
from filesystem import File
import cli
import system
import missions
SAVEGAME = "{}.sav"
DOWNLOADS_DIR = "C:\\Descargas"
class Game(object):
def __init__(self):
self.running = True
print("Bienvenido a Haxxor Engine.")
try:
self.name = "test" if tools.DEBUG else ask_for_name()
except EOFError:
self.running = False
return
self.clear()
if os.path.isfile(SAVEGAME.format(self.name)):
self.load()
print("Juego cargado.")
else:
self.aliases = default_aliases()
self.mission_id = 0
self.system = system.default_local_system()
self.save()
print("Una nueva partida fue creada para {}.".format(self.name))
print("Escribí \"help\" para ver la lista de comandos.")
self.start_mission()
self.cli = cli.CLI(self.system, self)
@property
def valid_hosts(self):
return ["127.0.0.1", "localhost", self.system.ip,
self.mission.system.ip]
def start_mission(self, restart=None):
self.mission = (missions.missions[self.mission_id].
get_prepared_copy(self, restart))
print("Tenés un e-mail. Escribí \"mail\" para verlo.")
def main_loop(self):
while self.running:
ms = time.time()
self.cli.prompt()
if not self.cli.system.is_local:
if self.mission.ip_tracker.update(time.time() - ms,
self.system.ip):
self.telnet_end("Conexión perdida.\nTu IP fue rastreada.",
True)
def load(self):
with open(SAVEGAME.format(self.name), "r") as f:
load_dict = json.loads(f.read())
self.aliases = load_dict["aliases"]
self.mission_id = load_dict["mission_id"]
filesystem = load_dict["filesystem"]
ip = load_dict["ip"]
def recursive_loop(directory):
for name, value in directory.items():
if isinstance(value, dict):
for element in recursive_loop(value):
pass
else:
directory[name] = File(value)
yield name
for element in recursive_loop(filesystem):
pass
self.system = system.System(filesystem, ip, True)
def save(self):
with open(SAVEGAME.format(self.name), "w") as f:
f.write(json.dumps({
"aliases": self.aliases,
"mission_id": self.mission_id,
"filesystem": self.system.filesystem,
"ip": self.system.ip
}, indent=4, default=lambda o: o.id_))
def clear(self):
if os.name == "posix":
os.system("clear")
elif os.name in ("nt", "dos", "ce"):
os.system("cls")
else:
print("\n" * 300)
def telnet_start(self):
self.cli.system = self.mission.system
self.clear()
print(self.mission.asciiart)
if not self.cli.telnet_login():
self.telnet_end()
def telnet_end(self, message="Conexión cerrada.", force_fail=False):
self.cli.system = self.system
self.clear()
print(message)
if force_fail or not self.mission.is_complete():
print("Misión fallida.")
self.start_mission(self.mission)
return
print("Misión superada.")
downloads_dir = self.system.retrieve(tools.
dir_to_dirlist(DOWNLOADS_DIR))
for file_name, file_ in self.mission.downloads:
downloads_dir[file_name] = file_
self.mission_id += 1
self.start_mission()
def default_aliases():
return
|
ask_for_name():
while True:
name = tools.iinput("¿Cuál es tu nombre? ")
if name == "":
print("Escribí tu nombre.")
continue
if not all(ord(c) < 128 for c in name):
print("Solo se permiten caracteres ASCII.")
continue
if not name.isalnum():
print("Solo se permiten caracteres alfanuméricos.")
continue
break
return name
|
{
"cd..": "cd ..",
"ls": "dir",
"rm": "del",
"clear": "cls"
}
def
|
identifier_body
|
game.py
|
# Copyright 2010, 2014 Gerardo Marset <[email protected]>
#
# This file is part of Haxxor Engine.
#
# Haxxor Engine 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.
#
# Haxxor Engine 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 Haxxor Engine. If not, see <http://www.gnu.org/licenses/>.
import os
import time
import json
import tools
from filesystem import File
|
SAVEGAME = "{}.sav"
DOWNLOADS_DIR = "C:\\Descargas"
class Game(object):
def __init__(self):
self.running = True
print("Bienvenido a Haxxor Engine.")
try:
self.name = "test" if tools.DEBUG else ask_for_name()
except EOFError:
self.running = False
return
self.clear()
if os.path.isfile(SAVEGAME.format(self.name)):
self.load()
print("Juego cargado.")
else:
self.aliases = default_aliases()
self.mission_id = 0
self.system = system.default_local_system()
self.save()
print("Una nueva partida fue creada para {}.".format(self.name))
print("Escribí \"help\" para ver la lista de comandos.")
self.start_mission()
self.cli = cli.CLI(self.system, self)
@property
def valid_hosts(self):
return ["127.0.0.1", "localhost", self.system.ip,
self.mission.system.ip]
def start_mission(self, restart=None):
self.mission = (missions.missions[self.mission_id].
get_prepared_copy(self, restart))
print("Tenés un e-mail. Escribí \"mail\" para verlo.")
def main_loop(self):
while self.running:
ms = time.time()
self.cli.prompt()
if not self.cli.system.is_local:
if self.mission.ip_tracker.update(time.time() - ms,
self.system.ip):
self.telnet_end("Conexión perdida.\nTu IP fue rastreada.",
True)
def load(self):
with open(SAVEGAME.format(self.name), "r") as f:
load_dict = json.loads(f.read())
self.aliases = load_dict["aliases"]
self.mission_id = load_dict["mission_id"]
filesystem = load_dict["filesystem"]
ip = load_dict["ip"]
def recursive_loop(directory):
for name, value in directory.items():
if isinstance(value, dict):
for element in recursive_loop(value):
pass
else:
directory[name] = File(value)
yield name
for element in recursive_loop(filesystem):
pass
self.system = system.System(filesystem, ip, True)
def save(self):
with open(SAVEGAME.format(self.name), "w") as f:
f.write(json.dumps({
"aliases": self.aliases,
"mission_id": self.mission_id,
"filesystem": self.system.filesystem,
"ip": self.system.ip
}, indent=4, default=lambda o: o.id_))
def clear(self):
if os.name == "posix":
os.system("clear")
elif os.name in ("nt", "dos", "ce"):
os.system("cls")
else:
print("\n" * 300)
def telnet_start(self):
self.cli.system = self.mission.system
self.clear()
print(self.mission.asciiart)
if not self.cli.telnet_login():
self.telnet_end()
def telnet_end(self, message="Conexión cerrada.", force_fail=False):
self.cli.system = self.system
self.clear()
print(message)
if force_fail or not self.mission.is_complete():
print("Misión fallida.")
self.start_mission(self.mission)
return
print("Misión superada.")
downloads_dir = self.system.retrieve(tools.
dir_to_dirlist(DOWNLOADS_DIR))
for file_name, file_ in self.mission.downloads:
downloads_dir[file_name] = file_
self.mission_id += 1
self.start_mission()
def default_aliases():
return {
"cd..": "cd ..",
"ls": "dir",
"rm": "del",
"clear": "cls"
}
def ask_for_name():
while True:
name = tools.iinput("¿Cuál es tu nombre? ")
if name == "":
print("Escribí tu nombre.")
continue
if not all(ord(c) < 128 for c in name):
print("Solo se permiten caracteres ASCII.")
continue
if not name.isalnum():
print("Solo se permiten caracteres alfanuméricos.")
continue
break
return name
|
import cli
import system
import missions
|
random_line_split
|
test_list.py
|
import sys
import unittest
from test import test_support, list_tests
class ListTest(list_tests.CommonTest):
type2test = list
def test_basic(self):
self.assertEqual(list([]), [])
l0_3 = [0, 1, 2, 3]
l0_3_bis = list(l0_3)
self.assertEqual(l0_3, l0_3_bis)
self.assertTrue(l0_3 is not l0_3_bis)
self.assertEqual(list(()), [])
self.assertEqual(list((0, 1, 2, 3)), [0, 1, 2, 3])
self.assertEqual(list(''), [])
self.assertEqual(list('spam'), ['s', 'p', 'a', 'm'])
if sys.maxsize == 0x7fffffff:
# This test can currently only work on 32-bit machines.
# XXX If/when PySequence_Length() returns a ssize_t, it should be
# XXX re-enabled.
# Verify clearing of bug #556025.
# This assumes that the max data size (sys.maxint) == max
# address size this also assumes that the address size is at
# least 4 bytes with 8 byte addresses, the bug is not well
# tested
#
# Note: This test is expected to SEGV under Cygwin 1.3.12 or
# earlier due to a newlib bug. See the following mailing list
# thread for the details:
# http://sources.redhat.com/ml/newlib/2002/msg00369.html
|
# This code used to segfault in Py2.4a3
x = []
x.extend(-y for y in x)
self.assertEqual(x, [])
def test_truth(self):
super(ListTest, self).test_truth()
self.assertTrue(not [])
self.assertTrue([42])
def test_identity(self):
self.assertTrue([] is not [])
def test_len(self):
super(ListTest, self).test_len()
self.assertEqual(len([]), 0)
self.assertEqual(len([0]), 1)
self.assertEqual(len([0, 1, 2]), 3)
@unittest.expectedFailure
def test_overflow(self):
lst = [4, 5, 6, 7]
n = int((sys.maxsize*2+2) // len(lst))
def mul(a, b): return a * b
def imul(a, b): a *= b
self.assertRaises((MemoryError, OverflowError), mul, lst, n)
self.assertRaises((MemoryError, OverflowError), imul, lst, n)
def test_main(verbose=None):
test_support.run_unittest(ListTest)
# verify reference counting
# import sys
# if verbose and hasattr(sys, "gettotalrefcount"):
# import gc
# counts = [None] * 5
# for i in xrange(len(counts)):
# test_support.run_unittest(ListTest)
# gc.collect()
# counts[i] = sys.gettotalrefcount()
# print counts
if __name__ == "__main__":
test_main(verbose=True)
|
self.assertRaises(MemoryError, list, xrange(sys.maxint // 2))
|
conditional_block
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.