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 |
|---|---|---|---|---|
syntax_iterators.py | from typing import Union, Iterator
from ...symbols import NOUN, PROPN, PRON
from ...errors import Errors
from ...tokens import Doc, Span
def noun_chunks(doclike: Union[Doc, Span]) -> Iterator[Span]:
"""
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
"""
# fmt: off
labels = ["nsubj", "nsubj:pass", "obj", "iobj", "ROOT", "appos", "nmod", "nmod:poss"]
# fmt: on
doc = doclike.doc # Ensure works on both Doc and Span.
if not doc.has_annotation("DEP"):
raise ValueError(Errors.E029)
np_deps = [doc.vocab.strings[label] for label in labels]
conj = doc.vocab.strings.add("conj")
np_label = doc.vocab.strings.add("NP")
prev_end = -1
for i, word in enumerate(doclike):
if word.pos not in (NOUN, PROPN, PRON):
continue
# Prevent nested chunks from being produced
if word.left_edge.i <= prev_end:
continue
if word.dep in np_deps:
prev_end = word.right_edge.i
yield word.left_edge.i, word.right_edge.i + 1, np_label
elif word.dep == conj:
|
SYNTAX_ITERATORS = {"noun_chunks": noun_chunks}
| head = word.head
while head.dep == conj and head.head.i < head.i:
head = head.head
# If the head is an NP, and we're coordinated to it, we're an NP
if head.dep in np_deps:
prev_end = word.right_edge.i
yield word.left_edge.i, word.right_edge.i + 1, np_label | conditional_block |
syntax_iterators.py | from typing import Union, Iterator
from ...symbols import NOUN, PROPN, PRON
from ...errors import Errors
from ...tokens import Doc, Span
def noun_chunks(doclike: Union[Doc, Span]) -> Iterator[Span]:
|
SYNTAX_ITERATORS = {"noun_chunks": noun_chunks}
| """
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
"""
# fmt: off
labels = ["nsubj", "nsubj:pass", "obj", "iobj", "ROOT", "appos", "nmod", "nmod:poss"]
# fmt: on
doc = doclike.doc # Ensure works on both Doc and Span.
if not doc.has_annotation("DEP"):
raise ValueError(Errors.E029)
np_deps = [doc.vocab.strings[label] for label in labels]
conj = doc.vocab.strings.add("conj")
np_label = doc.vocab.strings.add("NP")
prev_end = -1
for i, word in enumerate(doclike):
if word.pos not in (NOUN, PROPN, PRON):
continue
# Prevent nested chunks from being produced
if word.left_edge.i <= prev_end:
continue
if word.dep in np_deps:
prev_end = word.right_edge.i
yield word.left_edge.i, word.right_edge.i + 1, np_label
elif word.dep == conj:
head = word.head
while head.dep == conj and head.head.i < head.i:
head = head.head
# If the head is an NP, and we're coordinated to it, we're an NP
if head.dep in np_deps:
prev_end = word.right_edge.i
yield word.left_edge.i, word.right_edge.i + 1, np_label | identifier_body |
syntax_iterators.py | from typing import Union, Iterator
from ...symbols import NOUN, PROPN, PRON
from ...errors import Errors
from ...tokens import Doc, Span
def noun_chunks(doclike: Union[Doc, Span]) -> Iterator[Span]:
"""
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
"""
# fmt: off
labels = ["nsubj", "nsubj:pass", "obj", "iobj", "ROOT", "appos", "nmod", "nmod:poss"]
# fmt: on
doc = doclike.doc # Ensure works on both Doc and Span.
if not doc.has_annotation("DEP"):
raise ValueError(Errors.E029)
np_deps = [doc.vocab.strings[label] for label in labels]
conj = doc.vocab.strings.add("conj")
np_label = doc.vocab.strings.add("NP")
prev_end = -1
for i, word in enumerate(doclike):
if word.pos not in (NOUN, PROPN, PRON):
continue
# Prevent nested chunks from being produced
if word.left_edge.i <= prev_end:
continue | while head.dep == conj and head.head.i < head.i:
head = head.head
# If the head is an NP, and we're coordinated to it, we're an NP
if head.dep in np_deps:
prev_end = word.right_edge.i
yield word.left_edge.i, word.right_edge.i + 1, np_label
SYNTAX_ITERATORS = {"noun_chunks": noun_chunks} | if word.dep in np_deps:
prev_end = word.right_edge.i
yield word.left_edge.i, word.right_edge.i + 1, np_label
elif word.dep == conj:
head = word.head | random_line_split |
syntax_iterators.py | from typing import Union, Iterator
from ...symbols import NOUN, PROPN, PRON
from ...errors import Errors
from ...tokens import Doc, Span
def | (doclike: Union[Doc, Span]) -> Iterator[Span]:
"""
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
"""
# fmt: off
labels = ["nsubj", "nsubj:pass", "obj", "iobj", "ROOT", "appos", "nmod", "nmod:poss"]
# fmt: on
doc = doclike.doc # Ensure works on both Doc and Span.
if not doc.has_annotation("DEP"):
raise ValueError(Errors.E029)
np_deps = [doc.vocab.strings[label] for label in labels]
conj = doc.vocab.strings.add("conj")
np_label = doc.vocab.strings.add("NP")
prev_end = -1
for i, word in enumerate(doclike):
if word.pos not in (NOUN, PROPN, PRON):
continue
# Prevent nested chunks from being produced
if word.left_edge.i <= prev_end:
continue
if word.dep in np_deps:
prev_end = word.right_edge.i
yield word.left_edge.i, word.right_edge.i + 1, np_label
elif word.dep == conj:
head = word.head
while head.dep == conj and head.head.i < head.i:
head = head.head
# If the head is an NP, and we're coordinated to it, we're an NP
if head.dep in np_deps:
prev_end = word.right_edge.i
yield word.left_edge.i, word.right_edge.i + 1, np_label
SYNTAX_ITERATORS = {"noun_chunks": noun_chunks}
| noun_chunks | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(step_trait)]
#![deny(unsafe_code)]
extern crate heapsize;
#[macro_use] extern crate heapsize_derive;
extern crate num_traits;
extern crate rustc_serialize;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use std::cmp::{self, max, min};
use std::fmt;
use std::iter;
use std::marker::PhantomData;
use std::ops;
pub trait Int:
Copy
+ ops::Add<Self, Output=Self>
+ ops::Sub<Self, Output=Self>
+ cmp::Ord
{
fn zero() -> Self;
fn one() -> Self;
fn max_value() -> Self;
fn from_usize(n: usize) -> Option<Self>;
}
impl Int for isize {
#[inline]
fn zero() -> isize { 0 }
#[inline]
fn one() -> isize { 1 }
#[inline]
fn max_value() -> isize { ::std::isize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<isize> { num_traits::NumCast::from(n) }
}
impl Int for usize {
#[inline]
fn zero() -> usize { 0 }
#[inline]
fn one() -> usize { 1 }
#[inline]
fn max_value() -> usize { ::std::usize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<usize> { Some(n) }
}
/// An index type to be used by a `Range`
pub trait RangeIndex: Int + fmt::Debug {
type Index;
fn new(x: Self::Index) -> Self;
fn get(self) -> Self::Index;
}
impl RangeIndex for isize {
type Index = isize;
#[inline]
fn new(x: isize) -> isize { x }
#[inline]
fn get(self) -> isize { self }
}
impl RangeIndex for usize {
type Index = usize;
#[inline]
fn new(x: usize) -> usize { x }
#[inline]
fn | (self) -> usize { self }
}
/// Implements a range index type with operator overloads
#[macro_export]
macro_rules! int_range_index {
($(#[$attr:meta])* struct $Self_:ident($T:ty)) => (
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)]
$(#[$attr])*
pub struct $Self_(pub $T);
impl $Self_ {
#[inline]
pub fn to_usize(self) -> usize {
self.get() as usize
}
}
impl RangeIndex for $Self_ {
type Index = $T;
#[inline]
fn new(x: $T) -> $Self_ {
$Self_(x)
}
#[inline]
fn get(self) -> $T {
match self { $Self_(x) => x }
}
}
impl $crate::Int for $Self_ {
#[inline]
fn zero() -> $Self_ { $Self_($crate::Int::zero()) }
#[inline]
fn one() -> $Self_ { $Self_($crate::Int::one()) }
#[inline]
fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) }
#[inline]
fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) }
}
impl ::std::ops::Add<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn add(self, other: $Self_) -> $Self_ {
$Self_(self.get() + other.get())
}
}
impl ::std::ops::Sub<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn sub(self, other: $Self_) -> $Self_ {
$Self_(self.get() - other.get())
}
}
impl ::std::ops::Neg for $Self_ {
type Output = $Self_;
#[inline]
fn neg(self) -> $Self_ {
$Self_(-self.get())
}
}
)
}
/// A range of indices
#[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)]
pub struct Range<I> {
begin: I,
length: I,
}
impl<I: RangeIndex> fmt::Debug for Range<I> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{:?} .. {:?})", self.begin(), self.end())
}
}
/// An iterator over each index in a range
pub struct EachIndex<T, I> {
it: ops::Range<T>,
phantom: PhantomData<I>,
}
pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> {
EachIndex { it: start.get()..stop.get(), phantom: PhantomData }
}
impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I>
where T: Int + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> {
type Item = I;
#[inline]
fn next(&mut self) -> Option<I> {
self.it.next().map(RangeIndex::new)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<I: RangeIndex> Range<I> {
/// Create a new range from beginning and length offsets. This could be
/// denoted as `[begin, begin + length)`.
///
/// ~~~ignore
/// |-- begin ->|-- length ->|
/// | | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn new(begin: I, length: I) -> Range<I> {
Range { begin: begin, length: length }
}
#[inline]
pub fn empty() -> Range<I> {
Range::new(Int::zero(), Int::zero())
}
/// The index offset to the beginning of the range.
///
/// ~~~ignore
/// |-- begin ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn begin(&self) -> I { self.begin }
/// The index offset from the beginning to the end of the range.
///
/// ~~~ignore
/// |-- length ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn length(&self) -> I { self.length }
/// The index offset to the end of the range.
///
/// ~~~ignore
/// |--------- end --------->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn end(&self) -> I { self.begin + self.length }
/// `true` if the index is between the beginning and the end of the range.
///
/// ~~~ignore
/// false true false
/// | | |
/// <- o - - + - - +=====+======+ - + - ->
/// ~~~
#[inline]
pub fn contains(&self, i: I) -> bool {
i >= self.begin() && i < self.end()
}
/// `true` if the offset from the beginning to the end of the range is zero.
#[inline]
pub fn is_empty(&self) -> bool {
self.length() == Int::zero()
}
/// Shift the entire range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - +============+ - - - - - | - - - ->
/// |
/// <- o - - - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn shift_by(&mut self, delta: I) {
self.begin = self.begin + delta;
}
/// Extend the end of the range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_by(&mut self, delta: I) {
self.length = self.length + delta;
}
/// Move the end of the range to the target index.
///
/// ~~~ignore
/// target
/// |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_to(&mut self, target: I) {
self.length = target - self.begin;
}
/// Adjust the beginning offset and the length by the supplied deltas.
#[inline]
pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) {
self.begin = self.begin + begin_delta;
self.length = self.length + length_delta;
}
/// Set the begin and length values.
#[inline]
pub fn reset(&mut self, begin: I, length: I) {
self.begin = begin;
self.length = length;
}
#[inline]
pub fn intersect(&self, other: &Range<I>) -> Range<I> {
let begin = max(self.begin(), other.begin());
let end = min(self.end(), other.end());
if end < begin {
Range::empty()
} else {
Range::new(begin, end - begin)
}
}
}
/// Methods for `Range`s with indices based on integer values
impl<T: Int, I: RangeIndex<Index=T>> Range<I> {
/// Returns an iterater that increments over `[begin, end)`.
#[inline]
pub fn each_index(&self) -> EachIndex<T, I> {
each_index(self.begin(), self.end())
}
}
| get | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(step_trait)]
#![deny(unsafe_code)]
extern crate heapsize;
#[macro_use] extern crate heapsize_derive;
extern crate num_traits;
extern crate rustc_serialize;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use std::cmp::{self, max, min};
use std::fmt;
use std::iter;
use std::marker::PhantomData;
use std::ops;
pub trait Int:
Copy
+ ops::Add<Self, Output=Self>
+ ops::Sub<Self, Output=Self>
+ cmp::Ord
{
fn zero() -> Self;
fn one() -> Self;
fn max_value() -> Self;
fn from_usize(n: usize) -> Option<Self>;
}
impl Int for isize {
#[inline]
fn zero() -> isize { 0 }
#[inline]
fn one() -> isize { 1 }
#[inline]
fn max_value() -> isize { ::std::isize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<isize> { num_traits::NumCast::from(n) }
}
impl Int for usize {
#[inline]
fn zero() -> usize { 0 }
#[inline]
fn one() -> usize { 1 }
#[inline]
fn max_value() -> usize { ::std::usize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<usize> { Some(n) }
}
/// An index type to be used by a `Range`
pub trait RangeIndex: Int + fmt::Debug {
type Index;
fn new(x: Self::Index) -> Self;
fn get(self) -> Self::Index;
}
impl RangeIndex for isize {
type Index = isize;
#[inline]
fn new(x: isize) -> isize { x }
#[inline]
fn get(self) -> isize { self }
}
impl RangeIndex for usize {
type Index = usize;
#[inline]
fn new(x: usize) -> usize { x }
#[inline]
fn get(self) -> usize { self }
}
/// Implements a range index type with operator overloads
#[macro_export]
macro_rules! int_range_index {
($(#[$attr:meta])* struct $Self_:ident($T:ty)) => (
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)]
$(#[$attr])*
pub struct $Self_(pub $T);
impl $Self_ {
#[inline]
pub fn to_usize(self) -> usize {
self.get() as usize
}
}
impl RangeIndex for $Self_ {
type Index = $T;
#[inline]
fn new(x: $T) -> $Self_ {
$Self_(x)
}
#[inline]
fn get(self) -> $T {
match self { $Self_(x) => x }
}
}
impl $crate::Int for $Self_ {
#[inline]
fn zero() -> $Self_ { $Self_($crate::Int::zero()) }
#[inline]
fn one() -> $Self_ { $Self_($crate::Int::one()) }
#[inline]
fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) }
#[inline]
fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) }
}
impl ::std::ops::Add<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn add(self, other: $Self_) -> $Self_ {
$Self_(self.get() + other.get())
}
}
impl ::std::ops::Sub<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn sub(self, other: $Self_) -> $Self_ {
$Self_(self.get() - other.get())
}
}
impl ::std::ops::Neg for $Self_ {
type Output = $Self_;
#[inline]
fn neg(self) -> $Self_ {
$Self_(-self.get())
}
}
)
}
/// A range of indices
#[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)]
pub struct Range<I> {
begin: I,
length: I,
}
impl<I: RangeIndex> fmt::Debug for Range<I> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{:?} .. {:?})", self.begin(), self.end())
}
}
/// An iterator over each index in a range
pub struct EachIndex<T, I> {
it: ops::Range<T>,
phantom: PhantomData<I>,
}
pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> {
EachIndex { it: start.get()..stop.get(), phantom: PhantomData }
}
impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I>
where T: Int + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> {
type Item = I;
#[inline]
fn next(&mut self) -> Option<I> {
self.it.next().map(RangeIndex::new)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<I: RangeIndex> Range<I> {
/// Create a new range from beginning and length offsets. This could be
/// denoted as `[begin, begin + length)`.
///
/// ~~~ignore
/// |-- begin ->|-- length ->|
/// | | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn new(begin: I, length: I) -> Range<I> {
Range { begin: begin, length: length }
}
#[inline]
pub fn empty() -> Range<I> {
Range::new(Int::zero(), Int::zero())
}
/// The index offset to the beginning of the range.
///
/// ~~~ignore
/// |-- begin ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn begin(&self) -> I { self.begin }
/// The index offset from the beginning to the end of the range.
///
/// ~~~ignore
/// |-- length ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn length(&self) -> I { self.length }
/// The index offset to the end of the range.
///
/// ~~~ignore
/// |--------- end --------->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn end(&self) -> I { self.begin + self.length }
/// `true` if the index is between the beginning and the end of the range.
///
/// ~~~ignore
/// false true false
/// | | |
/// <- o - - + - - +=====+======+ - + - ->
/// ~~~
#[inline]
pub fn contains(&self, i: I) -> bool {
i >= self.begin() && i < self.end()
}
/// `true` if the offset from the beginning to the end of the range is zero.
#[inline]
pub fn is_empty(&self) -> bool {
self.length() == Int::zero()
}
/// Shift the entire range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - +============+ - - - - - | - - - ->
/// |
/// <- o - - - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn shift_by(&mut self, delta: I) {
self.begin = self.begin + delta;
}
/// Extend the end of the range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_by(&mut self, delta: I) {
self.length = self.length + delta;
}
/// Move the end of the range to the target index.
///
/// ~~~ignore
/// target
/// |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_to(&mut self, target: I) {
self.length = target - self.begin;
}
/// Adjust the beginning offset and the length by the supplied deltas.
#[inline]
pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) {
self.begin = self.begin + begin_delta;
self.length = self.length + length_delta;
}
/// Set the begin and length values.
#[inline]
pub fn reset(&mut self, begin: I, length: I) {
self.begin = begin;
self.length = length;
}
#[inline]
pub fn intersect(&self, other: &Range<I>) -> Range<I> {
let begin = max(self.begin(), other.begin());
let end = min(self.end(), other.end());
if end < begin | else {
Range::new(begin, end - begin)
}
}
}
/// Methods for `Range`s with indices based on integer values
impl<T: Int, I: RangeIndex<Index=T>> Range<I> {
/// Returns an iterater that increments over `[begin, end)`.
#[inline]
pub fn each_index(&self) -> EachIndex<T, I> {
each_index(self.begin(), self.end())
}
}
| {
Range::empty()
} | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(step_trait)]
#![deny(unsafe_code)]
extern crate heapsize;
#[macro_use] extern crate heapsize_derive;
extern crate num_traits;
extern crate rustc_serialize;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use std::cmp::{self, max, min};
use std::fmt;
use std::iter;
use std::marker::PhantomData;
use std::ops;
pub trait Int:
Copy
+ ops::Add<Self, Output=Self>
+ ops::Sub<Self, Output=Self>
+ cmp::Ord
{
fn zero() -> Self;
fn one() -> Self;
fn max_value() -> Self;
fn from_usize(n: usize) -> Option<Self>;
}
impl Int for isize {
#[inline]
fn zero() -> isize { 0 }
#[inline]
fn one() -> isize { 1 }
#[inline]
fn max_value() -> isize { ::std::isize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<isize> { num_traits::NumCast::from(n) }
}
impl Int for usize {
#[inline]
fn zero() -> usize { 0 }
#[inline]
fn one() -> usize { 1 }
#[inline]
fn max_value() -> usize { ::std::usize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<usize> { Some(n) }
}
/// An index type to be used by a `Range`
pub trait RangeIndex: Int + fmt::Debug {
type Index;
fn new(x: Self::Index) -> Self;
fn get(self) -> Self::Index;
}
impl RangeIndex for isize {
type Index = isize;
#[inline]
fn new(x: isize) -> isize { x }
#[inline]
fn get(self) -> isize { self }
}
impl RangeIndex for usize {
type Index = usize;
#[inline]
fn new(x: usize) -> usize { x }
#[inline]
fn get(self) -> usize { self }
}
/// Implements a range index type with operator overloads
#[macro_export]
macro_rules! int_range_index {
($(#[$attr:meta])* struct $Self_:ident($T:ty)) => (
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)]
$(#[$attr])*
pub struct $Self_(pub $T);
impl $Self_ {
#[inline]
pub fn to_usize(self) -> usize {
self.get() as usize
}
}
impl RangeIndex for $Self_ {
type Index = $T;
#[inline]
fn new(x: $T) -> $Self_ {
$Self_(x)
}
#[inline]
fn get(self) -> $T {
match self { $Self_(x) => x }
}
}
impl $crate::Int for $Self_ {
#[inline]
fn zero() -> $Self_ { $Self_($crate::Int::zero()) }
#[inline]
fn one() -> $Self_ { $Self_($crate::Int::one()) }
#[inline]
fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) }
#[inline]
fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) }
}
impl ::std::ops::Add<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn add(self, other: $Self_) -> $Self_ {
$Self_(self.get() + other.get())
}
}
impl ::std::ops::Sub<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn sub(self, other: $Self_) -> $Self_ {
$Self_(self.get() - other.get())
}
}
impl ::std::ops::Neg for $Self_ {
type Output = $Self_;
#[inline]
fn neg(self) -> $Self_ {
$Self_(-self.get())
}
}
)
}
/// A range of indices
#[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)]
pub struct Range<I> {
begin: I,
length: I,
}
impl<I: RangeIndex> fmt::Debug for Range<I> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{:?} .. {:?})", self.begin(), self.end())
}
}
/// An iterator over each index in a range
pub struct EachIndex<T, I> {
it: ops::Range<T>,
phantom: PhantomData<I>,
}
pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> {
EachIndex { it: start.get()..stop.get(), phantom: PhantomData }
}
impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I>
where T: Int + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> {
type Item = I;
#[inline]
fn next(&mut self) -> Option<I> {
self.it.next().map(RangeIndex::new)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<I: RangeIndex> Range<I> {
/// Create a new range from beginning and length offsets. This could be
/// denoted as `[begin, begin + length)`.
///
/// ~~~ignore
/// |-- begin ->|-- length ->|
/// | | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn new(begin: I, length: I) -> Range<I> {
Range { begin: begin, length: length }
}
#[inline]
pub fn empty() -> Range<I> {
Range::new(Int::zero(), Int::zero())
}
/// The index offset to the beginning of the range.
///
/// ~~~ignore
/// |-- begin ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn begin(&self) -> I { self.begin }
/// The index offset from the beginning to the end of the range.
///
/// ~~~ignore
/// |-- length ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn length(&self) -> I { self.length }
/// The index offset to the end of the range.
///
/// ~~~ignore
/// |--------- end --------->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn end(&self) -> I { self.begin + self.length }
/// `true` if the index is between the beginning and the end of the range.
///
/// ~~~ignore
/// false true false
/// | | |
/// <- o - - + - - +=====+======+ - + - ->
/// ~~~
#[inline]
pub fn contains(&self, i: I) -> bool {
i >= self.begin() && i < self.end() | self.length() == Int::zero()
}
/// Shift the entire range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - +============+ - - - - - | - - - ->
/// |
/// <- o - - - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn shift_by(&mut self, delta: I) {
self.begin = self.begin + delta;
}
/// Extend the end of the range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_by(&mut self, delta: I) {
self.length = self.length + delta;
}
/// Move the end of the range to the target index.
///
/// ~~~ignore
/// target
/// |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_to(&mut self, target: I) {
self.length = target - self.begin;
}
/// Adjust the beginning offset and the length by the supplied deltas.
#[inline]
pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) {
self.begin = self.begin + begin_delta;
self.length = self.length + length_delta;
}
/// Set the begin and length values.
#[inline]
pub fn reset(&mut self, begin: I, length: I) {
self.begin = begin;
self.length = length;
}
#[inline]
pub fn intersect(&self, other: &Range<I>) -> Range<I> {
let begin = max(self.begin(), other.begin());
let end = min(self.end(), other.end());
if end < begin {
Range::empty()
} else {
Range::new(begin, end - begin)
}
}
}
/// Methods for `Range`s with indices based on integer values
impl<T: Int, I: RangeIndex<Index=T>> Range<I> {
/// Returns an iterater that increments over `[begin, end)`.
#[inline]
pub fn each_index(&self) -> EachIndex<T, I> {
each_index(self.begin(), self.end())
}
} | }
/// `true` if the offset from the beginning to the end of the range is zero.
#[inline]
pub fn is_empty(&self) -> bool { | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(step_trait)]
#![deny(unsafe_code)]
extern crate heapsize;
#[macro_use] extern crate heapsize_derive;
extern crate num_traits;
extern crate rustc_serialize;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use std::cmp::{self, max, min};
use std::fmt;
use std::iter;
use std::marker::PhantomData;
use std::ops;
pub trait Int:
Copy
+ ops::Add<Self, Output=Self>
+ ops::Sub<Self, Output=Self>
+ cmp::Ord
{
fn zero() -> Self;
fn one() -> Self;
fn max_value() -> Self;
fn from_usize(n: usize) -> Option<Self>;
}
impl Int for isize {
#[inline]
fn zero() -> isize { 0 }
#[inline]
fn one() -> isize { 1 }
#[inline]
fn max_value() -> isize { ::std::isize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<isize> { num_traits::NumCast::from(n) }
}
impl Int for usize {
#[inline]
fn zero() -> usize |
#[inline]
fn one() -> usize { 1 }
#[inline]
fn max_value() -> usize { ::std::usize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<usize> { Some(n) }
}
/// An index type to be used by a `Range`
pub trait RangeIndex: Int + fmt::Debug {
type Index;
fn new(x: Self::Index) -> Self;
fn get(self) -> Self::Index;
}
impl RangeIndex for isize {
type Index = isize;
#[inline]
fn new(x: isize) -> isize { x }
#[inline]
fn get(self) -> isize { self }
}
impl RangeIndex for usize {
type Index = usize;
#[inline]
fn new(x: usize) -> usize { x }
#[inline]
fn get(self) -> usize { self }
}
/// Implements a range index type with operator overloads
#[macro_export]
macro_rules! int_range_index {
($(#[$attr:meta])* struct $Self_:ident($T:ty)) => (
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)]
$(#[$attr])*
pub struct $Self_(pub $T);
impl $Self_ {
#[inline]
pub fn to_usize(self) -> usize {
self.get() as usize
}
}
impl RangeIndex for $Self_ {
type Index = $T;
#[inline]
fn new(x: $T) -> $Self_ {
$Self_(x)
}
#[inline]
fn get(self) -> $T {
match self { $Self_(x) => x }
}
}
impl $crate::Int for $Self_ {
#[inline]
fn zero() -> $Self_ { $Self_($crate::Int::zero()) }
#[inline]
fn one() -> $Self_ { $Self_($crate::Int::one()) }
#[inline]
fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) }
#[inline]
fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) }
}
impl ::std::ops::Add<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn add(self, other: $Self_) -> $Self_ {
$Self_(self.get() + other.get())
}
}
impl ::std::ops::Sub<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn sub(self, other: $Self_) -> $Self_ {
$Self_(self.get() - other.get())
}
}
impl ::std::ops::Neg for $Self_ {
type Output = $Self_;
#[inline]
fn neg(self) -> $Self_ {
$Self_(-self.get())
}
}
)
}
/// A range of indices
#[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)]
pub struct Range<I> {
begin: I,
length: I,
}
impl<I: RangeIndex> fmt::Debug for Range<I> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{:?} .. {:?})", self.begin(), self.end())
}
}
/// An iterator over each index in a range
pub struct EachIndex<T, I> {
it: ops::Range<T>,
phantom: PhantomData<I>,
}
pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> {
EachIndex { it: start.get()..stop.get(), phantom: PhantomData }
}
impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I>
where T: Int + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> {
type Item = I;
#[inline]
fn next(&mut self) -> Option<I> {
self.it.next().map(RangeIndex::new)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<I: RangeIndex> Range<I> {
/// Create a new range from beginning and length offsets. This could be
/// denoted as `[begin, begin + length)`.
///
/// ~~~ignore
/// |-- begin ->|-- length ->|
/// | | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn new(begin: I, length: I) -> Range<I> {
Range { begin: begin, length: length }
}
#[inline]
pub fn empty() -> Range<I> {
Range::new(Int::zero(), Int::zero())
}
/// The index offset to the beginning of the range.
///
/// ~~~ignore
/// |-- begin ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn begin(&self) -> I { self.begin }
/// The index offset from the beginning to the end of the range.
///
/// ~~~ignore
/// |-- length ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn length(&self) -> I { self.length }
/// The index offset to the end of the range.
///
/// ~~~ignore
/// |--------- end --------->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn end(&self) -> I { self.begin + self.length }
/// `true` if the index is between the beginning and the end of the range.
///
/// ~~~ignore
/// false true false
/// | | |
/// <- o - - + - - +=====+======+ - + - ->
/// ~~~
#[inline]
pub fn contains(&self, i: I) -> bool {
i >= self.begin() && i < self.end()
}
/// `true` if the offset from the beginning to the end of the range is zero.
#[inline]
pub fn is_empty(&self) -> bool {
self.length() == Int::zero()
}
/// Shift the entire range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - +============+ - - - - - | - - - ->
/// |
/// <- o - - - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn shift_by(&mut self, delta: I) {
self.begin = self.begin + delta;
}
/// Extend the end of the range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_by(&mut self, delta: I) {
self.length = self.length + delta;
}
/// Move the end of the range to the target index.
///
/// ~~~ignore
/// target
/// |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_to(&mut self, target: I) {
self.length = target - self.begin;
}
/// Adjust the beginning offset and the length by the supplied deltas.
#[inline]
pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) {
self.begin = self.begin + begin_delta;
self.length = self.length + length_delta;
}
/// Set the begin and length values.
#[inline]
pub fn reset(&mut self, begin: I, length: I) {
self.begin = begin;
self.length = length;
}
#[inline]
pub fn intersect(&self, other: &Range<I>) -> Range<I> {
let begin = max(self.begin(), other.begin());
let end = min(self.end(), other.end());
if end < begin {
Range::empty()
} else {
Range::new(begin, end - begin)
}
}
}
/// Methods for `Range`s with indices based on integer values
impl<T: Int, I: RangeIndex<Index=T>> Range<I> {
/// Returns an iterater that increments over `[begin, end)`.
#[inline]
pub fn each_index(&self) -> EachIndex<T, I> {
each_index(self.begin(), self.end())
}
}
| { 0 } | identifier_body |
challenge.service.ts | import { Injectable } from '@angular/core';
import {BaseCrudService} from "./base-crud.service";
import {Observable} from "rxjs/Observable";
import {Ladder, LadderUser} from "./ladder.service";
import {User} from "./users.service";
@Injectable()
export class ChallengeService extends BaseCrudService<Challenge> {
url = '/api/ladder/challenge';
public deleteChallenge(ladder : Ladder, challenge : Challenge): Observable<any> {
return this.http.delete(this.url + "/" + ladder.id + "/" + challenge.id, {
responseType: 'text'
});
}
public postChallenge(ladder : Ladder, challenge : Challenge): Observable<Challenge> {
return this.http.post<Challenge>(this.url + "/" + ladder.id, challenge);
}
public putChallenge(challenge : Challenge) {
return this.http.put<Challenge>(this.url + "/" + challenge.id, challenge);
}
public getAvailableChallenges() |
}
export interface LadderNode extends Ladder {
above: LadderUser[],
below: LadderUser[]
}
export interface Challenge {
id: number;
name: string;
created: Date;
status: string; // PROPOSED, ACCEPTED, REJECTED, CLOSED
dateTime: Date;
dateTimeEnd: Date;
challengerId: number;
challengedId: number;
scoreChallenger: number;
scoreChallenged: number;
}
| {
return this.http.get<LadderNode[]>(this.url);
} | identifier_body |
challenge.service.ts | import { Injectable } from '@angular/core';
import {BaseCrudService} from "./base-crud.service";
import {Observable} from "rxjs/Observable";
import {Ladder, LadderUser} from "./ladder.service";
import {User} from "./users.service";
@Injectable()
export class ChallengeService extends BaseCrudService<Challenge> {
url = '/api/ladder/challenge';
public deleteChallenge(ladder : Ladder, challenge : Challenge): Observable<any> {
return this.http.delete(this.url + "/" + ladder.id + "/" + challenge.id, {
responseType: 'text'
});
}
public postChallenge(ladder : Ladder, challenge : Challenge): Observable<Challenge> {
return this.http.post<Challenge>(this.url + "/" + ladder.id, challenge);
}
public putChallenge(challenge : Challenge) {
return this.http.put<Challenge>(this.url + "/" + challenge.id, challenge);
}
public getAvailableChallenges() {
return this.http.get<LadderNode[]>(this.url);
}
}
export interface LadderNode extends Ladder {
above: LadderUser[],
below: LadderUser[]
}
export interface Challenge {
id: number; | name: string;
created: Date;
status: string; // PROPOSED, ACCEPTED, REJECTED, CLOSED
dateTime: Date;
dateTimeEnd: Date;
challengerId: number;
challengedId: number;
scoreChallenger: number;
scoreChallenged: number;
} | random_line_split | |
challenge.service.ts | import { Injectable } from '@angular/core';
import {BaseCrudService} from "./base-crud.service";
import {Observable} from "rxjs/Observable";
import {Ladder, LadderUser} from "./ladder.service";
import {User} from "./users.service";
@Injectable()
export class ChallengeService extends BaseCrudService<Challenge> {
url = '/api/ladder/challenge';
public deleteChallenge(ladder : Ladder, challenge : Challenge): Observable<any> {
return this.http.delete(this.url + "/" + ladder.id + "/" + challenge.id, {
responseType: 'text'
});
}
public | (ladder : Ladder, challenge : Challenge): Observable<Challenge> {
return this.http.post<Challenge>(this.url + "/" + ladder.id, challenge);
}
public putChallenge(challenge : Challenge) {
return this.http.put<Challenge>(this.url + "/" + challenge.id, challenge);
}
public getAvailableChallenges() {
return this.http.get<LadderNode[]>(this.url);
}
}
export interface LadderNode extends Ladder {
above: LadderUser[],
below: LadderUser[]
}
export interface Challenge {
id: number;
name: string;
created: Date;
status: string; // PROPOSED, ACCEPTED, REJECTED, CLOSED
dateTime: Date;
dateTimeEnd: Date;
challengerId: number;
challengedId: number;
scoreChallenger: number;
scoreChallenged: number;
}
| postChallenge | identifier_name |
highlight.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Basic html highlighting functionality
//!
//! This module uses libsyntax's lexer to provide token-based highlighting for
//! the HTML documentation generated by rustdoc.
use std::io;
use syntax::parse;
use syntax::parse::lexer;
use html::escape::Escape;
use t = syntax::parse::token;
/// Highlights some source code, returning the HTML output.
pub fn | (src: &str, class: Option<&str>, id: Option<&str>) -> String {
debug!("highlighting: ================\n{}\n==============", src);
let sess = parse::new_parse_sess();
let fm = parse::string_to_filemap(&sess,
src.to_string(),
"<stdin>".to_string());
let mut out = io::MemWriter::new();
doit(&sess,
lexer::StringReader::new(&sess.span_diagnostic, fm),
class,
id,
&mut out).unwrap();
String::from_utf8_lossy(out.unwrap().as_slice()).into_string()
}
/// Exhausts the `lexer` writing the output into `out`.
///
/// The general structure for this method is to iterate over each token,
/// possibly giving it an HTML span with a class specifying what flavor of token
/// it's used. All source code emission is done as slices from the source map,
/// not from the tokens themselves, in order to stay true to the original
/// source.
fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader,
class: Option<&str>, id: Option<&str>,
out: &mut Writer) -> io::IoResult<()> {
use syntax::parse::lexer::Reader;
try!(write!(out, "<pre "));
match id {
Some(id) => try!(write!(out, "id='{}' ", id)),
None => {}
}
try!(write!(out, "class='rust {}'>\n", class.unwrap_or("")));
let mut is_attribute = false;
let mut is_macro = false;
let mut is_macro_nonterminal = false;
loop {
let next = lexer.next_token();
let snip = |sp| sess.span_diagnostic.cm.span_to_snippet(sp).unwrap();
if next.tok == t::EOF { break }
let klass = match next.tok {
t::WS => {
try!(write!(out, "{}", Escape(snip(next.sp).as_slice())));
continue
},
t::COMMENT => {
try!(write!(out, "<span class='comment'>{}</span>",
Escape(snip(next.sp).as_slice())));
continue
},
t::SHEBANG(s) => {
try!(write!(out, "{}", Escape(s.as_str())));
continue
},
// If this '&' token is directly adjacent to another token, assume
// that it's the address-of operator instead of the and-operator.
// This allows us to give all pointers their own class (`Box` and
// `@` are below).
t::BINOP(t::AND) if lexer.peek().sp.lo == next.sp.hi => "kw-2",
t::AT | t::TILDE => "kw-2",
// consider this as part of a macro invocation if there was a
// leading identifier
t::NOT if is_macro => { is_macro = false; "macro" }
// operators
t::EQ | t::LT | t::LE | t::EQEQ | t::NE | t::GE | t::GT |
t::ANDAND | t::OROR | t::NOT | t::BINOP(..) | t::RARROW |
t::BINOPEQ(..) | t::FAT_ARROW => "op",
// miscellaneous, no highlighting
t::DOT | t::DOTDOT | t::DOTDOTDOT | t::COMMA | t::SEMI |
t::COLON | t::MOD_SEP | t::LARROW | t::LPAREN |
t::RPAREN | t::LBRACKET | t::LBRACE | t::RBRACE | t::QUESTION => "",
t::DOLLAR => {
if t::is_ident(&lexer.peek().tok) {
is_macro_nonterminal = true;
"macro-nonterminal"
} else {
""
}
}
// This is the start of an attribute. We're going to want to
// continue highlighting it as an attribute until the ending ']' is
// seen, so skip out early. Down below we terminate the attribute
// span when we see the ']'.
t::POUND => {
is_attribute = true;
try!(write!(out, r"<span class='attribute'>#"));
continue
}
t::RBRACKET => {
if is_attribute {
is_attribute = false;
try!(write!(out, "]</span>"));
continue
} else {
""
}
}
// text literals
t::LIT_BYTE(..) | t::LIT_BINARY(..) | t::LIT_BINARY_RAW(..) |
t::LIT_CHAR(..) | t::LIT_STR(..) | t::LIT_STR_RAW(..) => "string",
// number literals
t::LIT_INTEGER(..) | t::LIT_FLOAT(..) => "number",
// keywords are also included in the identifier set
t::IDENT(ident, _is_mod_sep) => {
match t::get_ident(ident).get() {
"ref" | "mut" => "kw-2",
"self" => "self",
"false" | "true" => "boolval",
"Option" | "Result" => "prelude-ty",
"Some" | "None" | "Ok" | "Err" => "prelude-val",
_ if t::is_any_keyword(&next.tok) => "kw",
_ => {
if is_macro_nonterminal {
is_macro_nonterminal = false;
"macro-nonterminal"
} else if lexer.peek().tok == t::NOT {
is_macro = true;
"macro"
} else {
"ident"
}
}
}
}
t::LIFETIME(..) => "lifetime",
t::DOC_COMMENT(..) => "doccomment",
t::UNDERSCORE | t::EOF | t::INTERPOLATED(..) => "",
};
// as mentioned above, use the original source code instead of
// stringifying this token
let snip = sess.span_diagnostic.cm.span_to_snippet(next.sp).unwrap();
if klass == "" {
try!(write!(out, "{}", Escape(snip.as_slice())));
} else {
try!(write!(out, "<span class='{}'>{}</span>", klass,
Escape(snip.as_slice())));
}
}
write!(out, "</pre>\n")
}
| highlight | identifier_name |
highlight.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Basic html highlighting functionality
//!
//! This module uses libsyntax's lexer to provide token-based highlighting for
//! the HTML documentation generated by rustdoc.
use std::io;
use syntax::parse;
use syntax::parse::lexer;
use html::escape::Escape;
use t = syntax::parse::token;
/// Highlights some source code, returning the HTML output.
pub fn highlight(src: &str, class: Option<&str>, id: Option<&str>) -> String {
debug!("highlighting: ================\n{}\n==============", src);
let sess = parse::new_parse_sess();
let fm = parse::string_to_filemap(&sess,
src.to_string(),
"<stdin>".to_string());
let mut out = io::MemWriter::new();
doit(&sess,
lexer::StringReader::new(&sess.span_diagnostic, fm),
class,
id,
&mut out).unwrap();
String::from_utf8_lossy(out.unwrap().as_slice()).into_string()
}
/// Exhausts the `lexer` writing the output into `out`.
///
/// The general structure for this method is to iterate over each token,
/// possibly giving it an HTML span with a class specifying what flavor of token
/// it's used. All source code emission is done as slices from the source map,
/// not from the tokens themselves, in order to stay true to the original
/// source.
fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader,
class: Option<&str>, id: Option<&str>,
out: &mut Writer) -> io::IoResult<()> {
use syntax::parse::lexer::Reader;
try!(write!(out, "<pre "));
match id {
Some(id) => try!(write!(out, "id='{}' ", id)),
None => {}
}
try!(write!(out, "class='rust {}'>\n", class.unwrap_or("")));
let mut is_attribute = false;
let mut is_macro = false;
let mut is_macro_nonterminal = false;
loop {
let next = lexer.next_token();
let snip = |sp| sess.span_diagnostic.cm.span_to_snippet(sp).unwrap();
if next.tok == t::EOF { break }
let klass = match next.tok {
t::WS => {
try!(write!(out, "{}", Escape(snip(next.sp).as_slice())));
continue
},
t::COMMENT => {
try!(write!(out, "<span class='comment'>{}</span>",
Escape(snip(next.sp).as_slice())));
continue
},
t::SHEBANG(s) => {
try!(write!(out, "{}", Escape(s.as_str())));
continue
},
// If this '&' token is directly adjacent to another token, assume
// that it's the address-of operator instead of the and-operator.
// This allows us to give all pointers their own class (`Box` and
// `@` are below).
t::BINOP(t::AND) if lexer.peek().sp.lo == next.sp.hi => "kw-2",
t::AT | t::TILDE => "kw-2",
// consider this as part of a macro invocation if there was a
// leading identifier
t::NOT if is_macro => { is_macro = false; "macro" }
// operators
t::EQ | t::LT | t::LE | t::EQEQ | t::NE | t::GE | t::GT |
t::ANDAND | t::OROR | t::NOT | t::BINOP(..) | t::RARROW |
t::BINOPEQ(..) | t::FAT_ARROW => "op",
// miscellaneous, no highlighting
t::DOT | t::DOTDOT | t::DOTDOTDOT | t::COMMA | t::SEMI |
t::COLON | t::MOD_SEP | t::LARROW | t::LPAREN |
t::RPAREN | t::LBRACKET | t::LBRACE | t::RBRACE | t::QUESTION => "",
t::DOLLAR => {
if t::is_ident(&lexer.peek().tok) {
is_macro_nonterminal = true;
"macro-nonterminal"
} else {
""
}
}
// This is the start of an attribute. We're going to want to
// continue highlighting it as an attribute until the ending ']' is
// seen, so skip out early. Down below we terminate the attribute
// span when we see the ']'.
t::POUND => {
is_attribute = true;
try!(write!(out, r"<span class='attribute'>#"));
continue
}
t::RBRACKET => {
if is_attribute {
is_attribute = false;
try!(write!(out, "]</span>"));
continue
} else {
"" | t::LIT_BYTE(..) | t::LIT_BINARY(..) | t::LIT_BINARY_RAW(..) |
t::LIT_CHAR(..) | t::LIT_STR(..) | t::LIT_STR_RAW(..) => "string",
// number literals
t::LIT_INTEGER(..) | t::LIT_FLOAT(..) => "number",
// keywords are also included in the identifier set
t::IDENT(ident, _is_mod_sep) => {
match t::get_ident(ident).get() {
"ref" | "mut" => "kw-2",
"self" => "self",
"false" | "true" => "boolval",
"Option" | "Result" => "prelude-ty",
"Some" | "None" | "Ok" | "Err" => "prelude-val",
_ if t::is_any_keyword(&next.tok) => "kw",
_ => {
if is_macro_nonterminal {
is_macro_nonterminal = false;
"macro-nonterminal"
} else if lexer.peek().tok == t::NOT {
is_macro = true;
"macro"
} else {
"ident"
}
}
}
}
t::LIFETIME(..) => "lifetime",
t::DOC_COMMENT(..) => "doccomment",
t::UNDERSCORE | t::EOF | t::INTERPOLATED(..) => "",
};
// as mentioned above, use the original source code instead of
// stringifying this token
let snip = sess.span_diagnostic.cm.span_to_snippet(next.sp).unwrap();
if klass == "" {
try!(write!(out, "{}", Escape(snip.as_slice())));
} else {
try!(write!(out, "<span class='{}'>{}</span>", klass,
Escape(snip.as_slice())));
}
}
write!(out, "</pre>\n")
} | }
}
// text literals | random_line_split |
highlight.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Basic html highlighting functionality
//!
//! This module uses libsyntax's lexer to provide token-based highlighting for
//! the HTML documentation generated by rustdoc.
use std::io;
use syntax::parse;
use syntax::parse::lexer;
use html::escape::Escape;
use t = syntax::parse::token;
/// Highlights some source code, returning the HTML output.
pub fn highlight(src: &str, class: Option<&str>, id: Option<&str>) -> String |
/// Exhausts the `lexer` writing the output into `out`.
///
/// The general structure for this method is to iterate over each token,
/// possibly giving it an HTML span with a class specifying what flavor of token
/// it's used. All source code emission is done as slices from the source map,
/// not from the tokens themselves, in order to stay true to the original
/// source.
fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader,
class: Option<&str>, id: Option<&str>,
out: &mut Writer) -> io::IoResult<()> {
use syntax::parse::lexer::Reader;
try!(write!(out, "<pre "));
match id {
Some(id) => try!(write!(out, "id='{}' ", id)),
None => {}
}
try!(write!(out, "class='rust {}'>\n", class.unwrap_or("")));
let mut is_attribute = false;
let mut is_macro = false;
let mut is_macro_nonterminal = false;
loop {
let next = lexer.next_token();
let snip = |sp| sess.span_diagnostic.cm.span_to_snippet(sp).unwrap();
if next.tok == t::EOF { break }
let klass = match next.tok {
t::WS => {
try!(write!(out, "{}", Escape(snip(next.sp).as_slice())));
continue
},
t::COMMENT => {
try!(write!(out, "<span class='comment'>{}</span>",
Escape(snip(next.sp).as_slice())));
continue
},
t::SHEBANG(s) => {
try!(write!(out, "{}", Escape(s.as_str())));
continue
},
// If this '&' token is directly adjacent to another token, assume
// that it's the address-of operator instead of the and-operator.
// This allows us to give all pointers their own class (`Box` and
// `@` are below).
t::BINOP(t::AND) if lexer.peek().sp.lo == next.sp.hi => "kw-2",
t::AT | t::TILDE => "kw-2",
// consider this as part of a macro invocation if there was a
// leading identifier
t::NOT if is_macro => { is_macro = false; "macro" }
// operators
t::EQ | t::LT | t::LE | t::EQEQ | t::NE | t::GE | t::GT |
t::ANDAND | t::OROR | t::NOT | t::BINOP(..) | t::RARROW |
t::BINOPEQ(..) | t::FAT_ARROW => "op",
// miscellaneous, no highlighting
t::DOT | t::DOTDOT | t::DOTDOTDOT | t::COMMA | t::SEMI |
t::COLON | t::MOD_SEP | t::LARROW | t::LPAREN |
t::RPAREN | t::LBRACKET | t::LBRACE | t::RBRACE | t::QUESTION => "",
t::DOLLAR => {
if t::is_ident(&lexer.peek().tok) {
is_macro_nonterminal = true;
"macro-nonterminal"
} else {
""
}
}
// This is the start of an attribute. We're going to want to
// continue highlighting it as an attribute until the ending ']' is
// seen, so skip out early. Down below we terminate the attribute
// span when we see the ']'.
t::POUND => {
is_attribute = true;
try!(write!(out, r"<span class='attribute'>#"));
continue
}
t::RBRACKET => {
if is_attribute {
is_attribute = false;
try!(write!(out, "]</span>"));
continue
} else {
""
}
}
// text literals
t::LIT_BYTE(..) | t::LIT_BINARY(..) | t::LIT_BINARY_RAW(..) |
t::LIT_CHAR(..) | t::LIT_STR(..) | t::LIT_STR_RAW(..) => "string",
// number literals
t::LIT_INTEGER(..) | t::LIT_FLOAT(..) => "number",
// keywords are also included in the identifier set
t::IDENT(ident, _is_mod_sep) => {
match t::get_ident(ident).get() {
"ref" | "mut" => "kw-2",
"self" => "self",
"false" | "true" => "boolval",
"Option" | "Result" => "prelude-ty",
"Some" | "None" | "Ok" | "Err" => "prelude-val",
_ if t::is_any_keyword(&next.tok) => "kw",
_ => {
if is_macro_nonterminal {
is_macro_nonterminal = false;
"macro-nonterminal"
} else if lexer.peek().tok == t::NOT {
is_macro = true;
"macro"
} else {
"ident"
}
}
}
}
t::LIFETIME(..) => "lifetime",
t::DOC_COMMENT(..) => "doccomment",
t::UNDERSCORE | t::EOF | t::INTERPOLATED(..) => "",
};
// as mentioned above, use the original source code instead of
// stringifying this token
let snip = sess.span_diagnostic.cm.span_to_snippet(next.sp).unwrap();
if klass == "" {
try!(write!(out, "{}", Escape(snip.as_slice())));
} else {
try!(write!(out, "<span class='{}'>{}</span>", klass,
Escape(snip.as_slice())));
}
}
write!(out, "</pre>\n")
}
| {
debug!("highlighting: ================\n{}\n==============", src);
let sess = parse::new_parse_sess();
let fm = parse::string_to_filemap(&sess,
src.to_string(),
"<stdin>".to_string());
let mut out = io::MemWriter::new();
doit(&sess,
lexer::StringReader::new(&sess.span_diagnostic, fm),
class,
id,
&mut out).unwrap();
String::from_utf8_lossy(out.unwrap().as_slice()).into_string()
} | identifier_body |
work.en.ts | export const work_en = `
# [Meituan-Dianping](http://meituan.com/)
## Web Frontend Developer
## 2015.10 - now
### Take part in developing the web applications for Meituan Dianping restaurant menu order business, including hybrid web applications, PC web applications.
### Designed and developed the client side code for the "Tianyan" food safety supervisor and as the person in responsible.
### Currently as a member of infrastructure team and as a person in responsible for the data platform of the Meituan-Dianping menu order business.
# [Dianping](http://www.dianping.com/)
## Web Frontend Developer
## 2015.06 - 2015.10
### Basiclly focused on javascript application development. Developed Hybrid web applications on mobile devices.
# [Taomee Entertainment](http://www.61.com/)
## Software Engineer
## 2014.07 - 2015.06
### Helped built javascript applications for an interanl used system for data statistics.
### Developed browser-side applications for [game accounts system](http://account.61.com)
### Developed browser-side applications for [payment system](http://pay.61.com)
| ### Embedded software development. Developed the tcp/udp server and client on pc and cortex m3 using the lwip protocal.
`; |
# [Changchun Institute of Applied Chemistry](http://www.ciac.jl.cn/)
## Software Development Intern
## 2013.04 - 2013.09 | random_line_split |
model_eval.py | import os
import argparse
import re
import numpy as np
from model import *
np.random.seed(1337)
def get_engine(address = "postgresql+pg8000://script@localhost:5432/ccfd"):
# disk_engine = create_engine('sqlite:///'+data_dir+db_name,convert_unicode=True)
# disk_engine.raw_connection().connection.text_factory = str
disk_engine = create_engine(address)
return disk_engine
class ModelLoader:
arch_dir = '/home/botty/Documents/CCFD/data/models/archs/'
archs = ['/home/botty/Documents/CCFD/data/archs/bi_GRU_320_4_DO-0.3']
w_dir = '/home/botty/Documents/CCFD/data/models/{table}/'
__ws = [
'Bidirectional_Class400.0_GRU_320_4_RMSprop_0.00025_epochs_10_DO-0.3.09-0.01.hdf5',
'Bidirectional_Class400.0_GRU_320_4_RMSprop_0.00025_epochs_10_DO-0.3.05-0.04623.hdf5'
]
def __init__(self,table,w_id=-1,arch_path=None,w_path=None):
if arch_path == None:
self.arch_path = self.archs[0]
else:
self.arch_path = ModelLoader.arch_dir+arch_path
if w_path == None:
self.w_path = ModelLoader.w_dir.format(table=table)+ModelLoader.__ws[w_id]
else:
self.w_path = ModelLoader.w_dir.format(table=table)+w_path
self.model = load_model(self.arch_path, self.w_path)
class Evaluator(ModelOperator):
'Evaluates models'
def __init__(self, *args, **kwargs):
ModelOperator.__init__(self, *args, **kwargs)
# self.disk_engine = disk_engine
# self.model = model
# self.table = table
# self.auc_list = []
# self.encoders = load_encoders()
# if 'events_tbl' in kwargs:
# self.events_tbl = kwargs['events_tbl']
# else:
# self.events_tbl = None
def evaluate_model(self,user_mode,trans_mode,title,add_info=''):
disk_engine = self.disk_engine
model = self.model
table = self.table
events_tbl = self.events_tbl
encoders = self.encoders
batch_size = 2000
#calcualte # samples
val_samples = trans_num_table(table,disk_engine,mode=user_mode,trans_mode=trans_mode)
# val_samples = 10
print '# samples',val_samples
eval_gen = data_generator(user_mode,trans_mode,disk_engine,encoders,table=table,
batch_size=batch_size,usr_ratio=80, class_weight=None,lbl_pad_val = 2, pad_val = -1,events_tbl=events_tbl)
plt_filename = './results/figures/'+table+'/'+'ROC_'+user_mode+'_'+trans_mode+'_'+title+'_'+add_info+".png"
eval_list = eval_auc_generator(model, eval_gen, val_samples, max_q_size=10000,plt_filename=plt_filename)
auc_val = eval_list[0]
clc_report = eval_list[1]
acc = eval_list[2]
print "AUC:", auc_val
print 'Classification report'
print clc_report
print 'Accuracy'
print acc
self.auc_list.append(str(auc_val))
return eval_list
def find_best_val_file(name,files):
pass
def extract_val_loss(f_name):
|
def eval_best_val(table):
#populate dictionary
directory = ModelLoader.w_dir.format(table=table)
print 'evaluating path @'
for root, dirs, files in os.walk(directory):
names = {}
for f in files:
# print f
m = re.search('\.[0-9]+-',f)
name_end = m.span()[0]
name = f[0:name_end]
if 'Bidirectional_Class' in f:
print 'skipping >>>>> '+f
continue
# print name
if name in names.keys():
temp = names[name]
temp_val = extract_val_loss(temp)
curr_val = extract_val_loss(f)
if(curr_val<temp_val):
names[name] = f
else:
names[name] = f
print 'TOTAL MODELS TO EVALUATE! - ',len(names)
for k,v in names.iteritems():
auc_list = eval_model(table,arch=k+'.yml',w_path=v,add_info='BEST_VAL',title = k)
rsl_file = '/home/botty/Documents/CCFD/results/psql_gs_{table}.csv'.format(table=table)
with io.open(rsl_file, 'a', encoding='utf-8') as file:
auc_string = ','.join(auc_list)
title_csv = k+','+auc_string+'\n'
file.write(unicode(title_csv))
print 'logged @ {file}'.format(file=rsl_file)
def eval_model(*args, **kwargs):
table = args[0]
arch = None
ws_path = None
add_info = ''
title = 'BiRNN-DO3-DLE'
if 'add_info' in kwargs.keys():
add_info = kwargs['add_info']
if 'title' in kwargs.keys():
title = kwargs['title']
if 'arch' in kwargs.keys():
arch = kwargs['arch']
if 'w_path' in kwargs.keys():
w_path = kwargs['w_path']
else:
w_id = kwargs['w_id']
#########################################
disk_engine = get_engine()
ml = ModelLoader(table,arch_path=arch,w_path=w_path)
model = ml.model
data_little_enc_eval = Evaluator(model, table, disk_engine)
table_auth = 'auth_enc'
auth_enc_eval = Evaluator(model, table_auth, disk_engine)
options = ['train','test']
py.sign_in('bottydim', 'o1kuyms9zv')
print '=======================DATA LITTLE============================'
for user_mode in options:
for trans_mode in options:
print '################## USER:{user_mode}--------TRANS:{trans_mode}###############'.format(user_mode=user_mode,trans_mode=trans_mode)
eval_list = data_little_enc_eval.evaluate_model(user_mode,trans_mode,title,add_info=add_info)
print '#########################################################################################################'
print '=======================AUC============================'
return data_little_enc_eval.auc_list
def parse_args():
parser = argparse.ArgumentParser(prog='Model Evaluator')
parser.add_argument('-t','--table',required=True)
parser.add_argument('-i','--id',default=1)
args = parser.parse_args()
####################################DATA SOURCE################################
var_args = vars(args)
table = var_args['table']
w_id = var_args['id']
return table, w_id
if __name__ == "__main__":
table, w_id = parse_args()
# eval_model(table,w_id = w_id):
eval_best_val(table)
# for user_mode in options:
# for trans_mode in options:
# print '################## USER:{user_mode}--------TRANS:{trans_mode}###############'.format(user_mode=user_mode,trans_mode=trans_mode)
# auth_enc_eval.evaluate_model(user_mode,trans_mode,title)
# print '#########################################################################################################' | m = re.search('-[0-9]+\.[0-9]+\.hdf5',f_name)
start = m.span()[0]+1
end = m.span()[1]-5
return float(f_name[start:end]) | identifier_body |
model_eval.py | import os
import argparse
import re
import numpy as np
from model import *
np.random.seed(1337)
def get_engine(address = "postgresql+pg8000://script@localhost:5432/ccfd"):
# disk_engine = create_engine('sqlite:///'+data_dir+db_name,convert_unicode=True)
# disk_engine.raw_connection().connection.text_factory = str
disk_engine = create_engine(address)
return disk_engine
class ModelLoader:
arch_dir = '/home/botty/Documents/CCFD/data/models/archs/'
archs = ['/home/botty/Documents/CCFD/data/archs/bi_GRU_320_4_DO-0.3']
w_dir = '/home/botty/Documents/CCFD/data/models/{table}/'
__ws = [
'Bidirectional_Class400.0_GRU_320_4_RMSprop_0.00025_epochs_10_DO-0.3.09-0.01.hdf5',
'Bidirectional_Class400.0_GRU_320_4_RMSprop_0.00025_epochs_10_DO-0.3.05-0.04623.hdf5'
]
def __init__(self,table,w_id=-1,arch_path=None,w_path=None):
if arch_path == None:
self.arch_path = self.archs[0]
else:
self.arch_path = ModelLoader.arch_dir+arch_path
if w_path == None:
self.w_path = ModelLoader.w_dir.format(table=table)+ModelLoader.__ws[w_id]
else:
self.w_path = ModelLoader.w_dir.format(table=table)+w_path
self.model = load_model(self.arch_path, self.w_path)
class Evaluator(ModelOperator):
'Evaluates models'
def __init__(self, *args, **kwargs):
ModelOperator.__init__(self, *args, **kwargs)
# self.disk_engine = disk_engine
# self.model = model
# self.table = table
# self.auc_list = []
# self.encoders = load_encoders()
# if 'events_tbl' in kwargs:
# self.events_tbl = kwargs['events_tbl']
# else:
# self.events_tbl = None
def evaluate_model(self,user_mode,trans_mode,title,add_info=''):
disk_engine = self.disk_engine
model = self.model
table = self.table
events_tbl = self.events_tbl
encoders = self.encoders
batch_size = 2000
#calcualte # samples
val_samples = trans_num_table(table,disk_engine,mode=user_mode,trans_mode=trans_mode)
# val_samples = 10
print '# samples',val_samples
eval_gen = data_generator(user_mode,trans_mode,disk_engine,encoders,table=table,
batch_size=batch_size,usr_ratio=80, class_weight=None,lbl_pad_val = 2, pad_val = -1,events_tbl=events_tbl)
plt_filename = './results/figures/'+table+'/'+'ROC_'+user_mode+'_'+trans_mode+'_'+title+'_'+add_info+".png"
eval_list = eval_auc_generator(model, eval_gen, val_samples, max_q_size=10000,plt_filename=plt_filename)
auc_val = eval_list[0]
clc_report = eval_list[1]
acc = eval_list[2]
print "AUC:", auc_val
print 'Classification report'
print clc_report
print 'Accuracy'
print acc
self.auc_list.append(str(auc_val))
return eval_list
def find_best_val_file(name,files):
pass
def extract_val_loss(f_name):
m = re.search('-[0-9]+\.[0-9]+\.hdf5',f_name)
start = m.span()[0]+1
end = m.span()[1]-5
return float(f_name[start:end])
def eval_best_val(table):
#populate dictionary
directory = ModelLoader.w_dir.format(table=table)
print 'evaluating path @'
for root, dirs, files in os.walk(directory):
names = {}
for f in files:
# print f
m = re.search('\.[0-9]+-',f)
name_end = m.span()[0]
name = f[0:name_end]
if 'Bidirectional_Class' in f:
print 'skipping >>>>> '+f
continue
# print name
if name in names.keys():
temp = names[name]
temp_val = extract_val_loss(temp)
curr_val = extract_val_loss(f)
if(curr_val<temp_val):
names[name] = f
else:
names[name] = f
print 'TOTAL MODELS TO EVALUATE! - ',len(names)
for k,v in names.iteritems():
auc_list = eval_model(table,arch=k+'.yml',w_path=v,add_info='BEST_VAL',title = k)
rsl_file = '/home/botty/Documents/CCFD/results/psql_gs_{table}.csv'.format(table=table)
with io.open(rsl_file, 'a', encoding='utf-8') as file:
auc_string = ','.join(auc_list)
title_csv = k+','+auc_string+'\n'
file.write(unicode(title_csv))
print 'logged @ {file}'.format(file=rsl_file)
def eval_model(*args, **kwargs):
table = args[0]
arch = None
ws_path = None
add_info = ''
title = 'BiRNN-DO3-DLE'
if 'add_info' in kwargs.keys():
add_info = kwargs['add_info']
if 'title' in kwargs.keys():
title = kwargs['title']
if 'arch' in kwargs.keys():
arch = kwargs['arch']
if 'w_path' in kwargs.keys():
w_path = kwargs['w_path']
else:
w_id = kwargs['w_id']
#########################################
disk_engine = get_engine()
ml = ModelLoader(table,arch_path=arch,w_path=w_path)
model = ml.model
data_little_enc_eval = Evaluator(model, table, disk_engine)
table_auth = 'auth_enc'
auth_enc_eval = Evaluator(model, table_auth, disk_engine)
options = ['train','test']
py.sign_in('bottydim', 'o1kuyms9zv')
print '=======================DATA LITTLE============================'
for user_mode in options:
|
print '=======================AUC============================'
return data_little_enc_eval.auc_list
def parse_args():
parser = argparse.ArgumentParser(prog='Model Evaluator')
parser.add_argument('-t','--table',required=True)
parser.add_argument('-i','--id',default=1)
args = parser.parse_args()
####################################DATA SOURCE################################
var_args = vars(args)
table = var_args['table']
w_id = var_args['id']
return table, w_id
if __name__ == "__main__":
table, w_id = parse_args()
# eval_model(table,w_id = w_id):
eval_best_val(table)
# for user_mode in options:
# for trans_mode in options:
# print '################## USER:{user_mode}--------TRANS:{trans_mode}###############'.format(user_mode=user_mode,trans_mode=trans_mode)
# auth_enc_eval.evaluate_model(user_mode,trans_mode,title)
# print '#########################################################################################################' | for trans_mode in options:
print '################## USER:{user_mode}--------TRANS:{trans_mode}###############'.format(user_mode=user_mode,trans_mode=trans_mode)
eval_list = data_little_enc_eval.evaluate_model(user_mode,trans_mode,title,add_info=add_info)
print '#########################################################################################################' | conditional_block |
model_eval.py | import os
import argparse
import re
import numpy as np
from model import *
np.random.seed(1337)
def get_engine(address = "postgresql+pg8000://script@localhost:5432/ccfd"):
# disk_engine = create_engine('sqlite:///'+data_dir+db_name,convert_unicode=True)
# disk_engine.raw_connection().connection.text_factory = str
disk_engine = create_engine(address)
return disk_engine
class ModelLoader:
arch_dir = '/home/botty/Documents/CCFD/data/models/archs/'
archs = ['/home/botty/Documents/CCFD/data/archs/bi_GRU_320_4_DO-0.3']
w_dir = '/home/botty/Documents/CCFD/data/models/{table}/'
__ws = [
'Bidirectional_Class400.0_GRU_320_4_RMSprop_0.00025_epochs_10_DO-0.3.09-0.01.hdf5',
'Bidirectional_Class400.0_GRU_320_4_RMSprop_0.00025_epochs_10_DO-0.3.05-0.04623.hdf5'
]
def __init__(self,table,w_id=-1,arch_path=None,w_path=None):
if arch_path == None:
self.arch_path = self.archs[0]
else:
self.arch_path = ModelLoader.arch_dir+arch_path
if w_path == None:
self.w_path = ModelLoader.w_dir.format(table=table)+ModelLoader.__ws[w_id]
else:
self.w_path = ModelLoader.w_dir.format(table=table)+w_path
self.model = load_model(self.arch_path, self.w_path)
class Evaluator(ModelOperator):
'Evaluates models'
def __init__(self, *args, **kwargs):
ModelOperator.__init__(self, *args, **kwargs)
# self.disk_engine = disk_engine
# self.model = model
# self.table = table
# self.auc_list = []
# self.encoders = load_encoders()
# if 'events_tbl' in kwargs:
# self.events_tbl = kwargs['events_tbl']
# else:
# self.events_tbl = None
def evaluate_model(self,user_mode,trans_mode,title,add_info=''):
disk_engine = self.disk_engine
model = self.model
table = self.table
events_tbl = self.events_tbl
encoders = self.encoders
batch_size = 2000
#calcualte # samples
val_samples = trans_num_table(table,disk_engine,mode=user_mode,trans_mode=trans_mode)
# val_samples = 10
print '# samples',val_samples
eval_gen = data_generator(user_mode,trans_mode,disk_engine,encoders,table=table,
batch_size=batch_size,usr_ratio=80, class_weight=None,lbl_pad_val = 2, pad_val = -1,events_tbl=events_tbl)
plt_filename = './results/figures/'+table+'/'+'ROC_'+user_mode+'_'+trans_mode+'_'+title+'_'+add_info+".png"
eval_list = eval_auc_generator(model, eval_gen, val_samples, max_q_size=10000,plt_filename=plt_filename)
auc_val = eval_list[0]
clc_report = eval_list[1]
acc = eval_list[2]
print "AUC:", auc_val
print 'Classification report'
print clc_report
print 'Accuracy'
print acc
self.auc_list.append(str(auc_val))
return eval_list
def find_best_val_file(name,files):
pass
def extract_val_loss(f_name):
m = re.search('-[0-9]+\.[0-9]+\.hdf5',f_name)
start = m.span()[0]+1
end = m.span()[1]-5
return float(f_name[start:end])
def eval_best_val(table):
#populate dictionary
directory = ModelLoader.w_dir.format(table=table)
print 'evaluating path @'
for root, dirs, files in os.walk(directory):
names = {}
for f in files:
# print f
m = re.search('\.[0-9]+-',f)
name_end = m.span()[0]
name = f[0:name_end]
if 'Bidirectional_Class' in f:
print 'skipping >>>>> '+f
continue
# print name
if name in names.keys():
temp = names[name]
temp_val = extract_val_loss(temp)
curr_val = extract_val_loss(f)
if(curr_val<temp_val):
names[name] = f
else:
names[name] = f
print 'TOTAL MODELS TO EVALUATE! - ',len(names)
for k,v in names.iteritems():
auc_list = eval_model(table,arch=k+'.yml',w_path=v,add_info='BEST_VAL',title = k)
rsl_file = '/home/botty/Documents/CCFD/results/psql_gs_{table}.csv'.format(table=table)
with io.open(rsl_file, 'a', encoding='utf-8') as file:
auc_string = ','.join(auc_list)
title_csv = k+','+auc_string+'\n'
file.write(unicode(title_csv))
print 'logged @ {file}'.format(file=rsl_file)
def eval_model(*args, **kwargs):
table = args[0]
arch = None
ws_path = None
add_info = ''
title = 'BiRNN-DO3-DLE'
if 'add_info' in kwargs.keys():
add_info = kwargs['add_info']
if 'title' in kwargs.keys():
title = kwargs['title']
if 'arch' in kwargs.keys():
arch = kwargs['arch']
if 'w_path' in kwargs.keys():
w_path = kwargs['w_path']
else:
w_id = kwargs['w_id']
######################################### | table_auth = 'auth_enc'
auth_enc_eval = Evaluator(model, table_auth, disk_engine)
options = ['train','test']
py.sign_in('bottydim', 'o1kuyms9zv')
print '=======================DATA LITTLE============================'
for user_mode in options:
for trans_mode in options:
print '################## USER:{user_mode}--------TRANS:{trans_mode}###############'.format(user_mode=user_mode,trans_mode=trans_mode)
eval_list = data_little_enc_eval.evaluate_model(user_mode,trans_mode,title,add_info=add_info)
print '#########################################################################################################'
print '=======================AUC============================'
return data_little_enc_eval.auc_list
def parse_args():
parser = argparse.ArgumentParser(prog='Model Evaluator')
parser.add_argument('-t','--table',required=True)
parser.add_argument('-i','--id',default=1)
args = parser.parse_args()
####################################DATA SOURCE################################
var_args = vars(args)
table = var_args['table']
w_id = var_args['id']
return table, w_id
if __name__ == "__main__":
table, w_id = parse_args()
# eval_model(table,w_id = w_id):
eval_best_val(table)
# for user_mode in options:
# for trans_mode in options:
# print '################## USER:{user_mode}--------TRANS:{trans_mode}###############'.format(user_mode=user_mode,trans_mode=trans_mode)
# auth_enc_eval.evaluate_model(user_mode,trans_mode,title)
# print '#########################################################################################################' | disk_engine = get_engine()
ml = ModelLoader(table,arch_path=arch,w_path=w_path)
model = ml.model
data_little_enc_eval = Evaluator(model, table, disk_engine) | random_line_split |
model_eval.py | import os
import argparse
import re
import numpy as np
from model import *
np.random.seed(1337)
def get_engine(address = "postgresql+pg8000://script@localhost:5432/ccfd"):
# disk_engine = create_engine('sqlite:///'+data_dir+db_name,convert_unicode=True)
# disk_engine.raw_connection().connection.text_factory = str
disk_engine = create_engine(address)
return disk_engine
class ModelLoader:
arch_dir = '/home/botty/Documents/CCFD/data/models/archs/'
archs = ['/home/botty/Documents/CCFD/data/archs/bi_GRU_320_4_DO-0.3']
w_dir = '/home/botty/Documents/CCFD/data/models/{table}/'
__ws = [
'Bidirectional_Class400.0_GRU_320_4_RMSprop_0.00025_epochs_10_DO-0.3.09-0.01.hdf5',
'Bidirectional_Class400.0_GRU_320_4_RMSprop_0.00025_epochs_10_DO-0.3.05-0.04623.hdf5'
]
def __init__(self,table,w_id=-1,arch_path=None,w_path=None):
if arch_path == None:
self.arch_path = self.archs[0]
else:
self.arch_path = ModelLoader.arch_dir+arch_path
if w_path == None:
self.w_path = ModelLoader.w_dir.format(table=table)+ModelLoader.__ws[w_id]
else:
self.w_path = ModelLoader.w_dir.format(table=table)+w_path
self.model = load_model(self.arch_path, self.w_path)
class Evaluator(ModelOperator):
'Evaluates models'
def | (self, *args, **kwargs):
ModelOperator.__init__(self, *args, **kwargs)
# self.disk_engine = disk_engine
# self.model = model
# self.table = table
# self.auc_list = []
# self.encoders = load_encoders()
# if 'events_tbl' in kwargs:
# self.events_tbl = kwargs['events_tbl']
# else:
# self.events_tbl = None
def evaluate_model(self,user_mode,trans_mode,title,add_info=''):
disk_engine = self.disk_engine
model = self.model
table = self.table
events_tbl = self.events_tbl
encoders = self.encoders
batch_size = 2000
#calcualte # samples
val_samples = trans_num_table(table,disk_engine,mode=user_mode,trans_mode=trans_mode)
# val_samples = 10
print '# samples',val_samples
eval_gen = data_generator(user_mode,trans_mode,disk_engine,encoders,table=table,
batch_size=batch_size,usr_ratio=80, class_weight=None,lbl_pad_val = 2, pad_val = -1,events_tbl=events_tbl)
plt_filename = './results/figures/'+table+'/'+'ROC_'+user_mode+'_'+trans_mode+'_'+title+'_'+add_info+".png"
eval_list = eval_auc_generator(model, eval_gen, val_samples, max_q_size=10000,plt_filename=plt_filename)
auc_val = eval_list[0]
clc_report = eval_list[1]
acc = eval_list[2]
print "AUC:", auc_val
print 'Classification report'
print clc_report
print 'Accuracy'
print acc
self.auc_list.append(str(auc_val))
return eval_list
def find_best_val_file(name,files):
pass
def extract_val_loss(f_name):
m = re.search('-[0-9]+\.[0-9]+\.hdf5',f_name)
start = m.span()[0]+1
end = m.span()[1]-5
return float(f_name[start:end])
def eval_best_val(table):
#populate dictionary
directory = ModelLoader.w_dir.format(table=table)
print 'evaluating path @'
for root, dirs, files in os.walk(directory):
names = {}
for f in files:
# print f
m = re.search('\.[0-9]+-',f)
name_end = m.span()[0]
name = f[0:name_end]
if 'Bidirectional_Class' in f:
print 'skipping >>>>> '+f
continue
# print name
if name in names.keys():
temp = names[name]
temp_val = extract_val_loss(temp)
curr_val = extract_val_loss(f)
if(curr_val<temp_val):
names[name] = f
else:
names[name] = f
print 'TOTAL MODELS TO EVALUATE! - ',len(names)
for k,v in names.iteritems():
auc_list = eval_model(table,arch=k+'.yml',w_path=v,add_info='BEST_VAL',title = k)
rsl_file = '/home/botty/Documents/CCFD/results/psql_gs_{table}.csv'.format(table=table)
with io.open(rsl_file, 'a', encoding='utf-8') as file:
auc_string = ','.join(auc_list)
title_csv = k+','+auc_string+'\n'
file.write(unicode(title_csv))
print 'logged @ {file}'.format(file=rsl_file)
def eval_model(*args, **kwargs):
table = args[0]
arch = None
ws_path = None
add_info = ''
title = 'BiRNN-DO3-DLE'
if 'add_info' in kwargs.keys():
add_info = kwargs['add_info']
if 'title' in kwargs.keys():
title = kwargs['title']
if 'arch' in kwargs.keys():
arch = kwargs['arch']
if 'w_path' in kwargs.keys():
w_path = kwargs['w_path']
else:
w_id = kwargs['w_id']
#########################################
disk_engine = get_engine()
ml = ModelLoader(table,arch_path=arch,w_path=w_path)
model = ml.model
data_little_enc_eval = Evaluator(model, table, disk_engine)
table_auth = 'auth_enc'
auth_enc_eval = Evaluator(model, table_auth, disk_engine)
options = ['train','test']
py.sign_in('bottydim', 'o1kuyms9zv')
print '=======================DATA LITTLE============================'
for user_mode in options:
for trans_mode in options:
print '################## USER:{user_mode}--------TRANS:{trans_mode}###############'.format(user_mode=user_mode,trans_mode=trans_mode)
eval_list = data_little_enc_eval.evaluate_model(user_mode,trans_mode,title,add_info=add_info)
print '#########################################################################################################'
print '=======================AUC============================'
return data_little_enc_eval.auc_list
def parse_args():
parser = argparse.ArgumentParser(prog='Model Evaluator')
parser.add_argument('-t','--table',required=True)
parser.add_argument('-i','--id',default=1)
args = parser.parse_args()
####################################DATA SOURCE################################
var_args = vars(args)
table = var_args['table']
w_id = var_args['id']
return table, w_id
if __name__ == "__main__":
table, w_id = parse_args()
# eval_model(table,w_id = w_id):
eval_best_val(table)
# for user_mode in options:
# for trans_mode in options:
# print '################## USER:{user_mode}--------TRANS:{trans_mode}###############'.format(user_mode=user_mode,trans_mode=trans_mode)
# auth_enc_eval.evaluate_model(user_mode,trans_mode,title)
# print '#########################################################################################################' | __init__ | identifier_name |
task-comm-7.rs | // run-pass
#![allow(unused_must_use)]
#![allow(unused_assignments)]
// ignore-emscripten no threads support
use std::sync::mpsc::{channel, Sender};
use std::thread;
pub fn main() |
fn test00_start(c: &Sender<isize>, start: isize,
number_of_messages: isize) {
let mut i: isize = 0;
while i < number_of_messages { c.send(start + i).unwrap(); i += 1; }
}
fn test00() {
let mut r: isize = 0;
let mut sum: isize = 0;
let (tx, rx) = channel();
let number_of_messages: isize = 10;
let tx2 = tx.clone();
let t1 = thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 0, number_of_messages);
});
let tx2 = tx.clone();
let t2 = thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 1, number_of_messages);
});
let tx2 = tx.clone();
let t3 = thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 2, number_of_messages);
});
let tx2 = tx.clone();
let t4 = thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 3, number_of_messages);
});
let mut i: isize = 0;
while i < number_of_messages {
r = rx.recv().unwrap();
sum += r;
r = rx.recv().unwrap();
sum += r;
r = rx.recv().unwrap();
sum += r;
r = rx.recv().unwrap();
sum += r;
i += 1;
}
assert_eq!(sum, number_of_messages * 4 * (number_of_messages * 4 - 1) / 2);
t1.join();
t2.join();
t3.join();
t4.join();
}
| { test00(); } | identifier_body |
task-comm-7.rs | // run-pass
#![allow(unused_must_use)]
#![allow(unused_assignments)]
// ignore-emscripten no threads support
use std::sync::mpsc::{channel, Sender}; | use std::thread;
pub fn main() { test00(); }
fn test00_start(c: &Sender<isize>, start: isize,
number_of_messages: isize) {
let mut i: isize = 0;
while i < number_of_messages { c.send(start + i).unwrap(); i += 1; }
}
fn test00() {
let mut r: isize = 0;
let mut sum: isize = 0;
let (tx, rx) = channel();
let number_of_messages: isize = 10;
let tx2 = tx.clone();
let t1 = thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 0, number_of_messages);
});
let tx2 = tx.clone();
let t2 = thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 1, number_of_messages);
});
let tx2 = tx.clone();
let t3 = thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 2, number_of_messages);
});
let tx2 = tx.clone();
let t4 = thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 3, number_of_messages);
});
let mut i: isize = 0;
while i < number_of_messages {
r = rx.recv().unwrap();
sum += r;
r = rx.recv().unwrap();
sum += r;
r = rx.recv().unwrap();
sum += r;
r = rx.recv().unwrap();
sum += r;
i += 1;
}
assert_eq!(sum, number_of_messages * 4 * (number_of_messages * 4 - 1) / 2);
t1.join();
t2.join();
t3.join();
t4.join();
} | random_line_split | |
task-comm-7.rs | // run-pass
#![allow(unused_must_use)]
#![allow(unused_assignments)]
// ignore-emscripten no threads support
use std::sync::mpsc::{channel, Sender};
use std::thread;
pub fn main() { test00(); }
fn test00_start(c: &Sender<isize>, start: isize,
number_of_messages: isize) {
let mut i: isize = 0;
while i < number_of_messages { c.send(start + i).unwrap(); i += 1; }
}
fn | () {
let mut r: isize = 0;
let mut sum: isize = 0;
let (tx, rx) = channel();
let number_of_messages: isize = 10;
let tx2 = tx.clone();
let t1 = thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 0, number_of_messages);
});
let tx2 = tx.clone();
let t2 = thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 1, number_of_messages);
});
let tx2 = tx.clone();
let t3 = thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 2, number_of_messages);
});
let tx2 = tx.clone();
let t4 = thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 3, number_of_messages);
});
let mut i: isize = 0;
while i < number_of_messages {
r = rx.recv().unwrap();
sum += r;
r = rx.recv().unwrap();
sum += r;
r = rx.recv().unwrap();
sum += r;
r = rx.recv().unwrap();
sum += r;
i += 1;
}
assert_eq!(sum, number_of_messages * 4 * (number_of_messages * 4 - 1) / 2);
t1.join();
t2.join();
t3.join();
t4.join();
}
| test00 | identifier_name |
RULE_9_2_D_use_reentrant_function.py | """
Use reentrant functions. Do not use not reentrant functions.(ctime, strtok, toupper)
== Violation ==
void A() {
k = ctime(); <== Violation. ctime() is not the reenterant function.
j = strok(blar blar); <== Violation. strok() is not the reenterant function.
}
== Good ==
void A() {
k = t.ctime(); <== Correct. It may be the reentrant function.
}
void A() {
k = ctime; <== Correct. It may be the reentrant function.
}
"""
from nsiqunittest.nsiqcppstyle_unittestbase import *
from nsiqcppstyle_rulehelper import *
from nsiqcppstyle_reporter import *
from nsiqcppstyle_rulemanager import *
no_reenterant_functions = (
'ctime',
'strtok',
'toupper',
)
def RunRule(lexer, contextStack):
"""
Use reenterant keyword.
"""
t = lexer.GetCurToken()
if t.type == "ID":
if t.value in no_reenterant_functions:
t2 = lexer.PeekNextTokenSkipWhiteSpaceAndComment()
t3 = lexer.PeekPrevTokenSkipWhiteSpaceAndComment()
if t2 is not None and t2.type == "LPAREN":
if t3 is None or t3.type != "PERIOD":
if t.value == "toupper" and nsiqcppstyle_state._nsiqcppstyle_state.GetVar(
"ignore_toupper", "false") == "true":
return
nsiqcppstyle_reporter.Error(t, __name__,
"Do not use not reentrant function(%s)." % t.value)
ruleManager.AddFunctionScopeRule(RunRule)
##########################################################################
# Unit Test
##########################################################################
class testRule(nct):
def setUpRule(self):
ruleManager.AddFunctionScopeRule(RunRule)
def test1(self):
self.Analyze("thisfile.c",
"""
void func1()
{
k = ctime()
}
""")
self.ExpectError(__name__)
def test2(self):
self.Analyze("thisfile.c",
"""
void func1() {
#define ctime() k
}
""")
self.ExpectSuccess(__name__)
def test3(self):
self.Analyze("thisfile.c",
"""
void ctime() {
}
| def test4(self):
self.Analyze("thisfile.c",
"""
void ctime () {
}
""")
self.ExpectSuccess(__name__)
def test5(self):
self.Analyze("thisfile.c",
"""
void func1()
{
k = help.ctime ()
}
""")
self.ExpectSuccess(__name__)
def test6(self):
self.Analyze("thisfile.c",
"""
void func1()
{
k = toupper()
}
""")
self.ExpectError(__name__)
def test7(self):
nsiqcppstyle_state._nsiqcppstyle_state.varMap["ignore_toupper"] = "true"
self.Analyze("thisfile.c",
"""
void func1()
{
k = toupper()
}
""")
self.ExpectSuccess(__name__) | """)
self.ExpectSuccess(__name__)
| random_line_split |
RULE_9_2_D_use_reentrant_function.py | """
Use reentrant functions. Do not use not reentrant functions.(ctime, strtok, toupper)
== Violation ==
void A() {
k = ctime(); <== Violation. ctime() is not the reenterant function.
j = strok(blar blar); <== Violation. strok() is not the reenterant function.
}
== Good ==
void A() {
k = t.ctime(); <== Correct. It may be the reentrant function.
}
void A() {
k = ctime; <== Correct. It may be the reentrant function.
}
"""
from nsiqunittest.nsiqcppstyle_unittestbase import *
from nsiqcppstyle_rulehelper import *
from nsiqcppstyle_reporter import *
from nsiqcppstyle_rulemanager import *
no_reenterant_functions = (
'ctime',
'strtok',
'toupper',
)
def RunRule(lexer, contextStack):
"""
Use reenterant keyword.
"""
t = lexer.GetCurToken()
if t.type == "ID":
if t.value in no_reenterant_functions:
t2 = lexer.PeekNextTokenSkipWhiteSpaceAndComment()
t3 = lexer.PeekPrevTokenSkipWhiteSpaceAndComment()
if t2 is not None and t2.type == "LPAREN":
if t3 is None or t3.type != "PERIOD":
if t.value == "toupper" and nsiqcppstyle_state._nsiqcppstyle_state.GetVar(
"ignore_toupper", "false") == "true":
return
nsiqcppstyle_reporter.Error(t, __name__,
"Do not use not reentrant function(%s)." % t.value)
ruleManager.AddFunctionScopeRule(RunRule)
##########################################################################
# Unit Test
##########################################################################
class testRule(nct):
def setUpRule(self):
ruleManager.AddFunctionScopeRule(RunRule)
def test1(self):
self.Analyze("thisfile.c",
"""
void func1()
{
k = ctime()
}
""")
self.ExpectError(__name__)
def test2(self):
self.Analyze("thisfile.c",
"""
void func1() {
#define ctime() k
}
""")
self.ExpectSuccess(__name__)
def test3(self):
self.Analyze("thisfile.c",
"""
void ctime() {
}
""")
self.ExpectSuccess(__name__)
def | (self):
self.Analyze("thisfile.c",
"""
void ctime () {
}
""")
self.ExpectSuccess(__name__)
def test5(self):
self.Analyze("thisfile.c",
"""
void func1()
{
k = help.ctime ()
}
""")
self.ExpectSuccess(__name__)
def test6(self):
self.Analyze("thisfile.c",
"""
void func1()
{
k = toupper()
}
""")
self.ExpectError(__name__)
def test7(self):
nsiqcppstyle_state._nsiqcppstyle_state.varMap["ignore_toupper"] = "true"
self.Analyze("thisfile.c",
"""
void func1()
{
k = toupper()
}
""")
self.ExpectSuccess(__name__)
| test4 | identifier_name |
RULE_9_2_D_use_reentrant_function.py | """
Use reentrant functions. Do not use not reentrant functions.(ctime, strtok, toupper)
== Violation ==
void A() {
k = ctime(); <== Violation. ctime() is not the reenterant function.
j = strok(blar blar); <== Violation. strok() is not the reenterant function.
}
== Good ==
void A() {
k = t.ctime(); <== Correct. It may be the reentrant function.
}
void A() {
k = ctime; <== Correct. It may be the reentrant function.
}
"""
from nsiqunittest.nsiqcppstyle_unittestbase import *
from nsiqcppstyle_rulehelper import *
from nsiqcppstyle_reporter import *
from nsiqcppstyle_rulemanager import *
no_reenterant_functions = (
'ctime',
'strtok',
'toupper',
)
def RunRule(lexer, contextStack):
"""
Use reenterant keyword.
"""
t = lexer.GetCurToken()
if t.type == "ID":
if t.value in no_reenterant_functions:
t2 = lexer.PeekNextTokenSkipWhiteSpaceAndComment()
t3 = lexer.PeekPrevTokenSkipWhiteSpaceAndComment()
if t2 is not None and t2.type == "LPAREN":
if t3 is None or t3.type != "PERIOD":
if t.value == "toupper" and nsiqcppstyle_state._nsiqcppstyle_state.GetVar(
"ignore_toupper", "false") == "true":
return
nsiqcppstyle_reporter.Error(t, __name__,
"Do not use not reentrant function(%s)." % t.value)
ruleManager.AddFunctionScopeRule(RunRule)
##########################################################################
# Unit Test
##########################################################################
class testRule(nct):
| def setUpRule(self):
ruleManager.AddFunctionScopeRule(RunRule)
def test1(self):
self.Analyze("thisfile.c",
"""
void func1()
{
k = ctime()
}
""")
self.ExpectError(__name__)
def test2(self):
self.Analyze("thisfile.c",
"""
void func1() {
#define ctime() k
}
""")
self.ExpectSuccess(__name__)
def test3(self):
self.Analyze("thisfile.c",
"""
void ctime() {
}
""")
self.ExpectSuccess(__name__)
def test4(self):
self.Analyze("thisfile.c",
"""
void ctime () {
}
""")
self.ExpectSuccess(__name__)
def test5(self):
self.Analyze("thisfile.c",
"""
void func1()
{
k = help.ctime ()
}
""")
self.ExpectSuccess(__name__)
def test6(self):
self.Analyze("thisfile.c",
"""
void func1()
{
k = toupper()
}
""")
self.ExpectError(__name__)
def test7(self):
nsiqcppstyle_state._nsiqcppstyle_state.varMap["ignore_toupper"] = "true"
self.Analyze("thisfile.c",
"""
void func1()
{
k = toupper()
}
""")
self.ExpectSuccess(__name__) | identifier_body | |
RULE_9_2_D_use_reentrant_function.py | """
Use reentrant functions. Do not use not reentrant functions.(ctime, strtok, toupper)
== Violation ==
void A() {
k = ctime(); <== Violation. ctime() is not the reenterant function.
j = strok(blar blar); <== Violation. strok() is not the reenterant function.
}
== Good ==
void A() {
k = t.ctime(); <== Correct. It may be the reentrant function.
}
void A() {
k = ctime; <== Correct. It may be the reentrant function.
}
"""
from nsiqunittest.nsiqcppstyle_unittestbase import *
from nsiqcppstyle_rulehelper import *
from nsiqcppstyle_reporter import *
from nsiqcppstyle_rulemanager import *
no_reenterant_functions = (
'ctime',
'strtok',
'toupper',
)
def RunRule(lexer, contextStack):
"""
Use reenterant keyword.
"""
t = lexer.GetCurToken()
if t.type == "ID":
if t.value in no_reenterant_functions:
t2 = lexer.PeekNextTokenSkipWhiteSpaceAndComment()
t3 = lexer.PeekPrevTokenSkipWhiteSpaceAndComment()
if t2 is not None and t2.type == "LPAREN":
if t3 is None or t3.type != "PERIOD":
if t.value == "toupper" and nsiqcppstyle_state._nsiqcppstyle_state.GetVar(
"ignore_toupper", "false") == "true":
|
nsiqcppstyle_reporter.Error(t, __name__,
"Do not use not reentrant function(%s)." % t.value)
ruleManager.AddFunctionScopeRule(RunRule)
##########################################################################
# Unit Test
##########################################################################
class testRule(nct):
def setUpRule(self):
ruleManager.AddFunctionScopeRule(RunRule)
def test1(self):
self.Analyze("thisfile.c",
"""
void func1()
{
k = ctime()
}
""")
self.ExpectError(__name__)
def test2(self):
self.Analyze("thisfile.c",
"""
void func1() {
#define ctime() k
}
""")
self.ExpectSuccess(__name__)
def test3(self):
self.Analyze("thisfile.c",
"""
void ctime() {
}
""")
self.ExpectSuccess(__name__)
def test4(self):
self.Analyze("thisfile.c",
"""
void ctime () {
}
""")
self.ExpectSuccess(__name__)
def test5(self):
self.Analyze("thisfile.c",
"""
void func1()
{
k = help.ctime ()
}
""")
self.ExpectSuccess(__name__)
def test6(self):
self.Analyze("thisfile.c",
"""
void func1()
{
k = toupper()
}
""")
self.ExpectError(__name__)
def test7(self):
nsiqcppstyle_state._nsiqcppstyle_state.varMap["ignore_toupper"] = "true"
self.Analyze("thisfile.c",
"""
void func1()
{
k = toupper()
}
""")
self.ExpectSuccess(__name__)
| return | conditional_block |
vibrance.rs | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ip.rsh"
float vibrance = 0.f;
static const float Rf = 0.2999f;
static const float Gf = 0.587f;
static const float Bf = 0.114f;
static float S = 0.f;
static float MS = 0.f;
static float Rt = 0.f;
static float Gt = 0.f;
static float Bt = 0.f;
static float Vib = 0.f;
void vibranceKernel(const uchar4 *in, uchar4 *out) {
float R, G, B;
int r = in->r;
int g = in->g;
int b = in->b;
float red = (r-max(g, b))/256.f;
float sx = (float)(Vib/(1+exp(-red*3)));
S = sx+1;
MS = 1.0f - S;
Rt = Rf * MS;
Gt = Gf * MS;
Bt = Bf * MS;
int t = (r + g) / 2; | B = b;
float Rc = R * (Rt + S) + G * Gt + B * Bt;
float Gc = R * Rt + G * (Gt + S) + B * Bt;
float Bc = R * Rt + G * Gt + B * (Bt + S);
out->r = rsClamp(Rc, 0, 255);
out->g = rsClamp(Gc, 0, 255);
out->b = rsClamp(Bc, 0, 255);
}
void prepareVibrance() {
Vib = vibrance/100.f;
S = Vib + 1;
MS = 1.0f - S;
Rt = Rf * MS;
Gt = Gf * MS;
Bt = Bf * MS;
} | R = r;
G = g; | random_line_split |
SeatgeekSVG.tsx | import React from 'react';
export default function SeatgeekSVG() | {
return (
<svg viewBox="20 554 299 228" width="24" height="24">
<g>
<path d="M71.3,578.6c0,0,37.5-24.6,98.2-24.6s98.2,24.6,98.2,24.6l-24.6,130.4H95.8L71.3,578.6z" />
<path d="M71.3,737.8c0,0,38.2,17.5,98.2,17.5s98.2-17.5,98.2-17.5v27.8c0,0-38.9,16.4-98.2,16.4 s-98.2-16.4-98.2-16.4V737.8z" />
<path d="M69.1,719.8v-46.4c0-7.5-6.1-13.6-13.6-13.6H20v24.6h22.9v35.5H69.1z" />
<path d="M269.9,719.8v-46.4c0-7.5,6.1-13.6,13.6-13.6H319v24.6H296v35.5H269.9z" />
</g>
</svg>
);
} | identifier_body | |
SeatgeekSVG.tsx | import React from 'react';
export default function | () {
return (
<svg viewBox="20 554 299 228" width="24" height="24">
<g>
<path d="M71.3,578.6c0,0,37.5-24.6,98.2-24.6s98.2,24.6,98.2,24.6l-24.6,130.4H95.8L71.3,578.6z" />
<path d="M71.3,737.8c0,0,38.2,17.5,98.2,17.5s98.2-17.5,98.2-17.5v27.8c0,0-38.9,16.4-98.2,16.4 s-98.2-16.4-98.2-16.4V737.8z" />
<path d="M69.1,719.8v-46.4c0-7.5-6.1-13.6-13.6-13.6H20v24.6h22.9v35.5H69.1z" />
<path d="M269.9,719.8v-46.4c0-7.5,6.1-13.6,13.6-13.6H319v24.6H296v35.5H269.9z" />
</g>
</svg>
);
}
| SeatgeekSVG | identifier_name |
SeatgeekSVG.tsx | import React from 'react';
export default function SeatgeekSVG() {
return (
<svg viewBox="20 554 299 228" width="24" height="24">
<g>
<path d="M71.3,578.6c0,0,37.5-24.6,98.2-24.6s98.2,24.6,98.2,24.6l-24.6,130.4H95.8L71.3,578.6z" />
<path d="M71.3,737.8c0,0,38.2,17.5,98.2,17.5s98.2-17.5,98.2-17.5v27.8c0,0-38.9,16.4-98.2,16.4 s-98.2-16.4-98.2-16.4V737.8z" /> | <path d="M269.9,719.8v-46.4c0-7.5,6.1-13.6,13.6-13.6H319v24.6H296v35.5H269.9z" />
</g>
</svg>
);
} | <path d="M69.1,719.8v-46.4c0-7.5-6.1-13.6-13.6-13.6H20v24.6h22.9v35.5H69.1z" /> | random_line_split |
message.rs | use std::str;
use std::str::FromStr;
use std::ascii::AsciiExt;
use IterListHeader;
use Error::{ForbiddenHeader, MissingHeader};
pub trait Message {
fn get_header(&self, &str) -> Option<&Vec<Vec<u8>>>;
fn contains_header(&self, &str) -> bool;
fn get_value_header(&self, name: &str) -> Option<&[u8]> {
let value_header = self.get_header(name);
if value_header.is_none() || value_header.unwrap().len() != 1 {
return None;
}
Some(&value_header.unwrap()[0])
}
fn get_list_header(&self, name: &str) -> Option<IterListHeader> {
if let Some(values) = self.get_header(name) {
Some(IterListHeader::new(values))
} else {
None
}
}
fn content_length(&self) -> ::Result<usize> {
if self.contains_header("Transfer-Encoding") {
return Err(ForbiddenHeader);
}
let value = try!(self.get_value_header("Content-Length").ok_or(MissingHeader));
FromStr::from_str(try!(str::from_utf8(value))).map_err(From::from)
}
fn is_chunked(&self) -> bool |
}
| {
if let Some(values) = self.get_list_header("Transfer-Encoding") {
for value in values {
if value.eq_ignore_ascii_case(b"chunked") {
return true
}
}
}
false
} | identifier_body |
message.rs | use std::str;
use std::str::FromStr;
use std::ascii::AsciiExt;
use IterListHeader;
use Error::{ForbiddenHeader, MissingHeader};
pub trait Message {
fn get_header(&self, &str) -> Option<&Vec<Vec<u8>>>;
fn contains_header(&self, &str) -> bool;
fn | (&self, name: &str) -> Option<&[u8]> {
let value_header = self.get_header(name);
if value_header.is_none() || value_header.unwrap().len() != 1 {
return None;
}
Some(&value_header.unwrap()[0])
}
fn get_list_header(&self, name: &str) -> Option<IterListHeader> {
if let Some(values) = self.get_header(name) {
Some(IterListHeader::new(values))
} else {
None
}
}
fn content_length(&self) -> ::Result<usize> {
if self.contains_header("Transfer-Encoding") {
return Err(ForbiddenHeader);
}
let value = try!(self.get_value_header("Content-Length").ok_or(MissingHeader));
FromStr::from_str(try!(str::from_utf8(value))).map_err(From::from)
}
fn is_chunked(&self) -> bool {
if let Some(values) = self.get_list_header("Transfer-Encoding") {
for value in values {
if value.eq_ignore_ascii_case(b"chunked") {
return true
}
}
}
false
}
}
| get_value_header | identifier_name |
message.rs | use std::str;
use std::str::FromStr;
use std::ascii::AsciiExt;
use IterListHeader;
use Error::{ForbiddenHeader, MissingHeader};
pub trait Message {
fn get_header(&self, &str) -> Option<&Vec<Vec<u8>>>;
fn contains_header(&self, &str) -> bool;
fn get_value_header(&self, name: &str) -> Option<&[u8]> {
let value_header = self.get_header(name);
if value_header.is_none() || value_header.unwrap().len() != 1 {
return None;
}
Some(&value_header.unwrap()[0])
}
fn get_list_header(&self, name: &str) -> Option<IterListHeader> {
if let Some(values) = self.get_header(name) | else {
None
}
}
fn content_length(&self) -> ::Result<usize> {
if self.contains_header("Transfer-Encoding") {
return Err(ForbiddenHeader);
}
let value = try!(self.get_value_header("Content-Length").ok_or(MissingHeader));
FromStr::from_str(try!(str::from_utf8(value))).map_err(From::from)
}
fn is_chunked(&self) -> bool {
if let Some(values) = self.get_list_header("Transfer-Encoding") {
for value in values {
if value.eq_ignore_ascii_case(b"chunked") {
return true
}
}
}
false
}
}
| {
Some(IterListHeader::new(values))
} | conditional_block |
message.rs | use std::str;
use std::str::FromStr;
use std::ascii::AsciiExt;
use IterListHeader;
use Error::{ForbiddenHeader, MissingHeader};
pub trait Message {
fn get_header(&self, &str) -> Option<&Vec<Vec<u8>>>;
fn contains_header(&self, &str) -> bool;
fn get_value_header(&self, name: &str) -> Option<&[u8]> {
let value_header = self.get_header(name);
if value_header.is_none() || value_header.unwrap().len() != 1 {
return None;
}
Some(&value_header.unwrap()[0])
}
fn get_list_header(&self, name: &str) -> Option<IterListHeader> {
if let Some(values) = self.get_header(name) {
Some(IterListHeader::new(values))
} else {
None
}
}
fn content_length(&self) -> ::Result<usize> {
if self.contains_header("Transfer-Encoding") { | let value = try!(self.get_value_header("Content-Length").ok_or(MissingHeader));
FromStr::from_str(try!(str::from_utf8(value))).map_err(From::from)
}
fn is_chunked(&self) -> bool {
if let Some(values) = self.get_list_header("Transfer-Encoding") {
for value in values {
if value.eq_ignore_ascii_case(b"chunked") {
return true
}
}
}
false
}
} | return Err(ForbiddenHeader);
} | random_line_split |
doctest.py | """ discover and run doctests in modules and test files."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import platform
import sys
import traceback
from contextlib import contextmanager
import pytest
from _pytest._code.code import ExceptionInfo
from _pytest._code.code import ReprFileLocation
from _pytest._code.code import TerminalRepr
from _pytest.compat import safe_getattr
from _pytest.fixtures import FixtureRequest
DOCTEST_REPORT_CHOICE_NONE = "none"
DOCTEST_REPORT_CHOICE_CDIFF = "cdiff"
DOCTEST_REPORT_CHOICE_NDIFF = "ndiff"
DOCTEST_REPORT_CHOICE_UDIFF = "udiff"
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = "only_first_failure"
DOCTEST_REPORT_CHOICES = (
DOCTEST_REPORT_CHOICE_NONE,
DOCTEST_REPORT_CHOICE_CDIFF,
DOCTEST_REPORT_CHOICE_NDIFF,
DOCTEST_REPORT_CHOICE_UDIFF,
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE,
)
# Lazy definition of runner class
RUNNER_CLASS = None
def pytest_addoption(parser):
parser.addini(
"doctest_optionflags",
"option flags for doctests",
type="args",
default=["ELLIPSIS"],
)
parser.addini(
"doctest_encoding", "encoding used for doctest files", default="utf-8"
)
group = parser.getgroup("collect")
group.addoption(
"--doctest-modules",
action="store_true",
default=False,
help="run doctests in all .py modules",
dest="doctestmodules",
)
group.addoption(
"--doctest-report",
type=str.lower,
default="udiff",
help="choose another output format for diffs on doctest failure",
choices=DOCTEST_REPORT_CHOICES,
dest="doctestreport",
)
group.addoption(
"--doctest-glob",
action="append",
default=[],
metavar="pat",
help="doctests file matching pattern, default: test*.txt",
dest="doctestglob",
)
group.addoption(
"--doctest-ignore-import-errors",
action="store_true",
default=False,
help="ignore doctest ImportErrors",
dest="doctest_ignore_import_errors",
)
group.addoption(
"--doctest-continue-on-failure",
action="store_true",
default=False,
help="for a given doctest, continue to run after the first failure",
dest="doctest_continue_on_failure",
)
def pytest_collect_file(path, parent):
config = parent.config
if path.ext == ".py":
if config.option.doctestmodules and not _is_setup_py(config, path, parent):
return DoctestModule(path, parent)
elif _is_doctest(config, path, parent):
return DoctestTextfile(path, parent)
def _is_setup_py(config, path, parent):
if path.basename != "setup.py":
return False
contents = path.read()
return "setuptools" in contents or "distutils" in contents
def _is_doctest(config, path, parent):
if path.ext in (".txt", ".rst") and parent.session.isinitpath(path):
return True
globs = config.getoption("doctestglob") or ["test*.txt"]
for glob in globs:
if path.check(fnmatch=glob):
return True
return False
class ReprFailDoctest(TerminalRepr):
def __init__(self, reprlocation_lines):
# List of (reprlocation, lines) tuples
self.reprlocation_lines = reprlocation_lines
def toterminal(self, tw):
for reprlocation, lines in self.reprlocation_lines:
for line in lines:
tw.line(line)
reprlocation.toterminal(tw)
class MultipleDoctestFailures(Exception):
def | (self, failures):
super(MultipleDoctestFailures, self).__init__()
self.failures = failures
def _init_runner_class():
import doctest
class PytestDoctestRunner(doctest.DebugRunner):
"""
Runner to collect failures. Note that the out variable in this case is
a list instead of a stdout-like object
"""
def __init__(
self, checker=None, verbose=None, optionflags=0, continue_on_failure=True
):
doctest.DebugRunner.__init__(
self, checker=checker, verbose=verbose, optionflags=optionflags
)
self.continue_on_failure = continue_on_failure
def report_failure(self, out, test, example, got):
failure = doctest.DocTestFailure(test, example, got)
if self.continue_on_failure:
out.append(failure)
else:
raise failure
def report_unexpected_exception(self, out, test, example, exc_info):
failure = doctest.UnexpectedException(test, example, exc_info)
if self.continue_on_failure:
out.append(failure)
else:
raise failure
return PytestDoctestRunner
def _get_runner(checker=None, verbose=None, optionflags=0, continue_on_failure=True):
# We need this in order to do a lazy import on doctest
global RUNNER_CLASS
if RUNNER_CLASS is None:
RUNNER_CLASS = _init_runner_class()
return RUNNER_CLASS(
checker=checker,
verbose=verbose,
optionflags=optionflags,
continue_on_failure=continue_on_failure,
)
class DoctestItem(pytest.Item):
def __init__(self, name, parent, runner=None, dtest=None):
super(DoctestItem, self).__init__(name, parent)
self.runner = runner
self.dtest = dtest
self.obj = None
self.fixture_request = None
def setup(self):
if self.dtest is not None:
self.fixture_request = _setup_fixtures(self)
globs = dict(getfixture=self.fixture_request.getfixturevalue)
for name, value in self.fixture_request.getfixturevalue(
"doctest_namespace"
).items():
globs[name] = value
self.dtest.globs.update(globs)
def runtest(self):
_check_all_skipped(self.dtest)
self._disable_output_capturing_for_darwin()
failures = []
self.runner.run(self.dtest, out=failures)
if failures:
raise MultipleDoctestFailures(failures)
def _disable_output_capturing_for_darwin(self):
"""
Disable output capturing. Otherwise, stdout is lost to doctest (#985)
"""
if platform.system() != "Darwin":
return
capman = self.config.pluginmanager.getplugin("capturemanager")
if capman:
capman.suspend_global_capture(in_=True)
out, err = capman.read_global_capture()
sys.stdout.write(out)
sys.stderr.write(err)
def repr_failure(self, excinfo):
import doctest
failures = None
if excinfo.errisinstance((doctest.DocTestFailure, doctest.UnexpectedException)):
failures = [excinfo.value]
elif excinfo.errisinstance(MultipleDoctestFailures):
failures = excinfo.value.failures
if failures is not None:
reprlocation_lines = []
for failure in failures:
example = failure.example
test = failure.test
filename = test.filename
if test.lineno is None:
lineno = None
else:
lineno = test.lineno + example.lineno + 1
message = type(failure).__name__
reprlocation = ReprFileLocation(filename, lineno, message)
checker = _get_checker()
report_choice = _get_report_choice(
self.config.getoption("doctestreport")
)
if lineno is not None:
lines = failure.test.docstring.splitlines(False)
# add line numbers to the left of the error message
lines = [
"%03d %s" % (i + test.lineno + 1, x)
for (i, x) in enumerate(lines)
]
# trim docstring error lines to 10
lines = lines[max(example.lineno - 9, 0) : example.lineno + 1]
else:
lines = [
"EXAMPLE LOCATION UNKNOWN, not showing all tests of that example"
]
indent = ">>>"
for line in example.source.splitlines():
lines.append("??? %s %s" % (indent, line))
indent = "..."
if isinstance(failure, doctest.DocTestFailure):
lines += checker.output_difference(
example, failure.got, report_choice
).split("\n")
else:
inner_excinfo = ExceptionInfo(failure.exc_info)
lines += ["UNEXPECTED EXCEPTION: %s" % repr(inner_excinfo.value)]
lines += traceback.format_exception(*failure.exc_info)
reprlocation_lines.append((reprlocation, lines))
return ReprFailDoctest(reprlocation_lines)
else:
return super(DoctestItem, self).repr_failure(excinfo)
def reportinfo(self):
return self.fspath, self.dtest.lineno, "[doctest] %s" % self.name
def _get_flag_lookup():
import doctest
return dict(
DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,
DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE,
NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,
ELLIPSIS=doctest.ELLIPSIS,
IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,
COMPARISON_FLAGS=doctest.COMPARISON_FLAGS,
ALLOW_UNICODE=_get_allow_unicode_flag(),
ALLOW_BYTES=_get_allow_bytes_flag(),
)
def get_optionflags(parent):
optionflags_str = parent.config.getini("doctest_optionflags")
flag_lookup_table = _get_flag_lookup()
flag_acc = 0
for flag in optionflags_str:
flag_acc |= flag_lookup_table[flag]
return flag_acc
def _get_continue_on_failure(config):
continue_on_failure = config.getvalue("doctest_continue_on_failure")
if continue_on_failure:
# We need to turn off this if we use pdb since we should stop at
# the first failure
if config.getvalue("usepdb"):
continue_on_failure = False
return continue_on_failure
class DoctestTextfile(pytest.Module):
obj = None
def collect(self):
import doctest
# inspired by doctest.testfile; ideally we would use it directly,
# but it doesn't support passing a custom checker
encoding = self.config.getini("doctest_encoding")
text = self.fspath.read_text(encoding)
filename = str(self.fspath)
name = self.fspath.basename
globs = {"__name__": "__main__"}
optionflags = get_optionflags(self)
runner = _get_runner(
verbose=0,
optionflags=optionflags,
checker=_get_checker(),
continue_on_failure=_get_continue_on_failure(self.config),
)
_fix_spoof_python2(runner, encoding)
parser = doctest.DocTestParser()
test = parser.get_doctest(text, globs, name, filename, 0)
if test.examples:
yield DoctestItem(test.name, self, runner, test)
def _check_all_skipped(test):
"""raises pytest.skip() if all examples in the given DocTest have the SKIP
option set.
"""
import doctest
all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)
if all_skipped:
pytest.skip("all tests skipped by +SKIP option")
def _is_mocked(obj):
"""
returns if a object is possibly a mock object by checking the existence of a highly improbable attribute
"""
return (
safe_getattr(obj, "pytest_mock_example_attribute_that_shouldnt_exist", None)
is not None
)
@contextmanager
def _patch_unwrap_mock_aware():
"""
contextmanager which replaces ``inspect.unwrap`` with a version
that's aware of mock objects and doesn't recurse on them
"""
real_unwrap = getattr(inspect, "unwrap", None)
if real_unwrap is None:
yield
else:
def _mock_aware_unwrap(obj, stop=None):
if stop is None:
return real_unwrap(obj, stop=_is_mocked)
else:
return real_unwrap(obj, stop=lambda obj: _is_mocked(obj) or stop(obj))
inspect.unwrap = _mock_aware_unwrap
try:
yield
finally:
inspect.unwrap = real_unwrap
class DoctestModule(pytest.Module):
def collect(self):
import doctest
class MockAwareDocTestFinder(doctest.DocTestFinder):
"""
a hackish doctest finder that overrides stdlib internals to fix a stdlib bug
https://github.com/pytest-dev/pytest/issues/3456
https://bugs.python.org/issue25532
"""
def _find(self, tests, obj, name, module, source_lines, globs, seen):
if _is_mocked(obj):
return
with _patch_unwrap_mock_aware():
doctest.DocTestFinder._find(
self, tests, obj, name, module, source_lines, globs, seen
)
if self.fspath.basename == "conftest.py":
module = self.config.pluginmanager._importconftest(self.fspath)
else:
try:
module = self.fspath.pyimport()
except ImportError:
if self.config.getvalue("doctest_ignore_import_errors"):
pytest.skip("unable to import module %r" % self.fspath)
else:
raise
# uses internal doctest module parsing mechanism
finder = MockAwareDocTestFinder()
optionflags = get_optionflags(self)
runner = _get_runner(
verbose=0,
optionflags=optionflags,
checker=_get_checker(),
continue_on_failure=_get_continue_on_failure(self.config),
)
for test in finder.find(module, module.__name__):
if test.examples: # skip empty doctests
yield DoctestItem(test.name, self, runner, test)
def _setup_fixtures(doctest_item):
"""
Used by DoctestTextfile and DoctestItem to setup fixture information.
"""
def func():
pass
doctest_item.funcargs = {}
fm = doctest_item.session._fixturemanager
doctest_item._fixtureinfo = fm.getfixtureinfo(
node=doctest_item, func=func, cls=None, funcargs=False
)
fixture_request = FixtureRequest(doctest_item)
fixture_request._fillfixtures()
return fixture_request
def _get_checker():
"""
Returns a doctest.OutputChecker subclass that takes in account the
ALLOW_UNICODE option to ignore u'' prefixes in strings and ALLOW_BYTES
to strip b'' prefixes.
Useful when the same doctest should run in Python 2 and Python 3.
An inner class is used to avoid importing "doctest" at the module
level.
"""
if hasattr(_get_checker, "LiteralsOutputChecker"):
return _get_checker.LiteralsOutputChecker()
import doctest
import re
class LiteralsOutputChecker(doctest.OutputChecker):
"""
Copied from doctest_nose_plugin.py from the nltk project:
https://github.com/nltk/nltk
Further extended to also support byte literals.
"""
_unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE)
_bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE)
def check_output(self, want, got, optionflags):
res = doctest.OutputChecker.check_output(self, want, got, optionflags)
if res:
return True
allow_unicode = optionflags & _get_allow_unicode_flag()
allow_bytes = optionflags & _get_allow_bytes_flag()
if not allow_unicode and not allow_bytes:
return False
else: # pragma: no cover
def remove_prefixes(regex, txt):
return re.sub(regex, r"\1\2", txt)
if allow_unicode:
want = remove_prefixes(self._unicode_literal_re, want)
got = remove_prefixes(self._unicode_literal_re, got)
if allow_bytes:
want = remove_prefixes(self._bytes_literal_re, want)
got = remove_prefixes(self._bytes_literal_re, got)
res = doctest.OutputChecker.check_output(self, want, got, optionflags)
return res
_get_checker.LiteralsOutputChecker = LiteralsOutputChecker
return _get_checker.LiteralsOutputChecker()
def _get_allow_unicode_flag():
"""
Registers and returns the ALLOW_UNICODE flag.
"""
import doctest
return doctest.register_optionflag("ALLOW_UNICODE")
def _get_allow_bytes_flag():
"""
Registers and returns the ALLOW_BYTES flag.
"""
import doctest
return doctest.register_optionflag("ALLOW_BYTES")
def _get_report_choice(key):
"""
This function returns the actual `doctest` module flag value, we want to do it as late as possible to avoid
importing `doctest` and all its dependencies when parsing options, as it adds overhead and breaks tests.
"""
import doctest
return {
DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF,
DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF,
DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF,
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE,
DOCTEST_REPORT_CHOICE_NONE: 0,
}[key]
def _fix_spoof_python2(runner, encoding):
"""
Installs a "SpoofOut" into the given DebugRunner so it properly deals with unicode output. This
should patch only doctests for text files because they don't have a way to declare their
encoding. Doctests in docstrings from Python modules don't have the same problem given that
Python already decoded the strings.
This fixes the problem related in issue #2434.
"""
from _pytest.compat import _PY2
if not _PY2:
return
from doctest import _SpoofOut
class UnicodeSpoof(_SpoofOut):
def getvalue(self):
result = _SpoofOut.getvalue(self)
if encoding and isinstance(result, bytes):
result = result.decode(encoding)
return result
runner._fakeout = UnicodeSpoof()
@pytest.fixture(scope="session")
def doctest_namespace():
"""
Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.
"""
return dict()
| __init__ | identifier_name |
doctest.py | """ discover and run doctests in modules and test files."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import platform
import sys
import traceback
from contextlib import contextmanager
import pytest
from _pytest._code.code import ExceptionInfo
from _pytest._code.code import ReprFileLocation
from _pytest._code.code import TerminalRepr
from _pytest.compat import safe_getattr
from _pytest.fixtures import FixtureRequest
DOCTEST_REPORT_CHOICE_NONE = "none"
DOCTEST_REPORT_CHOICE_CDIFF = "cdiff"
DOCTEST_REPORT_CHOICE_NDIFF = "ndiff"
DOCTEST_REPORT_CHOICE_UDIFF = "udiff"
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = "only_first_failure"
DOCTEST_REPORT_CHOICES = (
DOCTEST_REPORT_CHOICE_NONE,
DOCTEST_REPORT_CHOICE_CDIFF,
DOCTEST_REPORT_CHOICE_NDIFF,
DOCTEST_REPORT_CHOICE_UDIFF,
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE,
)
# Lazy definition of runner class
RUNNER_CLASS = None
def pytest_addoption(parser):
parser.addini(
"doctest_optionflags",
"option flags for doctests",
type="args",
default=["ELLIPSIS"],
)
parser.addini(
"doctest_encoding", "encoding used for doctest files", default="utf-8"
)
group = parser.getgroup("collect")
group.addoption(
"--doctest-modules",
action="store_true",
default=False,
help="run doctests in all .py modules",
dest="doctestmodules",
)
group.addoption(
"--doctest-report",
type=str.lower,
default="udiff",
help="choose another output format for diffs on doctest failure",
choices=DOCTEST_REPORT_CHOICES,
dest="doctestreport",
)
group.addoption(
"--doctest-glob",
action="append",
default=[],
metavar="pat",
help="doctests file matching pattern, default: test*.txt",
dest="doctestglob",
)
group.addoption(
"--doctest-ignore-import-errors",
action="store_true",
default=False,
help="ignore doctest ImportErrors",
dest="doctest_ignore_import_errors",
)
group.addoption(
"--doctest-continue-on-failure",
action="store_true",
default=False,
help="for a given doctest, continue to run after the first failure",
dest="doctest_continue_on_failure",
)
def pytest_collect_file(path, parent):
config = parent.config
if path.ext == ".py":
if config.option.doctestmodules and not _is_setup_py(config, path, parent):
return DoctestModule(path, parent)
elif _is_doctest(config, path, parent):
return DoctestTextfile(path, parent)
def _is_setup_py(config, path, parent):
if path.basename != "setup.py":
return False
contents = path.read()
return "setuptools" in contents or "distutils" in contents
def _is_doctest(config, path, parent):
if path.ext in (".txt", ".rst") and parent.session.isinitpath(path):
return True
globs = config.getoption("doctestglob") or ["test*.txt"]
for glob in globs:
if path.check(fnmatch=glob):
return True
return False
class ReprFailDoctest(TerminalRepr):
def __init__(self, reprlocation_lines):
# List of (reprlocation, lines) tuples
self.reprlocation_lines = reprlocation_lines
def toterminal(self, tw):
for reprlocation, lines in self.reprlocation_lines:
for line in lines:
tw.line(line)
reprlocation.toterminal(tw)
class MultipleDoctestFailures(Exception):
def __init__(self, failures):
super(MultipleDoctestFailures, self).__init__()
self.failures = failures
def _init_runner_class():
import doctest
class PytestDoctestRunner(doctest.DebugRunner):
"""
Runner to collect failures. Note that the out variable in this case is
a list instead of a stdout-like object
"""
def __init__(
self, checker=None, verbose=None, optionflags=0, continue_on_failure=True
):
doctest.DebugRunner.__init__(
self, checker=checker, verbose=verbose, optionflags=optionflags
)
self.continue_on_failure = continue_on_failure
def report_failure(self, out, test, example, got):
failure = doctest.DocTestFailure(test, example, got)
if self.continue_on_failure:
out.append(failure)
else:
raise failure
def report_unexpected_exception(self, out, test, example, exc_info):
failure = doctest.UnexpectedException(test, example, exc_info)
if self.continue_on_failure:
out.append(failure)
else:
raise failure
return PytestDoctestRunner
def _get_runner(checker=None, verbose=None, optionflags=0, continue_on_failure=True):
# We need this in order to do a lazy import on doctest
global RUNNER_CLASS
if RUNNER_CLASS is None:
RUNNER_CLASS = _init_runner_class()
return RUNNER_CLASS(
checker=checker,
verbose=verbose,
optionflags=optionflags,
continue_on_failure=continue_on_failure,
)
class DoctestItem(pytest.Item):
def __init__(self, name, parent, runner=None, dtest=None):
super(DoctestItem, self).__init__(name, parent)
self.runner = runner
self.dtest = dtest
self.obj = None
self.fixture_request = None
def setup(self):
if self.dtest is not None:
self.fixture_request = _setup_fixtures(self)
globs = dict(getfixture=self.fixture_request.getfixturevalue)
for name, value in self.fixture_request.getfixturevalue(
"doctest_namespace"
).items():
globs[name] = value
self.dtest.globs.update(globs)
def runtest(self):
_check_all_skipped(self.dtest)
self._disable_output_capturing_for_darwin()
failures = []
self.runner.run(self.dtest, out=failures)
if failures:
raise MultipleDoctestFailures(failures)
def _disable_output_capturing_for_darwin(self):
"""
Disable output capturing. Otherwise, stdout is lost to doctest (#985)
"""
if platform.system() != "Darwin":
return
capman = self.config.pluginmanager.getplugin("capturemanager")
if capman:
capman.suspend_global_capture(in_=True)
out, err = capman.read_global_capture()
sys.stdout.write(out)
sys.stderr.write(err)
def repr_failure(self, excinfo):
import doctest
failures = None
if excinfo.errisinstance((doctest.DocTestFailure, doctest.UnexpectedException)):
failures = [excinfo.value]
elif excinfo.errisinstance(MultipleDoctestFailures):
failures = excinfo.value.failures
if failures is not None:
reprlocation_lines = []
for failure in failures:
example = failure.example
test = failure.test
filename = test.filename
if test.lineno is None:
lineno = None
else:
lineno = test.lineno + example.lineno + 1
message = type(failure).__name__
reprlocation = ReprFileLocation(filename, lineno, message)
checker = _get_checker()
report_choice = _get_report_choice(
self.config.getoption("doctestreport")
)
if lineno is not None:
lines = failure.test.docstring.splitlines(False)
# add line numbers to the left of the error message
lines = [
"%03d %s" % (i + test.lineno + 1, x)
for (i, x) in enumerate(lines)
]
# trim docstring error lines to 10
lines = lines[max(example.lineno - 9, 0) : example.lineno + 1]
else:
lines = [
"EXAMPLE LOCATION UNKNOWN, not showing all tests of that example"
]
indent = ">>>"
for line in example.source.splitlines():
lines.append("??? %s %s" % (indent, line))
indent = "..."
if isinstance(failure, doctest.DocTestFailure):
lines += checker.output_difference(
example, failure.got, report_choice
).split("\n")
else:
inner_excinfo = ExceptionInfo(failure.exc_info)
lines += ["UNEXPECTED EXCEPTION: %s" % repr(inner_excinfo.value)]
lines += traceback.format_exception(*failure.exc_info)
reprlocation_lines.append((reprlocation, lines))
return ReprFailDoctest(reprlocation_lines)
else:
return super(DoctestItem, self).repr_failure(excinfo)
def reportinfo(self):
return self.fspath, self.dtest.lineno, "[doctest] %s" % self.name
def _get_flag_lookup():
import doctest
return dict(
DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,
DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE,
NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,
ELLIPSIS=doctest.ELLIPSIS,
IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,
COMPARISON_FLAGS=doctest.COMPARISON_FLAGS,
ALLOW_UNICODE=_get_allow_unicode_flag(),
ALLOW_BYTES=_get_allow_bytes_flag(),
)
def get_optionflags(parent):
optionflags_str = parent.config.getini("doctest_optionflags")
flag_lookup_table = _get_flag_lookup()
flag_acc = 0
for flag in optionflags_str:
flag_acc |= flag_lookup_table[flag]
return flag_acc
def _get_continue_on_failure(config):
continue_on_failure = config.getvalue("doctest_continue_on_failure")
if continue_on_failure:
# We need to turn off this if we use pdb since we should stop at
# the first failure
if config.getvalue("usepdb"):
continue_on_failure = False
return continue_on_failure
class DoctestTextfile(pytest.Module):
obj = None
def collect(self):
import doctest
# inspired by doctest.testfile; ideally we would use it directly,
# but it doesn't support passing a custom checker
encoding = self.config.getini("doctest_encoding")
text = self.fspath.read_text(encoding)
filename = str(self.fspath)
name = self.fspath.basename
globs = {"__name__": "__main__"}
optionflags = get_optionflags(self)
runner = _get_runner(
verbose=0,
optionflags=optionflags,
checker=_get_checker(),
continue_on_failure=_get_continue_on_failure(self.config),
)
_fix_spoof_python2(runner, encoding)
parser = doctest.DocTestParser()
test = parser.get_doctest(text, globs, name, filename, 0)
if test.examples:
yield DoctestItem(test.name, self, runner, test)
def _check_all_skipped(test):
"""raises pytest.skip() if all examples in the given DocTest have the SKIP
option set.
"""
import doctest
all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)
if all_skipped:
pytest.skip("all tests skipped by +SKIP option")
def _is_mocked(obj):
"""
returns if a object is possibly a mock object by checking the existence of a highly improbable attribute
"""
return (
safe_getattr(obj, "pytest_mock_example_attribute_that_shouldnt_exist", None)
is not None
)
@contextmanager
def _patch_unwrap_mock_aware():
"""
contextmanager which replaces ``inspect.unwrap`` with a version
that's aware of mock objects and doesn't recurse on them
"""
real_unwrap = getattr(inspect, "unwrap", None)
if real_unwrap is None:
yield
else:
def _mock_aware_unwrap(obj, stop=None):
if stop is None:
return real_unwrap(obj, stop=_is_mocked) | return real_unwrap(obj, stop=lambda obj: _is_mocked(obj) or stop(obj))
inspect.unwrap = _mock_aware_unwrap
try:
yield
finally:
inspect.unwrap = real_unwrap
class DoctestModule(pytest.Module):
def collect(self):
import doctest
class MockAwareDocTestFinder(doctest.DocTestFinder):
"""
a hackish doctest finder that overrides stdlib internals to fix a stdlib bug
https://github.com/pytest-dev/pytest/issues/3456
https://bugs.python.org/issue25532
"""
def _find(self, tests, obj, name, module, source_lines, globs, seen):
if _is_mocked(obj):
return
with _patch_unwrap_mock_aware():
doctest.DocTestFinder._find(
self, tests, obj, name, module, source_lines, globs, seen
)
if self.fspath.basename == "conftest.py":
module = self.config.pluginmanager._importconftest(self.fspath)
else:
try:
module = self.fspath.pyimport()
except ImportError:
if self.config.getvalue("doctest_ignore_import_errors"):
pytest.skip("unable to import module %r" % self.fspath)
else:
raise
# uses internal doctest module parsing mechanism
finder = MockAwareDocTestFinder()
optionflags = get_optionflags(self)
runner = _get_runner(
verbose=0,
optionflags=optionflags,
checker=_get_checker(),
continue_on_failure=_get_continue_on_failure(self.config),
)
for test in finder.find(module, module.__name__):
if test.examples: # skip empty doctests
yield DoctestItem(test.name, self, runner, test)
def _setup_fixtures(doctest_item):
"""
Used by DoctestTextfile and DoctestItem to setup fixture information.
"""
def func():
pass
doctest_item.funcargs = {}
fm = doctest_item.session._fixturemanager
doctest_item._fixtureinfo = fm.getfixtureinfo(
node=doctest_item, func=func, cls=None, funcargs=False
)
fixture_request = FixtureRequest(doctest_item)
fixture_request._fillfixtures()
return fixture_request
def _get_checker():
"""
Returns a doctest.OutputChecker subclass that takes in account the
ALLOW_UNICODE option to ignore u'' prefixes in strings and ALLOW_BYTES
to strip b'' prefixes.
Useful when the same doctest should run in Python 2 and Python 3.
An inner class is used to avoid importing "doctest" at the module
level.
"""
if hasattr(_get_checker, "LiteralsOutputChecker"):
return _get_checker.LiteralsOutputChecker()
import doctest
import re
class LiteralsOutputChecker(doctest.OutputChecker):
"""
Copied from doctest_nose_plugin.py from the nltk project:
https://github.com/nltk/nltk
Further extended to also support byte literals.
"""
_unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE)
_bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE)
def check_output(self, want, got, optionflags):
res = doctest.OutputChecker.check_output(self, want, got, optionflags)
if res:
return True
allow_unicode = optionflags & _get_allow_unicode_flag()
allow_bytes = optionflags & _get_allow_bytes_flag()
if not allow_unicode and not allow_bytes:
return False
else: # pragma: no cover
def remove_prefixes(regex, txt):
return re.sub(regex, r"\1\2", txt)
if allow_unicode:
want = remove_prefixes(self._unicode_literal_re, want)
got = remove_prefixes(self._unicode_literal_re, got)
if allow_bytes:
want = remove_prefixes(self._bytes_literal_re, want)
got = remove_prefixes(self._bytes_literal_re, got)
res = doctest.OutputChecker.check_output(self, want, got, optionflags)
return res
_get_checker.LiteralsOutputChecker = LiteralsOutputChecker
return _get_checker.LiteralsOutputChecker()
def _get_allow_unicode_flag():
"""
Registers and returns the ALLOW_UNICODE flag.
"""
import doctest
return doctest.register_optionflag("ALLOW_UNICODE")
def _get_allow_bytes_flag():
"""
Registers and returns the ALLOW_BYTES flag.
"""
import doctest
return doctest.register_optionflag("ALLOW_BYTES")
def _get_report_choice(key):
"""
This function returns the actual `doctest` module flag value, we want to do it as late as possible to avoid
importing `doctest` and all its dependencies when parsing options, as it adds overhead and breaks tests.
"""
import doctest
return {
DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF,
DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF,
DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF,
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE,
DOCTEST_REPORT_CHOICE_NONE: 0,
}[key]
def _fix_spoof_python2(runner, encoding):
"""
Installs a "SpoofOut" into the given DebugRunner so it properly deals with unicode output. This
should patch only doctests for text files because they don't have a way to declare their
encoding. Doctests in docstrings from Python modules don't have the same problem given that
Python already decoded the strings.
This fixes the problem related in issue #2434.
"""
from _pytest.compat import _PY2
if not _PY2:
return
from doctest import _SpoofOut
class UnicodeSpoof(_SpoofOut):
def getvalue(self):
result = _SpoofOut.getvalue(self)
if encoding and isinstance(result, bytes):
result = result.decode(encoding)
return result
runner._fakeout = UnicodeSpoof()
@pytest.fixture(scope="session")
def doctest_namespace():
"""
Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.
"""
return dict() | else: | random_line_split |
doctest.py | """ discover and run doctests in modules and test files."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import platform
import sys
import traceback
from contextlib import contextmanager
import pytest
from _pytest._code.code import ExceptionInfo
from _pytest._code.code import ReprFileLocation
from _pytest._code.code import TerminalRepr
from _pytest.compat import safe_getattr
from _pytest.fixtures import FixtureRequest
DOCTEST_REPORT_CHOICE_NONE = "none"
DOCTEST_REPORT_CHOICE_CDIFF = "cdiff"
DOCTEST_REPORT_CHOICE_NDIFF = "ndiff"
DOCTEST_REPORT_CHOICE_UDIFF = "udiff"
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = "only_first_failure"
DOCTEST_REPORT_CHOICES = (
DOCTEST_REPORT_CHOICE_NONE,
DOCTEST_REPORT_CHOICE_CDIFF,
DOCTEST_REPORT_CHOICE_NDIFF,
DOCTEST_REPORT_CHOICE_UDIFF,
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE,
)
# Lazy definition of runner class
RUNNER_CLASS = None
def pytest_addoption(parser):
parser.addini(
"doctest_optionflags",
"option flags for doctests",
type="args",
default=["ELLIPSIS"],
)
parser.addini(
"doctest_encoding", "encoding used for doctest files", default="utf-8"
)
group = parser.getgroup("collect")
group.addoption(
"--doctest-modules",
action="store_true",
default=False,
help="run doctests in all .py modules",
dest="doctestmodules",
)
group.addoption(
"--doctest-report",
type=str.lower,
default="udiff",
help="choose another output format for diffs on doctest failure",
choices=DOCTEST_REPORT_CHOICES,
dest="doctestreport",
)
group.addoption(
"--doctest-glob",
action="append",
default=[],
metavar="pat",
help="doctests file matching pattern, default: test*.txt",
dest="doctestglob",
)
group.addoption(
"--doctest-ignore-import-errors",
action="store_true",
default=False,
help="ignore doctest ImportErrors",
dest="doctest_ignore_import_errors",
)
group.addoption(
"--doctest-continue-on-failure",
action="store_true",
default=False,
help="for a given doctest, continue to run after the first failure",
dest="doctest_continue_on_failure",
)
def pytest_collect_file(path, parent):
config = parent.config
if path.ext == ".py":
if config.option.doctestmodules and not _is_setup_py(config, path, parent):
return DoctestModule(path, parent)
elif _is_doctest(config, path, parent):
return DoctestTextfile(path, parent)
def _is_setup_py(config, path, parent):
if path.basename != "setup.py":
return False
contents = path.read()
return "setuptools" in contents or "distutils" in contents
def _is_doctest(config, path, parent):
if path.ext in (".txt", ".rst") and parent.session.isinitpath(path):
return True
globs = config.getoption("doctestglob") or ["test*.txt"]
for glob in globs:
if path.check(fnmatch=glob):
return True
return False
class ReprFailDoctest(TerminalRepr):
def __init__(self, reprlocation_lines):
# List of (reprlocation, lines) tuples
self.reprlocation_lines = reprlocation_lines
def toterminal(self, tw):
for reprlocation, lines in self.reprlocation_lines:
for line in lines:
tw.line(line)
reprlocation.toterminal(tw)
class MultipleDoctestFailures(Exception):
def __init__(self, failures):
super(MultipleDoctestFailures, self).__init__()
self.failures = failures
def _init_runner_class():
import doctest
class PytestDoctestRunner(doctest.DebugRunner):
"""
Runner to collect failures. Note that the out variable in this case is
a list instead of a stdout-like object
"""
def __init__(
self, checker=None, verbose=None, optionflags=0, continue_on_failure=True
):
doctest.DebugRunner.__init__(
self, checker=checker, verbose=verbose, optionflags=optionflags
)
self.continue_on_failure = continue_on_failure
def report_failure(self, out, test, example, got):
failure = doctest.DocTestFailure(test, example, got)
if self.continue_on_failure:
out.append(failure)
else:
raise failure
def report_unexpected_exception(self, out, test, example, exc_info):
failure = doctest.UnexpectedException(test, example, exc_info)
if self.continue_on_failure:
out.append(failure)
else:
raise failure
return PytestDoctestRunner
def _get_runner(checker=None, verbose=None, optionflags=0, continue_on_failure=True):
# We need this in order to do a lazy import on doctest
global RUNNER_CLASS
if RUNNER_CLASS is None:
RUNNER_CLASS = _init_runner_class()
return RUNNER_CLASS(
checker=checker,
verbose=verbose,
optionflags=optionflags,
continue_on_failure=continue_on_failure,
)
class DoctestItem(pytest.Item):
def __init__(self, name, parent, runner=None, dtest=None):
super(DoctestItem, self).__init__(name, parent)
self.runner = runner
self.dtest = dtest
self.obj = None
self.fixture_request = None
def setup(self):
if self.dtest is not None:
self.fixture_request = _setup_fixtures(self)
globs = dict(getfixture=self.fixture_request.getfixturevalue)
for name, value in self.fixture_request.getfixturevalue(
"doctest_namespace"
).items():
globs[name] = value
self.dtest.globs.update(globs)
def runtest(self):
_check_all_skipped(self.dtest)
self._disable_output_capturing_for_darwin()
failures = []
self.runner.run(self.dtest, out=failures)
if failures:
raise MultipleDoctestFailures(failures)
def _disable_output_capturing_for_darwin(self):
"""
Disable output capturing. Otherwise, stdout is lost to doctest (#985)
"""
if platform.system() != "Darwin":
return
capman = self.config.pluginmanager.getplugin("capturemanager")
if capman:
capman.suspend_global_capture(in_=True)
out, err = capman.read_global_capture()
sys.stdout.write(out)
sys.stderr.write(err)
def repr_failure(self, excinfo):
import doctest
failures = None
if excinfo.errisinstance((doctest.DocTestFailure, doctest.UnexpectedException)):
failures = [excinfo.value]
elif excinfo.errisinstance(MultipleDoctestFailures):
failures = excinfo.value.failures
if failures is not None:
reprlocation_lines = []
for failure in failures:
example = failure.example
test = failure.test
filename = test.filename
if test.lineno is None:
lineno = None
else:
lineno = test.lineno + example.lineno + 1
message = type(failure).__name__
reprlocation = ReprFileLocation(filename, lineno, message)
checker = _get_checker()
report_choice = _get_report_choice(
self.config.getoption("doctestreport")
)
if lineno is not None:
lines = failure.test.docstring.splitlines(False)
# add line numbers to the left of the error message
lines = [
"%03d %s" % (i + test.lineno + 1, x)
for (i, x) in enumerate(lines)
]
# trim docstring error lines to 10
lines = lines[max(example.lineno - 9, 0) : example.lineno + 1]
else:
lines = [
"EXAMPLE LOCATION UNKNOWN, not showing all tests of that example"
]
indent = ">>>"
for line in example.source.splitlines():
lines.append("??? %s %s" % (indent, line))
indent = "..."
if isinstance(failure, doctest.DocTestFailure):
lines += checker.output_difference(
example, failure.got, report_choice
).split("\n")
else:
inner_excinfo = ExceptionInfo(failure.exc_info)
lines += ["UNEXPECTED EXCEPTION: %s" % repr(inner_excinfo.value)]
lines += traceback.format_exception(*failure.exc_info)
reprlocation_lines.append((reprlocation, lines))
return ReprFailDoctest(reprlocation_lines)
else:
return super(DoctestItem, self).repr_failure(excinfo)
def reportinfo(self):
return self.fspath, self.dtest.lineno, "[doctest] %s" % self.name
def _get_flag_lookup():
import doctest
return dict(
DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,
DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE,
NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,
ELLIPSIS=doctest.ELLIPSIS,
IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,
COMPARISON_FLAGS=doctest.COMPARISON_FLAGS,
ALLOW_UNICODE=_get_allow_unicode_flag(),
ALLOW_BYTES=_get_allow_bytes_flag(),
)
def get_optionflags(parent):
optionflags_str = parent.config.getini("doctest_optionflags")
flag_lookup_table = _get_flag_lookup()
flag_acc = 0
for flag in optionflags_str:
flag_acc |= flag_lookup_table[flag]
return flag_acc
def _get_continue_on_failure(config):
continue_on_failure = config.getvalue("doctest_continue_on_failure")
if continue_on_failure:
# We need to turn off this if we use pdb since we should stop at
# the first failure
if config.getvalue("usepdb"):
continue_on_failure = False
return continue_on_failure
class DoctestTextfile(pytest.Module):
obj = None
def collect(self):
import doctest
# inspired by doctest.testfile; ideally we would use it directly,
# but it doesn't support passing a custom checker
encoding = self.config.getini("doctest_encoding")
text = self.fspath.read_text(encoding)
filename = str(self.fspath)
name = self.fspath.basename
globs = {"__name__": "__main__"}
optionflags = get_optionflags(self)
runner = _get_runner(
verbose=0,
optionflags=optionflags,
checker=_get_checker(),
continue_on_failure=_get_continue_on_failure(self.config),
)
_fix_spoof_python2(runner, encoding)
parser = doctest.DocTestParser()
test = parser.get_doctest(text, globs, name, filename, 0)
if test.examples:
yield DoctestItem(test.name, self, runner, test)
def _check_all_skipped(test):
"""raises pytest.skip() if all examples in the given DocTest have the SKIP
option set.
"""
import doctest
all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)
if all_skipped:
pytest.skip("all tests skipped by +SKIP option")
def _is_mocked(obj):
"""
returns if a object is possibly a mock object by checking the existence of a highly improbable attribute
"""
return (
safe_getattr(obj, "pytest_mock_example_attribute_that_shouldnt_exist", None)
is not None
)
@contextmanager
def _patch_unwrap_mock_aware():
"""
contextmanager which replaces ``inspect.unwrap`` with a version
that's aware of mock objects and doesn't recurse on them
"""
real_unwrap = getattr(inspect, "unwrap", None)
if real_unwrap is None:
yield
else:
def _mock_aware_unwrap(obj, stop=None):
if stop is None:
return real_unwrap(obj, stop=_is_mocked)
else:
return real_unwrap(obj, stop=lambda obj: _is_mocked(obj) or stop(obj))
inspect.unwrap = _mock_aware_unwrap
try:
yield
finally:
inspect.unwrap = real_unwrap
class DoctestModule(pytest.Module):
def collect(self):
import doctest
class MockAwareDocTestFinder(doctest.DocTestFinder):
"""
a hackish doctest finder that overrides stdlib internals to fix a stdlib bug
https://github.com/pytest-dev/pytest/issues/3456
https://bugs.python.org/issue25532
"""
def _find(self, tests, obj, name, module, source_lines, globs, seen):
if _is_mocked(obj):
return
with _patch_unwrap_mock_aware():
doctest.DocTestFinder._find(
self, tests, obj, name, module, source_lines, globs, seen
)
if self.fspath.basename == "conftest.py":
module = self.config.pluginmanager._importconftest(self.fspath)
else:
try:
module = self.fspath.pyimport()
except ImportError:
if self.config.getvalue("doctest_ignore_import_errors"):
pytest.skip("unable to import module %r" % self.fspath)
else:
|
# uses internal doctest module parsing mechanism
finder = MockAwareDocTestFinder()
optionflags = get_optionflags(self)
runner = _get_runner(
verbose=0,
optionflags=optionflags,
checker=_get_checker(),
continue_on_failure=_get_continue_on_failure(self.config),
)
for test in finder.find(module, module.__name__):
if test.examples: # skip empty doctests
yield DoctestItem(test.name, self, runner, test)
def _setup_fixtures(doctest_item):
"""
Used by DoctestTextfile and DoctestItem to setup fixture information.
"""
def func():
pass
doctest_item.funcargs = {}
fm = doctest_item.session._fixturemanager
doctest_item._fixtureinfo = fm.getfixtureinfo(
node=doctest_item, func=func, cls=None, funcargs=False
)
fixture_request = FixtureRequest(doctest_item)
fixture_request._fillfixtures()
return fixture_request
def _get_checker():
"""
Returns a doctest.OutputChecker subclass that takes in account the
ALLOW_UNICODE option to ignore u'' prefixes in strings and ALLOW_BYTES
to strip b'' prefixes.
Useful when the same doctest should run in Python 2 and Python 3.
An inner class is used to avoid importing "doctest" at the module
level.
"""
if hasattr(_get_checker, "LiteralsOutputChecker"):
return _get_checker.LiteralsOutputChecker()
import doctest
import re
class LiteralsOutputChecker(doctest.OutputChecker):
"""
Copied from doctest_nose_plugin.py from the nltk project:
https://github.com/nltk/nltk
Further extended to also support byte literals.
"""
_unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE)
_bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE)
def check_output(self, want, got, optionflags):
res = doctest.OutputChecker.check_output(self, want, got, optionflags)
if res:
return True
allow_unicode = optionflags & _get_allow_unicode_flag()
allow_bytes = optionflags & _get_allow_bytes_flag()
if not allow_unicode and not allow_bytes:
return False
else: # pragma: no cover
def remove_prefixes(regex, txt):
return re.sub(regex, r"\1\2", txt)
if allow_unicode:
want = remove_prefixes(self._unicode_literal_re, want)
got = remove_prefixes(self._unicode_literal_re, got)
if allow_bytes:
want = remove_prefixes(self._bytes_literal_re, want)
got = remove_prefixes(self._bytes_literal_re, got)
res = doctest.OutputChecker.check_output(self, want, got, optionflags)
return res
_get_checker.LiteralsOutputChecker = LiteralsOutputChecker
return _get_checker.LiteralsOutputChecker()
def _get_allow_unicode_flag():
"""
Registers and returns the ALLOW_UNICODE flag.
"""
import doctest
return doctest.register_optionflag("ALLOW_UNICODE")
def _get_allow_bytes_flag():
"""
Registers and returns the ALLOW_BYTES flag.
"""
import doctest
return doctest.register_optionflag("ALLOW_BYTES")
def _get_report_choice(key):
"""
This function returns the actual `doctest` module flag value, we want to do it as late as possible to avoid
importing `doctest` and all its dependencies when parsing options, as it adds overhead and breaks tests.
"""
import doctest
return {
DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF,
DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF,
DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF,
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE,
DOCTEST_REPORT_CHOICE_NONE: 0,
}[key]
def _fix_spoof_python2(runner, encoding):
"""
Installs a "SpoofOut" into the given DebugRunner so it properly deals with unicode output. This
should patch only doctests for text files because they don't have a way to declare their
encoding. Doctests in docstrings from Python modules don't have the same problem given that
Python already decoded the strings.
This fixes the problem related in issue #2434.
"""
from _pytest.compat import _PY2
if not _PY2:
return
from doctest import _SpoofOut
class UnicodeSpoof(_SpoofOut):
def getvalue(self):
result = _SpoofOut.getvalue(self)
if encoding and isinstance(result, bytes):
result = result.decode(encoding)
return result
runner._fakeout = UnicodeSpoof()
@pytest.fixture(scope="session")
def doctest_namespace():
"""
Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.
"""
return dict()
| raise | conditional_block |
doctest.py | """ discover and run doctests in modules and test files."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import platform
import sys
import traceback
from contextlib import contextmanager
import pytest
from _pytest._code.code import ExceptionInfo
from _pytest._code.code import ReprFileLocation
from _pytest._code.code import TerminalRepr
from _pytest.compat import safe_getattr
from _pytest.fixtures import FixtureRequest
DOCTEST_REPORT_CHOICE_NONE = "none"
DOCTEST_REPORT_CHOICE_CDIFF = "cdiff"
DOCTEST_REPORT_CHOICE_NDIFF = "ndiff"
DOCTEST_REPORT_CHOICE_UDIFF = "udiff"
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = "only_first_failure"
DOCTEST_REPORT_CHOICES = (
DOCTEST_REPORT_CHOICE_NONE,
DOCTEST_REPORT_CHOICE_CDIFF,
DOCTEST_REPORT_CHOICE_NDIFF,
DOCTEST_REPORT_CHOICE_UDIFF,
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE,
)
# Lazy definition of runner class
RUNNER_CLASS = None
def pytest_addoption(parser):
parser.addini(
"doctest_optionflags",
"option flags for doctests",
type="args",
default=["ELLIPSIS"],
)
parser.addini(
"doctest_encoding", "encoding used for doctest files", default="utf-8"
)
group = parser.getgroup("collect")
group.addoption(
"--doctest-modules",
action="store_true",
default=False,
help="run doctests in all .py modules",
dest="doctestmodules",
)
group.addoption(
"--doctest-report",
type=str.lower,
default="udiff",
help="choose another output format for diffs on doctest failure",
choices=DOCTEST_REPORT_CHOICES,
dest="doctestreport",
)
group.addoption(
"--doctest-glob",
action="append",
default=[],
metavar="pat",
help="doctests file matching pattern, default: test*.txt",
dest="doctestglob",
)
group.addoption(
"--doctest-ignore-import-errors",
action="store_true",
default=False,
help="ignore doctest ImportErrors",
dest="doctest_ignore_import_errors",
)
group.addoption(
"--doctest-continue-on-failure",
action="store_true",
default=False,
help="for a given doctest, continue to run after the first failure",
dest="doctest_continue_on_failure",
)
def pytest_collect_file(path, parent):
config = parent.config
if path.ext == ".py":
if config.option.doctestmodules and not _is_setup_py(config, path, parent):
return DoctestModule(path, parent)
elif _is_doctest(config, path, parent):
return DoctestTextfile(path, parent)
def _is_setup_py(config, path, parent):
if path.basename != "setup.py":
return False
contents = path.read()
return "setuptools" in contents or "distutils" in contents
def _is_doctest(config, path, parent):
if path.ext in (".txt", ".rst") and parent.session.isinitpath(path):
return True
globs = config.getoption("doctestglob") or ["test*.txt"]
for glob in globs:
if path.check(fnmatch=glob):
return True
return False
class ReprFailDoctest(TerminalRepr):
def __init__(self, reprlocation_lines):
# List of (reprlocation, lines) tuples
self.reprlocation_lines = reprlocation_lines
def toterminal(self, tw):
for reprlocation, lines in self.reprlocation_lines:
for line in lines:
tw.line(line)
reprlocation.toterminal(tw)
class MultipleDoctestFailures(Exception):
def __init__(self, failures):
super(MultipleDoctestFailures, self).__init__()
self.failures = failures
def _init_runner_class():
import doctest
class PytestDoctestRunner(doctest.DebugRunner):
"""
Runner to collect failures. Note that the out variable in this case is
a list instead of a stdout-like object
"""
def __init__(
self, checker=None, verbose=None, optionflags=0, continue_on_failure=True
):
doctest.DebugRunner.__init__(
self, checker=checker, verbose=verbose, optionflags=optionflags
)
self.continue_on_failure = continue_on_failure
def report_failure(self, out, test, example, got):
failure = doctest.DocTestFailure(test, example, got)
if self.continue_on_failure:
out.append(failure)
else:
raise failure
def report_unexpected_exception(self, out, test, example, exc_info):
failure = doctest.UnexpectedException(test, example, exc_info)
if self.continue_on_failure:
out.append(failure)
else:
raise failure
return PytestDoctestRunner
def _get_runner(checker=None, verbose=None, optionflags=0, continue_on_failure=True):
# We need this in order to do a lazy import on doctest
global RUNNER_CLASS
if RUNNER_CLASS is None:
RUNNER_CLASS = _init_runner_class()
return RUNNER_CLASS(
checker=checker,
verbose=verbose,
optionflags=optionflags,
continue_on_failure=continue_on_failure,
)
class DoctestItem(pytest.Item):
def __init__(self, name, parent, runner=None, dtest=None):
super(DoctestItem, self).__init__(name, parent)
self.runner = runner
self.dtest = dtest
self.obj = None
self.fixture_request = None
def setup(self):
if self.dtest is not None:
self.fixture_request = _setup_fixtures(self)
globs = dict(getfixture=self.fixture_request.getfixturevalue)
for name, value in self.fixture_request.getfixturevalue(
"doctest_namespace"
).items():
globs[name] = value
self.dtest.globs.update(globs)
def runtest(self):
_check_all_skipped(self.dtest)
self._disable_output_capturing_for_darwin()
failures = []
self.runner.run(self.dtest, out=failures)
if failures:
raise MultipleDoctestFailures(failures)
def _disable_output_capturing_for_darwin(self):
"""
Disable output capturing. Otherwise, stdout is lost to doctest (#985)
"""
if platform.system() != "Darwin":
return
capman = self.config.pluginmanager.getplugin("capturemanager")
if capman:
capman.suspend_global_capture(in_=True)
out, err = capman.read_global_capture()
sys.stdout.write(out)
sys.stderr.write(err)
def repr_failure(self, excinfo):
import doctest
failures = None
if excinfo.errisinstance((doctest.DocTestFailure, doctest.UnexpectedException)):
failures = [excinfo.value]
elif excinfo.errisinstance(MultipleDoctestFailures):
failures = excinfo.value.failures
if failures is not None:
reprlocation_lines = []
for failure in failures:
example = failure.example
test = failure.test
filename = test.filename
if test.lineno is None:
lineno = None
else:
lineno = test.lineno + example.lineno + 1
message = type(failure).__name__
reprlocation = ReprFileLocation(filename, lineno, message)
checker = _get_checker()
report_choice = _get_report_choice(
self.config.getoption("doctestreport")
)
if lineno is not None:
lines = failure.test.docstring.splitlines(False)
# add line numbers to the left of the error message
lines = [
"%03d %s" % (i + test.lineno + 1, x)
for (i, x) in enumerate(lines)
]
# trim docstring error lines to 10
lines = lines[max(example.lineno - 9, 0) : example.lineno + 1]
else:
lines = [
"EXAMPLE LOCATION UNKNOWN, not showing all tests of that example"
]
indent = ">>>"
for line in example.source.splitlines():
lines.append("??? %s %s" % (indent, line))
indent = "..."
if isinstance(failure, doctest.DocTestFailure):
lines += checker.output_difference(
example, failure.got, report_choice
).split("\n")
else:
inner_excinfo = ExceptionInfo(failure.exc_info)
lines += ["UNEXPECTED EXCEPTION: %s" % repr(inner_excinfo.value)]
lines += traceback.format_exception(*failure.exc_info)
reprlocation_lines.append((reprlocation, lines))
return ReprFailDoctest(reprlocation_lines)
else:
return super(DoctestItem, self).repr_failure(excinfo)
def reportinfo(self):
return self.fspath, self.dtest.lineno, "[doctest] %s" % self.name
def _get_flag_lookup():
import doctest
return dict(
DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,
DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE,
NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,
ELLIPSIS=doctest.ELLIPSIS,
IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,
COMPARISON_FLAGS=doctest.COMPARISON_FLAGS,
ALLOW_UNICODE=_get_allow_unicode_flag(),
ALLOW_BYTES=_get_allow_bytes_flag(),
)
def get_optionflags(parent):
|
def _get_continue_on_failure(config):
continue_on_failure = config.getvalue("doctest_continue_on_failure")
if continue_on_failure:
# We need to turn off this if we use pdb since we should stop at
# the first failure
if config.getvalue("usepdb"):
continue_on_failure = False
return continue_on_failure
class DoctestTextfile(pytest.Module):
obj = None
def collect(self):
import doctest
# inspired by doctest.testfile; ideally we would use it directly,
# but it doesn't support passing a custom checker
encoding = self.config.getini("doctest_encoding")
text = self.fspath.read_text(encoding)
filename = str(self.fspath)
name = self.fspath.basename
globs = {"__name__": "__main__"}
optionflags = get_optionflags(self)
runner = _get_runner(
verbose=0,
optionflags=optionflags,
checker=_get_checker(),
continue_on_failure=_get_continue_on_failure(self.config),
)
_fix_spoof_python2(runner, encoding)
parser = doctest.DocTestParser()
test = parser.get_doctest(text, globs, name, filename, 0)
if test.examples:
yield DoctestItem(test.name, self, runner, test)
def _check_all_skipped(test):
"""raises pytest.skip() if all examples in the given DocTest have the SKIP
option set.
"""
import doctest
all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)
if all_skipped:
pytest.skip("all tests skipped by +SKIP option")
def _is_mocked(obj):
"""
returns if a object is possibly a mock object by checking the existence of a highly improbable attribute
"""
return (
safe_getattr(obj, "pytest_mock_example_attribute_that_shouldnt_exist", None)
is not None
)
@contextmanager
def _patch_unwrap_mock_aware():
"""
contextmanager which replaces ``inspect.unwrap`` with a version
that's aware of mock objects and doesn't recurse on them
"""
real_unwrap = getattr(inspect, "unwrap", None)
if real_unwrap is None:
yield
else:
def _mock_aware_unwrap(obj, stop=None):
if stop is None:
return real_unwrap(obj, stop=_is_mocked)
else:
return real_unwrap(obj, stop=lambda obj: _is_mocked(obj) or stop(obj))
inspect.unwrap = _mock_aware_unwrap
try:
yield
finally:
inspect.unwrap = real_unwrap
class DoctestModule(pytest.Module):
def collect(self):
import doctest
class MockAwareDocTestFinder(doctest.DocTestFinder):
"""
a hackish doctest finder that overrides stdlib internals to fix a stdlib bug
https://github.com/pytest-dev/pytest/issues/3456
https://bugs.python.org/issue25532
"""
def _find(self, tests, obj, name, module, source_lines, globs, seen):
if _is_mocked(obj):
return
with _patch_unwrap_mock_aware():
doctest.DocTestFinder._find(
self, tests, obj, name, module, source_lines, globs, seen
)
if self.fspath.basename == "conftest.py":
module = self.config.pluginmanager._importconftest(self.fspath)
else:
try:
module = self.fspath.pyimport()
except ImportError:
if self.config.getvalue("doctest_ignore_import_errors"):
pytest.skip("unable to import module %r" % self.fspath)
else:
raise
# uses internal doctest module parsing mechanism
finder = MockAwareDocTestFinder()
optionflags = get_optionflags(self)
runner = _get_runner(
verbose=0,
optionflags=optionflags,
checker=_get_checker(),
continue_on_failure=_get_continue_on_failure(self.config),
)
for test in finder.find(module, module.__name__):
if test.examples: # skip empty doctests
yield DoctestItem(test.name, self, runner, test)
def _setup_fixtures(doctest_item):
"""
Used by DoctestTextfile and DoctestItem to setup fixture information.
"""
def func():
pass
doctest_item.funcargs = {}
fm = doctest_item.session._fixturemanager
doctest_item._fixtureinfo = fm.getfixtureinfo(
node=doctest_item, func=func, cls=None, funcargs=False
)
fixture_request = FixtureRequest(doctest_item)
fixture_request._fillfixtures()
return fixture_request
def _get_checker():
"""
Returns a doctest.OutputChecker subclass that takes in account the
ALLOW_UNICODE option to ignore u'' prefixes in strings and ALLOW_BYTES
to strip b'' prefixes.
Useful when the same doctest should run in Python 2 and Python 3.
An inner class is used to avoid importing "doctest" at the module
level.
"""
if hasattr(_get_checker, "LiteralsOutputChecker"):
return _get_checker.LiteralsOutputChecker()
import doctest
import re
class LiteralsOutputChecker(doctest.OutputChecker):
"""
Copied from doctest_nose_plugin.py from the nltk project:
https://github.com/nltk/nltk
Further extended to also support byte literals.
"""
_unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE)
_bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE)
def check_output(self, want, got, optionflags):
res = doctest.OutputChecker.check_output(self, want, got, optionflags)
if res:
return True
allow_unicode = optionflags & _get_allow_unicode_flag()
allow_bytes = optionflags & _get_allow_bytes_flag()
if not allow_unicode and not allow_bytes:
return False
else: # pragma: no cover
def remove_prefixes(regex, txt):
return re.sub(regex, r"\1\2", txt)
if allow_unicode:
want = remove_prefixes(self._unicode_literal_re, want)
got = remove_prefixes(self._unicode_literal_re, got)
if allow_bytes:
want = remove_prefixes(self._bytes_literal_re, want)
got = remove_prefixes(self._bytes_literal_re, got)
res = doctest.OutputChecker.check_output(self, want, got, optionflags)
return res
_get_checker.LiteralsOutputChecker = LiteralsOutputChecker
return _get_checker.LiteralsOutputChecker()
def _get_allow_unicode_flag():
"""
Registers and returns the ALLOW_UNICODE flag.
"""
import doctest
return doctest.register_optionflag("ALLOW_UNICODE")
def _get_allow_bytes_flag():
"""
Registers and returns the ALLOW_BYTES flag.
"""
import doctest
return doctest.register_optionflag("ALLOW_BYTES")
def _get_report_choice(key):
"""
This function returns the actual `doctest` module flag value, we want to do it as late as possible to avoid
importing `doctest` and all its dependencies when parsing options, as it adds overhead and breaks tests.
"""
import doctest
return {
DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF,
DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF,
DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF,
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE,
DOCTEST_REPORT_CHOICE_NONE: 0,
}[key]
def _fix_spoof_python2(runner, encoding):
"""
Installs a "SpoofOut" into the given DebugRunner so it properly deals with unicode output. This
should patch only doctests for text files because they don't have a way to declare their
encoding. Doctests in docstrings from Python modules don't have the same problem given that
Python already decoded the strings.
This fixes the problem related in issue #2434.
"""
from _pytest.compat import _PY2
if not _PY2:
return
from doctest import _SpoofOut
class UnicodeSpoof(_SpoofOut):
def getvalue(self):
result = _SpoofOut.getvalue(self)
if encoding and isinstance(result, bytes):
result = result.decode(encoding)
return result
runner._fakeout = UnicodeSpoof()
@pytest.fixture(scope="session")
def doctest_namespace():
"""
Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.
"""
return dict()
| optionflags_str = parent.config.getini("doctest_optionflags")
flag_lookup_table = _get_flag_lookup()
flag_acc = 0
for flag in optionflags_str:
flag_acc |= flag_lookup_table[flag]
return flag_acc | identifier_body |
lt.js | /*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'image2', 'lt', { | captionPlaceholder: 'Caption', // MISSING
infoTab: 'Vaizdo informacija',
lockRatio: 'Išlaikyti proporciją',
menu: 'Vaizdo savybės',
pathName: 'image', // MISSING
pathNameCaption: 'caption', // MISSING
resetSize: 'Atstatyti dydį',
resizer: 'Click and drag to resize', // MISSING
title: 'Vaizdo savybės',
uploadTab: 'Siųsti',
urlMissing: 'Paveiksliuko nuorodos nėra.'
} ); | alt: 'Alternatyvus Tekstas',
btnUpload: 'Siųsti į serverį',
captioned: 'Captioned image', // MISSING | random_line_split |
pytiger2c.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script para ejecutar PyTiger2C desde la linea de comandos.
"""
import os
import sys
import optparse
import subprocess
# Add the directory containing the packages in the source distribution to the path.
# This should be removed when Tiger2C is installed.
PACKAGES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'packages'))
sys.path.insert(0, PACKAGES_DIR)
from pytiger2c import __version__, __authors__, tiger2c, tiger2dot
from pytiger2c.errors import PyTiger2CError
EXIT_SUCCESS, EXIT_FAILURE = 0, 1
def | (argv):
"""
Reconoce las opciones especificadas como argumentos.
@type argv: C{list}
@param argv: Lista de argumentos del programa.
@rtype: C{tuple}
@return: Retorna una tupla donde el primer elemento es una estructura
que almacena la información acerca de las opciones especificadas
y el segundo elemento es una lista con el resto de los argumentos.
"""
usage = '%prog <tiger-file> --output <output-file> [--output-type <output-type>]'
version = '%%prog (PyTiger2C) %s\n' % __version__
authors = '\n'.join(['Copyright (C) 2009, 2010 %s' % a for a in __authors__])
desc = 'Translates a Tiger program received as argument into a C program ' \
'and then compiles the C program into an executable using a C compiler. ' \
'This behavior can be modified using the --output-type option.'
parser = optparse.OptionParser(usage=usage,
version=version + authors,
description=desc,
prog=os.path.basename(argv[0]))
parser.add_option('-o', '--output', action='store', dest='output', metavar='FILE',
help='write the output to FILE')
parser.add_option('-t', '--output-type', action='store', dest='output_type', metavar='TYPE',
type='choice', choices=('ast', 'c', 'binary'),
help="output type: 'ast', 'c' or 'binary' (default '%default')")
parser.set_default('output_type', 'binary')
options, args = parser.parse_args(args=argv[1:])
optparse.check_choice(parser.get_option('--output-type'), '--output-type', options.output_type)
if not options.output:
parser.error('missing required --output option')
elif len(args) != 1:
parser.error('invalid number of arguments')
else:
return options, args
def main(argv):
"""
Función principal del script.
@type argv: C{list}
@param argv: Lista de argumentos del programa.
@rtype: C{int}
@return: Retorna 0 si no ocurrió ningún error durante la ejecución
del programa y 1 en el caso contrario.
"""
options, args = _parse_args(argv)
tiger_filename = os.path.abspath(args[0])
output_filename = os.path.abspath(options.output)
try:
if options.output_type == 'ast':
tiger2dot(tiger_filename, output_filename)
elif options.output_type == 'c':
tiger2c(tiger_filename, output_filename)
# Translation completed. Beautify the code using GNU Indent.
INDENT_CMD = ['indent', '-gnu', '-l100', '-o', output_filename, output_filename]
if subprocess.call(INDENT_CMD) != EXIT_SUCCESS:
# Leave the c file for debugging.
sys.exit(EXIT_FAILURE)
elif options.output_type == 'binary':
basename = os.path.basename(tiger_filename)
index = basename.rfind('.')
c_filename = '%s.c' % (basename[:index] if index > 0 else basename)
c_filename = os.path.join(os.path.dirname(tiger_filename), c_filename)
tiger2c(tiger_filename, c_filename)
# Translation completed. Compile using GCC.
GCC_CMD = ['gcc', c_filename, '-o', output_filename, '-std=c99', '-lgc']
if subprocess.call(GCC_CMD) != EXIT_SUCCESS:
# Leave the temporal c file for debugging.
sys.exit(EXIT_FAILURE)
os.unlink(c_filename)
except PyTiger2CError, error:
print >> sys.stderr, error
sys.exit(EXIT_FAILURE)
else:
sys.exit(EXIT_SUCCESS)
if __name__ == '__main__':
main(sys.argv) | _parse_args | identifier_name |
pytiger2c.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script para ejecutar PyTiger2C desde la linea de comandos.
"""
import os
import sys
import optparse
import subprocess
# Add the directory containing the packages in the source distribution to the path.
# This should be removed when Tiger2C is installed.
PACKAGES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'packages'))
sys.path.insert(0, PACKAGES_DIR) | EXIT_SUCCESS, EXIT_FAILURE = 0, 1
def _parse_args(argv):
"""
Reconoce las opciones especificadas como argumentos.
@type argv: C{list}
@param argv: Lista de argumentos del programa.
@rtype: C{tuple}
@return: Retorna una tupla donde el primer elemento es una estructura
que almacena la información acerca de las opciones especificadas
y el segundo elemento es una lista con el resto de los argumentos.
"""
usage = '%prog <tiger-file> --output <output-file> [--output-type <output-type>]'
version = '%%prog (PyTiger2C) %s\n' % __version__
authors = '\n'.join(['Copyright (C) 2009, 2010 %s' % a for a in __authors__])
desc = 'Translates a Tiger program received as argument into a C program ' \
'and then compiles the C program into an executable using a C compiler. ' \
'This behavior can be modified using the --output-type option.'
parser = optparse.OptionParser(usage=usage,
version=version + authors,
description=desc,
prog=os.path.basename(argv[0]))
parser.add_option('-o', '--output', action='store', dest='output', metavar='FILE',
help='write the output to FILE')
parser.add_option('-t', '--output-type', action='store', dest='output_type', metavar='TYPE',
type='choice', choices=('ast', 'c', 'binary'),
help="output type: 'ast', 'c' or 'binary' (default '%default')")
parser.set_default('output_type', 'binary')
options, args = parser.parse_args(args=argv[1:])
optparse.check_choice(parser.get_option('--output-type'), '--output-type', options.output_type)
if not options.output:
parser.error('missing required --output option')
elif len(args) != 1:
parser.error('invalid number of arguments')
else:
return options, args
def main(argv):
"""
Función principal del script.
@type argv: C{list}
@param argv: Lista de argumentos del programa.
@rtype: C{int}
@return: Retorna 0 si no ocurrió ningún error durante la ejecución
del programa y 1 en el caso contrario.
"""
options, args = _parse_args(argv)
tiger_filename = os.path.abspath(args[0])
output_filename = os.path.abspath(options.output)
try:
if options.output_type == 'ast':
tiger2dot(tiger_filename, output_filename)
elif options.output_type == 'c':
tiger2c(tiger_filename, output_filename)
# Translation completed. Beautify the code using GNU Indent.
INDENT_CMD = ['indent', '-gnu', '-l100', '-o', output_filename, output_filename]
if subprocess.call(INDENT_CMD) != EXIT_SUCCESS:
# Leave the c file for debugging.
sys.exit(EXIT_FAILURE)
elif options.output_type == 'binary':
basename = os.path.basename(tiger_filename)
index = basename.rfind('.')
c_filename = '%s.c' % (basename[:index] if index > 0 else basename)
c_filename = os.path.join(os.path.dirname(tiger_filename), c_filename)
tiger2c(tiger_filename, c_filename)
# Translation completed. Compile using GCC.
GCC_CMD = ['gcc', c_filename, '-o', output_filename, '-std=c99', '-lgc']
if subprocess.call(GCC_CMD) != EXIT_SUCCESS:
# Leave the temporal c file for debugging.
sys.exit(EXIT_FAILURE)
os.unlink(c_filename)
except PyTiger2CError, error:
print >> sys.stderr, error
sys.exit(EXIT_FAILURE)
else:
sys.exit(EXIT_SUCCESS)
if __name__ == '__main__':
main(sys.argv) |
from pytiger2c import __version__, __authors__, tiger2c, tiger2dot
from pytiger2c.errors import PyTiger2CError
| random_line_split |
pytiger2c.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script para ejecutar PyTiger2C desde la linea de comandos.
"""
import os
import sys
import optparse
import subprocess
# Add the directory containing the packages in the source distribution to the path.
# This should be removed when Tiger2C is installed.
PACKAGES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'packages'))
sys.path.insert(0, PACKAGES_DIR)
from pytiger2c import __version__, __authors__, tiger2c, tiger2dot
from pytiger2c.errors import PyTiger2CError
EXIT_SUCCESS, EXIT_FAILURE = 0, 1
def _parse_args(argv):
"""
Reconoce las opciones especificadas como argumentos.
@type argv: C{list}
@param argv: Lista de argumentos del programa.
@rtype: C{tuple}
@return: Retorna una tupla donde el primer elemento es una estructura
que almacena la información acerca de las opciones especificadas
y el segundo elemento es una lista con el resto de los argumentos.
"""
usage = '%prog <tiger-file> --output <output-file> [--output-type <output-type>]'
version = '%%prog (PyTiger2C) %s\n' % __version__
authors = '\n'.join(['Copyright (C) 2009, 2010 %s' % a for a in __authors__])
desc = 'Translates a Tiger program received as argument into a C program ' \
'and then compiles the C program into an executable using a C compiler. ' \
'This behavior can be modified using the --output-type option.'
parser = optparse.OptionParser(usage=usage,
version=version + authors,
description=desc,
prog=os.path.basename(argv[0]))
parser.add_option('-o', '--output', action='store', dest='output', metavar='FILE',
help='write the output to FILE')
parser.add_option('-t', '--output-type', action='store', dest='output_type', metavar='TYPE',
type='choice', choices=('ast', 'c', 'binary'),
help="output type: 'ast', 'c' or 'binary' (default '%default')")
parser.set_default('output_type', 'binary')
options, args = parser.parse_args(args=argv[1:])
optparse.check_choice(parser.get_option('--output-type'), '--output-type', options.output_type)
if not options.output:
p | elif len(args) != 1:
parser.error('invalid number of arguments')
else:
return options, args
def main(argv):
"""
Función principal del script.
@type argv: C{list}
@param argv: Lista de argumentos del programa.
@rtype: C{int}
@return: Retorna 0 si no ocurrió ningún error durante la ejecución
del programa y 1 en el caso contrario.
"""
options, args = _parse_args(argv)
tiger_filename = os.path.abspath(args[0])
output_filename = os.path.abspath(options.output)
try:
if options.output_type == 'ast':
tiger2dot(tiger_filename, output_filename)
elif options.output_type == 'c':
tiger2c(tiger_filename, output_filename)
# Translation completed. Beautify the code using GNU Indent.
INDENT_CMD = ['indent', '-gnu', '-l100', '-o', output_filename, output_filename]
if subprocess.call(INDENT_CMD) != EXIT_SUCCESS:
# Leave the c file for debugging.
sys.exit(EXIT_FAILURE)
elif options.output_type == 'binary':
basename = os.path.basename(tiger_filename)
index = basename.rfind('.')
c_filename = '%s.c' % (basename[:index] if index > 0 else basename)
c_filename = os.path.join(os.path.dirname(tiger_filename), c_filename)
tiger2c(tiger_filename, c_filename)
# Translation completed. Compile using GCC.
GCC_CMD = ['gcc', c_filename, '-o', output_filename, '-std=c99', '-lgc']
if subprocess.call(GCC_CMD) != EXIT_SUCCESS:
# Leave the temporal c file for debugging.
sys.exit(EXIT_FAILURE)
os.unlink(c_filename)
except PyTiger2CError, error:
print >> sys.stderr, error
sys.exit(EXIT_FAILURE)
else:
sys.exit(EXIT_SUCCESS)
if __name__ == '__main__':
main(sys.argv) | arser.error('missing required --output option')
| conditional_block |
pytiger2c.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script para ejecutar PyTiger2C desde la linea de comandos.
"""
import os
import sys
import optparse
import subprocess
# Add the directory containing the packages in the source distribution to the path.
# This should be removed when Tiger2C is installed.
PACKAGES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'packages'))
sys.path.insert(0, PACKAGES_DIR)
from pytiger2c import __version__, __authors__, tiger2c, tiger2dot
from pytiger2c.errors import PyTiger2CError
EXIT_SUCCESS, EXIT_FAILURE = 0, 1
def _parse_args(argv):
|
def main(argv):
"""
Función principal del script.
@type argv: C{list}
@param argv: Lista de argumentos del programa.
@rtype: C{int}
@return: Retorna 0 si no ocurrió ningún error durante la ejecución
del programa y 1 en el caso contrario.
"""
options, args = _parse_args(argv)
tiger_filename = os.path.abspath(args[0])
output_filename = os.path.abspath(options.output)
try:
if options.output_type == 'ast':
tiger2dot(tiger_filename, output_filename)
elif options.output_type == 'c':
tiger2c(tiger_filename, output_filename)
# Translation completed. Beautify the code using GNU Indent.
INDENT_CMD = ['indent', '-gnu', '-l100', '-o', output_filename, output_filename]
if subprocess.call(INDENT_CMD) != EXIT_SUCCESS:
# Leave the c file for debugging.
sys.exit(EXIT_FAILURE)
elif options.output_type == 'binary':
basename = os.path.basename(tiger_filename)
index = basename.rfind('.')
c_filename = '%s.c' % (basename[:index] if index > 0 else basename)
c_filename = os.path.join(os.path.dirname(tiger_filename), c_filename)
tiger2c(tiger_filename, c_filename)
# Translation completed. Compile using GCC.
GCC_CMD = ['gcc', c_filename, '-o', output_filename, '-std=c99', '-lgc']
if subprocess.call(GCC_CMD) != EXIT_SUCCESS:
# Leave the temporal c file for debugging.
sys.exit(EXIT_FAILURE)
os.unlink(c_filename)
except PyTiger2CError, error:
print >> sys.stderr, error
sys.exit(EXIT_FAILURE)
else:
sys.exit(EXIT_SUCCESS)
if __name__ == '__main__':
main(sys.argv) | """
Reconoce las opciones especificadas como argumentos.
@type argv: C{list}
@param argv: Lista de argumentos del programa.
@rtype: C{tuple}
@return: Retorna una tupla donde el primer elemento es una estructura
que almacena la información acerca de las opciones especificadas
y el segundo elemento es una lista con el resto de los argumentos.
"""
usage = '%prog <tiger-file> --output <output-file> [--output-type <output-type>]'
version = '%%prog (PyTiger2C) %s\n' % __version__
authors = '\n'.join(['Copyright (C) 2009, 2010 %s' % a for a in __authors__])
desc = 'Translates a Tiger program received as argument into a C program ' \
'and then compiles the C program into an executable using a C compiler. ' \
'This behavior can be modified using the --output-type option.'
parser = optparse.OptionParser(usage=usage,
version=version + authors,
description=desc,
prog=os.path.basename(argv[0]))
parser.add_option('-o', '--output', action='store', dest='output', metavar='FILE',
help='write the output to FILE')
parser.add_option('-t', '--output-type', action='store', dest='output_type', metavar='TYPE',
type='choice', choices=('ast', 'c', 'binary'),
help="output type: 'ast', 'c' or 'binary' (default '%default')")
parser.set_default('output_type', 'binary')
options, args = parser.parse_args(args=argv[1:])
optparse.check_choice(parser.get_option('--output-type'), '--output-type', options.output_type)
if not options.output:
parser.error('missing required --output option')
elif len(args) != 1:
parser.error('invalid number of arguments')
else:
return options, args
| identifier_body |
focusable.js | /*!
* jQuery UI Focusable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: :focusable Selector
//>>group: Core
//>>description: Selects elements which can be focused.
//>>docs: http://api.jqueryui.com/focusable-selector/
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
} ( function( $ ) {
// Selectors
$.ui.focusable = function( element, hasTabindex ) {
var map, mapName, img, focusableIfVisible, fieldset,
nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) |
if ( /^(input|select|textarea|button|object)$/.test( nodeName ) ) {
focusableIfVisible = !element.disabled;
if ( focusableIfVisible ) {
// Form controls within a disabled fieldset are disabled.
// However, controls within the fieldset's legend do not get disabled.
// Since controls generally aren't placed inside legends, we skip
// this portion of the check.
fieldset = $( element ).closest( "fieldset" )[ 0 ];
if ( fieldset ) {
focusableIfVisible = !fieldset.disabled;
}
}
} else if ( "a" === nodeName ) {
focusableIfVisible = element.href || hasTabindex;
} else {
focusableIfVisible = hasTabindex;
}
return focusableIfVisible && $( element ).is( ":visible" ) && visible( $( element ) );
};
// Support: IE 8 only
// IE 8 doesn't resolve inherit to visible/hidden for computed values
function visible( element ) {
var visibility = element.css( "visibility" );
while ( visibility === "inherit" ) {
element = element.parent();
visibility = element.css( "visibility" );
}
return visibility !== "hidden";
}
$.extend( $.expr[ ":" ], {
focusable: function( element ) {
return $.ui.focusable( element, $.attr( element, "tabindex" ) != null );
}
} );
return $.ui.focusable;
} ) );
| {
map = element.parentNode;
mapName = map.name;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap='#" + mapName + "']" );
return img.length > 0 && img.is( ":visible" );
} | conditional_block |
focusable.js | /*!
* jQuery UI Focusable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: :focusable Selector
//>>group: Core
//>>description: Selects elements which can be focused.
//>>docs: http://api.jqueryui.com/focusable-selector/
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
} ( function( $ ) {
// Selectors
$.ui.focusable = function( element, hasTabindex ) {
var map, mapName, img, focusableIfVisible, fieldset,
nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
map = element.parentNode;
mapName = map.name;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap='#" + mapName + "']" );
return img.length > 0 && img.is( ":visible" );
}
if ( /^(input|select|textarea|button|object)$/.test( nodeName ) ) {
focusableIfVisible = !element.disabled;
if ( focusableIfVisible ) {
// Form controls within a disabled fieldset are disabled.
// However, controls within the fieldset's legend do not get disabled.
// Since controls generally aren't placed inside legends, we skip
// this portion of the check.
fieldset = $( element ).closest( "fieldset" )[ 0 ];
if ( fieldset ) {
focusableIfVisible = !fieldset.disabled;
}
}
} else if ( "a" === nodeName ) {
focusableIfVisible = element.href || hasTabindex;
} else {
focusableIfVisible = hasTabindex;
}
return focusableIfVisible && $( element ).is( ":visible" ) && visible( $( element ) );
};
// Support: IE 8 only
// IE 8 doesn't resolve inherit to visible/hidden for computed values
function | ( element ) {
var visibility = element.css( "visibility" );
while ( visibility === "inherit" ) {
element = element.parent();
visibility = element.css( "visibility" );
}
return visibility !== "hidden";
}
$.extend( $.expr[ ":" ], {
focusable: function( element ) {
return $.ui.focusable( element, $.attr( element, "tabindex" ) != null );
}
} );
return $.ui.focusable;
} ) );
| visible | identifier_name |
focusable.js | /*!
* jQuery UI Focusable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: :focusable Selector
//>>group: Core
//>>description: Selects elements which can be focused.
//>>docs: http://api.jqueryui.com/focusable-selector/
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
} ( function( $ ) {
// Selectors
$.ui.focusable = function( element, hasTabindex ) {
var map, mapName, img, focusableIfVisible, fieldset,
nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
map = element.parentNode;
mapName = map.name;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap='#" + mapName + "']" );
return img.length > 0 && img.is( ":visible" );
}
if ( /^(input|select|textarea|button|object)$/.test( nodeName ) ) {
focusableIfVisible = !element.disabled;
if ( focusableIfVisible ) {
// Form controls within a disabled fieldset are disabled.
// However, controls within the fieldset's legend do not get disabled.
// Since controls generally aren't placed inside legends, we skip
// this portion of the check.
fieldset = $( element ).closest( "fieldset" )[ 0 ];
if ( fieldset ) {
focusableIfVisible = !fieldset.disabled;
}
}
} else if ( "a" === nodeName ) {
focusableIfVisible = element.href || hasTabindex;
} else {
focusableIfVisible = hasTabindex;
}
return focusableIfVisible && $( element ).is( ":visible" ) && visible( $( element ) );
};
// Support: IE 8 only
// IE 8 doesn't resolve inherit to visible/hidden for computed values
function visible( element ) |
$.extend( $.expr[ ":" ], {
focusable: function( element ) {
return $.ui.focusable( element, $.attr( element, "tabindex" ) != null );
}
} );
return $.ui.focusable;
} ) );
| {
var visibility = element.css( "visibility" );
while ( visibility === "inherit" ) {
element = element.parent();
visibility = element.css( "visibility" );
}
return visibility !== "hidden";
} | identifier_body |
focusable.js | /*!
* jQuery UI Focusable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: :focusable Selector
//>>group: Core
//>>description: Selects elements which can be focused.
//>>docs: http://api.jqueryui.com/focusable-selector/
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
} ( function( $ ) {
// Selectors
$.ui.focusable = function( element, hasTabindex ) {
var map, mapName, img, focusableIfVisible, fieldset,
nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
map = element.parentNode;
mapName = map.name;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap='#" + mapName + "']" );
return img.length > 0 && img.is( ":visible" );
}
if ( /^(input|select|textarea|button|object)$/.test( nodeName ) ) {
focusableIfVisible = !element.disabled;
if ( focusableIfVisible ) {
// Form controls within a disabled fieldset are disabled.
// However, controls within the fieldset's legend do not get disabled.
// Since controls generally aren't placed inside legends, we skip
// this portion of the check.
| fieldset = $( element ).closest( "fieldset" )[ 0 ];
if ( fieldset ) {
focusableIfVisible = !fieldset.disabled;
}
}
} else if ( "a" === nodeName ) {
focusableIfVisible = element.href || hasTabindex;
} else {
focusableIfVisible = hasTabindex;
}
return focusableIfVisible && $( element ).is( ":visible" ) && visible( $( element ) );
};
// Support: IE 8 only
// IE 8 doesn't resolve inherit to visible/hidden for computed values
function visible( element ) {
var visibility = element.css( "visibility" );
while ( visibility === "inherit" ) {
element = element.parent();
visibility = element.css( "visibility" );
}
return visibility !== "hidden";
}
$.extend( $.expr[ ":" ], {
focusable: function( element ) {
return $.ui.focusable( element, $.attr( element, "tabindex" ) != null );
}
} );
return $.ui.focusable;
} ) ); | random_line_split | |
RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery.graphql.js | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<ff40aed3600a349a81c8d336ef25c383>>
* @flow
* @lightSyntaxTransform
* @nogrep
*/
/* eslint-disable */
'use strict';
/*::
import type { ConcreteRequest, Query } from 'relay-runtime';
export type RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$variables = {|
userId: string,
|};
export type RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$data = {|
+user: ?{|
+id: string,
+name: ?string,
|},
|};
export type RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery = {|
variables: RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$variables,
response: RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$data,
|};
*/
var node/*: ConcreteRequest*/ = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "userId"
}
],
v1 = [
{
"kind": "Variable",
"name": "id",
"variableName": "userId"
}
],
v2 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
};
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery",
"selections": [
{
"alias": "user",
"args": (v1/*: any*/),
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v2/*: any*/),
(v3/*: any*/)
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery",
"selections": [
{
"alias": "user",
"args": (v1/*: any*/),
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
(v2/*: any*/),
(v3/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"cacheID": "0731919b754e27166d990aec021f2e80",
"id": null,
"metadata": {
"relayTestingSelectionTypeInfo": {
"user": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Node"
},
"user.__typename": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "String"
},
"user.id": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "ID"
},
"user.name": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "String"
}
}
},
"name": "RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery",
"operationKind": "query",
"text": "query RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery(\n $userId: ID!\n) {\n user: node(id: $userId) {\n __typename\n id\n name\n }\n}\n"
}
};
})();
if (__DEV__) |
module.exports = ((node/*: any*/)/*: Query<
RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$variables,
RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$data,
>*/);
| {
(node/*: any*/).hash = "dc18b1545e059ab74a8a0209a0c58b60";
} | conditional_block |
RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery.graphql.js | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<ff40aed3600a349a81c8d336ef25c383>>
* @flow
* @lightSyntaxTransform
* @nogrep
*/
/* eslint-disable */
'use strict';
/*::
import type { ConcreteRequest, Query } from 'relay-runtime';
export type RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$variables = {|
userId: string,
|};
export type RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$data = {|
+user: ?{|
+id: string,
+name: ?string,
|},
|};
export type RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery = {|
variables: RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$variables,
response: RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$data,
|};
*/
var node/*: ConcreteRequest*/ = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "userId"
}
],
v1 = [
{
"kind": "Variable",
"name": "id",
"variableName": "userId"
}
],
v2 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
};
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery",
"selections": [
{
"alias": "user",
"args": (v1/*: any*/),
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v2/*: any*/),
(v3/*: any*/)
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery",
"selections": [
{
"alias": "user",
"args": (v1/*: any*/),
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false, | "args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
(v2/*: any*/),
(v3/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"cacheID": "0731919b754e27166d990aec021f2e80",
"id": null,
"metadata": {
"relayTestingSelectionTypeInfo": {
"user": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Node"
},
"user.__typename": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "String"
},
"user.id": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "ID"
},
"user.name": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "String"
}
}
},
"name": "RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery",
"operationKind": "query",
"text": "query RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery(\n $userId: ID!\n) {\n user: node(id: $userId) {\n __typename\n id\n name\n }\n}\n"
}
};
})();
if (__DEV__) {
(node/*: any*/).hash = "dc18b1545e059ab74a8a0209a0c58b60";
}
module.exports = ((node/*: any*/)/*: Query<
RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$variables,
RelayMockEnvironmentWithComponentsTestWorldClassFeatureQuery$data,
>*/); | "selections": [
{
"alias": null, | random_line_split |
ExcelColumns.py | import string
def fillChars(chars):
for i in string.ascii_lowercase:
chars.append(i)
def getColumnNumber():
columnNumber=int(raw_input("Please input cell number: "))
return columnNumber
def printColumns(chars):
printBlank=True
counter=1
for c0 in chars:
for c1 in chars:
if printBlank:
start2=0
printBlank=False
else:
start2=1
for c2 in chars[start2:]:
print counter,':',
for c3 in chars[1:]:
print c0+c1+c2+c3,
counter += 1
print
raw_input("pause for a while")
def printColumns2(columnNumber):
counter=1
aColumn=1
while aColumn<=columnNumber:
if aColumn % 26 ==1:
print
print counter,':',
print getEquivalentColumn(computeColumnRecursive(aColumn,[])),
counter+=1
aColumn+=1
def computeColumn(columnNumber):
|
def computeColumn(columnNumber,column):
if columnNumber==0:
return column
print 'overloading'
base=26
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return computeColumn(columnNumber,column)
def computeColumnRecursive(columnNumber,column):
if columnNumber==0:
return column
base=26
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return computeColumnRecursive(columnNumber,column)
def getEquivalentColumn(column):
columnLetter=''
for i in column:
columnLetter+=string.ascii_uppercase[i-1]
return columnLetter
def printEquivalentColumn(column):
for i in column:
print string.ascii_uppercase[i-1],
if __name__ == '__main__':
#chars=['',]
#fillChars(chars)
#printColumns2(getColumnNumber())
printEquivalentColumn(computeColumn(getColumnNumber()))
printEquivalentColumn(computeColumn(getColumnNumber(),[]))
| base=26
column=[]
while columnNumber>0:
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return column | identifier_body |
ExcelColumns.py | import string
def fillChars(chars):
for i in string.ascii_lowercase:
chars.append(i)
def getColumnNumber():
columnNumber=int(raw_input("Please input cell number: "))
return columnNumber
def printColumns(chars):
printBlank=True
counter=1
for c0 in chars:
for c1 in chars:
if printBlank:
start2=0
printBlank=False
else:
start2=1
for c2 in chars[start2:]:
print counter,':',
for c3 in chars[1:]:
print c0+c1+c2+c3,
counter += 1
print
raw_input("pause for a while")
def printColumns2(columnNumber):
counter=1
aColumn=1
while aColumn<=columnNumber:
if aColumn % 26 ==1:
print
print counter,':',
print getEquivalentColumn(computeColumnRecursive(aColumn,[])),
counter+=1
aColumn+=1
def | (columnNumber):
base=26
column=[]
while columnNumber>0:
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return column
def computeColumn(columnNumber,column):
if columnNumber==0:
return column
print 'overloading'
base=26
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return computeColumn(columnNumber,column)
def computeColumnRecursive(columnNumber,column):
if columnNumber==0:
return column
base=26
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return computeColumnRecursive(columnNumber,column)
def getEquivalentColumn(column):
columnLetter=''
for i in column:
columnLetter+=string.ascii_uppercase[i-1]
return columnLetter
def printEquivalentColumn(column):
for i in column:
print string.ascii_uppercase[i-1],
if __name__ == '__main__':
#chars=['',]
#fillChars(chars)
#printColumns2(getColumnNumber())
printEquivalentColumn(computeColumn(getColumnNumber()))
printEquivalentColumn(computeColumn(getColumnNumber(),[]))
| computeColumn | identifier_name |
ExcelColumns.py | import string
def fillChars(chars):
for i in string.ascii_lowercase:
chars.append(i)
def getColumnNumber():
columnNumber=int(raw_input("Please input cell number: "))
return columnNumber
def printColumns(chars):
printBlank=True
counter=1
for c0 in chars:
for c1 in chars:
if printBlank:
start2=0
printBlank=False
else:
start2=1
for c2 in chars[start2:]:
print counter,':',
for c3 in chars[1:]:
print c0+c1+c2+c3,
counter += 1
print
raw_input("pause for a while")
def printColumns2(columnNumber):
counter=1
aColumn=1
while aColumn<=columnNumber:
|
def computeColumn(columnNumber):
base=26
column=[]
while columnNumber>0:
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return column
def computeColumn(columnNumber,column):
if columnNumber==0:
return column
print 'overloading'
base=26
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return computeColumn(columnNumber,column)
def computeColumnRecursive(columnNumber,column):
if columnNumber==0:
return column
base=26
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return computeColumnRecursive(columnNumber,column)
def getEquivalentColumn(column):
columnLetter=''
for i in column:
columnLetter+=string.ascii_uppercase[i-1]
return columnLetter
def printEquivalentColumn(column):
for i in column:
print string.ascii_uppercase[i-1],
if __name__ == '__main__':
#chars=['',]
#fillChars(chars)
#printColumns2(getColumnNumber())
printEquivalentColumn(computeColumn(getColumnNumber()))
printEquivalentColumn(computeColumn(getColumnNumber(),[]))
| if aColumn % 26 ==1:
print
print counter,':',
print getEquivalentColumn(computeColumnRecursive(aColumn,[])),
counter+=1
aColumn+=1 | conditional_block |
ExcelColumns.py | import string
def fillChars(chars):
for i in string.ascii_lowercase:
chars.append(i)
def getColumnNumber():
columnNumber=int(raw_input("Please input cell number: "))
return columnNumber
def printColumns(chars):
printBlank=True
counter=1
for c0 in chars:
for c1 in chars: | else:
start2=1
for c2 in chars[start2:]:
print counter,':',
for c3 in chars[1:]:
print c0+c1+c2+c3,
counter += 1
print
raw_input("pause for a while")
def printColumns2(columnNumber):
counter=1
aColumn=1
while aColumn<=columnNumber:
if aColumn % 26 ==1:
print
print counter,':',
print getEquivalentColumn(computeColumnRecursive(aColumn,[])),
counter+=1
aColumn+=1
def computeColumn(columnNumber):
base=26
column=[]
while columnNumber>0:
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return column
def computeColumn(columnNumber,column):
if columnNumber==0:
return column
print 'overloading'
base=26
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return computeColumn(columnNumber,column)
def computeColumnRecursive(columnNumber,column):
if columnNumber==0:
return column
base=26
col=columnNumber % base
columnNumber/=base
if col==0:
col=base
columnNumber=columnNumber-1
column.insert(0,col)
return computeColumnRecursive(columnNumber,column)
def getEquivalentColumn(column):
columnLetter=''
for i in column:
columnLetter+=string.ascii_uppercase[i-1]
return columnLetter
def printEquivalentColumn(column):
for i in column:
print string.ascii_uppercase[i-1],
if __name__ == '__main__':
#chars=['',]
#fillChars(chars)
#printColumns2(getColumnNumber())
printEquivalentColumn(computeColumn(getColumnNumber()))
printEquivalentColumn(computeColumn(getColumnNumber(),[])) | if printBlank:
start2=0
printBlank=False | random_line_split |
fd-generation-list-form.js | import { getOwner } from '@ember/application';
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import { get } from '@ember/object';
import ListFormController from 'ember-flexberry/controllers/list-form';
export default ListFormController.extend({
/**
Name of related edit form route.
@property editFormRoute
@type String
@default 'fd-generation-process-form'
*/
editFormRoute: 'fd-generation-process-form',
/**
Service for managing the state of the application.
@property appState
@type AppStateService
*/
appState: service(),
currentProjectContext: service('fd-current-project-context'),
generationService: service('fd-generation'),
/**
Property to form array of special structures of custom user buttons.
@property customButtons
@type Array
*/
customButtons: computed('i18n.locale', function() {
let i18n = this.get('i18n');
return [{
buttonName: i18n.t('forms.fd-generation-list-form.generation-button.caption'),
buttonAction: 'generationStartButtonClick',
buttonClasses: 'generation-start-button',
buttonTitle: i18n.t('forms.fd-generation-list-form.generation-button.title')
}];
}),
actions: {
/**
Handler for click on generate button.
@method actions.generationStartButtonClick
*/
generationStartButtonClick() |
},
/**
Method to get type and attributes of a component,
which will be embeded in object-list-view cell.
@method getCellComponent.
@param {Object} attr Attribute of projection property related to current table cell.
@param {String} bindingPath Path to model property related to current table cell.
@param {Object} modelClass Model class of data record related to current table row.
@return {Object} Object containing name & properties of component, which will be used to render current table cell.
{ componentName: 'my-component', componentProperties: { ... } }.
*/
getCellComponent: function(attr, bindingPath) {
if (bindingPath === 'startTime' || bindingPath === 'endTime') {
return {
componentName: 'object-list-view-cell',
componentProperties: {
dateFormat: 'DD.MM.YYYY, HH:mm:ss'
}
};
}
return this._super(...arguments);
},
});
| {
let _this = this;
_this.get('appState').loading();
let stagePk = _this.get('currentProjectContext').getCurrentStage();
let adapter = getOwner(this).lookup('adapter:application');
adapter.callFunction('Generate', { project: stagePk.toString() }, null, { withCredentials: true },
(result) => {
_this.set('generationService.lastGenerationToken', result);
result = result || {};
_this.get('appState').reset();
_this.transitionToRoute(_this.get('editFormRoute'), get(result, 'value'));
},
() => {
_this.get('appState').reset();
_this.set('error', new Error(_this.get('i18n').t('forms.fd-generation-process-form.connection-error-text')));
});
} | identifier_body |
fd-generation-list-form.js | import { getOwner } from '@ember/application';
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import { get } from '@ember/object';
import ListFormController from 'ember-flexberry/controllers/list-form';
export default ListFormController.extend({
/**
Name of related edit form route.
@property editFormRoute
@type String
@default 'fd-generation-process-form'
*/
editFormRoute: 'fd-generation-process-form',
/**
Service for managing the state of the application.
@property appState
@type AppStateService
*/
appState: service(),
currentProjectContext: service('fd-current-project-context'),
generationService: service('fd-generation'),
/**
Property to form array of special structures of custom user buttons.
@property customButtons
@type Array
*/
customButtons: computed('i18n.locale', function() {
let i18n = this.get('i18n');
return [{
buttonName: i18n.t('forms.fd-generation-list-form.generation-button.caption'),
buttonAction: 'generationStartButtonClick',
buttonClasses: 'generation-start-button',
buttonTitle: i18n.t('forms.fd-generation-list-form.generation-button.title')
}];
}),
actions: {
/**
Handler for click on generate button.
@method actions.generationStartButtonClick
*/
| () {
let _this = this;
_this.get('appState').loading();
let stagePk = _this.get('currentProjectContext').getCurrentStage();
let adapter = getOwner(this).lookup('adapter:application');
adapter.callFunction('Generate', { project: stagePk.toString() }, null, { withCredentials: true },
(result) => {
_this.set('generationService.lastGenerationToken', result);
result = result || {};
_this.get('appState').reset();
_this.transitionToRoute(_this.get('editFormRoute'), get(result, 'value'));
},
() => {
_this.get('appState').reset();
_this.set('error', new Error(_this.get('i18n').t('forms.fd-generation-process-form.connection-error-text')));
});
}
},
/**
Method to get type and attributes of a component,
which will be embeded in object-list-view cell.
@method getCellComponent.
@param {Object} attr Attribute of projection property related to current table cell.
@param {String} bindingPath Path to model property related to current table cell.
@param {Object} modelClass Model class of data record related to current table row.
@return {Object} Object containing name & properties of component, which will be used to render current table cell.
{ componentName: 'my-component', componentProperties: { ... } }.
*/
getCellComponent: function(attr, bindingPath) {
if (bindingPath === 'startTime' || bindingPath === 'endTime') {
return {
componentName: 'object-list-view-cell',
componentProperties: {
dateFormat: 'DD.MM.YYYY, HH:mm:ss'
}
};
}
return this._super(...arguments);
},
});
| generationStartButtonClick | identifier_name |
fd-generation-list-form.js | import { getOwner } from '@ember/application';
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import { get } from '@ember/object';
import ListFormController from 'ember-flexberry/controllers/list-form';
export default ListFormController.extend({
/**
Name of related edit form route.
@property editFormRoute
@type String
@default 'fd-generation-process-form'
*/
editFormRoute: 'fd-generation-process-form',
/**
Service for managing the state of the application.
@property appState
@type AppStateService
*/
appState: service(),
currentProjectContext: service('fd-current-project-context'),
generationService: service('fd-generation'),
/**
Property to form array of special structures of custom user buttons.
@property customButtons
@type Array
*/
customButtons: computed('i18n.locale', function() {
let i18n = this.get('i18n');
return [{
buttonName: i18n.t('forms.fd-generation-list-form.generation-button.caption'),
buttonAction: 'generationStartButtonClick',
buttonClasses: 'generation-start-button',
buttonTitle: i18n.t('forms.fd-generation-list-form.generation-button.title')
}];
}),
actions: {
/**
Handler for click on generate button.
@method actions.generationStartButtonClick
*/ | generationStartButtonClick() {
let _this = this;
_this.get('appState').loading();
let stagePk = _this.get('currentProjectContext').getCurrentStage();
let adapter = getOwner(this).lookup('adapter:application');
adapter.callFunction('Generate', { project: stagePk.toString() }, null, { withCredentials: true },
(result) => {
_this.set('generationService.lastGenerationToken', result);
result = result || {};
_this.get('appState').reset();
_this.transitionToRoute(_this.get('editFormRoute'), get(result, 'value'));
},
() => {
_this.get('appState').reset();
_this.set('error', new Error(_this.get('i18n').t('forms.fd-generation-process-form.connection-error-text')));
});
}
},
/**
Method to get type and attributes of a component,
which will be embeded in object-list-view cell.
@method getCellComponent.
@param {Object} attr Attribute of projection property related to current table cell.
@param {String} bindingPath Path to model property related to current table cell.
@param {Object} modelClass Model class of data record related to current table row.
@return {Object} Object containing name & properties of component, which will be used to render current table cell.
{ componentName: 'my-component', componentProperties: { ... } }.
*/
getCellComponent: function(attr, bindingPath) {
if (bindingPath === 'startTime' || bindingPath === 'endTime') {
return {
componentName: 'object-list-view-cell',
componentProperties: {
dateFormat: 'DD.MM.YYYY, HH:mm:ss'
}
};
}
return this._super(...arguments);
},
}); | random_line_split | |
fd-generation-list-form.js | import { getOwner } from '@ember/application';
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import { get } from '@ember/object';
import ListFormController from 'ember-flexberry/controllers/list-form';
export default ListFormController.extend({
/**
Name of related edit form route.
@property editFormRoute
@type String
@default 'fd-generation-process-form'
*/
editFormRoute: 'fd-generation-process-form',
/**
Service for managing the state of the application.
@property appState
@type AppStateService
*/
appState: service(),
currentProjectContext: service('fd-current-project-context'),
generationService: service('fd-generation'),
/**
Property to form array of special structures of custom user buttons.
@property customButtons
@type Array
*/
customButtons: computed('i18n.locale', function() {
let i18n = this.get('i18n');
return [{
buttonName: i18n.t('forms.fd-generation-list-form.generation-button.caption'),
buttonAction: 'generationStartButtonClick',
buttonClasses: 'generation-start-button',
buttonTitle: i18n.t('forms.fd-generation-list-form.generation-button.title')
}];
}),
actions: {
/**
Handler for click on generate button.
@method actions.generationStartButtonClick
*/
generationStartButtonClick() {
let _this = this;
_this.get('appState').loading();
let stagePk = _this.get('currentProjectContext').getCurrentStage();
let adapter = getOwner(this).lookup('adapter:application');
adapter.callFunction('Generate', { project: stagePk.toString() }, null, { withCredentials: true },
(result) => {
_this.set('generationService.lastGenerationToken', result);
result = result || {};
_this.get('appState').reset();
_this.transitionToRoute(_this.get('editFormRoute'), get(result, 'value'));
},
() => {
_this.get('appState').reset();
_this.set('error', new Error(_this.get('i18n').t('forms.fd-generation-process-form.connection-error-text')));
});
}
},
/**
Method to get type and attributes of a component,
which will be embeded in object-list-view cell.
@method getCellComponent.
@param {Object} attr Attribute of projection property related to current table cell.
@param {String} bindingPath Path to model property related to current table cell.
@param {Object} modelClass Model class of data record related to current table row.
@return {Object} Object containing name & properties of component, which will be used to render current table cell.
{ componentName: 'my-component', componentProperties: { ... } }.
*/
getCellComponent: function(attr, bindingPath) {
if (bindingPath === 'startTime' || bindingPath === 'endTime') |
return this._super(...arguments);
},
});
| {
return {
componentName: 'object-list-view-cell',
componentProperties: {
dateFormat: 'DD.MM.YYYY, HH:mm:ss'
}
};
} | conditional_block |
storage.py | import contextlib
import gc
import multiprocessing
import os
from memsql_loader.util.apsw_storage import APSWStorage
from memsql_loader.util import paths
MEMSQL_LOADER_DB = 'memsql_loader.db'
def get_loader_db_path():
return os.path.join(paths.get_data_dir(), MEMSQL_LOADER_DB)
# IMPORTANT NOTE: This class cannot be shared across forked processes unless
# you use fork_wrapper.
class LoaderStorage(APSWStorage):
_instance = None
_initialized = False
_instance_lock = multiprocessing.RLock()
# We use LoaderStorage as a singleton.
def __new__(cls, *args, **kwargs):
with cls._instance_lock:
if cls._instance is None:
cls._instance = super(LoaderStorage, cls).__new__(
cls, *args, **kwargs)
cls._initialized = False
return cls._instance
@classmethod
def drop_database(cls):
with cls._instance_lock:
if os.path.isfile(get_loader_db_path()):
os.remove(get_loader_db_path())
if os.path.isfile(get_loader_db_path() + '-shm'):
os.remove(get_loader_db_path() + '-shm')
if os.path.isfile(get_loader_db_path() + '-wal'):
os.remove(get_loader_db_path() + '-wal')
cls._instance = None
@classmethod
@contextlib.contextmanager
def fork_wrapper(cls):
# This context manager should be used around any code that forks new
# processes that will use a LoaderStorage object (e.g. Worker objects).
# This ensures that we don't share SQLite connections across forked
# processes.
with cls._instance_lock:
if cls._instance is not None:
cls._instance.close_connections()
# We garbage collect here to clean up any SQLite objects we
# may have missed; this is important because any surviving
# objects post-fork will mess up SQLite connections in the
# child process. We use generation=2 to collect as many
# objects as possible.
gc.collect(2)
yield
with cls._instance_lock:
if cls._instance is not None:
cls._instance.setup_connections() | # object in __new__. However, we may have closed this object's
# connections in fork_wrapper above; in that case, we want to set
# up new database connections.
if not LoaderStorage._initialized:
super(LoaderStorage, self).__init__(get_loader_db_path())
LoaderStorage._initialized = True
return
elif not self._db or not self._db_t:
self.setup_connections() |
def __init__(self):
with LoaderStorage._instance_lock:
# Since this is a singleton object, we don't want to call the
# parent object's __init__ if we've already instantiated this | random_line_split |
storage.py | import contextlib
import gc
import multiprocessing
import os
from memsql_loader.util.apsw_storage import APSWStorage
from memsql_loader.util import paths
MEMSQL_LOADER_DB = 'memsql_loader.db'
def get_loader_db_path():
return os.path.join(paths.get_data_dir(), MEMSQL_LOADER_DB)
# IMPORTANT NOTE: This class cannot be shared across forked processes unless
# you use fork_wrapper.
class LoaderStorage(APSWStorage):
_instance = None
_initialized = False
_instance_lock = multiprocessing.RLock()
# We use LoaderStorage as a singleton.
def __new__(cls, *args, **kwargs):
|
@classmethod
def drop_database(cls):
with cls._instance_lock:
if os.path.isfile(get_loader_db_path()):
os.remove(get_loader_db_path())
if os.path.isfile(get_loader_db_path() + '-shm'):
os.remove(get_loader_db_path() + '-shm')
if os.path.isfile(get_loader_db_path() + '-wal'):
os.remove(get_loader_db_path() + '-wal')
cls._instance = None
@classmethod
@contextlib.contextmanager
def fork_wrapper(cls):
# This context manager should be used around any code that forks new
# processes that will use a LoaderStorage object (e.g. Worker objects).
# This ensures that we don't share SQLite connections across forked
# processes.
with cls._instance_lock:
if cls._instance is not None:
cls._instance.close_connections()
# We garbage collect here to clean up any SQLite objects we
# may have missed; this is important because any surviving
# objects post-fork will mess up SQLite connections in the
# child process. We use generation=2 to collect as many
# objects as possible.
gc.collect(2)
yield
with cls._instance_lock:
if cls._instance is not None:
cls._instance.setup_connections()
def __init__(self):
with LoaderStorage._instance_lock:
# Since this is a singleton object, we don't want to call the
# parent object's __init__ if we've already instantiated this
# object in __new__. However, we may have closed this object's
# connections in fork_wrapper above; in that case, we want to set
# up new database connections.
if not LoaderStorage._initialized:
super(LoaderStorage, self).__init__(get_loader_db_path())
LoaderStorage._initialized = True
return
elif not self._db or not self._db_t:
self.setup_connections()
| with cls._instance_lock:
if cls._instance is None:
cls._instance = super(LoaderStorage, cls).__new__(
cls, *args, **kwargs)
cls._initialized = False
return cls._instance | identifier_body |
storage.py | import contextlib
import gc
import multiprocessing
import os
from memsql_loader.util.apsw_storage import APSWStorage
from memsql_loader.util import paths
MEMSQL_LOADER_DB = 'memsql_loader.db'
def get_loader_db_path():
return os.path.join(paths.get_data_dir(), MEMSQL_LOADER_DB)
# IMPORTANT NOTE: This class cannot be shared across forked processes unless
# you use fork_wrapper.
class LoaderStorage(APSWStorage):
_instance = None
_initialized = False
_instance_lock = multiprocessing.RLock()
# We use LoaderStorage as a singleton.
def __new__(cls, *args, **kwargs):
with cls._instance_lock:
if cls._instance is None:
|
return cls._instance
@classmethod
def drop_database(cls):
with cls._instance_lock:
if os.path.isfile(get_loader_db_path()):
os.remove(get_loader_db_path())
if os.path.isfile(get_loader_db_path() + '-shm'):
os.remove(get_loader_db_path() + '-shm')
if os.path.isfile(get_loader_db_path() + '-wal'):
os.remove(get_loader_db_path() + '-wal')
cls._instance = None
@classmethod
@contextlib.contextmanager
def fork_wrapper(cls):
# This context manager should be used around any code that forks new
# processes that will use a LoaderStorage object (e.g. Worker objects).
# This ensures that we don't share SQLite connections across forked
# processes.
with cls._instance_lock:
if cls._instance is not None:
cls._instance.close_connections()
# We garbage collect here to clean up any SQLite objects we
# may have missed; this is important because any surviving
# objects post-fork will mess up SQLite connections in the
# child process. We use generation=2 to collect as many
# objects as possible.
gc.collect(2)
yield
with cls._instance_lock:
if cls._instance is not None:
cls._instance.setup_connections()
def __init__(self):
with LoaderStorage._instance_lock:
# Since this is a singleton object, we don't want to call the
# parent object's __init__ if we've already instantiated this
# object in __new__. However, we may have closed this object's
# connections in fork_wrapper above; in that case, we want to set
# up new database connections.
if not LoaderStorage._initialized:
super(LoaderStorage, self).__init__(get_loader_db_path())
LoaderStorage._initialized = True
return
elif not self._db or not self._db_t:
self.setup_connections()
| cls._instance = super(LoaderStorage, cls).__new__(
cls, *args, **kwargs)
cls._initialized = False | conditional_block |
storage.py | import contextlib
import gc
import multiprocessing
import os
from memsql_loader.util.apsw_storage import APSWStorage
from memsql_loader.util import paths
MEMSQL_LOADER_DB = 'memsql_loader.db'
def get_loader_db_path():
return os.path.join(paths.get_data_dir(), MEMSQL_LOADER_DB)
# IMPORTANT NOTE: This class cannot be shared across forked processes unless
# you use fork_wrapper.
class LoaderStorage(APSWStorage):
_instance = None
_initialized = False
_instance_lock = multiprocessing.RLock()
# We use LoaderStorage as a singleton.
def | (cls, *args, **kwargs):
with cls._instance_lock:
if cls._instance is None:
cls._instance = super(LoaderStorage, cls).__new__(
cls, *args, **kwargs)
cls._initialized = False
return cls._instance
@classmethod
def drop_database(cls):
with cls._instance_lock:
if os.path.isfile(get_loader_db_path()):
os.remove(get_loader_db_path())
if os.path.isfile(get_loader_db_path() + '-shm'):
os.remove(get_loader_db_path() + '-shm')
if os.path.isfile(get_loader_db_path() + '-wal'):
os.remove(get_loader_db_path() + '-wal')
cls._instance = None
@classmethod
@contextlib.contextmanager
def fork_wrapper(cls):
# This context manager should be used around any code that forks new
# processes that will use a LoaderStorage object (e.g. Worker objects).
# This ensures that we don't share SQLite connections across forked
# processes.
with cls._instance_lock:
if cls._instance is not None:
cls._instance.close_connections()
# We garbage collect here to clean up any SQLite objects we
# may have missed; this is important because any surviving
# objects post-fork will mess up SQLite connections in the
# child process. We use generation=2 to collect as many
# objects as possible.
gc.collect(2)
yield
with cls._instance_lock:
if cls._instance is not None:
cls._instance.setup_connections()
def __init__(self):
with LoaderStorage._instance_lock:
# Since this is a singleton object, we don't want to call the
# parent object's __init__ if we've already instantiated this
# object in __new__. However, we may have closed this object's
# connections in fork_wrapper above; in that case, we want to set
# up new database connections.
if not LoaderStorage._initialized:
super(LoaderStorage, self).__init__(get_loader_db_path())
LoaderStorage._initialized = True
return
elif not self._db or not self._db_t:
self.setup_connections()
| __new__ | identifier_name |
transliterator.ts | export default {
translitePrimer: new Map([
['А', 'A'], ['а', 'a'], ['Б', 'B'], ['б', 'b'], ['В', 'V'], ['в', 'v'], ['Г', 'G'], ['г', 'g'],
['Д', 'D'], ['д', 'd'], ['Е', 'E'], ['е', 'e'], ['Ё', 'Yo'], ['ё', 'yo'], ['Ж', 'Zh'], ['ж', 'zh'],
['З', 'Z'], ['з', 'z'], ['И', 'I'], ['и', 'i'], ['Й', 'Y'], ['й', 'y'], ['К', 'K'], ['к', 'k'],
['Л', 'L'], ['л', 'l'], ['М', 'M'], ['м', 'm'], ['Н', 'N'], ['н', 'n'], ['О', 'O'], ['о', 'o'],
['П', 'P'], ['п', 'p'], ['Р', 'R'], ['р', 'r'], ['С', 'S'], ['с', 's'], ['Т', 'T'], ['т', 't'],
['У', 'U'], ['у', 'u'], ['Ф', 'F'], ['ф', 'f'], ['Х', 'Kh'], ['х', 'kh'], ['Ц', 'Ts'], ['ц', 'ts'],
['Ч', 'Ch'], ['ч', 'ch'], ['Ш', 'Sh'], ['ш', 'sh'], ['Щ', 'Sch'], ['щ', 'sch'], ['Ъ', '"'], ['ъ', '"'],
['Ы', 'Y'], ['ы', 'y'], ['Ь', "'"], ['ь', "'"], ['Э', 'E'], ['э', 'e'], ['Ю', 'Yu'], ['ю', 'yu'],
['Я', 'Ya'], ['я', 'ya'], [' ', '_'], ['Ä', 'A'], ['ä', 'a'], ['É', 'E'], ['é', 'e'], ['Ö', 'O'],
['ö', 'o'], ['Ü', 'U'], ['ü', 'u'], ['ß', 's']
]),
initializeTransliteration(options) {
if (options.schema) {
if (this.isShemaNew(options.schema)) {
options.schema = this.setOptionsToFieldsOfNewSchema(options.schema, options.transliteratedFields, options.inputSettings);
} else {
this.setOptionsToComputedTransliteratedFields(options.schema, options.transliteratedFields, options.inputSettings);
}
}
if (options.model) {
this.extendComputed(options.model, options.transliteratedFields, options.schema || options.schemaForExtendComputed);
options.model.computedFields = new Backbone.ComputedFields(options.model);
}
return {
schema: options.schema,
model: options.model,
transliteratedFields: options.transliteratedFields
};
},
setOptionsToComputedTransliteratedFields(schema, transliteratedFields = {name: 'alias'}, inputSettings = {
changeMode: 'blur',
autocommit: true,
forceCommit: true,
transliteratorChangedSomeProperties: true
}) {
let computedRelatedFields = Object.values(transliteratedFields);
computedRelatedFields = computedRelatedFields.concat(Object.keys(transliteratedFields).filter(name => !(schema[name] && schema[name].allowEmptyValue)));
computedRelatedFields.forEach((input) => {
if (!schema[input]) {
console.warn(`Transliterator: schema has no input '${input}'`);
return;
}
Object.keys(inputSettings).forEach((propetry) => {
if (schema[input][propetry] !== undefined && !schema[input].transliteratorChangedSomeProperties) {
console.warn(`Transliterator: Property '${propetry}' of input '${input}' was overwritten`);
}
});
Object.assign(schema[input], inputSettings);
});
return schema;
},
setOptionsToFieldsOfNewSchema(newSchema, transliteratedFields, inputSettings) {
this.setOptionsToComputedTransliteratedFields(this.mapNewSchemaToOld(newSchema), transliteratedFields, inputSettings);
return newSchema;
},
isShemaNew(schema) {
return Array.isArray(schema);
},
mapNewSchemaToOld(newSchema, initObject = {}) {
return newSchema.re | nput) => {
oldShema[input.key] = input;
return oldShema;
}, initObject);
},
mapOldSchemaToNew(oldShema, initArray = []) {
initArray.length = 0;
return Object.entries(oldShema).reduce((newSchema, keyValue) => {
const key = keyValue[0];
const input = keyValue[1];
input.key = input.key || key;
newSchema.push(input);
return newSchema;
}, initArray);
},
systemNameFiltration(string) {
if (!string) {
return '';
}
const str = this.translite(string);
let firstIsDigit = true;
const nonLatinReg = /[^a-zA-Z_]/g;
const nonLatinDigitReg = /[^a-zA-Z0-9_]/g;
return Array.from(str).map(char => {
firstIsDigit && (firstIsDigit = nonLatinReg.test(char));
return char.replace(firstIsDigit ? nonLatinReg : nonLatinDigitReg, '');
}).join('');
},
getTranslitToSystemName() {
if (!this.__translitToSystemName) {
this.__translitToSystemName = Object.create(null);
this.translitePrimer.forEach((value, key) => {
const err = Core.form.repository.validators.systemName()(value);
this.__translitToSystemName[key] = err ? '' : value;
});
}
return this.__translitToSystemName;
},
extendComputed(model, transliteratedFields = {name: 'alias'}, schema = {}) {
const computed = model.computed = model.computed || {};
const required = function(name) {
return function(fields) {
if (fields[name]) {
return fields[name];
}
return this.previous(name);
};
};
const getTranslite = (name, alias) =>
(fields) => {
if (fields[alias]) {
return schema[alias] && schema[alias].returnRawValue ? fields[alias] : this.systemNameFiltration(fields[alias]);
}
return this.systemNameFiltration(fields[name]);
};
Object.entries(transliteratedFields).forEach((keyValue) => {
const name = keyValue[0];
const alias = keyValue[1];
if (computed[name] && !computed[name].transliteratedFieldsClass) {
console.warn(`Transliterator: computed is not fully extended, computed[${name}] is exist in model!`);
return;
}
if (computed[alias] && !computed[alias].transliteratedFieldsClass) {
console.warn(`Transliterator: computed is not fully extended, computed[${alias}] is exist in model!`);
return;
}
if (!(schema[name] && schema[name].allowEmptyValue)) {
computed[name] = {
depends: [name],
get: required(name),
transliteratedFieldsClass: 'name' //flag for separate from original computed
};
}
computed[alias] = {
depends: [name, alias],
get: getTranslite(name, alias),
transliteratedFieldsClass: 'alias'
};
});
return model;
},
translite(text) {
return String(text).replace(/[а-яё]/gi, ruChar => this.getTranslitToSystemName()[ruChar] || '');
}
};
| duce((oldShema, i | identifier_name |
transliterator.ts | export default {
translitePrimer: new Map([
['А', 'A'], ['а', 'a'], ['Б', 'B'], ['б', 'b'], ['В', 'V'], ['в', 'v'], ['Г', 'G'], ['г', 'g'],
['Д', 'D'], ['д', 'd'], ['Е', 'E'], ['е', 'e'], ['Ё', 'Yo'], ['ё', 'yo'], ['Ж', 'Zh'], ['ж', 'zh'],
['З', 'Z'], ['з', 'z'], ['И', 'I'], ['и', 'i'], ['Й', 'Y'], ['й', 'y'], ['К', 'K'], ['к', 'k'],
['Л', 'L'], ['л', 'l'], ['М', 'M'], ['м', 'm'], ['Н', 'N'], ['н', 'n'], ['О', 'O'], ['о', 'o'],
['П', 'P'], ['п', 'p'], ['Р', 'R'], ['р', 'r'], ['С', 'S'], ['с', 's'], ['Т', 'T'], ['т', 't'],
['У', 'U'], ['у', 'u'], ['Ф', 'F'], ['ф', 'f'], ['Х', 'Kh'], ['х', 'kh'], ['Ц', 'Ts'], ['ц', 'ts'],
['Ч', 'Ch'], ['ч', 'ch'], ['Ш', 'Sh'], ['ш', 'sh'], ['Щ', 'Sch'], ['щ', 'sch'], ['Ъ', '"'], ['ъ', '"'],
['Ы', 'Y'], ['ы', 'y'], ['Ь', "'"], ['ь', "'"], ['Э', 'E'], ['э', 'e'], ['Ю', 'Yu'], ['ю', 'yu'],
['Я', 'Ya'], ['я', 'ya'], [' ', '_'], ['Ä', 'A'], ['ä', 'a'], ['É', 'E'], ['é', 'e'], ['Ö', 'O'],
['ö', 'o'], ['Ü', 'U'], ['ü', 'u'], ['ß', 's']
]),
initializeTransliteration(options) {
if (options.schema) {
if (this.isShemaNew(options.schema)) {
options.schema = this.setOptionsToFieldsOfNewSchema(options.schema, options.transliteratedFields, options.inputSettings);
} else {
this.setOptionsToComputedTransliteratedFields(options.schema, options.transliteratedFields, options.inputSettings);
}
}
if (options.model) {
this.extendComputed(options.model, options.transliteratedFields, options.schema || options.schemaForExtendComputed);
options.model.computedFields = new Backbone.ComputedFields(options.model);
}
return {
schema: options.schema,
model: options.model,
transliteratedFields: options.transliteratedFields
};
},
setOptionsToComputedTransliteratedFields(schema, transliteratedFields = {name: 'alias'}, inputSettings = {
changeMode: 'blur',
autocommit: true,
forceCommit: true,
transliteratorChangedSomeProperties: true
}) {
let computedRelatedFields = Object.values(transliteratedFields);
computedRelatedFields = computedRelatedFields.concat(Object.keys(transliteratedFields).filter(name => !(schema[name] && schema[name].allowEmptyValue)));
computedRelatedFields.forEach((input) => {
if (!schema[input]) {
console.warn(`Transliterator: schema has no input '${input}'`);
return;
}
Object.keys(inputSettings).forEach((propetry) => {
if (schema[input][propetry] !== undefined && !schema[input].transliteratorChangedSomeProperties) {
console.warn(`Transliterator: Property '${propetry}' of input '${input}' was overwritten`);
}
});
Object.assign(schema[input], inputSettings);
});
return schema;
},
setOptionsToFieldsOfNewSchema(newSchema, transliteratedFields, inputSettings) {
this.setOptionsToComputedTransliteratedFields(this.mapNewSchemaToOld(newSchema), transliteratedFields, inputSettings);
return newSchema;
},
isShemaNew(schema) {
return Array.isArray(schema);
},
mapNewSchemaToOld(newSchema, initObject = {}) {
return newSchema.reduce((oldShema, input) => {
oldShema[input.key] = input;
return oldShema;
}, initObject);
},
mapOldSchemaToNew(oldShema, initArray = []) {
initArray.length = 0;
return Object.entries(oldShema).reduce((newSchema, keyValue) => {
const key = keyValue[0];
const input = keyValue[1];
input.key = input.key || key;
newSchema.push(input);
return newSchema;
}, initArray);
},
systemNameFiltration(string) {
if (!string) {
return '';
}
const str = this.translite(string);
let firstIsDigit = true;
const nonLatinReg = /[^a-zA-Z_]/g;
const nonLatinDigitReg = /[^a-zA-Z0-9_]/g;
return Array.from(str).map(char => {
firstIsDigit && (firstIsDigit = nonLatinReg.test(char));
return char.replace(firstIsDigit ? nonLatinReg : nonLatinDigitReg, '');
}).join('');
},
getTranslitToSystemName() {
if (!this.__translitToSystemName) {
this.__translitToSystemName = Object.create(null);
| del, transliteratedFields = {name: 'alias'}, schema = {}) {
const computed = model.computed = model.computed || {};
const required = function(name) {
return function(fields) {
if (fields[name]) {
return fields[name];
}
return this.previous(name);
};
};
const getTranslite = (name, alias) =>
(fields) => {
if (fields[alias]) {
return schema[alias] && schema[alias].returnRawValue ? fields[alias] : this.systemNameFiltration(fields[alias]);
}
return this.systemNameFiltration(fields[name]);
};
Object.entries(transliteratedFields).forEach((keyValue) => {
const name = keyValue[0];
const alias = keyValue[1];
if (computed[name] && !computed[name].transliteratedFieldsClass) {
console.warn(`Transliterator: computed is not fully extended, computed[${name}] is exist in model!`);
return;
}
if (computed[alias] && !computed[alias].transliteratedFieldsClass) {
console.warn(`Transliterator: computed is not fully extended, computed[${alias}] is exist in model!`);
return;
}
if (!(schema[name] && schema[name].allowEmptyValue)) {
computed[name] = {
depends: [name],
get: required(name),
transliteratedFieldsClass: 'name' //flag for separate from original computed
};
}
computed[alias] = {
depends: [name, alias],
get: getTranslite(name, alias),
transliteratedFieldsClass: 'alias'
};
});
return model;
},
translite(text) {
return String(text).replace(/[а-яё]/gi, ruChar => this.getTranslitToSystemName()[ruChar] || '');
}
};
| this.translitePrimer.forEach((value, key) => {
const err = Core.form.repository.validators.systemName()(value);
this.__translitToSystemName[key] = err ? '' : value;
});
}
return this.__translitToSystemName;
},
extendComputed(mo | conditional_block |
transliterator.ts | export default {
translitePrimer: new Map([
['А', 'A'], ['а', 'a'], ['Б', 'B'], ['б', 'b'], ['В', 'V'], ['в', 'v'], ['Г', 'G'], ['г', 'g'],
['Д', 'D'], ['д', 'd'], ['Е', 'E'], ['е', 'e'], ['Ё', 'Yo'], ['ё', 'yo'], ['Ж', 'Zh'], ['ж', 'zh'],
['З', 'Z'], ['з', 'z'], ['И', 'I'], ['и', 'i'], ['Й', 'Y'], ['й', 'y'], ['К', 'K'], ['к', 'k'],
['Л', 'L'], ['л', 'l'], ['М', 'M'], ['м', 'm'], ['Н', 'N'], ['н', 'n'], ['О', 'O'], ['о', 'o'],
['П', 'P'], ['п', 'p'], ['Р', 'R'], ['р', 'r'], ['С', 'S'], ['с', 's'], ['Т', 'T'], ['т', 't'],
['У', 'U'], ['у', 'u'], ['Ф', 'F'], ['ф', 'f'], ['Х', 'Kh'], ['х', 'kh'], ['Ц', 'Ts'], ['ц', 'ts'],
['Ч', 'Ch'], ['ч', 'ch'], ['Ш', 'Sh'], ['ш', 'sh'], ['Щ', 'Sch'], ['щ', 'sch'], ['Ъ', '"'], ['ъ', '"'],
['Ы', 'Y'], ['ы', 'y'], ['Ь', "'"], ['ь', "'"], ['Э', 'E'], ['э', 'e'], ['Ю', 'Yu'], ['ю', 'yu'],
['Я', 'Ya'], ['я', 'ya'], [' ', '_'], ['Ä', 'A'], ['ä', 'a'], ['É', 'E'], ['é', 'e'], ['Ö', 'O'],
['ö', 'o'], ['Ü', 'U'], ['ü', 'u'], ['ß', 's']
]),
initializeTransliteration(options) {
if (options.schema) {
if (this.isShemaNew(options.schema)) {
options.schema = this.setOptionsToFieldsOfNewSchema(options.schema, options.transliteratedFields, options.inputSettings);
} else {
this.setOptionsToComputedTransliteratedFields(options.schema, options.transliteratedFields, options.inputSettings);
}
}
if (options.model) {
this.extendComputed(options.model, options.transliteratedFields, options.schema || options.schemaForExtendComputed);
options.model.computedFields = new Backbone.ComputedFields(options.model);
}
return {
schema: options.schema,
model: options.model,
transliteratedFields: options.transliteratedFields
};
},
setOptionsToComputedTransliteratedFields(schema, transliteratedFields = {name: 'alias'}, inputSettings = {
changeMode: 'blur',
autocommit: true,
forceCommit: true,
transliteratorChangedSomeProperties: true
}) {
let computedRelatedFields = Object.values(transliteratedFields);
computedRelatedFields = computedRelatedFields.concat(Object.keys(transliteratedFields).filter(name => !(schema[name] && schema[name].allowEmptyValue)));
computedRelatedFields.forEach((input) => {
if (!schema[input]) {
console.warn(`Transliterator: schema has no input '${input}'`);
return;
}
Object.keys(inputSettings).forEach((propetry) => {
if (schema[input][propetry] !== undefined && !schema[input].transliteratorChangedSomeProperties) {
console.warn(`Transliterator: Property '${propetry}' of input '${input}' was overwritten`);
}
});
Object.assign(schema[input], inputSettings);
});
return schema;
},
setOptionsToFieldsOfNewSchema(newSchema, transliteratedFields, inputSettings) {
this.setOptionsToComputedTransliteratedFields(this.mapNewSchemaToOld(newSchema), transliteratedFields, inputSettings);
return newSchema;
},
isShemaNew(schema) {
return Array.isArray(schema);
},
mapNewSchemaToOld(newSchema, initObject = {}) {
return newSchema.reduce((oldShema, input) => {
oldShema[input.key] = input;
return oldShema;
}, initObject);
},
mapOldSchemaToNew(oldShema, initArray = []) {
initArray.length = 0;
return Object.entries(oldShema).reduce((newSchema, keyValue) => {
const key = keyValue[0];
const input = keyValue[1];
input.key = input.key || key;
newSchema.push(input);
return newSchema;
}, initArray);
},
systemNameFiltration(string) {
if (!string) {
return '';
}
const str = this.translite(string);
let firstIsDigit = true;
const nonLatinReg = /[^a-zA-Z_]/g;
const nonLatinDigitReg = /[^a-zA-Z0-9_]/g;
return Array.from(str).map(char => {
firstIsDigit && (firstIsDigit = nonLatinReg.test(char));
return char.replace(firstIsDigit ? nonLatinReg : nonLatinDigitReg, '');
}).join('');
},
getTranslitToSystemName() {
if (!this.__translitToSystemName) {
this.__translitToSystemName = Object.create(null);
this.translitePrimer.forEach((value, key) => {
const err = Core.form.repository.validators.systemName()(value);
this.__translitToSystemName[key] = err ? '' : value;
});
}
return this.__translitToSystemName;
},
extendComputed(model, transliteratedFields = {name: 'alias'}, schema = {}) {
const computed = model.computed = model.computed || {};
| Char => this.getTranslitToSystemName()[ruChar] || '');
}
};
| const required = function(name) {
return function(fields) {
if (fields[name]) {
return fields[name];
}
return this.previous(name);
};
};
const getTranslite = (name, alias) =>
(fields) => {
if (fields[alias]) {
return schema[alias] && schema[alias].returnRawValue ? fields[alias] : this.systemNameFiltration(fields[alias]);
}
return this.systemNameFiltration(fields[name]);
};
Object.entries(transliteratedFields).forEach((keyValue) => {
const name = keyValue[0];
const alias = keyValue[1];
if (computed[name] && !computed[name].transliteratedFieldsClass) {
console.warn(`Transliterator: computed is not fully extended, computed[${name}] is exist in model!`);
return;
}
if (computed[alias] && !computed[alias].transliteratedFieldsClass) {
console.warn(`Transliterator: computed is not fully extended, computed[${alias}] is exist in model!`);
return;
}
if (!(schema[name] && schema[name].allowEmptyValue)) {
computed[name] = {
depends: [name],
get: required(name),
transliteratedFieldsClass: 'name' //flag for separate from original computed
};
}
computed[alias] = {
depends: [name, alias],
get: getTranslite(name, alias),
transliteratedFieldsClass: 'alias'
};
});
return model;
},
translite(text) {
return String(text).replace(/[а-яё]/gi, ru | identifier_body |
transliterator.ts | export default {
translitePrimer: new Map([
['А', 'A'], ['а', 'a'], ['Б', 'B'], ['б', 'b'], ['В', 'V'], ['в', 'v'], ['Г', 'G'], ['г', 'g'],
['Д', 'D'], ['д', 'd'], ['Е', 'E'], ['е', 'e'], ['Ё', 'Yo'], ['ё', 'yo'], ['Ж', 'Zh'], ['ж', 'zh'],
['З', 'Z'], ['з', 'z'], ['И', 'I'], ['и', 'i'], ['Й', 'Y'], ['й', 'y'], ['К', 'K'], ['к', 'k'],
['Л', 'L'], ['л', 'l'], ['М', 'M'], ['м', 'm'], ['Н', 'N'], ['н', 'n'], ['О', 'O'], ['о', 'o'],
['П', 'P'], ['п', 'p'], ['Р', 'R'], ['р', 'r'], ['С', 'S'], ['с', 's'], ['Т', 'T'], ['т', 't'],
['У', 'U'], ['у', 'u'], ['Ф', 'F'], ['ф', 'f'], ['Х', 'Kh'], ['х', 'kh'], ['Ц', 'Ts'], ['ц', 'ts'],
['Ч', 'Ch'], ['ч', 'ch'], ['Ш', 'Sh'], ['ш', 'sh'], ['Щ', 'Sch'], ['щ', 'sch'], ['Ъ', '"'], ['ъ', '"'],
['Ы', 'Y'], ['ы', 'y'], ['Ь', "'"], ['ь', "'"], ['Э', 'E'], ['э', 'e'], ['Ю', 'Yu'], ['ю', 'yu'],
['Я', 'Ya'], ['я', 'ya'], [' ', '_'], ['Ä', 'A'], ['ä', 'a'], ['É', 'E'], ['é', 'e'], ['Ö', 'O'],
['ö', 'o'], ['Ü', 'U'], ['ü', 'u'], ['ß', 's']
]),
initializeTransliteration(options) {
if (options.schema) {
if (this.isShemaNew(options.schema)) {
options.schema = this.setOptionsToFieldsOfNewSchema(options.schema, options.transliteratedFields, options.inputSettings);
} else {
this.setOptionsToComputedTransliteratedFields(options.schema, options.transliteratedFields, options.inputSettings);
}
}
if (options.model) {
this.extendComputed(options.model, options.transliteratedFields, options.schema || options.schemaForExtendComputed);
options.model.computedFields = new Backbone.ComputedFields(options.model);
}
return {
schema: options.schema,
model: options.model,
transliteratedFields: options.transliteratedFields
};
},
setOptionsToComputedTransliteratedFields(schema, transliteratedFields = {name: 'alias'}, inputSettings = {
changeMode: 'blur',
autocommit: true,
forceCommit: true,
transliteratorChangedSomeProperties: true
}) {
let computedRelatedFields = Object.values(transliteratedFields);
computedRelatedFields = computedRelatedFields.concat(Object.keys(transliteratedFields).filter(name => !(schema[name] && schema[name].allowEmptyValue)));
computedRelatedFields.forEach((input) => {
if (!schema[input]) {
console.warn(`Transliterator: schema has no input '${input}'`);
return;
}
Object.keys(inputSettings).forEach((propetry) => {
if (schema[input][propetry] !== undefined && !schema[input].transliteratorChangedSomeProperties) {
console.warn(`Transliterator: Property '${propetry}' of input '${input}' was overwritten`);
}
});
Object.assign(schema[input], inputSettings); |
setOptionsToFieldsOfNewSchema(newSchema, transliteratedFields, inputSettings) {
this.setOptionsToComputedTransliteratedFields(this.mapNewSchemaToOld(newSchema), transliteratedFields, inputSettings);
return newSchema;
},
isShemaNew(schema) {
return Array.isArray(schema);
},
mapNewSchemaToOld(newSchema, initObject = {}) {
return newSchema.reduce((oldShema, input) => {
oldShema[input.key] = input;
return oldShema;
}, initObject);
},
mapOldSchemaToNew(oldShema, initArray = []) {
initArray.length = 0;
return Object.entries(oldShema).reduce((newSchema, keyValue) => {
const key = keyValue[0];
const input = keyValue[1];
input.key = input.key || key;
newSchema.push(input);
return newSchema;
}, initArray);
},
systemNameFiltration(string) {
if (!string) {
return '';
}
const str = this.translite(string);
let firstIsDigit = true;
const nonLatinReg = /[^a-zA-Z_]/g;
const nonLatinDigitReg = /[^a-zA-Z0-9_]/g;
return Array.from(str).map(char => {
firstIsDigit && (firstIsDigit = nonLatinReg.test(char));
return char.replace(firstIsDigit ? nonLatinReg : nonLatinDigitReg, '');
}).join('');
},
getTranslitToSystemName() {
if (!this.__translitToSystemName) {
this.__translitToSystemName = Object.create(null);
this.translitePrimer.forEach((value, key) => {
const err = Core.form.repository.validators.systemName()(value);
this.__translitToSystemName[key] = err ? '' : value;
});
}
return this.__translitToSystemName;
},
extendComputed(model, transliteratedFields = {name: 'alias'}, schema = {}) {
const computed = model.computed = model.computed || {};
const required = function(name) {
return function(fields) {
if (fields[name]) {
return fields[name];
}
return this.previous(name);
};
};
const getTranslite = (name, alias) =>
(fields) => {
if (fields[alias]) {
return schema[alias] && schema[alias].returnRawValue ? fields[alias] : this.systemNameFiltration(fields[alias]);
}
return this.systemNameFiltration(fields[name]);
};
Object.entries(transliteratedFields).forEach((keyValue) => {
const name = keyValue[0];
const alias = keyValue[1];
if (computed[name] && !computed[name].transliteratedFieldsClass) {
console.warn(`Transliterator: computed is not fully extended, computed[${name}] is exist in model!`);
return;
}
if (computed[alias] && !computed[alias].transliteratedFieldsClass) {
console.warn(`Transliterator: computed is not fully extended, computed[${alias}] is exist in model!`);
return;
}
if (!(schema[name] && schema[name].allowEmptyValue)) {
computed[name] = {
depends: [name],
get: required(name),
transliteratedFieldsClass: 'name' //flag for separate from original computed
};
}
computed[alias] = {
depends: [name, alias],
get: getTranslite(name, alias),
transliteratedFieldsClass: 'alias'
};
});
return model;
},
translite(text) {
return String(text).replace(/[а-яё]/gi, ruChar => this.getTranslitToSystemName()[ruChar] || '');
}
}; | });
return schema;
}, | random_line_split |
parser-postfix-exp-assign.js | /* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// tests for ECMA-262 v6 12.4.3
var tests = [
// IdentifierReference
'var obj = {a : 10, ret : function(params) {return a++ = 42;}}',
'var obj = {a : 10, ret : function(params) {return a-- = 42;}}',
// NullLiteral
'var a = null; a++ = 42',
'var a = null; a-- = 42',
// BooleanLiteral
'var a = true; a++ = 42',
'var a = false; a++ = 42',
'var a = true; a-- = 42',
'var a = false; a-- = 42',
// DecimalLiteral
'var a = 5; a++ = 42',
'var a = 1.23e4; a++ = 42',
'var a = 5; a-- = 42',
'var a = 1.23e4; a-- = 42',
// BinaryIntegerLiteral
'var a = 0b11; a++ = 42',
'var a = 0B11; a++ = 42',
'var a = 0b11; a-- = 42',
'var a = 0B11; a-- = 42',
// OctalIntegerLiteral
'var a = 0o66; a++ = 42',
'var a = 0O66; a++ = 42',
'var a = 0o66; a-- = 42',
'var a = 0O66; a-- = 42',
// HexIntegerLiteral
'var a = 0xFF; a++ = 42',
'var a = 0xFF; a++ = 42',
'var a = 0xFF; a-- = 42',
'var a = 0xFF; a-- = 42',
// StringLiteral
'var a = "foo"; a++ = 42',
'var a = "\\n"; a++ = 42',
'var a = "\\uFFFF"; a++ = 42',
'var a ="\\u{F}"; a++ = 42',
'var a = "foo"; a-- = 42',
'var a = "\\n"; a-- = 42',
'var a = "\\uFFFF"; a-- = 42',
'var a ="\\u{F}"; a-- = 42',
// ArrayLiteral
'var a = []; a++ = 42',
'var a = [1,a=5]; a++ = 42',
'var a = []; a-- = 42',
'var a = [1,a=5]; a-- = 42',
// ObjectLiteral
'var a = {}; a++ = 42',
'var a = {"foo" : 5}; a++ = 42',
'var a = {5 : 5}; a++ = 42',
'var a = {a : 5}; a++ = 42',
'var a = {[key] : 5}; a++ = 42',
'var a = {func(){}}; a++ = 42',
'var a = {get(){}}; a++ = 42',
'var a = {set(prop){}}; a++ = 42',
'var a = {*func(){}}; a++ = 42',
'var a = {}; a-- = 42',
'var a = {"foo" : 5}; a-- = 42',
'var a = {5 : 5}; a-- = 42',
'var a = {a : 5}; a-- = 42',
'var a = {[key] : 5}; a-- = 42',
'var a = {func(){}}; a-- = 42',
'var a = {get(){}}; a-- = 42',
'var a = {set(prop){}}; a-- = 42',
'var a = {*func(){}}; a-- = 42',
// ClassExpression
'class a {}; a++ = 42',
'class a {}; class b extends a {}; b++ = 42',
'class a {function(){}}; a++ = 42',
'class a {}; a-- = 42',
'class a {}; class b extends a {}; b-- = 42',
'class a {function(){}}; a-- = 42',
// GeneratorExpression
'function *a (){}; a++ = 42',
'function *a (){}; a-- = 42',
// RegularExpressionLiteral
'var a = /(?:)/; a++ = 42',
'var a = /a/; a++ = 42',
'var a = /[a]/; a++ = 42',
'var a = /a/g; a++ = 42',
'var a = /(?:)/; a-- = 42',
'var a = /a/; a-- = 42',
'var a = /[a]/; a-- = 42',
'var a = /a/g; a-- = 42',
// TemplateLiteral
'var a = ``; a++ = 42',
'a = 5; var b = (`${a}`); b++ = 42',
'var a = `foo`; a++ = 42',
'var a = `\\uFFFF`; a++ = 42',
'var a = ``; a-- = 42',
'a = 5; var b = (`${a}`); b-- = 42',
'var a = `foo`; a-- = 42',
'var a = `\\uFFFF`; a-- = 42',
// MemberExpression
'var a = [1,2,3]; a[0]++ = 42',
'var a = {0:12}; a[0]++ = 42',
'var a = {"foo":12}; a.foo++ = 42',
'var a = {func: function(){}}; a.func++ = 42',
'var a = [1,2,3]; a[0]-- = 42',
'var a = {0:12}; a[0]-- = 42',
'var a = {"foo":12}; a.foo-- = 42',
'var a = {func: function(){}}; a.func-- = 42',
// SuperProperty
'class a {constructor() {Object.defineProperty(this, \'foo\', {configurable:true, writable:true, value:1}); }} ' +
'class b extends a {constructor() {super();} foo() {super.foo++ = 42;}}',
'class a {constructor() {Object.defineProperty(this, \'foo\', {configurable:true, writable:true, value:1}); }} ' +
'class b extends a {constructor() {super();} foo() {super.foo-- = 42;}}',
// NewExpression
'function a() {}; var b = new a(); b++ = 42',
'function a() {}; var b = new a(); b-- = 42',
'class g {constructor() {Object.defineProperty(this, \'foo\', {configurable:true, writable:true, value:1}); }}; ' +
'var a = new g(); a++ = 42',
'class g {constructor() {Object.defineProperty(this, \'foo\', {configurable:true, writable:true, value:1}); }}; ' +
'var a = new g(); a-- = 42',
'class a {}; var n = new a(); a++ = 42',
'class a {}; var n = new a(); a-- = 42',
// CallExpression
'function a(prop){return prop}; var b = a(12); b++ = 42',
'function a(prop){return prop}; var b = a(12); b-- = 42',
];
for (var i = 0; i < tests.length; i++)
| {
try {
eval(tests[i]);
assert(false);
} catch (e) {
assert(e instanceof SyntaxError);
}
} | conditional_block | |
parser-postfix-exp-assign.js | /* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// tests for ECMA-262 v6 12.4.3
var tests = [
// IdentifierReference
'var obj = {a : 10, ret : function(params) {return a++ = 42;}}',
'var obj = {a : 10, ret : function(params) {return a-- = 42;}}',
// NullLiteral
'var a = null; a++ = 42',
'var a = null; a-- = 42',
// BooleanLiteral
'var a = true; a++ = 42',
'var a = false; a++ = 42',
'var a = true; a-- = 42',
'var a = false; a-- = 42',
// DecimalLiteral
'var a = 5; a++ = 42',
'var a = 1.23e4; a++ = 42',
'var a = 5; a-- = 42', | 'var a = 0B11; a++ = 42',
'var a = 0b11; a-- = 42',
'var a = 0B11; a-- = 42',
// OctalIntegerLiteral
'var a = 0o66; a++ = 42',
'var a = 0O66; a++ = 42',
'var a = 0o66; a-- = 42',
'var a = 0O66; a-- = 42',
// HexIntegerLiteral
'var a = 0xFF; a++ = 42',
'var a = 0xFF; a++ = 42',
'var a = 0xFF; a-- = 42',
'var a = 0xFF; a-- = 42',
// StringLiteral
'var a = "foo"; a++ = 42',
'var a = "\\n"; a++ = 42',
'var a = "\\uFFFF"; a++ = 42',
'var a ="\\u{F}"; a++ = 42',
'var a = "foo"; a-- = 42',
'var a = "\\n"; a-- = 42',
'var a = "\\uFFFF"; a-- = 42',
'var a ="\\u{F}"; a-- = 42',
// ArrayLiteral
'var a = []; a++ = 42',
'var a = [1,a=5]; a++ = 42',
'var a = []; a-- = 42',
'var a = [1,a=5]; a-- = 42',
// ObjectLiteral
'var a = {}; a++ = 42',
'var a = {"foo" : 5}; a++ = 42',
'var a = {5 : 5}; a++ = 42',
'var a = {a : 5}; a++ = 42',
'var a = {[key] : 5}; a++ = 42',
'var a = {func(){}}; a++ = 42',
'var a = {get(){}}; a++ = 42',
'var a = {set(prop){}}; a++ = 42',
'var a = {*func(){}}; a++ = 42',
'var a = {}; a-- = 42',
'var a = {"foo" : 5}; a-- = 42',
'var a = {5 : 5}; a-- = 42',
'var a = {a : 5}; a-- = 42',
'var a = {[key] : 5}; a-- = 42',
'var a = {func(){}}; a-- = 42',
'var a = {get(){}}; a-- = 42',
'var a = {set(prop){}}; a-- = 42',
'var a = {*func(){}}; a-- = 42',
// ClassExpression
'class a {}; a++ = 42',
'class a {}; class b extends a {}; b++ = 42',
'class a {function(){}}; a++ = 42',
'class a {}; a-- = 42',
'class a {}; class b extends a {}; b-- = 42',
'class a {function(){}}; a-- = 42',
// GeneratorExpression
'function *a (){}; a++ = 42',
'function *a (){}; a-- = 42',
// RegularExpressionLiteral
'var a = /(?:)/; a++ = 42',
'var a = /a/; a++ = 42',
'var a = /[a]/; a++ = 42',
'var a = /a/g; a++ = 42',
'var a = /(?:)/; a-- = 42',
'var a = /a/; a-- = 42',
'var a = /[a]/; a-- = 42',
'var a = /a/g; a-- = 42',
// TemplateLiteral
'var a = ``; a++ = 42',
'a = 5; var b = (`${a}`); b++ = 42',
'var a = `foo`; a++ = 42',
'var a = `\\uFFFF`; a++ = 42',
'var a = ``; a-- = 42',
'a = 5; var b = (`${a}`); b-- = 42',
'var a = `foo`; a-- = 42',
'var a = `\\uFFFF`; a-- = 42',
// MemberExpression
'var a = [1,2,3]; a[0]++ = 42',
'var a = {0:12}; a[0]++ = 42',
'var a = {"foo":12}; a.foo++ = 42',
'var a = {func: function(){}}; a.func++ = 42',
'var a = [1,2,3]; a[0]-- = 42',
'var a = {0:12}; a[0]-- = 42',
'var a = {"foo":12}; a.foo-- = 42',
'var a = {func: function(){}}; a.func-- = 42',
// SuperProperty
'class a {constructor() {Object.defineProperty(this, \'foo\', {configurable:true, writable:true, value:1}); }} ' +
'class b extends a {constructor() {super();} foo() {super.foo++ = 42;}}',
'class a {constructor() {Object.defineProperty(this, \'foo\', {configurable:true, writable:true, value:1}); }} ' +
'class b extends a {constructor() {super();} foo() {super.foo-- = 42;}}',
// NewExpression
'function a() {}; var b = new a(); b++ = 42',
'function a() {}; var b = new a(); b-- = 42',
'class g {constructor() {Object.defineProperty(this, \'foo\', {configurable:true, writable:true, value:1}); }}; ' +
'var a = new g(); a++ = 42',
'class g {constructor() {Object.defineProperty(this, \'foo\', {configurable:true, writable:true, value:1}); }}; ' +
'var a = new g(); a-- = 42',
'class a {}; var n = new a(); a++ = 42',
'class a {}; var n = new a(); a-- = 42',
// CallExpression
'function a(prop){return prop}; var b = a(12); b++ = 42',
'function a(prop){return prop}; var b = a(12); b-- = 42',
];
for (var i = 0; i < tests.length; i++)
{
try {
eval(tests[i]);
assert(false);
} catch (e) {
assert(e instanceof SyntaxError);
}
} | 'var a = 1.23e4; a-- = 42',
// BinaryIntegerLiteral
'var a = 0b11; a++ = 42', | random_line_split |
vc.py | #
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# 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.
#
# TODO:
# * supported arch for versions: for old versions of batch file without
# argument, giving bogus argument cannot be detected, so we have to hardcode
# this here
# * print warning when msvc version specified but not found
# * find out why warning do not print
# * test on 64 bits XP + VS 2005 (and VS 6 if possible)
# * SDK
# * Assembly
__revision__ = "src/engine/SCons/Tool/MSCommon/vc.py rel_2.3.5:3329:275e75118ad4 2015/06/20 11:18:26 bdbaddog"
__doc__ = """Module for Visual C/C++ detection and configuration.
"""
import SCons.compat
import os
import platform
from string import digits as string_digits
import SCons.Warnings
import common
debug = common.debug
import sdk
get_installed_sdks = sdk.get_installed_sdks
class VisualCException(Exception):
pass
class UnsupportedVersion(VisualCException):
pass
class UnsupportedArch(VisualCException):
pass
class MissingConfiguration(VisualCException):
pass
class NoVersionFound(VisualCException):
pass
class BatchFileExecutionError(VisualCException):
pass
# Dict to 'canonalize' the arch
_ARCH_TO_CANONICAL = {
"amd64" : "amd64",
"emt64" : "amd64",
"i386" : "x86",
"i486" : "x86",
"i586" : "x86",
"i686" : "x86",
"ia64" : "ia64",
"itanium" : "ia64",
"x86" : "x86",
"x86_64" : "amd64",
"x86_amd64" : "x86_amd64", # Cross compile to 64 bit from 32bits
}
# Given a (host, target) tuple, return the argument for the bat file. Both host
# and targets should be canonalized.
_HOST_TARGET_ARCH_TO_BAT_ARCH = {
("x86", "x86"): "x86",
("x86", "amd64"): "x86_amd64",
("x86", "x86_amd64"): "x86_amd64",
("amd64", "x86_amd64"): "x86_amd64", # This is present in (at least) VS2012 express
("amd64", "amd64"): "amd64",
("amd64", "x86"): "x86",
("x86", "ia64"): "x86_ia64"
}
def get_host_target(env):
debug('vc.py:get_host_target()')
host_platform = env.get('HOST_ARCH')
if not host_platform:
host_platform = platform.machine()
# TODO(2.5): the native Python platform.machine() function returns
# '' on all Python versions before 2.6, after which it also uses
# PROCESSOR_ARCHITECTURE.
if not host_platform:
host_platform = os.environ.get('PROCESSOR_ARCHITECTURE', '')
# Retain user requested TARGET_ARCH
req_target_platform = env.get('TARGET_ARCH')
debug('vc.py:get_host_target() req_target_platform:%s'%req_target_platform)
if req_target_platform:
# If user requested a specific platform then only try that one.
target_platform = req_target_platform
else:
target_platform = host_platform
try:
host = _ARCH_TO_CANONICAL[host_platform.lower()]
except KeyError, e:
msg = "Unrecognized host architecture %s"
raise ValueError(msg % repr(host_platform))
try:
target = _ARCH_TO_CANONICAL[target_platform.lower()]
except KeyError, e:
all_archs = str(_ARCH_TO_CANONICAL.keys())
raise ValueError("Unrecognized target architecture %s\n\tValid architectures: %s" % (target_platform, all_archs))
return (host, target,req_target_platform)
# If you update this, update SupportedVSList in Tool/MSCommon/vs.py, and the
# MSVC_VERSION documentation in Tool/msvc.xml.
_VCVER = ["15.0", "14.0", "14.0Exp", "12.0", "12.0Exp", "11.0", "11.0Exp", "10.0", "10.0Exp", "9.0", "9.0Exp","8.0", "8.0Exp","7.1", "7.0", "6.0"]
_VCVER_TO_PRODUCT_DIR = {
'15.0' : [
r'Microsoft\VisualStudio\SxS\VS7\15.0'],
'14.0' : [
r'Microsoft\VisualStudio\14.0\Setup\VC\ProductDir'],
'14.0' : [
r'Microsoft\VisualStudio\14.0\Setup\VC\ProductDir'],
'12.0' : [
r'Microsoft\VisualStudio\12.0\Setup\VC\ProductDir'],
'12.0Exp' : [
r'Microsoft\VCExpress\12.0\Setup\VC\ProductDir'],
'11.0': [
r'Microsoft\VisualStudio\11.0\Setup\VC\ProductDir'],
'11.0Exp' : [
r'Microsoft\VCExpress\11.0\Setup\VC\ProductDir'],
'10.0': [
r'Microsoft\VisualStudio\10.0\Setup\VC\ProductDir'],
'10.0Exp' : [
r'Microsoft\VCExpress\10.0\Setup\VC\ProductDir'],
'9.0': [
r'Microsoft\VisualStudio\9.0\Setup\VC\ProductDir'],
'9.0Exp' : [
r'Microsoft\VCExpress\9.0\Setup\VC\ProductDir'],
'8.0': [
r'Microsoft\VisualStudio\8.0\Setup\VC\ProductDir'],
'8.0Exp': [
r'Microsoft\VCExpress\8.0\Setup\VC\ProductDir'],
'7.1': [
r'Microsoft\VisualStudio\7.1\Setup\VC\ProductDir'],
'7.0': [
r'Microsoft\VisualStudio\7.0\Setup\VC\ProductDir'],
'6.0': [
r'Microsoft\VisualStudio\6.0\Setup\Microsoft Visual C++\ProductDir']
}
def | (msvc_version):
msvc_version_numeric = ''.join([x for x in msvc_version if x in string_digits + '.'])
t = msvc_version_numeric.split(".")
if not len(t) == 2:
raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
try:
maj = int(t[0])
min = int(t[1])
return maj, min
except ValueError, e:
raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
def is_host_target_supported(host_target, msvc_version):
"""Return True if the given (host, target) tuple is supported given the
msvc version.
Parameters
----------
host_target: tuple
tuple of (canonalized) host-target, e.g. ("x86", "amd64") for cross
compilation from 32 bits windows to 64 bits.
msvc_version: str
msvc version (major.minor, e.g. 10.0)
Note
----
This only check whether a given version *may* support the given (host,
target), not that the toolchain is actually present on the machine.
"""
# We assume that any Visual Studio version supports x86 as a target
if host_target[1] != "x86":
maj, min = msvc_version_to_maj_min(msvc_version)
if maj < 8:
return False
return True
def find_vc_pdir(msvc_version):
"""Try to find the product directory for the given
version.
Note
----
If for some reason the requested version could not be found, an
exception which inherits from VisualCException will be raised."""
root = 'Software\\'
if common.is_win64():
root = root + 'Wow6432Node\\'
try:
hkeys = _VCVER_TO_PRODUCT_DIR[msvc_version]
except KeyError:
debug("Unknown version of MSVC: %s" % msvc_version)
raise UnsupportedVersion("Unknown version %s" % msvc_version)
for key in hkeys:
key = root + key
try:
comps = common.read_reg(key)
except WindowsError, e:
debug('find_vc_dir(): no VC registry key %s' % repr(key))
else:
debug('find_vc_dir(): found VC in registry: %s' % comps)
if msvc_version == "15.0":
comps = os.path.join(comps, "VC")
if os.path.exists(comps):
return comps
else:
debug('find_vc_dir(): reg says dir is %s, but it does not exist. (ignoring)'\
% comps)
raise MissingConfiguration("registry dir %s not found on the filesystem" % comps)
return None
def find_batch_file(env,msvc_version,host_arch,target_arch):
"""
Find the location of the batch script which should set up the compiler
for any TARGET_ARCH whose compilers were installed by Visual Studio/VCExpress
"""
pdir = find_vc_pdir(msvc_version)
if pdir is None:
raise NoVersionFound("No version of Visual Studio found")
debug('vc.py: find_batch_file() pdir:%s'%pdir)
# filter out e.g. "Exp" from the version name
msvc_ver_numeric = ''.join([x for x in msvc_version if x in string_digits + "."])
vernum = float(msvc_ver_numeric)
if 7 <= vernum < 8:
pdir = os.path.join(pdir, os.pardir, "Common7", "Tools")
batfilename = os.path.join(pdir, "vsvars32.bat")
elif vernum < 7:
pdir = os.path.join(pdir, "Bin")
batfilename = os.path.join(pdir, "vcvars32.bat")
elif vernum >= 15:
pdir = os.path.join(pdir, "Auxiliary", "Build")
batfilename = os.path.join(pdir, "vcvarsall.bat")
else: # >= 8
batfilename = os.path.join(pdir, "vcvarsall.bat")
if not os.path.exists(batfilename):
debug("Not found: %s" % batfilename)
batfilename = None
installed_sdks=get_installed_sdks()
for _sdk in installed_sdks:
sdk_bat_file = _sdk.get_sdk_vc_script(host_arch,target_arch)
if not sdk_bat_file:
debug("vc.py:find_batch_file() not found:%s"%_sdk)
else:
sdk_bat_file_path = os.path.join(pdir,sdk_bat_file)
if os.path.exists(sdk_bat_file_path):
debug('vc.py:find_batch_file() sdk_bat_file_path:%s'%sdk_bat_file_path)
return (batfilename,sdk_bat_file_path)
return (batfilename,None)
__INSTALLED_VCS_RUN = None
def cached_get_installed_vcs():
global __INSTALLED_VCS_RUN
if __INSTALLED_VCS_RUN is None:
ret = get_installed_vcs()
__INSTALLED_VCS_RUN = ret
return __INSTALLED_VCS_RUN
def get_installed_vcs():
installed_versions = []
for ver in _VCVER:
debug('trying to find VC %s' % ver)
try:
if find_vc_pdir(ver):
debug('found VC %s' % ver)
installed_versions.append(ver)
else:
debug('find_vc_pdir return None for ver %s' % ver)
except VisualCException, e:
debug('did not find VC %s: caught exception %s' % (ver, str(e)))
return installed_versions
def reset_installed_vcs():
"""Make it try again to find VC. This is just for the tests."""
__INSTALLED_VCS_RUN = None
# Running these batch files isn't cheap: most of the time spent in
# msvs.generate() is due to vcvars*.bat. In a build that uses "tools='msvs'"
# in multiple environments, for example:
# env1 = Environment(tools='msvs')
# env2 = Environment(tools='msvs')
# we can greatly improve the speed of the second and subsequent Environment
# (or Clone) calls by memoizing the environment variables set by vcvars*.bat.
script_env_stdout_cache = {}
def script_env(script, args=None):
cache_key = (script, args)
stdout = script_env_stdout_cache.get(cache_key, None)
if stdout is None:
stdout = common.get_output(script, args)
script_env_stdout_cache[cache_key] = stdout
# Stupid batch files do not set return code: we take a look at the
# beginning of the output for an error message instead
olines = stdout.splitlines()
if olines[0].startswith("The specified configuration type is missing"):
raise BatchFileExecutionError("\n".join(olines[:2]))
return common.parse_output(stdout)
def get_default_version(env):
debug('get_default_version()')
msvc_version = env.get('MSVC_VERSION')
msvs_version = env.get('MSVS_VERSION')
debug('get_default_version(): msvc_version:%s msvs_version:%s'%(msvc_version,msvs_version))
if msvs_version and not msvc_version:
SCons.Warnings.warn(
SCons.Warnings.DeprecatedWarning,
"MSVS_VERSION is deprecated: please use MSVC_VERSION instead ")
return msvs_version
elif msvc_version and msvs_version:
if not msvc_version == msvs_version:
SCons.Warnings.warn(
SCons.Warnings.VisualVersionMismatch,
"Requested msvc version (%s) and msvs version (%s) do " \
"not match: please use MSVC_VERSION only to request a " \
"visual studio version, MSVS_VERSION is deprecated" \
% (msvc_version, msvs_version))
return msvs_version
if not msvc_version:
installed_vcs = cached_get_installed_vcs()
debug('installed_vcs:%s' % installed_vcs)
if not installed_vcs:
#msg = 'No installed VCs'
#debug('msv %s\n' % repr(msg))
#SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, msg)
debug('msvc_setup_env: No installed VCs')
return None
msvc_version = installed_vcs[0]
debug('msvc_setup_env: using default installed MSVC version %s\n' % repr(msvc_version))
return msvc_version
def msvc_setup_env_once(env):
try:
has_run = env["MSVC_SETUP_RUN"]
except KeyError:
has_run = False
if not has_run:
msvc_setup_env(env)
env["MSVC_SETUP_RUN"] = True
def msvc_find_valid_batch_script(env,version):
debug('vc.py:msvc_find_valid_batch_script()')
# Find the host platform, target platform, and if present the requested
# target platform
(host_platform, target_platform,req_target_platform) = get_host_target(env)
try_target_archs = [target_platform]
debug("msvs_find_valid_batch_script(): req_target_platform %s target_platform:%s"%(req_target_platform,target_platform))
# VS2012 has a "cross compile" environment to build 64 bit
# with x86_amd64 as the argument to the batch setup script
if req_target_platform in ('amd64','x86_64'):
try_target_archs.append('x86_amd64')
elif not req_target_platform and target_platform in ['amd64','x86_64']:
# There may not be "native" amd64, but maybe "cross" x86_amd64 tools
try_target_archs.append('x86_amd64')
# If the user hasn't specifically requested a TARGET_ARCH, and
# The TARGET_ARCH is amd64 then also try 32 bits if there are no viable
# 64 bit tools installed
try_target_archs.append('x86')
debug("msvs_find_valid_batch_script(): host_platform: %s try_target_archs:%s"%(host_platform, try_target_archs))
d = None
for tp in try_target_archs:
# Set to current arch.
env['TARGET_ARCH']=tp
debug("vc.py:msvc_find_valid_batch_script() trying target_platform:%s"%tp)
host_target = (host_platform, tp)
if not is_host_target_supported(host_target, version):
warn_msg = "host, target = %s not supported for MSVC version %s" % \
(host_target, version)
SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
arg = _HOST_TARGET_ARCH_TO_BAT_ARCH[host_target]
# Try to locate a batch file for this host/target platform combo
try:
(vc_script,sdk_script) = find_batch_file(env,version,host_platform,tp)
debug('vc.py:msvc_find_valid_batch_script() vc_script:%s sdk_script:%s'%(vc_script,sdk_script))
except VisualCException, e:
msg = str(e)
debug('Caught exception while looking for batch file (%s)' % msg)
warn_msg = "VC version %s not installed. " + \
"C/C++ compilers are most likely not set correctly.\n" + \
" Installed versions are: %s"
warn_msg = warn_msg % (version, cached_get_installed_vcs())
SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
continue
# Try to use the located batch file for this host/target platform combo
debug('vc.py:msvc_find_valid_batch_script() use_script 2 %s, args:%s\n' % (repr(vc_script), arg))
if vc_script:
try:
d = script_env(vc_script, args=arg)
except BatchFileExecutionError, e:
debug('vc.py:msvc_find_valid_batch_script() use_script 3: failed running VC script %s: %s: Error:%s'%(repr(vc_script),arg,e))
vc_script=None
continue
if not vc_script and sdk_script:
debug('vc.py:msvc_find_valid_batch_script() use_script 4: trying sdk script: %s'%(sdk_script))
try:
d = script_env(sdk_script)
except BatchFileExecutionError,e:
debug('vc.py:msvc_find_valid_batch_script() use_script 5: failed running SDK script %s: Error:%s'%(repr(sdk_script),e))
continue
elif not vc_script and not sdk_script:
debug('vc.py:msvc_find_valid_batch_script() use_script 6: Neither VC script nor SDK script found')
continue
debug("vc.py:msvc_find_valid_batch_script() Found a working script/target: %s %s"%(repr(sdk_script),arg))
break # We've found a working target_platform, so stop looking
# If we cannot find a viable installed compiler, reset the TARGET_ARCH
# To it's initial value
if not d:
env['TARGET_ARCH']=req_target_platform
return d
def msvc_setup_env(env):
debug('msvc_setup_env()')
version = get_default_version(env)
if version is None:
warn_msg = "No version of Visual Studio compiler found - C/C++ " \
"compilers most likely not set correctly"
# Nuitka: Useless warning for us.
# SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
return None
debug('msvc_setup_env: using specified MSVC version %s\n' % repr(version))
# XXX: we set-up both MSVS version for backward
# compatibility with the msvs tool
env['MSVC_VERSION'] = version
env['MSVS_VERSION'] = version
env['MSVS'] = {}
use_script = env.get('MSVC_USE_SCRIPT', True)
if SCons.Util.is_String(use_script):
debug('vc.py:msvc_setup_env() use_script 1 %s\n' % repr(use_script))
d = script_env(use_script)
elif use_script:
d = msvc_find_valid_batch_script(env,version)
debug('vc.py:msvc_setup_env() use_script 2 %s\n' % d)
if not d:
return d
else:
debug('MSVC_USE_SCRIPT set to False')
warn_msg = "MSVC_USE_SCRIPT set to False, assuming environment " \
"set correctly."
# Nuitka: We use this on purpose.
# SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
return None
for k, v in d.items():
debug('vc.py:msvc_setup_env() env:%s -> %s'%(k,v))
env.PrependENVPath(k, v, delete_existing=True)
def msvc_exists(version=None):
vcs = cached_get_installed_vcs()
if version is None:
return len(vcs) > 0
return version in vcs
| msvc_version_to_maj_min | identifier_name |
vc.py | #
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# 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.
#
# TODO:
# * supported arch for versions: for old versions of batch file without
# argument, giving bogus argument cannot be detected, so we have to hardcode
# this here
# * print warning when msvc version specified but not found
# * find out why warning do not print
# * test on 64 bits XP + VS 2005 (and VS 6 if possible)
# * SDK
# * Assembly
__revision__ = "src/engine/SCons/Tool/MSCommon/vc.py rel_2.3.5:3329:275e75118ad4 2015/06/20 11:18:26 bdbaddog"
__doc__ = """Module for Visual C/C++ detection and configuration.
"""
import SCons.compat
import os
import platform
from string import digits as string_digits
import SCons.Warnings
import common
debug = common.debug
import sdk
get_installed_sdks = sdk.get_installed_sdks
class VisualCException(Exception):
pass
class UnsupportedVersion(VisualCException):
pass
class UnsupportedArch(VisualCException):
pass
class MissingConfiguration(VisualCException):
pass
class NoVersionFound(VisualCException):
pass
class BatchFileExecutionError(VisualCException):
pass
# Dict to 'canonalize' the arch
_ARCH_TO_CANONICAL = {
"amd64" : "amd64",
"emt64" : "amd64",
"i386" : "x86",
"i486" : "x86",
"i586" : "x86",
"i686" : "x86",
"ia64" : "ia64",
"itanium" : "ia64",
"x86" : "x86",
"x86_64" : "amd64",
"x86_amd64" : "x86_amd64", # Cross compile to 64 bit from 32bits
}
# Given a (host, target) tuple, return the argument for the bat file. Both host
# and targets should be canonalized.
_HOST_TARGET_ARCH_TO_BAT_ARCH = {
("x86", "x86"): "x86",
("x86", "amd64"): "x86_amd64",
("x86", "x86_amd64"): "x86_amd64",
("amd64", "x86_amd64"): "x86_amd64", # This is present in (at least) VS2012 express
("amd64", "amd64"): "amd64",
("amd64", "x86"): "x86",
("x86", "ia64"): "x86_ia64"
}
def get_host_target(env):
debug('vc.py:get_host_target()')
host_platform = env.get('HOST_ARCH')
if not host_platform:
host_platform = platform.machine()
# TODO(2.5): the native Python platform.machine() function returns
# '' on all Python versions before 2.6, after which it also uses
# PROCESSOR_ARCHITECTURE.
if not host_platform:
host_platform = os.environ.get('PROCESSOR_ARCHITECTURE', '')
# Retain user requested TARGET_ARCH
req_target_platform = env.get('TARGET_ARCH')
debug('vc.py:get_host_target() req_target_platform:%s'%req_target_platform)
if req_target_platform:
# If user requested a specific platform then only try that one.
target_platform = req_target_platform
else:
target_platform = host_platform
try:
host = _ARCH_TO_CANONICAL[host_platform.lower()]
except KeyError, e:
msg = "Unrecognized host architecture %s"
raise ValueError(msg % repr(host_platform))
try:
target = _ARCH_TO_CANONICAL[target_platform.lower()]
except KeyError, e:
all_archs = str(_ARCH_TO_CANONICAL.keys())
raise ValueError("Unrecognized target architecture %s\n\tValid architectures: %s" % (target_platform, all_archs))
return (host, target,req_target_platform)
# If you update this, update SupportedVSList in Tool/MSCommon/vs.py, and the
# MSVC_VERSION documentation in Tool/msvc.xml.
_VCVER = ["15.0", "14.0", "14.0Exp", "12.0", "12.0Exp", "11.0", "11.0Exp", "10.0", "10.0Exp", "9.0", "9.0Exp","8.0", "8.0Exp","7.1", "7.0", "6.0"]
_VCVER_TO_PRODUCT_DIR = {
'15.0' : [
r'Microsoft\VisualStudio\SxS\VS7\15.0'],
'14.0' : [
r'Microsoft\VisualStudio\14.0\Setup\VC\ProductDir'],
'14.0' : [
r'Microsoft\VisualStudio\14.0\Setup\VC\ProductDir'],
'12.0' : [
r'Microsoft\VisualStudio\12.0\Setup\VC\ProductDir'],
'12.0Exp' : [
r'Microsoft\VCExpress\12.0\Setup\VC\ProductDir'],
'11.0': [
r'Microsoft\VisualStudio\11.0\Setup\VC\ProductDir'],
'11.0Exp' : [
r'Microsoft\VCExpress\11.0\Setup\VC\ProductDir'],
'10.0': [
r'Microsoft\VisualStudio\10.0\Setup\VC\ProductDir'],
'10.0Exp' : [
r'Microsoft\VCExpress\10.0\Setup\VC\ProductDir'],
'9.0': [
r'Microsoft\VisualStudio\9.0\Setup\VC\ProductDir'],
'9.0Exp' : [
r'Microsoft\VCExpress\9.0\Setup\VC\ProductDir'],
'8.0': [
r'Microsoft\VisualStudio\8.0\Setup\VC\ProductDir'],
'8.0Exp': [
r'Microsoft\VCExpress\8.0\Setup\VC\ProductDir'],
'7.1': [
r'Microsoft\VisualStudio\7.1\Setup\VC\ProductDir'],
'7.0': [
r'Microsoft\VisualStudio\7.0\Setup\VC\ProductDir'],
'6.0': [
r'Microsoft\VisualStudio\6.0\Setup\Microsoft Visual C++\ProductDir']
}
def msvc_version_to_maj_min(msvc_version):
msvc_version_numeric = ''.join([x for x in msvc_version if x in string_digits + '.'])
t = msvc_version_numeric.split(".")
if not len(t) == 2:
raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
try:
maj = int(t[0])
min = int(t[1])
return maj, min
except ValueError, e:
raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
def is_host_target_supported(host_target, msvc_version):
"""Return True if the given (host, target) tuple is supported given the
msvc version.
Parameters
----------
host_target: tuple
tuple of (canonalized) host-target, e.g. ("x86", "amd64") for cross
compilation from 32 bits windows to 64 bits.
msvc_version: str
msvc version (major.minor, e.g. 10.0)
Note
----
This only check whether a given version *may* support the given (host,
target), not that the toolchain is actually present on the machine.
"""
# We assume that any Visual Studio version supports x86 as a target
if host_target[1] != "x86":
maj, min = msvc_version_to_maj_min(msvc_version)
if maj < 8:
return False
return True
def find_vc_pdir(msvc_version):
"""Try to find the product directory for the given
version.
Note
----
If for some reason the requested version could not be found, an
exception which inherits from VisualCException will be raised."""
root = 'Software\\'
if common.is_win64():
root = root + 'Wow6432Node\\'
try:
hkeys = _VCVER_TO_PRODUCT_DIR[msvc_version]
except KeyError:
debug("Unknown version of MSVC: %s" % msvc_version)
raise UnsupportedVersion("Unknown version %s" % msvc_version)
for key in hkeys:
key = root + key
try:
comps = common.read_reg(key)
except WindowsError, e:
debug('find_vc_dir(): no VC registry key %s' % repr(key))
else:
debug('find_vc_dir(): found VC in registry: %s' % comps)
if msvc_version == "15.0":
comps = os.path.join(comps, "VC")
if os.path.exists(comps):
return comps
else:
debug('find_vc_dir(): reg says dir is %s, but it does not exist. (ignoring)'\
% comps)
raise MissingConfiguration("registry dir %s not found on the filesystem" % comps)
return None
def find_batch_file(env,msvc_version,host_arch,target_arch):
"""
Find the location of the batch script which should set up the compiler
for any TARGET_ARCH whose compilers were installed by Visual Studio/VCExpress
"""
pdir = find_vc_pdir(msvc_version)
if pdir is None:
raise NoVersionFound("No version of Visual Studio found")
debug('vc.py: find_batch_file() pdir:%s'%pdir)
# filter out e.g. "Exp" from the version name
msvc_ver_numeric = ''.join([x for x in msvc_version if x in string_digits + "."])
vernum = float(msvc_ver_numeric)
if 7 <= vernum < 8:
pdir = os.path.join(pdir, os.pardir, "Common7", "Tools")
batfilename = os.path.join(pdir, "vsvars32.bat")
elif vernum < 7:
pdir = os.path.join(pdir, "Bin")
batfilename = os.path.join(pdir, "vcvars32.bat")
elif vernum >= 15:
pdir = os.path.join(pdir, "Auxiliary", "Build")
batfilename = os.path.join(pdir, "vcvarsall.bat")
else: # >= 8
batfilename = os.path.join(pdir, "vcvarsall.bat")
if not os.path.exists(batfilename):
debug("Not found: %s" % batfilename)
batfilename = None
installed_sdks=get_installed_sdks()
for _sdk in installed_sdks:
sdk_bat_file = _sdk.get_sdk_vc_script(host_arch,target_arch)
if not sdk_bat_file:
debug("vc.py:find_batch_file() not found:%s"%_sdk)
else:
sdk_bat_file_path = os.path.join(pdir,sdk_bat_file)
if os.path.exists(sdk_bat_file_path):
debug('vc.py:find_batch_file() sdk_bat_file_path:%s'%sdk_bat_file_path)
return (batfilename,sdk_bat_file_path)
return (batfilename,None)
__INSTALLED_VCS_RUN = None
def cached_get_installed_vcs():
global __INSTALLED_VCS_RUN
if __INSTALLED_VCS_RUN is None:
ret = get_installed_vcs()
__INSTALLED_VCS_RUN = ret
return __INSTALLED_VCS_RUN
def get_installed_vcs():
installed_versions = []
for ver in _VCVER:
debug('trying to find VC %s' % ver)
try:
if find_vc_pdir(ver):
debug('found VC %s' % ver)
installed_versions.append(ver)
else:
debug('find_vc_pdir return None for ver %s' % ver)
except VisualCException, e:
debug('did not find VC %s: caught exception %s' % (ver, str(e)))
return installed_versions
def reset_installed_vcs():
"""Make it try again to find VC. This is just for the tests."""
__INSTALLED_VCS_RUN = None
# Running these batch files isn't cheap: most of the time spent in
# msvs.generate() is due to vcvars*.bat. In a build that uses "tools='msvs'"
# in multiple environments, for example:
# env1 = Environment(tools='msvs')
# env2 = Environment(tools='msvs')
# we can greatly improve the speed of the second and subsequent Environment
# (or Clone) calls by memoizing the environment variables set by vcvars*.bat.
script_env_stdout_cache = {}
def script_env(script, args=None):
cache_key = (script, args)
stdout = script_env_stdout_cache.get(cache_key, None)
if stdout is None:
|
# Stupid batch files do not set return code: we take a look at the
# beginning of the output for an error message instead
olines = stdout.splitlines()
if olines[0].startswith("The specified configuration type is missing"):
raise BatchFileExecutionError("\n".join(olines[:2]))
return common.parse_output(stdout)
def get_default_version(env):
debug('get_default_version()')
msvc_version = env.get('MSVC_VERSION')
msvs_version = env.get('MSVS_VERSION')
debug('get_default_version(): msvc_version:%s msvs_version:%s'%(msvc_version,msvs_version))
if msvs_version and not msvc_version:
SCons.Warnings.warn(
SCons.Warnings.DeprecatedWarning,
"MSVS_VERSION is deprecated: please use MSVC_VERSION instead ")
return msvs_version
elif msvc_version and msvs_version:
if not msvc_version == msvs_version:
SCons.Warnings.warn(
SCons.Warnings.VisualVersionMismatch,
"Requested msvc version (%s) and msvs version (%s) do " \
"not match: please use MSVC_VERSION only to request a " \
"visual studio version, MSVS_VERSION is deprecated" \
% (msvc_version, msvs_version))
return msvs_version
if not msvc_version:
installed_vcs = cached_get_installed_vcs()
debug('installed_vcs:%s' % installed_vcs)
if not installed_vcs:
#msg = 'No installed VCs'
#debug('msv %s\n' % repr(msg))
#SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, msg)
debug('msvc_setup_env: No installed VCs')
return None
msvc_version = installed_vcs[0]
debug('msvc_setup_env: using default installed MSVC version %s\n' % repr(msvc_version))
return msvc_version
def msvc_setup_env_once(env):
try:
has_run = env["MSVC_SETUP_RUN"]
except KeyError:
has_run = False
if not has_run:
msvc_setup_env(env)
env["MSVC_SETUP_RUN"] = True
def msvc_find_valid_batch_script(env,version):
debug('vc.py:msvc_find_valid_batch_script()')
# Find the host platform, target platform, and if present the requested
# target platform
(host_platform, target_platform,req_target_platform) = get_host_target(env)
try_target_archs = [target_platform]
debug("msvs_find_valid_batch_script(): req_target_platform %s target_platform:%s"%(req_target_platform,target_platform))
# VS2012 has a "cross compile" environment to build 64 bit
# with x86_amd64 as the argument to the batch setup script
if req_target_platform in ('amd64','x86_64'):
try_target_archs.append('x86_amd64')
elif not req_target_platform and target_platform in ['amd64','x86_64']:
# There may not be "native" amd64, but maybe "cross" x86_amd64 tools
try_target_archs.append('x86_amd64')
# If the user hasn't specifically requested a TARGET_ARCH, and
# The TARGET_ARCH is amd64 then also try 32 bits if there are no viable
# 64 bit tools installed
try_target_archs.append('x86')
debug("msvs_find_valid_batch_script(): host_platform: %s try_target_archs:%s"%(host_platform, try_target_archs))
d = None
for tp in try_target_archs:
# Set to current arch.
env['TARGET_ARCH']=tp
debug("vc.py:msvc_find_valid_batch_script() trying target_platform:%s"%tp)
host_target = (host_platform, tp)
if not is_host_target_supported(host_target, version):
warn_msg = "host, target = %s not supported for MSVC version %s" % \
(host_target, version)
SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
arg = _HOST_TARGET_ARCH_TO_BAT_ARCH[host_target]
# Try to locate a batch file for this host/target platform combo
try:
(vc_script,sdk_script) = find_batch_file(env,version,host_platform,tp)
debug('vc.py:msvc_find_valid_batch_script() vc_script:%s sdk_script:%s'%(vc_script,sdk_script))
except VisualCException, e:
msg = str(e)
debug('Caught exception while looking for batch file (%s)' % msg)
warn_msg = "VC version %s not installed. " + \
"C/C++ compilers are most likely not set correctly.\n" + \
" Installed versions are: %s"
warn_msg = warn_msg % (version, cached_get_installed_vcs())
SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
continue
# Try to use the located batch file for this host/target platform combo
debug('vc.py:msvc_find_valid_batch_script() use_script 2 %s, args:%s\n' % (repr(vc_script), arg))
if vc_script:
try:
d = script_env(vc_script, args=arg)
except BatchFileExecutionError, e:
debug('vc.py:msvc_find_valid_batch_script() use_script 3: failed running VC script %s: %s: Error:%s'%(repr(vc_script),arg,e))
vc_script=None
continue
if not vc_script and sdk_script:
debug('vc.py:msvc_find_valid_batch_script() use_script 4: trying sdk script: %s'%(sdk_script))
try:
d = script_env(sdk_script)
except BatchFileExecutionError,e:
debug('vc.py:msvc_find_valid_batch_script() use_script 5: failed running SDK script %s: Error:%s'%(repr(sdk_script),e))
continue
elif not vc_script and not sdk_script:
debug('vc.py:msvc_find_valid_batch_script() use_script 6: Neither VC script nor SDK script found')
continue
debug("vc.py:msvc_find_valid_batch_script() Found a working script/target: %s %s"%(repr(sdk_script),arg))
break # We've found a working target_platform, so stop looking
# If we cannot find a viable installed compiler, reset the TARGET_ARCH
# To it's initial value
if not d:
env['TARGET_ARCH']=req_target_platform
return d
def msvc_setup_env(env):
debug('msvc_setup_env()')
version = get_default_version(env)
if version is None:
warn_msg = "No version of Visual Studio compiler found - C/C++ " \
"compilers most likely not set correctly"
# Nuitka: Useless warning for us.
# SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
return None
debug('msvc_setup_env: using specified MSVC version %s\n' % repr(version))
# XXX: we set-up both MSVS version for backward
# compatibility with the msvs tool
env['MSVC_VERSION'] = version
env['MSVS_VERSION'] = version
env['MSVS'] = {}
use_script = env.get('MSVC_USE_SCRIPT', True)
if SCons.Util.is_String(use_script):
debug('vc.py:msvc_setup_env() use_script 1 %s\n' % repr(use_script))
d = script_env(use_script)
elif use_script:
d = msvc_find_valid_batch_script(env,version)
debug('vc.py:msvc_setup_env() use_script 2 %s\n' % d)
if not d:
return d
else:
debug('MSVC_USE_SCRIPT set to False')
warn_msg = "MSVC_USE_SCRIPT set to False, assuming environment " \
"set correctly."
# Nuitka: We use this on purpose.
# SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
return None
for k, v in d.items():
debug('vc.py:msvc_setup_env() env:%s -> %s'%(k,v))
env.PrependENVPath(k, v, delete_existing=True)
def msvc_exists(version=None):
vcs = cached_get_installed_vcs()
if version is None:
return len(vcs) > 0
return version in vcs
| stdout = common.get_output(script, args)
script_env_stdout_cache[cache_key] = stdout | conditional_block |
vc.py | #
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# 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.
#
# TODO:
# * supported arch for versions: for old versions of batch file without
# argument, giving bogus argument cannot be detected, so we have to hardcode
# this here
# * print warning when msvc version specified but not found
# * find out why warning do not print
# * test on 64 bits XP + VS 2005 (and VS 6 if possible)
# * SDK
# * Assembly
__revision__ = "src/engine/SCons/Tool/MSCommon/vc.py rel_2.3.5:3329:275e75118ad4 2015/06/20 11:18:26 bdbaddog"
__doc__ = """Module for Visual C/C++ detection and configuration.
"""
import SCons.compat
import os
import platform
from string import digits as string_digits
import SCons.Warnings
import common
debug = common.debug
import sdk
get_installed_sdks = sdk.get_installed_sdks
class VisualCException(Exception):
pass
class UnsupportedVersion(VisualCException):
pass
class UnsupportedArch(VisualCException):
pass
class MissingConfiguration(VisualCException):
pass
class NoVersionFound(VisualCException):
pass
class BatchFileExecutionError(VisualCException):
pass
# Dict to 'canonalize' the arch
_ARCH_TO_CANONICAL = {
"amd64" : "amd64",
"emt64" : "amd64",
"i386" : "x86",
"i486" : "x86",
"i586" : "x86",
"i686" : "x86",
"ia64" : "ia64",
"itanium" : "ia64",
"x86" : "x86",
"x86_64" : "amd64",
"x86_amd64" : "x86_amd64", # Cross compile to 64 bit from 32bits
}
# Given a (host, target) tuple, return the argument for the bat file. Both host
# and targets should be canonalized.
_HOST_TARGET_ARCH_TO_BAT_ARCH = {
("x86", "x86"): "x86",
("x86", "amd64"): "x86_amd64",
("x86", "x86_amd64"): "x86_amd64",
("amd64", "x86_amd64"): "x86_amd64", # This is present in (at least) VS2012 express
("amd64", "amd64"): "amd64",
("amd64", "x86"): "x86",
("x86", "ia64"): "x86_ia64"
}
def get_host_target(env):
debug('vc.py:get_host_target()')
host_platform = env.get('HOST_ARCH')
if not host_platform:
host_platform = platform.machine()
# TODO(2.5): the native Python platform.machine() function returns
# '' on all Python versions before 2.6, after which it also uses
# PROCESSOR_ARCHITECTURE.
if not host_platform:
host_platform = os.environ.get('PROCESSOR_ARCHITECTURE', '')
# Retain user requested TARGET_ARCH
req_target_platform = env.get('TARGET_ARCH')
debug('vc.py:get_host_target() req_target_platform:%s'%req_target_platform)
if req_target_platform:
# If user requested a specific platform then only try that one.
target_platform = req_target_platform
else:
target_platform = host_platform
try:
host = _ARCH_TO_CANONICAL[host_platform.lower()]
except KeyError, e:
msg = "Unrecognized host architecture %s"
raise ValueError(msg % repr(host_platform))
try:
target = _ARCH_TO_CANONICAL[target_platform.lower()]
except KeyError, e:
all_archs = str(_ARCH_TO_CANONICAL.keys())
raise ValueError("Unrecognized target architecture %s\n\tValid architectures: %s" % (target_platform, all_archs))
return (host, target,req_target_platform)
# If you update this, update SupportedVSList in Tool/MSCommon/vs.py, and the
# MSVC_VERSION documentation in Tool/msvc.xml.
_VCVER = ["15.0", "14.0", "14.0Exp", "12.0", "12.0Exp", "11.0", "11.0Exp", "10.0", "10.0Exp", "9.0", "9.0Exp","8.0", "8.0Exp","7.1", "7.0", "6.0"]
_VCVER_TO_PRODUCT_DIR = {
'15.0' : [
r'Microsoft\VisualStudio\SxS\VS7\15.0'],
'14.0' : [
r'Microsoft\VisualStudio\14.0\Setup\VC\ProductDir'],
'14.0' : [
r'Microsoft\VisualStudio\14.0\Setup\VC\ProductDir'],
'12.0' : [
r'Microsoft\VisualStudio\12.0\Setup\VC\ProductDir'],
'12.0Exp' : [
r'Microsoft\VCExpress\12.0\Setup\VC\ProductDir'],
'11.0': [
r'Microsoft\VisualStudio\11.0\Setup\VC\ProductDir'],
'11.0Exp' : [
r'Microsoft\VCExpress\11.0\Setup\VC\ProductDir'],
'10.0': [
r'Microsoft\VisualStudio\10.0\Setup\VC\ProductDir'],
'10.0Exp' : [
r'Microsoft\VCExpress\10.0\Setup\VC\ProductDir'],
'9.0': [
r'Microsoft\VisualStudio\9.0\Setup\VC\ProductDir'],
'9.0Exp' : [
r'Microsoft\VCExpress\9.0\Setup\VC\ProductDir'],
'8.0': [
r'Microsoft\VisualStudio\8.0\Setup\VC\ProductDir'],
'8.0Exp': [
r'Microsoft\VCExpress\8.0\Setup\VC\ProductDir'],
'7.1': [
r'Microsoft\VisualStudio\7.1\Setup\VC\ProductDir'],
'7.0': [
r'Microsoft\VisualStudio\7.0\Setup\VC\ProductDir'],
'6.0': [
r'Microsoft\VisualStudio\6.0\Setup\Microsoft Visual C++\ProductDir']
}
def msvc_version_to_maj_min(msvc_version):
msvc_version_numeric = ''.join([x for x in msvc_version if x in string_digits + '.'])
t = msvc_version_numeric.split(".")
if not len(t) == 2:
raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
try:
maj = int(t[0])
min = int(t[1])
return maj, min
except ValueError, e:
raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
def is_host_target_supported(host_target, msvc_version):
"""Return True if the given (host, target) tuple is supported given the
msvc version.
Parameters
----------
host_target: tuple
tuple of (canonalized) host-target, e.g. ("x86", "amd64") for cross
compilation from 32 bits windows to 64 bits.
msvc_version: str
msvc version (major.minor, e.g. 10.0)
Note
----
This only check whether a given version *may* support the given (host,
target), not that the toolchain is actually present on the machine.
"""
# We assume that any Visual Studio version supports x86 as a target
if host_target[1] != "x86":
maj, min = msvc_version_to_maj_min(msvc_version)
if maj < 8:
return False
return True
def find_vc_pdir(msvc_version):
"""Try to find the product directory for the given
version.
Note
----
If for some reason the requested version could not be found, an
exception which inherits from VisualCException will be raised."""
root = 'Software\\'
if common.is_win64():
root = root + 'Wow6432Node\\'
try:
hkeys = _VCVER_TO_PRODUCT_DIR[msvc_version]
except KeyError:
debug("Unknown version of MSVC: %s" % msvc_version)
raise UnsupportedVersion("Unknown version %s" % msvc_version)
for key in hkeys:
key = root + key
try:
comps = common.read_reg(key)
except WindowsError, e:
debug('find_vc_dir(): no VC registry key %s' % repr(key))
else:
debug('find_vc_dir(): found VC in registry: %s' % comps)
if msvc_version == "15.0":
comps = os.path.join(comps, "VC")
if os.path.exists(comps):
return comps
else:
debug('find_vc_dir(): reg says dir is %s, but it does not exist. (ignoring)'\
% comps)
raise MissingConfiguration("registry dir %s not found on the filesystem" % comps)
return None
def find_batch_file(env,msvc_version,host_arch,target_arch):
"""
Find the location of the batch script which should set up the compiler
for any TARGET_ARCH whose compilers were installed by Visual Studio/VCExpress
"""
pdir = find_vc_pdir(msvc_version)
if pdir is None:
raise NoVersionFound("No version of Visual Studio found")
debug('vc.py: find_batch_file() pdir:%s'%pdir)
# filter out e.g. "Exp" from the version name
msvc_ver_numeric = ''.join([x for x in msvc_version if x in string_digits + "."])
vernum = float(msvc_ver_numeric)
if 7 <= vernum < 8:
pdir = os.path.join(pdir, os.pardir, "Common7", "Tools")
batfilename = os.path.join(pdir, "vsvars32.bat")
elif vernum < 7:
pdir = os.path.join(pdir, "Bin")
batfilename = os.path.join(pdir, "vcvars32.bat")
elif vernum >= 15:
pdir = os.path.join(pdir, "Auxiliary", "Build")
batfilename = os.path.join(pdir, "vcvarsall.bat")
else: # >= 8
batfilename = os.path.join(pdir, "vcvarsall.bat")
if not os.path.exists(batfilename):
debug("Not found: %s" % batfilename)
batfilename = None
installed_sdks=get_installed_sdks()
for _sdk in installed_sdks:
sdk_bat_file = _sdk.get_sdk_vc_script(host_arch,target_arch)
if not sdk_bat_file:
debug("vc.py:find_batch_file() not found:%s"%_sdk)
else:
sdk_bat_file_path = os.path.join(pdir,sdk_bat_file)
if os.path.exists(sdk_bat_file_path):
debug('vc.py:find_batch_file() sdk_bat_file_path:%s'%sdk_bat_file_path)
return (batfilename,sdk_bat_file_path)
return (batfilename,None)
__INSTALLED_VCS_RUN = None
def cached_get_installed_vcs():
global __INSTALLED_VCS_RUN
if __INSTALLED_VCS_RUN is None:
ret = get_installed_vcs()
__INSTALLED_VCS_RUN = ret
return __INSTALLED_VCS_RUN
def get_installed_vcs():
installed_versions = []
for ver in _VCVER:
debug('trying to find VC %s' % ver)
try:
if find_vc_pdir(ver):
debug('found VC %s' % ver)
installed_versions.append(ver)
else:
debug('find_vc_pdir return None for ver %s' % ver)
except VisualCException, e:
debug('did not find VC %s: caught exception %s' % (ver, str(e)))
return installed_versions
def reset_installed_vcs():
"""Make it try again to find VC. This is just for the tests."""
__INSTALLED_VCS_RUN = None
# Running these batch files isn't cheap: most of the time spent in
# msvs.generate() is due to vcvars*.bat. In a build that uses "tools='msvs'"
# in multiple environments, for example:
# env1 = Environment(tools='msvs')
# env2 = Environment(tools='msvs')
# we can greatly improve the speed of the second and subsequent Environment
# (or Clone) calls by memoizing the environment variables set by vcvars*.bat.
script_env_stdout_cache = {}
def script_env(script, args=None):
cache_key = (script, args)
stdout = script_env_stdout_cache.get(cache_key, None)
if stdout is None:
stdout = common.get_output(script, args)
script_env_stdout_cache[cache_key] = stdout
# Stupid batch files do not set return code: we take a look at the
# beginning of the output for an error message instead
olines = stdout.splitlines()
if olines[0].startswith("The specified configuration type is missing"):
raise BatchFileExecutionError("\n".join(olines[:2]))
return common.parse_output(stdout)
def get_default_version(env):
debug('get_default_version()')
msvc_version = env.get('MSVC_VERSION')
msvs_version = env.get('MSVS_VERSION')
debug('get_default_version(): msvc_version:%s msvs_version:%s'%(msvc_version,msvs_version))
if msvs_version and not msvc_version:
SCons.Warnings.warn(
SCons.Warnings.DeprecatedWarning,
"MSVS_VERSION is deprecated: please use MSVC_VERSION instead ")
return msvs_version
elif msvc_version and msvs_version:
if not msvc_version == msvs_version:
SCons.Warnings.warn(
SCons.Warnings.VisualVersionMismatch,
"Requested msvc version (%s) and msvs version (%s) do " \
"not match: please use MSVC_VERSION only to request a " \
"visual studio version, MSVS_VERSION is deprecated" \
% (msvc_version, msvs_version))
return msvs_version
if not msvc_version:
installed_vcs = cached_get_installed_vcs()
debug('installed_vcs:%s' % installed_vcs)
if not installed_vcs:
#msg = 'No installed VCs'
#debug('msv %s\n' % repr(msg))
#SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, msg)
debug('msvc_setup_env: No installed VCs')
return None
msvc_version = installed_vcs[0]
debug('msvc_setup_env: using default installed MSVC version %s\n' % repr(msvc_version))
return msvc_version
def msvc_setup_env_once(env):
try:
has_run = env["MSVC_SETUP_RUN"]
except KeyError:
has_run = False
if not has_run:
msvc_setup_env(env)
env["MSVC_SETUP_RUN"] = True
def msvc_find_valid_batch_script(env,version):
debug('vc.py:msvc_find_valid_batch_script()')
# Find the host platform, target platform, and if present the requested
# target platform
(host_platform, target_platform,req_target_platform) = get_host_target(env)
try_target_archs = [target_platform]
debug("msvs_find_valid_batch_script(): req_target_platform %s target_platform:%s"%(req_target_platform,target_platform))
# VS2012 has a "cross compile" environment to build 64 bit
# with x86_amd64 as the argument to the batch setup script
if req_target_platform in ('amd64','x86_64'):
try_target_archs.append('x86_amd64')
elif not req_target_platform and target_platform in ['amd64','x86_64']:
# There may not be "native" amd64, but maybe "cross" x86_amd64 tools
try_target_archs.append('x86_amd64')
# If the user hasn't specifically requested a TARGET_ARCH, and
# The TARGET_ARCH is amd64 then also try 32 bits if there are no viable
# 64 bit tools installed
try_target_archs.append('x86') |
debug("msvs_find_valid_batch_script(): host_platform: %s try_target_archs:%s"%(host_platform, try_target_archs))
d = None
for tp in try_target_archs:
# Set to current arch.
env['TARGET_ARCH']=tp
debug("vc.py:msvc_find_valid_batch_script() trying target_platform:%s"%tp)
host_target = (host_platform, tp)
if not is_host_target_supported(host_target, version):
warn_msg = "host, target = %s not supported for MSVC version %s" % \
(host_target, version)
SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
arg = _HOST_TARGET_ARCH_TO_BAT_ARCH[host_target]
# Try to locate a batch file for this host/target platform combo
try:
(vc_script,sdk_script) = find_batch_file(env,version,host_platform,tp)
debug('vc.py:msvc_find_valid_batch_script() vc_script:%s sdk_script:%s'%(vc_script,sdk_script))
except VisualCException, e:
msg = str(e)
debug('Caught exception while looking for batch file (%s)' % msg)
warn_msg = "VC version %s not installed. " + \
"C/C++ compilers are most likely not set correctly.\n" + \
" Installed versions are: %s"
warn_msg = warn_msg % (version, cached_get_installed_vcs())
SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
continue
# Try to use the located batch file for this host/target platform combo
debug('vc.py:msvc_find_valid_batch_script() use_script 2 %s, args:%s\n' % (repr(vc_script), arg))
if vc_script:
try:
d = script_env(vc_script, args=arg)
except BatchFileExecutionError, e:
debug('vc.py:msvc_find_valid_batch_script() use_script 3: failed running VC script %s: %s: Error:%s'%(repr(vc_script),arg,e))
vc_script=None
continue
if not vc_script and sdk_script:
debug('vc.py:msvc_find_valid_batch_script() use_script 4: trying sdk script: %s'%(sdk_script))
try:
d = script_env(sdk_script)
except BatchFileExecutionError,e:
debug('vc.py:msvc_find_valid_batch_script() use_script 5: failed running SDK script %s: Error:%s'%(repr(sdk_script),e))
continue
elif not vc_script and not sdk_script:
debug('vc.py:msvc_find_valid_batch_script() use_script 6: Neither VC script nor SDK script found')
continue
debug("vc.py:msvc_find_valid_batch_script() Found a working script/target: %s %s"%(repr(sdk_script),arg))
break # We've found a working target_platform, so stop looking
# If we cannot find a viable installed compiler, reset the TARGET_ARCH
# To it's initial value
if not d:
env['TARGET_ARCH']=req_target_platform
return d
def msvc_setup_env(env):
debug('msvc_setup_env()')
version = get_default_version(env)
if version is None:
warn_msg = "No version of Visual Studio compiler found - C/C++ " \
"compilers most likely not set correctly"
# Nuitka: Useless warning for us.
# SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
return None
debug('msvc_setup_env: using specified MSVC version %s\n' % repr(version))
# XXX: we set-up both MSVS version for backward
# compatibility with the msvs tool
env['MSVC_VERSION'] = version
env['MSVS_VERSION'] = version
env['MSVS'] = {}
use_script = env.get('MSVC_USE_SCRIPT', True)
if SCons.Util.is_String(use_script):
debug('vc.py:msvc_setup_env() use_script 1 %s\n' % repr(use_script))
d = script_env(use_script)
elif use_script:
d = msvc_find_valid_batch_script(env,version)
debug('vc.py:msvc_setup_env() use_script 2 %s\n' % d)
if not d:
return d
else:
debug('MSVC_USE_SCRIPT set to False')
warn_msg = "MSVC_USE_SCRIPT set to False, assuming environment " \
"set correctly."
# Nuitka: We use this on purpose.
# SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
return None
for k, v in d.items():
debug('vc.py:msvc_setup_env() env:%s -> %s'%(k,v))
env.PrependENVPath(k, v, delete_existing=True)
def msvc_exists(version=None):
vcs = cached_get_installed_vcs()
if version is None:
return len(vcs) > 0
return version in vcs | random_line_split | |
vc.py | #
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# 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.
#
# TODO:
# * supported arch for versions: for old versions of batch file without
# argument, giving bogus argument cannot be detected, so we have to hardcode
# this here
# * print warning when msvc version specified but not found
# * find out why warning do not print
# * test on 64 bits XP + VS 2005 (and VS 6 if possible)
# * SDK
# * Assembly
__revision__ = "src/engine/SCons/Tool/MSCommon/vc.py rel_2.3.5:3329:275e75118ad4 2015/06/20 11:18:26 bdbaddog"
__doc__ = """Module for Visual C/C++ detection and configuration.
"""
import SCons.compat
import os
import platform
from string import digits as string_digits
import SCons.Warnings
import common
debug = common.debug
import sdk
get_installed_sdks = sdk.get_installed_sdks
class VisualCException(Exception):
pass
class UnsupportedVersion(VisualCException):
pass
class UnsupportedArch(VisualCException):
pass
class MissingConfiguration(VisualCException):
pass
class NoVersionFound(VisualCException):
|
class BatchFileExecutionError(VisualCException):
pass
# Dict to 'canonalize' the arch
_ARCH_TO_CANONICAL = {
"amd64" : "amd64",
"emt64" : "amd64",
"i386" : "x86",
"i486" : "x86",
"i586" : "x86",
"i686" : "x86",
"ia64" : "ia64",
"itanium" : "ia64",
"x86" : "x86",
"x86_64" : "amd64",
"x86_amd64" : "x86_amd64", # Cross compile to 64 bit from 32bits
}
# Given a (host, target) tuple, return the argument for the bat file. Both host
# and targets should be canonalized.
_HOST_TARGET_ARCH_TO_BAT_ARCH = {
("x86", "x86"): "x86",
("x86", "amd64"): "x86_amd64",
("x86", "x86_amd64"): "x86_amd64",
("amd64", "x86_amd64"): "x86_amd64", # This is present in (at least) VS2012 express
("amd64", "amd64"): "amd64",
("amd64", "x86"): "x86",
("x86", "ia64"): "x86_ia64"
}
def get_host_target(env):
debug('vc.py:get_host_target()')
host_platform = env.get('HOST_ARCH')
if not host_platform:
host_platform = platform.machine()
# TODO(2.5): the native Python platform.machine() function returns
# '' on all Python versions before 2.6, after which it also uses
# PROCESSOR_ARCHITECTURE.
if not host_platform:
host_platform = os.environ.get('PROCESSOR_ARCHITECTURE', '')
# Retain user requested TARGET_ARCH
req_target_platform = env.get('TARGET_ARCH')
debug('vc.py:get_host_target() req_target_platform:%s'%req_target_platform)
if req_target_platform:
# If user requested a specific platform then only try that one.
target_platform = req_target_platform
else:
target_platform = host_platform
try:
host = _ARCH_TO_CANONICAL[host_platform.lower()]
except KeyError, e:
msg = "Unrecognized host architecture %s"
raise ValueError(msg % repr(host_platform))
try:
target = _ARCH_TO_CANONICAL[target_platform.lower()]
except KeyError, e:
all_archs = str(_ARCH_TO_CANONICAL.keys())
raise ValueError("Unrecognized target architecture %s\n\tValid architectures: %s" % (target_platform, all_archs))
return (host, target,req_target_platform)
# If you update this, update SupportedVSList in Tool/MSCommon/vs.py, and the
# MSVC_VERSION documentation in Tool/msvc.xml.
_VCVER = ["15.0", "14.0", "14.0Exp", "12.0", "12.0Exp", "11.0", "11.0Exp", "10.0", "10.0Exp", "9.0", "9.0Exp","8.0", "8.0Exp","7.1", "7.0", "6.0"]
_VCVER_TO_PRODUCT_DIR = {
'15.0' : [
r'Microsoft\VisualStudio\SxS\VS7\15.0'],
'14.0' : [
r'Microsoft\VisualStudio\14.0\Setup\VC\ProductDir'],
'14.0' : [
r'Microsoft\VisualStudio\14.0\Setup\VC\ProductDir'],
'12.0' : [
r'Microsoft\VisualStudio\12.0\Setup\VC\ProductDir'],
'12.0Exp' : [
r'Microsoft\VCExpress\12.0\Setup\VC\ProductDir'],
'11.0': [
r'Microsoft\VisualStudio\11.0\Setup\VC\ProductDir'],
'11.0Exp' : [
r'Microsoft\VCExpress\11.0\Setup\VC\ProductDir'],
'10.0': [
r'Microsoft\VisualStudio\10.0\Setup\VC\ProductDir'],
'10.0Exp' : [
r'Microsoft\VCExpress\10.0\Setup\VC\ProductDir'],
'9.0': [
r'Microsoft\VisualStudio\9.0\Setup\VC\ProductDir'],
'9.0Exp' : [
r'Microsoft\VCExpress\9.0\Setup\VC\ProductDir'],
'8.0': [
r'Microsoft\VisualStudio\8.0\Setup\VC\ProductDir'],
'8.0Exp': [
r'Microsoft\VCExpress\8.0\Setup\VC\ProductDir'],
'7.1': [
r'Microsoft\VisualStudio\7.1\Setup\VC\ProductDir'],
'7.0': [
r'Microsoft\VisualStudio\7.0\Setup\VC\ProductDir'],
'6.0': [
r'Microsoft\VisualStudio\6.0\Setup\Microsoft Visual C++\ProductDir']
}
def msvc_version_to_maj_min(msvc_version):
msvc_version_numeric = ''.join([x for x in msvc_version if x in string_digits + '.'])
t = msvc_version_numeric.split(".")
if not len(t) == 2:
raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
try:
maj = int(t[0])
min = int(t[1])
return maj, min
except ValueError, e:
raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
def is_host_target_supported(host_target, msvc_version):
"""Return True if the given (host, target) tuple is supported given the
msvc version.
Parameters
----------
host_target: tuple
tuple of (canonalized) host-target, e.g. ("x86", "amd64") for cross
compilation from 32 bits windows to 64 bits.
msvc_version: str
msvc version (major.minor, e.g. 10.0)
Note
----
This only check whether a given version *may* support the given (host,
target), not that the toolchain is actually present on the machine.
"""
# We assume that any Visual Studio version supports x86 as a target
if host_target[1] != "x86":
maj, min = msvc_version_to_maj_min(msvc_version)
if maj < 8:
return False
return True
def find_vc_pdir(msvc_version):
"""Try to find the product directory for the given
version.
Note
----
If for some reason the requested version could not be found, an
exception which inherits from VisualCException will be raised."""
root = 'Software\\'
if common.is_win64():
root = root + 'Wow6432Node\\'
try:
hkeys = _VCVER_TO_PRODUCT_DIR[msvc_version]
except KeyError:
debug("Unknown version of MSVC: %s" % msvc_version)
raise UnsupportedVersion("Unknown version %s" % msvc_version)
for key in hkeys:
key = root + key
try:
comps = common.read_reg(key)
except WindowsError, e:
debug('find_vc_dir(): no VC registry key %s' % repr(key))
else:
debug('find_vc_dir(): found VC in registry: %s' % comps)
if msvc_version == "15.0":
comps = os.path.join(comps, "VC")
if os.path.exists(comps):
return comps
else:
debug('find_vc_dir(): reg says dir is %s, but it does not exist. (ignoring)'\
% comps)
raise MissingConfiguration("registry dir %s not found on the filesystem" % comps)
return None
def find_batch_file(env,msvc_version,host_arch,target_arch):
"""
Find the location of the batch script which should set up the compiler
for any TARGET_ARCH whose compilers were installed by Visual Studio/VCExpress
"""
pdir = find_vc_pdir(msvc_version)
if pdir is None:
raise NoVersionFound("No version of Visual Studio found")
debug('vc.py: find_batch_file() pdir:%s'%pdir)
# filter out e.g. "Exp" from the version name
msvc_ver_numeric = ''.join([x for x in msvc_version if x in string_digits + "."])
vernum = float(msvc_ver_numeric)
if 7 <= vernum < 8:
pdir = os.path.join(pdir, os.pardir, "Common7", "Tools")
batfilename = os.path.join(pdir, "vsvars32.bat")
elif vernum < 7:
pdir = os.path.join(pdir, "Bin")
batfilename = os.path.join(pdir, "vcvars32.bat")
elif vernum >= 15:
pdir = os.path.join(pdir, "Auxiliary", "Build")
batfilename = os.path.join(pdir, "vcvarsall.bat")
else: # >= 8
batfilename = os.path.join(pdir, "vcvarsall.bat")
if not os.path.exists(batfilename):
debug("Not found: %s" % batfilename)
batfilename = None
installed_sdks=get_installed_sdks()
for _sdk in installed_sdks:
sdk_bat_file = _sdk.get_sdk_vc_script(host_arch,target_arch)
if not sdk_bat_file:
debug("vc.py:find_batch_file() not found:%s"%_sdk)
else:
sdk_bat_file_path = os.path.join(pdir,sdk_bat_file)
if os.path.exists(sdk_bat_file_path):
debug('vc.py:find_batch_file() sdk_bat_file_path:%s'%sdk_bat_file_path)
return (batfilename,sdk_bat_file_path)
return (batfilename,None)
__INSTALLED_VCS_RUN = None
def cached_get_installed_vcs():
global __INSTALLED_VCS_RUN
if __INSTALLED_VCS_RUN is None:
ret = get_installed_vcs()
__INSTALLED_VCS_RUN = ret
return __INSTALLED_VCS_RUN
def get_installed_vcs():
installed_versions = []
for ver in _VCVER:
debug('trying to find VC %s' % ver)
try:
if find_vc_pdir(ver):
debug('found VC %s' % ver)
installed_versions.append(ver)
else:
debug('find_vc_pdir return None for ver %s' % ver)
except VisualCException, e:
debug('did not find VC %s: caught exception %s' % (ver, str(e)))
return installed_versions
def reset_installed_vcs():
"""Make it try again to find VC. This is just for the tests."""
__INSTALLED_VCS_RUN = None
# Running these batch files isn't cheap: most of the time spent in
# msvs.generate() is due to vcvars*.bat. In a build that uses "tools='msvs'"
# in multiple environments, for example:
# env1 = Environment(tools='msvs')
# env2 = Environment(tools='msvs')
# we can greatly improve the speed of the second and subsequent Environment
# (or Clone) calls by memoizing the environment variables set by vcvars*.bat.
script_env_stdout_cache = {}
def script_env(script, args=None):
cache_key = (script, args)
stdout = script_env_stdout_cache.get(cache_key, None)
if stdout is None:
stdout = common.get_output(script, args)
script_env_stdout_cache[cache_key] = stdout
# Stupid batch files do not set return code: we take a look at the
# beginning of the output for an error message instead
olines = stdout.splitlines()
if olines[0].startswith("The specified configuration type is missing"):
raise BatchFileExecutionError("\n".join(olines[:2]))
return common.parse_output(stdout)
def get_default_version(env):
debug('get_default_version()')
msvc_version = env.get('MSVC_VERSION')
msvs_version = env.get('MSVS_VERSION')
debug('get_default_version(): msvc_version:%s msvs_version:%s'%(msvc_version,msvs_version))
if msvs_version and not msvc_version:
SCons.Warnings.warn(
SCons.Warnings.DeprecatedWarning,
"MSVS_VERSION is deprecated: please use MSVC_VERSION instead ")
return msvs_version
elif msvc_version and msvs_version:
if not msvc_version == msvs_version:
SCons.Warnings.warn(
SCons.Warnings.VisualVersionMismatch,
"Requested msvc version (%s) and msvs version (%s) do " \
"not match: please use MSVC_VERSION only to request a " \
"visual studio version, MSVS_VERSION is deprecated" \
% (msvc_version, msvs_version))
return msvs_version
if not msvc_version:
installed_vcs = cached_get_installed_vcs()
debug('installed_vcs:%s' % installed_vcs)
if not installed_vcs:
#msg = 'No installed VCs'
#debug('msv %s\n' % repr(msg))
#SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, msg)
debug('msvc_setup_env: No installed VCs')
return None
msvc_version = installed_vcs[0]
debug('msvc_setup_env: using default installed MSVC version %s\n' % repr(msvc_version))
return msvc_version
def msvc_setup_env_once(env):
try:
has_run = env["MSVC_SETUP_RUN"]
except KeyError:
has_run = False
if not has_run:
msvc_setup_env(env)
env["MSVC_SETUP_RUN"] = True
def msvc_find_valid_batch_script(env,version):
debug('vc.py:msvc_find_valid_batch_script()')
# Find the host platform, target platform, and if present the requested
# target platform
(host_platform, target_platform,req_target_platform) = get_host_target(env)
try_target_archs = [target_platform]
debug("msvs_find_valid_batch_script(): req_target_platform %s target_platform:%s"%(req_target_platform,target_platform))
# VS2012 has a "cross compile" environment to build 64 bit
# with x86_amd64 as the argument to the batch setup script
if req_target_platform in ('amd64','x86_64'):
try_target_archs.append('x86_amd64')
elif not req_target_platform and target_platform in ['amd64','x86_64']:
# There may not be "native" amd64, but maybe "cross" x86_amd64 tools
try_target_archs.append('x86_amd64')
# If the user hasn't specifically requested a TARGET_ARCH, and
# The TARGET_ARCH is amd64 then also try 32 bits if there are no viable
# 64 bit tools installed
try_target_archs.append('x86')
debug("msvs_find_valid_batch_script(): host_platform: %s try_target_archs:%s"%(host_platform, try_target_archs))
d = None
for tp in try_target_archs:
# Set to current arch.
env['TARGET_ARCH']=tp
debug("vc.py:msvc_find_valid_batch_script() trying target_platform:%s"%tp)
host_target = (host_platform, tp)
if not is_host_target_supported(host_target, version):
warn_msg = "host, target = %s not supported for MSVC version %s" % \
(host_target, version)
SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
arg = _HOST_TARGET_ARCH_TO_BAT_ARCH[host_target]
# Try to locate a batch file for this host/target platform combo
try:
(vc_script,sdk_script) = find_batch_file(env,version,host_platform,tp)
debug('vc.py:msvc_find_valid_batch_script() vc_script:%s sdk_script:%s'%(vc_script,sdk_script))
except VisualCException, e:
msg = str(e)
debug('Caught exception while looking for batch file (%s)' % msg)
warn_msg = "VC version %s not installed. " + \
"C/C++ compilers are most likely not set correctly.\n" + \
" Installed versions are: %s"
warn_msg = warn_msg % (version, cached_get_installed_vcs())
SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
continue
# Try to use the located batch file for this host/target platform combo
debug('vc.py:msvc_find_valid_batch_script() use_script 2 %s, args:%s\n' % (repr(vc_script), arg))
if vc_script:
try:
d = script_env(vc_script, args=arg)
except BatchFileExecutionError, e:
debug('vc.py:msvc_find_valid_batch_script() use_script 3: failed running VC script %s: %s: Error:%s'%(repr(vc_script),arg,e))
vc_script=None
continue
if not vc_script and sdk_script:
debug('vc.py:msvc_find_valid_batch_script() use_script 4: trying sdk script: %s'%(sdk_script))
try:
d = script_env(sdk_script)
except BatchFileExecutionError,e:
debug('vc.py:msvc_find_valid_batch_script() use_script 5: failed running SDK script %s: Error:%s'%(repr(sdk_script),e))
continue
elif not vc_script and not sdk_script:
debug('vc.py:msvc_find_valid_batch_script() use_script 6: Neither VC script nor SDK script found')
continue
debug("vc.py:msvc_find_valid_batch_script() Found a working script/target: %s %s"%(repr(sdk_script),arg))
break # We've found a working target_platform, so stop looking
# If we cannot find a viable installed compiler, reset the TARGET_ARCH
# To it's initial value
if not d:
env['TARGET_ARCH']=req_target_platform
return d
def msvc_setup_env(env):
debug('msvc_setup_env()')
version = get_default_version(env)
if version is None:
warn_msg = "No version of Visual Studio compiler found - C/C++ " \
"compilers most likely not set correctly"
# Nuitka: Useless warning for us.
# SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
return None
debug('msvc_setup_env: using specified MSVC version %s\n' % repr(version))
# XXX: we set-up both MSVS version for backward
# compatibility with the msvs tool
env['MSVC_VERSION'] = version
env['MSVS_VERSION'] = version
env['MSVS'] = {}
use_script = env.get('MSVC_USE_SCRIPT', True)
if SCons.Util.is_String(use_script):
debug('vc.py:msvc_setup_env() use_script 1 %s\n' % repr(use_script))
d = script_env(use_script)
elif use_script:
d = msvc_find_valid_batch_script(env,version)
debug('vc.py:msvc_setup_env() use_script 2 %s\n' % d)
if not d:
return d
else:
debug('MSVC_USE_SCRIPT set to False')
warn_msg = "MSVC_USE_SCRIPT set to False, assuming environment " \
"set correctly."
# Nuitka: We use this on purpose.
# SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
return None
for k, v in d.items():
debug('vc.py:msvc_setup_env() env:%s -> %s'%(k,v))
env.PrependENVPath(k, v, delete_existing=True)
def msvc_exists(version=None):
vcs = cached_get_installed_vcs()
if version is None:
return len(vcs) > 0
return version in vcs
| pass | identifier_body |
SelectEventPlugin-test.js | /**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
var React;
var ReactDOM;
var ReactDOMComponentTree;
var ReactTestUtils;
var SelectEventPlugin;
describe('SelectEventPlugin', () => {
function extract(node, topLevelEvent) {
return SelectEventPlugin.extractEvents(
topLevelEvent,
ReactDOMComponentTree.getInstanceFromNode(node),
{target: node},
node,
);
}
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
ReactTestUtils = require('react-dom/test-utils');
// TODO: can we express this test with only public API?
ReactDOMComponentTree = require('../../client/ReactDOMComponentTree')
.default;
SelectEventPlugin = require('../SelectEventPlugin').default;
});
it('should skip extraction if no listeners are present', () => {
class WithoutSelect extends React.Component {
render() {
return <input type="text" />;
}
}
var rendered = ReactTestUtils.renderIntoDocument(<WithoutSelect />);
var node = ReactDOM.findDOMNode(rendered);
node.focus();
// It seems that .focus() isn't triggering this event in our test
// environment so we need to ensure it gets set for this test to be valid.
var fakeNativeEvent = function() {};
fakeNativeEvent.target = node;
ReactTestUtils.simulateNativeEventOnNode('topFocus', node, fakeNativeEvent);
var mousedown = extract(node, 'topMouseDown');
expect(mousedown).toBe(null);
var mouseup = extract(node, 'topMouseUp');
expect(mouseup).toBe(null);
});
it('should extract if an `onSelect` listener is present', () => { |
var cb = jest.fn();
var rendered = ReactTestUtils.renderIntoDocument(
<WithSelect onSelect={cb} />,
);
var node = ReactDOM.findDOMNode(rendered);
node.selectionStart = 0;
node.selectionEnd = 0;
node.focus();
var focus = extract(node, 'topFocus');
expect(focus).toBe(null);
var mousedown = extract(node, 'topMouseDown');
expect(mousedown).toBe(null);
var mouseup = extract(node, 'topMouseUp');
expect(mouseup).not.toBe(null);
expect(typeof mouseup).toBe('object');
expect(mouseup.type).toBe('select');
expect(mouseup.target).toBe(node);
});
}); | class WithSelect extends React.Component {
render() {
return <input type="text" onSelect={this.props.onSelect} />;
}
} | random_line_split |
SelectEventPlugin-test.js | /**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
var React;
var ReactDOM;
var ReactDOMComponentTree;
var ReactTestUtils;
var SelectEventPlugin;
describe('SelectEventPlugin', () => {
function extract(node, topLevelEvent) {
return SelectEventPlugin.extractEvents(
topLevelEvent,
ReactDOMComponentTree.getInstanceFromNode(node),
{target: node},
node,
);
}
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
ReactTestUtils = require('react-dom/test-utils');
// TODO: can we express this test with only public API?
ReactDOMComponentTree = require('../../client/ReactDOMComponentTree')
.default;
SelectEventPlugin = require('../SelectEventPlugin').default;
});
it('should skip extraction if no listeners are present', () => {
class | extends React.Component {
render() {
return <input type="text" />;
}
}
var rendered = ReactTestUtils.renderIntoDocument(<WithoutSelect />);
var node = ReactDOM.findDOMNode(rendered);
node.focus();
// It seems that .focus() isn't triggering this event in our test
// environment so we need to ensure it gets set for this test to be valid.
var fakeNativeEvent = function() {};
fakeNativeEvent.target = node;
ReactTestUtils.simulateNativeEventOnNode('topFocus', node, fakeNativeEvent);
var mousedown = extract(node, 'topMouseDown');
expect(mousedown).toBe(null);
var mouseup = extract(node, 'topMouseUp');
expect(mouseup).toBe(null);
});
it('should extract if an `onSelect` listener is present', () => {
class WithSelect extends React.Component {
render() {
return <input type="text" onSelect={this.props.onSelect} />;
}
}
var cb = jest.fn();
var rendered = ReactTestUtils.renderIntoDocument(
<WithSelect onSelect={cb} />,
);
var node = ReactDOM.findDOMNode(rendered);
node.selectionStart = 0;
node.selectionEnd = 0;
node.focus();
var focus = extract(node, 'topFocus');
expect(focus).toBe(null);
var mousedown = extract(node, 'topMouseDown');
expect(mousedown).toBe(null);
var mouseup = extract(node, 'topMouseUp');
expect(mouseup).not.toBe(null);
expect(typeof mouseup).toBe('object');
expect(mouseup.type).toBe('select');
expect(mouseup.target).toBe(node);
});
});
| WithoutSelect | identifier_name |
executor.rs | use serde::{Serialize, Deserialize};
use std::mem;
use std::fmt::Debug;
use std::sync::mpsc::{Sender, Receiver};
use std::collections::HashMap;
use amy;
use slog;
use time::Duration;
use ferris::{Wheel, CopyWheel, Resolution};
use envelope::Envelope;
use pid::Pid;
use process::Process;
use node_id::NodeId;
use msg::Msg;
use cluster::ClusterMsg;
use correlation_id::CorrelationId;
use metrics::Metrics;
use super::{ExecutorStatus, ExecutorMetrics, ExecutorMsg};
pub struct | <T> {
pid: Pid,
node: NodeId,
envelopes: Vec<Envelope<T>>,
processes: HashMap<Pid, Box<Process<T>>>,
service_senders: HashMap<Pid, amy::Sender<Envelope<T>>>,
tx: Sender<ExecutorMsg<T>>,
rx: Receiver<ExecutorMsg<T>>,
cluster_tx: Sender<ClusterMsg<T>>,
timer_wheel: CopyWheel<(Pid, Option<CorrelationId>)>,
logger: slog::Logger,
metrics: ExecutorMetrics
}
impl<'de, T: Serialize + Deserialize<'de> + Send + Debug + Clone> Executor<T> {
pub fn new(node: NodeId,
tx: Sender<ExecutorMsg<T>>,
rx: Receiver<ExecutorMsg<T>>,
cluster_tx: Sender<ClusterMsg<T>>,
logger: slog::Logger) -> Executor<T> {
let pid = Pid {
group: Some("rabble".to_string()),
name: "executor".to_string(),
node: node.clone()
};
Executor {
pid: pid,
node: node,
envelopes: Vec::new(),
processes: HashMap::new(),
service_senders: HashMap::new(),
tx: tx,
rx: rx,
cluster_tx: cluster_tx,
timer_wheel: CopyWheel::new(vec![Resolution::TenMs, Resolution::Sec, Resolution::Min]),
logger: logger.new(o!("component" => "executor")),
metrics: ExecutorMetrics::new()
}
}
/// Run the executor
///
///This call blocks the current thread indefinitely.
pub fn run(mut self) {
while let Ok(msg) = self.rx.recv() {
match msg {
ExecutorMsg::Envelope(envelope) => {
self.metrics.received_envelopes += 1;
self.route(envelope);
},
ExecutorMsg::Start(pid, process) => self.start(pid, process),
ExecutorMsg::Stop(pid) => self.stop(pid),
ExecutorMsg::RegisterService(pid, tx) => {
self.service_senders.insert(pid, tx);
},
ExecutorMsg::GetStatus(correlation_id) => self.get_status(correlation_id),
ExecutorMsg::Tick => self.tick(),
// Just return so the thread exits
ExecutorMsg::Shutdown => return
}
}
}
fn get_status(&self, correlation_id: CorrelationId) {
let status = ExecutorStatus {
total_processes: self.processes.len(),
services: self.service_senders.keys().cloned().collect()
};
let envelope = Envelope {
to: correlation_id.pid.clone(),
from: self.pid.clone(),
msg: Msg::ExecutorStatus(status),
correlation_id: Some(correlation_id)
};
self.route_to_service(envelope);
}
fn start(&mut self, pid: Pid, mut process: Box<Process<T>>) {
let envelopes = process.init(self.pid.clone());
self.processes.insert(pid, process);
for envelope in envelopes {
if envelope.to == self.pid {
self.handle_executor_envelope(envelope);
} else {
self.route(envelope);
}
}
}
fn stop(&mut self, pid: Pid) {
self.processes.remove(&pid);
}
fn tick(&mut self) {
for (pid, c_id) in self.timer_wheel.expire() {
let envelope = Envelope::new(pid, self.pid.clone(), Msg::Timeout, c_id);
let _ = self.route_to_process(envelope);
}
}
/// Route envelopes to local or remote processes
///
/// Retrieve any envelopes from processes handling local messages and put them on either the
/// executor or the cluster channel depending upon whether they are local or remote.
///
/// Note that all envelopes sent to an executor are sent from the local cluster server and must
/// be addressed to local processes.
fn route(&mut self, envelope: Envelope<T>) {
if self.node != envelope.to.node {
self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap();
return;
}
if let Err(envelope) = self.route_to_process(envelope) {
self.route_to_service(envelope);
}
}
/// Route an envelope to a process if it exists on this node.
///
/// Return Ok(()) if the process exists, Err(envelope) otherwise.
fn route_to_process(&mut self, envelope: Envelope<T>) -> Result<(), Envelope<T>> {
if envelope.to == self.pid {
self.handle_executor_envelope(envelope);
return Ok(());
}
if &envelope.to.name == "cluster_server" &&
envelope.to.group.as_ref().unwrap() == "rabble"
{
self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap();
return Ok(());
}
if let Some(process) = self.processes.get_mut(&envelope.to) {
let Envelope {from, msg, correlation_id, ..} = envelope;
process.handle(msg, from, correlation_id, &mut self.envelopes);
} else {
return Err(envelope);
};
// Take envelopes out of self temporarily so we don't get a borrowck error
let mut envelopes = mem::replace(&mut self.envelopes, Vec::new());
for envelope in envelopes.drain(..) {
if envelope.to == self.pid {
self.handle_executor_envelope(envelope);
continue;
}
if envelope.to.node == self.node {
// This won't ever fail because we hold a ref to both ends of the channel
self.tx.send(ExecutorMsg::Envelope(envelope)).unwrap();
} else {
self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap();
}
}
// Return the allocated vec back to self
let _ = mem::replace(&mut self.envelopes, envelopes);
Ok(())
}
/// Route an envelope to a service on this node
fn route_to_service(&self, envelope: Envelope<T>) {
if let Some(tx) = self.service_senders.get(&envelope.to) {
tx.send(envelope).unwrap();
} else {
warn!(self.logger, "Failed to find service"; "pid" => envelope.to.to_string());
}
}
fn handle_executor_envelope(&mut self, envelope: Envelope<T>) {
let Envelope {from, msg, correlation_id, ..} = envelope;
match msg {
Msg::StartTimer(time_in_ms) => {
self.timer_wheel.start((from, correlation_id),
Duration::milliseconds(time_in_ms as i64));
self.metrics.timers_started += 1;
},
Msg::CancelTimer(correlation_id) => {
self.timer_wheel.stop((from, correlation_id));
self.metrics.timers_cancelled += 1;
}
Msg::GetMetrics => self.send_metrics(from, correlation_id),
_ => error!(self.logger, "Invalid message sent to executor";
"from" => from.to_string(), "msg" => format!("{:?}", msg))
}
}
fn send_metrics(&mut self, from: Pid, correlation_id: Option<CorrelationId>) {
self.metrics.processes = self.processes.len() as i64;
self.metrics.services = self.service_senders.len() as i64;
let envelope = Envelope {
to: from,
from: self.pid.clone(),
msg: Msg::Metrics(self.metrics.data()),
correlation_id: correlation_id
};
self.route(envelope);
}
}
| Executor | identifier_name |
executor.rs | use serde::{Serialize, Deserialize};
use std::mem;
use std::fmt::Debug;
use std::sync::mpsc::{Sender, Receiver};
use std::collections::HashMap;
use amy;
use slog;
use time::Duration;
use ferris::{Wheel, CopyWheel, Resolution};
use envelope::Envelope;
use pid::Pid;
use process::Process;
use node_id::NodeId;
use msg::Msg;
use cluster::ClusterMsg;
use correlation_id::CorrelationId;
use metrics::Metrics;
use super::{ExecutorStatus, ExecutorMetrics, ExecutorMsg};
pub struct Executor<T> {
pid: Pid,
node: NodeId,
envelopes: Vec<Envelope<T>>,
processes: HashMap<Pid, Box<Process<T>>>,
service_senders: HashMap<Pid, amy::Sender<Envelope<T>>>,
tx: Sender<ExecutorMsg<T>>,
rx: Receiver<ExecutorMsg<T>>,
cluster_tx: Sender<ClusterMsg<T>>,
timer_wheel: CopyWheel<(Pid, Option<CorrelationId>)>,
logger: slog::Logger,
metrics: ExecutorMetrics
}
impl<'de, T: Serialize + Deserialize<'de> + Send + Debug + Clone> Executor<T> {
pub fn new(node: NodeId,
tx: Sender<ExecutorMsg<T>>,
rx: Receiver<ExecutorMsg<T>>,
cluster_tx: Sender<ClusterMsg<T>>,
logger: slog::Logger) -> Executor<T> {
let pid = Pid {
group: Some("rabble".to_string()),
name: "executor".to_string(),
node: node.clone()
};
Executor {
pid: pid,
node: node,
envelopes: Vec::new(),
processes: HashMap::new(),
service_senders: HashMap::new(),
tx: tx,
rx: rx,
cluster_tx: cluster_tx,
timer_wheel: CopyWheel::new(vec![Resolution::TenMs, Resolution::Sec, Resolution::Min]),
logger: logger.new(o!("component" => "executor")),
metrics: ExecutorMetrics::new()
}
}
/// Run the executor | match msg {
ExecutorMsg::Envelope(envelope) => {
self.metrics.received_envelopes += 1;
self.route(envelope);
},
ExecutorMsg::Start(pid, process) => self.start(pid, process),
ExecutorMsg::Stop(pid) => self.stop(pid),
ExecutorMsg::RegisterService(pid, tx) => {
self.service_senders.insert(pid, tx);
},
ExecutorMsg::GetStatus(correlation_id) => self.get_status(correlation_id),
ExecutorMsg::Tick => self.tick(),
// Just return so the thread exits
ExecutorMsg::Shutdown => return
}
}
}
fn get_status(&self, correlation_id: CorrelationId) {
let status = ExecutorStatus {
total_processes: self.processes.len(),
services: self.service_senders.keys().cloned().collect()
};
let envelope = Envelope {
to: correlation_id.pid.clone(),
from: self.pid.clone(),
msg: Msg::ExecutorStatus(status),
correlation_id: Some(correlation_id)
};
self.route_to_service(envelope);
}
fn start(&mut self, pid: Pid, mut process: Box<Process<T>>) {
let envelopes = process.init(self.pid.clone());
self.processes.insert(pid, process);
for envelope in envelopes {
if envelope.to == self.pid {
self.handle_executor_envelope(envelope);
} else {
self.route(envelope);
}
}
}
fn stop(&mut self, pid: Pid) {
self.processes.remove(&pid);
}
fn tick(&mut self) {
for (pid, c_id) in self.timer_wheel.expire() {
let envelope = Envelope::new(pid, self.pid.clone(), Msg::Timeout, c_id);
let _ = self.route_to_process(envelope);
}
}
/// Route envelopes to local or remote processes
///
/// Retrieve any envelopes from processes handling local messages and put them on either the
/// executor or the cluster channel depending upon whether they are local or remote.
///
/// Note that all envelopes sent to an executor are sent from the local cluster server and must
/// be addressed to local processes.
fn route(&mut self, envelope: Envelope<T>) {
if self.node != envelope.to.node {
self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap();
return;
}
if let Err(envelope) = self.route_to_process(envelope) {
self.route_to_service(envelope);
}
}
/// Route an envelope to a process if it exists on this node.
///
/// Return Ok(()) if the process exists, Err(envelope) otherwise.
fn route_to_process(&mut self, envelope: Envelope<T>) -> Result<(), Envelope<T>> {
if envelope.to == self.pid {
self.handle_executor_envelope(envelope);
return Ok(());
}
if &envelope.to.name == "cluster_server" &&
envelope.to.group.as_ref().unwrap() == "rabble"
{
self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap();
return Ok(());
}
if let Some(process) = self.processes.get_mut(&envelope.to) {
let Envelope {from, msg, correlation_id, ..} = envelope;
process.handle(msg, from, correlation_id, &mut self.envelopes);
} else {
return Err(envelope);
};
// Take envelopes out of self temporarily so we don't get a borrowck error
let mut envelopes = mem::replace(&mut self.envelopes, Vec::new());
for envelope in envelopes.drain(..) {
if envelope.to == self.pid {
self.handle_executor_envelope(envelope);
continue;
}
if envelope.to.node == self.node {
// This won't ever fail because we hold a ref to both ends of the channel
self.tx.send(ExecutorMsg::Envelope(envelope)).unwrap();
} else {
self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap();
}
}
// Return the allocated vec back to self
let _ = mem::replace(&mut self.envelopes, envelopes);
Ok(())
}
/// Route an envelope to a service on this node
fn route_to_service(&self, envelope: Envelope<T>) {
if let Some(tx) = self.service_senders.get(&envelope.to) {
tx.send(envelope).unwrap();
} else {
warn!(self.logger, "Failed to find service"; "pid" => envelope.to.to_string());
}
}
fn handle_executor_envelope(&mut self, envelope: Envelope<T>) {
let Envelope {from, msg, correlation_id, ..} = envelope;
match msg {
Msg::StartTimer(time_in_ms) => {
self.timer_wheel.start((from, correlation_id),
Duration::milliseconds(time_in_ms as i64));
self.metrics.timers_started += 1;
},
Msg::CancelTimer(correlation_id) => {
self.timer_wheel.stop((from, correlation_id));
self.metrics.timers_cancelled += 1;
}
Msg::GetMetrics => self.send_metrics(from, correlation_id),
_ => error!(self.logger, "Invalid message sent to executor";
"from" => from.to_string(), "msg" => format!("{:?}", msg))
}
}
fn send_metrics(&mut self, from: Pid, correlation_id: Option<CorrelationId>) {
self.metrics.processes = self.processes.len() as i64;
self.metrics.services = self.service_senders.len() as i64;
let envelope = Envelope {
to: from,
from: self.pid.clone(),
msg: Msg::Metrics(self.metrics.data()),
correlation_id: correlation_id
};
self.route(envelope);
}
} | ///
///This call blocks the current thread indefinitely.
pub fn run(mut self) {
while let Ok(msg) = self.rx.recv() { | random_line_split |
executor.rs | use serde::{Serialize, Deserialize};
use std::mem;
use std::fmt::Debug;
use std::sync::mpsc::{Sender, Receiver};
use std::collections::HashMap;
use amy;
use slog;
use time::Duration;
use ferris::{Wheel, CopyWheel, Resolution};
use envelope::Envelope;
use pid::Pid;
use process::Process;
use node_id::NodeId;
use msg::Msg;
use cluster::ClusterMsg;
use correlation_id::CorrelationId;
use metrics::Metrics;
use super::{ExecutorStatus, ExecutorMetrics, ExecutorMsg};
pub struct Executor<T> {
pid: Pid,
node: NodeId,
envelopes: Vec<Envelope<T>>,
processes: HashMap<Pid, Box<Process<T>>>,
service_senders: HashMap<Pid, amy::Sender<Envelope<T>>>,
tx: Sender<ExecutorMsg<T>>,
rx: Receiver<ExecutorMsg<T>>,
cluster_tx: Sender<ClusterMsg<T>>,
timer_wheel: CopyWheel<(Pid, Option<CorrelationId>)>,
logger: slog::Logger,
metrics: ExecutorMetrics
}
impl<'de, T: Serialize + Deserialize<'de> + Send + Debug + Clone> Executor<T> {
pub fn new(node: NodeId,
tx: Sender<ExecutorMsg<T>>,
rx: Receiver<ExecutorMsg<T>>,
cluster_tx: Sender<ClusterMsg<T>>,
logger: slog::Logger) -> Executor<T> {
let pid = Pid {
group: Some("rabble".to_string()),
name: "executor".to_string(),
node: node.clone()
};
Executor {
pid: pid,
node: node,
envelopes: Vec::new(),
processes: HashMap::new(),
service_senders: HashMap::new(),
tx: tx,
rx: rx,
cluster_tx: cluster_tx,
timer_wheel: CopyWheel::new(vec![Resolution::TenMs, Resolution::Sec, Resolution::Min]),
logger: logger.new(o!("component" => "executor")),
metrics: ExecutorMetrics::new()
}
}
/// Run the executor
///
///This call blocks the current thread indefinitely.
pub fn run(mut self) {
while let Ok(msg) = self.rx.recv() {
match msg {
ExecutorMsg::Envelope(envelope) => {
self.metrics.received_envelopes += 1;
self.route(envelope);
},
ExecutorMsg::Start(pid, process) => self.start(pid, process),
ExecutorMsg::Stop(pid) => self.stop(pid),
ExecutorMsg::RegisterService(pid, tx) => {
self.service_senders.insert(pid, tx);
},
ExecutorMsg::GetStatus(correlation_id) => self.get_status(correlation_id),
ExecutorMsg::Tick => self.tick(),
// Just return so the thread exits
ExecutorMsg::Shutdown => return
}
}
}
fn get_status(&self, correlation_id: CorrelationId) {
let status = ExecutorStatus {
total_processes: self.processes.len(),
services: self.service_senders.keys().cloned().collect()
};
let envelope = Envelope {
to: correlation_id.pid.clone(),
from: self.pid.clone(),
msg: Msg::ExecutorStatus(status),
correlation_id: Some(correlation_id)
};
self.route_to_service(envelope);
}
fn start(&mut self, pid: Pid, mut process: Box<Process<T>>) {
let envelopes = process.init(self.pid.clone());
self.processes.insert(pid, process);
for envelope in envelopes {
if envelope.to == self.pid {
self.handle_executor_envelope(envelope);
} else {
self.route(envelope);
}
}
}
fn stop(&mut self, pid: Pid) {
self.processes.remove(&pid);
}
fn tick(&mut self) |
/// Route envelopes to local or remote processes
///
/// Retrieve any envelopes from processes handling local messages and put them on either the
/// executor or the cluster channel depending upon whether they are local or remote.
///
/// Note that all envelopes sent to an executor are sent from the local cluster server and must
/// be addressed to local processes.
fn route(&mut self, envelope: Envelope<T>) {
if self.node != envelope.to.node {
self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap();
return;
}
if let Err(envelope) = self.route_to_process(envelope) {
self.route_to_service(envelope);
}
}
/// Route an envelope to a process if it exists on this node.
///
/// Return Ok(()) if the process exists, Err(envelope) otherwise.
fn route_to_process(&mut self, envelope: Envelope<T>) -> Result<(), Envelope<T>> {
if envelope.to == self.pid {
self.handle_executor_envelope(envelope);
return Ok(());
}
if &envelope.to.name == "cluster_server" &&
envelope.to.group.as_ref().unwrap() == "rabble"
{
self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap();
return Ok(());
}
if let Some(process) = self.processes.get_mut(&envelope.to) {
let Envelope {from, msg, correlation_id, ..} = envelope;
process.handle(msg, from, correlation_id, &mut self.envelopes);
} else {
return Err(envelope);
};
// Take envelopes out of self temporarily so we don't get a borrowck error
let mut envelopes = mem::replace(&mut self.envelopes, Vec::new());
for envelope in envelopes.drain(..) {
if envelope.to == self.pid {
self.handle_executor_envelope(envelope);
continue;
}
if envelope.to.node == self.node {
// This won't ever fail because we hold a ref to both ends of the channel
self.tx.send(ExecutorMsg::Envelope(envelope)).unwrap();
} else {
self.cluster_tx.send(ClusterMsg::Envelope(envelope)).unwrap();
}
}
// Return the allocated vec back to self
let _ = mem::replace(&mut self.envelopes, envelopes);
Ok(())
}
/// Route an envelope to a service on this node
fn route_to_service(&self, envelope: Envelope<T>) {
if let Some(tx) = self.service_senders.get(&envelope.to) {
tx.send(envelope).unwrap();
} else {
warn!(self.logger, "Failed to find service"; "pid" => envelope.to.to_string());
}
}
fn handle_executor_envelope(&mut self, envelope: Envelope<T>) {
let Envelope {from, msg, correlation_id, ..} = envelope;
match msg {
Msg::StartTimer(time_in_ms) => {
self.timer_wheel.start((from, correlation_id),
Duration::milliseconds(time_in_ms as i64));
self.metrics.timers_started += 1;
},
Msg::CancelTimer(correlation_id) => {
self.timer_wheel.stop((from, correlation_id));
self.metrics.timers_cancelled += 1;
}
Msg::GetMetrics => self.send_metrics(from, correlation_id),
_ => error!(self.logger, "Invalid message sent to executor";
"from" => from.to_string(), "msg" => format!("{:?}", msg))
}
}
fn send_metrics(&mut self, from: Pid, correlation_id: Option<CorrelationId>) {
self.metrics.processes = self.processes.len() as i64;
self.metrics.services = self.service_senders.len() as i64;
let envelope = Envelope {
to: from,
from: self.pid.clone(),
msg: Msg::Metrics(self.metrics.data()),
correlation_id: correlation_id
};
self.route(envelope);
}
}
| {
for (pid, c_id) in self.timer_wheel.expire() {
let envelope = Envelope::new(pid, self.pid.clone(), Msg::Timeout, c_id);
let _ = self.route_to_process(envelope);
}
} | identifier_body |
gcthread.rs | //! Garbage collection thread
use std::any::Any;
use std::cmp::min;
use std::mem::size_of;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use num_cpus;
use scoped_pool::Pool;
use appthread::AppThread;
use constants::{MAJOR_COLLECT_THRESHOLD, MAX_SLEEP_DUR, MIN_SLEEP_DUR};
use heap::{CollectOps, Object};
use journal;
use parheap::ParHeap;
use statistics::{StatsLogger, DefaultLogger};
use youngheap::YoungHeap;
pub type EntryReceiver = journal::Receiver<Object>;
pub type EntrySender = journal::Sender<Object>;
pub type JournalReceiver = mpsc::Receiver<EntryReceiver>;
pub type JournalSender = mpsc::Sender<EntryReceiver>;
pub type JournalList = Vec<EntryReceiver>;
/// The Garbage Collection thread handle.
pub struct GcThread<S: StatsLogger> {
/// This is cloned and given to app threads.
tx_chan: JournalSender,
/// The GC thread's handle to join on.
handle: thread::JoinHandle<S>,
}
impl GcThread<DefaultLogger> {
/// Spawn a GC thread with default parameters: a `ParHeap` and a `DefaultLogger` parallelized
/// across all available CPUs.
pub fn spawn_gc() -> GcThread<DefaultLogger> {
let cores = num_cpus::get();
Self::spawn_gc_with(cores, ParHeap::new(cores), DefaultLogger::new())
}
}
impl<S: StatsLogger + 'static> GcThread<S> {
/// Run the GC on the current thread, spawning another thread to run the application function
/// on. Returns the AppThread std::thread::Thread handle. Caller must provide a custom
/// StatsLogger implementation and a CollectOps heap implementation.
pub fn spawn_gc_with<T>(num_threads: usize, mature: T, logger: S) -> GcThread<S>
where T: CollectOps + Send + 'static
{
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || gc_thread(num_threads, rx, mature, logger));
GcThread {
tx_chan: tx,
handle: handle,
}
}
/// Spawn an app thread that journals to the GC thread.
pub fn spawn<F, T>(&self, f: F) -> thread::JoinHandle<T>
where F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static
{
AppThread::spawn_from_gc(self.tx_chan.clone(), f)
}
/// Wait for the GC thread to finish. On success, returns the object that implements
/// `StatsLogger` for the calling thread to examine.
pub fn join(self) -> Result<S, Box<Any + Send + 'static>> {
self.handle.join()
}
}
/// Main GC thread loop.
fn gc_thread<S, T>(num_threads: usize, rx_chan: JournalReceiver, mature: T, logger: S) -> S
where S: StatsLogger,
T: CollectOps + Send
{
let mut pool = Pool::new(num_threads);
let mut gc = YoungHeap::new(num_threads, mature, logger);
// block, wait for first journal
gc.add_journal(rx_chan.recv().expect("Failed to receive first app journal!"));
gc.logger().mark_start_time();
// next duration to sleep if all journals are empty
let mut sleep_dur: usize = 0;
// loop until all journals are disconnected
while gc.num_journals() > 0 {
// new appthread connected
if let Ok(journal) = rx_chan.try_recv() {
gc.add_journal(journal);
}
let entries_read = gc.read_journals();
// sleep if nothing read from journal
if entries_read == 0 {
thread::sleep(Duration::from_millis(sleep_dur as u64));
gc.logger().add_sleep(sleep_dur);
// back off exponentially up to the max
sleep_dur = min(sleep_dur * 2, MAX_SLEEP_DUR);
} else {
// reset next sleep duration on receiving no entries
sleep_dur = MIN_SLEEP_DUR;
}
// TODO: base this call on a duration since last call?
let young_count = gc.minor_collection(&mut pool);
// do a major collection if the young count reaches a threshold and we're not just trying
// to keep up with the app threads
// TODO: force a major collection every n minutes
if sleep_dur != MIN_SLEEP_DUR && young_count >= MAJOR_COLLECT_THRESHOLD {
gc.major_collection(&mut pool);
}
}
// do a final collection where all roots should be unrooted
gc.minor_collection(&mut pool);
gc.major_collection(&mut pool);
// return logger to calling thread
gc.logger().mark_end_time();
gc.shutdown()
}
/// Pointers are word-aligned, meaning the least-significant 2 or 3 bits are always 0, depending
/// on the word size.
#[inline] | 3
}
} | pub fn ptr_shift() -> i32 {
if size_of::<usize>() == 32 {
2
} else { | random_line_split |
gcthread.rs | //! Garbage collection thread
use std::any::Any;
use std::cmp::min;
use std::mem::size_of;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use num_cpus;
use scoped_pool::Pool;
use appthread::AppThread;
use constants::{MAJOR_COLLECT_THRESHOLD, MAX_SLEEP_DUR, MIN_SLEEP_DUR};
use heap::{CollectOps, Object};
use journal;
use parheap::ParHeap;
use statistics::{StatsLogger, DefaultLogger};
use youngheap::YoungHeap;
pub type EntryReceiver = journal::Receiver<Object>;
pub type EntrySender = journal::Sender<Object>;
pub type JournalReceiver = mpsc::Receiver<EntryReceiver>;
pub type JournalSender = mpsc::Sender<EntryReceiver>;
pub type JournalList = Vec<EntryReceiver>;
/// The Garbage Collection thread handle.
pub struct GcThread<S: StatsLogger> {
/// This is cloned and given to app threads.
tx_chan: JournalSender,
/// The GC thread's handle to join on.
handle: thread::JoinHandle<S>,
}
impl GcThread<DefaultLogger> {
/// Spawn a GC thread with default parameters: a `ParHeap` and a `DefaultLogger` parallelized
/// across all available CPUs.
pub fn spawn_gc() -> GcThread<DefaultLogger> {
let cores = num_cpus::get();
Self::spawn_gc_with(cores, ParHeap::new(cores), DefaultLogger::new())
}
}
impl<S: StatsLogger + 'static> GcThread<S> {
/// Run the GC on the current thread, spawning another thread to run the application function
/// on. Returns the AppThread std::thread::Thread handle. Caller must provide a custom
/// StatsLogger implementation and a CollectOps heap implementation.
pub fn spawn_gc_with<T>(num_threads: usize, mature: T, logger: S) -> GcThread<S>
where T: CollectOps + Send + 'static
{
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || gc_thread(num_threads, rx, mature, logger));
GcThread {
tx_chan: tx,
handle: handle,
}
}
/// Spawn an app thread that journals to the GC thread.
pub fn spawn<F, T>(&self, f: F) -> thread::JoinHandle<T>
where F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static
{
AppThread::spawn_from_gc(self.tx_chan.clone(), f)
}
/// Wait for the GC thread to finish. On success, returns the object that implements
/// `StatsLogger` for the calling thread to examine.
pub fn join(self) -> Result<S, Box<Any + Send + 'static>> {
self.handle.join()
}
}
/// Main GC thread loop.
fn gc_thread<S, T>(num_threads: usize, rx_chan: JournalReceiver, mature: T, logger: S) -> S
where S: StatsLogger,
T: CollectOps + Send
{
let mut pool = Pool::new(num_threads);
let mut gc = YoungHeap::new(num_threads, mature, logger);
// block, wait for first journal
gc.add_journal(rx_chan.recv().expect("Failed to receive first app journal!"));
gc.logger().mark_start_time();
// next duration to sleep if all journals are empty
let mut sleep_dur: usize = 0;
// loop until all journals are disconnected
while gc.num_journals() > 0 {
// new appthread connected
if let Ok(journal) = rx_chan.try_recv() {
gc.add_journal(journal);
}
let entries_read = gc.read_journals();
// sleep if nothing read from journal
if entries_read == 0 {
thread::sleep(Duration::from_millis(sleep_dur as u64));
gc.logger().add_sleep(sleep_dur);
// back off exponentially up to the max
sleep_dur = min(sleep_dur * 2, MAX_SLEEP_DUR);
} else |
// TODO: base this call on a duration since last call?
let young_count = gc.minor_collection(&mut pool);
// do a major collection if the young count reaches a threshold and we're not just trying
// to keep up with the app threads
// TODO: force a major collection every n minutes
if sleep_dur != MIN_SLEEP_DUR && young_count >= MAJOR_COLLECT_THRESHOLD {
gc.major_collection(&mut pool);
}
}
// do a final collection where all roots should be unrooted
gc.minor_collection(&mut pool);
gc.major_collection(&mut pool);
// return logger to calling thread
gc.logger().mark_end_time();
gc.shutdown()
}
/// Pointers are word-aligned, meaning the least-significant 2 or 3 bits are always 0, depending
/// on the word size.
#[inline]
pub fn ptr_shift() -> i32 {
if size_of::<usize>() == 32 {
2
} else {
3
}
}
| {
// reset next sleep duration on receiving no entries
sleep_dur = MIN_SLEEP_DUR;
} | conditional_block |
gcthread.rs | //! Garbage collection thread
use std::any::Any;
use std::cmp::min;
use std::mem::size_of;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use num_cpus;
use scoped_pool::Pool;
use appthread::AppThread;
use constants::{MAJOR_COLLECT_THRESHOLD, MAX_SLEEP_DUR, MIN_SLEEP_DUR};
use heap::{CollectOps, Object};
use journal;
use parheap::ParHeap;
use statistics::{StatsLogger, DefaultLogger};
use youngheap::YoungHeap;
pub type EntryReceiver = journal::Receiver<Object>;
pub type EntrySender = journal::Sender<Object>;
pub type JournalReceiver = mpsc::Receiver<EntryReceiver>;
pub type JournalSender = mpsc::Sender<EntryReceiver>;
pub type JournalList = Vec<EntryReceiver>;
/// The Garbage Collection thread handle.
pub struct GcThread<S: StatsLogger> {
/// This is cloned and given to app threads.
tx_chan: JournalSender,
/// The GC thread's handle to join on.
handle: thread::JoinHandle<S>,
}
impl GcThread<DefaultLogger> {
/// Spawn a GC thread with default parameters: a `ParHeap` and a `DefaultLogger` parallelized
/// across all available CPUs.
pub fn spawn_gc() -> GcThread<DefaultLogger> {
let cores = num_cpus::get();
Self::spawn_gc_with(cores, ParHeap::new(cores), DefaultLogger::new())
}
}
impl<S: StatsLogger + 'static> GcThread<S> {
/// Run the GC on the current thread, spawning another thread to run the application function
/// on. Returns the AppThread std::thread::Thread handle. Caller must provide a custom
/// StatsLogger implementation and a CollectOps heap implementation.
pub fn spawn_gc_with<T>(num_threads: usize, mature: T, logger: S) -> GcThread<S>
where T: CollectOps + Send + 'static
{
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || gc_thread(num_threads, rx, mature, logger));
GcThread {
tx_chan: tx,
handle: handle,
}
}
/// Spawn an app thread that journals to the GC thread.
pub fn spawn<F, T>(&self, f: F) -> thread::JoinHandle<T>
where F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static
|
/// Wait for the GC thread to finish. On success, returns the object that implements
/// `StatsLogger` for the calling thread to examine.
pub fn join(self) -> Result<S, Box<Any + Send + 'static>> {
self.handle.join()
}
}
/// Main GC thread loop.
fn gc_thread<S, T>(num_threads: usize, rx_chan: JournalReceiver, mature: T, logger: S) -> S
where S: StatsLogger,
T: CollectOps + Send
{
let mut pool = Pool::new(num_threads);
let mut gc = YoungHeap::new(num_threads, mature, logger);
// block, wait for first journal
gc.add_journal(rx_chan.recv().expect("Failed to receive first app journal!"));
gc.logger().mark_start_time();
// next duration to sleep if all journals are empty
let mut sleep_dur: usize = 0;
// loop until all journals are disconnected
while gc.num_journals() > 0 {
// new appthread connected
if let Ok(journal) = rx_chan.try_recv() {
gc.add_journal(journal);
}
let entries_read = gc.read_journals();
// sleep if nothing read from journal
if entries_read == 0 {
thread::sleep(Duration::from_millis(sleep_dur as u64));
gc.logger().add_sleep(sleep_dur);
// back off exponentially up to the max
sleep_dur = min(sleep_dur * 2, MAX_SLEEP_DUR);
} else {
// reset next sleep duration on receiving no entries
sleep_dur = MIN_SLEEP_DUR;
}
// TODO: base this call on a duration since last call?
let young_count = gc.minor_collection(&mut pool);
// do a major collection if the young count reaches a threshold and we're not just trying
// to keep up with the app threads
// TODO: force a major collection every n minutes
if sleep_dur != MIN_SLEEP_DUR && young_count >= MAJOR_COLLECT_THRESHOLD {
gc.major_collection(&mut pool);
}
}
// do a final collection where all roots should be unrooted
gc.minor_collection(&mut pool);
gc.major_collection(&mut pool);
// return logger to calling thread
gc.logger().mark_end_time();
gc.shutdown()
}
/// Pointers are word-aligned, meaning the least-significant 2 or 3 bits are always 0, depending
/// on the word size.
#[inline]
pub fn ptr_shift() -> i32 {
if size_of::<usize>() == 32 {
2
} else {
3
}
}
| {
AppThread::spawn_from_gc(self.tx_chan.clone(), f)
} | identifier_body |
gcthread.rs | //! Garbage collection thread
use std::any::Any;
use std::cmp::min;
use std::mem::size_of;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use num_cpus;
use scoped_pool::Pool;
use appthread::AppThread;
use constants::{MAJOR_COLLECT_THRESHOLD, MAX_SLEEP_DUR, MIN_SLEEP_DUR};
use heap::{CollectOps, Object};
use journal;
use parheap::ParHeap;
use statistics::{StatsLogger, DefaultLogger};
use youngheap::YoungHeap;
pub type EntryReceiver = journal::Receiver<Object>;
pub type EntrySender = journal::Sender<Object>;
pub type JournalReceiver = mpsc::Receiver<EntryReceiver>;
pub type JournalSender = mpsc::Sender<EntryReceiver>;
pub type JournalList = Vec<EntryReceiver>;
/// The Garbage Collection thread handle.
pub struct | <S: StatsLogger> {
/// This is cloned and given to app threads.
tx_chan: JournalSender,
/// The GC thread's handle to join on.
handle: thread::JoinHandle<S>,
}
impl GcThread<DefaultLogger> {
/// Spawn a GC thread with default parameters: a `ParHeap` and a `DefaultLogger` parallelized
/// across all available CPUs.
pub fn spawn_gc() -> GcThread<DefaultLogger> {
let cores = num_cpus::get();
Self::spawn_gc_with(cores, ParHeap::new(cores), DefaultLogger::new())
}
}
impl<S: StatsLogger + 'static> GcThread<S> {
/// Run the GC on the current thread, spawning another thread to run the application function
/// on. Returns the AppThread std::thread::Thread handle. Caller must provide a custom
/// StatsLogger implementation and a CollectOps heap implementation.
pub fn spawn_gc_with<T>(num_threads: usize, mature: T, logger: S) -> GcThread<S>
where T: CollectOps + Send + 'static
{
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || gc_thread(num_threads, rx, mature, logger));
GcThread {
tx_chan: tx,
handle: handle,
}
}
/// Spawn an app thread that journals to the GC thread.
pub fn spawn<F, T>(&self, f: F) -> thread::JoinHandle<T>
where F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static
{
AppThread::spawn_from_gc(self.tx_chan.clone(), f)
}
/// Wait for the GC thread to finish. On success, returns the object that implements
/// `StatsLogger` for the calling thread to examine.
pub fn join(self) -> Result<S, Box<Any + Send + 'static>> {
self.handle.join()
}
}
/// Main GC thread loop.
fn gc_thread<S, T>(num_threads: usize, rx_chan: JournalReceiver, mature: T, logger: S) -> S
where S: StatsLogger,
T: CollectOps + Send
{
let mut pool = Pool::new(num_threads);
let mut gc = YoungHeap::new(num_threads, mature, logger);
// block, wait for first journal
gc.add_journal(rx_chan.recv().expect("Failed to receive first app journal!"));
gc.logger().mark_start_time();
// next duration to sleep if all journals are empty
let mut sleep_dur: usize = 0;
// loop until all journals are disconnected
while gc.num_journals() > 0 {
// new appthread connected
if let Ok(journal) = rx_chan.try_recv() {
gc.add_journal(journal);
}
let entries_read = gc.read_journals();
// sleep if nothing read from journal
if entries_read == 0 {
thread::sleep(Duration::from_millis(sleep_dur as u64));
gc.logger().add_sleep(sleep_dur);
// back off exponentially up to the max
sleep_dur = min(sleep_dur * 2, MAX_SLEEP_DUR);
} else {
// reset next sleep duration on receiving no entries
sleep_dur = MIN_SLEEP_DUR;
}
// TODO: base this call on a duration since last call?
let young_count = gc.minor_collection(&mut pool);
// do a major collection if the young count reaches a threshold and we're not just trying
// to keep up with the app threads
// TODO: force a major collection every n minutes
if sleep_dur != MIN_SLEEP_DUR && young_count >= MAJOR_COLLECT_THRESHOLD {
gc.major_collection(&mut pool);
}
}
// do a final collection where all roots should be unrooted
gc.minor_collection(&mut pool);
gc.major_collection(&mut pool);
// return logger to calling thread
gc.logger().mark_end_time();
gc.shutdown()
}
/// Pointers are word-aligned, meaning the least-significant 2 or 3 bits are always 0, depending
/// on the word size.
#[inline]
pub fn ptr_shift() -> i32 {
if size_of::<usize>() == 32 {
2
} else {
3
}
}
| GcThread | identifier_name |
test_pep8.py | #!/usr/bin/env python
import os.path
import unittest
import pep8 | SRC_PATH = os.path.dirname(os.path.dirname(__file__))
EXCLUDE = ['.svn', 'CVS', '.bzr', '.hg', '.git',
'Paste-1.7.5.1-py2.6.egg', 'PasteDeploy-1.5.0-py2.6.egg', 'data']
class AdhocracyStyleGuide(pep8.StyleGuide):
def ignore_code(self, code):
IGNORED = [
'E111', # indentation is not a multiple of four
'E121', # continuation line indentation is not a multiple of four
'E122', # continuation line missing indentation or outdented
'E123', # closing bracket does not match indentation of opening
# bracket
'E124', # closing bracket does not match visual indentation
'E126', # continuation line over
'E127', # continuation line over
'E128', # continuation line under
'E225', # missing whitespace around operator
'E226', # missing optional whitespace around operator
'E231', # missing whitespace after
'E241', # multiple spaces after
'E251', # no spaces around keyword
'E261', # at least two spaces before inline comment
'E301', # expected 1 blank line
'E302', # expected 2 blank lines
'E303', # too many blank lines
'E501', # line too long
'E701', # multiple statements on one line
'E702', # multiple statements on one line
'E711', # comparison to None should be 'if cond is None:'
'E712', # comparison to True should be 'if cond is True:' or
# 'if cond:'
'W291', # trailing whitespace
'W292', # no newline at end of file
'W293', # blank line contains whitespace
'W391', # blank line at end of file
]
return code in IGNORED
class TestPep8(unittest.TestCase):
def test_pep8(self):
sg = AdhocracyStyleGuide(exclude=EXCLUDE)
sg.input_dir(SRC_PATH)
self.assertEqual(sg.options.report.get_count(), 0) | random_line_split | |
test_pep8.py | #!/usr/bin/env python
import os.path
import unittest
import pep8
SRC_PATH = os.path.dirname(os.path.dirname(__file__))
EXCLUDE = ['.svn', 'CVS', '.bzr', '.hg', '.git',
'Paste-1.7.5.1-py2.6.egg', 'PasteDeploy-1.5.0-py2.6.egg', 'data']
class AdhocracyStyleGuide(pep8.StyleGuide):
def | (self, code):
IGNORED = [
'E111', # indentation is not a multiple of four
'E121', # continuation line indentation is not a multiple of four
'E122', # continuation line missing indentation or outdented
'E123', # closing bracket does not match indentation of opening
# bracket
'E124', # closing bracket does not match visual indentation
'E126', # continuation line over
'E127', # continuation line over
'E128', # continuation line under
'E225', # missing whitespace around operator
'E226', # missing optional whitespace around operator
'E231', # missing whitespace after
'E241', # multiple spaces after
'E251', # no spaces around keyword
'E261', # at least two spaces before inline comment
'E301', # expected 1 blank line
'E302', # expected 2 blank lines
'E303', # too many blank lines
'E501', # line too long
'E701', # multiple statements on one line
'E702', # multiple statements on one line
'E711', # comparison to None should be 'if cond is None:'
'E712', # comparison to True should be 'if cond is True:' or
# 'if cond:'
'W291', # trailing whitespace
'W292', # no newline at end of file
'W293', # blank line contains whitespace
'W391', # blank line at end of file
]
return code in IGNORED
class TestPep8(unittest.TestCase):
def test_pep8(self):
sg = AdhocracyStyleGuide(exclude=EXCLUDE)
sg.input_dir(SRC_PATH)
self.assertEqual(sg.options.report.get_count(), 0)
| ignore_code | identifier_name |
test_pep8.py | #!/usr/bin/env python
import os.path
import unittest
import pep8
SRC_PATH = os.path.dirname(os.path.dirname(__file__))
EXCLUDE = ['.svn', 'CVS', '.bzr', '.hg', '.git',
'Paste-1.7.5.1-py2.6.egg', 'PasteDeploy-1.5.0-py2.6.egg', 'data']
class AdhocracyStyleGuide(pep8.StyleGuide):
|
class TestPep8(unittest.TestCase):
def test_pep8(self):
sg = AdhocracyStyleGuide(exclude=EXCLUDE)
sg.input_dir(SRC_PATH)
self.assertEqual(sg.options.report.get_count(), 0)
| def ignore_code(self, code):
IGNORED = [
'E111', # indentation is not a multiple of four
'E121', # continuation line indentation is not a multiple of four
'E122', # continuation line missing indentation or outdented
'E123', # closing bracket does not match indentation of opening
# bracket
'E124', # closing bracket does not match visual indentation
'E126', # continuation line over
'E127', # continuation line over
'E128', # continuation line under
'E225', # missing whitespace around operator
'E226', # missing optional whitespace around operator
'E231', # missing whitespace after
'E241', # multiple spaces after
'E251', # no spaces around keyword
'E261', # at least two spaces before inline comment
'E301', # expected 1 blank line
'E302', # expected 2 blank lines
'E303', # too many blank lines
'E501', # line too long
'E701', # multiple statements on one line
'E702', # multiple statements on one line
'E711', # comparison to None should be 'if cond is None:'
'E712', # comparison to True should be 'if cond is True:' or
# 'if cond:'
'W291', # trailing whitespace
'W292', # no newline at end of file
'W293', # blank line contains whitespace
'W391', # blank line at end of file
]
return code in IGNORED | identifier_body |
asignacion-punto-juego.component.ts |
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { SelectionModel } from '@angular/cdk/collections';
import {MatTableDataSource} from '@angular/material/table';
import Swal from 'sweetalert2';
// Clases
import { Alumno, Equipo, Juego, Punto, AsignacionPuntosJuego} from '../../../clases/index';
// Services
import { SesionService, PeticionesAPIService } from '../../../servicios/index';
@Component({
selector: 'app-asignacion-punto-juego',
templateUrl: './asignacion-punto-juego.component.html',
styleUrls: ['./asignacion-punto-juego.component.scss']
})
export class AsignacionPuntoJuegoComponent implements OnInit {
@Output() emisorTiposDePuntos = new EventEmitter <any[]>();
grupoId: number;
profesorId: number;
// tslint:disable-next-line:ban-types
isDisabled: Boolean = true;
tiposPuntos: Punto[];
seleccionados: boolean[];
displayedColumns: string[] = ['select', 'nombrePunto', 'descripcionPunto'];
selection = new SelectionModel<Punto>(true, []);
juego: Juego;
dataSource;
puntosSeleccionados: Punto[] = [];
botonTablaDesactivado = false;
puntoAleatorio: Punto;
constructor(
private sesion: SesionService,
private peticionesAPI: PeticionesAPIService
) |
ngOnInit() {
console.log('Inicio el componente');
this.grupoId = this.sesion.DameGrupo().id;
this.juego = this.sesion.DameJuego();
this.profesorId = this.sesion.DameProfesor().id;
console.log(this.juego);
// traigo los tipos de puntos entre los que se puede seleccionar
this.peticionesAPI.DameTiposDePuntos(this.profesorId)
.subscribe(puntos => {
// ME guardo el tipo de punto aleatorio para añadirlo al final
this.puntoAleatorio = puntos.filter (p => p.Nombre === 'Aleatorio')[0];
// Elimino el tipo de punto aleatorio para que no salga entre los asignables
// porque ese tipo de punto se asigna al juego de forma automática
this.tiposPuntos = puntos.filter (p => p.Nombre !== 'Aleatorio');
this.seleccionados = Array(this.tiposPuntos.length).fill(false);
console.log(this.seleccionados);
this.dataSource = new MatTableDataSource (this.tiposPuntos);
});
}
/* Para averiguar si todas las filas están seleccionadas */
IsAllSelected() {
const numSelected = this.selection.selected.length;
const numRows = this.dataSource.data.length;
return numSelected === numRows;
}
/* Cuando se clica en el checkbox de cabecera hay que ver si todos los
* checkbox estan acivados, en cuyo caso se desactivan todos, o si hay alguno
* desactivado, en cuyo caso se activan todos */
MasterToggle() {
if (this.IsAllSelected()) {
this.selection.clear(); // Desactivamos todos
} else {
// activamos todos
this.dataSource.data.forEach(row => this.selection.select(row));
}
}
// Esta función decide si el boton de aceptar los tipos de puntos
// debe estar activo (si hay al menosuna fila seleccionada)
HaSeleccionado() {
if (this.selection.selected.length === 0) {
return false;
} else {
return true;
}
}
AgregarTiposPuntosAlJuego() {
console.log ('Vamos a agregar LOS PUNTOS');
const tiposDePuntosSeleccionados = [];
this.dataSource.data.forEach ( row => {
if (this.selection.isSelected(row)) {
tiposDePuntosSeleccionados.push (row);
}
});
// Añadimos el punto de tipo aleatorio que siempre ha de estar
tiposDePuntosSeleccionados.push (this.puntoAleatorio);
console.log (tiposDePuntosSeleccionados);
this.emisorTiposDePuntos.emit (tiposDePuntosSeleccionados);
this.selection.clear();
}
}
| {} | identifier_body |
asignacion-punto-juego.component.ts |
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { SelectionModel } from '@angular/cdk/collections';
import {MatTableDataSource} from '@angular/material/table';
import Swal from 'sweetalert2';
// Clases
import { Alumno, Equipo, Juego, Punto, AsignacionPuntosJuego} from '../../../clases/index';
// Services
import { SesionService, PeticionesAPIService } from '../../../servicios/index';
@Component({
selector: 'app-asignacion-punto-juego',
templateUrl: './asignacion-punto-juego.component.html',
styleUrls: ['./asignacion-punto-juego.component.scss']
})
export class AsignacionPuntoJuegoComponent implements OnInit {
@Output() emisorTiposDePuntos = new EventEmitter <any[]>();
grupoId: number;
profesorId: number;
// tslint:disable-next-line:ban-types
isDisabled: Boolean = true;
tiposPuntos: Punto[];
seleccionados: boolean[];
displayedColumns: string[] = ['select', 'nombrePunto', 'descripcionPunto'];
selection = new SelectionModel<Punto>(true, []);
juego: Juego;
dataSource;
puntosSeleccionados: Punto[] = [];
botonTablaDesactivado = false;
puntoAleatorio: Punto;
constructor(
private sesion: SesionService,
private peticionesAPI: PeticionesAPIService
) {}
ngOnInit() {
console.log('Inicio el componente');
this.grupoId = this.sesion.DameGrupo().id;
this.juego = this.sesion.DameJuego();
this.profesorId = this.sesion.DameProfesor().id;
console.log(this.juego);
// traigo los tipos de puntos entre los que se puede seleccionar
this.peticionesAPI.DameTiposDePuntos(this.profesorId)
.subscribe(puntos => {
// ME guardo el tipo de punto aleatorio para añadirlo al final
this.puntoAleatorio = puntos.filter (p => p.Nombre === 'Aleatorio')[0];
// Elimino el tipo de punto aleatorio para que no salga entre los asignables
// porque ese tipo de punto se asigna al juego de forma automática
this.tiposPuntos = puntos.filter (p => p.Nombre !== 'Aleatorio');
this.seleccionados = Array(this.tiposPuntos.length).fill(false);
console.log(this.seleccionados);
this.dataSource = new MatTableDataSource (this.tiposPuntos);
});
}
/* Para averiguar si todas las filas están seleccionadas */
IsAllSelected() {
const numSelected = this.selection.selected.length;
const numRows = this.dataSource.data.length;
return numSelected === numRows;
}
/* Cuando se clica en el checkbox de cabecera hay que ver si todos los
* checkbox estan acivados, en cuyo caso se desactivan todos, o si hay alguno
* desactivado, en cuyo caso se activan todos */
Mas | {
if (this.IsAllSelected()) {
this.selection.clear(); // Desactivamos todos
} else {
// activamos todos
this.dataSource.data.forEach(row => this.selection.select(row));
}
}
// Esta función decide si el boton de aceptar los tipos de puntos
// debe estar activo (si hay al menosuna fila seleccionada)
HaSeleccionado() {
if (this.selection.selected.length === 0) {
return false;
} else {
return true;
}
}
AgregarTiposPuntosAlJuego() {
console.log ('Vamos a agregar LOS PUNTOS');
const tiposDePuntosSeleccionados = [];
this.dataSource.data.forEach ( row => {
if (this.selection.isSelected(row)) {
tiposDePuntosSeleccionados.push (row);
}
});
// Añadimos el punto de tipo aleatorio que siempre ha de estar
tiposDePuntosSeleccionados.push (this.puntoAleatorio);
console.log (tiposDePuntosSeleccionados);
this.emisorTiposDePuntos.emit (tiposDePuntosSeleccionados);
this.selection.clear();
}
}
| terToggle() | identifier_name |
asignacion-punto-juego.component.ts | import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { SelectionModel } from '@angular/cdk/collections';
import {MatTableDataSource} from '@angular/material/table';
import Swal from 'sweetalert2';
// Clases
import { Alumno, Equipo, Juego, Punto, AsignacionPuntosJuego} from '../../../clases/index';
// Services
import { SesionService, PeticionesAPIService } from '../../../servicios/index';
@Component({
selector: 'app-asignacion-punto-juego',
templateUrl: './asignacion-punto-juego.component.html',
styleUrls: ['./asignacion-punto-juego.component.scss']
})
export class AsignacionPuntoJuegoComponent implements OnInit {
@Output() emisorTiposDePuntos = new EventEmitter <any[]>();
|
tiposPuntos: Punto[];
seleccionados: boolean[];
displayedColumns: string[] = ['select', 'nombrePunto', 'descripcionPunto'];
selection = new SelectionModel<Punto>(true, []);
juego: Juego;
dataSource;
puntosSeleccionados: Punto[] = [];
botonTablaDesactivado = false;
puntoAleatorio: Punto;
constructor(
private sesion: SesionService,
private peticionesAPI: PeticionesAPIService
) {}
ngOnInit() {
console.log('Inicio el componente');
this.grupoId = this.sesion.DameGrupo().id;
this.juego = this.sesion.DameJuego();
this.profesorId = this.sesion.DameProfesor().id;
console.log(this.juego);
// traigo los tipos de puntos entre los que se puede seleccionar
this.peticionesAPI.DameTiposDePuntos(this.profesorId)
.subscribe(puntos => {
// ME guardo el tipo de punto aleatorio para añadirlo al final
this.puntoAleatorio = puntos.filter (p => p.Nombre === 'Aleatorio')[0];
// Elimino el tipo de punto aleatorio para que no salga entre los asignables
// porque ese tipo de punto se asigna al juego de forma automática
this.tiposPuntos = puntos.filter (p => p.Nombre !== 'Aleatorio');
this.seleccionados = Array(this.tiposPuntos.length).fill(false);
console.log(this.seleccionados);
this.dataSource = new MatTableDataSource (this.tiposPuntos);
});
}
/* Para averiguar si todas las filas están seleccionadas */
IsAllSelected() {
const numSelected = this.selection.selected.length;
const numRows = this.dataSource.data.length;
return numSelected === numRows;
}
/* Cuando se clica en el checkbox de cabecera hay que ver si todos los
* checkbox estan acivados, en cuyo caso se desactivan todos, o si hay alguno
* desactivado, en cuyo caso se activan todos */
MasterToggle() {
if (this.IsAllSelected()) {
this.selection.clear(); // Desactivamos todos
} else {
// activamos todos
this.dataSource.data.forEach(row => this.selection.select(row));
}
}
// Esta función decide si el boton de aceptar los tipos de puntos
// debe estar activo (si hay al menosuna fila seleccionada)
HaSeleccionado() {
if (this.selection.selected.length === 0) {
return false;
} else {
return true;
}
}
AgregarTiposPuntosAlJuego() {
console.log ('Vamos a agregar LOS PUNTOS');
const tiposDePuntosSeleccionados = [];
this.dataSource.data.forEach ( row => {
if (this.selection.isSelected(row)) {
tiposDePuntosSeleccionados.push (row);
}
});
// Añadimos el punto de tipo aleatorio que siempre ha de estar
tiposDePuntosSeleccionados.push (this.puntoAleatorio);
console.log (tiposDePuntosSeleccionados);
this.emisorTiposDePuntos.emit (tiposDePuntosSeleccionados);
this.selection.clear();
}
} | grupoId: number;
profesorId: number;
// tslint:disable-next-line:ban-types
isDisabled: Boolean = true; | random_line_split |
asignacion-punto-juego.component.ts |
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { SelectionModel } from '@angular/cdk/collections';
import {MatTableDataSource} from '@angular/material/table';
import Swal from 'sweetalert2';
// Clases
import { Alumno, Equipo, Juego, Punto, AsignacionPuntosJuego} from '../../../clases/index';
// Services
import { SesionService, PeticionesAPIService } from '../../../servicios/index';
@Component({
selector: 'app-asignacion-punto-juego',
templateUrl: './asignacion-punto-juego.component.html',
styleUrls: ['./asignacion-punto-juego.component.scss']
})
export class AsignacionPuntoJuegoComponent implements OnInit {
@Output() emisorTiposDePuntos = new EventEmitter <any[]>();
grupoId: number;
profesorId: number;
// tslint:disable-next-line:ban-types
isDisabled: Boolean = true;
tiposPuntos: Punto[];
seleccionados: boolean[];
displayedColumns: string[] = ['select', 'nombrePunto', 'descripcionPunto'];
selection = new SelectionModel<Punto>(true, []);
juego: Juego;
dataSource;
puntosSeleccionados: Punto[] = [];
botonTablaDesactivado = false;
puntoAleatorio: Punto;
constructor(
private sesion: SesionService,
private peticionesAPI: PeticionesAPIService
) {}
ngOnInit() {
console.log('Inicio el componente');
this.grupoId = this.sesion.DameGrupo().id;
this.juego = this.sesion.DameJuego();
this.profesorId = this.sesion.DameProfesor().id;
console.log(this.juego);
// traigo los tipos de puntos entre los que se puede seleccionar
this.peticionesAPI.DameTiposDePuntos(this.profesorId)
.subscribe(puntos => {
// ME guardo el tipo de punto aleatorio para añadirlo al final
this.puntoAleatorio = puntos.filter (p => p.Nombre === 'Aleatorio')[0];
// Elimino el tipo de punto aleatorio para que no salga entre los asignables
// porque ese tipo de punto se asigna al juego de forma automática
this.tiposPuntos = puntos.filter (p => p.Nombre !== 'Aleatorio');
this.seleccionados = Array(this.tiposPuntos.length).fill(false);
console.log(this.seleccionados);
this.dataSource = new MatTableDataSource (this.tiposPuntos);
});
}
/* Para averiguar si todas las filas están seleccionadas */
IsAllSelected() {
const numSelected = this.selection.selected.length;
const numRows = this.dataSource.data.length;
return numSelected === numRows;
}
/* Cuando se clica en el checkbox de cabecera hay que ver si todos los
* checkbox estan acivados, en cuyo caso se desactivan todos, o si hay alguno
* desactivado, en cuyo caso se activan todos */
MasterToggle() {
if (this.IsAllSelected()) {
this.selection.clear(); // Desactivamos todos
} else {
| }
// Esta función decide si el boton de aceptar los tipos de puntos
// debe estar activo (si hay al menosuna fila seleccionada)
HaSeleccionado() {
if (this.selection.selected.length === 0) {
return false;
} else {
return true;
}
}
AgregarTiposPuntosAlJuego() {
console.log ('Vamos a agregar LOS PUNTOS');
const tiposDePuntosSeleccionados = [];
this.dataSource.data.forEach ( row => {
if (this.selection.isSelected(row)) {
tiposDePuntosSeleccionados.push (row);
}
});
// Añadimos el punto de tipo aleatorio que siempre ha de estar
tiposDePuntosSeleccionados.push (this.puntoAleatorio);
console.log (tiposDePuntosSeleccionados);
this.emisorTiposDePuntos.emit (tiposDePuntosSeleccionados);
this.selection.clear();
}
}
| // activamos todos
this.dataSource.data.forEach(row => this.selection.select(row));
}
| conditional_block |
index-2.js | //Auto generated index for searching.
w["dsc20"]="24";
w["dst"]="20";
w["due"]="20";
w["each"]="16,20";
w["echo"]="15,16,24";
w["edit"]="3,5,7,8,9,11,14,15,16,19,24,25";
w["either"]="7,13";
w["enabl"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27";
w["enable_isolated_metadata"]="11";
w["encapsul"]="22";
w["endpoint"]="20";
w["ensur"]="20";
w["enter"]="16,26";
w["environ"]="4,16,18,20";
w["eof"]="16";
w["error"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27";
w["establish"]="20";
w["etc"]="3,5,7,8,11,14,15,16,19,24,25";
w["eth1"]="20";
w["exampl"]="20,26";
w["except"]="5";
w["execut"]="2,7,15,24";
w["extens"]="22";
w["extern"]="20,21,25,26";
w["factor"]="16";
w["fail"]="24";
w["fals"]="3";
w["file"]="3,5,7,8,9,11,14,15,16,19,24,25,26";
w["filter"]="5";
w["find"]="20";
w["firewal"]="1";
w["firewalld"]="1";
w["first"]="20,24";
w["float"]="20";
w["flush"]="14";
w["follow"]="0,1,2,3,5,7,8,9,11,14,15,16,18,19,20,21,24,25,26";
w["form"]="17";
w["found"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27";
w["full"]="5";
w["further"]="20,27";
w["gateway"]="10,16,20,26";
w["gateway1"]="10,16,20,22,26";
w["gateway2"]="10,16,20,22,26";
w["general"]="10";
w["generic"]="22";
w["glanc"]="5,10";
w["gmt"]="15";
w["go"]="8,11,20,25";
w["got"]="20";
w["gpgcheck"]="19";
w["gpgkey"]="19";
w["grant"]="14";
w["gre"]="14,22";
w["group"]="5,20";
w["guid"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27";
w["handi"]="17";
w["happen"]="16";
w["has"]="5,15,16,20,24,26";
w["hat"]="0,2,5,8,11,14,19,21,25";
w["have"]="11,20,25,26";
w["head"]="14";
w["header"]="3";
w["horizon"]="10";
w["host"]="5,6,10,15,16,20,22,24,26";
w["host0"]="20,22";
w["host1"]="20,22";
w["host2"]="22";
w["host3"]="22";
w["host_id"]="20";
w["host_uuid"]="3";
w["hostnam"]="13,24";
w["howev"]="26";
w["hpet"]="5";
w["http"]="3,9,11,14,19";
w["https"]="19";
w["id"]="15,20,24";
w["ideal"]="26";
w["ident"]="2,10,18";
w["identifi"]="14";
w["if"]="7,15,17,19,24";
w["ifac"]="20";
w["imag"]="10";
w["imok"]="15";
w["import"]="0,1,2,5,7,8,11,13,14,15,16,17,18,20,21,22,24,25,26";
w["includ"]="17";
w["infilt"]="20";
w["inform"]="10,15,17,26";
w["ini"]="11,14,25";
w["init"]="24";
w["initi"]="27";
w["instal"]="0,1,2,3,5,6,7,8,9,11,12,15,16,18,19,21,23,24,25,26,27";
w["instead"]="1,5,8,11,14,26";
w["instruct"]="0,1,2,5,8,11,14,20,21,25,27";
w["integr"]="19,27";
w["interfac"]="5,11,20,25,26";
w["interface_driv"]="11";
w["into"]="27";
w["ip"]="20";
w["ip_address_of_host0"]="22";
w["ip_address_of_host1"]="22";
w["ip_address_of_host2"]="22";
w["ip_address_of_host3"]="22";
w["issu"]="17";
w["it"]="24,26";
w["java"]="15,16";
w["java-1"]="15,24";
w["javascript"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27";
w["join"]="24";
w["jre-1"]="15";
w["juno"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27";
w["just"]="26";
w["jvm"]="15,16";
w["kb"]="24";
w["key"]="5,14";
w["keyston"]="2,10,11,14,18,20";
w["keystone-admin_token"]="3";
w["keystone-service_host"]="3";
w["kqemu"]="5";
w["kvm"]="5";
w["l2"]="5";
w["l3"]="21,25";
w["lan"]="22";
w["larg"]="16";
w["latenc"]="15";
w["launch"]="5,8,14,20,22";
w["learn"]="18";
w["leastrout"]="25";
w["leav"]="14,16,24,26";
w["legal"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27";
w["lib"]="3,15";
w["librari"]="19";
w["libvirt"]="5";
w["libvirtd"]="5,8";
w["like"]="11,25";
w["line"]="14,26";
w["link"]="14";
w["linux"]="11";
w["list"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27";
w["listen_address"]="24";
w["ln"]="14,15";
w["load"]="20,24";
w["local"]="13,16";
w["local-"]="20";
w["localhost"]="3,14";
w["locat"]="24";
w["log"]="15,24,26";
w["log_fil"]="24";
w["loss"]="17";
w["lost"]="24";
w["mac"]="20";
w["machin"]="16,20";
w["mail"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27";
w["make"]="14,22";
w["manag"]="1";
w["manual"]="18";
w["mariadb"]="10";
w["max"]="15";
w["maxhttpheaders"]="3";
w["maximum"]="3";
w["may"]="24";
w["medium"]="16";
w["member"]="20,22";
w["messag"]="5,8,10,14,24";
w["metadata"]="8,10,14,25";
w["metadata_ag"]="25";
w["metadata_proxy_shared_secret"]="8,25";
w["metadata_secret"]="8,25";
w["midocluster-properties_fil"]="3";
w["midolman"]="6,10,16,26";
w["midolman-env"]="16";
w["midonet"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27";
w["midonet-api"]="3,9,11,14";
w["midonet-c"]="20,22";
w["midonet-misc"]="19";
w["midonet-openstack-integr"]="19";
w["midonet_driv"]="11";
w["midonet_pass"]="2,11,14";
w["midonet_uri"]="11,14";
w["midonetinterfacedriv"]="11";
w["midonetpluginv2"]="14";
w["midonetrc"]="9";
w["min"]="15";
w["misc"]="19";
w["mkdir"]="14,15,24";
w["ml2"]="26";
w["mn-conf"]="16";
w["mode"]="7,15";
w["more"]="15,26";
w["move"]="24";
w["mtu"]="20";
w["must"]="13,17";
w["myid"]="15";
w["mysql"]="14";
w["name"]="2,19,20,22,24";
w["nc"]="15";
w["necessari"]="19";
w["need"]="16,26";
w["net"]="5,20";
w["network"]="1,4,5,10,11,13,14,18,20,21,25,26,27";
w["neutron"]="8,10,11,14,18,21,25,26,27";
w["neutron-db-manag"]="14";
w["neutron-dist"]="14"; | w["neutron_dbpass"]="14";
w["neutron_dbpass@"]="14";
w["nmap-ncat"]="15";
w["node"]="0,5,6,8,10,11,12,14,15,16,20,21,23,24,25,26";
w["node-specif"]="15,24";
w["nodetool"]="24";
w["non-error"]="15,24";
w["normal"]="20,24";
w["not"]="1,5,8,11,14,20,21,24,25,26";
w["note"]="0,1,2,5,8,11,14,17,18,21,25,27";
w["notic"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27";
w["nova"]="0,5,8,10,18,25";
w["nova-rootwrap"]="5";
w["nova_metadata_ip"]="25";
w["now"]="27";
w["nsdb"]="6,10,15,16,23,24,26";
w["nsdb1"]="3,10,15,16,24,26";
w["nsdb2"]="3,10,15,16,24,26";
w["nsdb3"]="3,10,15,16,24,26";
w["null"]="5";
w["ok"]="15,26";
w["onc"]="16";
w["one"]="16,20";
w["onli"]="5,8,16";
w["open"]="14";
w["openstack"]="0,1,2,10,11,14,18,19,21,25,26,27";
w["openstack-juno"]="19";
w["openstack-neutron"]="1";
w["openstack-nova-api"]="8";
w["openstack-nova-comput"]="5,8";
w["openstack-nova-conductor"]="8";
w["openstack-nova-network"]="5";
w["openstack-nova-schedul"]="8";
w["openstack-selinux"]="1";
w["openstack-util"]="1,5";
w["oper"]="15,20,24,27";
w["order"]="16,20";
w["org"]="19,24";
w["osp"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27";
w["other"]="22,24,26";
w["outfilt"]="20";
w["outstand"]="15";
w["overflow"]="24";
w["own"]="24,26";
w["packag"]="1,3,5,8,9,15,16,19,24"; | w["neutron-metadata-ag"]="25"; | random_line_split |
proxy_crawler.py | import asyncio
from itertools import compress
import traceback
from proxypool.rules.rule_base import CrawlerRuleBase
from proxypool.utils import page_download, page_download_phantomjs, logger, Result
class ProxyCrawler(object):
"""Crawl proxies according to the rules."""
def __init__(self, proxies, rules=None):
"""Crawler init.
Args:
proxies: aysncio.Queue object
rules: crawler rules of each proxy web, should be iterable object
flag: stop flag for page downloading
"""
self._proxies = proxies
self._stop_flag = asyncio.Event() # stop flag for crawler, not for validator
self._pages = asyncio.Queue()
self._rules = rules if rules else CrawlerRuleBase.__subclasses__()
async def _parse_page(self):
while 1:
page = await self._pages.get()
await self._parse_proxy(page.rule, page.content)
self._pages.task_done()
async def _parse_proxy(self, rule, page):
|
@staticmethod
def _url_generator(rule):
"""Url generator of next page.
Returns:
url of next page, like: 'http://www.example.com/page/2'.
"""
page = yield Result(rule.start_url, rule)
for i in range(2, rule.page_count + 1):
if rule.urls_format:
yield
yield Result(rule.urls_format.format(rule.start_url, i), rule)
elif rule.next_page_xpath:
if page is None:
break
next_page = page.xpath(rule.next_page_xpath)
if next_page:
yield
page = yield Result(rule.next_page_host + str(next_page[0]).strip(), rule)
else:
break
async def _parser(self, count):
to_parse = [self._parse_page() for _ in range(count)]
await asyncio.wait(to_parse)
async def _downloader(self, rule):
if not rule.use_phantomjs:
await page_download(ProxyCrawler._url_generator(rule), self._pages,
self._stop_flag)
else:
await page_download_phantomjs(ProxyCrawler._url_generator(rule), self._pages,
rule.phantomjs_load_flag, self._stop_flag)
async def _crawler(self, rule):
logger.debug('{0} crawler started'.format(rule.__rule_name__))
parser = asyncio.ensure_future(self._parser(rule.page_count))
await self._downloader(rule)
await self._pages.join()
parser.cancel()
logger.debug('{0} crawler finished'.format(rule.__rule_name__))
async def start(self):
to_crawl = [self._crawler(rule) for rule in self._rules]
await asyncio.wait(to_crawl)
def stop(self):
self._stop_flag.set() # set crawler's stop flag
logger.warning('proxy crawler was stopping...')
def reset(self):
self._stop_flag = asyncio.Event() # once setted, create a new Event object
logger.debug('proxy crawler reseted')
def proxy_crawler_run(proxies, rules = None):
pc = ProxyCrawler(proxies, rules)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(pc.start())
except:
logger.error(traceback.format_exc())
finally:
loop.close()
def proxy_crawler_test_run(proxies, count, rules = None):
pc = ProxyCrawler(proxies, rules)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(pc.start())
count.value = proxies.qsize()
except:
logger.error(traceback.format_exc())
finally:
loop.close()
if __name__ == '__main__':
proxies = asyncio.Queue()
proxy_crawler_run(proxies)
| ips = page.xpath(rule.ip_xpath)
ports = page.xpath(rule.port_xpath)
if not ips or not ports:
logger.warning('{2} crawler could not get ip(len={0}) or port(len={1}), please check the xpaths or network'.
format(len(ips), len(ports), rule.__rule_name__))
return
proxies = map(lambda x, y: '{0}:{1}'.format(x.text.strip(), y.text.strip()), ips, ports)
if rule.filters: # filter proxies
filters = []
for i, ft in enumerate(rule.filters_xpath):
field = page.xpath(ft)
if not field:
logger.warning('{1} crawler could not get {0} field, please check the filter xpath'.
format(rule.filters[i], rule.__rule_name__))
continue
filters.append(map(lambda x: x.text.strip(), field))
filters = zip(*filters)
selector = map(lambda x: x == rule.filters, filters)
proxies = compress(proxies, selector)
for proxy in proxies:
await self._proxies.put(proxy) # put proxies in Queue to validate | identifier_body |
proxy_crawler.py | import asyncio
from itertools import compress
import traceback
from proxypool.rules.rule_base import CrawlerRuleBase
from proxypool.utils import page_download, page_download_phantomjs, logger, Result
class ProxyCrawler(object):
"""Crawl proxies according to the rules."""
def __init__(self, proxies, rules=None):
"""Crawler init.
Args:
proxies: aysncio.Queue object
rules: crawler rules of each proxy web, should be iterable object
flag: stop flag for page downloading
"""
self._proxies = proxies | self._pages = asyncio.Queue()
self._rules = rules if rules else CrawlerRuleBase.__subclasses__()
async def _parse_page(self):
while 1:
page = await self._pages.get()
await self._parse_proxy(page.rule, page.content)
self._pages.task_done()
async def _parse_proxy(self, rule, page):
ips = page.xpath(rule.ip_xpath)
ports = page.xpath(rule.port_xpath)
if not ips or not ports:
logger.warning('{2} crawler could not get ip(len={0}) or port(len={1}), please check the xpaths or network'.
format(len(ips), len(ports), rule.__rule_name__))
return
proxies = map(lambda x, y: '{0}:{1}'.format(x.text.strip(), y.text.strip()), ips, ports)
if rule.filters: # filter proxies
filters = []
for i, ft in enumerate(rule.filters_xpath):
field = page.xpath(ft)
if not field:
logger.warning('{1} crawler could not get {0} field, please check the filter xpath'.
format(rule.filters[i], rule.__rule_name__))
continue
filters.append(map(lambda x: x.text.strip(), field))
filters = zip(*filters)
selector = map(lambda x: x == rule.filters, filters)
proxies = compress(proxies, selector)
for proxy in proxies:
await self._proxies.put(proxy) # put proxies in Queue to validate
@staticmethod
def _url_generator(rule):
"""Url generator of next page.
Returns:
url of next page, like: 'http://www.example.com/page/2'.
"""
page = yield Result(rule.start_url, rule)
for i in range(2, rule.page_count + 1):
if rule.urls_format:
yield
yield Result(rule.urls_format.format(rule.start_url, i), rule)
elif rule.next_page_xpath:
if page is None:
break
next_page = page.xpath(rule.next_page_xpath)
if next_page:
yield
page = yield Result(rule.next_page_host + str(next_page[0]).strip(), rule)
else:
break
async def _parser(self, count):
to_parse = [self._parse_page() for _ in range(count)]
await asyncio.wait(to_parse)
async def _downloader(self, rule):
if not rule.use_phantomjs:
await page_download(ProxyCrawler._url_generator(rule), self._pages,
self._stop_flag)
else:
await page_download_phantomjs(ProxyCrawler._url_generator(rule), self._pages,
rule.phantomjs_load_flag, self._stop_flag)
async def _crawler(self, rule):
logger.debug('{0} crawler started'.format(rule.__rule_name__))
parser = asyncio.ensure_future(self._parser(rule.page_count))
await self._downloader(rule)
await self._pages.join()
parser.cancel()
logger.debug('{0} crawler finished'.format(rule.__rule_name__))
async def start(self):
to_crawl = [self._crawler(rule) for rule in self._rules]
await asyncio.wait(to_crawl)
def stop(self):
self._stop_flag.set() # set crawler's stop flag
logger.warning('proxy crawler was stopping...')
def reset(self):
self._stop_flag = asyncio.Event() # once setted, create a new Event object
logger.debug('proxy crawler reseted')
def proxy_crawler_run(proxies, rules = None):
pc = ProxyCrawler(proxies, rules)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(pc.start())
except:
logger.error(traceback.format_exc())
finally:
loop.close()
def proxy_crawler_test_run(proxies, count, rules = None):
pc = ProxyCrawler(proxies, rules)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(pc.start())
count.value = proxies.qsize()
except:
logger.error(traceback.format_exc())
finally:
loop.close()
if __name__ == '__main__':
proxies = asyncio.Queue()
proxy_crawler_run(proxies) | self._stop_flag = asyncio.Event() # stop flag for crawler, not for validator | random_line_split |
proxy_crawler.py | import asyncio
from itertools import compress
import traceback
from proxypool.rules.rule_base import CrawlerRuleBase
from proxypool.utils import page_download, page_download_phantomjs, logger, Result
class ProxyCrawler(object):
"""Crawl proxies according to the rules."""
def __init__(self, proxies, rules=None):
"""Crawler init.
Args:
proxies: aysncio.Queue object
rules: crawler rules of each proxy web, should be iterable object
flag: stop flag for page downloading
"""
self._proxies = proxies
self._stop_flag = asyncio.Event() # stop flag for crawler, not for validator
self._pages = asyncio.Queue()
self._rules = rules if rules else CrawlerRuleBase.__subclasses__()
async def _parse_page(self):
while 1:
page = await self._pages.get()
await self._parse_proxy(page.rule, page.content)
self._pages.task_done()
async def _parse_proxy(self, rule, page):
ips = page.xpath(rule.ip_xpath)
ports = page.xpath(rule.port_xpath)
if not ips or not ports:
logger.warning('{2} crawler could not get ip(len={0}) or port(len={1}), please check the xpaths or network'.
format(len(ips), len(ports), rule.__rule_name__))
return
proxies = map(lambda x, y: '{0}:{1}'.format(x.text.strip(), y.text.strip()), ips, ports)
if rule.filters: # filter proxies
filters = []
for i, ft in enumerate(rule.filters_xpath):
field = page.xpath(ft)
if not field:
logger.warning('{1} crawler could not get {0} field, please check the filter xpath'.
format(rule.filters[i], rule.__rule_name__))
continue
filters.append(map(lambda x: x.text.strip(), field))
filters = zip(*filters)
selector = map(lambda x: x == rule.filters, filters)
proxies = compress(proxies, selector)
for proxy in proxies:
await self._proxies.put(proxy) # put proxies in Queue to validate
@staticmethod
def _url_generator(rule):
"""Url generator of next page.
Returns:
url of next page, like: 'http://www.example.com/page/2'.
"""
page = yield Result(rule.start_url, rule)
for i in range(2, rule.page_count + 1):
if rule.urls_format:
|
elif rule.next_page_xpath:
if page is None:
break
next_page = page.xpath(rule.next_page_xpath)
if next_page:
yield
page = yield Result(rule.next_page_host + str(next_page[0]).strip(), rule)
else:
break
async def _parser(self, count):
to_parse = [self._parse_page() for _ in range(count)]
await asyncio.wait(to_parse)
async def _downloader(self, rule):
if not rule.use_phantomjs:
await page_download(ProxyCrawler._url_generator(rule), self._pages,
self._stop_flag)
else:
await page_download_phantomjs(ProxyCrawler._url_generator(rule), self._pages,
rule.phantomjs_load_flag, self._stop_flag)
async def _crawler(self, rule):
logger.debug('{0} crawler started'.format(rule.__rule_name__))
parser = asyncio.ensure_future(self._parser(rule.page_count))
await self._downloader(rule)
await self._pages.join()
parser.cancel()
logger.debug('{0} crawler finished'.format(rule.__rule_name__))
async def start(self):
to_crawl = [self._crawler(rule) for rule in self._rules]
await asyncio.wait(to_crawl)
def stop(self):
self._stop_flag.set() # set crawler's stop flag
logger.warning('proxy crawler was stopping...')
def reset(self):
self._stop_flag = asyncio.Event() # once setted, create a new Event object
logger.debug('proxy crawler reseted')
def proxy_crawler_run(proxies, rules = None):
pc = ProxyCrawler(proxies, rules)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(pc.start())
except:
logger.error(traceback.format_exc())
finally:
loop.close()
def proxy_crawler_test_run(proxies, count, rules = None):
pc = ProxyCrawler(proxies, rules)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(pc.start())
count.value = proxies.qsize()
except:
logger.error(traceback.format_exc())
finally:
loop.close()
if __name__ == '__main__':
proxies = asyncio.Queue()
proxy_crawler_run(proxies)
| yield
yield Result(rule.urls_format.format(rule.start_url, i), rule) | conditional_block |
proxy_crawler.py | import asyncio
from itertools import compress
import traceback
from proxypool.rules.rule_base import CrawlerRuleBase
from proxypool.utils import page_download, page_download_phantomjs, logger, Result
class | (object):
"""Crawl proxies according to the rules."""
def __init__(self, proxies, rules=None):
"""Crawler init.
Args:
proxies: aysncio.Queue object
rules: crawler rules of each proxy web, should be iterable object
flag: stop flag for page downloading
"""
self._proxies = proxies
self._stop_flag = asyncio.Event() # stop flag for crawler, not for validator
self._pages = asyncio.Queue()
self._rules = rules if rules else CrawlerRuleBase.__subclasses__()
async def _parse_page(self):
while 1:
page = await self._pages.get()
await self._parse_proxy(page.rule, page.content)
self._pages.task_done()
async def _parse_proxy(self, rule, page):
ips = page.xpath(rule.ip_xpath)
ports = page.xpath(rule.port_xpath)
if not ips or not ports:
logger.warning('{2} crawler could not get ip(len={0}) or port(len={1}), please check the xpaths or network'.
format(len(ips), len(ports), rule.__rule_name__))
return
proxies = map(lambda x, y: '{0}:{1}'.format(x.text.strip(), y.text.strip()), ips, ports)
if rule.filters: # filter proxies
filters = []
for i, ft in enumerate(rule.filters_xpath):
field = page.xpath(ft)
if not field:
logger.warning('{1} crawler could not get {0} field, please check the filter xpath'.
format(rule.filters[i], rule.__rule_name__))
continue
filters.append(map(lambda x: x.text.strip(), field))
filters = zip(*filters)
selector = map(lambda x: x == rule.filters, filters)
proxies = compress(proxies, selector)
for proxy in proxies:
await self._proxies.put(proxy) # put proxies in Queue to validate
@staticmethod
def _url_generator(rule):
"""Url generator of next page.
Returns:
url of next page, like: 'http://www.example.com/page/2'.
"""
page = yield Result(rule.start_url, rule)
for i in range(2, rule.page_count + 1):
if rule.urls_format:
yield
yield Result(rule.urls_format.format(rule.start_url, i), rule)
elif rule.next_page_xpath:
if page is None:
break
next_page = page.xpath(rule.next_page_xpath)
if next_page:
yield
page = yield Result(rule.next_page_host + str(next_page[0]).strip(), rule)
else:
break
async def _parser(self, count):
to_parse = [self._parse_page() for _ in range(count)]
await asyncio.wait(to_parse)
async def _downloader(self, rule):
if not rule.use_phantomjs:
await page_download(ProxyCrawler._url_generator(rule), self._pages,
self._stop_flag)
else:
await page_download_phantomjs(ProxyCrawler._url_generator(rule), self._pages,
rule.phantomjs_load_flag, self._stop_flag)
async def _crawler(self, rule):
logger.debug('{0} crawler started'.format(rule.__rule_name__))
parser = asyncio.ensure_future(self._parser(rule.page_count))
await self._downloader(rule)
await self._pages.join()
parser.cancel()
logger.debug('{0} crawler finished'.format(rule.__rule_name__))
async def start(self):
to_crawl = [self._crawler(rule) for rule in self._rules]
await asyncio.wait(to_crawl)
def stop(self):
self._stop_flag.set() # set crawler's stop flag
logger.warning('proxy crawler was stopping...')
def reset(self):
self._stop_flag = asyncio.Event() # once setted, create a new Event object
logger.debug('proxy crawler reseted')
def proxy_crawler_run(proxies, rules = None):
pc = ProxyCrawler(proxies, rules)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(pc.start())
except:
logger.error(traceback.format_exc())
finally:
loop.close()
def proxy_crawler_test_run(proxies, count, rules = None):
pc = ProxyCrawler(proxies, rules)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(pc.start())
count.value = proxies.qsize()
except:
logger.error(traceback.format_exc())
finally:
loop.close()
if __name__ == '__main__':
proxies = asyncio.Queue()
proxy_crawler_run(proxies)
| ProxyCrawler | identifier_name |
main.rs | use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
use std::collections::HashMap;
extern crate regex;
use regex::Regex;
enum Ineq {
Equals(i32),
GreaterThan(i32),
LessThan(i32),
}
// --------------------------------------------------------
fn find_sue (constraints: &HashMap<&str, Ineq>, filename: &str) -> i32 {
let path = Path::new(filename);
let display = path.display();
// Open the path in read-only mode, returns `io::Result<File>`
let file = match File::open(&path) {
// The `description` method of `io::Error` returns a string that describes the error
Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
Ok(file) => file,
}; |
let reader = BufReader::new(file);
let lines = reader.lines();
let re = Regex::new(r"(?P<key>[:alpha:]+): (?P<value>\d+)").unwrap();
let mut sue_num = 0;
let mut sue_no_conflict = -1i32;
for line in lines {
let text = line.unwrap();
sue_num += 1;
let mut has_conflict = false;
for cap in re.captures_iter(&text) {
let key = cap.name("key").unwrap_or("");
let value = cap.name("value").unwrap_or("").parse::<i32>().unwrap();
match constraints.get(&key) {
Some(&Ineq::Equals(present_value)) => {
if value != present_value {
has_conflict = true;
}
},
Some(&Ineq::GreaterThan(present_value)) => {
if value <= present_value {
has_conflict = true;
}
},
Some(&Ineq::LessThan(present_value)) => {
if value >= present_value {
has_conflict = true;
}
},
_ => {},
}
}
if !has_conflict {
println!("Sue {} has no conflicts", sue_num);
sue_no_conflict = sue_num;
}
}
sue_no_conflict
}
// --------------------------------------------------------
fn main() {
println!("Running part 1...");
let mut sue_stats_exact = HashMap::new();
sue_stats_exact.insert("children", Ineq::Equals(3) );
sue_stats_exact.insert("cats", Ineq::Equals(7) );
sue_stats_exact.insert("samoyeds", Ineq::Equals(2) );
sue_stats_exact.insert("pomeranians", Ineq::Equals(3) );
sue_stats_exact.insert("akitas", Ineq::Equals(0) );
sue_stats_exact.insert("vizslas", Ineq::Equals(0) );
sue_stats_exact.insert("goldfish", Ineq::Equals(5) );
sue_stats_exact.insert("trees", Ineq::Equals(3) );
sue_stats_exact.insert("cars", Ineq::Equals(2) );
sue_stats_exact.insert("perfumes", Ineq::Equals(1) );
find_sue(&sue_stats_exact, "day16.txt");
println!("Running part 2...");
let mut sue_stats_ineq = HashMap::new();
sue_stats_ineq.insert("children", Ineq::Equals(3) );
sue_stats_ineq.insert("cats", Ineq::GreaterThan(7) );
sue_stats_ineq.insert("samoyeds", Ineq::Equals(2) );
sue_stats_ineq.insert("pomeranians", Ineq::LessThan(3) );
sue_stats_ineq.insert("akitas", Ineq::Equals(0) );
sue_stats_ineq.insert("vizslas", Ineq::Equals(0) );
sue_stats_ineq.insert("goldfish", Ineq::LessThan(5) );
sue_stats_ineq.insert("trees", Ineq::GreaterThan(3) );
sue_stats_ineq.insert("cars", Ineq::Equals(2) );
sue_stats_ineq.insert("perfumes", Ineq::Equals(1) );
find_sue(&sue_stats_ineq, "day16.txt");
} | random_line_split | |
main.rs |
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
use std::collections::HashMap;
extern crate regex;
use regex::Regex;
enum Ineq {
Equals(i32),
GreaterThan(i32),
LessThan(i32),
}
// --------------------------------------------------------
fn find_sue (constraints: &HashMap<&str, Ineq>, filename: &str) -> i32 {
let path = Path::new(filename);
let display = path.display();
// Open the path in read-only mode, returns `io::Result<File>`
let file = match File::open(&path) {
// The `description` method of `io::Error` returns a string that describes the error
Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
Ok(file) => file,
};
let reader = BufReader::new(file);
let lines = reader.lines();
let re = Regex::new(r"(?P<key>[:alpha:]+): (?P<value>\d+)").unwrap();
let mut sue_num = 0;
let mut sue_no_conflict = -1i32;
for line in lines {
let text = line.unwrap();
sue_num += 1;
let mut has_conflict = false;
for cap in re.captures_iter(&text) {
let key = cap.name("key").unwrap_or("");
let value = cap.name("value").unwrap_or("").parse::<i32>().unwrap();
match constraints.get(&key) {
Some(&Ineq::Equals(present_value)) => {
if value != present_value {
has_conflict = true;
}
},
Some(&Ineq::GreaterThan(present_value)) => {
if value <= present_value {
has_conflict = true;
}
},
Some(&Ineq::LessThan(present_value)) => {
if value >= present_value |
},
_ => {},
}
}
if !has_conflict {
println!("Sue {} has no conflicts", sue_num);
sue_no_conflict = sue_num;
}
}
sue_no_conflict
}
// --------------------------------------------------------
fn main() {
println!("Running part 1...");
let mut sue_stats_exact = HashMap::new();
sue_stats_exact.insert("children", Ineq::Equals(3) );
sue_stats_exact.insert("cats", Ineq::Equals(7) );
sue_stats_exact.insert("samoyeds", Ineq::Equals(2) );
sue_stats_exact.insert("pomeranians", Ineq::Equals(3) );
sue_stats_exact.insert("akitas", Ineq::Equals(0) );
sue_stats_exact.insert("vizslas", Ineq::Equals(0) );
sue_stats_exact.insert("goldfish", Ineq::Equals(5) );
sue_stats_exact.insert("trees", Ineq::Equals(3) );
sue_stats_exact.insert("cars", Ineq::Equals(2) );
sue_stats_exact.insert("perfumes", Ineq::Equals(1) );
find_sue(&sue_stats_exact, "day16.txt");
println!("Running part 2...");
let mut sue_stats_ineq = HashMap::new();
sue_stats_ineq.insert("children", Ineq::Equals(3) );
sue_stats_ineq.insert("cats", Ineq::GreaterThan(7) );
sue_stats_ineq.insert("samoyeds", Ineq::Equals(2) );
sue_stats_ineq.insert("pomeranians", Ineq::LessThan(3) );
sue_stats_ineq.insert("akitas", Ineq::Equals(0) );
sue_stats_ineq.insert("vizslas", Ineq::Equals(0) );
sue_stats_ineq.insert("goldfish", Ineq::LessThan(5) );
sue_stats_ineq.insert("trees", Ineq::GreaterThan(3) );
sue_stats_ineq.insert("cars", Ineq::Equals(2) );
sue_stats_ineq.insert("perfumes", Ineq::Equals(1) );
find_sue(&sue_stats_ineq, "day16.txt");
}
| {
has_conflict = true;
} | conditional_block |
main.rs |
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;
use std::collections::HashMap;
extern crate regex;
use regex::Regex;
enum | {
Equals(i32),
GreaterThan(i32),
LessThan(i32),
}
// --------------------------------------------------------
fn find_sue (constraints: &HashMap<&str, Ineq>, filename: &str) -> i32 {
let path = Path::new(filename);
let display = path.display();
// Open the path in read-only mode, returns `io::Result<File>`
let file = match File::open(&path) {
// The `description` method of `io::Error` returns a string that describes the error
Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
Ok(file) => file,
};
let reader = BufReader::new(file);
let lines = reader.lines();
let re = Regex::new(r"(?P<key>[:alpha:]+): (?P<value>\d+)").unwrap();
let mut sue_num = 0;
let mut sue_no_conflict = -1i32;
for line in lines {
let text = line.unwrap();
sue_num += 1;
let mut has_conflict = false;
for cap in re.captures_iter(&text) {
let key = cap.name("key").unwrap_or("");
let value = cap.name("value").unwrap_or("").parse::<i32>().unwrap();
match constraints.get(&key) {
Some(&Ineq::Equals(present_value)) => {
if value != present_value {
has_conflict = true;
}
},
Some(&Ineq::GreaterThan(present_value)) => {
if value <= present_value {
has_conflict = true;
}
},
Some(&Ineq::LessThan(present_value)) => {
if value >= present_value {
has_conflict = true;
}
},
_ => {},
}
}
if !has_conflict {
println!("Sue {} has no conflicts", sue_num);
sue_no_conflict = sue_num;
}
}
sue_no_conflict
}
// --------------------------------------------------------
fn main() {
println!("Running part 1...");
let mut sue_stats_exact = HashMap::new();
sue_stats_exact.insert("children", Ineq::Equals(3) );
sue_stats_exact.insert("cats", Ineq::Equals(7) );
sue_stats_exact.insert("samoyeds", Ineq::Equals(2) );
sue_stats_exact.insert("pomeranians", Ineq::Equals(3) );
sue_stats_exact.insert("akitas", Ineq::Equals(0) );
sue_stats_exact.insert("vizslas", Ineq::Equals(0) );
sue_stats_exact.insert("goldfish", Ineq::Equals(5) );
sue_stats_exact.insert("trees", Ineq::Equals(3) );
sue_stats_exact.insert("cars", Ineq::Equals(2) );
sue_stats_exact.insert("perfumes", Ineq::Equals(1) );
find_sue(&sue_stats_exact, "day16.txt");
println!("Running part 2...");
let mut sue_stats_ineq = HashMap::new();
sue_stats_ineq.insert("children", Ineq::Equals(3) );
sue_stats_ineq.insert("cats", Ineq::GreaterThan(7) );
sue_stats_ineq.insert("samoyeds", Ineq::Equals(2) );
sue_stats_ineq.insert("pomeranians", Ineq::LessThan(3) );
sue_stats_ineq.insert("akitas", Ineq::Equals(0) );
sue_stats_ineq.insert("vizslas", Ineq::Equals(0) );
sue_stats_ineq.insert("goldfish", Ineq::LessThan(5) );
sue_stats_ineq.insert("trees", Ineq::GreaterThan(3) );
sue_stats_ineq.insert("cars", Ineq::Equals(2) );
sue_stats_ineq.insert("perfumes", Ineq::Equals(1) );
find_sue(&sue_stats_ineq, "day16.txt");
}
| Ineq | identifier_name |
ascii_chars_increasing.rs | use malachite_base::chars::exhaustive::ascii_chars_increasing;
#[test]
fn | () {
assert_eq!(
ascii_chars_increasing().collect::<String>(),
"\u{0}\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}\u{7}\u{8}\t\n\u{b}\u{c}\r\u{e}\u{f}\u{10}\u{11}\u{12}\
\u{13}\u{14}\u{15}\u{16}\u{17}\u{18}\u{19}\u{1a}\u{1b}\u{1c}\u{1d}\u{1e}\u{1f} !\"#$%&\'()*\
+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u{7f}"
);
assert_eq!(ascii_chars_increasing().count(), 1 << 7);
}
| test_ascii_chars_increasing | identifier_name |
ascii_chars_increasing.rs | use malachite_base::chars::exhaustive::ascii_chars_increasing;
#[test]
fn test_ascii_chars_increasing() | {
assert_eq!(
ascii_chars_increasing().collect::<String>(),
"\u{0}\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}\u{7}\u{8}\t\n\u{b}\u{c}\r\u{e}\u{f}\u{10}\u{11}\u{12}\
\u{13}\u{14}\u{15}\u{16}\u{17}\u{18}\u{19}\u{1a}\u{1b}\u{1c}\u{1d}\u{1e}\u{1f} !\"#$%&\'()*\
+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u{7f}"
);
assert_eq!(ascii_chars_increasing().count(), 1 << 7);
} | identifier_body | |
ascii_chars_increasing.rs | use malachite_base::chars::exhaustive::ascii_chars_increasing;
#[test]
fn test_ascii_chars_increasing() {
assert_eq!(
ascii_chars_increasing().collect::<String>(),
"\u{0}\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}\u{7}\u{8}\t\n\u{b}\u{c}\r\u{e}\u{f}\u{10}\u{11}\u{12}\
\u{13}\u{14}\u{15}\u{16}\u{17}\u{18}\u{19}\u{1a}\u{1b}\u{1c}\u{1d}\u{1e}\u{1f} !\"#$%&\'()*\
+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u{7f}" | );
assert_eq!(ascii_chars_increasing().count(), 1 << 7);
} | random_line_split | |
51_N-Queens.py | class Solution(object):
def | (self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
def search(cur):
if cur == n:
add_answer()
else:
for i in range(n):
ok = True
rows[cur] = i
for j in range(cur):
if not is_valied(cur, j):
ok = False
break
if ok:
search(cur + 1)
def is_valied(pre_row, cur_row):
if rows[pre_row] == rows[cur_row] or \
pre_row - rows[pre_row] == cur_row - rows[cur_row] or \
pre_row + rows[pre_row] == cur_row + rows[cur_row]:
return False
else:
return True
def add_answer():
ans = []
for num in rows:
res_str = ""
for i in range(n):
if i == num:
res_str += "Q"
else:
res_str += "."
ans.append(res_str)
result.append(ans)
result = []
rows = [0] * n
search(0)
return result
print Solution().solveNQueens(4)
| solveNQueens | identifier_name |
51_N-Queens.py | class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
def search(cur):
if cur == n:
add_answer()
else:
for i in range(n):
ok = True
rows[cur] = i
for j in range(cur):
if not is_valied(cur, j):
ok = False
break
if ok:
search(cur + 1)
def is_valied(pre_row, cur_row):
if rows[pre_row] == rows[cur_row] or \
pre_row - rows[pre_row] == cur_row - rows[cur_row] or \
pre_row + rows[pre_row] == cur_row + rows[cur_row]:
|
else:
return True
def add_answer():
ans = []
for num in rows:
res_str = ""
for i in range(n):
if i == num:
res_str += "Q"
else:
res_str += "."
ans.append(res_str)
result.append(ans)
result = []
rows = [0] * n
search(0)
return result
print Solution().solveNQueens(4)
| return False | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.