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 |
|---|---|---|---|---|
context.js | var url = require('url')
, path = require('path')
, fs = require('fs')
, utils = require('./utils')
, EventEmitter = require('events').EventEmitter
exports = module.exports = Context
function Context(app, req, res) {
var self = this
this.app = app
this.req = req
this.res = res
this.done = this.done.bind(this)
EventEmitter.call(this)
var socket = res.socket
res.on('finish', done)
socket.on('error', done)
socket.on('close', done)
function done(err) {
res.removeListener('finish', done)
socket.removeListener('error', done)
socket.removeListener('close', done)
self.done(err)
}
}
| done: function(err) {
if (this._notifiedDone === true) return
if (err) {
if (this.writable) {
this.resHeaders = {}
this.type = 'text/plain'
this.status = err.code === 'ENOENT' ? 404 : (err.status || 500)
this.length = Buffer.byteLength(err.message)
this.res.end(err.message)
}
this.app.emit('error', err)
}
this._notifiedDone = true
this.emit('done', err)
},
throw: function(status, err) {
status = status || 500
err = err || {}
err.status = status
err.message = err.message || status.toString()
this.done(err)
},
render: function *(view, locals) {
var app = this.app
, viewPath = path.join(app.viewRoot, view)
, ext = path.extname(viewPath)
, exts, engine, content, testPath, i, j
if (!ext || (yield utils.fileExists(viewPath))) {
for (i = 0; app.viewEngines[i]; i++) {
exts = (app.viewEngines[i].exts || ['.' + app.viewEngines[i].name.toLowerCase()])
if (ext) {
if (~exts.indexOf(ext)) {
engine = app.viewEngines[i]
break
}
continue
}
for (j = 0; exts[j]; j++) {
testPath = viewPath + exts[j]
if (yield utils.fileExists(testPath)) {
viewPath = testPath
engine = app.viewEngines[i]
break
}
}
}
}
if (!engine) return this.throw(500, new Error('View does not exist'))
return yield engine.render(viewPath, locals)
},
/*
* opts: { path: ..., domain: ..., expires: ..., maxAge: ..., httpOnly: ..., secure: ..., sign: ... }
*/
cookie: function(name, val, opts) {
if (!opts) opts = {}
if (typeof val == 'object') val = JSON.stringify(val)
if (this.secret && opts.sign) {
val = this.app.cookies.prefix + this.app.cookies.sign(val, this.secret)
}
var headerVal = name + '=' + val + '; Path=' + (opts.path || '/')
if (opts.domain) headerVal += '; Domain=' + opts.domain
if (opts.expires) {
if (typeof opts.expires === 'number') opts.expires = new Date(opts.expires)
if (opts.expires instanceof Date) opts.expires = opts.expires.toUTCString()
headerVal += '; Expires=' + opts.expires
}
if (opts.maxAge) headerVal += '; Max-Age=' + opts.maxAge
if (opts.httpOnly) headerVal += '; HttpOnly'
if (opts.secure) headerVal += '; Secure'
this.setResHeader('Set-Cookie', headerVal)
},
get writable() {
var socket = this.res.socket
return socket && socket.writable && !this.res.headersSent
},
get path() {
return url.parse(this.url).pathname
},
set path(val) {
var obj = url.parse(this.url)
obj.pathname = val
this.url = url.format(obj)
},
get status() {
return this._status
},
set status(code) {
this._status = this.res.statusCode = code
},
get type() {
return this.getResHeader('Content-Type')
},
set type(val) {
if (val == null) return this.removeResHeader('Content-Type')
this.setResHeader('Content-Type', val)
},
get length() {
return this.getResHeader('Content-Length')
},
set length(val) {
if (val == null) return this.removeResHeader('Content-Length')
this.setResHeader('Content-Length', val)
},
get body() {
return this._body
},
set body(val) {
this._body = val
}
}
utils.extend(Context.prototype, EventEmitter.prototype)
utils.proxy(Context.prototype, {
req: {
method : 'access',
url : 'access',
secure : 'getter',
headers : ['getter', 'reqHeaders'],
},
res: {
_headers : ['access', 'resHeaders'],
getHeader : ['invoke', 'getResHeader'],
setHeader : ['invoke', 'setResHeader'],
removeHeader : ['invoke', 'removeResHeader']
}
}) | Context.prototype = { | random_line_split |
vmware_local_user_manager.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2016, IBM Corp
# Author(s): Andreas Nafpliotis <nafpliot@de.ibm.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vmware_local_user_manager
short_description: Manage local users on an ESXi host
description:
- Manage local users on an ESXi host
version_added: "2.2"
author:
- Andreas Nafpliotis (@nafpliot-ibm)
notes:
- Tested on ESXi 6.0
- Be sure that the ESXi user used for login, has the appropriate rights to create / delete / edit users
requirements:
- "python >= 2.6"
- PyVmomi installed
options:
local_user_name:
description:
- The local user name to be changed.
required: True
local_user_password:
description:
- The password to be set.
required: False
local_user_description:
description:
- Description for the user.
required: False
state:
description:
- Indicate desired state of the user. If the user already exists when C(state=present), the user info is updated
choices: ['present', 'absent']
default: present
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
# Example vmware_local_user_manager command from Ansible Playbooks
- name: Add local user to ESXi
local_action:
module: vmware_local_user_manager
hostname: esxi_hostname
username: root
password: vmware
local_user_name: foo
'''
RETURN = '''# '''
try:
from pyVmomi import vim, vmodl
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec
class VMwareLocalUserManager(PyVmomi):
| self.state = self.module.params['state']
if self.is_vcenter():
self.module.fail_json(msg="Failed to get local account manager settings "
"from ESXi server: %s" % self.module.params['hostname'],
details="It seems that %s is a vCenter server instead of an "
"ESXi server" % self.module.params['hostname'])
def process_state(self):
try:
local_account_manager_states = {
'absent': {
'present': self.state_remove_user,
'absent': self.state_exit_unchanged,
},
'present': {
'present': self.state_update_user,
'absent': self.state_create_user,
}
}
local_account_manager_states[self.state][self.check_local_user_manager_state()]()
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
except Exception as e:
self.module.fail_json(msg=str(e))
def check_local_user_manager_state(self):
user_account = self.find_user_account()
if not user_account:
return 'absent'
else:
return 'present'
def find_user_account(self):
searchStr = self.local_user_name
exactMatch = True
findUsers = True
findGroups = False
user_account = self.content.userDirectory.RetrieveUserGroups(None, searchStr, None, None, exactMatch, findUsers, findGroups)
return user_account
def create_account_spec(self):
account_spec = vim.host.LocalAccountManager.AccountSpecification()
account_spec.id = self.local_user_name
account_spec.password = self.local_user_password
account_spec.description = self.local_user_description
return account_spec
def state_create_user(self):
account_spec = self.create_account_spec()
try:
self.content.accountManager.CreateUser(account_spec)
self.module.exit_json(changed=True)
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
def state_update_user(self):
account_spec = self.create_account_spec()
try:
self.content.accountManager.UpdateUser(account_spec)
self.module.exit_json(changed=True)
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
def state_remove_user(self):
try:
self.content.accountManager.RemoveUser(self.local_user_name)
self.module.exit_json(changed=True)
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
def state_exit_unchanged(self):
self.module.exit_json(changed=False)
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(dict(local_user_name=dict(required=True, type='str'),
local_user_password=dict(type='str', no_log=True),
local_user_description=dict(type='str'),
state=dict(default='present', choices=['present', 'absent'], type='str')))
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=False)
vmware_local_user_manager = VMwareLocalUserManager(module)
vmware_local_user_manager.process_state()
if __name__ == '__main__':
main() | def __init__(self, module):
super(VMwareLocalUserManager, self).__init__(module)
self.local_user_name = self.module.params['local_user_name']
self.local_user_password = self.module.params['local_user_password']
self.local_user_description = self.module.params['local_user_description'] | random_line_split |
vmware_local_user_manager.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2016, IBM Corp
# Author(s): Andreas Nafpliotis <nafpliot@de.ibm.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vmware_local_user_manager
short_description: Manage local users on an ESXi host
description:
- Manage local users on an ESXi host
version_added: "2.2"
author:
- Andreas Nafpliotis (@nafpliot-ibm)
notes:
- Tested on ESXi 6.0
- Be sure that the ESXi user used for login, has the appropriate rights to create / delete / edit users
requirements:
- "python >= 2.6"
- PyVmomi installed
options:
local_user_name:
description:
- The local user name to be changed.
required: True
local_user_password:
description:
- The password to be set.
required: False
local_user_description:
description:
- Description for the user.
required: False
state:
description:
- Indicate desired state of the user. If the user already exists when C(state=present), the user info is updated
choices: ['present', 'absent']
default: present
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
# Example vmware_local_user_manager command from Ansible Playbooks
- name: Add local user to ESXi
local_action:
module: vmware_local_user_manager
hostname: esxi_hostname
username: root
password: vmware
local_user_name: foo
'''
RETURN = '''# '''
try:
from pyVmomi import vim, vmodl
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec
class VMwareLocalUserManager(PyVmomi):
def __init__(self, module):
super(VMwareLocalUserManager, self).__init__(module)
self.local_user_name = self.module.params['local_user_name']
self.local_user_password = self.module.params['local_user_password']
self.local_user_description = self.module.params['local_user_description']
self.state = self.module.params['state']
if self.is_vcenter():
self.module.fail_json(msg="Failed to get local account manager settings "
"from ESXi server: %s" % self.module.params['hostname'],
details="It seems that %s is a vCenter server instead of an "
"ESXi server" % self.module.params['hostname'])
def process_state(self):
try:
local_account_manager_states = {
'absent': {
'present': self.state_remove_user,
'absent': self.state_exit_unchanged,
},
'present': {
'present': self.state_update_user,
'absent': self.state_create_user,
}
}
local_account_manager_states[self.state][self.check_local_user_manager_state()]()
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
except Exception as e:
self.module.fail_json(msg=str(e))
def check_local_user_manager_state(self):
user_account = self.find_user_account()
if not user_account:
return 'absent'
else:
return 'present'
def find_user_account(self):
|
def create_account_spec(self):
account_spec = vim.host.LocalAccountManager.AccountSpecification()
account_spec.id = self.local_user_name
account_spec.password = self.local_user_password
account_spec.description = self.local_user_description
return account_spec
def state_create_user(self):
account_spec = self.create_account_spec()
try:
self.content.accountManager.CreateUser(account_spec)
self.module.exit_json(changed=True)
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
def state_update_user(self):
account_spec = self.create_account_spec()
try:
self.content.accountManager.UpdateUser(account_spec)
self.module.exit_json(changed=True)
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
def state_remove_user(self):
try:
self.content.accountManager.RemoveUser(self.local_user_name)
self.module.exit_json(changed=True)
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
def state_exit_unchanged(self):
self.module.exit_json(changed=False)
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(dict(local_user_name=dict(required=True, type='str'),
local_user_password=dict(type='str', no_log=True),
local_user_description=dict(type='str'),
state=dict(default='present', choices=['present', 'absent'], type='str')))
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=False)
vmware_local_user_manager = VMwareLocalUserManager(module)
vmware_local_user_manager.process_state()
if __name__ == '__main__':
main()
| searchStr = self.local_user_name
exactMatch = True
findUsers = True
findGroups = False
user_account = self.content.userDirectory.RetrieveUserGroups(None, searchStr, None, None, exactMatch, findUsers, findGroups)
return user_account | identifier_body |
vmware_local_user_manager.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2016, IBM Corp
# Author(s): Andreas Nafpliotis <nafpliot@de.ibm.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vmware_local_user_manager
short_description: Manage local users on an ESXi host
description:
- Manage local users on an ESXi host
version_added: "2.2"
author:
- Andreas Nafpliotis (@nafpliot-ibm)
notes:
- Tested on ESXi 6.0
- Be sure that the ESXi user used for login, has the appropriate rights to create / delete / edit users
requirements:
- "python >= 2.6"
- PyVmomi installed
options:
local_user_name:
description:
- The local user name to be changed.
required: True
local_user_password:
description:
- The password to be set.
required: False
local_user_description:
description:
- Description for the user.
required: False
state:
description:
- Indicate desired state of the user. If the user already exists when C(state=present), the user info is updated
choices: ['present', 'absent']
default: present
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
# Example vmware_local_user_manager command from Ansible Playbooks
- name: Add local user to ESXi
local_action:
module: vmware_local_user_manager
hostname: esxi_hostname
username: root
password: vmware
local_user_name: foo
'''
RETURN = '''# '''
try:
from pyVmomi import vim, vmodl
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec
class VMwareLocalUserManager(PyVmomi):
def __init__(self, module):
super(VMwareLocalUserManager, self).__init__(module)
self.local_user_name = self.module.params['local_user_name']
self.local_user_password = self.module.params['local_user_password']
self.local_user_description = self.module.params['local_user_description']
self.state = self.module.params['state']
if self.is_vcenter():
self.module.fail_json(msg="Failed to get local account manager settings "
"from ESXi server: %s" % self.module.params['hostname'],
details="It seems that %s is a vCenter server instead of an "
"ESXi server" % self.module.params['hostname'])
def process_state(self):
try:
local_account_manager_states = {
'absent': {
'present': self.state_remove_user,
'absent': self.state_exit_unchanged,
},
'present': {
'present': self.state_update_user,
'absent': self.state_create_user,
}
}
local_account_manager_states[self.state][self.check_local_user_manager_state()]()
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
except Exception as e:
self.module.fail_json(msg=str(e))
def check_local_user_manager_state(self):
user_account = self.find_user_account()
if not user_account:
return 'absent'
else:
return 'present'
def | (self):
searchStr = self.local_user_name
exactMatch = True
findUsers = True
findGroups = False
user_account = self.content.userDirectory.RetrieveUserGroups(None, searchStr, None, None, exactMatch, findUsers, findGroups)
return user_account
def create_account_spec(self):
account_spec = vim.host.LocalAccountManager.AccountSpecification()
account_spec.id = self.local_user_name
account_spec.password = self.local_user_password
account_spec.description = self.local_user_description
return account_spec
def state_create_user(self):
account_spec = self.create_account_spec()
try:
self.content.accountManager.CreateUser(account_spec)
self.module.exit_json(changed=True)
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
def state_update_user(self):
account_spec = self.create_account_spec()
try:
self.content.accountManager.UpdateUser(account_spec)
self.module.exit_json(changed=True)
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
def state_remove_user(self):
try:
self.content.accountManager.RemoveUser(self.local_user_name)
self.module.exit_json(changed=True)
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
def state_exit_unchanged(self):
self.module.exit_json(changed=False)
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(dict(local_user_name=dict(required=True, type='str'),
local_user_password=dict(type='str', no_log=True),
local_user_description=dict(type='str'),
state=dict(default='present', choices=['present', 'absent'], type='str')))
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=False)
vmware_local_user_manager = VMwareLocalUserManager(module)
vmware_local_user_manager.process_state()
if __name__ == '__main__':
main()
| find_user_account | identifier_name |
vmware_local_user_manager.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2016, IBM Corp
# Author(s): Andreas Nafpliotis <nafpliot@de.ibm.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vmware_local_user_manager
short_description: Manage local users on an ESXi host
description:
- Manage local users on an ESXi host
version_added: "2.2"
author:
- Andreas Nafpliotis (@nafpliot-ibm)
notes:
- Tested on ESXi 6.0
- Be sure that the ESXi user used for login, has the appropriate rights to create / delete / edit users
requirements:
- "python >= 2.6"
- PyVmomi installed
options:
local_user_name:
description:
- The local user name to be changed.
required: True
local_user_password:
description:
- The password to be set.
required: False
local_user_description:
description:
- Description for the user.
required: False
state:
description:
- Indicate desired state of the user. If the user already exists when C(state=present), the user info is updated
choices: ['present', 'absent']
default: present
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
# Example vmware_local_user_manager command from Ansible Playbooks
- name: Add local user to ESXi
local_action:
module: vmware_local_user_manager
hostname: esxi_hostname
username: root
password: vmware
local_user_name: foo
'''
RETURN = '''# '''
try:
from pyVmomi import vim, vmodl
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec
class VMwareLocalUserManager(PyVmomi):
def __init__(self, module):
super(VMwareLocalUserManager, self).__init__(module)
self.local_user_name = self.module.params['local_user_name']
self.local_user_password = self.module.params['local_user_password']
self.local_user_description = self.module.params['local_user_description']
self.state = self.module.params['state']
if self.is_vcenter():
self.module.fail_json(msg="Failed to get local account manager settings "
"from ESXi server: %s" % self.module.params['hostname'],
details="It seems that %s is a vCenter server instead of an "
"ESXi server" % self.module.params['hostname'])
def process_state(self):
try:
local_account_manager_states = {
'absent': {
'present': self.state_remove_user,
'absent': self.state_exit_unchanged,
},
'present': {
'present': self.state_update_user,
'absent': self.state_create_user,
}
}
local_account_manager_states[self.state][self.check_local_user_manager_state()]()
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
except Exception as e:
self.module.fail_json(msg=str(e))
def check_local_user_manager_state(self):
user_account = self.find_user_account()
if not user_account:
return 'absent'
else:
|
def find_user_account(self):
searchStr = self.local_user_name
exactMatch = True
findUsers = True
findGroups = False
user_account = self.content.userDirectory.RetrieveUserGroups(None, searchStr, None, None, exactMatch, findUsers, findGroups)
return user_account
def create_account_spec(self):
account_spec = vim.host.LocalAccountManager.AccountSpecification()
account_spec.id = self.local_user_name
account_spec.password = self.local_user_password
account_spec.description = self.local_user_description
return account_spec
def state_create_user(self):
account_spec = self.create_account_spec()
try:
self.content.accountManager.CreateUser(account_spec)
self.module.exit_json(changed=True)
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
def state_update_user(self):
account_spec = self.create_account_spec()
try:
self.content.accountManager.UpdateUser(account_spec)
self.module.exit_json(changed=True)
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
def state_remove_user(self):
try:
self.content.accountManager.RemoveUser(self.local_user_name)
self.module.exit_json(changed=True)
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
def state_exit_unchanged(self):
self.module.exit_json(changed=False)
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(dict(local_user_name=dict(required=True, type='str'),
local_user_password=dict(type='str', no_log=True),
local_user_description=dict(type='str'),
state=dict(default='present', choices=['present', 'absent'], type='str')))
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=False)
vmware_local_user_manager = VMwareLocalUserManager(module)
vmware_local_user_manager.process_state()
if __name__ == '__main__':
main()
| return 'present' | conditional_block |
ng-admin.js | /*global require,define,angular*/
define('angular', [], function () {
'use strict';
return angular;
});
require.config({
paths: {
'angular-bootstrap': 'bower_components/angular-bootstrap/ui-bootstrap.min',
'angular-bootstrap-tpls': 'bower_components/angular-bootstrap/ui-bootstrap-tpls.min',
'angular-numeraljs': 'bower_components/angular-numeraljs/dist/angular-numeraljs',
'angular-resource': 'bower_components/angular-resource/angular-resource',
'angular-sanitize': 'bower_components/angular-sanitize/angular-sanitize',
'angular-ui-codemirror': 'bower_components/angular-ui-codemirror/ui-codemirror.min',
'angular-ui-router': 'bower_components/angular-ui-router/release/angular-ui-router',
'humane': 'bower_components/humane/humane',
'inflection': 'bower_components/inflection/inflection.min',
'lodash': 'bower_components/lodash/dist/lodash.min',
'ng-file-upload': 'bower_components/ng-file-upload/angular-file-upload',
'ngInflection': 'bower_components/ngInflection/ngInflection',
'nprogress': 'bower_components/nprogress/nprogress',
'numeral': 'bower_components/numeral/numeral',
'restangular': 'bower_components/restangular/dist/restangular',
'text' : 'bower_components/requirejs-text/text',
'textangular': 'bower_components/textAngular/dist/textAngular.min',
'CrudModule': 'ng-admin/Crud/CrudModule', | 'papaparse': 'bower_components/papaparse/papaparse.min',
'MainModule': 'ng-admin/Main/MainModule',
'AdminDescription': '../../build/ng-admin-configuration'
},
shim: {
'papaparse': {
exports: 'Papa'
},
'restangular': {
deps: ['angular', 'lodash']
},
'angular-ui-router': {
deps: ['angular']
},
'angular-bootstrap': {
deps: ['angular']
},
'angular-bootstrap-tpls': {
deps: ['angular', 'angular-bootstrap']
}
}
});
define(function (require) {
'use strict';
var angular = require('angular');
require('MainModule');
require('CrudModule');
var AdminDescription = require('AdminDescription');
var factory = angular.module('AdminDescriptionModule', []);
factory.constant('AdminDescription', new AdminDescription());
var ngadmin = angular.module('ng-admin', ['main', 'crud', 'AdminDescriptionModule']);
ngadmin.config(['NgAdminConfigurationProvider', 'AdminDescription', function(NgAdminConfigurationProvider, AdminDescription) {
NgAdminConfigurationProvider.setAdminDescription(AdminDescription);
}]);
}); | random_line_split | |
AlgoliaSearchProvider.tsx | import React, {
createContext,
useMemo,
useCallback,
useContext,
FC
} from 'react';
import algoliasearch from 'algoliasearch';
import {
searchRelatedArticles,
AlgoliaArticle,
SearchRelatedArticlesResult
} from './algoliaRelatedArticles';
const createAlgoliaIndex = (algoliaSearchKeys: AlgoliaSearchKeys) => {
if (algoliaSearchKeys) {
const { applicationId, apiKey, indexName } = algoliaSearchKeys;
return algoliasearch(applicationId, apiKey).initIndex(indexName);
}
return null;
}; | type AlgoliaSearchContextType = {
getRelatedArticles?: () => Promise<SearchRelatedArticlesResult | null>;
};
const AlgoliaSearchContext = createContext<AlgoliaSearchContextType>({});
export const AlgoliaSearchProvider: FC<AlgoliaSearchProps> = ({
algoliaSearchKeys,
article,
analyticsStream,
children
}) => {
const algoliaIndex = useMemo(() => createAlgoliaIndex(algoliaSearchKeys), [
algoliaSearchKeys
]);
const getRelatedArticles = useCallback(
async () => {
if (algoliaIndex && article) {
const results = await searchRelatedArticles(
algoliaIndex,
article,
analyticsStream
);
return results;
}
return null;
},
[algoliaIndex, article]
);
return (
<AlgoliaSearchContext.Provider value={{ getRelatedArticles }}>
{children}
</AlgoliaSearchContext.Provider>
);
};
export const useAlgoliaSearch = () => {
const context = useContext(AlgoliaSearchContext);
if (context === undefined) {
throw new Error('must be used within an AlgoliaSearchProvider');
}
return context;
};
type AlgoliaSearchKeys = {
applicationId: string;
apiKey: string;
indexName: string;
};
type AlgoliaSearchProps = {
algoliaSearchKeys: AlgoliaSearchKeys;
article: AlgoliaArticle | null;
analyticsStream: (event: any) => void;
}; | random_line_split | |
AlgoliaSearchProvider.tsx | import React, {
createContext,
useMemo,
useCallback,
useContext,
FC
} from 'react';
import algoliasearch from 'algoliasearch';
import {
searchRelatedArticles,
AlgoliaArticle,
SearchRelatedArticlesResult
} from './algoliaRelatedArticles';
const createAlgoliaIndex = (algoliaSearchKeys: AlgoliaSearchKeys) => {
if (algoliaSearchKeys) |
return null;
};
type AlgoliaSearchContextType = {
getRelatedArticles?: () => Promise<SearchRelatedArticlesResult | null>;
};
const AlgoliaSearchContext = createContext<AlgoliaSearchContextType>({});
export const AlgoliaSearchProvider: FC<AlgoliaSearchProps> = ({
algoliaSearchKeys,
article,
analyticsStream,
children
}) => {
const algoliaIndex = useMemo(() => createAlgoliaIndex(algoliaSearchKeys), [
algoliaSearchKeys
]);
const getRelatedArticles = useCallback(
async () => {
if (algoliaIndex && article) {
const results = await searchRelatedArticles(
algoliaIndex,
article,
analyticsStream
);
return results;
}
return null;
},
[algoliaIndex, article]
);
return (
<AlgoliaSearchContext.Provider value={{ getRelatedArticles }}>
{children}
</AlgoliaSearchContext.Provider>
);
};
export const useAlgoliaSearch = () => {
const context = useContext(AlgoliaSearchContext);
if (context === undefined) {
throw new Error('must be used within an AlgoliaSearchProvider');
}
return context;
};
type AlgoliaSearchKeys = {
applicationId: string;
apiKey: string;
indexName: string;
};
type AlgoliaSearchProps = {
algoliaSearchKeys: AlgoliaSearchKeys;
article: AlgoliaArticle | null;
analyticsStream: (event: any) => void;
};
| {
const { applicationId, apiKey, indexName } = algoliaSearchKeys;
return algoliasearch(applicationId, apiKey).initIndex(indexName);
} | conditional_block |
number.js | 'use strict';
// MODULES //
var betaincinv = require( 'compute-betaincinv/lib/ibeta_inv_imp.js' );
// QUANTILE //
/**
* FUNCTION: quantile( p, d1, d2 )
* Evaluates the quantile function for a F distribution with numerator degrees of freedom `d1` and denominator degrees of freedom `d2` at a probability `p`.
*
* @param {Number} p - input value
* @param {Number} d1 - numerator degrees of freedom
* @param {Number} d2 - denominator degrees of freedom
* @returns {Number} evaluated quantile function
*/
function quantile( p, d1, d2 ) {
var bVal, x1, x2;
if ( p !== p || p < 0 || p > 1 ) |
bVal = betaincinv( d1 / 2, d2 / 2, p, 1 - p );
x1 = bVal[ 0 ];
x2 = bVal[ 1 ];
return d2 * x1 / ( d1 * x2 );
} // end FUNCTION quantile()
// EXPORTS //
module.exports = quantile;
| {
return NaN;
} | conditional_block |
number.js | 'use strict';
// MODULES //
var betaincinv = require( 'compute-betaincinv/lib/ibeta_inv_imp.js' );
// QUANTILE //
/**
* FUNCTION: quantile( p, d1, d2 )
* Evaluates the quantile function for a F distribution with numerator degrees of freedom `d1` and denominator degrees of freedom `d2` at a probability `p`.
*
* @param {Number} p - input value
* @param {Number} d1 - numerator degrees of freedom
* @param {Number} d2 - denominator degrees of freedom
* @returns {Number} evaluated quantile function
*/
function | ( p, d1, d2 ) {
var bVal, x1, x2;
if ( p !== p || p < 0 || p > 1 ) {
return NaN;
}
bVal = betaincinv( d1 / 2, d2 / 2, p, 1 - p );
x1 = bVal[ 0 ];
x2 = bVal[ 1 ];
return d2 * x1 / ( d1 * x2 );
} // end FUNCTION quantile()
// EXPORTS //
module.exports = quantile;
| quantile | identifier_name |
number.js | 'use strict';
// MODULES //
var betaincinv = require( 'compute-betaincinv/lib/ibeta_inv_imp.js' );
// QUANTILE //
/**
* FUNCTION: quantile( p, d1, d2 )
* Evaluates the quantile function for a F distribution with numerator degrees of freedom `d1` and denominator degrees of freedom `d2` at a probability `p`.
*
* @param {Number} p - input value
* @param {Number} d1 - numerator degrees of freedom
* @param {Number} d2 - denominator degrees of freedom
* @returns {Number} evaluated quantile function
*/
function quantile( p, d1, d2 ) |
// EXPORTS //
module.exports = quantile;
| {
var bVal, x1, x2;
if ( p !== p || p < 0 || p > 1 ) {
return NaN;
}
bVal = betaincinv( d1 / 2, d2 / 2, p, 1 - p );
x1 = bVal[ 0 ];
x2 = bVal[ 1 ];
return d2 * x1 / ( d1 * x2 );
} // end FUNCTION quantile() | identifier_body |
number.js | 'use strict';
// MODULES //
var betaincinv = require( 'compute-betaincinv/lib/ibeta_inv_imp.js' );
// QUANTILE //
/**
* FUNCTION: quantile( p, d1, d2 )
* Evaluates the quantile function for a F distribution with numerator degrees of freedom `d1` and denominator degrees of freedom `d2` at a probability `p`.
* | * @param {Number} p - input value
* @param {Number} d1 - numerator degrees of freedom
* @param {Number} d2 - denominator degrees of freedom
* @returns {Number} evaluated quantile function
*/
function quantile( p, d1, d2 ) {
var bVal, x1, x2;
if ( p !== p || p < 0 || p > 1 ) {
return NaN;
}
bVal = betaincinv( d1 / 2, d2 / 2, p, 1 - p );
x1 = bVal[ 0 ];
x2 = bVal[ 1 ];
return d2 * x1 / ( d1 * x2 );
} // end FUNCTION quantile()
// EXPORTS //
module.exports = quantile; | random_line_split | |
core_sphere.rs | extern crate rustcmb;
use rustcmb::core::sphere;
const SIZE: usize = 4;
fn main() {
let default_field = sphere::Field::default();
let field = sphere::Field::new(SIZE);
let mut mut_field = sphere::Field::new(SIZE);
println!("default_field: {:?}", default_field);
println!("field: {:?}", field);
println!("mut_field: {:?}", mut_field);
println!("field size: {:?}", field.size());
println!("field at (2, 2): {:?}", field.at(2, 2));
*mut_field.at_mut(2, 2) = 1.;
println!("mut_field: {:?}", mut_field);
for i in mut_field.i_begin()..mut_field.i_end() {
for j in mut_field.j_begin()..mut_field.j_end() {
*mut_field.at_mut(i, j) = (i + j) as f64;
}
}
println!("mut_field after simple indexing: {:?}", mut_field); |
let mut foo_coef = sphere::Coef::new(SIZE);
for l in foo_coef.a_l_begin()..foo_coef.a_l_end() {
for m in foo_coef.a_m_begin()..foo_coef.a_m_end(l) {
*foo_coef.a_at_mut(l, m) = (l + m + 5) as f64;
}
}
for i in foo_coef.b_l_begin()..foo_coef.b_l_end() {
for j in foo_coef.b_m_begin()..foo_coef.b_m_end(i) {
*foo_coef.b_at_mut(i, j) = (i + j + 10) as f64;
}
}
println!("foo_coef after simple indexing: {:?}", foo_coef);
} | random_line_split | |
core_sphere.rs | extern crate rustcmb;
use rustcmb::core::sphere;
const SIZE: usize = 4;
fn | () {
let default_field = sphere::Field::default();
let field = sphere::Field::new(SIZE);
let mut mut_field = sphere::Field::new(SIZE);
println!("default_field: {:?}", default_field);
println!("field: {:?}", field);
println!("mut_field: {:?}", mut_field);
println!("field size: {:?}", field.size());
println!("field at (2, 2): {:?}", field.at(2, 2));
*mut_field.at_mut(2, 2) = 1.;
println!("mut_field: {:?}", mut_field);
for i in mut_field.i_begin()..mut_field.i_end() {
for j in mut_field.j_begin()..mut_field.j_end() {
*mut_field.at_mut(i, j) = (i + j) as f64;
}
}
println!("mut_field after simple indexing: {:?}", mut_field);
let mut foo_coef = sphere::Coef::new(SIZE);
for l in foo_coef.a_l_begin()..foo_coef.a_l_end() {
for m in foo_coef.a_m_begin()..foo_coef.a_m_end(l) {
*foo_coef.a_at_mut(l, m) = (l + m + 5) as f64;
}
}
for i in foo_coef.b_l_begin()..foo_coef.b_l_end() {
for j in foo_coef.b_m_begin()..foo_coef.b_m_end(i) {
*foo_coef.b_at_mut(i, j) = (i + j + 10) as f64;
}
}
println!("foo_coef after simple indexing: {:?}", foo_coef);
}
| main | identifier_name |
core_sphere.rs | extern crate rustcmb;
use rustcmb::core::sphere;
const SIZE: usize = 4;
fn main() | {
let default_field = sphere::Field::default();
let field = sphere::Field::new(SIZE);
let mut mut_field = sphere::Field::new(SIZE);
println!("default_field: {:?}", default_field);
println!("field: {:?}", field);
println!("mut_field: {:?}", mut_field);
println!("field size: {:?}", field.size());
println!("field at (2, 2): {:?}", field.at(2, 2));
*mut_field.at_mut(2, 2) = 1.;
println!("mut_field: {:?}", mut_field);
for i in mut_field.i_begin()..mut_field.i_end() {
for j in mut_field.j_begin()..mut_field.j_end() {
*mut_field.at_mut(i, j) = (i + j) as f64;
}
}
println!("mut_field after simple indexing: {:?}", mut_field);
let mut foo_coef = sphere::Coef::new(SIZE);
for l in foo_coef.a_l_begin()..foo_coef.a_l_end() {
for m in foo_coef.a_m_begin()..foo_coef.a_m_end(l) {
*foo_coef.a_at_mut(l, m) = (l + m + 5) as f64;
}
}
for i in foo_coef.b_l_begin()..foo_coef.b_l_end() {
for j in foo_coef.b_m_begin()..foo_coef.b_m_end(i) {
*foo_coef.b_at_mut(i, j) = (i + j + 10) as f64;
}
}
println!("foo_coef after simple indexing: {:?}", foo_coef);
} | identifier_body | |
test_cp2_x_cincoffset_sealed.py | #-
# Copyright (c) 2014 Michael Roe
# All rights reserved.
#
# This software was developed by SRI International and the University of
# Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
# ("CTSRD"), as part of the DARPA CRASH research programme.
#
# @BERI_LICENSE_HEADER_START@
#
# Licensed to BERI Open Systems C.I.C. (BERI) under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. BERI licenses this
# file to you under the BERI Hardware-Software License, Version 1.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.beri-open-systems.org/legal/license-1-0.txt
#
# Unless required by applicable law or agreed to in writing, Work 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.
#
# @BERI_LICENSE_HEADER_END@
#
from beritest_tools import BaseBERITestCase
from nose.plugins.attrib import attr
class test_cp2_x_cincoffset_sealed(BaseBERITestCase):
@attr('capabilities')
def | (self):
'''Test that CIncOffset on a sealed capability does not change the offsrt'''
self.assertRegisterEqual(self.MIPS.a0, 0, "CIncOffset changed the offset of a sealed capability")
@attr('capabilities')
def test_cp2_x_cincoffset_sealed_2(self):
'''Test that CIncOffset on a sealed capability raised an exception'''
self.assertRegisterEqual(self.MIPS.a2, 1, "CIncOffset on a sealed capability did not raise an exception")
@attr('capabilities')
def test_cp2_x_cincoffset_sealed_3(self):
'''Test that CIncOffset on a sealed capability sets CapCause'''
self.assertRegisterEqual(self.MIPS.a3, 0x0301, "CIncOffset on a sealed capability did not set CapCause correctly")
| test_cp2_x_cincoffset_sealed_1 | identifier_name |
test_cp2_x_cincoffset_sealed.py | #-
# Copyright (c) 2014 Michael Roe
# All rights reserved.
#
# This software was developed by SRI International and the University of
# Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
# ("CTSRD"), as part of the DARPA CRASH research programme.
#
# @BERI_LICENSE_HEADER_START@
#
# Licensed to BERI Open Systems C.I.C. (BERI) under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. BERI licenses this
# file to you under the BERI Hardware-Software License, Version 1.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.beri-open-systems.org/legal/license-1-0.txt
#
# Unless required by applicable law or agreed to in writing, Work 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.
#
# @BERI_LICENSE_HEADER_END@
#
from beritest_tools import BaseBERITestCase
from nose.plugins.attrib import attr
class test_cp2_x_cincoffset_sealed(BaseBERITestCase):
| @attr('capabilities')
def test_cp2_x_cincoffset_sealed_1(self):
'''Test that CIncOffset on a sealed capability does not change the offsrt'''
self.assertRegisterEqual(self.MIPS.a0, 0, "CIncOffset changed the offset of a sealed capability")
@attr('capabilities')
def test_cp2_x_cincoffset_sealed_2(self):
'''Test that CIncOffset on a sealed capability raised an exception'''
self.assertRegisterEqual(self.MIPS.a2, 1, "CIncOffset on a sealed capability did not raise an exception")
@attr('capabilities')
def test_cp2_x_cincoffset_sealed_3(self):
'''Test that CIncOffset on a sealed capability sets CapCause'''
self.assertRegisterEqual(self.MIPS.a3, 0x0301, "CIncOffset on a sealed capability did not set CapCause correctly") | identifier_body | |
test_cp2_x_cincoffset_sealed.py | #-
# Copyright (c) 2014 Michael Roe
# All rights reserved.
#
# This software was developed by SRI International and the University of
# Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
# ("CTSRD"), as part of the DARPA CRASH research programme.
#
# @BERI_LICENSE_HEADER_START@
#
# Licensed to BERI Open Systems C.I.C. (BERI) under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. BERI licenses this
# file to you under the BERI Hardware-Software License, Version 1.0 (the
# "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at: | #
# Unless required by applicable law or agreed to in writing, Work 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.
#
# @BERI_LICENSE_HEADER_END@
#
from beritest_tools import BaseBERITestCase
from nose.plugins.attrib import attr
class test_cp2_x_cincoffset_sealed(BaseBERITestCase):
@attr('capabilities')
def test_cp2_x_cincoffset_sealed_1(self):
'''Test that CIncOffset on a sealed capability does not change the offsrt'''
self.assertRegisterEqual(self.MIPS.a0, 0, "CIncOffset changed the offset of a sealed capability")
@attr('capabilities')
def test_cp2_x_cincoffset_sealed_2(self):
'''Test that CIncOffset on a sealed capability raised an exception'''
self.assertRegisterEqual(self.MIPS.a2, 1, "CIncOffset on a sealed capability did not raise an exception")
@attr('capabilities')
def test_cp2_x_cincoffset_sealed_3(self):
'''Test that CIncOffset on a sealed capability sets CapCause'''
self.assertRegisterEqual(self.MIPS.a3, 0x0301, "CIncOffset on a sealed capability did not set CapCause correctly") | #
# http://www.beri-open-systems.org/legal/license-1-0.txt | random_line_split |
test_diff.py | #!/usr/bin/env python
# encoding: utf-8
import unittest
import os.path as p, sys; sys.path.append(p.join(p.dirname(__file__), ".."))
from _diff import diff, guess_edit
from geometry import Position
def transform(a, cmds):
buf = a.split("\n")
for cmd in cmds:
ctype, line, col, char = cmd
if ctype == "D":
if char != '\n':
buf[line] = buf[line][:col] + buf[line][col+len(char):]
else:
buf[line] = buf[line] + buf[line+1]
del buf[line+1]
elif ctype == "I":
buf[line] = buf[line][:col] + char + buf[line][col:]
buf = '\n'.join(buf).split('\n')
return '\n'.join(buf)
import unittest
# Test Guessing {{{
class _BaseGuessing(object):
def runTest(self):
rv, es = guess_edit(self.initial_line, self.a, self.b, Position(*self.ppos), Position(*self.pos))
self.assertEqual(rv, True)
self.assertEqual(self.wanted, es)
class TestGuessing_Noop0(_BaseGuessing, unittest.TestCase):
a, b = [], []
initial_line = 0
ppos, pos = (0, 6), (0, 7)
wanted = ()
class TestGuessing_InsertOneChar(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 6), (0, 7)
wanted = (
("I", 0, 6, " "),
)
class TestGuessing_InsertOneChar1(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 7), (0, 8)
wanted = (
("I", 0, 7, " "),
)
class TestGuessing_BackspaceOneChar(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 7), (0, 6)
wanted = (
("D", 0, 6, " "),
)
class TestGuessing_DeleteOneChar(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 5), (0, 5)
wanted = (
("D", 0, 5, " "),
)
# End: Test Guessing }}}
class _Base(object):
def runTest(self):
es = diff(self.a, self.b)
tr = transform(self.a, es)
self.assertEqual(self.b, tr)
self.assertEqual(self.wanted, es)
class TestEmptyString(_Base, unittest.TestCase):
a, b = "", ""
wanted = ()
class TestAllMatch(_Base, unittest.TestCase):
a, b = "abcdef", "abcdef"
wanted = ()
class TestLotsaNewlines(_Base, unittest.TestCase):
a, b = "Hello", "Hello\nWorld\nWorld\nWorld"
wanted = (
("I", 0, 5, "\n"),
("I", 1, 0, "World"),
("I", 1, 5, "\n"),
("I", 2, 0, "World"),
("I", 2, 5, "\n"),
("I", 3, 0, "World"),
)
class TestCrash(_Base, unittest.TestCase):
a = 'hallo Blah mitte=sdfdsfsd\nhallo kjsdhfjksdhfkjhsdfkh mittekjshdkfhkhsdfdsf'
b = 'hallo Blah mitte=sdfdsfsd\nhallo b mittekjshdkfhkhsdfdsf'
wanted = (
("D", 1, 6, "kjsdhfjksdhfkjhsdfkh"),
("I", 1, 6, "b"),
)
class TestRealLife(_Base, unittest.TestCase):
a = 'hallo End Beginning'
b = 'hallo End t'
wanted = (
("D", 0, 10, "Beginning"),
("I", 0, 10, "t"),
)
class TestRealLife1(_Base, unittest.TestCase):
a = 'Vorne hallo Hinten'
b = 'Vorne hallo Hinten'
wanted = (
("I", 0, 11, " "),
)
class TestWithNewline(_Base, unittest.TestCase):
a = 'First Line\nSecond Line'
b = 'n'
wanted = (
("D", 0, 0, "First Line"),
("D", 0, 0, "\n"),
("D", 0, 0, "Second Line"),
("I", 0, 0, "n"),
)
class TestCheapDelete(_Base, unittest.TestCase):
a = 'Vorne hallo Hinten'
b = 'Vorne Hinten'
wanted = (
("D", 0, 5, " hallo"),
)
class TestNoSubstring(_Base, unittest.TestCase):
|
class TestCommonCharacters(_Base, unittest.TestCase):
a,b = "hasomelongertextbl", "hol"
wanted = (
("D", 0, 1, "asomelongertextb"),
("I", 0, 1, "o"),
)
class TestUltiSnipsProblem(_Base, unittest.TestCase):
a = "this is it this is it this is it"
b = "this is it a this is it"
wanted = (
("D", 0, 11, "this is it"),
("I", 0, 11, "a"),
)
class MatchIsTooCheap(_Base, unittest.TestCase):
a = "stdin.h"
b = "s"
wanted = (
("D", 0, 1, "tdin.h"),
)
class MultiLine(_Base, unittest.TestCase):
a = "hi first line\nsecond line first line\nsecond line world"
b = "hi first line\nsecond line k world"
wanted = (
("D", 1, 12, "first line"),
("D", 1, 12, "\n"),
("D", 1, 12, "second line"),
("I", 1, 12, "k"),
)
if __name__ == '__main__':
unittest.main()
# k = TestEditScript()
# unittest.TextTestRunner().run(k)
| a,b = "abc", "def"
wanted = (
("D", 0, 0, "abc"),
("I", 0, 0, "def"),
) | identifier_body |
test_diff.py | #!/usr/bin/env python
# encoding: utf-8
import unittest
import os.path as p, sys; sys.path.append(p.join(p.dirname(__file__), ".."))
from _diff import diff, guess_edit
from geometry import Position
def transform(a, cmds):
buf = a.split("\n")
for cmd in cmds:
ctype, line, col, char = cmd
if ctype == "D":
if char != '\n':
|
else:
buf[line] = buf[line] + buf[line+1]
del buf[line+1]
elif ctype == "I":
buf[line] = buf[line][:col] + char + buf[line][col:]
buf = '\n'.join(buf).split('\n')
return '\n'.join(buf)
import unittest
# Test Guessing {{{
class _BaseGuessing(object):
def runTest(self):
rv, es = guess_edit(self.initial_line, self.a, self.b, Position(*self.ppos), Position(*self.pos))
self.assertEqual(rv, True)
self.assertEqual(self.wanted, es)
class TestGuessing_Noop0(_BaseGuessing, unittest.TestCase):
a, b = [], []
initial_line = 0
ppos, pos = (0, 6), (0, 7)
wanted = ()
class TestGuessing_InsertOneChar(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 6), (0, 7)
wanted = (
("I", 0, 6, " "),
)
class TestGuessing_InsertOneChar1(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 7), (0, 8)
wanted = (
("I", 0, 7, " "),
)
class TestGuessing_BackspaceOneChar(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 7), (0, 6)
wanted = (
("D", 0, 6, " "),
)
class TestGuessing_DeleteOneChar(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 5), (0, 5)
wanted = (
("D", 0, 5, " "),
)
# End: Test Guessing }}}
class _Base(object):
def runTest(self):
es = diff(self.a, self.b)
tr = transform(self.a, es)
self.assertEqual(self.b, tr)
self.assertEqual(self.wanted, es)
class TestEmptyString(_Base, unittest.TestCase):
a, b = "", ""
wanted = ()
class TestAllMatch(_Base, unittest.TestCase):
a, b = "abcdef", "abcdef"
wanted = ()
class TestLotsaNewlines(_Base, unittest.TestCase):
a, b = "Hello", "Hello\nWorld\nWorld\nWorld"
wanted = (
("I", 0, 5, "\n"),
("I", 1, 0, "World"),
("I", 1, 5, "\n"),
("I", 2, 0, "World"),
("I", 2, 5, "\n"),
("I", 3, 0, "World"),
)
class TestCrash(_Base, unittest.TestCase):
a = 'hallo Blah mitte=sdfdsfsd\nhallo kjsdhfjksdhfkjhsdfkh mittekjshdkfhkhsdfdsf'
b = 'hallo Blah mitte=sdfdsfsd\nhallo b mittekjshdkfhkhsdfdsf'
wanted = (
("D", 1, 6, "kjsdhfjksdhfkjhsdfkh"),
("I", 1, 6, "b"),
)
class TestRealLife(_Base, unittest.TestCase):
a = 'hallo End Beginning'
b = 'hallo End t'
wanted = (
("D", 0, 10, "Beginning"),
("I", 0, 10, "t"),
)
class TestRealLife1(_Base, unittest.TestCase):
a = 'Vorne hallo Hinten'
b = 'Vorne hallo Hinten'
wanted = (
("I", 0, 11, " "),
)
class TestWithNewline(_Base, unittest.TestCase):
a = 'First Line\nSecond Line'
b = 'n'
wanted = (
("D", 0, 0, "First Line"),
("D", 0, 0, "\n"),
("D", 0, 0, "Second Line"),
("I", 0, 0, "n"),
)
class TestCheapDelete(_Base, unittest.TestCase):
a = 'Vorne hallo Hinten'
b = 'Vorne Hinten'
wanted = (
("D", 0, 5, " hallo"),
)
class TestNoSubstring(_Base, unittest.TestCase):
a,b = "abc", "def"
wanted = (
("D", 0, 0, "abc"),
("I", 0, 0, "def"),
)
class TestCommonCharacters(_Base, unittest.TestCase):
a,b = "hasomelongertextbl", "hol"
wanted = (
("D", 0, 1, "asomelongertextb"),
("I", 0, 1, "o"),
)
class TestUltiSnipsProblem(_Base, unittest.TestCase):
a = "this is it this is it this is it"
b = "this is it a this is it"
wanted = (
("D", 0, 11, "this is it"),
("I", 0, 11, "a"),
)
class MatchIsTooCheap(_Base, unittest.TestCase):
a = "stdin.h"
b = "s"
wanted = (
("D", 0, 1, "tdin.h"),
)
class MultiLine(_Base, unittest.TestCase):
a = "hi first line\nsecond line first line\nsecond line world"
b = "hi first line\nsecond line k world"
wanted = (
("D", 1, 12, "first line"),
("D", 1, 12, "\n"),
("D", 1, 12, "second line"),
("I", 1, 12, "k"),
)
if __name__ == '__main__':
unittest.main()
# k = TestEditScript()
# unittest.TextTestRunner().run(k)
| buf[line] = buf[line][:col] + buf[line][col+len(char):] | conditional_block |
test_diff.py | #!/usr/bin/env python
# encoding: utf-8
import unittest
import os.path as p, sys; sys.path.append(p.join(p.dirname(__file__), ".."))
from _diff import diff, guess_edit
from geometry import Position
def transform(a, cmds):
buf = a.split("\n")
for cmd in cmds:
ctype, line, col, char = cmd
if ctype == "D":
if char != '\n':
buf[line] = buf[line][:col] + buf[line][col+len(char):]
else:
buf[line] = buf[line] + buf[line+1]
del buf[line+1]
elif ctype == "I":
buf[line] = buf[line][:col] + char + buf[line][col:]
buf = '\n'.join(buf).split('\n')
return '\n'.join(buf)
import unittest
# Test Guessing {{{
class _BaseGuessing(object):
def runTest(self):
rv, es = guess_edit(self.initial_line, self.a, self.b, Position(*self.ppos), Position(*self.pos))
self.assertEqual(rv, True)
self.assertEqual(self.wanted, es)
class TestGuessing_Noop0(_BaseGuessing, unittest.TestCase):
a, b = [], []
initial_line = 0
ppos, pos = (0, 6), (0, 7)
wanted = ()
class TestGuessing_InsertOneChar(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 6), (0, 7)
wanted = (
("I", 0, 6, " "),
)
class TestGuessing_InsertOneChar1(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 7), (0, 8)
wanted = (
("I", 0, 7, " "),
)
class TestGuessing_BackspaceOneChar(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 7), (0, 6)
wanted = (
("D", 0, 6, " "),
)
class TestGuessing_DeleteOneChar(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 5), (0, 5)
wanted = (
("D", 0, 5, " "),
)
# End: Test Guessing }}}
class _Base(object):
def runTest(self):
es = diff(self.a, self.b)
tr = transform(self.a, es)
self.assertEqual(self.b, tr)
self.assertEqual(self.wanted, es)
class TestEmptyString(_Base, unittest.TestCase):
a, b = "", ""
wanted = ()
class TestAllMatch(_Base, unittest.TestCase):
a, b = "abcdef", "abcdef"
wanted = ()
class TestLotsaNewlines(_Base, unittest.TestCase):
a, b = "Hello", "Hello\nWorld\nWorld\nWorld"
wanted = (
("I", 0, 5, "\n"),
("I", 1, 0, "World"),
("I", 1, 5, "\n"),
("I", 2, 0, "World"),
("I", 2, 5, "\n"),
("I", 3, 0, "World"),
)
class TestCrash(_Base, unittest.TestCase):
a = 'hallo Blah mitte=sdfdsfsd\nhallo kjsdhfjksdhfkjhsdfkh mittekjshdkfhkhsdfdsf'
b = 'hallo Blah mitte=sdfdsfsd\nhallo b mittekjshdkfhkhsdfdsf'
wanted = (
("D", 1, 6, "kjsdhfjksdhfkjhsdfkh"),
("I", 1, 6, "b"),
)
class TestRealLife(_Base, unittest.TestCase):
a = 'hallo End Beginning'
b = 'hallo End t'
wanted = (
("D", 0, 10, "Beginning"),
("I", 0, 10, "t"),
)
class TestRealLife1(_Base, unittest.TestCase):
a = 'Vorne hallo Hinten'
b = 'Vorne hallo Hinten'
wanted = (
("I", 0, 11, " "),
)
class TestWithNewline(_Base, unittest.TestCase):
a = 'First Line\nSecond Line'
b = 'n'
wanted = (
("D", 0, 0, "First Line"),
("D", 0, 0, "\n"),
("D", 0, 0, "Second Line"),
("I", 0, 0, "n"),
)
class TestCheapDelete(_Base, unittest.TestCase):
a = 'Vorne hallo Hinten'
b = 'Vorne Hinten'
wanted = (
("D", 0, 5, " hallo"),
)
| wanted = (
("D", 0, 0, "abc"),
("I", 0, 0, "def"),
)
class TestCommonCharacters(_Base, unittest.TestCase):
a,b = "hasomelongertextbl", "hol"
wanted = (
("D", 0, 1, "asomelongertextb"),
("I", 0, 1, "o"),
)
class TestUltiSnipsProblem(_Base, unittest.TestCase):
a = "this is it this is it this is it"
b = "this is it a this is it"
wanted = (
("D", 0, 11, "this is it"),
("I", 0, 11, "a"),
)
class MatchIsTooCheap(_Base, unittest.TestCase):
a = "stdin.h"
b = "s"
wanted = (
("D", 0, 1, "tdin.h"),
)
class MultiLine(_Base, unittest.TestCase):
a = "hi first line\nsecond line first line\nsecond line world"
b = "hi first line\nsecond line k world"
wanted = (
("D", 1, 12, "first line"),
("D", 1, 12, "\n"),
("D", 1, 12, "second line"),
("I", 1, 12, "k"),
)
if __name__ == '__main__':
unittest.main()
# k = TestEditScript()
# unittest.TextTestRunner().run(k) | class TestNoSubstring(_Base, unittest.TestCase):
a,b = "abc", "def" | random_line_split |
test_diff.py | #!/usr/bin/env python
# encoding: utf-8
import unittest
import os.path as p, sys; sys.path.append(p.join(p.dirname(__file__), ".."))
from _diff import diff, guess_edit
from geometry import Position
def transform(a, cmds):
buf = a.split("\n")
for cmd in cmds:
ctype, line, col, char = cmd
if ctype == "D":
if char != '\n':
buf[line] = buf[line][:col] + buf[line][col+len(char):]
else:
buf[line] = buf[line] + buf[line+1]
del buf[line+1]
elif ctype == "I":
buf[line] = buf[line][:col] + char + buf[line][col:]
buf = '\n'.join(buf).split('\n')
return '\n'.join(buf)
import unittest
# Test Guessing {{{
class _BaseGuessing(object):
def runTest(self):
rv, es = guess_edit(self.initial_line, self.a, self.b, Position(*self.ppos), Position(*self.pos))
self.assertEqual(rv, True)
self.assertEqual(self.wanted, es)
class TestGuessing_Noop0(_BaseGuessing, unittest.TestCase):
a, b = [], []
initial_line = 0
ppos, pos = (0, 6), (0, 7)
wanted = ()
class TestGuessing_InsertOneChar(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 6), (0, 7)
wanted = (
("I", 0, 6, " "),
)
class TestGuessing_InsertOneChar1(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 7), (0, 8)
wanted = (
("I", 0, 7, " "),
)
class TestGuessing_BackspaceOneChar(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 7), (0, 6)
wanted = (
("D", 0, 6, " "),
)
class TestGuessing_DeleteOneChar(_BaseGuessing, unittest.TestCase):
a, b = ["Hello World"], ["Hello World"]
initial_line = 0
ppos, pos = (0, 5), (0, 5)
wanted = (
("D", 0, 5, " "),
)
# End: Test Guessing }}}
class _Base(object):
def runTest(self):
es = diff(self.a, self.b)
tr = transform(self.a, es)
self.assertEqual(self.b, tr)
self.assertEqual(self.wanted, es)
class TestEmptyString(_Base, unittest.TestCase):
a, b = "", ""
wanted = ()
class | (_Base, unittest.TestCase):
a, b = "abcdef", "abcdef"
wanted = ()
class TestLotsaNewlines(_Base, unittest.TestCase):
a, b = "Hello", "Hello\nWorld\nWorld\nWorld"
wanted = (
("I", 0, 5, "\n"),
("I", 1, 0, "World"),
("I", 1, 5, "\n"),
("I", 2, 0, "World"),
("I", 2, 5, "\n"),
("I", 3, 0, "World"),
)
class TestCrash(_Base, unittest.TestCase):
a = 'hallo Blah mitte=sdfdsfsd\nhallo kjsdhfjksdhfkjhsdfkh mittekjshdkfhkhsdfdsf'
b = 'hallo Blah mitte=sdfdsfsd\nhallo b mittekjshdkfhkhsdfdsf'
wanted = (
("D", 1, 6, "kjsdhfjksdhfkjhsdfkh"),
("I", 1, 6, "b"),
)
class TestRealLife(_Base, unittest.TestCase):
a = 'hallo End Beginning'
b = 'hallo End t'
wanted = (
("D", 0, 10, "Beginning"),
("I", 0, 10, "t"),
)
class TestRealLife1(_Base, unittest.TestCase):
a = 'Vorne hallo Hinten'
b = 'Vorne hallo Hinten'
wanted = (
("I", 0, 11, " "),
)
class TestWithNewline(_Base, unittest.TestCase):
a = 'First Line\nSecond Line'
b = 'n'
wanted = (
("D", 0, 0, "First Line"),
("D", 0, 0, "\n"),
("D", 0, 0, "Second Line"),
("I", 0, 0, "n"),
)
class TestCheapDelete(_Base, unittest.TestCase):
a = 'Vorne hallo Hinten'
b = 'Vorne Hinten'
wanted = (
("D", 0, 5, " hallo"),
)
class TestNoSubstring(_Base, unittest.TestCase):
a,b = "abc", "def"
wanted = (
("D", 0, 0, "abc"),
("I", 0, 0, "def"),
)
class TestCommonCharacters(_Base, unittest.TestCase):
a,b = "hasomelongertextbl", "hol"
wanted = (
("D", 0, 1, "asomelongertextb"),
("I", 0, 1, "o"),
)
class TestUltiSnipsProblem(_Base, unittest.TestCase):
a = "this is it this is it this is it"
b = "this is it a this is it"
wanted = (
("D", 0, 11, "this is it"),
("I", 0, 11, "a"),
)
class MatchIsTooCheap(_Base, unittest.TestCase):
a = "stdin.h"
b = "s"
wanted = (
("D", 0, 1, "tdin.h"),
)
class MultiLine(_Base, unittest.TestCase):
a = "hi first line\nsecond line first line\nsecond line world"
b = "hi first line\nsecond line k world"
wanted = (
("D", 1, 12, "first line"),
("D", 1, 12, "\n"),
("D", 1, 12, "second line"),
("I", 1, 12, "k"),
)
if __name__ == '__main__':
unittest.main()
# k = TestEditScript()
# unittest.TextTestRunner().run(k)
| TestAllMatch | identifier_name |
views.py | from django.shortcuts import render
from django.conf import settings
from common.views import AbsSegmentSelection
#from common.views import AbsTargetSelection
from common.views import AbsTargetSelectionTable
# from common.alignment_SITE_NAME import Alignment
from protwis.context_processors import site_title
Alignment = getattr(__import__('common.alignment_' + settings.SITE_NAME, fromlist=['Alignment']), 'Alignment')
from collections import OrderedDict
class | (AbsTargetSelectionTable):
step = 1
number_of_steps = 2
title = "SELECT RECEPTORS"
description = "Select receptors in the table (below) or browse the classification tree (right). You can select entire" \
+ " families or individual receptors.\n\nOnce you have selected all your receptors, click the green button."
docs = "sequences.html#similarity-matrix"
selection_boxes = OrderedDict([
("reference", False),
("targets", True),
("segments", False),
])
buttons = {
"continue": {
"label": "Next",
"onclick": "submitSelection('/similaritymatrix/segmentselection');",
"color": "success",
},
}
# class TargetSelection(AbsTargetSelection):
# step = 1
# number_of_steps = 2
# docs = 'sequences.html#similarity-matrix'
# selection_boxes = OrderedDict([
# ('reference', False),
# ('targets', True),
# ('segments', False),
# ])
# buttons = {
# 'continue': {
# 'label': 'Continue to next step',
# 'url': '/similaritymatrix/segmentselection',
# 'color': 'success',
# },
# }
class SegmentSelection(AbsSegmentSelection):
step = 2
number_of_steps = 2
docs = 'sequences.html#similarity-matrix'
selection_boxes = OrderedDict([
('reference', False),
('targets', False),
('segments', True),
])
buttons = {
'continue': {
'label': 'Show matrix',
'url': '/similaritymatrix/render',
'color': 'success',
},
}
def render_matrix(request):
# get the user selection from session
simple_selection = request.session.get('selection', False)
# create an alignment object
a = Alignment()
# load data from selection into the alignment
a.load_proteins_from_selection(simple_selection)
a.load_segments_from_selection(simple_selection)
# build the alignment data matrix
a.build_alignment()
# NOTE: NOT necessary for similarity matrix
# calculate consensus sequence + amino acid and feature frequency
# a.calculate_statistics()
# calculate identity and similarity of each row compared to the reference
a.calculate_similarity_matrix()
return render(request, 'similaritymatrix/matrix.html', {'p': a.proteins, 'm': a.similarity_matrix})
def render_csv_matrix(request):
# get the user selection from session
simple_selection = request.session.get('selection', False)
# create an alignment object
a = Alignment()
a.show_padding = False
# load data from selection into the alignment
a.load_proteins_from_selection(simple_selection)
a.load_segments_from_selection(simple_selection)
# build the alignment data matrix
a.build_alignment()
# calculate consensus sequence + amino acid and feature frequency
# NOTE: NOT necessary for similarity matrix
# a.calculate_statistics()
# calculate identity and similarity of each row compared to the reference
a.calculate_similarity_matrix()
response = render(request, 'similaritymatrix/matrix_csv.html', {'p': a.proteins, 'm': a.similarity_matrix})
response['Content-Disposition'] = "attachment; filename=" + site_title(request)["site_title"] + "_similaritymatrix.csv"
return response
| TargetSelection | identifier_name |
views.py | from django.shortcuts import render
from django.conf import settings
from common.views import AbsSegmentSelection
#from common.views import AbsTargetSelection
from common.views import AbsTargetSelectionTable
# from common.alignment_SITE_NAME import Alignment
from protwis.context_processors import site_title
Alignment = getattr(__import__('common.alignment_' + settings.SITE_NAME, fromlist=['Alignment']), 'Alignment')
from collections import OrderedDict
class TargetSelection(AbsTargetSelectionTable):
step = 1
number_of_steps = 2
title = "SELECT RECEPTORS"
description = "Select receptors in the table (below) or browse the classification tree (right). You can select entire" \
+ " families or individual receptors.\n\nOnce you have selected all your receptors, click the green button."
docs = "sequences.html#similarity-matrix"
selection_boxes = OrderedDict([
("reference", False),
("targets", True),
("segments", False),
])
buttons = {
"continue": {
"label": "Next",
"onclick": "submitSelection('/similaritymatrix/segmentselection');",
"color": "success",
},
}
# class TargetSelection(AbsTargetSelection):
# step = 1
# number_of_steps = 2
# docs = 'sequences.html#similarity-matrix'
# selection_boxes = OrderedDict([
# ('reference', False),
# ('targets', True),
# ('segments', False),
# ])
# buttons = {
# 'continue': {
# 'label': 'Continue to next step',
# 'url': '/similaritymatrix/segmentselection',
# 'color': 'success',
# },
# }
class SegmentSelection(AbsSegmentSelection):
step = 2
number_of_steps = 2
docs = 'sequences.html#similarity-matrix'
selection_boxes = OrderedDict([
('reference', False),
('targets', False),
('segments', True),
])
buttons = {
'continue': {
'label': 'Show matrix',
'url': '/similaritymatrix/render',
'color': 'success',
},
}
def render_matrix(request):
# get the user selection from session
|
def render_csv_matrix(request):
# get the user selection from session
simple_selection = request.session.get('selection', False)
# create an alignment object
a = Alignment()
a.show_padding = False
# load data from selection into the alignment
a.load_proteins_from_selection(simple_selection)
a.load_segments_from_selection(simple_selection)
# build the alignment data matrix
a.build_alignment()
# calculate consensus sequence + amino acid and feature frequency
# NOTE: NOT necessary for similarity matrix
# a.calculate_statistics()
# calculate identity and similarity of each row compared to the reference
a.calculate_similarity_matrix()
response = render(request, 'similaritymatrix/matrix_csv.html', {'p': a.proteins, 'm': a.similarity_matrix})
response['Content-Disposition'] = "attachment; filename=" + site_title(request)["site_title"] + "_similaritymatrix.csv"
return response
| simple_selection = request.session.get('selection', False)
# create an alignment object
a = Alignment()
# load data from selection into the alignment
a.load_proteins_from_selection(simple_selection)
a.load_segments_from_selection(simple_selection)
# build the alignment data matrix
a.build_alignment()
# NOTE: NOT necessary for similarity matrix
# calculate consensus sequence + amino acid and feature frequency
# a.calculate_statistics()
# calculate identity and similarity of each row compared to the reference
a.calculate_similarity_matrix()
return render(request, 'similaritymatrix/matrix.html', {'p': a.proteins, 'm': a.similarity_matrix}) | identifier_body |
views.py | from django.shortcuts import render
from django.conf import settings
from common.views import AbsSegmentSelection
#from common.views import AbsTargetSelection
from common.views import AbsTargetSelectionTable
# from common.alignment_SITE_NAME import Alignment
from protwis.context_processors import site_title
Alignment = getattr(__import__('common.alignment_' + settings.SITE_NAME, fromlist=['Alignment']), 'Alignment')
from collections import OrderedDict
class TargetSelection(AbsTargetSelectionTable):
step = 1
number_of_steps = 2
title = "SELECT RECEPTORS"
description = "Select receptors in the table (below) or browse the classification tree (right). You can select entire" \
+ " families or individual receptors.\n\nOnce you have selected all your receptors, click the green button."
docs = "sequences.html#similarity-matrix"
selection_boxes = OrderedDict([
("reference", False),
("targets", True),
("segments", False),
])
buttons = {
"continue": {
"label": "Next",
"onclick": "submitSelection('/similaritymatrix/segmentselection');",
"color": "success",
},
}
# class TargetSelection(AbsTargetSelection):
# step = 1
# number_of_steps = 2
# docs = 'sequences.html#similarity-matrix'
# selection_boxes = OrderedDict([
# ('reference', False),
# ('targets', True),
# ('segments', False),
# ])
# buttons = { | # },
# }
class SegmentSelection(AbsSegmentSelection):
step = 2
number_of_steps = 2
docs = 'sequences.html#similarity-matrix'
selection_boxes = OrderedDict([
('reference', False),
('targets', False),
('segments', True),
])
buttons = {
'continue': {
'label': 'Show matrix',
'url': '/similaritymatrix/render',
'color': 'success',
},
}
def render_matrix(request):
# get the user selection from session
simple_selection = request.session.get('selection', False)
# create an alignment object
a = Alignment()
# load data from selection into the alignment
a.load_proteins_from_selection(simple_selection)
a.load_segments_from_selection(simple_selection)
# build the alignment data matrix
a.build_alignment()
# NOTE: NOT necessary for similarity matrix
# calculate consensus sequence + amino acid and feature frequency
# a.calculate_statistics()
# calculate identity and similarity of each row compared to the reference
a.calculate_similarity_matrix()
return render(request, 'similaritymatrix/matrix.html', {'p': a.proteins, 'm': a.similarity_matrix})
def render_csv_matrix(request):
# get the user selection from session
simple_selection = request.session.get('selection', False)
# create an alignment object
a = Alignment()
a.show_padding = False
# load data from selection into the alignment
a.load_proteins_from_selection(simple_selection)
a.load_segments_from_selection(simple_selection)
# build the alignment data matrix
a.build_alignment()
# calculate consensus sequence + amino acid and feature frequency
# NOTE: NOT necessary for similarity matrix
# a.calculate_statistics()
# calculate identity and similarity of each row compared to the reference
a.calculate_similarity_matrix()
response = render(request, 'similaritymatrix/matrix_csv.html', {'p': a.proteins, 'm': a.similarity_matrix})
response['Content-Disposition'] = "attachment; filename=" + site_title(request)["site_title"] + "_similaritymatrix.csv"
return response | # 'continue': {
# 'label': 'Continue to next step',
# 'url': '/similaritymatrix/segmentselection',
# 'color': 'success', | random_line_split |
forEach.js | "use strict";
var Activity = require("./activity");
var util = require("util");
var _ = require("lodash");
var is = require("../common/is");
var Block = require("./block");
var WithBody = require("./withBody");
var errors = require("../common/errors");
function ForEach() |
util.inherits(ForEach, WithBody);
ForEach.prototype.initializeStructure = function () {
if (this.parallel) {
var numCPUs = require("os").cpus().length;
this._bodies = [];
if (this.args && this.args.length) {
for (var i = 0; i < Math.min(process.env.UV_THREADPOOL_SIZE || 100000, numCPUs); i++) {
var newArgs = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var arg = _step.value;
if (arg instanceof Activity) {
newArgs.push(arg.clone());
} else {
newArgs.push(arg);
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
var newBody = new Block();
newBody.args = newArgs;
this._bodies.push(newBody);
}
}
this.args = null;
} else {
WithBody.prototype.initializeStructure.call(this);
}
};
ForEach.prototype.run = function (callContext, args) {
var varName = this.varName;
var items = this.items;
if (!_.isNull(items)) {
this[varName] = null;
callContext.schedule(items, "_itemsGot");
} else {
callContext.complete();
}
};
ForEach.prototype._itemsGot = function (callContext, reason, result) {
if (reason === Activity.states.complete && !_.isUndefined(result)) {
if (result && _.isFunction(result.next)) {
this._iterator = result;
} else {
this._remainingItems = _.isArray(result) ? result : [result];
}
callContext.activity._doStep.call(this, callContext);
} else {
callContext.end(reason, result);
}
};
ForEach.prototype._doStep = function (callContext, lastResult) {
var varName = this.varName;
var remainingItems = this._remainingItems;
var iterator = this._iterator;
if (remainingItems && remainingItems.length) {
if (this.parallel) {
var bodies = this._bodies;
var pack = [];
var idx = 0;
while (remainingItems.length && idx < bodies.length) {
var item = remainingItems[0];
remainingItems.splice(0, 1);
var variables = {};
variables[varName] = item;
pack.push({
variables: variables,
activity: bodies[idx++]
});
}
callContext.schedule(pack, "_bodyFinished");
} else {
var item = remainingItems[0];
remainingItems.splice(0, 1);
var variables = {};
variables[varName] = item;
callContext.schedule({ activity: this._body, variables: variables }, "_bodyFinished");
}
return;
}
if (iterator) {
if (this.parallel) {
callContext.fail(new errors.ActivityRuntimeError("Parallel execution not supported with generators."));
return;
} else {
var next = iterator.next();
if (!next.done) {
var variables = {};
variables[varName] = next.value;
callContext.schedule({ activity: this._body, variables: variables }, "_bodyFinished");
return;
}
}
}
callContext.complete(lastResult);
};
ForEach.prototype._bodyFinished = function (callContext, reason, result) {
if (reason === Activity.states.complete) {
callContext.activity._doStep.call(this, callContext, result);
} else {
callContext.end(reason, result);
}
};
module.exports = ForEach;
//# sourceMappingURL=forEach.js.map
| {
WithBody.call(this);
this.items = null;
this.varName = "item";
this.parallel = false;
this._bodies = null;
} | identifier_body |
forEach.js | "use strict";
var Activity = require("./activity");
var util = require("util");
var _ = require("lodash");
var is = require("../common/is");
var Block = require("./block");
var WithBody = require("./withBody");
var errors = require("../common/errors");
function ForEach() {
WithBody.call(this);
this.items = null;
this.varName = "item";
this.parallel = false;
this._bodies = null;
}
util.inherits(ForEach, WithBody);
ForEach.prototype.initializeStructure = function () {
if (this.parallel) {
var numCPUs = require("os").cpus().length;
this._bodies = [];
if (this.args && this.args.length) {
for (var i = 0; i < Math.min(process.env.UV_THREADPOOL_SIZE || 100000, numCPUs); i++) {
var newArgs = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var arg = _step.value;
if (arg instanceof Activity) {
newArgs.push(arg.clone());
} else {
newArgs.push(arg);
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
var newBody = new Block();
newBody.args = newArgs;
this._bodies.push(newBody);
}
}
this.args = null;
} else {
WithBody.prototype.initializeStructure.call(this);
}
};
ForEach.prototype.run = function (callContext, args) {
var varName = this.varName;
var items = this.items;
if (!_.isNull(items)) {
this[varName] = null;
callContext.schedule(items, "_itemsGot");
} else {
callContext.complete();
}
};
ForEach.prototype._itemsGot = function (callContext, reason, result) {
if (reason === Activity.states.complete && !_.isUndefined(result)) {
if (result && _.isFunction(result.next)) {
this._iterator = result;
} else {
this._remainingItems = _.isArray(result) ? result : [result];
}
callContext.activity._doStep.call(this, callContext);
} else {
callContext.end(reason, result);
}
};
ForEach.prototype._doStep = function (callContext, lastResult) {
var varName = this.varName;
var remainingItems = this._remainingItems;
var iterator = this._iterator; | while (remainingItems.length && idx < bodies.length) {
var item = remainingItems[0];
remainingItems.splice(0, 1);
var variables = {};
variables[varName] = item;
pack.push({
variables: variables,
activity: bodies[idx++]
});
}
callContext.schedule(pack, "_bodyFinished");
} else {
var item = remainingItems[0];
remainingItems.splice(0, 1);
var variables = {};
variables[varName] = item;
callContext.schedule({ activity: this._body, variables: variables }, "_bodyFinished");
}
return;
}
if (iterator) {
if (this.parallel) {
callContext.fail(new errors.ActivityRuntimeError("Parallel execution not supported with generators."));
return;
} else {
var next = iterator.next();
if (!next.done) {
var variables = {};
variables[varName] = next.value;
callContext.schedule({ activity: this._body, variables: variables }, "_bodyFinished");
return;
}
}
}
callContext.complete(lastResult);
};
ForEach.prototype._bodyFinished = function (callContext, reason, result) {
if (reason === Activity.states.complete) {
callContext.activity._doStep.call(this, callContext, result);
} else {
callContext.end(reason, result);
}
};
module.exports = ForEach;
//# sourceMappingURL=forEach.js.map | if (remainingItems && remainingItems.length) {
if (this.parallel) {
var bodies = this._bodies;
var pack = [];
var idx = 0; | random_line_split |
forEach.js | "use strict";
var Activity = require("./activity");
var util = require("util");
var _ = require("lodash");
var is = require("../common/is");
var Block = require("./block");
var WithBody = require("./withBody");
var errors = require("../common/errors");
function ForEach() {
WithBody.call(this);
this.items = null;
this.varName = "item";
this.parallel = false;
this._bodies = null;
}
util.inherits(ForEach, WithBody);
ForEach.prototype.initializeStructure = function () {
if (this.parallel) {
var numCPUs = require("os").cpus().length;
this._bodies = [];
if (this.args && this.args.length) {
for (var i = 0; i < Math.min(process.env.UV_THREADPOOL_SIZE || 100000, numCPUs); i++) {
var newArgs = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var arg = _step.value;
if (arg instanceof Activity) {
newArgs.push(arg.clone());
} else {
newArgs.push(arg);
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
var newBody = new Block();
newBody.args = newArgs;
this._bodies.push(newBody);
}
}
this.args = null;
} else {
WithBody.prototype.initializeStructure.call(this);
}
};
ForEach.prototype.run = function (callContext, args) {
var varName = this.varName;
var items = this.items;
if (!_.isNull(items)) {
this[varName] = null;
callContext.schedule(items, "_itemsGot");
} else {
callContext.complete();
}
};
ForEach.prototype._itemsGot = function (callContext, reason, result) {
if (reason === Activity.states.complete && !_.isUndefined(result)) {
if (result && _.isFunction(result.next)) {
this._iterator = result;
} else {
this._remainingItems = _.isArray(result) ? result : [result];
}
callContext.activity._doStep.call(this, callContext);
} else {
callContext.end(reason, result);
}
};
ForEach.prototype._doStep = function (callContext, lastResult) {
var varName = this.varName;
var remainingItems = this._remainingItems;
var iterator = this._iterator;
if (remainingItems && remainingItems.length) {
if (this.parallel) | else {
var item = remainingItems[0];
remainingItems.splice(0, 1);
var variables = {};
variables[varName] = item;
callContext.schedule({ activity: this._body, variables: variables }, "_bodyFinished");
}
return;
}
if (iterator) {
if (this.parallel) {
callContext.fail(new errors.ActivityRuntimeError("Parallel execution not supported with generators."));
return;
} else {
var next = iterator.next();
if (!next.done) {
var variables = {};
variables[varName] = next.value;
callContext.schedule({ activity: this._body, variables: variables }, "_bodyFinished");
return;
}
}
}
callContext.complete(lastResult);
};
ForEach.prototype._bodyFinished = function (callContext, reason, result) {
if (reason === Activity.states.complete) {
callContext.activity._doStep.call(this, callContext, result);
} else {
callContext.end(reason, result);
}
};
module.exports = ForEach;
//# sourceMappingURL=forEach.js.map
| {
var bodies = this._bodies;
var pack = [];
var idx = 0;
while (remainingItems.length && idx < bodies.length) {
var item = remainingItems[0];
remainingItems.splice(0, 1);
var variables = {};
variables[varName] = item;
pack.push({
variables: variables,
activity: bodies[idx++]
});
}
callContext.schedule(pack, "_bodyFinished");
} | conditional_block |
forEach.js | "use strict";
var Activity = require("./activity");
var util = require("util");
var _ = require("lodash");
var is = require("../common/is");
var Block = require("./block");
var WithBody = require("./withBody");
var errors = require("../common/errors");
function | () {
WithBody.call(this);
this.items = null;
this.varName = "item";
this.parallel = false;
this._bodies = null;
}
util.inherits(ForEach, WithBody);
ForEach.prototype.initializeStructure = function () {
if (this.parallel) {
var numCPUs = require("os").cpus().length;
this._bodies = [];
if (this.args && this.args.length) {
for (var i = 0; i < Math.min(process.env.UV_THREADPOOL_SIZE || 100000, numCPUs); i++) {
var newArgs = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var arg = _step.value;
if (arg instanceof Activity) {
newArgs.push(arg.clone());
} else {
newArgs.push(arg);
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
var newBody = new Block();
newBody.args = newArgs;
this._bodies.push(newBody);
}
}
this.args = null;
} else {
WithBody.prototype.initializeStructure.call(this);
}
};
ForEach.prototype.run = function (callContext, args) {
var varName = this.varName;
var items = this.items;
if (!_.isNull(items)) {
this[varName] = null;
callContext.schedule(items, "_itemsGot");
} else {
callContext.complete();
}
};
ForEach.prototype._itemsGot = function (callContext, reason, result) {
if (reason === Activity.states.complete && !_.isUndefined(result)) {
if (result && _.isFunction(result.next)) {
this._iterator = result;
} else {
this._remainingItems = _.isArray(result) ? result : [result];
}
callContext.activity._doStep.call(this, callContext);
} else {
callContext.end(reason, result);
}
};
ForEach.prototype._doStep = function (callContext, lastResult) {
var varName = this.varName;
var remainingItems = this._remainingItems;
var iterator = this._iterator;
if (remainingItems && remainingItems.length) {
if (this.parallel) {
var bodies = this._bodies;
var pack = [];
var idx = 0;
while (remainingItems.length && idx < bodies.length) {
var item = remainingItems[0];
remainingItems.splice(0, 1);
var variables = {};
variables[varName] = item;
pack.push({
variables: variables,
activity: bodies[idx++]
});
}
callContext.schedule(pack, "_bodyFinished");
} else {
var item = remainingItems[0];
remainingItems.splice(0, 1);
var variables = {};
variables[varName] = item;
callContext.schedule({ activity: this._body, variables: variables }, "_bodyFinished");
}
return;
}
if (iterator) {
if (this.parallel) {
callContext.fail(new errors.ActivityRuntimeError("Parallel execution not supported with generators."));
return;
} else {
var next = iterator.next();
if (!next.done) {
var variables = {};
variables[varName] = next.value;
callContext.schedule({ activity: this._body, variables: variables }, "_bodyFinished");
return;
}
}
}
callContext.complete(lastResult);
};
ForEach.prototype._bodyFinished = function (callContext, reason, result) {
if (reason === Activity.states.complete) {
callContext.activity._doStep.call(this, callContext, result);
} else {
callContext.end(reason, result);
}
};
module.exports = ForEach;
//# sourceMappingURL=forEach.js.map
| ForEach | identifier_name |
firstValueFrom.ts | import { Observable } from './Observable';
import { EmptyError } from './util/EmptyError';
import { SafeSubscriber } from './Subscriber';
export interface FirstValueFromConfig<T> {
defaultValue: T;
}
export function firstValueFrom<T, D>(source: Observable<T>, config: FirstValueFromConfig<D>): Promise<T | D>;
export function firstValueFrom<T>(source: Observable<T>): Promise<T>;
/**
* Converts an observable to a promise by subscribing to the observable,
* and returning a promise that will resolve as soon as the first value
* arrives from the observable. The subscription will then be closed.
*
* If the observable stream completes before any values were emitted, the
* returned promise will reject with {@link EmptyError} or will resolve
* with the default value if a default was specified.
*
* If the observable stream emits an error, the returned promise will reject
* with that error.
*
* **WARNING**: Only use this with observables you *know* will emit at least one value,
* *OR* complete. If the source observable does not emit one value or complete, you will
* end up with a promise that is hung up, and potentially all of the state of an
* async function hanging out in memory. To avoid this situation, look into adding
* something like {@link timeout}, {@link take}, {@link takeWhile}, or {@link takeUntil}
* amongst others.
*
* ### Example
*
* Wait for the first value from a stream and emit it from a promise in
* an async function.
*
* ```ts
* import { interval, firstValueFrom } from 'rxjs';
*
* async function execute() {
* const source$ = interval(2000);
* const firstNumber = await firstValueFrom(source$);
* console.log(`The first number is ${firstNumber}`);
* }
*
* execute();
*
* // Expected output:
* // "The first number is 0"
* ```
*
* @see {@link lastValueFrom}
*
* @param source the observable to convert to a promise
* @param config a configuration object to define the `defaultValue` to use if the source completes without emitting a value
*/
export function firstValueFrom<T, D>(source: Observable<T>, config?: FirstValueFromConfig<D>): Promise<T | D> {
const hasConfig = typeof config === 'object';
return new Promise<T | D>((resolve, reject) => {
const subscriber = new SafeSubscriber<T>({
next: (value) => {
resolve(value);
subscriber.unsubscribe();
},
error: reject,
complete: () => {
if (hasConfig) {
resolve(config!.defaultValue);
} else |
},
});
source.subscribe(subscriber);
});
}
| {
reject(new EmptyError());
} | conditional_block |
firstValueFrom.ts | import { Observable } from './Observable';
import { EmptyError } from './util/EmptyError';
import { SafeSubscriber } from './Subscriber';
export interface FirstValueFromConfig<T> {
defaultValue: T;
}
export function firstValueFrom<T, D>(source: Observable<T>, config: FirstValueFromConfig<D>): Promise<T | D>;
export function firstValueFrom<T>(source: Observable<T>): Promise<T>;
/**
* Converts an observable to a promise by subscribing to the observable,
* and returning a promise that will resolve as soon as the first value
* arrives from the observable. The subscription will then be closed.
*
* If the observable stream completes before any values were emitted, the
* returned promise will reject with {@link EmptyError} or will resolve
* with the default value if a default was specified.
*
* If the observable stream emits an error, the returned promise will reject
* with that error.
*
* **WARNING**: Only use this with observables you *know* will emit at least one value,
* *OR* complete. If the source observable does not emit one value or complete, you will
* end up with a promise that is hung up, and potentially all of the state of an
* async function hanging out in memory. To avoid this situation, look into adding
* something like {@link timeout}, {@link take}, {@link takeWhile}, or {@link takeUntil}
* amongst others.
*
* ### Example
*
* Wait for the first value from a stream and emit it from a promise in
* an async function.
*
* ```ts
* import { interval, firstValueFrom } from 'rxjs';
*
* async function execute() {
* const source$ = interval(2000);
* const firstNumber = await firstValueFrom(source$);
* console.log(`The first number is ${firstNumber}`);
* }
*
* execute();
*
* // Expected output:
* // "The first number is 0"
* ```
*
* @see {@link lastValueFrom}
*
* @param source the observable to convert to a promise
* @param config a configuration object to define the `defaultValue` to use if the source completes without emitting a value
*/
export function firstValueFrom<T, D>(source: Observable<T>, config?: FirstValueFromConfig<D>): Promise<T | D> | {
const hasConfig = typeof config === 'object';
return new Promise<T | D>((resolve, reject) => {
const subscriber = new SafeSubscriber<T>({
next: (value) => {
resolve(value);
subscriber.unsubscribe();
},
error: reject,
complete: () => {
if (hasConfig) {
resolve(config!.defaultValue);
} else {
reject(new EmptyError());
}
},
});
source.subscribe(subscriber);
});
} | identifier_body | |
firstValueFrom.ts | import { Observable } from './Observable';
import { EmptyError } from './util/EmptyError';
import { SafeSubscriber } from './Subscriber';
export interface FirstValueFromConfig<T> {
defaultValue: T;
}
export function firstValueFrom<T, D>(source: Observable<T>, config: FirstValueFromConfig<D>): Promise<T | D>;
export function firstValueFrom<T>(source: Observable<T>): Promise<T>;
/**
* Converts an observable to a promise by subscribing to the observable,
* and returning a promise that will resolve as soon as the first value
* arrives from the observable. The subscription will then be closed.
*
* If the observable stream completes before any values were emitted, the
* returned promise will reject with {@link EmptyError} or will resolve
* with the default value if a default was specified.
*
* If the observable stream emits an error, the returned promise will reject
* with that error.
*
* **WARNING**: Only use this with observables you *know* will emit at least one value,
* *OR* complete. If the source observable does not emit one value or complete, you will
* end up with a promise that is hung up, and potentially all of the state of an
* async function hanging out in memory. To avoid this situation, look into adding
* something like {@link timeout}, {@link take}, {@link takeWhile}, or {@link takeUntil}
* amongst others.
*
* ### Example
*
* Wait for the first value from a stream and emit it from a promise in
* an async function.
*
* ```ts
* import { interval, firstValueFrom } from 'rxjs';
*
* async function execute() {
* const source$ = interval(2000);
* const firstNumber = await firstValueFrom(source$);
* console.log(`The first number is ${firstNumber}`);
* }
*
* execute();
*
* // Expected output:
* // "The first number is 0"
* ```
*
* @see {@link lastValueFrom}
*
* @param source the observable to convert to a promise
* @param config a configuration object to define the `defaultValue` to use if the source completes without emitting a value
*/
export function | <T, D>(source: Observable<T>, config?: FirstValueFromConfig<D>): Promise<T | D> {
const hasConfig = typeof config === 'object';
return new Promise<T | D>((resolve, reject) => {
const subscriber = new SafeSubscriber<T>({
next: (value) => {
resolve(value);
subscriber.unsubscribe();
},
error: reject,
complete: () => {
if (hasConfig) {
resolve(config!.defaultValue);
} else {
reject(new EmptyError());
}
},
});
source.subscribe(subscriber);
});
}
| firstValueFrom | identifier_name |
firstValueFrom.ts | import { Observable } from './Observable';
import { EmptyError } from './util/EmptyError';
import { SafeSubscriber } from './Subscriber';
export interface FirstValueFromConfig<T> {
defaultValue: T;
}
export function firstValueFrom<T, D>(source: Observable<T>, config: FirstValueFromConfig<D>): Promise<T | D>;
export function firstValueFrom<T>(source: Observable<T>): Promise<T>;
/**
* Converts an observable to a promise by subscribing to the observable,
* and returning a promise that will resolve as soon as the first value
* arrives from the observable. The subscription will then be closed.
*
* If the observable stream completes before any values were emitted, the
* returned promise will reject with {@link EmptyError} or will resolve
* with the default value if a default was specified.
*
* If the observable stream emits an error, the returned promise will reject
* with that error.
*
* **WARNING**: Only use this with observables you *know* will emit at least one value,
* *OR* complete. If the source observable does not emit one value or complete, you will
* end up with a promise that is hung up, and potentially all of the state of an
* async function hanging out in memory. To avoid this situation, look into adding | * Wait for the first value from a stream and emit it from a promise in
* an async function.
*
* ```ts
* import { interval, firstValueFrom } from 'rxjs';
*
* async function execute() {
* const source$ = interval(2000);
* const firstNumber = await firstValueFrom(source$);
* console.log(`The first number is ${firstNumber}`);
* }
*
* execute();
*
* // Expected output:
* // "The first number is 0"
* ```
*
* @see {@link lastValueFrom}
*
* @param source the observable to convert to a promise
* @param config a configuration object to define the `defaultValue` to use if the source completes without emitting a value
*/
export function firstValueFrom<T, D>(source: Observable<T>, config?: FirstValueFromConfig<D>): Promise<T | D> {
const hasConfig = typeof config === 'object';
return new Promise<T | D>((resolve, reject) => {
const subscriber = new SafeSubscriber<T>({
next: (value) => {
resolve(value);
subscriber.unsubscribe();
},
error: reject,
complete: () => {
if (hasConfig) {
resolve(config!.defaultValue);
} else {
reject(new EmptyError());
}
},
});
source.subscribe(subscriber);
});
} | * something like {@link timeout}, {@link take}, {@link takeWhile}, or {@link takeUntil}
* amongst others.
*
* ### Example
* | random_line_split |
categorical_color_mapper.ts | import {ColorMapper} from "./color_mapper"
import {Factor} from "../ranges/factor_range"
import * as p from "core/properties"
import {Arrayable} from "core/types"
import {findIndex} from "core/util/array"
import {isString} from "core/util/types"
function _equals(a: Arrayable<any>, b: Arrayable<any>): boolean {
if (a.length != b.length)
return false
for (let i = 0, end = a.length; i < end; i++) {
if (a[i] !== b[i])
return false
}
return true
}
export namespace CategoricalColorMapper {
export interface Attrs extends ColorMapper.Attrs {
factors: string[]
start: number
end: number
}
export interface Props extends ColorMapper.Props {}
}
export interface CategoricalColorMapper extends CategoricalColorMapper.Attrs {}
export class CategoricalColorMapper extends ColorMapper {
properties: CategoricalColorMapper.Props
constructor(attrs?: Partial<CategoricalColorMapper.Attrs>) {
super(attrs)
}
static initClass(): void {
this.prototype.type = "CategoricalColorMapper"
this.define({
factors: [ p.Array ],
start: [ p.Number, 0 ],
end: [ p.Number ],
}) | protected _v_compute<T>(data: Arrayable<Factor>, values: Arrayable<T>,
palette: Arrayable<T>, {nan_color}: {nan_color: T}): void {
for (let i = 0, end = data.length; i < end; i++) {
let d = data[i]
let key: number
if (isString(d))
key = this.factors.indexOf(d)
else {
if (this.start != null) {
if (this.end != null)
d = d.slice(this.start, this.end) as Factor
else
d = d.slice(this.start) as Factor
} else if (this.end != null)
d = d.slice(0, this.end) as Factor
if (d.length == 1)
key = this.factors.indexOf(d[0])
else
key = findIndex(this.factors, (x) => _equals(x, d))
}
let color: T
if (key < 0 || key >= palette.length)
color = nan_color
else
color = palette[key]
values[i] = color
}
}
}
CategoricalColorMapper.initClass() | }
| random_line_split |
categorical_color_mapper.ts | import {ColorMapper} from "./color_mapper"
import {Factor} from "../ranges/factor_range"
import * as p from "core/properties"
import {Arrayable} from "core/types"
import {findIndex} from "core/util/array"
import {isString} from "core/util/types"
function | (a: Arrayable<any>, b: Arrayable<any>): boolean {
if (a.length != b.length)
return false
for (let i = 0, end = a.length; i < end; i++) {
if (a[i] !== b[i])
return false
}
return true
}
export namespace CategoricalColorMapper {
export interface Attrs extends ColorMapper.Attrs {
factors: string[]
start: number
end: number
}
export interface Props extends ColorMapper.Props {}
}
export interface CategoricalColorMapper extends CategoricalColorMapper.Attrs {}
export class CategoricalColorMapper extends ColorMapper {
properties: CategoricalColorMapper.Props
constructor(attrs?: Partial<CategoricalColorMapper.Attrs>) {
super(attrs)
}
static initClass(): void {
this.prototype.type = "CategoricalColorMapper"
this.define({
factors: [ p.Array ],
start: [ p.Number, 0 ],
end: [ p.Number ],
})
}
protected _v_compute<T>(data: Arrayable<Factor>, values: Arrayable<T>,
palette: Arrayable<T>, {nan_color}: {nan_color: T}): void {
for (let i = 0, end = data.length; i < end; i++) {
let d = data[i]
let key: number
if (isString(d))
key = this.factors.indexOf(d)
else {
if (this.start != null) {
if (this.end != null)
d = d.slice(this.start, this.end) as Factor
else
d = d.slice(this.start) as Factor
} else if (this.end != null)
d = d.slice(0, this.end) as Factor
if (d.length == 1)
key = this.factors.indexOf(d[0])
else
key = findIndex(this.factors, (x) => _equals(x, d))
}
let color: T
if (key < 0 || key >= palette.length)
color = nan_color
else
color = palette[key]
values[i] = color
}
}
}
CategoricalColorMapper.initClass()
| _equals | identifier_name |
categorical_color_mapper.ts | import {ColorMapper} from "./color_mapper"
import {Factor} from "../ranges/factor_range"
import * as p from "core/properties"
import {Arrayable} from "core/types"
import {findIndex} from "core/util/array"
import {isString} from "core/util/types"
function _equals(a: Arrayable<any>, b: Arrayable<any>): boolean {
if (a.length != b.length)
return false
for (let i = 0, end = a.length; i < end; i++) {
if (a[i] !== b[i])
return false
}
return true
}
export namespace CategoricalColorMapper {
export interface Attrs extends ColorMapper.Attrs {
factors: string[]
start: number
end: number
}
export interface Props extends ColorMapper.Props {}
}
export interface CategoricalColorMapper extends CategoricalColorMapper.Attrs {}
export class CategoricalColorMapper extends ColorMapper {
properties: CategoricalColorMapper.Props
constructor(attrs?: Partial<CategoricalColorMapper.Attrs>) |
static initClass(): void {
this.prototype.type = "CategoricalColorMapper"
this.define({
factors: [ p.Array ],
start: [ p.Number, 0 ],
end: [ p.Number ],
})
}
protected _v_compute<T>(data: Arrayable<Factor>, values: Arrayable<T>,
palette: Arrayable<T>, {nan_color}: {nan_color: T}): void {
for (let i = 0, end = data.length; i < end; i++) {
let d = data[i]
let key: number
if (isString(d))
key = this.factors.indexOf(d)
else {
if (this.start != null) {
if (this.end != null)
d = d.slice(this.start, this.end) as Factor
else
d = d.slice(this.start) as Factor
} else if (this.end != null)
d = d.slice(0, this.end) as Factor
if (d.length == 1)
key = this.factors.indexOf(d[0])
else
key = findIndex(this.factors, (x) => _equals(x, d))
}
let color: T
if (key < 0 || key >= palette.length)
color = nan_color
else
color = palette[key]
values[i] = color
}
}
}
CategoricalColorMapper.initClass()
| {
super(attrs)
} | identifier_body |
rbf.py | import numpy as np
import tensorflow as tf
from .module import Module
class RBFExpansion(Module):
def __init__(self, low, high, gap, dim=1, name=None):
self.low = low
self.high = high
self.gap = gap
self.dim = dim
xrange = high - low
self.centers = np.linspace(low, high, int(np.ceil(xrange / gap)))
self.centers = self.centers[:, np.newaxis]
self.n_centers = len(self.centers)
self.fan_out = self.dim * self.n_centers
super(RBFExpansion, self).__init__(name)
def | (self, d):
cshape = tf.shape(d)
CS = d.get_shape()
centers = self.centers.reshape((1, -1)).astype(np.float32)
d -= tf.constant(centers)
rbf = tf.exp(-(d ** 2) / self.gap)
# rbf = tf.reshape(rbf, (
# cshape[0], cshape[1], cshape[2],
# self.dim * centers.shape[-1]))
rbf.set_shape([CS[0], self.fan_out])
return rbf
| _forward | identifier_name |
rbf.py | import numpy as np
import tensorflow as tf
from .module import Module
class RBFExpansion(Module):
def __init__(self, low, high, gap, dim=1, name=None):
self.low = low
self.high = high
self.gap = gap
self.dim = dim
xrange = high - low
self.centers = np.linspace(low, high, int(np.ceil(xrange / gap)))
self.centers = self.centers[:, np.newaxis]
self.n_centers = len(self.centers)
self.fan_out = self.dim * self.n_centers
super(RBFExpansion, self).__init__(name)
def _forward(self, d):
| cshape = tf.shape(d)
CS = d.get_shape()
centers = self.centers.reshape((1, -1)).astype(np.float32)
d -= tf.constant(centers)
rbf = tf.exp(-(d ** 2) / self.gap)
# rbf = tf.reshape(rbf, (
# cshape[0], cshape[1], cshape[2],
# self.dim * centers.shape[-1]))
rbf.set_shape([CS[0], self.fan_out])
return rbf | identifier_body | |
rbf.py | import numpy as np
import tensorflow as tf
from .module import Module
| class RBFExpansion(Module):
def __init__(self, low, high, gap, dim=1, name=None):
self.low = low
self.high = high
self.gap = gap
self.dim = dim
xrange = high - low
self.centers = np.linspace(low, high, int(np.ceil(xrange / gap)))
self.centers = self.centers[:, np.newaxis]
self.n_centers = len(self.centers)
self.fan_out = self.dim * self.n_centers
super(RBFExpansion, self).__init__(name)
def _forward(self, d):
cshape = tf.shape(d)
CS = d.get_shape()
centers = self.centers.reshape((1, -1)).astype(np.float32)
d -= tf.constant(centers)
rbf = tf.exp(-(d ** 2) / self.gap)
# rbf = tf.reshape(rbf, (
# cshape[0], cshape[1], cshape[2],
# self.dim * centers.shape[-1]))
rbf.set_shape([CS[0], self.fan_out])
return rbf | random_line_split | |
data_exportor.py | # -*- coding: utf-8 -*-
# @date 161103 - Export excel with get_work_order_report function
"""
Data exportor (Excel, CSV...)
"""
import io
import math
from datetime import datetime
from xlsxwriter.workbook import Workbook
import tablib
from utils.tools import get_product_size
def get_customers(customer_list=None, file_format='csv'):
"""Generate customer data file for download."""
if customer_list is None:
customer_list = []
data = tablib.Dataset()
data.headers = ('客戶代碼', '客戶名稱')
for c in customer_list:
data.append((c.c_code, c.c_name))
if file_format == 'csv':
return data.csv
return data
def get_maintenance_log(log_list=None, file_format='csv'):
"""Generate maintenance log to csv file for download."""
if log_list is None:
log_list = []
data = tablib.Dataset()
data.headers = ('機台', '維修項目', '開始時間',
'員工', '結束時間', '員工',
'總計時間')
for log in log_list:
m_code = log['m_code'].replace('<br>', '\n')
data.append((log['machine_id'], m_code, log['start_time'],
log['who_start'], log['end_time'], log['who_end'],
log['total_time'][0])
)
if file_format == 'csv':
return data.csv
return data
def get_w_m_performance_report(file_format='xls'):
"""Genera | by worker and machine performance."""
row_number = 11
data = tablib.Dataset()
data.append(['個人效率期間表 ({})'.format(
datetime.now().strftime("%Y/%m/%d"))] + [''] * (row_number - 1))
data.append(['工號', '姓名', '日期', '標準量', '效率標準量',
'實質生產量', '總稼動時間', '總停機時間', '稼動 %', '數量效率 %',
'平均效率 %'])
if file_format == 'xls':
return data.xls
return data
def get_loss_rate_report(report_data, file_format='csv'):
"""Generate csv file for download by machine loss rate."""
data = tablib.Dataset()
data.headers = ('機台', '機型', '良品數', '不良品數', '損耗率(%)',
'損耗金額(RMB)', '損耗率排名')
rank = 0
old_loss_rate = None
for r in sorted(report_data, key=lambda k: k['loss_rate'], reverse=True):
if old_loss_rate != r['loss_rate']:
rank += 1
old_loss_rate = r['loss_rate']
record = [r['machine_id'], r['machine_type'], r['count_qty'],
r['event_qty'], r['loss_rate'], r['total_loss_money'],
rank]
data.append(record)
if file_format == 'csv':
return data.csv
return data
def get_loss_rate_detail_report(report_data, file_format='csv'):
"""Generate csv file for download by machine loss rate detail."""
data = tablib.Dataset()
data.headers = ('日期', '良品數', '不良品數', '損耗率(%)',
'損耗金額(RMB)')
for r in sorted(report_data, key=lambda k: k['record_date']):
record = [r['record_date'], r['count_qty'], r['event_qty'],
r['loss_rate'], r['total_loss_money']]
data.append(record)
if file_format == 'csv':
return data.csv
return data
def get_uptime_report(report_data='', file_format='xls'):
"""Generate excel file for download by uptime information."""
data = tablib.Dataset()
data.append_separator('製造部各工程稼動率一覽表')
data.append(['月份:10', '星期', '', '', '', '', '',
'目標', '', '', '', ''])
data.append(['', '', '加締卷取(%)', '組立(%)', '老化(%)',
'CUTTING(%)', 'TAPPING(%)', '加締卷取',
'組立', '老化', 'CUTTING', 'TAPPING'])
if file_format == 'xls':
return data.xls
return data
def get_work_order_report(report_data, file_format='csv'):
"""Generate csv file for download by work order."""
# data = tablib.Dataset()
# data.headers = ('製令編號', '料號', '客戶', '產品規格',
# '投入數', '應繳庫數',
# '加締捲取', '組立', '老化', '選別', '加工切角')
# for r in sorted(report_data, key=lambda k: k['order_no']):
# try:
# intput_count = int(r['input_count'])
# except (TypeError, ValueError):
# intput_count = -1
# record = [r['order_no'], r['part_no'], r['customer'], r['product'],
# intput_count, math.floor(intput_count / 1.03),
# r['step1_status'], r['step2_status'], r['step3_status'],
# r['step4_status'], r['step5_status']]
# data.append(record)
# if file_format == 'csv':
# return data.csv
# return data
output = io.BytesIO()
if file_format == 'xls':
workbook = Workbook(output, {'in_memory': True})
worksheet = workbook.add_worksheet()
# merge_format = workbook.add_format({
# 'bold': 1,
# 'border': 1,
# 'align': 'center',
# 'valign': 'vcenter'})
worksheet.merge_range('A1:A3', '製令編號')
worksheet.merge_range('B1:B3', '料號')
worksheet.merge_range('C1:C3', '客戶')
worksheet.merge_range('D1:D3', '產品規格')
worksheet.merge_range('E1:E3', '投入數')
worksheet.merge_range('F1:F3', '應繳庫數')
worksheet.write('G1', '加締捲取')
worksheet.write('H1', '組立')
worksheet.write('I1', '老化')
worksheet.write('J1', '選別')
worksheet.write('K1', '加工切角')
for col_name in ('G', 'H', 'I', 'J', 'K'):
worksheet.write(col_name + '2', '機器')
worksheet.write(col_name + '3', '良品數')
row = 4
for r in sorted(report_data, key=lambda k: k['order_no']):
try:
intput_count = int(r['input_count'])
except (TypeError, ValueError):
intput_count = -1
worksheet.merge_range('A{}:A{}'.format(row, row + 2),
r['order_no'])
worksheet.merge_range('B{}:B{}'.format(row, row + 2), r['part_no'])
worksheet.merge_range('C{}:C{}'.format(row, row + 2),
r['customer'])
worksheet.merge_range('D{}:D{}'.format(row, row + 2), r['product'])
worksheet.merge_range('E{}:E{}'.format(row, row + 2), intput_count)
worksheet.merge_range('F{}:F{}'.format(row, row + 2),
math.floor(intput_count / 1.03))
for process in range(1, 6):
row_tag = chr(71 + process - 1)
worksheet.write_string('{}{}'.format(row_tag, row),
r['step{}_status'.format(process)])
machine = r['step{}_machine'.format(process)]
count = r['step{}_count'.format(process)]
worksheet.write_string('{}{}'.format(row_tag, row + 1),
machine if machine else '')
worksheet.write_string('{}{}'.format(row_tag, row + 2),
str(count) if count else '')
row += 3
workbook.close()
output.seek(0)
return output.read()
def get_order_report(report_data, file_format='csv'):
"""Generate csv file for download by machine loss rate detail."""
data = tablib.Dataset()
data.headers = ('製令編號', '客戶', '規格', '投入數', '需求數',
'加締捲曲', '組立', '老化', '選別', '加工切腳')
for r in sorted(report_data, key=lambda k: k['order_no']):
record = [r['order_no'], r['customer'], get_product_size(r['part_no']),
r['input_count'], r['require_count'],
r['step1_prod_qty'], r['step2_prod_qty'],
r['step3_prod_qty'], r['step4_prod_qty'],
r['step5_prod_qty']]
data.append(record)
if file_format == 'csv':
return data.csv
return data
| te excel file for download | identifier_name |
data_exportor.py | # -*- coding: utf-8 -*-
# @date 161103 - Export excel with get_work_order_report function
"""
Data exportor (Excel, CSV...)
"""
import io
import math
from datetime import datetime
from xlsxwriter.workbook import Workbook
import tablib
from utils.tools import get_product_size
def get_customers(customer_list=None, file_format='csv'):
"""Generate customer data file for download."""
if customer_list is None:
customer_list = []
data = tablib.Dataset()
data.headers = ('客戶代碼', '客戶名稱')
for c in customer_list:
data.append((c.c_code, c.c_name))
if file_format == 'csv':
return data.csv
return data
def get_maintenance_log(log_list=None, file_format='csv'): | data.headers = ('機台', '維修項目', '開始時間',
'員工', '結束時間', '員工',
'總計時間')
for log in log_list:
m_code = log['m_code'].replace('<br>', '\n')
data.append((log['machine_id'], m_code, log['start_time'],
log['who_start'], log['end_time'], log['who_end'],
log['total_time'][0])
)
if file_format == 'csv':
return data.csv
return data
def get_w_m_performance_report(file_format='xls'):
"""Generate excel file for download by worker and machine performance."""
row_number = 11
data = tablib.Dataset()
data.append(['個人效率期間表 ({})'.format(
datetime.now().strftime("%Y/%m/%d"))] + [''] * (row_number - 1))
data.append(['工號', '姓名', '日期', '標準量', '效率標準量',
'實質生產量', '總稼動時間', '總停機時間', '稼動 %', '數量效率 %',
'平均效率 %'])
if file_format == 'xls':
return data.xls
return data
def get_loss_rate_report(report_data, file_format='csv'):
"""Generate csv file for download by machine loss rate."""
data = tablib.Dataset()
data.headers = ('機台', '機型', '良品數', '不良品數', '損耗率(%)',
'損耗金額(RMB)', '損耗率排名')
rank = 0
old_loss_rate = None
for r in sorted(report_data, key=lambda k: k['loss_rate'], reverse=True):
if old_loss_rate != r['loss_rate']:
rank += 1
old_loss_rate = r['loss_rate']
record = [r['machine_id'], r['machine_type'], r['count_qty'],
r['event_qty'], r['loss_rate'], r['total_loss_money'],
rank]
data.append(record)
if file_format == 'csv':
return data.csv
return data
def get_loss_rate_detail_report(report_data, file_format='csv'):
"""Generate csv file for download by machine loss rate detail."""
data = tablib.Dataset()
data.headers = ('日期', '良品數', '不良品數', '損耗率(%)',
'損耗金額(RMB)')
for r in sorted(report_data, key=lambda k: k['record_date']):
record = [r['record_date'], r['count_qty'], r['event_qty'],
r['loss_rate'], r['total_loss_money']]
data.append(record)
if file_format == 'csv':
return data.csv
return data
def get_uptime_report(report_data='', file_format='xls'):
"""Generate excel file for download by uptime information."""
data = tablib.Dataset()
data.append_separator('製造部各工程稼動率一覽表')
data.append(['月份:10', '星期', '', '', '', '', '',
'目標', '', '', '', ''])
data.append(['', '', '加締卷取(%)', '組立(%)', '老化(%)',
'CUTTING(%)', 'TAPPING(%)', '加締卷取',
'組立', '老化', 'CUTTING', 'TAPPING'])
if file_format == 'xls':
return data.xls
return data
def get_work_order_report(report_data, file_format='csv'):
"""Generate csv file for download by work order."""
# data = tablib.Dataset()
# data.headers = ('製令編號', '料號', '客戶', '產品規格',
# '投入數', '應繳庫數',
# '加締捲取', '組立', '老化', '選別', '加工切角')
# for r in sorted(report_data, key=lambda k: k['order_no']):
# try:
# intput_count = int(r['input_count'])
# except (TypeError, ValueError):
# intput_count = -1
# record = [r['order_no'], r['part_no'], r['customer'], r['product'],
# intput_count, math.floor(intput_count / 1.03),
# r['step1_status'], r['step2_status'], r['step3_status'],
# r['step4_status'], r['step5_status']]
# data.append(record)
# if file_format == 'csv':
# return data.csv
# return data
output = io.BytesIO()
if file_format == 'xls':
workbook = Workbook(output, {'in_memory': True})
worksheet = workbook.add_worksheet()
# merge_format = workbook.add_format({
# 'bold': 1,
# 'border': 1,
# 'align': 'center',
# 'valign': 'vcenter'})
worksheet.merge_range('A1:A3', '製令編號')
worksheet.merge_range('B1:B3', '料號')
worksheet.merge_range('C1:C3', '客戶')
worksheet.merge_range('D1:D3', '產品規格')
worksheet.merge_range('E1:E3', '投入數')
worksheet.merge_range('F1:F3', '應繳庫數')
worksheet.write('G1', '加締捲取')
worksheet.write('H1', '組立')
worksheet.write('I1', '老化')
worksheet.write('J1', '選別')
worksheet.write('K1', '加工切角')
for col_name in ('G', 'H', 'I', 'J', 'K'):
worksheet.write(col_name + '2', '機器')
worksheet.write(col_name + '3', '良品數')
row = 4
for r in sorted(report_data, key=lambda k: k['order_no']):
try:
intput_count = int(r['input_count'])
except (TypeError, ValueError):
intput_count = -1
worksheet.merge_range('A{}:A{}'.format(row, row + 2),
r['order_no'])
worksheet.merge_range('B{}:B{}'.format(row, row + 2), r['part_no'])
worksheet.merge_range('C{}:C{}'.format(row, row + 2),
r['customer'])
worksheet.merge_range('D{}:D{}'.format(row, row + 2), r['product'])
worksheet.merge_range('E{}:E{}'.format(row, row + 2), intput_count)
worksheet.merge_range('F{}:F{}'.format(row, row + 2),
math.floor(intput_count / 1.03))
for process in range(1, 6):
row_tag = chr(71 + process - 1)
worksheet.write_string('{}{}'.format(row_tag, row),
r['step{}_status'.format(process)])
machine = r['step{}_machine'.format(process)]
count = r['step{}_count'.format(process)]
worksheet.write_string('{}{}'.format(row_tag, row + 1),
machine if machine else '')
worksheet.write_string('{}{}'.format(row_tag, row + 2),
str(count) if count else '')
row += 3
workbook.close()
output.seek(0)
return output.read()
def get_order_report(report_data, file_format='csv'):
"""Generate csv file for download by machine loss rate detail."""
data = tablib.Dataset()
data.headers = ('製令編號', '客戶', '規格', '投入數', '需求數',
'加締捲曲', '組立', '老化', '選別', '加工切腳')
for r in sorted(report_data, key=lambda k: k['order_no']):
record = [r['order_no'], r['customer'], get_product_size(r['part_no']),
r['input_count'], r['require_count'],
r['step1_prod_qty'], r['step2_prod_qty'],
r['step3_prod_qty'], r['step4_prod_qty'],
r['step5_prod_qty']]
data.append(record)
if file_format == 'csv':
return data.csv
return data | """Generate maintenance log to csv file for download."""
if log_list is None:
log_list = []
data = tablib.Dataset() | random_line_split |
data_exportor.py | # -*- coding: utf-8 -*-
# @date 161103 - Export excel with get_work_order_report function
"""
Data exportor (Excel, CSV...)
"""
import io
import math
from datetime import datetime
from xlsxwriter.workbook import Workbook
import tablib
from utils.tools import get_product_size
def get_customers(customer_list=None, file_format='csv'):
"""Generate customer data file for download."""
if customer_list is None:
customer_list = []
data = tablib.Dataset()
data.headers = ('客戶代碼', '客戶名稱')
for c in customer_list:
data.append((c.c_code, c.c_name))
if file_format == 'csv':
return data.csv
| a
def get_maintenance_log(log_list=None, file_format='csv'):
"""Generate maintenance log to csv file for download."""
if log_list is None:
log_list = []
data = tablib.Dataset()
data.headers = ('機台', '維修項目', '開始時間',
'員工', '結束時間', '員工',
'總計時間')
for log in log_list:
m_code = log['m_code'].replace('<br>', '\n')
data.append((log['machine_id'], m_code, log['start_time'],
log['who_start'], log['end_time'], log['who_end'],
log['total_time'][0])
)
if file_format == 'csv':
return data.csv
return data
def get_w_m_performance_report(file_format='xls'):
"""Generate excel file for download by worker and machine performance."""
row_number = 11
data = tablib.Dataset()
data.append(['個人效率期間表 ({})'.format(
datetime.now().strftime("%Y/%m/%d"))] + [''] * (row_number - 1))
data.append(['工號', '姓名', '日期', '標準量', '效率標準量',
'實質生產量', '總稼動時間', '總停機時間', '稼動 %', '數量效率 %',
'平均效率 %'])
if file_format == 'xls':
return data.xls
return data
def get_loss_rate_report(report_data, file_format='csv'):
"""Generate csv file for download by machine loss rate."""
data = tablib.Dataset()
data.headers = ('機台', '機型', '良品數', '不良品數', '損耗率(%)',
'損耗金額(RMB)', '損耗率排名')
rank = 0
old_loss_rate = None
for r in sorted(report_data, key=lambda k: k['loss_rate'], reverse=True):
if old_loss_rate != r['loss_rate']:
rank += 1
old_loss_rate = r['loss_rate']
record = [r['machine_id'], r['machine_type'], r['count_qty'],
r['event_qty'], r['loss_rate'], r['total_loss_money'],
rank]
data.append(record)
if file_format == 'csv':
return data.csv
return data
def get_loss_rate_detail_report(report_data, file_format='csv'):
"""Generate csv file for download by machine loss rate detail."""
data = tablib.Dataset()
data.headers = ('日期', '良品數', '不良品數', '損耗率(%)',
'損耗金額(RMB)')
for r in sorted(report_data, key=lambda k: k['record_date']):
record = [r['record_date'], r['count_qty'], r['event_qty'],
r['loss_rate'], r['total_loss_money']]
data.append(record)
if file_format == 'csv':
return data.csv
return data
def get_uptime_report(report_data='', file_format='xls'):
"""Generate excel file for download by uptime information."""
data = tablib.Dataset()
data.append_separator('製造部各工程稼動率一覽表')
data.append(['月份:10', '星期', '', '', '', '', '',
'目標', '', '', '', ''])
data.append(['', '', '加締卷取(%)', '組立(%)', '老化(%)',
'CUTTING(%)', 'TAPPING(%)', '加締卷取',
'組立', '老化', 'CUTTING', 'TAPPING'])
if file_format == 'xls':
return data.xls
return data
def get_work_order_report(report_data, file_format='csv'):
"""Generate csv file for download by work order."""
# data = tablib.Dataset()
# data.headers = ('製令編號', '料號', '客戶', '產品規格',
# '投入數', '應繳庫數',
# '加締捲取', '組立', '老化', '選別', '加工切角')
# for r in sorted(report_data, key=lambda k: k['order_no']):
# try:
# intput_count = int(r['input_count'])
# except (TypeError, ValueError):
# intput_count = -1
# record = [r['order_no'], r['part_no'], r['customer'], r['product'],
# intput_count, math.floor(intput_count / 1.03),
# r['step1_status'], r['step2_status'], r['step3_status'],
# r['step4_status'], r['step5_status']]
# data.append(record)
# if file_format == 'csv':
# return data.csv
# return data
output = io.BytesIO()
if file_format == 'xls':
workbook = Workbook(output, {'in_memory': True})
worksheet = workbook.add_worksheet()
# merge_format = workbook.add_format({
# 'bold': 1,
# 'border': 1,
# 'align': 'center',
# 'valign': 'vcenter'})
worksheet.merge_range('A1:A3', '製令編號')
worksheet.merge_range('B1:B3', '料號')
worksheet.merge_range('C1:C3', '客戶')
worksheet.merge_range('D1:D3', '產品規格')
worksheet.merge_range('E1:E3', '投入數')
worksheet.merge_range('F1:F3', '應繳庫數')
worksheet.write('G1', '加締捲取')
worksheet.write('H1', '組立')
worksheet.write('I1', '老化')
worksheet.write('J1', '選別')
worksheet.write('K1', '加工切角')
for col_name in ('G', 'H', 'I', 'J', 'K'):
worksheet.write(col_name + '2', '機器')
worksheet.write(col_name + '3', '良品數')
row = 4
for r in sorted(report_data, key=lambda k: k['order_no']):
try:
intput_count = int(r['input_count'])
except (TypeError, ValueError):
intput_count = -1
worksheet.merge_range('A{}:A{}'.format(row, row + 2),
r['order_no'])
worksheet.merge_range('B{}:B{}'.format(row, row + 2), r['part_no'])
worksheet.merge_range('C{}:C{}'.format(row, row + 2),
r['customer'])
worksheet.merge_range('D{}:D{}'.format(row, row + 2), r['product'])
worksheet.merge_range('E{}:E{}'.format(row, row + 2), intput_count)
worksheet.merge_range('F{}:F{}'.format(row, row + 2),
math.floor(intput_count / 1.03))
for process in range(1, 6):
row_tag = chr(71 + process - 1)
worksheet.write_string('{}{}'.format(row_tag, row),
r['step{}_status'.format(process)])
machine = r['step{}_machine'.format(process)]
count = r['step{}_count'.format(process)]
worksheet.write_string('{}{}'.format(row_tag, row + 1),
machine if machine else '')
worksheet.write_string('{}{}'.format(row_tag, row + 2),
str(count) if count else '')
row += 3
workbook.close()
output.seek(0)
return output.read()
def get_order_report(report_data, file_format='csv'):
"""Generate csv file for download by machine loss rate detail."""
data = tablib.Dataset()
data.headers = ('製令編號', '客戶', '規格', '投入數', '需求數',
'加締捲曲', '組立', '老化', '選別', '加工切腳')
for r in sorted(report_data, key=lambda k: k['order_no']):
record = [r['order_no'], r['customer'], get_product_size(r['part_no']),
r['input_count'], r['require_count'],
r['step1_prod_qty'], r['step2_prod_qty'],
r['step3_prod_qty'], r['step4_prod_qty'],
r['step5_prod_qty']]
data.append(record)
if file_format == 'csv':
return data.csv
return data
|
return dat | conditional_block |
data_exportor.py | # -*- coding: utf-8 -*-
# @date 161103 - Export excel with get_work_order_report function
"""
Data exportor (Excel, CSV...)
"""
import io
import math
from datetime import datetime
from xlsxwriter.workbook import Workbook
import tablib
from utils.tools import get_product_size
def get_customers(customer_list=None, file_format='csv'):
"""Generate customer data file for download."""
if customer_list is None:
customer_list = []
data = tablib.Dataset()
data.headers = ('客戶代碼', '客戶名稱')
for c in customer_list:
data.append((c.c_code, c.c_name))
if file_format == 'csv':
return data.csv
return data
def get_maintenance_log(log_list=None, file_format='csv'):
"""Generate main | "Generate excel file for download by worker and machine performance."""
row_number = 11
data = tablib.Dataset()
data.append(['個人效率期間表 ({})'.format(
datetime.now().strftime("%Y/%m/%d"))] + [''] * (row_number - 1))
data.append(['工號', '姓名', '日期', '標準量', '效率標準量',
'實質生產量', '總稼動時間', '總停機時間', '稼動 %', '數量效率 %',
'平均效率 %'])
if file_format == 'xls':
return data.xls
return data
def get_loss_rate_report(report_data, file_format='csv'):
"""Generate csv file for download by machine loss rate."""
data = tablib.Dataset()
data.headers = ('機台', '機型', '良品數', '不良品數', '損耗率(%)',
'損耗金額(RMB)', '損耗率排名')
rank = 0
old_loss_rate = None
for r in sorted(report_data, key=lambda k: k['loss_rate'], reverse=True):
if old_loss_rate != r['loss_rate']:
rank += 1
old_loss_rate = r['loss_rate']
record = [r['machine_id'], r['machine_type'], r['count_qty'],
r['event_qty'], r['loss_rate'], r['total_loss_money'],
rank]
data.append(record)
if file_format == 'csv':
return data.csv
return data
def get_loss_rate_detail_report(report_data, file_format='csv'):
"""Generate csv file for download by machine loss rate detail."""
data = tablib.Dataset()
data.headers = ('日期', '良品數', '不良品數', '損耗率(%)',
'損耗金額(RMB)')
for r in sorted(report_data, key=lambda k: k['record_date']):
record = [r['record_date'], r['count_qty'], r['event_qty'],
r['loss_rate'], r['total_loss_money']]
data.append(record)
if file_format == 'csv':
return data.csv
return data
def get_uptime_report(report_data='', file_format='xls'):
"""Generate excel file for download by uptime information."""
data = tablib.Dataset()
data.append_separator('製造部各工程稼動率一覽表')
data.append(['月份:10', '星期', '', '', '', '', '',
'目標', '', '', '', ''])
data.append(['', '', '加締卷取(%)', '組立(%)', '老化(%)',
'CUTTING(%)', 'TAPPING(%)', '加締卷取',
'組立', '老化', 'CUTTING', 'TAPPING'])
if file_format == 'xls':
return data.xls
return data
def get_work_order_report(report_data, file_format='csv'):
"""Generate csv file for download by work order."""
# data = tablib.Dataset()
# data.headers = ('製令編號', '料號', '客戶', '產品規格',
# '投入數', '應繳庫數',
# '加締捲取', '組立', '老化', '選別', '加工切角')
# for r in sorted(report_data, key=lambda k: k['order_no']):
# try:
# intput_count = int(r['input_count'])
# except (TypeError, ValueError):
# intput_count = -1
# record = [r['order_no'], r['part_no'], r['customer'], r['product'],
# intput_count, math.floor(intput_count / 1.03),
# r['step1_status'], r['step2_status'], r['step3_status'],
# r['step4_status'], r['step5_status']]
# data.append(record)
# if file_format == 'csv':
# return data.csv
# return data
output = io.BytesIO()
if file_format == 'xls':
workbook = Workbook(output, {'in_memory': True})
worksheet = workbook.add_worksheet()
# merge_format = workbook.add_format({
# 'bold': 1,
# 'border': 1,
# 'align': 'center',
# 'valign': 'vcenter'})
worksheet.merge_range('A1:A3', '製令編號')
worksheet.merge_range('B1:B3', '料號')
worksheet.merge_range('C1:C3', '客戶')
worksheet.merge_range('D1:D3', '產品規格')
worksheet.merge_range('E1:E3', '投入數')
worksheet.merge_range('F1:F3', '應繳庫數')
worksheet.write('G1', '加締捲取')
worksheet.write('H1', '組立')
worksheet.write('I1', '老化')
worksheet.write('J1', '選別')
worksheet.write('K1', '加工切角')
for col_name in ('G', 'H', 'I', 'J', 'K'):
worksheet.write(col_name + '2', '機器')
worksheet.write(col_name + '3', '良品數')
row = 4
for r in sorted(report_data, key=lambda k: k['order_no']):
try:
intput_count = int(r['input_count'])
except (TypeError, ValueError):
intput_count = -1
worksheet.merge_range('A{}:A{}'.format(row, row + 2),
r['order_no'])
worksheet.merge_range('B{}:B{}'.format(row, row + 2), r['part_no'])
worksheet.merge_range('C{}:C{}'.format(row, row + 2),
r['customer'])
worksheet.merge_range('D{}:D{}'.format(row, row + 2), r['product'])
worksheet.merge_range('E{}:E{}'.format(row, row + 2), intput_count)
worksheet.merge_range('F{}:F{}'.format(row, row + 2),
math.floor(intput_count / 1.03))
for process in range(1, 6):
row_tag = chr(71 + process - 1)
worksheet.write_string('{}{}'.format(row_tag, row),
r['step{}_status'.format(process)])
machine = r['step{}_machine'.format(process)]
count = r['step{}_count'.format(process)]
worksheet.write_string('{}{}'.format(row_tag, row + 1),
machine if machine else '')
worksheet.write_string('{}{}'.format(row_tag, row + 2),
str(count) if count else '')
row += 3
workbook.close()
output.seek(0)
return output.read()
def get_order_report(report_data, file_format='csv'):
"""Generate csv file for download by machine loss rate detail."""
data = tablib.Dataset()
data.headers = ('製令編號', '客戶', '規格', '投入數', '需求數',
'加締捲曲', '組立', '老化', '選別', '加工切腳')
for r in sorted(report_data, key=lambda k: k['order_no']):
record = [r['order_no'], r['customer'], get_product_size(r['part_no']),
r['input_count'], r['require_count'],
r['step1_prod_qty'], r['step2_prod_qty'],
r['step3_prod_qty'], r['step4_prod_qty'],
r['step5_prod_qty']]
data.append(record)
if file_format == 'csv':
return data.csv
return data
| tenance log to csv file for download."""
if log_list is None:
log_list = []
data = tablib.Dataset()
data.headers = ('機台', '維修項目', '開始時間',
'員工', '結束時間', '員工',
'總計時間')
for log in log_list:
m_code = log['m_code'].replace('<br>', '\n')
data.append((log['machine_id'], m_code, log['start_time'],
log['who_start'], log['end_time'], log['who_end'],
log['total_time'][0])
)
if file_format == 'csv':
return data.csv
return data
def get_w_m_performance_report(file_format='xls'):
"" | identifier_body |
phantom-tests.ts | import phantom = require("phantom");
phantom.create().then((ph: phantom.PhantomJS): void => {
ph.createPage().then((page): void => {
page.open("http://www.google.com", {
operation: "GET"
}).then((status: string) => {
console.log("opened google? ", status);
return page.evaluate((): string => {
return document.title;
});
}).then((result: string): void => {
console.log('Page title is ' + result);
ph.exit();
});
});
});
phantom.create(["--web-security=no", "--ignore-ssl-errors=yes"]).then((ph) => {
console.log("Phantom Bridge Initiated");
ph.createPage().then((page) => {
console.log("Page created!");
return page.open("http://www.google.com").then(function(status) {
if (status == "success") {
console.log("Page is open!");
}
return page.evaluate(function() {
var title = (<HTMLElement>document.querySelector("title")).innerText;
console.log("The page title is " + title);
});
}).then(() => {
return page.evaluate(function(selector) {
var text = (<HTMLElement>document.querySelector(selector)).innerText;
console.log(selector + " contains the following text: " + text);
}, "title");
}).then(() => {
page.evaluate(f => f + 1, "zero");
return page.evaluate(function(selector) {
var text = (<HTMLElement>document.querySelector(selector)).innerText
return text
}, "mySelector")
}).then(function(result) {
console.log("The element contains the following text: " + result)
return page.property('onConsoleMessage', function(msg: string) {
console.log("Phantom Console: " + msg);
});
}).then(() => {
return page.property('onUrlChanged', function(url: string) {
console.log("New URL: " + url);
});
}).then(() => {
return page.property('onResourceRequested', function() {
console.log("Resource requested..");
});
}).then(() => {
return page.property('onResourceReceived', function(res: any) {
if (res.stage == 'end') {
console.log("Resource received!")
}
});
}).then(() => {
return page.property('onLoadStarted', function() {
console.log("Loading started");
});
}).then(() => {
return page.property('onLoadFinished', function(status: string) {
console.log("Loading finished, the page is " + ((status == "success") ? "open." : "not open!"));
});
}).then(() => {
return page.property('settings.loadImages', false);
}).then(() => {
return page.property('settings.resourceTimeout', 1000);
}).then(() => {
return page.property('settings.viewportSize', {
width: 1920,
height: 1080
});
}).then(() => {
return page.open("http://google.co.jp");
}).then((status) => {
return page.render("/tmp/google-top.jpg", {
format: 'jpeg',
quality: '80'
});
}).then(() => {
return page.close();
});
}).then(() => {
ph.exit();
});
});
phantom.create().then((ph) => {
return ph.createPage().then((page) => {
page.open("http://localhost:9901/cookie").then((status) => {
var someFunc = function (aaa: string, my_obj: Object) {
var attribute_to_want = aaa;
var h2Arr: string[] = [];
var results = document.querySelectorAll(attribute_to_want);
for (var i = 0, len = results.length; i < len; ++i) {
var result = <HTMLElement>results[i];
h2Arr.push(result.innerText);
} | aaa: this.arguments,
obj: my_obj
};
};
var finishedFunc = (result: any) => {
ph.exit();
};
return page.evaluate<string, { wahtt: number; }, void>(someFunc, 'div', { wahtt: 111 }).then(finishedFunc);
});
}).then(() => {
return ph.createPage().then((page) => {
page.open('http://www.phantomjs.org').then((status) => {
if (status === 'success') {
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js').then(() => {
page.injectJs('do.js').then((res) => {
page.evaluate(() => {
return document.title;
}).then((title: string) => {
console.log(title);
ph.exit();
});
});
});
page.sendEvent('click', 350, 320);
page.sendEvent('click', 350, 320, 'right');
page.sendEvent('keypress', 'A', null, null, 0x02000000 | 0x08000000);
page.sendEvent('keypress', 'A');
}
});
});
});
}); | return {
h2: h2Arr, | random_line_split |
phantom-tests.ts | import phantom = require("phantom");
phantom.create().then((ph: phantom.PhantomJS): void => {
ph.createPage().then((page): void => {
page.open("http://www.google.com", {
operation: "GET"
}).then((status: string) => {
console.log("opened google? ", status);
return page.evaluate((): string => {
return document.title;
});
}).then((result: string): void => {
console.log('Page title is ' + result);
ph.exit();
});
});
});
phantom.create(["--web-security=no", "--ignore-ssl-errors=yes"]).then((ph) => {
console.log("Phantom Bridge Initiated");
ph.createPage().then((page) => {
console.log("Page created!");
return page.open("http://www.google.com").then(function(status) {
if (status == "success") {
console.log("Page is open!");
}
return page.evaluate(function() {
var title = (<HTMLElement>document.querySelector("title")).innerText;
console.log("The page title is " + title);
});
}).then(() => {
return page.evaluate(function(selector) {
var text = (<HTMLElement>document.querySelector(selector)).innerText;
console.log(selector + " contains the following text: " + text);
}, "title");
}).then(() => {
page.evaluate(f => f + 1, "zero");
return page.evaluate(function(selector) {
var text = (<HTMLElement>document.querySelector(selector)).innerText
return text
}, "mySelector")
}).then(function(result) {
console.log("The element contains the following text: " + result)
return page.property('onConsoleMessage', function(msg: string) {
console.log("Phantom Console: " + msg);
});
}).then(() => {
return page.property('onUrlChanged', function(url: string) {
console.log("New URL: " + url);
});
}).then(() => {
return page.property('onResourceRequested', function() {
console.log("Resource requested..");
});
}).then(() => {
return page.property('onResourceReceived', function(res: any) {
if (res.stage == 'end') {
console.log("Resource received!")
}
});
}).then(() => {
return page.property('onLoadStarted', function() {
console.log("Loading started");
});
}).then(() => {
return page.property('onLoadFinished', function(status: string) {
console.log("Loading finished, the page is " + ((status == "success") ? "open." : "not open!"));
});
}).then(() => {
return page.property('settings.loadImages', false);
}).then(() => {
return page.property('settings.resourceTimeout', 1000);
}).then(() => {
return page.property('settings.viewportSize', {
width: 1920,
height: 1080
});
}).then(() => {
return page.open("http://google.co.jp");
}).then((status) => {
return page.render("/tmp/google-top.jpg", {
format: 'jpeg',
quality: '80'
});
}).then(() => {
return page.close();
});
}).then(() => {
ph.exit();
});
});
phantom.create().then((ph) => {
return ph.createPage().then((page) => {
page.open("http://localhost:9901/cookie").then((status) => {
var someFunc = function (aaa: string, my_obj: Object) {
var attribute_to_want = aaa;
var h2Arr: string[] = [];
var results = document.querySelectorAll(attribute_to_want);
for (var i = 0, len = results.length; i < len; ++i) {
var result = <HTMLElement>results[i];
h2Arr.push(result.innerText);
}
return {
h2: h2Arr,
aaa: this.arguments,
obj: my_obj
};
};
var finishedFunc = (result: any) => {
ph.exit();
};
return page.evaluate<string, { wahtt: number; }, void>(someFunc, 'div', { wahtt: 111 }).then(finishedFunc);
});
}).then(() => {
return ph.createPage().then((page) => {
page.open('http://www.phantomjs.org').then((status) => {
if (status === 'success') |
});
});
});
});
| {
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js').then(() => {
page.injectJs('do.js').then((res) => {
page.evaluate(() => {
return document.title;
}).then((title: string) => {
console.log(title);
ph.exit();
});
});
});
page.sendEvent('click', 350, 320);
page.sendEvent('click', 350, 320, 'right');
page.sendEvent('keypress', 'A', null, null, 0x02000000 | 0x08000000);
page.sendEvent('keypress', 'A');
} | conditional_block |
dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_sync.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for DeleteConversationDataset | # python3 -m pip install google-cloud-dialogflow
# [START dialogflow_v2_generated_ConversationDatasets_DeleteConversationDataset_sync]
from google.cloud import dialogflow_v2
def sample_delete_conversation_dataset():
# Create a client
client = dialogflow_v2.ConversationDatasetsClient()
# Initialize request argument(s)
request = dialogflow_v2.DeleteConversationDatasetRequest(
name="name_value",
)
# Make the request
operation = client.delete_conversation_dataset(request=request)
print("Waiting for operation to complete...")
response = operation.result()
# Handle the response
print(response)
# [END dialogflow_v2_generated_ConversationDatasets_DeleteConversationDataset_sync] | # NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following: | random_line_split |
dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_sync.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for DeleteConversationDataset
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-dialogflow
# [START dialogflow_v2_generated_ConversationDatasets_DeleteConversationDataset_sync]
from google.cloud import dialogflow_v2
def sample_delete_conversation_dataset():
# Create a client
|
# [END dialogflow_v2_generated_ConversationDatasets_DeleteConversationDataset_sync]
| client = dialogflow_v2.ConversationDatasetsClient()
# Initialize request argument(s)
request = dialogflow_v2.DeleteConversationDatasetRequest(
name="name_value",
)
# Make the request
operation = client.delete_conversation_dataset(request=request)
print("Waiting for operation to complete...")
response = operation.result()
# Handle the response
print(response) | identifier_body |
dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_sync.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for DeleteConversationDataset
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-dialogflow
# [START dialogflow_v2_generated_ConversationDatasets_DeleteConversationDataset_sync]
from google.cloud import dialogflow_v2
def | ():
# Create a client
client = dialogflow_v2.ConversationDatasetsClient()
# Initialize request argument(s)
request = dialogflow_v2.DeleteConversationDatasetRequest(
name="name_value",
)
# Make the request
operation = client.delete_conversation_dataset(request=request)
print("Waiting for operation to complete...")
response = operation.result()
# Handle the response
print(response)
# [END dialogflow_v2_generated_ConversationDatasets_DeleteConversationDataset_sync]
| sample_delete_conversation_dataset | identifier_name |
pickle_helpers.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains simple input/output related functionality that is not
part of a larger framework or standard.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from ...extern import six
from ...extern.six.moves import range
__all__ = ['fnpickle', 'fnunpickle']
def fnunpickle(fileorname, number=0, usecPickle=True):
""" Unpickle pickled objects from a specified file and return the contents.
Parameters
----------
fileorname : str or file-like
The file name or file from which to unpickle objects. If a file object,
it should have been opened in binary mode.
number : int
If 0, a single object will be returned (the first in the file). If >0,
this specifies the number of objects to be unpickled, and a list will
be returned with exactly that many objects. If <0, all objects in the
file will be unpickled and returned as a list.
usecPickle : bool
If True, the :mod:`cPickle` module is to be used in place of
:mod:`pickle` (cPickle is faster). This only applies for python 2.x.
Raises
------
EOFError
If ``number`` is >0 and there are fewer than ``number`` objects in the
pickled file.
Returns
-------
contents : obj or list
If ``number`` is 0, this is a individual object - the first one unpickled
from the file. Otherwise, it is a list of objects unpickled from the
file.
"""
if usecPickle and six.PY2:
import cPickle as pickle
else:
import pickle
if isinstance(fileorname, six.string_types):
f = open(fileorname, 'rb')
close = True
else:
f = fileorname
close = False
try:
if number > 0: # get that number
res = []
for i in range(number):
res.append(pickle.load(f))
elif number < 0: # get all objects
res = []
eof = False
while not eof:
try:
res.append(pickle.load(f))
except EOFError:
eof = True
else: # number==0
res = pickle.load(f)
finally:
if close:
f.close()
return res
def | (object, fileorname, usecPickle=True, protocol=None, append=False):
"""Pickle an object to a specified file.
Parameters
----------
object
The python object to pickle.
fileorname : str or file-like
The filename or file into which the `object` should be pickled. If a
file object, it should have been opened in binary mode.
usecPickle : bool
If True (default), the :mod:`cPickle` module is to be used in place of
:mod:`pickle` (cPickle is faster). This only applies for python 2.x.
protocol : int or None
Pickle protocol to use - see the :mod:`pickle` module for details on
these options. If None, the most recent protocol will be used.
append : bool
If True, the object is appended to the end of the file, otherwise the
file will be overwritten (if a file object is given instead of a
file name, this has no effect).
"""
if usecPickle and six.PY2:
import cPickle as pickle
else:
import pickle
if protocol is None:
protocol = pickle.HIGHEST_PROTOCOL
if isinstance(fileorname, six.string_types):
f = open(fileorname, 'ab' if append else 'wb')
close = True
else:
f = fileorname
close = False
try:
pickle.dump(object, f, protocol=protocol)
finally:
if close:
f.close()
| fnpickle | identifier_name |
pickle_helpers.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains simple input/output related functionality that is not
part of a larger framework or standard.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from ...extern import six
from ...extern.six.moves import range
__all__ = ['fnpickle', 'fnunpickle']
def fnunpickle(fileorname, number=0, usecPickle=True):
""" Unpickle pickled objects from a specified file and return the contents.
Parameters
----------
fileorname : str or file-like
The file name or file from which to unpickle objects. If a file object,
it should have been opened in binary mode.
number : int
If 0, a single object will be returned (the first in the file). If >0,
this specifies the number of objects to be unpickled, and a list will
be returned with exactly that many objects. If <0, all objects in the
file will be unpickled and returned as a list.
usecPickle : bool
If True, the :mod:`cPickle` module is to be used in place of
:mod:`pickle` (cPickle is faster). This only applies for python 2.x.
Raises
------
EOFError
If ``number`` is >0 and there are fewer than ``number`` objects in the
pickled file.
Returns
-------
contents : obj or list
If ``number`` is 0, this is a individual object - the first one unpickled
from the file. Otherwise, it is a list of objects unpickled from the
file.
"""
if usecPickle and six.PY2:
import cPickle as pickle
else:
import pickle
if isinstance(fileorname, six.string_types):
f = open(fileorname, 'rb')
close = True
else:
f = fileorname
close = False
try:
if number > 0: # get that number
res = []
for i in range(number):
res.append(pickle.load(f))
elif number < 0: # get all objects
res = []
eof = False
while not eof:
try:
res.append(pickle.load(f))
except EOFError:
eof = True
else: # number==0
res = pickle.load(f)
finally:
if close:
f.close()
|
Parameters
----------
object
The python object to pickle.
fileorname : str or file-like
The filename or file into which the `object` should be pickled. If a
file object, it should have been opened in binary mode.
usecPickle : bool
If True (default), the :mod:`cPickle` module is to be used in place of
:mod:`pickle` (cPickle is faster). This only applies for python 2.x.
protocol : int or None
Pickle protocol to use - see the :mod:`pickle` module for details on
these options. If None, the most recent protocol will be used.
append : bool
If True, the object is appended to the end of the file, otherwise the
file will be overwritten (if a file object is given instead of a
file name, this has no effect).
"""
if usecPickle and six.PY2:
import cPickle as pickle
else:
import pickle
if protocol is None:
protocol = pickle.HIGHEST_PROTOCOL
if isinstance(fileorname, six.string_types):
f = open(fileorname, 'ab' if append else 'wb')
close = True
else:
f = fileorname
close = False
try:
pickle.dump(object, f, protocol=protocol)
finally:
if close:
f.close() | return res
def fnpickle(object, fileorname, usecPickle=True, protocol=None, append=False):
"""Pickle an object to a specified file. | random_line_split |
pickle_helpers.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains simple input/output related functionality that is not
part of a larger framework or standard.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from ...extern import six
from ...extern.six.moves import range
__all__ = ['fnpickle', 'fnunpickle']
def fnunpickle(fileorname, number=0, usecPickle=True):
|
def fnpickle(object, fileorname, usecPickle=True, protocol=None, append=False):
"""Pickle an object to a specified file.
Parameters
----------
object
The python object to pickle.
fileorname : str or file-like
The filename or file into which the `object` should be pickled. If a
file object, it should have been opened in binary mode.
usecPickle : bool
If True (default), the :mod:`cPickle` module is to be used in place of
:mod:`pickle` (cPickle is faster). This only applies for python 2.x.
protocol : int or None
Pickle protocol to use - see the :mod:`pickle` module for details on
these options. If None, the most recent protocol will be used.
append : bool
If True, the object is appended to the end of the file, otherwise the
file will be overwritten (if a file object is given instead of a
file name, this has no effect).
"""
if usecPickle and six.PY2:
import cPickle as pickle
else:
import pickle
if protocol is None:
protocol = pickle.HIGHEST_PROTOCOL
if isinstance(fileorname, six.string_types):
f = open(fileorname, 'ab' if append else 'wb')
close = True
else:
f = fileorname
close = False
try:
pickle.dump(object, f, protocol=protocol)
finally:
if close:
f.close()
| """ Unpickle pickled objects from a specified file and return the contents.
Parameters
----------
fileorname : str or file-like
The file name or file from which to unpickle objects. If a file object,
it should have been opened in binary mode.
number : int
If 0, a single object will be returned (the first in the file). If >0,
this specifies the number of objects to be unpickled, and a list will
be returned with exactly that many objects. If <0, all objects in the
file will be unpickled and returned as a list.
usecPickle : bool
If True, the :mod:`cPickle` module is to be used in place of
:mod:`pickle` (cPickle is faster). This only applies for python 2.x.
Raises
------
EOFError
If ``number`` is >0 and there are fewer than ``number`` objects in the
pickled file.
Returns
-------
contents : obj or list
If ``number`` is 0, this is a individual object - the first one unpickled
from the file. Otherwise, it is a list of objects unpickled from the
file.
"""
if usecPickle and six.PY2:
import cPickle as pickle
else:
import pickle
if isinstance(fileorname, six.string_types):
f = open(fileorname, 'rb')
close = True
else:
f = fileorname
close = False
try:
if number > 0: # get that number
res = []
for i in range(number):
res.append(pickle.load(f))
elif number < 0: # get all objects
res = []
eof = False
while not eof:
try:
res.append(pickle.load(f))
except EOFError:
eof = True
else: # number==0
res = pickle.load(f)
finally:
if close:
f.close()
return res | identifier_body |
pickle_helpers.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains simple input/output related functionality that is not
part of a larger framework or standard.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from ...extern import six
from ...extern.six.moves import range
__all__ = ['fnpickle', 'fnunpickle']
def fnunpickle(fileorname, number=0, usecPickle=True):
""" Unpickle pickled objects from a specified file and return the contents.
Parameters
----------
fileorname : str or file-like
The file name or file from which to unpickle objects. If a file object,
it should have been opened in binary mode.
number : int
If 0, a single object will be returned (the first in the file). If >0,
this specifies the number of objects to be unpickled, and a list will
be returned with exactly that many objects. If <0, all objects in the
file will be unpickled and returned as a list.
usecPickle : bool
If True, the :mod:`cPickle` module is to be used in place of
:mod:`pickle` (cPickle is faster). This only applies for python 2.x.
Raises
------
EOFError
If ``number`` is >0 and there are fewer than ``number`` objects in the
pickled file.
Returns
-------
contents : obj or list
If ``number`` is 0, this is a individual object - the first one unpickled
from the file. Otherwise, it is a list of objects unpickled from the
file.
"""
if usecPickle and six.PY2:
import cPickle as pickle
else:
import pickle
if isinstance(fileorname, six.string_types):
f = open(fileorname, 'rb')
close = True
else:
f = fileorname
close = False
try:
if number > 0: # get that number
res = []
for i in range(number):
res.append(pickle.load(f))
elif number < 0: # get all objects
|
else: # number==0
res = pickle.load(f)
finally:
if close:
f.close()
return res
def fnpickle(object, fileorname, usecPickle=True, protocol=None, append=False):
"""Pickle an object to a specified file.
Parameters
----------
object
The python object to pickle.
fileorname : str or file-like
The filename or file into which the `object` should be pickled. If a
file object, it should have been opened in binary mode.
usecPickle : bool
If True (default), the :mod:`cPickle` module is to be used in place of
:mod:`pickle` (cPickle is faster). This only applies for python 2.x.
protocol : int or None
Pickle protocol to use - see the :mod:`pickle` module for details on
these options. If None, the most recent protocol will be used.
append : bool
If True, the object is appended to the end of the file, otherwise the
file will be overwritten (if a file object is given instead of a
file name, this has no effect).
"""
if usecPickle and six.PY2:
import cPickle as pickle
else:
import pickle
if protocol is None:
protocol = pickle.HIGHEST_PROTOCOL
if isinstance(fileorname, six.string_types):
f = open(fileorname, 'ab' if append else 'wb')
close = True
else:
f = fileorname
close = False
try:
pickle.dump(object, f, protocol=protocol)
finally:
if close:
f.close()
| res = []
eof = False
while not eof:
try:
res.append(pickle.load(f))
except EOFError:
eof = True | conditional_block |
admin-date-preview.js | /**
* Provides live preview facilities for the event date format fields, akin
* to (and using the same ajax mechanism as) the date format preview in WP's
* general settings screen.
*/
jQuery( document ).ready( function( $ ) {
// Whenever the input field for a date format changes, update the matching
// live preview area
$( ".live-date-preview" ).siblings( "input" ).change( function() {
var $format_field = $( this );
var new_format = $format_field.val();
var $preview_field = $format_field.siblings( ".live-date-preview" );
/**
* Update the preview field when we get our response back from WP.
*/
var show_update = function( preview_text ) {
preview_text = $( "<div/>" ).html( preview_text ).text(); // Escaping! |
// Before making the request, show the spinner (this should naturally be "wiped"
// when the response is rendered)
$preview_field.append( "<span class='spinner'></span>" );
$preview_field.find( ".spinner" ).css( "visibility", "visible" );
var request = {
action: "date_format",
date: new_format
}
$.post( ajaxurl, request, show_update, "text" );
} );
} ); | $preview_field.html( preview_text );
} | random_line_split |
compiled.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_upper_case_globals, missing_docs)]
//! ncurses-compatible compiled terminfo format parsing (term(5))
use std::collections::HashMap;
use std::io::prelude::*;
use std::io;
use super::super::TermInfo;
// These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable.
pub static boolfnames: &'static[&'static str] = &["auto_left_margin", "auto_right_margin",
"no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type",
"hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above",
"memory_below", "move_insert_mode", "move_standout_mode", "over_strike", "status_line_esc_ok",
"dest_tabs_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff",
"prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region",
"can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch",
"cr_cancels_micro_mode", "has_print_wheel", "row_addr_glitch", "semi_auto_right_margin",
"cpi_changes_res", "lpi_changes_res", "backspaces_with_bs", "crt_no_scrolling",
"no_correctly_working_cr", "gnu_has_meta_key", "linefeed_is_newline", "has_hardware_tabs",
"return_does_clr_eol"];
pub static boolnames: &'static[&'static str] = &["bw", "am", "xsb", "xhp", "xenl", "eo",
"gn", "hc", "km", "hs", "in", "db", "da", "mir", "msgr", "os", "eslok", "xt", "hz", "ul", "xon",
"nxon", "mc5i", "chts", "nrrmc", "npc", "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy",
"xvpa", "sam", "cpix", "lpix", "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"];
pub static numfnames: &'static[&'static str] = &[ "columns", "init_tabs", "lines",
"lines_of_memory", "magic_cookie_glitch", "padding_baud_rate", "virtual_terminal",
"width_status_line", "num_labels", "label_height", "label_width", "max_attributes",
"maximum_windows", "max_colors", "max_pairs", "no_color_video", "buffer_capacity",
"dot_vert_spacing", "dot_horz_spacing", "max_micro_address", "max_micro_jump", "micro_col_size",
"micro_line_size", "number_of_pins", "output_res_char", "output_res_line",
"output_res_horz_inch", "output_res_vert_inch", "print_rate", "wide_char_size", "buttons",
"bit_image_entwining", "bit_image_type", "magic_cookie_glitch_ul", "carriage_return_delay",
"new_line_delay", "backspace_delay", "horizontal_tab_delay", "number_of_function_keys"];
pub static numnames: &'static[&'static str] = &[ "cols", "it", "lines", "lm", "xmc", "pb",
"vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", "colors", "pairs", "ncv", "bufsz", "spinv",
"spinh", "maddr", "mjump", "mcs", "mls", "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs",
"btns", "bitwin", "bitype", "UTug", "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"];
pub static stringfnames: &'static[&'static str] = &[ "back_tab", "bell", "carriage_return",
"change_scroll_region", "clear_all_tabs", "clear_screen", "clr_eol", "clr_eos",
"column_address", "command_character", "cursor_address", "cursor_down", "cursor_home",
"cursor_invisible", "cursor_left", "cursor_mem_address", "cursor_normal", "cursor_right",
"cursor_to_ll", "cursor_up", "cursor_visible", "delete_character", "delete_line",
"dis_status_line", "down_half_line", "enter_alt_charset_mode", "enter_blink_mode",
"enter_bold_mode", "enter_ca_mode", "enter_delete_mode", "enter_dim_mode", "enter_insert_mode",
"enter_secure_mode", "enter_protected_mode", "enter_reverse_mode", "enter_standout_mode",
"enter_underline_mode", "erase_chars", "exit_alt_charset_mode", "exit_attribute_mode",
"exit_ca_mode", "exit_delete_mode", "exit_insert_mode", "exit_standout_mode",
"exit_underline_mode", "flash_screen", "form_feed", "from_status_line", "init_1string",
"init_2string", "init_3string", "init_file", "insert_character", "insert_line",
"insert_padding", "key_backspace", "key_catab", "key_clear", "key_ctab", "key_dc", "key_dl",
"key_down", "key_eic", "key_eol", "key_eos", "key_f0", "key_f1", "key_f10", "key_f2", "key_f3",
"key_f4", "key_f5", "key_f6", "key_f7", "key_f8", "key_f9", "key_home", "key_ic", "key_il",
"key_left", "key_ll", "key_npage", "key_ppage", "key_right", "key_sf", "key_sr", "key_stab",
"key_up", "keypad_local", "keypad_xmit", "lab_f0", "lab_f1", "lab_f10", "lab_f2", "lab_f3",
"lab_f4", "lab_f5", "lab_f6", "lab_f7", "lab_f8", "lab_f9", "meta_off", "meta_on", "newline",
"pad_char", "parm_dch", "parm_delete_line", "parm_down_cursor", "parm_ich", "parm_index",
"parm_insert_line", "parm_left_cursor", "parm_right_cursor", "parm_rindex", "parm_up_cursor",
"pkey_key", "pkey_local", "pkey_xmit", "print_screen", "prtr_off", "prtr_on", "repeat_char",
"reset_1string", "reset_2string", "reset_3string", "reset_file", "restore_cursor",
"row_address", "save_cursor", "scroll_forward", "scroll_reverse", "set_attributes", "set_tab",
"set_window", "tab", "to_status_line", "underline_char", "up_half_line", "init_prog", "key_a1",
"key_a3", "key_b2", "key_c1", "key_c3", "prtr_non", "char_padding", "acs_chars", "plab_norm",
"key_btab", "enter_xon_mode", "exit_xon_mode", "enter_am_mode", "exit_am_mode", "xon_character",
"xoff_character", "ena_acs", "label_on", "label_off", "key_beg", "key_cancel", "key_close",
"key_command", "key_copy", "key_create", "key_end", "key_enter", "key_exit", "key_find",
"key_help", "key_mark", "key_message", "key_move", "key_next", "key_open", "key_options",
"key_previous", "key_print", "key_redo", "key_reference", "key_refresh", "key_replace",
"key_restart", "key_resume", "key_save", "key_suspend", "key_undo", "key_sbeg", "key_scancel",
"key_scommand", "key_scopy", "key_screate", "key_sdc", "key_sdl", "key_select", "key_send",
"key_seol", "key_sexit", "key_sfind", "key_shelp", "key_shome", "key_sic", "key_sleft",
"key_smessage", "key_smove", "key_snext", "key_soptions", "key_sprevious", "key_sprint",
"key_sredo", "key_sreplace", "key_sright", "key_srsume", "key_ssave", "key_ssuspend",
"key_sundo", "req_for_input", "key_f11", "key_f12", "key_f13", "key_f14", "key_f15", "key_f16",
"key_f17", "key_f18", "key_f19", "key_f20", "key_f21", "key_f22", "key_f23", "key_f24",
"key_f25", "key_f26", "key_f27", "key_f28", "key_f29", "key_f30", "key_f31", "key_f32",
"key_f33", "key_f34", "key_f35", "key_f36", "key_f37", "key_f38", "key_f39", "key_f40",
"key_f41", "key_f42", "key_f43", "key_f44", "key_f45", "key_f46", "key_f47", "key_f48",
"key_f49", "key_f50", "key_f51", "key_f52", "key_f53", "key_f54", "key_f55", "key_f56",
"key_f57", "key_f58", "key_f59", "key_f60", "key_f61", "key_f62", "key_f63", "clr_bol",
"clear_margins", "set_left_margin", "set_right_margin", "label_format", "set_clock",
"display_clock", "remove_clock", "create_window", "goto_window", "hangup", "dial_phone",
"quick_dial", "tone", "pulse", "flash_hook", "fixed_pause", "wait_tone", "user0", "user1",
"user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "orig_pair",
"orig_colors", "initialize_color", "initialize_pair", "set_color_pair", "set_foreground",
"set_background", "change_char_pitch", "change_line_pitch", "change_res_horz",
"change_res_vert", "define_char", "enter_doublewide_mode", "enter_draft_quality",
"enter_italics_mode", "enter_leftward_mode", "enter_micro_mode", "enter_near_letter_quality",
"enter_normal_quality", "enter_shadow_mode", "enter_subscript_mode", "enter_superscript_mode",
"enter_upward_mode", "exit_doublewide_mode", "exit_italics_mode", "exit_leftward_mode",
"exit_micro_mode", "exit_shadow_mode", "exit_subscript_mode", "exit_superscript_mode",
"exit_upward_mode", "micro_column_address", "micro_down", "micro_left", "micro_right",
"micro_row_address", "micro_up", "order_of_pins", "parm_down_micro", "parm_left_micro",
"parm_right_micro", "parm_up_micro", "select_char_set", "set_bottom_margin",
"set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin",
"set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image",
"stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr",
"zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse",
"set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init",
"set0_des_seq", "set1_des_seq", "set2_des_seq", "set3_des_seq", "set_lr_margin",
"set_tb_margin", "bit_image_repeat", "bit_image_newline", "bit_image_carriage_return",
"color_names", "define_bit_image_region", "end_bit_image_region", "set_color_band",
"set_page_length", "display_pc_char", "enter_pc_charset_mode", "exit_pc_charset_mode",
"enter_scancode_mode", "exit_scancode_mode", "pc_term_options", "scancode_escape",
"alt_scancode_esc", "enter_horizontal_hl_mode", "enter_left_hl_mode", "enter_low_hl_mode",
"enter_right_hl_mode", "enter_top_hl_mode", "enter_vertical_hl_mode", "set_a_attributes",
"set_pglen_inch", "termcap_init2", "termcap_reset", "linefeed_if_not_lf", "backspace_if_not_bs",
"other_non_function_keys", "arrow_key_map", "acs_ulcorner", "acs_llcorner", "acs_urcorner",
"acs_lrcorner", "acs_ltee", "acs_rtee", "acs_btee", "acs_ttee", "acs_hline", "acs_vline",
"acs_plus", "memory_lock", "memory_unlock", "box_chars_1"];
pub static stringnames: &'static[&'static str] = &[ "cbt", "_", "cr", "csr", "tbc", "clear",
"_", "_", "hpa", "cmdch", "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1",
"ll", "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc",
"dim", "smir", "invis", "prot", "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc",
"rmir", "rmso", "rmul", "flash", "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip",
"kbs", "ktbc", "kclr", "kctab", "_", "_", "kcud1", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "khome", "_", "_", "kcub1", "_", "knp", "kpp", "kcuf1", "_", "_",
"khts", "_", "rmkx", "smkx", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "rmm", "_",
"_", "pad", "dch", "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey",
"pfloc", "pfx", "mc0", "mc4", "_", "rep", "rs1", "rs2", "rs3", "rf", "rc", "vpa", "sc", "ind",
"ri", "sgr", "_", "wind", "_", "tsl", "uc", "hu", "iprog", "_", "_", "_", "_", "_", "mc5p",
"rmp", "acsc", "pln", "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", "_", "smln",
"rmln", "_", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "_", "kent", "kext", "kfnd", "khlp",
"kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt", "kprv", "kprt", "krdo", "kref", "krfr", "krpl",
"krst", "kres", "ksav", "kspd", "kund", "kBEG", "kCAN", "kCMD", "kCPY", "kCRT", "_", "_",
"kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", "kHOM", "_", "kLFT", "kMSG", "kMOV", "kNXT",
"kOPT", "kPRV", "kPRT", "kRDO", "kRPL", "kRIT", "kRES", "kSAV", "kSPD", "kUND", "rfi", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"dclk", "rmclk", "cwin", "wingo", "_", "dial", "qdial", "_", "_", "hook", "pause", "wait", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "op", "oc", "initc", "initp", "scp", "setf",
"setb", "cpi", "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", "smicm", "snlq",
"snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm", "rmicm", "rshm", "rsubm",
"rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1", "mvpa", "mcuu1", "porder", "mcud", "mcub",
"mcuf", "mcuu", "scs", "smgb", "smgbp", "smglp", "smgrp", "smgt", "smgtp", "sbim", "scsd",
"rbim", "rcsd", "subcs", "supcs", "docr", "zerom", "csnm", "kmous", "minfo", "reqmp", "getm",
"setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds", "s3ds", "smglr", "smgtb",
"birep", "binel", "bicr", "colornm", "defbi", "endbi", "setcolor", "slines", "dispc", "smpch",
"rmpch", "smsc", "rmsc", "pctrm", "scesc", "scesa", "ehhlm", "elhlm", "elohlm", "erhlm",
"ethlm", "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", "OTbs", "OTko", "OTma", "OTG2",
"OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", "OTGH", "OTGV", "OTGC", "meml", "memu",
"box1"];
fn read_le_u16(r: &mut io::Read) -> io::Result<u16> {
let mut b = [0; 2];
let mut amt = 0;
while amt < b.len() {
match try!(r.read(&mut b[amt..])) {
0 => return Err(io::Error::new(io::ErrorKind::Other, "end of file")),
n => amt += n,
}
}
Ok((b[0] as u16) | ((b[1] as u16) << 8))
}
fn read_byte(r: &mut io::Read) -> io::Result<u8> {
match r.bytes().next() {
Some(s) => s,
None => Err(io::Error::new(io::ErrorKind::Other, "end of file"))
}
}
/// Parse a compiled terminfo entry, using long capability names if `longnames`
/// is true
pub fn parse(file: &mut io::Read, longnames: bool) -> Result<TermInfo, String> |
/// Create a dummy TermInfo struct for msys terminals
pub fn msys_terminfo() -> TermInfo {
let mut strings = HashMap::new();
strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec());
strings.insert("bold".to_string(), b"\x1B[1m".to_vec());
strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec());
strings.insert("setab".to_string(), b"\x1B[4%p1%dm".to_vec());
let mut numbers = HashMap::new();
numbers.insert("colors".to_string(), 8u16);
TermInfo {
names: vec!("cygwin".to_string()), // msys is a fork of an older cygwin version
bools: HashMap::new(),
numbers: numbers,
strings: strings
}
}
#[cfg(test)]
mod test {
use super::{boolnames, boolfnames, numnames, numfnames, stringnames, stringfnames};
#[test]
fn test_veclens() {
assert_eq!(boolfnames.len(), boolnames.len());
assert_eq!(numfnames.len(), numnames.len());
assert_eq!(stringfnames.len(), stringnames.len());
}
#[test]
#[ignore(reason = "no ncurses on buildbots, needs a bundled terminfo file to test against")]
fn test_parse() {
// FIXME #6870: Distribute a compiled file in src/tests and test there
// parse(io::fs_reader(&p("/usr/share/terminfo/r/rxvt-256color")).unwrap(), false);
}
}
| {
macro_rules! try( ($e:expr) => (
match $e {
Ok(e) => e,
Err(e) => return Err(format!("{}", e))
}
) );
let (bnames, snames, nnames) = if longnames {
(boolfnames, stringfnames, numfnames)
} else {
(boolnames, stringnames, numnames)
};
// Check magic number
let magic = try!(read_le_u16(file));
if magic != 0x011A {
return Err(format!("invalid magic number: expected {:x}, found {:x}",
0x011A, magic));
}
// According to the spec, these fields must be >= -1 where -1 means that the feature is not
// supported. Using 0 instead of -1 works because we skip sections with length 0.
macro_rules! read_nonneg {
() => {{
match try!(read_le_u16(file)) as i16 {
n if n >= 0 => n as usize,
-1 => 0,
_ => return Err("incompatible file: length fields must be >= -1".to_string()),
}
}}
}
let names_bytes = read_nonneg!();
let bools_bytes = read_nonneg!();
let numbers_count = read_nonneg!();
let string_offsets_count = read_nonneg!();
let string_table_bytes = read_nonneg!();
if names_bytes == 0 {
return Err("incompatible file: names field must be \
at least 1 byte wide".to_string());
}
if bools_bytes > boolnames.len() {
return Err("incompatible file: more booleans than \
expected".to_string());
}
if numbers_count > numnames.len() {
return Err("incompatible file: more numbers than \
expected".to_string());
}
if string_offsets_count > stringnames.len() {
return Err("incompatible file: more string offsets than \
expected".to_string());
}
// don't read NUL
let mut bytes = Vec::new();
try!(file.take((names_bytes - 1) as u64).read_to_end(&mut bytes));
let names_str = match String::from_utf8(bytes) {
Ok(s) => s,
Err(_) => return Err("input not utf-8".to_string()),
};
let term_names: Vec<String> = names_str.split('|')
.map(|s| s.to_string())
.collect();
// consume NUL
if try!(read_byte(file)) != b'\0' {
return Err("incompatible file: missing null terminator \
for names section".to_string());
}
let bools_map: HashMap<String, bool> = try!(
(0..bools_bytes).filter_map(|i| match read_byte(file) {
Err(e) => Some(Err(e)),
Ok(1) => Some(Ok((bnames[i].to_string(), true))),
Ok(_) => None
}).collect());
if (bools_bytes + names_bytes) % 2 == 1 {
try!(read_byte(file)); // compensate for padding
}
let numbers_map: HashMap<String, u16> = try!(
(0..numbers_count).filter_map(|i| match read_le_u16(file) {
Ok(0xFFFF) => None,
Ok(n) => Some(Ok((nnames[i].to_string(), n))),
Err(e) => Some(Err(e))
}).collect());
let string_map: HashMap<String, Vec<u8>> = if string_offsets_count > 0 {
let string_offsets: Vec<u16> = try!((0..string_offsets_count).map(|_| {
read_le_u16(file)
}).collect());
let mut string_table = Vec::new();
try!(file.take(string_table_bytes as u64).read_to_end(&mut string_table));
try!(string_offsets.into_iter().enumerate().filter(|&(_, offset)| {
// non-entry
offset != 0xFFFF
}).map(|(i, offset)| {
let offset = offset as usize;
let name = if snames[i] == "_" {
stringfnames[i]
} else {
snames[i]
};
if offset == 0xFFFE {
// undocumented: FFFE indicates cap@, which means the capability is not present
// unsure if the handling for this is correct
return Ok((name.to_string(), Vec::new()));
}
// Find the offset of the NUL we want to go to
let nulpos = string_table[offset..string_table_bytes].iter().position(|&b| b == 0);
match nulpos {
Some(len) => Ok((name.to_string(), string_table[offset..offset + len].to_vec())),
None => Err("invalid file: missing NUL in string_table".to_string()),
}
}).collect())
} else {
HashMap::new()
};
// And that's all there is to it
Ok(TermInfo {
names: term_names,
bools: bools_map,
numbers: numbers_map,
strings: string_map
})
} | identifier_body |
compiled.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_upper_case_globals, missing_docs)]
//! ncurses-compatible compiled terminfo format parsing (term(5))
use std::collections::HashMap;
use std::io::prelude::*;
use std::io;
use super::super::TermInfo;
// These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable.
pub static boolfnames: &'static[&'static str] = &["auto_left_margin", "auto_right_margin",
"no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type",
"hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above",
"memory_below", "move_insert_mode", "move_standout_mode", "over_strike", "status_line_esc_ok",
"dest_tabs_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff",
"prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region",
"can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch",
"cr_cancels_micro_mode", "has_print_wheel", "row_addr_glitch", "semi_auto_right_margin",
"cpi_changes_res", "lpi_changes_res", "backspaces_with_bs", "crt_no_scrolling",
"no_correctly_working_cr", "gnu_has_meta_key", "linefeed_is_newline", "has_hardware_tabs",
"return_does_clr_eol"];
pub static boolnames: &'static[&'static str] = &["bw", "am", "xsb", "xhp", "xenl", "eo",
"gn", "hc", "km", "hs", "in", "db", "da", "mir", "msgr", "os", "eslok", "xt", "hz", "ul", "xon",
"nxon", "mc5i", "chts", "nrrmc", "npc", "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy",
"xvpa", "sam", "cpix", "lpix", "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"];
pub static numfnames: &'static[&'static str] = &[ "columns", "init_tabs", "lines",
"lines_of_memory", "magic_cookie_glitch", "padding_baud_rate", "virtual_terminal",
"width_status_line", "num_labels", "label_height", "label_width", "max_attributes",
"maximum_windows", "max_colors", "max_pairs", "no_color_video", "buffer_capacity",
"dot_vert_spacing", "dot_horz_spacing", "max_micro_address", "max_micro_jump", "micro_col_size",
"micro_line_size", "number_of_pins", "output_res_char", "output_res_line",
"output_res_horz_inch", "output_res_vert_inch", "print_rate", "wide_char_size", "buttons",
"bit_image_entwining", "bit_image_type", "magic_cookie_glitch_ul", "carriage_return_delay",
"new_line_delay", "backspace_delay", "horizontal_tab_delay", "number_of_function_keys"];
pub static numnames: &'static[&'static str] = &[ "cols", "it", "lines", "lm", "xmc", "pb",
"vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", "colors", "pairs", "ncv", "bufsz", "spinv",
"spinh", "maddr", "mjump", "mcs", "mls", "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs",
"btns", "bitwin", "bitype", "UTug", "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"];
pub static stringfnames: &'static[&'static str] = &[ "back_tab", "bell", "carriage_return",
"change_scroll_region", "clear_all_tabs", "clear_screen", "clr_eol", "clr_eos",
"column_address", "command_character", "cursor_address", "cursor_down", "cursor_home",
"cursor_invisible", "cursor_left", "cursor_mem_address", "cursor_normal", "cursor_right",
"cursor_to_ll", "cursor_up", "cursor_visible", "delete_character", "delete_line",
"dis_status_line", "down_half_line", "enter_alt_charset_mode", "enter_blink_mode",
"enter_bold_mode", "enter_ca_mode", "enter_delete_mode", "enter_dim_mode", "enter_insert_mode",
"enter_secure_mode", "enter_protected_mode", "enter_reverse_mode", "enter_standout_mode",
"enter_underline_mode", "erase_chars", "exit_alt_charset_mode", "exit_attribute_mode",
"exit_ca_mode", "exit_delete_mode", "exit_insert_mode", "exit_standout_mode",
"exit_underline_mode", "flash_screen", "form_feed", "from_status_line", "init_1string",
"init_2string", "init_3string", "init_file", "insert_character", "insert_line",
"insert_padding", "key_backspace", "key_catab", "key_clear", "key_ctab", "key_dc", "key_dl",
"key_down", "key_eic", "key_eol", "key_eos", "key_f0", "key_f1", "key_f10", "key_f2", "key_f3",
"key_f4", "key_f5", "key_f6", "key_f7", "key_f8", "key_f9", "key_home", "key_ic", "key_il",
"key_left", "key_ll", "key_npage", "key_ppage", "key_right", "key_sf", "key_sr", "key_stab",
"key_up", "keypad_local", "keypad_xmit", "lab_f0", "lab_f1", "lab_f10", "lab_f2", "lab_f3",
"lab_f4", "lab_f5", "lab_f6", "lab_f7", "lab_f8", "lab_f9", "meta_off", "meta_on", "newline",
"pad_char", "parm_dch", "parm_delete_line", "parm_down_cursor", "parm_ich", "parm_index",
"parm_insert_line", "parm_left_cursor", "parm_right_cursor", "parm_rindex", "parm_up_cursor",
"pkey_key", "pkey_local", "pkey_xmit", "print_screen", "prtr_off", "prtr_on", "repeat_char",
"reset_1string", "reset_2string", "reset_3string", "reset_file", "restore_cursor",
"row_address", "save_cursor", "scroll_forward", "scroll_reverse", "set_attributes", "set_tab",
"set_window", "tab", "to_status_line", "underline_char", "up_half_line", "init_prog", "key_a1",
"key_a3", "key_b2", "key_c1", "key_c3", "prtr_non", "char_padding", "acs_chars", "plab_norm",
"key_btab", "enter_xon_mode", "exit_xon_mode", "enter_am_mode", "exit_am_mode", "xon_character",
"xoff_character", "ena_acs", "label_on", "label_off", "key_beg", "key_cancel", "key_close",
"key_command", "key_copy", "key_create", "key_end", "key_enter", "key_exit", "key_find",
"key_help", "key_mark", "key_message", "key_move", "key_next", "key_open", "key_options",
"key_previous", "key_print", "key_redo", "key_reference", "key_refresh", "key_replace",
"key_restart", "key_resume", "key_save", "key_suspend", "key_undo", "key_sbeg", "key_scancel",
"key_scommand", "key_scopy", "key_screate", "key_sdc", "key_sdl", "key_select", "key_send",
"key_seol", "key_sexit", "key_sfind", "key_shelp", "key_shome", "key_sic", "key_sleft",
"key_smessage", "key_smove", "key_snext", "key_soptions", "key_sprevious", "key_sprint",
"key_sredo", "key_sreplace", "key_sright", "key_srsume", "key_ssave", "key_ssuspend",
"key_sundo", "req_for_input", "key_f11", "key_f12", "key_f13", "key_f14", "key_f15", "key_f16",
"key_f17", "key_f18", "key_f19", "key_f20", "key_f21", "key_f22", "key_f23", "key_f24",
"key_f25", "key_f26", "key_f27", "key_f28", "key_f29", "key_f30", "key_f31", "key_f32",
"key_f33", "key_f34", "key_f35", "key_f36", "key_f37", "key_f38", "key_f39", "key_f40",
"key_f41", "key_f42", "key_f43", "key_f44", "key_f45", "key_f46", "key_f47", "key_f48",
"key_f49", "key_f50", "key_f51", "key_f52", "key_f53", "key_f54", "key_f55", "key_f56",
"key_f57", "key_f58", "key_f59", "key_f60", "key_f61", "key_f62", "key_f63", "clr_bol",
"clear_margins", "set_left_margin", "set_right_margin", "label_format", "set_clock",
"display_clock", "remove_clock", "create_window", "goto_window", "hangup", "dial_phone",
"quick_dial", "tone", "pulse", "flash_hook", "fixed_pause", "wait_tone", "user0", "user1",
"user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "orig_pair",
"orig_colors", "initialize_color", "initialize_pair", "set_color_pair", "set_foreground",
"set_background", "change_char_pitch", "change_line_pitch", "change_res_horz",
"change_res_vert", "define_char", "enter_doublewide_mode", "enter_draft_quality",
"enter_italics_mode", "enter_leftward_mode", "enter_micro_mode", "enter_near_letter_quality",
"enter_normal_quality", "enter_shadow_mode", "enter_subscript_mode", "enter_superscript_mode",
"enter_upward_mode", "exit_doublewide_mode", "exit_italics_mode", "exit_leftward_mode",
"exit_micro_mode", "exit_shadow_mode", "exit_subscript_mode", "exit_superscript_mode",
"exit_upward_mode", "micro_column_address", "micro_down", "micro_left", "micro_right",
"micro_row_address", "micro_up", "order_of_pins", "parm_down_micro", "parm_left_micro",
"parm_right_micro", "parm_up_micro", "select_char_set", "set_bottom_margin",
"set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin",
"set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image",
"stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr",
"zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse",
"set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init",
"set0_des_seq", "set1_des_seq", "set2_des_seq", "set3_des_seq", "set_lr_margin",
"set_tb_margin", "bit_image_repeat", "bit_image_newline", "bit_image_carriage_return",
"color_names", "define_bit_image_region", "end_bit_image_region", "set_color_band",
"set_page_length", "display_pc_char", "enter_pc_charset_mode", "exit_pc_charset_mode",
"enter_scancode_mode", "exit_scancode_mode", "pc_term_options", "scancode_escape",
"alt_scancode_esc", "enter_horizontal_hl_mode", "enter_left_hl_mode", "enter_low_hl_mode",
"enter_right_hl_mode", "enter_top_hl_mode", "enter_vertical_hl_mode", "set_a_attributes",
"set_pglen_inch", "termcap_init2", "termcap_reset", "linefeed_if_not_lf", "backspace_if_not_bs",
"other_non_function_keys", "arrow_key_map", "acs_ulcorner", "acs_llcorner", "acs_urcorner",
"acs_lrcorner", "acs_ltee", "acs_rtee", "acs_btee", "acs_ttee", "acs_hline", "acs_vline",
"acs_plus", "memory_lock", "memory_unlock", "box_chars_1"];
pub static stringnames: &'static[&'static str] = &[ "cbt", "_", "cr", "csr", "tbc", "clear",
"_", "_", "hpa", "cmdch", "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1",
"ll", "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc",
"dim", "smir", "invis", "prot", "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc",
"rmir", "rmso", "rmul", "flash", "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip",
"kbs", "ktbc", "kclr", "kctab", "_", "_", "kcud1", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "khome", "_", "_", "kcub1", "_", "knp", "kpp", "kcuf1", "_", "_",
"khts", "_", "rmkx", "smkx", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "rmm", "_",
"_", "pad", "dch", "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey",
"pfloc", "pfx", "mc0", "mc4", "_", "rep", "rs1", "rs2", "rs3", "rf", "rc", "vpa", "sc", "ind",
"ri", "sgr", "_", "wind", "_", "tsl", "uc", "hu", "iprog", "_", "_", "_", "_", "_", "mc5p",
"rmp", "acsc", "pln", "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", "_", "smln",
"rmln", "_", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "_", "kent", "kext", "kfnd", "khlp",
"kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt", "kprv", "kprt", "krdo", "kref", "krfr", "krpl",
"krst", "kres", "ksav", "kspd", "kund", "kBEG", "kCAN", "kCMD", "kCPY", "kCRT", "_", "_",
"kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", "kHOM", "_", "kLFT", "kMSG", "kMOV", "kNXT",
"kOPT", "kPRV", "kPRT", "kRDO", "kRPL", "kRIT", "kRES", "kSAV", "kSPD", "kUND", "rfi", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"dclk", "rmclk", "cwin", "wingo", "_", "dial", "qdial", "_", "_", "hook", "pause", "wait", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "op", "oc", "initc", "initp", "scp", "setf",
"setb", "cpi", "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", "smicm", "snlq",
"snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm", "rmicm", "rshm", "rsubm",
"rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1", "mvpa", "mcuu1", "porder", "mcud", "mcub",
"mcuf", "mcuu", "scs", "smgb", "smgbp", "smglp", "smgrp", "smgt", "smgtp", "sbim", "scsd",
"rbim", "rcsd", "subcs", "supcs", "docr", "zerom", "csnm", "kmous", "minfo", "reqmp", "getm",
"setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds", "s3ds", "smglr", "smgtb",
"birep", "binel", "bicr", "colornm", "defbi", "endbi", "setcolor", "slines", "dispc", "smpch",
"rmpch", "smsc", "rmsc", "pctrm", "scesc", "scesa", "ehhlm", "elhlm", "elohlm", "erhlm",
"ethlm", "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", "OTbs", "OTko", "OTma", "OTG2",
"OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", "OTGH", "OTGV", "OTGC", "meml", "memu",
"box1"];
fn read_le_u16(r: &mut io::Read) -> io::Result<u16> {
let mut b = [0; 2];
let mut amt = 0;
while amt < b.len() {
match try!(r.read(&mut b[amt..])) {
0 => return Err(io::Error::new(io::ErrorKind::Other, "end of file")),
n => amt += n,
}
}
Ok((b[0] as u16) | ((b[1] as u16) << 8))
}
fn read_byte(r: &mut io::Read) -> io::Result<u8> {
match r.bytes().next() {
Some(s) => s,
None => Err(io::Error::new(io::ErrorKind::Other, "end of file"))
}
}
/// Parse a compiled terminfo entry, using long capability names if `longnames`
/// is true
pub fn | (file: &mut io::Read, longnames: bool) -> Result<TermInfo, String> {
macro_rules! try( ($e:expr) => (
match $e {
Ok(e) => e,
Err(e) => return Err(format!("{}", e))
}
) );
let (bnames, snames, nnames) = if longnames {
(boolfnames, stringfnames, numfnames)
} else {
(boolnames, stringnames, numnames)
};
// Check magic number
let magic = try!(read_le_u16(file));
if magic != 0x011A {
return Err(format!("invalid magic number: expected {:x}, found {:x}",
0x011A, magic));
}
// According to the spec, these fields must be >= -1 where -1 means that the feature is not
// supported. Using 0 instead of -1 works because we skip sections with length 0.
macro_rules! read_nonneg {
() => {{
match try!(read_le_u16(file)) as i16 {
n if n >= 0 => n as usize,
-1 => 0,
_ => return Err("incompatible file: length fields must be >= -1".to_string()),
}
}}
}
let names_bytes = read_nonneg!();
let bools_bytes = read_nonneg!();
let numbers_count = read_nonneg!();
let string_offsets_count = read_nonneg!();
let string_table_bytes = read_nonneg!();
if names_bytes == 0 {
return Err("incompatible file: names field must be \
at least 1 byte wide".to_string());
}
if bools_bytes > boolnames.len() {
return Err("incompatible file: more booleans than \
expected".to_string());
}
if numbers_count > numnames.len() {
return Err("incompatible file: more numbers than \
expected".to_string());
}
if string_offsets_count > stringnames.len() {
return Err("incompatible file: more string offsets than \
expected".to_string());
}
// don't read NUL
let mut bytes = Vec::new();
try!(file.take((names_bytes - 1) as u64).read_to_end(&mut bytes));
let names_str = match String::from_utf8(bytes) {
Ok(s) => s,
Err(_) => return Err("input not utf-8".to_string()),
};
let term_names: Vec<String> = names_str.split('|')
.map(|s| s.to_string())
.collect();
// consume NUL
if try!(read_byte(file)) != b'\0' {
return Err("incompatible file: missing null terminator \
for names section".to_string());
}
let bools_map: HashMap<String, bool> = try!(
(0..bools_bytes).filter_map(|i| match read_byte(file) {
Err(e) => Some(Err(e)),
Ok(1) => Some(Ok((bnames[i].to_string(), true))),
Ok(_) => None
}).collect());
if (bools_bytes + names_bytes) % 2 == 1 {
try!(read_byte(file)); // compensate for padding
}
let numbers_map: HashMap<String, u16> = try!(
(0..numbers_count).filter_map(|i| match read_le_u16(file) {
Ok(0xFFFF) => None,
Ok(n) => Some(Ok((nnames[i].to_string(), n))),
Err(e) => Some(Err(e))
}).collect());
let string_map: HashMap<String, Vec<u8>> = if string_offsets_count > 0 {
let string_offsets: Vec<u16> = try!((0..string_offsets_count).map(|_| {
read_le_u16(file)
}).collect());
let mut string_table = Vec::new();
try!(file.take(string_table_bytes as u64).read_to_end(&mut string_table));
try!(string_offsets.into_iter().enumerate().filter(|&(_, offset)| {
// non-entry
offset != 0xFFFF
}).map(|(i, offset)| {
let offset = offset as usize;
let name = if snames[i] == "_" {
stringfnames[i]
} else {
snames[i]
};
if offset == 0xFFFE {
// undocumented: FFFE indicates cap@, which means the capability is not present
// unsure if the handling for this is correct
return Ok((name.to_string(), Vec::new()));
}
// Find the offset of the NUL we want to go to
let nulpos = string_table[offset..string_table_bytes].iter().position(|&b| b == 0);
match nulpos {
Some(len) => Ok((name.to_string(), string_table[offset..offset + len].to_vec())),
None => Err("invalid file: missing NUL in string_table".to_string()),
}
}).collect())
} else {
HashMap::new()
};
// And that's all there is to it
Ok(TermInfo {
names: term_names,
bools: bools_map,
numbers: numbers_map,
strings: string_map
})
}
/// Create a dummy TermInfo struct for msys terminals
pub fn msys_terminfo() -> TermInfo {
let mut strings = HashMap::new();
strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec());
strings.insert("bold".to_string(), b"\x1B[1m".to_vec());
strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec());
strings.insert("setab".to_string(), b"\x1B[4%p1%dm".to_vec());
let mut numbers = HashMap::new();
numbers.insert("colors".to_string(), 8u16);
TermInfo {
names: vec!("cygwin".to_string()), // msys is a fork of an older cygwin version
bools: HashMap::new(),
numbers: numbers,
strings: strings
}
}
#[cfg(test)]
mod test {
use super::{boolnames, boolfnames, numnames, numfnames, stringnames, stringfnames};
#[test]
fn test_veclens() {
assert_eq!(boolfnames.len(), boolnames.len());
assert_eq!(numfnames.len(), numnames.len());
assert_eq!(stringfnames.len(), stringnames.len());
}
#[test]
#[ignore(reason = "no ncurses on buildbots, needs a bundled terminfo file to test against")]
fn test_parse() {
// FIXME #6870: Distribute a compiled file in src/tests and test there
// parse(io::fs_reader(&p("/usr/share/terminfo/r/rxvt-256color")).unwrap(), false);
}
}
| parse | identifier_name |
compiled.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_upper_case_globals, missing_docs)]
//! ncurses-compatible compiled terminfo format parsing (term(5))
use std::collections::HashMap;
use std::io::prelude::*;
use std::io;
use super::super::TermInfo;
// These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable.
pub static boolfnames: &'static[&'static str] = &["auto_left_margin", "auto_right_margin",
"no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type",
"hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above",
"memory_below", "move_insert_mode", "move_standout_mode", "over_strike", "status_line_esc_ok",
"dest_tabs_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff",
"prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region",
"can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch",
"cr_cancels_micro_mode", "has_print_wheel", "row_addr_glitch", "semi_auto_right_margin",
"cpi_changes_res", "lpi_changes_res", "backspaces_with_bs", "crt_no_scrolling",
"no_correctly_working_cr", "gnu_has_meta_key", "linefeed_is_newline", "has_hardware_tabs",
"return_does_clr_eol"];
pub static boolnames: &'static[&'static str] = &["bw", "am", "xsb", "xhp", "xenl", "eo",
"gn", "hc", "km", "hs", "in", "db", "da", "mir", "msgr", "os", "eslok", "xt", "hz", "ul", "xon",
"nxon", "mc5i", "chts", "nrrmc", "npc", "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy",
"xvpa", "sam", "cpix", "lpix", "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"];
pub static numfnames: &'static[&'static str] = &[ "columns", "init_tabs", "lines",
"lines_of_memory", "magic_cookie_glitch", "padding_baud_rate", "virtual_terminal",
"width_status_line", "num_labels", "label_height", "label_width", "max_attributes",
"maximum_windows", "max_colors", "max_pairs", "no_color_video", "buffer_capacity",
"dot_vert_spacing", "dot_horz_spacing", "max_micro_address", "max_micro_jump", "micro_col_size",
"micro_line_size", "number_of_pins", "output_res_char", "output_res_line",
"output_res_horz_inch", "output_res_vert_inch", "print_rate", "wide_char_size", "buttons",
"bit_image_entwining", "bit_image_type", "magic_cookie_glitch_ul", "carriage_return_delay",
"new_line_delay", "backspace_delay", "horizontal_tab_delay", "number_of_function_keys"];
pub static numnames: &'static[&'static str] = &[ "cols", "it", "lines", "lm", "xmc", "pb",
"vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", "colors", "pairs", "ncv", "bufsz", "spinv",
"spinh", "maddr", "mjump", "mcs", "mls", "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs",
"btns", "bitwin", "bitype", "UTug", "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"];
pub static stringfnames: &'static[&'static str] = &[ "back_tab", "bell", "carriage_return",
"change_scroll_region", "clear_all_tabs", "clear_screen", "clr_eol", "clr_eos",
"column_address", "command_character", "cursor_address", "cursor_down", "cursor_home",
"cursor_invisible", "cursor_left", "cursor_mem_address", "cursor_normal", "cursor_right",
"cursor_to_ll", "cursor_up", "cursor_visible", "delete_character", "delete_line",
"dis_status_line", "down_half_line", "enter_alt_charset_mode", "enter_blink_mode",
"enter_bold_mode", "enter_ca_mode", "enter_delete_mode", "enter_dim_mode", "enter_insert_mode",
"enter_secure_mode", "enter_protected_mode", "enter_reverse_mode", "enter_standout_mode",
"enter_underline_mode", "erase_chars", "exit_alt_charset_mode", "exit_attribute_mode",
"exit_ca_mode", "exit_delete_mode", "exit_insert_mode", "exit_standout_mode",
"exit_underline_mode", "flash_screen", "form_feed", "from_status_line", "init_1string",
"init_2string", "init_3string", "init_file", "insert_character", "insert_line",
"insert_padding", "key_backspace", "key_catab", "key_clear", "key_ctab", "key_dc", "key_dl",
"key_down", "key_eic", "key_eol", "key_eos", "key_f0", "key_f1", "key_f10", "key_f2", "key_f3",
"key_f4", "key_f5", "key_f6", "key_f7", "key_f8", "key_f9", "key_home", "key_ic", "key_il",
"key_left", "key_ll", "key_npage", "key_ppage", "key_right", "key_sf", "key_sr", "key_stab",
"key_up", "keypad_local", "keypad_xmit", "lab_f0", "lab_f1", "lab_f10", "lab_f2", "lab_f3",
"lab_f4", "lab_f5", "lab_f6", "lab_f7", "lab_f8", "lab_f9", "meta_off", "meta_on", "newline",
"pad_char", "parm_dch", "parm_delete_line", "parm_down_cursor", "parm_ich", "parm_index",
"parm_insert_line", "parm_left_cursor", "parm_right_cursor", "parm_rindex", "parm_up_cursor",
"pkey_key", "pkey_local", "pkey_xmit", "print_screen", "prtr_off", "prtr_on", "repeat_char",
"reset_1string", "reset_2string", "reset_3string", "reset_file", "restore_cursor",
"row_address", "save_cursor", "scroll_forward", "scroll_reverse", "set_attributes", "set_tab",
"set_window", "tab", "to_status_line", "underline_char", "up_half_line", "init_prog", "key_a1",
"key_a3", "key_b2", "key_c1", "key_c3", "prtr_non", "char_padding", "acs_chars", "plab_norm",
"key_btab", "enter_xon_mode", "exit_xon_mode", "enter_am_mode", "exit_am_mode", "xon_character",
"xoff_character", "ena_acs", "label_on", "label_off", "key_beg", "key_cancel", "key_close",
"key_command", "key_copy", "key_create", "key_end", "key_enter", "key_exit", "key_find",
"key_help", "key_mark", "key_message", "key_move", "key_next", "key_open", "key_options",
"key_previous", "key_print", "key_redo", "key_reference", "key_refresh", "key_replace",
"key_restart", "key_resume", "key_save", "key_suspend", "key_undo", "key_sbeg", "key_scancel",
"key_scommand", "key_scopy", "key_screate", "key_sdc", "key_sdl", "key_select", "key_send",
"key_seol", "key_sexit", "key_sfind", "key_shelp", "key_shome", "key_sic", "key_sleft",
"key_smessage", "key_smove", "key_snext", "key_soptions", "key_sprevious", "key_sprint",
"key_sredo", "key_sreplace", "key_sright", "key_srsume", "key_ssave", "key_ssuspend",
"key_sundo", "req_for_input", "key_f11", "key_f12", "key_f13", "key_f14", "key_f15", "key_f16",
"key_f17", "key_f18", "key_f19", "key_f20", "key_f21", "key_f22", "key_f23", "key_f24",
"key_f25", "key_f26", "key_f27", "key_f28", "key_f29", "key_f30", "key_f31", "key_f32",
"key_f33", "key_f34", "key_f35", "key_f36", "key_f37", "key_f38", "key_f39", "key_f40",
"key_f41", "key_f42", "key_f43", "key_f44", "key_f45", "key_f46", "key_f47", "key_f48",
"key_f49", "key_f50", "key_f51", "key_f52", "key_f53", "key_f54", "key_f55", "key_f56",
"key_f57", "key_f58", "key_f59", "key_f60", "key_f61", "key_f62", "key_f63", "clr_bol",
"clear_margins", "set_left_margin", "set_right_margin", "label_format", "set_clock",
"display_clock", "remove_clock", "create_window", "goto_window", "hangup", "dial_phone",
"quick_dial", "tone", "pulse", "flash_hook", "fixed_pause", "wait_tone", "user0", "user1",
"user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "orig_pair",
"orig_colors", "initialize_color", "initialize_pair", "set_color_pair", "set_foreground",
"set_background", "change_char_pitch", "change_line_pitch", "change_res_horz",
"change_res_vert", "define_char", "enter_doublewide_mode", "enter_draft_quality",
"enter_italics_mode", "enter_leftward_mode", "enter_micro_mode", "enter_near_letter_quality",
"enter_normal_quality", "enter_shadow_mode", "enter_subscript_mode", "enter_superscript_mode",
"enter_upward_mode", "exit_doublewide_mode", "exit_italics_mode", "exit_leftward_mode",
"exit_micro_mode", "exit_shadow_mode", "exit_subscript_mode", "exit_superscript_mode",
"exit_upward_mode", "micro_column_address", "micro_down", "micro_left", "micro_right",
"micro_row_address", "micro_up", "order_of_pins", "parm_down_micro", "parm_left_micro",
"parm_right_micro", "parm_up_micro", "select_char_set", "set_bottom_margin",
"set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin",
"set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image",
"stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr",
"zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse",
"set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init",
"set0_des_seq", "set1_des_seq", "set2_des_seq", "set3_des_seq", "set_lr_margin",
"set_tb_margin", "bit_image_repeat", "bit_image_newline", "bit_image_carriage_return",
"color_names", "define_bit_image_region", "end_bit_image_region", "set_color_band",
"set_page_length", "display_pc_char", "enter_pc_charset_mode", "exit_pc_charset_mode",
"enter_scancode_mode", "exit_scancode_mode", "pc_term_options", "scancode_escape",
"alt_scancode_esc", "enter_horizontal_hl_mode", "enter_left_hl_mode", "enter_low_hl_mode",
"enter_right_hl_mode", "enter_top_hl_mode", "enter_vertical_hl_mode", "set_a_attributes",
"set_pglen_inch", "termcap_init2", "termcap_reset", "linefeed_if_not_lf", "backspace_if_not_bs",
"other_non_function_keys", "arrow_key_map", "acs_ulcorner", "acs_llcorner", "acs_urcorner",
"acs_lrcorner", "acs_ltee", "acs_rtee", "acs_btee", "acs_ttee", "acs_hline", "acs_vline",
"acs_plus", "memory_lock", "memory_unlock", "box_chars_1"];
pub static stringnames: &'static[&'static str] = &[ "cbt", "_", "cr", "csr", "tbc", "clear",
"_", "_", "hpa", "cmdch", "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1",
"ll", "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc",
"dim", "smir", "invis", "prot", "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc",
"rmir", "rmso", "rmul", "flash", "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip",
"kbs", "ktbc", "kclr", "kctab", "_", "_", "kcud1", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "khome", "_", "_", "kcub1", "_", "knp", "kpp", "kcuf1", "_", "_",
"khts", "_", "rmkx", "smkx", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "rmm", "_",
"_", "pad", "dch", "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey",
"pfloc", "pfx", "mc0", "mc4", "_", "rep", "rs1", "rs2", "rs3", "rf", "rc", "vpa", "sc", "ind",
"ri", "sgr", "_", "wind", "_", "tsl", "uc", "hu", "iprog", "_", "_", "_", "_", "_", "mc5p",
"rmp", "acsc", "pln", "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", "_", "smln",
"rmln", "_", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "_", "kent", "kext", "kfnd", "khlp",
"kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt", "kprv", "kprt", "krdo", "kref", "krfr", "krpl",
"krst", "kres", "ksav", "kspd", "kund", "kBEG", "kCAN", "kCMD", "kCPY", "kCRT", "_", "_",
"kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", "kHOM", "_", "kLFT", "kMSG", "kMOV", "kNXT",
"kOPT", "kPRV", "kPRT", "kRDO", "kRPL", "kRIT", "kRES", "kSAV", "kSPD", "kUND", "rfi", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"dclk", "rmclk", "cwin", "wingo", "_", "dial", "qdial", "_", "_", "hook", "pause", "wait", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "op", "oc", "initc", "initp", "scp", "setf",
"setb", "cpi", "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", "smicm", "snlq",
"snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm", "rmicm", "rshm", "rsubm",
"rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1", "mvpa", "mcuu1", "porder", "mcud", "mcub",
"mcuf", "mcuu", "scs", "smgb", "smgbp", "smglp", "smgrp", "smgt", "smgtp", "sbim", "scsd",
"rbim", "rcsd", "subcs", "supcs", "docr", "zerom", "csnm", "kmous", "minfo", "reqmp", "getm",
"setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds", "s3ds", "smglr", "smgtb",
"birep", "binel", "bicr", "colornm", "defbi", "endbi", "setcolor", "slines", "dispc", "smpch",
"rmpch", "smsc", "rmsc", "pctrm", "scesc", "scesa", "ehhlm", "elhlm", "elohlm", "erhlm",
"ethlm", "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", "OTbs", "OTko", "OTma", "OTG2",
"OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", "OTGH", "OTGV", "OTGC", "meml", "memu",
"box1"];
fn read_le_u16(r: &mut io::Read) -> io::Result<u16> {
let mut b = [0; 2];
let mut amt = 0;
while amt < b.len() {
match try!(r.read(&mut b[amt..])) {
0 => return Err(io::Error::new(io::ErrorKind::Other, "end of file")),
n => amt += n,
}
}
Ok((b[0] as u16) | ((b[1] as u16) << 8))
}
fn read_byte(r: &mut io::Read) -> io::Result<u8> {
match r.bytes().next() {
Some(s) => s,
None => Err(io::Error::new(io::ErrorKind::Other, "end of file"))
}
}
/// Parse a compiled terminfo entry, using long capability names if `longnames`
/// is true
pub fn parse(file: &mut io::Read, longnames: bool) -> Result<TermInfo, String> {
macro_rules! try( ($e:expr) => (
match $e {
Ok(e) => e,
Err(e) => return Err(format!("{}", e))
}
) );
let (bnames, snames, nnames) = if longnames {
(boolfnames, stringfnames, numfnames)
} else {
(boolnames, stringnames, numnames)
};
// Check magic number
let magic = try!(read_le_u16(file));
if magic != 0x011A {
return Err(format!("invalid magic number: expected {:x}, found {:x}",
0x011A, magic));
}
// According to the spec, these fields must be >= -1 where -1 means that the feature is not
// supported. Using 0 instead of -1 works because we skip sections with length 0.
macro_rules! read_nonneg {
() => {{
match try!(read_le_u16(file)) as i16 {
n if n >= 0 => n as usize,
-1 => 0,
_ => return Err("incompatible file: length fields must be >= -1".to_string()),
}
}}
}
let names_bytes = read_nonneg!();
let bools_bytes = read_nonneg!();
let numbers_count = read_nonneg!();
let string_offsets_count = read_nonneg!();
let string_table_bytes = read_nonneg!();
if names_bytes == 0 {
return Err("incompatible file: names field must be \
at least 1 byte wide".to_string());
}
if bools_bytes > boolnames.len() {
return Err("incompatible file: more booleans than \
expected".to_string());
}
if numbers_count > numnames.len() {
return Err("incompatible file: more numbers than \
expected".to_string());
}
if string_offsets_count > stringnames.len() {
return Err("incompatible file: more string offsets than \
expected".to_string());
}
// don't read NUL
let mut bytes = Vec::new();
try!(file.take((names_bytes - 1) as u64).read_to_end(&mut bytes));
let names_str = match String::from_utf8(bytes) {
Ok(s) => s,
Err(_) => return Err("input not utf-8".to_string()),
};
let term_names: Vec<String> = names_str.split('|')
.map(|s| s.to_string())
.collect();
// consume NUL
if try!(read_byte(file)) != b'\0' {
return Err("incompatible file: missing null terminator \
for names section".to_string());
}
let bools_map: HashMap<String, bool> = try!(
(0..bools_bytes).filter_map(|i| match read_byte(file) {
Err(e) => Some(Err(e)),
Ok(1) => Some(Ok((bnames[i].to_string(), true))),
Ok(_) => None
}).collect());
if (bools_bytes + names_bytes) % 2 == 1 {
try!(read_byte(file)); // compensate for padding
} |
let numbers_map: HashMap<String, u16> = try!(
(0..numbers_count).filter_map(|i| match read_le_u16(file) {
Ok(0xFFFF) => None,
Ok(n) => Some(Ok((nnames[i].to_string(), n))),
Err(e) => Some(Err(e))
}).collect());
let string_map: HashMap<String, Vec<u8>> = if string_offsets_count > 0 {
let string_offsets: Vec<u16> = try!((0..string_offsets_count).map(|_| {
read_le_u16(file)
}).collect());
let mut string_table = Vec::new();
try!(file.take(string_table_bytes as u64).read_to_end(&mut string_table));
try!(string_offsets.into_iter().enumerate().filter(|&(_, offset)| {
// non-entry
offset != 0xFFFF
}).map(|(i, offset)| {
let offset = offset as usize;
let name = if snames[i] == "_" {
stringfnames[i]
} else {
snames[i]
};
if offset == 0xFFFE {
// undocumented: FFFE indicates cap@, which means the capability is not present
// unsure if the handling for this is correct
return Ok((name.to_string(), Vec::new()));
}
// Find the offset of the NUL we want to go to
let nulpos = string_table[offset..string_table_bytes].iter().position(|&b| b == 0);
match nulpos {
Some(len) => Ok((name.to_string(), string_table[offset..offset + len].to_vec())),
None => Err("invalid file: missing NUL in string_table".to_string()),
}
}).collect())
} else {
HashMap::new()
};
// And that's all there is to it
Ok(TermInfo {
names: term_names,
bools: bools_map,
numbers: numbers_map,
strings: string_map
})
}
/// Create a dummy TermInfo struct for msys terminals
pub fn msys_terminfo() -> TermInfo {
let mut strings = HashMap::new();
strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec());
strings.insert("bold".to_string(), b"\x1B[1m".to_vec());
strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec());
strings.insert("setab".to_string(), b"\x1B[4%p1%dm".to_vec());
let mut numbers = HashMap::new();
numbers.insert("colors".to_string(), 8u16);
TermInfo {
names: vec!("cygwin".to_string()), // msys is a fork of an older cygwin version
bools: HashMap::new(),
numbers: numbers,
strings: strings
}
}
#[cfg(test)]
mod test {
use super::{boolnames, boolfnames, numnames, numfnames, stringnames, stringfnames};
#[test]
fn test_veclens() {
assert_eq!(boolfnames.len(), boolnames.len());
assert_eq!(numfnames.len(), numnames.len());
assert_eq!(stringfnames.len(), stringnames.len());
}
#[test]
#[ignore(reason = "no ncurses on buildbots, needs a bundled terminfo file to test against")]
fn test_parse() {
// FIXME #6870: Distribute a compiled file in src/tests and test there
// parse(io::fs_reader(&p("/usr/share/terminfo/r/rxvt-256color")).unwrap(), false);
}
} | random_line_split | |
compiled.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_upper_case_globals, missing_docs)]
//! ncurses-compatible compiled terminfo format parsing (term(5))
use std::collections::HashMap;
use std::io::prelude::*;
use std::io;
use super::super::TermInfo;
// These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable.
pub static boolfnames: &'static[&'static str] = &["auto_left_margin", "auto_right_margin",
"no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type",
"hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above",
"memory_below", "move_insert_mode", "move_standout_mode", "over_strike", "status_line_esc_ok",
"dest_tabs_magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff",
"prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region",
"can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch",
"cr_cancels_micro_mode", "has_print_wheel", "row_addr_glitch", "semi_auto_right_margin",
"cpi_changes_res", "lpi_changes_res", "backspaces_with_bs", "crt_no_scrolling",
"no_correctly_working_cr", "gnu_has_meta_key", "linefeed_is_newline", "has_hardware_tabs",
"return_does_clr_eol"];
pub static boolnames: &'static[&'static str] = &["bw", "am", "xsb", "xhp", "xenl", "eo",
"gn", "hc", "km", "hs", "in", "db", "da", "mir", "msgr", "os", "eslok", "xt", "hz", "ul", "xon",
"nxon", "mc5i", "chts", "nrrmc", "npc", "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy",
"xvpa", "sam", "cpix", "lpix", "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"];
pub static numfnames: &'static[&'static str] = &[ "columns", "init_tabs", "lines",
"lines_of_memory", "magic_cookie_glitch", "padding_baud_rate", "virtual_terminal",
"width_status_line", "num_labels", "label_height", "label_width", "max_attributes",
"maximum_windows", "max_colors", "max_pairs", "no_color_video", "buffer_capacity",
"dot_vert_spacing", "dot_horz_spacing", "max_micro_address", "max_micro_jump", "micro_col_size",
"micro_line_size", "number_of_pins", "output_res_char", "output_res_line",
"output_res_horz_inch", "output_res_vert_inch", "print_rate", "wide_char_size", "buttons",
"bit_image_entwining", "bit_image_type", "magic_cookie_glitch_ul", "carriage_return_delay",
"new_line_delay", "backspace_delay", "horizontal_tab_delay", "number_of_function_keys"];
pub static numnames: &'static[&'static str] = &[ "cols", "it", "lines", "lm", "xmc", "pb",
"vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", "colors", "pairs", "ncv", "bufsz", "spinv",
"spinh", "maddr", "mjump", "mcs", "mls", "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs",
"btns", "bitwin", "bitype", "UTug", "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"];
pub static stringfnames: &'static[&'static str] = &[ "back_tab", "bell", "carriage_return",
"change_scroll_region", "clear_all_tabs", "clear_screen", "clr_eol", "clr_eos",
"column_address", "command_character", "cursor_address", "cursor_down", "cursor_home",
"cursor_invisible", "cursor_left", "cursor_mem_address", "cursor_normal", "cursor_right",
"cursor_to_ll", "cursor_up", "cursor_visible", "delete_character", "delete_line",
"dis_status_line", "down_half_line", "enter_alt_charset_mode", "enter_blink_mode",
"enter_bold_mode", "enter_ca_mode", "enter_delete_mode", "enter_dim_mode", "enter_insert_mode",
"enter_secure_mode", "enter_protected_mode", "enter_reverse_mode", "enter_standout_mode",
"enter_underline_mode", "erase_chars", "exit_alt_charset_mode", "exit_attribute_mode",
"exit_ca_mode", "exit_delete_mode", "exit_insert_mode", "exit_standout_mode",
"exit_underline_mode", "flash_screen", "form_feed", "from_status_line", "init_1string",
"init_2string", "init_3string", "init_file", "insert_character", "insert_line",
"insert_padding", "key_backspace", "key_catab", "key_clear", "key_ctab", "key_dc", "key_dl",
"key_down", "key_eic", "key_eol", "key_eos", "key_f0", "key_f1", "key_f10", "key_f2", "key_f3",
"key_f4", "key_f5", "key_f6", "key_f7", "key_f8", "key_f9", "key_home", "key_ic", "key_il",
"key_left", "key_ll", "key_npage", "key_ppage", "key_right", "key_sf", "key_sr", "key_stab",
"key_up", "keypad_local", "keypad_xmit", "lab_f0", "lab_f1", "lab_f10", "lab_f2", "lab_f3",
"lab_f4", "lab_f5", "lab_f6", "lab_f7", "lab_f8", "lab_f9", "meta_off", "meta_on", "newline",
"pad_char", "parm_dch", "parm_delete_line", "parm_down_cursor", "parm_ich", "parm_index",
"parm_insert_line", "parm_left_cursor", "parm_right_cursor", "parm_rindex", "parm_up_cursor",
"pkey_key", "pkey_local", "pkey_xmit", "print_screen", "prtr_off", "prtr_on", "repeat_char",
"reset_1string", "reset_2string", "reset_3string", "reset_file", "restore_cursor",
"row_address", "save_cursor", "scroll_forward", "scroll_reverse", "set_attributes", "set_tab",
"set_window", "tab", "to_status_line", "underline_char", "up_half_line", "init_prog", "key_a1",
"key_a3", "key_b2", "key_c1", "key_c3", "prtr_non", "char_padding", "acs_chars", "plab_norm",
"key_btab", "enter_xon_mode", "exit_xon_mode", "enter_am_mode", "exit_am_mode", "xon_character",
"xoff_character", "ena_acs", "label_on", "label_off", "key_beg", "key_cancel", "key_close",
"key_command", "key_copy", "key_create", "key_end", "key_enter", "key_exit", "key_find",
"key_help", "key_mark", "key_message", "key_move", "key_next", "key_open", "key_options",
"key_previous", "key_print", "key_redo", "key_reference", "key_refresh", "key_replace",
"key_restart", "key_resume", "key_save", "key_suspend", "key_undo", "key_sbeg", "key_scancel",
"key_scommand", "key_scopy", "key_screate", "key_sdc", "key_sdl", "key_select", "key_send",
"key_seol", "key_sexit", "key_sfind", "key_shelp", "key_shome", "key_sic", "key_sleft",
"key_smessage", "key_smove", "key_snext", "key_soptions", "key_sprevious", "key_sprint",
"key_sredo", "key_sreplace", "key_sright", "key_srsume", "key_ssave", "key_ssuspend",
"key_sundo", "req_for_input", "key_f11", "key_f12", "key_f13", "key_f14", "key_f15", "key_f16",
"key_f17", "key_f18", "key_f19", "key_f20", "key_f21", "key_f22", "key_f23", "key_f24",
"key_f25", "key_f26", "key_f27", "key_f28", "key_f29", "key_f30", "key_f31", "key_f32",
"key_f33", "key_f34", "key_f35", "key_f36", "key_f37", "key_f38", "key_f39", "key_f40",
"key_f41", "key_f42", "key_f43", "key_f44", "key_f45", "key_f46", "key_f47", "key_f48",
"key_f49", "key_f50", "key_f51", "key_f52", "key_f53", "key_f54", "key_f55", "key_f56",
"key_f57", "key_f58", "key_f59", "key_f60", "key_f61", "key_f62", "key_f63", "clr_bol",
"clear_margins", "set_left_margin", "set_right_margin", "label_format", "set_clock",
"display_clock", "remove_clock", "create_window", "goto_window", "hangup", "dial_phone",
"quick_dial", "tone", "pulse", "flash_hook", "fixed_pause", "wait_tone", "user0", "user1",
"user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "orig_pair",
"orig_colors", "initialize_color", "initialize_pair", "set_color_pair", "set_foreground",
"set_background", "change_char_pitch", "change_line_pitch", "change_res_horz",
"change_res_vert", "define_char", "enter_doublewide_mode", "enter_draft_quality",
"enter_italics_mode", "enter_leftward_mode", "enter_micro_mode", "enter_near_letter_quality",
"enter_normal_quality", "enter_shadow_mode", "enter_subscript_mode", "enter_superscript_mode",
"enter_upward_mode", "exit_doublewide_mode", "exit_italics_mode", "exit_leftward_mode",
"exit_micro_mode", "exit_shadow_mode", "exit_subscript_mode", "exit_superscript_mode",
"exit_upward_mode", "micro_column_address", "micro_down", "micro_left", "micro_right",
"micro_row_address", "micro_up", "order_of_pins", "parm_down_micro", "parm_left_micro",
"parm_right_micro", "parm_up_micro", "select_char_set", "set_bottom_margin",
"set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin",
"set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image",
"stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr",
"zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse",
"set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init",
"set0_des_seq", "set1_des_seq", "set2_des_seq", "set3_des_seq", "set_lr_margin",
"set_tb_margin", "bit_image_repeat", "bit_image_newline", "bit_image_carriage_return",
"color_names", "define_bit_image_region", "end_bit_image_region", "set_color_band",
"set_page_length", "display_pc_char", "enter_pc_charset_mode", "exit_pc_charset_mode",
"enter_scancode_mode", "exit_scancode_mode", "pc_term_options", "scancode_escape",
"alt_scancode_esc", "enter_horizontal_hl_mode", "enter_left_hl_mode", "enter_low_hl_mode",
"enter_right_hl_mode", "enter_top_hl_mode", "enter_vertical_hl_mode", "set_a_attributes",
"set_pglen_inch", "termcap_init2", "termcap_reset", "linefeed_if_not_lf", "backspace_if_not_bs",
"other_non_function_keys", "arrow_key_map", "acs_ulcorner", "acs_llcorner", "acs_urcorner",
"acs_lrcorner", "acs_ltee", "acs_rtee", "acs_btee", "acs_ttee", "acs_hline", "acs_vline",
"acs_plus", "memory_lock", "memory_unlock", "box_chars_1"];
pub static stringnames: &'static[&'static str] = &[ "cbt", "_", "cr", "csr", "tbc", "clear",
"_", "_", "hpa", "cmdch", "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1",
"ll", "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc",
"dim", "smir", "invis", "prot", "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc",
"rmir", "rmso", "rmul", "flash", "ff", "fsl", "is1", "is2", "is3", "if", "ich1", "il1", "ip",
"kbs", "ktbc", "kclr", "kctab", "_", "_", "kcud1", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "khome", "_", "_", "kcub1", "_", "knp", "kpp", "kcuf1", "_", "_",
"khts", "_", "rmkx", "smkx", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "rmm", "_",
"_", "pad", "dch", "dl", "cud", "ich", "indn", "il", "cub", "cuf", "rin", "cuu", "pfkey",
"pfloc", "pfx", "mc0", "mc4", "_", "rep", "rs1", "rs2", "rs3", "rf", "rc", "vpa", "sc", "ind",
"ri", "sgr", "_", "wind", "_", "tsl", "uc", "hu", "iprog", "_", "_", "_", "_", "_", "mc5p",
"rmp", "acsc", "pln", "kcbt", "smxon", "rmxon", "smam", "rmam", "xonc", "xoffc", "_", "smln",
"rmln", "_", "kcan", "kclo", "kcmd", "kcpy", "kcrt", "_", "kent", "kext", "kfnd", "khlp",
"kmrk", "kmsg", "kmov", "knxt", "kopn", "kopt", "kprv", "kprt", "krdo", "kref", "krfr", "krpl",
"krst", "kres", "ksav", "kspd", "kund", "kBEG", "kCAN", "kCMD", "kCPY", "kCRT", "_", "_",
"kslt", "kEND", "kEOL", "kEXT", "kFND", "kHLP", "kHOM", "_", "kLFT", "kMSG", "kMOV", "kNXT",
"kOPT", "kPRV", "kPRT", "kRDO", "kRPL", "kRIT", "kRES", "kSAV", "kSPD", "kUND", "rfi", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_",
"dclk", "rmclk", "cwin", "wingo", "_", "dial", "qdial", "_", "_", "hook", "pause", "wait", "_",
"_", "_", "_", "_", "_", "_", "_", "_", "_", "op", "oc", "initc", "initp", "scp", "setf",
"setb", "cpi", "lpi", "chr", "cvr", "defc", "swidm", "sdrfq", "sitm", "slm", "smicm", "snlq",
"snrmq", "sshm", "ssubm", "ssupm", "sum", "rwidm", "ritm", "rlm", "rmicm", "rshm", "rsubm",
"rsupm", "rum", "mhpa", "mcud1", "mcub1", "mcuf1", "mvpa", "mcuu1", "porder", "mcud", "mcub",
"mcuf", "mcuu", "scs", "smgb", "smgbp", "smglp", "smgrp", "smgt", "smgtp", "sbim", "scsd",
"rbim", "rcsd", "subcs", "supcs", "docr", "zerom", "csnm", "kmous", "minfo", "reqmp", "getm",
"setaf", "setab", "pfxl", "devt", "csin", "s0ds", "s1ds", "s2ds", "s3ds", "smglr", "smgtb",
"birep", "binel", "bicr", "colornm", "defbi", "endbi", "setcolor", "slines", "dispc", "smpch",
"rmpch", "smsc", "rmsc", "pctrm", "scesc", "scesa", "ehhlm", "elhlm", "elohlm", "erhlm",
"ethlm", "evhlm", "sgr1", "slength", "OTi2", "OTrs", "OTnl", "OTbs", "OTko", "OTma", "OTG2",
"OTG3", "OTG1", "OTG4", "OTGR", "OTGL", "OTGU", "OTGD", "OTGH", "OTGV", "OTGC", "meml", "memu",
"box1"];
fn read_le_u16(r: &mut io::Read) -> io::Result<u16> {
let mut b = [0; 2];
let mut amt = 0;
while amt < b.len() {
match try!(r.read(&mut b[amt..])) {
0 => return Err(io::Error::new(io::ErrorKind::Other, "end of file")),
n => amt += n,
}
}
Ok((b[0] as u16) | ((b[1] as u16) << 8))
}
fn read_byte(r: &mut io::Read) -> io::Result<u8> {
match r.bytes().next() {
Some(s) => s,
None => Err(io::Error::new(io::ErrorKind::Other, "end of file"))
}
}
/// Parse a compiled terminfo entry, using long capability names if `longnames`
/// is true
pub fn parse(file: &mut io::Read, longnames: bool) -> Result<TermInfo, String> {
macro_rules! try( ($e:expr) => (
match $e {
Ok(e) => e,
Err(e) => return Err(format!("{}", e))
}
) );
let (bnames, snames, nnames) = if longnames {
(boolfnames, stringfnames, numfnames)
} else {
(boolnames, stringnames, numnames)
};
// Check magic number
let magic = try!(read_le_u16(file));
if magic != 0x011A {
return Err(format!("invalid magic number: expected {:x}, found {:x}",
0x011A, magic));
}
// According to the spec, these fields must be >= -1 where -1 means that the feature is not
// supported. Using 0 instead of -1 works because we skip sections with length 0.
macro_rules! read_nonneg {
() => {{
match try!(read_le_u16(file)) as i16 {
n if n >= 0 => n as usize,
-1 => 0,
_ => return Err("incompatible file: length fields must be >= -1".to_string()),
}
}}
}
let names_bytes = read_nonneg!();
let bools_bytes = read_nonneg!();
let numbers_count = read_nonneg!();
let string_offsets_count = read_nonneg!();
let string_table_bytes = read_nonneg!();
if names_bytes == 0 {
return Err("incompatible file: names field must be \
at least 1 byte wide".to_string());
}
if bools_bytes > boolnames.len() {
return Err("incompatible file: more booleans than \
expected".to_string());
}
if numbers_count > numnames.len() {
return Err("incompatible file: more numbers than \
expected".to_string());
}
if string_offsets_count > stringnames.len() {
return Err("incompatible file: more string offsets than \
expected".to_string());
}
// don't read NUL
let mut bytes = Vec::new();
try!(file.take((names_bytes - 1) as u64).read_to_end(&mut bytes));
let names_str = match String::from_utf8(bytes) {
Ok(s) => s,
Err(_) => return Err("input not utf-8".to_string()),
};
let term_names: Vec<String> = names_str.split('|')
.map(|s| s.to_string())
.collect();
// consume NUL
if try!(read_byte(file)) != b'\0' {
return Err("incompatible file: missing null terminator \
for names section".to_string());
}
let bools_map: HashMap<String, bool> = try!(
(0..bools_bytes).filter_map(|i| match read_byte(file) {
Err(e) => Some(Err(e)),
Ok(1) => Some(Ok((bnames[i].to_string(), true))),
Ok(_) => None
}).collect());
if (bools_bytes + names_bytes) % 2 == 1 {
try!(read_byte(file)); // compensate for padding
}
let numbers_map: HashMap<String, u16> = try!(
(0..numbers_count).filter_map(|i| match read_le_u16(file) {
Ok(0xFFFF) => None,
Ok(n) => Some(Ok((nnames[i].to_string(), n))),
Err(e) => Some(Err(e))
}).collect());
let string_map: HashMap<String, Vec<u8>> = if string_offsets_count > 0 {
let string_offsets: Vec<u16> = try!((0..string_offsets_count).map(|_| {
read_le_u16(file)
}).collect());
let mut string_table = Vec::new();
try!(file.take(string_table_bytes as u64).read_to_end(&mut string_table));
try!(string_offsets.into_iter().enumerate().filter(|&(_, offset)| {
// non-entry
offset != 0xFFFF
}).map(|(i, offset)| {
let offset = offset as usize;
let name = if snames[i] == "_" | else {
snames[i]
};
if offset == 0xFFFE {
// undocumented: FFFE indicates cap@, which means the capability is not present
// unsure if the handling for this is correct
return Ok((name.to_string(), Vec::new()));
}
// Find the offset of the NUL we want to go to
let nulpos = string_table[offset..string_table_bytes].iter().position(|&b| b == 0);
match nulpos {
Some(len) => Ok((name.to_string(), string_table[offset..offset + len].to_vec())),
None => Err("invalid file: missing NUL in string_table".to_string()),
}
}).collect())
} else {
HashMap::new()
};
// And that's all there is to it
Ok(TermInfo {
names: term_names,
bools: bools_map,
numbers: numbers_map,
strings: string_map
})
}
/// Create a dummy TermInfo struct for msys terminals
pub fn msys_terminfo() -> TermInfo {
let mut strings = HashMap::new();
strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec());
strings.insert("bold".to_string(), b"\x1B[1m".to_vec());
strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec());
strings.insert("setab".to_string(), b"\x1B[4%p1%dm".to_vec());
let mut numbers = HashMap::new();
numbers.insert("colors".to_string(), 8u16);
TermInfo {
names: vec!("cygwin".to_string()), // msys is a fork of an older cygwin version
bools: HashMap::new(),
numbers: numbers,
strings: strings
}
}
#[cfg(test)]
mod test {
use super::{boolnames, boolfnames, numnames, numfnames, stringnames, stringfnames};
#[test]
fn test_veclens() {
assert_eq!(boolfnames.len(), boolnames.len());
assert_eq!(numfnames.len(), numnames.len());
assert_eq!(stringfnames.len(), stringnames.len());
}
#[test]
#[ignore(reason = "no ncurses on buildbots, needs a bundled terminfo file to test against")]
fn test_parse() {
// FIXME #6870: Distribute a compiled file in src/tests and test there
// parse(io::fs_reader(&p("/usr/share/terminfo/r/rxvt-256color")).unwrap(), false);
}
}
| {
stringfnames[i]
} | conditional_block |
gstr.rs | // This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2013-2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
use glib as ffi;
use types::{gchar,gpointer};
use libc;
use std::ffi::{CStr, CString, NulError};
use std::mem;
use std::ops::Deref;
use std::str;
pub struct OwnedGStr {
ptr: *const gchar,
}
impl OwnedGStr {
pub unsafe fn from_ptr(ptr: *mut gchar) -> OwnedGStr {
OwnedGStr { ptr: ptr }
}
}
impl Deref for OwnedGStr {
type Target = CStr;
fn deref(&self) -> &CStr {
unsafe { CStr::from_ptr(self.ptr) }
}
}
impl Drop for OwnedGStr {
fn | (&mut self) {
unsafe { ffi::g_free(self.ptr as gpointer) }
}
}
impl Clone for OwnedGStr {
fn clone(&self) -> OwnedGStr {
unsafe {
OwnedGStr::from_ptr(ffi::g_strdup(self.ptr))
}
}
}
impl PartialEq for OwnedGStr {
fn eq(&self, other: &OwnedGStr) -> bool {
unsafe { libc::strcmp(self.ptr, other.ptr) == 0 }
}
}
impl Eq for OwnedGStr { }
pub struct Utf8 {
inner: CStr
}
impl Utf8 {
#[inline]
pub fn as_ptr(&self) -> *const gchar {
self.inner.as_ptr()
}
#[inline]
pub fn to_str(&self) -> &str {
unsafe { str::from_utf8_unchecked(self.inner.to_bytes()) }
}
pub fn from_static_str(s: &'static str) -> &'static Utf8 {
assert!(s.ends_with("\0"),
"static string is not null-terminated: \"{}\"", s);
unsafe { Utf8::from_ptr(s.as_ptr() as *const gchar) }
}
pub unsafe fn from_ptr<'a>(ptr: *const gchar) -> &'a Utf8 {
mem::transmute(CStr::from_ptr(ptr))
}
}
impl AsRef<CStr> for Utf8 {
#[inline]
fn as_ref(&self) -> &CStr { &self.inner }
}
pub struct Utf8String {
inner: CString
}
impl Deref for Utf8String {
type Target = Utf8;
fn deref(&self) -> &Utf8 {
unsafe { Utf8::from_ptr(self.inner.as_ptr()) }
}
}
impl Utf8String {
pub fn new<T>(t: T) -> Result<Utf8String, NulError>
where T: Into<String>
{
let c_str = try!(CString::new(t.into()));
Ok(Utf8String { inner: c_str })
}
}
| drop | identifier_name |
gstr.rs | // This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2013-2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
use glib as ffi;
use types::{gchar,gpointer};
use libc;
use std::ffi::{CStr, CString, NulError};
use std::mem;
use std::ops::Deref;
use std::str;
pub struct OwnedGStr {
ptr: *const gchar,
}
impl OwnedGStr {
pub unsafe fn from_ptr(ptr: *mut gchar) -> OwnedGStr {
OwnedGStr { ptr: ptr }
}
}
impl Deref for OwnedGStr {
type Target = CStr;
fn deref(&self) -> &CStr {
unsafe { CStr::from_ptr(self.ptr) }
}
}
impl Drop for OwnedGStr {
fn drop(&mut self) {
unsafe { ffi::g_free(self.ptr as gpointer) }
}
}
impl Clone for OwnedGStr {
fn clone(&self) -> OwnedGStr {
unsafe {
OwnedGStr::from_ptr(ffi::g_strdup(self.ptr))
}
}
}
impl PartialEq for OwnedGStr {
fn eq(&self, other: &OwnedGStr) -> bool {
unsafe { libc::strcmp(self.ptr, other.ptr) == 0 }
}
}
impl Eq for OwnedGStr { }
pub struct Utf8 {
inner: CStr
}
impl Utf8 {
#[inline]
pub fn as_ptr(&self) -> *const gchar {
self.inner.as_ptr()
}
#[inline]
pub fn to_str(&self) -> &str {
unsafe { str::from_utf8_unchecked(self.inner.to_bytes()) }
}
pub fn from_static_str(s: &'static str) -> &'static Utf8 {
assert!(s.ends_with("\0"),
"static string is not null-terminated: \"{}\"", s);
unsafe { Utf8::from_ptr(s.as_ptr() as *const gchar) }
}
pub unsafe fn from_ptr<'a>(ptr: *const gchar) -> &'a Utf8 {
mem::transmute(CStr::from_ptr(ptr))
}
}
impl AsRef<CStr> for Utf8 { | inner: CString
}
impl Deref for Utf8String {
type Target = Utf8;
fn deref(&self) -> &Utf8 {
unsafe { Utf8::from_ptr(self.inner.as_ptr()) }
}
}
impl Utf8String {
pub fn new<T>(t: T) -> Result<Utf8String, NulError>
where T: Into<String>
{
let c_str = try!(CString::new(t.into()));
Ok(Utf8String { inner: c_str })
}
} | #[inline]
fn as_ref(&self) -> &CStr { &self.inner }
}
pub struct Utf8String { | random_line_split |
gstr.rs | // This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2013-2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
use glib as ffi;
use types::{gchar,gpointer};
use libc;
use std::ffi::{CStr, CString, NulError};
use std::mem;
use std::ops::Deref;
use std::str;
pub struct OwnedGStr {
ptr: *const gchar,
}
impl OwnedGStr {
pub unsafe fn from_ptr(ptr: *mut gchar) -> OwnedGStr {
OwnedGStr { ptr: ptr }
}
}
impl Deref for OwnedGStr {
type Target = CStr;
fn deref(&self) -> &CStr {
unsafe { CStr::from_ptr(self.ptr) }
}
}
impl Drop for OwnedGStr {
fn drop(&mut self) {
unsafe { ffi::g_free(self.ptr as gpointer) }
}
}
impl Clone for OwnedGStr {
fn clone(&self) -> OwnedGStr {
unsafe {
OwnedGStr::from_ptr(ffi::g_strdup(self.ptr))
}
}
}
impl PartialEq for OwnedGStr {
fn eq(&self, other: &OwnedGStr) -> bool {
unsafe { libc::strcmp(self.ptr, other.ptr) == 0 }
}
}
impl Eq for OwnedGStr { }
pub struct Utf8 {
inner: CStr
}
impl Utf8 {
#[inline]
pub fn as_ptr(&self) -> *const gchar {
self.inner.as_ptr()
}
#[inline]
pub fn to_str(&self) -> &str {
unsafe { str::from_utf8_unchecked(self.inner.to_bytes()) }
}
pub fn from_static_str(s: &'static str) -> &'static Utf8 |
pub unsafe fn from_ptr<'a>(ptr: *const gchar) -> &'a Utf8 {
mem::transmute(CStr::from_ptr(ptr))
}
}
impl AsRef<CStr> for Utf8 {
#[inline]
fn as_ref(&self) -> &CStr { &self.inner }
}
pub struct Utf8String {
inner: CString
}
impl Deref for Utf8String {
type Target = Utf8;
fn deref(&self) -> &Utf8 {
unsafe { Utf8::from_ptr(self.inner.as_ptr()) }
}
}
impl Utf8String {
pub fn new<T>(t: T) -> Result<Utf8String, NulError>
where T: Into<String>
{
let c_str = try!(CString::new(t.into()));
Ok(Utf8String { inner: c_str })
}
}
| {
assert!(s.ends_with("\0"),
"static string is not null-terminated: \"{}\"", s);
unsafe { Utf8::from_ptr(s.as_ptr() as *const gchar) }
} | identifier_body |
AlwaysBeCasting.tsx | import React from 'react';
class AlwaysBeCasting extends CoreAlwaysBeCasting {
get suggestionThresholds() {
return {
actual: this.activeTimePercentage,
isLessThan: {
minor: 0.95,
average: 0.85,
major: 0.75,
},
style: ThresholdStyle.PERCENTAGE,
};
}
suggestions(when: When) {
when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => suggest(<>Your downtime can be improved. If you need to move use <SpellLink id={SPELLS.FLAME_SHOCK.id} />, <SpellLink id={SPELLS.EARTH_SHOCK.id} /> or <SpellLink id={SPELLS.FROST_SHOCK.id} /></>)
.icon('spell_mage_altertime')
.actual(`${formatPercentage(1 - actual)}% downtime`)
.recommended(`<${formatPercentage(1 - recommended)}% is recommended`));
}
}
export default AlwaysBeCasting; | import CoreAlwaysBeCasting from 'parser/shared/modules/AlwaysBeCasting';
import { ThresholdStyle, When } from 'parser/core/ParseResults';
import { SpellLink } from 'interface';
import SPELLS from 'common/SPELLS';
import { formatPercentage } from 'common/format'; | random_line_split | |
AlwaysBeCasting.tsx | import CoreAlwaysBeCasting from 'parser/shared/modules/AlwaysBeCasting';
import { ThresholdStyle, When } from 'parser/core/ParseResults';
import { SpellLink } from 'interface';
import SPELLS from 'common/SPELLS';
import { formatPercentage } from 'common/format';
import React from 'react';
class AlwaysBeCasting extends CoreAlwaysBeCasting {
get suggestionThresholds() {
return {
actual: this.activeTimePercentage,
isLessThan: {
minor: 0.95,
average: 0.85,
major: 0.75,
},
style: ThresholdStyle.PERCENTAGE,
};
}
| (when: When) {
when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => suggest(<>Your downtime can be improved. If you need to move use <SpellLink id={SPELLS.FLAME_SHOCK.id} />, <SpellLink id={SPELLS.EARTH_SHOCK.id} /> or <SpellLink id={SPELLS.FROST_SHOCK.id} /></>)
.icon('spell_mage_altertime')
.actual(`${formatPercentage(1 - actual)}% downtime`)
.recommended(`<${formatPercentage(1 - recommended)}% is recommended`));
}
}
export default AlwaysBeCasting;
| suggestions | identifier_name |
page_test_runner.py | # Copyright (c) 2012 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 logging
import os
import sys
from telemetry.core import browser_finder
from telemetry.core import browser_options
from telemetry.page import page_test
from telemetry.page import page_runner
from telemetry.page import page_set
from telemetry.test import discover
def | (test_dir, page_set_filenames):
"""Turns a PageTest into a command-line program.
Args:
test_dir: Path to directory containing PageTests.
"""
tests = discover.DiscoverClasses(test_dir,
os.path.join(test_dir, '..'),
page_test.PageTest)
# Naively find the test. If we use the browser options parser, we run
# the risk of failing to parse if we use a test-specific parameter.
test_name = None
for arg in sys.argv:
if arg in tests:
test_name = arg
options = browser_options.BrowserOptions()
parser = options.CreateParser('%prog [options] <test> <page_set>')
page_runner.PageRunner.AddCommandLineOptions(parser)
test = None
if test_name is not None:
if test_name not in tests:
sys.stderr.write('No test name %s found' % test_name)
sys.exit(1)
test = tests[test_name]()
test.AddCommandLineOptions(parser)
_, args = parser.parse_args()
if test is None or len(args) != 2:
parser.print_usage()
print >> sys.stderr, 'Available tests:\n%s\n' % ',\n'.join(
sorted(tests.keys()))
print >> sys.stderr, 'Available page_sets:\n%s\n' % ',\n'.join(
sorted([os.path.relpath(f)
for f in page_set_filenames]))
sys.exit(1)
ps = page_set.PageSet.FromFile(args[1])
results = page_test.PageTestResults()
return RunTestOnPageSet(options, ps, test, results)
def RunTestOnPageSet(options, ps, test, results):
test.CustomizeBrowserOptions(options)
possible_browser = browser_finder.FindBrowser(options)
if not possible_browser:
print >> sys.stderr, """No browser found.\n
Use --browser=list to figure out which are available.\n"""
sys.exit(1)
with page_runner.PageRunner(ps) as runner:
runner.Run(options, possible_browser, test, results)
print '%i pages succeed\n' % len(results.page_successes)
if len(results.page_failures):
logging.warning('Failed pages: %s', '\n'.join(
[failure['page'].url for failure in results.page_failures]))
if len(results.skipped_pages):
logging.warning('Skipped pages: %s', '\n'.join(
[skipped['page'].url for skipped in results.skipped_pages]))
return min(255, len(results.page_failures))
| Main | identifier_name |
page_test_runner.py | # Copyright (c) 2012 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 logging
import os
import sys
from telemetry.core import browser_finder
from telemetry.core import browser_options
from telemetry.page import page_test
from telemetry.page import page_runner
from telemetry.page import page_set
from telemetry.test import discover
def Main(test_dir, page_set_filenames):
"""Turns a PageTest into a command-line program.
Args:
test_dir: Path to directory containing PageTests.
"""
tests = discover.DiscoverClasses(test_dir,
os.path.join(test_dir, '..'),
page_test.PageTest)
# Naively find the test. If we use the browser options parser, we run
# the risk of failing to parse if we use a test-specific parameter.
test_name = None
for arg in sys.argv:
if arg in tests:
test_name = arg
options = browser_options.BrowserOptions()
parser = options.CreateParser('%prog [options] <test> <page_set>')
page_runner.PageRunner.AddCommandLineOptions(parser)
test = None
if test_name is not None:
if test_name not in tests:
sys.stderr.write('No test name %s found' % test_name)
sys.exit(1)
test = tests[test_name]()
test.AddCommandLineOptions(parser)
_, args = parser.parse_args()
if test is None or len(args) != 2:
parser.print_usage()
print >> sys.stderr, 'Available tests:\n%s\n' % ',\n'.join(
sorted(tests.keys()))
print >> sys.stderr, 'Available page_sets:\n%s\n' % ',\n'.join(
sorted([os.path.relpath(f) |
return RunTestOnPageSet(options, ps, test, results)
def RunTestOnPageSet(options, ps, test, results):
test.CustomizeBrowserOptions(options)
possible_browser = browser_finder.FindBrowser(options)
if not possible_browser:
print >> sys.stderr, """No browser found.\n
Use --browser=list to figure out which are available.\n"""
sys.exit(1)
with page_runner.PageRunner(ps) as runner:
runner.Run(options, possible_browser, test, results)
print '%i pages succeed\n' % len(results.page_successes)
if len(results.page_failures):
logging.warning('Failed pages: %s', '\n'.join(
[failure['page'].url for failure in results.page_failures]))
if len(results.skipped_pages):
logging.warning('Skipped pages: %s', '\n'.join(
[skipped['page'].url for skipped in results.skipped_pages]))
return min(255, len(results.page_failures)) | for f in page_set_filenames]))
sys.exit(1)
ps = page_set.PageSet.FromFile(args[1])
results = page_test.PageTestResults() | random_line_split |
page_test_runner.py | # Copyright (c) 2012 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 logging
import os
import sys
from telemetry.core import browser_finder
from telemetry.core import browser_options
from telemetry.page import page_test
from telemetry.page import page_runner
from telemetry.page import page_set
from telemetry.test import discover
def Main(test_dir, page_set_filenames):
"""Turns a PageTest into a command-line program.
Args:
test_dir: Path to directory containing PageTests.
"""
tests = discover.DiscoverClasses(test_dir,
os.path.join(test_dir, '..'),
page_test.PageTest)
# Naively find the test. If we use the browser options parser, we run
# the risk of failing to parse if we use a test-specific parameter.
test_name = None
for arg in sys.argv:
if arg in tests:
test_name = arg
options = browser_options.BrowserOptions()
parser = options.CreateParser('%prog [options] <test> <page_set>')
page_runner.PageRunner.AddCommandLineOptions(parser)
test = None
if test_name is not None:
if test_name not in tests:
sys.stderr.write('No test name %s found' % test_name)
sys.exit(1)
test = tests[test_name]()
test.AddCommandLineOptions(parser)
_, args = parser.parse_args()
if test is None or len(args) != 2:
parser.print_usage()
print >> sys.stderr, 'Available tests:\n%s\n' % ',\n'.join(
sorted(tests.keys()))
print >> sys.stderr, 'Available page_sets:\n%s\n' % ',\n'.join(
sorted([os.path.relpath(f)
for f in page_set_filenames]))
sys.exit(1)
ps = page_set.PageSet.FromFile(args[1])
results = page_test.PageTestResults()
return RunTestOnPageSet(options, ps, test, results)
def RunTestOnPageSet(options, ps, test, results):
| test.CustomizeBrowserOptions(options)
possible_browser = browser_finder.FindBrowser(options)
if not possible_browser:
print >> sys.stderr, """No browser found.\n
Use --browser=list to figure out which are available.\n"""
sys.exit(1)
with page_runner.PageRunner(ps) as runner:
runner.Run(options, possible_browser, test, results)
print '%i pages succeed\n' % len(results.page_successes)
if len(results.page_failures):
logging.warning('Failed pages: %s', '\n'.join(
[failure['page'].url for failure in results.page_failures]))
if len(results.skipped_pages):
logging.warning('Skipped pages: %s', '\n'.join(
[skipped['page'].url for skipped in results.skipped_pages]))
return min(255, len(results.page_failures)) | identifier_body | |
page_test_runner.py | # Copyright (c) 2012 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 logging
import os
import sys
from telemetry.core import browser_finder
from telemetry.core import browser_options
from telemetry.page import page_test
from telemetry.page import page_runner
from telemetry.page import page_set
from telemetry.test import discover
def Main(test_dir, page_set_filenames):
"""Turns a PageTest into a command-line program.
Args:
test_dir: Path to directory containing PageTests.
"""
tests = discover.DiscoverClasses(test_dir,
os.path.join(test_dir, '..'),
page_test.PageTest)
# Naively find the test. If we use the browser options parser, we run
# the risk of failing to parse if we use a test-specific parameter.
test_name = None
for arg in sys.argv:
if arg in tests:
test_name = arg
options = browser_options.BrowserOptions()
parser = options.CreateParser('%prog [options] <test> <page_set>')
page_runner.PageRunner.AddCommandLineOptions(parser)
test = None
if test_name is not None:
if test_name not in tests:
sys.stderr.write('No test name %s found' % test_name)
sys.exit(1)
test = tests[test_name]()
test.AddCommandLineOptions(parser)
_, args = parser.parse_args()
if test is None or len(args) != 2:
|
ps = page_set.PageSet.FromFile(args[1])
results = page_test.PageTestResults()
return RunTestOnPageSet(options, ps, test, results)
def RunTestOnPageSet(options, ps, test, results):
test.CustomizeBrowserOptions(options)
possible_browser = browser_finder.FindBrowser(options)
if not possible_browser:
print >> sys.stderr, """No browser found.\n
Use --browser=list to figure out which are available.\n"""
sys.exit(1)
with page_runner.PageRunner(ps) as runner:
runner.Run(options, possible_browser, test, results)
print '%i pages succeed\n' % len(results.page_successes)
if len(results.page_failures):
logging.warning('Failed pages: %s', '\n'.join(
[failure['page'].url for failure in results.page_failures]))
if len(results.skipped_pages):
logging.warning('Skipped pages: %s', '\n'.join(
[skipped['page'].url for skipped in results.skipped_pages]))
return min(255, len(results.page_failures))
| parser.print_usage()
print >> sys.stderr, 'Available tests:\n%s\n' % ',\n'.join(
sorted(tests.keys()))
print >> sys.stderr, 'Available page_sets:\n%s\n' % ',\n'.join(
sorted([os.path.relpath(f)
for f in page_set_filenames]))
sys.exit(1) | conditional_block |
test_cookiestorage.py | from django.test import TestCase
from django.core import signing
from django.core.exceptions import SuspiciousOperation
from django.http import HttpResponse
from django.contrib.auth.tests.utils import skipIfCustomUser
from django.contrib.formtools.wizard.storage.cookie import CookieStorage
from django.contrib.formtools.tests.wizard.storage import get_request, TestStorage
@skipIfCustomUser
class TestCookieStorage(TestStorage, TestCase):
def get_storage(self):
return CookieStorage
def test_manipulated_cookie(self):
request = get_request()
storage = self.get_storage()('wizard1', request, None)
cookie_signer = signing.get_cookie_signer(storage.prefix)
storage.request.COOKIES[storage.prefix] = cookie_signer.sign(
storage.encoder.encode({'key1': 'value1'}))
self.assertEqual(storage.load_data(), {'key1': 'value1'})
storage.request.COOKIES[storage.prefix] = 'i_am_manipulated'
self.assertRaises(SuspiciousOperation, storage.load_data)
def test_reset_cookie(self):
request = get_request() | storage.update_response(response)
cookie_signer = signing.get_cookie_signer(storage.prefix)
signed_cookie_data = cookie_signer.sign(storage.encoder.encode(storage.data))
self.assertEqual(response.cookies[storage.prefix].value, signed_cookie_data)
storage.init_data()
storage.update_response(response)
unsigned_cookie_data = cookie_signer.unsign(response.cookies[storage.prefix].value)
self.assertJSONEqual(unsigned_cookie_data,
{"step_files": {}, "step": None, "extra_data": {}, "step_data": {}}) | storage = self.get_storage()('wizard1', request, None)
storage.data = {'key1': 'value1'}
response = HttpResponse() | random_line_split |
test_cookiestorage.py | from django.test import TestCase
from django.core import signing
from django.core.exceptions import SuspiciousOperation
from django.http import HttpResponse
from django.contrib.auth.tests.utils import skipIfCustomUser
from django.contrib.formtools.wizard.storage.cookie import CookieStorage
from django.contrib.formtools.tests.wizard.storage import get_request, TestStorage
@skipIfCustomUser
class | (TestStorage, TestCase):
def get_storage(self):
return CookieStorage
def test_manipulated_cookie(self):
request = get_request()
storage = self.get_storage()('wizard1', request, None)
cookie_signer = signing.get_cookie_signer(storage.prefix)
storage.request.COOKIES[storage.prefix] = cookie_signer.sign(
storage.encoder.encode({'key1': 'value1'}))
self.assertEqual(storage.load_data(), {'key1': 'value1'})
storage.request.COOKIES[storage.prefix] = 'i_am_manipulated'
self.assertRaises(SuspiciousOperation, storage.load_data)
def test_reset_cookie(self):
request = get_request()
storage = self.get_storage()('wizard1', request, None)
storage.data = {'key1': 'value1'}
response = HttpResponse()
storage.update_response(response)
cookie_signer = signing.get_cookie_signer(storage.prefix)
signed_cookie_data = cookie_signer.sign(storage.encoder.encode(storage.data))
self.assertEqual(response.cookies[storage.prefix].value, signed_cookie_data)
storage.init_data()
storage.update_response(response)
unsigned_cookie_data = cookie_signer.unsign(response.cookies[storage.prefix].value)
self.assertJSONEqual(unsigned_cookie_data,
{"step_files": {}, "step": None, "extra_data": {}, "step_data": {}})
| TestCookieStorage | identifier_name |
test_cookiestorage.py | from django.test import TestCase
from django.core import signing
from django.core.exceptions import SuspiciousOperation
from django.http import HttpResponse
from django.contrib.auth.tests.utils import skipIfCustomUser
from django.contrib.formtools.wizard.storage.cookie import CookieStorage
from django.contrib.formtools.tests.wizard.storage import get_request, TestStorage
@skipIfCustomUser
class TestCookieStorage(TestStorage, TestCase):
def get_storage(self):
return CookieStorage
def test_manipulated_cookie(self):
request = get_request()
storage = self.get_storage()('wizard1', request, None)
cookie_signer = signing.get_cookie_signer(storage.prefix)
storage.request.COOKIES[storage.prefix] = cookie_signer.sign(
storage.encoder.encode({'key1': 'value1'}))
self.assertEqual(storage.load_data(), {'key1': 'value1'})
storage.request.COOKIES[storage.prefix] = 'i_am_manipulated'
self.assertRaises(SuspiciousOperation, storage.load_data)
def test_reset_cookie(self):
| request = get_request()
storage = self.get_storage()('wizard1', request, None)
storage.data = {'key1': 'value1'}
response = HttpResponse()
storage.update_response(response)
cookie_signer = signing.get_cookie_signer(storage.prefix)
signed_cookie_data = cookie_signer.sign(storage.encoder.encode(storage.data))
self.assertEqual(response.cookies[storage.prefix].value, signed_cookie_data)
storage.init_data()
storage.update_response(response)
unsigned_cookie_data = cookie_signer.unsign(response.cookies[storage.prefix].value)
self.assertJSONEqual(unsigned_cookie_data,
{"step_files": {}, "step": None, "extra_data": {}, "step_data": {}}) | identifier_body | |
parameter_tests_edges.py |
# coding: utf-8
# In[1]:
import os
from shutil import copyfile
import subprocess
from save_embedded_graph27 import main_binary as embed_main
from spearmint_ghsom import main as ghsom_main
import numpy as np
import pickle
from time import time
def save_obj(obj, name):
with open(name + '.pkl', 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(name):
with open(name + '.pkl', 'rb') as f:
return pickle.load(f)
#root dir
os.chdir("C:\Miniconda3\Jupyter\GHSOM_simplex_dsd")
#save directory
dir = os.path.abspath("parameter_tests_edges")
#number of times to repeat
num_repeats = 30
#number of nodes in the graph
N = 64
#make save directory
if not os.path.isdir(dir):
os.mkdir(dir)
#change to dir
os.chdir(dir)
#network file names -- output of network generator
network = "network.dat"
first_level = "community.dat"
#community labels
labels = 'firstlevelcommunity'
#mixing factors
mu = 0.1
num_edges_ls = [256, 512, 1024]
parameter_settings = [0.5, 0.6, 0.7, 0.8, 0.9, 1][::-1]
overall_nmi_scores = np.zeros((len(num_edges_ls), len(parameter_settings)))
for i in range(len(num_edges_ls)):
#number of edges
num_edges = num_edges_ls[i]
#create directory
dir_string = os.path.join(dir, str(num_edges))
if not os.path.isdir(dir_string):
os.mkdir(dir_string)
#change working directory
os.chdir(dir_string)
for j in range(len(parameter_settings)):
#setting fo e_sg
p = parameter_settings[j]
#ghsom parameters
params = {'w': 0.0001,
'eta': 0.0001,
'sigma': 1,
'e_sg': p,
'e_en': 0.8}
#create directory
dir_string_p = os.path.join(dir_string, str(p))
if not os.path.isdir(dir_string_p):
os.mkdir(dir_string_p)
#change working directory
os.chdir(dir_string_p)
if os.path.isfile('nmi_scores.csv'):
print 'already completed {}/{}, loading scores and continuing'.format(k1, p)
nmi_scores = np.genfromtxt('nmi_scores.csv', delimiter=',')
overall_nmi_scores[i,j] = np.mean(nmi_scores, axis=0)
continue
#copy executable
ex = "benchmark.exe"
if not os.path.isfile(ex):
source = "C:\\Users\\davem\\Documents\\PhD\\Benchmark Graph Generators\\binary_networks\\benchmark.exe"
copyfile(source, ex)
#record NMI scores
if not os.path.isfile('nmi_scores.pkl'):
print 'creating new nmi scores array'
nmi_scores = np.zeros(num_repeats)
else:
print 'loading nmi score progress'
nmi_scores = load_obj('nmi_scores')
#record running times
if not os.path.isfile('running_times.pkl'):
print 'creating new running time array'
running_times = np.zeros(num_repeats)
else:
print 'loading running time progress'
running_times = load_obj('running_times')
print
#generate networks
for r in range(1, num_repeats+1):
#number of communities
num_communities = np.random.randint(1,5)
#number of nodes in micro community
minc = np.floor(float(N) / num_communities)
maxc = np.ceil(float(N) / num_communities)
#average number of edges
k = float(num_edges) / N
#max number of edges
maxk = 2 * k
#make benchmark parameter file
filename = "benchmark_flags_{}_{}_{}.dat".format(num_edges,p,r)
if not os.path.isfile(filename):
|
#cmd strings
change_dir_cmd = "cd {}".format(dir_string_p)
generate_network_cmd = "benchmark -f {}".format(filename)
#output of cmd
output_file = open("cmd_output.out", 'w')
network_rename = "{}_{}".format(r,network)
first_level_rename = "{}_{}".format(r,first_level)
gml_filename = 'embedded_network_{}.gml'.format(r)
if not os.path.isfile(network_rename):
process = subprocess.Popen(change_dir_cmd + " && " + generate_network_cmd,
stdout=output_file,
stderr=output_file,
shell=True)
process.wait()
print 'generated graph {}'.format(r)
os.rename(network, network_rename)
os.rename(first_level, first_level_rename)
print 'renamed graph {}'.format(r)
if not os.path.isfile(gml_filename):
##embed graph
embed_main(network_rename, first_level_rename)
print 'embedded graph {} as {} in {}'.format(r, gml_filename, os.getcwd())
##score for this network
if not np.all(nmi_scores[r-1]):
start_time = time()
print 'starting ghsom for: {}/{}/{}'.format(num_edges, p, gml_filename)
nmi_score, communities_detected = ghsom_main(params, gml_filename, labels)
nmi_scores[r-1] = nmi_score
running_time = time() - start_time
print 'running time of algorithm: {}'.format(running_time)
running_times[r-1] = running_time
#save
save_obj(nmi_scores, 'nmi_scores')
save_obj(running_times, 'running_times')
print 'saved nmi score for network {}: {}'.format(gml_filename, nmi_score)
print
##output nmi scores to csv file
print 'writing nmi scores and running times to file'
np.savetxt('nmi_scores.csv',nmi_scores,delimiter=',')
np.savetxt('running_times.csv',running_times,delimiter=',')
print
#odd to overall list
overall_nmi_scores[i,j] = np.mean(nmi_scores, axis=0)
print 'DONE'
print 'OVERALL NMI SCORES'
print overall_nmi_scores
# In[3]:
for scores in overall_nmi_scores:
print scores
idx = np.argsort(scores)[::-1]
print parameter_settings[idx[0]]
| print 'number of edges: {}'.format(num_edges)
print 'number of communities: {}'.format(num_communities)
print '-N {} -k {} -maxk {} -minc {} -maxc {} -mu {}'.format(N, k, maxk, minc, maxc, mu)
with open(filename,"w") as f:
f.write("-N {} -k {} -maxk {} -minc {} -maxc {} -mu {}".format(N, k, maxk, minc, maxc, mu))
print 'written flag file: {}'.format(filename) | conditional_block |
parameter_tests_edges.py |
# coding: utf-8
# In[1]:
import os
from shutil import copyfile
import subprocess
from save_embedded_graph27 import main_binary as embed_main
from spearmint_ghsom import main as ghsom_main
import numpy as np
import pickle
from time import time
def save_obj(obj, name):
with open(name + '.pkl', 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def | (name):
with open(name + '.pkl', 'rb') as f:
return pickle.load(f)
#root dir
os.chdir("C:\Miniconda3\Jupyter\GHSOM_simplex_dsd")
#save directory
dir = os.path.abspath("parameter_tests_edges")
#number of times to repeat
num_repeats = 30
#number of nodes in the graph
N = 64
#make save directory
if not os.path.isdir(dir):
os.mkdir(dir)
#change to dir
os.chdir(dir)
#network file names -- output of network generator
network = "network.dat"
first_level = "community.dat"
#community labels
labels = 'firstlevelcommunity'
#mixing factors
mu = 0.1
num_edges_ls = [256, 512, 1024]
parameter_settings = [0.5, 0.6, 0.7, 0.8, 0.9, 1][::-1]
overall_nmi_scores = np.zeros((len(num_edges_ls), len(parameter_settings)))
for i in range(len(num_edges_ls)):
#number of edges
num_edges = num_edges_ls[i]
#create directory
dir_string = os.path.join(dir, str(num_edges))
if not os.path.isdir(dir_string):
os.mkdir(dir_string)
#change working directory
os.chdir(dir_string)
for j in range(len(parameter_settings)):
#setting fo e_sg
p = parameter_settings[j]
#ghsom parameters
params = {'w': 0.0001,
'eta': 0.0001,
'sigma': 1,
'e_sg': p,
'e_en': 0.8}
#create directory
dir_string_p = os.path.join(dir_string, str(p))
if not os.path.isdir(dir_string_p):
os.mkdir(dir_string_p)
#change working directory
os.chdir(dir_string_p)
if os.path.isfile('nmi_scores.csv'):
print 'already completed {}/{}, loading scores and continuing'.format(k1, p)
nmi_scores = np.genfromtxt('nmi_scores.csv', delimiter=',')
overall_nmi_scores[i,j] = np.mean(nmi_scores, axis=0)
continue
#copy executable
ex = "benchmark.exe"
if not os.path.isfile(ex):
source = "C:\\Users\\davem\\Documents\\PhD\\Benchmark Graph Generators\\binary_networks\\benchmark.exe"
copyfile(source, ex)
#record NMI scores
if not os.path.isfile('nmi_scores.pkl'):
print 'creating new nmi scores array'
nmi_scores = np.zeros(num_repeats)
else:
print 'loading nmi score progress'
nmi_scores = load_obj('nmi_scores')
#record running times
if not os.path.isfile('running_times.pkl'):
print 'creating new running time array'
running_times = np.zeros(num_repeats)
else:
print 'loading running time progress'
running_times = load_obj('running_times')
print
#generate networks
for r in range(1, num_repeats+1):
#number of communities
num_communities = np.random.randint(1,5)
#number of nodes in micro community
minc = np.floor(float(N) / num_communities)
maxc = np.ceil(float(N) / num_communities)
#average number of edges
k = float(num_edges) / N
#max number of edges
maxk = 2 * k
#make benchmark parameter file
filename = "benchmark_flags_{}_{}_{}.dat".format(num_edges,p,r)
if not os.path.isfile(filename):
print 'number of edges: {}'.format(num_edges)
print 'number of communities: {}'.format(num_communities)
print '-N {} -k {} -maxk {} -minc {} -maxc {} -mu {}'.format(N, k, maxk, minc, maxc, mu)
with open(filename,"w") as f:
f.write("-N {} -k {} -maxk {} -minc {} -maxc {} -mu {}".format(N, k, maxk, minc, maxc, mu))
print 'written flag file: {}'.format(filename)
#cmd strings
change_dir_cmd = "cd {}".format(dir_string_p)
generate_network_cmd = "benchmark -f {}".format(filename)
#output of cmd
output_file = open("cmd_output.out", 'w')
network_rename = "{}_{}".format(r,network)
first_level_rename = "{}_{}".format(r,first_level)
gml_filename = 'embedded_network_{}.gml'.format(r)
if not os.path.isfile(network_rename):
process = subprocess.Popen(change_dir_cmd + " && " + generate_network_cmd,
stdout=output_file,
stderr=output_file,
shell=True)
process.wait()
print 'generated graph {}'.format(r)
os.rename(network, network_rename)
os.rename(first_level, first_level_rename)
print 'renamed graph {}'.format(r)
if not os.path.isfile(gml_filename):
##embed graph
embed_main(network_rename, first_level_rename)
print 'embedded graph {} as {} in {}'.format(r, gml_filename, os.getcwd())
##score for this network
if not np.all(nmi_scores[r-1]):
start_time = time()
print 'starting ghsom for: {}/{}/{}'.format(num_edges, p, gml_filename)
nmi_score, communities_detected = ghsom_main(params, gml_filename, labels)
nmi_scores[r-1] = nmi_score
running_time = time() - start_time
print 'running time of algorithm: {}'.format(running_time)
running_times[r-1] = running_time
#save
save_obj(nmi_scores, 'nmi_scores')
save_obj(running_times, 'running_times')
print 'saved nmi score for network {}: {}'.format(gml_filename, nmi_score)
print
##output nmi scores to csv file
print 'writing nmi scores and running times to file'
np.savetxt('nmi_scores.csv',nmi_scores,delimiter=',')
np.savetxt('running_times.csv',running_times,delimiter=',')
print
#odd to overall list
overall_nmi_scores[i,j] = np.mean(nmi_scores, axis=0)
print 'DONE'
print 'OVERALL NMI SCORES'
print overall_nmi_scores
# In[3]:
for scores in overall_nmi_scores:
print scores
idx = np.argsort(scores)[::-1]
print parameter_settings[idx[0]]
| load_obj | identifier_name |
parameter_tests_edges.py | # coding: utf-8
# In[1]:
import os
from shutil import copyfile
import subprocess
from save_embedded_graph27 import main_binary as embed_main
from spearmint_ghsom import main as ghsom_main
import numpy as np
import pickle
from time import time
def save_obj(obj, name):
with open(name + '.pkl', 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(name):
with open(name + '.pkl', 'rb') as f:
return pickle.load(f)
#root dir
os.chdir("C:\Miniconda3\Jupyter\GHSOM_simplex_dsd")
#save directory
dir = os.path.abspath("parameter_tests_edges")
#number of times to repeat
num_repeats = 30
#number of nodes in the graph
N = 64
#make save directory
if not os.path.isdir(dir):
os.mkdir(dir)
#change to dir
os.chdir(dir)
#network file names -- output of network generator
network = "network.dat"
first_level = "community.dat"
#community labels
labels = 'firstlevelcommunity'
#mixing factors
mu = 0.1
num_edges_ls = [256, 512, 1024]
parameter_settings = [0.5, 0.6, 0.7, 0.8, 0.9, 1][::-1]
overall_nmi_scores = np.zeros((len(num_edges_ls), len(parameter_settings)))
for i in range(len(num_edges_ls)):
#number of edges
num_edges = num_edges_ls[i]
#create directory
dir_string = os.path.join(dir, str(num_edges))
if not os.path.isdir(dir_string):
os.mkdir(dir_string)
#change working directory
os.chdir(dir_string)
for j in range(len(parameter_settings)):
#setting fo e_sg
p = parameter_settings[j]
#ghsom parameters
params = {'w': 0.0001,
'eta': 0.0001,
'sigma': 1,
'e_sg': p,
'e_en': 0.8}
#create directory
dir_string_p = os.path.join(dir_string, str(p))
if not os.path.isdir(dir_string_p):
os.mkdir(dir_string_p)
#change working directory
os.chdir(dir_string_p)
if os.path.isfile('nmi_scores.csv'):
print 'already completed {}/{}, loading scores and continuing'.format(k1, p)
nmi_scores = np.genfromtxt('nmi_scores.csv', delimiter=',')
overall_nmi_scores[i,j] = np.mean(nmi_scores, axis=0)
continue
#copy executable
ex = "benchmark.exe"
if not os.path.isfile(ex):
source = "C:\\Users\\davem\\Documents\\PhD\\Benchmark Graph Generators\\binary_networks\\benchmark.exe"
copyfile(source, ex)
#record NMI scores
if not os.path.isfile('nmi_scores.pkl'):
print 'creating new nmi scores array'
nmi_scores = np.zeros(num_repeats)
else:
print 'loading nmi score progress'
nmi_scores = load_obj('nmi_scores')
#record running times
if not os.path.isfile('running_times.pkl'):
print 'creating new running time array'
running_times = np.zeros(num_repeats)
else:
print 'loading running time progress'
running_times = load_obj('running_times')
print
#generate networks
for r in range(1, num_repeats+1):
#number of communities
num_communities = np.random.randint(1,5)
#number of nodes in micro community
minc = np.floor(float(N) / num_communities)
maxc = np.ceil(float(N) / num_communities)
#average number of edges
k = float(num_edges) / N
#max number of edges
maxk = 2 * k
#make benchmark parameter file
filename = "benchmark_flags_{}_{}_{}.dat".format(num_edges,p,r)
if not os.path.isfile(filename):
print 'number of edges: {}'.format(num_edges)
print 'number of communities: {}'.format(num_communities)
print '-N {} -k {} -maxk {} -minc {} -maxc {} -mu {}'.format(N, k, maxk, minc, maxc, mu)
with open(filename,"w") as f:
f.write("-N {} -k {} -maxk {} -minc {} -maxc {} -mu {}".format(N, k, maxk, minc, maxc, mu))
print 'written flag file: {}'.format(filename)
#cmd strings
change_dir_cmd = "cd {}".format(dir_string_p)
generate_network_cmd = "benchmark -f {}".format(filename)
#output of cmd
output_file = open("cmd_output.out", 'w')
network_rename = "{}_{}".format(r,network)
first_level_rename = "{}_{}".format(r,first_level)
gml_filename = 'embedded_network_{}.gml'.format(r)
if not os.path.isfile(network_rename):
process = subprocess.Popen(change_dir_cmd + " && " + generate_network_cmd,
stdout=output_file,
stderr=output_file,
shell=True)
process.wait()
print 'generated graph {}'.format(r)
os.rename(network, network_rename)
os.rename(first_level, first_level_rename)
print 'renamed graph {}'.format(r)
if not os.path.isfile(gml_filename):
##embed graph
embed_main(network_rename, first_level_rename)
print 'embedded graph {} as {} in {}'.format(r, gml_filename, os.getcwd())
##score for this network
if not np.all(nmi_scores[r-1]):
start_time = time()
print 'starting ghsom for: {}/{}/{}'.format(num_edges, p, gml_filename)
nmi_score, communities_detected = ghsom_main(params, gml_filename, labels)
nmi_scores[r-1] = nmi_score
running_time = time() - start_time
print 'running time of algorithm: {}'.format(running_time)
running_times[r-1] = running_time
#save
save_obj(nmi_scores, 'nmi_scores')
save_obj(running_times, 'running_times')
print 'saved nmi score for network {}: {}'.format(gml_filename, nmi_score)
print
##output nmi scores to csv file
print 'writing nmi scores and running times to file'
np.savetxt('nmi_scores.csv',nmi_scores,delimiter=',')
np.savetxt('running_times.csv',running_times,delimiter=',')
print
#odd to overall list
overall_nmi_scores[i,j] = np.mean(nmi_scores, axis=0)
print 'DONE'
| print 'OVERALL NMI SCORES'
print overall_nmi_scores
# In[3]:
for scores in overall_nmi_scores:
print scores
idx = np.argsort(scores)[::-1]
print parameter_settings[idx[0]] | random_line_split | |
parameter_tests_edges.py |
# coding: utf-8
# In[1]:
import os
from shutil import copyfile
import subprocess
from save_embedded_graph27 import main_binary as embed_main
from spearmint_ghsom import main as ghsom_main
import numpy as np
import pickle
from time import time
def save_obj(obj, name):
with open(name + '.pkl', 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(name):
|
#root dir
os.chdir("C:\Miniconda3\Jupyter\GHSOM_simplex_dsd")
#save directory
dir = os.path.abspath("parameter_tests_edges")
#number of times to repeat
num_repeats = 30
#number of nodes in the graph
N = 64
#make save directory
if not os.path.isdir(dir):
os.mkdir(dir)
#change to dir
os.chdir(dir)
#network file names -- output of network generator
network = "network.dat"
first_level = "community.dat"
#community labels
labels = 'firstlevelcommunity'
#mixing factors
mu = 0.1
num_edges_ls = [256, 512, 1024]
parameter_settings = [0.5, 0.6, 0.7, 0.8, 0.9, 1][::-1]
overall_nmi_scores = np.zeros((len(num_edges_ls), len(parameter_settings)))
for i in range(len(num_edges_ls)):
#number of edges
num_edges = num_edges_ls[i]
#create directory
dir_string = os.path.join(dir, str(num_edges))
if not os.path.isdir(dir_string):
os.mkdir(dir_string)
#change working directory
os.chdir(dir_string)
for j in range(len(parameter_settings)):
#setting fo e_sg
p = parameter_settings[j]
#ghsom parameters
params = {'w': 0.0001,
'eta': 0.0001,
'sigma': 1,
'e_sg': p,
'e_en': 0.8}
#create directory
dir_string_p = os.path.join(dir_string, str(p))
if not os.path.isdir(dir_string_p):
os.mkdir(dir_string_p)
#change working directory
os.chdir(dir_string_p)
if os.path.isfile('nmi_scores.csv'):
print 'already completed {}/{}, loading scores and continuing'.format(k1, p)
nmi_scores = np.genfromtxt('nmi_scores.csv', delimiter=',')
overall_nmi_scores[i,j] = np.mean(nmi_scores, axis=0)
continue
#copy executable
ex = "benchmark.exe"
if not os.path.isfile(ex):
source = "C:\\Users\\davem\\Documents\\PhD\\Benchmark Graph Generators\\binary_networks\\benchmark.exe"
copyfile(source, ex)
#record NMI scores
if not os.path.isfile('nmi_scores.pkl'):
print 'creating new nmi scores array'
nmi_scores = np.zeros(num_repeats)
else:
print 'loading nmi score progress'
nmi_scores = load_obj('nmi_scores')
#record running times
if not os.path.isfile('running_times.pkl'):
print 'creating new running time array'
running_times = np.zeros(num_repeats)
else:
print 'loading running time progress'
running_times = load_obj('running_times')
print
#generate networks
for r in range(1, num_repeats+1):
#number of communities
num_communities = np.random.randint(1,5)
#number of nodes in micro community
minc = np.floor(float(N) / num_communities)
maxc = np.ceil(float(N) / num_communities)
#average number of edges
k = float(num_edges) / N
#max number of edges
maxk = 2 * k
#make benchmark parameter file
filename = "benchmark_flags_{}_{}_{}.dat".format(num_edges,p,r)
if not os.path.isfile(filename):
print 'number of edges: {}'.format(num_edges)
print 'number of communities: {}'.format(num_communities)
print '-N {} -k {} -maxk {} -minc {} -maxc {} -mu {}'.format(N, k, maxk, minc, maxc, mu)
with open(filename,"w") as f:
f.write("-N {} -k {} -maxk {} -minc {} -maxc {} -mu {}".format(N, k, maxk, minc, maxc, mu))
print 'written flag file: {}'.format(filename)
#cmd strings
change_dir_cmd = "cd {}".format(dir_string_p)
generate_network_cmd = "benchmark -f {}".format(filename)
#output of cmd
output_file = open("cmd_output.out", 'w')
network_rename = "{}_{}".format(r,network)
first_level_rename = "{}_{}".format(r,first_level)
gml_filename = 'embedded_network_{}.gml'.format(r)
if not os.path.isfile(network_rename):
process = subprocess.Popen(change_dir_cmd + " && " + generate_network_cmd,
stdout=output_file,
stderr=output_file,
shell=True)
process.wait()
print 'generated graph {}'.format(r)
os.rename(network, network_rename)
os.rename(first_level, first_level_rename)
print 'renamed graph {}'.format(r)
if not os.path.isfile(gml_filename):
##embed graph
embed_main(network_rename, first_level_rename)
print 'embedded graph {} as {} in {}'.format(r, gml_filename, os.getcwd())
##score for this network
if not np.all(nmi_scores[r-1]):
start_time = time()
print 'starting ghsom for: {}/{}/{}'.format(num_edges, p, gml_filename)
nmi_score, communities_detected = ghsom_main(params, gml_filename, labels)
nmi_scores[r-1] = nmi_score
running_time = time() - start_time
print 'running time of algorithm: {}'.format(running_time)
running_times[r-1] = running_time
#save
save_obj(nmi_scores, 'nmi_scores')
save_obj(running_times, 'running_times')
print 'saved nmi score for network {}: {}'.format(gml_filename, nmi_score)
print
##output nmi scores to csv file
print 'writing nmi scores and running times to file'
np.savetxt('nmi_scores.csv',nmi_scores,delimiter=',')
np.savetxt('running_times.csv',running_times,delimiter=',')
print
#odd to overall list
overall_nmi_scores[i,j] = np.mean(nmi_scores, axis=0)
print 'DONE'
print 'OVERALL NMI SCORES'
print overall_nmi_scores
# In[3]:
for scores in overall_nmi_scores:
print scores
idx = np.argsort(scores)[::-1]
print parameter_settings[idx[0]]
| with open(name + '.pkl', 'rb') as f:
return pickle.load(f) | identifier_body |
bip.py | #! /usr/bin/env python
#################################################################################################
#
# Script Name: bip.py
# Script Usage: This script is the menu system and runs everything else. Do not use other
# files unless you are comfortable with the code.
#
# It has the following:
# 1.
# 2.
# 3.
# 4.
#
# You will probably want to do the following:
# 1. Make sure the info in bip_config.py is correct.
# 2. Make sure GAM (Google Apps Manager) is installed and the path is correct.
# 3. Make sure the AD scripts in toos/ are present on the DC running run.ps1.
#
# Script Updates:
# 201709191243 - rdegennaro@sscps.org - copied boilerplate.
#
#################################################################################################
import os # os.system for clearing screen and simple gam calls
import subprocess # subprocess.Popen is to capture gam output (needed for user info in particular)
import MySQLdb # MySQLdb is to get data from relevant tables
import csv # CSV is used to read output of drive commands that supply data in CSV form
| varMySQLPassword = bip_config.mysqlconfig['password']
varMySQLDB = bip_config.mysqlconfig['db']
# setup to find GAM
varCommandGam = bip_config.gamconfig['fullpath']
#################################################################################################
#
################################################################################################# | import bip_config # declare installation specific variables
# setup for MySQLdb connection
varMySQLHost = bip_config.mysqlconfig['host']
varMySQLUser = bip_config.mysqlconfig['user'] | random_line_split |
setup.py | """
Setup Module
This module is used to make a distribution of
the game using distutils.
"""
from distutils.core import setup
setup(
name = 'Breakout',
version = '1.0',
description = 'A remake of the classic video game',
author = 'Derek Morey',
author_email = 'dman6505@gmail.com',
license = 'GPL',
url = 'https://github.com/Oisota/Breakout',
download_url = 'https://github.com/Oisota/Breakout/archive/master.zip',
keywords = ['breakout', 'arcade', 'game', 'pygame', 'python',],
platforms = ['linux', 'windows'],
scripts = ['breakout.py','breakout-editor.py'],
packages = ['breakout','breakout.game','breakout.utils','breakout.editor'],
package_data = {'breakout':['assets/images/*.gif',
'assets/images/*.png',
'assets/sounds/*.wav',
'assets/levels/*.json']},
requires = ['sys', 'os', 'random', 'tkinter', 'pygame', 'json'],
classifiers = ['Programming Language :: Python',
'Programming Language :: Python :: 3',
'Development Status :: 4 - Beta',
'Environment :: Other Environment',
'Framework :: Pygame', | 'Intended Audience :: Education',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Topic :: Games/Entertainment',
'Topic :: Games/Entertainment :: Arcade'],
long_description =
"""
Breakout
--------
This is a remake of the classic game Breakout. I made this game for the sole
purpose of educating myself about python, pygame, and game development in general.
Feel free to use or modify my code in any way.
"""
) | 'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers', | random_line_split |
testSegment.py | # -*- coding: utf8 -*-
###########################################################################
# This is part of the module phystricks
#
# phystricks 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.
#
# phystricks 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 phystricks.py. If not, see <http://www.gnu.org/licenses/>.
###########################################################################
# copyright (c) Laurent Claessens, 2017
# email: laurent@claessens-donadello.eu
from __future__ import division
from phystricks import *
from Testing import assert_true
from Testing import assert_false
from Testing import assert_equal
from Testing import assert_almost_equal
from Testing import echo_function
from Testing import echo_single_test
from Testing import SilentOutput
def test_almost_equal():
echo_function("test_almost_equal")
s= Segment(Point(1,1),Point(2,2))
v=s.get_normal_vector()
assert_equal(v.I,Point(1.5,1.5))
assert_almost_equal(v.length,1,epsilon=0.001)
assert_almost_equal(v.F,Point(1/2*sqrt(2) + 1.5,-1/2*sqrt(2) + 1.5),epsilon=0.001)
def | ():
echo_single_test("Usual constructor")
seg=Segment( Point(0,0),Point(2,10) )
assert_equal(seg.I,Point(0,0))
assert_equal(seg.F,Point(2,10))
echo_single_test("Construct with a vector")
seg=Segment( Point(-3,4),vector=Vector(1,2) )
assert_equal(seg.I,Point(-3,4))
assert_equal(seg.F,Point(-2,6))
echo_single_test("Construct with an affine vector")
v=AffineVector( Point(1,2),Point(-2,5) )
seg=Segment( Point(-3,4),vector=v )
assert_equal(seg.I,Point(-3,4))
assert_equal(seg.F,Point(-6,7))
def testSegment():
test_constructors()
test_almost_equal()
| test_constructors | identifier_name |
testSegment.py | # -*- coding: utf8 -*-
###########################################################################
# This is part of the module phystricks
#
# phystricks 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.
#
# phystricks 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 phystricks.py. If not, see <http://www.gnu.org/licenses/>.
###########################################################################
# copyright (c) Laurent Claessens, 2017
# email: laurent@claessens-donadello.eu
from __future__ import division
from phystricks import *
from Testing import assert_true
from Testing import assert_false
from Testing import assert_equal
from Testing import assert_almost_equal
from Testing import echo_function
from Testing import echo_single_test
from Testing import SilentOutput
def test_almost_equal():
echo_function("test_almost_equal")
s= Segment(Point(1,1),Point(2,2))
v=s.get_normal_vector()
assert_equal(v.I,Point(1.5,1.5))
assert_almost_equal(v.length,1,epsilon=0.001)
assert_almost_equal(v.F,Point(1/2*sqrt(2) + 1.5,-1/2*sqrt(2) + 1.5),epsilon=0.001)
def test_constructors():
echo_single_test("Usual constructor")
seg=Segment( Point(0,0),Point(2,10) )
assert_equal(seg.I,Point(0,0))
assert_equal(seg.F,Point(2,10))
echo_single_test("Construct with a vector")
seg=Segment( Point(-3,4),vector=Vector(1,2) )
assert_equal(seg.I,Point(-3,4))
assert_equal(seg.F,Point(-2,6))
echo_single_test("Construct with an affine vector")
v=AffineVector( Point(1,2),Point(-2,5) )
seg=Segment( Point(-3,4),vector=v )
assert_equal(seg.I,Point(-3,4))
assert_equal(seg.F,Point(-6,7))
def testSegment():
| test_constructors()
test_almost_equal() | identifier_body | |
testSegment.py | # -*- coding: utf8 -*-
###########################################################################
# This is part of the module phystricks
#
# phystricks 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.
#
# phystricks 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 phystricks.py. If not, see <http://www.gnu.org/licenses/>.
###########################################################################
# copyright (c) Laurent Claessens, 2017
# email: laurent@claessens-donadello.eu
from __future__ import division
from phystricks import *
from Testing import assert_true
from Testing import assert_false
from Testing import assert_equal
from Testing import assert_almost_equal
from Testing import echo_function
from Testing import echo_single_test
from Testing import SilentOutput
def test_almost_equal():
echo_function("test_almost_equal")
s= Segment(Point(1,1),Point(2,2))
v=s.get_normal_vector()
assert_equal(v.I,Point(1.5,1.5))
assert_almost_equal(v.length,1,epsilon=0.001) | def test_constructors():
echo_single_test("Usual constructor")
seg=Segment( Point(0,0),Point(2,10) )
assert_equal(seg.I,Point(0,0))
assert_equal(seg.F,Point(2,10))
echo_single_test("Construct with a vector")
seg=Segment( Point(-3,4),vector=Vector(1,2) )
assert_equal(seg.I,Point(-3,4))
assert_equal(seg.F,Point(-2,6))
echo_single_test("Construct with an affine vector")
v=AffineVector( Point(1,2),Point(-2,5) )
seg=Segment( Point(-3,4),vector=v )
assert_equal(seg.I,Point(-3,4))
assert_equal(seg.F,Point(-6,7))
def testSegment():
test_constructors()
test_almost_equal() | assert_almost_equal(v.F,Point(1/2*sqrt(2) + 1.5,-1/2*sqrt(2) + 1.5),epsilon=0.001)
| random_line_split |
graph.js | // @flow
// connection types
export type Edge<T> = {
node: T,
cursor: string
}
export type PageInfo = {
hasNextPage: boolean
}
export type Connection<T> = {
edges: Array<Edge<T>>,
pageInfo: PageInfo
}
export type SearchConnection<T> = {
count: number
} & Connection<T>
// data types
export type Chamber
= 'LOWER'
| 'UPPER'
export type Committee = {
name: string,
chamber: Chamber
}
export type Hearing = {
id: string,
date: string,
committee: Committee
}
export type StepActor
= 'LOWER'
| 'LOWER_COMMITTEE'
| 'UPPER'
| 'UPPER_COMMITTEE'
| 'GOVERNOR'
export type StepAction
= 'INTRODUCED'
| 'RESOLVED' | | 'FAILED'
| 'SIGNED'
| 'VETOED'
| 'VETOED_LINE'
| 'NONE'
export type Step = {
actor: StepActor,
action: StepAction,
resolution: StepResolution,
date: string
}
export type Document = {
id: string,
number: string,
fullTextUrl: string,
slipUrl: string,
slipResultsUrl: string
}
export type Bill = {
id: string,
documentNumber: string,
title: string,
summary: string,
sponsorName: string,
detailsUrl: string,
witnessSlipUrl: string,
witnessSlipResultUrl: string,
steps: Array<Step>,
hearing: ?Hearing,
document: Document,
updatedAt: string
}
export type SearchParamsSubset
= 'SLIPS'
| 'LOWER'
| 'UPPER'
| 'GOVERNOR'
export type SearchParams = {
query?: string,
subset?: SearchParamsSubset
}
export type Viewer = {
isAdmin: boolean,
bill: Bill,
bills: SearchConnection<Bill>
} |
export type StepResolution
= 'PASSED' | random_line_split |
npm-installation-manager.ts | import * as path from "path";
import * as semver from "semver";
import * as npm from "npm";
import * as constants from "./constants";
import {sleep} from "../lib/common/helpers";
export class NpmInstallationManager implements INpmInstallationManager {
private static NPM_LOAD_FAILED = "Failed to retrieve data from npm. Please try again a little bit later.";
private versionsCache: IDictionary<string[]>;
private packageSpecificDirectories: IStringDictionary = {
"tns-android": constants.PROJECT_FRAMEWORK_FOLDER_NAME,
"tns-ios": constants.PROJECT_FRAMEWORK_FOLDER_NAME,
"tns-ios-inspector": "WebInspectorUI",
"tns-template-hello-world": constants.APP_RESOURCES_FOLDER_NAME,
"tns-template-hello-world-ts": constants.APP_RESOURCES_FOLDER_NAME,
"tns-template-hello-world-ng": constants.APP_RESOURCES_FOLDER_NAME
};
constructor(private $npm: INodePackageManager,
private $logger: ILogger,
private $lockfile: ILockFile,
private $errors: IErrors,
private $options: IOptions,
private $fs: IFileSystem,
private $staticConfig: IStaticConfig) {
this.versionsCache = {};
this.$npm.load().wait();
}
public getCacheRootPath(): string {
return this.$npm.getCache();
}
public getCachedPackagePath(packageName: string, version: string): string {
return path.join(this.getCacheRootPath(), packageName, version, "package");
}
public addToCache(packageName: string, version: string): IFuture<any> {
return (() => {
let cachedPackagePath = this.getCachedPackagePath(packageName, version);
let cachedPackageData: any;
if(!this.$fs.exists(cachedPackagePath).wait() || !this.$fs.exists(path.join(cachedPackagePath, "framework")).wait()) {
cachedPackageData = this.addToCacheCore(packageName, version).wait();
}
// In case the version is tag (for example `next`), we need the real version number from the cache.
// In these cases the cachePackageData is populated when data is added to the cache.
// Also whenever the version is tag, we always get inside the above `if` and the cachedPackageData is populated.
let realVersion = (cachedPackageData && cachedPackageData.version) || version;
if(!this.isShasumOfPackageCorrect(packageName, realVersion).wait()) {
// In some cases the package is not fully downloaded and there are missing directories
// Try removing the old package and add the real one to cache again
cachedPackageData = this.addCleanCopyToCache(packageName, version).wait();
}
return cachedPackageData;
}).future<any>()();
}
public cacheUnpack(packageName: string, version: string, unpackTarget?: string): IFuture<void> {
unpackTarget = unpackTarget || path.join(npm.cache, packageName, version, "package");
return this.$npm.cacheUnpack(packageName, version, unpackTarget);
}
public getLatestVersion(packageName: string): IFuture<string> {
return (() => {
let data = this.$npm.view(packageName, "dist-tags").wait();
// data is something like :
// { '1.0.1': { 'dist-tags': { latest: '1.0.1', next: '1.0.2-2016-02-25-181', next1: '1.0.2' } }
// There's only one key and it's always the @latest tag.
let latestVersion = _.first(_.keys(data));
this.$logger.trace("Using version %s. ", latestVersion);
return latestVersion;
}).future<string>()();
}
public getLatestCompatibleVersion(packageName: string): IFuture<string> {
return (() => {
let cliVersionRange = `~${this.$staticConfig.version}`;
let latestVersion = this.getLatestVersion(packageName).wait();
if(semver.satisfies(latestVersion, cliVersionRange)) {
return latestVersion;
}
let data: any = this.$npm.view(packageName, "versions").wait();
/* data is something like:
{
"1.1.0":{
"versions":[
"1.0.0",
"1.0.1-2016-02-25-181",
"1.0.1",
"1.0.2-2016-02-25-182",
"1.0.2",
"1.1.0-2016-02-25-183",
"1.1.0",
"1.2.0-2016-02-25-184"
]
}
}
*/
let versions: string[] = data && data[latestVersion] && data[latestVersion].versions;
return semver.maxSatisfying(versions, cliVersionRange) || latestVersion;
}).future<string>()();
}
public install(packageName: string, opts?: INpmInstallOptions): IFuture<string> {
return (() => {
while(this.$lockfile.check().wait()) {
sleep(10);
}
this.$lockfile.lock().wait();
try {
let packageToInstall = packageName;
let pathToSave = (opts && opts.pathToSave) || npm.cache;
let version = (opts && opts.version) || null;
return this.installCore(packageToInstall, pathToSave, version).wait();
} catch(error) {
this.$logger.debug(error);
this.$errors.fail("%s. Error: %s", NpmInstallationManager.NPM_LOAD_FAILED, error);
} finally {
this.$lockfile.unlock().wait();
}
}).future<string>()();
}
private addCleanCopyToCache(packageName: string, version: string): IFuture<any> {
return (() => {
let packagePath = path.join(this.getCacheRootPath(), packageName, version);
this.$logger.trace(`Deleting: ${packagePath}.`);
this.$fs.deleteDirectory(packagePath).wait();
let cachedPackageData = this.addToCacheCore(packageName, version).wait();
if(!this.isShasumOfPackageCorrect(packageName, cachedPackageData.version).wait()) {
this.$errors.failWithoutHelp(`Unable to add package ${packageName} with version ${cachedPackageData.version} to npm cache. Try cleaning your cache and execute the command again.`);
}
return cachedPackageData;
}).future<any>()();
}
private | (packageName: string, version: string): IFuture<any> {
return (() => {
let cachedPackageData = this.$npm.cache(packageName, version).wait();
let packagePath = path.join(this.getCacheRootPath(), packageName, cachedPackageData.version, "package");
if(!this.isPackageUnpacked(packagePath, packageName).wait()) {
this.cacheUnpack(packageName, cachedPackageData.version).wait();
}
return cachedPackageData;
}).future<any>()();
}
private isShasumOfPackageCorrect(packageName: string, version: string): IFuture<boolean> {
return ((): boolean => {
let shasumProperty = "dist.shasum";
let cachedPackagePath = this.getCachedPackagePath(packageName, version);
let packageInfo = this.$npm.view(`${packageName}@${version}`, shasumProperty).wait();
if (_.isEmpty(packageInfo)) {
// this package has not been published to npmjs.org yet - perhaps manually added via --framework-path
this.$logger.trace(`Checking shasum of package ${packageName}@${version}: skipped because the package was not found in npmjs.org`);
return true;
}
let realShasum = packageInfo[version][shasumProperty];
let packageTgz = cachedPackagePath + ".tgz";
let currentShasum = "";
if(this.$fs.exists(packageTgz).wait()) {
currentShasum = this.$fs.getFileShasum(packageTgz).wait();
}
this.$logger.trace(`Checking shasum of package ${packageName}@${version}: expected ${realShasum}, actual ${currentShasum}.`);
return realShasum === currentShasum;
}).future<boolean>()();
}
private installCore(packageName: string, pathToSave: string, version: string): IFuture<string> {
return (() => {
if (this.$options.frameworkPath) {
this.npmInstall(this.$options.frameworkPath, pathToSave, version).wait();
let pathToNodeModules = path.join(pathToSave, "node_modules");
let folders = this.$fs.readDirectory(pathToNodeModules).wait();
let data = this.$fs.readJson(path.join(pathToNodeModules, folders[0], "package.json")).wait();
if(!this.isPackageUnpacked(this.getCachedPackagePath(data.name, data.version), data.name).wait()) {
this.cacheUnpack(data.name, data.version).wait();
}
return path.join(pathToNodeModules, folders[0]);
} else {
version = version || this.getLatestCompatibleVersion(packageName).wait();
let cachedData = this.addToCache(packageName, version).wait();
let packageVersion = (cachedData && cachedData.version) || version;
return this.getCachedPackagePath(packageName, packageVersion);
}
}).future<string>()();
}
private npmInstall(packageName: string, pathToSave: string, version: string): IFuture<void> {
this.$logger.out("Installing ", packageName);
let incrementedVersion = semver.inc(version, constants.ReleaseType.MINOR);
if (!this.$options.frameworkPath && packageName.indexOf("@") < 0) {
packageName = packageName + "@<" + incrementedVersion;
}
return this.$npm.install(packageName, pathToSave);
}
private isPackageUnpacked(packagePath: string, packageName: string): IFuture<boolean> {
return (() => {
let additionalDirectoryToCheck = this.packageSpecificDirectories[packageName];
return this.$fs.getFsStats(packagePath).wait().isDirectory() &&
(!additionalDirectoryToCheck || this.hasFilesInDirectory(path.join(packagePath, additionalDirectoryToCheck)).wait());
}).future<boolean>()();
}
private hasFilesInDirectory(directory: string): IFuture<boolean> {
return ((): boolean => {
return this.$fs.exists(directory).wait() && this.$fs.enumerateFilesInDirectorySync(directory).length > 0;
}).future<boolean>()();
}
}
$injector.register("npmInstallationManager", NpmInstallationManager);
| addToCacheCore | identifier_name |
npm-installation-manager.ts | import * as path from "path";
import * as semver from "semver";
import * as npm from "npm";
import * as constants from "./constants";
import {sleep} from "../lib/common/helpers";
export class NpmInstallationManager implements INpmInstallationManager {
private static NPM_LOAD_FAILED = "Failed to retrieve data from npm. Please try again a little bit later.";
private versionsCache: IDictionary<string[]>;
private packageSpecificDirectories: IStringDictionary = {
"tns-android": constants.PROJECT_FRAMEWORK_FOLDER_NAME,
"tns-ios": constants.PROJECT_FRAMEWORK_FOLDER_NAME,
"tns-ios-inspector": "WebInspectorUI",
"tns-template-hello-world": constants.APP_RESOURCES_FOLDER_NAME,
"tns-template-hello-world-ts": constants.APP_RESOURCES_FOLDER_NAME,
"tns-template-hello-world-ng": constants.APP_RESOURCES_FOLDER_NAME
};
constructor(private $npm: INodePackageManager,
private $logger: ILogger,
private $lockfile: ILockFile,
private $errors: IErrors,
private $options: IOptions,
private $fs: IFileSystem,
private $staticConfig: IStaticConfig) {
this.versionsCache = {};
this.$npm.load().wait();
}
public getCacheRootPath(): string {
return this.$npm.getCache();
}
public getCachedPackagePath(packageName: string, version: string): string {
return path.join(this.getCacheRootPath(), packageName, version, "package");
}
public addToCache(packageName: string, version: string): IFuture<any> {
return (() => {
let cachedPackagePath = this.getCachedPackagePath(packageName, version);
let cachedPackageData: any;
if(!this.$fs.exists(cachedPackagePath).wait() || !this.$fs.exists(path.join(cachedPackagePath, "framework")).wait()) {
cachedPackageData = this.addToCacheCore(packageName, version).wait();
}
// In case the version is tag (for example `next`), we need the real version number from the cache.
// In these cases the cachePackageData is populated when data is added to the cache.
// Also whenever the version is tag, we always get inside the above `if` and the cachedPackageData is populated.
let realVersion = (cachedPackageData && cachedPackageData.version) || version;
if(!this.isShasumOfPackageCorrect(packageName, realVersion).wait()) {
// In some cases the package is not fully downloaded and there are missing directories
// Try removing the old package and add the real one to cache again
cachedPackageData = this.addCleanCopyToCache(packageName, version).wait();
}
return cachedPackageData;
}).future<any>()();
}
public cacheUnpack(packageName: string, version: string, unpackTarget?: string): IFuture<void> {
unpackTarget = unpackTarget || path.join(npm.cache, packageName, version, "package");
return this.$npm.cacheUnpack(packageName, version, unpackTarget);
}
public getLatestVersion(packageName: string): IFuture<string> {
return (() => {
let data = this.$npm.view(packageName, "dist-tags").wait();
// data is something like :
// { '1.0.1': { 'dist-tags': { latest: '1.0.1', next: '1.0.2-2016-02-25-181', next1: '1.0.2' } }
// There's only one key and it's always the @latest tag.
let latestVersion = _.first(_.keys(data));
this.$logger.trace("Using version %s. ", latestVersion);
return latestVersion;
}).future<string>()();
}
public getLatestCompatibleVersion(packageName: string): IFuture<string> {
return (() => {
let cliVersionRange = `~${this.$staticConfig.version}`;
let latestVersion = this.getLatestVersion(packageName).wait();
if(semver.satisfies(latestVersion, cliVersionRange)) {
return latestVersion;
}
let data: any = this.$npm.view(packageName, "versions").wait();
/* data is something like:
{
"1.1.0":{
"versions":[
"1.0.0",
"1.0.1-2016-02-25-181",
"1.0.1",
"1.0.2-2016-02-25-182",
"1.0.2",
"1.1.0-2016-02-25-183",
"1.1.0",
"1.2.0-2016-02-25-184"
]
}
}
*/
let versions: string[] = data && data[latestVersion] && data[latestVersion].versions;
return semver.maxSatisfying(versions, cliVersionRange) || latestVersion;
}).future<string>()();
}
public install(packageName: string, opts?: INpmInstallOptions): IFuture<string> {
return (() => {
while(this.$lockfile.check().wait()) {
sleep(10);
}
this.$lockfile.lock().wait();
try {
let packageToInstall = packageName;
let pathToSave = (opts && opts.pathToSave) || npm.cache;
let version = (opts && opts.version) || null;
return this.installCore(packageToInstall, pathToSave, version).wait();
} catch(error) {
this.$logger.debug(error);
this.$errors.fail("%s. Error: %s", NpmInstallationManager.NPM_LOAD_FAILED, error);
} finally {
this.$lockfile.unlock().wait();
}
}).future<string>()();
}
private addCleanCopyToCache(packageName: string, version: string): IFuture<any> {
return (() => {
let packagePath = path.join(this.getCacheRootPath(), packageName, version);
this.$logger.trace(`Deleting: ${packagePath}.`);
this.$fs.deleteDirectory(packagePath).wait();
let cachedPackageData = this.addToCacheCore(packageName, version).wait();
if(!this.isShasumOfPackageCorrect(packageName, cachedPackageData.version).wait()) {
this.$errors.failWithoutHelp(`Unable to add package ${packageName} with version ${cachedPackageData.version} to npm cache. Try cleaning your cache and execute the command again.`);
}
return cachedPackageData;
}).future<any>()();
}
private addToCacheCore(packageName: string, version: string): IFuture<any> {
return (() => {
let cachedPackageData = this.$npm.cache(packageName, version).wait();
let packagePath = path.join(this.getCacheRootPath(), packageName, cachedPackageData.version, "package");
if(!this.isPackageUnpacked(packagePath, packageName).wait()) {
this.cacheUnpack(packageName, cachedPackageData.version).wait();
}
return cachedPackageData;
}).future<any>()();
}
private isShasumOfPackageCorrect(packageName: string, version: string): IFuture<boolean> {
return ((): boolean => {
let shasumProperty = "dist.shasum";
let cachedPackagePath = this.getCachedPackagePath(packageName, version);
let packageInfo = this.$npm.view(`${packageName}@${version}`, shasumProperty).wait();
if (_.isEmpty(packageInfo)) {
// this package has not been published to npmjs.org yet - perhaps manually added via --framework-path
this.$logger.trace(`Checking shasum of package ${packageName}@${version}: skipped because the package was not found in npmjs.org`);
return true;
}
let realShasum = packageInfo[version][shasumProperty];
let packageTgz = cachedPackagePath + ".tgz";
let currentShasum = "";
if(this.$fs.exists(packageTgz).wait()) {
currentShasum = this.$fs.getFileShasum(packageTgz).wait();
}
this.$logger.trace(`Checking shasum of package ${packageName}@${version}: expected ${realShasum}, actual ${currentShasum}.`);
return realShasum === currentShasum;
}).future<boolean>()();
}
private installCore(packageName: string, pathToSave: string, version: string): IFuture<string> {
return (() => {
if (this.$options.frameworkPath) {
this.npmInstall(this.$options.frameworkPath, pathToSave, version).wait();
let pathToNodeModules = path.join(pathToSave, "node_modules");
let folders = this.$fs.readDirectory(pathToNodeModules).wait();
let data = this.$fs.readJson(path.join(pathToNodeModules, folders[0], "package.json")).wait();
if(!this.isPackageUnpacked(this.getCachedPackagePath(data.name, data.version), data.name).wait()) {
this.cacheUnpack(data.name, data.version).wait();
}
return path.join(pathToNodeModules, folders[0]);
} else {
version = version || this.getLatestCompatibleVersion(packageName).wait();
let cachedData = this.addToCache(packageName, version).wait();
let packageVersion = (cachedData && cachedData.version) || version;
return this.getCachedPackagePath(packageName, packageVersion);
}
}).future<string>()();
}
private npmInstall(packageName: string, pathToSave: string, version: string): IFuture<void> {
this.$logger.out("Installing ", packageName);
let incrementedVersion = semver.inc(version, constants.ReleaseType.MINOR);
if (!this.$options.frameworkPath && packageName.indexOf("@") < 0) {
packageName = packageName + "@<" + incrementedVersion;
}
return this.$npm.install(packageName, pathToSave);
}
private isPackageUnpacked(packagePath: string, packageName: string): IFuture<boolean> {
return (() => {
let additionalDirectoryToCheck = this.packageSpecificDirectories[packageName];
return this.$fs.getFsStats(packagePath).wait().isDirectory() &&
(!additionalDirectoryToCheck || this.hasFilesInDirectory(path.join(packagePath, additionalDirectoryToCheck)).wait());
}).future<boolean>()();
}
| private hasFilesInDirectory(directory: string): IFuture<boolean> {
return ((): boolean => {
return this.$fs.exists(directory).wait() && this.$fs.enumerateFilesInDirectorySync(directory).length > 0;
}).future<boolean>()();
}
}
$injector.register("npmInstallationManager", NpmInstallationManager); | random_line_split | |
npm-installation-manager.ts | import * as path from "path";
import * as semver from "semver";
import * as npm from "npm";
import * as constants from "./constants";
import {sleep} from "../lib/common/helpers";
export class NpmInstallationManager implements INpmInstallationManager {
private static NPM_LOAD_FAILED = "Failed to retrieve data from npm. Please try again a little bit later.";
private versionsCache: IDictionary<string[]>;
private packageSpecificDirectories: IStringDictionary = {
"tns-android": constants.PROJECT_FRAMEWORK_FOLDER_NAME,
"tns-ios": constants.PROJECT_FRAMEWORK_FOLDER_NAME,
"tns-ios-inspector": "WebInspectorUI",
"tns-template-hello-world": constants.APP_RESOURCES_FOLDER_NAME,
"tns-template-hello-world-ts": constants.APP_RESOURCES_FOLDER_NAME,
"tns-template-hello-world-ng": constants.APP_RESOURCES_FOLDER_NAME
};
constructor(private $npm: INodePackageManager,
private $logger: ILogger,
private $lockfile: ILockFile,
private $errors: IErrors,
private $options: IOptions,
private $fs: IFileSystem,
private $staticConfig: IStaticConfig) {
this.versionsCache = {};
this.$npm.load().wait();
}
public getCacheRootPath(): string {
return this.$npm.getCache();
}
public getCachedPackagePath(packageName: string, version: string): string {
return path.join(this.getCacheRootPath(), packageName, version, "package");
}
public addToCache(packageName: string, version: string): IFuture<any> {
return (() => {
let cachedPackagePath = this.getCachedPackagePath(packageName, version);
let cachedPackageData: any;
if(!this.$fs.exists(cachedPackagePath).wait() || !this.$fs.exists(path.join(cachedPackagePath, "framework")).wait()) {
cachedPackageData = this.addToCacheCore(packageName, version).wait();
}
// In case the version is tag (for example `next`), we need the real version number from the cache.
// In these cases the cachePackageData is populated when data is added to the cache.
// Also whenever the version is tag, we always get inside the above `if` and the cachedPackageData is populated.
let realVersion = (cachedPackageData && cachedPackageData.version) || version;
if(!this.isShasumOfPackageCorrect(packageName, realVersion).wait()) {
// In some cases the package is not fully downloaded and there are missing directories
// Try removing the old package and add the real one to cache again
cachedPackageData = this.addCleanCopyToCache(packageName, version).wait();
}
return cachedPackageData;
}).future<any>()();
}
public cacheUnpack(packageName: string, version: string, unpackTarget?: string): IFuture<void> {
unpackTarget = unpackTarget || path.join(npm.cache, packageName, version, "package");
return this.$npm.cacheUnpack(packageName, version, unpackTarget);
}
public getLatestVersion(packageName: string): IFuture<string> {
return (() => {
let data = this.$npm.view(packageName, "dist-tags").wait();
// data is something like :
// { '1.0.1': { 'dist-tags': { latest: '1.0.1', next: '1.0.2-2016-02-25-181', next1: '1.0.2' } }
// There's only one key and it's always the @latest tag.
let latestVersion = _.first(_.keys(data));
this.$logger.trace("Using version %s. ", latestVersion);
return latestVersion;
}).future<string>()();
}
public getLatestCompatibleVersion(packageName: string): IFuture<string> |
public install(packageName: string, opts?: INpmInstallOptions): IFuture<string> {
return (() => {
while(this.$lockfile.check().wait()) {
sleep(10);
}
this.$lockfile.lock().wait();
try {
let packageToInstall = packageName;
let pathToSave = (opts && opts.pathToSave) || npm.cache;
let version = (opts && opts.version) || null;
return this.installCore(packageToInstall, pathToSave, version).wait();
} catch(error) {
this.$logger.debug(error);
this.$errors.fail("%s. Error: %s", NpmInstallationManager.NPM_LOAD_FAILED, error);
} finally {
this.$lockfile.unlock().wait();
}
}).future<string>()();
}
private addCleanCopyToCache(packageName: string, version: string): IFuture<any> {
return (() => {
let packagePath = path.join(this.getCacheRootPath(), packageName, version);
this.$logger.trace(`Deleting: ${packagePath}.`);
this.$fs.deleteDirectory(packagePath).wait();
let cachedPackageData = this.addToCacheCore(packageName, version).wait();
if(!this.isShasumOfPackageCorrect(packageName, cachedPackageData.version).wait()) {
this.$errors.failWithoutHelp(`Unable to add package ${packageName} with version ${cachedPackageData.version} to npm cache. Try cleaning your cache and execute the command again.`);
}
return cachedPackageData;
}).future<any>()();
}
private addToCacheCore(packageName: string, version: string): IFuture<any> {
return (() => {
let cachedPackageData = this.$npm.cache(packageName, version).wait();
let packagePath = path.join(this.getCacheRootPath(), packageName, cachedPackageData.version, "package");
if(!this.isPackageUnpacked(packagePath, packageName).wait()) {
this.cacheUnpack(packageName, cachedPackageData.version).wait();
}
return cachedPackageData;
}).future<any>()();
}
private isShasumOfPackageCorrect(packageName: string, version: string): IFuture<boolean> {
return ((): boolean => {
let shasumProperty = "dist.shasum";
let cachedPackagePath = this.getCachedPackagePath(packageName, version);
let packageInfo = this.$npm.view(`${packageName}@${version}`, shasumProperty).wait();
if (_.isEmpty(packageInfo)) {
// this package has not been published to npmjs.org yet - perhaps manually added via --framework-path
this.$logger.trace(`Checking shasum of package ${packageName}@${version}: skipped because the package was not found in npmjs.org`);
return true;
}
let realShasum = packageInfo[version][shasumProperty];
let packageTgz = cachedPackagePath + ".tgz";
let currentShasum = "";
if(this.$fs.exists(packageTgz).wait()) {
currentShasum = this.$fs.getFileShasum(packageTgz).wait();
}
this.$logger.trace(`Checking shasum of package ${packageName}@${version}: expected ${realShasum}, actual ${currentShasum}.`);
return realShasum === currentShasum;
}).future<boolean>()();
}
private installCore(packageName: string, pathToSave: string, version: string): IFuture<string> {
return (() => {
if (this.$options.frameworkPath) {
this.npmInstall(this.$options.frameworkPath, pathToSave, version).wait();
let pathToNodeModules = path.join(pathToSave, "node_modules");
let folders = this.$fs.readDirectory(pathToNodeModules).wait();
let data = this.$fs.readJson(path.join(pathToNodeModules, folders[0], "package.json")).wait();
if(!this.isPackageUnpacked(this.getCachedPackagePath(data.name, data.version), data.name).wait()) {
this.cacheUnpack(data.name, data.version).wait();
}
return path.join(pathToNodeModules, folders[0]);
} else {
version = version || this.getLatestCompatibleVersion(packageName).wait();
let cachedData = this.addToCache(packageName, version).wait();
let packageVersion = (cachedData && cachedData.version) || version;
return this.getCachedPackagePath(packageName, packageVersion);
}
}).future<string>()();
}
private npmInstall(packageName: string, pathToSave: string, version: string): IFuture<void> {
this.$logger.out("Installing ", packageName);
let incrementedVersion = semver.inc(version, constants.ReleaseType.MINOR);
if (!this.$options.frameworkPath && packageName.indexOf("@") < 0) {
packageName = packageName + "@<" + incrementedVersion;
}
return this.$npm.install(packageName, pathToSave);
}
private isPackageUnpacked(packagePath: string, packageName: string): IFuture<boolean> {
return (() => {
let additionalDirectoryToCheck = this.packageSpecificDirectories[packageName];
return this.$fs.getFsStats(packagePath).wait().isDirectory() &&
(!additionalDirectoryToCheck || this.hasFilesInDirectory(path.join(packagePath, additionalDirectoryToCheck)).wait());
}).future<boolean>()();
}
private hasFilesInDirectory(directory: string): IFuture<boolean> {
return ((): boolean => {
return this.$fs.exists(directory).wait() && this.$fs.enumerateFilesInDirectorySync(directory).length > 0;
}).future<boolean>()();
}
}
$injector.register("npmInstallationManager", NpmInstallationManager);
| {
return (() => {
let cliVersionRange = `~${this.$staticConfig.version}`;
let latestVersion = this.getLatestVersion(packageName).wait();
if(semver.satisfies(latestVersion, cliVersionRange)) {
return latestVersion;
}
let data: any = this.$npm.view(packageName, "versions").wait();
/* data is something like:
{
"1.1.0":{
"versions":[
"1.0.0",
"1.0.1-2016-02-25-181",
"1.0.1",
"1.0.2-2016-02-25-182",
"1.0.2",
"1.1.0-2016-02-25-183",
"1.1.0",
"1.2.0-2016-02-25-184"
]
}
}
*/
let versions: string[] = data && data[latestVersion] && data[latestVersion].versions;
return semver.maxSatisfying(versions, cliVersionRange) || latestVersion;
}).future<string>()();
} | identifier_body |
npm-installation-manager.ts | import * as path from "path";
import * as semver from "semver";
import * as npm from "npm";
import * as constants from "./constants";
import {sleep} from "../lib/common/helpers";
export class NpmInstallationManager implements INpmInstallationManager {
private static NPM_LOAD_FAILED = "Failed to retrieve data from npm. Please try again a little bit later.";
private versionsCache: IDictionary<string[]>;
private packageSpecificDirectories: IStringDictionary = {
"tns-android": constants.PROJECT_FRAMEWORK_FOLDER_NAME,
"tns-ios": constants.PROJECT_FRAMEWORK_FOLDER_NAME,
"tns-ios-inspector": "WebInspectorUI",
"tns-template-hello-world": constants.APP_RESOURCES_FOLDER_NAME,
"tns-template-hello-world-ts": constants.APP_RESOURCES_FOLDER_NAME,
"tns-template-hello-world-ng": constants.APP_RESOURCES_FOLDER_NAME
};
constructor(private $npm: INodePackageManager,
private $logger: ILogger,
private $lockfile: ILockFile,
private $errors: IErrors,
private $options: IOptions,
private $fs: IFileSystem,
private $staticConfig: IStaticConfig) {
this.versionsCache = {};
this.$npm.load().wait();
}
public getCacheRootPath(): string {
return this.$npm.getCache();
}
public getCachedPackagePath(packageName: string, version: string): string {
return path.join(this.getCacheRootPath(), packageName, version, "package");
}
public addToCache(packageName: string, version: string): IFuture<any> {
return (() => {
let cachedPackagePath = this.getCachedPackagePath(packageName, version);
let cachedPackageData: any;
if(!this.$fs.exists(cachedPackagePath).wait() || !this.$fs.exists(path.join(cachedPackagePath, "framework")).wait()) {
cachedPackageData = this.addToCacheCore(packageName, version).wait();
}
// In case the version is tag (for example `next`), we need the real version number from the cache.
// In these cases the cachePackageData is populated when data is added to the cache.
// Also whenever the version is tag, we always get inside the above `if` and the cachedPackageData is populated.
let realVersion = (cachedPackageData && cachedPackageData.version) || version;
if(!this.isShasumOfPackageCorrect(packageName, realVersion).wait()) {
// In some cases the package is not fully downloaded and there are missing directories
// Try removing the old package and add the real one to cache again
cachedPackageData = this.addCleanCopyToCache(packageName, version).wait();
}
return cachedPackageData;
}).future<any>()();
}
public cacheUnpack(packageName: string, version: string, unpackTarget?: string): IFuture<void> {
unpackTarget = unpackTarget || path.join(npm.cache, packageName, version, "package");
return this.$npm.cacheUnpack(packageName, version, unpackTarget);
}
public getLatestVersion(packageName: string): IFuture<string> {
return (() => {
let data = this.$npm.view(packageName, "dist-tags").wait();
// data is something like :
// { '1.0.1': { 'dist-tags': { latest: '1.0.1', next: '1.0.2-2016-02-25-181', next1: '1.0.2' } }
// There's only one key and it's always the @latest tag.
let latestVersion = _.first(_.keys(data));
this.$logger.trace("Using version %s. ", latestVersion);
return latestVersion;
}).future<string>()();
}
public getLatestCompatibleVersion(packageName: string): IFuture<string> {
return (() => {
let cliVersionRange = `~${this.$staticConfig.version}`;
let latestVersion = this.getLatestVersion(packageName).wait();
if(semver.satisfies(latestVersion, cliVersionRange)) |
let data: any = this.$npm.view(packageName, "versions").wait();
/* data is something like:
{
"1.1.0":{
"versions":[
"1.0.0",
"1.0.1-2016-02-25-181",
"1.0.1",
"1.0.2-2016-02-25-182",
"1.0.2",
"1.1.0-2016-02-25-183",
"1.1.0",
"1.2.0-2016-02-25-184"
]
}
}
*/
let versions: string[] = data && data[latestVersion] && data[latestVersion].versions;
return semver.maxSatisfying(versions, cliVersionRange) || latestVersion;
}).future<string>()();
}
public install(packageName: string, opts?: INpmInstallOptions): IFuture<string> {
return (() => {
while(this.$lockfile.check().wait()) {
sleep(10);
}
this.$lockfile.lock().wait();
try {
let packageToInstall = packageName;
let pathToSave = (opts && opts.pathToSave) || npm.cache;
let version = (opts && opts.version) || null;
return this.installCore(packageToInstall, pathToSave, version).wait();
} catch(error) {
this.$logger.debug(error);
this.$errors.fail("%s. Error: %s", NpmInstallationManager.NPM_LOAD_FAILED, error);
} finally {
this.$lockfile.unlock().wait();
}
}).future<string>()();
}
private addCleanCopyToCache(packageName: string, version: string): IFuture<any> {
return (() => {
let packagePath = path.join(this.getCacheRootPath(), packageName, version);
this.$logger.trace(`Deleting: ${packagePath}.`);
this.$fs.deleteDirectory(packagePath).wait();
let cachedPackageData = this.addToCacheCore(packageName, version).wait();
if(!this.isShasumOfPackageCorrect(packageName, cachedPackageData.version).wait()) {
this.$errors.failWithoutHelp(`Unable to add package ${packageName} with version ${cachedPackageData.version} to npm cache. Try cleaning your cache and execute the command again.`);
}
return cachedPackageData;
}).future<any>()();
}
private addToCacheCore(packageName: string, version: string): IFuture<any> {
return (() => {
let cachedPackageData = this.$npm.cache(packageName, version).wait();
let packagePath = path.join(this.getCacheRootPath(), packageName, cachedPackageData.version, "package");
if(!this.isPackageUnpacked(packagePath, packageName).wait()) {
this.cacheUnpack(packageName, cachedPackageData.version).wait();
}
return cachedPackageData;
}).future<any>()();
}
private isShasumOfPackageCorrect(packageName: string, version: string): IFuture<boolean> {
return ((): boolean => {
let shasumProperty = "dist.shasum";
let cachedPackagePath = this.getCachedPackagePath(packageName, version);
let packageInfo = this.$npm.view(`${packageName}@${version}`, shasumProperty).wait();
if (_.isEmpty(packageInfo)) {
// this package has not been published to npmjs.org yet - perhaps manually added via --framework-path
this.$logger.trace(`Checking shasum of package ${packageName}@${version}: skipped because the package was not found in npmjs.org`);
return true;
}
let realShasum = packageInfo[version][shasumProperty];
let packageTgz = cachedPackagePath + ".tgz";
let currentShasum = "";
if(this.$fs.exists(packageTgz).wait()) {
currentShasum = this.$fs.getFileShasum(packageTgz).wait();
}
this.$logger.trace(`Checking shasum of package ${packageName}@${version}: expected ${realShasum}, actual ${currentShasum}.`);
return realShasum === currentShasum;
}).future<boolean>()();
}
private installCore(packageName: string, pathToSave: string, version: string): IFuture<string> {
return (() => {
if (this.$options.frameworkPath) {
this.npmInstall(this.$options.frameworkPath, pathToSave, version).wait();
let pathToNodeModules = path.join(pathToSave, "node_modules");
let folders = this.$fs.readDirectory(pathToNodeModules).wait();
let data = this.$fs.readJson(path.join(pathToNodeModules, folders[0], "package.json")).wait();
if(!this.isPackageUnpacked(this.getCachedPackagePath(data.name, data.version), data.name).wait()) {
this.cacheUnpack(data.name, data.version).wait();
}
return path.join(pathToNodeModules, folders[0]);
} else {
version = version || this.getLatestCompatibleVersion(packageName).wait();
let cachedData = this.addToCache(packageName, version).wait();
let packageVersion = (cachedData && cachedData.version) || version;
return this.getCachedPackagePath(packageName, packageVersion);
}
}).future<string>()();
}
private npmInstall(packageName: string, pathToSave: string, version: string): IFuture<void> {
this.$logger.out("Installing ", packageName);
let incrementedVersion = semver.inc(version, constants.ReleaseType.MINOR);
if (!this.$options.frameworkPath && packageName.indexOf("@") < 0) {
packageName = packageName + "@<" + incrementedVersion;
}
return this.$npm.install(packageName, pathToSave);
}
private isPackageUnpacked(packagePath: string, packageName: string): IFuture<boolean> {
return (() => {
let additionalDirectoryToCheck = this.packageSpecificDirectories[packageName];
return this.$fs.getFsStats(packagePath).wait().isDirectory() &&
(!additionalDirectoryToCheck || this.hasFilesInDirectory(path.join(packagePath, additionalDirectoryToCheck)).wait());
}).future<boolean>()();
}
private hasFilesInDirectory(directory: string): IFuture<boolean> {
return ((): boolean => {
return this.$fs.exists(directory).wait() && this.$fs.enumerateFilesInDirectorySync(directory).length > 0;
}).future<boolean>()();
}
}
$injector.register("npmInstallationManager", NpmInstallationManager);
| {
return latestVersion;
} | conditional_block |
app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 09:53:39 2018
@author: mayank
"""
from forms import SignupForm
from flask import Flask, request, render_template
from flask_login import LoginManager, login_user, login_required, logout_user
app = Flask(__name__)
app.secret_key = 'gMALVWEuxBSxQ44bomDOsWniejrPbhDV'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db/database.sqlite'
login_manager = LoginManager()
login_manager.init_app(app)
@app.route('/')
def index():
return "Welcome to Home Page"
@app.route('/signup', methods=['GET', 'POST'])
def signup():
form = SignupForm()
if request.method == 'GET':
return render_template('signup.html', form=form)
elif request.method == 'POST':
if form.validate_on_submit():
if User.query.filter_by(email=form.email.data).first():
return "!!! Email address already exists !!!"
newuser = User(form.email.data, form.password.data)
db.session.add(newuser)
db.session.flush()
db.session.commit()
login_user(newuser)
return "User created!!!"
else:
return "Form didn't validate"
@login_manager.user_loader
def load_user(email):
return User.query.filter_by(email=email).first()
@app.route('/login', methods=['GET', 'POST'])
def login():
form = SignupForm()
if request.method == 'GET':
return render_template('login.html', form=form)
elif request.method == 'POST' and form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and user.password == form.password.data:
login_user(user)
return "User logged in"
return "<h1>Wrong username or password</h1>"
return "form not validated or invalid request"
@app.route("/logout")
@login_required
def logout():
logout_user()
return "Logged out"
@app.route('/protected')
@login_required
def protected():
return "protected area"
def init_db():
db.init_app(app)
db.app = app
db.create_all()
| init_db()
app.run(port=5000, host='localhost') |
if __name__ == '__main__':
from models import db, User | random_line_split |
app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 09:53:39 2018
@author: mayank
"""
from forms import SignupForm
from flask import Flask, request, render_template
from flask_login import LoginManager, login_user, login_required, logout_user
app = Flask(__name__)
app.secret_key = 'gMALVWEuxBSxQ44bomDOsWniejrPbhDV'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db/database.sqlite'
login_manager = LoginManager()
login_manager.init_app(app)
@app.route('/')
def index():
return "Welcome to Home Page"
@app.route('/signup', methods=['GET', 'POST'])
def signup():
form = SignupForm()
if request.method == 'GET':
return render_template('signup.html', form=form)
elif request.method == 'POST':
if form.validate_on_submit():
if User.query.filter_by(email=form.email.data).first():
return "!!! Email address already exists !!!"
newuser = User(form.email.data, form.password.data)
db.session.add(newuser)
db.session.flush()
db.session.commit()
login_user(newuser)
return "User created!!!"
else:
return "Form didn't validate"
@login_manager.user_loader
def load_user(email):
return User.query.filter_by(email=email).first()
@app.route('/login', methods=['GET', 'POST'])
def login():
form = SignupForm()
if request.method == 'GET':
return render_template('login.html', form=form)
elif request.method == 'POST' and form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and user.password == form.password.data:
login_user(user)
return "User logged in"
return "<h1>Wrong username or password</h1>"
return "form not validated or invalid request"
@app.route("/logout")
@login_required
def logout():
|
@app.route('/protected')
@login_required
def protected():
return "protected area"
def init_db():
db.init_app(app)
db.app = app
db.create_all()
if __name__ == '__main__':
from models import db, User
init_db()
app.run(port=5000, host='localhost')
| logout_user()
return "Logged out" | identifier_body |
app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 09:53:39 2018
@author: mayank
"""
from forms import SignupForm
from flask import Flask, request, render_template
from flask_login import LoginManager, login_user, login_required, logout_user
app = Flask(__name__)
app.secret_key = 'gMALVWEuxBSxQ44bomDOsWniejrPbhDV'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db/database.sqlite'
login_manager = LoginManager()
login_manager.init_app(app)
@app.route('/')
def | ():
return "Welcome to Home Page"
@app.route('/signup', methods=['GET', 'POST'])
def signup():
form = SignupForm()
if request.method == 'GET':
return render_template('signup.html', form=form)
elif request.method == 'POST':
if form.validate_on_submit():
if User.query.filter_by(email=form.email.data).first():
return "!!! Email address already exists !!!"
newuser = User(form.email.data, form.password.data)
db.session.add(newuser)
db.session.flush()
db.session.commit()
login_user(newuser)
return "User created!!!"
else:
return "Form didn't validate"
@login_manager.user_loader
def load_user(email):
return User.query.filter_by(email=email).first()
@app.route('/login', methods=['GET', 'POST'])
def login():
form = SignupForm()
if request.method == 'GET':
return render_template('login.html', form=form)
elif request.method == 'POST' and form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and user.password == form.password.data:
login_user(user)
return "User logged in"
return "<h1>Wrong username or password</h1>"
return "form not validated or invalid request"
@app.route("/logout")
@login_required
def logout():
logout_user()
return "Logged out"
@app.route('/protected')
@login_required
def protected():
return "protected area"
def init_db():
db.init_app(app)
db.app = app
db.create_all()
if __name__ == '__main__':
from models import db, User
init_db()
app.run(port=5000, host='localhost')
| index | identifier_name |
app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 09:53:39 2018
@author: mayank
"""
from forms import SignupForm
from flask import Flask, request, render_template
from flask_login import LoginManager, login_user, login_required, logout_user
app = Flask(__name__)
app.secret_key = 'gMALVWEuxBSxQ44bomDOsWniejrPbhDV'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db/database.sqlite'
login_manager = LoginManager()
login_manager.init_app(app)
@app.route('/')
def index():
return "Welcome to Home Page"
@app.route('/signup', methods=['GET', 'POST'])
def signup():
form = SignupForm()
if request.method == 'GET':
return render_template('signup.html', form=form)
elif request.method == 'POST':
if form.validate_on_submit():
if User.query.filter_by(email=form.email.data).first():
return "!!! Email address already exists !!!"
newuser = User(form.email.data, form.password.data)
db.session.add(newuser)
db.session.flush()
db.session.commit()
login_user(newuser)
return "User created!!!"
else:
|
@login_manager.user_loader
def load_user(email):
return User.query.filter_by(email=email).first()
@app.route('/login', methods=['GET', 'POST'])
def login():
form = SignupForm()
if request.method == 'GET':
return render_template('login.html', form=form)
elif request.method == 'POST' and form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and user.password == form.password.data:
login_user(user)
return "User logged in"
return "<h1>Wrong username or password</h1>"
return "form not validated or invalid request"
@app.route("/logout")
@login_required
def logout():
logout_user()
return "Logged out"
@app.route('/protected')
@login_required
def protected():
return "protected area"
def init_db():
db.init_app(app)
db.app = app
db.create_all()
if __name__ == '__main__':
from models import db, User
init_db()
app.run(port=5000, host='localhost')
| return "Form didn't validate" | conditional_block |
css-hint-server.js | /*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* 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.
*/
define(['external/lodash/lodash.min',
'webida-lib/util/path',
'plugins/webida.editor.code-editor/content-assist/file-server',
'plugins/webida.editor.code-editor/content-assist/reference'],
function (_, pathUtil, fileServer, reference) {
'use strict';
var csshint = {};
function findCompletions(body) |
/**
* @param {files: [{name, type, text}], query: {type: string, end:{line,ch}, file: string}} body
* @returns {from: {line, ch}, to: {line, ch}, list: [string]}
**/
csshint.request = function (serverId, body, c) {
_.each(body.files, function (file) {
if (file.type === 'full') {
fileServer.setText(file.name, file.text);
file.type = null;
}
});
body.files = _.filter(body.files, function (file) {
return file.type !== null;
});
var result = {};
if (body.query.type === 'completions') {
result = findCompletions(body);
}
c(undefined, result);
};
return csshint;
});
| {
var result = {};
var token = body.query.token;
if (token) {
if ((token.type === 'tag' || token.type === 'qualifier') && /^\./.test(token.string)) {
token.type = 'class';
token.start = token.start + 1;
token.string = token.string.substr(1);
} else if (token.type === 'builtin' && /^#/.test(token.string)) {
token.type = 'id';
token.start = token.start + 1;
token.string = token.string.substr(1);
}
if (token.type === 'id' || token.type === 'class') {
var htmls = reference.getReferenceFroms(body.query.file);
if (pathUtil.isHtml(body.query.file)) {
htmls = _.union(htmls, [body.query.file]);
}
_.each(htmls, function (htmlpath) {
var html = fileServer.getLocalFile(htmlpath);
if (html) {
if (token.type === 'id') {
result.list = _.union(result, html.getHtmlIds());
} else if (token.type === 'class') {
result.list = _.union(result, html.getHtmlClasses());
}
}
});
if (result.list) {
result.to = body.query.end;
result.from = {
line: body.query.end.line,
ch: body.query.end.ch - token.string.length
};
}
}
}
return result;
} | identifier_body |
css-hint-server.js | /*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* 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.
*/
define(['external/lodash/lodash.min',
'webida-lib/util/path',
'plugins/webida.editor.code-editor/content-assist/file-server',
'plugins/webida.editor.code-editor/content-assist/reference'],
function (_, pathUtil, fileServer, reference) {
'use strict';
var csshint = {};
function | (body) {
var result = {};
var token = body.query.token;
if (token) {
if ((token.type === 'tag' || token.type === 'qualifier') && /^\./.test(token.string)) {
token.type = 'class';
token.start = token.start + 1;
token.string = token.string.substr(1);
} else if (token.type === 'builtin' && /^#/.test(token.string)) {
token.type = 'id';
token.start = token.start + 1;
token.string = token.string.substr(1);
}
if (token.type === 'id' || token.type === 'class') {
var htmls = reference.getReferenceFroms(body.query.file);
if (pathUtil.isHtml(body.query.file)) {
htmls = _.union(htmls, [body.query.file]);
}
_.each(htmls, function (htmlpath) {
var html = fileServer.getLocalFile(htmlpath);
if (html) {
if (token.type === 'id') {
result.list = _.union(result, html.getHtmlIds());
} else if (token.type === 'class') {
result.list = _.union(result, html.getHtmlClasses());
}
}
});
if (result.list) {
result.to = body.query.end;
result.from = {
line: body.query.end.line,
ch: body.query.end.ch - token.string.length
};
}
}
}
return result;
}
/**
* @param {files: [{name, type, text}], query: {type: string, end:{line,ch}, file: string}} body
* @returns {from: {line, ch}, to: {line, ch}, list: [string]}
**/
csshint.request = function (serverId, body, c) {
_.each(body.files, function (file) {
if (file.type === 'full') {
fileServer.setText(file.name, file.text);
file.type = null;
}
});
body.files = _.filter(body.files, function (file) {
return file.type !== null;
});
var result = {};
if (body.query.type === 'completions') {
result = findCompletions(body);
}
c(undefined, result);
};
return csshint;
});
| findCompletions | identifier_name |
css-hint-server.js | /*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* 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.
*/
define(['external/lodash/lodash.min',
'webida-lib/util/path',
'plugins/webida.editor.code-editor/content-assist/file-server',
'plugins/webida.editor.code-editor/content-assist/reference'],
function (_, pathUtil, fileServer, reference) {
'use strict';
var csshint = {};
function findCompletions(body) {
var result = {};
var token = body.query.token;
if (token) {
if ((token.type === 'tag' || token.type === 'qualifier') && /^\./.test(token.string)) {
token.type = 'class';
token.start = token.start + 1;
token.string = token.string.substr(1);
} else if (token.type === 'builtin' && /^#/.test(token.string)) {
token.type = 'id';
token.start = token.start + 1;
token.string = token.string.substr(1);
}
if (token.type === 'id' || token.type === 'class') {
var htmls = reference.getReferenceFroms(body.query.file);
if (pathUtil.isHtml(body.query.file)) {
htmls = _.union(htmls, [body.query.file]);
}
_.each(htmls, function (htmlpath) {
var html = fileServer.getLocalFile(htmlpath);
if (html) {
if (token.type === 'id') {
result.list = _.union(result, html.getHtmlIds());
} else if (token.type === 'class') {
result.list = _.union(result, html.getHtmlClasses());
}
}
});
if (result.list) {
result.to = body.query.end;
result.from = {
line: body.query.end.line,
ch: body.query.end.ch - token.string.length
};
}
}
}
return result;
}
/**
* @param {files: [{name, type, text}], query: {type: string, end:{line,ch}, file: string}} body
* @returns {from: {line, ch}, to: {line, ch}, list: [string]} | fileServer.setText(file.name, file.text);
file.type = null;
}
});
body.files = _.filter(body.files, function (file) {
return file.type !== null;
});
var result = {};
if (body.query.type === 'completions') {
result = findCompletions(body);
}
c(undefined, result);
};
return csshint;
}); | **/
csshint.request = function (serverId, body, c) {
_.each(body.files, function (file) {
if (file.type === 'full') { | random_line_split |
css-hint-server.js | /*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* 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.
*/
define(['external/lodash/lodash.min',
'webida-lib/util/path',
'plugins/webida.editor.code-editor/content-assist/file-server',
'plugins/webida.editor.code-editor/content-assist/reference'],
function (_, pathUtil, fileServer, reference) {
'use strict';
var csshint = {};
function findCompletions(body) {
var result = {};
var token = body.query.token;
if (token) {
if ((token.type === 'tag' || token.type === 'qualifier') && /^\./.test(token.string)) {
token.type = 'class';
token.start = token.start + 1;
token.string = token.string.substr(1);
} else if (token.type === 'builtin' && /^#/.test(token.string)) {
token.type = 'id';
token.start = token.start + 1;
token.string = token.string.substr(1);
}
if (token.type === 'id' || token.type === 'class') {
var htmls = reference.getReferenceFroms(body.query.file);
if (pathUtil.isHtml(body.query.file)) |
_.each(htmls, function (htmlpath) {
var html = fileServer.getLocalFile(htmlpath);
if (html) {
if (token.type === 'id') {
result.list = _.union(result, html.getHtmlIds());
} else if (token.type === 'class') {
result.list = _.union(result, html.getHtmlClasses());
}
}
});
if (result.list) {
result.to = body.query.end;
result.from = {
line: body.query.end.line,
ch: body.query.end.ch - token.string.length
};
}
}
}
return result;
}
/**
* @param {files: [{name, type, text}], query: {type: string, end:{line,ch}, file: string}} body
* @returns {from: {line, ch}, to: {line, ch}, list: [string]}
**/
csshint.request = function (serverId, body, c) {
_.each(body.files, function (file) {
if (file.type === 'full') {
fileServer.setText(file.name, file.text);
file.type = null;
}
});
body.files = _.filter(body.files, function (file) {
return file.type !== null;
});
var result = {};
if (body.query.type === 'completions') {
result = findCompletions(body);
}
c(undefined, result);
};
return csshint;
});
| {
htmls = _.union(htmls, [body.query.file]);
} | conditional_block |
TakeoutDiningOutlined.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
}); | exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m7.79 18-.51-7h9.46l-.51 7H7.79zM9.83 5h4.33l2.8 2.73L16.87 9H7.12l-.09-1.27L9.83 5zM22 7.46l-1.41-1.41L19 7.63l.03-.56L14.98 3H9.02L4.97 7.07l.03.5-1.59-1.56L2 7.44l3.23 3.11.7 9.45h12.14l.7-9.44L22 7.46z"
}), 'TakeoutDiningOutlined');
exports.default = _default; | random_line_split | |
p2p_fingerprint.py | #!/usr/bin/env python3
# Copyright (c) 2017-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test various fingerprinting protections.
If a stale block more than a month old or its header are requested by a peer,
the node should pretend that it does not have it to avoid fingerprinting.
"""
import time
from test_framework.blocktools import (create_block, create_coinbase)
from test_framework.messages import CInv
from test_framework.mininode import (
P2PInterface,
msg_headers,
msg_block,
msg_getdata,
msg_getheaders,
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
wait_until,
)
class P2PFingerprintTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
# Build a chain of blocks on top of given one
def build_chain(self, nblocks, prev_hash, prev_height, prev_median_time):
blocks = []
for _ in range(nblocks):
coinbase = create_coinbase(prev_height + 1)
block_time = prev_median_time + 1
block = create_block(int(prev_hash, 16), coinbase, block_time)
block.solve()
blocks.append(block)
prev_hash = block.hash
prev_height += 1
prev_median_time = block_time
return blocks
# Send a getdata request for a given block hash
def send_block_request(self, block_hash, node):
msg = msg_getdata()
msg.inv.append(CInv(2, block_hash)) # 2 == "Block"
node.send_message(msg)
# Send a getheaders request for a given single block hash
def send_header_request(self, block_hash, node):
msg = msg_getheaders()
msg.hashstop = block_hash
node.send_message(msg)
# Check whether last block received from node has a given hash
def last_block_equals(self, expected_hash, node):
block_msg = node.last_message.get("block")
return block_msg and block_msg.block.rehash() == expected_hash
# Check whether last block header received from node has a given hash
def last_header_equals(self, expected_hash, node):
headers_msg = node.last_message.get("headers")
return (headers_msg and
headers_msg.headers and
headers_msg.headers[0].rehash() == expected_hash)
# Checks that stale blocks timestamped more than a month ago are not served
# by the node while recent stale blocks and old active chain blocks are.
# This does not currently test that stale blocks timestamped within the
# last month but that have over a month's worth of work are also withheld.
def run_test(self):
|
if __name__ == '__main__':
P2PFingerprintTest().main()
| node0 = self.nodes[0].add_p2p_connection(P2PInterface())
# Set node time to 60 days ago
self.nodes[0].setmocktime(int(time.time()) - 60 * 24 * 60 * 60)
# Generating a chain of 10 blocks
block_hashes = self.nodes[0].generate(nblocks=10)
# Create longer chain starting 2 blocks before current tip
height = len(block_hashes) - 2
block_hash = block_hashes[height - 1]
block_time = self.nodes[0].getblockheader(block_hash)["mediantime"] + 1
new_blocks = self.build_chain(5, block_hash, height, block_time)
# Force reorg to a longer chain
node0.send_message(msg_headers(new_blocks))
node0.wait_for_getdata()
for block in new_blocks:
node0.send_and_ping(msg_block(block))
# Check that reorg succeeded
assert_equal(self.nodes[0].getblockcount(), 13)
stale_hash = int(block_hashes[-1], 16)
# Check that getdata request for stale block succeeds
self.send_block_request(stale_hash, node0)
test_function = lambda: self.last_block_equals(stale_hash, node0)
wait_until(test_function, timeout=3)
# Check that getheader request for stale block header succeeds
self.send_header_request(stale_hash, node0)
test_function = lambda: self.last_header_equals(stale_hash, node0)
wait_until(test_function, timeout=3)
# Longest chain is extended so stale is much older than chain tip
self.nodes[0].setmocktime(0)
tip = self.nodes[0].generate(nblocks=1)[0]
assert_equal(self.nodes[0].getblockcount(), 14)
# Send getdata & getheaders to refresh last received getheader message
block_hash = int(tip, 16)
self.send_block_request(block_hash, node0)
self.send_header_request(block_hash, node0)
node0.sync_with_ping()
# Request for very old stale block should now fail
self.send_block_request(stale_hash, node0)
time.sleep(3)
assert not self.last_block_equals(stale_hash, node0)
# Request for very old stale block header should now fail
self.send_header_request(stale_hash, node0)
time.sleep(3)
assert not self.last_header_equals(stale_hash, node0)
# Verify we can fetch very old blocks and headers on the active chain
block_hash = int(block_hashes[2], 16)
self.send_block_request(block_hash, node0)
self.send_header_request(block_hash, node0)
node0.sync_with_ping()
self.send_block_request(block_hash, node0)
test_function = lambda: self.last_block_equals(block_hash, node0)
wait_until(test_function, timeout=3)
self.send_header_request(block_hash, node0)
test_function = lambda: self.last_header_equals(block_hash, node0)
wait_until(test_function, timeout=3) | identifier_body |
p2p_fingerprint.py | #!/usr/bin/env python3
# Copyright (c) 2017-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test various fingerprinting protections.
If a stale block more than a month old or its header are requested by a peer,
the node should pretend that it does not have it to avoid fingerprinting.
"""
import time
from test_framework.blocktools import (create_block, create_coinbase)
from test_framework.messages import CInv
from test_framework.mininode import (
P2PInterface,
msg_headers,
msg_block,
msg_getdata,
msg_getheaders,
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
wait_until,
)
class P2PFingerprintTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
# Build a chain of blocks on top of given one
def build_chain(self, nblocks, prev_hash, prev_height, prev_median_time):
blocks = []
for _ in range(nblocks):
coinbase = create_coinbase(prev_height + 1)
block_time = prev_median_time + 1
block = create_block(int(prev_hash, 16), coinbase, block_time)
block.solve()
blocks.append(block)
prev_hash = block.hash
prev_height += 1
prev_median_time = block_time
return blocks
# Send a getdata request for a given block hash
def send_block_request(self, block_hash, node):
msg = msg_getdata()
msg.inv.append(CInv(2, block_hash)) # 2 == "Block"
node.send_message(msg)
# Send a getheaders request for a given single block hash
def send_header_request(self, block_hash, node):
msg = msg_getheaders()
msg.hashstop = block_hash
node.send_message(msg)
# Check whether last block received from node has a given hash
def last_block_equals(self, expected_hash, node):
block_msg = node.last_message.get("block")
return block_msg and block_msg.block.rehash() == expected_hash
# Check whether last block header received from node has a given hash
def last_header_equals(self, expected_hash, node):
headers_msg = node.last_message.get("headers")
return (headers_msg and
headers_msg.headers and
headers_msg.headers[0].rehash() == expected_hash)
# Checks that stale blocks timestamped more than a month ago are not served
# by the node while recent stale blocks and old active chain blocks are.
# This does not currently test that stale blocks timestamped within the
# last month but that have over a month's worth of work are also withheld.
def run_test(self):
node0 = self.nodes[0].add_p2p_connection(P2PInterface())
# Set node time to 60 days ago
self.nodes[0].setmocktime(int(time.time()) - 60 * 24 * 60 * 60)
# Generating a chain of 10 blocks
block_hashes = self.nodes[0].generate(nblocks=10)
# Create longer chain starting 2 blocks before current tip
height = len(block_hashes) - 2
block_hash = block_hashes[height - 1]
block_time = self.nodes[0].getblockheader(block_hash)["mediantime"] + 1
new_blocks = self.build_chain(5, block_hash, height, block_time)
# Force reorg to a longer chain
node0.send_message(msg_headers(new_blocks))
node0.wait_for_getdata()
for block in new_blocks:
node0.send_and_ping(msg_block(block))
# Check that reorg succeeded
assert_equal(self.nodes[0].getblockcount(), 13)
stale_hash = int(block_hashes[-1], 16)
# Check that getdata request for stale block succeeds
self.send_block_request(stale_hash, node0)
test_function = lambda: self.last_block_equals(stale_hash, node0)
wait_until(test_function, timeout=3)
# Check that getheader request for stale block header succeeds
self.send_header_request(stale_hash, node0)
test_function = lambda: self.last_header_equals(stale_hash, node0)
wait_until(test_function, timeout=3)
# Longest chain is extended so stale is much older than chain tip
self.nodes[0].setmocktime(0)
tip = self.nodes[0].generate(nblocks=1)[0]
assert_equal(self.nodes[0].getblockcount(), 14)
# Send getdata & getheaders to refresh last received getheader message
block_hash = int(tip, 16)
self.send_block_request(block_hash, node0)
self.send_header_request(block_hash, node0)
node0.sync_with_ping()
# Request for very old stale block should now fail
self.send_block_request(stale_hash, node0)
time.sleep(3)
assert not self.last_block_equals(stale_hash, node0)
# Request for very old stale block header should now fail
self.send_header_request(stale_hash, node0)
time.sleep(3)
assert not self.last_header_equals(stale_hash, node0)
# Verify we can fetch very old blocks and headers on the active chain
block_hash = int(block_hashes[2], 16)
self.send_block_request(block_hash, node0)
self.send_header_request(block_hash, node0)
node0.sync_with_ping()
self.send_block_request(block_hash, node0)
test_function = lambda: self.last_block_equals(block_hash, node0)
wait_until(test_function, timeout=3)
self.send_header_request(block_hash, node0)
test_function = lambda: self.last_header_equals(block_hash, node0)
wait_until(test_function, timeout=3)
if __name__ == '__main__':
| P2PFingerprintTest().main() | conditional_block | |
p2p_fingerprint.py | #!/usr/bin/env python3
# Copyright (c) 2017-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test various fingerprinting protections.
If a stale block more than a month old or its header are requested by a peer,
the node should pretend that it does not have it to avoid fingerprinting.
"""
import time
from test_framework.blocktools import (create_block, create_coinbase)
from test_framework.messages import CInv
from test_framework.mininode import (
P2PInterface,
msg_headers,
msg_block,
msg_getdata,
msg_getheaders,
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
wait_until,
)
class P2PFingerprintTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
# Build a chain of blocks on top of given one
def build_chain(self, nblocks, prev_hash, prev_height, prev_median_time):
blocks = []
for _ in range(nblocks):
coinbase = create_coinbase(prev_height + 1)
block_time = prev_median_time + 1
block = create_block(int(prev_hash, 16), coinbase, block_time)
block.solve()
blocks.append(block)
prev_hash = block.hash
prev_height += 1
prev_median_time = block_time
return blocks
# Send a getdata request for a given block hash
def send_block_request(self, block_hash, node):
msg = msg_getdata()
msg.inv.append(CInv(2, block_hash)) # 2 == "Block"
node.send_message(msg)
# Send a getheaders request for a given single block hash
def send_header_request(self, block_hash, node):
msg = msg_getheaders()
msg.hashstop = block_hash
node.send_message(msg)
# Check whether last block received from node has a given hash
def last_block_equals(self, expected_hash, node):
block_msg = node.last_message.get("block")
return block_msg and block_msg.block.rehash() == expected_hash
# Check whether last block header received from node has a given hash
def last_header_equals(self, expected_hash, node):
headers_msg = node.last_message.get("headers")
return (headers_msg and
headers_msg.headers and
headers_msg.headers[0].rehash() == expected_hash)
# Checks that stale blocks timestamped more than a month ago are not served
# by the node while recent stale blocks and old active chain blocks are.
# This does not currently test that stale blocks timestamped within the
# last month but that have over a month's worth of work are also withheld.
def run_test(self):
node0 = self.nodes[0].add_p2p_connection(P2PInterface())
# Set node time to 60 days ago
self.nodes[0].setmocktime(int(time.time()) - 60 * 24 * 60 * 60)
# Generating a chain of 10 blocks
block_hashes = self.nodes[0].generate(nblocks=10)
# Create longer chain starting 2 blocks before current tip
height = len(block_hashes) - 2
block_hash = block_hashes[height - 1]
block_time = self.nodes[0].getblockheader(block_hash)["mediantime"] + 1
new_blocks = self.build_chain(5, block_hash, height, block_time)
# Force reorg to a longer chain | node0.send_message(msg_headers(new_blocks))
node0.wait_for_getdata()
for block in new_blocks:
node0.send_and_ping(msg_block(block))
# Check that reorg succeeded
assert_equal(self.nodes[0].getblockcount(), 13)
stale_hash = int(block_hashes[-1], 16)
# Check that getdata request for stale block succeeds
self.send_block_request(stale_hash, node0)
test_function = lambda: self.last_block_equals(stale_hash, node0)
wait_until(test_function, timeout=3)
# Check that getheader request for stale block header succeeds
self.send_header_request(stale_hash, node0)
test_function = lambda: self.last_header_equals(stale_hash, node0)
wait_until(test_function, timeout=3)
# Longest chain is extended so stale is much older than chain tip
self.nodes[0].setmocktime(0)
tip = self.nodes[0].generate(nblocks=1)[0]
assert_equal(self.nodes[0].getblockcount(), 14)
# Send getdata & getheaders to refresh last received getheader message
block_hash = int(tip, 16)
self.send_block_request(block_hash, node0)
self.send_header_request(block_hash, node0)
node0.sync_with_ping()
# Request for very old stale block should now fail
self.send_block_request(stale_hash, node0)
time.sleep(3)
assert not self.last_block_equals(stale_hash, node0)
# Request for very old stale block header should now fail
self.send_header_request(stale_hash, node0)
time.sleep(3)
assert not self.last_header_equals(stale_hash, node0)
# Verify we can fetch very old blocks and headers on the active chain
block_hash = int(block_hashes[2], 16)
self.send_block_request(block_hash, node0)
self.send_header_request(block_hash, node0)
node0.sync_with_ping()
self.send_block_request(block_hash, node0)
test_function = lambda: self.last_block_equals(block_hash, node0)
wait_until(test_function, timeout=3)
self.send_header_request(block_hash, node0)
test_function = lambda: self.last_header_equals(block_hash, node0)
wait_until(test_function, timeout=3)
if __name__ == '__main__':
P2PFingerprintTest().main() | random_line_split | |
p2p_fingerprint.py | #!/usr/bin/env python3
# Copyright (c) 2017-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test various fingerprinting protections.
If a stale block more than a month old or its header are requested by a peer,
the node should pretend that it does not have it to avoid fingerprinting.
"""
import time
from test_framework.blocktools import (create_block, create_coinbase)
from test_framework.messages import CInv
from test_framework.mininode import (
P2PInterface,
msg_headers,
msg_block,
msg_getdata,
msg_getheaders,
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
wait_until,
)
class P2PFingerprintTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
# Build a chain of blocks on top of given one
def build_chain(self, nblocks, prev_hash, prev_height, prev_median_time):
blocks = []
for _ in range(nblocks):
coinbase = create_coinbase(prev_height + 1)
block_time = prev_median_time + 1
block = create_block(int(prev_hash, 16), coinbase, block_time)
block.solve()
blocks.append(block)
prev_hash = block.hash
prev_height += 1
prev_median_time = block_time
return blocks
# Send a getdata request for a given block hash
def send_block_request(self, block_hash, node):
msg = msg_getdata()
msg.inv.append(CInv(2, block_hash)) # 2 == "Block"
node.send_message(msg)
# Send a getheaders request for a given single block hash
def send_header_request(self, block_hash, node):
msg = msg_getheaders()
msg.hashstop = block_hash
node.send_message(msg)
# Check whether last block received from node has a given hash
def last_block_equals(self, expected_hash, node):
block_msg = node.last_message.get("block")
return block_msg and block_msg.block.rehash() == expected_hash
# Check whether last block header received from node has a given hash
def last_header_equals(self, expected_hash, node):
headers_msg = node.last_message.get("headers")
return (headers_msg and
headers_msg.headers and
headers_msg.headers[0].rehash() == expected_hash)
# Checks that stale blocks timestamped more than a month ago are not served
# by the node while recent stale blocks and old active chain blocks are.
# This does not currently test that stale blocks timestamped within the
# last month but that have over a month's worth of work are also withheld.
def | (self):
node0 = self.nodes[0].add_p2p_connection(P2PInterface())
# Set node time to 60 days ago
self.nodes[0].setmocktime(int(time.time()) - 60 * 24 * 60 * 60)
# Generating a chain of 10 blocks
block_hashes = self.nodes[0].generate(nblocks=10)
# Create longer chain starting 2 blocks before current tip
height = len(block_hashes) - 2
block_hash = block_hashes[height - 1]
block_time = self.nodes[0].getblockheader(block_hash)["mediantime"] + 1
new_blocks = self.build_chain(5, block_hash, height, block_time)
# Force reorg to a longer chain
node0.send_message(msg_headers(new_blocks))
node0.wait_for_getdata()
for block in new_blocks:
node0.send_and_ping(msg_block(block))
# Check that reorg succeeded
assert_equal(self.nodes[0].getblockcount(), 13)
stale_hash = int(block_hashes[-1], 16)
# Check that getdata request for stale block succeeds
self.send_block_request(stale_hash, node0)
test_function = lambda: self.last_block_equals(stale_hash, node0)
wait_until(test_function, timeout=3)
# Check that getheader request for stale block header succeeds
self.send_header_request(stale_hash, node0)
test_function = lambda: self.last_header_equals(stale_hash, node0)
wait_until(test_function, timeout=3)
# Longest chain is extended so stale is much older than chain tip
self.nodes[0].setmocktime(0)
tip = self.nodes[0].generate(nblocks=1)[0]
assert_equal(self.nodes[0].getblockcount(), 14)
# Send getdata & getheaders to refresh last received getheader message
block_hash = int(tip, 16)
self.send_block_request(block_hash, node0)
self.send_header_request(block_hash, node0)
node0.sync_with_ping()
# Request for very old stale block should now fail
self.send_block_request(stale_hash, node0)
time.sleep(3)
assert not self.last_block_equals(stale_hash, node0)
# Request for very old stale block header should now fail
self.send_header_request(stale_hash, node0)
time.sleep(3)
assert not self.last_header_equals(stale_hash, node0)
# Verify we can fetch very old blocks and headers on the active chain
block_hash = int(block_hashes[2], 16)
self.send_block_request(block_hash, node0)
self.send_header_request(block_hash, node0)
node0.sync_with_ping()
self.send_block_request(block_hash, node0)
test_function = lambda: self.last_block_equals(block_hash, node0)
wait_until(test_function, timeout=3)
self.send_header_request(block_hash, node0)
test_function = lambda: self.last_header_equals(block_hash, node0)
wait_until(test_function, timeout=3)
if __name__ == '__main__':
P2PFingerprintTest().main()
| run_test | identifier_name |
FlattenIntoArray.js | 'use strict';
var GetIntrinsic = require('../GetIntrinsic');
var $TypeError = GetIntrinsic('%TypeError%');
var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger');
var Call = require('./Call');
var CreateDataPropertyOrThrow = require('./CreateDataPropertyOrThrow');
var Get = require('./Get');
var HasProperty = require('./HasProperty');
var IsArray = require('./IsArray');
var ToLength = require('./ToLength');
var ToString = require('./ToString');
// https://ecma-international.org/ecma-262/10.0/#sec-flattenintoarray
// eslint-disable-next-line max-params
module.exports = function FlattenIntoArray(target, source, sourceLen, start, depth) {
var mapperFunction;
if (arguments.length > 5) {
mapperFunction = arguments[5];
}
var targetIndex = start;
var sourceIndex = 0;
while (sourceIndex < sourceLen) {
var P = ToString(sourceIndex);
var exists = HasProperty(source, P);
if (exists === true) |
sourceIndex += 1;
}
return targetIndex;
};
| {
var element = Get(source, P);
if (typeof mapperFunction !== 'undefined') {
if (arguments.length <= 6) {
throw new $TypeError('Assertion failed: thisArg is required when mapperFunction is provided');
}
element = Call(mapperFunction, arguments[6], [element, sourceIndex, source]);
}
var shouldFlatten = false;
if (depth > 0) {
shouldFlatten = IsArray(element);
}
if (shouldFlatten) {
var elementLen = ToLength(Get(element, 'length'));
targetIndex = FlattenIntoArray(target, element, elementLen, targetIndex, depth - 1);
} else {
if (targetIndex >= MAX_SAFE_INTEGER) {
throw new $TypeError('index too large');
}
CreateDataPropertyOrThrow(target, ToString(targetIndex), element);
targetIndex += 1;
}
} | conditional_block |
FlattenIntoArray.js | 'use strict';
var GetIntrinsic = require('../GetIntrinsic');
var $TypeError = GetIntrinsic('%TypeError%');
var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger');
var Call = require('./Call');
var CreateDataPropertyOrThrow = require('./CreateDataPropertyOrThrow');
var Get = require('./Get');
var HasProperty = require('./HasProperty');
var IsArray = require('./IsArray');
var ToLength = require('./ToLength');
var ToString = require('./ToString');
// https://ecma-international.org/ecma-262/10.0/#sec-flattenintoarray
// eslint-disable-next-line max-params
module.exports = function FlattenIntoArray(target, source, sourceLen, start, depth) { | if (arguments.length > 5) {
mapperFunction = arguments[5];
}
var targetIndex = start;
var sourceIndex = 0;
while (sourceIndex < sourceLen) {
var P = ToString(sourceIndex);
var exists = HasProperty(source, P);
if (exists === true) {
var element = Get(source, P);
if (typeof mapperFunction !== 'undefined') {
if (arguments.length <= 6) {
throw new $TypeError('Assertion failed: thisArg is required when mapperFunction is provided');
}
element = Call(mapperFunction, arguments[6], [element, sourceIndex, source]);
}
var shouldFlatten = false;
if (depth > 0) {
shouldFlatten = IsArray(element);
}
if (shouldFlatten) {
var elementLen = ToLength(Get(element, 'length'));
targetIndex = FlattenIntoArray(target, element, elementLen, targetIndex, depth - 1);
} else {
if (targetIndex >= MAX_SAFE_INTEGER) {
throw new $TypeError('index too large');
}
CreateDataPropertyOrThrow(target, ToString(targetIndex), element);
targetIndex += 1;
}
}
sourceIndex += 1;
}
return targetIndex;
}; | var mapperFunction; | random_line_split |
interval.rs | //! Support for creating futures that represent intervals.
//!
//! This module contains the `Interval` type which is a stream that will
//! resolve at a fixed intervals in future
use std::io;
use std::time::{Duration, Instant};
use futures::{Poll, Async};
use futures::stream::{Stream};
use reactor::{Remote, Handle};
use reactor::timeout_token::TimeoutToken;
/// A stream representing notifications at fixed interval
///
/// Intervals are created through the `Interval::new` or
/// `Interval::new_at` methods indicating when a first notification
/// should be triggered and when it will be repeated.
///
/// Note that timeouts are not intended for high resolution timers, but rather
/// they will likely fire some granularity after the exact instant that they're
/// otherwise indicated to fire at.
pub struct Interval {
token: TimeoutToken,
next: Instant,
interval: Duration,
handle: Remote,
}
impl Interval {
/// Creates a new interval which will fire at `dur` time into the future,
/// and will repeat every `dur` interval after
///
/// This function will return a future that will resolve to the actual
/// interval object. The interval object itself is then a stream which will
/// be set to fire at the specified intervals
pub fn new(dur: Duration, handle: &Handle) -> io::Result<Interval> {
Interval::new_at(Instant::now() + dur, dur, handle)
}
/// Creates a new interval which will fire at the time specified by `at`,
/// and then will repeat every `dur` interval after
///
/// This function will return a future that will resolve to the actual
/// timeout object. The timeout object itself is then a future which will be
/// set to fire at the specified point in the future.
pub fn new_at(at: Instant, dur: Duration, handle: &Handle)
-> io::Result<Interval>
{
Ok(Interval {
token: try!(TimeoutToken::new(at, &handle)),
next: at,
interval: dur,
handle: handle.remote().clone(),
})
}
}
impl Stream for Interval {
type Item = ();
type Error = io::Error;
fn poll(&mut self) -> Poll<Option<()>, io::Error> {
// TODO: is this fast enough?
let now = Instant::now();
if self.next <= now {
self.next = next_interval(self.next, now, self.interval);
self.token.reset_timeout(self.next, &self.handle);
Ok(Async::Ready(Some(())))
} else {
self.token.update_timeout(&self.handle);
Ok(Async::NotReady)
}
}
}
impl Drop for Interval {
fn drop(&mut self) {
self.token.cancel_timeout(&self.handle);
}
}
/// Converts Duration object to raw nanoseconds if possible
///
/// This is useful to divide intervals.
///
/// While technically for large duration it's impossible to represent any
/// duration as nanoseconds, the largest duration we can represent is about
/// 427_000 years. Large enough for any interval we would use or calculate in
/// tokio.
fn duration_to_nanos(dur: Duration) -> Option<u64> {
dur.as_secs()
.checked_mul(1_000_000_000)
.and_then(|v| v.checked_add(dur.subsec_nanos() as u64))
}
fn next_interval(prev: Instant, now: Instant, interval: Duration) -> Instant {
let new = prev + interval;
if new > now {
return new;
} else {
let spent_ns = duration_to_nanos(now.duration_since(prev))
.expect("interval should be expired");
let interval_ns = duration_to_nanos(interval)
.expect("interval is less that 427 thousand years");
let mult = spent_ns/interval_ns + 1;
assert!(mult < (1 << 32),
"can't skip more than 4 billion intervals of {:?} \
(trying to skip {})", interval, mult);
return prev + interval * (mult as u32);
}
}
#[cfg(test)]
mod test {
use std::time::{Instant, Duration};
use super::next_interval;
struct Timeline(Instant);
impl Timeline {
fn new() -> Timeline {
Timeline(Instant::now())
}
fn at(&self, millis: u64) -> Instant {
self.0 + Duration::from_millis(millis)
}
fn at_ns(&self, sec: u64, nanos: u32) -> Instant {
self.0 + Duration::new(sec, nanos)
}
}
fn dur(millis: u64) -> Duration {
Duration::from_millis(millis)
}
#[test]
fn norm_next() |
#[test]
fn fast_forward() {
let tm = Timeline::new();
assert_eq!(next_interval(tm.at(1), tm.at(1000), dur(10)),
tm.at(1001));
assert_eq!(next_interval(tm.at(7777), tm.at(8888), dur(100)),
tm.at(8977));
assert_eq!(next_interval(tm.at(1), tm.at(10000), dur(2100)),
tm.at(10501));
}
/// TODO: this test actually should be successful, but since we can't
/// multiply Duration on anything larger than u32 easily we decided
/// to allow thit to fail for now
#[test]
#[should_panic(expected = "can't skip more than 4 billion intervals")]
fn large_skip() {
let tm = Timeline::new();
assert_eq!(next_interval(
tm.at_ns(0, 1), tm.at_ns(25, 0), Duration::new(0, 2)),
tm.at_ns(25, 1));
}
}
| {
let tm = Timeline::new();
assert_eq!(next_interval(tm.at(1), tm.at(2), dur(10)), tm.at(11));
assert_eq!(next_interval(tm.at(7777), tm.at(7788), dur(100)),
tm.at(7877));
assert_eq!(next_interval(tm.at(1), tm.at(1000), dur(2100)),
tm.at(2101));
} | identifier_body |
interval.rs | //! Support for creating futures that represent intervals.
//!
//! This module contains the `Interval` type which is a stream that will
//! resolve at a fixed intervals in future
use std::io;
use std::time::{Duration, Instant};
use futures::{Poll, Async};
use futures::stream::{Stream};
use reactor::{Remote, Handle};
use reactor::timeout_token::TimeoutToken;
/// A stream representing notifications at fixed interval
///
/// Intervals are created through the `Interval::new` or
/// `Interval::new_at` methods indicating when a first notification
/// should be triggered and when it will be repeated.
///
/// Note that timeouts are not intended for high resolution timers, but rather
/// they will likely fire some granularity after the exact instant that they're
/// otherwise indicated to fire at.
pub struct Interval {
token: TimeoutToken,
next: Instant,
interval: Duration,
handle: Remote,
}
impl Interval {
/// Creates a new interval which will fire at `dur` time into the future,
/// and will repeat every `dur` interval after
///
/// This function will return a future that will resolve to the actual
/// interval object. The interval object itself is then a stream which will
/// be set to fire at the specified intervals
pub fn new(dur: Duration, handle: &Handle) -> io::Result<Interval> {
Interval::new_at(Instant::now() + dur, dur, handle)
}
/// Creates a new interval which will fire at the time specified by `at`,
/// and then will repeat every `dur` interval after
///
/// This function will return a future that will resolve to the actual
/// timeout object. The timeout object itself is then a future which will be
/// set to fire at the specified point in the future.
pub fn | (at: Instant, dur: Duration, handle: &Handle)
-> io::Result<Interval>
{
Ok(Interval {
token: try!(TimeoutToken::new(at, &handle)),
next: at,
interval: dur,
handle: handle.remote().clone(),
})
}
}
impl Stream for Interval {
type Item = ();
type Error = io::Error;
fn poll(&mut self) -> Poll<Option<()>, io::Error> {
// TODO: is this fast enough?
let now = Instant::now();
if self.next <= now {
self.next = next_interval(self.next, now, self.interval);
self.token.reset_timeout(self.next, &self.handle);
Ok(Async::Ready(Some(())))
} else {
self.token.update_timeout(&self.handle);
Ok(Async::NotReady)
}
}
}
impl Drop for Interval {
fn drop(&mut self) {
self.token.cancel_timeout(&self.handle);
}
}
/// Converts Duration object to raw nanoseconds if possible
///
/// This is useful to divide intervals.
///
/// While technically for large duration it's impossible to represent any
/// duration as nanoseconds, the largest duration we can represent is about
/// 427_000 years. Large enough for any interval we would use or calculate in
/// tokio.
fn duration_to_nanos(dur: Duration) -> Option<u64> {
dur.as_secs()
.checked_mul(1_000_000_000)
.and_then(|v| v.checked_add(dur.subsec_nanos() as u64))
}
fn next_interval(prev: Instant, now: Instant, interval: Duration) -> Instant {
let new = prev + interval;
if new > now {
return new;
} else {
let spent_ns = duration_to_nanos(now.duration_since(prev))
.expect("interval should be expired");
let interval_ns = duration_to_nanos(interval)
.expect("interval is less that 427 thousand years");
let mult = spent_ns/interval_ns + 1;
assert!(mult < (1 << 32),
"can't skip more than 4 billion intervals of {:?} \
(trying to skip {})", interval, mult);
return prev + interval * (mult as u32);
}
}
#[cfg(test)]
mod test {
use std::time::{Instant, Duration};
use super::next_interval;
struct Timeline(Instant);
impl Timeline {
fn new() -> Timeline {
Timeline(Instant::now())
}
fn at(&self, millis: u64) -> Instant {
self.0 + Duration::from_millis(millis)
}
fn at_ns(&self, sec: u64, nanos: u32) -> Instant {
self.0 + Duration::new(sec, nanos)
}
}
fn dur(millis: u64) -> Duration {
Duration::from_millis(millis)
}
#[test]
fn norm_next() {
let tm = Timeline::new();
assert_eq!(next_interval(tm.at(1), tm.at(2), dur(10)), tm.at(11));
assert_eq!(next_interval(tm.at(7777), tm.at(7788), dur(100)),
tm.at(7877));
assert_eq!(next_interval(tm.at(1), tm.at(1000), dur(2100)),
tm.at(2101));
}
#[test]
fn fast_forward() {
let tm = Timeline::new();
assert_eq!(next_interval(tm.at(1), tm.at(1000), dur(10)),
tm.at(1001));
assert_eq!(next_interval(tm.at(7777), tm.at(8888), dur(100)),
tm.at(8977));
assert_eq!(next_interval(tm.at(1), tm.at(10000), dur(2100)),
tm.at(10501));
}
/// TODO: this test actually should be successful, but since we can't
/// multiply Duration on anything larger than u32 easily we decided
/// to allow thit to fail for now
#[test]
#[should_panic(expected = "can't skip more than 4 billion intervals")]
fn large_skip() {
let tm = Timeline::new();
assert_eq!(next_interval(
tm.at_ns(0, 1), tm.at_ns(25, 0), Duration::new(0, 2)),
tm.at_ns(25, 1));
}
}
| new_at | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.