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 |
---|---|---|---|---|
worker.js
|
// Generated by CoffeeScript 1.8.0
var BITSTR, DERNULL, INTERGER, OID, PRTSTR, SEQUENCE, SET, TAG, UTF8STR, asn1Util, cryptoUtil, generateCSR, generateKeyPair, j, keyUtil, onmessage;
postMessage({
type: 'status',
message: 'Importing JSRSASign library ...'
});
importScripts('jsrsasign-4.7.0-all-min.js');
j = KJUR;
keyUtil = KEYUTIL;
asn1Util = j.asn1.ASN1Util;
cryptoUtil = j.crypto.Util;
SEQUENCE = function(arr) {
return new j.asn1.DERSequence({
'array': arr
});
};
SET = function(arr) {
return new j.asn1.DERSet({
'array': arr
});
};
INTERGER = function(num) {
return new j.asn1.DERInteger({
'int': num
});
};
PRTSTR = function(str) {
return new j.asn1.DERPrintableString({
'str': str
});
};
UTF8STR = function(str) {
return new j.asn1.DERUTF8String({
'str': str
});
};
BITSTR = function(hex) {
return new j.asn1.DERBitString({
'hex': hex
});
};
OID = function(oid) {
return j.asn1.x509.OID.name2obj(oid);
};
TAG = function(tag) {
return new j.asn1.DERTaggedObject({
'tag': tag || 'a0'
});
};
DERNULL = function() {
return new j.asn1.DERNull();
};
generateKeyPair = function(len) {
var keyPair, privateKeyHex, privateKeyObj, privateKeyPEM, publicKeyHex, publicKeyObj, publicKeyPEM, ret, tbl;
ret = {};
tbl = [324, 588];
keyPair = keyUtil.generateKeypair("RSA", len);
privateKeyObj = ret.privateKeyObj = keyPair.prvKeyObj;
publicKeyObj = ret.publicKeyObj = keyPair.pubKeyObj;
privateKeyObj.isPrivate = true;
privateKeyPEM = ret.privateKeyPEM = keyUtil.getPEM(privateKeyObj, "PKCS8PRV");
privateKeyHex = ret.privateKeyHex = keyUtil.getHexFromPEM(privateKeyPEM, "PRIVATE KEY");
publicKeyPEM = ret.publicKeyPEM = keyUtil.getPEM(publicKeyObj);
publicKeyHex = ret.publicKeyHex = keyUtil.getHexFromPEM(publicKeyPEM, "PUBLIC KEY");
if (tbl.indexOf(ret.publicKeyHex.length) === -1) {
return false;
}
return ret;
};
generateCSR = function(data, keyPair, alg) {
var certificateRequestInfo, sig;
alg = alg || 'SHA256withRSA';
certificateRequestInfo = SEQUENCE([INTERGER(0), SEQUENCE([SET([SEQUENCE([OID("countryName"), PRTSTR(data.countryName)])]), SET([SEQUENCE([OID("stateOrProvinceName"), UTF8STR(data.stateOrProvinceName)])]), SET([SEQUENCE([OID("locality"), UTF8STR(data.locality)])]), SET([SEQUENCE([OID("organization"), UTF8STR(data.organization)])]), SET([SEQUENCE([OID("commonName"), UTF8STR(data.commonName)])])]), new j.asn1.x509.SubjectPublicKeyInfo(keyPair.publicKeyObj), TAG()]);
sig = new j.crypto.Signature({
alg: alg
});
sig.init(keyPair.privateKeyPEM);
sig.updateHex(certificateRequestInfo.getEncodedHex());
return SEQUENCE([certificateRequestInfo, SEQUENCE([OID(alg), DERNULL()]), BITSTR('00' + sig.sign())]);
};
onmessage = function(e) {
var CSR, CSRPEM, data, keyPair;
data = e.data.workload;
postMessage({
type: 'status',
message: 'Generating private key ...'
});
keyPair = false;
while (1)
|
postMessage({
type: 'status',
message: 'Generating CSR ...'
});
CSR = generateCSR(data, keyPair, "SHA256withRSA");
postMessage({
type: 'status',
message: 'Converting CSR to PEM format ...'
});
CSRPEM = asn1Util.getPEMStringFromHex(CSR.getEncodedHex(), "CERTIFICATE REQUEST");
postMessage({
type: 'private',
pem: keyPair.privateKeyPEM
});
postMessage({
type: 'csr',
pem: CSRPEM
});
return postMessage({
type: 'done'
});
};
|
{
keyPair = generateKeyPair(parseInt(data.keySize));
if (keyPair === false) {
postMessage({
type: 'status',
message: 'Regenerating private key ...'
});
} else {
break;
}
}
|
conditional_block
|
actions.js
|
/*
*
* FileContainer actions
*
*/
import {
DEFAULT_ACTION,
UPDATE_FILE_INFO,
RECEIVE_FILE_ID,
UPDATE_BY_FILE_ID,
NEW_CONTAINER_ACTION,
ADD_NEW_ROW,
EDIT_ROW,
MAKE_SAVE_METADATA_ACTION,
MAKE_SAVE_METADATA_FROM_BACKEND,
DONT_SHOW_METADATA_FOR_DIRECTORY,
} from './constants';
// import { ADD_NEW_CONTAINER_ACTION } from '../../constants';
export function defaultAction({ frontendId }) {
return {
type: DEFAULT_ACTION,
frontendId,
};
}
export function makeUpdateFileInfoAction( fileInfo ) {
return {
type: UPDATE_FILE_INFO,
fileInfo,
};
}
export function receiveFileById({ fileId })
{
return {
type: RECEIVE_FILE_ID,
fileId,
};
}
export function updateFileById({ fileInfo }) {
return {
type: UPDATE_BY_FILE_ID,
fileInfo,
};
}
export function makeNewContainerAction(container) {
return {
type: NEW_CONTAINER_ACTION,
container,
};
}
export function makeChangeNewRowAction(row){
return {
type: ADD_NEW_ROW,
row,
};
}
export function makeEditRowAction(row,cellName,cellValue){
return {
type: EDIT_ROW,
row,
cellName,
cellValue,
};
}
export function makeSaveMetaDataAction()
|
export function makeSaveMetaDataFromBackendAction( fileInfo ) {
return {
type: MAKE_SAVE_METADATA_FROM_BACKEND,
fileInfo,
};
}
export function makeDontShowMetaDataForDirectoryAction( ) {
return {
type: DONT_SHOW_METADATA_FOR_DIRECTORY,
}
}
|
{
return {
type: MAKE_SAVE_METADATA_ACTION,
};
}
|
identifier_body
|
actions.js
|
/*
*
* FileContainer actions
*
*/
import {
DEFAULT_ACTION,
UPDATE_FILE_INFO,
RECEIVE_FILE_ID,
UPDATE_BY_FILE_ID,
NEW_CONTAINER_ACTION,
ADD_NEW_ROW,
EDIT_ROW,
MAKE_SAVE_METADATA_ACTION,
MAKE_SAVE_METADATA_FROM_BACKEND,
DONT_SHOW_METADATA_FOR_DIRECTORY,
} from './constants';
// import { ADD_NEW_CONTAINER_ACTION } from '../../constants';
export function defaultAction({ frontendId }) {
return {
type: DEFAULT_ACTION,
frontendId,
};
}
export function makeUpdateFileInfoAction( fileInfo ) {
return {
type: UPDATE_FILE_INFO,
fileInfo,
};
}
export function receiveFileById({ fileId })
{
return {
type: RECEIVE_FILE_ID,
fileId,
};
}
export function updateFileById({ fileInfo }) {
return {
type: UPDATE_BY_FILE_ID,
fileInfo,
};
}
export function makeNewContainerAction(container) {
return {
type: NEW_CONTAINER_ACTION,
container,
};
}
export function makeChangeNewRowAction(row){
return {
type: ADD_NEW_ROW,
row,
};
}
export function makeEditRowAction(row,cellName,cellValue){
return {
type: EDIT_ROW,
row,
cellName,
cellValue,
};
}
export function
|
() {
return {
type: MAKE_SAVE_METADATA_ACTION,
};
}
export function makeSaveMetaDataFromBackendAction( fileInfo ) {
return {
type: MAKE_SAVE_METADATA_FROM_BACKEND,
fileInfo,
};
}
export function makeDontShowMetaDataForDirectoryAction( ) {
return {
type: DONT_SHOW_METADATA_FOR_DIRECTORY,
}
}
|
makeSaveMetaDataAction
|
identifier_name
|
actions.js
|
/*
*
* FileContainer actions
*
*/
import {
DEFAULT_ACTION,
UPDATE_FILE_INFO,
RECEIVE_FILE_ID,
UPDATE_BY_FILE_ID,
NEW_CONTAINER_ACTION,
ADD_NEW_ROW,
EDIT_ROW,
MAKE_SAVE_METADATA_ACTION,
MAKE_SAVE_METADATA_FROM_BACKEND,
DONT_SHOW_METADATA_FOR_DIRECTORY,
} from './constants';
// import { ADD_NEW_CONTAINER_ACTION } from '../../constants';
export function defaultAction({ frontendId }) {
return {
type: DEFAULT_ACTION,
frontendId,
};
}
export function makeUpdateFileInfoAction( fileInfo ) {
return {
type: UPDATE_FILE_INFO,
fileInfo,
};
}
export function receiveFileById({ fileId })
{
return {
type: RECEIVE_FILE_ID,
fileId,
};
|
type: UPDATE_BY_FILE_ID,
fileInfo,
};
}
export function makeNewContainerAction(container) {
return {
type: NEW_CONTAINER_ACTION,
container,
};
}
export function makeChangeNewRowAction(row){
return {
type: ADD_NEW_ROW,
row,
};
}
export function makeEditRowAction(row,cellName,cellValue){
return {
type: EDIT_ROW,
row,
cellName,
cellValue,
};
}
export function makeSaveMetaDataAction() {
return {
type: MAKE_SAVE_METADATA_ACTION,
};
}
export function makeSaveMetaDataFromBackendAction( fileInfo ) {
return {
type: MAKE_SAVE_METADATA_FROM_BACKEND,
fileInfo,
};
}
export function makeDontShowMetaDataForDirectoryAction( ) {
return {
type: DONT_SHOW_METADATA_FOR_DIRECTORY,
}
}
|
}
export function updateFileById({ fileInfo }) {
return {
|
random_line_split
|
valid.js
|
/**
* @fileOverview 表单验证
* @ignore
*/
var BUI = require('bui-common'),
Rules = require('./rules');
/**
* @class BUI.Form.ValidView
* @private
* 对控件内的字段域进行验证的视图
*/
var ValidView = function(){
};
ValidView.prototype = {
/**
* 获取错误信息的容器
* @protected
* @return {jQuery}
*/
getErrorsContainer : function(){
var _self = this,
errorContainer = _self.get('errorContainer');
if(errorContainer){
if(BUI.isString(errorContainer)){
return _self.get('el').find(errorContainer);
}
return errorContainer;
}
return _self.getContentElement();
},
/**
* 显示错误
*/
showErrors : function(errors){
var _self = this,
errorsContainer = _self.getErrorsContainer(),
errorTpl = _self.get('errorTpl');
_self.clearErrors();
if(!_self.get('showError')){
return ;
}
//如果仅显示第一条错误记录
if(_self.get('showOneError')){
if(errors && errors.length){
_self.showError(errors[0],errorTpl,errorsContainer);
}
return ;
}
BUI.each(errors,function(error){
if(error){
_self.showError(error,errorTpl,errorsContainer);
}
});
},
/**
* 显示一条错误
* @protected
* @template
* @param {String} msg 错误信息
*/
showError : function(msg,errorTpl,container){
},
/**
* @protected
* @template
* 清除错误
*/
clearErrors : function(){
}
};
/**
* 对控件内的字段域进行验证
* @class BUI.Form.Valid
*/
var Valid = function(){
};
Valid.ATTRS = {
/**
* 控件固有的验证规则,例如,日期字段域,有的date类型的验证
* @protected
* @type {Object}
*/
defaultRules : {
value : {}
},
/**
* 控件固有的验证出错信息,例如,日期字段域,不是有效日期的验证字段
* @protected
* @type {Object}
*/
defaultMessages : {
value : {}
},
/**
* 验证规则
* @type {Object}
*/
rules : {
shared : false,
value : {}
},
/**
* 验证信息集合
* @type {Object}
*/
messages : {
shared : false,
value : {}
},
/**
* 验证器 验证容器内的表单字段是否通过验证
* @type {Function}
*/
validator : {
},
/**
* 存放错误信息容器的选择器,如果未提供则默认显示在控件中
* @private
* @type {String}
*/
errorContainer : {
view : true
},
/**
* 显示错误信息的模板
* @type {Object}
*/
errorTpl : {
view : true,
value : '<span class="x-field-error"><span class="x-icon x-icon-mini x-icon-error">!</span><label class="x-field-error-text">{error}</label></span>'
},
/**
* 显示错误
* @type {Boolean}
*/
showError : {
view : true,
value : true
},
/**
* 是否仅显示一个错误
* @type {Boolean}
*/
showOneError: {
},
/**
* 错误信息,这个验证错误不包含子控件的验证错误
* @type {String}
*/
error : {
},
/**
* 暂停验证
* <pre><code>
* field.set('pauseValid',true); //可以调用field.clearErrors()
* field.set('pauseValid',false); //可以同时调用field.valid()
* </code></pre>
* @type {Boolean}
*/
pauseValid : {
value : false
}
};
Valid.prototype = {
__bindUI : function(){
var _self = this;
//监听是否禁用
_self.on('afterDisabledChange',function(ev){
var disabled = ev.newVal;
if(disabled){
_self.clearErrors(false,false);
}else{
_self.valid();
}
});
},
/**
* 是否通过验证
* @template
* @return {Boolean} 是否通过验证
*/
isValid : function(){
},
/**
* 进行验证
*/
valid : function(){
},
/**
* @protected
* @template
* 验证自身的规则和验证器
*/
validControl : function(){
},
//验证规则
validRules : function(rules,value){
if(!rules){
return null;
}
if(this.get('pauseValid')){
return null;
}
var _self = this,
messages = _self._getValidMessages(),
error = null;
for(var name in rules){
if(rules.hasOwnProperty(name)){
var baseValue = rules[name];
error = Rules.valid(name,value,baseValue,messages[name],_self);
if(error){
break;
}
}
}
return error;
},
//获取验证错误信息
_getValidMessages : function(){
var _self = this,
defaultMessages = _self.get('defaultMessages'),
messages = _self.get('messages');
return BUI.merge(defaultMessages,messages);
},
/**
* @template
* @protected
* 控件本身是否通过验证,不考虑子控件
* @return {String} 验证的错误
*/
getValidError : function(value){
var _self = this,
validator = _self.get('validator'),
error = null;
error = _self.validRules(_self.get('defaultRules'),value) || _self.validRules(_self.get('rules'),value);
if(!error && !this.get('pauseValid')){
if(_self.parseValue){
value = _self.parseValue(value);
}
error = validator ? validator.call(this,value) : '';
}
return error;
},
/**
* 获取验证出错信息,包括自身和子控件的验证错误信息
* @return {Array} 出错信息
*/
getErrors : function(){
},
/**
* 显示错误
* @param {Array} errors 显示错误
*/
showErrors : function(errors){
var _self = this,
errors = errors || _self.getErrors();
_self.get('view').showErrors(errors);
},
/**
* 清除错误
* @param {Boolean} reset 清除错误时是否重置
* @param {Boolean} [deep = true] 是否清理子控件的错误
*/
clearErrors : function(reset,deep){
deep = deep == null ? true :
|
f.get('children');
if(deep){
BUI.each(children,function(item){
if(item.clearErrors){
if(item.field){
item.clearErrors(reset);
}else{
item.clearErrors(reset,deep);
}
}
});
}
_self.set('error',null);
_self.get('view').clearErrors();
},
/**
* 添加验证规则
* @param {String} name 规则名称
* @param {*} [value] 规则进行校验的进行对比的值,如max : 10
* @param {String} [message] 出错信息,可以使模板
* <ol>
* <li>如果 value 是单个值,例如最大值 value = 10,那么模板可以写成: '输入值不能大于{0}!'</li>
* <li>如果 value 是个复杂对象,数组时,按照索引,对象时按照 key 阻止。如:value= {max:10,min:5} ,则'输入值不能大于{max},不能小于{min}'</li>
* </ol>
* var field = form.getField('name');
* field.addRule('required',true);
*
* field.addRule('max',10,'不能大于{0}');
*/
addRule : function(name,value,message){
var _self = this,
rules = _self.get('rules'),
messages = _self.get('messages');
rules[name] = value;
if(message){
messages[name] = message;
}
},
/**
* 添加多个验证规则
* @param {Object} rules 多个验证规则
* @param {Object} [messages] 验证规则的出错信息
* var field = form.getField('name');
* field.addRules({
* required : true,
* max : 10
* });
*/
addRules : function(rules,messages){
var _self = this;
BUI.each(rules,function(value,name){
var msg = messages ? messages[name] : null;
_self.addRule(name,value,msg);
});
},
/**
* 移除指定名称的验证规则
* @param {String} name 验证规则名称
* var field = form.getField('name');
* field.remove('required');
*/
removeRule : function(name){
var _self = this,
rules = _self.get('rules');
delete rules[name];
},
/**
* 清理验证规则
*/
clearRules : function(){
var _self = this;
_self.set('rules',{});
}
};
Valid.View = ValidView;
module.exports = Valid;
|
deep;
var _self = this,
children = _sel
|
conditional_block
|
valid.js
|
/**
* @fileOverview 表单验证
* @ignore
*/
var BUI = require('bui-common'),
Rules = require('./rules');
/**
* @class BUI.Form.ValidView
* @private
* 对控件内的字段域进行验证的视图
*/
var ValidView = function(){
};
ValidView.prototype = {
/**
* 获取错误信息的容器
* @protected
* @return {jQuery}
*/
getErrorsContainer : function(){
var _self = this,
errorContainer = _self.get('errorContainer');
if(errorContainer){
if(BUI.isString(errorContainer)){
return _self.get('el').find(errorContainer);
}
return errorContainer;
}
return _self.getContentElement();
},
/**
* 显示错误
*/
showErrors : function(errors){
var _self = this,
errorsContainer = _self.getErrorsContainer(),
errorTpl = _self.get('errorTpl');
_self.clearErrors();
if(!_self.get('showError')){
|
}
//如果仅显示第一条错误记录
if(_self.get('showOneError')){
if(errors && errors.length){
_self.showError(errors[0],errorTpl,errorsContainer);
}
return ;
}
BUI.each(errors,function(error){
if(error){
_self.showError(error,errorTpl,errorsContainer);
}
});
},
/**
* 显示一条错误
* @protected
* @template
* @param {String} msg 错误信息
*/
showError : function(msg,errorTpl,container){
},
/**
* @protected
* @template
* 清除错误
*/
clearErrors : function(){
}
};
/**
* 对控件内的字段域进行验证
* @class BUI.Form.Valid
*/
var Valid = function(){
};
Valid.ATTRS = {
/**
* 控件固有的验证规则,例如,日期字段域,有的date类型的验证
* @protected
* @type {Object}
*/
defaultRules : {
value : {}
},
/**
* 控件固有的验证出错信息,例如,日期字段域,不是有效日期的验证字段
* @protected
* @type {Object}
*/
defaultMessages : {
value : {}
},
/**
* 验证规则
* @type {Object}
*/
rules : {
shared : false,
value : {}
},
/**
* 验证信息集合
* @type {Object}
*/
messages : {
shared : false,
value : {}
},
/**
* 验证器 验证容器内的表单字段是否通过验证
* @type {Function}
*/
validator : {
},
/**
* 存放错误信息容器的选择器,如果未提供则默认显示在控件中
* @private
* @type {String}
*/
errorContainer : {
view : true
},
/**
* 显示错误信息的模板
* @type {Object}
*/
errorTpl : {
view : true,
value : '<span class="x-field-error"><span class="x-icon x-icon-mini x-icon-error">!</span><label class="x-field-error-text">{error}</label></span>'
},
/**
* 显示错误
* @type {Boolean}
*/
showError : {
view : true,
value : true
},
/**
* 是否仅显示一个错误
* @type {Boolean}
*/
showOneError: {
},
/**
* 错误信息,这个验证错误不包含子控件的验证错误
* @type {String}
*/
error : {
},
/**
* 暂停验证
* <pre><code>
* field.set('pauseValid',true); //可以调用field.clearErrors()
* field.set('pauseValid',false); //可以同时调用field.valid()
* </code></pre>
* @type {Boolean}
*/
pauseValid : {
value : false
}
};
Valid.prototype = {
__bindUI : function(){
var _self = this;
//监听是否禁用
_self.on('afterDisabledChange',function(ev){
var disabled = ev.newVal;
if(disabled){
_self.clearErrors(false,false);
}else{
_self.valid();
}
});
},
/**
* 是否通过验证
* @template
* @return {Boolean} 是否通过验证
*/
isValid : function(){
},
/**
* 进行验证
*/
valid : function(){
},
/**
* @protected
* @template
* 验证自身的规则和验证器
*/
validControl : function(){
},
//验证规则
validRules : function(rules,value){
if(!rules){
return null;
}
if(this.get('pauseValid')){
return null;
}
var _self = this,
messages = _self._getValidMessages(),
error = null;
for(var name in rules){
if(rules.hasOwnProperty(name)){
var baseValue = rules[name];
error = Rules.valid(name,value,baseValue,messages[name],_self);
if(error){
break;
}
}
}
return error;
},
//获取验证错误信息
_getValidMessages : function(){
var _self = this,
defaultMessages = _self.get('defaultMessages'),
messages = _self.get('messages');
return BUI.merge(defaultMessages,messages);
},
/**
* @template
* @protected
* 控件本身是否通过验证,不考虑子控件
* @return {String} 验证的错误
*/
getValidError : function(value){
var _self = this,
validator = _self.get('validator'),
error = null;
error = _self.validRules(_self.get('defaultRules'),value) || _self.validRules(_self.get('rules'),value);
if(!error && !this.get('pauseValid')){
if(_self.parseValue){
value = _self.parseValue(value);
}
error = validator ? validator.call(this,value) : '';
}
return error;
},
/**
* 获取验证出错信息,包括自身和子控件的验证错误信息
* @return {Array} 出错信息
*/
getErrors : function(){
},
/**
* 显示错误
* @param {Array} errors 显示错误
*/
showErrors : function(errors){
var _self = this,
errors = errors || _self.getErrors();
_self.get('view').showErrors(errors);
},
/**
* 清除错误
* @param {Boolean} reset 清除错误时是否重置
* @param {Boolean} [deep = true] 是否清理子控件的错误
*/
clearErrors : function(reset,deep){
deep = deep == null ? true : deep;
var _self = this,
children = _self.get('children');
if(deep){
BUI.each(children,function(item){
if(item.clearErrors){
if(item.field){
item.clearErrors(reset);
}else{
item.clearErrors(reset,deep);
}
}
});
}
_self.set('error',null);
_self.get('view').clearErrors();
},
/**
* 添加验证规则
* @param {String} name 规则名称
* @param {*} [value] 规则进行校验的进行对比的值,如max : 10
* @param {String} [message] 出错信息,可以使模板
* <ol>
* <li>如果 value 是单个值,例如最大值 value = 10,那么模板可以写成: '输入值不能大于{0}!'</li>
* <li>如果 value 是个复杂对象,数组时,按照索引,对象时按照 key 阻止。如:value= {max:10,min:5} ,则'输入值不能大于{max},不能小于{min}'</li>
* </ol>
* var field = form.getField('name');
* field.addRule('required',true);
*
* field.addRule('max',10,'不能大于{0}');
*/
addRule : function(name,value,message){
var _self = this,
rules = _self.get('rules'),
messages = _self.get('messages');
rules[name] = value;
if(message){
messages[name] = message;
}
},
/**
* 添加多个验证规则
* @param {Object} rules 多个验证规则
* @param {Object} [messages] 验证规则的出错信息
* var field = form.getField('name');
* field.addRules({
* required : true,
* max : 10
* });
*/
addRules : function(rules,messages){
var _self = this;
BUI.each(rules,function(value,name){
var msg = messages ? messages[name] : null;
_self.addRule(name,value,msg);
});
},
/**
* 移除指定名称的验证规则
* @param {String} name 验证规则名称
* var field = form.getField('name');
* field.remove('required');
*/
removeRule : function(name){
var _self = this,
rules = _self.get('rules');
delete rules[name];
},
/**
* 清理验证规则
*/
clearRules : function(){
var _self = this;
_self.set('rules',{});
}
};
Valid.View = ValidView;
module.exports = Valid;
|
return ;
|
random_line_split
|
createEpisodeTest.js
|
'use strict';
const sinon = require('sinon'),
q = require('q'),
mockery = require('mockery'),
_ = require('lodash'),
should = require('chai').should();
describe('Create episode', () => {
const idsGeneratorStub = () => '123';
it('Should call the next callback', done => {
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockRequest('book-id-123'), mockResponse(), done);
deferred.resolve();
});
it('Should return 201 created', done => {
const responseMock = mockResponse();
const responseSpy = sinon.spy(responseMock, 'json');
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockRequest('book-id-123'), responseMock, checkResponse);
function checkResponse() {
responseSpy.args[0][0].should.equal(201);
done();
}
deferred.resolve();
});
it('Should return an id property with the scenario id', done => {
const responseMock = mockResponse();
const responseSpy = sinon.spy(responseMock, 'json');
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockRequest('book-id-123'), responseMock, checkResponse);
function checkResponse() {
const body = responseSpy.args[0][1];
body.should.deep.equal({id: idsGeneratorStub()});
done();
}
deferred.resolve();
});
it('Should store the scenario data and id', done => {
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const bookId = 'abc1234';
const mockedRequest = mockRequest(bookId);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockedRequest, mockResponse(), checkResponse);
deferred.resolve();
function
|
() {
persistEpisodeInStorage.calledOnce.should.equal(true);
persistEpisodeInStorage.args[0][0].should.equal(bookId);
persistEpisodeInStorage.args[0][1].should.deep.equal(_.assign({id: idsGeneratorStub()}, mockedRequest.body));
done();
}
});
afterEach(() => {
mockery.deregisterAll();
mockery.disable();
});
});
function getCreateEpisodeMiddleware(idsMock, persistEpisodeInStorage) {
mockery.registerMock('../idsGenerator/generateId.js', idsMock);
mockery.registerMock('./persistEpisodeInStorage.js', persistEpisodeInStorage);
mockery.enable({
useCleanCache: true,
warnOnReplace: false,
warnOnUnregistered: false
});
return require('../../src/episodes/createEpisode.js');
}
function mockResponse() {
return { json: () => {} };
}
function mockRequest(bookId) {
return {
context: {
bookId: bookId
},
body: {
a: 1,
b: 2
}
};
}
|
checkResponse
|
identifier_name
|
createEpisodeTest.js
|
'use strict';
const sinon = require('sinon'),
q = require('q'),
mockery = require('mockery'),
_ = require('lodash'),
should = require('chai').should();
describe('Create episode', () => {
const idsGeneratorStub = () => '123';
it('Should call the next callback', done => {
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockRequest('book-id-123'), mockResponse(), done);
deferred.resolve();
});
it('Should return 201 created', done => {
const responseMock = mockResponse();
const responseSpy = sinon.spy(responseMock, 'json');
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockRequest('book-id-123'), responseMock, checkResponse);
function checkResponse() {
responseSpy.args[0][0].should.equal(201);
done();
}
deferred.resolve();
});
it('Should return an id property with the scenario id', done => {
const responseMock = mockResponse();
const responseSpy = sinon.spy(responseMock, 'json');
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockRequest('book-id-123'), responseMock, checkResponse);
function checkResponse() {
const body = responseSpy.args[0][1];
body.should.deep.equal({id: idsGeneratorStub()});
done();
}
deferred.resolve();
});
it('Should store the scenario data and id', done => {
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const bookId = 'abc1234';
const mockedRequest = mockRequest(bookId);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockedRequest, mockResponse(), checkResponse);
deferred.resolve();
function checkResponse()
|
});
afterEach(() => {
mockery.deregisterAll();
mockery.disable();
});
});
function getCreateEpisodeMiddleware(idsMock, persistEpisodeInStorage) {
mockery.registerMock('../idsGenerator/generateId.js', idsMock);
mockery.registerMock('./persistEpisodeInStorage.js', persistEpisodeInStorage);
mockery.enable({
useCleanCache: true,
warnOnReplace: false,
warnOnUnregistered: false
});
return require('../../src/episodes/createEpisode.js');
}
function mockResponse() {
return { json: () => {} };
}
function mockRequest(bookId) {
return {
context: {
bookId: bookId
},
body: {
a: 1,
b: 2
}
};
}
|
{
persistEpisodeInStorage.calledOnce.should.equal(true);
persistEpisodeInStorage.args[0][0].should.equal(bookId);
persistEpisodeInStorage.args[0][1].should.deep.equal(_.assign({id: idsGeneratorStub()}, mockedRequest.body));
done();
}
|
identifier_body
|
createEpisodeTest.js
|
'use strict';
const sinon = require('sinon'),
q = require('q'),
mockery = require('mockery'),
_ = require('lodash'),
should = require('chai').should();
describe('Create episode', () => {
const idsGeneratorStub = () => '123';
it('Should call the next callback', done => {
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockRequest('book-id-123'), mockResponse(), done);
deferred.resolve();
});
it('Should return 201 created', done => {
const responseMock = mockResponse();
const responseSpy = sinon.spy(responseMock, 'json');
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockRequest('book-id-123'), responseMock, checkResponse);
function checkResponse() {
responseSpy.args[0][0].should.equal(201);
done();
}
deferred.resolve();
});
it('Should return an id property with the scenario id', done => {
const responseMock = mockResponse();
const responseSpy = sinon.spy(responseMock, 'json');
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockRequest('book-id-123'), responseMock, checkResponse);
function checkResponse() {
|
done();
}
deferred.resolve();
});
it('Should store the scenario data and id', done => {
let deferred = q.defer();
let promise = deferred.promise;
let persistEpisodeInStorage = sinon.stub();
persistEpisodeInStorage.returns(promise);
const bookId = 'abc1234';
const mockedRequest = mockRequest(bookId);
const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage);
createEpisode(mockedRequest, mockResponse(), checkResponse);
deferred.resolve();
function checkResponse() {
persistEpisodeInStorage.calledOnce.should.equal(true);
persistEpisodeInStorage.args[0][0].should.equal(bookId);
persistEpisodeInStorage.args[0][1].should.deep.equal(_.assign({id: idsGeneratorStub()}, mockedRequest.body));
done();
}
});
afterEach(() => {
mockery.deregisterAll();
mockery.disable();
});
});
function getCreateEpisodeMiddleware(idsMock, persistEpisodeInStorage) {
mockery.registerMock('../idsGenerator/generateId.js', idsMock);
mockery.registerMock('./persistEpisodeInStorage.js', persistEpisodeInStorage);
mockery.enable({
useCleanCache: true,
warnOnReplace: false,
warnOnUnregistered: false
});
return require('../../src/episodes/createEpisode.js');
}
function mockResponse() {
return { json: () => {} };
}
function mockRequest(bookId) {
return {
context: {
bookId: bookId
},
body: {
a: 1,
b: 2
}
};
}
|
const body = responseSpy.args[0][1];
body.should.deep.equal({id: idsGeneratorStub()});
|
random_line_split
|
authors.service.ts
|
import getIndex from './helpers/get_index';
import {name as filterServiceName} from './filter.service';
import {Author, AuthorWithID} from './interfaces/author';
import {AuthorsServiceCtor, FilterServiceInstance} from './interfaces/services';
const AuthorsService: AuthorsServiceCtor = function AuthorsService(filterService: FilterServiceInstance, $http, $q) {
this.baseUrl = 'http://127.0.0.1:3000/authors/';
this.filterService = filterService;
this.$http = $http;
this.$q = $q;
this.data = [];
return this;
};
AuthorsService.$inject = [filterServiceName, '$http', '$q'];
AuthorsService.prototype.addAuthor = function (author: Author) {
return this.$http({
method: 'POST',
url: this.baseUrl,
data: author
}).then((response) => {
this.data.push(response.data);
});
};
AuthorsService.prototype.deleteAuthor = function (id: number): any {
return this.$http({
method: 'DELETE',
url: this.baseUrl + id
}).then(() => {
this.data.splice(getIndex(id, this.data), 1);
return this.data;
});
};
AuthorsService.prototype.getAuthors = function (): any {
return this.$http({
method: 'GET',
url: this.baseUrl,
cache: true
}).then((response) => {
this.data = response.data;
return response.data;
});
};
AuthorsService.prototype.getAuthor = function (id: number): any {
if (this.data.length !== 0)
|
else {
return this.getAuthors().then((authors: Array<AuthorWithID>) => {
return authors[getIndex(id, authors)];
});
}
};
AuthorsService.prototype.updateAuthor = function (author: AuthorWithID): any {
return this.$http({
method: 'PUT',
url: this.baseUrl + author._id,
data: author
}).then(() => {
this.data[getIndex(author._id, this.data)] = author;
});
};
AuthorsService.prototype.filter = function (searchTerm: string) {
return this.filterService.filterList(this.data, searchTerm);
};
export default AuthorsService;
export const name = 'AuthorsService';
|
{
return this.$q.resolve(this.data[getIndex(id, this.data)]);
}
|
conditional_block
|
authors.service.ts
|
import getIndex from './helpers/get_index';
import {name as filterServiceName} from './filter.service';
import {Author, AuthorWithID} from './interfaces/author';
import {AuthorsServiceCtor, FilterServiceInstance} from './interfaces/services';
const AuthorsService: AuthorsServiceCtor = function AuthorsService(filterService: FilterServiceInstance, $http, $q) {
this.baseUrl = 'http://127.0.0.1:3000/authors/';
this.filterService = filterService;
this.$http = $http;
this.$q = $q;
this.data = [];
return this;
};
AuthorsService.$inject = [filterServiceName, '$http', '$q'];
|
AuthorsService.prototype.addAuthor = function (author: Author) {
return this.$http({
method: 'POST',
url: this.baseUrl,
data: author
}).then((response) => {
this.data.push(response.data);
});
};
AuthorsService.prototype.deleteAuthor = function (id: number): any {
return this.$http({
method: 'DELETE',
url: this.baseUrl + id
}).then(() => {
this.data.splice(getIndex(id, this.data), 1);
return this.data;
});
};
AuthorsService.prototype.getAuthors = function (): any {
return this.$http({
method: 'GET',
url: this.baseUrl,
cache: true
}).then((response) => {
this.data = response.data;
return response.data;
});
};
AuthorsService.prototype.getAuthor = function (id: number): any {
if (this.data.length !== 0) {
return this.$q.resolve(this.data[getIndex(id, this.data)]);
} else {
return this.getAuthors().then((authors: Array<AuthorWithID>) => {
return authors[getIndex(id, authors)];
});
}
};
AuthorsService.prototype.updateAuthor = function (author: AuthorWithID): any {
return this.$http({
method: 'PUT',
url: this.baseUrl + author._id,
data: author
}).then(() => {
this.data[getIndex(author._id, this.data)] = author;
});
};
AuthorsService.prototype.filter = function (searchTerm: string) {
return this.filterService.filterList(this.data, searchTerm);
};
export default AuthorsService;
export const name = 'AuthorsService';
|
random_line_split
|
|
introspection.py
|
from django.contrib.gis.gdal import OGRGeomType
from django.db.backends.postgresql.introspection import DatabaseIntrospection
class GeoIntrospectionError(Exception):
pass
class PostGISIntrospection(DatabaseIntrospection):
# Reverse dictionary for PostGIS geometry types not populated until
# introspection is actually performed.
postgis_types_reverse = {}
ignored_tables = DatabaseIntrospection.ignored_tables + [
'geography_columns',
'geometry_columns',
'raster_columns',
'spatial_ref_sys',
'raster_overviews',
|
identification integers for the PostGIS geometry and/or
geography types (if supported).
"""
field_types = [
('geometry', 'GeometryField'),
# The value for the geography type is actually a tuple
# to pass in the `geography=True` keyword to the field
# definition.
('geography', ('GeometryField', {'geography': True})),
]
postgis_types = {}
# The OID integers associated with the geometry type may
# be different across versions; hence, this is why we have
# to query the PostgreSQL pg_type table corresponding to the
# PostGIS custom data types.
oid_sql = 'SELECT "oid" FROM "pg_type" WHERE "typname" = %s'
with self.connection.cursor() as cursor:
for field_type in field_types:
cursor.execute(oid_sql, (field_type[0],))
for result in cursor.fetchall():
postgis_types[result[0]] = field_type[1]
return postgis_types
def get_field_type(self, data_type, description):
if not self.postgis_types_reverse:
# If the PostGIS types reverse dictionary is not populated, do so
# now. In order to prevent unnecessary requests upon connection
# initialization, the `data_types_reverse` dictionary is not updated
# with the PostGIS custom types until introspection is actually
# performed -- in other words, when this function is called.
self.postgis_types_reverse = self.get_postgis_types()
self.data_types_reverse.update(self.postgis_types_reverse)
return super().get_field_type(data_type, description)
def get_geometry_type(self, table_name, geo_col):
"""
The geometry type OID used by PostGIS does not indicate the particular
type of field that a geometry column is (e.g., whether it's a
PointField or a PolygonField). Thus, this routine queries the PostGIS
metadata tables to determine the geometry type.
"""
with self.connection.cursor() as cursor:
try:
# First seeing if this geometry column is in the `geometry_columns`
cursor.execute('SELECT "coord_dimension", "srid", "type" '
'FROM "geometry_columns" '
'WHERE "f_table_name"=%s AND "f_geometry_column"=%s',
(table_name, geo_col))
row = cursor.fetchone()
if not row:
raise GeoIntrospectionError
except GeoIntrospectionError:
cursor.execute('SELECT "coord_dimension", "srid", "type" '
'FROM "geography_columns" '
'WHERE "f_table_name"=%s AND "f_geography_column"=%s',
(table_name, geo_col))
row = cursor.fetchone()
if not row:
raise Exception('Could not find a geometry or geography column for "%s"."%s"' %
(table_name, geo_col))
# OGRGeomType does not require GDAL and makes it easy to convert
# from OGC geom type name to Django field.
field_type = OGRGeomType(row[2]).django
# Getting any GeometryField keyword arguments that are not the default.
dim = row[0]
srid = row[1]
field_params = {}
if srid != 4326:
field_params['srid'] = srid
if dim != 2:
field_params['dim'] = dim
return field_type, field_params
|
]
def get_postgis_types(self):
"""
Return a dictionary with keys that are the PostgreSQL object
|
random_line_split
|
introspection.py
|
from django.contrib.gis.gdal import OGRGeomType
from django.db.backends.postgresql.introspection import DatabaseIntrospection
class GeoIntrospectionError(Exception):
pass
class PostGISIntrospection(DatabaseIntrospection):
# Reverse dictionary for PostGIS geometry types not populated until
# introspection is actually performed.
|
postgis_types_reverse = {}
ignored_tables = DatabaseIntrospection.ignored_tables + [
'geography_columns',
'geometry_columns',
'raster_columns',
'spatial_ref_sys',
'raster_overviews',
]
def get_postgis_types(self):
"""
Return a dictionary with keys that are the PostgreSQL object
identification integers for the PostGIS geometry and/or
geography types (if supported).
"""
field_types = [
('geometry', 'GeometryField'),
# The value for the geography type is actually a tuple
# to pass in the `geography=True` keyword to the field
# definition.
('geography', ('GeometryField', {'geography': True})),
]
postgis_types = {}
# The OID integers associated with the geometry type may
# be different across versions; hence, this is why we have
# to query the PostgreSQL pg_type table corresponding to the
# PostGIS custom data types.
oid_sql = 'SELECT "oid" FROM "pg_type" WHERE "typname" = %s'
with self.connection.cursor() as cursor:
for field_type in field_types:
cursor.execute(oid_sql, (field_type[0],))
for result in cursor.fetchall():
postgis_types[result[0]] = field_type[1]
return postgis_types
def get_field_type(self, data_type, description):
if not self.postgis_types_reverse:
# If the PostGIS types reverse dictionary is not populated, do so
# now. In order to prevent unnecessary requests upon connection
# initialization, the `data_types_reverse` dictionary is not updated
# with the PostGIS custom types until introspection is actually
# performed -- in other words, when this function is called.
self.postgis_types_reverse = self.get_postgis_types()
self.data_types_reverse.update(self.postgis_types_reverse)
return super().get_field_type(data_type, description)
def get_geometry_type(self, table_name, geo_col):
"""
The geometry type OID used by PostGIS does not indicate the particular
type of field that a geometry column is (e.g., whether it's a
PointField or a PolygonField). Thus, this routine queries the PostGIS
metadata tables to determine the geometry type.
"""
with self.connection.cursor() as cursor:
try:
# First seeing if this geometry column is in the `geometry_columns`
cursor.execute('SELECT "coord_dimension", "srid", "type" '
'FROM "geometry_columns" '
'WHERE "f_table_name"=%s AND "f_geometry_column"=%s',
(table_name, geo_col))
row = cursor.fetchone()
if not row:
raise GeoIntrospectionError
except GeoIntrospectionError:
cursor.execute('SELECT "coord_dimension", "srid", "type" '
'FROM "geography_columns" '
'WHERE "f_table_name"=%s AND "f_geography_column"=%s',
(table_name, geo_col))
row = cursor.fetchone()
if not row:
raise Exception('Could not find a geometry or geography column for "%s"."%s"' %
(table_name, geo_col))
# OGRGeomType does not require GDAL and makes it easy to convert
# from OGC geom type name to Django field.
field_type = OGRGeomType(row[2]).django
# Getting any GeometryField keyword arguments that are not the default.
dim = row[0]
srid = row[1]
field_params = {}
if srid != 4326:
field_params['srid'] = srid
if dim != 2:
field_params['dim'] = dim
return field_type, field_params
|
identifier_body
|
|
introspection.py
|
from django.contrib.gis.gdal import OGRGeomType
from django.db.backends.postgresql.introspection import DatabaseIntrospection
class GeoIntrospectionError(Exception):
pass
class PostGISIntrospection(DatabaseIntrospection):
# Reverse dictionary for PostGIS geometry types not populated until
# introspection is actually performed.
postgis_types_reverse = {}
ignored_tables = DatabaseIntrospection.ignored_tables + [
'geography_columns',
'geometry_columns',
'raster_columns',
'spatial_ref_sys',
'raster_overviews',
]
def get_postgis_types(self):
"""
Return a dictionary with keys that are the PostgreSQL object
identification integers for the PostGIS geometry and/or
geography types (if supported).
"""
field_types = [
('geometry', 'GeometryField'),
# The value for the geography type is actually a tuple
# to pass in the `geography=True` keyword to the field
# definition.
('geography', ('GeometryField', {'geography': True})),
]
postgis_types = {}
# The OID integers associated with the geometry type may
# be different across versions; hence, this is why we have
# to query the PostgreSQL pg_type table corresponding to the
# PostGIS custom data types.
oid_sql = 'SELECT "oid" FROM "pg_type" WHERE "typname" = %s'
with self.connection.cursor() as cursor:
for field_type in field_types:
cursor.execute(oid_sql, (field_type[0],))
for result in cursor.fetchall():
postgis_types[result[0]] = field_type[1]
return postgis_types
def get_field_type(self, data_type, description):
if not self.postgis_types_reverse:
# If the PostGIS types reverse dictionary is not populated, do so
# now. In order to prevent unnecessary requests upon connection
# initialization, the `data_types_reverse` dictionary is not updated
# with the PostGIS custom types until introspection is actually
# performed -- in other words, when this function is called.
self.postgis_types_reverse = self.get_postgis_types()
self.data_types_reverse.update(self.postgis_types_reverse)
return super().get_field_type(data_type, description)
def get_geometry_type(self, table_name, geo_col):
"""
The geometry type OID used by PostGIS does not indicate the particular
type of field that a geometry column is (e.g., whether it's a
PointField or a PolygonField). Thus, this routine queries the PostGIS
metadata tables to determine the geometry type.
"""
with self.connection.cursor() as cursor:
try:
# First seeing if this geometry column is in the `geometry_columns`
cursor.execute('SELECT "coord_dimension", "srid", "type" '
'FROM "geometry_columns" '
'WHERE "f_table_name"=%s AND "f_geometry_column"=%s',
(table_name, geo_col))
row = cursor.fetchone()
if not row:
raise GeoIntrospectionError
except GeoIntrospectionError:
cursor.execute('SELECT "coord_dimension", "srid", "type" '
'FROM "geography_columns" '
'WHERE "f_table_name"=%s AND "f_geography_column"=%s',
(table_name, geo_col))
row = cursor.fetchone()
if not row:
|
# OGRGeomType does not require GDAL and makes it easy to convert
# from OGC geom type name to Django field.
field_type = OGRGeomType(row[2]).django
# Getting any GeometryField keyword arguments that are not the default.
dim = row[0]
srid = row[1]
field_params = {}
if srid != 4326:
field_params['srid'] = srid
if dim != 2:
field_params['dim'] = dim
return field_type, field_params
|
raise Exception('Could not find a geometry or geography column for "%s"."%s"' %
(table_name, geo_col))
|
conditional_block
|
introspection.py
|
from django.contrib.gis.gdal import OGRGeomType
from django.db.backends.postgresql.introspection import DatabaseIntrospection
class GeoIntrospectionError(Exception):
pass
class PostGISIntrospection(DatabaseIntrospection):
# Reverse dictionary for PostGIS geometry types not populated until
# introspection is actually performed.
postgis_types_reverse = {}
ignored_tables = DatabaseIntrospection.ignored_tables + [
'geography_columns',
'geometry_columns',
'raster_columns',
'spatial_ref_sys',
'raster_overviews',
]
def get_postgis_types(self):
"""
Return a dictionary with keys that are the PostgreSQL object
identification integers for the PostGIS geometry and/or
geography types (if supported).
"""
field_types = [
('geometry', 'GeometryField'),
# The value for the geography type is actually a tuple
# to pass in the `geography=True` keyword to the field
# definition.
('geography', ('GeometryField', {'geography': True})),
]
postgis_types = {}
# The OID integers associated with the geometry type may
# be different across versions; hence, this is why we have
# to query the PostgreSQL pg_type table corresponding to the
# PostGIS custom data types.
oid_sql = 'SELECT "oid" FROM "pg_type" WHERE "typname" = %s'
with self.connection.cursor() as cursor:
for field_type in field_types:
cursor.execute(oid_sql, (field_type[0],))
for result in cursor.fetchall():
postgis_types[result[0]] = field_type[1]
return postgis_types
def
|
(self, data_type, description):
if not self.postgis_types_reverse:
# If the PostGIS types reverse dictionary is not populated, do so
# now. In order to prevent unnecessary requests upon connection
# initialization, the `data_types_reverse` dictionary is not updated
# with the PostGIS custom types until introspection is actually
# performed -- in other words, when this function is called.
self.postgis_types_reverse = self.get_postgis_types()
self.data_types_reverse.update(self.postgis_types_reverse)
return super().get_field_type(data_type, description)
def get_geometry_type(self, table_name, geo_col):
"""
The geometry type OID used by PostGIS does not indicate the particular
type of field that a geometry column is (e.g., whether it's a
PointField or a PolygonField). Thus, this routine queries the PostGIS
metadata tables to determine the geometry type.
"""
with self.connection.cursor() as cursor:
try:
# First seeing if this geometry column is in the `geometry_columns`
cursor.execute('SELECT "coord_dimension", "srid", "type" '
'FROM "geometry_columns" '
'WHERE "f_table_name"=%s AND "f_geometry_column"=%s',
(table_name, geo_col))
row = cursor.fetchone()
if not row:
raise GeoIntrospectionError
except GeoIntrospectionError:
cursor.execute('SELECT "coord_dimension", "srid", "type" '
'FROM "geography_columns" '
'WHERE "f_table_name"=%s AND "f_geography_column"=%s',
(table_name, geo_col))
row = cursor.fetchone()
if not row:
raise Exception('Could not find a geometry or geography column for "%s"."%s"' %
(table_name, geo_col))
# OGRGeomType does not require GDAL and makes it easy to convert
# from OGC geom type name to Django field.
field_type = OGRGeomType(row[2]).django
# Getting any GeometryField keyword arguments that are not the default.
dim = row[0]
srid = row[1]
field_params = {}
if srid != 4326:
field_params['srid'] = srid
if dim != 2:
field_params['dim'] = dim
return field_type, field_params
|
get_field_type
|
identifier_name
|
ir_exports.py
|
# -*- coding: utf-8 -*-
# Copyright 2015-2016 Jairo Llopis <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import _, api, fields, models
from openerp.exceptions import ValidationError
class IrExports(models.Model):
_inherit = 'ir.exports'
name = fields.Char(required=True)
resource = fields.Char(
required=False,
readonly=True,
help="Model's technical name.")
model_id = fields.Many2one(
"ir.model",
|
inverse="_inverse_model_id",
help="Database model to export.")
@api.multi
@api.depends("resource")
def _compute_model_id(self):
"""Get the model from the resource."""
for s in self:
s.model_id = self._get_model_id(s.resource)
@api.multi
@api.onchange("model_id")
def _inverse_model_id(self):
"""Get the resource from the model."""
for s in self:
s.resource = s.model_id.model
@api.multi
@api.onchange("resource")
def _onchange_resource(self):
"""Void fields if model is changed in a view."""
for s in self:
s.export_fields = False
@api.model
def _get_model_id(self, resource):
"""Return a model object from its technical name.
:param str resource:
Technical name of the model, like ``ir.model``.
"""
return self.env["ir.model"].search([("model", "=", resource)])
@api.model
def create(self, vals):
"""Check required values when creating the record.
Odoo's export dialog populates ``resource``, while this module's new
form populates ``model_id``. At least one of them is required to
trigger the methods that fill up the other, so this should fail if
one is missing.
"""
if not any(f in vals for f in {"model_id", "resource"}):
raise ValidationError(_("You must supply a model or resource."))
return super(IrExports, self).create(vals)
|
"Model",
store=True,
domain=[("transient", "=", False)],
compute="_compute_model_id",
|
random_line_split
|
ir_exports.py
|
# -*- coding: utf-8 -*-
# Copyright 2015-2016 Jairo Llopis <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import _, api, fields, models
from openerp.exceptions import ValidationError
class IrExports(models.Model):
_inherit = 'ir.exports'
name = fields.Char(required=True)
resource = fields.Char(
required=False,
readonly=True,
help="Model's technical name.")
model_id = fields.Many2one(
"ir.model",
"Model",
store=True,
domain=[("transient", "=", False)],
compute="_compute_model_id",
inverse="_inverse_model_id",
help="Database model to export.")
@api.multi
@api.depends("resource")
def _compute_model_id(self):
"""Get the model from the resource."""
for s in self:
s.model_id = self._get_model_id(s.resource)
@api.multi
@api.onchange("model_id")
def _inverse_model_id(self):
"""Get the resource from the model."""
for s in self:
s.resource = s.model_id.model
@api.multi
@api.onchange("resource")
def _onchange_resource(self):
"""Void fields if model is changed in a view."""
for s in self:
|
@api.model
def _get_model_id(self, resource):
"""Return a model object from its technical name.
:param str resource:
Technical name of the model, like ``ir.model``.
"""
return self.env["ir.model"].search([("model", "=", resource)])
@api.model
def create(self, vals):
"""Check required values when creating the record.
Odoo's export dialog populates ``resource``, while this module's new
form populates ``model_id``. At least one of them is required to
trigger the methods that fill up the other, so this should fail if
one is missing.
"""
if not any(f in vals for f in {"model_id", "resource"}):
raise ValidationError(_("You must supply a model or resource."))
return super(IrExports, self).create(vals)
|
s.export_fields = False
|
conditional_block
|
ir_exports.py
|
# -*- coding: utf-8 -*-
# Copyright 2015-2016 Jairo Llopis <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import _, api, fields, models
from openerp.exceptions import ValidationError
class IrExports(models.Model):
_inherit = 'ir.exports'
name = fields.Char(required=True)
resource = fields.Char(
required=False,
readonly=True,
help="Model's technical name.")
model_id = fields.Many2one(
"ir.model",
"Model",
store=True,
domain=[("transient", "=", False)],
compute="_compute_model_id",
inverse="_inverse_model_id",
help="Database model to export.")
@api.multi
@api.depends("resource")
def _compute_model_id(self):
"""Get the model from the resource."""
for s in self:
s.model_id = self._get_model_id(s.resource)
@api.multi
@api.onchange("model_id")
def _inverse_model_id(self):
"""Get the resource from the model."""
for s in self:
s.resource = s.model_id.model
@api.multi
@api.onchange("resource")
def
|
(self):
"""Void fields if model is changed in a view."""
for s in self:
s.export_fields = False
@api.model
def _get_model_id(self, resource):
"""Return a model object from its technical name.
:param str resource:
Technical name of the model, like ``ir.model``.
"""
return self.env["ir.model"].search([("model", "=", resource)])
@api.model
def create(self, vals):
"""Check required values when creating the record.
Odoo's export dialog populates ``resource``, while this module's new
form populates ``model_id``. At least one of them is required to
trigger the methods that fill up the other, so this should fail if
one is missing.
"""
if not any(f in vals for f in {"model_id", "resource"}):
raise ValidationError(_("You must supply a model or resource."))
return super(IrExports, self).create(vals)
|
_onchange_resource
|
identifier_name
|
ir_exports.py
|
# -*- coding: utf-8 -*-
# Copyright 2015-2016 Jairo Llopis <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import _, api, fields, models
from openerp.exceptions import ValidationError
class IrExports(models.Model):
_inherit = 'ir.exports'
name = fields.Char(required=True)
resource = fields.Char(
required=False,
readonly=True,
help="Model's technical name.")
model_id = fields.Many2one(
"ir.model",
"Model",
store=True,
domain=[("transient", "=", False)],
compute="_compute_model_id",
inverse="_inverse_model_id",
help="Database model to export.")
@api.multi
@api.depends("resource")
def _compute_model_id(self):
"""Get the model from the resource."""
for s in self:
s.model_id = self._get_model_id(s.resource)
@api.multi
@api.onchange("model_id")
def _inverse_model_id(self):
|
@api.multi
@api.onchange("resource")
def _onchange_resource(self):
"""Void fields if model is changed in a view."""
for s in self:
s.export_fields = False
@api.model
def _get_model_id(self, resource):
"""Return a model object from its technical name.
:param str resource:
Technical name of the model, like ``ir.model``.
"""
return self.env["ir.model"].search([("model", "=", resource)])
@api.model
def create(self, vals):
"""Check required values when creating the record.
Odoo's export dialog populates ``resource``, while this module's new
form populates ``model_id``. At least one of them is required to
trigger the methods that fill up the other, so this should fail if
one is missing.
"""
if not any(f in vals for f in {"model_id", "resource"}):
raise ValidationError(_("You must supply a model or resource."))
return super(IrExports, self).create(vals)
|
"""Get the resource from the model."""
for s in self:
s.resource = s.model_id.model
|
identifier_body
|
unique-pinned-nocopy-2.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct r {
i: @mut int,
}
#[unsafe_destructor]
impl Drop for r {
fn drop(&self) {
unsafe {
*(self.i) = *(self.i) + 1;
}
}
}
fn r(i: @mut int) -> r {
r {
i: i
}
}
pub fn
|
() {
let i = @mut 0;
{
let j = ~r(i);
}
assert_eq!(*i, 1);
}
|
main
|
identifier_name
|
unique-pinned-nocopy-2.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct r {
i: @mut int,
}
#[unsafe_destructor]
impl Drop for r {
fn drop(&self) {
unsafe {
*(self.i) = *(self.i) + 1;
}
}
|
fn r(i: @mut int) -> r {
r {
i: i
}
}
pub fn main() {
let i = @mut 0;
{
let j = ~r(i);
}
assert_eq!(*i, 1);
}
|
}
|
random_line_split
|
unique-pinned-nocopy-2.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct r {
i: @mut int,
}
#[unsafe_destructor]
impl Drop for r {
fn drop(&self)
|
}
fn r(i: @mut int) -> r {
r {
i: i
}
}
pub fn main() {
let i = @mut 0;
{
let j = ~r(i);
}
assert_eq!(*i, 1);
}
|
{
unsafe {
*(self.i) = *(self.i) + 1;
}
}
|
identifier_body
|
polar.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from numpy import array, zeros, linspace, meshgrid, ndarray, diag
from numpy import uint8, float64, int8, int0, float128, complex128
from numpy import exp, sqrt, cos, tan, arctan
from numpy import minimum, maximum
from numpy import ceil, floor
from numpy import matrix as npmatrix
from numpy.fft import fft, ifft
from numpy import pi
from scipy.linalg import solve_triangular as solve
from scipy.signal import fftconvolve as conv
from scipy.ndimage import geometric_transform as transform
# We will make use of *reentrant* locks.
from threading import RLock as Lock
from threading import Condition, Thread
# This module is a modification on python's queue module,
# which allows one to interrupt a queue.
import iqueue
# This is a module written to execute code in parallel.
# While python is limited by the Global Interpreter Lock,
# numerical operations on NumPy arrays are generally not
# limited by the GIL.
import parallel
# This module allows the conversion of SAGE symbolic expressions
# to RPN code through the symbolic_to_rpn. RPNProgram is a subclass
# of list that comes equipped with a __call__ method that implements
# execution of the RPN code.
import rpncalc
def _E(m):
return int0(npmatrix(diag((1,) * int(m + 1), k=0)[:, :-1]))
def _X(m):
return int0(npmatrix(diag((1,) * int(m), k=-1)[:, :-1]))
def _Del(m):
return int0(npmatrix(diag(xrange(1, int(m)), k=1)[:-1]))
class _CD_RPN:
def __init__(self):
self.coeffs = [(npmatrix((-1,)), npmatrix((-1,)))]
self.rpn = [(rpncalc.RPNProgram([-1]), rpncalc.RPNProgram([-1]))]
# In case this class is utilized by multiple threads.
self.lock = Lock()
def getcoeffs(self, m):
# Returns coefficients for $c_{m}$ and $d_{m}$.
# If they already exist in cache, just return what is there.
with self.lock:
if len(self.coeffs) <= m:
# Need to generate coefficients for $c_{m}$ and $d_{m}$.
# Fetch the coefficients for $c_{m-1}$ and $d_{m-1}$.
C, D = self.getcoeffs(m - 1)
if m % 2: # $m$ is odd
C_new = _E(m) * D * _X((m + 1) / 2).transpose() \
- ((1 + m) * _E(m) + 3 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * C \
* _E((m + 1) / 2).transpose()
D_new = _X(m) * C - (m * _E(m) + 2 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * D
else: # $m$ is even
C_new = _E(m) * D * _X(m / 2).transpose() \
- ((1 + m) * _E(m) + 3 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * C
D_new = _X(m) * C - (m * _E(m) + 2 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * D \
* _E(m / 2).transpose()
self.coeffs.append((C_new, D_new))
return self.coeffs[m]
def __getitem__(self, m):
n2 = rpncalc.wild("n2")
v2 = rpncalc.wild("v2")
mul = rpncalc.rpn_funcs[u"⋅"]
add = rpncalc.rpn_funcs[u"+"]
# Returns RPN code for $c_j$ and $d_j$. Generate on the fly if needed.
with self.lock:
while len(self.rpn) <= m:
cm_rpn = []
dm_rpn = []
C, D = self.getcoeffs(len(self.rpn))
# Generate RPN code for $c_j$ and $d_j$.
for row in array(C[::-1]):
npoly_rpn = []
for coeff in row[::-1]:
if coeff:
if len(npoly_rpn):
npoly_rpn.extend([n2, mul])
npoly_rpn.extend([coeff, add])
else:
npoly_rpn.append(coeff)
elif len(npoly_rpn):
np
|
if len(cm_rpn):
cm_rpn.extend([v2, mul])
cm_rpn.extend(npoly_rpn)
cm_rpn.append(add)
else:
cm_rpn.extend(npoly_rpn)
for row in array(D[::-1]):
npoly_rpn = []
for coeff in row[::-1]:
if coeff:
if len(npoly_rpn):
npoly_rpn.extend([n2, mul])
npoly_rpn.extend([coeff, add])
else:
npoly_rpn.append(coeff)
elif len(npoly_rpn):
npoly_rpn.extend([n2, mul])
if len(dm_rpn):
dm_rpn.extend([v2, mul])
dm_rpn.extend(npoly_rpn)
dm_rpn.append(add)
else:
dm_rpn.extend(npoly_rpn)
self.rpn.append(
(rpncalc.RPNProgram(cm_rpn), rpncalc.RPNProgram(dm_rpn)))
return self.rpn[m]
class Sderiv:
def __init__(self, alpha):
self.alpha = alpha
def __call__(self, A, ds):
H, W = A.shape
psi = rpncalc.decode(u"« x 3 ^ 4 / +/- 3 x * 4 / + »")
N = ceil(self.alpha / ds)
X = linspace(-N * ds - ds, N * ds + ds, 2 * N + 3)
Psi = psi(x=X / self.alpha)
Psi[X > self.alpha] = psi(x=1)
Psi[X < -self.alpha] = psi(x=-1)
stencil = (Psi[:-2] + Psi[2:] - 2 * Psi[1:-1]) / ds
diff = conv([stencil], A)
return N, N, diff[:, 2 * N:-2 * N]
class PolarBrokenRayInversion(parallel.BaseTaskClass):
_cd = _CD_RPN()
_u = rpncalc.decode(u"« q phi sin ⋅ arcsin »")
_v = rpncalc.decode(u"« q phi sin ⋅ +/- q 2 ^ phi sin 2 ^ ⋅ +/- 1 + √ ÷ »")
_w = rpncalc.decode(u"« i phi u - ⋅ exp »")
_tm = rpncalc.decode(u"« i dm ⋅ n ⋅ cm v ⋅ + dlnr m ^ ⋅ m 2 + ! ÷ »")
_cf = rpncalc.decode(u"« dr r ⋅ v 2 ^ ⋅ phi csc ⋅ s 2 ^ ÷ »")
_invlock = Lock()
def __init__(self, Qf, Phi, smin, smax, alpha, nmax=200):
# Parameters:
# $\mathbf{Qf}$ -- $\mathcal{Q}f$, sampled on an $r\theta$ grid.
# $\mathbf{Phi}$ ($\phi$) -- Scattering angle
# $\mathbf{rmin}$ -- $r_{\min}$, defaults to $1$.
# $\mathbf{rmax}$ -- $r_{\max}$, defaults to $6$.
# $\mathbf{D}$ -- Numerical implemenation of $\frac{\partial}{\partial r}$.
# $\mathbf{nmax}$ -- $n_{\max}$, reconstructs $\tilde{f}\left(r,n\right)$
# for $\left|n\right| \le n_{\max}$. Defaults to $200$.
# This reconstruction will assume that $\mathcal{Q}f$ is real and exploit
# conjugate symmetry in the Fourier series.
# Initialize variables.
self.Qf = Qf
self.Phi = Phi
self.smin = smin
self.smax = smax
H, W = Qf.shape
self.thetamin = thetamin = -pi
self.thetamax = thetamax = pi*(1-2.0/H)
self.nmax = nmax
self.F = None
self.F_cartesian = None
self.lock = Lock()
self.status = Condition(self.lock)
self.jobsdone = 0
self.jobcount = nmax + 1
self.running = False
self.projectioncount = 0
self.projecting = False
self.dr = dr = ds = (smax - smin) / float(W - 1)
self.dtheta = dtheta = (thetamax - thetamin) / float(H)
# Compute $\widetilde{\mathcal{Q}f}$.
self.FQf = FQf = fft(Qf, axis=0)
# Perform differentiation of $\widetilde{\mathcal{Q}f}$.
D = Sderiv(alpha)
try:
clip_left, clip_right, self.DFQf = D(FQf, ds)
except:
clip_left, clip_right, self.DFQf = D(float64(FQf), ds)
# Initialize array that will store $\tilde{f}$.
self.Ff = zeros(self.DFQf.shape, dtype=complex128)
# Initialize $rs$ grid.
self.rmin = self.smin + clip_left * ds
self.rmax = self.smax - clip_right * ds
R = linspace(self.rmin, self.rmax, W - clip_left - clip_right)
self.R, self.S = meshgrid(R, R)
# Compute $q$, $u$, $v$, $w$, and $v^{2}r*\csc(\phi)*{\Delta}r/s^2$.
self.Q = self.S / self.R
args = dict(q=self.Q, r=self.R, s=self.S, phi=self.Phi, dr=dr)
args["u"] = self.U = self._u(**args)
args["v"] = self.V = self._v(**args)
self.W = self._w(**args)
self.Factor = self._cf(**args)
def A(self, n, eps=0.0000001, p=16):
# Compute matrix $\mathbf{A}_n$.
H, W = self.DFQf.shape
# Initialize the An matrix (as an array for now).
An = zeros(self.R.shape, dtype=complex128)
# First compute a partial sum for the upper triangular part.
# Start with $m=0$
mask = self.S < self.R
Sum = zeros(self.R.shape, dtype=complex128)
for m in xrange(0, p + 1, 2):
cm_rpn, dm_rpn = self._cd[m]
Term = self._tm(v=self.V[mask], v2=self.V[mask] ** 2,
dlnr=self.dr / self.R[mask],
n=n, n2=n ** 2, m=m, cm=cm_rpn, dm=dm_rpn)
Sum[mask] += Term
mask[mask] *= abs(Term) >= eps
if not mask.any():
break
mask = self.S < self.R
An[mask] = 2 * self.W[mask] ** n * self.Factor[mask] * Sum[mask]
# Now to do the diagonal.
# Since $r=s$ here, we have $q=1$, $u=\phi$, $v=-\tan\phi$,
# and $w=1$.
mask = self.S == self.R
Sum = zeros(self.R.shape, dtype=complex128)
for m in xrange(0, p + 1):
cm_rpn, dm_rpn = self._cd[m]
Term = self._tm(v=-tan(self.Phi), v2=tan(self.Phi) ** 2,
dlnr=self.dr / self.R[mask],
n=n, n2=n ** 2, m=m, cm=cm_rpn, dm=dm_rpn)
Sum[mask] += Term
mask[mask] *= abs(Term) >= eps
if not mask.any():
break
mask = self.S == self.R
An[mask] = self.Factor[mask] * Sum[mask] + \
array([1 - 1 / cos(self.Phi)] * W)
return npmatrix(An)
def f(self, n):
# This is the function that is run in parallel.
An = self.A(n, eps=10 ** -9, p=24)
DFQf = self.DFQf[n]
#AnInv = inv(An).transpose()
#Ff = array(DFQf*AnInv)[0]
Ff = solve(An, DFQf)
return Ff
def populatequeue(self, queue):
for n in xrange(self.nmax + 1):
queue.put(n)
def postproc(self, (n, Ff)):
with self.status:
self.Ff[n] = Ff
if n > 0:
self.Ff[-n] = Ff.conjugate()
self.jobsdone += 1
self.status.notifyAll()
def reconstruct(self):
with self.lock:
self.F = ifft(self.Ff, axis=0)
return self.F
|
oly_rpn.extend([n2, mul])
|
conditional_block
|
polar.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from numpy import array, zeros, linspace, meshgrid, ndarray, diag
from numpy import uint8, float64, int8, int0, float128, complex128
from numpy import exp, sqrt, cos, tan, arctan
from numpy import minimum, maximum
from numpy import ceil, floor
from numpy import matrix as npmatrix
from numpy.fft import fft, ifft
from numpy import pi
from scipy.linalg import solve_triangular as solve
from scipy.signal import fftconvolve as conv
from scipy.ndimage import geometric_transform as transform
# We will make use of *reentrant* locks.
from threading import RLock as Lock
from threading import Condition, Thread
# This module is a modification on python's queue module,
# which allows one to interrupt a queue.
import iqueue
# This is a module written to execute code in parallel.
# While python is limited by the Global Interpreter Lock,
# numerical operations on NumPy arrays are generally not
# limited by the GIL.
import parallel
# This module allows the conversion of SAGE symbolic expressions
# to RPN code through the symbolic_to_rpn. RPNProgram is a subclass
# of list that comes equipped with a __call__ method that implements
# execution of the RPN code.
import rpncalc
def _E(m):
return int0(npmatrix(diag((1,) * int(m + 1), k=0)[:, :-1]))
def _X(m):
return int0(npmatrix(diag((1,) * int(m), k=-1)[:, :-1]))
def _Del(m):
return int0(npmatrix(diag(xrange(1, int(m)), k=1)[:-1]))
class _CD_RPN:
def __init__(self):
self.coeffs = [(npmatrix((-1,)), npmatrix((-1,)))]
self.rpn = [(rpncalc.RPNProgram([-1]), rpncalc.RPNProgram([-1]))]
# In case this class is utilized by multiple threads.
self.lock = Lock()
def getcoeffs(self, m):
# Returns coefficients for $c_{m}$ and $d_{m}$.
# If they already exist in cache, just return what is there.
with self.lock:
if len(self.coeffs) <= m:
# Need to generate coefficients for $c_{m}$ and $d_{m}$.
# Fetch the coefficients for $c_{m-1}$ and $d_{m-1}$.
C, D = self.getcoeffs(m - 1)
if m % 2: # $m$ is odd
C_new = _E(m) * D * _X((m + 1) / 2).transpose() \
- ((1 + m) * _E(m) + 3 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * C \
* _E((m + 1) / 2).transpose()
D_new = _X(m) * C - (m * _E(m) + 2 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * D
else: # $m$ is even
C_new = _E(m) * D * _X(m / 2).transpose() \
- ((1 + m) * _E(m) + 3 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * C
D_new = _X(m) * C - (m * _E(m) + 2 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * D \
* _E(m / 2).transpose()
self.coeffs.append((C_new, D_new))
return self.coeffs[m]
def __getitem__(self, m):
n2 = rpncalc.wild("n2")
v2 = rpncalc.wild("v2")
mul = rpncalc.rpn_funcs[u"⋅"]
add = rpncalc.rpn_funcs[u"+"]
# Returns RPN code for $c_j$ and $d_j$. Generate on the fly if needed.
with self.lock:
while len(self.rpn) <= m:
cm_rpn = []
dm_rpn = []
C, D = self.getcoeffs(len(self.rpn))
# Generate RPN code for $c_j$ and $d_j$.
for row in array(C[::-1]):
npoly_rpn = []
for coeff in row[::-1]:
if coeff:
if len(npoly_rpn):
npoly_rpn.extend([n2, mul])
npoly_rpn.extend([coeff, add])
else:
npoly_rpn.append(coeff)
elif len(npoly_rpn):
npoly_rpn.extend([n2, mul])
if len(cm_rpn):
cm_rpn.extend([v2, mul])
cm_rpn.extend(npoly_rpn)
cm_rpn.append(add)
else:
cm_rpn.extend(npoly_rpn)
for row in array(D[::-1]):
npoly_rpn = []
for coeff in row[::-1]:
if coeff:
if len(npoly_rpn):
npoly_rpn.extend([n2, mul])
npoly_rpn.extend([coeff, add])
else:
npoly_rpn.append(coeff)
elif len(npoly_rpn):
npoly_rpn.extend([n2, mul])
if len(dm_rpn):
dm_rpn.extend([v2, mul])
dm_rpn.extend(npoly_rpn)
dm_rpn.append(add)
else:
dm_rpn.extend(npoly_rpn)
self.rpn.append(
(rpncalc.RPNProgram(cm_rpn), rpncalc.RPNProgram(dm_rpn)))
return self.rpn[m]
class Sderiv:
def __init__(self, alpha):
self.alpha = alpha
def __call__(self, A, ds):
H, W = A.shape
psi = rpncalc.decode(u"« x 3 ^ 4 / +/- 3 x * 4 / + »")
N = ceil(self.alpha / ds)
X = linspace(-N * ds - ds, N * ds + ds, 2 * N + 3)
Psi = psi(x=X / self.alpha)
Psi[X > self.alpha] = psi(x=1)
Psi[X < -self.alpha] = psi(x=-1)
stencil = (Psi[:-2] + Psi[2:] - 2 * Psi[1:-1]) / ds
diff = conv([stencil], A)
return N, N, diff[:, 2 * N:-2 * N]
class PolarBrokenRayInversion(parallel.BaseTaskClass):
_cd = _CD_RPN()
_u = rpncalc.decode(u"« q phi sin ⋅ arcsin »")
_v = rpncalc.decode(u"« q phi sin ⋅ +/- q 2 ^ phi sin 2 ^ ⋅ +/- 1 + √ ÷ »")
_w = rpncalc.decode(u"« i phi u - ⋅ exp »")
_tm = rpncalc.decode(u"« i dm ⋅ n ⋅ cm v ⋅ + dlnr m ^ ⋅ m 2 + ! ÷ »")
_cf = rpncalc.decode(u"« dr r ⋅ v 2 ^ ⋅ phi csc ⋅ s 2 ^ ÷ »")
_invlock = Lock()
def __init__(self, Qf, Phi, smin, smax, alpha, nmax=200):
# Parameters:
# $\mathbf{Qf}$ -- $\mathcal{Q}f$, sampled on an $r\theta$ grid.
# $\mathbf{Phi}$ ($\phi$) -- Scattering angle
# $\mathbf{rmin}$ -- $r_{\min}$, defaults to $1$.
# $\mathbf{rmax}$ -- $r_{\max}$, defaults to $6$.
# $\mathbf{D}$ -- Numerical implemenation of $\frac{\partial}{\partial r}$.
# $\mathbf{nmax}$ -- $n_{\max}$, reconstructs $\tilde{f}\left(r,n\right)$
# for $\left|n\right| \le n_{\max}$. Defaults to $200$.
# This reconstruction will assume that $\mathcal{Q}f$ is real and exploit
# conjugate symmetry in the Fourier series.
# Initialize variables.
self.Qf = Qf
self.Phi = Phi
self.smin = smin
self.smax = smax
H, W = Qf.shape
self.thetamin = thetamin = -pi
self.thetamax = thetamax = pi*(1-2.0/H)
self.nmax = nmax
self.F = None
self.F_cartesian = None
self.lock = Lock()
self.status = Condition(self.lock)
self.jobsdone = 0
self.jobcount = nmax + 1
self.running = False
self.projectioncount = 0
self.projecting = False
self.dr = dr = ds = (smax - smin) / float(W - 1)
self.dtheta = dtheta = (thetamax - thetamin) / float(H)
# Compute $\widetilde{\mathcal{Q}f}$.
self.FQf = FQf = fft(Qf, axis=0)
# Perform differentiation of $\widetilde{\mathcal{Q}f}$.
D = Sderiv(alpha)
try:
clip_left, clip_right, self.DFQf = D(FQf, ds)
except:
clip_left, clip_right, self.DFQf = D(float64(FQf), ds)
# Initialize array that will store $\tilde{f}$.
self.Ff = zeros(self.DFQf.shape, dtype=complex128)
# Initialize $rs$ grid.
self.rmin = self.smin + clip_left * ds
self.rmax = self.smax - clip_right * ds
R = linspace(self.rmin, self.rmax, W - clip_left - clip_right)
self.R, self.S = meshgrid(R, R)
# Compute $q$, $u$, $v$, $w$, and $v^{2}r*\csc(\phi)*{\Delta}r/s^2$.
self.Q = self.S / self.R
args = dict(q=self.Q, r=self.R, s=self.S, phi=self.Phi, dr=dr)
args["u"] = self.U = self._u(**args)
args["v"] = self.V = self._v(**args)
self.W = self._w(**args)
self.Factor = self._cf(**args)
def A(self, n, eps=0.0000001, p=16):
|
Compute matrix $\mathbf{A}_n$.
H, W = self.DFQf.shape
# Initialize the An matrix (as an array for now).
An = zeros(self.R.shape, dtype=complex128)
# First compute a partial sum for the upper triangular part.
# Start with $m=0$
mask = self.S < self.R
Sum = zeros(self.R.shape, dtype=complex128)
for m in xrange(0, p + 1, 2):
cm_rpn, dm_rpn = self._cd[m]
Term = self._tm(v=self.V[mask], v2=self.V[mask] ** 2,
dlnr=self.dr / self.R[mask],
n=n, n2=n ** 2, m=m, cm=cm_rpn, dm=dm_rpn)
Sum[mask] += Term
mask[mask] *= abs(Term) >= eps
if not mask.any():
break
mask = self.S < self.R
An[mask] = 2 * self.W[mask] ** n * self.Factor[mask] * Sum[mask]
# Now to do the diagonal.
# Since $r=s$ here, we have $q=1$, $u=\phi$, $v=-\tan\phi$,
# and $w=1$.
mask = self.S == self.R
Sum = zeros(self.R.shape, dtype=complex128)
for m in xrange(0, p + 1):
cm_rpn, dm_rpn = self._cd[m]
Term = self._tm(v=-tan(self.Phi), v2=tan(self.Phi) ** 2,
dlnr=self.dr / self.R[mask],
n=n, n2=n ** 2, m=m, cm=cm_rpn, dm=dm_rpn)
Sum[mask] += Term
mask[mask] *= abs(Term) >= eps
if not mask.any():
break
mask = self.S == self.R
An[mask] = self.Factor[mask] * Sum[mask] + \
array([1 - 1 / cos(self.Phi)] * W)
return npmatrix(An)
def f(self, n):
# This is the function that is run in parallel.
An = self.A(n, eps=10 ** -9, p=24)
DFQf = self.DFQf[n]
#AnInv = inv(An).transpose()
#Ff = array(DFQf*AnInv)[0]
Ff = solve(An, DFQf)
return Ff
def populatequeue(self, queue):
for n in xrange(self.nmax + 1):
queue.put(n)
def postproc(self, (n, Ff)):
with self.status:
self.Ff[n] = Ff
if n > 0:
self.Ff[-n] = Ff.conjugate()
self.jobsdone += 1
self.status.notifyAll()
def reconstruct(self):
with self.lock:
self.F = ifft(self.Ff, axis=0)
return self.F
|
#
|
identifier_name
|
polar.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from numpy import array, zeros, linspace, meshgrid, ndarray, diag
from numpy import uint8, float64, int8, int0, float128, complex128
from numpy import exp, sqrt, cos, tan, arctan
from numpy import minimum, maximum
from numpy import ceil, floor
from numpy import matrix as npmatrix
from numpy.fft import fft, ifft
from numpy import pi
from scipy.linalg import solve_triangular as solve
from scipy.signal import fftconvolve as conv
from scipy.ndimage import geometric_transform as transform
# We will make use of *reentrant* locks.
from threading import RLock as Lock
from threading import Condition, Thread
# This module is a modification on python's queue module,
# which allows one to interrupt a queue.
import iqueue
# This is a module written to execute code in parallel.
# While python is limited by the Global Interpreter Lock,
# numerical operations on NumPy arrays are generally not
# limited by the GIL.
import parallel
# This module allows the conversion of SAGE symbolic expressions
# to RPN code through the symbolic_to_rpn. RPNProgram is a subclass
# of list that comes equipped with a __call__ method that implements
# execution of the RPN code.
import rpncalc
def _E(m):
return int0(npmatrix(diag((1,) * int(m + 1), k=0)[:, :-1]))
def _X(m):
return int0(npmatrix(diag((1,) * int(m), k=-1)[:, :-1]))
def _Del(m):
return int0(npmatrix(diag(xrange(1, int(m)), k=1)[:-1]))
class _CD_RPN:
def __init__(self):
self.coeffs = [(npmatrix((-1,)), npmatrix((-1,)))]
self.rpn = [(rpncalc.RPNProgram([-1]), rpncalc.RPNProgram([-1]))]
# In case this class is utilized by multiple threads.
self.lock = Lock()
def getcoeffs(self, m):
# Returns coefficients for $c_{m}$ and $d_{m}$.
# If they already exist in cache, just return what is there.
with self.lock:
if len(self.coeffs) <= m:
# Need to generate coefficients for $c_{m}$ and $d_{m}$.
# Fetch the coefficients for $c_{m-1}$ and $d_{m-1}$.
C, D = self.getcoeffs(m - 1)
if m % 2: # $m$ is odd
C_new = _E(m) * D * _X((m + 1) / 2).transpose() \
- ((1 + m) * _E(m) + 3 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * C \
* _E((m + 1) / 2).transpose()
D_new = _X(m) * C - (m * _E(m) + 2 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * D
else: # $m$ is even
C_new = _E(m) * D * _X(m / 2).transpose() \
- ((1 + m) * _E(m) + 3 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * C
D_new = _X(m) * C - (m * _E(m) + 2 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * D \
* _E(m / 2).transpose()
self.coeffs.append((C_new, D_new))
return self.coeffs[m]
def __getitem__(self, m):
n2 = rpncalc.wild("n2")
v2 = rpncalc.wild("v2")
mul = rpncalc.rpn_funcs[u"⋅"]
add = rpncalc.rpn_funcs[u"+"]
# Returns RPN code for $c_j$ and $d_j$. Generate on the fly if needed.
with self.lock:
while len(self.rpn) <= m:
cm_rpn = []
dm_rpn = []
C, D = self.getcoeffs(len(self.rpn))
# Generate RPN code for $c_j$ and $d_j$.
for row in array(C[::-1]):
npoly_rpn = []
for coeff in row[::-1]:
if coeff:
if len(npoly_rpn):
npoly_rpn.extend([n2, mul])
npoly_rpn.extend([coeff, add])
else:
npoly_rpn.append(coeff)
elif len(npoly_rpn):
npoly_rpn.extend([n2, mul])
if len(cm_rpn):
cm_rpn.extend([v2, mul])
cm_rpn.extend(npoly_rpn)
cm_rpn.append(add)
else:
cm_rpn.extend(npoly_rpn)
for row in array(D[::-1]):
npoly_rpn = []
for coeff in row[::-1]:
if coeff:
if len(npoly_rpn):
npoly_rpn.extend([n2, mul])
npoly_rpn.extend([coeff, add])
else:
npoly_rpn.append(coeff)
elif len(npoly_rpn):
npoly_rpn.extend([n2, mul])
if len(dm_rpn):
dm_rpn.extend([v2, mul])
dm_rpn.extend(npoly_rpn)
dm_rpn.append(add)
else:
dm_rpn.extend(npoly_rpn)
self.rpn.append(
(rpncalc.RPNProgram(cm_rpn), rpncalc.RPNProgram(dm_rpn)))
return self.rpn[m]
class Sderiv:
def __init__(self, alpha):
self.alpha = alpha
def __call__(self, A, ds):
H, W = A.shape
psi = rpncalc.decode(u"« x 3 ^ 4 / +/- 3 x * 4 / + »")
N = ceil(self.alpha / ds)
X = linspace(-N * ds - ds, N * ds + ds, 2 * N + 3)
Psi = psi(x=X / self.alpha)
Psi[X > self.alpha] = psi(x=1)
Psi[X < -self.alpha] = psi(x=-1)
stencil = (Psi[:-2] + Psi[2:] - 2 * Psi[1:-1]) / ds
diff = conv([stencil], A)
return N, N, diff[:, 2 * N:-2 * N]
class PolarBrokenRayInversion(parallel.BaseTaskClass):
_cd = _CD_RPN()
_u = rpncalc.decode(u"« q phi sin ⋅ arcsin »")
_v = rpncalc.decode(u"« q phi sin ⋅ +/- q 2 ^ phi sin 2 ^ ⋅ +/- 1 + √ ÷ »")
_w = rpncalc.decode(u"« i phi u - ⋅ exp »")
_tm = rpncalc.decode(u"« i dm ⋅ n ⋅ cm v ⋅ + dlnr m ^ ⋅ m 2 + ! ÷ »")
_cf = rpncalc.decode(u"« dr r ⋅ v 2 ^ ⋅ phi csc ⋅ s 2 ^ ÷ »")
_invlock = Lock()
def __init__(self, Qf, Phi, smin, smax, alpha, nmax=200):
# Parameters:
# $\mathbf{Qf}$ -- $\mathcal{Q}f$, sampled on an $r\theta$ grid.
# $\mathbf{Phi}$ ($\phi$) -- Scattering angle
# $\mathbf{rmin}$ -- $r_{\min}$, defaults to $1$.
# $\mathbf{rmax}$ -- $r_{\max}$, defaults to $6$.
# $\mathbf{D}$ -- Numerical implemenation of $\frac{\partial}{\partial r}$.
# $\mathbf{nmax}$ -- $n_{\max}$, reconstructs $\tilde{f}\left(r,n\right)$
# for $\left|n\right| \le n_{\max}$. Defaults to $200$.
# This reconstruction will assume that $\mathcal{Q}f$ is real and exploit
# conjugate symmetry in the Fourier series.
# Initialize variables.
self.Qf = Qf
self.Phi = Phi
self.smin = smin
self.smax = smax
H, W = Qf.shape
self.thetamin = thetamin = -pi
self.thetamax = thetamax = pi*(1-2.0/H)
self.nmax = nmax
self.F = None
self.F_cartesian = None
self.lock = Lock()
self.status = Condition(self.lock)
self.jobsdone = 0
self.jobcount = nmax + 1
self.running = False
self.projectioncount = 0
self.projecting = False
self.dr = dr = ds = (smax - smin) / float(W - 1)
self.dtheta = dtheta = (thetamax - thetamin) / float(H)
# Compute $\widetilde{\mathcal{Q}f}$.
self.FQf = FQf = fft(Qf, axis=0)
# Perform differentiation of $\widetilde{\mathcal{Q}f}$.
D = Sderiv(alpha)
try:
clip_left, clip_right, self.DFQf = D(FQf, ds)
except:
clip_left, clip_right, self.DFQf = D(float64(FQf), ds)
# Initialize array that will store $\tilde{f}$.
self.Ff = zeros(self.DFQf.shape, dtype=complex128)
# Initialize $rs$ grid.
self.rmin = self.smin + clip_left * ds
self.rmax = self.smax - clip_right * ds
R = linspace(self.rmin, self.rmax, W - clip_left - clip_right)
self.R, self.S = meshgrid(R, R)
# Compute $q$, $u$, $v$, $w$, and $v^{2}r*\csc(\phi)*{\Delta}r/s^2$.
self.Q = self.S / self.R
args = dict(q=self.Q, r=self.R, s=self.S, phi=self.Phi, dr=dr)
args["u"] = self.U = self._u(**args)
args["v"] = self.V = self._v(**args)
self.W = self._w(**args)
self.Factor = self._cf(**args)
def A(self, n, eps=0.0000001, p=16):
# Compute matrix $\mathbf{A}_n$.
H, W = self.DFQf.shape
# Initialize the An matrix (as an array for now).
An = zeros(self.R.shape, dtype=complex128)
# First compute a partial sum for the upper triangular part.
# Start with $m=0$
mask = self.S < self.R
Sum = zeros(self.R.shape, dtype=complex128)
for m in xrange(0, p + 1, 2):
cm_rpn, dm_rpn = self._cd[m]
Term = self._tm(v=self.V[mask], v2=self.V[mask] ** 2,
dlnr=self.dr / self.R[mask],
n=n, n2=n ** 2, m=m, cm=cm_rpn, dm=dm_rpn)
Sum[mask] += Term
mask[mask] *= abs(Term) >= eps
if not mask.any():
break
mask = self.S < self.R
An[mask] = 2 * self.W[mask] ** n * self.Factor[mask] * Sum[mask]
# Now to do the diagonal.
# Since $r=s$ here, we have $q=1$, $u=\phi$, $v=-\tan\phi$,
# and $w=1$.
mask = self.S == self.R
Sum = zeros(self.R.shape, dtype=complex128)
for m in xrange(0, p + 1):
cm_rpn, dm_rpn = self._cd[m]
Term = self._tm(v=-tan(self.Phi), v2=tan(self.Phi) ** 2,
dlnr=self.dr / self.R[mask],
n=n, n2=n ** 2, m=m, cm=cm_rpn, dm=dm_rpn)
Sum[mask] += Term
mask[mask] *= abs(Term) >= eps
if not mask.any():
break
mask = self.S == self.R
An[mask] = self.Factor[mask] * Sum[mask] + \
array([1 - 1 / cos(self.Phi)] * W)
return npmatrix(An)
def f(self, n):
# This is the function that is run in parallel.
An = self.A(n, eps=10 ** -9, p=24)
DFQf = self.DFQf[n]
#AnInv = inv(An).transpose()
#Ff = array(DFQf*AnInv)[0]
Ff = solve(An, DFQf)
return Ff
def populatequeue(self, queue):
for n in xrange(self.nmax + 1):
queue.put(n)
def postproc(self, (n, Ff)):
with self.status:
self.Ff[n] = Ff
if n > 0:
self.Ff[-n] = Ff.conjugate()
self.jobsdone += 1
self.status.notifyAll()
def reconstruct(self):
with self.lock:
self.F = ifft
|
(self.Ff, axis=0)
return self.F
|
identifier_body
|
|
polar.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from numpy import array, zeros, linspace, meshgrid, ndarray, diag
from numpy import uint8, float64, int8, int0, float128, complex128
from numpy import exp, sqrt, cos, tan, arctan
from numpy import minimum, maximum
from numpy import ceil, floor
from numpy import matrix as npmatrix
from numpy.fft import fft, ifft
from numpy import pi
from scipy.linalg import solve_triangular as solve
from scipy.signal import fftconvolve as conv
from scipy.ndimage import geometric_transform as transform
# We will make use of *reentrant* locks.
from threading import RLock as Lock
from threading import Condition, Thread
# This module is a modification on python's queue module,
# which allows one to interrupt a queue.
import iqueue
# This is a module written to execute code in parallel.
# While python is limited by the Global Interpreter Lock,
# numerical operations on NumPy arrays are generally not
# limited by the GIL.
import parallel
# This module allows the conversion of SAGE symbolic expressions
# to RPN code through the symbolic_to_rpn. RPNProgram is a subclass
# of list that comes equipped with a __call__ method that implements
# execution of the RPN code.
import rpncalc
def _E(m):
return int0(npmatrix(diag((1,) * int(m + 1), k=0)[:, :-1]))
def _X(m):
return int0(npmatrix(diag((1,) * int(m), k=-1)[:, :-1]))
def _Del(m):
return int0(npmatrix(diag(xrange(1, int(m)), k=1)[:-1]))
class _CD_RPN:
def __init__(self):
self.coeffs = [(npmatrix((-1,)), npmatrix((-1,)))]
self.rpn = [(rpncalc.RPNProgram([-1]), rpncalc.RPNProgram([-1]))]
# In case this class is utilized by multiple threads.
self.lock = Lock()
def getcoeffs(self, m):
# Returns coefficients for $c_{m}$ and $d_{m}$.
# If they already exist in cache, just return what is there.
with self.lock:
if len(self.coeffs) <= m:
# Need to generate coefficients for $c_{m}$ and $d_{m}$.
# Fetch the coefficients for $c_{m-1}$ and $d_{m-1}$.
C, D = self.getcoeffs(m - 1)
if m % 2: # $m$ is odd
C_new = _E(m) * D * _X((m + 1) / 2).transpose() \
- ((1 + m) * _E(m) + 3 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * C \
* _E((m + 1) / 2).transpose()
D_new = _X(m) * C - (m * _E(m) + 2 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * D
else: # $m$ is even
C_new = _E(m) * D * _X(m / 2).transpose() \
- ((1 + m) * _E(m) + 3 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * C
D_new = _X(m) * C - (m * _E(m) + 2 * _X(m)
+ 2 * (_E(m) + _X(m)) * _X(m - 1) * _Del(m)) * D \
* _E(m / 2).transpose()
self.coeffs.append((C_new, D_new))
return self.coeffs[m]
def __getitem__(self, m):
n2 = rpncalc.wild("n2")
v2 = rpncalc.wild("v2")
mul = rpncalc.rpn_funcs[u"⋅"]
add = rpncalc.rpn_funcs[u"+"]
# Returns RPN code for $c_j$ and $d_j$. Generate on the fly if needed.
with self.lock:
while len(self.rpn) <= m:
cm_rpn = []
dm_rpn = []
C, D = self.getcoeffs(len(self.rpn))
# Generate RPN code for $c_j$ and $d_j$.
for row in array(C[::-1]):
npoly_rpn = []
for coeff in row[::-1]:
if coeff:
if len(npoly_rpn):
npoly_rpn.extend([n2, mul])
npoly_rpn.extend([coeff, add])
else:
npoly_rpn.append(coeff)
elif len(npoly_rpn):
npoly_rpn.extend([n2, mul])
if len(cm_rpn):
cm_rpn.extend([v2, mul])
cm_rpn.extend(npoly_rpn)
cm_rpn.append(add)
else:
cm_rpn.extend(npoly_rpn)
for row in array(D[::-1]):
npoly_rpn = []
for coeff in row[::-1]:
if coeff:
if len(npoly_rpn):
npoly_rpn.extend([n2, mul])
npoly_rpn.extend([coeff, add])
else:
npoly_rpn.append(coeff)
|
dm_rpn.extend(npoly_rpn)
dm_rpn.append(add)
else:
dm_rpn.extend(npoly_rpn)
self.rpn.append(
(rpncalc.RPNProgram(cm_rpn), rpncalc.RPNProgram(dm_rpn)))
return self.rpn[m]
class Sderiv:
def __init__(self, alpha):
self.alpha = alpha
def __call__(self, A, ds):
H, W = A.shape
psi = rpncalc.decode(u"« x 3 ^ 4 / +/- 3 x * 4 / + »")
N = ceil(self.alpha / ds)
X = linspace(-N * ds - ds, N * ds + ds, 2 * N + 3)
Psi = psi(x=X / self.alpha)
Psi[X > self.alpha] = psi(x=1)
Psi[X < -self.alpha] = psi(x=-1)
stencil = (Psi[:-2] + Psi[2:] - 2 * Psi[1:-1]) / ds
diff = conv([stencil], A)
return N, N, diff[:, 2 * N:-2 * N]
class PolarBrokenRayInversion(parallel.BaseTaskClass):
_cd = _CD_RPN()
_u = rpncalc.decode(u"« q phi sin ⋅ arcsin »")
_v = rpncalc.decode(u"« q phi sin ⋅ +/- q 2 ^ phi sin 2 ^ ⋅ +/- 1 + √ ÷ »")
_w = rpncalc.decode(u"« i phi u - ⋅ exp »")
_tm = rpncalc.decode(u"« i dm ⋅ n ⋅ cm v ⋅ + dlnr m ^ ⋅ m 2 + ! ÷ »")
_cf = rpncalc.decode(u"« dr r ⋅ v 2 ^ ⋅ phi csc ⋅ s 2 ^ ÷ »")
_invlock = Lock()
def __init__(self, Qf, Phi, smin, smax, alpha, nmax=200):
# Parameters:
# $\mathbf{Qf}$ -- $\mathcal{Q}f$, sampled on an $r\theta$ grid.
# $\mathbf{Phi}$ ($\phi$) -- Scattering angle
# $\mathbf{rmin}$ -- $r_{\min}$, defaults to $1$.
# $\mathbf{rmax}$ -- $r_{\max}$, defaults to $6$.
# $\mathbf{D}$ -- Numerical implemenation of $\frac{\partial}{\partial r}$.
# $\mathbf{nmax}$ -- $n_{\max}$, reconstructs $\tilde{f}\left(r,n\right)$
# for $\left|n\right| \le n_{\max}$. Defaults to $200$.
# This reconstruction will assume that $\mathcal{Q}f$ is real and exploit
# conjugate symmetry in the Fourier series.
# Initialize variables.
self.Qf = Qf
self.Phi = Phi
self.smin = smin
self.smax = smax
H, W = Qf.shape
self.thetamin = thetamin = -pi
self.thetamax = thetamax = pi*(1-2.0/H)
self.nmax = nmax
self.F = None
self.F_cartesian = None
self.lock = Lock()
self.status = Condition(self.lock)
self.jobsdone = 0
self.jobcount = nmax + 1
self.running = False
self.projectioncount = 0
self.projecting = False
self.dr = dr = ds = (smax - smin) / float(W - 1)
self.dtheta = dtheta = (thetamax - thetamin) / float(H)
# Compute $\widetilde{\mathcal{Q}f}$.
self.FQf = FQf = fft(Qf, axis=0)
# Perform differentiation of $\widetilde{\mathcal{Q}f}$.
D = Sderiv(alpha)
try:
clip_left, clip_right, self.DFQf = D(FQf, ds)
except:
clip_left, clip_right, self.DFQf = D(float64(FQf), ds)
# Initialize array that will store $\tilde{f}$.
self.Ff = zeros(self.DFQf.shape, dtype=complex128)
# Initialize $rs$ grid.
self.rmin = self.smin + clip_left * ds
self.rmax = self.smax - clip_right * ds
R = linspace(self.rmin, self.rmax, W - clip_left - clip_right)
self.R, self.S = meshgrid(R, R)
# Compute $q$, $u$, $v$, $w$, and $v^{2}r*\csc(\phi)*{\Delta}r/s^2$.
self.Q = self.S / self.R
args = dict(q=self.Q, r=self.R, s=self.S, phi=self.Phi, dr=dr)
args["u"] = self.U = self._u(**args)
args["v"] = self.V = self._v(**args)
self.W = self._w(**args)
self.Factor = self._cf(**args)
def A(self, n, eps=0.0000001, p=16):
# Compute matrix $\mathbf{A}_n$.
H, W = self.DFQf.shape
# Initialize the An matrix (as an array for now).
An = zeros(self.R.shape, dtype=complex128)
# First compute a partial sum for the upper triangular part.
# Start with $m=0$
mask = self.S < self.R
Sum = zeros(self.R.shape, dtype=complex128)
for m in xrange(0, p + 1, 2):
cm_rpn, dm_rpn = self._cd[m]
Term = self._tm(v=self.V[mask], v2=self.V[mask] ** 2,
dlnr=self.dr / self.R[mask],
n=n, n2=n ** 2, m=m, cm=cm_rpn, dm=dm_rpn)
Sum[mask] += Term
mask[mask] *= abs(Term) >= eps
if not mask.any():
break
mask = self.S < self.R
An[mask] = 2 * self.W[mask] ** n * self.Factor[mask] * Sum[mask]
# Now to do the diagonal.
# Since $r=s$ here, we have $q=1$, $u=\phi$, $v=-\tan\phi$,
# and $w=1$.
mask = self.S == self.R
Sum = zeros(self.R.shape, dtype=complex128)
for m in xrange(0, p + 1):
cm_rpn, dm_rpn = self._cd[m]
Term = self._tm(v=-tan(self.Phi), v2=tan(self.Phi) ** 2,
dlnr=self.dr / self.R[mask],
n=n, n2=n ** 2, m=m, cm=cm_rpn, dm=dm_rpn)
Sum[mask] += Term
mask[mask] *= abs(Term) >= eps
if not mask.any():
break
mask = self.S == self.R
An[mask] = self.Factor[mask] * Sum[mask] + \
array([1 - 1 / cos(self.Phi)] * W)
return npmatrix(An)
def f(self, n):
# This is the function that is run in parallel.
An = self.A(n, eps=10 ** -9, p=24)
DFQf = self.DFQf[n]
#AnInv = inv(An).transpose()
#Ff = array(DFQf*AnInv)[0]
Ff = solve(An, DFQf)
return Ff
def populatequeue(self, queue):
for n in xrange(self.nmax + 1):
queue.put(n)
def postproc(self, (n, Ff)):
with self.status:
self.Ff[n] = Ff
if n > 0:
self.Ff[-n] = Ff.conjugate()
self.jobsdone += 1
self.status.notifyAll()
def reconstruct(self):
with self.lock:
self.F = ifft(self.Ff, axis=0)
return self.F
|
elif len(npoly_rpn):
npoly_rpn.extend([n2, mul])
if len(dm_rpn):
dm_rpn.extend([v2, mul])
|
random_line_split
|
tableButton.js
|
//ButtonTable is a very very special case, because I am still not sure why it is a table :-)
// alternate design is to make it a field. Filed looks more logical, but table is more convenient at this time.
// we will review this design later and decide, meanwhile here is the ButtonPane table that DOES NOT inherit from AbstractTable
//button field is only a data structure that is stored under buttons collection
var ButtonField = function (nam, label, actionName)
{
this.name = nam;
this.label = label;
this.actionName = actionName;
};
var ButtonPanel = function ()
{
this.name = null;
this.P2 = null;
this.renderingOption = null;
this.buttons = new Object(); //collection of buttonFields
};
ButtonPanel.prototype.setData = function (dc)
{
var data = dc.grids[this.name];
if (data.length <= 1)
{
if (this.renderingOption == 'nextToEachOther')
{
this.P2.hideOrShowPanels([this.name], 'none');
}
else
{
var listName = this.name + 'ButtonList';
var buttonList = this.P2.doc.getElementById(listName);
//should we do the following or just say buttonList.innerHTML = ''
while (buttonList.options.length)
{
buttonList.remove(0);
}
}
return;
}
data = this.transposeIfRequired(data);
//possible that it was hidden earlier.. Let us show it first
this.P2.hideOrShowPanels([this.name], '');
if (this.renderingOption == 'nextToEachOther')
this.enableButtons(data);
else
this.buildDropDown(data);
};
//enable/disable buttons in a button panel based on data received from server
ButtonPanel.prototype.enableButtons = function (data)
{
var doc = this.P2.doc;
var n = data.length;
|
//for convenience, get the buttons into a collection indexed by name
var btnsToEnable = {};
for (var i = 1; i < n; i++)
{
var row = data[i];
if (hasFlag)
{
var flag = row[1];
if (!flag || flag == '0')
continue;
}
btnsToEnable[row[0]] = true;
}
//now let us go thru each button, and hide or who it
for (var btnName in this.buttons)
{
var ele = doc.getElementById(btnName);
if (!ele)
{
debug('Design Error: Button panel ' + this.name + ' has not produced a DOM element with name ' + btnName);
continue;
}
ele.style.display = btnsToEnable[btnName] ? '' : 'none';
}
};
ButtonPanel.prototype.buildDropDown = function (data)
{
var flag;
var doc = this.P2.doc;
var ele = doc.getElementById(this.name + 'ButtonList');
if (!ele)
{
debug('DESIGN ERROR: Button Panel ' + this.name + ' has not produced a drop-down boc with name = ' + this.Name + 'ButtonList');
return;
}
//zap options first
ele.innerHTML = '';
//that took away the first one also. Add a blank option
var option = doc.createElement('option');
ele.appendChild(option);
//this.buttons has all the button names defined for this panel with value = 'disabled'
// i.e. this.buttons['button1'] = 'disabled';
// for the rows that are in data, mark them as enabled.
var n = data.length;
if (n <= 1) return;
if ((n == 2) && (data[0].length > 1))
{
var hasFlag = data[0].length > 1;
for (var i = 0; i < data[0].length; i++)
{
if (hasFlag)
{
flag = data[1][i];
if (!flag || flag == '0')
continue;
}
var btnName = data[0][i];
var btn = this.buttons[btnName];
if (!btn)
{
debug('Button Panel ' + this.name + ' is not defined with a button with name ' + btnName + ' but server is trying to enable this button');
continue;
}
option = doc.createElement('option');
option.value = btn.actionName;
option.innerHTML = btn.label;
ele.appendChild(option);
}
}
else
{
var hasFlag = data[0].length > 1;
for (var i = 1; i < n; i++)
{
if (hasFlag)
{
flag = data[i][1];
if (!flag || flag == '0')
continue;
}
var btnName = data[i][0];
var btn = this.buttons[btnName];
if (!btn)
{
debug('Button Panel ' + this.name + ' is not defined with a button with name ' + btnName + ' but server is trying to enable this button');
continue;
}
option = doc.createElement('option');
option.value = btn.actionName;
option.innerHTML = btn.label;
ele.appendChild(option);
}
}
};
//Standard way of getting data from server is a grid with first row as header row and rest a data rows.
//But it is possible that server may send button names in first row, and optional second row as enable flag.
//We detect the second case, and transpose the grid, so that a common logic can be used.
ButtonPanel.prototype.transposeIfRequired = function (data)
{
//we need to transpose only if we have one or two rows
var nbrRows = data && data.length;
if (!nbrRows || nbrRows > 2)
return data;
var row = data[0];
var nbrCols = row.length;
if (!nbrCols)
return data;
//We make a simple assumption, that the label for last column can not clash with the name of a button.
if (!this.buttons[row[nbrCols - 1]])
return data;
//we transpose the grid, with an empty header row
var newData = null;
if (data.length == 1) //button name only
{
newData = [['']];
for (var i = 0; i < nbrCols; i++)
newData.push([row[i]]);
}
else
{
//button name with enable flag
newData = [['', '']];
var row1 = data[1];
for (var i = 0; i < nbrCols; i++)
newData.push([row[i], row1[i]]);
}
return newData;
};
|
if (n <= 1) return;
//if the table has its second column, it is interpreted as Yes/No for enable. 0 or empty string is No, everything else is Yes
var hasFlag = data[0].length > 1;
|
random_line_split
|
insc.py
|
# coding: utf-8
if DefLANG in ("RU", "UA"):
AnsBase_temp = tuple([line.decode("utf-8") for line in (
"\nВсего входов - %d\nВремя последнего входа - %s\nПоследняя роль - %s", # 0
"\nВремя последнего выхода - %s\nПричина выхода - %s", # 1
"\nНики: %s", # 2
"Нет статистики.", # 3
"«%s» сидит здесь - %s.", # 4
"Ты провёл здесь - %s.", # 5
"Здесь нет такого юзера." # 6
)])
else:
AnsBase_temp = (
"\nTotal joins - %d\nThe Last join-time - %s\nThe last role - %s", # 0
"\nThe last leave-time - %s\nExit reason - %s",
|
# 1
"\nNicks: %s", # 2
"No statistics.", # 3
"'%s' spent here - %s.", # 4
"You spent here - %s.", # 5
"No such user here." # 6
)
|
conditional_block
|
|
insc.py
|
# coding: utf-8
if DefLANG in ("RU", "UA"):
AnsBase_temp = tuple([line.decode("utf-8") for line in (
"\nВсего входов - %d\nВремя последнего входа - %s\nПоследняя роль - %s", # 0
"\nВремя последнего выхода - %s\nПричина выхода - %s", # 1
"\nНики: %s", # 2
"Нет статистики.", # 3
"«%s» сидит здесь - %s.", # 4
"Ты провёл здесь - %s.", # 5
|
"Здесь нет такого юзера." # 6
)])
else:
AnsBase_temp = (
"\nTotal joins - %d\nThe Last join-time - %s\nThe last role - %s", # 0
"\nThe last leave-time - %s\nExit reason - %s", # 1
"\nNicks: %s", # 2
"No statistics.", # 3
"'%s' spent here - %s.", # 4
"You spent here - %s.", # 5
"No such user here." # 6
)
|
random_line_split
|
|
legacy_test_runner.ts
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../core/common/common-legacy.js';
import '../models/text_utils/text_utils-legacy.js';
import '../core/host/host-legacy.js';
import '../core/protocol_client/protocol_client-legacy.js';
import '../ui/legacy/legacy-legacy.js';
import '../models/workspace/workspace-legacy.js';
import '../models/bindings/bindings-legacy.js';
import '../ui/legacy/components/utils/utils-legacy.js';
import '../models/persistence/persistence-legacy.js';
import '../models/extensions/extensions-legacy.js';
import '../entrypoints/devtools_app/devtools_app.js';
import '../panels/accessibility/accessibility-legacy.js';
import '../panels/animation/animation-legacy.js';
import '../models/bindings/bindings-legacy.js';
import '../ui/legacy/components/color_picker/color_picker-legacy.js';
import '../core/common/common-legacy.js';
import '../ui/legacy/components/data_grid/data_grid-legacy.js';
import '../third_party/diff/diff-legacy.js';
import '../models/extensions/extensions-legacy.js';
import '../models/formatter/formatter-legacy.js';
import '../ui/legacy/components/inline_editor/inline_editor-legacy.js';
import '../core/root/root-legacy.js';
import '../core/sdk/sdk-legacy.js';
import './test_runner/test_runner.js';
// @ts-ignore
if (self.testRunner)
|
{
// @ts-ignore
testRunner.dumpAsText();
// @ts-ignore
testRunner.waitUntilDone();
}
|
conditional_block
|
|
legacy_test_runner.ts
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../core/common/common-legacy.js';
import '../models/text_utils/text_utils-legacy.js';
import '../core/host/host-legacy.js';
import '../core/protocol_client/protocol_client-legacy.js';
import '../ui/legacy/legacy-legacy.js';
import '../models/workspace/workspace-legacy.js';
import '../models/bindings/bindings-legacy.js';
import '../ui/legacy/components/utils/utils-legacy.js';
import '../models/persistence/persistence-legacy.js';
import '../models/extensions/extensions-legacy.js';
import '../entrypoints/devtools_app/devtools_app.js';
import '../panels/accessibility/accessibility-legacy.js';
import '../panels/animation/animation-legacy.js';
import '../models/bindings/bindings-legacy.js';
import '../ui/legacy/components/color_picker/color_picker-legacy.js';
import '../core/common/common-legacy.js';
|
import '../ui/legacy/components/inline_editor/inline_editor-legacy.js';
import '../core/root/root-legacy.js';
import '../core/sdk/sdk-legacy.js';
import './test_runner/test_runner.js';
// @ts-ignore
if (self.testRunner) {
// @ts-ignore
testRunner.dumpAsText();
// @ts-ignore
testRunner.waitUntilDone();
}
|
import '../ui/legacy/components/data_grid/data_grid-legacy.js';
import '../third_party/diff/diff-legacy.js';
import '../models/extensions/extensions-legacy.js';
import '../models/formatter/formatter-legacy.js';
|
random_line_split
|
type_infer.rs
|
/*
类型推导引擎不仅仅在初始化期间分析右值的类型,
还会通过分析变量在后面是 怎么使用的来推导该变量的类型
*/
fn main() {
// 借助类型标注,编译器知道 `elem` 具有 u8 类型
let elem = 5u8;
// 创建一个空 vector(可增长数组)。
let m
|
ut vec = Vec::new();
// 此时编译器并未知道 `vec` 的确切类型,它只知道 `vec` 是一个含有某种类型
// 的 vector(`Vec<_>`)。
// 将 `elem` 插入 vector。
vec.push(elem);
// Aha!现在编译器就知道了 `vec` 是一个含有 `u8` 类型的 vector(`Vec<u8>`)
// 试一试 ^ 尝试将 `vec.push(elem)` 那行注释掉
println!("{:?}", vec);
}
|
identifier_body
|
|
type_infer.rs
|
/*
类型推导引擎不仅仅在初始化期间分析右值的类型,
还会通过分析变量在后面是 怎么使用的来推导该变量的类型
*/
fn main() {
// 借助类型标注,编译器知道 `elem` 具有 u8 类型
let elem = 5u8;
// 创建一个空 vector(可增长数组)。
|
t mut vec = Vec::new();
// 此时编译器并未知道 `vec` 的确切类型,它只知道 `vec` 是一个含有某种类型
// 的 vector(`Vec<_>`)。
// 将 `elem` 插入 vector。
vec.push(elem);
// Aha!现在编译器就知道了 `vec` 是一个含有 `u8` 类型的 vector(`Vec<u8>`)
// 试一试 ^ 尝试将 `vec.push(elem)` 那行注释掉
println!("{:?}", vec);
}
|
le
|
identifier_name
|
type_infer.rs
|
/*
类型推导引擎不仅仅在初始化期间分析右值的类型,
还会通过分析变量在后面是 怎么使用的来推导该变量的类型
|
// 创建一个空 vector(可增长数组)。
let mut vec = Vec::new();
// 此时编译器并未知道 `vec` 的确切类型,它只知道 `vec` 是一个含有某种类型
// 的 vector(`Vec<_>`)。
// 将 `elem` 插入 vector。
vec.push(elem);
// Aha!现在编译器就知道了 `vec` 是一个含有 `u8` 类型的 vector(`Vec<u8>`)
// 试一试 ^ 尝试将 `vec.push(elem)` 那行注释掉
println!("{:?}", vec);
}
|
*/
fn main() {
// 借助类型标注,编译器知道 `elem` 具有 u8 类型
let elem = 5u8;
|
random_line_split
|
entity.py
|
##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business involves the administration of students, teachers,
# courses, programs and so on.
#
# Copyright (C) 2015-2019 Université catholique de Louvain (http://www.uclouvain.be)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
##############################################################################
import django_filters
from django.forms import TextInput
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from base.models.entity_version import EntityVersion
class EntityVersionFilter(django_filters.FilterSet):
acronym = django_filters.CharFilter(
lookup_expr='icontains', label=_("Acronym"),
widget=TextInput(attrs={'style': "text-transform:uppercase"})
)
title = django_filters.CharFilter(lookup_expr='icontains', label=_("Title"), )
class Meta:
model = EntityVersion
fields = ["entity_type"]
class EntityListSerializer(serializers.Serializer):
acronym = serializers.CharField()
title = serializers.CharField()
entity_type = serializers.CharField()
# Display human readable value
entity_type_text = serializers.CharField(source='get_entity_type_display', read_only=True)
organization = serializers.SerializerMethodField()
select_url = serializers.SerializerMethodField()
def get_organization(self, obj):
return str(obj.entity.organization)
def g
|
self, obj):
return reverse(
"entity_read",
kwargs={'entity_version_id': obj.id}
)
|
et_select_url(
|
identifier_name
|
entity.py
|
##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business involves the administration of students, teachers,
# courses, programs and so on.
#
# Copyright (C) 2015-2019 Université catholique de Louvain (http://www.uclouvain.be)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
##############################################################################
import django_filters
from django.forms import TextInput
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from base.models.entity_version import EntityVersion
class EntityVersionFilter(django_filters.FilterSet):
acronym = django_filters.CharFilter(
lookup_expr='icontains', label=_("Acronym"),
widget=TextInput(attrs={'style': "text-transform:uppercase"})
)
title = django_filters.CharFilter(lookup_expr='icontains', label=_("Title"), )
class Meta:
model = EntityVersion
fields = ["entity_type"]
class EntityListSerializer(serializers.Serializer):
acronym = serializers.CharField()
title = serializers.CharField()
entity_type = serializers.CharField()
# Display human readable value
entity_type_text = serializers.CharField(source='get_entity_type_display', read_only=True)
organization = serializers.SerializerMethodField()
select_url = serializers.SerializerMethodField()
def get_organization(self, obj):
return str(obj.entity.organization)
def get_select_url(self, obj):
r
|
eturn reverse(
"entity_read",
kwargs={'entity_version_id': obj.id}
)
|
identifier_body
|
|
entity.py
|
##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business involves the administration of students, teachers,
# courses, programs and so on.
#
# Copyright (C) 2015-2019 Université catholique de Louvain (http://www.uclouvain.be)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
##############################################################################
import django_filters
from django.forms import TextInput
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from base.models.entity_version import EntityVersion
|
acronym = django_filters.CharFilter(
lookup_expr='icontains', label=_("Acronym"),
widget=TextInput(attrs={'style': "text-transform:uppercase"})
)
title = django_filters.CharFilter(lookup_expr='icontains', label=_("Title"), )
class Meta:
model = EntityVersion
fields = ["entity_type"]
class EntityListSerializer(serializers.Serializer):
acronym = serializers.CharField()
title = serializers.CharField()
entity_type = serializers.CharField()
# Display human readable value
entity_type_text = serializers.CharField(source='get_entity_type_display', read_only=True)
organization = serializers.SerializerMethodField()
select_url = serializers.SerializerMethodField()
def get_organization(self, obj):
return str(obj.entity.organization)
def get_select_url(self, obj):
return reverse(
"entity_read",
kwargs={'entity_version_id': obj.id}
)
|
class EntityVersionFilter(django_filters.FilterSet):
|
random_line_split
|
a4.rs
|
fn main() { // Declaración de vectores o arrays
let vector1 = vec!["primer lemento","segundo elemento","tercer elemento"] ; // Se utiliza "vec!" para declarar una apuntador de variable como vector.
let mut vector2: Vec<&str> = Vec::new(); // Declaración de un vector vacío con el tipo de elementos que va a contener, en este caso cadenas de texto y se deja mutable para poder agregar elementos.
|
println!("primer elemento vector 1: {} y tercer elemento vector 2: {}", vector1[0], vector2[2]); // También se puede consultar el índice de uno de los elementos del vector usando "[X]" junto al nombre del vecto, dónde X es el número de la posición del elemento.
}
|
vector2 = vec!["Primero","Segundo"]; // Se agregan elementos al vector sobreescribiendolo gracias a "mut".
vector2.push("Tercero"); // Agrega un elemento al final del vector.
println!("primer vector 1: {:?} y segundo vector: {:?}", vector1, vector2); // Forma de ver en consola un vector no olvidar el ":?" entre los corchetes para que se imprima de lo contraria genera error.
|
random_line_split
|
a4.rs
|
fn main()
|
{ // Declaración de vectores o arrays
let vector1 = vec!["primer lemento","segundo elemento","tercer elemento"] ; // Se utiliza "vec!" para declarar una apuntador de variable como vector.
let mut vector2: Vec<&str> = Vec::new(); // Declaración de un vector vacío con el tipo de elementos que va a contener, en este caso cadenas de texto y se deja mutable para poder agregar elementos.
vector2 = vec!["Primero","Segundo"]; // Se agregan elementos al vector sobreescribiendolo gracias a "mut".
vector2.push("Tercero"); // Agrega un elemento al final del vector.
println!("primer vector 1: {:?} y segundo vector: {:?}", vector1, vector2); // Forma de ver en consola un vector no olvidar el ":?" entre los corchetes para que se imprima de lo contraria genera error.
println!("primer elemento vector 1: {} y tercer elemento vector 2: {}", vector1[0], vector2[2]); // También se puede consultar el índice de uno de los elementos del vector usando "[X]" junto al nombre del vecto, dónde X es el número de la posición del elemento.
}
|
identifier_body
|
|
a4.rs
|
fn
|
() { // Declaración de vectores o arrays
let vector1 = vec!["primer lemento","segundo elemento","tercer elemento"] ; // Se utiliza "vec!" para declarar una apuntador de variable como vector.
let mut vector2: Vec<&str> = Vec::new(); // Declaración de un vector vacío con el tipo de elementos que va a contener, en este caso cadenas de texto y se deja mutable para poder agregar elementos.
vector2 = vec!["Primero","Segundo"]; // Se agregan elementos al vector sobreescribiendolo gracias a "mut".
vector2.push("Tercero"); // Agrega un elemento al final del vector.
println!("primer vector 1: {:?} y segundo vector: {:?}", vector1, vector2); // Forma de ver en consola un vector no olvidar el ":?" entre los corchetes para que se imprima de lo contraria genera error.
println!("primer elemento vector 1: {} y tercer elemento vector 2: {}", vector1[0], vector2[2]); // También se puede consultar el índice de uno de los elementos del vector usando "[X]" junto al nombre del vecto, dónde X es el número de la posición del elemento.
}
|
main
|
identifier_name
|
DIAMOND_results_filter.py
|
#!/usr/lib/python2.7
##########################################################################
#
# Copyright (C) 2015-2016 Sam Westreich
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation;
#
# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##########################################################################
#
# DIAMOND_results_filter.py
# Created 1/30/17, this version updated 5/22/17
# Sam Westreich, [email protected], github.com/transcript
#
# Purpose: This takes a DIAMOND outfile and the RefSeq database and pulls
# out hits to any specific organism, identifying the raw input reads that
# were mapped to that organism.
# Usage:
#
# -I infile specifies the infile (a DIAMOND results file
# in m8 format)
# -SO specific target the organism search term, either genus,
# species, or function.
# -D database file specifies a reference database to search
# against for results
# -O outfile name optional; changes the default outfile name
#
##########################################################################
# imports
import operator, sys, time, gzip, re
# String searching function:
def string_find(usage_term):
for idx, elem in enumerate(sys.argv):
this_elem = elem
next_elem = sys.argv[(idx + 1) % len(sys.argv)]
if elem == usage_term:
return next_elem
# loading starting file
if "-I" in sys.argv:
infile_name = string_find("-I")
else:
sys.exit ("WARNING: infile must be specified using '-I' flag.")
# optional outfile of specific organism results
if "-SO" in sys.argv:
target_org = string_find("-SO")
if '"' in target_org:
for idx, elem in enumerate(sys.argv):
this_elem = elem
next_elem = sys.argv[(idx + 1) % len(sys.argv)]
second_elem = sys.argv[(idx + 2) % len(sys.argv)]
if elem == "-SO":
target_org = next_elem + " " + second_elem
if "-O" in sys.argv:
target_org_outfile = open(string_find("-O"), "w")
else:
target_org_outfile = open(infile_name[:-4] + "_" + target_org + ".tsv", "w")
else:
sys.exit("Need to specify target organism or function to filter by, using -SO flag.")
# loading database file
if "-D" in sys.argv:
db = open(string_find("-D"), "r")
else:
sys.exit("WARNING: database must be specified using '-D' flag.")
# Getting the database assembled
db_org_dictionary = {}
db_id_dictionary = {}
db_line_counter = 0
db_error_counter = 0
t0 = time.time()
for line in db:
if line.startswith(">") == True:
db_line_counter += 1
# line counter to show progress
if db_line_counter % 1000000 == 0: # each million
t95 = time.time()
print (str(db_line_counter) + " lines processed so far in " + str(t95-t0) + " seconds.")
if target_org in line:
splitline = line.split(" ")
# ID, the hit returned in DIAMOND results
db_id = str(splitline[0])[1:].split(" ")[0]
# name and functional description
db_entry = line.split("[", 1)
db_entry = db_entry[0].split(" ", 1)
db_entry = db_entry[1][:-1]
# organism name
if line.count("[") != 1:
|
else:
db_org = line.split("[", 1)
db_org = db_org[1].split()
try:
db_org = str(db_org[0]) + " " + str(db_org[1])
except IndexError:
db_org = line.strip().split("[", 1)
db_org = db_org[1][:-1]
db_error_counter += 1
db_org = re.sub('[^a-zA-Z0-9-_*. ]', '', db_org)
# add to dictionaries
db_org_dictionary[db_id] = db_org
db_id_dictionary[db_id] = db_entry
db.close()
print ("Database is read and set up, moving on to the infile...")
infile = open (infile_name, "r")
# setting up databases
RefSeq_hit_count_db = {}
unique_seq_db = {}
line_counter = 0
hit_counter = 0
t1 = time.time()
# reading through the infile
for line in infile:
line_counter += 1
splitline = line.split("\t")
try:
target_org_outfile.write(splitline[0] + "\t" + splitline[1] + "\t" + db_org_dictionary[splitline[1]] + "\t" + db_id_dictionary[splitline[1]] + "\n")
hit_counter += 1
except KeyError:
continue
if line_counter % 1000000 == 0:
t99 = time.time()
print (str(line_counter)[:-6] + "M lines processed so far in " + str(t99-t1) + " seconds.")
# results stats
t100 = time.time()
print ("Run complete!")
print ("Number of sequences found matching target query, " + target_org + ":\t" + str(hit_counter))
print ("Time elapsed: " + str(t100-t0) + " seconds.")
infile.close()
target_org_outfile.close()
|
splitline = line.split("[")
db_org = splitline[line.count("[")].strip()[:-1]
if db_org[0].isdigit():
split_db_org = db_org.split()
try:
db_org = split_db_org[1] + " " + split_db_org[2]
except IndexError:
try:
db_org = split_db_org[1]
except IndexError:
db_org = splitline[line.count("[")-1]
if db_org[0].isdigit():
split_db_org = db_org.split()
db_org = split_db_org[1] + " " + split_db_org[2]
|
conditional_block
|
DIAMOND_results_filter.py
|
#!/usr/lib/python2.7
##########################################################################
#
# Copyright (C) 2015-2016 Sam Westreich
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation;
#
# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##########################################################################
#
# DIAMOND_results_filter.py
# Created 1/30/17, this version updated 5/22/17
# Sam Westreich, [email protected], github.com/transcript
#
# Purpose: This takes a DIAMOND outfile and the RefSeq database and pulls
# out hits to any specific organism, identifying the raw input reads that
# were mapped to that organism.
# Usage:
#
# -I infile specifies the infile (a DIAMOND results file
# in m8 format)
# -SO specific target the organism search term, either genus,
# species, or function.
# -D database file specifies a reference database to search
# against for results
# -O outfile name optional; changes the default outfile name
#
##########################################################################
# imports
import operator, sys, time, gzip, re
# String searching function:
def
|
(usage_term):
for idx, elem in enumerate(sys.argv):
this_elem = elem
next_elem = sys.argv[(idx + 1) % len(sys.argv)]
if elem == usage_term:
return next_elem
# loading starting file
if "-I" in sys.argv:
infile_name = string_find("-I")
else:
sys.exit ("WARNING: infile must be specified using '-I' flag.")
# optional outfile of specific organism results
if "-SO" in sys.argv:
target_org = string_find("-SO")
if '"' in target_org:
for idx, elem in enumerate(sys.argv):
this_elem = elem
next_elem = sys.argv[(idx + 1) % len(sys.argv)]
second_elem = sys.argv[(idx + 2) % len(sys.argv)]
if elem == "-SO":
target_org = next_elem + " " + second_elem
if "-O" in sys.argv:
target_org_outfile = open(string_find("-O"), "w")
else:
target_org_outfile = open(infile_name[:-4] + "_" + target_org + ".tsv", "w")
else:
sys.exit("Need to specify target organism or function to filter by, using -SO flag.")
# loading database file
if "-D" in sys.argv:
db = open(string_find("-D"), "r")
else:
sys.exit("WARNING: database must be specified using '-D' flag.")
# Getting the database assembled
db_org_dictionary = {}
db_id_dictionary = {}
db_line_counter = 0
db_error_counter = 0
t0 = time.time()
for line in db:
if line.startswith(">") == True:
db_line_counter += 1
# line counter to show progress
if db_line_counter % 1000000 == 0: # each million
t95 = time.time()
print (str(db_line_counter) + " lines processed so far in " + str(t95-t0) + " seconds.")
if target_org in line:
splitline = line.split(" ")
# ID, the hit returned in DIAMOND results
db_id = str(splitline[0])[1:].split(" ")[0]
# name and functional description
db_entry = line.split("[", 1)
db_entry = db_entry[0].split(" ", 1)
db_entry = db_entry[1][:-1]
# organism name
if line.count("[") != 1:
splitline = line.split("[")
db_org = splitline[line.count("[")].strip()[:-1]
if db_org[0].isdigit():
split_db_org = db_org.split()
try:
db_org = split_db_org[1] + " " + split_db_org[2]
except IndexError:
try:
db_org = split_db_org[1]
except IndexError:
db_org = splitline[line.count("[")-1]
if db_org[0].isdigit():
split_db_org = db_org.split()
db_org = split_db_org[1] + " " + split_db_org[2]
else:
db_org = line.split("[", 1)
db_org = db_org[1].split()
try:
db_org = str(db_org[0]) + " " + str(db_org[1])
except IndexError:
db_org = line.strip().split("[", 1)
db_org = db_org[1][:-1]
db_error_counter += 1
db_org = re.sub('[^a-zA-Z0-9-_*. ]', '', db_org)
# add to dictionaries
db_org_dictionary[db_id] = db_org
db_id_dictionary[db_id] = db_entry
db.close()
print ("Database is read and set up, moving on to the infile...")
infile = open (infile_name, "r")
# setting up databases
RefSeq_hit_count_db = {}
unique_seq_db = {}
line_counter = 0
hit_counter = 0
t1 = time.time()
# reading through the infile
for line in infile:
line_counter += 1
splitline = line.split("\t")
try:
target_org_outfile.write(splitline[0] + "\t" + splitline[1] + "\t" + db_org_dictionary[splitline[1]] + "\t" + db_id_dictionary[splitline[1]] + "\n")
hit_counter += 1
except KeyError:
continue
if line_counter % 1000000 == 0:
t99 = time.time()
print (str(line_counter)[:-6] + "M lines processed so far in " + str(t99-t1) + " seconds.")
# results stats
t100 = time.time()
print ("Run complete!")
print ("Number of sequences found matching target query, " + target_org + ":\t" + str(hit_counter))
print ("Time elapsed: " + str(t100-t0) + " seconds.")
infile.close()
target_org_outfile.close()
|
string_find
|
identifier_name
|
DIAMOND_results_filter.py
|
#!/usr/lib/python2.7
##########################################################################
#
# Copyright (C) 2015-2016 Sam Westreich
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation;
#
# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##########################################################################
#
# DIAMOND_results_filter.py
# Created 1/30/17, this version updated 5/22/17
# Sam Westreich, [email protected], github.com/transcript
#
# Purpose: This takes a DIAMOND outfile and the RefSeq database and pulls
# out hits to any specific organism, identifying the raw input reads that
# were mapped to that organism.
# Usage:
#
# -I infile specifies the infile (a DIAMOND results file
# in m8 format)
# -SO specific target the organism search term, either genus,
# species, or function.
# -D database file specifies a reference database to search
# against for results
# -O outfile name optional; changes the default outfile name
#
##########################################################################
# imports
import operator, sys, time, gzip, re
# String searching function:
def string_find(usage_term):
|
# loading starting file
if "-I" in sys.argv:
infile_name = string_find("-I")
else:
sys.exit ("WARNING: infile must be specified using '-I' flag.")
# optional outfile of specific organism results
if "-SO" in sys.argv:
target_org = string_find("-SO")
if '"' in target_org:
for idx, elem in enumerate(sys.argv):
this_elem = elem
next_elem = sys.argv[(idx + 1) % len(sys.argv)]
second_elem = sys.argv[(idx + 2) % len(sys.argv)]
if elem == "-SO":
target_org = next_elem + " " + second_elem
if "-O" in sys.argv:
target_org_outfile = open(string_find("-O"), "w")
else:
target_org_outfile = open(infile_name[:-4] + "_" + target_org + ".tsv", "w")
else:
sys.exit("Need to specify target organism or function to filter by, using -SO flag.")
# loading database file
if "-D" in sys.argv:
db = open(string_find("-D"), "r")
else:
sys.exit("WARNING: database must be specified using '-D' flag.")
# Getting the database assembled
db_org_dictionary = {}
db_id_dictionary = {}
db_line_counter = 0
db_error_counter = 0
t0 = time.time()
for line in db:
if line.startswith(">") == True:
db_line_counter += 1
# line counter to show progress
if db_line_counter % 1000000 == 0: # each million
t95 = time.time()
print (str(db_line_counter) + " lines processed so far in " + str(t95-t0) + " seconds.")
if target_org in line:
splitline = line.split(" ")
# ID, the hit returned in DIAMOND results
db_id = str(splitline[0])[1:].split(" ")[0]
# name and functional description
db_entry = line.split("[", 1)
db_entry = db_entry[0].split(" ", 1)
db_entry = db_entry[1][:-1]
# organism name
if line.count("[") != 1:
splitline = line.split("[")
db_org = splitline[line.count("[")].strip()[:-1]
if db_org[0].isdigit():
split_db_org = db_org.split()
try:
db_org = split_db_org[1] + " " + split_db_org[2]
except IndexError:
try:
db_org = split_db_org[1]
except IndexError:
db_org = splitline[line.count("[")-1]
if db_org[0].isdigit():
split_db_org = db_org.split()
db_org = split_db_org[1] + " " + split_db_org[2]
else:
db_org = line.split("[", 1)
db_org = db_org[1].split()
try:
db_org = str(db_org[0]) + " " + str(db_org[1])
except IndexError:
db_org = line.strip().split("[", 1)
db_org = db_org[1][:-1]
db_error_counter += 1
db_org = re.sub('[^a-zA-Z0-9-_*. ]', '', db_org)
# add to dictionaries
db_org_dictionary[db_id] = db_org
db_id_dictionary[db_id] = db_entry
db.close()
print ("Database is read and set up, moving on to the infile...")
infile = open (infile_name, "r")
# setting up databases
RefSeq_hit_count_db = {}
unique_seq_db = {}
line_counter = 0
hit_counter = 0
t1 = time.time()
# reading through the infile
for line in infile:
line_counter += 1
splitline = line.split("\t")
try:
target_org_outfile.write(splitline[0] + "\t" + splitline[1] + "\t" + db_org_dictionary[splitline[1]] + "\t" + db_id_dictionary[splitline[1]] + "\n")
hit_counter += 1
except KeyError:
continue
if line_counter % 1000000 == 0:
t99 = time.time()
print (str(line_counter)[:-6] + "M lines processed so far in " + str(t99-t1) + " seconds.")
# results stats
t100 = time.time()
print ("Run complete!")
print ("Number of sequences found matching target query, " + target_org + ":\t" + str(hit_counter))
print ("Time elapsed: " + str(t100-t0) + " seconds.")
infile.close()
target_org_outfile.close()
|
for idx, elem in enumerate(sys.argv):
this_elem = elem
next_elem = sys.argv[(idx + 1) % len(sys.argv)]
if elem == usage_term:
return next_elem
|
identifier_body
|
DIAMOND_results_filter.py
|
#!/usr/lib/python2.7
##########################################################################
#
# Copyright (C) 2015-2016 Sam Westreich
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation;
#
# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##########################################################################
#
# DIAMOND_results_filter.py
# Created 1/30/17, this version updated 5/22/17
# Sam Westreich, [email protected], github.com/transcript
#
# Purpose: This takes a DIAMOND outfile and the RefSeq database and pulls
# out hits to any specific organism, identifying the raw input reads that
# were mapped to that organism.
# Usage:
#
# -I infile specifies the infile (a DIAMOND results file
# in m8 format)
# -SO specific target the organism search term, either genus,
# species, or function.
# -D database file specifies a reference database to search
# against for results
# -O outfile name optional; changes the default outfile name
#
##########################################################################
# imports
import operator, sys, time, gzip, re
# String searching function:
def string_find(usage_term):
for idx, elem in enumerate(sys.argv):
this_elem = elem
next_elem = sys.argv[(idx + 1) % len(sys.argv)]
if elem == usage_term:
return next_elem
# loading starting file
if "-I" in sys.argv:
infile_name = string_find("-I")
|
# optional outfile of specific organism results
if "-SO" in sys.argv:
target_org = string_find("-SO")
if '"' in target_org:
for idx, elem in enumerate(sys.argv):
this_elem = elem
next_elem = sys.argv[(idx + 1) % len(sys.argv)]
second_elem = sys.argv[(idx + 2) % len(sys.argv)]
if elem == "-SO":
target_org = next_elem + " " + second_elem
if "-O" in sys.argv:
target_org_outfile = open(string_find("-O"), "w")
else:
target_org_outfile = open(infile_name[:-4] + "_" + target_org + ".tsv", "w")
else:
sys.exit("Need to specify target organism or function to filter by, using -SO flag.")
# loading database file
if "-D" in sys.argv:
db = open(string_find("-D"), "r")
else:
sys.exit("WARNING: database must be specified using '-D' flag.")
# Getting the database assembled
db_org_dictionary = {}
db_id_dictionary = {}
db_line_counter = 0
db_error_counter = 0
t0 = time.time()
for line in db:
if line.startswith(">") == True:
db_line_counter += 1
# line counter to show progress
if db_line_counter % 1000000 == 0: # each million
t95 = time.time()
print (str(db_line_counter) + " lines processed so far in " + str(t95-t0) + " seconds.")
if target_org in line:
splitline = line.split(" ")
# ID, the hit returned in DIAMOND results
db_id = str(splitline[0])[1:].split(" ")[0]
# name and functional description
db_entry = line.split("[", 1)
db_entry = db_entry[0].split(" ", 1)
db_entry = db_entry[1][:-1]
# organism name
if line.count("[") != 1:
splitline = line.split("[")
db_org = splitline[line.count("[")].strip()[:-1]
if db_org[0].isdigit():
split_db_org = db_org.split()
try:
db_org = split_db_org[1] + " " + split_db_org[2]
except IndexError:
try:
db_org = split_db_org[1]
except IndexError:
db_org = splitline[line.count("[")-1]
if db_org[0].isdigit():
split_db_org = db_org.split()
db_org = split_db_org[1] + " " + split_db_org[2]
else:
db_org = line.split("[", 1)
db_org = db_org[1].split()
try:
db_org = str(db_org[0]) + " " + str(db_org[1])
except IndexError:
db_org = line.strip().split("[", 1)
db_org = db_org[1][:-1]
db_error_counter += 1
db_org = re.sub('[^a-zA-Z0-9-_*. ]', '', db_org)
# add to dictionaries
db_org_dictionary[db_id] = db_org
db_id_dictionary[db_id] = db_entry
db.close()
print ("Database is read and set up, moving on to the infile...")
infile = open (infile_name, "r")
# setting up databases
RefSeq_hit_count_db = {}
unique_seq_db = {}
line_counter = 0
hit_counter = 0
t1 = time.time()
# reading through the infile
for line in infile:
line_counter += 1
splitline = line.split("\t")
try:
target_org_outfile.write(splitline[0] + "\t" + splitline[1] + "\t" + db_org_dictionary[splitline[1]] + "\t" + db_id_dictionary[splitline[1]] + "\n")
hit_counter += 1
except KeyError:
continue
if line_counter % 1000000 == 0:
t99 = time.time()
print (str(line_counter)[:-6] + "M lines processed so far in " + str(t99-t1) + " seconds.")
# results stats
t100 = time.time()
print ("Run complete!")
print ("Number of sequences found matching target query, " + target_org + ":\t" + str(hit_counter))
print ("Time elapsed: " + str(t100-t0) + " seconds.")
infile.close()
target_org_outfile.close()
|
else:
sys.exit ("WARNING: infile must be specified using '-I' flag.")
|
random_line_split
|
colors.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" Convenience functions for generating distinct colors.
Usage:
>>> generate_colors(4)
[(1.0, 0.0, 0.0), (0.5, 1.0, 0.0), (0.0, 1.0, 1.0), (0.5, 0.0, 1.0)]
"""
from __future__ import division
__author__ = 'Maarten Versteegh'
import math
def _hsv_to_rgb(h,f):
"""Convert a color specified by h-value and f-value to rgb triple
"""
v = 1.0
p = 0.0
if h == 0:
return v, f, p
elif h == 1:
return 1-f, v, p
elif h == 2:
return p, v, f
elif h == 3:
return p, 1-f, v
elif h == 4:
return f, p, v
elif h == 5:
return v, p, 1-f
def
|
(n):
"""Generate n distinct colors as rgb triples
Arguments:
n : int
number of colors to generate
Returns:
List of rgb triples
"""
hues = [360/n*i for i in range(n)]
hs = [(math.floor(hue/60) % 6) for hue in hues]
fs = [(hue/60 - math.floor(hue / 60)) for hue in hues]
return [_hsv_to_rgb(h,f) for h,f in zip(hs,fs)]
|
generate_colors
|
identifier_name
|
colors.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" Convenience functions for generating distinct colors.
Usage:
>>> generate_colors(4)
[(1.0, 0.0, 0.0), (0.5, 1.0, 0.0), (0.0, 1.0, 1.0), (0.5, 0.0, 1.0)]
"""
from __future__ import division
__author__ = 'Maarten Versteegh'
import math
def _hsv_to_rgb(h,f):
"""Convert a color specified by h-value and f-value to rgb triple
"""
v = 1.0
p = 0.0
if h == 0:
return v, f, p
elif h == 1:
return 1-f, v, p
elif h == 2:
return p, v, f
elif h == 3:
|
elif h == 4:
return f, p, v
elif h == 5:
return v, p, 1-f
def generate_colors(n):
"""Generate n distinct colors as rgb triples
Arguments:
n : int
number of colors to generate
Returns:
List of rgb triples
"""
hues = [360/n*i for i in range(n)]
hs = [(math.floor(hue/60) % 6) for hue in hues]
fs = [(hue/60 - math.floor(hue / 60)) for hue in hues]
return [_hsv_to_rgb(h,f) for h,f in zip(hs,fs)]
|
return p, 1-f, v
|
conditional_block
|
colors.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" Convenience functions for generating distinct colors.
Usage:
>>> generate_colors(4)
[(1.0, 0.0, 0.0), (0.5, 1.0, 0.0), (0.0, 1.0, 1.0), (0.5, 0.0, 1.0)]
"""
from __future__ import division
__author__ = 'Maarten Versteegh'
import math
def _hsv_to_rgb(h,f):
|
def generate_colors(n):
"""Generate n distinct colors as rgb triples
Arguments:
n : int
number of colors to generate
Returns:
List of rgb triples
"""
hues = [360/n*i for i in range(n)]
hs = [(math.floor(hue/60) % 6) for hue in hues]
fs = [(hue/60 - math.floor(hue / 60)) for hue in hues]
return [_hsv_to_rgb(h,f) for h,f in zip(hs,fs)]
|
"""Convert a color specified by h-value and f-value to rgb triple
"""
v = 1.0
p = 0.0
if h == 0:
return v, f, p
elif h == 1:
return 1-f, v, p
elif h == 2:
return p, v, f
elif h == 3:
return p, 1-f, v
elif h == 4:
return f, p, v
elif h == 5:
return v, p, 1-f
|
identifier_body
|
colors.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" Convenience functions for generating distinct colors.
Usage:
>>> generate_colors(4)
[(1.0, 0.0, 0.0), (0.5, 1.0, 0.0), (0.0, 1.0, 1.0), (0.5, 0.0, 1.0)]
"""
from __future__ import division
__author__ = 'Maarten Versteegh'
import math
def _hsv_to_rgb(h,f):
"""Convert a color specified by h-value and f-value to rgb triple
"""
v = 1.0
p = 0.0
if h == 0:
return v, f, p
elif h == 1:
return 1-f, v, p
elif h == 2:
return p, v, f
elif h == 3:
return p, 1-f, v
elif h == 4:
return f, p, v
elif h == 5:
return v, p, 1-f
|
Arguments:
n : int
number of colors to generate
Returns:
List of rgb triples
"""
hues = [360/n*i for i in range(n)]
hs = [(math.floor(hue/60) % 6) for hue in hues]
fs = [(hue/60 - math.floor(hue / 60)) for hue in hues]
return [_hsv_to_rgb(h,f) for h,f in zip(hs,fs)]
|
def generate_colors(n):
"""Generate n distinct colors as rgb triples
|
random_line_split
|
NoteMouseHandler.ts
|
import { observeDrag } from "../../../helpers/observeDrag"
import RootStore from "../../../stores/RootStore"
import {
getPencilActionForMouseDown,
getPencilActionForMouseUp,
getPencilCursorForMouseMove,
} from "./PencilMouseHandler"
import {
getSelectionActionForMouseDown,
getSelectionCursorForMouseMoven,
} from "./SelectionMouseHandler"
export type MouseGesture = (rootStore: RootStore) => (e: MouseEvent) => void
export default class NoteMouseHandler {
protected readonly rootStore: RootStore
private isMouseDown = false
constructor(rootStore: RootStore) {
this.rootStore = rootStore
this.onMouseDown = this.onMouseDown.bind(this)
this.onMouseMove = this.onMouseMove.bind(this)
this.onMouseUp = this.onMouseUp.bind(this)
}
// mousedown 以降に行う MouseAction を返す
// Returns a MouseAction to do after MouseDown
|
// 共通の action
// Common Action
// wheel drag to start scrolling
if (e.button === 1) {
return dragScrollAction
}
// 右ダブルクリック
// Right Double-click
if (e.button === 2 && e.detail % 2 === 0) {
return changeToolAction
}
switch (this.rootStore.pianoRollStore.mouseMode) {
case "pencil":
return getPencilActionForMouseDown(this.rootStore)(e)
case "selection":
return getSelectionActionForMouseDown(this.rootStore)(e)
}
}
protected getCursorForMouseMove(e: MouseEvent): string {
switch (this.rootStore.pianoRollStore.mouseMode) {
case "pencil":
return getPencilCursorForMouseMove(this.rootStore)(e)
case "selection":
return getSelectionCursorForMouseMoven(this.rootStore)(e)
}
}
onMouseDown(ev: React.MouseEvent) {
const e = ev.nativeEvent
this.isMouseDown = true
this.actionForMouseDown(e)?.(this.rootStore)(e)
}
onMouseMove(ev: React.MouseEvent) {
const e = ev.nativeEvent
if (!this.isMouseDown) {
const cursor = this.getCursorForMouseMove(e)
this.rootStore.pianoRollStore.notesCursor = cursor
}
}
onMouseUp(ev: React.MouseEvent) {
const e = ev.nativeEvent
this.isMouseDown = false
switch (this.rootStore.pianoRollStore.mouseMode) {
case "pencil":
getPencilActionForMouseUp()(this.rootStore)(e)
}
}
}
const dragScrollAction: MouseGesture =
({ pianoRollStore }) =>
() => {
observeDrag({
onMouseMove: (e: MouseEvent) => {
pianoRollStore.scrollBy(e.movementX, e.movementY)
},
})
}
const changeToolAction: MouseGesture =
({ pianoRollStore }) =>
() => {
pianoRollStore.toggleTool()
pianoRollStore.notesCursor = "crosshair"
}
|
actionForMouseDown(e: MouseEvent): MouseGesture | null {
|
random_line_split
|
NoteMouseHandler.ts
|
import { observeDrag } from "../../../helpers/observeDrag"
import RootStore from "../../../stores/RootStore"
import {
getPencilActionForMouseDown,
getPencilActionForMouseUp,
getPencilCursorForMouseMove,
} from "./PencilMouseHandler"
import {
getSelectionActionForMouseDown,
getSelectionCursorForMouseMoven,
} from "./SelectionMouseHandler"
export type MouseGesture = (rootStore: RootStore) => (e: MouseEvent) => void
export default class NoteMouseHandler {
protected readonly rootStore: RootStore
private isMouseDown = false
|
(rootStore: RootStore) {
this.rootStore = rootStore
this.onMouseDown = this.onMouseDown.bind(this)
this.onMouseMove = this.onMouseMove.bind(this)
this.onMouseUp = this.onMouseUp.bind(this)
}
// mousedown 以降に行う MouseAction を返す
// Returns a MouseAction to do after MouseDown
actionForMouseDown(e: MouseEvent): MouseGesture | null {
// 共通の action
// Common Action
// wheel drag to start scrolling
if (e.button === 1) {
return dragScrollAction
}
// 右ダブルクリック
// Right Double-click
if (e.button === 2 && e.detail % 2 === 0) {
return changeToolAction
}
switch (this.rootStore.pianoRollStore.mouseMode) {
case "pencil":
return getPencilActionForMouseDown(this.rootStore)(e)
case "selection":
return getSelectionActionForMouseDown(this.rootStore)(e)
}
}
protected getCursorForMouseMove(e: MouseEvent): string {
switch (this.rootStore.pianoRollStore.mouseMode) {
case "pencil":
return getPencilCursorForMouseMove(this.rootStore)(e)
case "selection":
return getSelectionCursorForMouseMoven(this.rootStore)(e)
}
}
onMouseDown(ev: React.MouseEvent) {
const e = ev.nativeEvent
this.isMouseDown = true
this.actionForMouseDown(e)?.(this.rootStore)(e)
}
onMouseMove(ev: React.MouseEvent) {
const e = ev.nativeEvent
if (!this.isMouseDown) {
const cursor = this.getCursorForMouseMove(e)
this.rootStore.pianoRollStore.notesCursor = cursor
}
}
onMouseUp(ev: React.MouseEvent) {
const e = ev.nativeEvent
this.isMouseDown = false
switch (this.rootStore.pianoRollStore.mouseMode) {
case "pencil":
getPencilActionForMouseUp()(this.rootStore)(e)
}
}
}
const dragScrollAction: MouseGesture =
({ pianoRollStore }) =>
() => {
observeDrag({
onMouseMove: (e: MouseEvent) => {
pianoRollStore.scrollBy(e.movementX, e.movementY)
},
})
}
const changeToolAction: MouseGesture =
({ pianoRollStore }) =>
() => {
pianoRollStore.toggleTool()
pianoRollStore.notesCursor = "crosshair"
}
|
constructor
|
identifier_name
|
CodeModal.tsx
|
import MonacoEditor from '@monaco-editor/react';
import classNames from 'classnames';
import React, { useEffect, useState } from 'react';
import { AutoSizer } from 'react-virtualized';
// @ts-ignore
import Rodal from 'rodal';
import { ValueType } from 'tweek-client';
import { isStringValidJson } from '../../../services/types-service';
const monacoOptions = {
autoIndent: 'full' as const,
automaticLayout: true,
formatOnPaste: true,
formatOnType: true,
scrollBeyondLastLine: false,
minimap: {
enabled: false,
},
readOnly: false,
};
export type CodeModalProps = {
visible: boolean;
value: string;
valueType: ValueType;
onClose: (value?: string) => void;
};
const CodeModal = ({ visible, value: initialValue, valueType, onClose }: CodeModalProps) => {
const [value, setValue] = useState(initialValue);
useEffect(() => {
setValue(initialValue);
}, [visible, initialValue]);
return (
<Rodal
closeOnEsc
visible={visible}
showCloseButton={false}
onClose={onClose}
className={classNames('rodal-container', 'resizable')}
>
<h1 className="rodal-header">Edit Object</h1>
{visible && (
<AutoSizer disableWidth>
{({ height }) => (
<div style={{ height: height - 75 }}>
<MonacoEditor
key={`m_${height}`}
language="json"
value={value}
options={monacoOptions}
onChange={(value) => setValue(value!)}
onMount={(editor) => {
setTimeout(() => {
|
const editLineNum = lineCount > 1 ? lineCount - 1 : lineCount;
editor.setPosition({
lineNumber: editLineNum,
column: model.getLineMaxColumn(editLineNum),
});
editor.revealLine(lineCount);
}
editor.focus();
}, 500);
}}
/>
</div>
)}
</AutoSizer>
)}
<div className="rodal-button-container">
<button
disabled={value === initialValue || !isStringValidJson(value, valueType)}
onClick={() => onClose(value)}
className="rodal-save-btn"
data-alert-button="save"
>
Save
</button>
<button onClick={() => onClose()} className="rodal-cancel-btn" data-alert-button="cancel">
Cancel
</button>
</div>
</Rodal>
);
};
export default CodeModal;
|
const model = editor.getModel();
if (model) {
const lineCount = model.getLineCount();
|
random_line_split
|
CodeModal.tsx
|
import MonacoEditor from '@monaco-editor/react';
import classNames from 'classnames';
import React, { useEffect, useState } from 'react';
import { AutoSizer } from 'react-virtualized';
// @ts-ignore
import Rodal from 'rodal';
import { ValueType } from 'tweek-client';
import { isStringValidJson } from '../../../services/types-service';
const monacoOptions = {
autoIndent: 'full' as const,
automaticLayout: true,
formatOnPaste: true,
formatOnType: true,
scrollBeyondLastLine: false,
minimap: {
enabled: false,
},
readOnly: false,
};
export type CodeModalProps = {
visible: boolean;
value: string;
valueType: ValueType;
onClose: (value?: string) => void;
};
const CodeModal = ({ visible, value: initialValue, valueType, onClose }: CodeModalProps) => {
const [value, setValue] = useState(initialValue);
useEffect(() => {
setValue(initialValue);
}, [visible, initialValue]);
return (
<Rodal
closeOnEsc
visible={visible}
showCloseButton={false}
onClose={onClose}
className={classNames('rodal-container', 'resizable')}
>
<h1 className="rodal-header">Edit Object</h1>
{visible && (
<AutoSizer disableWidth>
{({ height }) => (
<div style={{ height: height - 75 }}>
<MonacoEditor
key={`m_${height}`}
language="json"
value={value}
options={monacoOptions}
onChange={(value) => setValue(value!)}
onMount={(editor) => {
setTimeout(() => {
const model = editor.getModel();
if (model)
|
editor.focus();
}, 500);
}}
/>
</div>
)}
</AutoSizer>
)}
<div className="rodal-button-container">
<button
disabled={value === initialValue || !isStringValidJson(value, valueType)}
onClick={() => onClose(value)}
className="rodal-save-btn"
data-alert-button="save"
>
Save
</button>
<button onClick={() => onClose()} className="rodal-cancel-btn" data-alert-button="cancel">
Cancel
</button>
</div>
</Rodal>
);
};
export default CodeModal;
|
{
const lineCount = model.getLineCount();
const editLineNum = lineCount > 1 ? lineCount - 1 : lineCount;
editor.setPosition({
lineNumber: editLineNum,
column: model.getLineMaxColumn(editLineNum),
});
editor.revealLine(lineCount);
}
|
conditional_block
|
debug_node.d.ts
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Injector } from '../di';
import { Predicate } from '../facade/collection';
import { RenderDebugInfo } from '../render/api';
export declare class EventListener {
name: string;
callback: Function;
constructor(name: string, callback: Function);
}
/**
* @experimental All debugging apis are currently experimental.
*/
export declare class DebugNode {
private _debugInfo;
nativeNode: any;
listeners: EventListener[];
parent: DebugElement;
constructor(nativeNode: any, parent: DebugNode, _debugInfo: RenderDebugInfo);
injector: Injector;
componentInstance: any;
context: any;
references: {
[key: string]: any;
};
providerTokens: any[];
source: string;
}
/**
* @experimental All debugging apis are currently experimental.
*/
export declare class
|
extends DebugNode {
name: string;
properties: {
[key: string]: any;
};
attributes: {
[key: string]: string;
};
classes: {
[key: string]: boolean;
};
styles: {
[key: string]: string;
};
childNodes: DebugNode[];
nativeElement: any;
constructor(nativeNode: any, parent: any, _debugInfo: RenderDebugInfo);
addChild(child: DebugNode): void;
removeChild(child: DebugNode): void;
insertChildrenAfter(child: DebugNode, newChildren: DebugNode[]): void;
query(predicate: Predicate<DebugElement>): DebugElement;
queryAll(predicate: Predicate<DebugElement>): DebugElement[];
queryAllNodes(predicate: Predicate<DebugNode>): DebugNode[];
children: DebugElement[];
triggerEventHandler(eventName: string, eventObj: any): void;
}
/**
* @experimental
*/
export declare function asNativeElements(debugEls: DebugElement[]): any;
/**
* @experimental
*/
export declare function getDebugNode(nativeNode: any): DebugNode;
export declare function getAllDebugNodes(): DebugNode[];
export declare function indexDebugNode(node: DebugNode): void;
export declare function removeDebugNodeFromIndex(node: DebugNode): void;
|
DebugElement
|
identifier_name
|
debug_node.d.ts
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Injector } from '../di';
import { Predicate } from '../facade/collection';
import { RenderDebugInfo } from '../render/api';
export declare class EventListener {
name: string;
callback: Function;
constructor(name: string, callback: Function);
}
/**
* @experimental All debugging apis are currently experimental.
*/
export declare class DebugNode {
private _debugInfo;
nativeNode: any;
listeners: EventListener[];
parent: DebugElement;
constructor(nativeNode: any, parent: DebugNode, _debugInfo: RenderDebugInfo);
injector: Injector;
componentInstance: any;
context: any;
references: {
[key: string]: any;
};
providerTokens: any[];
source: string;
}
/**
* @experimental All debugging apis are currently experimental.
*/
export declare class DebugElement extends DebugNode {
name: string;
properties: {
[key: string]: any;
};
attributes: {
[key: string]: string;
};
classes: {
[key: string]: boolean;
};
styles: {
[key: string]: string;
};
childNodes: DebugNode[];
nativeElement: any;
constructor(nativeNode: any, parent: any, _debugInfo: RenderDebugInfo);
addChild(child: DebugNode): void;
removeChild(child: DebugNode): void;
insertChildrenAfter(child: DebugNode, newChildren: DebugNode[]): void;
query(predicate: Predicate<DebugElement>): DebugElement;
queryAll(predicate: Predicate<DebugElement>): DebugElement[];
queryAllNodes(predicate: Predicate<DebugNode>): DebugNode[];
children: DebugElement[];
triggerEventHandler(eventName: string, eventObj: any): void;
}
/**
* @experimental
*/
export declare function asNativeElements(debugEls: DebugElement[]): any;
/**
* @experimental
|
export declare function getAllDebugNodes(): DebugNode[];
export declare function indexDebugNode(node: DebugNode): void;
export declare function removeDebugNodeFromIndex(node: DebugNode): void;
|
*/
export declare function getDebugNode(nativeNode: any): DebugNode;
|
random_line_split
|
different-category-comparison.test.js
|
/**
* @license Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
/* eslint-env jest, browser */
const {shouldRunE2E, emptyTest, getTestLHRPath, waitForNetworkIdle0} = require('../test-utils.js');
describe('Viewer simple comparison', () => {
if (!shouldRunE2E()) return emptyTest();
const state = /** @type {LHCI.E2EState} */ ({});
require('./steps/setup')(state);
describe('render the landing route', () => {
it('should navigate to the page', async () => {
await Promise.all([state.page.goto(state.rootURL), waitForNetworkIdle0(state.page)]);
});
it('should upload the first report', async () => {
const baseUpload = await state.page.$('.report-upload-box--base input[type=file]');
if (!baseUpload) throw new Error('Missing base upload box');
await baseUpload.uploadFile(getTestLHRPath('7.0.0', 'coursehero-perf', 'a'));
|
});
it('should upload the second report', async () => {
const compareUpload = await state.page.$('.report-upload-box--compare input[type=file]');
if (!compareUpload) throw new Error('Missing compare upload box');
await compareUpload.uploadFile(getTestLHRPath('7.0.0', 'coursehero', 'b'));
});
});
describe('render the comparison route', () => {
it('should wait for the diff to render', async () => {
await Promise.all([
waitForNetworkIdle0(state.page),
state.page.waitForSelector('.lhr-comparison'),
]);
});
it('should look correct', async () => {
expect(await state.page.screenshot()).toMatchImageSnapshot();
});
});
require('./steps/teardown')(state);
});
|
random_line_split
|
|
ProjOpen.js
|
/**
* File: app/project/ProjOpen.js
* Author: liusha
|
grid: null,
initComponent: function() {
var me = this;
me.openStore = Ext.create('xdfn.project.store.ProjOpenJsonStore');
me.rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
errorSummary: false
});
me.callParent(arguments);
me.down('button[text="增加记录"]').on('click', me.OnAddProjOpenBtnClick, me);
me.down('button[text="删除记录"]').on('click', me.OnDeleteProjOpenBtnClick, me);
me.down('button[text="导出"]').on('click', me.OnExportProjOpenBtnClick, me);
me.rowEditing.on('edit', me.OnGridEdit, me);
me.rowEditing.on('beforeedit', me.OnGridBeforeEdit, me);
},
OnGridBeforeEdit: function(editor, e, epts) {
xdfn.user.Rights.noRights('XMGL-XMZL-31', function() {
editor.cancelEdit();
});
},
OnGridEdit: function(editor, e) {
var me = this;
if (!e.record.dirty) return;
var url = './proExec.do?method=modifyKbjl';
if (Ext.isEmpty(e.record.get('ID_VIEW'))) {
var rows = me.grid.getSelectionModel().getSelection();
e.record.set('ID_VIEW', rows[0].get('ID_VIEW'));
url = './proExec.do?method=addProKbjl';
}
e.record.commit();
Ext.Ajax.request({
url: url,
method: 'post',
params: {
ID: e.record.get('ID_VIEW'),
V_MANU: e.record.get('V_MANU_VIEW'),
V_MACHINE: e.record.get('V_MACHINE_VIEW'),
N_CAP: e.record.get('N_CAP_VIEW'),
N_SUM_NUM: e.record.get('N_SUM_NUM_VIEW'),
N_SUM_MONEY: e.record.get('N_SUM_MONEY_VIEW'),
V_MEMO: e.record.get('V_MEMO_VIEW')
},
success: function(response, opts) {
var result = Ext.JSON.decode(response.responseText); //服务端返回新建ID
e.record.set(result.data);
e.record.commit();
},
failure: function(response, opts) {
Ext.Msg.alert('提示','提交失败!');
}
});
},
OnAddProjOpenBtnClick: function(self, e, options) {
var me = this,
sm = me.grid.getSelectionModel(),
rows = sm.getSelection();
xdfn.user.Rights.hasRights('XMGL-XMZL-30', function() {
if (rows.length > 0) {
me.rowEditing.cancelEdit();
me.openStore.insert(0, {});
me.rowEditing.startEdit(0, 0);
} else {
Ext.Msg.alert('提示','请先选择相应的项目!');
}
});
},
OnDeleteProjOpenBtnClick: function(self, e, options) {
var me = this,
grid = self.up('gridpanel'),
store = grid.getStore(),
sm = grid.getSelectionModel(),
rows = sm.getSelection();
xdfn.user.Rights.hasRights('XMGL-XMZL-32', function() {
if (rows.length > 0) {
if (Ext.isEmpty(rows[0].get('ID_VIEW'))) {
me.rowEditing.cancelEdit();
var i = store.indexOf(rows[0]);
store.remove(rows);
var count = store.getCount();
if (count > 0) {
sm.select((i == count)? --i : i);
}
return;
}
Ext.MessageBox.confirm('提示', '确定删除该记录吗?', function(id) {
if (id == 'yes') {
//TODO 删除记录
Ext.Ajax.request({
url: './proExec.do?method=deleteKbjl', //改为实际的删除请求url
method: 'get',
params: {
ID: rows[0].get('ID_VIEW')
},
success: function(response, opts) {
me.rowEditing.cancelEdit();
var i = store.indexOf(rows[0]);
store.remove(rows);
var count = store.getCount();
if (count > 0) {
sm.select((i == count)? --i : i);
}
},
failure: function(response, opts) {
Ext.Msg.alert('提示','删除失败!');
}
});
}
});
} else {
Ext.Msg.alert('提示','请选择要删除的记录!');
}
});
},
OnExportProjOpenBtnClick: function(self, e, options) {
var me = this;
//导出为excel文件
xdfn.user.Rights.hasRights('XMGL-XMZL-33', function() {
me.openStore.load({
limit: me.openStore.getTotalCount(),
scope: this,
callback: function(records, operation, success) {
var excelXml = Ext.ux.exporter.Exporter.exportGrid(self.up('gridpanel'), 'excel', {title: '项目开标记录'});
document.location = 'data:application/vnd.ms-excel;base64,' + Ext.ux.exporter.Base64.encode(excelXml);
}
});
});
}
});
|
*/
Ext.define('xdfn.project.ProjOpen', {
extend: 'xdfn.project.ui.ProjOpen',
|
random_line_split
|
ProjOpen.js
|
/**
* File: app/project/ProjOpen.js
* Author: liusha
*/
Ext.define('xdfn.project.ProjOpen', {
extend: 'xdfn.project.ui.ProjOpen',
grid: null,
initComponent: function() {
var me = this;
me.openStore = Ext.create('xdfn.project.store.ProjOpenJsonStore');
me.rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
errorSummary: false
});
me.callParent(arguments);
me.down('button[text="增加记录"]').on('click', me.OnAddProjOpenBtnClick, me);
me.down('button[text="删除记录"]').on('click', me.OnDeleteProjOpenBtnClick, me);
me.down('button[text="导出"]').on('click', me.OnExportProjOpenBtnClick, me);
me.rowEditing.on('edit', me.OnGridEdit, me);
me.rowEditing.on('beforeedit', me.OnGridBeforeEdit, me);
},
OnGridBeforeEdit: function(editor, e, epts) {
xdfn.user.Rights.noRights('XMGL-XMZL-31', function() {
editor.cancelEdit();
});
},
OnGridEdit: function(editor, e) {
var me = this;
if (!e.record.dirty) return;
var url = './proExec.do?method=modifyKbjl';
if (Ext.isEmpty(e.record.get('ID_VIEW'))) {
var rows = me.grid.getSelectionModel().getSelection();
e.record.set('ID_VIEW', rows[0].get('ID_VIEW'));
url = './proExec.do?method=addProKbjl';
}
e.record.commit();
Ext.Ajax.request({
url: url,
method: 'post',
params: {
ID: e.record.get('ID_VIEW'),
V_MANU: e.record.get('V_MANU_VIEW'),
V_MACHINE: e.record.get('V_MACHINE_VIEW'),
N_CAP: e.record.get('N_CAP_VIEW'),
N_SUM_NUM: e.record.get('N_SUM_NUM_VIEW'),
N_SUM_MONEY: e.record.get('N_SUM_MONEY_VIEW'),
V_MEMO: e.record.get('V_MEMO_VIEW')
},
success: function(response, opts) {
var result = Ext.JSON.decode(response.responseText); //服务端返回新建ID
e.record.set(result.data);
e.record.commit();
},
failure: function(response, opts) {
Ext.Msg.alert('提示','提交失败!');
}
});
},
OnAddProjOpenBtnClick: function(self, e, options) {
var me = this,
sm = me.grid.getSelectionModel(),
rows = sm.getSelection();
xdfn.user.Rights.hasRights('XMGL-XMZL-30', function() {
if (rows.length > 0) {
me.rowEditing.cancelEdit();
me.openStore.insert(0, {});
me.rowEditing.startEdit(0, 0);
} else {
Ext.Msg.alert('提示','请先选择相应的项目!');
}
});
},
OnDeleteProjOpenBtnClick: function(self, e, options) {
var me = this,
grid = self.up('gridpanel'),
store = grid.getStore(),
sm = grid.getSelectionModel(),
rows = sm.getSelection();
xdfn.user.Rights.hasRights('XMGL-XMZL-32', function() {
if (rows.length > 0) {
if (Ext.isEmpty(rows[0].get('ID_VIEW'))) {
me.rowEditin
|
{
var me = this;
//导出为excel文件
xdfn.user.Rights.hasRights('XMGL-XMZL-33', function() {
me.openStore.load({
limit: me.openStore.getTotalCount(),
scope: this,
callback: function(records, operation, success) {
var excelXml = Ext.ux.exporter.Exporter.exportGrid(self.up('gridpanel'), 'excel', {title: '项目开标记录'});
document.location = 'data:application/vnd.ms-excel;base64,' + Ext.ux.exporter.Base64.encode(excelXml);
}
});
});
}
});
|
g.cancelEdit();
var i = store.indexOf(rows[0]);
store.remove(rows);
var count = store.getCount();
if (count > 0) {
sm.select((i == count)? --i : i);
}
return;
}
Ext.MessageBox.confirm('提示', '确定删除该记录吗?', function(id) {
if (id == 'yes') {
//TODO 删除记录
Ext.Ajax.request({
url: './proExec.do?method=deleteKbjl', //改为实际的删除请求url
method: 'get',
params: {
ID: rows[0].get('ID_VIEW')
},
success: function(response, opts) {
me.rowEditing.cancelEdit();
var i = store.indexOf(rows[0]);
store.remove(rows);
var count = store.getCount();
if (count > 0) {
sm.select((i == count)? --i : i);
}
},
failure: function(response, opts) {
Ext.Msg.alert('提示','删除失败!');
}
});
}
});
} else {
Ext.Msg.alert('提示','请选择要删除的记录!');
}
});
},
OnExportProjOpenBtnClick: function(self, e, options)
|
conditional_block
|
server.sitemap.ts
|
// tslint:disable:no-require-imports
import { writeFile } from 'fs'
const sitemapGenerator = require('sitemap-generator')
export const sitemap = (host: string) => new Promise<string>((resolve, reject) => {
const generator = new sitemapGenerator(host)
// Avoid infinite loop during initial creation
generator.crawler.addFetchCondition((parsedUrl: any) => {
return !parsedUrl.url.includes('sitemap.xml')
})
// TODO: this isn't working!
// generator.crawler.on('fetchconditionerror', (queueItem: any) => {
// add back into sitemap stack
// });
generator.on('done', (sitemaps: string[]) => {
if (sitemaps && sitemaps[0]) {
writeFile('dist/sitemap.xml', sitemaps[0], () => {
console.log('Generated sitemap.xml')
return resolve(sitemaps[0])
})
|
generator.on('clienterror', (err: any) => {
return reject(err)
})
console.log(`starting sitemap crawler on ${host}`)
generator.start()
})
|
} else {
return reject('Failed to generate sitemap.xml')
}
})
|
random_line_split
|
server.sitemap.ts
|
// tslint:disable:no-require-imports
import { writeFile } from 'fs'
const sitemapGenerator = require('sitemap-generator')
export const sitemap = (host: string) => new Promise<string>((resolve, reject) => {
const generator = new sitemapGenerator(host)
// Avoid infinite loop during initial creation
generator.crawler.addFetchCondition((parsedUrl: any) => {
return !parsedUrl.url.includes('sitemap.xml')
})
// TODO: this isn't working!
// generator.crawler.on('fetchconditionerror', (queueItem: any) => {
// add back into sitemap stack
// });
generator.on('done', (sitemaps: string[]) => {
if (sitemaps && sitemaps[0]) {
writeFile('dist/sitemap.xml', sitemaps[0], () => {
console.log('Generated sitemap.xml')
return resolve(sitemaps[0])
})
} else
|
})
generator.on('clienterror', (err: any) => {
return reject(err)
})
console.log(`starting sitemap crawler on ${host}`)
generator.start()
})
|
{
return reject('Failed to generate sitemap.xml')
}
|
conditional_block
|
index.ts
|
import { NextApiRequest, NextApiResponse } from 'next'
|
import { formatAmountForStripe } from '../../../utils/stripe-helpers'
import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-node#configuration
apiVersion: '2020-03-02',
})
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === 'POST') {
const amount: number = req.body.amount
try {
// Validate the amount that was passed from the client.
if (!(amount >= MIN_AMOUNT && amount <= MAX_AMOUNT)) {
throw new Error('Invalid amount.')
}
// Create Checkout Sessions from body params.
const params: Stripe.Checkout.SessionCreateParams = {
submit_type: 'donate',
payment_method_types: ['card'],
line_items: [
{
name: 'Custom amount donation',
amount: formatAmountForStripe(amount, CURRENCY),
currency: CURRENCY,
quantity: 1,
},
],
success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/donate-with-checkout`,
}
const checkoutSession: Stripe.Checkout.Session = await stripe.checkout.sessions.create(
params
)
res.status(200).json(checkoutSession)
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message })
}
} else {
res.setHeader('Allow', 'POST')
res.status(405).end('Method Not Allowed')
}
}
|
import { CURRENCY, MIN_AMOUNT, MAX_AMOUNT } from '../../../config'
|
random_line_split
|
index.ts
|
import { NextApiRequest, NextApiResponse } from 'next'
import { CURRENCY, MIN_AMOUNT, MAX_AMOUNT } from '../../../config'
import { formatAmountForStripe } from '../../../utils/stripe-helpers'
import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-node#configuration
apiVersion: '2020-03-02',
})
export default async function
|
(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === 'POST') {
const amount: number = req.body.amount
try {
// Validate the amount that was passed from the client.
if (!(amount >= MIN_AMOUNT && amount <= MAX_AMOUNT)) {
throw new Error('Invalid amount.')
}
// Create Checkout Sessions from body params.
const params: Stripe.Checkout.SessionCreateParams = {
submit_type: 'donate',
payment_method_types: ['card'],
line_items: [
{
name: 'Custom amount donation',
amount: formatAmountForStripe(amount, CURRENCY),
currency: CURRENCY,
quantity: 1,
},
],
success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/donate-with-checkout`,
}
const checkoutSession: Stripe.Checkout.Session = await stripe.checkout.sessions.create(
params
)
res.status(200).json(checkoutSession)
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message })
}
} else {
res.setHeader('Allow', 'POST')
res.status(405).end('Method Not Allowed')
}
}
|
handler
|
identifier_name
|
index.ts
|
import { NextApiRequest, NextApiResponse } from 'next'
import { CURRENCY, MIN_AMOUNT, MAX_AMOUNT } from '../../../config'
import { formatAmountForStripe } from '../../../utils/stripe-helpers'
import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-node#configuration
apiVersion: '2020-03-02',
})
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
)
|
{
if (req.method === 'POST') {
const amount: number = req.body.amount
try {
// Validate the amount that was passed from the client.
if (!(amount >= MIN_AMOUNT && amount <= MAX_AMOUNT)) {
throw new Error('Invalid amount.')
}
// Create Checkout Sessions from body params.
const params: Stripe.Checkout.SessionCreateParams = {
submit_type: 'donate',
payment_method_types: ['card'],
line_items: [
{
name: 'Custom amount donation',
amount: formatAmountForStripe(amount, CURRENCY),
currency: CURRENCY,
quantity: 1,
},
],
success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/donate-with-checkout`,
}
const checkoutSession: Stripe.Checkout.Session = await stripe.checkout.sessions.create(
params
)
res.status(200).json(checkoutSession)
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message })
}
} else {
res.setHeader('Allow', 'POST')
res.status(405).end('Method Not Allowed')
}
}
|
identifier_body
|
|
index.ts
|
import { NextApiRequest, NextApiResponse } from 'next'
import { CURRENCY, MIN_AMOUNT, MAX_AMOUNT } from '../../../config'
import { formatAmountForStripe } from '../../../utils/stripe-helpers'
import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-node#configuration
apiVersion: '2020-03-02',
})
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === 'POST') {
const amount: number = req.body.amount
try {
// Validate the amount that was passed from the client.
if (!(amount >= MIN_AMOUNT && amount <= MAX_AMOUNT)) {
throw new Error('Invalid amount.')
}
// Create Checkout Sessions from body params.
const params: Stripe.Checkout.SessionCreateParams = {
submit_type: 'donate',
payment_method_types: ['card'],
line_items: [
{
name: 'Custom amount donation',
amount: formatAmountForStripe(amount, CURRENCY),
currency: CURRENCY,
quantity: 1,
},
],
success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/donate-with-checkout`,
}
const checkoutSession: Stripe.Checkout.Session = await stripe.checkout.sessions.create(
params
)
res.status(200).json(checkoutSession)
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message })
}
} else
|
}
|
{
res.setHeader('Allow', 'POST')
res.status(405).end('Method Not Allowed')
}
|
conditional_block
|
unique-enum.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-tidy-linelength
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *the_a
// gdb-check:$1 = {{RUST$ENUM$DISR = TheA, x = 0, y = 8970181431921507452}, {RUST$ENUM$DISR = TheA, 0, 2088533116, 2088533116}}
// gdb-command:print *the_b
// gdb-check:$2 = {{RUST$ENUM$DISR = TheB, x = 0, y = 1229782938247303441}, {RUST$ENUM$DISR = TheB, 0, 286331153, 286331153}}
// gdb-command:print *univariant
// gdb-check:$3 = {{123234}}
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print *the_a
// lldb-check:[...]$0 = TheA { x: 0, y: 8970181431921507452 }
// lldb-command:print *the_b
// lldb-check:[...]$1 = TheB(0, 286331153, 286331153)
// lldb-command:print *univariant
// lldb-check:[...]$2 = TheOnlyCase(123234)
#![allow(unused_variables)]
#![feature(box_syntax)]
#![omit_gdb_pretty_printer_section]
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum
|
{
TheA { x: i64, y: i64 },
TheB (i64, i32, i32),
}
// This is a special case since it does not have the implicit discriminant field.
enum Univariant {
TheOnlyCase(i64)
}
fn main() {
// In order to avoid endianness trouble all of the following test values consist of a single
// repeated byte. This way each interpretation of the union should look the same, no matter if
// this is a big or little endian machine.
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
let the_a: Box<_> = box ABC::TheA { x: 0, y: 8970181431921507452 };
// 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441
// 0b00010001000100010001000100010001 = 286331153
// 0b0001000100010001 = 4369
// 0b00010001 = 17
let the_b: Box<_> = box ABC::TheB (0, 286331153, 286331153);
let univariant: Box<_> = box Univariant::TheOnlyCase(123234);
zzz(); // #break
}
fn zzz() {()}
|
ABC
|
identifier_name
|
unique-enum.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-tidy-linelength
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *the_a
// gdb-check:$1 = {{RUST$ENUM$DISR = TheA, x = 0, y = 8970181431921507452}, {RUST$ENUM$DISR = TheA, 0, 2088533116, 2088533116}}
// gdb-command:print *the_b
// gdb-check:$2 = {{RUST$ENUM$DISR = TheB, x = 0, y = 1229782938247303441}, {RUST$ENUM$DISR = TheB, 0, 286331153, 286331153}}
// gdb-command:print *univariant
// gdb-check:$3 = {{123234}}
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print *the_a
// lldb-check:[...]$0 = TheA { x: 0, y: 8970181431921507452 }
// lldb-command:print *the_b
// lldb-check:[...]$1 = TheB(0, 286331153, 286331153)
// lldb-command:print *univariant
// lldb-check:[...]$2 = TheOnlyCase(123234)
#![allow(unused_variables)]
#![feature(box_syntax)]
#![omit_gdb_pretty_printer_section]
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum ABC {
TheA { x: i64, y: i64 },
TheB (i64, i32, i32),
}
// This is a special case since it does not have the implicit discriminant field.
enum Univariant {
TheOnlyCase(i64)
}
fn main() {
// In order to avoid endianness trouble all of the following test values consist of a single
// repeated byte. This way each interpretation of the union should look the same, no matter if
// this is a big or little endian machine.
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
let the_a: Box<_> = box ABC::TheA { x: 0, y: 8970181431921507452 };
// 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441
|
// 0b0001000100010001 = 4369
// 0b00010001 = 17
let the_b: Box<_> = box ABC::TheB (0, 286331153, 286331153);
let univariant: Box<_> = box Univariant::TheOnlyCase(123234);
zzz(); // #break
}
fn zzz() {()}
|
// 0b00010001000100010001000100010001 = 286331153
|
random_line_split
|
vertex.rs
|
//! Vertex data structures.
use cgmath::{Point2,Point3,Vector2};
#[cfg(test)]
use std::mem;
use common::color::Color4;
#[derive(Debug, Clone, Copy, PartialEq)]
/// An untextured rendering vertex, with position and color.
pub struct ColoredVertex {
/// The 3-d position of this vertex in world space.
pub position: Point3<f32>,
/// The color to apply to this vertex, in lieu of a texture.
pub color: Color4<f32>,
}
#[test]
fn check_vertex_size() {
assert_eq!(mem::size_of::<ColoredVertex>(), 7*4);
assert_eq!(mem::size_of::<TextureVertex>(), 5*4);
}
impl ColoredVertex {
|
};
[
vtx(min.x, min.y), vtx(max.x, max.y), vtx(min.x, max.y),
vtx(min.x, min.y), vtx(max.x, min.y), vtx(max.x, max.y),
]
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
/// A point in the world with corresponding texture data.
///
/// The texture position is [0, 1].
pub struct TextureVertex {
/// The position of this vertex in the world.
pub world_position: Point3<f32>,
/// The position of this vertex on a texture. The range of valid values
/// in each dimension is [0, 1].
pub texture_position: Vector2<f32>,
}
|
/// Generates two colored triangles, representing a square, at z=0.
/// The bounds of the square is represented by `b`.
pub fn square(min: Point2<f32>, max: Point2<f32>, color: Color4<f32>) -> [ColoredVertex; 6] {
let vtx = |x, y| {
ColoredVertex { position: Point3::new(x, y, 0.0), color: color }
|
random_line_split
|
vertex.rs
|
//! Vertex data structures.
use cgmath::{Point2,Point3,Vector2};
#[cfg(test)]
use std::mem;
use common::color::Color4;
#[derive(Debug, Clone, Copy, PartialEq)]
/// An untextured rendering vertex, with position and color.
pub struct ColoredVertex {
/// The 3-d position of this vertex in world space.
pub position: Point3<f32>,
/// The color to apply to this vertex, in lieu of a texture.
pub color: Color4<f32>,
}
#[test]
fn check_vertex_size() {
assert_eq!(mem::size_of::<ColoredVertex>(), 7*4);
assert_eq!(mem::size_of::<TextureVertex>(), 5*4);
}
impl ColoredVertex {
/// Generates two colored triangles, representing a square, at z=0.
/// The bounds of the square is represented by `b`.
pub fn square(min: Point2<f32>, max: Point2<f32>, color: Color4<f32>) -> [ColoredVertex; 6]
|
}
#[derive(Debug, Clone, Copy, PartialEq)]
/// A point in the world with corresponding texture data.
///
/// The texture position is [0, 1].
pub struct TextureVertex {
/// The position of this vertex in the world.
pub world_position: Point3<f32>,
/// The position of this vertex on a texture. The range of valid values
/// in each dimension is [0, 1].
pub texture_position: Vector2<f32>,
}
|
{
let vtx = |x, y| {
ColoredVertex { position: Point3::new(x, y, 0.0), color: color }
};
[
vtx(min.x, min.y), vtx(max.x, max.y), vtx(min.x, max.y),
vtx(min.x, min.y), vtx(max.x, min.y), vtx(max.x, max.y),
]
}
|
identifier_body
|
vertex.rs
|
//! Vertex data structures.
use cgmath::{Point2,Point3,Vector2};
#[cfg(test)]
use std::mem;
use common::color::Color4;
#[derive(Debug, Clone, Copy, PartialEq)]
/// An untextured rendering vertex, with position and color.
pub struct ColoredVertex {
/// The 3-d position of this vertex in world space.
pub position: Point3<f32>,
/// The color to apply to this vertex, in lieu of a texture.
pub color: Color4<f32>,
}
#[test]
fn check_vertex_size() {
assert_eq!(mem::size_of::<ColoredVertex>(), 7*4);
assert_eq!(mem::size_of::<TextureVertex>(), 5*4);
}
impl ColoredVertex {
/// Generates two colored triangles, representing a square, at z=0.
/// The bounds of the square is represented by `b`.
pub fn square(min: Point2<f32>, max: Point2<f32>, color: Color4<f32>) -> [ColoredVertex; 6] {
let vtx = |x, y| {
ColoredVertex { position: Point3::new(x, y, 0.0), color: color }
};
[
vtx(min.x, min.y), vtx(max.x, max.y), vtx(min.x, max.y),
vtx(min.x, min.y), vtx(max.x, min.y), vtx(max.x, max.y),
]
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
/// A point in the world with corresponding texture data.
///
/// The texture position is [0, 1].
pub struct
|
{
/// The position of this vertex in the world.
pub world_position: Point3<f32>,
/// The position of this vertex on a texture. The range of valid values
/// in each dimension is [0, 1].
pub texture_position: Vector2<f32>,
}
|
TextureVertex
|
identifier_name
|
plugin.js
|
/**
* @license
* Copyright (c) 2016 The {life-parser} Project Authors. All rights reserved.
* This code may only be used under the MIT style license found at http://100dayproject.github.io/LICENSE.txt
* The complete set of authors may be found at http://100dayproject.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://100dayproject.github.io/CONTRIBUTORS.txt
* Code distributed by 100dayproject as part of the life.
*/
"use strict";
CKEDITOR.plugins.add('crab_media', {
icon: 'timestamp',
init: function (editor) {
editor.addCommand('insertMedia', {
exec: function (e) {
var now = new Date();
e.insertHtml('The current date and time is: <em>' + now.toString() + '</em>');
}
|
command: 'insertMedia',
toolbar: 'insert'
});
}
});
|
});
editor.ui.addButton('crab_media', {
label: 'CrabJS: Insert Media',
|
random_line_split
|
geeks_events.js
|
/* This is where are handled "live" events of the application.
*/
var events = require('events')
, URL = require('url')
, io = require('socket.io')
, extend = require('nodetk/utils').extend
, error = require('./utils').error
;
var emitter = exports.emitter = new events.EventEmitter();
emitter.on('CREATE:Geek', function(geek) {
websocket_listener.broadcast({event: "NewGeek", data: geek.json()});
|
emitter.on('UPDATE:Geek', function(ids, data_) {
var data = extend({}, data_);
ids.forEach(function(id) {
data.id = id;
websocket_listener.broadcast({event: "UpdateGeek", data: data});
});
});
// TODO: events to deletion of geeks
// ----------------------------------
emitter.on('DELETE:Geek', function(ids) {
var data = {ids: ids};
websocket_listener.broadcast({event: "DeleteGeek", data: data});
});
emitter.on('REMOVE:Geek', function() {
});
// ----------------------------------
var websocket_listener;
var listen = exports.listen = function(server) {
/* Plug web-socket on given server to send events to clients. */
websocket_listener = io.listen(server, {
resource: "socket.io"
, transports: ['websocket', 'flashsocket', 'htmlfile', 'xhr-multipart', 'xhr-polling']
});
};
// -----------------------------------
// Connect middleware to handle events post:
var post_event = function(req, res) {
/* POST /events */
req.form.complete(function(err, fields) {
if(err) return error(res, err);
var event_name = fields['event']
, event_data = fields['data']
;
if(!event_name || !event_data) {
res.writeHead(400, {}); res.end();
return;
}
data = JSON.parse(event_data);
res.writeHead(200, {}); res.end();
websocket_listener.broadcast({event: event_name, data: data});
});
};
exports.connector = function(req, res, next) {
var url = URL.parse(req.url);
if (req.method == "POST" && url.pathname == "/events") post_event(req, res);
else next();
};
|
});
|
random_line_split
|
observeOn-spec.ts
|
import * as Rx from '../../dist/cjs/Rx';
import { expect } from 'chai';
import marbleTestingSignature = require('../helpers/marble-testing'); // tslint:disable-line:no-require-imports
declare const { asDiagram };
declare const hot: typeof marbleTestingSignature.hot;
declare const expectObservable: typeof marbleTestingSignature.expectObservable;
declare const expectSubscriptions: typeof marbleTestingSignature.expectSubscriptions;
declare const rxTestScheduler: Rx.TestScheduler;
const Observable = Rx.Observable;
/** @test {observeOn} */
describe('Observable.prototype.observeOn', () => {
asDiagram('observeOn(scheduler)')('should observe on specified scheduler', () => {
const e1 = hot('--a--b--|');
const expected = '--a--b--|';
const sub = '^ !';
expectObservable(e1.observeOn(rxTestScheduler)).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(sub);
});
it('should observe after specified delay', () => {
const e1 = hot('--a--b--|');
const expected = '-----a--b--|';
const sub = '^ !';
expectObservable(e1.observeOn(rxTestScheduler, 30)).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(sub);
});
it('should observe when source raises error', () => {
const e1 = hot('--a--#');
const expected = '--a--#';
const sub = '^ !';
expectObservable(e1.observeOn(rxTestScheduler)).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(sub);
});
it('should observe when source is empty', () => {
const e1 = hot('-----|');
const expected = '-----|';
const sub = '^ !';
expectObservable(e1.observeOn(rxTestScheduler)).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(sub);
});
it('should observe when source does not complete', () => {
const e1 = hot('-----');
const expected = '-----';
const sub = '^ ';
expectObservable(e1.observeOn(rxTestScheduler)).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(sub);
});
it('should allow unsubscribing early and explicitly', () => {
const e1 = hot('--a--b--|');
const sub = '^ ! ';
const expected = '--a-- ';
const unsub = ' ! ';
const result = e1.observeOn(rxTestScheduler);
expectObservable(result, unsub).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(sub);
});
|
const sub = '^ ! ';
const expected = '--a-- ';
const unsub = ' ! ';
const result = e1
.mergeMap((x: string) => Observable.of(x))
.observeOn(rxTestScheduler)
.mergeMap((x: string) => Observable.of(x));
expectObservable(result, unsub).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(sub);
});
it('should clean up subscriptions created by async scheduling (prevent memory leaks #2244)', (done) => {
//HACK: Deep introspection to make sure we're cleaning up notifications in scheduling.
// as the architecture changes, this test may become brittle.
const results = [];
// This is to build a scheduled observable with a slightly more stable
// subscription structure, since we're going to hack in to analyze it in this test.
const subscription: any = new Observable(observer => {
let i = 1;
return Rx.Scheduler.asap.schedule(function () {
if (i > 3) {
observer.complete();
} else {
observer.next(i++);
this.schedule();
}
});
})
.observeOn(Rx.Scheduler.asap)
.subscribe(
x => {
const observeOnSubscriber = subscription._subscriptions[0];
expect(observeOnSubscriber._subscriptions.length).to.equal(2); // 1 for the consumer, and one for the notification
expect(observeOnSubscriber._subscriptions[1].state.notification.kind)
.to.equal('N');
expect(observeOnSubscriber._subscriptions[1].state.notification.value)
.to.equal(x);
results.push(x);
},
err => done(err),
() => {
// now that the last nexted value is done, there should only be a complete notification scheduled
const observeOnSubscriber = subscription._subscriptions[0];
expect(observeOnSubscriber._subscriptions.length).to.equal(2); // 1 for the consumer, one for the complete notification
// only this completion notification should remain.
expect(observeOnSubscriber._subscriptions[1].state.notification.kind)
.to.equal('C');
// After completion, the entire _subscriptions list is nulled out anyhow, so we can't test much further than this.
expect(results).to.deep.equal([1, 2, 3]);
done();
}
);
});
});
|
it('should not break unsubscription chains when the result is unsubscribed explicitly', () => {
const e1 = hot('--a--b--|');
|
random_line_split
|
observeOn-spec.ts
|
import * as Rx from '../../dist/cjs/Rx';
import { expect } from 'chai';
import marbleTestingSignature = require('../helpers/marble-testing'); // tslint:disable-line:no-require-imports
declare const { asDiagram };
declare const hot: typeof marbleTestingSignature.hot;
declare const expectObservable: typeof marbleTestingSignature.expectObservable;
declare const expectSubscriptions: typeof marbleTestingSignature.expectSubscriptions;
declare const rxTestScheduler: Rx.TestScheduler;
const Observable = Rx.Observable;
/** @test {observeOn} */
describe('Observable.prototype.observeOn', () => {
asDiagram('observeOn(scheduler)')('should observe on specified scheduler', () => {
const e1 = hot('--a--b--|');
const expected = '--a--b--|';
const sub = '^ !';
expectObservable(e1.observeOn(rxTestScheduler)).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(sub);
});
it('should observe after specified delay', () => {
const e1 = hot('--a--b--|');
const expected = '-----a--b--|';
const sub = '^ !';
expectObservable(e1.observeOn(rxTestScheduler, 30)).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(sub);
});
it('should observe when source raises error', () => {
const e1 = hot('--a--#');
const expected = '--a--#';
const sub = '^ !';
expectObservable(e1.observeOn(rxTestScheduler)).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(sub);
});
it('should observe when source is empty', () => {
const e1 = hot('-----|');
const expected = '-----|';
const sub = '^ !';
expectObservable(e1.observeOn(rxTestScheduler)).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(sub);
});
it('should observe when source does not complete', () => {
const e1 = hot('-----');
const expected = '-----';
const sub = '^ ';
expectObservable(e1.observeOn(rxTestScheduler)).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(sub);
});
it('should allow unsubscribing early and explicitly', () => {
const e1 = hot('--a--b--|');
const sub = '^ ! ';
const expected = '--a-- ';
const unsub = ' ! ';
const result = e1.observeOn(rxTestScheduler);
expectObservable(result, unsub).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(sub);
});
it('should not break unsubscription chains when the result is unsubscribed explicitly', () => {
const e1 = hot('--a--b--|');
const sub = '^ ! ';
const expected = '--a-- ';
const unsub = ' ! ';
const result = e1
.mergeMap((x: string) => Observable.of(x))
.observeOn(rxTestScheduler)
.mergeMap((x: string) => Observable.of(x));
expectObservable(result, unsub).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(sub);
});
it('should clean up subscriptions created by async scheduling (prevent memory leaks #2244)', (done) => {
//HACK: Deep introspection to make sure we're cleaning up notifications in scheduling.
// as the architecture changes, this test may become brittle.
const results = [];
// This is to build a scheduled observable with a slightly more stable
// subscription structure, since we're going to hack in to analyze it in this test.
const subscription: any = new Observable(observer => {
let i = 1;
return Rx.Scheduler.asap.schedule(function () {
if (i > 3)
|
else {
observer.next(i++);
this.schedule();
}
});
})
.observeOn(Rx.Scheduler.asap)
.subscribe(
x => {
const observeOnSubscriber = subscription._subscriptions[0];
expect(observeOnSubscriber._subscriptions.length).to.equal(2); // 1 for the consumer, and one for the notification
expect(observeOnSubscriber._subscriptions[1].state.notification.kind)
.to.equal('N');
expect(observeOnSubscriber._subscriptions[1].state.notification.value)
.to.equal(x);
results.push(x);
},
err => done(err),
() => {
// now that the last nexted value is done, there should only be a complete notification scheduled
const observeOnSubscriber = subscription._subscriptions[0];
expect(observeOnSubscriber._subscriptions.length).to.equal(2); // 1 for the consumer, one for the complete notification
// only this completion notification should remain.
expect(observeOnSubscriber._subscriptions[1].state.notification.kind)
.to.equal('C');
// After completion, the entire _subscriptions list is nulled out anyhow, so we can't test much further than this.
expect(results).to.deep.equal([1, 2, 3]);
done();
}
);
});
});
|
{
observer.complete();
}
|
conditional_block
|
messages_ua.js
|
/*
|
required: "Це поле необхідно заповнити.",
remote: "Будь ласка, введіть правильне значення.",
email: "Будь ласка, введіть коректну адресу електронної пошти.",
url: "Будь ласка, введіть коректний URL.",
date: "Будь ласка, введіть коректну дату.",
dateISO: "Будь ласка, введіть коректну дату у форматі ISO.",
number: "Будь ласка, введіть число.",
digits: "Вводите потрібно лише цифри.",
creditcard: "Будь ласка, введіть правильний номер кредитної карти.",
equalTo: "Будь ласка, введіть таке ж значення ще раз.",
accept: "Будь ласка, виберіть файл з правильним розширенням.",
maxlength: jQuery.validator.format("Будь ласка, введіть не більше {0} символів."),
minlength: jQuery.validator.format("Будь ласка, введіть не менше {0} символів."),
rangelength: jQuery.validator.format("Будь ласка, введіть значення довжиною від {0} до {1} символів."),
range: jQuery.validator.format("Будь ласка, введіть число від {0} до {1}."),
max: jQuery.validator.format("Будь ласка, введіть число, менше або рівно {0}."),
min: jQuery.validator.format("Будь ласка, введіть число, більше або рівно {0}.")
});
|
* Translated default messages for the jQuery validation plugin.
* Localex: UA (Ukrainian)
*/
jQuery.extend(jQuery.validator.messages, {
|
random_line_split
|
addCrewSlot.js
|
$(document).ready(function(){
var nbSlots = 1;
var roles = [];
$('.captain-role option').each(function(){
roles.push([$(this).val(), $(this).text()]);
});
$(".crew-slots").append(generateDivSlot(nbSlots));
$('#add_slot').click(function(){
nbSlots++;
$(".crew-slots").append(generateDivSlot(nbSlots));
})
|
var crewSlot = $(this).parent("div");
$('#' + crewSlot.attr('id')).remove();
renameCrewSlotDiv();
})
function generateDivSlot(nbSlots)
{
var str = "<div id=slot" + nbSlots + " class='crew-slot'>";
str += " <label for='crew-role'>Slot " + nbSlots + " : </label>";
str += " <select name='crew-role[]'>";
$(roles).each(function(){
str += " <option value='" + $(this)[0] + "'>" + $(this)[1] + "</option>";
})
str += " </select>";
if(nbSlots > 1){
str += " <button type='button' class='btn btn-default btn-xs remove-slot'>";
str += " <span class='glyphicon glyphicon-remove' aria-hidden='true'></span>";
str += " </button>";
}
str += "<br />";
str += "</div>";
return str;
}
function renameCrewSlotDiv()
{
var slotNum = 0;
$(".crew-slot").each(function(){
slotNum++;
$(this).attr('id', 'slot' + slotNum);
$(this).find("label").text("Slot " + slotNum + " : ");
})
nbSlots = slotNum;
}
})
|
$(document).on('click', '.remove-slot', function(){
|
random_line_split
|
addCrewSlot.js
|
$(document).ready(function(){
var nbSlots = 1;
var roles = [];
$('.captain-role option').each(function(){
roles.push([$(this).val(), $(this).text()]);
});
$(".crew-slots").append(generateDivSlot(nbSlots));
$('#add_slot').click(function(){
nbSlots++;
$(".crew-slots").append(generateDivSlot(nbSlots));
})
$(document).on('click', '.remove-slot', function(){
var crewSlot = $(this).parent("div");
$('#' + crewSlot.attr('id')).remove();
renameCrewSlotDiv();
})
function generateDivSlot(nbSlots)
|
function renameCrewSlotDiv()
{
var slotNum = 0;
$(".crew-slot").each(function(){
slotNum++;
$(this).attr('id', 'slot' + slotNum);
$(this).find("label").text("Slot " + slotNum + " : ");
})
nbSlots = slotNum;
}
})
|
{
var str = "<div id=slot" + nbSlots + " class='crew-slot'>";
str += " <label for='crew-role'>Slot " + nbSlots + " : </label>";
str += " <select name='crew-role[]'>";
$(roles).each(function(){
str += " <option value='" + $(this)[0] + "'>" + $(this)[1] + "</option>";
})
str += " </select>";
if(nbSlots > 1){
str += " <button type='button' class='btn btn-default btn-xs remove-slot'>";
str += " <span class='glyphicon glyphicon-remove' aria-hidden='true'></span>";
str += " </button>";
}
str += "<br />";
str += "</div>";
return str;
}
|
identifier_body
|
addCrewSlot.js
|
$(document).ready(function(){
var nbSlots = 1;
var roles = [];
$('.captain-role option').each(function(){
roles.push([$(this).val(), $(this).text()]);
});
$(".crew-slots").append(generateDivSlot(nbSlots));
$('#add_slot').click(function(){
nbSlots++;
$(".crew-slots").append(generateDivSlot(nbSlots));
})
$(document).on('click', '.remove-slot', function(){
var crewSlot = $(this).parent("div");
$('#' + crewSlot.attr('id')).remove();
renameCrewSlotDiv();
})
function generateDivSlot(nbSlots)
{
var str = "<div id=slot" + nbSlots + " class='crew-slot'>";
str += " <label for='crew-role'>Slot " + nbSlots + " : </label>";
str += " <select name='crew-role[]'>";
$(roles).each(function(){
str += " <option value='" + $(this)[0] + "'>" + $(this)[1] + "</option>";
})
str += " </select>";
if(nbSlots > 1){
str += " <button type='button' class='btn btn-default btn-xs remove-slot'>";
str += " <span class='glyphicon glyphicon-remove' aria-hidden='true'></span>";
str += " </button>";
}
str += "<br />";
str += "</div>";
return str;
}
function
|
()
{
var slotNum = 0;
$(".crew-slot").each(function(){
slotNum++;
$(this).attr('id', 'slot' + slotNum);
$(this).find("label").text("Slot " + slotNum + " : ");
})
nbSlots = slotNum;
}
})
|
renameCrewSlotDiv
|
identifier_name
|
addCrewSlot.js
|
$(document).ready(function(){
var nbSlots = 1;
var roles = [];
$('.captain-role option').each(function(){
roles.push([$(this).val(), $(this).text()]);
});
$(".crew-slots").append(generateDivSlot(nbSlots));
$('#add_slot').click(function(){
nbSlots++;
$(".crew-slots").append(generateDivSlot(nbSlots));
})
$(document).on('click', '.remove-slot', function(){
var crewSlot = $(this).parent("div");
$('#' + crewSlot.attr('id')).remove();
renameCrewSlotDiv();
})
function generateDivSlot(nbSlots)
{
var str = "<div id=slot" + nbSlots + " class='crew-slot'>";
str += " <label for='crew-role'>Slot " + nbSlots + " : </label>";
str += " <select name='crew-role[]'>";
$(roles).each(function(){
str += " <option value='" + $(this)[0] + "'>" + $(this)[1] + "</option>";
})
str += " </select>";
if(nbSlots > 1)
|
str += "<br />";
str += "</div>";
return str;
}
function renameCrewSlotDiv()
{
var slotNum = 0;
$(".crew-slot").each(function(){
slotNum++;
$(this).attr('id', 'slot' + slotNum);
$(this).find("label").text("Slot " + slotNum + " : ");
})
nbSlots = slotNum;
}
})
|
{
str += " <button type='button' class='btn btn-default btn-xs remove-slot'>";
str += " <span class='glyphicon glyphicon-remove' aria-hidden='true'></span>";
str += " </button>";
}
|
conditional_block
|
db.py
|
# -*- coding: utf-8 -*-
#########################################################################
## This scaffolding model makes your app work on Google App Engine too
## File is released under public domain and you can use without limitations
#########################################################################
## if SSL/HTTPS is properly configured and you want all HTTP requests to
## be redirected to HTTPS, uncomment the line below:
# request.requires_https()
## app configuration made easy. Look inside private/appconfig.ini
from gluon.contrib.appconfig import AppConfig
## once in production, remove reload=True to gain full speed
myconf = AppConfig(reload=True)
if not request.env.web2py_runtime_gae:
## if NOT running on Google App Engine use SQLite or other DB
db = DAL(myconf.get('db.uri'),
pool_size = myconf.get('db.pool_size'),
migrate_enabled = myconf.get('db.migrate'),
check_reserved = ['all'])
else:
## connect to Google BigTable (optional 'google:datastore://namespace')
db = DAL('google:datastore+ndb')
## store sessions and tickets there
session.connect(request, response, db=db)
## or store session in Memcache, Redis, etc.
## from gluon.contrib.memdb import MEMDB
## from google.appengine.api.memcache import Client
## session.connect(request, response, db = MEMDB(Client()))
## by default give a view/generic.extension to all actions from localhost
## none otherwise. a pattern can be 'controller/function.extension'
response.generic_patterns = ['*'] if request.is_local else []
## choose a style for forms
response.formstyle = myconf.get('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other
response.form_label_separator = myconf.get('forms.separator') or ''
## (optional) optimize handling of static files
# response.optimize_css = 'concat,minify,inline'
# response.optimize_js = 'concat,minify,inline'
## (optional) static assets folder versioning
# response.static_version = '0.0.0'
#########################################################################
## Here is sample code if you need for
## - email capabilities
## - authentication (registration, login, logout, ... )
## - authorization (role based authorization)
## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss)
## - old style crud actions
## (more options discussed in gluon/tools.py)
#########################################################################
|
## create all tables needed by auth if not custom tables
auth.define_tables(username=False, signature=False)
## configure email
mail = auth.settings.mailer
mail.settings.server = 'logging' if request.is_local else myconf.get('smtp.server')
mail.settings.sender = myconf.get('smtp.sender')
mail.settings.login = myconf.get('smtp.login')
mail.settings.tls = myconf.get('smtp.tls') or False
mail.settings.ssl = myconf.get('smtp.ssl') or False
## configure auth policy
auth.settings.registration_requires_verification = False
auth.settings.registration_requires_approval = False
auth.settings.reset_password_requires_verification = True
#########################################################################
## Define your tables below (or better in another model file) for example
##
## >>> db.define_table('mytable',Field('myfield','string'))
##
## Fields can be 'string','text','password','integer','double','boolean'
## 'date','time','datetime','blob','upload', 'reference TABLENAME'
## There is an implicit 'id integer autoincrement' field
## Consult manual for more options, validators, etc.
##
## More API examples for controllers:
##
## >>> db.mytable.insert(myfield='value')
## >>> rows=db(db.mytable.myfield=='value').select(db.mytable.ALL)
## >>> for row in rows: print row.id, row.myfield
#########################################################################
## after defining tables, uncomment below to enable auditing
# auth.enable_record_versioning(db)
|
from gluon.tools import Auth, Service, PluginManager
auth = Auth(db, host=myconf.get('host.name'))
service = Service()
plugins = PluginManager()
|
random_line_split
|
db.py
|
# -*- coding: utf-8 -*-
#########################################################################
## This scaffolding model makes your app work on Google App Engine too
## File is released under public domain and you can use without limitations
#########################################################################
## if SSL/HTTPS is properly configured and you want all HTTP requests to
## be redirected to HTTPS, uncomment the line below:
# request.requires_https()
## app configuration made easy. Look inside private/appconfig.ini
from gluon.contrib.appconfig import AppConfig
## once in production, remove reload=True to gain full speed
myconf = AppConfig(reload=True)
if not request.env.web2py_runtime_gae:
## if NOT running on Google App Engine use SQLite or other DB
|
else:
## connect to Google BigTable (optional 'google:datastore://namespace')
db = DAL('google:datastore+ndb')
## store sessions and tickets there
session.connect(request, response, db=db)
## or store session in Memcache, Redis, etc.
## from gluon.contrib.memdb import MEMDB
## from google.appengine.api.memcache import Client
## session.connect(request, response, db = MEMDB(Client()))
## by default give a view/generic.extension to all actions from localhost
## none otherwise. a pattern can be 'controller/function.extension'
response.generic_patterns = ['*'] if request.is_local else []
## choose a style for forms
response.formstyle = myconf.get('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other
response.form_label_separator = myconf.get('forms.separator') or ''
## (optional) optimize handling of static files
# response.optimize_css = 'concat,minify,inline'
# response.optimize_js = 'concat,minify,inline'
## (optional) static assets folder versioning
# response.static_version = '0.0.0'
#########################################################################
## Here is sample code if you need for
## - email capabilities
## - authentication (registration, login, logout, ... )
## - authorization (role based authorization)
## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss)
## - old style crud actions
## (more options discussed in gluon/tools.py)
#########################################################################
from gluon.tools import Auth, Service, PluginManager
auth = Auth(db, host=myconf.get('host.name'))
service = Service()
plugins = PluginManager()
## create all tables needed by auth if not custom tables
auth.define_tables(username=False, signature=False)
## configure email
mail = auth.settings.mailer
mail.settings.server = 'logging' if request.is_local else myconf.get('smtp.server')
mail.settings.sender = myconf.get('smtp.sender')
mail.settings.login = myconf.get('smtp.login')
mail.settings.tls = myconf.get('smtp.tls') or False
mail.settings.ssl = myconf.get('smtp.ssl') or False
## configure auth policy
auth.settings.registration_requires_verification = False
auth.settings.registration_requires_approval = False
auth.settings.reset_password_requires_verification = True
#########################################################################
## Define your tables below (or better in another model file) for example
##
## >>> db.define_table('mytable',Field('myfield','string'))
##
## Fields can be 'string','text','password','integer','double','boolean'
## 'date','time','datetime','blob','upload', 'reference TABLENAME'
## There is an implicit 'id integer autoincrement' field
## Consult manual for more options, validators, etc.
##
## More API examples for controllers:
##
## >>> db.mytable.insert(myfield='value')
## >>> rows=db(db.mytable.myfield=='value').select(db.mytable.ALL)
## >>> for row in rows: print row.id, row.myfield
#########################################################################
## after defining tables, uncomment below to enable auditing
# auth.enable_record_versioning(db)
|
db = DAL(myconf.get('db.uri'),
pool_size = myconf.get('db.pool_size'),
migrate_enabled = myconf.get('db.migrate'),
check_reserved = ['all'])
|
conditional_block
|
coin-block-chain-info.module.ts
|
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { RouterModule } from '@angular/router';
import { BlockchainSharedModule } from '../../shared';
import {
CoinBlockChainInfoService,
CoinBlockChainInfoPopupService,
CoinBlockChainInfoComponent,
CoinBlockChainInfoDetailComponent,
CoinBlockChainInfoDialogComponent,
CoinBlockChainInfoPopupComponent,
CoinBlockChainInfoDeletePopupComponent,
CoinBlockChainInfoDeleteDialogComponent,
coinRoute,
coinPopupRoute,
} from './';
const ENTITY_STATES = [
...coinRoute,
...coinPopupRoute,
];
@NgModule({
imports: [
BlockchainSharedModule,
RouterModule.forRoot(ENTITY_STATES, { useHash: true })
],
declarations: [
CoinBlockChainInfoComponent,
CoinBlockChainInfoDetailComponent,
CoinBlockChainInfoDialogComponent,
CoinBlockChainInfoDeleteDialogComponent,
CoinBlockChainInfoPopupComponent,
CoinBlockChainInfoDeletePopupComponent,
],
entryComponents: [
CoinBlockChainInfoComponent,
CoinBlockChainInfoDialogComponent,
CoinBlockChainInfoPopupComponent,
CoinBlockChainInfoDeleteDialogComponent,
CoinBlockChainInfoDeletePopupComponent,
],
providers: [
CoinBlockChainInfoService,
CoinBlockChainInfoPopupService,
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class
|
{}
|
BlockchainCoinBlockChainInfoModule
|
identifier_name
|
coin-block-chain-info.module.ts
|
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { RouterModule } from '@angular/router';
import { BlockchainSharedModule } from '../../shared';
import {
CoinBlockChainInfoService,
CoinBlockChainInfoPopupService,
CoinBlockChainInfoComponent,
CoinBlockChainInfoDetailComponent,
CoinBlockChainInfoDialogComponent,
CoinBlockChainInfoPopupComponent,
CoinBlockChainInfoDeletePopupComponent,
CoinBlockChainInfoDeleteDialogComponent,
coinRoute,
coinPopupRoute,
} from './';
const ENTITY_STATES = [
...coinRoute,
...coinPopupRoute,
];
@NgModule({
imports: [
BlockchainSharedModule,
RouterModule.forRoot(ENTITY_STATES, { useHash: true })
],
declarations: [
CoinBlockChainInfoComponent,
CoinBlockChainInfoDetailComponent,
CoinBlockChainInfoDialogComponent,
CoinBlockChainInfoDeleteDialogComponent,
CoinBlockChainInfoPopupComponent,
|
CoinBlockChainInfoPopupComponent,
CoinBlockChainInfoDeleteDialogComponent,
CoinBlockChainInfoDeletePopupComponent,
],
providers: [
CoinBlockChainInfoService,
CoinBlockChainInfoPopupService,
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class BlockchainCoinBlockChainInfoModule {}
|
CoinBlockChainInfoDeletePopupComponent,
],
entryComponents: [
CoinBlockChainInfoComponent,
CoinBlockChainInfoDialogComponent,
|
random_line_split
|
webpack.config.prod.js
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: [
'./app/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
],
module: {
|
preLoaders: [
{
test: /\.tsx?$/,
exclude: /(node_modules)/,
loader: 'source-map'
}
],
loaders: [{
test: /\.scss$/,
include: /src/,
loaders: [
'style',
'css',
'autoprefixer?browsers=last 3 versions',
'sass?outputStyle=expanded'
]},{
test: /\.tsx?$/,
loaders: [
'babel',
'ts-loader'
],
include: path.join(__dirname, 'app')
}]
},
resolve: {
extensions: ["", ".webpack.js", ".web.js", ".js", ".ts", ".tsx"]
}
};
|
random_line_split
|
|
distinct_clause.rs
|
use crate::backend::Backend;
use crate::query_builder::*;
use crate::query_dsl::order_dsl::ValidOrderingForDistinct;
use crate::result::QueryResult;
|
#[derive(Debug, Clone, Copy, QueryId)]
pub struct NoDistinctClause;
#[derive(Debug, Clone, Copy, QueryId)]
pub struct DistinctClause;
impl<DB: Backend> QueryFragment<DB> for NoDistinctClause {
fn walk_ast(&self, _: AstPass<DB>) -> QueryResult<()> {
Ok(())
}
}
impl<DB: Backend> QueryFragment<DB> for DistinctClause {
fn walk_ast(&self, mut out: AstPass<DB>) -> QueryResult<()> {
out.push_sql("DISTINCT ");
Ok(())
}
}
impl<O> ValidOrderingForDistinct<NoDistinctClause> for O {}
impl<O> ValidOrderingForDistinct<DistinctClause> for O {}
#[cfg(feature = "postgres")]
pub use crate::pg::DistinctOnClause;
|
random_line_split
|
|
distinct_clause.rs
|
use crate::backend::Backend;
use crate::query_builder::*;
use crate::query_dsl::order_dsl::ValidOrderingForDistinct;
use crate::result::QueryResult;
#[derive(Debug, Clone, Copy, QueryId)]
pub struct
|
;
#[derive(Debug, Clone, Copy, QueryId)]
pub struct DistinctClause;
impl<DB: Backend> QueryFragment<DB> for NoDistinctClause {
fn walk_ast(&self, _: AstPass<DB>) -> QueryResult<()> {
Ok(())
}
}
impl<DB: Backend> QueryFragment<DB> for DistinctClause {
fn walk_ast(&self, mut out: AstPass<DB>) -> QueryResult<()> {
out.push_sql("DISTINCT ");
Ok(())
}
}
impl<O> ValidOrderingForDistinct<NoDistinctClause> for O {}
impl<O> ValidOrderingForDistinct<DistinctClause> for O {}
#[cfg(feature = "postgres")]
pub use crate::pg::DistinctOnClause;
|
NoDistinctClause
|
identifier_name
|
icon-picker.tsx
|
import React from 'react';
import { FieldProps } from 'formik';
import { Text, BorderBox, FilterList } from '@primer/components';
import { iconThemes } from '@renderer/icons';
const IconPicker: React.FC<FieldProps> = ({ field, form }): JSX.Element => {
const currentIconTheme = iconThemes.find(
(iconTheme) => iconTheme.name === field.value,
);
return (
<React.Fragment>
<Text
fontWeight="bold"
fontSize="14px"
as="label"
style={{ display: 'block' }}
mt="3"
mb="2"
>
Icon theme
</Text>
<FilterList>
{iconThemes.map(({ name, displayName, icons }) => (
<FilterList.Item
key={name}
mr="3"
selected={name === field.value}
|
onClick={(): void => form.setFieldValue('iconTheme', name)}
>
<img
src={icons.contributed}
style={{
height: 16,
marginRight: 10,
position: 'relative',
top: 2,
}}
/>
{displayName}
</FilterList.Item>
))}
</FilterList>
<BorderBox mr="3" mt="3" bg="gray.0">
<table style={{ width: '100%' }}>
<tr>
<td style={{ textAlign: 'center' }}>
<Text fontWeight="bold" fontSize="14px">
Pending
</Text>
</td>
<td style={{ textAlign: 'center' }}>
<Text fontWeight="bold" fontSize="14px">
Contributed
</Text>
</td>
<td style={{ textAlign: 'center' }}>
<Text fontWeight="bold" fontSize="14px">
Streaking
</Text>
</td>
</tr>
<tr>
<td style={{ textAlign: 'center' }}>
<img
src={currentIconTheme.icons.pending}
style={{ height: 16 }}
/>
</td>
<td style={{ textAlign: 'center' }}>
<img
src={currentIconTheme.icons.contributed}
style={{ height: 16 }}
/>
</td>
<td style={{ textAlign: 'center' }}>
<img
src={currentIconTheme.icons.streaking}
style={{ height: 16 }}
/>
</td>
</tr>
</table>
</BorderBox>
</React.Fragment>
);
};
export default IconPicker;
|
random_line_split
|
|
chunk.rs
|
use std::io;
use std::fmt;
use std::ops::{Deref, DerefMut};
use ::aux::ReadExt;
static NAME_LENGTH: u32 = 8;
pub struct Root<R> {
pub name: String,
input: R,
buffer: Vec<u8>,
position: u32,
}
impl<R: io::Seek> Root<R> {
pub fn tell(&mut self) -> u32 {
self.input.seek(io::SeekFrom::Current(0)).unwrap() as u32
}
}
impl<R: io::Read> Root<R> {
pub fn new(name: String, input: R) -> Root<R> {
Root {
name: name,
input: input,
buffer: Vec::new(),
position: 0,
}
}
pub fn get_pos(&self) -> u32 {
self.position
}
fn skip(&mut self, num: u32) {
self.read_bytes(num);
}
pub fn read_bytes(&mut self, num: u32) -> &[u8] {
self.position += num;
self.buffer.clear();
for _ in (0.. num) {
let b = self.input.read_u8().unwrap();
self.buffer.push(b);
}
&self.buffer
}
pub fn read_u8(&mut self) -> u8 {
self.position += 1;
self.input.read_u8().unwrap()
}
pub fn read_u32(&mut self) -> u32 {
self.position += 4;
self.input.read_u32().unwrap()
}
pub fn read_bool(&mut self) -> bool {
self.position += 1;
self.input.read_u8().unwrap() != 0
}
pub fn read_str(&mut self) -> &str {
use std::str::from_utf8;
let size = self.input.read_u8().unwrap() as u32;
self.position += 1;
let buf = self.read_bytes(size);
from_utf8(buf).unwrap()
}
pub fn enter<'b>(&'b mut self) -> Chunk<'b, R> {
let name = {
let raw = self.read_bytes(NAME_LENGTH);
let buf = match raw.iter().position(|b| *b == 0) {
Some(p) => &raw[..p],
None => raw,
};
String::from_utf8_lossy(buf)
.into_owned()
};
debug!("Entering chunk {}", name);
let size = self.read_u32();
Chunk {
name: name,
size: size,
end_pos: self.position + size,
root: self,
}
}
}
pub struct Chunk<'a, R: io::Read + 'a> {
name: String,
size: u32,
end_pos: u32,
root: &'a mut Root<R>,
}
impl<'a, R: io::Read> fmt::Display for Chunk<'a, R> {
fn fmt(&self, fm: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(fm, "Chunk({}, {} left)", self.name, self.size)
}
}
impl<'a, R: io::Read> Chunk<'a, R> {
pub fn get_name(&self) -> &str {
&self.name
}
pub fn has_more(&self)-> bool
|
pub fn ignore(self) {
let left = self.end_pos - self.root.get_pos();
self.root.skip(left)
}
}
impl<'a, R: io::Read> Drop for Chunk<'a, R> {
fn drop(&mut self) {
debug!("Leaving chunk");
assert!(!self.has_more())
}
}
impl<'a, R: io::Read> Deref for Chunk<'a, R> {
type Target = Root<R>;
fn deref(&self) -> &Root<R> {
self.root
}
}
impl<'a, R: io::Read> DerefMut for Chunk<'a, R> {
fn deref_mut(&mut self) -> &mut Root<R> {
self.root
}
}
|
{
self.root.get_pos() < self.end_pos
}
|
identifier_body
|
chunk.rs
|
use std::io;
use std::fmt;
use std::ops::{Deref, DerefMut};
use ::aux::ReadExt;
static NAME_LENGTH: u32 = 8;
pub struct Root<R> {
pub name: String,
input: R,
buffer: Vec<u8>,
position: u32,
}
impl<R: io::Seek> Root<R> {
pub fn tell(&mut self) -> u32 {
self.input.seek(io::SeekFrom::Current(0)).unwrap() as u32
}
}
impl<R: io::Read> Root<R> {
pub fn new(name: String, input: R) -> Root<R> {
Root {
name: name,
input: input,
buffer: Vec::new(),
position: 0,
}
}
pub fn get_pos(&self) -> u32 {
self.position
}
fn skip(&mut self, num: u32) {
self.read_bytes(num);
}
pub fn read_bytes(&mut self, num: u32) -> &[u8] {
self.position += num;
self.buffer.clear();
for _ in (0.. num) {
let b = self.input.read_u8().unwrap();
self.buffer.push(b);
}
&self.buffer
}
pub fn read_u8(&mut self) -> u8 {
self.position += 1;
self.input.read_u8().unwrap()
}
pub fn read_u32(&mut self) -> u32 {
self.position += 4;
self.input.read_u32().unwrap()
}
pub fn read_bool(&mut self) -> bool {
self.position += 1;
self.input.read_u8().unwrap() != 0
}
pub fn read_str(&mut self) -> &str {
use std::str::from_utf8;
let size = self.input.read_u8().unwrap() as u32;
self.position += 1;
let buf = self.read_bytes(size);
from_utf8(buf).unwrap()
}
pub fn enter<'b>(&'b mut self) -> Chunk<'b, R> {
let name = {
let raw = self.read_bytes(NAME_LENGTH);
let buf = match raw.iter().position(|b| *b == 0) {
Some(p) => &raw[..p],
None => raw,
};
String::from_utf8_lossy(buf)
.into_owned()
};
debug!("Entering chunk {}", name);
let size = self.read_u32();
Chunk {
name: name,
size: size,
end_pos: self.position + size,
root: self,
}
}
}
pub struct Chunk<'a, R: io::Read + 'a> {
name: String,
size: u32,
end_pos: u32,
root: &'a mut Root<R>,
}
impl<'a, R: io::Read> fmt::Display for Chunk<'a, R> {
fn fmt(&self, fm: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(fm, "Chunk({}, {} left)", self.name, self.size)
}
}
impl<'a, R: io::Read> Chunk<'a, R> {
pub fn get_name(&self) -> &str {
&self.name
}
pub fn has_more(&self)-> bool {
self.root.get_pos() < self.end_pos
}
pub fn ignore(self) {
let left = self.end_pos - self.root.get_pos();
self.root.skip(left)
}
}
impl<'a, R: io::Read> Drop for Chunk<'a, R> {
fn drop(&mut self) {
debug!("Leaving chunk");
assert!(!self.has_more())
}
}
impl<'a, R: io::Read> Deref for Chunk<'a, R> {
type Target = Root<R>;
fn deref(&self) -> &Root<R> {
self.root
}
|
}
}
|
}
impl<'a, R: io::Read> DerefMut for Chunk<'a, R> {
fn deref_mut(&mut self) -> &mut Root<R> {
self.root
|
random_line_split
|
chunk.rs
|
use std::io;
use std::fmt;
use std::ops::{Deref, DerefMut};
use ::aux::ReadExt;
static NAME_LENGTH: u32 = 8;
pub struct Root<R> {
pub name: String,
input: R,
buffer: Vec<u8>,
position: u32,
}
impl<R: io::Seek> Root<R> {
pub fn tell(&mut self) -> u32 {
self.input.seek(io::SeekFrom::Current(0)).unwrap() as u32
}
}
impl<R: io::Read> Root<R> {
pub fn new(name: String, input: R) -> Root<R> {
Root {
name: name,
input: input,
buffer: Vec::new(),
position: 0,
}
}
pub fn get_pos(&self) -> u32 {
self.position
}
fn skip(&mut self, num: u32) {
self.read_bytes(num);
}
pub fn read_bytes(&mut self, num: u32) -> &[u8] {
self.position += num;
self.buffer.clear();
for _ in (0.. num) {
let b = self.input.read_u8().unwrap();
self.buffer.push(b);
}
&self.buffer
}
pub fn
|
(&mut self) -> u8 {
self.position += 1;
self.input.read_u8().unwrap()
}
pub fn read_u32(&mut self) -> u32 {
self.position += 4;
self.input.read_u32().unwrap()
}
pub fn read_bool(&mut self) -> bool {
self.position += 1;
self.input.read_u8().unwrap() != 0
}
pub fn read_str(&mut self) -> &str {
use std::str::from_utf8;
let size = self.input.read_u8().unwrap() as u32;
self.position += 1;
let buf = self.read_bytes(size);
from_utf8(buf).unwrap()
}
pub fn enter<'b>(&'b mut self) -> Chunk<'b, R> {
let name = {
let raw = self.read_bytes(NAME_LENGTH);
let buf = match raw.iter().position(|b| *b == 0) {
Some(p) => &raw[..p],
None => raw,
};
String::from_utf8_lossy(buf)
.into_owned()
};
debug!("Entering chunk {}", name);
let size = self.read_u32();
Chunk {
name: name,
size: size,
end_pos: self.position + size,
root: self,
}
}
}
pub struct Chunk<'a, R: io::Read + 'a> {
name: String,
size: u32,
end_pos: u32,
root: &'a mut Root<R>,
}
impl<'a, R: io::Read> fmt::Display for Chunk<'a, R> {
fn fmt(&self, fm: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(fm, "Chunk({}, {} left)", self.name, self.size)
}
}
impl<'a, R: io::Read> Chunk<'a, R> {
pub fn get_name(&self) -> &str {
&self.name
}
pub fn has_more(&self)-> bool {
self.root.get_pos() < self.end_pos
}
pub fn ignore(self) {
let left = self.end_pos - self.root.get_pos();
self.root.skip(left)
}
}
impl<'a, R: io::Read> Drop for Chunk<'a, R> {
fn drop(&mut self) {
debug!("Leaving chunk");
assert!(!self.has_more())
}
}
impl<'a, R: io::Read> Deref for Chunk<'a, R> {
type Target = Root<R>;
fn deref(&self) -> &Root<R> {
self.root
}
}
impl<'a, R: io::Read> DerefMut for Chunk<'a, R> {
fn deref_mut(&mut self) -> &mut Root<R> {
self.root
}
}
|
read_u8
|
identifier_name
|
urls.py
|
"""effcalculator URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.conf.urls import url, include
from django.contrib.auth import views as auth_views
|
url(r'^', include('frontend.urls'))
]
|
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include('api.urls')),
|
random_line_split
|
do.ts
|
import Operator from '../Operator';
import Observer from '../Observer';
import Subscriber from '../Subscriber';
import noop from '../util/noop';
import tryCatch from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
import bindCallback from '../util/bindCallback';
export default function _do<T>(next?: (x: T) => void, error?: (e: any) => void, complete?: () => void) {
return this.lift(new DoOperator(next || noop, error || noop, complete || noop));
}
class DoOperator<T, R> implements Operator<T, R> {
next: (x: T) => void;
error: (e: any) => void;
complete: () => void;
constructor(next: (x: T) => void, error: (e: any) => void, complete: () => void) {
this.next = next;
this.error = error;
this.complete = complete;
}
call(subscriber: Subscriber<T>): Subscriber<T> {
return new DoSubscriber(subscriber, this.next, this.error, this.complete);
}
}
class DoSubscriber<T> extends Subscriber<T> {
__next: (x: T) => void;
__error: (e: any) => void;
__complete: () => void;
|
(destination: Observer<T>, next: (x: T) => void, error: (e: any) => void, complete: () => void) {
super(destination);
this.__next = next;
this.__error = error;
this.__complete = complete;
}
_next(x) {
const result = tryCatch(this.__next)(x);
if (result === errorObject) {
this.destination.error(errorObject.e);
} else {
this.destination.next(x);
}
}
_error(e) {
const result = tryCatch(this.__error)(e);
if (result === errorObject) {
this.destination.error(errorObject.e);
} else {
this.destination.error(e);
}
}
_complete() {
const result = tryCatch(this.__complete)();
if (result === errorObject) {
this.destination.error(errorObject.e);
} else {
this.destination.complete();
}
}
}
|
constructor
|
identifier_name
|
do.ts
|
import Operator from '../Operator';
import Observer from '../Observer';
|
import {errorObject} from '../util/errorObject';
import bindCallback from '../util/bindCallback';
export default function _do<T>(next?: (x: T) => void, error?: (e: any) => void, complete?: () => void) {
return this.lift(new DoOperator(next || noop, error || noop, complete || noop));
}
class DoOperator<T, R> implements Operator<T, R> {
next: (x: T) => void;
error: (e: any) => void;
complete: () => void;
constructor(next: (x: T) => void, error: (e: any) => void, complete: () => void) {
this.next = next;
this.error = error;
this.complete = complete;
}
call(subscriber: Subscriber<T>): Subscriber<T> {
return new DoSubscriber(subscriber, this.next, this.error, this.complete);
}
}
class DoSubscriber<T> extends Subscriber<T> {
__next: (x: T) => void;
__error: (e: any) => void;
__complete: () => void;
constructor(destination: Observer<T>, next: (x: T) => void, error: (e: any) => void, complete: () => void) {
super(destination);
this.__next = next;
this.__error = error;
this.__complete = complete;
}
_next(x) {
const result = tryCatch(this.__next)(x);
if (result === errorObject) {
this.destination.error(errorObject.e);
} else {
this.destination.next(x);
}
}
_error(e) {
const result = tryCatch(this.__error)(e);
if (result === errorObject) {
this.destination.error(errorObject.e);
} else {
this.destination.error(e);
}
}
_complete() {
const result = tryCatch(this.__complete)();
if (result === errorObject) {
this.destination.error(errorObject.e);
} else {
this.destination.complete();
}
}
}
|
import Subscriber from '../Subscriber';
import noop from '../util/noop';
import tryCatch from '../util/tryCatch';
|
random_line_split
|
do.ts
|
import Operator from '../Operator';
import Observer from '../Observer';
import Subscriber from '../Subscriber';
import noop from '../util/noop';
import tryCatch from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
import bindCallback from '../util/bindCallback';
export default function _do<T>(next?: (x: T) => void, error?: (e: any) => void, complete?: () => void) {
return this.lift(new DoOperator(next || noop, error || noop, complete || noop));
}
class DoOperator<T, R> implements Operator<T, R> {
next: (x: T) => void;
error: (e: any) => void;
complete: () => void;
constructor(next: (x: T) => void, error: (e: any) => void, complete: () => void) {
this.next = next;
this.error = error;
this.complete = complete;
}
call(subscriber: Subscriber<T>): Subscriber<T> {
return new DoSubscriber(subscriber, this.next, this.error, this.complete);
}
}
class DoSubscriber<T> extends Subscriber<T> {
__next: (x: T) => void;
__error: (e: any) => void;
__complete: () => void;
constructor(destination: Observer<T>, next: (x: T) => void, error: (e: any) => void, complete: () => void)
|
_next(x) {
const result = tryCatch(this.__next)(x);
if (result === errorObject) {
this.destination.error(errorObject.e);
} else {
this.destination.next(x);
}
}
_error(e) {
const result = tryCatch(this.__error)(e);
if (result === errorObject) {
this.destination.error(errorObject.e);
} else {
this.destination.error(e);
}
}
_complete() {
const result = tryCatch(this.__complete)();
if (result === errorObject) {
this.destination.error(errorObject.e);
} else {
this.destination.complete();
}
}
}
|
{
super(destination);
this.__next = next;
this.__error = error;
this.__complete = complete;
}
|
identifier_body
|
do.ts
|
import Operator from '../Operator';
import Observer from '../Observer';
import Subscriber from '../Subscriber';
import noop from '../util/noop';
import tryCatch from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
import bindCallback from '../util/bindCallback';
export default function _do<T>(next?: (x: T) => void, error?: (e: any) => void, complete?: () => void) {
return this.lift(new DoOperator(next || noop, error || noop, complete || noop));
}
class DoOperator<T, R> implements Operator<T, R> {
next: (x: T) => void;
error: (e: any) => void;
complete: () => void;
constructor(next: (x: T) => void, error: (e: any) => void, complete: () => void) {
this.next = next;
this.error = error;
this.complete = complete;
}
call(subscriber: Subscriber<T>): Subscriber<T> {
return new DoSubscriber(subscriber, this.next, this.error, this.complete);
}
}
class DoSubscriber<T> extends Subscriber<T> {
__next: (x: T) => void;
__error: (e: any) => void;
__complete: () => void;
constructor(destination: Observer<T>, next: (x: T) => void, error: (e: any) => void, complete: () => void) {
super(destination);
this.__next = next;
this.__error = error;
this.__complete = complete;
}
_next(x) {
const result = tryCatch(this.__next)(x);
if (result === errorObject) {
this.destination.error(errorObject.e);
} else
|
}
_error(e) {
const result = tryCatch(this.__error)(e);
if (result === errorObject) {
this.destination.error(errorObject.e);
} else {
this.destination.error(e);
}
}
_complete() {
const result = tryCatch(this.__complete)();
if (result === errorObject) {
this.destination.error(errorObject.e);
} else {
this.destination.complete();
}
}
}
|
{
this.destination.next(x);
}
|
conditional_block
|
xwrapper.rs
|
use libc::*;
use std::ffi::{CString, CStr};
use std::ptr;
use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints };
use x11::xrender::{ XRenderCreatePicture, XRenderFindVisualFormat, XRenderPictureAttributes, XRenderQueryExtension };
use x11::xlib::{ _XDisplay, XDefaultVisual };
//
// X Definitions
//
static XNone: c_ulong = 0;
static CPSubWindowMode: c_ulong = 1 << 8;
//
// Xlib Types
//
#[repr(C)]
pub struct struct__XWMHints {
pub flags: c_long,
pub input: c_int,
pub initial_state: c_int,
pub icon_pixmap: Pixmap,
pub icon_window: Window,
pub icon_x: c_int,
pub icon_y: c_int,
pub icon_mask: Pixmap,
pub window_group: XID,
}
pub type XWMHints = struct__XWMHints;
//
// Xlib & X Extensions Linking
//
#[link(name = "X11")]
extern {
fn Xutf8SetWMProperties(display: *mut Display, window: Window, window_name: *mut c_char,
icon_name: *mut c_char, argv: *mut *mut c_char, argc: i32,
normal_hints: *mut XSizeHints, wm_hints: *mut XWMHints,
class_hints: *mut XClassHint);
}
#[link(name = "Xcomposite")]
extern {
fn XCompositeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
#[link(name = "Xdamage")]
extern {
fn XDamageQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
#[link(name = "Xext")]
extern {
fn XShapeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
#[link(name = "Xfixes")]
extern {
fn XFixesQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
//
// XServer Struct
//
pub struct XServer {
display: *mut Display,
root: Window
}
impl XServer {
pub fn new() -> XServer {
unsafe {
let display = XOpenDisplay(ptr::null_mut());
if display.is_null() {
panic!("Could not open display!");
}
let screen = XDefaultScreenOfDisplay(display);
let root = XRootWindowOfScreen(screen);
XServer {
display: display,
root: root
}
}
}
}
pub fn query_extension(xserver: &XServer, name: &str) {
let mut event_base = &mut 0;
let mut error_base = &mut 0;
unsafe {
match name {
"Xcomposite" => if XCompositeQueryExtension(xserver.display, event_base, error_base) == 0 {
panic!("No XComposite extension!");
},
"Xdamage" => if XDamageQueryExtension(xserver.display, event_base, error_base) == 0 {
panic!("No XDamage extension!");
},
"Xfixes" => if XFixesQueryExtension(xserver.display, event_base, error_base) == 0 {
panic!("No XFixes extension!");
},
"Xrender" => { let have_xrender = XRenderQueryExtension(xserver.display as *mut _XDisplay,
event_base, error_base);
if have_xrender == 0 {
panic!("No XRender extension!");
}
},
"Xshape" => if XShapeQueryExtension(xserver.display, event_base, error_base) == 0 {
panic!("No XShape extension!");
},
_ => panic!(format!("Don't know how to query for {} extension", name)),
}
}
}
pub struct WindowSettings {
pub opacity: XID,
pub type_atom: XID,
pub is_desktop: XID,
pub is_dock: XID,
pub is_toolbar: XID,
pub is_menu: XID,
pub is_util: XID,
pub is_splash: XID,
pub is_dialog: XID,
pub is_dropdown: XID,
pub is_popup: XID,
pub is_tooltip: XID,
pub is_notification: XID,
pub is_combo: XID,
pub is_dnd: XID,
pub is_normal: XID,
}
pub fn find_window_settings(xserver: &XServer) -> WindowSettings
|
pub fn intern_atom(xserver: &XServer, name: &str) -> XID {
return unsafe { XInternAtom(xserver.display, name.as_ptr() as *mut c_char, 0) };
}
pub fn null_xrender_picture_attributes() -> XRenderPictureAttributes {
return XRenderPictureAttributes {
repeat: 0,
alpha_map: XNone,
alpha_x_origin: 0,
alpha_y_origin: 0,
clip_x_origin: 0,
clip_y_origin: 0,
clip_mask: XNone,
graphics_exposures: 0,
subwindow_mode: 0,
poly_edge: 0,
poly_mode: 0,
dither: XNone,
component_alpha: 0,
}
}
//
// Side-Effecting Stuff
//
pub fn register_compositing_window_manager(xserver: &XServer, wm_name: &CStr) -> bool {
let screen = unsafe { XDefaultScreen(xserver.display) };
let reg_atom_name = CString::new(format!("_NET_WM_CM_S{}", screen)).unwrap();
let reg_atom = unsafe { XInternAtom(xserver.display, reg_atom_name.as_ptr() as *mut c_char, 0) };
let extant_window = unsafe { XGetSelectionOwner(xserver.display, reg_atom) };
if extant_window != XNone {
return false;
}
unsafe {
let our_window = XCreateSimpleWindow(xserver.display, xserver.root,
0, 0, 1, 1, 0, XNone, XNone);
Xutf8SetWMProperties(xserver.display, our_window,
wm_name.as_ptr() as *mut c_char, wm_name.as_ptr() as *mut c_char,
ptr::null_mut(), 0, ptr::null_mut(), ptr::null_mut(), ptr::null_mut());
XSetSelectionOwner(xserver.display, reg_atom, our_window, 0);
};
return true;
}
pub fn create_root_picture(xserver: &XServer, attributes: &mut XRenderPictureAttributes) -> c_ulong {
let display = xserver.display;
let xr_display = xserver.display as *mut _XDisplay;
let format = unsafe {
XRenderFindVisualFormat(xr_display, XDefaultVisual(xr_display, XDefaultScreen(display)))
};
return unsafe {
XRenderCreatePicture( xr_display
, xserver.root
, format
, CPSubWindowMode
, attributes
)
};
}
|
{
WindowSettings {
opacity: intern_atom(xserver, "_NET_WM_WINDOW_OPACITY"),
type_atom: intern_atom(xserver, "_NET_WM_WINDOW_TYPE"),
is_desktop: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DESKTOP"),
is_dock: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DOCK"),
is_toolbar: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLBAR"),
is_menu: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_MENU"),
is_util: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_UTILITY"),
is_splash: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_SPLASH"),
is_dialog: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DIALOG"),
is_dropdown: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DROPDOWN"),
is_popup: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_POPUP"),
is_tooltip: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLTIP"),
is_notification: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NOTIFICATION"),
is_combo: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_COMBO"),
is_dnd: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DND"),
is_normal: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NORMAL"),
}
}
|
identifier_body
|
xwrapper.rs
|
use libc::*;
use std::ffi::{CString, CStr};
use std::ptr;
use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints };
use x11::xrender::{ XRenderCreatePicture, XRenderFindVisualFormat, XRenderPictureAttributes, XRenderQueryExtension };
use x11::xlib::{ _XDisplay, XDefaultVisual };
//
// X Definitions
//
static XNone: c_ulong = 0;
static CPSubWindowMode: c_ulong = 1 << 8;
//
// Xlib Types
//
#[repr(C)]
pub struct struct__XWMHints {
pub flags: c_long,
pub input: c_int,
pub initial_state: c_int,
pub icon_pixmap: Pixmap,
pub icon_window: Window,
pub icon_x: c_int,
pub icon_y: c_int,
pub icon_mask: Pixmap,
pub window_group: XID,
}
pub type XWMHints = struct__XWMHints;
//
// Xlib & X Extensions Linking
//
#[link(name = "X11")]
extern {
fn Xutf8SetWMProperties(display: *mut Display, window: Window, window_name: *mut c_char,
icon_name: *mut c_char, argv: *mut *mut c_char, argc: i32,
normal_hints: *mut XSizeHints, wm_hints: *mut XWMHints,
class_hints: *mut XClassHint);
}
#[link(name = "Xcomposite")]
extern {
fn XCompositeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
#[link(name = "Xdamage")]
extern {
fn XDamageQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
#[link(name = "Xext")]
extern {
fn XShapeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
#[link(name = "Xfixes")]
extern {
fn XFixesQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
//
// XServer Struct
//
pub struct XServer {
display: *mut Display,
root: Window
}
impl XServer {
pub fn new() -> XServer {
unsafe {
let display = XOpenDisplay(ptr::null_mut());
if display.is_null() {
panic!("Could not open display!");
}
let screen = XDefaultScreenOfDisplay(display);
let root = XRootWindowOfScreen(screen);
XServer {
display: display,
root: root
}
}
}
}
pub fn query_extension(xserver: &XServer, name: &str) {
let mut event_base = &mut 0;
let mut error_base = &mut 0;
unsafe {
match name {
"Xcomposite" => if XCompositeQueryExtension(xserver.display, event_base, error_base) == 0 {
panic!("No XComposite extension!");
},
"Xdamage" => if XDamageQueryExtension(xserver.display, event_base, error_base) == 0 {
panic!("No XDamage extension!");
},
"Xfixes" => if XFixesQueryExtension(xserver.display, event_base, error_base) == 0 {
panic!("No XFixes extension!");
},
"Xrender" => { let have_xrender = XRenderQueryExtension(xserver.display as *mut _XDisplay,
event_base, error_base);
if have_xrender == 0 {
panic!("No XRender extension!");
}
},
"Xshape" => if XShapeQueryExtension(xserver.display, event_base, error_base) == 0 {
panic!("No XShape extension!");
},
_ => panic!(format!("Don't know how to query for {} extension", name)),
}
}
}
pub struct WindowSettings {
pub opacity: XID,
pub type_atom: XID,
pub is_desktop: XID,
pub is_dock: XID,
pub is_toolbar: XID,
pub is_menu: XID,
pub is_util: XID,
pub is_splash: XID,
pub is_dialog: XID,
pub is_dropdown: XID,
pub is_popup: XID,
pub is_tooltip: XID,
pub is_notification: XID,
pub is_combo: XID,
pub is_dnd: XID,
pub is_normal: XID,
}
pub fn
|
(xserver: &XServer) -> WindowSettings {
WindowSettings {
opacity: intern_atom(xserver, "_NET_WM_WINDOW_OPACITY"),
type_atom: intern_atom(xserver, "_NET_WM_WINDOW_TYPE"),
is_desktop: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DESKTOP"),
is_dock: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DOCK"),
is_toolbar: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLBAR"),
is_menu: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_MENU"),
is_util: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_UTILITY"),
is_splash: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_SPLASH"),
is_dialog: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DIALOG"),
is_dropdown: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DROPDOWN"),
is_popup: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_POPUP"),
is_tooltip: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLTIP"),
is_notification: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NOTIFICATION"),
is_combo: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_COMBO"),
is_dnd: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DND"),
is_normal: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NORMAL"),
}
}
pub fn intern_atom(xserver: &XServer, name: &str) -> XID {
return unsafe { XInternAtom(xserver.display, name.as_ptr() as *mut c_char, 0) };
}
pub fn null_xrender_picture_attributes() -> XRenderPictureAttributes {
return XRenderPictureAttributes {
repeat: 0,
alpha_map: XNone,
alpha_x_origin: 0,
alpha_y_origin: 0,
clip_x_origin: 0,
clip_y_origin: 0,
clip_mask: XNone,
graphics_exposures: 0,
subwindow_mode: 0,
poly_edge: 0,
poly_mode: 0,
dither: XNone,
component_alpha: 0,
}
}
//
// Side-Effecting Stuff
//
pub fn register_compositing_window_manager(xserver: &XServer, wm_name: &CStr) -> bool {
let screen = unsafe { XDefaultScreen(xserver.display) };
let reg_atom_name = CString::new(format!("_NET_WM_CM_S{}", screen)).unwrap();
let reg_atom = unsafe { XInternAtom(xserver.display, reg_atom_name.as_ptr() as *mut c_char, 0) };
let extant_window = unsafe { XGetSelectionOwner(xserver.display, reg_atom) };
if extant_window != XNone {
return false;
}
unsafe {
let our_window = XCreateSimpleWindow(xserver.display, xserver.root,
0, 0, 1, 1, 0, XNone, XNone);
Xutf8SetWMProperties(xserver.display, our_window,
wm_name.as_ptr() as *mut c_char, wm_name.as_ptr() as *mut c_char,
ptr::null_mut(), 0, ptr::null_mut(), ptr::null_mut(), ptr::null_mut());
XSetSelectionOwner(xserver.display, reg_atom, our_window, 0);
};
return true;
}
pub fn create_root_picture(xserver: &XServer, attributes: &mut XRenderPictureAttributes) -> c_ulong {
let display = xserver.display;
let xr_display = xserver.display as *mut _XDisplay;
let format = unsafe {
XRenderFindVisualFormat(xr_display, XDefaultVisual(xr_display, XDefaultScreen(display)))
};
return unsafe {
XRenderCreatePicture( xr_display
, xserver.root
, format
, CPSubWindowMode
, attributes
)
};
}
|
find_window_settings
|
identifier_name
|
xwrapper.rs
|
use libc::*;
use std::ffi::{CString, CStr};
use std::ptr;
use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints };
use x11::xrender::{ XRenderCreatePicture, XRenderFindVisualFormat, XRenderPictureAttributes, XRenderQueryExtension };
use x11::xlib::{ _XDisplay, XDefaultVisual };
//
// X Definitions
//
static XNone: c_ulong = 0;
static CPSubWindowMode: c_ulong = 1 << 8;
//
// Xlib Types
//
#[repr(C)]
pub struct struct__XWMHints {
pub flags: c_long,
pub input: c_int,
pub initial_state: c_int,
pub icon_pixmap: Pixmap,
pub icon_window: Window,
pub icon_x: c_int,
pub icon_y: c_int,
pub icon_mask: Pixmap,
pub window_group: XID,
}
pub type XWMHints = struct__XWMHints;
//
// Xlib & X Extensions Linking
//
#[link(name = "X11")]
extern {
fn Xutf8SetWMProperties(display: *mut Display, window: Window, window_name: *mut c_char,
icon_name: *mut c_char, argv: *mut *mut c_char, argc: i32,
normal_hints: *mut XSizeHints, wm_hints: *mut XWMHints,
class_hints: *mut XClassHint);
}
#[link(name = "Xcomposite")]
extern {
fn XCompositeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
#[link(name = "Xdamage")]
extern {
fn XDamageQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
#[link(name = "Xext")]
extern {
fn XShapeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
#[link(name = "Xfixes")]
extern {
fn XFixesQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
//
// XServer Struct
//
pub struct XServer {
display: *mut Display,
root: Window
}
impl XServer {
pub fn new() -> XServer {
unsafe {
let display = XOpenDisplay(ptr::null_mut());
if display.is_null() {
panic!("Could not open display!");
}
let screen = XDefaultScreenOfDisplay(display);
let root = XRootWindowOfScreen(screen);
XServer {
display: display,
root: root
}
}
}
}
pub fn query_extension(xserver: &XServer, name: &str) {
let mut event_base = &mut 0;
let mut error_base = &mut 0;
unsafe {
match name {
"Xcomposite" => if XCompositeQueryExtension(xserver.display, event_base, error_base) == 0 {
panic!("No XComposite extension!");
},
"Xdamage" => if XDamageQueryExtension(xserver.display, event_base, error_base) == 0 {
panic!("No XDamage extension!");
},
"Xfixes" => if XFixesQueryExtension(xserver.display, event_base, error_base) == 0 {
panic!("No XFixes extension!");
},
"Xrender" => { let have_xrender = XRenderQueryExtension(xserver.display as *mut _XDisplay,
event_base, error_base);
if have_xrender == 0 {
panic!("No XRender extension!");
}
},
"Xshape" => if XShapeQueryExtension(xserver.display, event_base, error_base) == 0 {
panic!("No XShape extension!");
},
_ => panic!(format!("Don't know how to query for {} extension", name)),
}
}
}
pub struct WindowSettings {
pub opacity: XID,
pub type_atom: XID,
pub is_desktop: XID,
pub is_dock: XID,
pub is_toolbar: XID,
pub is_menu: XID,
pub is_util: XID,
pub is_splash: XID,
pub is_dialog: XID,
pub is_dropdown: XID,
pub is_popup: XID,
pub is_tooltip: XID,
pub is_notification: XID,
pub is_combo: XID,
pub is_dnd: XID,
pub is_normal: XID,
}
pub fn find_window_settings(xserver: &XServer) -> WindowSettings {
WindowSettings {
opacity: intern_atom(xserver, "_NET_WM_WINDOW_OPACITY"),
type_atom: intern_atom(xserver, "_NET_WM_WINDOW_TYPE"),
is_desktop: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DESKTOP"),
is_dock: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DOCK"),
is_toolbar: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLBAR"),
is_menu: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_MENU"),
is_util: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_UTILITY"),
is_splash: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_SPLASH"),
is_dialog: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DIALOG"),
is_dropdown: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DROPDOWN"),
is_popup: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_POPUP"),
is_tooltip: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLTIP"),
is_notification: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NOTIFICATION"),
is_combo: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_COMBO"),
is_dnd: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DND"),
is_normal: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NORMAL"),
}
}
pub fn intern_atom(xserver: &XServer, name: &str) -> XID {
return unsafe { XInternAtom(xserver.display, name.as_ptr() as *mut c_char, 0) };
}
pub fn null_xrender_picture_attributes() -> XRenderPictureAttributes {
return XRenderPictureAttributes {
repeat: 0,
alpha_map: XNone,
alpha_x_origin: 0,
alpha_y_origin: 0,
clip_x_origin: 0,
clip_y_origin: 0,
clip_mask: XNone,
|
dither: XNone,
component_alpha: 0,
}
}
//
// Side-Effecting Stuff
//
pub fn register_compositing_window_manager(xserver: &XServer, wm_name: &CStr) -> bool {
let screen = unsafe { XDefaultScreen(xserver.display) };
let reg_atom_name = CString::new(format!("_NET_WM_CM_S{}", screen)).unwrap();
let reg_atom = unsafe { XInternAtom(xserver.display, reg_atom_name.as_ptr() as *mut c_char, 0) };
let extant_window = unsafe { XGetSelectionOwner(xserver.display, reg_atom) };
if extant_window != XNone {
return false;
}
unsafe {
let our_window = XCreateSimpleWindow(xserver.display, xserver.root,
0, 0, 1, 1, 0, XNone, XNone);
Xutf8SetWMProperties(xserver.display, our_window,
wm_name.as_ptr() as *mut c_char, wm_name.as_ptr() as *mut c_char,
ptr::null_mut(), 0, ptr::null_mut(), ptr::null_mut(), ptr::null_mut());
XSetSelectionOwner(xserver.display, reg_atom, our_window, 0);
};
return true;
}
pub fn create_root_picture(xserver: &XServer, attributes: &mut XRenderPictureAttributes) -> c_ulong {
let display = xserver.display;
let xr_display = xserver.display as *mut _XDisplay;
let format = unsafe {
XRenderFindVisualFormat(xr_display, XDefaultVisual(xr_display, XDefaultScreen(display)))
};
return unsafe {
XRenderCreatePicture( xr_display
, xserver.root
, format
, CPSubWindowMode
, attributes
)
};
}
|
graphics_exposures: 0,
subwindow_mode: 0,
poly_edge: 0,
poly_mode: 0,
|
random_line_split
|
xwrapper.rs
|
use libc::*;
use std::ffi::{CString, CStr};
use std::ptr;
use xlib::{ Display, Pixmap, Window, XClassHint, XCreateSimpleWindow, XDefaultScreen, XDefaultScreenOfDisplay, XGetSelectionOwner, XID, XInternAtom, XOpenDisplay, XRootWindowOfScreen, XSetSelectionOwner, XSizeHints };
use x11::xrender::{ XRenderCreatePicture, XRenderFindVisualFormat, XRenderPictureAttributes, XRenderQueryExtension };
use x11::xlib::{ _XDisplay, XDefaultVisual };
//
// X Definitions
//
static XNone: c_ulong = 0;
static CPSubWindowMode: c_ulong = 1 << 8;
//
// Xlib Types
//
#[repr(C)]
pub struct struct__XWMHints {
pub flags: c_long,
pub input: c_int,
pub initial_state: c_int,
pub icon_pixmap: Pixmap,
pub icon_window: Window,
pub icon_x: c_int,
pub icon_y: c_int,
pub icon_mask: Pixmap,
pub window_group: XID,
}
pub type XWMHints = struct__XWMHints;
//
// Xlib & X Extensions Linking
//
#[link(name = "X11")]
extern {
fn Xutf8SetWMProperties(display: *mut Display, window: Window, window_name: *mut c_char,
icon_name: *mut c_char, argv: *mut *mut c_char, argc: i32,
normal_hints: *mut XSizeHints, wm_hints: *mut XWMHints,
class_hints: *mut XClassHint);
}
#[link(name = "Xcomposite")]
extern {
fn XCompositeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
#[link(name = "Xdamage")]
extern {
fn XDamageQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
#[link(name = "Xext")]
extern {
fn XShapeQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
#[link(name = "Xfixes")]
extern {
fn XFixesQueryExtension(display: *mut Display, event: *mut i32, error: *mut i32) -> i32;
}
//
// XServer Struct
//
pub struct XServer {
display: *mut Display,
root: Window
}
impl XServer {
pub fn new() -> XServer {
unsafe {
let display = XOpenDisplay(ptr::null_mut());
if display.is_null() {
panic!("Could not open display!");
}
let screen = XDefaultScreenOfDisplay(display);
let root = XRootWindowOfScreen(screen);
XServer {
display: display,
root: root
}
}
}
}
pub fn query_extension(xserver: &XServer, name: &str) {
let mut event_base = &mut 0;
let mut error_base = &mut 0;
unsafe {
match name {
"Xcomposite" => if XCompositeQueryExtension(xserver.display, event_base, error_base) == 0 {
panic!("No XComposite extension!");
},
"Xdamage" => if XDamageQueryExtension(xserver.display, event_base, error_base) == 0 {
panic!("No XDamage extension!");
},
"Xfixes" => if XFixesQueryExtension(xserver.display, event_base, error_base) == 0 {
panic!("No XFixes extension!");
},
"Xrender" => { let have_xrender = XRenderQueryExtension(xserver.display as *mut _XDisplay,
event_base, error_base);
if have_xrender == 0 {
panic!("No XRender extension!");
}
},
"Xshape" => if XShapeQueryExtension(xserver.display, event_base, error_base) == 0
|
,
_ => panic!(format!("Don't know how to query for {} extension", name)),
}
}
}
pub struct WindowSettings {
pub opacity: XID,
pub type_atom: XID,
pub is_desktop: XID,
pub is_dock: XID,
pub is_toolbar: XID,
pub is_menu: XID,
pub is_util: XID,
pub is_splash: XID,
pub is_dialog: XID,
pub is_dropdown: XID,
pub is_popup: XID,
pub is_tooltip: XID,
pub is_notification: XID,
pub is_combo: XID,
pub is_dnd: XID,
pub is_normal: XID,
}
pub fn find_window_settings(xserver: &XServer) -> WindowSettings {
WindowSettings {
opacity: intern_atom(xserver, "_NET_WM_WINDOW_OPACITY"),
type_atom: intern_atom(xserver, "_NET_WM_WINDOW_TYPE"),
is_desktop: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DESKTOP"),
is_dock: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DOCK"),
is_toolbar: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLBAR"),
is_menu: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_MENU"),
is_util: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_UTILITY"),
is_splash: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_SPLASH"),
is_dialog: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DIALOG"),
is_dropdown: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DROPDOWN"),
is_popup: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_POPUP"),
is_tooltip: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_TOOLTIP"),
is_notification: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NOTIFICATION"),
is_combo: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_COMBO"),
is_dnd: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_DND"),
is_normal: intern_atom(xserver, "_NET_WM_WINDOW_TYPE_NORMAL"),
}
}
pub fn intern_atom(xserver: &XServer, name: &str) -> XID {
return unsafe { XInternAtom(xserver.display, name.as_ptr() as *mut c_char, 0) };
}
pub fn null_xrender_picture_attributes() -> XRenderPictureAttributes {
return XRenderPictureAttributes {
repeat: 0,
alpha_map: XNone,
alpha_x_origin: 0,
alpha_y_origin: 0,
clip_x_origin: 0,
clip_y_origin: 0,
clip_mask: XNone,
graphics_exposures: 0,
subwindow_mode: 0,
poly_edge: 0,
poly_mode: 0,
dither: XNone,
component_alpha: 0,
}
}
//
// Side-Effecting Stuff
//
pub fn register_compositing_window_manager(xserver: &XServer, wm_name: &CStr) -> bool {
let screen = unsafe { XDefaultScreen(xserver.display) };
let reg_atom_name = CString::new(format!("_NET_WM_CM_S{}", screen)).unwrap();
let reg_atom = unsafe { XInternAtom(xserver.display, reg_atom_name.as_ptr() as *mut c_char, 0) };
let extant_window = unsafe { XGetSelectionOwner(xserver.display, reg_atom) };
if extant_window != XNone {
return false;
}
unsafe {
let our_window = XCreateSimpleWindow(xserver.display, xserver.root,
0, 0, 1, 1, 0, XNone, XNone);
Xutf8SetWMProperties(xserver.display, our_window,
wm_name.as_ptr() as *mut c_char, wm_name.as_ptr() as *mut c_char,
ptr::null_mut(), 0, ptr::null_mut(), ptr::null_mut(), ptr::null_mut());
XSetSelectionOwner(xserver.display, reg_atom, our_window, 0);
};
return true;
}
pub fn create_root_picture(xserver: &XServer, attributes: &mut XRenderPictureAttributes) -> c_ulong {
let display = xserver.display;
let xr_display = xserver.display as *mut _XDisplay;
let format = unsafe {
XRenderFindVisualFormat(xr_display, XDefaultVisual(xr_display, XDefaultScreen(display)))
};
return unsafe {
XRenderCreatePicture( xr_display
, xserver.root
, format
, CPSubWindowMode
, attributes
)
};
}
|
{
panic!("No XShape extension!");
}
|
conditional_block
|
list.mako.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/. */
|
${helpers.single_keyword("list-style-position", "outside inside", animatable=False)}
// TODO(pcwalton): Implement the full set of counter styles per CSS-COUNTER-STYLES [1] 6.1:
//
// decimal-leading-zero, armenian, upper-armenian, lower-armenian, georgian, lower-roman,
// upper-roman
//
// TODO(bholley): Missing quite a few gecko properties here as well.
//
// [1]: http://dev.w3.org/csswg/css-counter-styles/
${helpers.single_keyword("list-style-type", """
disc none circle square decimal lower-alpha upper-alpha disclosure-open disclosure-closed
""", extra_servo_values="""arabic-indic bengali cambodian cjk-decimal devanagari
gujarati gurmukhi kannada khmer lao malayalam mongolian
myanmar oriya persian telugu thai tibetan cjk-earthly-branch
cjk-heavenly-stem lower-greek hiragana hiragana-iroha katakana
katakana-iroha""",
gecko_constant_prefix="NS_STYLE_LIST_STYLE",
animatable=False)}
${helpers.predefined_type("list-style-image", "UrlOrNone", "computed_value::T::None",
animatable="False")}
<%helpers:longhand name="quotes" animatable="False">
use cssparser::Token;
use std::borrow::Cow;
use std::fmt;
use style_traits::ToCss;
use values::computed::ComputedValueAsSpecified;
use values::NoViewportPercentage;
pub use self::computed_value::T as SpecifiedValue;
pub mod computed_value {
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct T(pub Vec<(String,String)>);
}
impl ComputedValueAsSpecified for SpecifiedValue {}
impl NoViewportPercentage for SpecifiedValue {}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut first = true;
for pair in &self.0 {
if !first {
try!(dest.write_str(" "));
}
first = false;
try!(Token::QuotedString(Cow::from(&*pair.0)).to_css(dest));
try!(dest.write_str(" "));
try!(Token::QuotedString(Cow::from(&*pair.1)).to_css(dest));
}
Ok(())
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(vec![
("\u{201c}".to_owned(), "\u{201d}".to_owned()),
("\u{2018}".to_owned(), "\u{2019}".to_owned()),
])
}
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(SpecifiedValue(Vec::new()))
}
let mut quotes = Vec::new();
loop {
let first = match input.next() {
Ok(Token::QuotedString(value)) => value.into_owned(),
Ok(_) => return Err(()),
Err(()) => break,
};
let second = match input.next() {
Ok(Token::QuotedString(value)) => value.into_owned(),
_ => return Err(()),
};
quotes.push((first, second))
}
if !quotes.is_empty() {
Ok(SpecifiedValue(quotes))
} else {
Err(())
}
}
</%helpers:longhand>
|
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("List", inherited=True) %>
|
random_line_split
|
list.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("List", inherited=True) %>
${helpers.single_keyword("list-style-position", "outside inside", animatable=False)}
// TODO(pcwalton): Implement the full set of counter styles per CSS-COUNTER-STYLES [1] 6.1:
//
// decimal-leading-zero, armenian, upper-armenian, lower-armenian, georgian, lower-roman,
// upper-roman
//
// TODO(bholley): Missing quite a few gecko properties here as well.
//
// [1]: http://dev.w3.org/csswg/css-counter-styles/
${helpers.single_keyword("list-style-type", """
disc none circle square decimal lower-alpha upper-alpha disclosure-open disclosure-closed
""", extra_servo_values="""arabic-indic bengali cambodian cjk-decimal devanagari
gujarati gurmukhi kannada khmer lao malayalam mongolian
myanmar oriya persian telugu thai tibetan cjk-earthly-branch
cjk-heavenly-stem lower-greek hiragana hiragana-iroha katakana
katakana-iroha""",
gecko_constant_prefix="NS_STYLE_LIST_STYLE",
animatable=False)}
${helpers.predefined_type("list-style-image", "UrlOrNone", "computed_value::T::None",
animatable="False")}
<%helpers:longhand name="quotes" animatable="False">
use cssparser::Token;
use std::borrow::Cow;
use std::fmt;
use style_traits::ToCss;
use values::computed::ComputedValueAsSpecified;
use values::NoViewportPercentage;
pub use self::computed_value::T as SpecifiedValue;
pub mod computed_value {
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct T(pub Vec<(String,String)>);
}
impl ComputedValueAsSpecified for SpecifiedValue {}
impl NoViewportPercentage for SpecifiedValue {}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut first = true;
for pair in &self.0 {
if !first {
try!(dest.write_str(" "));
}
first = false;
try!(Token::QuotedString(Cow::from(&*pair.0)).to_css(dest));
try!(dest.write_str(" "));
try!(Token::QuotedString(Cow::from(&*pair.1)).to_css(dest));
}
Ok(())
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(vec![
("\u{201c}".to_owned(), "\u{201d}".to_owned()),
("\u{2018}".to_owned(), "\u{2019}".to_owned()),
])
}
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()>
|
</%helpers:longhand>
|
{
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(SpecifiedValue(Vec::new()))
}
let mut quotes = Vec::new();
loop {
let first = match input.next() {
Ok(Token::QuotedString(value)) => value.into_owned(),
Ok(_) => return Err(()),
Err(()) => break,
};
let second = match input.next() {
Ok(Token::QuotedString(value)) => value.into_owned(),
_ => return Err(()),
};
quotes.push((first, second))
}
if !quotes.is_empty() {
Ok(SpecifiedValue(quotes))
} else {
Err(())
}
}
|
identifier_body
|
list.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("List", inherited=True) %>
${helpers.single_keyword("list-style-position", "outside inside", animatable=False)}
// TODO(pcwalton): Implement the full set of counter styles per CSS-COUNTER-STYLES [1] 6.1:
//
// decimal-leading-zero, armenian, upper-armenian, lower-armenian, georgian, lower-roman,
// upper-roman
//
// TODO(bholley): Missing quite a few gecko properties here as well.
//
// [1]: http://dev.w3.org/csswg/css-counter-styles/
${helpers.single_keyword("list-style-type", """
disc none circle square decimal lower-alpha upper-alpha disclosure-open disclosure-closed
""", extra_servo_values="""arabic-indic bengali cambodian cjk-decimal devanagari
gujarati gurmukhi kannada khmer lao malayalam mongolian
myanmar oriya persian telugu thai tibetan cjk-earthly-branch
cjk-heavenly-stem lower-greek hiragana hiragana-iroha katakana
katakana-iroha""",
gecko_constant_prefix="NS_STYLE_LIST_STYLE",
animatable=False)}
${helpers.predefined_type("list-style-image", "UrlOrNone", "computed_value::T::None",
animatable="False")}
<%helpers:longhand name="quotes" animatable="False">
use cssparser::Token;
use std::borrow::Cow;
use std::fmt;
use style_traits::ToCss;
use values::computed::ComputedValueAsSpecified;
use values::NoViewportPercentage;
pub use self::computed_value::T as SpecifiedValue;
pub mod computed_value {
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct
|
(pub Vec<(String,String)>);
}
impl ComputedValueAsSpecified for SpecifiedValue {}
impl NoViewportPercentage for SpecifiedValue {}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut first = true;
for pair in &self.0 {
if !first {
try!(dest.write_str(" "));
}
first = false;
try!(Token::QuotedString(Cow::from(&*pair.0)).to_css(dest));
try!(dest.write_str(" "));
try!(Token::QuotedString(Cow::from(&*pair.1)).to_css(dest));
}
Ok(())
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(vec![
("\u{201c}".to_owned(), "\u{201d}".to_owned()),
("\u{2018}".to_owned(), "\u{2019}".to_owned()),
])
}
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(SpecifiedValue(Vec::new()))
}
let mut quotes = Vec::new();
loop {
let first = match input.next() {
Ok(Token::QuotedString(value)) => value.into_owned(),
Ok(_) => return Err(()),
Err(()) => break,
};
let second = match input.next() {
Ok(Token::QuotedString(value)) => value.into_owned(),
_ => return Err(()),
};
quotes.push((first, second))
}
if !quotes.is_empty() {
Ok(SpecifiedValue(quotes))
} else {
Err(())
}
}
</%helpers:longhand>
|
T
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.