text:
// ***********************************************************************
// Copyright (c) 2019-2021 Charlie Poole, Terje Sandstrom
//
// 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.
// ***********************************************************************

using System.Linq;
using NUnit.Framework;

namespace NUnit.VisualStudio.TestAdapter.Tests
{
    public class CurrentDirectoryTests
    {
        [TestCase(@"C:\Windows")]
        [TestCase(@"C:\Windows\Whatever")]
        [TestCase(@"C:\Program Files\Something")]
        [TestCase(@"C:\Program Files (x86)\Something")]
        [Platform("Win")]
        public void ThatWeFindForbiddenFolders(string folder)
        {
            var sut = new NUnit3TestExecutor();
            sut.InitializeForbiddenFolders();
            Assert.That(sut.CheckDirectory(folder));
        }

        [TestCase(@"C:\Whatever")]
        [TestCase(@"C:\WindowsWhatever")]
        [TestCase(@"C:\Program Files Whatever\Something")]
        public void ThatWeAcceptNonForbiddenFolders(string folder)
        {
            var sut = new NUnit3TestExecutor();
            sut.InitializeForbiddenFolders();
            Assert.That(sut.CheckDirectory(folder), Is.False);
        }

        [Test]
        public void ThatForbiddenFoldersAreUnique()
        {
            var sut = new NUnit3TestExecutor();
            sut.InitializeForbiddenFolders();
            var sutunique = sut.ForbiddenFolders.Distinct();
            Assert.That(sutunique.Count(), Is.EqualTo(sut.ForbiddenFolders.Count), "There are duplicate entries in ForbiddenFolders");
        }
    }
}


text:
Minor

### Version Introduced
4.5

### Version Reverted
4.6.2

### Source Analyzer Status
NotPlanned

### Change Description
Suppose a Selector (with multiple selection enabled) has duplicates in its SelectedItems
collection - the same item appears more than once.  Removing those items from the
data source (e.g. by calling Items.Clear) fails to remove them from SelectedItems;
only the first instance is removed.  Furthermore, subsequent use of SelectedItems
(e.g. SelectedItems.Clear()) can encounter problems such as ArgumentException, because
SelectedItems contains items that are no longer in the data source.

- [ ] Quirked
- [ ] Build-time break

### Recommended Action
Upgrade if possible to .NET 4.6.2.

### Affected APIs
* `P:System.Windows.Controls.Primitives.MultiSelector.SelectedItems`

### Category
Windows Presentation Foundation (WPF)

<!--
    ### Original Bug
    154627
-->

redpajama_set_name: RedPajamaGithub


text:
package com.javarush.task.task13.task1325;

import java.awt.*;

/*
Компиляция программы
1. Исправь классы Fox и BigFox так, чтобы программа компилировалась.
Задача не предполагает создания экземпляров базового класса.
2. Метод main менять нельзя.
*/

public class Solution {

    public static void main(String[] args) throws Exception {
        Fox bigFox = new BigFox();
        System.out.println(bigFox.getName());
        System.out.println(bigFox.getColor());
    }

    public interface Animal {
        Color getColor();
    }

    public abstract static class Fox implements Animal {
        public String getName() {
            return "Fox";
        }

    }

    public static class BigFox extends Fox {

        @Override
        public Color getColor() {
            return null;
        }

    }

}


text:
import unittest

from edb.common import debug

class DebugTests(unittest.TestCase):

    def test_common_debug_flags(self):
        flags = {flag.name: flag for flag in debug.flags}
        self.assertIn('edgeql_compile', flags)
        self.assertIn('EdgeQL', flags['edgeql_compile'].doc)
        self.assertIsInstance(debug.flags.edgeql_compile, bool)


text:
package gov.va.med.lom.avs.model;

import java.io.Serializable;
import javax.persistence.*;

@Entity
@Table(name="ckoHealthFactors")
public class FacilityHealthFactor extends BaseModel implements Serializable  {

  private String stationNo;
  private String type;
  private String ien;
  private String value;

  public String getStationNo() {
    return stationNo;
  }
  public void setStationNo(String stationNo) {
    this.stationNo = stationNo;
  }
  public String getType() {
    return type;
  }
  public void setType(String type) {
    this.type = type;
  }
  public String getIen() {
    return ien;
  }
  public void setIen(String ien) {
    this.ien = ien;
  }
  public String getValue() {
    return value;
  }
  public void setValue(String value) {
    this.value = value;
  }

}


text:
from sys import version_info
if version_info >= (2,6,0):
    def swig_import_helper():
        from os.path import dirname
        import imp
        fp = None
        try:
            fp, pathname, description = imp.find_module('_param_NoncoherentBus', [dirname(__file__)])
        except ImportError:
            import _param_NoncoherentBus
            return _param_NoncoherentBus
        if fp is not None:
            try:
                _mod = imp.load_module('_param_NoncoherentBus', fp, pathname, description)
            finally:
                fp.close()
            return _mod
    _param_NoncoherentBus = swig_import_helper()
    del swig_import_helper
else:
    import _param_NoncoherentBus
del version_info
try:
    _swig_property = property
except NameError:
    pass # Python < 2.2 doesn't have 'property'.
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
    if (name == "thisown"): return self.this.own(value)
    if (name == "this"):
        if type(value).__name__ == 'SwigPyObject':
            self.__dict__[name] = value
            return
    method = class_type.__swig_setmethods__.get(name,None)
    if method: return method(self,value)
    if (not static) or hasattr(self,name):
        self.__dict__[name] = value
    else:
        raise AttributeError("You cannot add attributes to %s" % self)

def _swig_setattr(self,class_type,name,value):
    return _swig_setattr_nondynamic(self,class_type,name,value,0)

def _swig_getattr(self,class_type,name):
    if (name == "thisown"): return self.this.own()
    method = class_type.__swig_getmethods__.get(name,None)
    if method: return method(self)
    raise AttributeError(name)

def _swig_repr(self):
    try: strthis = "proxy of " + self.this.__repr__()
    except: strthis = ""
    return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)

try:
    _object = object
    _newclass = 1
except AttributeError:
    class _object : pass
    _newclass = 0

def _swig_setattr_nondynamic_method(set):
    def set_attr(self,name,value):
        if (name == "thisown"): return self.this.own(value)
        if hasattr(self,name) or (name == "this"):
            set(self,name,value)
        else:
            raise AttributeError("You cannot add attributes to %s" % self)
    return set_attr

import param_BaseBus
import param_MemObject
import param_SimObject
class NoncoherentBus(param_BaseBus.BaseBus):
    thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
    def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined")
    __repr__ = _swig_repr
NoncoherentBus_swigregister = _param_NoncoherentBus.NoncoherentBus_swigregister
NoncoherentBus_swigregister(NoncoherentBus)

class NoncoherentBusParams(param_BaseBus.BaseBusParams):
    thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
    __repr__ = _swig_repr
    def create(self): return _param_NoncoherentBus.NoncoherentBusParams_create(self)
    def __init__(self):
        this = _param_NoncoherentBus.new_NoncoherentBusParams()
        try: self.this.append(this)
        except: self.this = this
    __swig_destroy__ = _param_NoncoherentBus.delete_NoncoherentBusParams
    __del__ = lambda self : None;
NoncoherentBusParams_swigregister = _param_NoncoherentBus.NoncoherentBusParams_swigregister
NoncoherentBusParams_swigregister(NoncoherentBusParams)


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fillAfter="true">

  <alpha
      android:fromAlpha="1"
      android:toAlpha="0"/>

</set>


text:
package testclient

import (
	"github.com/GoogleCloudPlatform/kubernetes/pkg/fields"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
	userapi "github.com/projectatomic/atomic-enterprise/pkg/user/api"
)

// FakeIdentities implements IdentitiesInterface. Meant to be embedded into a struct to get a default
// implementation. This makes faking out just the methods you want to test easier.
type FakeIdentities struct {
	Fake *Fake
}

func (c *FakeIdentities) List(label labels.Selector, field fields.Selector) (*userapi.IdentityList, error) {
	obj, err := c.Fake.Invokes(FakeAction{Action: "list-identities"}, &userapi.IdentityList{})
	return obj.(*userapi.IdentityList), err
}

func (c *FakeIdentities) Get(name string) (*userapi.Identity, error) {
	obj, err := c.Fake.Invokes(FakeAction{Action: "get-identity", Value: name}, &userapi.Identity{})
	return obj.(*userapi.Identity), err
}

func (c *FakeIdentities) Create(identity *userapi.Identity) (*userapi.Identity, error) {
	obj, err := c.Fake.Invokes(FakeAction{Action: "create-identity", Value: identity}, &userapi.Identity{})
	return obj.(*userapi.Identity), err
}

func (c *FakeIdentities) Update(identity *userapi.Identity) (*userapi.Identity, error) {
	obj, err := c.Fake.Invokes(FakeAction{Action: "update-identity", Value: identity}, &userapi.Identity{})
	return obj.(*userapi.Identity), err
}


text:
from typing import Dict, List, Set, Tuple

from .decode import OTBNProgram
from .insn_yaml import Insn
from .section import CodeSection

class ControlLoc:
    '''Base class for control-flow locations.

    Represents a normal PC that a branch or jump instruction could link to.
    '''
    def __init__(self, pc: int) -> None:
        self.pc = pc

    @classmethod
    def is_special(cls) -> bool:
        return False

    def pretty(self) -> str:
        return '{:#x}'.format(self.pc)

class ImemEnd(ControlLoc):
    '''Represents the end of instruction memory.'''
    def __init__(self) -> None:
        super().__init__(-1)

    @classmethod
    def is_special(cls) -> bool:
        return True

    def pretty(self) -> str:
        return '<imem end>'

class Ret(ControlLoc):
    '''Represents the location at the top of the call stack.'''
    def __init__(self) -> None:
        super().__init__(-1)

    @classmethod
    def is_special(cls) -> bool:
        return True

    def pretty(self) -> str:
        return 'RET'

class Ecall(ControlLoc):
    '''Represents program termination as a result of an ecall.'''
    def __init__(self) -> None:
        super().__init__(-1)

    @classmethod
    def is_special(cls) -> bool:
        return True

    def pretty(self) -> str:
        return 'ECALL'

class LoopStart(ControlLoc):
    '''Represents the start of a loop.

    The `loop_start_pc` is the first PC of the loop body, and the `loop_end_pc`
    is the last PC of the loop body.
    '''
    def __init__(self, loop_start_pc: int, loop_end_pc: int):
        super().__init__(loop_start_pc)
        self.loop_start_pc = loop_start_pc
        self.loop_end_pc = loop_end_pc

    @classmethod
    def is_special(cls) -> bool:
        return True

    def pretty(self) -> str:
        return '<loop from {:#x}-{:#x}>'.format(self.loop_start_pc,
                                                self.loop_end_pc)

class Cycle(ControlLoc):
    '''Represents a control flow that loops back to a previous PC.

    This is not represented as a normal ControlLoc because it's convenient to
    catch these cyclic control flows rather than follow the jump/branch and
    potentially cause an infinite loop; with this structure, the control-flow
    graph remains a DAG.
    '''
    @classmethod
    def is_special(cls) -> bool:
        return True

    def pretty(self) -> str:
        return '<cycle: back to {:#x}>'.format(self.pc)

class LoopEnd(Cycle):
    '''Represents the end of a loop (looping back to the start).

    Contains the LoopStart instance we're looping back to.
    '''
    def __init__(self, loop_start: LoopStart):
        super().__init__(loop_start.loop_start_pc)
        self.loop_start = loop_start

    def pretty(self) -> str:
        return '<loop end: back to {:#x}>'.format(
            self.loop_start.loop_start_pc)

class ControlGraph:
    '''Represents the control flow graph of (part of) an OTBN program.

    The `start` PC is the entrypoint of the control-flow graph.

    The `graph` dictionary maps PCs to 2-item tuples. Not all PCs are in
    `graph`; only ones that are jumped, branched, or looped to in the control
    flow starting at `start`. The 2-item tuple for each PC is as follows:
        - 0: the CodeSection that starts at the PC. It is guaranteed to be 0
          or more straightline instructions, followed by a final
          non-straightline instruction.
        - 1: a list of the various control-flow locations that can be reached
          *after* the CodeSection has run.  For example, a CodeSection ending
          in a BNE instruction would have two ControlLocs in its list, and a
          CodeSection ending in `ret` would have a single Ret() instance in its
          list.
    '''
    def __init__(self, start: int, graph: Dict[int, Tuple[CodeSection,
                                                          List[ControlLoc]]]):
        for pc, (sec, _) in graph.items():
            assert sec.start == pc
        self.start = start
        self.graph = graph

    def get_entry(self, pc: int) -> Tuple[CodeSection, List[ControlLoc]]:
        '''Returns the entry in the graph for the given PC.

        Raises a ValueError if the PC is not in the graph.
        '''
        try:
            return self.graph[pc]
        except KeyError:
            graph_pcs = [hex(pc) for pc in self.graph.keys()]
            raise ValueError(
                'PC {:#x} not found in control graph (PCs in graph are: {})'.
                format(pc, graph_pcs)) from None

    def get_section(self, pc: int) -> CodeSection:
        '''Returns the CodeSection for the given PC.

        Raises a ValueError if the PC is not in the graph.
        '''
        return self.get_entry(pc)[0]

    def get_edges(self, pc: int) -> List[ControlLoc]:
        '''Returns the edges for the section starting at pc.

        Raises a ValueError if the PC is not in the graph.
        '''
        return self.get_entry(pc)[1]

    def get_cycle_starts(self) -> Set[int]:
        '''Returns start PCs of all marked cycles in the graph.'''
        out = set()
        for pc, entry in self.graph.items():
            for edge in entry[1]:
                if isinstance(edge, Cycle):
                    out.add(edge.pc)
        return out

    def _pretty_lines(self,
                      program: OTBNProgram,
                      entry_pc: int,
                      concise: bool,
                      already_printed: Set[int],
                      call_stack: List[int] = []) -> List[Tuple[int, str]]:
        '''Returns lines for pretty-printing.

        Returns each line as an (int,str) pair, where the int is the indent
        level.
        '''
        out = []
        sec, edges = self.get_entry(entry_pc)
        symbols = [s for s in program.get_symbols_for_pc(entry_pc) if s != '']
        pcs_to_print = list(range(sec.start, sec.end + 4, 4))
        if entry_pc in already_printed and not concise:
            if len(symbols) > 0:
                out.append((0, '<{}> (see above)'.format(', '.join(symbols))))
            else:
                out.append(
                    (0, '{:#x}..{:#x} (see above)'.format(entry_pc, sec.end)))
            pcs_to_print = []
        elif len(symbols) > 0:
            out.append((0, '<{}>'.format(', '.join(symbols))))
        if concise:
            # only print last insn
            out.append((0, '...'))
            pcs_to_print = [sec.end]
        for pc in pcs_to_print:
            insn = program.get_insn(pc)
            operands = program.get_operands(pc)
            disassembly = insn.disassemble(pc, operands)
            out.append((0, '{:#x}: {}'.format(pc, disassembly)))
            already_printed.add(sec.start)
        # Indent if we have more than 1 non-special edge, excluding LoopEnds
        # (i.e. if this is a branch)
        non_special_edges = [
            loc for loc in edges
            if not (loc.is_special() or isinstance(loc, LoopEnd))
        ]
        child_indent = 0 if len(non_special_edges) <= 1 else 2
        if any(map(lambda loc: isinstance(loc, LoopEnd), edges)):
            child_indent = -2
        for loc in edges:
            if isinstance(loc, LoopEnd):
                out.append((0, loc.pretty()))
                continue
            if len(non_special_edges) > 1:
                last_insn = program.get_insn(sec.end)
                out.append((0, '-> (branch from {:#x}: {})'.format(
                    sec.end, last_insn.mnemonic)))
            if loc.is_special():
                out.append((child_indent, loc.pretty()))
                if isinstance(loc, Ret) and len(call_stack) > 0:
                    # pop the call stack and print flow after return to caller
                    out += [(indent - 2, line)
                            for indent, line in self._pretty_lines(
                                program, call_stack[0], concise,
                                already_printed, call_stack[1:])]
                if isinstance(loc, LoopStart):
                    out += [(indent + child_indent + 2, line)
                            for indent, line in self._pretty_lines(
                                program, loc.loop_start_pc, concise,
                                already_printed, call_stack)]
            else:
                insn = program.get_insn(sec.end)
                operands = program.get_operands(sec.end)
                if insn.mnemonic == 'jal' and operands['grd'] == 1:
                    # push to to the call stack
                    call_stack = [sec.end + 4] + call_stack
                    child_indent += 2
                out += [
                    (indent + child_indent, line)
                    for indent, line in self._pretty_lines(
                        program, loc.pc, concise, already_printed, call_stack)
                ]
        return out

    def pretty(self,
               program: OTBNProgram,
               indent: int = 0,
               concise: bool = False) -> str:
        '''Returns string for pretty-printing.'''
        lines = self._pretty_lines(program, self.start, concise, set())
        lines = [(indent + lindent, line) for (lindent, line) in lines]
        line_strings = [
            '{}{}'.format(' ' * lindent, line) for (lindent, line) in lines
        ]
        return '\n'.join(line_strings)

def _clip_to_32(value: int) -> int:
    '''Truncates a number to 32 bits.'''
    return value & ((1 << 32) - 1)

def _get_next_control_locations(insn: Insn, operands: Dict[str, int],
                                pc: int) -> List[ControlLoc]:
    '''Given a control-flow instruction, returns the possible destinations.

    Raises a RuntimeError if the instruction is not a recognized control-flow
    instruction, or if some unsupported construct is encountered.
    '''
    if insn.mnemonic == 'beq' or insn.mnemonic == 'bne':
        branch_dst = _clip_to_32(operands['offset'])
        # Branch can either go to branch_dst or next PC
        return [ControlLoc(branch_dst), ControlLoc(pc + 4)]
    elif insn.mnemonic == 'jal':
        jump_dst = _clip_to_32(operands['offset'])
        return [ControlLoc(jump_dst)]
    elif insn.mnemonic == 'jalr':
        if operands['grs1'] != 1:
            # This is a function call through a pointer e.g. `jal x1,
            # <addr>, 0`; not currently supported
            raise RuntimeError(
                'Cannot create control graph because of a function '
                'call from a pointer at PC {:#x}: {}\nThis is '
                'permitted by OTBN but not supported by this check.'.format(
                    pc, insn.disassemble(pc, operands)))
        if operands['offset'] != 0:
            raise RuntimeError(
                'Cannot create control graph because of a nonzero offset for '
                'JALR at PC {:#x}: {}.\nThis is permitted by OTBN but not '
                'supported by this check.'.format(
                    pc, insn.disassemble(pc, operands)))
        # This jump returns to whatever's on top of the call stack
        return [Ret()]
    elif insn.mnemonic == 'loopi' or insn.mnemonic == 'loop':
        loop_end_pc = pc + (operands['bodysize'] * 4)
        return [LoopStart(pc + 4, loop_end_pc)]
    elif insn.mnemonic == 'ecall':
        return [Ecall()]

    raise RuntimeError(
        'Unrecognized control flow instruction (straight-line=false) at PC {:#x}: {}'
        .format(pc, insn.disassemble(pc, operands)))

def _populate_control_graph(graph: ControlGraph, program: OTBNProgram,
                            start_pc: int,
                            loop_stack: List[LoopStart]) -> None:
    '''Populates input control flow graph starting from start_pc.

    The `loop_stack` argument holds the LoopStart instances for all the loops
    that enclose the start_pc, with the innermost loop first. This routine
    checks only for the innermost loop's end PC; if the loops are incorrectly
    nested, it will not warn. However, it will raise a RuntimeError if the loop
    stack size (8) is exceeded.

    This function will not record cycles in the control graph with the Cycle
    instance; run _fix_cycles afterward.
    '''
    LOOP_STACK_SIZE = 8

    if start_pc in graph.graph:
        # Nothing to do; this section has already been populated.
        return

    # Top element of the loop stack, if any:
    loop = loop_stack[0] if len(loop_stack) > 0 else None

    # Follow straightline code until we get to a control flow instruction, the
    # end of the loop body, or the end of imem
    for pc in range(start_pc, program.max_pc() + 4, 4):

        # Special handling for reaching the end of a loop body
        if loop is not None and pc == loop.loop_end_pc:
            # Finished the loop; add the current section and connect it to a
            # LoopEnd instance as well as the next pc, then recurse on the next
            # PC.
            sec = CodeSection(start_pc, pc)
            graph.graph[start_pc] = (sec, [LoopEnd(loop), ControlLoc(pc + 4)])
            _populate_control_graph(graph, program, pc + 4, loop_stack[1:])
            return

        insn = program.get_insn(pc)
        if insn.straight_line:
            continue
        operands = program.get_operands(pc)
        section = CodeSection(start_pc, pc)
        locs = _get_next_control_locations(insn, operands, pc)
        if start_pc in graph.graph:
            raise RuntimeError
        graph.graph[start_pc] = (section, locs)

        # Recurse on next control-flow locations.
        for loc in locs:
            if not loc.is_special():
                # Destination is just a normal PC
                _populate_control_graph(graph, program, loc.pc, loop_stack)
            elif isinstance(loc, LoopStart):
                if len(loop_stack) >= LOOP_STACK_SIZE - 1:
                    loop_start_pcs = [
                        loop.loop_start_pc for loop in [loc] + loop_stack
                    ]
                    raise RuntimeError(
                        'Loop stack overflow at PC {} (loop stack includes '
                        'loops starting at the following PCs: {})'.format(
                            pc, loop_start_pcs))
                _populate_control_graph(graph, program, loc.loop_start_pc,
                                        [loc] + loop_stack)
            elif isinstance(loc, ImemEnd) or isinstance(
                    loc, Ecall) or isinstance(loc, Ret):
                # Nothing more to do
                pass
            else:
                raise ValueError(
                    'Control-flow location of type {} is special '
                    'but does not have a recognized special type.'.format(
                        type(loc)))

        # If this was a jump that pushed to the call stack, we need to also
        # populate the control graph for what happens after we return from the
        # jump
        if insn.mnemonic == 'jal' and operands['grd'] == 1:
            _populate_control_graph(graph, program, pc + 4, loop_stack)

        return

    # If we get here, we've reached the max PC
    graph.graph[start_pc] = (CodeSection(start_pc,
                                         program.max_pc()), [ImemEnd()])
    return

def _label_cycles(program: OTBNProgram, graph: ControlGraph, start_pc: int,
                  visited_pcs: Set[int]) -> None:
    '''Creates Cycle edges to remove cyclic control flow from the graph.

    Modifies graph in place. Works by replacing edges that loop back to an
    already-traversed part of the control flow with a Cycle instance.
    '''
    sec, edges = graph.get_entry(start_pc)
    for pc in sec:
        visited_pcs.add(pc)
    for i in range(len(edges)):
        edge = edges[i]
        if isinstance(edge, Ret) or isinstance(edge, ImemEnd) or isinstance(
                edge, Ecall):
            # Cannot possibly loop back
            continue
        elif isinstance(edge, Cycle):
            # Done; no need to traverse or replace
            continue
        if edge.pc in visited_pcs:
            # Replace with Cycle instance and do not traverse
            edges[i] = Cycle(edge.pc)
        else:
            _label_cycles(program, graph, edge.pc, visited_pcs.copy())

def _fix_cycles(program: OTBNProgram, graph: ControlGraph) -> None:
    '''Labels cycles and splits them from other CodeSections in the graph.

    Modifies graph in place.
    '''
    _label_cycles(program, graph, graph.start, set())
    cycle_start_pcs = graph.get_cycle_starts()
    # The new_entries dictionary will have the same structure as graph.graph.
    new_entries = {}
    for start_pc in graph.graph:
        sec, edges = graph.get_entry(start_pc)
        for pc in sec:
            if pc in cycle_start_pcs and pc != sec.start:
                # Split this section and create a new edge leading to the cycle
                new_entries[start_pc] = (CodeSection(start_pc,
                                                     pc), [ControlLoc(pc)])
                break
    graph.graph.update(new_entries)

def _make_control_graph(program: OTBNProgram, start_pc: int) -> ControlGraph:
    '''Constructs a control flow graph with start_pc as the entrypoint.

    Assumes the loop stack is empty at start_pc.
    '''
    graph = ControlGraph(start_pc, {})
    _populate_control_graph(graph, program, start_pc, [])
    _fix_cycles(program, graph)
    return graph

def program_control_graph(program: OTBNProgram) -> ControlGraph:
    '''Constructs a control flow graph representing an entire program.'''
    return _make_control_graph(program, program.min_pc())

def subroutine_control_graph(program: OTBNProgram,
                             subroutine: str) -> ControlGraph:
    '''Control flow graph from the given symbol to the first unmatched `ret`.

    The control flow graph finishes when either an `ecall` instruction is
    reached or a `ret` returns to the caller of the subroutine.
    '''
    start_pc = program.get_pc_at_symbol(subroutine)
    return _make_control_graph(program, start_pc)


text:
require 'dump/env'

module Dump
  # Methods to work with db using ActiveRecord
  module TableManipulation
  protected

    def schema_tables
      %w[schema_info schema_migrations]
    end

    def verify_connection
      connection.verify!(0)
    end

    def quote_table_name(table)
      connection.quote_table_name(table)
    end

    def quote_column_name(column)
      connection.quote_column_name(column)
    end

    def quote_value(value)
      connection.quote(value)
    end

    def clear_table(table_sql)
      connection.delete("DELETE FROM #{table_sql}", 'Clearing table')
    end

    def insert_into_table(table_sql, columns_sql, values_sql)
      values_sql = values_sql.join(',') if values_sql.is_a?(Array)
      sql = "INSERT INTO #{table_sql} #{columns_sql} VALUES #{values_sql}"
      connection.insert(sql, 'Loading dump')
    end

    def fix_sequence!(table)
      return unless connection.respond_to?(:reset_pk_sequence!)
      connection.reset_pk_sequence!(table)
    end

    def join_for_sql(quoted)
      "(#{quoted.join(',')})"
    end

    def columns_insert_sql(columns)
      join_for_sql(columns.map{ |column| quote_column_name(column) })
    end

    def values_insert_sql(values)
      join_for_sql(values.map{ |value| quote_value(value) })
    end

    def avaliable_tables
      connection.tables
    end

    def tables_to_dump
      if Dump::Env[:tables]
        avaliable_tables.select do |table|
          schema_tables.include?(table) ||
            Dump::Env.filter(:tables).pass?(table)
        end
      else
        avaliable_tables - %w[sessions]
      end
    end

    def table_row_count(table)
      sql = "SELECT COUNT(*) FROM #{quote_table_name(table)}"
      connection.select_value(sql).to_i
    end

    CHUNK_SIZE_MIN = 100
    CHUNK_SIZE_MAX = 3_000
    def table_chunk_size(table)
      expected_row_size = table_columns(table).sum do |column|
        case column.type
        when :text
          Math.sqrt(column.limit || 2_147_483_647)
        when :string
          Math.sqrt(column.limit || 255)
        else
          column.limit || 10
        end
      end
      [
        CHUNK_SIZE_MIN,
        (10_000_000 / expected_row_size).round,
        CHUNK_SIZE_MAX,
      ].sort[1]
    end

    def table_columns(table)
      connection.columns(table)
    end

    def table_has_primary_column?(table)
      # bad test for primary column, but primary even for primary column is nil
      table_columns(table).any? do |column|
        column.name == table_primary_key(table) && column.type == :integer
      end
    end

    def table_primary_key(_table)
      'id'
    end

    def each_table_row(table, row_count, &block)
      chunk_size = table_chunk_size(table)
      if table_has_primary_column?(table) && row_count > chunk_size
        # adapted from ActiveRecord::Batches
        primary_key = table_primary_key(table)
        quoted_primary_key =
          "#{quote_table_name(table)}.#{quote_column_name(primary_key)}"
        select_where_primary_key =
          "SELECT * FROM #{quote_table_name(table)}" \
            " WHERE #{quoted_primary_key} %s" \
            " ORDER BY #{quoted_primary_key} ASC" \
            " LIMIT #{chunk_size}"
        rows = select_all_by_sql(select_where_primary_key % '>= 0')
        until rows.blank?
          rows.each(&block)
          break if rows.count < chunk_size
          sql = select_where_primary_key % "> #{rows.last[primary_key].to_i}"
          rows = select_all_by_sql(sql)
        end
      else
        table_rows(table).each(&block)
      end
    end

    def table_rows(table)
      select_all_by_sql("SELECT * FROM #{quote_table_name(table)}")
    end

    def select_all_by_sql(sql)
      connection.select_all(sql)
    end

  private

    def connection
      ActiveRecord::Base.connection
    end
  end
end


text: search_result['2877']=["topic_00000000000006EB_methods--.html","StaffProfile Methods",""];


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Orcamentos extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
            $this->load->model('orcamento_model');
                $this->load->model('usuarios_model');

                $this->load->library('pagination');

            $config = array(
            "base_url" => base_url()."index.php/orcamentos/p",
            "per_page" => 3,
            "num_links" => 6,
            "uri_segment" => 3,
            "total_rows" => $this->orcamento_model->pegarQtdOrcamentos(),
            "full_tag_open" => "
",
            "full_tag_close" => "
",
            "first_link" => TRUE,
            "last_link" => FALSE,
            "first_tag_open" => "
",
            "first_tag_close" => "
",
            "prev_link" => "Anterior",
            "prev_tag_open" => "
",
            "prev_tag_close" => "
",
            "next_link" => "Próxima",
            "next_tag_open" => "
",
            "next_tag_close" => "
",
            "last_tag_open" => "
",
            "last_tag_close" => "
",
            "cur_tag_open" => "
",
            "cur_tag_close" => "
",
            "num_tag_open" => "
",
            "num_tag_close" => "
"
        );
              $this->pagination->initialize($config);

        $dados["pagination"] = $this->pagination->create_links();
        $offset = ($this->uri->segment(3)) ? $this->uri->segment(3) :0;

        $dados["orcamentos"] = $this->orcamento_model->pegarOrcamentos($config['per_page'],$offset);

		$this->load->view('orcamentos/inicio', $dados);
	}

        public function novoOrcamento(){
             $this->load->model('usuarios_model');
            if($this->usuarios_model->checarSessao()){
                $dados['logado'] = true;
		$this->load->view('orcamentos/novo_orcamento', $dados);
           }else {
               $dados['logado'] = false;
               $this->load->view('orcamentos/novo_orcamento', $dados);
           }

        }
        public function visualizarOrcamento($indice = null){
                   $this->load->model('orcamento_model');
        $this->load->model('usuarios_model');
        if ($indice == null) {
            redirect(base_url());
        } else if($this->orcamento_model->contarOrcamentoId($indice) == 1){
            $dados['orcamento'] = $this->orcamento_model->pegarOrcamentoId($indice);

            $this->load->view('orcamentos/visualizar_orcamento', $dados);
        }else{
             $dados['heading'] = "O produto não existe";
             $dados['message'] = "Impossível visualizar este produto pois ele não se encontra na nossa base de dados.";
             $this->load->view('errors/html/error_general', $dados);
        }

        }

        public function fazerCadastroOrcamento(){
            $this->load->model('orcamento_model');
            if($this->orcamento_model->cadastrarOrcamento()){
               redirect(base_url()."index.php/usuarios");
            }
        }

       public function editarorcamento($indice = null)
	  {
            $this->load->model('usuarios_model');
            $this->load->model('orcamento_model');
                 if ($this->usuarios_model->checarSessao()) {
            if ($indice == null) {
                redirect(base_url());
            } else if ($this->orcamento_model->contarOrcamentoId($indice) == 1) {
                $dados['logado'] = true;
                $dados['orcamento'] = $this->orcamento_model->pegarOrcamentoId($indice);

                $this->load->view('orcamentos/editar_orcamento', $dados);
            } else {
                $dados['heading'] = "O produto não existe";
                $dados['message'] = "Impossível editar este produto pois ele não se encontra na nossa base de dados.";
                $this->load->view('errors/html/error_general', $dados);
            }
        } else {
            redirect(base_url() . "index.php/usuarios");
        }
    }

    public function alterarorcamento($id){
        $this->load->model('orcamento_model');
        $this->load->model('usuarios_model');
         if ($this->usuarios_model->checarSessao()) {
            if($this->orcamento_model->editarorcamento($id)){
               redirect(base_url()."index.php/orcamentos/visualizarorcamento/".$id);
            }
         }else{
             redirect(base_url() . "index.php/usuarios");
         }

    }

    public function pesquisa(){

        $this->load->model('orcamento_model');
            $this->load->model('usuarios_model');

                $this->load->library('pagination');

            $config = array(
            "base_url" => base_url()."index.php/orcamentos/pesquisa/p",
            "per_page" => 9,
            "num_links" => 6,
            "uri_segment" => 4,
            "total_rows" => $this->orcamento_model->pegarQtdPesquisa(),
            "full_tag_open" => "
",
            "full_tag_close" => "
",
            "first_link" => TRUE,
            "last_link" => FALSE,
            "first_tag_open" => "
",
            "first_tag_close" => "
",
            "prev_link" => "Anterior",
            "prev_tag_open" => "
",
            "prev_tag_close" => "
",
            "next_link" => "Próxima",
            "next_tag_open" => "
",
            "next_tag_close" => "
",
            "last_tag_open" => "
",
            "last_tag_close" => "
",
            "cur_tag_open" => "
",
            "cur_tag_close" => "
",
            "num_tag_open" => "
",
            "num_tag_close" => "
"
        );
              $this->pagination->initialize($config);

        $dados["pagination"] = $this->pagination->create_links();
        $offset = ($this->uri->segment(4)) ? $this->uri->segment(4) :0;

        $dados["orcamentos"] = $this->orcamento_model->pegarOrcamentosPesquisa($config['per_page'],$offset);

		$this->load->view('orcamentos/inicio', $dados);

    }

}


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
Cat. afr. pl. 1:767. 1898

#### Original name
null

### Remarks
null


text:
// Copyright (c) 2015-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <qt/test/wallettests.h>
#include <qt/test/util.h>

#include <interfaces/chain.h>
#include <interfaces/node.h>
#include <qt/bitcoinamountfield.h>
#include <qt/clientmodel.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <qt/qvalidatedlineedit.h>
#include <qt/sendcoinsdialog.h>
#include <qt/sendcoinsentry.h>
#include <qt/transactiontablemodel.h>
#include <qt/transactionview.h>
#include <qt/walletmodel.h>
#include <key_io.h>
#include <test/util/setup_common.h>
#include <validation.h>
#include <wallet/wallet.h>
#include <qt/overviewpage.h>
#include <qt/receivecoinsdialog.h>
#include <qt/recentrequeststablemodel.h>
#include <qt/receiverequestdialog.h>

#include <memory>

#include <QAbstractButton>
#include <QAction>
#include <QApplication>
#include <QCheckBox>
#include <QPushButton>
#include <QTimer>
#include <QVBoxLayout>
#include <QTextEdit>
#include <QListView>
#include <QDialogButtonBox>

namespace
{
//! Press "Yes" or "Cancel" buttons in modal send confirmation dialog.
void ConfirmSend(QString* text = nullptr, bool cancel = false)
{
    QTimer::singleShot(0, [text, cancel]() {
        for (QWidget* widget : QApplication::topLevelWidgets()) {
            if (widget->inherits("SendConfirmationDialog")) {
                SendConfirmationDialog* dialog = qobject_cast<SendConfirmationDialog*>(widget);
                if (text) *text = dialog->text();
                QAbstractButton* button = dialog->button(cancel ? QMessageBox::Cancel : QMessageBox::Yes);
                button->setEnabled(true);
                button->click();
            }
        }
    });
}

//! Send coins to address and return txid.
uint256 SendCoins(CWallet& wallet, SendCoinsDialog& sendCoinsDialog, const CTxDestination& address, CAmount amount, bool rbf)
{
    QVBoxLayout* entries = sendCoinsDialog.findChild<QVBoxLayout*>("entries");
    SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(entries->itemAt(0)->widget());
    entry->findChild<QValidatedLineEdit*>("payTo")->setText(QString::fromStdString(EncodeDestination(address)));
    entry->findChild<BitcoinAmountField*>("payAmount")->setValue(amount);
    sendCoinsDialog.findChild<QFrame*>("frameFee")
        ->findChild<QFrame*>("frameFeeSelection")
        ->findChild<QCheckBox*>("optInRBF")
        ->setCheckState(rbf ? Qt::Checked : Qt::Unchecked);
    uint256 txid;
    boost::signals2::scoped_connection c(wallet.NotifyTransactionChanged.connect([&txid](CWallet*, const uint256& hash, ChangeType status) {
        if (status == CT_NEW) txid = hash;
    }));
    ConfirmSend();
    bool invoked = QMetaObject::invokeMethod(&sendCoinsDialog, "on_sendButton_clicked");
    assert(invoked);
    return txid;
}

//! Find index of txid in transaction list.
QModelIndex FindTx(const QAbstractItemModel& model, const uint256& txid)
{
    QString hash = QString::fromStdString(txid.ToString());
    int rows = model.rowCount({});
    for (int row = 0; row < rows; ++row) {
        QModelIndex index = model.index(row, 0, {});
        if (model.data(index, TransactionTableModel::TxHashRole) == hash) {
            return index;
        }
    }
    return {};
}

//! Invoke bumpfee on txid and check results.
void BumpFee(TransactionView& view, const uint256& txid, bool expectDisabled, std::string expectError, bool cancel)
{
    QTableView* table = view.findChild<QTableView*>("transactionView");
    QModelIndex index = FindTx(*table->selectionModel()->model(), txid);
    QVERIFY2(index.isValid(), "Could not find BumpFee txid");

    // Select row in table, invoke context menu, and make sure bumpfee action is
    // enabled or disabled as expected.
    QAction* action = view.findChild<QAction*>("bumpFeeAction");
    table->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
    action->setEnabled(expectDisabled);
    table->customContextMenuRequested({});
    QCOMPARE(action->isEnabled(), !expectDisabled);

    action->setEnabled(true);
    QString text;
    if (expectError.empty()) {
        ConfirmSend(&text, cancel);
    } else {
        ConfirmMessage(&text);
    }
    action->trigger();
    QVERIFY(text.indexOf(QString::fromStdString(expectError)) != -1);
}

//! Simple qt wallet tests.
//
// Test widgets can be debugged interactively calling show() on them and
// manually running the event loop, e.g.:
//
//     sendCoinsDialog.show();
//     QEventLoop().exec();
//
// This also requires overriding the default minimal Qt platform:
//
//     QT_QPA_PLATFORM=xcb     src/qt/test/test_bitcoin-qt  # Linux
//     QT_QPA_PLATFORM=windows src/qt/test/test_bitcoin-qt  # Windows
//     QT_QPA_PLATFORM=cocoa   src/qt/test/test_bitcoin-qt  # macOS
void TestGUI(interfaces::Node& node)
{
    // Set up wallet and chain with 105 blocks (5 mature blocks for spending).
    TestChain100Setup test;
    for (int i = 0; i < 5; ++i) {
        test.CreateAndProcessBlock({}, GetScriptForRawPubKey(test.coinbaseKey.GetPubKey()));
    }
    node.setContext(&test.m_node);
    std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(node.context()->chain.get(), "", CreateMockWalletDatabase());
    bool firstRun;
    wallet->LoadWallet(firstRun);
    {
        auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan();
        LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore);
        wallet->SetAddressBook(GetDestinationForKey(test.coinbaseKey.GetPubKey(), wallet->m_default_address_type), "", "receive");
        spk_man->AddKeyPubKey(test.coinbaseKey, test.coinbaseKey.GetPubKey());
        wallet->SetLastBlockProcessed(105, ::ChainActive().Tip()->GetBlockHash());
    }
    {
        WalletRescanReserver reserver(*wallet);
        reserver.reserve();
        CWallet::ScanResult result = wallet->ScanForWalletTransactions(Params().GetConsensus().hashGenesisBlock, 0 /* block height */, {} /* max height */, reserver, true /* fUpdate */);
        QCOMPARE(result.status, CWallet::ScanResult::SUCCESS);
        QCOMPARE(result.last_scanned_block, ::ChainActive().Tip()->GetBlockHash());
        QVERIFY(result.last_failed_block.IsNull());
    }
    wallet->SetBroadcastTransactions(true);

    // Create widgets for sending coins and listing transactions.
    std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other"));
    SendCoinsDialog sendCoinsDialog(platformStyle.get());
    TransactionView transactionView(platformStyle.get());
    OptionsModel optionsModel;
    ClientModel clientModel(node, &optionsModel);
    AddWallet(wallet);
    WalletModel walletModel(interfaces::MakeWallet(wallet), clientModel, platformStyle.get());
    RemoveWallet(wallet, nullopt);
    sendCoinsDialog.setModel(&walletModel);
    transactionView.setModel(&walletModel);

    {
        // Check balance in send dialog
        QLabel* balanceLabel = sendCoinsDialog.findChild<QLabel*>("labelBalance");
        QString balanceText = balanceLabel->text();
        int unit = walletModel.getOptionsModel()->getDisplayUnit();
        CAmount balance = walletModel.wallet().getBalance();
        QString balanceComparison = BitcoinUnits::formatWithUnit(unit, balance, false, BitcoinUnits::SeparatorStyle::ALWAYS);
        QCOMPARE(balanceText, balanceComparison);
    }

    // Send two transactions, and verify they are added to transaction list.
    TransactionTableModel* transactionTableModel = walletModel.getTransactionTableModel();
    QCOMPARE(transactionTableModel->rowCount({}), 105);
    uint256 txid1 = SendCoins(*wallet.get(), sendCoinsDialog, PKHash(), 5 * COIN, false /* rbf */);
    uint256 txid2 = SendCoins(*wallet.get(), sendCoinsDialog, PKHash(), 10 * COIN, true /* rbf */);
    QCOMPARE(transactionTableModel->rowCount({}), 107);
    QVERIFY(FindTx(*transactionTableModel, txid1).isValid());
    QVERIFY(FindTx(*transactionTableModel, txid2).isValid());

    // Call bumpfee. Test disabled, canceled, enabled, then failing cases.
    BumpFee(transactionView, txid1, true /* expect disabled */, "not BIP 125 replaceable" /* expected error */, false /* cancel */);
    BumpFee(transactionView, txid2, false /* expect disabled */, {} /* expected error */, true /* cancel */);
    BumpFee(transactionView, txid2, false /* expect disabled */, {} /* expected error */, false /* cancel */);
    BumpFee(transactionView, txid2, true /* expect disabled */, "already bumped" /* expected error */, false /* cancel */);

    // Check current balance on OverviewPage
    OverviewPage overviewPage(platformStyle.get());
    overviewPage.setWalletModel(&walletModel);
    QLabel* balanceLabel = overviewPage.findChild<QLabel*>("labelBalance");
    QString balanceText = balanceLabel->text().trimmed();
    int unit = walletModel.getOptionsModel()->getDisplayUnit();
    CAmount balance = walletModel.wallet().getBalance();
    QString balanceComparison = BitcoinUnits::formatWithUnit(unit, balance, false, BitcoinUnits::SeparatorStyle::ALWAYS);
    QCOMPARE(balanceText, balanceComparison);

    // Check Request Payment button
    ReceiveCoinsDialog receiveCoinsDialog(platformStyle.get());
    receiveCoinsDialog.setModel(&walletModel);
    RecentRequestsTableModel* requestTableModel = walletModel.getRecentRequestsTableModel();

    // Label input
    QLineEdit* labelInput = receiveCoinsDialog.findChild<QLineEdit*>("reqLabel");
    labelInput->setText("TEST_LABEL_1");

    // Amount input
    BitcoinAmountField* amountInput = receiveCoinsDialog.findChild<BitcoinAmountField*>("reqAmount");
    amountInput->setValue(1);

    // Message input
    QLineEdit* messageInput = receiveCoinsDialog.findChild<QLineEdit*>("reqMessage");
    messageInput->setText("TEST_MESSAGE_1");
    int initialRowCount = requestTableModel->rowCount({});
    QPushButton* requestPaymentButton = receiveCoinsDialog.findChild<QPushButton*>("receiveButton");
    requestPaymentButton->click();
    for (QWidget* widget : QApplication::topLevelWidgets()) {
        if (widget->inherits("ReceiveRequestDialog")) {
            ReceiveRequestDialog* receiveRequestDialog = qobject_cast<ReceiveRequestDialog*>(widget);
            QCOMPARE(receiveRequestDialog->QObject::findChild<QLabel*>("payment_header")->text(), QString("Payment information"));
            QCOMPARE(receiveRequestDialog->QObject::findChild<QLabel*>("uri_tag")->text(), QString("URI:"));
            QString uri = receiveRequestDialog->QObject::findChild<QLabel*>("uri_content")->text();
            QCOMPARE(uri.count("bitcoin:"), 2);
            QCOMPARE(receiveRequestDialog->QObject::findChild<QLabel*>("address_tag")->text(), QString("Address:"));

            QCOMPARE(uri.count("amount=0.00000001"), 2);
            QCOMPARE(receiveRequestDialog->QObject::findChild<QLabel*>("amount_tag")->text(), QString("Amount:"));
            QCOMPARE(receiveRequestDialog->QObject::findChild<QLabel*>("amount_content")->text(), QString("0.00000001 ") + QString::fromStdString(CURRENCY_UNIT));

            QCOMPARE(uri.count("label=TEST_LABEL_1"), 2);
            QCOMPARE(receiveRequestDialog->QObject::findChild<QLabel*>("label_tag")->text(), QString("Label:"));
            QCOMPARE(receiveRequestDialog->QObject::findChild<QLabel*>("label_content")->text(), QString("TEST_LABEL_1"));

            QCOMPARE(uri.count("message=TEST_MESSAGE_1"), 2);
            QCOMPARE(receiveRequestDialog->QObject::findChild<QLabel*>("message_tag")->text(), QString("Message:"));
            QCOMPARE(receiveRequestDialog->QObject::findChild<QLabel*>("message_content")->text(), QString("TEST_MESSAGE_1"));
        }
    }

    // Clear button
    QPushButton* clearButton = receiveCoinsDialog.findChild<QPushButton*>("clearButton");
    clearButton->click();
    QCOMPARE(labelInput->text(), QString(""));
    QCOMPARE(amountInput->value(), CAmount(0));
    QCOMPARE(messageInput->text(), QString(""));

    // Check addition to history
    int currentRowCount = requestTableModel->rowCount({});
    QCOMPARE(currentRowCount, initialRowCount+1);

    // Check Remove button
    QTableView* table = receiveCoinsDialog.findChild<QTableView*>("recentRequestsView");
    table->selectRow(currentRowCount-1);
    QPushButton* removeRequestButton = receiveCoinsDialog.findChild<QPushButton*>("removeRequestButton");
    removeRequestButton->click();
    QCOMPARE(requestTableModel->rowCount({}), currentRowCount-1);
}

} // namespace

void WalletTests::walletTests()
{
#ifdef Q_OS_MAC
    if (QApplication::platformName() == "minimal") {
        // Disable for mac on "minimal" platform to avoid crashes inside the Qt
        // framework when it tries to look up unimplemented cocoa functions,
        // and fails to handle returned nulls
        // (https://bugreports.qt.io/browse/QTBUG-49686).
        QWARN("Skipping WalletTests on mac build with 'minimal' platform set due to Qt bugs. To run AppTests, invoke "
              "with 'QT_QPA_PLATFORM=cocoa test_bitcoin-qt' on mac, or else use a linux or windows build.");
        return;
    }
#endif
    TestGUI(m_node);
}


text:
require 'rails/generators/base'

module ConveyUser
    MissingORMError = Class.new(Thor::Error)

    class SetupGenerator < Rails::Generators::Base
      source_root File.expand_path("../../templates", __FILE__)

      desc "Creates a Convey initializer and copy locale files to your application."

      hook_for :orm do |instance, controller|
        instance.invoke controller, [ "User" ]
      end

      def copy_initializer
        template "convey.rb", "config/initializers/convey.rb"
        route "mount ConveyUser::Engine => '/'"
        route "#TODO handle get 'auth/success'"
      end

      def rails_4?
        Rails::VERSION::MAJOR == 4
      end
    end
end


text:
/**
 A **Perspective** defines a perspective projection transform for a {{#crossLink "Camera"}}Camera{{/crossLink}}.

 ## Overview

 * A {{#crossLink "Camera"}}Camera{{/crossLink}} has a Perspective to configure its perspective projection mode.

 ## Examples

 * [Camera with perspective projection](../../examples/#camera_perspective)

 ## Usage

 * See {{#crossLink "Camera"}}{{/crossLink}}

 @class Perspective
 @module xeogl
 @submodule camera
 @constructor
 @param [owner] {Component} Owner component. When destroyed, the owner will destroy this component as well. Creates this component within the default {{#crossLink "Scene"}}{{/crossLink}} when omitted.
 @param [cfg] {*} Configs
 @param [cfg.id] {String} Optional ID, unique among all components in the parent scene, generated automatically when omitted.
 @param [cfg.meta] {String:Object} Optional map of user-defined metadata to attach to this Perspective.
 @param [cfg.parent] {String|Transform} ID or instance of a parent {{#crossLink "Transform"}}{{/crossLink}} within the same {{#crossLink "Scene"}}Scene{{/crossLink}}.
 @param [cfg.fov=60.0] {Number} Field-of-view angle, in degrees.
 @param [cfg.fovAxis="min"] {String} The field-of-view axis: "x", "y", or "min" to use whichever is currently the minimum.
 @param [cfg.near=0.1] {Number} Position of the near plane on the View-space Z-axis.
 @param [cfg.far=10000] {Number} Position of the far plane on the View-space Z-axis.
 @author xeolabs / http://xeolabs.com
 @author Artur-Sampaio / https://github.com/Artur-Sampaio
 @extends Component
 */

import {math} from '../math/math.js';
import {Component} from '../component.js';
import {State} from '../renderer/state.js';
import {componentClasses} from "./../componentClasses.js";

const type = "xeogl.Perspective";

class Perspective extends Component {

    /**
     JavaScript class name for this Component.

     For example: "xeogl.AmbientLight", "xeogl.MetallicMaterial" etc.

     @property type
     @type String
     @final
     */
    get type() {
        return type;
    }

    init(cfg) {

        super.init(cfg);

        this._state = new State({
            matrix: math.mat4()
        });

        this._dirty = false;
        this._fov = 60.0;
        this._near = 0.1;
        this._far = 10000.0;

        // Recompute aspect from change in canvas size
        this._canvasResized = this.scene.canvas.on("boundary", this._needUpdate, this);

        this.fov = cfg.fov;
        this.fovAxis = cfg.fovAxis;
        this.near = cfg.near;
        this.far = cfg.far;
    }

    _update() {
        const WIDTH_INDEX = 2;
        const HEIGHT_INDEX = 3;
        const boundary = this.scene.viewport.boundary;
        const aspect = boundary[WIDTH_INDEX] / boundary[HEIGHT_INDEX];
        let fov = this._fov;
        const fovAxis = this._fovAxis;
        if (fovAxis == "x" || (fovAxis == "min" && aspect < 1) || (fovAxis == "max" && aspect > 1)) {
            fov = fov / aspect;
        }
        fov = Math.min(fov, 120);
        math.perspectiveMat4(fov * (Math.PI / 180.0), aspect, this._near, this._far, this._state.matrix);
        this._renderer.imageDirty();
        this.fire("matrix", this._state.matrix);
    }

    /**
     The field-of-view angle (FOV).

     Fires a {{#crossLink "Perspective/fov:event"}}{{/crossLink}} event on change.

     @property fov
     @default 60.0
     @type Number
     */
    set fov(value) {
        this._fov = (value !== undefined && value !== null) ? value : 60.0;
        this._needUpdate(0); // Ensure matrix built on next "tick"
        /**
         Fired whenever this Perspective's {{#crossLink "Perspective/fov:property"}}{{/crossLink}} property changes.

         @event fov
         @param value The property's new value
         */
        this.fire("fov", this._fov);
    }

    get fov() {
        return this._fov;
    }

    /**
     The FOV axis.

     Options are "x", "y" or "min", to use the minimum axis.

     Fires a {{#crossLink "Perspective/fov:event"}}{{/crossLink}} event on change.

     @property fovAxis
     @default "min"
     @type String
     */
    set fovAxis(value) {
        value = value || "min";
        if (this._fovAxis === value) {
            return;
        }
        if (value !== "x" && value !== "y" && value !== "min") {
            this.error("Unsupported value for 'fovAxis': " + value + " - defaulting to 'min'");
            value = "min";
        }
        this._fovAxis = value;
        this._needUpdate(0); // Ensure matrix built on next "tick"
        /**
         Fired whenever this Perspective's {{#crossLink "Perspective/fovAxis:property"}}{{/crossLink}} property changes.

         @event fovAxis
         @param value The property's new value
         */
        this.fire("fovAxis", this._fovAxis);
    }

    get fovAxis() {
        return this._fovAxis;
    }

    /**
     Position of this Perspective's near plane on the positive View-space Z-axis.

     Fires a {{#crossLink "Perspective/near:event"}}{{/crossLink}} event on change.

     @property near
     @default 0.1
     @type Number
     */
    set near(value) {
        this._near = (value !== undefined && value !== null) ? value : 0.1;
        this._needUpdate(0); // Ensure matrix built on next "tick"
        /**
         Fired whenever this Perspective's   {{#crossLink "Perspective/near:property"}}{{/crossLink}} property changes.
         @event near
         @param value The property's new value
         */
        this.fire("near", this._near);
    }

    get near() {
        return this._near;
    }

    /**
     Position of this Perspective's far plane on the positive View-space Z-axis.

     Fires a {{#crossLink "Perspective/far:event"}}{{/crossLink}} event on change.

     @property far
     @default 10000.0
     @type Number
     */
    set far(value) {
        this._far = (value !== undefined && value !== null) ? value : 10000;
        this._needUpdate(0); // Ensure matrix built on next "tick"
        /**
         Fired whenever this Perspective's  {{#crossLink "Perspective/far:property"}}{{/crossLink}} property changes.

         @event far
         @param value The property's new value
         */
        this.fire("far", this._far);
    }

    get far() {
        return this._far;
    }

    /**
     The Perspective's projection transform matrix.

     Fires a {{#crossLink "Perspective/matrix:event"}}{{/crossLink}} event on change.

     @property matrix
     @default [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
     @type {Float32Array}
     */
    get matrix() {
        if (this._updateScheduled) {
            this._doUpdate();
        }
        return this._state.matrix;
    }

    destroy() {
        super.destroy();
        this._state.destroy();
        super.destroy();
        this.scene.canvas.off(this._canvasResized);
    }
}

componentClasses[type] = Perspective;

export{Perspective};


text:
var TaskPanel = (function () {
    function TaskPanel(stage, taskService) {
        this.bgColor_Task = 0x00559d; //Task Panel
        this.panelX = 0;
        this.panelY = 0;
        this.panelWidth = 300;
        this.panelHeight = 200;
        this.taskNameTextFieldText = "Task Panel";
        this.taskNameTextFieldX = 70;
        this.taskNameTextFieldY = 25;
        this.taskNameTextFieldWidth = 300;
        this.taskNameTextFieldColor = 0x000000;
        this.taskStateTextField = "";
        this.taskStateTextX = 30;
        this.taskStateTextY = 80;
        this.taskStateTextWidth = 180;
        this.taskStateTextColor = 0xFF0000;
        this.buttonColor = 0xeaffb1;
        this.buttonX = 60;
        this.buttonY = 130;
        this.buttonWidth = 180;
        this.buttonHeight = 45;
        this.buttonText = "No Task";
        this.buttonTextX = this.buttonX + 12;
        this.buttonTextY = this.buttonY + 10;
        this.buttonTextWidth = 180;
        this.buttonTextColor = 0x808080; //grey
        this.stage = stage;
        this.taskService = taskService;
        this.taskService.Attach(this, "TaskPanel");
        this.panel = new egret.DisplayObjectContainer();
        this.taskNameTextField = new egret.TextField();
        this.taskStateText = new egret.TextField();
        this.rectTaskPanel = new egret.Shape();
        this.button = new egret.DisplayObjectContainer();
        this.rectButton = new egret.Shape();
        this.buttonTextField = new egret.TextField();
        this.stage.addChild(this.panel);
        this.drawPanel();
    }
    var d = __define,c=TaskPanel,p=c.prototype;
    p.setText = function () {
        this.taskNameTextField.text = this.taskNameTextFieldText;
        this.taskNameTextField.x = this.taskNameTextFieldX;
        this.taskNameTextField.y = this.taskNameTextFieldY;
        this.taskNameTextField.width = this.taskNameTextFieldWidth;
        this.taskNameTextField.bold = true;
        this.taskNameTextField.textColor = this.taskNameTextFieldColor;
        this.taskStateText.text = this.taskStateTextField;
        this.taskStateText.x = this.taskStateTextX;
        this.taskStateText.y = this.taskStateTextY;
        this.taskStateText.width = this.taskStateTextWidth;
        this.taskStateText.bold = false;
        this.taskStateText.textColor = this.taskStateTextColor;
        this.taskStateText.textAlign = egret.HorizontalAlign.LEFT;
    };
    p.drawTaskPanel = function () {
        this.rectTaskPanel.graphics.beginFill(this.bgColor_Task, 1);
        this.rectTaskPanel.graphics.drawRect(0, 0, this.panelWidth, this.panelHeight);
        this.rectTaskPanel.graphics.endFill();
    };
    p.drawButtonPanel = function () {
        this.rectButton.graphics.beginFill(this.buttonColor, 1);
        this.rectButton.graphics.drawRect(this.buttonX, this.buttonY, this.buttonWidth, this.buttonHeight);
        this.rectButton.graphics.endFill();
    };
    p.setButtonText = function () {
        this.buttonTextField.text = this.buttonText;
        this.buttonTextField.x = this.buttonTextX;
        this.buttonTextField.y = this.buttonTextY;
        this.buttonTextField.width = this.buttonTextWidth;
        this.buttonTextField.bold = false;
        this.buttonTextField.textColor = this.buttonTextColor;
    };
    p.drawButton = function () {
        this.drawButtonPanel();
        this.setButtonText();
        this.button.addChild(this.rectButton);
        this.button.addChild(this.buttonTextField);
    };
    p.drawPanel = function () {
        this.panel.x = this.panelX;
        this.panel.y = this.panelY;
        this.panel.width = this.panelWidth;
        this.panel.height = this.panelHeight;
        this.drawButton();
        this.drawTaskPanel();
        this.setText();
        this.panel.addChild(this.rectTaskPanel);
        this.panel.addChild(this.taskNameTextField);
        this.panel.addChild(this.taskStateText);
        this.panel.addChild(this.button);
        this.button.touchEnabled = true;
    };
    p.onChange = function (task) {
        this.currentTaskId = task.id;
        this.changeTaskText(task.name, task.desc);
        this.changeButton(task.status);
        this.currentTaskStatus = task.status;
    };
    p.changeTaskText = function (name, desc) {
        this.taskNameTextField.text = name;
        this.taskStateText.text = desc;
    };
    p.changeButton = function (taskStatus) {
        switch (taskStatus) {
            case TaskStatus.ACCEPTABLE:
                this.buttonTextField.text = "acceptable";
                break;
            case TaskStatus.DURING:
                this.buttonTextField.text = "unfinished";
                break;
            case TaskStatus.CAN_SUBMIT:
                this.buttonTextField.text = "submit";
                break;
            case TaskStatus.SUBMITTED:
                this.taskNameTextField.text = "Task Panel";
                this.taskStateText.text = "NULL";
                this.buttonTextField.text = "No Task";
                break;
            default:
                this.buttonTextField.text = "None";
                break;
        }
    };
    return TaskPanel;
}());
egret.registerClass(TaskPanel,'TaskPanel');
//# sourceMappingURL=TaskPanel.js.map


text:
"""Created originally by Ethan Chiu 10/25/16
v2.0.0 created on 8/4/18
Complete redesign for efficiency and scalability
Uses Python 3 now

v2.1.0 created on 5/10/19
Improve efficiency and design
 """
from .pylint_errors import pylint_dict_final
from flask import Flask, render_template, request, jsonify, session
from flask_socketio import SocketIO
import eventlet.wsgi
import tempfile, mmap, os, re
from datetime import datetime
from pylint import epylint as lint
from subprocess import Popen, PIPE, STDOUT
from multiprocessing import Pool, cpu_count

def is_os_linux():
    if os.name == "nt":
        return False
    return True

# Configure Flask App
# Remember to change the SECRET_KEY!
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
socketio = SocketIO(app)

# Get number of cores for multiprocessing
num_cores = cpu_count()

@app.route('/')
def index():
    """Display home page
        :return: index.html

        Initializes session variables for tracking time between running code.
    """
    session["count"] = 0
    session["time_now"] = datetime.now()
    return render_template("index.html")

@app.route('/check_code', methods=['POST'])
def check_code():
    """Run pylint on code and get output
        :return: JSON object of pylint errors
            {
                {
                    "code":...,
                    "error": ...,
                    "message": ...,
                    "line": ...,
                    "error_info": ...,
                }
                ...
            }

        For more customization, please look at Pylint's library code:
        https://github.com/PyCQA/pylint/blob/master/pylint/lint.py
    """
    # Session to handle multiple users at one time and to get textarea from AJAX call
    session["code"] = request.form['text']
    text = session["code"]
    output = evaluate_pylint(text)

    # MANAGER.astroid_cache.clear()
    return jsonify(output)

# Run python in secure system
@app.route('/run_code', methods=['POST'])
def run_code():
    """Run python 3 code
        :return: JSON object of python 3 output
            {
                ...
            }
    """
    # Don't run too many times
    if slow():
        return jsonify("Running code too much within a short time period. Please wait a few seconds before clicking \"Run\" each time.")
    session["time_now"] = datetime.now()

    output = None
    if not "file_name" in session:
        with tempfile.NamedTemporaryFile(delete=False) as temp:
            session["file_name"] = temp.name
    cmd = 'python ' + session["file_name"]
    p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE,
              stderr=STDOUT, close_fds=True)
    output = p.stdout.read()

    return jsonify(output.decode('utf-8'))

# Slow down if user clicks "Run" too many times
def slow():
    session["count"] += 1
    time = datetime.now() - session["time_now"]
    if float(session["count"]) / float(time.total_seconds()) > 5:
        return True
    return False

def evaluate_pylint(text):
    """Create temp files for pylint parsing on user code

    :param text: user code
    :return: dictionary of pylint errors:
        {
            {
                "code":...,
                "error": ...,
                "message": ...,
                "line": ...,
                "error_info": ...,
            }
            ...
        }
    """
    # Open temp file for specific session.
    # IF it doesn't exist (aka the key doesn't exist), create one
    if "file_name" in session:
        f = open(session["file_name"], "w")
        for t in text:
            f.write(t)
        f.flush()
    else:
        with tempfile.NamedTemporaryFile(delete=False) as temp:
            session["file_name"] = temp.name
            for t in text:
                temp.write(t.encode("utf-8"))
            temp.flush()

    try:
        ARGS = " -r n --disable=R,C"
        (pylint_stdout, pylint_stderr) = lint.py_run(
            session["file_name"] + ARGS, return_std=True)
    except Exception as e:
        raise Exception(e)

    if pylint_stderr.getvalue():
        raise Exception("Issue with pylint configuration")

    return format_errors(pylint_stdout.getvalue())

# def split_error_gen(error):
#     """Inspired by this Python discussion: https://bugs.python.org/issue17343
#     Uses a generator to split error by token and save some space
#
#         :param error: string to be split
#         :yield: next line split by new line
#     """
#     for e in error.split():
#         yield e

def process_error(error):
    """Formats error message into dictionary

        :param error: pylint error full text
        :return: dictionary of error as:
            {
                "code":...,
                "error": ...,
                "message": ...,
                "line": ...,
                "error_info": ...,
            }
    """
    # Return None if not an error or warning
    if error == " " or error is None:
        return None
    if error.find("Your code has been rated at") > -1:
        return None

    list_words = error.split()
    if len(list_words) < 3:
        return None

    # Detect OS
    line_num = None
    if is_os_linux():
        try:
            line_num = error.split(":")[1]
        except Exception as e:
            print(os.name + " not compatible: " + e)
    else:
        line_num = error.split(":")[2]

    # list_words.pop(0)
    error_yet, message_yet, first_time = False, False, True
    i, length = 0, len(list_words)
    # error_code=None
    while i < length:
        word = list_words[i]
        if (word == "error" or word == "warning") and first_time:
            error_yet = True
            first_time = False
            i += 1
            continue
        if error_yet:
            error_code = word[1:-1]
            error_string = list_words[i + 1][:-1]
            i = i + 3
            error_yet = False
            message_yet = True
            continue
        if message_yet:
            full_message = ' '.join(list_words[i:length - 1])
            break
        i += 1

    error_info = pylint_dict_final[error_code]

    return {
        "code": error_code,
        "error": error_string,
        "message": full_message,
        "line": line_num,
        "error_info": error_info,
    }

def format_errors(pylint_text):
    """Format errors into parsable nested dictionary

    :param pylint_text: original pylint output
    :return: dictionary of errors as:
        {
            {
                "code":...,
                "error": ...,
                "message": ...,
                "line": ...,
                "error_info": ...,
            }
            ...
        }
    """
    errors_list = pylint_text.splitlines(True)

    # If there is not an error, return nothing
    if "--------------------------------------------------------------------" in errors_list[1] and \
            "Your code has been rated at" in errors_list[2] and "module" not in errors_list[0]:
        return None

    errors_list.pop(0)

    pylint_dict = {}
    try:
        pool = Pool(num_cores)
        pylint_dict = pool.map(process_error, errors_list)
    finally:
        pool.close()
        pool.join()
        return pylint_dict

    # count = 0
    # for error in errors_list:
    #     pylint_dict[count]=process_error(error)
    #     count +=1
    return pylint_dict

# def find_error(id):
#     """Find relevant info about pylint error
#
#     :param id: pylint error id
#     :return: returns error message description
#
#     pylint_errors.txt is the result from "pylint --list-msgs"
#     """
#     file = open('pylint_errors.txt', 'r')
#     s = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ)
#     location = s.find(id.encode())
#     if location != -1:
#         search_text = s[location:]
#         lines = search_text.splitlines(True)
#         error_message = []
#         for l in lines:
#             if l.startswith(':'.encode()):
#                 full_message = b''.join(error_message)
#                 full_message = full_message.decode('utf-8')
#                 replaced = id+"):"
#                 full_message = full_message.replace(replaced, "")
#                 full_message = full_message.replace("Used", "Occurs")
#                 return full_message
#             error_message.append(l)
#
#     return "No information at the moment"

def remove_temp_code_file():
    os.remove(session["file_name"])

@socketio.on('disconnect', namespace='/check_disconnect')
def disconnect():
    """Remove temp file associated with current session"""
    remove_temp_code_file()

if __name__ == "__main__":
    """Initialize app"""
    socketio.run(app)


text:
package com.seafile.seadroid2.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.*;
import android.widget.AbsListView.OnScrollListener;
import com.seafile.seadroid2.R;

/**
 * Custom pull to refresh widget
 *
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class PullToRefreshListView extends ListView implements OnScrollListener {

    private final static String DEBGU_TAG = "PullToRefreshListView";

    // Pull to Refresh flag
    private final static int PULL_To_REFRESH = 0;
    // Release to refresh flag
    private final static int RELEASE_To_REFRESH = 1;
    // Refreshing flag
    private final static int REFRESHING = 2;
    // Done refreshing flag
    private final static int DONE = 3;

    private LayoutInflater inflater;

    private LinearLayout headView;
    private TextView tipsTextview;
    private TextView lastUpdatedTextView;
    private ImageView arrowImageView;
    private ProgressBar progressBar;
    // arrow animations of pull to refresh
    private RotateAnimation animation;
    private RotateAnimation reverseAnimation;

    // use to ensure the value of startY only record once during the whole touch event
    private boolean isRecored;

    private int headContentWidth;
    private int headContentHeight;
    private int headContentOriginalTopPadding;

    private int startY;
    private int firstItemIndex;
    private int currentScrollState;

    private int state;

    private boolean isBack;

    public OnRefreshListener refreshListener;

    public PullToRefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public PullToRefreshListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        // set animations
        animation = new RotateAnimation(0, -180,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        animation.setInterpolator(new LinearInterpolator());
        animation.setDuration(100);
        animation.setFillAfter(true);

        reverseAnimation = new RotateAnimation(-180, 0,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        reverseAnimation.setInterpolator(new LinearInterpolator());
        reverseAnimation.setDuration(100);
        reverseAnimation.setFillAfter(true);

        inflater = LayoutInflater.from(context);
        headView = (LinearLayout) inflater.inflate(R.layout.pull_to_refresh_head, null);

        arrowImageView = (ImageView) headView.findViewById(R.id.head_arrowImageView);
        arrowImageView.setMinimumWidth(50);
        arrowImageView.setMinimumHeight(50);
        progressBar = (ProgressBar) headView.findViewById(R.id.head_progressBar);
        tipsTextview = (TextView) headView.findViewById(R.id.head_tipsTextView);
        lastUpdatedTextView = (TextView) headView.findViewById(R.id.head_lastUpdatedTextView);

        headContentOriginalTopPadding = headView.getPaddingTop();

        measureView(headView);
        headContentHeight = headView.getMeasuredHeight();
        headContentWidth = headView.getMeasuredWidth();

        headView.setPadding(headView.getPaddingLeft(), -1 * headContentHeight, headView.getPaddingRight(), headView.getPaddingBottom());
        headView.invalidate();

        // System.out.println("initial height: " + headContentHeight);
        // System.out.println("initial TopPad:" + headContentOriginalTopPadding);

        addHeaderView(headView);
        setOnScrollListener(this);
    }

    public void onScroll(AbsListView view, int firstVisiableItem, int visibleItemCount, int totalItemCount) {
        firstItemIndex = firstVisiableItem;
    }

    public void onScrollStateChanged(AbsListView view, int scrollState) {
        currentScrollState = scrollState;
    }

    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (firstItemIndex == 0 && !isRecored) {
                    startY = (int) event.getY();
                    isRecored = true;
                    // System.out.println("ACTION_DOWN-Y:" + startY);
                }
                break;

            case MotionEvent.ACTION_CANCEL:// lose focus & cancel refresh
            case MotionEvent.ACTION_UP:

                if (state != REFRESHING) {
                    if (state == DONE) {
                        // System.out.println("ACTION_UP:DONE");
                    } else if (state == PULL_To_REFRESH) {
                        state = DONE;
                        changeHeaderViewByState();
                        // System.out.println("ACTION_UP:PULL_To_REFRESH-->DONE");
                    } else if (state == RELEASE_To_REFRESH) {
                        state = REFRESHING;
                        changeHeaderViewByState();
                        onRefresh();
                        // System.out.println("ACTION_UP:RELEASE_To_REFRESH-->REFRESHING");
                    }
                }

                isRecored = false;
                isBack = false;

                break;

            case MotionEvent.ACTION_MOVE:
                int tempY = (int) event.getY();
                // System.out.println("ACTION_MOVE Y:"+tempY);
                if (!isRecored && firstItemIndex == 0) {
                    // System.out.println("Y:"+tempY);
                    isRecored = true;
                    startY = tempY;
                }
                if (state != REFRESHING && isRecored) {
                    // ready to refresh
                    if (state == RELEASE_To_REFRESH) {
                        if ((tempY - startY < headContentHeight + 20)
                                && (tempY - startY) > 0) {
                            state = PULL_To_REFRESH;
                            changeHeaderViewByState();
                            // System.out.println("ACTION_MOVE:RELEASE_To_REFRESH-->PULL_To_REFRESH");
                        } else if (tempY - startY <= 0) {
                            state = DONE;
                            changeHeaderViewByState();
                            // System.out.println("ACTION_MOVE:RELEASE_To_REFRESH-->DONE");
                        }
                        //
                        else {
                            //
                        }
                    } else if (state == PULL_To_REFRESH) {
                        if (tempY - startY >= headContentHeight + 20 && currentScrollState == SCROLL_STATE_TOUCH_SCROLL) {
                            state = RELEASE_To_REFRESH;
                            isBack = true;
                            changeHeaderViewByState();
                            // System.out.println("PULL_To_REFRESH-->RELEASE_To_REFRESH");
                        } else if (tempY - startY <= 0) {
                            state = DONE;
                            changeHeaderViewByState();
                            // System.out.println("PULL_To_REFRESH-->DONE");
                        }
                    } else if (state == DONE) {
                        if (tempY - startY > 0) {
                            state = PULL_To_REFRESH;
                            changeHeaderViewByState();
                            // System.out.println("DONE-->PULL_To_REFRESH");
                        }
                    }

                    if (state == PULL_To_REFRESH) {
                        int topPadding = (int) ((-1 * headContentHeight + (tempY - startY)));
                        headView.setPadding(headView.getPaddingLeft(), topPadding, headView.getPaddingRight(), headView.getPaddingBottom());
                        headView.invalidate();
                        // System.out.println("PULL_To_REFRESH-TopPad:" + topPadding);
                    }

                    if (state == RELEASE_To_REFRESH) {
                        int topPadding = (int) ((tempY - startY - headContentHeight));
                        headView.setPadding(headView.getPaddingLeft(), topPadding, headView.getPaddingRight(), headView.getPaddingBottom());
                        headView.invalidate();
                        // System.out.println("RELEASE_To_REFRESH-TopPad:" + topPadding);
                    }
                }
                break;
        }
        return super.onTouchEvent(event);
    }

    /**
     * call this method to update ui when state changes
     */
    private void changeHeaderViewByState() {
        switch (state) {
            case RELEASE_To_REFRESH:

                arrowImageView.setVisibility(View.VISIBLE);
                progressBar.setVisibility(View.GONE);
                tipsTextview.setVisibility(View.VISIBLE);
                lastUpdatedTextView.setVisibility(View.VISIBLE);

                arrowImageView.clearAnimation();
                arrowImageView.startAnimation(animation);

                tipsTextview.setText(R.string.pull_to_refresh_release_label);

                // Log.v(DEBGU_TAG, "state: release to refresh");
                break;
            case PULL_To_REFRESH:

                progressBar.setVisibility(View.GONE);
                tipsTextview.setVisibility(View.VISIBLE);
                lastUpdatedTextView.setVisibility(View.VISIBLE);
                arrowImageView.clearAnimation();
                arrowImageView.setVisibility(View.VISIBLE);
                if (isBack) {
                    isBack = false;
                    arrowImageView.clearAnimation();
                    arrowImageView.startAnimation(reverseAnimation);
                }
                tipsTextview.setText(R.string.pull_to_refresh_pull_label);

                // Log.v(DEBGU_TAG, "state: pull to refresh");
                break;

            case REFRESHING:
                // System.out.println("REFRESHING-TopPad:" + headContentOriginalTopPadding);
                headView.setPadding(headView.getPaddingLeft(), headContentOriginalTopPadding, headView.getPaddingRight(), headView.getPaddingBottom());
                headView.invalidate();

                progressBar.setVisibility(View.VISIBLE);
                arrowImageView.clearAnimation();
                arrowImageView.setVisibility(View.GONE);
                tipsTextview.setText(R.string.pull_to_refresh_refreshing_label);
                lastUpdatedTextView.setVisibility(View.GONE);

                // Log.v(DEBGU_TAG, "state: refreshing...");
                break;
            case DONE:
                // System.out.println("DONE-TopPad: " + (-1 * headContentHeight));
                headView.setPadding(headView.getPaddingLeft(), -1 * headContentHeight, headView.getPaddingRight(), headView.getPaddingBottom());
                headView.invalidate();

                progressBar.setVisibility(View.GONE);
                arrowImageView.clearAnimation();
                //  change icon
                arrowImageView.setImageResource(R.drawable.pulltorefresh_arrow);

                tipsTextview.setText(R.string.pull_to_refresh_pull_label);
                lastUpdatedTextView.setVisibility(View.VISIBLE);

                // Log.v(DEBGU_TAG, "state: done");
                break;
        }
    }

    // click to refresh
    public void clickRefresh() {
        setSelection(0);
        state = REFRESHING;
        changeHeaderViewByState();
        onRefresh();
    }

    public void setOnRefreshListener(OnRefreshListener refreshListener) {
        this.refreshListener = refreshListener;
    }

    public interface OnRefreshListener {
        public void onRefresh();
    }

    public void onRefreshComplete(String update) {
        lastUpdatedTextView.setText(update);
        onRefreshComplete();
    }

    public void onRefreshComplete() {
        state = DONE;
        changeHeaderViewByState();
    }

    private void onRefresh() {
        if (refreshListener != null) {
            refreshListener.onRefresh();
        }
    }

    // calculate width and height value of headview
    private void measureView(View child) {
        ViewGroup.LayoutParams p = child.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
                    MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = MeasureSpec.makeMeasureSpec(0,
                    MeasureSpec.UNSPECIFIED);
        }
        child.measure(childWidthSpec, childHeightSpec);
    }

}


text:
require 'spec_helper'

describe Banzai::Redactor do
  let(:user) { create(:user) }
  let(:project) { build(:project) }
  let(:redactor) { described_class.new(Banzai::RenderContext.new(project, user)) }

  describe '#redact' do
    context 'when reference not visible to user' do
      before do
        expect(redactor).to receive(:nodes_visible_to_user).and_return([])
      end

      it 'redacts an array of documents' do
        doc1 = Nokogiri::HTML
               .fragment('foo')

        doc2 = Nokogiri::HTML
               .fragment('bar')

        redacted_data = redactor.redact([doc1, doc2])

        expect(redacted_data.map { |data| data[:document] }).to eq([doc1, doc2])
        expect(redacted_data.map { |data| data[:visible_reference_count] }).to eq([0, 0])
        expect(doc1.to_html).to eq('foo')
        expect(doc2.to_html).to eq('bar')
      end

      it 'replaces redacted reference with inner HTML' do
        doc = Nokogiri::HTML.fragment("foo")
        redactor.redact([doc])
        expect(doc.to_html).to eq('foo')
      end

      context 'when data-original attribute provided' do
        let(:original_content) { 'foo' }
        it 'replaces redacted reference with original content' do
          doc = Nokogiri::HTML.fragment("bar")
          redactor.redact([doc])
          expect(doc.to_html).to eq(original_content)
        end
      end

      it 'returns  tag with original href if it is originally a link reference' do
        href = 'http://localhost:3000'
        doc = Nokogiri::HTML
          .fragment("#{href}")

        redactor.redact([doc])

        expect(doc.to_html).to eq('http://localhost:3000')
      end
    end

    context 'when project is in pending delete' do
      let!(:issue) { create(:issue, project: project) }
      let(:redactor) { described_class.new(Banzai::RenderContext.new(project, user)) }

      before do
        project.update(pending_delete: true)
      end

      it 'redacts an issue attached' do
        doc = Nokogiri::HTML.fragment("foo")

        redactor.redact([doc])

        expect(doc.to_html).to eq('foo')
      end

      it 'redacts an external issue' do
        doc = Nokogiri::HTML.fragment("foo")

        redactor.redact([doc])

        expect(doc.to_html).to eq('foo')
      end
    end

    context 'when reference visible to user' do
      it 'does not redact an array of documents' do
        doc1_html = 'foo'
        doc1 = Nokogiri::HTML.fragment(doc1_html)

        doc2_html = 'bar'
        doc2 = Nokogiri::HTML.fragment(doc2_html)

        nodes = redactor.document_nodes([doc1, doc2]).map { |x| x[:nodes] }
        expect(redactor).to receive(:nodes_visible_to_user).and_return(nodes.flatten)

        redacted_data = redactor.redact([doc1, doc2])

        expect(redacted_data.map { |data| data[:document] }).to eq([doc1, doc2])
        expect(redacted_data.map { |data| data[:visible_reference_count] }).to eq([1, 1])
        expect(doc1.to_html).to eq(doc1_html)
        expect(doc2.to_html).to eq(doc2_html)
      end
    end
  end

  context 'when the user cannot read cross project' do
    include ActionView::Helpers::UrlHelper
    let(:project) { create(:project) }
    let(:other_project) { create(:project, :public) }

    def create_link(issuable)
      type = issuable.class.name.underscore.downcase
      link_to(issuable.to_reference, '',
              class: 'gfm has-tooltip',
              title: issuable.title,
              data: {
                reference_type: type,
                "#{type}": issuable.id
              })
    end

    before do
      project.add_developer(user)

      allow(Ability).to receive(:allowed?).and_call_original
      allow(Ability).to receive(:allowed?).with(user, :read_cross_project, :global) { false }
      allow(Ability).to receive(:allowed?).with(user, :read_cross_project) { false }
    end

    it 'skips links to issues within the same project' do
      issue = create(:issue, project: project)
      link = create_link(issue)
      doc = Nokogiri::HTML.fragment(link)

      redactor.redact([doc])
      result = doc.css('a').last

      expect(result['class']).to include('has-tooltip')
      expect(result['title']).to eq(issue.title)
    end

    it 'removes info from a cross project reference' do
      issue = create(:issue, project: other_project)
      link = create_link(issue)
      doc = Nokogiri::HTML.fragment(link)

      redactor.redact([doc])
      result = doc.css('a').last

      expect(result['class']).not_to include('has-tooltip')
      expect(result['title']).to be_empty
    end
  end

  describe '#redact_nodes' do
    it 'redacts an Array of nodes' do
      doc = Nokogiri::HTML.fragment('foo')
      node = doc.children[0]

      expect(redactor).to receive(:nodes_visible_to_user)
        .with([node])
        .and_return(Set.new)

      redactor.redact_document_nodes([{ document: doc, nodes: [node] }])

      expect(doc.to_html).to eq('foo')
    end
  end

  describe '#nodes_visible_to_user' do
    it 'returns a Set containing the visible nodes' do
      doc = Nokogiri::HTML.fragment('')
      node = doc.children[0]

      expect_any_instance_of(Banzai::ReferenceParser::IssueParser)
        .to receive(:nodes_visible_to_user)
        .with(user, [node])
        .and_return([node])

      expect(redactor.nodes_visible_to_user([node])).to eq(Set.new([node]))
    end
  end
end


text:
package org.vertx.scala.testtools;

import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.TestClass;
import org.vertx.testtools.JavaClassRunner;

import java.util.List;

/**
 * Scala class runner. This class used to be a Scala class, but due to the lack
 * of support for SBT project detection in JavaClassRunner, a static
 * initialization is needed to set the correct value for -Dvertx.mods system
 * property before super() constructor executes.
 */
public class ScalaClassRunner extends JavaClassRunner {

  static {
    if (System.getProperty("vertx.mods") == null) {
      // JavaClassRunner can currently only detect gradle/maven projects,
      // so force SBT expectations when it comes to modules location
      // if not pre-configured.
      System.setProperty("vertx.mods", "target/mods");
    }
  }

  public ScalaClassRunner(Class<?> clazz) throws InitializationError {
    super(clazz);
  }

  @Override
  protected List<FrameworkMethod> computeTestMethods() {
    Class<?> testClass = getTestClass().getJavaClass();
    if (!TestVerticle.class.isAssignableFrom(testClass)) {
      throw new IllegalArgumentException("Scala Test classes must extend org.vertx.scala.testtools.TestVerticle");
    }
    this.main = "scala:" + testClass.getName();
    return getTestMethods();
  }

}


text:
<?php

/*
 * This file is part of the Sami utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sami\Parser\ClassVisitor;

use Sami\Reflection\ClassReflection;
use Sami\Parser\ClassVisitorInterface;
use Sami\Reflection\MethodReflection;
use Sami\Reflection\ParameterReflection;

/**
 * Looks for @method tags on classes in the format of:
 * @method [return type] [name]([type] [parameter], [...]) [<description>]
 */
class MethodClassVisitor implements ClassVisitorInterface
{
    public function visit(ClassReflection $class)
    {
        $modified = false;

        $methods = $class->getTags('method');
        if (!empty($methods)) {
            foreach ($methods as $methodTag) {
                if ($this->injectMethod($class, implode(' ', $methodTag))) {
                    $modified = true;
                }
            }
        }

        return $modified;
    }

    /**
     * Parse the parts of an @method tag into an associative array
     *
     * Original @method parsing by https://github.com/phpDocumentor/ReflectionDocBlock/blob/master/src/phpDocumentor/Reflection/DocBlock/Tag/MethodTag.php
     *
     * @param string $tag Method tag contents
     *
     * @return array
     */
    protected function parseMethod($tag)
    {
        // Account for default array syntax
        $tag = str_replace('array()', 'array', $tag);

        $matches = array();
        // 1. none or more whitespace
        // 2. optionally a word with underscores followed by whitespace : as
        //    type for the return value
        // 3. then optionally a word with underscores followed by () and
        //    whitespace : as method name as used by phpDocumentor
        // 4. then a word with underscores, followed by ( and any character
        //    until a ) and whitespace : as method name with signature
        // 5. any remaining text : as description
        $pattern = '/^[\s]*(?P<hint>([\w\|_\\\\]+)[\s]+)?(?:[\w_]+\(\)[\s]+)?(?P<method>[\w\|_\\\\]+)\((?P<args>[^\)]*)\)[\s]*(?P<description>.*)/u';
        if (!preg_match($pattern, $tag, $matches)) {
            return false;
        }

        // Parse arguments
        $args = array();
        if (isset($matches['args'])) {
            foreach (explode(',', $matches['args']) as $arg) {
                $parts = array();
                if (preg_match('/^[\s]*(?P<hint>([\w\|_\\\\]+)[\s]+)*[\s]*\$(?P<name>[\w\|_\\\\]+)?(?:[\s]*=[\s]*)?(?P<default>.*)/', $arg, $parts)) {
                    // Fix array default values
                    if ($parts['default'] == 'array') {
                        $parts['default'] = 'array()';
                    }
                    $args[$parts['name']] = array(
                        'hint'    => $parts['hint'],
                        'name'    => $parts['name'],
                        'default' => $parts['default']
                    );
                }
            }
        }

        return array(
            'hint'        => trim($matches['hint']),
            'name'        => $matches['method'],
            'args'        => $args,
            'description' => $matches['description']
        );
    }

    /**
     * Adds a new method to the class using an array of tokens
     *
     * @param ClassReflection $class     Class reflection
     * @param string          $methodTag Method tag contents
     *
     * @return bool
     */
    protected function injectMethod(ClassReflection $class, $methodTag)
    {
        $data = $this->parseMethod($methodTag);

        // Bail if the method format is invalid
        if (!$data) {
            return false;
        }

        $method = new MethodReflection($data['name'], $class->getLine());
        $method->setDocComment($data['description']);
        $method->setShortDesc($data['description']);

        if ($data['hint']) {
            $method->setHint(array(array($data['hint'], null)));
        }

        // Add arguments to the method
        foreach ($data['args'] as $name => $arg) {
            $param = new ParameterReflection($name, $class->getLine());
            if (!empty($arg['hint'])) {
                $param->setHint(array(array($arg['hint'], null)));
            }
            if (!empty($arg['default'])) {
                $param->setDefault($arg['default']);
            }
            $method->addParameter($param);
        }

        $class->addMethod($method);

        return true;
    }
}