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 |
|---|---|---|---|---|
import_.py |
from __future__ import absolute_import
class DummyException(Exception):
pass
def | (
name, modules=None, exceptions=DummyException, locals_=None,
globals_=None, level=-1):
'''Import the requested items into the global scope
WARNING! this method _will_ overwrite your global scope
If you have a variable named "path" and you call import_global('sys')
it will be overwritten with sys.path
Args:
name (str): the name of the module to import, e.g. sys
modules (str): the modules to import, use None for everything
exception (Exception): the exception to catch, e.g. ImportError
`locals_`: the `locals()` method (in case you need a different scope)
`globals_`: the `globals()` method (in case you need a different scope)
level (int): the level to import from, this can be used for
relative imports
'''
frame = None
try:
# If locals_ or globals_ are not given, autodetect them by inspecting
# the current stack
if locals_ is None or globals_ is None:
import inspect
frame = inspect.stack()[1][0]
if locals_ is None:
locals_ = frame.f_locals
if globals_ is None:
globals_ = frame.f_globals
try:
name = name.split('.')
# Relative imports are supported (from .spam import eggs)
if not name[0]:
name = name[1:]
level = 1
# raise IOError((name, level))
module = __import__(
name=name[0] or '.',
globals=globals_,
locals=locals_,
fromlist=name[1:],
level=max(level, 0),
)
# Make sure we get the right part of a dotted import (i.e.
# spam.eggs should return eggs, not spam)
try:
for attr in name[1:]:
module = getattr(module, attr)
except AttributeError:
raise ImportError('No module named ' + '.'.join(name))
# If no list of modules is given, autodetect from either __all__
# or a dir() of the module
if not modules:
modules = getattr(module, '__all__', dir(module))
else:
modules = set(modules).intersection(dir(module))
# Add all items in modules to the global scope
for k in set(dir(module)).intersection(modules):
if k and k[0] != '_':
globals_[k] = getattr(module, k)
except exceptions as e:
return e
finally:
# Clean up, just to be sure
del name, modules, exceptions, locals_, globals_, frame
| import_global | identifier_name |
import_.py | from __future__ import absolute_import
class DummyException(Exception):
pass
def import_global(
name, modules=None, exceptions=DummyException, locals_=None,
globals_=None, level=-1):
'''Import the requested items into the global scope
WARNING! this method _will_ overwrite your global scope
If you have a variable named "path" and you call import_global('sys')
it will be overwritten with sys.path
Args:
name (str): the name of the module to import, e.g. sys
modules (str): the modules to import, use None for everything
exception (Exception): the exception to catch, e.g. ImportError
`locals_`: the `locals()` method (in case you need a different scope)
`globals_`: the `globals()` method (in case you need a different scope)
level (int): the level to import from, this can be used for
relative imports
'''
frame = None
try:
# If locals_ or globals_ are not given, autodetect them by inspecting
# the current stack
if locals_ is None or globals_ is None:
import inspect
frame = inspect.stack()[1][0]
if locals_ is None:
locals_ = frame.f_locals
if globals_ is None:
globals_ = frame.f_globals
try:
name = name.split('.')
# Relative imports are supported (from .spam import eggs)
if not name[0]:
name = name[1:]
level = 1
# raise IOError((name, level))
module = __import__(
name=name[0] or '.',
globals=globals_,
locals=locals_,
fromlist=name[1:],
level=max(level, 0),
)
# Make sure we get the right part of a dotted import (i.e.
# spam.eggs should return eggs, not spam)
try:
for attr in name[1:]:
module = getattr(module, attr)
except AttributeError:
raise ImportError('No module named ' + '.'.join(name))
# If no list of modules is given, autodetect from either __all__
# or a dir() of the module
if not modules:
modules = getattr(module, '__all__', dir(module))
else: | if k and k[0] != '_':
globals_[k] = getattr(module, k)
except exceptions as e:
return e
finally:
# Clean up, just to be sure
del name, modules, exceptions, locals_, globals_, frame | modules = set(modules).intersection(dir(module))
# Add all items in modules to the global scope
for k in set(dir(module)).intersection(modules): | random_line_split |
import_.py |
from __future__ import absolute_import
class DummyException(Exception):
pass
def import_global(
name, modules=None, exceptions=DummyException, locals_=None,
globals_=None, level=-1):
| '''Import the requested items into the global scope
WARNING! this method _will_ overwrite your global scope
If you have a variable named "path" and you call import_global('sys')
it will be overwritten with sys.path
Args:
name (str): the name of the module to import, e.g. sys
modules (str): the modules to import, use None for everything
exception (Exception): the exception to catch, e.g. ImportError
`locals_`: the `locals()` method (in case you need a different scope)
`globals_`: the `globals()` method (in case you need a different scope)
level (int): the level to import from, this can be used for
relative imports
'''
frame = None
try:
# If locals_ or globals_ are not given, autodetect them by inspecting
# the current stack
if locals_ is None or globals_ is None:
import inspect
frame = inspect.stack()[1][0]
if locals_ is None:
locals_ = frame.f_locals
if globals_ is None:
globals_ = frame.f_globals
try:
name = name.split('.')
# Relative imports are supported (from .spam import eggs)
if not name[0]:
name = name[1:]
level = 1
# raise IOError((name, level))
module = __import__(
name=name[0] or '.',
globals=globals_,
locals=locals_,
fromlist=name[1:],
level=max(level, 0),
)
# Make sure we get the right part of a dotted import (i.e.
# spam.eggs should return eggs, not spam)
try:
for attr in name[1:]:
module = getattr(module, attr)
except AttributeError:
raise ImportError('No module named ' + '.'.join(name))
# If no list of modules is given, autodetect from either __all__
# or a dir() of the module
if not modules:
modules = getattr(module, '__all__', dir(module))
else:
modules = set(modules).intersection(dir(module))
# Add all items in modules to the global scope
for k in set(dir(module)).intersection(modules):
if k and k[0] != '_':
globals_[k] = getattr(module, k)
except exceptions as e:
return e
finally:
# Clean up, just to be sure
del name, modules, exceptions, locals_, globals_, frame | identifier_body | |
import_.py |
from __future__ import absolute_import
class DummyException(Exception):
pass
def import_global(
name, modules=None, exceptions=DummyException, locals_=None,
globals_=None, level=-1):
'''Import the requested items into the global scope
WARNING! this method _will_ overwrite your global scope
If you have a variable named "path" and you call import_global('sys')
it will be overwritten with sys.path
Args:
name (str): the name of the module to import, e.g. sys
modules (str): the modules to import, use None for everything
exception (Exception): the exception to catch, e.g. ImportError
`locals_`: the `locals()` method (in case you need a different scope)
`globals_`: the `globals()` method (in case you need a different scope)
level (int): the level to import from, this can be used for
relative imports
'''
frame = None
try:
# If locals_ or globals_ are not given, autodetect them by inspecting
# the current stack
if locals_ is None or globals_ is None:
import inspect
frame = inspect.stack()[1][0]
if locals_ is None:
locals_ = frame.f_locals
if globals_ is None:
|
try:
name = name.split('.')
# Relative imports are supported (from .spam import eggs)
if not name[0]:
name = name[1:]
level = 1
# raise IOError((name, level))
module = __import__(
name=name[0] or '.',
globals=globals_,
locals=locals_,
fromlist=name[1:],
level=max(level, 0),
)
# Make sure we get the right part of a dotted import (i.e.
# spam.eggs should return eggs, not spam)
try:
for attr in name[1:]:
module = getattr(module, attr)
except AttributeError:
raise ImportError('No module named ' + '.'.join(name))
# If no list of modules is given, autodetect from either __all__
# or a dir() of the module
if not modules:
modules = getattr(module, '__all__', dir(module))
else:
modules = set(modules).intersection(dir(module))
# Add all items in modules to the global scope
for k in set(dir(module)).intersection(modules):
if k and k[0] != '_':
globals_[k] = getattr(module, k)
except exceptions as e:
return e
finally:
# Clean up, just to be sure
del name, modules, exceptions, locals_, globals_, frame
| globals_ = frame.f_globals | conditional_block |
HINFO.py | # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import struct
import dns.exception
import dns.immutable
import dns.rdata
import dns.tokenizer
@dns.immutable.immutable
class HINFO(dns.rdata.Rdata):
"""HINFO record"""
# see: RFC 1035
__slots__ = ['cpu', 'os']
def __init__(self, rdclass, rdtype, cpu, os):
super().__init__(rdclass, rdtype)
self.cpu = self._as_bytes(cpu, True, 255)
self.os = self._as_bytes(os, True, 255)
def to_text(self, origin=None, relativize=True, **kw):
return '"{}" "{}"'.format(dns.rdata._escapify(self.cpu),
dns.rdata._escapify(self.os))
@classmethod
def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True,
relativize_to=None):
cpu = tok.get_string(max_length=255)
os = tok.get_string(max_length=255)
return cls(rdclass, rdtype, cpu, os)
def _to_wire(self, file, compress=None, origin=None, canonicalize=False):
l = len(self.cpu)
assert l < 256
file.write(struct.pack('!B', l))
file.write(self.cpu)
l = len(self.os)
assert l < 256
file.write(struct.pack('!B', l))
file.write(self.os)
@classmethod
def from_wire_parser(cls, rdclass, rdtype, parser, origin=None):
| cpu = parser.get_counted_bytes()
os = parser.get_counted_bytes()
return cls(rdclass, rdtype, cpu, os) | identifier_body | |
HINFO.py | # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import struct
import dns.exception
import dns.immutable
import dns.rdata
import dns.tokenizer
@dns.immutable.immutable
class HINFO(dns.rdata.Rdata):
"""HINFO record"""
# see: RFC 1035 | def __init__(self, rdclass, rdtype, cpu, os):
super().__init__(rdclass, rdtype)
self.cpu = self._as_bytes(cpu, True, 255)
self.os = self._as_bytes(os, True, 255)
def to_text(self, origin=None, relativize=True, **kw):
return '"{}" "{}"'.format(dns.rdata._escapify(self.cpu),
dns.rdata._escapify(self.os))
@classmethod
def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True,
relativize_to=None):
cpu = tok.get_string(max_length=255)
os = tok.get_string(max_length=255)
return cls(rdclass, rdtype, cpu, os)
def _to_wire(self, file, compress=None, origin=None, canonicalize=False):
l = len(self.cpu)
assert l < 256
file.write(struct.pack('!B', l))
file.write(self.cpu)
l = len(self.os)
assert l < 256
file.write(struct.pack('!B', l))
file.write(self.os)
@classmethod
def from_wire_parser(cls, rdclass, rdtype, parser, origin=None):
cpu = parser.get_counted_bytes()
os = parser.get_counted_bytes()
return cls(rdclass, rdtype, cpu, os) |
__slots__ = ['cpu', 'os']
| random_line_split |
HINFO.py | # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import struct
import dns.exception
import dns.immutable
import dns.rdata
import dns.tokenizer
@dns.immutable.immutable
class HINFO(dns.rdata.Rdata):
"""HINFO record"""
# see: RFC 1035
__slots__ = ['cpu', 'os']
def __init__(self, rdclass, rdtype, cpu, os):
super().__init__(rdclass, rdtype)
self.cpu = self._as_bytes(cpu, True, 255)
self.os = self._as_bytes(os, True, 255)
def | (self, origin=None, relativize=True, **kw):
return '"{}" "{}"'.format(dns.rdata._escapify(self.cpu),
dns.rdata._escapify(self.os))
@classmethod
def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True,
relativize_to=None):
cpu = tok.get_string(max_length=255)
os = tok.get_string(max_length=255)
return cls(rdclass, rdtype, cpu, os)
def _to_wire(self, file, compress=None, origin=None, canonicalize=False):
l = len(self.cpu)
assert l < 256
file.write(struct.pack('!B', l))
file.write(self.cpu)
l = len(self.os)
assert l < 256
file.write(struct.pack('!B', l))
file.write(self.os)
@classmethod
def from_wire_parser(cls, rdclass, rdtype, parser, origin=None):
cpu = parser.get_counted_bytes()
os = parser.get_counted_bytes()
return cls(rdclass, rdtype, cpu, os)
| to_text | identifier_name |
Sequence.js | /*
* Sequence is used internally to provide further methods to iterables
* that are also genuine flat sequences, i.e all iterables but maps.
*
* None of the Sequence methods mutates the collection.
*
* Sequence can also act as a temporary Array wrapper so that an Array instance
* can beneficiate from all Sequence methods, e.g var otherArray = Seq(array).dropWhile(...);
* This can be useful as a one-off when using a List over an Array is not wanted.
*/
var Sequence = function(array) {
if (this instanceof Sequence) return;
return ArraySeq(array);
};
Sequence.prototype = new Iterable();
/*
* Tests whether this sequence contains a given item.
*/
Sequence.prototype.contains = function(item) {
for (var i = 0, length = this.items.length; i < length; i++) {
if (this.items[i] === item) return true;
}
return false;
};
/*
* Builds a new sequence without any duplicate item.
*/
Sequence.prototype.distinct = function() {
var set = Set(), result = [];
for (var i = 0, length = this.items.length; i < length; i++) {
var item = this.items[i];
if (!set.add(item)) continue;
result.push(item);
}
return this._createNew(result);
};
/*
* Converts this sequence of collections
* into a sequence formed by the items of these collections.
*/
Sequence.prototype.flatten = function() {
var result = [], item;
for (var i = 0, length = this.items.length; i < length; i++) {
item = this.items[i];
var seq = asSequence(item);
if (seq) result.push.apply(result, seq.items);
else result.push(item);
} |
/*
* Returns the index of the first occurence of item
* in this sequence or -1 if none exists.
*/
Sequence.prototype.indexOf = function(item, startingIndex) {
startingIndex = startingIndex || 0;
for (var i = startingIndex, length = this.items.length; i < length; i++) {
if (this.items[i] === item) return i;
}
return -1;
};
/*
* Returns the index of the last occurence of item
* in this sequence or -1 if none exists.
*/
Sequence.prototype.lastIndexOf = function(item) {
for (var i = this.items.length - 1; i >= 0 ; i--) {
if (this.items[i] === item) return i;
}
return -1;
};
/*
* Builds a new sequence where all ocurrences
* of the specified arguments have been removed.
*/
Sequence.prototype.removeItems = function() {
var blackList = Set.fromArray(arguments);
var result = [];
for (var i = 0, length = this.items.length; i < length; i++) {
var item = this.items[i];
if (!blackList.contains(item)) result.push(item);
}
return this._createNew(result);
};
/*
* Checks whether the specified sequence contains
* the same items in the same order as this sequence.
*/
Sequence.prototype.sameItems = function(collection) {
collection = asSequence(collection);
if (this.size() != collection.size()) return false;
for (var i = 0, length = this.items.length; i < length; i++) {
if (this.items[i] !== collection.items[i]) return false;
}
return true;
};
var asSequence = function(instance) {
if (instance instanceof Seq) return instance;
if (isArray(instance)) return Seq(instance);
return null;
};
/*
* ArraySeq is used internally as a temporary wrapper to augment
* an Array instance with Sequence methods.
*/
var ArraySeq = createType('ArraySeq', Sequence);
ArraySeq.prototype._init = function(items) {
this.items = items;
};
ArraySeq.fromArray = function(array) {
return array;
};
var Seq = Collection.Seq = Collection.Sequence = Sequence; | return this._createNew(result);
}; | random_line_split |
hsibackend.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2002 Ben Escoto <ben@emerose.org>
# Copyright 2007 Kenneth Loafman <kenneth@loafman.com>
#
# This file is part of duplicity.
#
# Duplicity is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# Duplicity 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 duplicity; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import os
import duplicity.backend
hsi_command = "hsi"
class HSIBackend(duplicity.backend.Backend):
def __init__(self, parsed_url):
duplicity.backend.Backend.__init__(self, parsed_url)
self.host_string = parsed_url.hostname
self.remote_dir = parsed_url.path
if self.remote_dir:
|
else:
self.remote_prefix = ""
def _put(self, source_path, remote_filename):
commandline = '%s "put %s : %s%s"' % (hsi_command, source_path.name, self.remote_prefix, remote_filename)
self.subprocess_popen(commandline)
def _get(self, remote_filename, local_path):
commandline = '%s "get %s : %s%s"' % (hsi_command, local_path.name, self.remote_prefix, remote_filename)
self.subprocess_popen(commandline)
def _list(self):
import sys
commandline = '%s "ls -l %s"' % (hsi_command, self.remote_dir)
l = self.subprocess_popen(commandline)[2]
l = l.split(os.linesep)[3:]
for i in range(0, len(l)):
if l[i]:
l[i] = l[i].split()[-1]
return [x for x in l if x]
def _delete(self, filename):
commandline = '%s "rm %s%s"' % (hsi_command, self.remote_prefix, filename)
self.subprocess_popen(commandline)
duplicity.backend.register_backend("hsi", HSIBackend)
duplicity.backend.uses_netloc.extend(['hsi'])
| self.remote_prefix = self.remote_dir + "/" | conditional_block |
hsibackend.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2002 Ben Escoto <ben@emerose.org>
# Copyright 2007 Kenneth Loafman <kenneth@loafman.com>
#
# This file is part of duplicity.
#
# Duplicity is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# Duplicity 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 duplicity; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import os
import duplicity.backend
hsi_command = "hsi"
class | (duplicity.backend.Backend):
def __init__(self, parsed_url):
duplicity.backend.Backend.__init__(self, parsed_url)
self.host_string = parsed_url.hostname
self.remote_dir = parsed_url.path
if self.remote_dir:
self.remote_prefix = self.remote_dir + "/"
else:
self.remote_prefix = ""
def _put(self, source_path, remote_filename):
commandline = '%s "put %s : %s%s"' % (hsi_command, source_path.name, self.remote_prefix, remote_filename)
self.subprocess_popen(commandline)
def _get(self, remote_filename, local_path):
commandline = '%s "get %s : %s%s"' % (hsi_command, local_path.name, self.remote_prefix, remote_filename)
self.subprocess_popen(commandline)
def _list(self):
import sys
commandline = '%s "ls -l %s"' % (hsi_command, self.remote_dir)
l = self.subprocess_popen(commandline)[2]
l = l.split(os.linesep)[3:]
for i in range(0, len(l)):
if l[i]:
l[i] = l[i].split()[-1]
return [x for x in l if x]
def _delete(self, filename):
commandline = '%s "rm %s%s"' % (hsi_command, self.remote_prefix, filename)
self.subprocess_popen(commandline)
duplicity.backend.register_backend("hsi", HSIBackend)
duplicity.backend.uses_netloc.extend(['hsi'])
| HSIBackend | identifier_name |
hsibackend.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2002 Ben Escoto <ben@emerose.org>
# Copyright 2007 Kenneth Loafman <kenneth@loafman.com>
#
# This file is part of duplicity.
#
# Duplicity is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# Duplicity 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 duplicity; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import os
import duplicity.backend
hsi_command = "hsi"
class HSIBackend(duplicity.backend.Backend):
def __init__(self, parsed_url):
duplicity.backend.Backend.__init__(self, parsed_url)
self.host_string = parsed_url.hostname
self.remote_dir = parsed_url.path
if self.remote_dir:
self.remote_prefix = self.remote_dir + "/"
else:
self.remote_prefix = ""
def _put(self, source_path, remote_filename):
commandline = '%s "put %s : %s%s"' % (hsi_command, source_path.name, self.remote_prefix, remote_filename)
self.subprocess_popen(commandline)
def _get(self, remote_filename, local_path):
commandline = '%s "get %s : %s%s"' % (hsi_command, local_path.name, self.remote_prefix, remote_filename)
self.subprocess_popen(commandline)
def _list(self):
import sys
commandline = '%s "ls -l %s"' % (hsi_command, self.remote_dir)
l = self.subprocess_popen(commandline)[2]
l = l.split(os.linesep)[3:]
for i in range(0, len(l)):
if l[i]:
l[i] = l[i].split()[-1]
return [x for x in l if x]
def _delete(self, filename):
|
duplicity.backend.register_backend("hsi", HSIBackend)
duplicity.backend.uses_netloc.extend(['hsi'])
| commandline = '%s "rm %s%s"' % (hsi_command, self.remote_prefix, filename)
self.subprocess_popen(commandline) | identifier_body |
hsibackend.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2002 Ben Escoto <ben@emerose.org>
# Copyright 2007 Kenneth Loafman <kenneth@loafman.com>
#
# This file is part of duplicity.
#
# Duplicity is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# Duplicity 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 duplicity; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import os
import duplicity.backend
hsi_command = "hsi"
class HSIBackend(duplicity.backend.Backend):
def __init__(self, parsed_url):
duplicity.backend.Backend.__init__(self, parsed_url)
self.host_string = parsed_url.hostname
self.remote_dir = parsed_url.path
if self.remote_dir:
self.remote_prefix = self.remote_dir + "/"
else:
self.remote_prefix = ""
def _put(self, source_path, remote_filename): |
def _get(self, remote_filename, local_path):
commandline = '%s "get %s : %s%s"' % (hsi_command, local_path.name, self.remote_prefix, remote_filename)
self.subprocess_popen(commandline)
def _list(self):
import sys
commandline = '%s "ls -l %s"' % (hsi_command, self.remote_dir)
l = self.subprocess_popen(commandline)[2]
l = l.split(os.linesep)[3:]
for i in range(0, len(l)):
if l[i]:
l[i] = l[i].split()[-1]
return [x for x in l if x]
def _delete(self, filename):
commandline = '%s "rm %s%s"' % (hsi_command, self.remote_prefix, filename)
self.subprocess_popen(commandline)
duplicity.backend.register_backend("hsi", HSIBackend)
duplicity.backend.uses_netloc.extend(['hsi']) | commandline = '%s "put %s : %s%s"' % (hsi_command, source_path.name, self.remote_prefix, remote_filename)
self.subprocess_popen(commandline) | random_line_split |
casper.py | #!/usr/bin/env python
"""casper.py
Utility class for getting and presenting information from casper.jxml.
The results from casper.jxml are undocumented and thus quite likely to be
removed. Do not rely on its continued existence!
Copyright (C) 2014 Shea G Craig <shea.craig@da.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import copy
from .contrib import requests
import urllib
from xml.etree import ElementTree
class Casper(ElementTree.Element):
def __init__(self, jss):
"""Initialize a Casper object.
jss: JSS object.
"""
self.jss = jss
self.url = "%s%s" % (self.jss.base_url, '/casper.jxml')
self.auth = urllib.urlencode({'username': self.jss.user,
'password': self.jss.password})
super(Casper, self).__init__(tag='Casper')
self.update()
def _indent(self, elem, level=0, more_sibs=False):
"""Indent an xml element object to prepare for pretty printing.
Method is internal to discourage indenting the self._root Element,
thus potentially corrupting it.
"""
i = "\n"
pad = ' '
if level:
i += (level - 1) * pad
num_kids = len(elem)
if num_kids:
if not elem.text or not elem.text.strip():
elem.text = i + pad
if level:
elem.text += pad
count = 0
for kid in elem:
self._indent(kid, level+1, count < num_kids - 1)
count += 1
if not elem.tail or not elem.tail.strip():
elem.tail = i
if more_sibs:
elem.tail += pad
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
if more_sibs:
elem.tail += pad
def | (self):
"""Make our data human readable."""
# deepcopy so we don't mess with the valid XML.
pretty_data = copy.deepcopy(self)
self._indent(pretty_data)
elementstring = ElementTree.tostring(pretty_data)
return elementstring.encode('utf-8')
def makeelement(self, tag, attrib):
"""Return an Element."""
# We use ElementTree.SubElement() a lot. Unfortunately, it relies on a
# super() call to its __class__.makeelement(), which will fail due to
# the class NOT being Element.
# This handles that issue.
return ElementTree.Element(tag, attrib)
def update(self):
"""Request an updated set of data from casper.jxml."""
response = requests.post(self.url, data=self.auth)
response_xml = ElementTree.fromstring(response.text)
# Remove previous data, if any, and then add in response's XML.
self.clear()
for child in response_xml.getchildren():
self.append(child)
| __repr__ | identifier_name |
casper.py | #!/usr/bin/env python
"""casper.py
Utility class for getting and presenting information from casper.jxml.
The results from casper.jxml are undocumented and thus quite likely to be
removed. Do not rely on its continued existence!
Copyright (C) 2014 Shea G Craig <shea.craig@da.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import copy
from .contrib import requests
import urllib
from xml.etree import ElementTree
class Casper(ElementTree.Element):
def __init__(self, jss):
"""Initialize a Casper object.
jss: JSS object.
"""
self.jss = jss
self.url = "%s%s" % (self.jss.base_url, '/casper.jxml')
self.auth = urllib.urlencode({'username': self.jss.user,
'password': self.jss.password})
super(Casper, self).__init__(tag='Casper')
self.update()
def _indent(self, elem, level=0, more_sibs=False):
"""Indent an xml element object to prepare for pretty printing.
Method is internal to discourage indenting the self._root Element,
thus potentially corrupting it.
"""
i = "\n"
pad = ' '
if level:
i += (level - 1) * pad
num_kids = len(elem)
if num_kids:
if not elem.text or not elem.text.strip():
elem.text = i + pad
if level:
elem.text += pad
count = 0
for kid in elem:
self._indent(kid, level+1, count < num_kids - 1)
count += 1
if not elem.tail or not elem.tail.strip():
elem.tail = i
if more_sibs:
elem.tail += pad
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
if more_sibs:
|
def __repr__(self):
"""Make our data human readable."""
# deepcopy so we don't mess with the valid XML.
pretty_data = copy.deepcopy(self)
self._indent(pretty_data)
elementstring = ElementTree.tostring(pretty_data)
return elementstring.encode('utf-8')
def makeelement(self, tag, attrib):
"""Return an Element."""
# We use ElementTree.SubElement() a lot. Unfortunately, it relies on a
# super() call to its __class__.makeelement(), which will fail due to
# the class NOT being Element.
# This handles that issue.
return ElementTree.Element(tag, attrib)
def update(self):
"""Request an updated set of data from casper.jxml."""
response = requests.post(self.url, data=self.auth)
response_xml = ElementTree.fromstring(response.text)
# Remove previous data, if any, and then add in response's XML.
self.clear()
for child in response_xml.getchildren():
self.append(child)
| elem.tail += pad | conditional_block |
casper.py | #!/usr/bin/env python
"""casper.py
Utility class for getting and presenting information from casper.jxml.
The results from casper.jxml are undocumented and thus quite likely to be
removed. Do not rely on its continued existence!
Copyright (C) 2014 Shea G Craig <shea.craig@da.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import copy
from .contrib import requests
import urllib
from xml.etree import ElementTree
class Casper(ElementTree.Element):
def __init__(self, jss):
"""Initialize a Casper object.
jss: JSS object.
"""
self.jss = jss
self.url = "%s%s" % (self.jss.base_url, '/casper.jxml')
self.auth = urllib.urlencode({'username': self.jss.user,
'password': self.jss.password})
super(Casper, self).__init__(tag='Casper')
self.update()
def _indent(self, elem, level=0, more_sibs=False):
"""Indent an xml element object to prepare for pretty printing.
Method is internal to discourage indenting the self._root Element,
thus potentially corrupting it.
"""
i = "\n"
pad = ' '
if level:
i += (level - 1) * pad
num_kids = len(elem)
if num_kids:
if not elem.text or not elem.text.strip():
elem.text = i + pad
if level:
elem.text += pad
count = 0
for kid in elem:
self._indent(kid, level+1, count < num_kids - 1)
count += 1
if not elem.tail or not elem.tail.strip():
elem.tail = i
if more_sibs:
elem.tail += pad
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
if more_sibs:
elem.tail += pad
def __repr__(self):
"""Make our data human readable."""
# deepcopy so we don't mess with the valid XML.
pretty_data = copy.deepcopy(self)
self._indent(pretty_data)
elementstring = ElementTree.tostring(pretty_data)
return elementstring.encode('utf-8')
| # This handles that issue.
return ElementTree.Element(tag, attrib)
def update(self):
"""Request an updated set of data from casper.jxml."""
response = requests.post(self.url, data=self.auth)
response_xml = ElementTree.fromstring(response.text)
# Remove previous data, if any, and then add in response's XML.
self.clear()
for child in response_xml.getchildren():
self.append(child) | def makeelement(self, tag, attrib):
"""Return an Element."""
# We use ElementTree.SubElement() a lot. Unfortunately, it relies on a
# super() call to its __class__.makeelement(), which will fail due to
# the class NOT being Element. | random_line_split |
casper.py | #!/usr/bin/env python
"""casper.py
Utility class for getting and presenting information from casper.jxml.
The results from casper.jxml are undocumented and thus quite likely to be
removed. Do not rely on its continued existence!
Copyright (C) 2014 Shea G Craig <shea.craig@da.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import copy
from .contrib import requests
import urllib
from xml.etree import ElementTree
class Casper(ElementTree.Element):
def __init__(self, jss):
|
def _indent(self, elem, level=0, more_sibs=False):
"""Indent an xml element object to prepare for pretty printing.
Method is internal to discourage indenting the self._root Element,
thus potentially corrupting it.
"""
i = "\n"
pad = ' '
if level:
i += (level - 1) * pad
num_kids = len(elem)
if num_kids:
if not elem.text or not elem.text.strip():
elem.text = i + pad
if level:
elem.text += pad
count = 0
for kid in elem:
self._indent(kid, level+1, count < num_kids - 1)
count += 1
if not elem.tail or not elem.tail.strip():
elem.tail = i
if more_sibs:
elem.tail += pad
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
if more_sibs:
elem.tail += pad
def __repr__(self):
"""Make our data human readable."""
# deepcopy so we don't mess with the valid XML.
pretty_data = copy.deepcopy(self)
self._indent(pretty_data)
elementstring = ElementTree.tostring(pretty_data)
return elementstring.encode('utf-8')
def makeelement(self, tag, attrib):
"""Return an Element."""
# We use ElementTree.SubElement() a lot. Unfortunately, it relies on a
# super() call to its __class__.makeelement(), which will fail due to
# the class NOT being Element.
# This handles that issue.
return ElementTree.Element(tag, attrib)
def update(self):
"""Request an updated set of data from casper.jxml."""
response = requests.post(self.url, data=self.auth)
response_xml = ElementTree.fromstring(response.text)
# Remove previous data, if any, and then add in response's XML.
self.clear()
for child in response_xml.getchildren():
self.append(child)
| """Initialize a Casper object.
jss: JSS object.
"""
self.jss = jss
self.url = "%s%s" % (self.jss.base_url, '/casper.jxml')
self.auth = urllib.urlencode({'username': self.jss.user,
'password': self.jss.password})
super(Casper, self).__init__(tag='Casper')
self.update() | identifier_body |
index.d.ts | // Type definitions for bootstrap-datepicker
// Project: https://github.com/eternicode/bootstrap-datepicker
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="jquery"/>
/**
* All options that take a “Date” can handle a Date object; a String
* formatted according to the given format; or a timedelta relative
* to today, eg “-1d”, “+6m +1y”, etc, where valid units are “d” (day),
* “w” (week), “m” (month), and “y” (year).
*
* See online docs for more info:
* https://bootstrap-datepicker.readthedocs.io/en/latest/options.html
*/
interface DatepickerOptions {
format?: string | DatepickerCustomFormatOptions;
weekStart?: number;
startDate?: Date|string;
endDate?: Date|string;
autoclose?: boolean;
startView?: number;
todayBtn?: boolean|"linked";
todayHighlight?: boolean;
keyboardNavigation?: boolean;
language?: string;
beforeShowDay?: (date: Date) => undefined|string|boolean|DatepickerBeforeShowDayResponse;
beforeShowYear?: (date: Date) => undefined|string|boolean|DatepickerBeforeShowResponse;
beforeShowDecade?: (date: Date) => undefined|string|boolean|DatepickerBeforeShowResponse;
beforeShowCentury?: (date: Date) => undefined|string|boolean|DatepickerBeforeShowResponse;
calendarWeeks?: boolean;
clearBtn?: boolean;
daysOfWeekDisabled?: number[];
forceParse?: boolean;
inputs?: any[];
minViewMode?: 0|"days"|1|"months"|2|"years"|3|"decades"|4|"centuries"|"millenium";
multidate?: boolean|number;
multidateSeparator?: string;
orientation?: "auto"|"left top"|"left bottom"|"right top"|"right bottom";
assumeNearbyYear?: boolean|number;
viewMode?: string;
templates?: any; | datesDisabled?:string|string[];
daysOfWeekHighlighted?:string|number[];
defaultViewDate?:Date|string|DatepickerViewDate;
updateViewDate?:boolean;
}
interface DatepickerViewDate {
year:number;
/** Month starting with 0 */
month:number;
/** Day of the month starting with 1 */
day:number;
}
interface DatepickerBeforeShowResponse {
enabled?:boolean;
classes?: string;
tooltip?: string;
}
interface DatepickerBeforeShowDayResponse extends DatepickerBeforeShowResponse {
content?: string;
}
interface DatepickerCustomFormatOptions {
toDisplay?(date: string, format: any, language: any): string;
toValue?(date: string, format: any, language: any): Date;
}
interface DatepickerEventObject extends JQueryEventObject {
date: Date;
dates: Date[];
format(ix?:number): string;
format(format?: string): string;
format(ix?:number, format?: string): string;
}
interface JQuery {
datepicker(): JQuery;
datepicker(methodName: string): any;
datepicker(methodName: string, params: any): any;
datepicker(options: DatepickerOptions): JQuery;
off(events: "changeDate", selector?: string, handler?: (eventObject: DatepickerEventObject) => any): JQuery;
off(events: "changeDate", handler: (eventObject: DatepickerEventObject) => any): JQuery;
on(events: "changeDate", selector: string, data: any, handler?: (eventObject: DatepickerEventObject) => any): JQuery;
on(events: "changeDate", selector: string, handler: (eventObject: DatepickerEventObject) => any): JQuery;
on(events: 'changeDate', handler: (eventObject: DatepickerEventObject) => any): JQuery;
} | zIndexOffset?: number;
showOnFocus?: boolean;
immediateUpdates?: boolean;
title?: string;
container?: string; | random_line_split |
locked_env_var.rs | //! Unit test helpers for dealing with environment variables.
//!
//! A lot of our functionality can change depending on how certain
//! environment variables are set. This complicates unit testing,
//! because Rust runs test cases in parallel on separate threads, but
//! environment variables are shared across threads. Thus, one test
//! may modify an environment variable for itself while simultaneously
//! clobbering any similar changes being made concurrently by another
//! test.
//!
//! We can run all tests using only a single thread, but this
//! needlessly slows down the entire test suite for what may be as few
//! as two test cases.
//!
//! This module provides types and macros to use in tests to create a
//! global lock on individual environment variables. For tests that
//! depend on a given environment variable, you should declare a locked
//! variable using the `locked_env_var!` macro _outside_ of any
//! individual test case. Then, in each test case, you can obtain the
//! lock to the variable using the lock function created by the
//! macro. This will provide a reference to the locked environment
//! variable, ensuring that the current test is the only one with
//! access to it. Changes may be made using the `set` method of the
//! lock; any value that the variable had prior to the test is
//! remembered and set back when the lock is dropped.
//!
//! This does, of course, depend on the test author taking care to set
//! up the locking infrastructure, and you're on the honor system to
//! not try and modify the variable outside of the bounds of this
//! locking paradigm. Once the locks are in place, however, only the
//! tests that need access to the locked variable will be serialized,
//! leaving the rest of the tests to proceed in parallel.
use std::{env,
ffi::{OsStr,
OsString},
sync::MutexGuard};
/// Models an exclusive "honor system" lock on a single environment variable.
pub struct LockedEnvVar {
/// The checked-out lock for the variable.
lock: MutexGuard<'static, String>,
/// The original value of the environment variable, prior to any
/// modifications through this lock.
///
/// `Some` means a value was set when this struct was created,
/// while `None` means that the variable was not present.
original_value: Option<OsString>,
}
impl LockedEnvVar {
/// Create a new lock. Users should not call this directly, but
/// use locking function generated by the `locked_env_var!` macro.
///
/// The current value of the variable is recorded at the time of
/// creation; it will be reset when the lock is dropped.
pub fn new(lock: MutexGuard<'static, String>) -> Self {
let original = match env::var(&*lock) {
Ok(val) => Some(OsString::from(val)),
Err(env::VarError::NotPresent) => None,
Err(env::VarError::NotUnicode(os_string)) => Some(os_string),
};
LockedEnvVar { lock,
original_value: original }
}
/// Set the locked environment variable to `value`.
pub fn set<V>(&self, value: V)
where V: AsRef<OsStr>
{
env::set_var(&*self.lock, value.as_ref());
}
/// Unsets an environment variable.
pub fn unset(&self) |
}
impl Drop for LockedEnvVar {
fn drop(&mut self) {
match self.original_value {
Some(ref val) => {
env::set_var(&*self.lock, val);
}
None => {
env::remove_var(&*self.lock);
}
}
}
}
/// Create a static thread-safe mutex for accessing a named
/// environment variable.
///
/// `lock_fn` is the name of the function to create to actually check
/// out this lock. You have to provide it explicitly because Rust's
/// macros are not able to generate identifiers at this time.
#[macro_export]
macro_rules! locked_env_var {
($env_var_name:ident, $lock_fn:ident) => {
lazy_static::lazy_static! {
static ref $env_var_name: ::std::sync::Arc<::std::sync::Mutex<String>> =
::std::sync::Arc::new(::std::sync::Mutex::new(String::from(stringify!(
$env_var_name
))));
}
fn $lock_fn() -> $crate::locked_env_var::LockedEnvVar {
// Yup, we're ignoring poisoned mutexes. We're not
// actually changing the contents of the mutex, just using
// it to serialize access.
//
// Furthermore, if a test using the lock fails, that's a
// panic! That would end up failing any tests that were
// run afterwards.
let lock = match $env_var_name.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
$crate::locked_env_var::LockedEnvVar::new(lock)
}
};
}
#[cfg(test)]
mod tests {
use super::*;
use std::{env::VarError,
thread};
#[test]
fn initially_unset_value_is_unset_after_drop() {
// Don't use this variable for any other tests, because we're
// going to be poking at it outside of the lock to verify the
// macro and types behave properly!
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET, lock_var);
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Err(env::VarError::NotPresent));
{
let lock = lock_var();
lock.set("foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Ok(String::from("foo")));
}
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Err(env::VarError::NotPresent));
}
#[test]
fn original_value_is_retained_across_multiple_modifications() {
// Don't use this variable for any other tests, because we're
// going to be poking at it outside of the lock to verify the
// macro and types behave properly!
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR, lock_var);
env::set_var("HAB_TESTING_LOCKED_ENV_VAR", "original_value");
{
let lock = lock_var();
lock.set("foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("foo")));
lock.set("bar");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("bar")));
lock.set("foobar");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("foobar")));
lock.unset();
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Err(VarError::NotPresent));
}
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("original_value")));
}
#[test]
fn can_recover_from_poisoned_mutex() {
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR_POISONED, lock_var);
// Poison the lock
let _ = thread::Builder::new().name("testing-locked-env-var-panic".into())
.spawn(move || {
let _lock = lock_var();
panic!("This is an intentional panic; it's OK");
})
.expect("Couldn't spawn thread!")
.join();
// We should still be able to do something with it; otherwise
// any test that used this variable and failed would fail any
// other test that ran after it.
let lock = lock_var();
lock.set("poisoned foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_POISONED"),
Ok(String::from("poisoned foo")));
}
}
| { env::remove_var(&*self.lock); } | identifier_body |
locked_env_var.rs | //! Unit test helpers for dealing with environment variables.
//!
//! A lot of our functionality can change depending on how certain
//! environment variables are set. This complicates unit testing,
//! because Rust runs test cases in parallel on separate threads, but
//! environment variables are shared across threads. Thus, one test
//! may modify an environment variable for itself while simultaneously
//! clobbering any similar changes being made concurrently by another
//! test.
//!
//! We can run all tests using only a single thread, but this
//! needlessly slows down the entire test suite for what may be as few
//! as two test cases.
//!
//! This module provides types and macros to use in tests to create a
//! global lock on individual environment variables. For tests that
//! depend on a given environment variable, you should declare a locked
//! variable using the `locked_env_var!` macro _outside_ of any
//! individual test case. Then, in each test case, you can obtain the
//! lock to the variable using the lock function created by the
//! macro. This will provide a reference to the locked environment
//! variable, ensuring that the current test is the only one with
//! access to it. Changes may be made using the `set` method of the
//! lock; any value that the variable had prior to the test is
//! remembered and set back when the lock is dropped.
//!
//! This does, of course, depend on the test author taking care to set
//! up the locking infrastructure, and you're on the honor system to
//! not try and modify the variable outside of the bounds of this
//! locking paradigm. Once the locks are in place, however, only the
//! tests that need access to the locked variable will be serialized,
//! leaving the rest of the tests to proceed in parallel.
use std::{env,
ffi::{OsStr,
OsString},
sync::MutexGuard};
/// Models an exclusive "honor system" lock on a single environment variable.
pub struct LockedEnvVar {
/// The checked-out lock for the variable.
lock: MutexGuard<'static, String>,
/// The original value of the environment variable, prior to any
/// modifications through this lock.
///
/// `Some` means a value was set when this struct was created,
/// while `None` means that the variable was not present.
original_value: Option<OsString>,
}
impl LockedEnvVar {
/// Create a new lock. Users should not call this directly, but
/// use locking function generated by the `locked_env_var!` macro.
///
/// The current value of the variable is recorded at the time of
/// creation; it will be reset when the lock is dropped.
pub fn new(lock: MutexGuard<'static, String>) -> Self {
let original = match env::var(&*lock) {
Ok(val) => Some(OsString::from(val)),
Err(env::VarError::NotPresent) => None,
Err(env::VarError::NotUnicode(os_string)) => Some(os_string),
};
LockedEnvVar { lock,
original_value: original }
}
/// Set the locked environment variable to `value`.
pub fn set<V>(&self, value: V)
where V: AsRef<OsStr>
{
env::set_var(&*self.lock, value.as_ref());
}
/// Unsets an environment variable.
pub fn unset(&self) { env::remove_var(&*self.lock); }
}
impl Drop for LockedEnvVar {
fn drop(&mut self) {
match self.original_value {
Some(ref val) => {
env::set_var(&*self.lock, val);
}
None => {
env::remove_var(&*self.lock);
}
}
}
}
/// Create a static thread-safe mutex for accessing a named
/// environment variable.
///
/// `lock_fn` is the name of the function to create to actually check
/// out this lock. You have to provide it explicitly because Rust's
/// macros are not able to generate identifiers at this time.
#[macro_export]
macro_rules! locked_env_var {
($env_var_name:ident, $lock_fn:ident) => {
lazy_static::lazy_static! {
static ref $env_var_name: ::std::sync::Arc<::std::sync::Mutex<String>> =
::std::sync::Arc::new(::std::sync::Mutex::new(String::from(stringify!(
$env_var_name
))));
}
fn $lock_fn() -> $crate::locked_env_var::LockedEnvVar {
// Yup, we're ignoring poisoned mutexes. We're not
// actually changing the contents of the mutex, just using
// it to serialize access.
//
// Furthermore, if a test using the lock fails, that's a
// panic! That would end up failing any tests that were
// run afterwards.
let lock = match $env_var_name.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
$crate::locked_env_var::LockedEnvVar::new(lock)
}
};
}
#[cfg(test)]
mod tests {
use super::*;
use std::{env::VarError,
thread};
#[test]
fn initially_unset_value_is_unset_after_drop() {
// Don't use this variable for any other tests, because we're
// going to be poking at it outside of the lock to verify the
// macro and types behave properly!
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET, lock_var);
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Err(env::VarError::NotPresent));
{
let lock = lock_var();
lock.set("foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Ok(String::from("foo")));
}
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Err(env::VarError::NotPresent));
}
#[test]
fn original_value_is_retained_across_multiple_modifications() {
// Don't use this variable for any other tests, because we're
// going to be poking at it outside of the lock to verify the
// macro and types behave properly!
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR, lock_var);
env::set_var("HAB_TESTING_LOCKED_ENV_VAR", "original_value"); | assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("foo")));
lock.set("bar");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("bar")));
lock.set("foobar");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("foobar")));
lock.unset();
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Err(VarError::NotPresent));
}
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("original_value")));
}
#[test]
fn can_recover_from_poisoned_mutex() {
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR_POISONED, lock_var);
// Poison the lock
let _ = thread::Builder::new().name("testing-locked-env-var-panic".into())
.spawn(move || {
let _lock = lock_var();
panic!("This is an intentional panic; it's OK");
})
.expect("Couldn't spawn thread!")
.join();
// We should still be able to do something with it; otherwise
// any test that used this variable and failed would fail any
// other test that ran after it.
let lock = lock_var();
lock.set("poisoned foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_POISONED"),
Ok(String::from("poisoned foo")));
}
} |
{
let lock = lock_var();
lock.set("foo"); | random_line_split |
locked_env_var.rs | //! Unit test helpers for dealing with environment variables.
//!
//! A lot of our functionality can change depending on how certain
//! environment variables are set. This complicates unit testing,
//! because Rust runs test cases in parallel on separate threads, but
//! environment variables are shared across threads. Thus, one test
//! may modify an environment variable for itself while simultaneously
//! clobbering any similar changes being made concurrently by another
//! test.
//!
//! We can run all tests using only a single thread, but this
//! needlessly slows down the entire test suite for what may be as few
//! as two test cases.
//!
//! This module provides types and macros to use in tests to create a
//! global lock on individual environment variables. For tests that
//! depend on a given environment variable, you should declare a locked
//! variable using the `locked_env_var!` macro _outside_ of any
//! individual test case. Then, in each test case, you can obtain the
//! lock to the variable using the lock function created by the
//! macro. This will provide a reference to the locked environment
//! variable, ensuring that the current test is the only one with
//! access to it. Changes may be made using the `set` method of the
//! lock; any value that the variable had prior to the test is
//! remembered and set back when the lock is dropped.
//!
//! This does, of course, depend on the test author taking care to set
//! up the locking infrastructure, and you're on the honor system to
//! not try and modify the variable outside of the bounds of this
//! locking paradigm. Once the locks are in place, however, only the
//! tests that need access to the locked variable will be serialized,
//! leaving the rest of the tests to proceed in parallel.
use std::{env,
ffi::{OsStr,
OsString},
sync::MutexGuard};
/// Models an exclusive "honor system" lock on a single environment variable.
pub struct LockedEnvVar {
/// The checked-out lock for the variable.
lock: MutexGuard<'static, String>,
/// The original value of the environment variable, prior to any
/// modifications through this lock.
///
/// `Some` means a value was set when this struct was created,
/// while `None` means that the variable was not present.
original_value: Option<OsString>,
}
impl LockedEnvVar {
/// Create a new lock. Users should not call this directly, but
/// use locking function generated by the `locked_env_var!` macro.
///
/// The current value of the variable is recorded at the time of
/// creation; it will be reset when the lock is dropped.
pub fn new(lock: MutexGuard<'static, String>) -> Self {
let original = match env::var(&*lock) {
Ok(val) => Some(OsString::from(val)),
Err(env::VarError::NotPresent) => None,
Err(env::VarError::NotUnicode(os_string)) => Some(os_string),
};
LockedEnvVar { lock,
original_value: original }
}
/// Set the locked environment variable to `value`.
pub fn | <V>(&self, value: V)
where V: AsRef<OsStr>
{
env::set_var(&*self.lock, value.as_ref());
}
/// Unsets an environment variable.
pub fn unset(&self) { env::remove_var(&*self.lock); }
}
impl Drop for LockedEnvVar {
fn drop(&mut self) {
match self.original_value {
Some(ref val) => {
env::set_var(&*self.lock, val);
}
None => {
env::remove_var(&*self.lock);
}
}
}
}
/// Create a static thread-safe mutex for accessing a named
/// environment variable.
///
/// `lock_fn` is the name of the function to create to actually check
/// out this lock. You have to provide it explicitly because Rust's
/// macros are not able to generate identifiers at this time.
#[macro_export]
macro_rules! locked_env_var {
($env_var_name:ident, $lock_fn:ident) => {
lazy_static::lazy_static! {
static ref $env_var_name: ::std::sync::Arc<::std::sync::Mutex<String>> =
::std::sync::Arc::new(::std::sync::Mutex::new(String::from(stringify!(
$env_var_name
))));
}
fn $lock_fn() -> $crate::locked_env_var::LockedEnvVar {
// Yup, we're ignoring poisoned mutexes. We're not
// actually changing the contents of the mutex, just using
// it to serialize access.
//
// Furthermore, if a test using the lock fails, that's a
// panic! That would end up failing any tests that were
// run afterwards.
let lock = match $env_var_name.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
$crate::locked_env_var::LockedEnvVar::new(lock)
}
};
}
#[cfg(test)]
mod tests {
use super::*;
use std::{env::VarError,
thread};
#[test]
fn initially_unset_value_is_unset_after_drop() {
// Don't use this variable for any other tests, because we're
// going to be poking at it outside of the lock to verify the
// macro and types behave properly!
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET, lock_var);
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Err(env::VarError::NotPresent));
{
let lock = lock_var();
lock.set("foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Ok(String::from("foo")));
}
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_INITIALLY_UNSET"),
Err(env::VarError::NotPresent));
}
#[test]
fn original_value_is_retained_across_multiple_modifications() {
// Don't use this variable for any other tests, because we're
// going to be poking at it outside of the lock to verify the
// macro and types behave properly!
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR, lock_var);
env::set_var("HAB_TESTING_LOCKED_ENV_VAR", "original_value");
{
let lock = lock_var();
lock.set("foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("foo")));
lock.set("bar");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("bar")));
lock.set("foobar");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("foobar")));
lock.unset();
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Err(VarError::NotPresent));
}
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"),
Ok(String::from("original_value")));
}
#[test]
fn can_recover_from_poisoned_mutex() {
locked_env_var!(HAB_TESTING_LOCKED_ENV_VAR_POISONED, lock_var);
// Poison the lock
let _ = thread::Builder::new().name("testing-locked-env-var-panic".into())
.spawn(move || {
let _lock = lock_var();
panic!("This is an intentional panic; it's OK");
})
.expect("Couldn't spawn thread!")
.join();
// We should still be able to do something with it; otherwise
// any test that used this variable and failed would fail any
// other test that ran after it.
let lock = lock_var();
lock.set("poisoned foo");
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR_POISONED"),
Ok(String::from("poisoned foo")));
}
}
| set | identifier_name |
fig4.py | ####
# Figure 4
# needs:
# - data/*.npz produced by run.py
####
import glob
import sys
sys.path.append('..')
from lib.mppaper import *
import lib.mpsetup as mpsetup
import lib.immune as immune
files = sorted((immune.parse_value(f, 'epsilon'), f) for f in glob.glob("data/*.npz"))
import run
sigma = run.sigma
#### left figure ####
epsilons = []
similarities = []
similaritiesQ = []
similaritiesPtilde = []
for epsilon, f in files:
npz = np.load(f)
P1 = npz['P1']
P2 = npz['P2']
Ptilde1 = npz['Ptilde1']
Ptilde2 = npz['Ptilde2']
Q1 = npz['Q1']
Q2 = npz['Q2']
epsilons.append(epsilon)
similarities.append(immune.similarity(P1, P2))
similaritiesQ.append(immune.similarity(Q1, Q2))
similaritiesPtilde.append(immune.similarity(Ptilde1, Ptilde2))
fig = plt.figure()
ax = fig.add_subplot(121)
ax.axhline(1.0, color=almostblack)
ax.plot(epsilons, similarities, label='$P_r^\star$', **linedotstyle)
ax.plot(epsilons, similaritiesQ, label='$Q_a$', **linedotstyle)
ax.plot(epsilons, similaritiesPtilde, label=r'$\tilde P_a$', **linedotstyle)
ax.set_xlabel('noise $\epsilon$')
ax.set_ylabel('Similarity')
ax.set_xlim(0.0, 0.5)
ax.set_ylim(0.0, 1.05)
ax.legend(ncol=1, loc='center right')
ax.xaxis.labelpad = axis_labelpad
ax.yaxis.labelpad = axis_labelpad
mpsetup.despine(ax)
fig.tight_layout(pad=tight_layout_pad)
fig.subplots_adjust(top=0.85)
#### right figures ####
epsilon_illustration = 0.2
epsilon, f = [tup for tup in files if tup[0] == epsilon_illustration][0]
npz = np.load(f)
P1 = npz['P1']
P2 = npz['P2']
Qbase = npz['Qbase']
Q1 = npz['Q1']
Q2 = npz['Q2']
x = npz['x']
axQ = fig.add_subplot(222)
for i, Q in enumerate([Q1, Q2]):
axQ.plot(x/sigma, Q, lw=0.5 * linewidth, label='ind. %g' % (i+1))
axQ.set_xlim(0, 10)
axQ.set_ylabel(r'$Q_a$')
axP = fig.add_subplot(224, sharex=axQ)
for i, p in enumerate([P1, P2]):
|
axP.locator_params(axis='x', nbins=5, tight=True)
axP.set_xlim(0, 20)
axP.set_ylabel(r'$P_r^\star$')
axP.legend(ncol=2, handletextpad=0.1,
loc='upper right',
bbox_to_anchor=(1.05, 1.20))
for a in [axQ, axP]:
a.set_ylim(ymin=0.0)
mpsetup.despine(a)
a.set_yticks([])
a.xaxis.labelpad = axis_labelpad
a.yaxis.labelpad = axis_labelpad
axP.set_xlabel('$x \; / \; \sigma$')
plt.setp(axQ.get_xticklabels(), visible=False)
#### finish figure ####
fig.tight_layout(pad=tight_layout_pad, h_pad=1.0)
fig.savefig('fig4.svg')
plt.show()
| axP.plot(x/sigma, p, label='ind. %g' % (i+1), **linedotstyle) | conditional_block |
fig4.py | ####
# Figure 4
# needs:
# - data/*.npz produced by run.py
####
import glob
import sys
sys.path.append('..')
from lib.mppaper import *
import lib.mpsetup as mpsetup
import lib.immune as immune | import run
sigma = run.sigma
#### left figure ####
epsilons = []
similarities = []
similaritiesQ = []
similaritiesPtilde = []
for epsilon, f in files:
npz = np.load(f)
P1 = npz['P1']
P2 = npz['P2']
Ptilde1 = npz['Ptilde1']
Ptilde2 = npz['Ptilde2']
Q1 = npz['Q1']
Q2 = npz['Q2']
epsilons.append(epsilon)
similarities.append(immune.similarity(P1, P2))
similaritiesQ.append(immune.similarity(Q1, Q2))
similaritiesPtilde.append(immune.similarity(Ptilde1, Ptilde2))
fig = plt.figure()
ax = fig.add_subplot(121)
ax.axhline(1.0, color=almostblack)
ax.plot(epsilons, similarities, label='$P_r^\star$', **linedotstyle)
ax.plot(epsilons, similaritiesQ, label='$Q_a$', **linedotstyle)
ax.plot(epsilons, similaritiesPtilde, label=r'$\tilde P_a$', **linedotstyle)
ax.set_xlabel('noise $\epsilon$')
ax.set_ylabel('Similarity')
ax.set_xlim(0.0, 0.5)
ax.set_ylim(0.0, 1.05)
ax.legend(ncol=1, loc='center right')
ax.xaxis.labelpad = axis_labelpad
ax.yaxis.labelpad = axis_labelpad
mpsetup.despine(ax)
fig.tight_layout(pad=tight_layout_pad)
fig.subplots_adjust(top=0.85)
#### right figures ####
epsilon_illustration = 0.2
epsilon, f = [tup for tup in files if tup[0] == epsilon_illustration][0]
npz = np.load(f)
P1 = npz['P1']
P2 = npz['P2']
Qbase = npz['Qbase']
Q1 = npz['Q1']
Q2 = npz['Q2']
x = npz['x']
axQ = fig.add_subplot(222)
for i, Q in enumerate([Q1, Q2]):
axQ.plot(x/sigma, Q, lw=0.5 * linewidth, label='ind. %g' % (i+1))
axQ.set_xlim(0, 10)
axQ.set_ylabel(r'$Q_a$')
axP = fig.add_subplot(224, sharex=axQ)
for i, p in enumerate([P1, P2]):
axP.plot(x/sigma, p, label='ind. %g' % (i+1), **linedotstyle)
axP.locator_params(axis='x', nbins=5, tight=True)
axP.set_xlim(0, 20)
axP.set_ylabel(r'$P_r^\star$')
axP.legend(ncol=2, handletextpad=0.1,
loc='upper right',
bbox_to_anchor=(1.05, 1.20))
for a in [axQ, axP]:
a.set_ylim(ymin=0.0)
mpsetup.despine(a)
a.set_yticks([])
a.xaxis.labelpad = axis_labelpad
a.yaxis.labelpad = axis_labelpad
axP.set_xlabel('$x \; / \; \sigma$')
plt.setp(axQ.get_xticklabels(), visible=False)
#### finish figure ####
fig.tight_layout(pad=tight_layout_pad, h_pad=1.0)
fig.savefig('fig4.svg')
plt.show() |
files = sorted((immune.parse_value(f, 'epsilon'), f) for f in glob.glob("data/*.npz")) | random_line_split |
IOErrorEvent.ts | //////////////////////////////////////////////////////////////////////////////////////
//
// The MIT License (MIT)
//
// Copyright (c) 2017-present, cyder.org
// All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in the
// Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////////////
/**
* An IOErrorEvent object is emitted when an error causes input or output operations to fail.
*/ | class IOErrorEvent extends Event {
/**
* Emitted when an error causes input or output operations to fail.
*/
public static readonly IO_ERROR:string = "ioError";
/**
* Creates an Event object that contains specific information about ioError events. Event objects are passed as
* parameters to Event listeners.
* @param type The type of the event.
* @param cancelable Determine whether the Event object can be canceled. The default value is false.
* @param text Text to be displayed as an error message.
*/
public constructor(type:string, cancelable?:boolean, text:string = "") {
super(type, cancelable);
this.text = text;
}
/**
* Text to be displayed as an error message.
*/
public text:string;
} | random_line_split | |
IOErrorEvent.ts | //////////////////////////////////////////////////////////////////////////////////////
//
// The MIT License (MIT)
//
// Copyright (c) 2017-present, cyder.org
// All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in the
// Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////////////
/**
* An IOErrorEvent object is emitted when an error causes input or output operations to fail.
*/
class | extends Event {
/**
* Emitted when an error causes input or output operations to fail.
*/
public static readonly IO_ERROR:string = "ioError";
/**
* Creates an Event object that contains specific information about ioError events. Event objects are passed as
* parameters to Event listeners.
* @param type The type of the event.
* @param cancelable Determine whether the Event object can be canceled. The default value is false.
* @param text Text to be displayed as an error message.
*/
public constructor(type:string, cancelable?:boolean, text:string = "") {
super(type, cancelable);
this.text = text;
}
/**
* Text to be displayed as an error message.
*/
public text:string;
} | IOErrorEvent | identifier_name |
pandoc_fignos.py | #! /usr/bin/env python
"""pandoc-fignos: a pandoc filter that inserts figure nos. and refs."""
# Copyright 2015, 2016 Thomas J. Duck.
# All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# OVERVIEW
#
# The basic idea is to scan the AST two times in order to:
#
# 1. Insert text for the figure number in each figure caption.
# For LaTeX, insert \label{...} instead. The figure labels
# and associated figure numbers are stored in the global
# references tracker.
#
# 2. Replace each reference with a figure number. For LaTeX,
# replace with \ref{...} instead.
#
# There is also an initial scan to do some preprocessing.
import re
import functools
import itertools
import io
import sys
# pylint: disable=import-error
import pandocfilters
from pandocfilters import stringify, walk
from pandocfilters import RawInline, Str, Space, Para, Plain, Cite, elt
from pandocattributes import PandocAttributes
# Create our own pandoc image primitives to accommodate different pandoc
# versions.
# pylint: disable=invalid-name
Image = elt('Image', 2) # Pandoc < 1.16
AttrImage = elt('Image', 3) # Pandoc >= 1.16
# Patterns for matching labels and references
LABEL_PATTERN = re.compile(r'(fig:[\w/-]*)(.*)')
REF_PATTERN = re.compile(r'@(fig:[\w/-]+)')
# Detect python 3
PY3 = sys.version_info > (3,)
# Pandoc uses UTF-8 for both input and output; so must we
if PY3: # Force utf-8 decoding (decoding of input streams is automatic in py3)
STDIN = io.TextIOWrapper(sys.stdin.buffer, 'utf-8', 'strict')
STDOUT = io.TextIOWrapper(sys.stdout.buffer, 'utf-8', 'strict')
else: # No decoding; utf-8-encoded strings in means the same out
STDIN = sys.stdin
STDOUT = sys.stdout
# pylint: disable=invalid-name
references = {} # Global references tracker
def is_attrimage(key, value):
"""True if this is an attributed image; False otherwise."""
try:
if key == 'Para' and value[0]['t'] == 'Image':
| if s.startswith('{') and s.endswith('}'):
return True
else:
return False
# New pandoc >= 1.16
else:
assert len(value[0]['c']) == 3
return True # Pandoc >= 1.16 has image attributes by default
# pylint: disable=bare-except
except:
return False
def parse_attrimage(value):
"""Parses an attributed image."""
if len(value[0]['c']) == 2: # Old pandoc < 1.16
attrs, (caption, target) = None, value[0]['c']
s = stringify(value[1:]).strip() # The attribute string
# Extract label from attributes (label, classes, kvs)
label = PandocAttributes(s, 'markdown').to_pandoc()[0]
if label == 'fig:': # Make up a unique description
label = label + '__'+str(hash(target[0]))+'__'
return attrs, caption, target, label
else: # New pandoc >= 1.16
assert len(value[0]['c']) == 3
attrs, caption, target = value[0]['c']
s = stringify(value[1:]).strip() # The attribute string
# Extract label from attributes
label = attrs[0]
if label == 'fig:': # Make up a unique description
label = label + '__'+str(hash(target[0]))+'__'
return attrs, caption, target, label
def is_ref(key, value):
"""True if this is a figure reference; False otherwise."""
return key == 'Cite' and REF_PATTERN.match(value[1][0]['c']) and \
parse_ref(value)[1] in references
def parse_ref(value):
"""Parses a figure reference."""
prefix = value[0][0]['citationPrefix']
label = REF_PATTERN.match(value[1][0]['c']).groups()[0]
suffix = value[0][0]['citationSuffix']
return prefix, label, suffix
def ast(string):
"""Returns an AST representation of the string."""
toks = [Str(tok) for tok in string.split()]
spaces = [Space()]*len(toks)
ret = list(itertools.chain(*zip(toks, spaces)))
if string[0] == ' ':
ret = [Space()] + ret
return ret if string[-1] == ' ' else ret[:-1]
def is_broken_ref(key1, value1, key2, value2):
"""True if this is a broken link; False otherwise."""
try: # Pandoc >= 1.16
return key1 == 'Link' and value1[1][0]['t'] == 'Str' and \
value1[1][0]['c'].endswith('{@fig') \
and key2 == 'Str' and '}' in value2
except TypeError: # Pandoc < 1.16
return key1 == 'Link' and value1[0][0]['t'] == 'Str' and \
value1[0][0]['c'].endswith('{@fig') \
and key2 == 'Str' and '}' in value2
def repair_broken_refs(value):
"""Repairs references broken by pandoc's --autolink_bare_uris."""
# autolink_bare_uris splits {@fig:label} at the ':' and treats
# the first half as if it is a mailto url and the second half as a string.
# Let's replace this mess with Cite and Str elements that we normally
# get.
flag = False
for i in range(len(value)-1):
if value[i] == None:
continue
if is_broken_ref(value[i]['t'], value[i]['c'],
value[i+1]['t'], value[i+1]['c']):
flag = True # Found broken reference
try: # Pandoc >= 1.16
s1 = value[i]['c'][1][0]['c'] # Get the first half of the ref
except TypeError: # Pandoc < 1.16
s1 = value[i]['c'][0][0]['c'] # Get the first half of the ref
s2 = value[i+1]['c'] # Get the second half of the ref
ref = '@fig' + s2[:s2.index('}')] # Form the reference
prefix = s1[:s1.index('{@fig')] # Get the prefix
suffix = s2[s2.index('}')+1:] # Get the suffix
# We need to be careful with the prefix string because it might be
# part of another broken reference. Simply put it back into the
# stream and repeat the preprocess() call.
if i > 0 and value[i-1]['t'] == 'Str':
value[i-1]['c'] = value[i-1]['c'] + prefix
value[i] = None
else:
value[i] = Str(prefix)
# Put fixed reference in as a citation that can be processed
value[i+1] = Cite(
[{"citationId":ref[1:],
"citationPrefix":[],
"citationSuffix":[Str(suffix)],
"citationNoteNum":0,
"citationMode":{"t":"AuthorInText", "c":[]},
"citationHash":0}],
[Str(ref)])
if flag:
return [v for v in value if v is not None]
def is_braced_ref(i, value):
"""Returns true if a reference is braced; otherwise False."""
return is_ref(value[i]['t'], value[i]['c']) \
and value[i-1]['t'] == 'Str' and value[i+1]['t'] == 'Str' \
and value[i-1]['c'].endswith('{') and value[i+1]['c'].startswith('}')
def remove_braces(value):
"""Search for references and remove curly braces around them."""
flag = False
for i in range(len(value)-1)[1:]:
if is_braced_ref(i, value):
flag = True # Found reference
# Remove the braces
value[i-1]['c'] = value[i-1]['c'][:-1]
value[i+1]['c'] = value[i+1]['c'][1:]
return flag
# pylint: disable=unused-argument
def preprocess(key, value, fmt, meta):
"""Preprocesses to correct for problems."""
if key in ('Para', 'Plain'):
while True:
newvalue = repair_broken_refs(value)
if newvalue:
value = newvalue
else:
break
if key == 'Para':
return Para(value)
else:
return Plain(value)
# pylint: disable=unused-argument
def replace_attrimages(key, value, fmt, meta):
"""Replaces attributed images while storing reference labels."""
if is_attrimage(key, value):
# Parse the image
attrs, caption, target, label = parse_attrimage(value)
# Bail out if the label does not conform
if not label or not LABEL_PATTERN.match(label):
return None
# Save the reference
references[label] = len(references) + 1
# Adjust caption depending on the output format
if fmt == 'latex':
caption = list(caption) + [RawInline('tex', r'\label{%s}'%label)]
else:
caption = ast('Figure %d. '%references[label]) + list(caption)
# Required for pandoc to process the image
target[1] = "fig:"
# Return the replacement
if len(value[0]['c']) == 2: # Old pandoc < 1.16
img = Image(caption, target)
else: # New pandoc >= 1.16
assert len(value[0]['c']) == 3
img = AttrImage(attrs, caption, target)
if fmt in ('html', 'html5'):
anchor = RawInline('html', '<a name="%s"></a>'%label)
return [Plain([anchor]), Para([img])]
else:
return Para([img])
# pylint: disable=unused-argument
def replace_refs(key, value, fmt, meta):
"""Replaces references to labelled images."""
# Remove braces around references
if key in ('Para', 'Plain'):
if remove_braces(value):
if key == 'Para':
return Para(value)
else:
return Plain(value)
# Replace references
if is_ref(key, value):
prefix, label, suffix = parse_ref(value)
# The replacement depends on the output format
if fmt == 'latex':
return prefix + [RawInline('tex', r'\ref{%s}'%label)] + suffix
elif fmt in ('html', 'html5'):
link = '<a href="#%s">%s</a>' % (label, references[label])
return prefix + [RawInline('html', link)] + suffix
else:
return prefix + [Str('%d'%references[label])] + suffix
def main():
"""Filters the document AST."""
# Get the output format, document and metadata
fmt = sys.argv[1] if len(sys.argv) > 1 else ''
doc = pandocfilters.json.loads(STDIN.read())
meta = doc[0]['unMeta']
# Replace attributed images and references in the AST
altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
[preprocess, replace_attrimages, replace_refs],
doc)
# Dump the results
pandocfilters.json.dump(altered, STDOUT)
# Flush stdout
STDOUT.flush()
if __name__ == '__main__':
main() | # Old pandoc < 1.16
if len(value[0]['c']) == 2:
s = stringify(value[1:]).strip() | random_line_split |
pandoc_fignos.py | #! /usr/bin/env python
"""pandoc-fignos: a pandoc filter that inserts figure nos. and refs."""
# Copyright 2015, 2016 Thomas J. Duck.
# All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# OVERVIEW
#
# The basic idea is to scan the AST two times in order to:
#
# 1. Insert text for the figure number in each figure caption.
# For LaTeX, insert \label{...} instead. The figure labels
# and associated figure numbers are stored in the global
# references tracker.
#
# 2. Replace each reference with a figure number. For LaTeX,
# replace with \ref{...} instead.
#
# There is also an initial scan to do some preprocessing.
import re
import functools
import itertools
import io
import sys
# pylint: disable=import-error
import pandocfilters
from pandocfilters import stringify, walk
from pandocfilters import RawInline, Str, Space, Para, Plain, Cite, elt
from pandocattributes import PandocAttributes
# Create our own pandoc image primitives to accommodate different pandoc
# versions.
# pylint: disable=invalid-name
Image = elt('Image', 2) # Pandoc < 1.16
AttrImage = elt('Image', 3) # Pandoc >= 1.16
# Patterns for matching labels and references
LABEL_PATTERN = re.compile(r'(fig:[\w/-]*)(.*)')
REF_PATTERN = re.compile(r'@(fig:[\w/-]+)')
# Detect python 3
PY3 = sys.version_info > (3,)
# Pandoc uses UTF-8 for both input and output; so must we
if PY3: # Force utf-8 decoding (decoding of input streams is automatic in py3)
STDIN = io.TextIOWrapper(sys.stdin.buffer, 'utf-8', 'strict')
STDOUT = io.TextIOWrapper(sys.stdout.buffer, 'utf-8', 'strict')
else: # No decoding; utf-8-encoded strings in means the same out
STDIN = sys.stdin
STDOUT = sys.stdout
# pylint: disable=invalid-name
references = {} # Global references tracker
def is_attrimage(key, value):
"""True if this is an attributed image; False otherwise."""
try:
if key == 'Para' and value[0]['t'] == 'Image':
# Old pandoc < 1.16
if len(value[0]['c']) == 2:
s = stringify(value[1:]).strip()
if s.startswith('{') and s.endswith('}'):
return True
else:
return False
# New pandoc >= 1.16
else:
assert len(value[0]['c']) == 3
return True # Pandoc >= 1.16 has image attributes by default
# pylint: disable=bare-except
except:
return False
def parse_attrimage(value):
"""Parses an attributed image."""
if len(value[0]['c']) == 2: # Old pandoc < 1.16
attrs, (caption, target) = None, value[0]['c']
s = stringify(value[1:]).strip() # The attribute string
# Extract label from attributes (label, classes, kvs)
label = PandocAttributes(s, 'markdown').to_pandoc()[0]
if label == 'fig:': # Make up a unique description
label = label + '__'+str(hash(target[0]))+'__'
return attrs, caption, target, label
else: # New pandoc >= 1.16
assert len(value[0]['c']) == 3
attrs, caption, target = value[0]['c']
s = stringify(value[1:]).strip() # The attribute string
# Extract label from attributes
label = attrs[0]
if label == 'fig:': # Make up a unique description
label = label + '__'+str(hash(target[0]))+'__'
return attrs, caption, target, label
def is_ref(key, value):
"""True if this is a figure reference; False otherwise."""
return key == 'Cite' and REF_PATTERN.match(value[1][0]['c']) and \
parse_ref(value)[1] in references
def parse_ref(value):
|
def ast(string):
"""Returns an AST representation of the string."""
toks = [Str(tok) for tok in string.split()]
spaces = [Space()]*len(toks)
ret = list(itertools.chain(*zip(toks, spaces)))
if string[0] == ' ':
ret = [Space()] + ret
return ret if string[-1] == ' ' else ret[:-1]
def is_broken_ref(key1, value1, key2, value2):
"""True if this is a broken link; False otherwise."""
try: # Pandoc >= 1.16
return key1 == 'Link' and value1[1][0]['t'] == 'Str' and \
value1[1][0]['c'].endswith('{@fig') \
and key2 == 'Str' and '}' in value2
except TypeError: # Pandoc < 1.16
return key1 == 'Link' and value1[0][0]['t'] == 'Str' and \
value1[0][0]['c'].endswith('{@fig') \
and key2 == 'Str' and '}' in value2
def repair_broken_refs(value):
"""Repairs references broken by pandoc's --autolink_bare_uris."""
# autolink_bare_uris splits {@fig:label} at the ':' and treats
# the first half as if it is a mailto url and the second half as a string.
# Let's replace this mess with Cite and Str elements that we normally
# get.
flag = False
for i in range(len(value)-1):
if value[i] == None:
continue
if is_broken_ref(value[i]['t'], value[i]['c'],
value[i+1]['t'], value[i+1]['c']):
flag = True # Found broken reference
try: # Pandoc >= 1.16
s1 = value[i]['c'][1][0]['c'] # Get the first half of the ref
except TypeError: # Pandoc < 1.16
s1 = value[i]['c'][0][0]['c'] # Get the first half of the ref
s2 = value[i+1]['c'] # Get the second half of the ref
ref = '@fig' + s2[:s2.index('}')] # Form the reference
prefix = s1[:s1.index('{@fig')] # Get the prefix
suffix = s2[s2.index('}')+1:] # Get the suffix
# We need to be careful with the prefix string because it might be
# part of another broken reference. Simply put it back into the
# stream and repeat the preprocess() call.
if i > 0 and value[i-1]['t'] == 'Str':
value[i-1]['c'] = value[i-1]['c'] + prefix
value[i] = None
else:
value[i] = Str(prefix)
# Put fixed reference in as a citation that can be processed
value[i+1] = Cite(
[{"citationId":ref[1:],
"citationPrefix":[],
"citationSuffix":[Str(suffix)],
"citationNoteNum":0,
"citationMode":{"t":"AuthorInText", "c":[]},
"citationHash":0}],
[Str(ref)])
if flag:
return [v for v in value if v is not None]
def is_braced_ref(i, value):
"""Returns true if a reference is braced; otherwise False."""
return is_ref(value[i]['t'], value[i]['c']) \
and value[i-1]['t'] == 'Str' and value[i+1]['t'] == 'Str' \
and value[i-1]['c'].endswith('{') and value[i+1]['c'].startswith('}')
def remove_braces(value):
"""Search for references and remove curly braces around them."""
flag = False
for i in range(len(value)-1)[1:]:
if is_braced_ref(i, value):
flag = True # Found reference
# Remove the braces
value[i-1]['c'] = value[i-1]['c'][:-1]
value[i+1]['c'] = value[i+1]['c'][1:]
return flag
# pylint: disable=unused-argument
def preprocess(key, value, fmt, meta):
"""Preprocesses to correct for problems."""
if key in ('Para', 'Plain'):
while True:
newvalue = repair_broken_refs(value)
if newvalue:
value = newvalue
else:
break
if key == 'Para':
return Para(value)
else:
return Plain(value)
# pylint: disable=unused-argument
def replace_attrimages(key, value, fmt, meta):
"""Replaces attributed images while storing reference labels."""
if is_attrimage(key, value):
# Parse the image
attrs, caption, target, label = parse_attrimage(value)
# Bail out if the label does not conform
if not label or not LABEL_PATTERN.match(label):
return None
# Save the reference
references[label] = len(references) + 1
# Adjust caption depending on the output format
if fmt == 'latex':
caption = list(caption) + [RawInline('tex', r'\label{%s}'%label)]
else:
caption = ast('Figure %d. '%references[label]) + list(caption)
# Required for pandoc to process the image
target[1] = "fig:"
# Return the replacement
if len(value[0]['c']) == 2: # Old pandoc < 1.16
img = Image(caption, target)
else: # New pandoc >= 1.16
assert len(value[0]['c']) == 3
img = AttrImage(attrs, caption, target)
if fmt in ('html', 'html5'):
anchor = RawInline('html', '<a name="%s"></a>'%label)
return [Plain([anchor]), Para([img])]
else:
return Para([img])
# pylint: disable=unused-argument
def replace_refs(key, value, fmt, meta):
"""Replaces references to labelled images."""
# Remove braces around references
if key in ('Para', 'Plain'):
if remove_braces(value):
if key == 'Para':
return Para(value)
else:
return Plain(value)
# Replace references
if is_ref(key, value):
prefix, label, suffix = parse_ref(value)
# The replacement depends on the output format
if fmt == 'latex':
return prefix + [RawInline('tex', r'\ref{%s}'%label)] + suffix
elif fmt in ('html', 'html5'):
link = '<a href="#%s">%s</a>' % (label, references[label])
return prefix + [RawInline('html', link)] + suffix
else:
return prefix + [Str('%d'%references[label])] + suffix
def main():
"""Filters the document AST."""
# Get the output format, document and metadata
fmt = sys.argv[1] if len(sys.argv) > 1 else ''
doc = pandocfilters.json.loads(STDIN.read())
meta = doc[0]['unMeta']
# Replace attributed images and references in the AST
altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
[preprocess, replace_attrimages, replace_refs],
doc)
# Dump the results
pandocfilters.json.dump(altered, STDOUT)
# Flush stdout
STDOUT.flush()
if __name__ == '__main__':
main()
| """Parses a figure reference."""
prefix = value[0][0]['citationPrefix']
label = REF_PATTERN.match(value[1][0]['c']).groups()[0]
suffix = value[0][0]['citationSuffix']
return prefix, label, suffix | identifier_body |
pandoc_fignos.py | #! /usr/bin/env python
"""pandoc-fignos: a pandoc filter that inserts figure nos. and refs."""
# Copyright 2015, 2016 Thomas J. Duck.
# All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# OVERVIEW
#
# The basic idea is to scan the AST two times in order to:
#
# 1. Insert text for the figure number in each figure caption.
# For LaTeX, insert \label{...} instead. The figure labels
# and associated figure numbers are stored in the global
# references tracker.
#
# 2. Replace each reference with a figure number. For LaTeX,
# replace with \ref{...} instead.
#
# There is also an initial scan to do some preprocessing.
import re
import functools
import itertools
import io
import sys
# pylint: disable=import-error
import pandocfilters
from pandocfilters import stringify, walk
from pandocfilters import RawInline, Str, Space, Para, Plain, Cite, elt
from pandocattributes import PandocAttributes
# Create our own pandoc image primitives to accommodate different pandoc
# versions.
# pylint: disable=invalid-name
Image = elt('Image', 2) # Pandoc < 1.16
AttrImage = elt('Image', 3) # Pandoc >= 1.16
# Patterns for matching labels and references
LABEL_PATTERN = re.compile(r'(fig:[\w/-]*)(.*)')
REF_PATTERN = re.compile(r'@(fig:[\w/-]+)')
# Detect python 3
PY3 = sys.version_info > (3,)
# Pandoc uses UTF-8 for both input and output; so must we
if PY3: # Force utf-8 decoding (decoding of input streams is automatic in py3)
STDIN = io.TextIOWrapper(sys.stdin.buffer, 'utf-8', 'strict')
STDOUT = io.TextIOWrapper(sys.stdout.buffer, 'utf-8', 'strict')
else: # No decoding; utf-8-encoded strings in means the same out
STDIN = sys.stdin
STDOUT = sys.stdout
# pylint: disable=invalid-name
references = {} # Global references tracker
def is_attrimage(key, value):
"""True if this is an attributed image; False otherwise."""
try:
if key == 'Para' and value[0]['t'] == 'Image':
# Old pandoc < 1.16
if len(value[0]['c']) == 2:
s = stringify(value[1:]).strip()
if s.startswith('{') and s.endswith('}'):
return True
else:
return False
# New pandoc >= 1.16
else:
assert len(value[0]['c']) == 3
return True # Pandoc >= 1.16 has image attributes by default
# pylint: disable=bare-except
except:
return False
def parse_attrimage(value):
"""Parses an attributed image."""
if len(value[0]['c']) == 2: # Old pandoc < 1.16
attrs, (caption, target) = None, value[0]['c']
s = stringify(value[1:]).strip() # The attribute string
# Extract label from attributes (label, classes, kvs)
label = PandocAttributes(s, 'markdown').to_pandoc()[0]
if label == 'fig:': # Make up a unique description
label = label + '__'+str(hash(target[0]))+'__'
return attrs, caption, target, label
else: # New pandoc >= 1.16
assert len(value[0]['c']) == 3
attrs, caption, target = value[0]['c']
s = stringify(value[1:]).strip() # The attribute string
# Extract label from attributes
label = attrs[0]
if label == 'fig:': # Make up a unique description
label = label + '__'+str(hash(target[0]))+'__'
return attrs, caption, target, label
def is_ref(key, value):
"""True if this is a figure reference; False otherwise."""
return key == 'Cite' and REF_PATTERN.match(value[1][0]['c']) and \
parse_ref(value)[1] in references
def parse_ref(value):
"""Parses a figure reference."""
prefix = value[0][0]['citationPrefix']
label = REF_PATTERN.match(value[1][0]['c']).groups()[0]
suffix = value[0][0]['citationSuffix']
return prefix, label, suffix
def ast(string):
"""Returns an AST representation of the string."""
toks = [Str(tok) for tok in string.split()]
spaces = [Space()]*len(toks)
ret = list(itertools.chain(*zip(toks, spaces)))
if string[0] == ' ':
ret = [Space()] + ret
return ret if string[-1] == ' ' else ret[:-1]
def is_broken_ref(key1, value1, key2, value2):
"""True if this is a broken link; False otherwise."""
try: # Pandoc >= 1.16
return key1 == 'Link' and value1[1][0]['t'] == 'Str' and \
value1[1][0]['c'].endswith('{@fig') \
and key2 == 'Str' and '}' in value2
except TypeError: # Pandoc < 1.16
return key1 == 'Link' and value1[0][0]['t'] == 'Str' and \
value1[0][0]['c'].endswith('{@fig') \
and key2 == 'Str' and '}' in value2
def repair_broken_refs(value):
"""Repairs references broken by pandoc's --autolink_bare_uris."""
# autolink_bare_uris splits {@fig:label} at the ':' and treats
# the first half as if it is a mailto url and the second half as a string.
# Let's replace this mess with Cite and Str elements that we normally
# get.
flag = False
for i in range(len(value)-1):
if value[i] == None:
continue
if is_broken_ref(value[i]['t'], value[i]['c'],
value[i+1]['t'], value[i+1]['c']):
flag = True # Found broken reference
try: # Pandoc >= 1.16
s1 = value[i]['c'][1][0]['c'] # Get the first half of the ref
except TypeError: # Pandoc < 1.16
s1 = value[i]['c'][0][0]['c'] # Get the first half of the ref
s2 = value[i+1]['c'] # Get the second half of the ref
ref = '@fig' + s2[:s2.index('}')] # Form the reference
prefix = s1[:s1.index('{@fig')] # Get the prefix
suffix = s2[s2.index('}')+1:] # Get the suffix
# We need to be careful with the prefix string because it might be
# part of another broken reference. Simply put it back into the
# stream and repeat the preprocess() call.
if i > 0 and value[i-1]['t'] == 'Str':
value[i-1]['c'] = value[i-1]['c'] + prefix
value[i] = None
else:
value[i] = Str(prefix)
# Put fixed reference in as a citation that can be processed
value[i+1] = Cite(
[{"citationId":ref[1:],
"citationPrefix":[],
"citationSuffix":[Str(suffix)],
"citationNoteNum":0,
"citationMode":{"t":"AuthorInText", "c":[]},
"citationHash":0}],
[Str(ref)])
if flag:
return [v for v in value if v is not None]
def is_braced_ref(i, value):
"""Returns true if a reference is braced; otherwise False."""
return is_ref(value[i]['t'], value[i]['c']) \
and value[i-1]['t'] == 'Str' and value[i+1]['t'] == 'Str' \
and value[i-1]['c'].endswith('{') and value[i+1]['c'].startswith('}')
def remove_braces(value):
"""Search for references and remove curly braces around them."""
flag = False
for i in range(len(value)-1)[1:]:
if is_braced_ref(i, value):
flag = True # Found reference
# Remove the braces
value[i-1]['c'] = value[i-1]['c'][:-1]
value[i+1]['c'] = value[i+1]['c'][1:]
return flag
# pylint: disable=unused-argument
def preprocess(key, value, fmt, meta):
"""Preprocesses to correct for problems."""
if key in ('Para', 'Plain'):
while True:
|
if key == 'Para':
return Para(value)
else:
return Plain(value)
# pylint: disable=unused-argument
def replace_attrimages(key, value, fmt, meta):
"""Replaces attributed images while storing reference labels."""
if is_attrimage(key, value):
# Parse the image
attrs, caption, target, label = parse_attrimage(value)
# Bail out if the label does not conform
if not label or not LABEL_PATTERN.match(label):
return None
# Save the reference
references[label] = len(references) + 1
# Adjust caption depending on the output format
if fmt == 'latex':
caption = list(caption) + [RawInline('tex', r'\label{%s}'%label)]
else:
caption = ast('Figure %d. '%references[label]) + list(caption)
# Required for pandoc to process the image
target[1] = "fig:"
# Return the replacement
if len(value[0]['c']) == 2: # Old pandoc < 1.16
img = Image(caption, target)
else: # New pandoc >= 1.16
assert len(value[0]['c']) == 3
img = AttrImage(attrs, caption, target)
if fmt in ('html', 'html5'):
anchor = RawInline('html', '<a name="%s"></a>'%label)
return [Plain([anchor]), Para([img])]
else:
return Para([img])
# pylint: disable=unused-argument
def replace_refs(key, value, fmt, meta):
"""Replaces references to labelled images."""
# Remove braces around references
if key in ('Para', 'Plain'):
if remove_braces(value):
if key == 'Para':
return Para(value)
else:
return Plain(value)
# Replace references
if is_ref(key, value):
prefix, label, suffix = parse_ref(value)
# The replacement depends on the output format
if fmt == 'latex':
return prefix + [RawInline('tex', r'\ref{%s}'%label)] + suffix
elif fmt in ('html', 'html5'):
link = '<a href="#%s">%s</a>' % (label, references[label])
return prefix + [RawInline('html', link)] + suffix
else:
return prefix + [Str('%d'%references[label])] + suffix
def main():
"""Filters the document AST."""
# Get the output format, document and metadata
fmt = sys.argv[1] if len(sys.argv) > 1 else ''
doc = pandocfilters.json.loads(STDIN.read())
meta = doc[0]['unMeta']
# Replace attributed images and references in the AST
altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
[preprocess, replace_attrimages, replace_refs],
doc)
# Dump the results
pandocfilters.json.dump(altered, STDOUT)
# Flush stdout
STDOUT.flush()
if __name__ == '__main__':
main()
| newvalue = repair_broken_refs(value)
if newvalue:
value = newvalue
else:
break | conditional_block |
pandoc_fignos.py | #! /usr/bin/env python
"""pandoc-fignos: a pandoc filter that inserts figure nos. and refs."""
# Copyright 2015, 2016 Thomas J. Duck.
# All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# OVERVIEW
#
# The basic idea is to scan the AST two times in order to:
#
# 1. Insert text for the figure number in each figure caption.
# For LaTeX, insert \label{...} instead. The figure labels
# and associated figure numbers are stored in the global
# references tracker.
#
# 2. Replace each reference with a figure number. For LaTeX,
# replace with \ref{...} instead.
#
# There is also an initial scan to do some preprocessing.
import re
import functools
import itertools
import io
import sys
# pylint: disable=import-error
import pandocfilters
from pandocfilters import stringify, walk
from pandocfilters import RawInline, Str, Space, Para, Plain, Cite, elt
from pandocattributes import PandocAttributes
# Create our own pandoc image primitives to accommodate different pandoc
# versions.
# pylint: disable=invalid-name
Image = elt('Image', 2) # Pandoc < 1.16
AttrImage = elt('Image', 3) # Pandoc >= 1.16
# Patterns for matching labels and references
LABEL_PATTERN = re.compile(r'(fig:[\w/-]*)(.*)')
REF_PATTERN = re.compile(r'@(fig:[\w/-]+)')
# Detect python 3
PY3 = sys.version_info > (3,)
# Pandoc uses UTF-8 for both input and output; so must we
if PY3: # Force utf-8 decoding (decoding of input streams is automatic in py3)
STDIN = io.TextIOWrapper(sys.stdin.buffer, 'utf-8', 'strict')
STDOUT = io.TextIOWrapper(sys.stdout.buffer, 'utf-8', 'strict')
else: # No decoding; utf-8-encoded strings in means the same out
STDIN = sys.stdin
STDOUT = sys.stdout
# pylint: disable=invalid-name
references = {} # Global references tracker
def is_attrimage(key, value):
"""True if this is an attributed image; False otherwise."""
try:
if key == 'Para' and value[0]['t'] == 'Image':
# Old pandoc < 1.16
if len(value[0]['c']) == 2:
s = stringify(value[1:]).strip()
if s.startswith('{') and s.endswith('}'):
return True
else:
return False
# New pandoc >= 1.16
else:
assert len(value[0]['c']) == 3
return True # Pandoc >= 1.16 has image attributes by default
# pylint: disable=bare-except
except:
return False
def parse_attrimage(value):
"""Parses an attributed image."""
if len(value[0]['c']) == 2: # Old pandoc < 1.16
attrs, (caption, target) = None, value[0]['c']
s = stringify(value[1:]).strip() # The attribute string
# Extract label from attributes (label, classes, kvs)
label = PandocAttributes(s, 'markdown').to_pandoc()[0]
if label == 'fig:': # Make up a unique description
label = label + '__'+str(hash(target[0]))+'__'
return attrs, caption, target, label
else: # New pandoc >= 1.16
assert len(value[0]['c']) == 3
attrs, caption, target = value[0]['c']
s = stringify(value[1:]).strip() # The attribute string
# Extract label from attributes
label = attrs[0]
if label == 'fig:': # Make up a unique description
label = label + '__'+str(hash(target[0]))+'__'
return attrs, caption, target, label
def is_ref(key, value):
"""True if this is a figure reference; False otherwise."""
return key == 'Cite' and REF_PATTERN.match(value[1][0]['c']) and \
parse_ref(value)[1] in references
def parse_ref(value):
"""Parses a figure reference."""
prefix = value[0][0]['citationPrefix']
label = REF_PATTERN.match(value[1][0]['c']).groups()[0]
suffix = value[0][0]['citationSuffix']
return prefix, label, suffix
def ast(string):
"""Returns an AST representation of the string."""
toks = [Str(tok) for tok in string.split()]
spaces = [Space()]*len(toks)
ret = list(itertools.chain(*zip(toks, spaces)))
if string[0] == ' ':
ret = [Space()] + ret
return ret if string[-1] == ' ' else ret[:-1]
def is_broken_ref(key1, value1, key2, value2):
"""True if this is a broken link; False otherwise."""
try: # Pandoc >= 1.16
return key1 == 'Link' and value1[1][0]['t'] == 'Str' and \
value1[1][0]['c'].endswith('{@fig') \
and key2 == 'Str' and '}' in value2
except TypeError: # Pandoc < 1.16
return key1 == 'Link' and value1[0][0]['t'] == 'Str' and \
value1[0][0]['c'].endswith('{@fig') \
and key2 == 'Str' and '}' in value2
def repair_broken_refs(value):
"""Repairs references broken by pandoc's --autolink_bare_uris."""
# autolink_bare_uris splits {@fig:label} at the ':' and treats
# the first half as if it is a mailto url and the second half as a string.
# Let's replace this mess with Cite and Str elements that we normally
# get.
flag = False
for i in range(len(value)-1):
if value[i] == None:
continue
if is_broken_ref(value[i]['t'], value[i]['c'],
value[i+1]['t'], value[i+1]['c']):
flag = True # Found broken reference
try: # Pandoc >= 1.16
s1 = value[i]['c'][1][0]['c'] # Get the first half of the ref
except TypeError: # Pandoc < 1.16
s1 = value[i]['c'][0][0]['c'] # Get the first half of the ref
s2 = value[i+1]['c'] # Get the second half of the ref
ref = '@fig' + s2[:s2.index('}')] # Form the reference
prefix = s1[:s1.index('{@fig')] # Get the prefix
suffix = s2[s2.index('}')+1:] # Get the suffix
# We need to be careful with the prefix string because it might be
# part of another broken reference. Simply put it back into the
# stream and repeat the preprocess() call.
if i > 0 and value[i-1]['t'] == 'Str':
value[i-1]['c'] = value[i-1]['c'] + prefix
value[i] = None
else:
value[i] = Str(prefix)
# Put fixed reference in as a citation that can be processed
value[i+1] = Cite(
[{"citationId":ref[1:],
"citationPrefix":[],
"citationSuffix":[Str(suffix)],
"citationNoteNum":0,
"citationMode":{"t":"AuthorInText", "c":[]},
"citationHash":0}],
[Str(ref)])
if flag:
return [v for v in value if v is not None]
def is_braced_ref(i, value):
"""Returns true if a reference is braced; otherwise False."""
return is_ref(value[i]['t'], value[i]['c']) \
and value[i-1]['t'] == 'Str' and value[i+1]['t'] == 'Str' \
and value[i-1]['c'].endswith('{') and value[i+1]['c'].startswith('}')
def remove_braces(value):
"""Search for references and remove curly braces around them."""
flag = False
for i in range(len(value)-1)[1:]:
if is_braced_ref(i, value):
flag = True # Found reference
# Remove the braces
value[i-1]['c'] = value[i-1]['c'][:-1]
value[i+1]['c'] = value[i+1]['c'][1:]
return flag
# pylint: disable=unused-argument
def | (key, value, fmt, meta):
"""Preprocesses to correct for problems."""
if key in ('Para', 'Plain'):
while True:
newvalue = repair_broken_refs(value)
if newvalue:
value = newvalue
else:
break
if key == 'Para':
return Para(value)
else:
return Plain(value)
# pylint: disable=unused-argument
def replace_attrimages(key, value, fmt, meta):
"""Replaces attributed images while storing reference labels."""
if is_attrimage(key, value):
# Parse the image
attrs, caption, target, label = parse_attrimage(value)
# Bail out if the label does not conform
if not label or not LABEL_PATTERN.match(label):
return None
# Save the reference
references[label] = len(references) + 1
# Adjust caption depending on the output format
if fmt == 'latex':
caption = list(caption) + [RawInline('tex', r'\label{%s}'%label)]
else:
caption = ast('Figure %d. '%references[label]) + list(caption)
# Required for pandoc to process the image
target[1] = "fig:"
# Return the replacement
if len(value[0]['c']) == 2: # Old pandoc < 1.16
img = Image(caption, target)
else: # New pandoc >= 1.16
assert len(value[0]['c']) == 3
img = AttrImage(attrs, caption, target)
if fmt in ('html', 'html5'):
anchor = RawInline('html', '<a name="%s"></a>'%label)
return [Plain([anchor]), Para([img])]
else:
return Para([img])
# pylint: disable=unused-argument
def replace_refs(key, value, fmt, meta):
"""Replaces references to labelled images."""
# Remove braces around references
if key in ('Para', 'Plain'):
if remove_braces(value):
if key == 'Para':
return Para(value)
else:
return Plain(value)
# Replace references
if is_ref(key, value):
prefix, label, suffix = parse_ref(value)
# The replacement depends on the output format
if fmt == 'latex':
return prefix + [RawInline('tex', r'\ref{%s}'%label)] + suffix
elif fmt in ('html', 'html5'):
link = '<a href="#%s">%s</a>' % (label, references[label])
return prefix + [RawInline('html', link)] + suffix
else:
return prefix + [Str('%d'%references[label])] + suffix
def main():
"""Filters the document AST."""
# Get the output format, document and metadata
fmt = sys.argv[1] if len(sys.argv) > 1 else ''
doc = pandocfilters.json.loads(STDIN.read())
meta = doc[0]['unMeta']
# Replace attributed images and references in the AST
altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
[preprocess, replace_attrimages, replace_refs],
doc)
# Dump the results
pandocfilters.json.dump(altered, STDOUT)
# Flush stdout
STDOUT.flush()
if __name__ == '__main__':
main()
| preprocess | identifier_name |
legendre.rs | //compute Jacobi symbol of a number
use super::Mod;
use std::collections::HashSet;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Jacobi {
Value(i8), // -1, 0, 1
Frac{pos: bool, numer: u64, denom: u64},
}
impl Jacobi {
fn from_val(a: i8) -> Jacobi {
Jacobi::Value(a)
}
fn from_frac(s: bool, a: u64, b: u64) -> Jacobi {
Jacobi::Frac{pos: s, numer: a, denom: b}
}
fn print(&self) {
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
println!(" {} J( {} / {} )",
if p { '+' } else { '-' }, n, d);
} else if let &Jacobi::Value(v) = self {
println!(" {} ", v)
}
}
fn reduce(&self) -> Jacobi {
//let reductions = vec![Jacobi::modulo, Jacobi::two_numer, Jacobi::reciprocal];
let a = &Jacobi::modulo;
let b = &Jacobi::two_numer;
let c = &Jacobi::reciprocal;;
let mut reductions: Vec<&Fn(&Jacobi) -> Option<Jacobi>> = Vec::new();
reductions.push(a);
reductions.push(b);
reductions.push(c);
let mut attempts: HashSet<Jacobi> = HashSet::new();
loop {
}
Jacobi::Value(0)
}
//methods of reducing:
fn modulo(&self) -> Option<Jacobi> {
// if a≡b(mod p), L(a/p) = L(b/p)
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
Some(Jacobi::from_frac(p, n.modulo(d), d)) | }
}
fn two_numer(&self) -> Option<Jacobi> {
// J((ab)/n) = J(a/n)*J(b/n)
// J(2/n) = { 1 iff n≡±1(mod 8), -1 iff n≡ٍ±3(mod 8) }
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
let z = n.trailing_zeros();
let n_ = n / 2u64.pow(z);
let rem = d.modulo(8);
let sign: i8 = {
if rem == 1 || rem == 7 { 1 }
else if rem == 3 || rem == 5 { -1 }
else { return None }
};
let mut acc_sign = sign.pow(z);
if !p { acc_sign *= -1; }
Some(Jacobi::from_frac(acc_sign == 1, n, d))
} else {
None
}
}
fn reciprocal(&self) -> Option<Jacobi> {
// J(m/n) = {-J(n/m) if m≡n≡3(mod 4)
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
if n.modulo(4) == 3 && d.modulo(4) == 3 {
Some(Jacobi::from_frac(!p, d, n))
} else {
None
}
} else {
None
}
}
} | } else {
None | random_line_split |
legendre.rs | //compute Jacobi symbol of a number
use super::Mod;
use std::collections::HashSet;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Jacobi {
Value(i8), // -1, 0, 1
Frac{pos: bool, numer: u64, denom: u64},
}
impl Jacobi {
fn from_val(a: i8) -> Jacobi {
Jacobi::Value(a)
}
fn | (s: bool, a: u64, b: u64) -> Jacobi {
Jacobi::Frac{pos: s, numer: a, denom: b}
}
fn print(&self) {
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
println!(" {} J( {} / {} )",
if p { '+' } else { '-' }, n, d);
} else if let &Jacobi::Value(v) = self {
println!(" {} ", v)
}
}
fn reduce(&self) -> Jacobi {
//let reductions = vec![Jacobi::modulo, Jacobi::two_numer, Jacobi::reciprocal];
let a = &Jacobi::modulo;
let b = &Jacobi::two_numer;
let c = &Jacobi::reciprocal;;
let mut reductions: Vec<&Fn(&Jacobi) -> Option<Jacobi>> = Vec::new();
reductions.push(a);
reductions.push(b);
reductions.push(c);
let mut attempts: HashSet<Jacobi> = HashSet::new();
loop {
}
Jacobi::Value(0)
}
//methods of reducing:
fn modulo(&self) -> Option<Jacobi> {
// if a≡b(mod p), L(a/p) = L(b/p)
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
Some(Jacobi::from_frac(p, n.modulo(d), d))
} else {
None
}
}
fn two_numer(&self) -> Option<Jacobi> {
// J((ab)/n) = J(a/n)*J(b/n)
// J(2/n) = { 1 iff n≡±1(mod 8), -1 iff n≡ٍ±3(mod 8) }
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
let z = n.trailing_zeros();
let n_ = n / 2u64.pow(z);
let rem = d.modulo(8);
let sign: i8 = {
if rem == 1 || rem == 7 { 1 }
else if rem == 3 || rem == 5 { -1 }
else { return None }
};
let mut acc_sign = sign.pow(z);
if !p { acc_sign *= -1; }
Some(Jacobi::from_frac(acc_sign == 1, n, d))
} else {
None
}
}
fn reciprocal(&self) -> Option<Jacobi> {
// J(m/n) = {-J(n/m) if m≡n≡3(mod 4)
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
if n.modulo(4) == 3 && d.modulo(4) == 3 {
Some(Jacobi::from_frac(!p, d, n))
} else {
None
}
} else {
None
}
}
}
| from_frac | identifier_name |
legendre.rs | //compute Jacobi symbol of a number
use super::Mod;
use std::collections::HashSet;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Jacobi {
Value(i8), // -1, 0, 1
Frac{pos: bool, numer: u64, denom: u64},
}
impl Jacobi {
fn from_val(a: i8) -> Jacobi {
Jacobi::Value(a)
}
fn from_frac(s: bool, a: u64, b: u64) -> Jacobi {
Jacobi::Frac{pos: s, numer: a, denom: b}
}
fn print(&self) {
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
println!(" {} J( {} / {} )",
if p { '+' } else { '-' }, n, d);
} else if let &Jacobi::Value(v) = self {
println!(" {} ", v)
}
}
fn reduce(&self) -> Jacobi {
//let reductions = vec![Jacobi::modulo, Jacobi::two_numer, Jacobi::reciprocal];
let a = &Jacobi::modulo;
let b = &Jacobi::two_numer;
let c = &Jacobi::reciprocal;;
let mut reductions: Vec<&Fn(&Jacobi) -> Option<Jacobi>> = Vec::new();
reductions.push(a);
reductions.push(b);
reductions.push(c);
let mut attempts: HashSet<Jacobi> = HashSet::new();
loop {
}
Jacobi::Value(0)
}
//methods of reducing:
fn modulo(&self) -> Option<Jacobi> {
// if a≡b(mod p), L(a/p) = L(b/p)
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
Some(Jacobi::from_frac(p, n.modulo(d), d))
} else {
None
}
}
fn two_numer(&self) -> Option<Jacobi> {
// J((ab)/n) = J(a/n)*J(b/n)
// J(2/n) = { 1 iff n≡±1(mod 8), -1 iff n≡ٍ±3(mod 8) }
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
let z = n.trailing_zeros();
let n_ = n / 2u64.pow(z);
let rem = d.modulo(8);
let sign: i8 = {
if rem == 1 || rem == 7 { 1 }
else if rem == 3 || rem == 5 { -1 }
else { return None }
};
let mut acc_sign = sign.pow(z);
if !p { acc_sign *= -1; }
Some(Jacobi::from_frac(acc_sign == 1, n, d))
} else {
None
}
}
fn reciprocal(&self) -> Option<Jacobi> {
// J(m/n) = {-J(n/m) if m≡n≡3(mod 4)
if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self {
| None
}
}
}
| if n.modulo(4) == 3 && d.modulo(4) == 3 {
Some(Jacobi::from_frac(!p, d, n))
} else {
None
}
} else {
| conditional_block |
issue-13698.rs | // Copyright 2015 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 | // except according to those terms.
// aux-build:issue-13698.rs
// ignore-cross-compile
extern crate issue_13698;
pub struct Foo;
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn foo'
impl issue_13698::Foo for Foo {}
pub trait Bar {
#[doc(hidden)]
fn bar(&self) {}
}
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn bar'
impl Bar for Foo {} | // option. This file may not be copied, modified, or distributed | random_line_split |
issue-13698.rs | // Copyright 2015 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.
// aux-build:issue-13698.rs
// ignore-cross-compile
extern crate issue_13698;
pub struct Foo;
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn foo'
impl issue_13698::Foo for Foo {}
pub trait Bar {
#[doc(hidden)]
fn bar(&self) |
}
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn bar'
impl Bar for Foo {}
| {} | identifier_body |
issue-13698.rs | // Copyright 2015 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.
// aux-build:issue-13698.rs
// ignore-cross-compile
extern crate issue_13698;
pub struct | ;
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn foo'
impl issue_13698::Foo for Foo {}
pub trait Bar {
#[doc(hidden)]
fn bar(&self) {}
}
// @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn bar'
impl Bar for Foo {}
| Foo | identifier_name |
primitives_OBSERVED.py | from astrodata.ReductionObjects import PrimitiveSet
class OBSERVEDPrimitives(PrimitiveSet):
astrotype = "OBSERVED"
def init(self, rc):
print "OBSERVEDPrimitives.init(rc)"
return
def typeSpecificPrimitive(self, rc):
print "OBSERVEDPrimitives::typeSpecificPrimitive()"
def mark(self, rc):
|
def unmark(self, rc):
for ad in rc.get_inputs_as_astrodata():
if ad.is_type("UNMARKED"):
print "OBSERVEDPrimitives::unmark(%s) not marked" % ad.filename
else:
ad.phu_set_key_value("S_MARKED", None)
rc.report_output(ad)
yield rc
| for ad in rc.get_inputs_as_astrodata():
if ad.is_type("MARKED"):
print "OBSERVEDPrimitives::mark(%s) already marked" % ad.filename
else:
ad.phu_set_key_value("S_MARKED", "TRUE")
rc.report_output(ad)
yield rc | identifier_body |
primitives_OBSERVED.py | from astrodata.ReductionObjects import PrimitiveSet
class OBSERVEDPrimitives(PrimitiveSet):
astrotype = "OBSERVED"
def init(self, rc):
print "OBSERVEDPrimitives.init(rc)"
return
def typeSpecificPrimitive(self, rc):
print "OBSERVEDPrimitives::typeSpecificPrimitive()"
def mark(self, rc):
for ad in rc.get_inputs_as_astrodata():
if ad.is_type("MARKED"):
print "OBSERVEDPrimitives::mark(%s) already marked" % ad.filename
else:
ad.phu_set_key_value("S_MARKED", "TRUE")
rc.report_output(ad)
yield rc
def unmark(self, rc):
for ad in rc.get_inputs_as_astrodata():
if ad.is_type("UNMARKED"):
|
else:
ad.phu_set_key_value("S_MARKED", None)
rc.report_output(ad)
yield rc
| print "OBSERVEDPrimitives::unmark(%s) not marked" % ad.filename | conditional_block |
primitives_OBSERVED.py | from astrodata.ReductionObjects import PrimitiveSet
class | (PrimitiveSet):
astrotype = "OBSERVED"
def init(self, rc):
print "OBSERVEDPrimitives.init(rc)"
return
def typeSpecificPrimitive(self, rc):
print "OBSERVEDPrimitives::typeSpecificPrimitive()"
def mark(self, rc):
for ad in rc.get_inputs_as_astrodata():
if ad.is_type("MARKED"):
print "OBSERVEDPrimitives::mark(%s) already marked" % ad.filename
else:
ad.phu_set_key_value("S_MARKED", "TRUE")
rc.report_output(ad)
yield rc
def unmark(self, rc):
for ad in rc.get_inputs_as_astrodata():
if ad.is_type("UNMARKED"):
print "OBSERVEDPrimitives::unmark(%s) not marked" % ad.filename
else:
ad.phu_set_key_value("S_MARKED", None)
rc.report_output(ad)
yield rc
| OBSERVEDPrimitives | identifier_name |
primitives_OBSERVED.py | from astrodata.ReductionObjects import PrimitiveSet
class OBSERVEDPrimitives(PrimitiveSet):
astrotype = "OBSERVED"
def init(self, rc): | def mark(self, rc):
for ad in rc.get_inputs_as_astrodata():
if ad.is_type("MARKED"):
print "OBSERVEDPrimitives::mark(%s) already marked" % ad.filename
else:
ad.phu_set_key_value("S_MARKED", "TRUE")
rc.report_output(ad)
yield rc
def unmark(self, rc):
for ad in rc.get_inputs_as_astrodata():
if ad.is_type("UNMARKED"):
print "OBSERVEDPrimitives::unmark(%s) not marked" % ad.filename
else:
ad.phu_set_key_value("S_MARKED", None)
rc.report_output(ad)
yield rc | print "OBSERVEDPrimitives.init(rc)"
return
def typeSpecificPrimitive(self, rc):
print "OBSERVEDPrimitives::typeSpecificPrimitive()"
| random_line_split |
index.js | //inicializamos eventos y procesos desde el DOM
$(document).ready(function(){
IniciarEventos();}
);
function IniciarEventos(){
$('#datetimepicker1').datetimepicker({locale:'es',format: "DD/MM/YYYY"});
$('#datetimepicker2').datetimepicker({locale:'es',format: "DD/MM/YYYY"});
fechaactual('fecdesde')
fechaactual('fechasta')
reloadList(rlink)
$('#viewfaults').click(function(){
//call API changed state
reloadList(rlink)
})
$('#modalview').on('hidden.bs.modal', function () {
$('#content').empty();
$(this).data('bs.modal', null); //<---- empty() to clear the modal
})
}
function reloadList(link){
serialize=$('#filter').serialize()
$('#cargandodatos').show(1)
$.post(link,serialize,
function(data) {
$('#listfaultcars').html(data);
var divPaginationLinks = '#listfaultcars'+" .pagination a,.sort a";
$(divPaginationLinks).click(function(){
var thisHref = $(this).attr("href");
reloadList(thisHref);
//recarmamos el proceso de carga
return false;
});
}).always(function() {
$('#cargandodatos').hide(1)
});
}
function changestate(id) |
function getubication(lat,lng){
$('#modalview').modal({
show: true,
remote: '/faultcars/getubicationmaps/'+lat+'/'+lng
});
return false
}
| {
if(typeof(id) != 'undefined'){
$.ajax({url:'/faultcars/faultcarschangedstatenj.json',
type:'post',
dataType:'json',
headers: {
'Security-Access-PublicToken':'A33esaSP9skSjasdSfFSssEwS2IksSZxPlA4asSJ4GEW4S'
},
data:{id:id,state:1},
success: function(data){
$.each( data, function( key, val ) {
if(val.error != ''){
alert('Error: '+val.error)
}else{
$('#faultend'+id).hide(1)
}
});
}
})
}
} | identifier_body |
index.js | //inicializamos eventos y procesos desde el DOM
$(document).ready(function(){
IniciarEventos();}
);
function IniciarEventos(){
$('#datetimepicker1').datetimepicker({locale:'es',format: "DD/MM/YYYY"});
$('#datetimepicker2').datetimepicker({locale:'es',format: "DD/MM/YYYY"});
fechaactual('fecdesde')
fechaactual('fechasta')
reloadList(rlink)
$('#viewfaults').click(function(){
//call API changed state
reloadList(rlink)
})
$('#modalview').on('hidden.bs.modal', function () {
$('#content').empty();
$(this).data('bs.modal', null); //<---- empty() to clear the modal
})
}
function reloadList(link){
serialize=$('#filter').serialize()
$('#cargandodatos').show(1)
$.post(link,serialize,
function(data) {
$('#listfaultcars').html(data);
var divPaginationLinks = '#listfaultcars'+" .pagination a,.sort a";
$(divPaginationLinks).click(function(){
var thisHref = $(this).attr("href");
reloadList(thisHref);
//recarmamos el proceso de carga
return false;
});
}).always(function() {
$('#cargandodatos').hide(1)
});
}
function changestate(id){
if(typeof(id) != 'undefined'){
$.ajax({url:'/faultcars/faultcarschangedstatenj.json',
type:'post',
dataType:'json',
headers: {
'Security-Access-PublicToken':'A33esaSP9skSjasdSfFSssEwS2IksSZxPlA4asSJ4GEW4S'
},
data:{id:id,state:1},
success: function(data){
$.each( data, function( key, val ) {
if(val.error != ''){
alert('Error: '+val.error)
}else{
$('#faultend'+id).hide(1)
}
});
}
})
}
}
function | (lat,lng){
$('#modalview').modal({
show: true,
remote: '/faultcars/getubicationmaps/'+lat+'/'+lng
});
return false
}
| getubication | identifier_name |
index.js | //inicializamos eventos y procesos desde el DOM
$(document).ready(function(){
IniciarEventos();}
);
function IniciarEventos(){
$('#datetimepicker1').datetimepicker({locale:'es',format: "DD/MM/YYYY"});
$('#datetimepicker2').datetimepicker({locale:'es',format: "DD/MM/YYYY"});
fechaactual('fecdesde')
fechaactual('fechasta')
reloadList(rlink)
$('#viewfaults').click(function(){
//call API changed state
reloadList(rlink)
})
$('#modalview').on('hidden.bs.modal', function () {
$('#content').empty();
$(this).data('bs.modal', null); //<---- empty() to clear the modal
})
}
function reloadList(link){
serialize=$('#filter').serialize()
$('#cargandodatos').show(1)
$.post(link,serialize,
function(data) {
$('#listfaultcars').html(data);
var divPaginationLinks = '#listfaultcars'+" .pagination a,.sort a";
$(divPaginationLinks).click(function(){
var thisHref = $(this).attr("href");
reloadList(thisHref);
//recarmamos el proceso de carga
return false;
});
}).always(function() {
$('#cargandodatos').hide(1)
});
}
function changestate(id){
if(typeof(id) != 'undefined'){
$.ajax({url:'/faultcars/faultcarschangedstatenj.json',
type:'post',
dataType:'json',
headers: {
'Security-Access-PublicToken':'A33esaSP9skSjasdSfFSssEwS2IksSZxPlA4asSJ4GEW4S'
},
data:{id:id,state:1}, | if(val.error != ''){
alert('Error: '+val.error)
}else{
$('#faultend'+id).hide(1)
}
});
}
})
}
}
function getubication(lat,lng){
$('#modalview').modal({
show: true,
remote: '/faultcars/getubicationmaps/'+lat+'/'+lng
});
return false
} | success: function(data){
$.each( data, function( key, val ) { | random_line_split |
index.js | //inicializamos eventos y procesos desde el DOM
$(document).ready(function(){
IniciarEventos();}
);
function IniciarEventos(){
$('#datetimepicker1').datetimepicker({locale:'es',format: "DD/MM/YYYY"});
$('#datetimepicker2').datetimepicker({locale:'es',format: "DD/MM/YYYY"});
fechaactual('fecdesde')
fechaactual('fechasta')
reloadList(rlink)
$('#viewfaults').click(function(){
//call API changed state
reloadList(rlink)
})
$('#modalview').on('hidden.bs.modal', function () {
$('#content').empty();
$(this).data('bs.modal', null); //<---- empty() to clear the modal
})
}
function reloadList(link){
serialize=$('#filter').serialize()
$('#cargandodatos').show(1)
$.post(link,serialize,
function(data) {
$('#listfaultcars').html(data);
var divPaginationLinks = '#listfaultcars'+" .pagination a,.sort a";
$(divPaginationLinks).click(function(){
var thisHref = $(this).attr("href");
reloadList(thisHref);
//recarmamos el proceso de carga
return false;
});
}).always(function() {
$('#cargandodatos').hide(1)
});
}
function changestate(id){
if(typeof(id) != 'undefined') |
}
function getubication(lat,lng){
$('#modalview').modal({
show: true,
remote: '/faultcars/getubicationmaps/'+lat+'/'+lng
});
return false
}
| {
$.ajax({url:'/faultcars/faultcarschangedstatenj.json',
type:'post',
dataType:'json',
headers: {
'Security-Access-PublicToken':'A33esaSP9skSjasdSfFSssEwS2IksSZxPlA4asSJ4GEW4S'
},
data:{id:id,state:1},
success: function(data){
$.each( data, function( key, val ) {
if(val.error != ''){
alert('Error: '+val.error)
}else{
$('#faultend'+id).hide(1)
}
});
}
})
} | conditional_block |
tests.py | """Unittests that do not require the server to be running an common tests of responses.
The TestCase here just calls the functions that provide the logic to the ws views with DummyRequest
objects to mock a real request.
The functions starting with `check_...` are called with UnitTest.TestCase instance as the first
arg and the response. These functions are used within the unit tests in this file, but also
in the `ws-tests` calls that perform the tests through http.
"""
import os
import unittest
from pyramid import testing
from phylesystem_api.utility import fill_app_settings, umbrella_from_request
from phylesystem_api.views import import_nexson_from_crossref_metadata
def get_app_settings_for_testing(settings):
"""Fills the settings of a DummyRequest, with info from the development.ini
This allows the dummy requests to mock a real request wrt configuration-dependent settings."""
from peyotl.utility.imports import SafeConfigParser
cfg = SafeConfigParser()
devini_path = os.path.abspath(os.path.join('..', 'development.ini'))
if not os.path.isfile(devini_path):
raise RuntimeError('Expecting a INI file at "{}" to run tests'.format(devini_path))
cfg.read(devini_path)
settings['repo_parent'] = cfg.get('app:main', 'repo_parent')
fill_app_settings(settings=settings)
def gen_versioned_dummy_request():
"""Adds a version number (3) to the request to mimic the matching based on URL in the real app.
"""
req = testing.DummyRequest()
get_app_settings_for_testing(req.registry.settings)
req.matchdict['api_version'] = 'v3'
return req
def check_index_response(test_case, response):
"""Verifies the existene of expected keys in the response to an index call.
'documentation_url', 'description', and 'source_url' keys must be in the response.
"""
for k in ['documentation_url', 'description', 'source_url']:
|
def check_render_markdown_response(test_case, response):
"""Check of `response` to a `render_markdown` call."""
expected = '<p>hi from <a href="http://phylo.bio.ku.edu" target="_blank">' \
'http://phylo.bio.ku.edu</a> and ' \
'<a href="https://github.com/orgs/OpenTreeOfLife/dashboard" target="_blank">' \
'https://github.com/orgs/OpenTreeOfLife/dashboard</a></p>'
test_case.assertEquals(response.body, expected)
def check_study_list_and_config_response(test_case,
sl_response,
config_response,
from_generic_config):
"""Checks of responses from study_list, config, and the generic config calls."""
nsis = sum([i['number of documents'] for i in config_response['shards']])
test_case.assertEquals(nsis, len(sl_response))
test_case.assertEquals(from_generic_config, config_response)
def check_unmerged_response(test_case, ub):
"""Check of `ub` response from an `unmerged_branches` call"""
test_case.assertTrue('master' not in ub)
def check_config_response(test_case, cfg):
"""Check of `cfg` response from a `config` call"""
test_case.assertSetEqual(set(cfg.keys()), {"initialization", "shards", "number_of_shards"})
def check_external_url_response(test_case, doc_id, resp):
"""Simple check of an `external_url` `resp` response for `doc_id`.
`doc_id` and `url` fields of the response are checked."""
test_case.assertEquals(resp.get('doc_id'), doc_id)
test_case.assertTrue(resp.get('url', '').endswith('{}.json'.format(doc_id)))
def check_push_failure_response(test_case, resp):
"""Check of the `resp` response of a `push_failure` method call to verify it has the right keys.
"""
test_case.assertSetEqual(set(resp.keys()), {"doc_type", "errors", "pushes_succeeding"})
test_case.assertTrue(resp["pushes_succeeding"])
render_test_input = 'hi from <a href="http://phylo.bio.ku.edu" target="new">' \
'http://phylo.bio.ku.edu</a> and ' \
'https://github.com/orgs/OpenTreeOfLife/dashboard'
class ViewTests(unittest.TestCase):
"""UnitTest of the functions that underlie the ws views."""
def setUp(self):
"""Calls pyramid testing.setUp"""
self.config = testing.setUp()
def tearDown(self):
"""Calls pyramid testing.tearDown"""
testing.tearDown()
def test_index(self):
"""Test of index view"""
request = gen_versioned_dummy_request()
from phylesystem_api.views import index
check_index_response(self, index(request))
def test_render_markdown(self):
"""Test of render_markdown view"""
request = testing.DummyRequest(post={'src': render_test_input})
from phylesystem_api.views import render_markdown
check_render_markdown_response(self, render_markdown(request))
def test_study_list_and_config(self):
"""Test of study_list and phylesystem_config views"""
request = gen_versioned_dummy_request()
from phylesystem_api.views import study_list
sl = study_list(request)
request = gen_versioned_dummy_request()
from phylesystem_api.views import phylesystem_config
x = phylesystem_config(request)
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'study'
from phylesystem_api.views import generic_config
y = generic_config(request)
check_study_list_and_config_response(self, sl, x, y)
if not sl:
return
from phylesystem_api.views import external_url
doc_id = sl[0]
request.matchdict['doc_id'] = doc_id
e = external_url(request)
check_external_url_response(self, doc_id, e)
def test_unmerged(self):
"""Test of unmerged_branches view"""
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'study'
from phylesystem_api.views import unmerged_branches
check_unmerged_response(self, unmerged_branches(request))
def test_config(self):
"""Test of generic_config view"""
request = gen_versioned_dummy_request()
from phylesystem_api.views import phylesystem_config, generic_config
r2 = phylesystem_config(request)
check_config_response(self, r2)
request.matchdict['resource_type'] = 'study'
r = generic_config(request)
check_config_response(self, r)
self.assertDictEqual(r, r2)
request.matchdict['resource_type'] = 'amendment'
ra = generic_config(request)
check_config_response(self, ra)
self.assertNotEqual(ra, r)
def test_push_failure_state(self):
"""Test of push_failure view"""
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'collection'
from phylesystem_api.views import push_failure
pf = push_failure(request)
check_push_failure_response(self, pf)
def test_doi_import(self):
"""Make sure that fetching from DOI generates a valid study shell."""
doi = "10.3732/ajb.0800060"
document = import_nexson_from_crossref_metadata(doi=doi,
ref_string=None,
include_cc0=None)
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'study'
umbrella = umbrella_from_request(request)
errors = umbrella.validate_and_convert_doc(document, {})[1]
self.assertEquals(len(errors), 0)
if __name__ == '__main__':
unittest.main()
| test_case.assertIn(k, response) | conditional_block |
tests.py | """Unittests that do not require the server to be running an common tests of responses.
The TestCase here just calls the functions that provide the logic to the ws views with DummyRequest
objects to mock a real request.
The functions starting with `check_...` are called with UnitTest.TestCase instance as the first
arg and the response. These functions are used within the unit tests in this file, but also
in the `ws-tests` calls that perform the tests through http.
"""
import os
import unittest
from pyramid import testing
from phylesystem_api.utility import fill_app_settings, umbrella_from_request
from phylesystem_api.views import import_nexson_from_crossref_metadata
def get_app_settings_for_testing(settings):
"""Fills the settings of a DummyRequest, with info from the development.ini
This allows the dummy requests to mock a real request wrt configuration-dependent settings."""
from peyotl.utility.imports import SafeConfigParser
cfg = SafeConfigParser()
devini_path = os.path.abspath(os.path.join('..', 'development.ini'))
if not os.path.isfile(devini_path):
raise RuntimeError('Expecting a INI file at "{}" to run tests'.format(devini_path))
cfg.read(devini_path)
settings['repo_parent'] = cfg.get('app:main', 'repo_parent')
fill_app_settings(settings=settings)
def gen_versioned_dummy_request():
|
def check_index_response(test_case, response):
"""Verifies the existene of expected keys in the response to an index call.
'documentation_url', 'description', and 'source_url' keys must be in the response.
"""
for k in ['documentation_url', 'description', 'source_url']:
test_case.assertIn(k, response)
def check_render_markdown_response(test_case, response):
"""Check of `response` to a `render_markdown` call."""
expected = '<p>hi from <a href="http://phylo.bio.ku.edu" target="_blank">' \
'http://phylo.bio.ku.edu</a> and ' \
'<a href="https://github.com/orgs/OpenTreeOfLife/dashboard" target="_blank">' \
'https://github.com/orgs/OpenTreeOfLife/dashboard</a></p>'
test_case.assertEquals(response.body, expected)
def check_study_list_and_config_response(test_case,
sl_response,
config_response,
from_generic_config):
"""Checks of responses from study_list, config, and the generic config calls."""
nsis = sum([i['number of documents'] for i in config_response['shards']])
test_case.assertEquals(nsis, len(sl_response))
test_case.assertEquals(from_generic_config, config_response)
def check_unmerged_response(test_case, ub):
"""Check of `ub` response from an `unmerged_branches` call"""
test_case.assertTrue('master' not in ub)
def check_config_response(test_case, cfg):
"""Check of `cfg` response from a `config` call"""
test_case.assertSetEqual(set(cfg.keys()), {"initialization", "shards", "number_of_shards"})
def check_external_url_response(test_case, doc_id, resp):
"""Simple check of an `external_url` `resp` response for `doc_id`.
`doc_id` and `url` fields of the response are checked."""
test_case.assertEquals(resp.get('doc_id'), doc_id)
test_case.assertTrue(resp.get('url', '').endswith('{}.json'.format(doc_id)))
def check_push_failure_response(test_case, resp):
"""Check of the `resp` response of a `push_failure` method call to verify it has the right keys.
"""
test_case.assertSetEqual(set(resp.keys()), {"doc_type", "errors", "pushes_succeeding"})
test_case.assertTrue(resp["pushes_succeeding"])
render_test_input = 'hi from <a href="http://phylo.bio.ku.edu" target="new">' \
'http://phylo.bio.ku.edu</a> and ' \
'https://github.com/orgs/OpenTreeOfLife/dashboard'
class ViewTests(unittest.TestCase):
"""UnitTest of the functions that underlie the ws views."""
def setUp(self):
"""Calls pyramid testing.setUp"""
self.config = testing.setUp()
def tearDown(self):
"""Calls pyramid testing.tearDown"""
testing.tearDown()
def test_index(self):
"""Test of index view"""
request = gen_versioned_dummy_request()
from phylesystem_api.views import index
check_index_response(self, index(request))
def test_render_markdown(self):
"""Test of render_markdown view"""
request = testing.DummyRequest(post={'src': render_test_input})
from phylesystem_api.views import render_markdown
check_render_markdown_response(self, render_markdown(request))
def test_study_list_and_config(self):
"""Test of study_list and phylesystem_config views"""
request = gen_versioned_dummy_request()
from phylesystem_api.views import study_list
sl = study_list(request)
request = gen_versioned_dummy_request()
from phylesystem_api.views import phylesystem_config
x = phylesystem_config(request)
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'study'
from phylesystem_api.views import generic_config
y = generic_config(request)
check_study_list_and_config_response(self, sl, x, y)
if not sl:
return
from phylesystem_api.views import external_url
doc_id = sl[0]
request.matchdict['doc_id'] = doc_id
e = external_url(request)
check_external_url_response(self, doc_id, e)
def test_unmerged(self):
"""Test of unmerged_branches view"""
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'study'
from phylesystem_api.views import unmerged_branches
check_unmerged_response(self, unmerged_branches(request))
def test_config(self):
"""Test of generic_config view"""
request = gen_versioned_dummy_request()
from phylesystem_api.views import phylesystem_config, generic_config
r2 = phylesystem_config(request)
check_config_response(self, r2)
request.matchdict['resource_type'] = 'study'
r = generic_config(request)
check_config_response(self, r)
self.assertDictEqual(r, r2)
request.matchdict['resource_type'] = 'amendment'
ra = generic_config(request)
check_config_response(self, ra)
self.assertNotEqual(ra, r)
def test_push_failure_state(self):
"""Test of push_failure view"""
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'collection'
from phylesystem_api.views import push_failure
pf = push_failure(request)
check_push_failure_response(self, pf)
def test_doi_import(self):
"""Make sure that fetching from DOI generates a valid study shell."""
doi = "10.3732/ajb.0800060"
document = import_nexson_from_crossref_metadata(doi=doi,
ref_string=None,
include_cc0=None)
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'study'
umbrella = umbrella_from_request(request)
errors = umbrella.validate_and_convert_doc(document, {})[1]
self.assertEquals(len(errors), 0)
if __name__ == '__main__':
unittest.main()
| """Adds a version number (3) to the request to mimic the matching based on URL in the real app.
"""
req = testing.DummyRequest()
get_app_settings_for_testing(req.registry.settings)
req.matchdict['api_version'] = 'v3'
return req | identifier_body |
tests.py | """Unittests that do not require the server to be running an common tests of responses.
The TestCase here just calls the functions that provide the logic to the ws views with DummyRequest
objects to mock a real request.
The functions starting with `check_...` are called with UnitTest.TestCase instance as the first
arg and the response. These functions are used within the unit tests in this file, but also
in the `ws-tests` calls that perform the tests through http.
"""
import os
import unittest
from pyramid import testing
from phylesystem_api.utility import fill_app_settings, umbrella_from_request
from phylesystem_api.views import import_nexson_from_crossref_metadata
def get_app_settings_for_testing(settings):
"""Fills the settings of a DummyRequest, with info from the development.ini
This allows the dummy requests to mock a real request wrt configuration-dependent settings."""
from peyotl.utility.imports import SafeConfigParser
cfg = SafeConfigParser()
devini_path = os.path.abspath(os.path.join('..', 'development.ini'))
if not os.path.isfile(devini_path):
raise RuntimeError('Expecting a INI file at "{}" to run tests'.format(devini_path))
cfg.read(devini_path)
settings['repo_parent'] = cfg.get('app:main', 'repo_parent')
fill_app_settings(settings=settings)
| req = testing.DummyRequest()
get_app_settings_for_testing(req.registry.settings)
req.matchdict['api_version'] = 'v3'
return req
def check_index_response(test_case, response):
"""Verifies the existene of expected keys in the response to an index call.
'documentation_url', 'description', and 'source_url' keys must be in the response.
"""
for k in ['documentation_url', 'description', 'source_url']:
test_case.assertIn(k, response)
def check_render_markdown_response(test_case, response):
"""Check of `response` to a `render_markdown` call."""
expected = '<p>hi from <a href="http://phylo.bio.ku.edu" target="_blank">' \
'http://phylo.bio.ku.edu</a> and ' \
'<a href="https://github.com/orgs/OpenTreeOfLife/dashboard" target="_blank">' \
'https://github.com/orgs/OpenTreeOfLife/dashboard</a></p>'
test_case.assertEquals(response.body, expected)
def check_study_list_and_config_response(test_case,
sl_response,
config_response,
from_generic_config):
"""Checks of responses from study_list, config, and the generic config calls."""
nsis = sum([i['number of documents'] for i in config_response['shards']])
test_case.assertEquals(nsis, len(sl_response))
test_case.assertEquals(from_generic_config, config_response)
def check_unmerged_response(test_case, ub):
"""Check of `ub` response from an `unmerged_branches` call"""
test_case.assertTrue('master' not in ub)
def check_config_response(test_case, cfg):
"""Check of `cfg` response from a `config` call"""
test_case.assertSetEqual(set(cfg.keys()), {"initialization", "shards", "number_of_shards"})
def check_external_url_response(test_case, doc_id, resp):
"""Simple check of an `external_url` `resp` response for `doc_id`.
`doc_id` and `url` fields of the response are checked."""
test_case.assertEquals(resp.get('doc_id'), doc_id)
test_case.assertTrue(resp.get('url', '').endswith('{}.json'.format(doc_id)))
def check_push_failure_response(test_case, resp):
"""Check of the `resp` response of a `push_failure` method call to verify it has the right keys.
"""
test_case.assertSetEqual(set(resp.keys()), {"doc_type", "errors", "pushes_succeeding"})
test_case.assertTrue(resp["pushes_succeeding"])
render_test_input = 'hi from <a href="http://phylo.bio.ku.edu" target="new">' \
'http://phylo.bio.ku.edu</a> and ' \
'https://github.com/orgs/OpenTreeOfLife/dashboard'
class ViewTests(unittest.TestCase):
"""UnitTest of the functions that underlie the ws views."""
def setUp(self):
"""Calls pyramid testing.setUp"""
self.config = testing.setUp()
def tearDown(self):
"""Calls pyramid testing.tearDown"""
testing.tearDown()
def test_index(self):
"""Test of index view"""
request = gen_versioned_dummy_request()
from phylesystem_api.views import index
check_index_response(self, index(request))
def test_render_markdown(self):
"""Test of render_markdown view"""
request = testing.DummyRequest(post={'src': render_test_input})
from phylesystem_api.views import render_markdown
check_render_markdown_response(self, render_markdown(request))
def test_study_list_and_config(self):
"""Test of study_list and phylesystem_config views"""
request = gen_versioned_dummy_request()
from phylesystem_api.views import study_list
sl = study_list(request)
request = gen_versioned_dummy_request()
from phylesystem_api.views import phylesystem_config
x = phylesystem_config(request)
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'study'
from phylesystem_api.views import generic_config
y = generic_config(request)
check_study_list_and_config_response(self, sl, x, y)
if not sl:
return
from phylesystem_api.views import external_url
doc_id = sl[0]
request.matchdict['doc_id'] = doc_id
e = external_url(request)
check_external_url_response(self, doc_id, e)
def test_unmerged(self):
"""Test of unmerged_branches view"""
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'study'
from phylesystem_api.views import unmerged_branches
check_unmerged_response(self, unmerged_branches(request))
def test_config(self):
"""Test of generic_config view"""
request = gen_versioned_dummy_request()
from phylesystem_api.views import phylesystem_config, generic_config
r2 = phylesystem_config(request)
check_config_response(self, r2)
request.matchdict['resource_type'] = 'study'
r = generic_config(request)
check_config_response(self, r)
self.assertDictEqual(r, r2)
request.matchdict['resource_type'] = 'amendment'
ra = generic_config(request)
check_config_response(self, ra)
self.assertNotEqual(ra, r)
def test_push_failure_state(self):
"""Test of push_failure view"""
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'collection'
from phylesystem_api.views import push_failure
pf = push_failure(request)
check_push_failure_response(self, pf)
def test_doi_import(self):
"""Make sure that fetching from DOI generates a valid study shell."""
doi = "10.3732/ajb.0800060"
document = import_nexson_from_crossref_metadata(doi=doi,
ref_string=None,
include_cc0=None)
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'study'
umbrella = umbrella_from_request(request)
errors = umbrella.validate_and_convert_doc(document, {})[1]
self.assertEquals(len(errors), 0)
if __name__ == '__main__':
unittest.main() |
def gen_versioned_dummy_request():
"""Adds a version number (3) to the request to mimic the matching based on URL in the real app.
""" | random_line_split |
tests.py | """Unittests that do not require the server to be running an common tests of responses.
The TestCase here just calls the functions that provide the logic to the ws views with DummyRequest
objects to mock a real request.
The functions starting with `check_...` are called with UnitTest.TestCase instance as the first
arg and the response. These functions are used within the unit tests in this file, but also
in the `ws-tests` calls that perform the tests through http.
"""
import os
import unittest
from pyramid import testing
from phylesystem_api.utility import fill_app_settings, umbrella_from_request
from phylesystem_api.views import import_nexson_from_crossref_metadata
def get_app_settings_for_testing(settings):
"""Fills the settings of a DummyRequest, with info from the development.ini
This allows the dummy requests to mock a real request wrt configuration-dependent settings."""
from peyotl.utility.imports import SafeConfigParser
cfg = SafeConfigParser()
devini_path = os.path.abspath(os.path.join('..', 'development.ini'))
if not os.path.isfile(devini_path):
raise RuntimeError('Expecting a INI file at "{}" to run tests'.format(devini_path))
cfg.read(devini_path)
settings['repo_parent'] = cfg.get('app:main', 'repo_parent')
fill_app_settings(settings=settings)
def gen_versioned_dummy_request():
"""Adds a version number (3) to the request to mimic the matching based on URL in the real app.
"""
req = testing.DummyRequest()
get_app_settings_for_testing(req.registry.settings)
req.matchdict['api_version'] = 'v3'
return req
def check_index_response(test_case, response):
"""Verifies the existene of expected keys in the response to an index call.
'documentation_url', 'description', and 'source_url' keys must be in the response.
"""
for k in ['documentation_url', 'description', 'source_url']:
test_case.assertIn(k, response)
def check_render_markdown_response(test_case, response):
"""Check of `response` to a `render_markdown` call."""
expected = '<p>hi from <a href="http://phylo.bio.ku.edu" target="_blank">' \
'http://phylo.bio.ku.edu</a> and ' \
'<a href="https://github.com/orgs/OpenTreeOfLife/dashboard" target="_blank">' \
'https://github.com/orgs/OpenTreeOfLife/dashboard</a></p>'
test_case.assertEquals(response.body, expected)
def check_study_list_and_config_response(test_case,
sl_response,
config_response,
from_generic_config):
"""Checks of responses from study_list, config, and the generic config calls."""
nsis = sum([i['number of documents'] for i in config_response['shards']])
test_case.assertEquals(nsis, len(sl_response))
test_case.assertEquals(from_generic_config, config_response)
def check_unmerged_response(test_case, ub):
"""Check of `ub` response from an `unmerged_branches` call"""
test_case.assertTrue('master' not in ub)
def check_config_response(test_case, cfg):
"""Check of `cfg` response from a `config` call"""
test_case.assertSetEqual(set(cfg.keys()), {"initialization", "shards", "number_of_shards"})
def | (test_case, doc_id, resp):
"""Simple check of an `external_url` `resp` response for `doc_id`.
`doc_id` and `url` fields of the response are checked."""
test_case.assertEquals(resp.get('doc_id'), doc_id)
test_case.assertTrue(resp.get('url', '').endswith('{}.json'.format(doc_id)))
def check_push_failure_response(test_case, resp):
"""Check of the `resp` response of a `push_failure` method call to verify it has the right keys.
"""
test_case.assertSetEqual(set(resp.keys()), {"doc_type", "errors", "pushes_succeeding"})
test_case.assertTrue(resp["pushes_succeeding"])
render_test_input = 'hi from <a href="http://phylo.bio.ku.edu" target="new">' \
'http://phylo.bio.ku.edu</a> and ' \
'https://github.com/orgs/OpenTreeOfLife/dashboard'
class ViewTests(unittest.TestCase):
"""UnitTest of the functions that underlie the ws views."""
def setUp(self):
"""Calls pyramid testing.setUp"""
self.config = testing.setUp()
def tearDown(self):
"""Calls pyramid testing.tearDown"""
testing.tearDown()
def test_index(self):
"""Test of index view"""
request = gen_versioned_dummy_request()
from phylesystem_api.views import index
check_index_response(self, index(request))
def test_render_markdown(self):
"""Test of render_markdown view"""
request = testing.DummyRequest(post={'src': render_test_input})
from phylesystem_api.views import render_markdown
check_render_markdown_response(self, render_markdown(request))
def test_study_list_and_config(self):
"""Test of study_list and phylesystem_config views"""
request = gen_versioned_dummy_request()
from phylesystem_api.views import study_list
sl = study_list(request)
request = gen_versioned_dummy_request()
from phylesystem_api.views import phylesystem_config
x = phylesystem_config(request)
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'study'
from phylesystem_api.views import generic_config
y = generic_config(request)
check_study_list_and_config_response(self, sl, x, y)
if not sl:
return
from phylesystem_api.views import external_url
doc_id = sl[0]
request.matchdict['doc_id'] = doc_id
e = external_url(request)
check_external_url_response(self, doc_id, e)
def test_unmerged(self):
"""Test of unmerged_branches view"""
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'study'
from phylesystem_api.views import unmerged_branches
check_unmerged_response(self, unmerged_branches(request))
def test_config(self):
"""Test of generic_config view"""
request = gen_versioned_dummy_request()
from phylesystem_api.views import phylesystem_config, generic_config
r2 = phylesystem_config(request)
check_config_response(self, r2)
request.matchdict['resource_type'] = 'study'
r = generic_config(request)
check_config_response(self, r)
self.assertDictEqual(r, r2)
request.matchdict['resource_type'] = 'amendment'
ra = generic_config(request)
check_config_response(self, ra)
self.assertNotEqual(ra, r)
def test_push_failure_state(self):
"""Test of push_failure view"""
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'collection'
from phylesystem_api.views import push_failure
pf = push_failure(request)
check_push_failure_response(self, pf)
def test_doi_import(self):
"""Make sure that fetching from DOI generates a valid study shell."""
doi = "10.3732/ajb.0800060"
document = import_nexson_from_crossref_metadata(doi=doi,
ref_string=None,
include_cc0=None)
request = gen_versioned_dummy_request()
request.matchdict['resource_type'] = 'study'
umbrella = umbrella_from_request(request)
errors = umbrella.validate_and_convert_doc(document, {})[1]
self.assertEquals(len(errors), 0)
if __name__ == '__main__':
unittest.main()
| check_external_url_response | identifier_name |
auction_demo_tests.py | from itertools import product
from demos.auction_model import demo
def test02():
sellers = [4]
buyers = [100]
results = demo(sellers, buyers, time_limit=False)
expected_results = {100: 4, 4: 100}
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def test03():
expected_results = {101: 5, 5: 101, 6: None, 7: None}
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
results = demo(sellers, buyers)
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def test04():
expected_results = {0: 101, 101: 0, 102: None,
103: None} # result: 0 enters contract with price 334.97 (the highest price)
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
results = demo(sellers, buyers)
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def test05():
expected_results = {101: 7, 102: 6, 103: 5, 5: 103, 6: 102, 7: 101}
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
results = demo(sellers, buyers)
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def test06():
expected_results = {0: 102, 1: 108, 2: 105, 3: 107, 4: 100, 5: 106, 6: 112, 7: 111, 8: 103, 9: 109, 10: 104, 100: 4, 101: None, 102: 0, 103: 8, 104: 10, 105: 2, 106: 5, 107: 3, 108: 1, 109: 9, 110: None, 111: 7, 112: 6}
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
error_sets = []
for s_init, b_init in list(product([True, False], repeat=2)):
if not s_init and not b_init:
continue # if neither seller or buyer initialise, obviously nothing will happen.
results = demo(sellers=sellers, buyers=buyers, seller_can_initialise=s_init, buyer_can_initialise=b_init) | errors = []
for k, v in results.items():
if not expected_results[k] == v: # , "Hmmm... That's not right {}={}".format(k, v)
errors.append((k, v))
if errors:
error_sets.append(errors)
if error_sets:
print("-" * 80)
for i in error_sets:
print(",".join(str(i) for i in sorted(i)), flush=True)
raise AssertionError("output does not reflect expected results.") | random_line_split | |
auction_demo_tests.py | from itertools import product
from demos.auction_model import demo
def test02():
|
def test03():
expected_results = {101: 5, 5: 101, 6: None, 7: None}
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
results = demo(sellers, buyers)
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def test04():
expected_results = {0: 101, 101: 0, 102: None,
103: None} # result: 0 enters contract with price 334.97 (the highest price)
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
results = demo(sellers, buyers)
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def test05():
expected_results = {101: 7, 102: 6, 103: 5, 5: 103, 6: 102, 7: 101}
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
results = demo(sellers, buyers)
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def test06():
expected_results = {0: 102, 1: 108, 2: 105, 3: 107, 4: 100, 5: 106, 6: 112, 7: 111, 8: 103, 9: 109, 10: 104, 100: 4, 101: None, 102: 0, 103: 8, 104: 10, 105: 2, 106: 5, 107: 3, 108: 1, 109: 9, 110: None, 111: 7, 112: 6}
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
error_sets = []
for s_init, b_init in list(product([True, False], repeat=2)):
if not s_init and not b_init:
continue # if neither seller or buyer initialise, obviously nothing will happen.
results = demo(sellers=sellers, buyers=buyers, seller_can_initialise=s_init, buyer_can_initialise=b_init)
errors = []
for k, v in results.items():
if not expected_results[k] == v: # , "Hmmm... That's not right {}={}".format(k, v)
errors.append((k, v))
if errors:
error_sets.append(errors)
if error_sets:
print("-" * 80)
for i in error_sets:
print(",".join(str(i) for i in sorted(i)), flush=True)
raise AssertionError("output does not reflect expected results.") | sellers = [4]
buyers = [100]
results = demo(sellers, buyers, time_limit=False)
expected_results = {100: 4, 4: 100}
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v) | identifier_body |
auction_demo_tests.py | from itertools import product
from demos.auction_model import demo
def test02():
sellers = [4]
buyers = [100]
results = demo(sellers, buyers, time_limit=False)
expected_results = {100: 4, 4: 100}
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def test03():
expected_results = {101: 5, 5: 101, 6: None, 7: None}
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
results = demo(sellers, buyers)
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def test04():
expected_results = {0: 101, 101: 0, 102: None,
103: None} # result: 0 enters contract with price 334.97 (the highest price)
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
results = demo(sellers, buyers)
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def test05():
expected_results = {101: 7, 102: 6, 103: 5, 5: 103, 6: 102, 7: 101}
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
results = demo(sellers, buyers)
for k, v in results.items():
|
def test06():
expected_results = {0: 102, 1: 108, 2: 105, 3: 107, 4: 100, 5: 106, 6: 112, 7: 111, 8: 103, 9: 109, 10: 104, 100: 4, 101: None, 102: 0, 103: 8, 104: 10, 105: 2, 106: 5, 107: 3, 108: 1, 109: 9, 110: None, 111: 7, 112: 6}
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
error_sets = []
for s_init, b_init in list(product([True, False], repeat=2)):
if not s_init and not b_init:
continue # if neither seller or buyer initialise, obviously nothing will happen.
results = demo(sellers=sellers, buyers=buyers, seller_can_initialise=s_init, buyer_can_initialise=b_init)
errors = []
for k, v in results.items():
if not expected_results[k] == v: # , "Hmmm... That's not right {}={}".format(k, v)
errors.append((k, v))
if errors:
error_sets.append(errors)
if error_sets:
print("-" * 80)
for i in error_sets:
print(",".join(str(i) for i in sorted(i)), flush=True)
raise AssertionError("output does not reflect expected results.") | assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v) | conditional_block |
auction_demo_tests.py | from itertools import product
from demos.auction_model import demo
def test02():
sellers = [4]
buyers = [100]
results = demo(sellers, buyers, time_limit=False)
expected_results = {100: 4, 4: 100}
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def test03():
expected_results = {101: 5, 5: 101, 6: None, 7: None}
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
results = demo(sellers, buyers)
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def | ():
expected_results = {0: 101, 101: 0, 102: None,
103: None} # result: 0 enters contract with price 334.97 (the highest price)
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
results = demo(sellers, buyers)
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def test05():
expected_results = {101: 7, 102: 6, 103: 5, 5: 103, 6: 102, 7: 101}
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
results = demo(sellers, buyers)
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def test06():
expected_results = {0: 102, 1: 108, 2: 105, 3: 107, 4: 100, 5: 106, 6: 112, 7: 111, 8: 103, 9: 109, 10: 104, 100: 4, 101: None, 102: 0, 103: 8, 104: 10, 105: 2, 106: 5, 107: 3, 108: 1, 109: 9, 110: None, 111: 7, 112: 6}
sellers = [k for k in expected_results if k < 100]
buyers = [k for k in expected_results if k >= 100]
error_sets = []
for s_init, b_init in list(product([True, False], repeat=2)):
if not s_init and not b_init:
continue # if neither seller or buyer initialise, obviously nothing will happen.
results = demo(sellers=sellers, buyers=buyers, seller_can_initialise=s_init, buyer_can_initialise=b_init)
errors = []
for k, v in results.items():
if not expected_results[k] == v: # , "Hmmm... That's not right {}={}".format(k, v)
errors.append((k, v))
if errors:
error_sets.append(errors)
if error_sets:
print("-" * 80)
for i in error_sets:
print(",".join(str(i) for i in sorted(i)), flush=True)
raise AssertionError("output does not reflect expected results.") | test04 | identifier_name |
hoit.rs | pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) {
unsafe{
let synth = instance as *mut Lv2SynthPlugin;
let uris = &mut (*synth).uris;
let seq = (*synth).in_port;
let output = (*synth).output;
// pointer to 1st event body
let mut ev: *const lv2::Lv2AtomEvent = lv2::lv2_atom_sequence_begin(&(*seq).body);
// loop through event sequence
while !lv2::lv2_atom_sequence_is_end(&(*seq).body, (*seq).atom.size, ev) {
// check if event is midi
if (*ev).body.mytype == (*uris).midi_event {
// pointer to midi event data
let msg: *const u8 = ev.offset(1) as *const u8;
(*synth).midievent(msg);
for i in istart-1..n_samples {
*output.offset(i as isize) = (*synth).getAmp();
}
}
ev = lv2::lv2_atom_sequence_next(ev);
}
}
}
pub extern fn | (instance: lv2::Lv2handle, n_samples: u32) {
unsafe{
let synth = instance as *mut Synth;
// frameindex of eventstart. In jalv this is relative to currently processed buffer chunk of length n_samples
let istart = (*ev).time_in_frames as u32;
match lv2::lv2_midi_message_type(msg) {
// note on event
lv2::Lv2MidiMessageType::Lv2MidiMsgNoteOn => {
(*synth).noteison = true;
let f0 = f0_from_midimsg(msg);
(*synth).f0 = f0;
(*synth).currentmidivel = *msg.offset(2);
let coef = 1.0 as f32;
(*synth).osc.reset();
(*synth).osc.set_dphase(f0,(*synth).fs);
// TODO don't set fs here
(*synth).OscBLIT.reset((*synth).fs);
(*synth).OscBLIT.set_f0fn(f0);
for i in istart-1..n_samples {
// let amp = (*synth).osc.get() as f32;
let amp = (*synth).OscBLIT.get() as f32;
*output.offset(i as isize) = amp;
}
}
// note off event
lv2::Lv2MidiMessageType::Lv2MidiMsgNoteOff => {
(*synth).noteison = false;
(*synth).makesilence = true;
for i in istart-1..n_samples {
let amp = 0.0 as f32;
*output.offset(i as isize) = amp as f32;
}
}
_ => {
println!("DON'T UNDERSTAND MESSAGE")
}
}
}
ev = lv2::lv2_atom_sequence_next(ev);
}
if (*synth).noteison {
let coef = 1.0 as f32;
let f0 = (*synth).f0;
for i in 0..n_samples {
// let amp = (*synth).osc.get();
let amp = (*synth).OscBLIT.get();
*output.offset(i as isize) = (amp as f32) * coef;
}
} else if (*synth).makesilence {
(*synth).makesilence = false;
for i in 0..n_samples {
let amp = 0.0;
*output.offset(i as isize) = amp as f32;
}
}
}
}
| run | identifier_name |
hoit.rs | pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) {
unsafe{
let synth = instance as *mut Lv2SynthPlugin;
let uris = &mut (*synth).uris;
let seq = (*synth).in_port;
let output = (*synth).output;
// pointer to 1st event body
let mut ev: *const lv2::Lv2AtomEvent = lv2::lv2_atom_sequence_begin(&(*seq).body);
// loop through event sequence
while !lv2::lv2_atom_sequence_is_end(&(*seq).body, (*seq).atom.size, ev) {
// check if event is midi
if (*ev).body.mytype == (*uris).midi_event {
// pointer to midi event data
let msg: *const u8 = ev.offset(1) as *const u8;
(*synth).midievent(msg);
for i in istart-1..n_samples {
*output.offset(i as isize) = (*synth).getAmp();
}
}
ev = lv2::lv2_atom_sequence_next(ev);
}
}
}
pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) |
if (*synth).noteison {
let coef = 1.0 as f32;
let f0 = (*synth).f0;
for i in 0..n_samples {
// let amp = (*synth).osc.get();
let amp = (*synth).OscBLIT.get();
*output.offset(i as isize) = (amp as f32) * coef;
}
} else if (*synth).makesilence {
(*synth).makesilence = false;
for i in 0..n_samples {
let amp = 0.0;
*output.offset(i as isize) = amp as f32;
}
}
}
}
| {
unsafe{
let synth = instance as *mut Synth;
// frameindex of eventstart. In jalv this is relative to currently processed buffer chunk of length n_samples
let istart = (*ev).time_in_frames as u32;
match lv2::lv2_midi_message_type(msg) {
// note on event
lv2::Lv2MidiMessageType::Lv2MidiMsgNoteOn => {
(*synth).noteison = true;
let f0 = f0_from_midimsg(msg);
(*synth).f0 = f0;
(*synth).currentmidivel = *msg.offset(2);
let coef = 1.0 as f32;
(*synth).osc.reset();
(*synth).osc.set_dphase(f0,(*synth).fs);
// TODO don't set fs here
(*synth).OscBLIT.reset((*synth).fs);
(*synth).OscBLIT.set_f0fn(f0);
for i in istart-1..n_samples {
// let amp = (*synth).osc.get() as f32;
let amp = (*synth).OscBLIT.get() as f32;
*output.offset(i as isize) = amp;
}
}
// note off event
lv2::Lv2MidiMessageType::Lv2MidiMsgNoteOff => {
(*synth).noteison = false;
(*synth).makesilence = true;
for i in istart-1..n_samples {
let amp = 0.0 as f32;
*output.offset(i as isize) = amp as f32;
}
}
_ => {
println!("DON'T UNDERSTAND MESSAGE")
}
}
}
ev = lv2::lv2_atom_sequence_next(ev);
} | identifier_body |
hoit.rs | pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) {
unsafe{
let synth = instance as *mut Lv2SynthPlugin;
let uris = &mut (*synth).uris;
let seq = (*synth).in_port;
let output = (*synth).output;
// pointer to 1st event body
let mut ev: *const lv2::Lv2AtomEvent = lv2::lv2_atom_sequence_begin(&(*seq).body);
// loop through event sequence
while !lv2::lv2_atom_sequence_is_end(&(*seq).body, (*seq).atom.size, ev) {
// check if event is midi
if (*ev).body.mytype == (*uris).midi_event {
// pointer to midi event data
let msg: *const u8 = ev.offset(1) as *const u8;
(*synth).midievent(msg);
for i in istart-1..n_samples {
*output.offset(i as isize) = (*synth).getAmp();
}
}
ev = lv2::lv2_atom_sequence_next(ev);
}
}
}
pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) {
unsafe{
let synth = instance as *mut Synth;
// frameindex of eventstart. In jalv this is relative to currently processed buffer chunk of length n_samples
let istart = (*ev).time_in_frames as u32;
match lv2::lv2_midi_message_type(msg) {
// note on event
lv2::Lv2MidiMessageType::Lv2MidiMsgNoteOn => {
(*synth).noteison = true;
let f0 = f0_from_midimsg(msg); | (*synth).osc.set_dphase(f0,(*synth).fs);
// TODO don't set fs here
(*synth).OscBLIT.reset((*synth).fs);
(*synth).OscBLIT.set_f0fn(f0);
for i in istart-1..n_samples {
// let amp = (*synth).osc.get() as f32;
let amp = (*synth).OscBLIT.get() as f32;
*output.offset(i as isize) = amp;
}
}
// note off event
lv2::Lv2MidiMessageType::Lv2MidiMsgNoteOff => {
(*synth).noteison = false;
(*synth).makesilence = true;
for i in istart-1..n_samples {
let amp = 0.0 as f32;
*output.offset(i as isize) = amp as f32;
}
}
_ => {
println!("DON'T UNDERSTAND MESSAGE")
}
}
}
ev = lv2::lv2_atom_sequence_next(ev);
}
if (*synth).noteison {
let coef = 1.0 as f32;
let f0 = (*synth).f0;
for i in 0..n_samples {
// let amp = (*synth).osc.get();
let amp = (*synth).OscBLIT.get();
*output.offset(i as isize) = (amp as f32) * coef;
}
} else if (*synth).makesilence {
(*synth).makesilence = false;
for i in 0..n_samples {
let amp = 0.0;
*output.offset(i as isize) = amp as f32;
}
}
}
} | (*synth).f0 = f0;
(*synth).currentmidivel = *msg.offset(2);
let coef = 1.0 as f32;
(*synth).osc.reset(); | random_line_split |
TicketGrid.js | /**
* @class NetProfile.tickets.controller.TicketGrid
* @extends Ext.app.Controller
*/
Ext.define('NetProfile.tickets.controller.TicketGrid', {
extend: 'Ext.app.Controller',
requires: [
'Ext.menu.Menu'
],
fromTemplateText: 'From Template',
fromTemplateTipText: 'Add ticket from template',
scheduleText: 'Schedule',
init: function()
{
this.control({
'grid_tickets_Ticket' : {
beforerender: function(grid)
{
var tb;
tb = grid.getDockedItems('toolbar[dock=top]');
if(!tb || !tb.length)
return;
tb = tb[0];
tb.add({
text: this.fromTemplateText,
tooltip: { text: this.fromTemplateTipText, title: this.fromTemplateText },
iconCls: 'ico-add',
handler: function()
{
grid.spawnWizard('tpl');
}
});
}
},
'npwizard button#btn_sched' : {
click: {
scope: this, fn: function(btn, ev)
{
var wiz = btn.up('npwizard'),
date_field = wiz.down('datetimefield[name=assigned_time]'),
cfg = { dateField: date_field },
win, sched, values;
values = wiz.getValues();
if(values['assigned_uid'])
cfg.userId = parseInt(values['assigned_uid']);
if(values['assigned_gid'])
cfg.groupId = parseInt(values['assigned_gid']);
if(values['ticketid'])
cfg.ticketId = parseInt(values['ticketid']);
if(values['tstid'])
cfg.ticketStateId = parseInt(values['tstid']);
if(values['tschedid'])
cfg.schedulerId = parseInt(values['tschedid']);
if(values['ttplid'])
cfg.templateId = parseInt(values['ttplid']);
win = Ext.create('Ext.ux.window.CenterWindow', {
title: this.scheduleText,
modal: true
});
sched = Ext.create('NetProfile.tickets.view.Scheduler', cfg);
win.add(sched);
win.show();
return true;
}}
} | }); | });
} | random_line_split |
app-state.ts | import { observable, computed, action } from 'mobx';
import { remote as electron } from 'electron';
class AppState {
@observable isFocused = false;
@observable isIdle = false;
@observable devModeEnabled = false;
// network status as reported by chromium
@observable isOnline = navigator.onLine;
@computed
get isActive() {
return this.isFocused && !this.isIdle;
}
@action.bound
changeOnlineStatus() {
console.log(`Chromium reports state change to: ${navigator.onLine ? 'ONLINE' : 'OFFLINE'}`);
this.isOnline = navigator.onLine;
}
constructor() |
}
export default new AppState();
| {
const win = electron.getCurrentWindow();
win.on('focus', () => {
this.isFocused = true;
console.log('App got focus');
});
win.on('blur', () => {
this.isFocused = false;
console.log('App lost focus');
});
this.isFocused = win.isFocused();
// prevents some noise in the logs on app shutdown
window.onunload = () => win.removeAllListeners();
window.addEventListener('online', this.changeOnlineStatus, false);
window.addEventListener('offline', this.changeOnlineStatus, false);
} | identifier_body |
app-state.ts | import { observable, computed, action } from 'mobx';
import { remote as electron } from 'electron';
class AppState {
@observable isFocused = false;
@observable isIdle = false;
@observable devModeEnabled = false;
// network status as reported by chromium
@observable isOnline = navigator.onLine;
@computed
get isActive() {
return this.isFocused && !this.isIdle;
}
@action.bound
changeOnlineStatus() {
console.log(`Chromium reports state change to: ${navigator.onLine ? 'ONLINE' : 'OFFLINE'}`);
this.isOnline = navigator.onLine;
}
constructor() {
const win = electron.getCurrentWindow();
win.on('focus', () => {
this.isFocused = true;
console.log('App got focus');
});
win.on('blur', () => {
this.isFocused = false;
console.log('App lost focus');
});
this.isFocused = win.isFocused();
// prevents some noise in the logs on app shutdown
window.onunload = () => win.removeAllListeners();
window.addEventListener('online', this.changeOnlineStatus, false);
window.addEventListener('offline', this.changeOnlineStatus, false);
}
}
| export default new AppState(); | random_line_split | |
app-state.ts | import { observable, computed, action } from 'mobx';
import { remote as electron } from 'electron';
class AppState {
@observable isFocused = false;
@observable isIdle = false;
@observable devModeEnabled = false;
// network status as reported by chromium
@observable isOnline = navigator.onLine;
@computed
get isActive() {
return this.isFocused && !this.isIdle;
}
@action.bound
| () {
console.log(`Chromium reports state change to: ${navigator.onLine ? 'ONLINE' : 'OFFLINE'}`);
this.isOnline = navigator.onLine;
}
constructor() {
const win = electron.getCurrentWindow();
win.on('focus', () => {
this.isFocused = true;
console.log('App got focus');
});
win.on('blur', () => {
this.isFocused = false;
console.log('App lost focus');
});
this.isFocused = win.isFocused();
// prevents some noise in the logs on app shutdown
window.onunload = () => win.removeAllListeners();
window.addEventListener('online', this.changeOnlineStatus, false);
window.addEventListener('offline', this.changeOnlineStatus, false);
}
}
export default new AppState();
| changeOnlineStatus | identifier_name |
lib.rs | extern crate rusty_c_sys;
use rusty_c_sys as ffi;
trait Pika2 {
fn next_pika2(&mut self) -> i32;
}
impl Pika2 for i32 {
fn next_pika2(&mut self) -> i32 {
let raw = self as *mut i32;
unsafe {
ffi::next_pika2(raw)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_escape() {
let mut x = ffi::escape;
let p = x.next_pika2();
assert_eq!(x, ffi::attack);
assert_eq!(p, ffi::attack);
}
#[test]
fn from_attack() {
let mut x = ffi::attack;
let p = x.next_pika2();
assert_eq!(x, ffi::defend);
assert_eq!(p, ffi::defend);
}
#[test]
fn | () {
let mut x = ffi::defend;
let p = x.next_pika2();
assert_eq!(x, ffi::attack);
assert_eq!(p, ffi::attack);
}
}
| from_defend | identifier_name |
lib.rs | extern crate rusty_c_sys;
use rusty_c_sys as ffi;
trait Pika2 {
fn next_pika2(&mut self) -> i32;
}
impl Pika2 for i32 {
fn next_pika2(&mut self) -> i32 {
let raw = self as *mut i32;
unsafe {
ffi::next_pika2(raw)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_escape() {
let mut x = ffi::escape;
let p = x.next_pika2();
assert_eq!(x, ffi::attack);
assert_eq!(p, ffi::attack);
}
#[test]
fn from_attack() {
let mut x = ffi::attack;
let p = x.next_pika2();
assert_eq!(x, ffi::defend);
assert_eq!(p, ffi::defend);
}
#[test]
fn from_defend() { | let mut x = ffi::defend;
let p = x.next_pika2();
assert_eq!(x, ffi::attack);
assert_eq!(p, ffi::attack);
}
} | random_line_split | |
lib.rs | extern crate rusty_c_sys;
use rusty_c_sys as ffi;
trait Pika2 {
fn next_pika2(&mut self) -> i32;
}
impl Pika2 for i32 {
fn next_pika2(&mut self) -> i32 {
let raw = self as *mut i32;
unsafe {
ffi::next_pika2(raw)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_escape() {
let mut x = ffi::escape;
let p = x.next_pika2();
assert_eq!(x, ffi::attack);
assert_eq!(p, ffi::attack);
}
#[test]
fn from_attack() |
#[test]
fn from_defend() {
let mut x = ffi::defend;
let p = x.next_pika2();
assert_eq!(x, ffi::attack);
assert_eq!(p, ffi::attack);
}
}
| {
let mut x = ffi::attack;
let p = x.next_pika2();
assert_eq!(x, ffi::defend);
assert_eq!(p, ffi::defend);
} | identifier_body |
app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { MyfriendsComponent } from './component/myfriends/myfriends.component';
import { AddFriendComponent } from './component/add-friend/add-friend.component';
import { UserInfoComponent } from './component/user-info/user-info.component';
import { ChatRoomComponent } from './component/chat-room/chat-room.component';
import { MyFriendsService } from './service/my-friends.service';
import { WebsocketService } from './service/websocket.service';
@NgModule({
declarations: [
AppComponent,
MyfriendsComponent,
AddFriendComponent,
UserInfoComponent,
ChatRoomComponent
],
imports: [
BrowserModule,
HttpClientModule, | FormsModule,
AppRoutingModule
],
providers: [
MyFriendsService,
WebsocketService
],
bootstrap: [AppComponent]
})
export class AppModule { } | random_line_split | |
app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { MyfriendsComponent } from './component/myfriends/myfriends.component';
import { AddFriendComponent } from './component/add-friend/add-friend.component';
import { UserInfoComponent } from './component/user-info/user-info.component';
import { ChatRoomComponent } from './component/chat-room/chat-room.component';
import { MyFriendsService } from './service/my-friends.service';
import { WebsocketService } from './service/websocket.service';
@NgModule({
declarations: [
AppComponent,
MyfriendsComponent,
AddFriendComponent,
UserInfoComponent,
ChatRoomComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
AppRoutingModule
],
providers: [
MyFriendsService,
WebsocketService
],
bootstrap: [AppComponent]
})
export class | { }
| AppModule | identifier_name |
wrapping_sub_mul.rs | use num::arithmetic::traits::{
WrappingMul, WrappingSub, WrappingSubAssign, WrappingSubMul, WrappingSubMulAssign,
};
fn | <T: WrappingMul<T, Output = T> + WrappingSub<T, Output = T>>(
x: T,
y: T,
z: T,
) -> T {
x.wrapping_sub(y.wrapping_mul(z))
}
fn wrapping_sub_mul_assign<T: WrappingMul<T, Output = T> + WrappingSubAssign<T>>(
x: &mut T,
y: T,
z: T,
) {
x.wrapping_sub_assign(y.wrapping_mul(z));
}
macro_rules! impl_wrapping_sub_mul {
($t:ident) => {
impl WrappingSubMul<$t> for $t {
type Output = $t;
/// Computes $x - yz$, wrapping around at the boundary of the type.
///
/// $f(x, y, z) = w$, where $w \equiv x - yz \mod 2^W$ and $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::wrapping_sub_mul` module.
#[inline]
fn wrapping_sub_mul(self, y: $t, z: $t) -> $t {
wrapping_sub_mul(self, y, z)
}
}
impl WrappingSubMulAssign<$t> for $t {
/// Replaces $x$ with $x - yz$, wrapping around at the boundary of the type.
///
/// $x \gets w$, where $w \equiv x - yz \mod 2^W$ and $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::wrapping_sub_mul` module.
#[inline]
fn wrapping_sub_mul_assign(&mut self, y: $t, z: $t) {
wrapping_sub_mul_assign(self, y, z)
}
}
};
}
apply_to_primitive_ints!(impl_wrapping_sub_mul);
| wrapping_sub_mul | identifier_name |
wrapping_sub_mul.rs | use num::arithmetic::traits::{
WrappingMul, WrappingSub, WrappingSubAssign, WrappingSubMul, WrappingSubMulAssign,
};
| ) -> T {
x.wrapping_sub(y.wrapping_mul(z))
}
fn wrapping_sub_mul_assign<T: WrappingMul<T, Output = T> + WrappingSubAssign<T>>(
x: &mut T,
y: T,
z: T,
) {
x.wrapping_sub_assign(y.wrapping_mul(z));
}
macro_rules! impl_wrapping_sub_mul {
($t:ident) => {
impl WrappingSubMul<$t> for $t {
type Output = $t;
/// Computes $x - yz$, wrapping around at the boundary of the type.
///
/// $f(x, y, z) = w$, where $w \equiv x - yz \mod 2^W$ and $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::wrapping_sub_mul` module.
#[inline]
fn wrapping_sub_mul(self, y: $t, z: $t) -> $t {
wrapping_sub_mul(self, y, z)
}
}
impl WrappingSubMulAssign<$t> for $t {
/// Replaces $x$ with $x - yz$, wrapping around at the boundary of the type.
///
/// $x \gets w$, where $w \equiv x - yz \mod 2^W$ and $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::wrapping_sub_mul` module.
#[inline]
fn wrapping_sub_mul_assign(&mut self, y: $t, z: $t) {
wrapping_sub_mul_assign(self, y, z)
}
}
};
}
apply_to_primitive_ints!(impl_wrapping_sub_mul); | fn wrapping_sub_mul<T: WrappingMul<T, Output = T> + WrappingSub<T, Output = T>>(
x: T,
y: T,
z: T, | random_line_split |
wrapping_sub_mul.rs | use num::arithmetic::traits::{
WrappingMul, WrappingSub, WrappingSubAssign, WrappingSubMul, WrappingSubMulAssign,
};
fn wrapping_sub_mul<T: WrappingMul<T, Output = T> + WrappingSub<T, Output = T>>(
x: T,
y: T,
z: T,
) -> T |
fn wrapping_sub_mul_assign<T: WrappingMul<T, Output = T> + WrappingSubAssign<T>>(
x: &mut T,
y: T,
z: T,
) {
x.wrapping_sub_assign(y.wrapping_mul(z));
}
macro_rules! impl_wrapping_sub_mul {
($t:ident) => {
impl WrappingSubMul<$t> for $t {
type Output = $t;
/// Computes $x - yz$, wrapping around at the boundary of the type.
///
/// $f(x, y, z) = w$, where $w \equiv x - yz \mod 2^W$ and $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::wrapping_sub_mul` module.
#[inline]
fn wrapping_sub_mul(self, y: $t, z: $t) -> $t {
wrapping_sub_mul(self, y, z)
}
}
impl WrappingSubMulAssign<$t> for $t {
/// Replaces $x$ with $x - yz$, wrapping around at the boundary of the type.
///
/// $x \gets w$, where $w \equiv x - yz \mod 2^W$ and $W$ is `$t::WIDTH`.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::wrapping_sub_mul` module.
#[inline]
fn wrapping_sub_mul_assign(&mut self, y: $t, z: $t) {
wrapping_sub_mul_assign(self, y, z)
}
}
};
}
apply_to_primitive_ints!(impl_wrapping_sub_mul);
| {
x.wrapping_sub(y.wrapping_mul(z))
} | identifier_body |
dwr_db_I_gid_0.js | // This file is generated
I_gid_0 = [
"I2111",
"I2106",
"I2113",
"I2115",
"I2105",
"I2114",
"I2110",
"I1004",
"I0554",
"I0701",
"I0553",
"I0559",
"I1408",
"I0551",
"I0702",
"I0953",
"I0693",
"I2002",
"I2011",
"I1996",
"I2017",
"I0678",
"I2007",
"I1999",
"I2016",
"I2005",
"I2013",
"I2010",
"I1995",
"I2008",
"I1997",
"I0473",
"I1466",
"I1467",
"I0754",
"I1465",
"I1470",
"I0531",
"I0472",
"I1556",
"I1469",
"I1468",
"I0508",
"I1645",
"I2057",
"I0511",
"I0680",
"I0744",
"I0933",
"I0938",
"I0945",
"I1194",
"I0022",
"I1965",
"I1967",
"I0033",
"I1963",
"I1964",
"I1968",
"I1970",
"I0568",
"I0027",
"I1961",
"I0565",
"I2081",
"I1241",
"I2006",
"I0793",
"I1310",
"I0523",
"I0561",
"I1320",
"I1316",
"I1329",
"I1331",
"I1314",
"I1321",
"I1311",
"I1327",
"I1323",
"I1306",
"I1309",
"I1277",
"I1275",
"I1279",
"I1333",
"I1325",
"I1318",
"I1307",
"I1180",
"I0640",
"I1587",
"I1586",
"I0774",
"I0770",
"I0772",
"I1584",
"I1592",
"I1603",
"I1596",
"I1588",
"I1582",
"I1583",
"I1581",
"I0773",
"I0767",
"I1590",
"I1585",
"I0478",
"I1601",
"I1591",
"I1605",
"I1589",
"I1599",
"I1580",
"I1594",
"I0771",
"I1142",
"I0391",
"I0762",
"I1187",
"I1003",
"I1621",
"I0463",
"I0067",
"I1685",
"I1680",
"I0926",
"I1681",
"I1684",
"I1678",
"I0915",
"I0924",
"I0927",
"I0923",
"I0929",
"I1673",
"I0874",
"I0880",
"I0069",
"I0873",
"I1679",
"I1677",
"I0875",
"I0879",
"I0922",
"I0876",
"I0917",
"I1675",
"I0599",
"I1683",
"I0878",
"I1488",
"I0394",
"I0805",
"I0803",
"I0392",
"I0403",
"I1743",
"I0404",
"I1741",
"I0840",
"I0506",
"I0096",
"I0377",
"I1744",
"I0055",
"I0390",
"I0095",
"I0374",
"I1745",
"I0842",
"I0498",
"I0813",
"I0380",
"I0376",
"I0393",
"I0812",
"I0051",
"I0384",
"I1297",
"I1484",
"I2020",
"I1355",
"I1291",
"I0254",
"I0431",
"I1098",
"I1101",
"I1103",
"I1095",
"I1097",
"I0957",
"I0956",
"I1094",
"I1100",
"I1096",
"I1099",
"I1092",
"I0712",
"I0928",
"I0934",
"I0024",
"I1756",
"I1757",
"I1754",
"I1747",
"I1753",
"I1755",
"I1758",
"I1301",
"I1124",
"I2101",
"I0745",
"I1119",
"I0607",
"I0763",
"I0605",
"I1190",
"I0888",
"I2097",
"I1031",
"I0522",
"I0525",
"I0526",
"I0545",
"I0679",
"I0748",
"I1029",
"I0677",
"I0681",
"I0529",
"I0530",
"I0570",
"I0078",
"I0076",
"I1724",
"I1017",
"I2079",
"I1165",
"I1424",
"I0469",
"I0464",
"I0467",
"I1619",
"I1152",
"I1150",
"I2050",
"I1422",
"I0973",
"I0622",
"I0692",
"I0690",
"I0544",
"I0548",
"I1141",
"I1666",
"I2000",
"I1746",
"I1939",
"I1212",
"I1206",
"I1208",
"I0970",
"I1211",
"I1207",
"I1210",
"I1916",
"I1205",
"I1209",
"I0984",
"I1201",
"I1946",
"I1356",
"I0889",
"I1375",
"I0421",
"I1352",
"I1509",
"I1505",
"I0471",
"I1493",
"I1528",
"I1524",
"I1520",
"I1492",
"I1475",
"I1473",
"I1523",
"I0039",
"I1489",
"I1494",
"I1526",
"I1522",
"I1527",
"I1476",
"I1506",
"I1508",
"I0574",
"I1521",
"I0604",
"I1495",
"I0921",
"I1525",
"I1496",
"I1507",
"I1497",
"I1917",
"I1305",
"I1295",
"I0494",
"I0105",
"I1168",
"I1595",
"I1182",
"I0270",
"I1294",
"I0086",
"I1283",
"I1302",
"I0364",
"I1285",
"I1298",
"I0088",
"I1300",
"I0365",
"I1290",
"I1273",
"I0366",
"I1287",
"I0360",
"I1304",
"I0363",
"I1296",
"I0359",
"I1281",
"I1292",
"I0361",
"I1288",
"I0362",
"I0758",
"I1790",
"I0097",
"I0925",
"I1941",
"I0341",
"I1606",
"I1120",
"I0251",
"I0094",
"I1644",
"I2090",
"I0407",
"I1303",
"I1122",
"I1888",
"I0944",
"I1943",
"I1037",
"I1033",
"I1035",
"I1002",
"I0674",
"I1674",
"I0025",
"I0518",
"I0032",
"I0515",
"I0682",
"I1313",
"I1315",
"I1319",
"I1937",
"I0871",
"I1116",
"I1106",
"I1126",
"I1128",
"I0628",
"I0631",
"I0634",
"I0627",
"I1125",
"I0046",
"I1121",
"I0625",
"I0623",
"I1105",
"I0044",
"I1039",
"I1114",
"I1115",
"I1113",
"I0624",
"I1117",
"I1123",
"I0106",
"I0626",
"I0787",
"I1490",
"I1843",
"I1911",
"I1153",
"I1804",
"I1219",
"I1535",
"I1360",
"I0918",
"I1030",
"I1032",
"I2047",
"I1971",
"I0539",
"I1169",
"I1859",
"I0616",
"I1011",
"I0542",
"I0535",
"I0026",
"I0546",
"I0547",
"I0848",
"I0696",
"I1477",
"I0689",
"I0752",
"I0528",
"I2012",
"I1156",
"I1155",
"I1159",
"I1157",
"I1158",
"I0378",
"I1102",
"I0961",
"I1014",
"I1322",
"I0749",
"I0517",
"I1998",
"I0733",
"I1622",
"I0976",
"I0800",
"I0799",
"I2015",
"I1649",
"I1511",
"I1312",
"I1949",
"I1474",
"I1485",
"I1202",
"I1280",
"I0092",
"I0030",
"I1074",
"I0571",
"I0954",
"I0751",
"I1019",
"I1023",
"I1905",
"I0738",
"I1107",
"I1541",
"I1530",
"I1542",
"I0479",
"I1546",
"I0729",
"I0476",
"I1538",
"I1539",
"I1544",
"I1532",
"I1536",
"I1534",
"I1543",
"I1483",
"I1548",
"I1531",
"I0730",
"I1545",
"I1547",
"I1533",
"I1401",
"I1390",
"I1398",
"I1396",
"I1395",
"I1402",
"I1399",
"I1404",
"I1391",
"I1392",
"I0939",
"I0935",
"I1198",
"I1344",
"I1612",
"I1370",
"I1620",
"I1609",
"I1374",
"I0066",
"I0064",
"I0462",
"I1346",
"I1614",
"I1347",
"I1372",
"I1351",
"I0041",
"I1348",
"I1369",
"I1349",
"I1345",
"I1373",
"I1607",
"I1618",
"I1350",
"I1616",
"I1368",
"I1371",
"I1682",
"I0578",
"I0637",
"I1007",
"I1006",
"I2022",
"I2071",
"I0063",
"I1856",
"I1896",
"I1512",
"I2018",
"I0584",
"I0103",
"I0691",
"I1024",
"I1026", | "I1022",
"I1018",
"I1016",
"I1145",
"I1147",
"I1036",
"I0583",
"I0585",
"I0587",
"I0580",
"I0586",
"I0582",
"I0050",
"I0250",
"I0256",
"I0253",
"I0249",
"I0792",
"I1174",
"I0987",
"I1193",
"I1192",
"I1519",
"I1549",
"I1886",
"I0533",
"I0536",
"I0532",
"I0686",
"I1676",
"I1738",
"I0887",
"I0035",
"I1339",
"I0040",
"I0420",
"I1354",
"I0187",
"I0188",
"I1366",
"I1353",
"I1357",
"I1359",
"I1397",
"I1692",
"I1278",
"I1328",
"I1362",
"I1191",
"I0514",
"I0703",
"I0199",
"I0093",
"I0245",
"I0134",
"I1985",
"I0198",
"I0202",
"I0049",
"I0244",
"I0203",
"I0200",
"I0054",
"I0201",
"I0405",
"I0242",
"I0936",
"I1647",
"I0975",
"I0045",
"I0683",
"I0684",
"I1027",
"I0567",
"I0563",
"I1164",
"I1617",
"I1801",
"I1798",
"I1407",
"I2004",
"I0102",
"I1324",
"I1330",
"I1289",
"I0087",
"I0543",
"I1154",
"I1956",
"I1486",
"I0576",
"I2054",
"I2055",
"I2053",
"I0061",
"I0028",
"I2093",
"I2087",
"I0058",
"I2069",
"I2051",
"I2098",
"I2056",
"I2089",
"I2095",
"I2104",
"I2100",
"I2084",
"I2052",
"I0059",
"I2092",
"I2049",
"I2096",
"I2082",
"I2086",
"I0060",
"I2085",
"I2062",
"I2070",
"I2094",
"I2080",
"I2091",
"I2077",
"I2048",
"I1308",
"I0614",
"I1979",
"I1980",
"I0615",
"I0084",
"I1984",
"I1982",
"I1983",
"I1981",
"I1978",
"I1073",
"I1988",
"I1173",
"I1162",
"I0881",
"I0882",
"I1378",
"I1379",
"I1386",
"I1380",
"I1377",
"I1381",
"I1382",
"I1384",
"I1897",
"I1954",
"I0562",
"I0552",
"I2014",
"I0750",
"I1994",
"I0610",
"I0246",
"I0098",
"I1410",
"I1597",
"I1400",
"I0194",
"I1423",
"I0037",
"I0038",
"I1634",
"I0196",
"I1376",
"I1414",
"I1406",
"I1389",
"I1434",
"I1537",
"I1435",
"I1642",
"I1387",
"I1176",
"I1615",
"I0519",
"I1613",
"I0521",
"I1646",
"I0475",
"I1502",
"I1503",
"I1501",
"I0728",
"I1499",
"I1500",
"I1504",
"I0470",
"I0468",
"I1127",
"I1514",
"I1299",
"I2083",
"I1894",
"I1885",
"I1884",
"I0955",
"I1892",
"I0722",
"I0960",
"I0962",
"I1890",
"I1891",
"I1889",
"I1893",
"I1887",
"I1604",
"I2078",
"I1933",
"I1426",
"I0851",
"I0850",
"I0753",
"I0072",
"I0742",
"I0074",
"I1551",
"I0581",
"I2063",
"I1828",
"I1170",
"I1160",
"I2088",
"I1670",
"I0877",
"I1118",
"I1149",
"I0756",
"I0852",
"I0707",
"I1850",
"I1132",
"I1133",
"I0047",
"I0705",
"I1855",
"I1833",
"I0089",
"I0706",
"I1803",
"I1805",
"I1858",
"I1846",
"I1822",
"I1851",
"I1806",
"I1845",
"I1802",
"I0458",
"I1936",
"I1934",
"I1938",
"I1932",
"I0401",
"I0101",
"I1940",
"I1929",
"I0400",
"I0052",
"I0399",
"I1930",
"I0395",
"I1931",
"I0947",
"I0940",
"I0964",
"I0963",
"I0967",
"I1171",
"I0965",
"I1898",
"I0966",
"I0557",
"I0732",
"I1009",
"I0849",
"I1012",
"I1659",
"I1709",
"I1714",
"I1717",
"I1728",
"I1734",
"I1715",
"I1729",
"I1713",
"I1710",
"I1732",
"I1720",
"I0598",
"I1723",
"I1719",
"I1721",
"I1725",
"I1718",
"I1722",
"I1730",
"I1733",
"I1712",
"I1716",
"I1510",
"I1405",
"I0999",
"I1986",
"I1091",
"I0958",
"I0466",
"I1942",
"I1034",
"I1895",
"I0685",
"I1000",
"I0675",
"I1550",
"I1148",
"I0760",
"I0838",
"I0930",
"I1383",
"I1452",
"I0100",
"I0949",
"I1015",
"I1667",
"I1668",
"I1669",
"I0741",
"I1284",
"I0065",
"I0768",
"I0769",
"I1188",
"I1969",
"I0579",
"I1001",
"I1317",
"I1686",
"I1172",
"I1648",
"I0943",
"I0932",
"I1326",
"I1920",
"I1919",
"I1203",
"I1918",
"I1204",
"I1197",
"I0504",
"I1293",
"I0641",
"I1935",
"I0524",
"I0527",
"I1286",
"I0204",
"I0205",
"I0357",
"I0077",
"I0350",
"I0083",
"I0352",
"I0075",
"I0073",
"I0353",
"I0070",
"I0085",
"I0043",
"I0727",
"I0358",
"I0351",
"I0081",
"I0951",
"I0273",
"I1238",
"I1256",
"I0695",
"I1742",
"I0872",
"I1021",
"I1271",
"I1247",
"I0512",
"I0509",
"I0737",
"I0507",
"I1257",
"I1948",
"I1252",
"I0128",
"I1261",
"I1248",
"I0510",
"I1265",
"I1255",
"I1250",
"I0071",
"I1950",
"I1268",
"I1260",
"I1944",
"I1953",
"I1245",
"I1258",
"I1947",
"I1263",
"I1951",
"I1957",
"I1958",
"I1270",
"I1262",
"I1955",
"I0137",
"I1253",
"I1251",
"I0020",
"I1945",
"I1249",
"I0126",
"I1267",
"I0023",
"I0031",
"I1264",
"I1246",
"I1269",
"I0847",
"I1254",
"I0845",
"I0021",
"I1266",
"I2045",
"I1224",
"I1385",
"I1220",
"I0994",
"I0990",
"I1701",
"I1231",
"I0796",
"I1698",
"I1218",
"I1694",
"I0042",
"I1703",
"I1665",
"I1699",
"I1239",
"I1233",
"I1232",
"I1663",
"I0797",
"I0193",
"I0068",
"I1664",
"I0191",
"I0991",
"I1223",
"I1228",
"I1702",
"I1700",
"I1227",
"I1234",
"I1226",
"I1225",
"I1222",
"I1230",
"I1242",
"I1229",
"I1189",
"I0853",
"I1146",
"I1832",
"I1610",
"I0687",
"I1643",
"I0639",
"I1417",
"I1600",
"I1910",
"I1909",
"I1902",
"I1915",
"I1901",
"I0107",
"I0867",
"I1334",
"I1332",
"I1602",
"I1518",
"I1282",
"I0916",
"I0942",
"I0946",
"I1093",
"I1336",
"I0606",
"I0765",
"I1727",
"I0755",
"I1151",
"I1276",
"I2046",
"I1914",
"I1178",
"I0986",
"I1183",
"I1185",
"I1184",
"I1181",
"I1179",
"I1904",
"I1908",
"I1175",
"I0538",
"I1731",
"I1650",
"I0555",
"I0560",
"I0566",
"I0034",
"I0029",
"I1903",
"I1726",
"I1139",
"I1005",
"I1343",
"I1196",
"I1807",
"I0080",
"I1952",
"I0588",
"I1235",
"I1221",
"I2003",
"I0541",
"I0537",
"I0890",
"I1028",
"I0704",
"I1487",
"I1274",
"I1195",
"I0764",
"I1186",
"I2001",
"I2009",
"I1515",
"I1013",
"I0520",
"I2099",
"I0941",
"I1008",
"I1010",
"I1214",
"I0414",
"I1112",
"I1110",
"I1109",
"I1111",
"I1108",
"I0048",
"I0710",
"I0711",
"I0091",
"I0709",
"I1830",
"I0747",
"I1640",
"I1641",
"I1403",
"I1025",
"I0564",
"I0972",
"I2112",
"I2116",
"I1608",
"I1137",
"I0766",
"I1593",
"I1213",
"I0761",
"I0082",
"I0247",
"I1706"
]
Dwr.ScriptLoaded('dwr_db_I_gid_0.js'); | "I1020", | random_line_split |
helpDisplay.py | # -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico 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.
##
## Indico 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 Indico;if not, see <http://www.gnu.org/licenses/>.
import MaKaC.webinterface.rh.base as base
import MaKaC.webinterface.pages.help as help
class RHHelp( base.RH ):
def _process( self ):
| p = help.WPHelp(self)
return p.display() | identifier_body | |
helpDisplay.py | # -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico 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.
##
## Indico 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 Indico;if not, see <http://www.gnu.org/licenses/>.
import MaKaC.webinterface.rh.base as base
import MaKaC.webinterface.pages.help as help
class RHHelp( base.RH ):
def _process( self ):
p = help.WPHelp(self)
return p.display() | ## | random_line_split |
helpDisplay.py | # -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico 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.
##
## Indico 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 Indico;if not, see <http://www.gnu.org/licenses/>.
import MaKaC.webinterface.rh.base as base
import MaKaC.webinterface.pages.help as help
class RHHelp( base.RH ):
def | ( self ):
p = help.WPHelp(self)
return p.display()
| _process | identifier_name |
DownloadingButton.tsx | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
import * as React from 'react';
import * as events from '@csegames/camelot-unchained/lib/events';
import styled, { keyframes } from 'react-emotion';
import { ButtonText, PatchButtonStyle } from '../styles';
const goldenColor = 'rgba(192, 173, 124, 0.9)';
const shineAnim = keyframes`
0% {
left: 30px;
opacity: 0;
}
30% {
opacity: 0.5;
}
100% {
left: 35%;
opacity: 0;
}
`;
const DownloadingButtonView = styled('div')`
${PatchButtonStyle};
background: url(images/controller/play-button-grey.png);
filter: brightness(140%);
&:hover {
filter: brightness(140%);
}
&:hover:before {
animation: none;
-webkit-animation: none;
}
&:hover:after {
animation: none;
-webkit-animation: none;
}
`;
const Shine = styled('div')`
position: absolute;
height: 90%;
width: 70%;
border-left-radius: 50%;
background: linear-gradient(to right, transparent, ${goldenColor}, transparent);
bottom: 5px;
left: 15px;
opacity: 0;
-webkit-animation: ${shineAnim} 1.3s ease infinite;
animation: ${shineAnim} 1.3s ease infinite;
-webkit-clip-path: polygon(5% 0%, 100% 0%, 90% 100%, 0% 100%);
clip-path: polygon(5% 0%, 100% 0%, 90% 100%, 0% 100%);
z-index: 2;
`;
export interface DownloadingButtonProps {
text: string;
onClick?: (e: React.MouseEvent<HTMLDivElement>) => void;
}
class | extends React.Component<DownloadingButtonProps> {
public render() {
return (
<DownloadingButtonView onClick={this.props.onClick} onMouseOver={this.playSound}>
<ButtonText>{this.props.text}</ButtonText>
<Shine />
</DownloadingButtonView>
);
}
private playSound = () => {
events.fire('play-sound', 'select-change');
}
}
export default DownloadingButton;
| DownloadingButton | identifier_name |
DownloadingButton.tsx | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
import * as React from 'react';
import * as events from '@csegames/camelot-unchained/lib/events';
import styled, { keyframes } from 'react-emotion';
import { ButtonText, PatchButtonStyle } from '../styles';
const goldenColor = 'rgba(192, 173, 124, 0.9)';
const shineAnim = keyframes`
0% {
left: 30px;
opacity: 0;
}
30% {
opacity: 0.5;
}
100% {
left: 35%;
opacity: 0;
}
`;
const DownloadingButtonView = styled('div')`
${PatchButtonStyle};
background: url(images/controller/play-button-grey.png);
filter: brightness(140%);
&:hover {
filter: brightness(140%);
}
&:hover:before {
animation: none;
-webkit-animation: none;
}
&:hover:after {
animation: none;
-webkit-animation: none;
}
`; | position: absolute;
height: 90%;
width: 70%;
border-left-radius: 50%;
background: linear-gradient(to right, transparent, ${goldenColor}, transparent);
bottom: 5px;
left: 15px;
opacity: 0;
-webkit-animation: ${shineAnim} 1.3s ease infinite;
animation: ${shineAnim} 1.3s ease infinite;
-webkit-clip-path: polygon(5% 0%, 100% 0%, 90% 100%, 0% 100%);
clip-path: polygon(5% 0%, 100% 0%, 90% 100%, 0% 100%);
z-index: 2;
`;
export interface DownloadingButtonProps {
text: string;
onClick?: (e: React.MouseEvent<HTMLDivElement>) => void;
}
class DownloadingButton extends React.Component<DownloadingButtonProps> {
public render() {
return (
<DownloadingButtonView onClick={this.props.onClick} onMouseOver={this.playSound}>
<ButtonText>{this.props.text}</ButtonText>
<Shine />
</DownloadingButtonView>
);
}
private playSound = () => {
events.fire('play-sound', 'select-change');
}
}
export default DownloadingButton; |
const Shine = styled('div')` | random_line_split |
DownloadingButton.tsx | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
import * as React from 'react';
import * as events from '@csegames/camelot-unchained/lib/events';
import styled, { keyframes } from 'react-emotion';
import { ButtonText, PatchButtonStyle } from '../styles';
const goldenColor = 'rgba(192, 173, 124, 0.9)';
const shineAnim = keyframes`
0% {
left: 30px;
opacity: 0;
}
30% {
opacity: 0.5;
}
100% {
left: 35%;
opacity: 0;
}
`;
const DownloadingButtonView = styled('div')`
${PatchButtonStyle};
background: url(images/controller/play-button-grey.png);
filter: brightness(140%);
&:hover {
filter: brightness(140%);
}
&:hover:before {
animation: none;
-webkit-animation: none;
}
&:hover:after {
animation: none;
-webkit-animation: none;
}
`;
const Shine = styled('div')`
position: absolute;
height: 90%;
width: 70%;
border-left-radius: 50%;
background: linear-gradient(to right, transparent, ${goldenColor}, transparent);
bottom: 5px;
left: 15px;
opacity: 0;
-webkit-animation: ${shineAnim} 1.3s ease infinite;
animation: ${shineAnim} 1.3s ease infinite;
-webkit-clip-path: polygon(5% 0%, 100% 0%, 90% 100%, 0% 100%);
clip-path: polygon(5% 0%, 100% 0%, 90% 100%, 0% 100%);
z-index: 2;
`;
export interface DownloadingButtonProps {
text: string;
onClick?: (e: React.MouseEvent<HTMLDivElement>) => void;
}
class DownloadingButton extends React.Component<DownloadingButtonProps> {
public render() |
private playSound = () => {
events.fire('play-sound', 'select-change');
}
}
export default DownloadingButton;
| {
return (
<DownloadingButtonView onClick={this.props.onClick} onMouseOver={this.playSound}>
<ButtonText>{this.props.text}</ButtonText>
<Shine />
</DownloadingButtonView>
);
} | identifier_body |
sintez.js |
$(document).ready(function(){
$("#dropdownleft").hover(
function() {
$('.dropdown-menu', this).stop( true, true ).slideDown("fast");
$(this).toggleClass('open');
},
function() {
$('.dropdown-menu', this).stop( true, true ).slideUp("fast");
$(this).toggleClass('open');
}
);
//
// Language
$('#form-language .language-select').on('click', function(e) {
e.preventDefault();
$('#form-language input[name=\'code\']').val($(this).attr('name'));
$('#form-language').submit();
});
// Zone
$('#form-zone .zone-select').on('click', function(e) {
e.preventDefault();
$('#form-zone input[name=\'code\']').val($(this).attr('name'));
console.log( "FORM-ZONE: ", $('#form-zone input[name=\'code\']').val($(this).attr('name')) );
$('#form-zone').submit();
});
}); | /* sintez.js */ | random_line_split | |
three_dim_stats.py | """
30 Oct 2013
"""
from pytadbit.eqv_rms_drms import rmsdRMSD_wrapper
from pytadbit.consistency import consistency_wrapper
from itertools import combinations
import numpy as np
from math import pi, sqrt, cos, sin, acos
def generate_sphere_points(n=100):
"""
Returns list of 3d coordinates of points on a sphere using the
Golden Section Spiral algorithm.
:param n: number of points in the sphere
:returns a sphere of radius 1, centered in the origin
"""
points = []
inc = pi * (3 - sqrt(5))
offset = 2 / float(n)
for k in range(int(n)):
y = k * offset - 1 + (offset / 2)
r = sqrt(1 - y*y)
phi = k * inc
# points.append(dict((('x', cos(phi) * r),('y', y),('z', sin(phi) * r))))
points.append((cos(phi) * r, y, sin(phi) * r))
return points
def get_center_of_mass(x, y, z, zeros):
"""
get the center of mass of a given object with list of x, y, z coordinates
"""
xm = ym = zm = 0.
size = len(x)
subsize = 0
for i in xrange(size):
if not zeros[i]:
continue
subsize += 1
xm += x[i]
ym += y[i]
zm += z[i]
xm /= subsize
ym /= subsize
zm /= subsize
return xm, ym, zm
def mass_center(x, y, z, zeros):
"""
Transforms coordinates according to the center of mass
:param x: list of x coordinates
:param y: list of y coordinates
:param z: list of z coordinates
"""
xm, ym, zm = get_center_of_mass(x, y, z, zeros)
for i in xrange(len(x)):
x[i] -= xm
y[i] -= ym
z[i] -= zm
# def generate_circle_points(x, y, z, a, b, c, u, v, w, n):
# """
# Returns list of 3d coordinates of points on a circle using the
# Rodrigues rotation formula.
#
# see *Murray, G. (2013). Rotation About an Arbitrary Axis in 3 Dimensions*
# for details
#
# :param x: x coordinate of a point somewhere on the circle
# :param y: y coordinate of a point somewhere on the circle
# :param z: z coordinate of a point somewhere on the circle
# :param a: x coordinate of the center
# :param b: y coordinate of the center
# :param c: z coordinate of the center
# :param u: 1st element of a vector in the same plane as the circle
# :param v: 2nd element of a vector in the same plane as the circle
# :param w: 3rd element of a vector in the same plane as the circle
# :param n: number of points in the circle
#
# TODO: try simplification for a=b=c=0 (and do the translation in the main
# function)
# """
# points = []
# offset = 2 * pi / float(n)
# u_2 = u**2
# v_2 = v**2
# w_2 = w**2
# dst = u_2 + v_2 + w_2
# sqrtdst = sqrt(dst)
# uxvywz = - u*x - v*y - w*z
# b_v = b*v
# c_w = c*w
# a_u = a*u
# one = (a * (v_2 + w_2) - u*(b_v + c_w + uxvywz))
# two = (b * (u_2 + w_2) - v*(a_u + c_w + uxvywz))
# tre = (c * (u_2 + v_2) - w*(a_u + b_v + uxvywz))
# onep = sqrtdst * (-c*v + b*w - w*y + v*z)
# twop = sqrtdst * ( c*u - a*w + w*x - u*z)
# trep = sqrtdst * (-b*u + a*v - v*x + u*y)
# for k in range(int(n)):
# ang = k * offset
# cosang = cos(ang)
# dcosang = cosang * dst
# sinang = sin(ang)
# points.append([(one * (1 - cosang) + x * dcosang + onep * sinang) / dst,
# (two * (1 - cosang) + y * dcosang + twop * sinang) / dst,
# (tre * (1 - cosang) + z * dcosang + trep * sinang) / dst]
# )
# return points
def rotate_among_y_axis(x, y, z, angle):
"""
Rotate and object with a list of x, y, z coordinates among its center of
mass
"""
xj = []
yj = []
zj = []
for xi, yi, zi in zip(*(x, y, z)):
#dist = square_distance((xi, yi, zi), center_of_mass)
xj.append(xi*cos(angle) + zi*sin(angle))
yj.append(yi)
zj.append(xi*-sin(angle)+zi*cos(angle))
return xj, yj, zj
def find_angle_rotation_improve_x(x, y, z, center_of_mass):
"""
Finds the rotation angle needed to face the longest edge of the molecule
"""
# find most distant point from center of mass:
coords = zip(*(x, y, z))
xdst, ydst, zdst = max(coords, key=lambda i: square_distance(i, center_of_mass))
dist = distance((xdst, ydst, zdst), center_of_mass)
angle = acos((-xdst**2 - (dist + sqrt(dist**2 - xdst**2))) /
(2 * dist**2) + 1)
return angle
def generate_circle_points(x, y, z, u, v, w, n):
"""
Returns list of 3d coordinates of points on a circle using the
Rodrigues rotation formula.
see *Murray, G. (2013). Rotation About an Arbitrary Axis in 3 Dimensions*
for details
:param x: x coordinate of a point somewhere on the circle
:param y: y coordinate of a point somewhere on the circle
:param z: z coordinate of a point somewhere on the circle
:param a: x coordinate of the center
:param b: y coordinate of the center
:param c: z coordinate of the center
:param u: 1st element of a vector in the same plane as the circle
:param v: 2nd element of a vector in the same plane as the circle
:param w: 3rd element of a vector in the same plane as the circle
:param n: number of points in the circle
TODO: try simplification for a=b=c=0 (and do the translation in the main
function)
"""
points = []
offset = 2 * pi / float(n)
u_2 = u**2
v_2 = v**2
w_2 = w**2
dst = u_2 + v_2 + w_2
sqrtdst = sqrt(dst)
uxvywz = - u*x - v*y - w*z
one = (-u * (uxvywz))
two = (-v * (uxvywz))
tre = (-w * (uxvywz))
onep = sqrtdst * (- w*y + v*z)
twop = sqrtdst * (+ w*x - u*z)
trep = sqrtdst * (- v*x + u*y)
for k in range(int(n)):
ang = k * offset
cosang = cos(ang)
dcosang = cosang * dst
sinang = sin(ang)
points.append([(one * (1 - cosang) + x * dcosang + onep * sinang) / dst,
(two * (1 - cosang) + y * dcosang + twop * sinang) / dst,
(tre * (1 - cosang) + z * dcosang + trep * sinang) / dst]
)
return points
def square_distance(part1, part2):
"""
Calculates the square distance between two particles.
:param part1: coordinate (dict format with x, y, z keys)
:param part2: coordinate (dict format with x, y, z keys)
:returns: square distance between two points in space
"""
return ((part1[0] - part2[0])**2 +
(part1[1] - part2[1])**2 +
(part1[2] - part2[2])**2)
def fast_square_distance(x1, y1, z1, x2, y2, z2):
"""
Calculates the square distance between two coordinates.
:param part1: coordinate (dict format with x, y, z keys)
:param part2: coordinate (dict format with x, y, z keys)
:returns: square distance between two points in space
"""
return ((x1 - x2)**2 +
(y1 - y2)**2 +
(z1 - z2)**2)
def distance(part1, part2):
"""
Calculates the distance between two particles.
:param part1: coordinate in list format (x, y, z)
:param part2: coordinate in list format (x, y, z)
:returns: distance between two points in space
"""
return sqrt((part1[0] - part2[0])**2 +
(part1[1] - part2[1])**2 +
(part1[2] - part2[2])**2)
def angle_between_3_points(point1, point2, point3):
"""
Calculates the angle between 3 particles
Given three particles A, B and C, the angle g (angle ACB, shown below):
::
A
/|
/i| | c/ |
/ |
/ |
B )g |b
\ |
\ |
a\ |
\h|
\|
C
is given by the theorem of Al-Kashi:
.. math::
b^2 = a^2 + c^2 - 2ac\cos(g)
:param point1: list of 3 coordinate for x, y and z
:param point2: list of 3 coordinate for x, y and z
:param point3: list of 3 coordinate for x, y and z
:returns: angle in radians
"""
a = distance(point2, point3)
c = distance(point1, point2)
b = distance(point1, point3)
try:
g = acos((a**2 - b**2 + c**2) / (2 * a * c))
except ValueError:
g = 0.
return g
def calc_consistency(models, nloci, zeros, dcutoff=200):
combines = list(combinations(models, 2))
parts = [0 for _ in xrange(nloci)]
for pm in consistency_wrapper([models[m]['x'] for m in models],
[models[m]['y'] for m in models],
[models[m]['z'] for m in models],
zeros,
nloci, dcutoff, range(len(models)),
len(models)):
for i, p in enumerate(pm):
parts[i] += p
return [float(p)/len(combines) * 100 for p in parts]
def calc_eqv_rmsd(models, nloci, zeros, dcutoff=200, one=False, what='score',
normed=True):
"""
Calculates the RMSD, dRMSD, the number of equivalent positions and a score
combining these three measures. The measure are done between a group of
models in a one against all manner.
:param nloci: number of particles per model
:param zeros: list of True/False representing particles to skip
:param 200 dcutoff: distance in nanometer from which it is considered
that two particles are separated.
:param 0.75 fact: Factor for equivalent positions
:param False one: if True assumes that only two models are passed, and
returns the rmsd of their comparison
:param 'score' what: values to return. Can be one of 'score', 'rmsd',
'drmsd' or 'eqv'
:param True normed: normalize result by maximum value (only applies to rmsd
and drmsd)
:returns: a score of each pairwise comparison according to:
.. math::
score_i = eqvs_i \\times \\frac{dRMSD_i / max(dRMSD)}
{RMSD_i / max(RMSD)}
where :math:`eqvs_i` is the number of equivalent position for the ith
pairwise model comparison.
"""
what = what.lower()
if not what in ['score', 'rmsd', 'drmsd', 'eqv']:
raise NotImplementedError("Only 'score', 'rmsd', 'drmsd' or 'eqv' " +
"features are available\n")
# remove particles with zeros from calculation
x = []
y = []
z = []
for m in xrange(len(models)):
x.append([models[m]['x'][i] for i in xrange(nloci) if zeros[i]])
y.append([models[m]['y'][i] for i in xrange(nloci) if zeros[i]])
z.append([models[m]['z'][i] for i in xrange(nloci) if zeros[i]])
zeros = tuple([True for _ in xrange(len(x[0]))])
scores = rmsdRMSD_wrapper(x, y, z, zeros, len(zeros),
dcutoff, range(len(models)), len(models),
int(one), what, int(normed))
return scores
def dihedral(a, b, c, d):
"""
Calculates dihedral angle between 4 points in 3D (array with x,y,z)
"""
v1 = getNormedVector(b - a)
v2 = getNormedVector(b - c)
v3 = getNormedVector(c - b)
v4 = getNormedVector(c - d)
v1v2 = np.cross(v1, v2)
v2v3 = np.cross(v3, v4)
sign = -1 if np.linalg.det([v2, v1v2, v2v3]) < 0 else 1
angle = getAngle(v1v2, v2v3)
angle, sign = (angle, sign) if angle <= 90 else (180 - angle, - sign)
return sign * angle
def getNormedVector(dif):
return (dif) / np.linalg.norm(dif)
def getAngle(v1v2, v2v3):
return np.rad2deg(
np.arccos(np.dot(
v1v2 / np.linalg.norm(v1v2),
v2v3.T / np.linalg.norm(v2v3)))
)
def build_mesh(xis, yis, zis, nloci, nump, radius, superradius, include_edges):
"""
Main function for the calculation of the accessibility of a model.
"""
superradius = superradius or 1
# number of dots in a circle is dependent the ones in a sphere
numc = sqrt(nump) * sqrt(pi)
right_angle = pi / 2 - pi / numc
# keeps the remaining of integer conversion, to correct
remaining = int(100*(numc - int(numc)) + 0.5)
c_count = 0
# number of circles per sphere needed to get previous equality are
# dependent of:
fact = float(nump)/numc/(2*radius)
# starts big loop
points = [] # stores the particle coordinates and,
# if include_edges is True, the edge segments
subpoints = [] # store the coordinates of each dot in the mesh
supersubpoints = [] # store the coordinates of each dot in the mesh
positions = {} # a dict to get dots belonging to a given point
sphere = generate_sphere_points(nump)
i = 0
for i in xrange(nloci - 1):
modelx = xis[i]
modely = yis[i]
modelz = zis[i]
modelx1 = xis[i+1]
modely1 = yis[i+1]
modelz1 = zis[i+1]
if i < nloci - 2:
modelx2 = xis[i+2]
modely2 = yis[i+2]
modelz2 = zis[i+2]
if i:
modelx_1 = xis[i-1]
modely_1 = yis[i-1]
modelz_1 = zis[i-1]
point = [modelx, modely, modelz]
points.append(point)
# get minimum length from next particle to display the sphere dot
adj1 = distance(point, [modelx1, modely1, modelz1])
# find a vector orthogonal to the axe between particle i and i+1
difx = modelx - modelx1
dify = modely - modely1
difz = modelz - modelz1
# orthox = 1.
# orthoy = 1.
orthoz = -(difx + dify) / difz
#normer = sqrt(orthox**2 + orthoy**2 + orthoz**2) / radius
normer = sqrt(2. + orthoz**2)# / radius
orthox = 1. / normer
orthoy = 1. / normer
orthoz /= normer
# define the number of circle to draw in this section
between = int(fact * adj1 + 0.5)
try:
stepx = difx / between
stepy = dify / between
stepz = difz / between
except ZeroDivisionError:
stepx = stepy = stepz = 0
hyp1 = sqrt(adj1**2 + radius**2)
# this is an attempt of correction for the integrity of dots
# uses intercept theorem
hyp1 = (hyp1 - hyp1 / (2 * (1 + between)))**2
# get minimum length from prev particle to display the sphere dot
if i:
adj2 = distance(point, [modelx_1, modely_1, modelz_1])
hyp2 = sqrt(adj2**2 + radius**2)
# this is an attempt of correction for the integrity of dots
hyp2 = (hyp2 - hyp2 / (2 * (1 + between)))**2
# set sphere around each particle
for xxx, yyy, zzz in sphere:
thing = [xxx * radius + modelx,
yyy * radius + modely,
zzz * radius + modelz]
# same for super mesh
superthing = [xxx * superradius + modelx,
yyy * superradius + modely,
zzz * superradius + modelz]
# only place mesh outside torsion angle
if fast_square_distance(modelx1, modely1, modelz1,
thing[0], thing[1], thing[2]) > hyp1:
if not i:
subpoints.append(thing)
supersubpoints.append(superthing)
elif fast_square_distance(modelx_1, modely_1, modelz_1,
thing[0], thing[1], thing[2]) > hyp2:
subpoints.append(thing)
supersubpoints.append(superthing)
else:
continue
positions.setdefault(i, []).append(len(subpoints)-1)
def _add_circle(k, ptx, pty, ptz):
for spoint in generate_circle_points(
orthox, orthoy, orthoz, difx ,dify, difz,
# correction for integer of numc
numc + (1 if c_count%100 < remaining else 0)):
dot = [spoint[0] * radius + ptx,
spoint[1] * radius + pty,
spoint[2] * radius + ptz]
superdot = [spoint[0] * superradius + ptx,
spoint[1] * superradius + pty,
spoint[2] * superradius + ptz]
# check that dot in circle is not too close from next edge
if i < nloci - 2:
hyp = distance((modelx1, modely1, modelz1), dot)
ang = angle_between_3_points(dot,
(modelx1, modely1, modelz1),
(modelx2, modely2, modelz2))
if ang < right_angle:
if sin(ang) * hyp < radius:
continue
# check that dot in circle is not too close from previous edge
if i:
hyp = distance((modelx, modely, modelz), dot)
ang = angle_between_3_points(dot,
(modelx, modely, modelz),
(modelx_1, modely_1, modelz_1))
if ang < right_angle:
if sin(ang) * hyp < radius:
continue
# print 'here'
subpoints.append([dot[0], dot[1], dot[2]])
supersubpoints.append([superdot[0], superdot[1], superdot[2]])
positions.setdefault(i + float(k)/between, []).append(
len(subpoints) - 1)
# define slices
for k in xrange(between - 1, 0, -1):
point = [modelx - k * stepx, modely - k * stepy, modelz - k * stepz]
points.append(point)
pointx, pointy, pointz = point
if not include_edges:
continue
# define circles
_add_circle(k, pointx, pointy, pointz)
c_count += 1
# add last point!!
point = [xis[i+1], yis[i+1], zis[i+1]]
points.append(point)
# and its sphere
adj = distance(point, [modelx, modely, modelz])
hyp2 = sqrt(adj**2 + radius**2)
hyp2 = (hyp2 - hyp2 / (2 * (1 + between)))**2
for xxx, yyy, zzz in sphere:
thing = [xxx * radius + modelx1,
yyy * radius + modely1,
zzz * radius + modelz1]
superthing = [xxx * superradius + modelx1,
yyy * superradius + modely1,
zzz * superradius + modelz1]
if fast_square_distance(modelx, modely, modelz,
thing[0], thing[1], thing[2]) > hyp2:
subpoints.append(thing)
supersubpoints.append(superthing)
positions.setdefault(i+1, []).append(len(subpoints)-1)
return points, subpoints, supersubpoints, positions | random_line_split | |
three_dim_stats.py | """
30 Oct 2013
"""
from pytadbit.eqv_rms_drms import rmsdRMSD_wrapper
from pytadbit.consistency import consistency_wrapper
from itertools import combinations
import numpy as np
from math import pi, sqrt, cos, sin, acos
def generate_sphere_points(n=100):
"""
Returns list of 3d coordinates of points on a sphere using the
Golden Section Spiral algorithm.
:param n: number of points in the sphere
:returns a sphere of radius 1, centered in the origin
"""
points = []
inc = pi * (3 - sqrt(5))
offset = 2 / float(n)
for k in range(int(n)):
y = k * offset - 1 + (offset / 2)
r = sqrt(1 - y*y)
phi = k * inc
# points.append(dict((('x', cos(phi) * r),('y', y),('z', sin(phi) * r))))
points.append((cos(phi) * r, y, sin(phi) * r))
return points
def get_center_of_mass(x, y, z, zeros):
"""
get the center of mass of a given object with list of x, y, z coordinates
"""
xm = ym = zm = 0.
size = len(x)
subsize = 0
for i in xrange(size):
if not zeros[i]:
continue
subsize += 1
xm += x[i]
ym += y[i]
zm += z[i]
xm /= subsize
ym /= subsize
zm /= subsize
return xm, ym, zm
def mass_center(x, y, z, zeros):
"""
Transforms coordinates according to the center of mass
:param x: list of x coordinates
:param y: list of y coordinates
:param z: list of z coordinates
"""
xm, ym, zm = get_center_of_mass(x, y, z, zeros)
for i in xrange(len(x)):
x[i] -= xm
y[i] -= ym
z[i] -= zm
# def generate_circle_points(x, y, z, a, b, c, u, v, w, n):
# """
# Returns list of 3d coordinates of points on a circle using the
# Rodrigues rotation formula.
#
# see *Murray, G. (2013). Rotation About an Arbitrary Axis in 3 Dimensions*
# for details
#
# :param x: x coordinate of a point somewhere on the circle
# :param y: y coordinate of a point somewhere on the circle
# :param z: z coordinate of a point somewhere on the circle
# :param a: x coordinate of the center
# :param b: y coordinate of the center
# :param c: z coordinate of the center
# :param u: 1st element of a vector in the same plane as the circle
# :param v: 2nd element of a vector in the same plane as the circle
# :param w: 3rd element of a vector in the same plane as the circle
# :param n: number of points in the circle
#
# TODO: try simplification for a=b=c=0 (and do the translation in the main
# function)
# """
# points = []
# offset = 2 * pi / float(n)
# u_2 = u**2
# v_2 = v**2
# w_2 = w**2
# dst = u_2 + v_2 + w_2
# sqrtdst = sqrt(dst)
# uxvywz = - u*x - v*y - w*z
# b_v = b*v
# c_w = c*w
# a_u = a*u
# one = (a * (v_2 + w_2) - u*(b_v + c_w + uxvywz))
# two = (b * (u_2 + w_2) - v*(a_u + c_w + uxvywz))
# tre = (c * (u_2 + v_2) - w*(a_u + b_v + uxvywz))
# onep = sqrtdst * (-c*v + b*w - w*y + v*z)
# twop = sqrtdst * ( c*u - a*w + w*x - u*z)
# trep = sqrtdst * (-b*u + a*v - v*x + u*y)
# for k in range(int(n)):
# ang = k * offset
# cosang = cos(ang)
# dcosang = cosang * dst
# sinang = sin(ang)
# points.append([(one * (1 - cosang) + x * dcosang + onep * sinang) / dst,
# (two * (1 - cosang) + y * dcosang + twop * sinang) / dst,
# (tre * (1 - cosang) + z * dcosang + trep * sinang) / dst]
# )
# return points
def rotate_among_y_axis(x, y, z, angle):
"""
Rotate and object with a list of x, y, z coordinates among its center of
mass
"""
xj = []
yj = []
zj = []
for xi, yi, zi in zip(*(x, y, z)):
#dist = square_distance((xi, yi, zi), center_of_mass)
xj.append(xi*cos(angle) + zi*sin(angle))
yj.append(yi)
zj.append(xi*-sin(angle)+zi*cos(angle))
return xj, yj, zj
def find_angle_rotation_improve_x(x, y, z, center_of_mass):
"""
Finds the rotation angle needed to face the longest edge of the molecule
"""
# find most distant point from center of mass:
coords = zip(*(x, y, z))
xdst, ydst, zdst = max(coords, key=lambda i: square_distance(i, center_of_mass))
dist = distance((xdst, ydst, zdst), center_of_mass)
angle = acos((-xdst**2 - (dist + sqrt(dist**2 - xdst**2))) /
(2 * dist**2) + 1)
return angle
def generate_circle_points(x, y, z, u, v, w, n):
"""
Returns list of 3d coordinates of points on a circle using the
Rodrigues rotation formula.
see *Murray, G. (2013). Rotation About an Arbitrary Axis in 3 Dimensions*
for details
:param x: x coordinate of a point somewhere on the circle
:param y: y coordinate of a point somewhere on the circle
:param z: z coordinate of a point somewhere on the circle
:param a: x coordinate of the center
:param b: y coordinate of the center
:param c: z coordinate of the center
:param u: 1st element of a vector in the same plane as the circle
:param v: 2nd element of a vector in the same plane as the circle
:param w: 3rd element of a vector in the same plane as the circle
:param n: number of points in the circle
TODO: try simplification for a=b=c=0 (and do the translation in the main
function)
"""
points = []
offset = 2 * pi / float(n)
u_2 = u**2
v_2 = v**2
w_2 = w**2
dst = u_2 + v_2 + w_2
sqrtdst = sqrt(dst)
uxvywz = - u*x - v*y - w*z
one = (-u * (uxvywz))
two = (-v * (uxvywz))
tre = (-w * (uxvywz))
onep = sqrtdst * (- w*y + v*z)
twop = sqrtdst * (+ w*x - u*z)
trep = sqrtdst * (- v*x + u*y)
for k in range(int(n)):
ang = k * offset
cosang = cos(ang)
dcosang = cosang * dst
sinang = sin(ang)
points.append([(one * (1 - cosang) + x * dcosang + onep * sinang) / dst,
(two * (1 - cosang) + y * dcosang + twop * sinang) / dst,
(tre * (1 - cosang) + z * dcosang + trep * sinang) / dst]
)
return points
def square_distance(part1, part2):
"""
Calculates the square distance between two particles.
:param part1: coordinate (dict format with x, y, z keys)
:param part2: coordinate (dict format with x, y, z keys)
:returns: square distance between two points in space
"""
return ((part1[0] - part2[0])**2 +
(part1[1] - part2[1])**2 +
(part1[2] - part2[2])**2)
def fast_square_distance(x1, y1, z1, x2, y2, z2):
"""
Calculates the square distance between two coordinates.
:param part1: coordinate (dict format with x, y, z keys)
:param part2: coordinate (dict format with x, y, z keys)
:returns: square distance between two points in space
"""
return ((x1 - x2)**2 +
(y1 - y2)**2 +
(z1 - z2)**2)
def distance(part1, part2):
"""
Calculates the distance between two particles.
:param part1: coordinate in list format (x, y, z)
:param part2: coordinate in list format (x, y, z)
:returns: distance between two points in space
"""
return sqrt((part1[0] - part2[0])**2 +
(part1[1] - part2[1])**2 +
(part1[2] - part2[2])**2)
def angle_between_3_points(point1, point2, point3):
"""
Calculates the angle between 3 particles
Given three particles A, B and C, the angle g (angle ACB, shown below):
::
A
/|
/i|
c/ |
/ |
/ |
B )g |b
\ |
\ |
a\ |
\h|
\|
C
is given by the theorem of Al-Kashi:
.. math::
b^2 = a^2 + c^2 - 2ac\cos(g)
:param point1: list of 3 coordinate for x, y and z
:param point2: list of 3 coordinate for x, y and z
:param point3: list of 3 coordinate for x, y and z
:returns: angle in radians
"""
a = distance(point2, point3)
c = distance(point1, point2)
b = distance(point1, point3)
try:
g = acos((a**2 - b**2 + c**2) / (2 * a * c))
except ValueError:
g = 0.
return g
def calc_consistency(models, nloci, zeros, dcutoff=200):
combines = list(combinations(models, 2))
parts = [0 for _ in xrange(nloci)]
for pm in consistency_wrapper([models[m]['x'] for m in models],
[models[m]['y'] for m in models],
[models[m]['z'] for m in models],
zeros,
nloci, dcutoff, range(len(models)),
len(models)):
for i, p in enumerate(pm):
parts[i] += p
return [float(p)/len(combines) * 100 for p in parts]
def calc_eqv_rmsd(models, nloci, zeros, dcutoff=200, one=False, what='score',
normed=True):
"""
Calculates the RMSD, dRMSD, the number of equivalent positions and a score
combining these three measures. The measure are done between a group of
models in a one against all manner.
:param nloci: number of particles per model
:param zeros: list of True/False representing particles to skip
:param 200 dcutoff: distance in nanometer from which it is considered
that two particles are separated.
:param 0.75 fact: Factor for equivalent positions
:param False one: if True assumes that only two models are passed, and
returns the rmsd of their comparison
:param 'score' what: values to return. Can be one of 'score', 'rmsd',
'drmsd' or 'eqv'
:param True normed: normalize result by maximum value (only applies to rmsd
and drmsd)
:returns: a score of each pairwise comparison according to:
.. math::
score_i = eqvs_i \\times \\frac{dRMSD_i / max(dRMSD)}
{RMSD_i / max(RMSD)}
where :math:`eqvs_i` is the number of equivalent position for the ith
pairwise model comparison.
"""
what = what.lower()
if not what in ['score', 'rmsd', 'drmsd', 'eqv']:
raise NotImplementedError("Only 'score', 'rmsd', 'drmsd' or 'eqv' " +
"features are available\n")
# remove particles with zeros from calculation
x = []
y = []
z = []
for m in xrange(len(models)):
x.append([models[m]['x'][i] for i in xrange(nloci) if zeros[i]])
y.append([models[m]['y'][i] for i in xrange(nloci) if zeros[i]])
z.append([models[m]['z'][i] for i in xrange(nloci) if zeros[i]])
zeros = tuple([True for _ in xrange(len(x[0]))])
scores = rmsdRMSD_wrapper(x, y, z, zeros, len(zeros),
dcutoff, range(len(models)), len(models),
int(one), what, int(normed))
return scores
def dihedral(a, b, c, d):
"""
Calculates dihedral angle between 4 points in 3D (array with x,y,z)
"""
v1 = getNormedVector(b - a)
v2 = getNormedVector(b - c)
v3 = getNormedVector(c - b)
v4 = getNormedVector(c - d)
v1v2 = np.cross(v1, v2)
v2v3 = np.cross(v3, v4)
sign = -1 if np.linalg.det([v2, v1v2, v2v3]) < 0 else 1
angle = getAngle(v1v2, v2v3)
angle, sign = (angle, sign) if angle <= 90 else (180 - angle, - sign)
return sign * angle
def getNormedVector(dif):
return (dif) / np.linalg.norm(dif)
def getAngle(v1v2, v2v3):
return np.rad2deg(
np.arccos(np.dot(
v1v2 / np.linalg.norm(v1v2),
v2v3.T / np.linalg.norm(v2v3)))
)
def build_mesh(xis, yis, zis, nloci, nump, radius, superradius, include_edges):
| """
Main function for the calculation of the accessibility of a model.
"""
superradius = superradius or 1
# number of dots in a circle is dependent the ones in a sphere
numc = sqrt(nump) * sqrt(pi)
right_angle = pi / 2 - pi / numc
# keeps the remaining of integer conversion, to correct
remaining = int(100*(numc - int(numc)) + 0.5)
c_count = 0
# number of circles per sphere needed to get previous equality are
# dependent of:
fact = float(nump)/numc/(2*radius)
# starts big loop
points = [] # stores the particle coordinates and,
# if include_edges is True, the edge segments
subpoints = [] # store the coordinates of each dot in the mesh
supersubpoints = [] # store the coordinates of each dot in the mesh
positions = {} # a dict to get dots belonging to a given point
sphere = generate_sphere_points(nump)
i = 0
for i in xrange(nloci - 1):
modelx = xis[i]
modely = yis[i]
modelz = zis[i]
modelx1 = xis[i+1]
modely1 = yis[i+1]
modelz1 = zis[i+1]
if i < nloci - 2:
modelx2 = xis[i+2]
modely2 = yis[i+2]
modelz2 = zis[i+2]
if i:
modelx_1 = xis[i-1]
modely_1 = yis[i-1]
modelz_1 = zis[i-1]
point = [modelx, modely, modelz]
points.append(point)
# get minimum length from next particle to display the sphere dot
adj1 = distance(point, [modelx1, modely1, modelz1])
# find a vector orthogonal to the axe between particle i and i+1
difx = modelx - modelx1
dify = modely - modely1
difz = modelz - modelz1
# orthox = 1.
# orthoy = 1.
orthoz = -(difx + dify) / difz
#normer = sqrt(orthox**2 + orthoy**2 + orthoz**2) / radius
normer = sqrt(2. + orthoz**2)# / radius
orthox = 1. / normer
orthoy = 1. / normer
orthoz /= normer
# define the number of circle to draw in this section
between = int(fact * adj1 + 0.5)
try:
stepx = difx / between
stepy = dify / between
stepz = difz / between
except ZeroDivisionError:
stepx = stepy = stepz = 0
hyp1 = sqrt(adj1**2 + radius**2)
# this is an attempt of correction for the integrity of dots
# uses intercept theorem
hyp1 = (hyp1 - hyp1 / (2 * (1 + between)))**2
# get minimum length from prev particle to display the sphere dot
if i:
adj2 = distance(point, [modelx_1, modely_1, modelz_1])
hyp2 = sqrt(adj2**2 + radius**2)
# this is an attempt of correction for the integrity of dots
hyp2 = (hyp2 - hyp2 / (2 * (1 + between)))**2
# set sphere around each particle
for xxx, yyy, zzz in sphere:
thing = [xxx * radius + modelx,
yyy * radius + modely,
zzz * radius + modelz]
# same for super mesh
superthing = [xxx * superradius + modelx,
yyy * superradius + modely,
zzz * superradius + modelz]
# only place mesh outside torsion angle
if fast_square_distance(modelx1, modely1, modelz1,
thing[0], thing[1], thing[2]) > hyp1:
if not i:
subpoints.append(thing)
supersubpoints.append(superthing)
elif fast_square_distance(modelx_1, modely_1, modelz_1,
thing[0], thing[1], thing[2]) > hyp2:
subpoints.append(thing)
supersubpoints.append(superthing)
else:
continue
positions.setdefault(i, []).append(len(subpoints)-1)
def _add_circle(k, ptx, pty, ptz):
for spoint in generate_circle_points(
orthox, orthoy, orthoz, difx ,dify, difz,
# correction for integer of numc
numc + (1 if c_count%100 < remaining else 0)):
dot = [spoint[0] * radius + ptx,
spoint[1] * radius + pty,
spoint[2] * radius + ptz]
superdot = [spoint[0] * superradius + ptx,
spoint[1] * superradius + pty,
spoint[2] * superradius + ptz]
# check that dot in circle is not too close from next edge
if i < nloci - 2:
hyp = distance((modelx1, modely1, modelz1), dot)
ang = angle_between_3_points(dot,
(modelx1, modely1, modelz1),
(modelx2, modely2, modelz2))
if ang < right_angle:
if sin(ang) * hyp < radius:
continue
# check that dot in circle is not too close from previous edge
if i:
hyp = distance((modelx, modely, modelz), dot)
ang = angle_between_3_points(dot,
(modelx, modely, modelz),
(modelx_1, modely_1, modelz_1))
if ang < right_angle:
if sin(ang) * hyp < radius:
continue
# print 'here'
subpoints.append([dot[0], dot[1], dot[2]])
supersubpoints.append([superdot[0], superdot[1], superdot[2]])
positions.setdefault(i + float(k)/between, []).append(
len(subpoints) - 1)
# define slices
for k in xrange(between - 1, 0, -1):
point = [modelx - k * stepx, modely - k * stepy, modelz - k * stepz]
points.append(point)
pointx, pointy, pointz = point
if not include_edges:
continue
# define circles
_add_circle(k, pointx, pointy, pointz)
c_count += 1
# add last point!!
point = [xis[i+1], yis[i+1], zis[i+1]]
points.append(point)
# and its sphere
adj = distance(point, [modelx, modely, modelz])
hyp2 = sqrt(adj**2 + radius**2)
hyp2 = (hyp2 - hyp2 / (2 * (1 + between)))**2
for xxx, yyy, zzz in sphere:
thing = [xxx * radius + modelx1,
yyy * radius + modely1,
zzz * radius + modelz1]
superthing = [xxx * superradius + modelx1,
yyy * superradius + modely1,
zzz * superradius + modelz1]
if fast_square_distance(modelx, modely, modelz,
thing[0], thing[1], thing[2]) > hyp2:
subpoints.append(thing)
supersubpoints.append(superthing)
positions.setdefault(i+1, []).append(len(subpoints)-1)
return points, subpoints, supersubpoints, positions | identifier_body | |
three_dim_stats.py | """
30 Oct 2013
"""
from pytadbit.eqv_rms_drms import rmsdRMSD_wrapper
from pytadbit.consistency import consistency_wrapper
from itertools import combinations
import numpy as np
from math import pi, sqrt, cos, sin, acos
def generate_sphere_points(n=100):
"""
Returns list of 3d coordinates of points on a sphere using the
Golden Section Spiral algorithm.
:param n: number of points in the sphere
:returns a sphere of radius 1, centered in the origin
"""
points = []
inc = pi * (3 - sqrt(5))
offset = 2 / float(n)
for k in range(int(n)):
y = k * offset - 1 + (offset / 2)
r = sqrt(1 - y*y)
phi = k * inc
# points.append(dict((('x', cos(phi) * r),('y', y),('z', sin(phi) * r))))
points.append((cos(phi) * r, y, sin(phi) * r))
return points
def get_center_of_mass(x, y, z, zeros):
"""
get the center of mass of a given object with list of x, y, z coordinates
"""
xm = ym = zm = 0.
size = len(x)
subsize = 0
for i in xrange(size):
if not zeros[i]:
continue
subsize += 1
xm += x[i]
ym += y[i]
zm += z[i]
xm /= subsize
ym /= subsize
zm /= subsize
return xm, ym, zm
def mass_center(x, y, z, zeros):
"""
Transforms coordinates according to the center of mass
:param x: list of x coordinates
:param y: list of y coordinates
:param z: list of z coordinates
"""
xm, ym, zm = get_center_of_mass(x, y, z, zeros)
for i in xrange(len(x)):
x[i] -= xm
y[i] -= ym
z[i] -= zm
# def generate_circle_points(x, y, z, a, b, c, u, v, w, n):
# """
# Returns list of 3d coordinates of points on a circle using the
# Rodrigues rotation formula.
#
# see *Murray, G. (2013). Rotation About an Arbitrary Axis in 3 Dimensions*
# for details
#
# :param x: x coordinate of a point somewhere on the circle
# :param y: y coordinate of a point somewhere on the circle
# :param z: z coordinate of a point somewhere on the circle
# :param a: x coordinate of the center
# :param b: y coordinate of the center
# :param c: z coordinate of the center
# :param u: 1st element of a vector in the same plane as the circle
# :param v: 2nd element of a vector in the same plane as the circle
# :param w: 3rd element of a vector in the same plane as the circle
# :param n: number of points in the circle
#
# TODO: try simplification for a=b=c=0 (and do the translation in the main
# function)
# """
# points = []
# offset = 2 * pi / float(n)
# u_2 = u**2
# v_2 = v**2
# w_2 = w**2
# dst = u_2 + v_2 + w_2
# sqrtdst = sqrt(dst)
# uxvywz = - u*x - v*y - w*z
# b_v = b*v
# c_w = c*w
# a_u = a*u
# one = (a * (v_2 + w_2) - u*(b_v + c_w + uxvywz))
# two = (b * (u_2 + w_2) - v*(a_u + c_w + uxvywz))
# tre = (c * (u_2 + v_2) - w*(a_u + b_v + uxvywz))
# onep = sqrtdst * (-c*v + b*w - w*y + v*z)
# twop = sqrtdst * ( c*u - a*w + w*x - u*z)
# trep = sqrtdst * (-b*u + a*v - v*x + u*y)
# for k in range(int(n)):
# ang = k * offset
# cosang = cos(ang)
# dcosang = cosang * dst
# sinang = sin(ang)
# points.append([(one * (1 - cosang) + x * dcosang + onep * sinang) / dst,
# (two * (1 - cosang) + y * dcosang + twop * sinang) / dst,
# (tre * (1 - cosang) + z * dcosang + trep * sinang) / dst]
# )
# return points
def rotate_among_y_axis(x, y, z, angle):
"""
Rotate and object with a list of x, y, z coordinates among its center of
mass
"""
xj = []
yj = []
zj = []
for xi, yi, zi in zip(*(x, y, z)):
#dist = square_distance((xi, yi, zi), center_of_mass)
xj.append(xi*cos(angle) + zi*sin(angle))
yj.append(yi)
zj.append(xi*-sin(angle)+zi*cos(angle))
return xj, yj, zj
def find_angle_rotation_improve_x(x, y, z, center_of_mass):
"""
Finds the rotation angle needed to face the longest edge of the molecule
"""
# find most distant point from center of mass:
coords = zip(*(x, y, z))
xdst, ydst, zdst = max(coords, key=lambda i: square_distance(i, center_of_mass))
dist = distance((xdst, ydst, zdst), center_of_mass)
angle = acos((-xdst**2 - (dist + sqrt(dist**2 - xdst**2))) /
(2 * dist**2) + 1)
return angle
def generate_circle_points(x, y, z, u, v, w, n):
"""
Returns list of 3d coordinates of points on a circle using the
Rodrigues rotation formula.
see *Murray, G. (2013). Rotation About an Arbitrary Axis in 3 Dimensions*
for details
:param x: x coordinate of a point somewhere on the circle
:param y: y coordinate of a point somewhere on the circle
:param z: z coordinate of a point somewhere on the circle
:param a: x coordinate of the center
:param b: y coordinate of the center
:param c: z coordinate of the center
:param u: 1st element of a vector in the same plane as the circle
:param v: 2nd element of a vector in the same plane as the circle
:param w: 3rd element of a vector in the same plane as the circle
:param n: number of points in the circle
TODO: try simplification for a=b=c=0 (and do the translation in the main
function)
"""
points = []
offset = 2 * pi / float(n)
u_2 = u**2
v_2 = v**2
w_2 = w**2
dst = u_2 + v_2 + w_2
sqrtdst = sqrt(dst)
uxvywz = - u*x - v*y - w*z
one = (-u * (uxvywz))
two = (-v * (uxvywz))
tre = (-w * (uxvywz))
onep = sqrtdst * (- w*y + v*z)
twop = sqrtdst * (+ w*x - u*z)
trep = sqrtdst * (- v*x + u*y)
for k in range(int(n)):
ang = k * offset
cosang = cos(ang)
dcosang = cosang * dst
sinang = sin(ang)
points.append([(one * (1 - cosang) + x * dcosang + onep * sinang) / dst,
(two * (1 - cosang) + y * dcosang + twop * sinang) / dst,
(tre * (1 - cosang) + z * dcosang + trep * sinang) / dst]
)
return points
def square_distance(part1, part2):
"""
Calculates the square distance between two particles.
:param part1: coordinate (dict format with x, y, z keys)
:param part2: coordinate (dict format with x, y, z keys)
:returns: square distance between two points in space
"""
return ((part1[0] - part2[0])**2 +
(part1[1] - part2[1])**2 +
(part1[2] - part2[2])**2)
def fast_square_distance(x1, y1, z1, x2, y2, z2):
"""
Calculates the square distance between two coordinates.
:param part1: coordinate (dict format with x, y, z keys)
:param part2: coordinate (dict format with x, y, z keys)
:returns: square distance between two points in space
"""
return ((x1 - x2)**2 +
(y1 - y2)**2 +
(z1 - z2)**2)
def | (part1, part2):
"""
Calculates the distance between two particles.
:param part1: coordinate in list format (x, y, z)
:param part2: coordinate in list format (x, y, z)
:returns: distance between two points in space
"""
return sqrt((part1[0] - part2[0])**2 +
(part1[1] - part2[1])**2 +
(part1[2] - part2[2])**2)
def angle_between_3_points(point1, point2, point3):
"""
Calculates the angle between 3 particles
Given three particles A, B and C, the angle g (angle ACB, shown below):
::
A
/|
/i|
c/ |
/ |
/ |
B )g |b
\ |
\ |
a\ |
\h|
\|
C
is given by the theorem of Al-Kashi:
.. math::
b^2 = a^2 + c^2 - 2ac\cos(g)
:param point1: list of 3 coordinate for x, y and z
:param point2: list of 3 coordinate for x, y and z
:param point3: list of 3 coordinate for x, y and z
:returns: angle in radians
"""
a = distance(point2, point3)
c = distance(point1, point2)
b = distance(point1, point3)
try:
g = acos((a**2 - b**2 + c**2) / (2 * a * c))
except ValueError:
g = 0.
return g
def calc_consistency(models, nloci, zeros, dcutoff=200):
combines = list(combinations(models, 2))
parts = [0 for _ in xrange(nloci)]
for pm in consistency_wrapper([models[m]['x'] for m in models],
[models[m]['y'] for m in models],
[models[m]['z'] for m in models],
zeros,
nloci, dcutoff, range(len(models)),
len(models)):
for i, p in enumerate(pm):
parts[i] += p
return [float(p)/len(combines) * 100 for p in parts]
def calc_eqv_rmsd(models, nloci, zeros, dcutoff=200, one=False, what='score',
normed=True):
"""
Calculates the RMSD, dRMSD, the number of equivalent positions and a score
combining these three measures. The measure are done between a group of
models in a one against all manner.
:param nloci: number of particles per model
:param zeros: list of True/False representing particles to skip
:param 200 dcutoff: distance in nanometer from which it is considered
that two particles are separated.
:param 0.75 fact: Factor for equivalent positions
:param False one: if True assumes that only two models are passed, and
returns the rmsd of their comparison
:param 'score' what: values to return. Can be one of 'score', 'rmsd',
'drmsd' or 'eqv'
:param True normed: normalize result by maximum value (only applies to rmsd
and drmsd)
:returns: a score of each pairwise comparison according to:
.. math::
score_i = eqvs_i \\times \\frac{dRMSD_i / max(dRMSD)}
{RMSD_i / max(RMSD)}
where :math:`eqvs_i` is the number of equivalent position for the ith
pairwise model comparison.
"""
what = what.lower()
if not what in ['score', 'rmsd', 'drmsd', 'eqv']:
raise NotImplementedError("Only 'score', 'rmsd', 'drmsd' or 'eqv' " +
"features are available\n")
# remove particles with zeros from calculation
x = []
y = []
z = []
for m in xrange(len(models)):
x.append([models[m]['x'][i] for i in xrange(nloci) if zeros[i]])
y.append([models[m]['y'][i] for i in xrange(nloci) if zeros[i]])
z.append([models[m]['z'][i] for i in xrange(nloci) if zeros[i]])
zeros = tuple([True for _ in xrange(len(x[0]))])
scores = rmsdRMSD_wrapper(x, y, z, zeros, len(zeros),
dcutoff, range(len(models)), len(models),
int(one), what, int(normed))
return scores
def dihedral(a, b, c, d):
"""
Calculates dihedral angle between 4 points in 3D (array with x,y,z)
"""
v1 = getNormedVector(b - a)
v2 = getNormedVector(b - c)
v3 = getNormedVector(c - b)
v4 = getNormedVector(c - d)
v1v2 = np.cross(v1, v2)
v2v3 = np.cross(v3, v4)
sign = -1 if np.linalg.det([v2, v1v2, v2v3]) < 0 else 1
angle = getAngle(v1v2, v2v3)
angle, sign = (angle, sign) if angle <= 90 else (180 - angle, - sign)
return sign * angle
def getNormedVector(dif):
return (dif) / np.linalg.norm(dif)
def getAngle(v1v2, v2v3):
return np.rad2deg(
np.arccos(np.dot(
v1v2 / np.linalg.norm(v1v2),
v2v3.T / np.linalg.norm(v2v3)))
)
def build_mesh(xis, yis, zis, nloci, nump, radius, superradius, include_edges):
"""
Main function for the calculation of the accessibility of a model.
"""
superradius = superradius or 1
# number of dots in a circle is dependent the ones in a sphere
numc = sqrt(nump) * sqrt(pi)
right_angle = pi / 2 - pi / numc
# keeps the remaining of integer conversion, to correct
remaining = int(100*(numc - int(numc)) + 0.5)
c_count = 0
# number of circles per sphere needed to get previous equality are
# dependent of:
fact = float(nump)/numc/(2*radius)
# starts big loop
points = [] # stores the particle coordinates and,
# if include_edges is True, the edge segments
subpoints = [] # store the coordinates of each dot in the mesh
supersubpoints = [] # store the coordinates of each dot in the mesh
positions = {} # a dict to get dots belonging to a given point
sphere = generate_sphere_points(nump)
i = 0
for i in xrange(nloci - 1):
modelx = xis[i]
modely = yis[i]
modelz = zis[i]
modelx1 = xis[i+1]
modely1 = yis[i+1]
modelz1 = zis[i+1]
if i < nloci - 2:
modelx2 = xis[i+2]
modely2 = yis[i+2]
modelz2 = zis[i+2]
if i:
modelx_1 = xis[i-1]
modely_1 = yis[i-1]
modelz_1 = zis[i-1]
point = [modelx, modely, modelz]
points.append(point)
# get minimum length from next particle to display the sphere dot
adj1 = distance(point, [modelx1, modely1, modelz1])
# find a vector orthogonal to the axe between particle i and i+1
difx = modelx - modelx1
dify = modely - modely1
difz = modelz - modelz1
# orthox = 1.
# orthoy = 1.
orthoz = -(difx + dify) / difz
#normer = sqrt(orthox**2 + orthoy**2 + orthoz**2) / radius
normer = sqrt(2. + orthoz**2)# / radius
orthox = 1. / normer
orthoy = 1. / normer
orthoz /= normer
# define the number of circle to draw in this section
between = int(fact * adj1 + 0.5)
try:
stepx = difx / between
stepy = dify / between
stepz = difz / between
except ZeroDivisionError:
stepx = stepy = stepz = 0
hyp1 = sqrt(adj1**2 + radius**2)
# this is an attempt of correction for the integrity of dots
# uses intercept theorem
hyp1 = (hyp1 - hyp1 / (2 * (1 + between)))**2
# get minimum length from prev particle to display the sphere dot
if i:
adj2 = distance(point, [modelx_1, modely_1, modelz_1])
hyp2 = sqrt(adj2**2 + radius**2)
# this is an attempt of correction for the integrity of dots
hyp2 = (hyp2 - hyp2 / (2 * (1 + between)))**2
# set sphere around each particle
for xxx, yyy, zzz in sphere:
thing = [xxx * radius + modelx,
yyy * radius + modely,
zzz * radius + modelz]
# same for super mesh
superthing = [xxx * superradius + modelx,
yyy * superradius + modely,
zzz * superradius + modelz]
# only place mesh outside torsion angle
if fast_square_distance(modelx1, modely1, modelz1,
thing[0], thing[1], thing[2]) > hyp1:
if not i:
subpoints.append(thing)
supersubpoints.append(superthing)
elif fast_square_distance(modelx_1, modely_1, modelz_1,
thing[0], thing[1], thing[2]) > hyp2:
subpoints.append(thing)
supersubpoints.append(superthing)
else:
continue
positions.setdefault(i, []).append(len(subpoints)-1)
def _add_circle(k, ptx, pty, ptz):
for spoint in generate_circle_points(
orthox, orthoy, orthoz, difx ,dify, difz,
# correction for integer of numc
numc + (1 if c_count%100 < remaining else 0)):
dot = [spoint[0] * radius + ptx,
spoint[1] * radius + pty,
spoint[2] * radius + ptz]
superdot = [spoint[0] * superradius + ptx,
spoint[1] * superradius + pty,
spoint[2] * superradius + ptz]
# check that dot in circle is not too close from next edge
if i < nloci - 2:
hyp = distance((modelx1, modely1, modelz1), dot)
ang = angle_between_3_points(dot,
(modelx1, modely1, modelz1),
(modelx2, modely2, modelz2))
if ang < right_angle:
if sin(ang) * hyp < radius:
continue
# check that dot in circle is not too close from previous edge
if i:
hyp = distance((modelx, modely, modelz), dot)
ang = angle_between_3_points(dot,
(modelx, modely, modelz),
(modelx_1, modely_1, modelz_1))
if ang < right_angle:
if sin(ang) * hyp < radius:
continue
# print 'here'
subpoints.append([dot[0], dot[1], dot[2]])
supersubpoints.append([superdot[0], superdot[1], superdot[2]])
positions.setdefault(i + float(k)/between, []).append(
len(subpoints) - 1)
# define slices
for k in xrange(between - 1, 0, -1):
point = [modelx - k * stepx, modely - k * stepy, modelz - k * stepz]
points.append(point)
pointx, pointy, pointz = point
if not include_edges:
continue
# define circles
_add_circle(k, pointx, pointy, pointz)
c_count += 1
# add last point!!
point = [xis[i+1], yis[i+1], zis[i+1]]
points.append(point)
# and its sphere
adj = distance(point, [modelx, modely, modelz])
hyp2 = sqrt(adj**2 + radius**2)
hyp2 = (hyp2 - hyp2 / (2 * (1 + between)))**2
for xxx, yyy, zzz in sphere:
thing = [xxx * radius + modelx1,
yyy * radius + modely1,
zzz * radius + modelz1]
superthing = [xxx * superradius + modelx1,
yyy * superradius + modely1,
zzz * superradius + modelz1]
if fast_square_distance(modelx, modely, modelz,
thing[0], thing[1], thing[2]) > hyp2:
subpoints.append(thing)
supersubpoints.append(superthing)
positions.setdefault(i+1, []).append(len(subpoints)-1)
return points, subpoints, supersubpoints, positions
| distance | identifier_name |
three_dim_stats.py | """
30 Oct 2013
"""
from pytadbit.eqv_rms_drms import rmsdRMSD_wrapper
from pytadbit.consistency import consistency_wrapper
from itertools import combinations
import numpy as np
from math import pi, sqrt, cos, sin, acos
def generate_sphere_points(n=100):
"""
Returns list of 3d coordinates of points on a sphere using the
Golden Section Spiral algorithm.
:param n: number of points in the sphere
:returns a sphere of radius 1, centered in the origin
"""
points = []
inc = pi * (3 - sqrt(5))
offset = 2 / float(n)
for k in range(int(n)):
y = k * offset - 1 + (offset / 2)
r = sqrt(1 - y*y)
phi = k * inc
# points.append(dict((('x', cos(phi) * r),('y', y),('z', sin(phi) * r))))
points.append((cos(phi) * r, y, sin(phi) * r))
return points
def get_center_of_mass(x, y, z, zeros):
"""
get the center of mass of a given object with list of x, y, z coordinates
"""
xm = ym = zm = 0.
size = len(x)
subsize = 0
for i in xrange(size):
if not zeros[i]:
|
subsize += 1
xm += x[i]
ym += y[i]
zm += z[i]
xm /= subsize
ym /= subsize
zm /= subsize
return xm, ym, zm
def mass_center(x, y, z, zeros):
"""
Transforms coordinates according to the center of mass
:param x: list of x coordinates
:param y: list of y coordinates
:param z: list of z coordinates
"""
xm, ym, zm = get_center_of_mass(x, y, z, zeros)
for i in xrange(len(x)):
x[i] -= xm
y[i] -= ym
z[i] -= zm
# def generate_circle_points(x, y, z, a, b, c, u, v, w, n):
# """
# Returns list of 3d coordinates of points on a circle using the
# Rodrigues rotation formula.
#
# see *Murray, G. (2013). Rotation About an Arbitrary Axis in 3 Dimensions*
# for details
#
# :param x: x coordinate of a point somewhere on the circle
# :param y: y coordinate of a point somewhere on the circle
# :param z: z coordinate of a point somewhere on the circle
# :param a: x coordinate of the center
# :param b: y coordinate of the center
# :param c: z coordinate of the center
# :param u: 1st element of a vector in the same plane as the circle
# :param v: 2nd element of a vector in the same plane as the circle
# :param w: 3rd element of a vector in the same plane as the circle
# :param n: number of points in the circle
#
# TODO: try simplification for a=b=c=0 (and do the translation in the main
# function)
# """
# points = []
# offset = 2 * pi / float(n)
# u_2 = u**2
# v_2 = v**2
# w_2 = w**2
# dst = u_2 + v_2 + w_2
# sqrtdst = sqrt(dst)
# uxvywz = - u*x - v*y - w*z
# b_v = b*v
# c_w = c*w
# a_u = a*u
# one = (a * (v_2 + w_2) - u*(b_v + c_w + uxvywz))
# two = (b * (u_2 + w_2) - v*(a_u + c_w + uxvywz))
# tre = (c * (u_2 + v_2) - w*(a_u + b_v + uxvywz))
# onep = sqrtdst * (-c*v + b*w - w*y + v*z)
# twop = sqrtdst * ( c*u - a*w + w*x - u*z)
# trep = sqrtdst * (-b*u + a*v - v*x + u*y)
# for k in range(int(n)):
# ang = k * offset
# cosang = cos(ang)
# dcosang = cosang * dst
# sinang = sin(ang)
# points.append([(one * (1 - cosang) + x * dcosang + onep * sinang) / dst,
# (two * (1 - cosang) + y * dcosang + twop * sinang) / dst,
# (tre * (1 - cosang) + z * dcosang + trep * sinang) / dst]
# )
# return points
def rotate_among_y_axis(x, y, z, angle):
"""
Rotate and object with a list of x, y, z coordinates among its center of
mass
"""
xj = []
yj = []
zj = []
for xi, yi, zi in zip(*(x, y, z)):
#dist = square_distance((xi, yi, zi), center_of_mass)
xj.append(xi*cos(angle) + zi*sin(angle))
yj.append(yi)
zj.append(xi*-sin(angle)+zi*cos(angle))
return xj, yj, zj
def find_angle_rotation_improve_x(x, y, z, center_of_mass):
"""
Finds the rotation angle needed to face the longest edge of the molecule
"""
# find most distant point from center of mass:
coords = zip(*(x, y, z))
xdst, ydst, zdst = max(coords, key=lambda i: square_distance(i, center_of_mass))
dist = distance((xdst, ydst, zdst), center_of_mass)
angle = acos((-xdst**2 - (dist + sqrt(dist**2 - xdst**2))) /
(2 * dist**2) + 1)
return angle
def generate_circle_points(x, y, z, u, v, w, n):
"""
Returns list of 3d coordinates of points on a circle using the
Rodrigues rotation formula.
see *Murray, G. (2013). Rotation About an Arbitrary Axis in 3 Dimensions*
for details
:param x: x coordinate of a point somewhere on the circle
:param y: y coordinate of a point somewhere on the circle
:param z: z coordinate of a point somewhere on the circle
:param a: x coordinate of the center
:param b: y coordinate of the center
:param c: z coordinate of the center
:param u: 1st element of a vector in the same plane as the circle
:param v: 2nd element of a vector in the same plane as the circle
:param w: 3rd element of a vector in the same plane as the circle
:param n: number of points in the circle
TODO: try simplification for a=b=c=0 (and do the translation in the main
function)
"""
points = []
offset = 2 * pi / float(n)
u_2 = u**2
v_2 = v**2
w_2 = w**2
dst = u_2 + v_2 + w_2
sqrtdst = sqrt(dst)
uxvywz = - u*x - v*y - w*z
one = (-u * (uxvywz))
two = (-v * (uxvywz))
tre = (-w * (uxvywz))
onep = sqrtdst * (- w*y + v*z)
twop = sqrtdst * (+ w*x - u*z)
trep = sqrtdst * (- v*x + u*y)
for k in range(int(n)):
ang = k * offset
cosang = cos(ang)
dcosang = cosang * dst
sinang = sin(ang)
points.append([(one * (1 - cosang) + x * dcosang + onep * sinang) / dst,
(two * (1 - cosang) + y * dcosang + twop * sinang) / dst,
(tre * (1 - cosang) + z * dcosang + trep * sinang) / dst]
)
return points
def square_distance(part1, part2):
"""
Calculates the square distance between two particles.
:param part1: coordinate (dict format with x, y, z keys)
:param part2: coordinate (dict format with x, y, z keys)
:returns: square distance between two points in space
"""
return ((part1[0] - part2[0])**2 +
(part1[1] - part2[1])**2 +
(part1[2] - part2[2])**2)
def fast_square_distance(x1, y1, z1, x2, y2, z2):
"""
Calculates the square distance between two coordinates.
:param part1: coordinate (dict format with x, y, z keys)
:param part2: coordinate (dict format with x, y, z keys)
:returns: square distance between two points in space
"""
return ((x1 - x2)**2 +
(y1 - y2)**2 +
(z1 - z2)**2)
def distance(part1, part2):
"""
Calculates the distance between two particles.
:param part1: coordinate in list format (x, y, z)
:param part2: coordinate in list format (x, y, z)
:returns: distance between two points in space
"""
return sqrt((part1[0] - part2[0])**2 +
(part1[1] - part2[1])**2 +
(part1[2] - part2[2])**2)
def angle_between_3_points(point1, point2, point3):
"""
Calculates the angle between 3 particles
Given three particles A, B and C, the angle g (angle ACB, shown below):
::
A
/|
/i|
c/ |
/ |
/ |
B )g |b
\ |
\ |
a\ |
\h|
\|
C
is given by the theorem of Al-Kashi:
.. math::
b^2 = a^2 + c^2 - 2ac\cos(g)
:param point1: list of 3 coordinate for x, y and z
:param point2: list of 3 coordinate for x, y and z
:param point3: list of 3 coordinate for x, y and z
:returns: angle in radians
"""
a = distance(point2, point3)
c = distance(point1, point2)
b = distance(point1, point3)
try:
g = acos((a**2 - b**2 + c**2) / (2 * a * c))
except ValueError:
g = 0.
return g
def calc_consistency(models, nloci, zeros, dcutoff=200):
combines = list(combinations(models, 2))
parts = [0 for _ in xrange(nloci)]
for pm in consistency_wrapper([models[m]['x'] for m in models],
[models[m]['y'] for m in models],
[models[m]['z'] for m in models],
zeros,
nloci, dcutoff, range(len(models)),
len(models)):
for i, p in enumerate(pm):
parts[i] += p
return [float(p)/len(combines) * 100 for p in parts]
def calc_eqv_rmsd(models, nloci, zeros, dcutoff=200, one=False, what='score',
normed=True):
"""
Calculates the RMSD, dRMSD, the number of equivalent positions and a score
combining these three measures. The measure are done between a group of
models in a one against all manner.
:param nloci: number of particles per model
:param zeros: list of True/False representing particles to skip
:param 200 dcutoff: distance in nanometer from which it is considered
that two particles are separated.
:param 0.75 fact: Factor for equivalent positions
:param False one: if True assumes that only two models are passed, and
returns the rmsd of their comparison
:param 'score' what: values to return. Can be one of 'score', 'rmsd',
'drmsd' or 'eqv'
:param True normed: normalize result by maximum value (only applies to rmsd
and drmsd)
:returns: a score of each pairwise comparison according to:
.. math::
score_i = eqvs_i \\times \\frac{dRMSD_i / max(dRMSD)}
{RMSD_i / max(RMSD)}
where :math:`eqvs_i` is the number of equivalent position for the ith
pairwise model comparison.
"""
what = what.lower()
if not what in ['score', 'rmsd', 'drmsd', 'eqv']:
raise NotImplementedError("Only 'score', 'rmsd', 'drmsd' or 'eqv' " +
"features are available\n")
# remove particles with zeros from calculation
x = []
y = []
z = []
for m in xrange(len(models)):
x.append([models[m]['x'][i] for i in xrange(nloci) if zeros[i]])
y.append([models[m]['y'][i] for i in xrange(nloci) if zeros[i]])
z.append([models[m]['z'][i] for i in xrange(nloci) if zeros[i]])
zeros = tuple([True for _ in xrange(len(x[0]))])
scores = rmsdRMSD_wrapper(x, y, z, zeros, len(zeros),
dcutoff, range(len(models)), len(models),
int(one), what, int(normed))
return scores
def dihedral(a, b, c, d):
"""
Calculates dihedral angle between 4 points in 3D (array with x,y,z)
"""
v1 = getNormedVector(b - a)
v2 = getNormedVector(b - c)
v3 = getNormedVector(c - b)
v4 = getNormedVector(c - d)
v1v2 = np.cross(v1, v2)
v2v3 = np.cross(v3, v4)
sign = -1 if np.linalg.det([v2, v1v2, v2v3]) < 0 else 1
angle = getAngle(v1v2, v2v3)
angle, sign = (angle, sign) if angle <= 90 else (180 - angle, - sign)
return sign * angle
def getNormedVector(dif):
return (dif) / np.linalg.norm(dif)
def getAngle(v1v2, v2v3):
return np.rad2deg(
np.arccos(np.dot(
v1v2 / np.linalg.norm(v1v2),
v2v3.T / np.linalg.norm(v2v3)))
)
def build_mesh(xis, yis, zis, nloci, nump, radius, superradius, include_edges):
"""
Main function for the calculation of the accessibility of a model.
"""
superradius = superradius or 1
# number of dots in a circle is dependent the ones in a sphere
numc = sqrt(nump) * sqrt(pi)
right_angle = pi / 2 - pi / numc
# keeps the remaining of integer conversion, to correct
remaining = int(100*(numc - int(numc)) + 0.5)
c_count = 0
# number of circles per sphere needed to get previous equality are
# dependent of:
fact = float(nump)/numc/(2*radius)
# starts big loop
points = [] # stores the particle coordinates and,
# if include_edges is True, the edge segments
subpoints = [] # store the coordinates of each dot in the mesh
supersubpoints = [] # store the coordinates of each dot in the mesh
positions = {} # a dict to get dots belonging to a given point
sphere = generate_sphere_points(nump)
i = 0
for i in xrange(nloci - 1):
modelx = xis[i]
modely = yis[i]
modelz = zis[i]
modelx1 = xis[i+1]
modely1 = yis[i+1]
modelz1 = zis[i+1]
if i < nloci - 2:
modelx2 = xis[i+2]
modely2 = yis[i+2]
modelz2 = zis[i+2]
if i:
modelx_1 = xis[i-1]
modely_1 = yis[i-1]
modelz_1 = zis[i-1]
point = [modelx, modely, modelz]
points.append(point)
# get minimum length from next particle to display the sphere dot
adj1 = distance(point, [modelx1, modely1, modelz1])
# find a vector orthogonal to the axe between particle i and i+1
difx = modelx - modelx1
dify = modely - modely1
difz = modelz - modelz1
# orthox = 1.
# orthoy = 1.
orthoz = -(difx + dify) / difz
#normer = sqrt(orthox**2 + orthoy**2 + orthoz**2) / radius
normer = sqrt(2. + orthoz**2)# / radius
orthox = 1. / normer
orthoy = 1. / normer
orthoz /= normer
# define the number of circle to draw in this section
between = int(fact * adj1 + 0.5)
try:
stepx = difx / between
stepy = dify / between
stepz = difz / between
except ZeroDivisionError:
stepx = stepy = stepz = 0
hyp1 = sqrt(adj1**2 + radius**2)
# this is an attempt of correction for the integrity of dots
# uses intercept theorem
hyp1 = (hyp1 - hyp1 / (2 * (1 + between)))**2
# get minimum length from prev particle to display the sphere dot
if i:
adj2 = distance(point, [modelx_1, modely_1, modelz_1])
hyp2 = sqrt(adj2**2 + radius**2)
# this is an attempt of correction for the integrity of dots
hyp2 = (hyp2 - hyp2 / (2 * (1 + between)))**2
# set sphere around each particle
for xxx, yyy, zzz in sphere:
thing = [xxx * radius + modelx,
yyy * radius + modely,
zzz * radius + modelz]
# same for super mesh
superthing = [xxx * superradius + modelx,
yyy * superradius + modely,
zzz * superradius + modelz]
# only place mesh outside torsion angle
if fast_square_distance(modelx1, modely1, modelz1,
thing[0], thing[1], thing[2]) > hyp1:
if not i:
subpoints.append(thing)
supersubpoints.append(superthing)
elif fast_square_distance(modelx_1, modely_1, modelz_1,
thing[0], thing[1], thing[2]) > hyp2:
subpoints.append(thing)
supersubpoints.append(superthing)
else:
continue
positions.setdefault(i, []).append(len(subpoints)-1)
def _add_circle(k, ptx, pty, ptz):
for spoint in generate_circle_points(
orthox, orthoy, orthoz, difx ,dify, difz,
# correction for integer of numc
numc + (1 if c_count%100 < remaining else 0)):
dot = [spoint[0] * radius + ptx,
spoint[1] * radius + pty,
spoint[2] * radius + ptz]
superdot = [spoint[0] * superradius + ptx,
spoint[1] * superradius + pty,
spoint[2] * superradius + ptz]
# check that dot in circle is not too close from next edge
if i < nloci - 2:
hyp = distance((modelx1, modely1, modelz1), dot)
ang = angle_between_3_points(dot,
(modelx1, modely1, modelz1),
(modelx2, modely2, modelz2))
if ang < right_angle:
if sin(ang) * hyp < radius:
continue
# check that dot in circle is not too close from previous edge
if i:
hyp = distance((modelx, modely, modelz), dot)
ang = angle_between_3_points(dot,
(modelx, modely, modelz),
(modelx_1, modely_1, modelz_1))
if ang < right_angle:
if sin(ang) * hyp < radius:
continue
# print 'here'
subpoints.append([dot[0], dot[1], dot[2]])
supersubpoints.append([superdot[0], superdot[1], superdot[2]])
positions.setdefault(i + float(k)/between, []).append(
len(subpoints) - 1)
# define slices
for k in xrange(between - 1, 0, -1):
point = [modelx - k * stepx, modely - k * stepy, modelz - k * stepz]
points.append(point)
pointx, pointy, pointz = point
if not include_edges:
continue
# define circles
_add_circle(k, pointx, pointy, pointz)
c_count += 1
# add last point!!
point = [xis[i+1], yis[i+1], zis[i+1]]
points.append(point)
# and its sphere
adj = distance(point, [modelx, modely, modelz])
hyp2 = sqrt(adj**2 + radius**2)
hyp2 = (hyp2 - hyp2 / (2 * (1 + between)))**2
for xxx, yyy, zzz in sphere:
thing = [xxx * radius + modelx1,
yyy * radius + modely1,
zzz * radius + modelz1]
superthing = [xxx * superradius + modelx1,
yyy * superradius + modely1,
zzz * superradius + modelz1]
if fast_square_distance(modelx, modely, modelz,
thing[0], thing[1], thing[2]) > hyp2:
subpoints.append(thing)
supersubpoints.append(superthing)
positions.setdefault(i+1, []).append(len(subpoints)-1)
return points, subpoints, supersubpoints, positions
| continue | conditional_block |
task_basic_info.rs | // Copyright 2014 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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.
//! Interface to the measurements in the task_basic_info struct, gathered by
//! invoking `task_info()` with the `TASK_BASIC_INFO` flavor.
use std::os::raw::c_int;
#[allow(non_camel_case_types)]
type size_t = usize;
/// Obtains task_basic_info::virtual_size.
pub fn virtual_size() -> Option<usize> {
let mut virtual_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoVirtualSize(&mut virtual_size)
};
if rv == 0 { Some(virtual_size as usize) } else { None }
} | let mut resident_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoResidentSize(&mut resident_size)
};
if rv == 0 { Some(resident_size as usize) } else { None }
}
extern {
fn TaskBasicInfoVirtualSize(virtual_size: *mut size_t) -> c_int;
fn TaskBasicInfoResidentSize(resident_size: *mut size_t) -> c_int;
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_stuff() {
// In theory these can fail to return a value, but in practice they
// don't unless something really bizarre has happened with the OS. So
// assume they succeed. The returned values are non-deterministic, but
// check they're non-zero as a basic sanity test.
assert!(virtual_size().unwrap() > 0);
assert!(resident_size().unwrap() > 0);
}
} |
/// Obtains task_basic_info::resident_size.
pub fn resident_size() -> Option<usize> { | random_line_split |
task_basic_info.rs | // Copyright 2014 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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.
//! Interface to the measurements in the task_basic_info struct, gathered by
//! invoking `task_info()` with the `TASK_BASIC_INFO` flavor.
use std::os::raw::c_int;
#[allow(non_camel_case_types)]
type size_t = usize;
/// Obtains task_basic_info::virtual_size.
pub fn virtual_size() -> Option<usize> {
let mut virtual_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoVirtualSize(&mut virtual_size)
};
if rv == 0 { Some(virtual_size as usize) } else { None }
}
/// Obtains task_basic_info::resident_size.
pub fn resident_size() -> Option<usize> |
extern {
fn TaskBasicInfoVirtualSize(virtual_size: *mut size_t) -> c_int;
fn TaskBasicInfoResidentSize(resident_size: *mut size_t) -> c_int;
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_stuff() {
// In theory these can fail to return a value, but in practice they
// don't unless something really bizarre has happened with the OS. So
// assume they succeed. The returned values are non-deterministic, but
// check they're non-zero as a basic sanity test.
assert!(virtual_size().unwrap() > 0);
assert!(resident_size().unwrap() > 0);
}
}
| {
let mut resident_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoResidentSize(&mut resident_size)
};
if rv == 0 { Some(resident_size as usize) } else { None }
} | identifier_body |
task_basic_info.rs | // Copyright 2014 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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.
//! Interface to the measurements in the task_basic_info struct, gathered by
//! invoking `task_info()` with the `TASK_BASIC_INFO` flavor.
use std::os::raw::c_int;
#[allow(non_camel_case_types)]
type size_t = usize;
/// Obtains task_basic_info::virtual_size.
pub fn virtual_size() -> Option<usize> {
let mut virtual_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoVirtualSize(&mut virtual_size)
};
if rv == 0 | else { None }
}
/// Obtains task_basic_info::resident_size.
pub fn resident_size() -> Option<usize> {
let mut resident_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoResidentSize(&mut resident_size)
};
if rv == 0 { Some(resident_size as usize) } else { None }
}
extern {
fn TaskBasicInfoVirtualSize(virtual_size: *mut size_t) -> c_int;
fn TaskBasicInfoResidentSize(resident_size: *mut size_t) -> c_int;
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_stuff() {
// In theory these can fail to return a value, but in practice they
// don't unless something really bizarre has happened with the OS. So
// assume they succeed. The returned values are non-deterministic, but
// check they're non-zero as a basic sanity test.
assert!(virtual_size().unwrap() > 0);
assert!(resident_size().unwrap() > 0);
}
}
| { Some(virtual_size as usize) } | conditional_block |
task_basic_info.rs | // Copyright 2014 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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.
//! Interface to the measurements in the task_basic_info struct, gathered by
//! invoking `task_info()` with the `TASK_BASIC_INFO` flavor.
use std::os::raw::c_int;
#[allow(non_camel_case_types)]
type size_t = usize;
/// Obtains task_basic_info::virtual_size.
pub fn virtual_size() -> Option<usize> {
let mut virtual_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoVirtualSize(&mut virtual_size)
};
if rv == 0 { Some(virtual_size as usize) } else { None }
}
/// Obtains task_basic_info::resident_size.
pub fn resident_size() -> Option<usize> {
let mut resident_size: size_t = 0;
let rv = unsafe {
TaskBasicInfoResidentSize(&mut resident_size)
};
if rv == 0 { Some(resident_size as usize) } else { None }
}
extern {
fn TaskBasicInfoVirtualSize(virtual_size: *mut size_t) -> c_int;
fn TaskBasicInfoResidentSize(resident_size: *mut size_t) -> c_int;
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn | () {
// In theory these can fail to return a value, but in practice they
// don't unless something really bizarre has happened with the OS. So
// assume they succeed. The returned values are non-deterministic, but
// check they're non-zero as a basic sanity test.
assert!(virtual_size().unwrap() > 0);
assert!(resident_size().unwrap() > 0);
}
}
| test_stuff | identifier_name |
config.py | """
Configurations
--------------
Various setups for different app instances
"""
class Config:
"""Default config"""
DEBUG = False
TESTING = False
SESSION_STORE = 'session'
MONGODB_DB = 'default'
SECRET_KEY = 'flask+braiiin=<3'
LIVE = ['v1']
STATIC_PATH = 'static'
HASHING_ROUNDS = 15
INIT = {
'port': 8006,
'host': '127.0.0.1',
}
class ProductionConfig(Config):
"""Production vars"""
INIT = {
'port': 80,
'host': '127.0.0.1',
}
class DevelopmentConfig(Config):
|
class TestConfig(Config):
"""For automated testing"""
TESTING = True
MONGODB_DB = 'test'
| """For local runs"""
DEBUG = True
MONGODB_DB = 'dev' | identifier_body |
config.py | """
Configurations
--------------
Various setups for different app instances
"""
class Config:
"""Default config"""
DEBUG = False
TESTING = False
SESSION_STORE = 'session'
MONGODB_DB = 'default'
SECRET_KEY = 'flask+braiiin=<3'
LIVE = ['v1']
STATIC_PATH = 'static'
HASHING_ROUNDS = 15
INIT = {
'port': 8006,
'host': '127.0.0.1',
}
class | (Config):
"""Production vars"""
INIT = {
'port': 80,
'host': '127.0.0.1',
}
class DevelopmentConfig(Config):
"""For local runs"""
DEBUG = True
MONGODB_DB = 'dev'
class TestConfig(Config):
"""For automated testing"""
TESTING = True
MONGODB_DB = 'test'
| ProductionConfig | identifier_name |
config.py | """
Configurations
--------------
Various setups for different app instances
"""
class Config:
"""Default config"""
DEBUG = False
TESTING = False
SESSION_STORE = 'session'
MONGODB_DB = 'default'
SECRET_KEY = 'flask+braiiin=<3'
LIVE = ['v1']
STATIC_PATH = 'static'
HASHING_ROUNDS = 15
INIT = {
'port': 8006,
'host': '127.0.0.1',
}
class ProductionConfig(Config):
"""Production vars"""
INIT = {
'port': 80,
'host': '127.0.0.1',
} | class DevelopmentConfig(Config):
"""For local runs"""
DEBUG = True
MONGODB_DB = 'dev'
class TestConfig(Config):
"""For automated testing"""
TESTING = True
MONGODB_DB = 'test' | random_line_split | |
StopPropagation.tsx | /*
* Copyright (C) 2020 Graylog, Inc. | *
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*/
import * as React from 'react';
type Props = {
children: React.ReactElement[],
};
const stopPropagation = (evt) => {
evt.stopPropagation();
evt.preventDefault();
};
const StopPropagation = ({ children }: Props) => (
<span role="presentation" onClick={stopPropagation} onMouseDown={stopPropagation}>
{children}
</span>
);
export default StopPropagation; | *
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc. | random_line_split |
test_link_aggregator.py | import unittest
import logging
from domaincrawl.link_aggregator import LinkAggregator
from domaincrawl.link_filters import DomainFilter, is_acceptable_url_scheme
from domaincrawl.site_graph import SiteGraph
from domaincrawl.util import URLNormalizer, extract_domain_port
class LinkAggregatorTest(unittest.TestCase):
logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%m/%d/%Y %I:%M:%S %p')
def test_link_dedup(self):
base_url = "acme.com:8999"
base_domain, port = extract_domain_port(base_url)
logger = logging.getLogger()
url_norm = URLNormalizer(base_domain, port)
normalized_url = url_norm.normalize_with_domain(base_url)
| site_graph = SiteGraph(logger)
link_aggregator = LinkAggregator(logger, site_graph, link_mappers=[url_norm.normalize_with_domain], link_filters=[domain_filter.passes, is_acceptable_url_scheme])
valid_links = ["/a/b","/a/b/./","http://acme.com:8002/a","https://acme.com:8002/b?q=asd#frag"]
expected_links = ["http://acme.com:8999/a/b","http://acme.com:8002/a","https://acme.com:8002/b"]
# This time, we also specify a referrer page
filtered_links = link_aggregator.filter_update_links(valid_links, normalized_url)
self.assertListEqual(expected_links,filtered_links)
self.assertSetEqual(set(expected_links),link_aggregator._links)
# Second invocation should result in deduplication
filtered_links = link_aggregator.filter_update_links(valid_links, None)
self.assertTrue(len(filtered_links) == 0)
self.assertSetEqual(set(expected_links),link_aggregator._links)
# None of the invalid links should pass
invalid_links = ["mailto://user@mail.com","code.acme.com","code.acme.com/b","https://127.122.9.1"]
filtered_links = link_aggregator.filter_update_links(invalid_links, None)
self.assertTrue(len(filtered_links) == 0)
self.assertSetEqual(set(expected_links),link_aggregator._links)
# A new valid link should pass
new_valid_links = ["http://acme.com:8999/"]
filtered_links = link_aggregator.filter_update_links(new_valid_links, None)
expected_result = ["http://acme.com:8999"]
self.assertListEqual(expected_result,filtered_links)
expected_result_set = set(expected_links)
expected_result_set.update(set(expected_result))
self.assertSetEqual(expected_result_set,link_aggregator._links)
self.assertEqual(len(expected_result_set), site_graph.num_nodes())
for link in expected_result_set:
self.assertTrue(site_graph.has_vertex(link))
self.assertEqual(len(expected_links), site_graph.num_edges())
for link in expected_links:
self.assertTrue(site_graph.has_edge(normalized_url, link)) | logger.debug("Constructed normalized base url : %s"%normalized_url)
domain_filter = DomainFilter(base_domain, logger)
| random_line_split |
test_link_aggregator.py | import unittest
import logging
from domaincrawl.link_aggregator import LinkAggregator
from domaincrawl.link_filters import DomainFilter, is_acceptable_url_scheme
from domaincrawl.site_graph import SiteGraph
from domaincrawl.util import URLNormalizer, extract_domain_port
class LinkAggregatorTest(unittest.TestCase):
logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%m/%d/%Y %I:%M:%S %p')
def test_link_dedup(self):
base_url = "acme.com:8999"
base_domain, port = extract_domain_port(base_url)
logger = logging.getLogger()
url_norm = URLNormalizer(base_domain, port)
normalized_url = url_norm.normalize_with_domain(base_url)
logger.debug("Constructed normalized base url : %s"%normalized_url)
domain_filter = DomainFilter(base_domain, logger)
site_graph = SiteGraph(logger)
link_aggregator = LinkAggregator(logger, site_graph, link_mappers=[url_norm.normalize_with_domain], link_filters=[domain_filter.passes, is_acceptable_url_scheme])
valid_links = ["/a/b","/a/b/./","http://acme.com:8002/a","https://acme.com:8002/b?q=asd#frag"]
expected_links = ["http://acme.com:8999/a/b","http://acme.com:8002/a","https://acme.com:8002/b"]
# This time, we also specify a referrer page
filtered_links = link_aggregator.filter_update_links(valid_links, normalized_url)
self.assertListEqual(expected_links,filtered_links)
self.assertSetEqual(set(expected_links),link_aggregator._links)
# Second invocation should result in deduplication
filtered_links = link_aggregator.filter_update_links(valid_links, None)
self.assertTrue(len(filtered_links) == 0)
self.assertSetEqual(set(expected_links),link_aggregator._links)
# None of the invalid links should pass
invalid_links = ["mailto://user@mail.com","code.acme.com","code.acme.com/b","https://127.122.9.1"]
filtered_links = link_aggregator.filter_update_links(invalid_links, None)
self.assertTrue(len(filtered_links) == 0)
self.assertSetEqual(set(expected_links),link_aggregator._links)
# A new valid link should pass
new_valid_links = ["http://acme.com:8999/"]
filtered_links = link_aggregator.filter_update_links(new_valid_links, None)
expected_result = ["http://acme.com:8999"]
self.assertListEqual(expected_result,filtered_links)
expected_result_set = set(expected_links)
expected_result_set.update(set(expected_result))
self.assertSetEqual(expected_result_set,link_aggregator._links)
self.assertEqual(len(expected_result_set), site_graph.num_nodes())
for link in expected_result_set:
|
self.assertEqual(len(expected_links), site_graph.num_edges())
for link in expected_links:
self.assertTrue(site_graph.has_edge(normalized_url, link))
| self.assertTrue(site_graph.has_vertex(link)) | conditional_block |
test_link_aggregator.py | import unittest
import logging
from domaincrawl.link_aggregator import LinkAggregator
from domaincrawl.link_filters import DomainFilter, is_acceptable_url_scheme
from domaincrawl.site_graph import SiteGraph
from domaincrawl.util import URLNormalizer, extract_domain_port
class | (unittest.TestCase):
logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%m/%d/%Y %I:%M:%S %p')
def test_link_dedup(self):
base_url = "acme.com:8999"
base_domain, port = extract_domain_port(base_url)
logger = logging.getLogger()
url_norm = URLNormalizer(base_domain, port)
normalized_url = url_norm.normalize_with_domain(base_url)
logger.debug("Constructed normalized base url : %s"%normalized_url)
domain_filter = DomainFilter(base_domain, logger)
site_graph = SiteGraph(logger)
link_aggregator = LinkAggregator(logger, site_graph, link_mappers=[url_norm.normalize_with_domain], link_filters=[domain_filter.passes, is_acceptable_url_scheme])
valid_links = ["/a/b","/a/b/./","http://acme.com:8002/a","https://acme.com:8002/b?q=asd#frag"]
expected_links = ["http://acme.com:8999/a/b","http://acme.com:8002/a","https://acme.com:8002/b"]
# This time, we also specify a referrer page
filtered_links = link_aggregator.filter_update_links(valid_links, normalized_url)
self.assertListEqual(expected_links,filtered_links)
self.assertSetEqual(set(expected_links),link_aggregator._links)
# Second invocation should result in deduplication
filtered_links = link_aggregator.filter_update_links(valid_links, None)
self.assertTrue(len(filtered_links) == 0)
self.assertSetEqual(set(expected_links),link_aggregator._links)
# None of the invalid links should pass
invalid_links = ["mailto://user@mail.com","code.acme.com","code.acme.com/b","https://127.122.9.1"]
filtered_links = link_aggregator.filter_update_links(invalid_links, None)
self.assertTrue(len(filtered_links) == 0)
self.assertSetEqual(set(expected_links),link_aggregator._links)
# A new valid link should pass
new_valid_links = ["http://acme.com:8999/"]
filtered_links = link_aggregator.filter_update_links(new_valid_links, None)
expected_result = ["http://acme.com:8999"]
self.assertListEqual(expected_result,filtered_links)
expected_result_set = set(expected_links)
expected_result_set.update(set(expected_result))
self.assertSetEqual(expected_result_set,link_aggregator._links)
self.assertEqual(len(expected_result_set), site_graph.num_nodes())
for link in expected_result_set:
self.assertTrue(site_graph.has_vertex(link))
self.assertEqual(len(expected_links), site_graph.num_edges())
for link in expected_links:
self.assertTrue(site_graph.has_edge(normalized_url, link))
| LinkAggregatorTest | identifier_name |
test_link_aggregator.py | import unittest
import logging
from domaincrawl.link_aggregator import LinkAggregator
from domaincrawl.link_filters import DomainFilter, is_acceptable_url_scheme
from domaincrawl.site_graph import SiteGraph
from domaincrawl.util import URLNormalizer, extract_domain_port
class LinkAggregatorTest(unittest.TestCase):
| logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%m/%d/%Y %I:%M:%S %p')
def test_link_dedup(self):
base_url = "acme.com:8999"
base_domain, port = extract_domain_port(base_url)
logger = logging.getLogger()
url_norm = URLNormalizer(base_domain, port)
normalized_url = url_norm.normalize_with_domain(base_url)
logger.debug("Constructed normalized base url : %s"%normalized_url)
domain_filter = DomainFilter(base_domain, logger)
site_graph = SiteGraph(logger)
link_aggregator = LinkAggregator(logger, site_graph, link_mappers=[url_norm.normalize_with_domain], link_filters=[domain_filter.passes, is_acceptable_url_scheme])
valid_links = ["/a/b","/a/b/./","http://acme.com:8002/a","https://acme.com:8002/b?q=asd#frag"]
expected_links = ["http://acme.com:8999/a/b","http://acme.com:8002/a","https://acme.com:8002/b"]
# This time, we also specify a referrer page
filtered_links = link_aggregator.filter_update_links(valid_links, normalized_url)
self.assertListEqual(expected_links,filtered_links)
self.assertSetEqual(set(expected_links),link_aggregator._links)
# Second invocation should result in deduplication
filtered_links = link_aggregator.filter_update_links(valid_links, None)
self.assertTrue(len(filtered_links) == 0)
self.assertSetEqual(set(expected_links),link_aggregator._links)
# None of the invalid links should pass
invalid_links = ["mailto://user@mail.com","code.acme.com","code.acme.com/b","https://127.122.9.1"]
filtered_links = link_aggregator.filter_update_links(invalid_links, None)
self.assertTrue(len(filtered_links) == 0)
self.assertSetEqual(set(expected_links),link_aggregator._links)
# A new valid link should pass
new_valid_links = ["http://acme.com:8999/"]
filtered_links = link_aggregator.filter_update_links(new_valid_links, None)
expected_result = ["http://acme.com:8999"]
self.assertListEqual(expected_result,filtered_links)
expected_result_set = set(expected_links)
expected_result_set.update(set(expected_result))
self.assertSetEqual(expected_result_set,link_aggregator._links)
self.assertEqual(len(expected_result_set), site_graph.num_nodes())
for link in expected_result_set:
self.assertTrue(site_graph.has_vertex(link))
self.assertEqual(len(expected_links), site_graph.num_edges())
for link in expected_links:
self.assertTrue(site_graph.has_edge(normalized_url, link)) | identifier_body | |
index.js | var through = require('through2'),
falafel = require('falafel'), | function lintroller(_checks) {
var count = 0,
files = [],
stream = through(add_files, noop),
checks = _checks || []
checks.forEach(resolve_check)
checks = checks.filter(Boolean)
return stream
function add_files(chunk, enc, next) {
files.push(chunk.toString())
if (!count) {
count++
read_file(files.shift())
}
next()
}
function read_file(filename) {
fs.readFile(filename, 'utf8', process_file)
function process_file(err, data) {
if (err) process.stdout.write('whoopsie goldberg') && process.exit(1)
falafel('' + data, check_node)
if (!files.length) return finish()
count++
read_file(files.shift())
}
}
function check_node(node) {
checks.forEach(run_check)
function run_check(check) {
if (check.selectors.some(match_selector)) {
check.rules.forEach(compare_and_count)
}
function match_selector(selector) {
return selector(node)
}
function compare_and_count(rule) {
if (rule.test(node)) rule.count++
}
}
}
function finish() {
process.stdout.write('processed ' + count + ' files\n')
console.dir(checks)
}
}
function resolve_check(check) {
if (typeof check === 'string') {
try {
check = require(check)
} catch(e) {
check = false
return
}
}
if (!check.rules || !check.rules.length) {
check = false
return
}
check.rules.forEach(validate_rules)
check.rules = check.rules.filter(Boolean)
function validate_rules(rule) {
if (!rule.name || !rule.test || typeof rule.test !== 'function') {
rule = false
return
}
rule.description = rule.description || rule.name
rule.count = rule.count || 0
}
}
function noop() {} | fs = require('fs')
module.exports = lintroller
| random_line_split |
index.js | var through = require('through2'),
falafel = require('falafel'),
fs = require('fs')
module.exports = lintroller
function lintroller(_checks) {
var count = 0,
files = [],
stream = through(add_files, noop),
checks = _checks || []
checks.forEach(resolve_check)
checks = checks.filter(Boolean)
return stream
function add_files(chunk, enc, next) {
files.push(chunk.toString())
if (!count) {
count++
read_file(files.shift())
}
next()
}
function read_file(filename) {
fs.readFile(filename, 'utf8', process_file)
function process_file(err, data) {
if (err) process.stdout.write('whoopsie goldberg') && process.exit(1)
falafel('' + data, check_node)
if (!files.length) return finish()
count++
read_file(files.shift())
}
}
function check_node(node) {
checks.forEach(run_check)
function run_check(check) {
if (check.selectors.some(match_selector)) {
check.rules.forEach(compare_and_count)
}
function match_selector(selector) {
return selector(node)
}
function compare_and_count(rule) {
if (rule.test(node)) rule.count++
}
}
}
function finish() {
process.stdout.write('processed ' + count + ' files\n')
console.dir(checks)
}
}
function resolve_check(check) {
if (typeof check === 'string') {
try {
check = require(check)
} catch(e) {
check = false
return
}
}
if (!check.rules || !check.rules.length) {
check = false
return
}
check.rules.forEach(validate_rules)
check.rules = check.rules.filter(Boolean)
function validate_rules(rule) |
}
function noop() {}
| {
if (!rule.name || !rule.test || typeof rule.test !== 'function') {
rule = false
return
}
rule.description = rule.description || rule.name
rule.count = rule.count || 0
} | identifier_body |
index.js | var through = require('through2'),
falafel = require('falafel'),
fs = require('fs')
module.exports = lintroller
function lintroller(_checks) {
var count = 0,
files = [],
stream = through(add_files, noop),
checks = _checks || []
checks.forEach(resolve_check)
checks = checks.filter(Boolean)
return stream
function | (chunk, enc, next) {
files.push(chunk.toString())
if (!count) {
count++
read_file(files.shift())
}
next()
}
function read_file(filename) {
fs.readFile(filename, 'utf8', process_file)
function process_file(err, data) {
if (err) process.stdout.write('whoopsie goldberg') && process.exit(1)
falafel('' + data, check_node)
if (!files.length) return finish()
count++
read_file(files.shift())
}
}
function check_node(node) {
checks.forEach(run_check)
function run_check(check) {
if (check.selectors.some(match_selector)) {
check.rules.forEach(compare_and_count)
}
function match_selector(selector) {
return selector(node)
}
function compare_and_count(rule) {
if (rule.test(node)) rule.count++
}
}
}
function finish() {
process.stdout.write('processed ' + count + ' files\n')
console.dir(checks)
}
}
function resolve_check(check) {
if (typeof check === 'string') {
try {
check = require(check)
} catch(e) {
check = false
return
}
}
if (!check.rules || !check.rules.length) {
check = false
return
}
check.rules.forEach(validate_rules)
check.rules = check.rules.filter(Boolean)
function validate_rules(rule) {
if (!rule.name || !rule.test || typeof rule.test !== 'function') {
rule = false
return
}
rule.description = rule.description || rule.name
rule.count = rule.count || 0
}
}
function noop() {}
| add_files | identifier_name |
index.js | var through = require('through2'),
falafel = require('falafel'),
fs = require('fs')
module.exports = lintroller
function lintroller(_checks) {
var count = 0,
files = [],
stream = through(add_files, noop),
checks = _checks || []
checks.forEach(resolve_check)
checks = checks.filter(Boolean)
return stream
function add_files(chunk, enc, next) {
files.push(chunk.toString())
if (!count) |
next()
}
function read_file(filename) {
fs.readFile(filename, 'utf8', process_file)
function process_file(err, data) {
if (err) process.stdout.write('whoopsie goldberg') && process.exit(1)
falafel('' + data, check_node)
if (!files.length) return finish()
count++
read_file(files.shift())
}
}
function check_node(node) {
checks.forEach(run_check)
function run_check(check) {
if (check.selectors.some(match_selector)) {
check.rules.forEach(compare_and_count)
}
function match_selector(selector) {
return selector(node)
}
function compare_and_count(rule) {
if (rule.test(node)) rule.count++
}
}
}
function finish() {
process.stdout.write('processed ' + count + ' files\n')
console.dir(checks)
}
}
function resolve_check(check) {
if (typeof check === 'string') {
try {
check = require(check)
} catch(e) {
check = false
return
}
}
if (!check.rules || !check.rules.length) {
check = false
return
}
check.rules.forEach(validate_rules)
check.rules = check.rules.filter(Boolean)
function validate_rules(rule) {
if (!rule.name || !rule.test || typeof rule.test !== 'function') {
rule = false
return
}
rule.description = rule.description || rule.name
rule.count = rule.count || 0
}
}
function noop() {}
| {
count++
read_file(files.shift())
} | conditional_block |
NodeGraphContainer.tsx | import React from 'react';
import { useToggle } from 'react-use';
import { Badge, Collapse, useStyles2, useTheme2 } from '@grafana/ui';
import { applyFieldOverrides, DataFrame, GrafanaTheme2 } from '@grafana/data';
import { css } from '@emotion/css';
import { ExploreId, StoreState } from '../../types';
import { splitOpen } from './state/main';
import { connect, ConnectedProps } from 'react-redux';
import { useLinks } from './utils/links';
import { NodeGraph } from '../../plugins/panel/nodeGraph';
import { useCategorizeFrames } from '../../plugins/panel/nodeGraph/useCategorizeFrames';
const getStyles = (theme: GrafanaTheme2) => ({
warningText: css`
label: warningText;
font-size: ${theme.typography.bodySmall.fontSize};
color: ${theme.colors.text.secondary};
`,
}); | exploreId: ExploreId;
// When showing the node graph together with trace view we do some changes so it works better.
withTraceView?: boolean;
}
type Props = OwnProps & ConnectedProps<typeof connector>;
export function UnconnectedNodeGraphContainer(props: Props) {
const { dataFrames, range, splitOpen, withTraceView } = props;
const getLinks = useLinks(range, splitOpen);
const theme = useTheme2();
const styles = useStyles2(getStyles);
// This is implicit dependency that is needed for links to work. At some point when replacing variables in the link
// it requires field to have a display property which is added by the overrides even though we don't add any field
// overrides in explore.
const frames = applyFieldOverrides({
fieldConfig: {
defaults: {},
overrides: [],
},
data: dataFrames,
// We don't need proper replace here as it is only used in getLinks and we use getFieldLinks
replaceVariables: (value) => value,
theme,
});
const { nodes } = useCategorizeFrames(frames);
const [open, toggleOpen] = useToggle(false);
const countWarning =
withTraceView && nodes[0]?.length > 1000 ? (
<span className={styles.warningText}> ({nodes[0].length} nodes, can be slow to load)</span>
) : null;
return (
<Collapse
label={
<span>
Node graph{countWarning}{' '}
<Badge text={'Beta'} color={'blue'} icon={'rocket'} tooltip={'This visualization is in beta'} />
</span>
}
collapsible={withTraceView}
// We allow collapsing this only when it is shown together with trace view.
isOpen={withTraceView ? open : true}
onToggle={withTraceView ? () => toggleOpen() : undefined}
>
<div style={{ height: withTraceView ? 500 : 600 }}>
<NodeGraph dataFrames={frames} getLinks={getLinks} />
</div>
</Collapse>
);
}
function mapStateToProps(state: StoreState, { exploreId }: OwnProps) {
return {
range: state.explore[exploreId]!.range,
};
}
const mapDispatchToProps = {
splitOpen,
};
const connector = connect(mapStateToProps, mapDispatchToProps);
export const NodeGraphContainer = connector(UnconnectedNodeGraphContainer); |
interface OwnProps {
// Edges and Nodes are separate frames
dataFrames: DataFrame[]; | random_line_split |
NodeGraphContainer.tsx | import React from 'react';
import { useToggle } from 'react-use';
import { Badge, Collapse, useStyles2, useTheme2 } from '@grafana/ui';
import { applyFieldOverrides, DataFrame, GrafanaTheme2 } from '@grafana/data';
import { css } from '@emotion/css';
import { ExploreId, StoreState } from '../../types';
import { splitOpen } from './state/main';
import { connect, ConnectedProps } from 'react-redux';
import { useLinks } from './utils/links';
import { NodeGraph } from '../../plugins/panel/nodeGraph';
import { useCategorizeFrames } from '../../plugins/panel/nodeGraph/useCategorizeFrames';
const getStyles = (theme: GrafanaTheme2) => ({
warningText: css`
label: warningText;
font-size: ${theme.typography.bodySmall.fontSize};
color: ${theme.colors.text.secondary};
`,
});
interface OwnProps {
// Edges and Nodes are separate frames
dataFrames: DataFrame[];
exploreId: ExploreId;
// When showing the node graph together with trace view we do some changes so it works better.
withTraceView?: boolean;
}
type Props = OwnProps & ConnectedProps<typeof connector>;
export function UnconnectedNodeGraphContainer(props: Props) {
const { dataFrames, range, splitOpen, withTraceView } = props;
const getLinks = useLinks(range, splitOpen);
const theme = useTheme2();
const styles = useStyles2(getStyles);
// This is implicit dependency that is needed for links to work. At some point when replacing variables in the link
// it requires field to have a display property which is added by the overrides even though we don't add any field
// overrides in explore.
const frames = applyFieldOverrides({
fieldConfig: {
defaults: {},
overrides: [],
},
data: dataFrames,
// We don't need proper replace here as it is only used in getLinks and we use getFieldLinks
replaceVariables: (value) => value,
theme,
});
const { nodes } = useCategorizeFrames(frames);
const [open, toggleOpen] = useToggle(false);
const countWarning =
withTraceView && nodes[0]?.length > 1000 ? (
<span className={styles.warningText}> ({nodes[0].length} nodes, can be slow to load)</span>
) : null;
return (
<Collapse
label={
<span>
Node graph{countWarning}{' '}
<Badge text={'Beta'} color={'blue'} icon={'rocket'} tooltip={'This visualization is in beta'} />
</span>
}
collapsible={withTraceView}
// We allow collapsing this only when it is shown together with trace view.
isOpen={withTraceView ? open : true}
onToggle={withTraceView ? () => toggleOpen() : undefined}
>
<div style={{ height: withTraceView ? 500 : 600 }}>
<NodeGraph dataFrames={frames} getLinks={getLinks} />
</div>
</Collapse>
);
}
function mapStateToProps(state: StoreState, { exploreId }: OwnProps) {
return {
range: state.explore[exploreId]!.range,
};
}
const mapDispatchToProps = | {
splitOpen,
};
const connector = connect(mapStateToProps, mapDispatchToProps);
export const NodeGraphContainer = connector(UnconnectedNodeGraphContainer); | identifier_body | |
NodeGraphContainer.tsx | import React from 'react';
import { useToggle } from 'react-use';
import { Badge, Collapse, useStyles2, useTheme2 } from '@grafana/ui';
import { applyFieldOverrides, DataFrame, GrafanaTheme2 } from '@grafana/data';
import { css } from '@emotion/css';
import { ExploreId, StoreState } from '../../types';
import { splitOpen } from './state/main';
import { connect, ConnectedProps } from 'react-redux';
import { useLinks } from './utils/links';
import { NodeGraph } from '../../plugins/panel/nodeGraph';
import { useCategorizeFrames } from '../../plugins/panel/nodeGraph/useCategorizeFrames';
const getStyles = (theme: GrafanaTheme2) => ({
warningText: css`
label: warningText;
font-size: ${theme.typography.bodySmall.fontSize};
color: ${theme.colors.text.secondary};
`,
});
interface OwnProps {
// Edges and Nodes are separate frames
dataFrames: DataFrame[];
exploreId: ExploreId;
// When showing the node graph together with trace view we do some changes so it works better.
withTraceView?: boolean;
}
type Props = OwnProps & ConnectedProps<typeof connector>;
export function UnconnectedNodeGraphContainer(props: Props) {
const { dataFrames, range, splitOpen, withTraceView } = props;
const getLinks = useLinks(range, splitOpen);
const theme = useTheme2();
const styles = useStyles2(getStyles);
// This is implicit dependency that is needed for links to work. At some point when replacing variables in the link
// it requires field to have a display property which is added by the overrides even though we don't add any field
// overrides in explore.
const frames = applyFieldOverrides({
fieldConfig: {
defaults: {},
overrides: [],
},
data: dataFrames,
// We don't need proper replace here as it is only used in getLinks and we use getFieldLinks
replaceVariables: (value) => value,
theme,
});
const { nodes } = useCategorizeFrames(frames);
const [open, toggleOpen] = useToggle(false);
const countWarning =
withTraceView && nodes[0]?.length > 1000 ? (
<span className={styles.warningText}> ({nodes[0].length} nodes, can be slow to load)</span>
) : null;
return (
<Collapse
label={
<span>
Node graph{countWarning}{' '}
<Badge text={'Beta'} color={'blue'} icon={'rocket'} tooltip={'This visualization is in beta'} />
</span>
}
collapsible={withTraceView}
// We allow collapsing this only when it is shown together with trace view.
isOpen={withTraceView ? open : true}
onToggle={ | ? () => toggleOpen() : undefined}
>
<div style={{ height: withTraceView ? 500 : 600 }}>
<NodeGraph dataFrames={frames} getLinks={getLinks} />
</div>
</Collapse>
);
}
function mapStateToProps(state: StoreState, { exploreId }: OwnProps) {
return {
range: state.explore[exploreId]!.range,
};
}
const mapDispatchToProps = {
splitOpen,
};
const connector = connect(mapStateToProps, mapDispatchToProps);
export const NodeGraphContainer = connector(UnconnectedNodeGraphContainer);
| withTraceView | identifier_name |
util.py | # coding: utf-8
""" General utilities. """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Standard library
import collections
import sys
import logging
import multiprocessing
# Third-party
import numpy as np
__all__ = ['get_pool']
# Create logger
logger = logging.getLogger(__name__)
class SerialPool(object):
def close(self):
return
def map(self, *args, **kwargs):
return map(*args, **kwargs)
def get_pool(mpi=False, threads=None):
""" Get a pool object to pass to emcee for parallel processing.
If mpi is False and threads is None, pool is None.
Parameters
----------
mpi : bool
Use MPI or not. If specified, ignores the threads kwarg.
threads : int (optional)
If mpi is False and threads is specified, use a Python
multiprocessing pool with the specified number of threads.
"""
if mpi:
from emcee.utils import MPIPool
# Initialize the MPI pool
pool = MPIPool()
# Make sure the thread we're running on is the master
if not pool.is_master():
pool.wait()
sys.exit(0)
logger.debug("Running with MPI...")
elif threads > 1:
logger.debug("Running with multiprocessing on {} cores..."
.format(threads))
pool = multiprocessing.Pool(threads)
else:
logger.debug("Running serial...")
pool = SerialPool()
return pool
def gram_schmidt(y):
""" Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """
n = y.shape[0]
if y.shape[1] != n:
raise ValueError("Invalid shape: {}".format(y.shape))
mo = np.zeros(n)
# Main loop
for i in range(n):
# Remove component in direction i
for j in range(i):
esc = np.sum(y[j]*y[i])
y[i] -= y[j]*esc
# Normalization
mo[i] = np.linalg.norm(y[i])
y[i] /= mo[i]
return mo
class use_backend(object):
def | (self, backend):
import matplotlib.pyplot as plt
from IPython.core.interactiveshell import InteractiveShell
from IPython.core.pylabtools import backend2gui
self.shell = InteractiveShell.instance()
self.old_backend = backend2gui[str(plt.get_backend())]
self.new_backend = backend
def __enter__(self):
gui, backend = self.shell.enable_matplotlib(self.new_backend)
def __exit__(self, type, value, tb):
gui, backend = self.shell.enable_matplotlib(self.old_backend)
def inherit_docs(cls):
for name, func in vars(cls).items():
if not func.__doc__:
for parent in cls.__bases__:
try:
parfunc = getattr(parent, name)
except AttributeError: # parent doesn't have function
break
if parfunc and getattr(parfunc, '__doc__', None):
func.__doc__ = parfunc.__doc__
break
return cls
class ImmutableDict(collections.Mapping):
def __init__(self, somedict):
self._dict = dict(somedict) # make a copy
self._hash = None
def __getitem__(self, key):
return self._dict[key]
def __len__(self):
return len(self._dict)
def __iter__(self):
return iter(self._dict)
def __hash__(self):
if self._hash is None:
self._hash = hash(frozenset(self._dict.items()))
return self._hash
def __eq__(self, other):
return self._dict == other._dict
| __init__ | identifier_name |
util.py | # coding: utf-8
""" General utilities. """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Standard library
import collections
import sys
import logging
import multiprocessing
# Third-party
import numpy as np
__all__ = ['get_pool']
# Create logger
logger = logging.getLogger(__name__)
class SerialPool(object):
def close(self):
return
def map(self, *args, **kwargs):
return map(*args, **kwargs)
def get_pool(mpi=False, threads=None):
""" Get a pool object to pass to emcee for parallel processing.
If mpi is False and threads is None, pool is None.
Parameters
----------
mpi : bool
Use MPI or not. If specified, ignores the threads kwarg.
threads : int (optional)
If mpi is False and threads is specified, use a Python
multiprocessing pool with the specified number of threads.
"""
if mpi:
from emcee.utils import MPIPool
# Initialize the MPI pool
pool = MPIPool()
# Make sure the thread we're running on is the master
if not pool.is_master():
pool.wait()
sys.exit(0)
logger.debug("Running with MPI...")
elif threads > 1:
logger.debug("Running with multiprocessing on {} cores..."
.format(threads))
pool = multiprocessing.Pool(threads)
else:
logger.debug("Running serial...")
pool = SerialPool()
return pool
def gram_schmidt(y):
""" Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """
n = y.shape[0]
if y.shape[1] != n:
raise ValueError("Invalid shape: {}".format(y.shape))
mo = np.zeros(n)
# Main loop
for i in range(n):
# Remove component in direction i
for j in range(i):
esc = np.sum(y[j]*y[i])
y[i] -= y[j]*esc
# Normalization
mo[i] = np.linalg.norm(y[i])
y[i] /= mo[i]
return mo
class use_backend(object):
def __init__(self, backend):
import matplotlib.pyplot as plt
from IPython.core.interactiveshell import InteractiveShell
from IPython.core.pylabtools import backend2gui
self.shell = InteractiveShell.instance()
self.old_backend = backend2gui[str(plt.get_backend())]
self.new_backend = backend
def __enter__(self):
gui, backend = self.shell.enable_matplotlib(self.new_backend)
def __exit__(self, type, value, tb):
gui, backend = self.shell.enable_matplotlib(self.old_backend)
def inherit_docs(cls):
|
class ImmutableDict(collections.Mapping):
def __init__(self, somedict):
self._dict = dict(somedict) # make a copy
self._hash = None
def __getitem__(self, key):
return self._dict[key]
def __len__(self):
return len(self._dict)
def __iter__(self):
return iter(self._dict)
def __hash__(self):
if self._hash is None:
self._hash = hash(frozenset(self._dict.items()))
return self._hash
def __eq__(self, other):
return self._dict == other._dict
| for name, func in vars(cls).items():
if not func.__doc__:
for parent in cls.__bases__:
try:
parfunc = getattr(parent, name)
except AttributeError: # parent doesn't have function
break
if parfunc and getattr(parfunc, '__doc__', None):
func.__doc__ = parfunc.__doc__
break
return cls | identifier_body |
util.py | # coding: utf-8
""" General utilities. """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Standard library
import collections
import sys
import logging
import multiprocessing
# Third-party
import numpy as np
__all__ = ['get_pool']
# Create logger
logger = logging.getLogger(__name__)
class SerialPool(object):
def close(self):
return
def map(self, *args, **kwargs):
return map(*args, **kwargs)
def get_pool(mpi=False, threads=None):
""" Get a pool object to pass to emcee for parallel processing.
If mpi is False and threads is None, pool is None.
Parameters
----------
mpi : bool
Use MPI or not. If specified, ignores the threads kwarg.
threads : int (optional)
If mpi is False and threads is specified, use a Python
multiprocessing pool with the specified number of threads.
"""
if mpi:
from emcee.utils import MPIPool
# Initialize the MPI pool
pool = MPIPool()
# Make sure the thread we're running on is the master
if not pool.is_master():
pool.wait()
sys.exit(0)
logger.debug("Running with MPI...")
elif threads > 1:
|
else:
logger.debug("Running serial...")
pool = SerialPool()
return pool
def gram_schmidt(y):
""" Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """
n = y.shape[0]
if y.shape[1] != n:
raise ValueError("Invalid shape: {}".format(y.shape))
mo = np.zeros(n)
# Main loop
for i in range(n):
# Remove component in direction i
for j in range(i):
esc = np.sum(y[j]*y[i])
y[i] -= y[j]*esc
# Normalization
mo[i] = np.linalg.norm(y[i])
y[i] /= mo[i]
return mo
class use_backend(object):
def __init__(self, backend):
import matplotlib.pyplot as plt
from IPython.core.interactiveshell import InteractiveShell
from IPython.core.pylabtools import backend2gui
self.shell = InteractiveShell.instance()
self.old_backend = backend2gui[str(plt.get_backend())]
self.new_backend = backend
def __enter__(self):
gui, backend = self.shell.enable_matplotlib(self.new_backend)
def __exit__(self, type, value, tb):
gui, backend = self.shell.enable_matplotlib(self.old_backend)
def inherit_docs(cls):
for name, func in vars(cls).items():
if not func.__doc__:
for parent in cls.__bases__:
try:
parfunc = getattr(parent, name)
except AttributeError: # parent doesn't have function
break
if parfunc and getattr(parfunc, '__doc__', None):
func.__doc__ = parfunc.__doc__
break
return cls
class ImmutableDict(collections.Mapping):
def __init__(self, somedict):
self._dict = dict(somedict) # make a copy
self._hash = None
def __getitem__(self, key):
return self._dict[key]
def __len__(self):
return len(self._dict)
def __iter__(self):
return iter(self._dict)
def __hash__(self):
if self._hash is None:
self._hash = hash(frozenset(self._dict.items()))
return self._hash
def __eq__(self, other):
return self._dict == other._dict
| logger.debug("Running with multiprocessing on {} cores..."
.format(threads))
pool = multiprocessing.Pool(threads) | conditional_block |
util.py | # coding: utf-8
""" General utilities. """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Standard library
import collections
import sys
import logging
import multiprocessing
# Third-party
import numpy as np
__all__ = ['get_pool']
# Create logger
logger = logging.getLogger(__name__)
class SerialPool(object):
def close(self):
return
def map(self, *args, **kwargs):
return map(*args, **kwargs)
def get_pool(mpi=False, threads=None):
""" Get a pool object to pass to emcee for parallel processing.
If mpi is False and threads is None, pool is None.
Parameters
----------
mpi : bool
Use MPI or not. If specified, ignores the threads kwarg. |
if mpi:
from emcee.utils import MPIPool
# Initialize the MPI pool
pool = MPIPool()
# Make sure the thread we're running on is the master
if not pool.is_master():
pool.wait()
sys.exit(0)
logger.debug("Running with MPI...")
elif threads > 1:
logger.debug("Running with multiprocessing on {} cores..."
.format(threads))
pool = multiprocessing.Pool(threads)
else:
logger.debug("Running serial...")
pool = SerialPool()
return pool
def gram_schmidt(y):
""" Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """
n = y.shape[0]
if y.shape[1] != n:
raise ValueError("Invalid shape: {}".format(y.shape))
mo = np.zeros(n)
# Main loop
for i in range(n):
# Remove component in direction i
for j in range(i):
esc = np.sum(y[j]*y[i])
y[i] -= y[j]*esc
# Normalization
mo[i] = np.linalg.norm(y[i])
y[i] /= mo[i]
return mo
class use_backend(object):
def __init__(self, backend):
import matplotlib.pyplot as plt
from IPython.core.interactiveshell import InteractiveShell
from IPython.core.pylabtools import backend2gui
self.shell = InteractiveShell.instance()
self.old_backend = backend2gui[str(plt.get_backend())]
self.new_backend = backend
def __enter__(self):
gui, backend = self.shell.enable_matplotlib(self.new_backend)
def __exit__(self, type, value, tb):
gui, backend = self.shell.enable_matplotlib(self.old_backend)
def inherit_docs(cls):
for name, func in vars(cls).items():
if not func.__doc__:
for parent in cls.__bases__:
try:
parfunc = getattr(parent, name)
except AttributeError: # parent doesn't have function
break
if parfunc and getattr(parfunc, '__doc__', None):
func.__doc__ = parfunc.__doc__
break
return cls
class ImmutableDict(collections.Mapping):
def __init__(self, somedict):
self._dict = dict(somedict) # make a copy
self._hash = None
def __getitem__(self, key):
return self._dict[key]
def __len__(self):
return len(self._dict)
def __iter__(self):
return iter(self._dict)
def __hash__(self):
if self._hash is None:
self._hash = hash(frozenset(self._dict.items()))
return self._hash
def __eq__(self, other):
return self._dict == other._dict | threads : int (optional)
If mpi is False and threads is specified, use a Python
multiprocessing pool with the specified number of threads.
""" | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.