text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta name="author" content="Emanuel Eichhammer" />
<meta name="copyright" content="(C) 2011-2016 Emanuel Eichhammer" />
<title>QCPAbstractPlottable1D< DataType > Class Template Reference</title>
<link href="qcp.css" rel="stylesheet" type="text/css"/>

Main Page ·
Class Overview ·
Hierarchy ·
All Classes ·
Special Pages

Public Functions |
Protected Functions

QCPAbstractPlottable1D< DataType > Class Template Reference

A template base class for plottables with one-dimensional data.
 More...

Inheritance diagram for QCPAbstractPlottable1D< DataType >:

<map name="QCPAbstractPlottable1D_3_01DataType_01_4_inherit__map" id="QCPAbstractPlottable1D_3_01DataType_01_4_inherit__map">
<area shape="rect" id="node2" href="classQCPAbstractPlottable.html" title="The abstract base class for all data representing objects in a plot. " alt="" coords="5,77,145,101"/>
<area shape="rect" id="node3" href="classQCPLayerable.html" title="Base class for all drawable objects. " alt="" coords="25,5,127,29"/>
<area shape="rect" id="node4" href="classQCPPlottableInterface1D.html" title="Defines an abstract interface for one-dimensional plottables. " alt="" coords="171,77,329,101"/>
</map>

Public Functions

 	QCPAbstractPlottable1D (QCPAxis *keyAxis, QCPAxis *valueAxis)

virtual int 	dataCount () const

virtual double 	dataMainKey (int index) const

virtual double 	dataSortKey (int index) const

virtual double 	dataMainValue (int index) const

virtual QCPRange 	dataValueRange (int index) const

virtual QPointF 	dataPixelPosition (int index) const

virtual bool 	sortKeyIsMainKey () const

virtual QCPDataSelection 	selectTestRect (const QRectF &rect, bool onlySelectable) const

virtual int 	findBegin (double sortKey, bool expandedRange=true) const

virtual int 	findEnd (double sortKey, bool expandedRange=true) const

virtual double 	selectTest (const QPointF &pos, bool onlySelectable, QVariant *details=0) const

virtual QCPPlottableInterface1D * 	interface1D ()

 Public Functions inherited from QCPAbstractPlottable

 	QCPAbstractPlottable (QCPAxis *keyAxis, QCPAxis *valueAxis)

QString 	name () const

bool 	antialiasedFill () const

bool 	antialiasedScatters () const

QPen 	pen () const

QBrush 	brush () const

QCPAxis * 	keyAxis () const

QCPAxis * 	valueAxis () const

QCP::SelectionType 	selectable () const

bool 	selected () const

QCPDataSelection 	selection () const

QCPSelectionDecorator * 	selectionDecorator () const

void 	setName (const QString &name)

void 	setAntialiasedFill (bool enabled)

void 	setAntialiasedScatters (bool enabled)

void 	setPen (const QPen &pen)

void 	setBrush (const QBrush &brush)

void 	setKeyAxis (QCPAxis *axis)

void 	setValueAxis (QCPAxis *axis)

Q_SLOT void 	setSelectable (QCP::SelectionType selectable)

Q_SLOT void 	setSelection (QCPDataSelection selection)

void 	setSelectionDecorator (QCPSelectionDecorator *decorator)

virtual QCPRange 	getKeyRange (bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const =0

virtual QCPRange 	getValueRange (bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const =0

void 	coordsToPixels (double key, double value, double &x, double &y) const

const QPointF 	coordsToPixels (double key, double value) const

void 	pixelsToCoords (double x, double y, double &key, double &value) const

void 	pixelsToCoords (const QPointF &pixelPos, double &key, double &value) const

void 	rescaleAxes (bool onlyEnlarge=false) const

void 	rescaleKeyAxis (bool onlyEnlarge=false) const

void 	rescaleValueAxis (bool onlyEnlarge=false, bool inKeyRange=false) const

bool 	addToLegend (QCPLegend *legend)

bool 	addToLegend ()

bool 	removeFromLegend (QCPLegend *legend) const

bool 	removeFromLegend () const

 Public Functions inherited from QCPLayerable

 	QCPLayerable (QCustomPlot *plot, QString targetLayer=QString(), QCPLayerable *parentLayerable=0)

bool 	visible () const

QCustomPlot * 	parentPlot () const

QCPLayerable * 	parentLayerable () const

QCPLayer * 	layer () const

bool 	antialiased () const

void 	setVisible (bool on)

Q_SLOT bool 	setLayer (QCPLayer *layer)

bool 	setLayer (const QString &layerName)

void 	setAntialiased (bool enabled)

bool 	realVisibility () const

Protected Functions

void 	getDataSegments (QList< QCPDataRange > &selectedSegments, QList< QCPDataRange > &unselectedSegments) const

void 	drawPolyline (QCPPainter *painter, const QVector< QPointF > &lineData) const

 Protected Functions inherited from QCPAbstractPlottable

virtual QRect 	clipRect () const

virtual void 	draw (QCPPainter *painter)=0

virtual QCP::Interaction 	selectionCategory () const

void 	applyDefaultAntialiasingHint (QCPPainter *painter) const

virtual void 	selectEvent (QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)

virtual void 	deselectEvent (bool *selectionStateChanged)

virtual void 	drawLegendIcon (QCPPainter *painter, const QRectF &rect) const =0

void 	applyFillAntialiasingHint (QCPPainter *painter) const

void 	applyScattersAntialiasingHint (QCPPainter *painter) const

 Protected Functions inherited from QCPLayerable

virtual void 	parentPlotInitialized (QCustomPlot *parentPlot)

virtual void 	mousePressEvent (QMouseEvent *event, const QVariant &details)

virtual void 	mouseMoveEvent (QMouseEvent *event, const QPointF &startPos)

virtual void 	mouseReleaseEvent (QMouseEvent *event, const QPointF &startPos)

virtual void 	mouseDoubleClickEvent (QMouseEvent *event, const QVariant &details)

virtual void 	wheelEvent (QWheelEvent *event)

void 	initializeParentPlot (QCustomPlot *parentPlot)

void 	setParentLayerable (QCPLayerable *parentLayerable)

bool 	moveToLayer (QCPLayer *layer, bool prepend)

void 	applyAntialiasingHint (QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const

Additional Inherited Members

 Signals inherited from QCPAbstractPlottable

void 	selectionChanged (bool selected)

void 	selectionChanged (const QCPDataSelection &selection)

void 	selectableChanged (QCP::SelectionType selectable)

 Signals inherited from QCPLayerable

void 	layerChanged (QCPLayer *newLayer)

Detailed Description

template<class DataType>

class QCPAbstractPlottable1D< DataType >

A template base class for plottables with one-dimensional data.

This template class derives from QCPAbstractPlottable and from the abstract interface QCPPlottableInterface1D. It serves as a base class for all one-dimensional data (i.e. data with one key dimension), such as QCPGraph and QCPCurve.

The template parameter DataType is the type of the data points of this plottable (e.g. QCPGraphData or QCPCurveData). The main purpose of this base class is to provide the member mDataContainer (a shared pointer to a QCPDataContainer<DataType>) and implement the according virtual methods of the QCPPlottableInterface1D, such that most subclassed plottables don't need to worry about this anymore.

Further, it provides a convenience method for retrieving selected/unselected data segments via getDataSegments. This is useful when subclasses implement their draw method and need to draw selected segments with a different pen/brush than unselected segments (also see QCPSelectionDecorator).

This class implements basic functionality of QCPAbstractPlottable::selectTest and QCPPlottableInterface1D::selectTestRect, assuming point-like data points, based on the 1D data interface. In spite of that, most plottable subclasses will want to reimplement those methods again, to provide a more accurate hit test based on their specific data visualization geometry.

Constructor & Destructor Documentation

§ QCPAbstractPlottable1D()

template<class DataType >

          QCPAbstractPlottable1D< DataType >::QCPAbstractPlottable1D
          (
          QCPAxis *
          keyAxis,

          QCPAxis *
          valueAxis

          )

Forwards keyAxis and valueAxis to the QCPAbstractPlottable constructor and allocates the mDataContainer.

Member Function Documentation

§ dataCount()

template<class DataType >

          int QCPAbstractPlottable1D< DataType >::dataCount
          (
          	)
           const

virtual

Returns the number of data points of the plottable.

Implements QCPPlottableInterface1D.

§ dataMainKey()

template<class DataType >

          double QCPAbstractPlottable1D< DataType >::dataMainKey
          (
          int
          index	)
           const

virtual

Returns the main key of the data point at the given index.

What the main key is, is defined by the plottable's data type. See the QCPDataContainer DataType documentation for details about this naming convention.

Implements QCPPlottableInterface1D.

§ dataSortKey()

template<class DataType >

          double QCPAbstractPlottable1D< DataType >::dataSortKey
          (
          int
          index	)
           const

virtual

Returns the sort key of the data point at the given index.

What the sort key is, is defined by the plottable's data type. See the QCPDataContainer DataType documentation for details about this naming convention.

Implements QCPPlottableInterface1D.

§ dataMainValue()

template<class DataType >

          double QCPAbstractPlottable1D< DataType >::dataMainValue
          (
          int
          index	)
           const

virtual

Returns the main value of the data point at the given index.

What the main value is, is defined by the plottable's data type. See the QCPDataContainer DataType documentation for details about this naming convention.

Implements QCPPlottableInterface1D.

§ dataValueRange()

template<class DataType >

          QCPRange QCPAbstractPlottable1D< DataType >::dataValueRange
          (
          int
          index	)
           const

virtual

Returns the value range of the data point at the given index.

What the value range is, is defined by the plottable's data type. See the QCPDataContainer DataType documentation for details about this naming convention.

Implements QCPPlottableInterface1D.

§ dataPixelPosition()

template<class DataType >

          QPointF QCPAbstractPlottable1D< DataType >::dataPixelPosition
          (
          int
          index	)
           const

virtual

Returns the pixel position on the widget surface at which the data point at the given index appears.

Usually this corresponds to the point of dataMainKey/dataMainValue, in pixel coordinates. However, depending on the plottable, this might be a different apparent position than just a coord-to-pixel transform of those values. For example, QCPBars apparent data values can be shifted depending on their stacking, bar grouping or configured base value.

Implements QCPPlottableInterface1D.

Reimplemented in QCPBars.

§ sortKeyIsMainKey()

template<class DataType >

          bool QCPAbstractPlottable1D< DataType >::sortKeyIsMainKey
          (
          	)
           const

virtual

Returns whether the sort key (dataSortKey) is identical to the main key (dataMainKey).

What the sort and main keys are, is defined by the plottable's data type. See the QCPDataContainer DataType documentation for details about this naming convention.

Implements QCPPlottableInterface1D.

§ selectTestRect()

template<class DataType >

          QCPDataSelection QCPAbstractPlottable1D< DataType >::selectTestRect
          (
          const QRectF &
          rect,

          bool
          onlySelectable

          )
          	 const

virtual

Implements a rect-selection algorithm assuming the data (accessed via the 1D data interface) is point-like. Most subclasses will want to reimplement this method again, to provide a more accurate hit test based on the true data visualization geometry.

For general information about this virtual method, see the base class implementation.

Implements QCPPlottableInterface1D.

Reimplemented in QCPBars, QCPFinancial, and QCPStatisticalBox.

§ findBegin()

template<class DataType >

          int QCPAbstractPlottable1D< DataType >::findBegin
          (
          double
          sortKey,

          bool
          expandedRange = true

          )
          	 const

virtual

Returns the index of the data point with a (sort-)key that is equal to, just below, or just above sortKey. If expandedRange is true, the data point just below sortKey will be considered, otherwise the one just above.

This can be used in conjunction with findEnd to iterate over data points within a given key range, including or excluding the bounding data points that are just beyond the specified range.

If expandedRange is true but there are no data points below sortKey, 0 is returned.

If the container is empty, returns 0 (in that case, findEnd will also return 0, so a loop using these methods will not iterate over the index 0).

See also

findEnd, QCPDataContainer::findBegin

Implements QCPPlottableInterface1D.

§ findEnd()

template<class DataType >

          int QCPAbstractPlottable1D< DataType >::findEnd
          (
          double
          sortKey,

          bool
          expandedRange = true

          )
          	 const

virtual

Returns the index one after the data point with a (sort-)key that is equal to, just above, or just below sortKey. If expandedRange is true, the data point just above sortKey will be considered, otherwise the one just below.

This can be used in conjunction with findBegin to iterate over data points within a given key range, including the bounding data points that are just below and above the specified range.

If expandedRange is true but there are no data points above sortKey, the index just above the highest data point is returned.

If the container is empty, returns 0.

See also

findBegin, QCPDataContainer::findEnd

Implements QCPPlottableInterface1D.

§ selectTest()

template<class DataType >

          double QCPAbstractPlottable1D< DataType >::selectTest
          (
          const QPointF &
          pos,

          bool
          onlySelectable,

          QVariant *
          details = 0

          )
          	 const

virtual

Implements a point-selection algorithm assuming the data (accessed via the 1D data interface) is point-like. Most subclasses will want to reimplement this method again, to provide a more accurate hit test based on the true data visualization geometry.

For general information about this virtual method, see the base class implementation.

Implements QCPAbstractPlottable.

Reimplemented in QCPBars, QCPFinancial, QCPGraph, QCPStatisticalBox, and QCPCurve.

§ interface1D()

template<class DataType>

          QCPPlottableInterface1D * QCPAbstractPlottable1D< DataType >::interface1D
          (
          	)

inlinevirtual

Returns a QCPPlottableInterface1D pointer to this plottable, providing access to its 1D interface.

For general information about this virtual method, see the base class implementation.

Reimplemented from QCPAbstractPlottable.

§ getDataSegments()

template<class DataType >

          void QCPAbstractPlottable1D< DataType >::getDataSegments
          (
          QList< QCPDataRange > &
          selectedSegments,

          QList< QCPDataRange > &
          unselectedSegments

          )
          	 const

protected

Splits all data into selected and unselected segments and outputs them via selectedSegments and unselectedSegments, respectively.

This is useful when subclasses implement their draw method and need to draw selected segments with a different pen/brush than unselected segments (also see QCPSelectionDecorator).

See also

setSelection

§ drawPolyline()

template<class DataType >

          void QCPAbstractPlottable1D< DataType >::drawPolyline
          (
          QCPPainter *
          painter,

          const QVector< QPointF > &
          lineData

          )
          	 const

protected

A helper method which draws a line with the passed painter, according to the pixel data in lineData. NaN points create gaps in the line, as expected from QCustomPlot's plottables (this is the main difference to QPainter's regular drawPolyline, which handles NaNs by lagging or crashing).

Further it uses a faster line drawing technique based on QCPPainter::drawLine rather than QPainter::drawPolyline if the configured QCustomPlot::setPlottingHints() and painter style allows.

The documentation for this class was generated from the following files:

src/plottable1d.h

src/plottable1d.cpp


text:
"""Tests gemini api endpoints."""
import requests

from behave import given, when, then
from urllib.parse import urljoin

from src.parsing import parse_token_clause
from src.authorization_tokens import authorization
from src.attribute_checks import check_attribute_presence, check_and_get_attribute, is_string
from src.attribute_checks import check_year, check_month, check_date, check_timestamp
from src.attribute_checks import check_response_time, check_cve_value, check_cve_score
from src.attribute_checks import is_posint_or_zero
from src.utils import read_data_gemini
import os
import datetime
import json
import re

SUPPORTED_ECOSYSTEMS = ("pypi", "npm", "maven")

@given('Gemini service is running')
def running_gemini_api(context):
    """Check if gemini pod is running."""
    return context.is_gemini_api_running

@given('Gemini service git url is {url}')
def set_git_url(context, url):
    """Set Git URL for test."""
    context.url = url

@given('Gemini service git sha is {sha}')
def set_git_sha(context, sha):
    """Set Git SHA for test."""
    context.sha = sha

@given('Gemini service epv list is {epv_list}')
def set_epv_list(context, epv_list):
    """Set epv_list for test."""
    context.epv_list = epv_list

@given('Gemini service dependency files are set')
def set_dependency_files(context):
    """Set dependency_files for test."""
    path_to_direct_file = os.path.abspath('data/gemini_scan_data/direct-dependencies.txt')
    path_to_transitive_file = os.path.abspath('data/gemini_scan_data/transitive-dependencies.txt')
    context.dependency_files = list()
    with open(path_to_direct_file, 'rb') as f:
        context.dependency_files.append((
            "dependencyFile[]",
            (
                'direct-dependencies.txt',
                f.read(),
                'text/plain'
            )
        ))
    with open(path_to_transitive_file, 'rb') as f:
        context.dependency_files.append((
            "dependencyFile[]",
            (
                'transitive-dependencies.txt',
                f.read(),
                'text/plain'
            )
        ))

@when('I access the {endpoint} endpoint of Gemini service')
@when('I access the {endpoint} endpoint of Gemini service {token} authorization token')
def access_gemini_url(context, endpoint, token="without"):
    """Access the Gemini service API using the HTTP GET method."""
    url = urljoin(context.gemini_api_url, endpoint)
    use_token = parse_token_clause(token)
    headers = {}
    if use_token:
        headers = authorization(context)
    context.response = requests.get(url, headers=headers)

@when('I access the {endpoint} endpoint of Gemini service for {parameter} report {history}')
@when('I access the {endpoint} endpoint of Gemini service for {parameter} report')
def access_stacks_report_list(context, endpoint, parameter='', history=''):
    """Access the Gemini stacks-report/list API endpoint using the HTTP GET method."""
    url = urljoin(context.gemini_api_url, '{ep}/{param}'.format(ep=endpoint, param=parameter))
    context.response = requests.get(url)
    context.history = True if history == 'history' else False

def get_list_of_reports_for_period(context, endpoint, period):
    """Get list of stack reports for selected period."""
    assert period in ("daily", "weekly", "monthly")

    # call the REST API
    url = urljoin(context.gemini_api_url, '{ep}/list/{param}'.format(ep=endpoint, param=period))
    response = requests.get(url).json()
    assert response is not None
    objects = check_and_get_attribute(response, "objects")

    # ATM we have at least one daily, weekly, monthly report
    assert len(objects) > 1
    return objects

def select_stack_report(objects, what):
    """Select the first or the last stack report."""
    assert what in ("first", "last")
    if what == "first":
        return objects[0]
    else:
        return objects[-1]

@when('I access the {endpoint} endpoint of Gemini service to get the {what} {period} report')
def access_stacks_report_for_given_time(context, endpoint, what, period):
    """Access the Gemini endpoint to get the first or last list of reports."""
    objects = get_list_of_reports_for_period(context, endpoint, period)

    # select the first or the last stack report
    stack_report = select_stack_report(objects, what)
    assert stack_report is not None

    # retrieve the selected stack report
    url = urljoin(context.gemini_api_url,
                  '{ep}/report/{stack_report}'.format(ep=endpoint, stack_report=stack_report))
    context.response = requests.get(url)
    assert context.response is not None

@when('I call the {endpoint} endpoint of Gemini service using the HTTP PUT method')
def access_gemini_url_put_method(context, endpoint):
    """Access the Gemini service API using the HTTP PUT method."""
    url = urljoin(context.gemini_api_url, endpoint)
    context.response = requests.put(url)

@when('I call the {endpoint} endpoint of Gemini service using the HTTP PATCH method')
def access_gemini_url_patch_method(context, endpoint):
    """Access the Gemini service API using the HTTP PATCH method."""
    url = urljoin(context.gemini_api_url, endpoint)
    context.response = requests.patch(url)

@when('I call the {endpoint} endpoint of Gemini service using the HTTP DELETE method')
def access_gemini_url_delete_method(context, endpoint):
    """Access the Gemini service API using the HTTP DELETE method."""
    url = urljoin(context.gemini_api_url, endpoint)
    context.response = requests.delete(url)

@when('I call the {endpoint} endpoint of Gemini service using the HTTP HEAD method')
def access_gemini_url_head_method(context, endpoint):
    """Access the Gemini service API using the HTTP HEAD method."""
    url = urljoin(context.gemini_api_url, endpoint)
    context.response = requests.head(url)

@when('I {method} to Gemini API {endpoint}')
@when('I {method} to Gemini API {endpoint} {token} authorization token')
def call_backbone_api(context, method="get", endpoint="/api/v1/register", token="without"):
    """Get or post data to gemini API."""
    use_token = parse_token_clause(token)
    headers = {}
    if use_token:
        headers = authorization(context)
    headers['Content-Type'] = 'application/json'
    headers['Accept'] = 'application/json'
    headers['git-url'] = "https://github.com/heroku/node-js-sample.git"

    if method == 'post':
        content = {
            'git-url': context.url,
            'git-sha': context.sha
        }

        if endpoint == "/api/v1/user-repo/notify":
            content.update({
                "epv_list": context.epv_list
            })
        url = '{}/{}'.format(context.gemini_api_url, endpoint)
        if endpoint == '/api/v1/user-repo/scan':
            content = read_data_gemini()
            headers['git-url'] = "https://github.com/heroku/node-js-sample.git"
            headers.pop('Accept', None)
            context.response = requests.post(url, data=json.dumps(content),
                                             headers=headers)
        else:
            context.response = requests.post(url, json=content, headers=headers)
    else:
        api_url = "{api_url}/{endpoint}?git-url={git_url}&git-sha={git_sha}".format(
            api_url=context.gemini_api_url,
            endpoint=endpoint,
            git_url=context.url,
            git_sha=context.sha)
        context.response = requests.get(api_url, headers=headers)

def check_cve_count(cve_count, cves):
    """Check if number of returned CVEs is expected."""
    assert cve_count is not None
    assert int(cve_count) >= int(cves), \
        "at least {exp} CVEs expected, but {found} was found".format(exp=cves, found=cve_count)

@then('I should find {cves} CVEs for package {p} version {v} from ecosystem {e} in dependencies')
def check_cves_for_epv(context, cves, p, v, e):
    """Check number of CVEs reported for given e/p/v in dependencies."""
    response = context.response.json()
    depencencies = check_and_get_attribute(response, "dependencies")

    for dependency in depencencies:
        cve_count = check_and_get_attribute(dependency, "cve_count")
        ecosystem = check_and_get_attribute(dependency, "ecosystem")
        package = check_and_get_attribute(dependency, "name")
        version = check_and_get_attribute(dependency, "version")
        if ecosystem == e and package == p and version == v:
            # check whether at least 'cves' CVEs has been reported
            check_cve_count(cve_count, cves)
            return
    raise Exception("{e}/{p}/{v} was not found".format(e=e, p=p, v=v))

@when('I retrieve at most {num:d} stacks from the stacks report')
def retrieve_stacks_from_report(context, num):
    """Retrieve stacks from Gemini stacks report."""
    response = context.response.json()
    assert not context.history

    check_attribute_presence(response, "report")
    stacks_details = check_and_get_attribute(response, "stacks_details")
    i = 0
    stacks = []
    for stack_detail in stacks_details:
        ecosystem = check_and_get_attribute(stack_detail, "ecosystem")
        stack = stack_detail["stack"]
        i += 1
        if i > num:
            break
        item = {
            "ecosystem": ecosystem,
            "stack": stack}

        stacks.append(item)

    context.stacks = stacks

@then('I should be able to export stacks into JSON format')
def export_stacks_from_report_into_json(context):
    """Export stacks retrieved from Gemini stacks report."""
    i = 0
    for record in context.stacks:
        i += 1
        ecosystem = record["ecosystem"]
        filename = "stack_{}_{:04}.json".format(ecosystem, i)
        with open(filename, "w") as fout:
            stack = record["stack"]
            json.dump(stack, fout)

@then('I should get a valid report')
def check_valid_report(context):
    """Check if the stacks report is a valid one."""
    response = context.response.json()
    if context.history:
        assert isinstance(response['objects'], list)
    else:
        assert isinstance(response, dict)

def check_one_daily_report_item(obj):
    """Check one item from the list of daily reports."""
    assert obj is not None
    is_string(obj)

    # path to daily report should contain the date in format YYYY-MM-DD
    # also the path is always the same
    pattern = re.compile("^daily/(20[0-9][0-9]-[0-1][0-9]-[0-3][0-9]).json$")
    m = pattern.match(obj)
    assert m is not None

    # ok, input string matches the pattern, let's check actual date
    date = m.group(1)
    check_date(date)

def check_one_weekly_report_item(obj):
    """Check one item from the list of weekly reports."""
    assert obj is not None
    is_string(obj)

    # path to weekly report should contain the date in format YYYY-MM-DD
    # also the path is always the same
    pattern = re.compile("^weekly/(20[0-9][0-9]-[0-1][0-9]-[0-3][0-9]).json$")
    m = pattern.match(obj)
    assert m is not None

    # ok, input string matches the pattern, let's check actual date
    date = m.group(1)
    check_date(date)

def check_one_monthly_report_item(obj):
    """Check one item from the list of monthly reports."""
    assert obj is not None
    is_string(obj)

    # path to monthly report should contain the date in format YYYY-MM (day is not specified)
    # also the path is always the same
    pattern = re.compile("^monthly/(20[0-9][0-9])-([0-1][0-9]).json$")
    m = pattern.match(obj)
    assert m is not None

    # ok, input string matches the pattern, let's check actual values
    year = m.group(1)
    month = m.group(2)
    check_year(year)
    check_month(month)

@then('I should get valid list of daily reports')
def check_list_of_daily_reports(context):
    """Check the validity of list of daily reports."""
    response = context.response.json()
    objects = check_and_get_attribute(response, "objects")

    # ATM we have at least one daily report
    assert len(objects) > 1

    # check details about are listed reports
    for obj in objects:
        check_one_daily_report_item(obj)

@then('I should get valid list of weekly reports')
def check_list_of_weekly_reports(context):
    """Check the validity of list of weekly reports."""
    response = context.response.json()
    objects = check_and_get_attribute(response, "objects")

    # ATM we have at least one weekly report
    assert len(objects) > 1

    # check details about are listed reports
    for obj in objects:
        check_one_weekly_report_item(obj)

@then('I should get valid list of monthly reports')
def check_list_of_monthly_reports(context):
    """Check the validity of list of monthly reports."""
    response = context.response.json()
    objects = check_and_get_attribute(response, "objects")

    # ATM we have at least one monthly report
    assert len(objects) > 1

    # check details about are listed reports
    for obj in objects:
        check_one_monthly_report_item(obj)

def check_report_from_to_dates(report):
    """Check all attributes stored in 'report' node from the stack analysis."""
    assert report is not None
    from_date = check_and_get_attribute(report, "from")
    to_date = check_and_get_attribute(report, "to")
    generated_on = check_and_get_attribute(report, "generated_on")

    # 'generated_on' attribute should contain a proper timestamp
    check_timestamp(generated_on)

    # 'from' and 'to' attributes should contain a date in format YYYY-MM-DD
    check_date(from_date)
    check_date(to_date)

def parse_date(date_str):
    """Parse date from given string."""
    return datetime.datetime.strptime(date_str, "%Y-%m-%d")

def check_dates_difference(report, days_threshold):
    """Compute the difference between two dates and compare it with given threshold value."""
    from_date = parse_date(check_and_get_attribute(report, "from"))
    to_date = parse_date(check_and_get_attribute(report, "to"))
    assert from_date is not None
    assert to_date is not None
    # a day (at least)
    diff = to_date - from_date
    assert diff.days >= days_threshold

def check_report_from_to_dates_daily(report):
    """Check the content of 'report' node in daily report."""
    # check all the required attributes in 'report' node
    check_report_from_to_dates(report)
    # a day (at least)
    check_dates_difference(report, 1)

def check_report_from_to_dates_weekly(report):
    """Check the content of 'report' node in weekly report."""
    # check all the required attributes in 'report' node
    check_report_from_to_dates(report)
    # work week (at least)
    check_dates_difference(report, 5)

def check_report_from_to_dates_monthly(report):
    """Check the content of 'report' node in monthly report."""
    # check all the required attributes in 'report' node
    check_report_from_to_dates(report)
    # more than four weeks
    check_dates_difference(report, 27)

def check_license(license):
    """Check the license from the stack detail."""
    # TODO: better checks needs to be added
    assert license is not None

def check_stacks_detail(detail):
    """Check selected stacks detail in generated stack report."""
    # try to retrieve all required attributes
    ecosystem = check_and_get_attribute(detail, "ecosystem")
    license = check_and_get_attribute(detail, "license")
    response_time = check_and_get_attribute(detail, "response_time")
    security = check_and_get_attribute(detail, "security")
    stack = check_and_get_attribute(detail, "stack")
    unknown_dependencies = check_and_get_attribute(detail, "unknown_dependencies")

    # check actual values of required attributes
    assert ecosystem in SUPPORTED_ECOSYSTEMS
    check_response_time(response_time)

    for package in stack:
        # TODO: add some package+version check
        is_string(package)

    for package in unknown_dependencies:
        # TODO: add some package+version check
        is_string(package)

    cve_list = check_and_get_attribute(security, "cve_list")

    check_license(license)

    for cve_record in cve_list:
        cve = check_and_get_attribute(cve_record, "CVE")
        cvss = check_and_get_attribute(cve_record, "CVSS")
        check_cve_value(cve, with_score=False)
        check_cve_score(cvss)

def check_stacks_details(details):
    """Check the stacks details in generated stack report."""
    assert details is not None
    for detail in details:
        check_stacks_detail(detail)

def check_report_for_ecosystem(summary, ecosystem):
    """Check the stack report for the selected ecosystem."""
    report = check_and_get_attribute(summary, ecosystem)

    # try to retrieve all required attributes
    response_time = check_and_get_attribute(report, "average_response_time")

    # check actual values of required attributes
    check_response_time(response_time)

def check_stacks_summary(summary):
    """Check the stacks summary in generated stack report."""
    assert summary is not None
    for ecosystem in SUPPORTED_ECOSYSTEMS:
        if ecosystem in summary:
            check_report_for_ecosystem(summary, ecosystem)

    # try to retrieve all required attributes
    cves = check_and_get_attribute(summary, "unique_cves")
    requests = check_and_get_attribute(summary, "total_stack_requests_count")
    response_time = check_and_get_attribute(summary, "total_average_response_time")

    # check actual values of required attributes
    check_response_time(response_time)
    is_posint_or_zero(requests)

    # check all reported CVEs
    for cve, count in cves.items():
        check_cve_value(cve, with_score=True)
        is_posint_or_zero(count)

@then('I should get a valid daily report')
def check_valid_daily_report(context):
    """Check if the daily stacks report is valid."""
    response = context.response.json()
    assert response is not None

    # try to retrieve all required attributes
    report = check_and_get_attribute(response, "report")
    stacks_details = check_and_get_attribute(response, "stacks_details")
    stacks_summary = check_and_get_attribute(response, "stacks_summary")

    # check actual values of required attributes
    check_report_from_to_dates_daily(report)
    check_stacks_details(stacks_details)
    check_stacks_summary(stacks_summary)

@then('I should get a valid weekly report')
def check_valid_weekly_report(context):
    """Check if the weekly stacks report is valid."""
    response = context.response.json()
    assert response is not None

    # try to retrieve all required attributes
    report = check_and_get_attribute(response, "report")
    stacks_details = check_and_get_attribute(response, "stacks_details")
    stacks_summary = check_and_get_attribute(response, "stacks_summary")

    # check actual values of required attributes
    check_report_from_to_dates_weekly(report)
    check_stacks_details(stacks_details)
    check_stacks_summary(stacks_summary)

@then('I should get a valid monthly report')
def check_valid_monthly_report(context):
    """Check if the monthly stacks report is valid."""
    response = context.response.json()
    assert response is not None

    # try to retrieve all required attributes
    report = check_and_get_attribute(response, "report")
    stacks_details = check_and_get_attribute(response, "stacks_details")
    stacks_summary = check_and_get_attribute(response, "stacks_summary")

    # check actual values of required attributes
    check_report_from_to_dates_monthly(report)
    check_stacks_details(stacks_details)
    check_stacks_summary(stacks_summary)

redpajama_set_name: RedPajamaGithub


text:
#ifndef SHA1_H
#define SHA1_H
/* ================ sha1.h ================ */
/*
SHA-1 in C
By Steve Reid <steve@edmweb.com>
100% Public Domain
*/

typedef struct {
    uint32_t state[5];
    uint32_t count[2];
    unsigned char buffer[64];
} SHA1_CTX;

void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]);
void SHA1Init(SHA1_CTX* context);
void SHA1Update(SHA1_CTX* context, const unsigned char* data, uint32_t len);
void SHA1Final(unsigned char digest[20], SHA1_CTX* context);

#ifdef REDIS_TEST
int sha1Test(int argc, char **argv);
#endif
#endif


text:
    <input type="radio" name="showAllDecks" value="false" autocomplete="off"
           (change)="setShowAllDecks(false)"> Player decks ({{ myDecks?.length }})

    <input type="radio" name="showAllDecks" value="true" autocomplete="off"
           (change)="setShowAllDecks(true)"> All ({{ allDecks?.length }})

  <agot-deck-chooser [decks]="myDecks" [isLoading]="isLoadingMyDecks"
                     [existingDeck]="existingDeck"
                     (selectDeck)="onDeckSelect($event)"></agot-deck-chooser>

  <agot-deck-chooser [decks]="allDecks" [isLoading]="isLoadingAllDecks"
                     [existingDeck]="existingDeck"
                     (selectDeck)="onDeckSelect($event)"></agot-deck-chooser>


text:
<?php

namespace App\Http\Controllers\Admin;

use App\Mount;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use GuzzleHttp\Exception\RequestException;

class MountController extends Controller
{
	/** @GuzzleHttp */
	private $client;

	function __construct()
	{
		// $this->apiUrl = 'http://icecast.'.env('APP_URL').':3000';
		$apiUrl = 'http://icecast.sintoniza.la:3000/';
		$this->client = new Client(['base_uri' => $apiUrl]);
	}

	public function test() {
		$response = $this->client->request('delete', 'mounts/1');
		// $response = $client->send($request, ['timeout' => 2]);
		// $code = $response->getStatusCode();
		// $reason = $response->getReasonPhrase();
		// $body = $response->getBody();
		dump($response);die;
	}

	/**
	 * Vista con todos los puntos de montajes.
	 *
	 * @return Object
	 */
	public function index()
	{
		$title = 'Puntos de montajes';
		$mounts = Mount::latest()->paginate(30);

		return view('admin.mount.index', [
			'title' => $title,
			'mounts' => $mounts
		]);
    }

    /**
	 * Vista con el formulario para agregar un nuevo punto de montaje.
	 *
	 * @return void
	 */
	public function create()
	{
		$title = 'Agregar punto de montaje';

		return view('admin.mount.create')->with('title', $title);
    }

    /**
	 * Metodo para agregar el punto de montaje a la base de datos.
	 *
	 * @param  StoreUpdatePost $request
	 * @return void
	 */
	public function store(Request $request)
	{
		$data = $request->except(['_token']); // Quitar del array el token enviado por el formulario
		$mount = Mount::create($data);
		try {
			$this->client->request('post', 'mounts', [
				'json' => [
					'id' => $mount->id,
					'mount-name' => $mount->name,
					'username' => $mount->username,
					'password' => $mount->password
				]
			]);
		} catch (RequestException $e) {
			$guzzleResult = $e->getResponse();
		}

		return redirect()
			   ->route('admin.mount.edit', ['id' => $mount->id])
			   ->with('status', '¡Punto de montaje agregada!');
    }

    /**
	 * Vista con el formulario para editar un punto de montaje.
	 *
	 * @return Object
	 */
	public function edit($id)
	{
		$title = 'Editar punto de montaje';
		$mount = Mount::find($id);

		return view('admin.mount.edit', [
			'title' => $title,
			'mount' => $mount
		]);
	}

	/**
	 * Metodo para actualizar los datos de un punto de montaje.
     *
     * @return void
	 */
	public function update($id, Request $request)
	{
		// Retrieve the validated input data...
		$validated = $request->validated();

        $data = $request->except(['_token']); // Quitar el token enviado por el form del array

		$mount = Mount::find($id); // Buscar por el id

		$mount->update($data); // Actualizar la entrada con los nuevos datos

		return redirect()
			   ->route('admin.mount.edit', ['id' => $id]) // Redirección a la vista editar con el ID de la entrada
			   ->with('status', 'Punto de montaje actualizado!'); // Crear una session flash con el status de la operación
	}

	/**
	 * Metodo para eliminar un punto de montaje.
	 *
	 * @return Object
	 */
	public function destroy($id)
	{
		$mount = Mount::find($id);

		try {
			$this->client->request('delete', 'mounts/'.$mount->id);
		} catch (RequestException $e) {
			$guzzleResult = $e->getResponse();
		}

		$mount->delete();

		return redirect()
			   ->route('admin.mount.index')
			   ->with('status', '¡Punto de montaje eliminado!');
	}
}


text:
package pbmeta

import (
	"fmt"
	"strings"

	pbprotos "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
)

type FieldDescriptor struct {
	Define *pbprotos.FieldDescriptorProto
	CommentMeta
	dp *DescriptorPool

	msg *Descriptor
}

func (self *FieldDescriptor) Name() string {
	return self.Define.GetName()
}

func (self *FieldDescriptor) TypeName() string {
	return self.Define.GetTypeName()
}

// pb定义中插件返回的格式时 .package.type.value的格式, 这里返回去掉头的.
func (self *FieldDescriptor) FullTypeName() string {
	return normalizeFullName(self.Define.GetTypeName())
}

func (self *FieldDescriptor) MessageDesc() *Descriptor {

	// TODO 内嵌结构估计得使用和枚举一样的方法进行
	if d := self.msg.NestedMsg.MessageByName(self.FullTypeName()); d != nil {
		return d
	}

	return self.dp.MessageByFullName(self.FullTypeName())
}

func (self *FieldDescriptor) EnumDesc() *EnumDescriptor {

	// 这里很奇怪, 按descriptor.proto里FieldDescriptorProto的type_name注释说:
	// "."开头的名字是全局空间, 然而内嵌的类型并不是这样导出的
	// 而要找到结构体的完全路径是非常困难的, 因此这里用一个取巧的方法:
	// 使用字段所在消息的名字+字段所在消息内嵌枚举的名字不断进行尝试, 直到
	// 符合自己枚举的全名尾缀
	for i := 0; i < self.msg.EnumSet.EnumCount(); i++ {

		en := self.msg.EnumSet.Enum(i)

		tailName := fmt.Sprintf("%s.%s", self.msg.Define.GetName(), en.Name())

		if strings.HasSuffix(self.FullTypeName(), tailName) {
			return en
		}

	}

	return self.dp.EnumByFullName(self.FullTypeName())
}

func (self *FieldDescriptor) IsRequired() bool {
	return self.Define.GetLabel() == pbprotos.FieldDescriptorProto_LABEL_REQUIRED
}

func (self *FieldDescriptor) IsOptional() bool {
	return self.Define.GetLabel() == pbprotos.FieldDescriptorProto_LABEL_OPTIONAL
}

func (self *FieldDescriptor) IsRepeated() bool {
	return self.Define.GetLabel() == pbprotos.FieldDescriptorProto_LABEL_REPEATED
}

func (self *FieldDescriptor) IsMessageType() bool {
	return self.Define.GetType() == pbprotos.FieldDescriptorProto_TYPE_MESSAGE
}

func (self *FieldDescriptor) IsEnumType() bool {
	return self.Define.GetType() == pbprotos.FieldDescriptorProto_TYPE_ENUM
}

func (self *FieldDescriptor) Label() pbprotos.FieldDescriptorProto_Label {
	return self.Define.GetLabel()
}
func (self *FieldDescriptor) Type() pbprotos.FieldDescriptorProto_Type {
	return self.Define.GetType()
}

func (self *FieldDescriptor) DefaultValue() string {
	return self.Define.GetDefaultValue()
}

func newFieldDescriptor(parent *Descriptor, raw *pbprotos.FieldDescriptorProto,
	comment *pbprotos.SourceCodeInfo_Location,
	dp *DescriptorPool) *FieldDescriptor {

	md := &FieldDescriptor{
		Define:      raw,
		dp:          dp,
		msg:         parent,
		CommentMeta: newCommentMeta(comment),
	}

	//log.Printf("field: %s %s", md.Define.GetName(), md.comment.GetTrailingComments())

	return md

}


text:
module(..., lunit.testcase, package.seeall)

local common = dofile("common.lua")
local net = require "luanode.net"

function test()
local tests_run = 0

function pingPong (port, host)
	local N = 1000
	local count = 0
	local sent_final_ping = false

	local server = net.createServer(function (self, socket)
		console.log("connection: %s:%d", socket:remoteAddress())
		assert_equal(self, socket.server)
		assert_equal(1, self.connections)

		socket:setNoDelay()
		socket.timeout = 0

		socket:setEncoding("utf8")
		socket:addListener("data", function (self, data)
			console.log("server got: %s", data)
			assert_equal(true, socket.writable)
			assert_equal(true, socket.readable)
			assert_equal(true, count <= N)
			if data:match("PING") then
				socket:write("PONG")
			end
		end)

		socket:addListener("end", function (self)
			assert_equal(true, socket.writable)
			assert_equal(false, socket.readable)
			socket:finish()
		end)

		socket:addListener("error", function (self, e)
			error(e)
		end)

		socket:addListener("close", function (self)
			console.log("server socket.end")
			assert_equal(false, socket.writable)
			assert_equal(false, socket.readable)
			socket.server:close()
		end)
	end)

	server:listen(port, host, function (self)
		console.log("server listening on " .. port .. " " .. (host and host or ""))

		local client = net.createConnection(port, host)
		collectgarbage()

		client:setEncoding("ascii")
		client:addListener("connect", function ()
			assert_equal(true, client.readable)
			assert_equal(true, client.writable)
			client:write("PING")
		end)

		client:addListener("data", function (self, data)
			console.log("client got: %s", data)

			assert_equal("PONG", data)
			count = count + 1

			if sent_final_ping then
				assert_equal(false, client.writable)
				assert_equal(true, client.readable)
				return
			else
				assert_equal(true, client.writable)
				assert_equal(true, client.readable)
			end

			if count < N then
				client:write("PING")
			else
				sent_final_ping = true
				client:write("PING")
				client:finish()
			end
		end)

		client:addListener("close", function ()
			console.log("client.end")
			assert_equal(N + 1, count)
			assert_equal(true, sent_final_ping)
			tests_run = tests_run + 1
		end)

		client:addListener("error", function (self, e)
			error(e)
		end)
	end)
end

-- All are run at once, so run on different ports
pingPong(20989, "localhost")
pingPong(20988)
--pingPong(20997, "::1")	-- deshabilitado porque mi notebook no soporta ipv6
--pingPong("/tmp/pingpong.sock")	-- aun no soporto unix domain sockets

process:addListener("exit", function ()
	--assert_equal(3, tests_run)
	assert_equal(2, tests_run)
	console.log("done")
end)

process:loop()
end


text:
import mock

from solum.api.controllers.v1.pub import trigger
from solum.tests import base
from solum.tests import fakes

@mock.patch('pecan.request', new_callable=fakes.FakePecanRequest)
@mock.patch('pecan.response', new_callable=fakes.FakePecanResponse)
class TestTriggerController(base.BaseTestCase):
    def test_trigger_post(self, resp_mock, request_mock):
        obj = trigger.TriggerController()
        obj.post(1)
        self.assertEqual(400, resp_mock.status)


text:
'use strict';

var responses = {
	'badRequest':require('./badRequest.js'),
	'forbidden':require('./forbidden.js'),
	'notFound':require('./notFound.js'),
	'ok':require('./ok.js'),
	'serverError':require('./serverError.js'),
	'unauthorized':require('./unauthorized.js')
};

module.exports = responses;


text:
namespace DataTemplateDemo
{
    using System.Collections.Generic;
    using System.Windows;
    using System.Windows.Media.Media3D;

    using ExampleBrowser;

    using HelixToolkit.Wpf;

    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    [Example(null, "Creating Visual3Ds by a template.")]
    public partial class MainWindow : Window
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow"/> class.
        /// </summary>
        public MainWindow()
        {
            this.InitializeComponent();
            this.Elements = new List<Element>
                             {
                                 new Element
                                     {
                                         Position = new Point3D(0, 0, 0),
                                         Material = Materials.Red,
                                         Radius = 1
                                     },
                                 new Element
                                     {
                                         Position = new Point3D(-0.757, 0.586, 0),
                                         Material = Materials.White,
                                         Radius = 0.6
                                     },
                                 new Element
                                     {
                                         Position = new Point3D(0.757, 0.586, 0),
                                         Material = Materials.White,
                                         Radius = 0.6
                                     }
                             };
            this.DataContext = this;
        }

        /// <summary>
        /// Gets or sets the items.
        /// </summary>
        public IList<Element> Elements { get; set; }
    }
}


text:
// Programar em C# #46 - Classe Math

using System;

namespace Base {
    class ClasseMath {
        public void Run() {
            Console.WriteLine($"Resultado do método Sin(): {Math.Sin(10.5)}");
            Console.WriteLine($"Resultado do método Cos(): {Math.Cos(10.5)}");
            Console.WriteLine($"Resultado do método Tan(): {Math.Tan(10.5)}");
            Console.WriteLine($"Resultado do método Floor(): {Math.Floor(10.5)}");
            Console.WriteLine($"Resultado do método Ceiling(): {Math.Ceiling(10.5)}");
            Console.WriteLine($"Resultado do método Abs(): {Math.Abs(-10.5)}");
            Console.WriteLine($"Resultado do método Sqrt(): {Math.Sqrt(10.5)}");
            Console.WriteLine($"Resultado do método Pow(): {Math.Pow(2, 5)}"); // 2 * 2 * 2 * 2 * 2
        }
    }
}


text:
* Use google analytics universal (Chamnap Chhorn)

* Render liquid template as html_safe by default (Dan Kubb)

## 0.1.1

### New Features

* Add `bootstrap_pagination` filter. (Radin Reth)

* Allow `translate` filter with interpolation. (Tomasz Stachewicz, Chamnap Chhorn)

* Support `rails` 4.2 and `ruby` 2.2. (Chamnap Chhorn)

* Support `scope` on collection drop. (Radin Reth)

### Resolved Issues

* Add `rel="prev"` and `rel="next"` to `default_pagination` filter. (Radin Reth)

* Fix `content_for` and `yield` tag on `rails` 3.2. (Chamnap Chhorn)

* \#4 Makes partial template work in namespaced controller. (Tomasz Stachewicz)

* `truncate` filter now forwards to the standard filters. (Radin Reth)

## 0.1.0

* Initial Release


text:
class IndentationParser
  class Node
    def initialize source, indentation
      @source = source
      @indentation = indentation
      @subnodes = []
    end
    def add node
      node.set_parent self
      @subnodes << node
    end
    def parent
      @parent
    end
    def set_parent parent
      @parent = parent
    end
    def indentation
      @indentation
    end
    def source
      @source
    end
    def value
      @value
    end
    def set_value value
      @value = value
    end
  end

  class RootNode < Node
    def initialize
      super "root", -1
    end
  end
end


text:
import React, { PropTypes } from 'react'
import Details from './Details'
import Skill from './Skill'

const styles = {
  sidebar: {
    padding: '15px',
  },
}

const Sidebar = (props) => {
  const skills = Object.keys(props.skills)
    .map(key => <Skill key={key} name={key} values={props.skills[key]} />)

  return (
    <div style={styles.sidebar}>
      <Details {...props.details} />
      {skills}
    </div>
  )
}
Sidebar.propTypes = {
  skills: PropTypes.object,
  details: PropTypes.object,
}

export default Sidebar


text:
package br.gdgsp.volleydemo.domain;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author : ubiratanfsoares
 **/

public class CityWeatherInfo {

    private static final String BASE_IMAGE_URL = "http://openweathermap.org/img/w/";

    public static String getBaseImageUrl() {
        return BASE_IMAGE_URL;
    }

    private String mName;
    private int mTemperature;
    private int mHumidity;
    private String mWeatherCondition;
    private String mWeatherIconURL;

    public CityWeatherInfo(JSONObject infoJson) throws JSONException {
        mName = infoJson.getString("name");
        parseTemperature(infoJson);
        parseConditions(infoJson);
    }

    public String getName() {
        return mName;
    }

    public int getTemperature() {
        return mTemperature;
    }

    public int getHumidity() {
        return mHumidity;
    }

    public String getWeatherCondition() {
        return mWeatherCondition;
    }

    public String getWeatherIconURL() {
        return mWeatherIconURL;
    }

    @Override
    public String toString() {
        return mName + " | " + mTemperature;
    }
    private void parseConditions(JSONObject infoJson) throws JSONException {
        final JSONArray conditionsArray = infoJson.getJSONArray("weather");
        final JSONObject conditionInfo = conditionsArray.getJSONObject(0);
        mWeatherCondition = conditionInfo.getString("main");
        mWeatherIconURL = BASE_IMAGE_URL + conditionInfo.getString("icon");
    }

    private void parseTemperature(JSONObject infoJson) throws JSONException {
        final JSONObject mainJson = infoJson.getJSONObject("main");
        mTemperature = mainJson.getInt("temp");
        mHumidity = mainJson.getInt("humidity");
    }
}


text:
/**
 * Sample BLE React Native App
 *
 * @format
 * @flow strict-local
 */

import React, {
  useState,
  useEffect,
} from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
  NativeModules,
  NativeEventEmitter,
  Button,
  Platform,
  PermissionsAndroid,
  FlatList,
  TouchableHighlight,
} from 'react-native';

import {
  Colors,
} from 'react-native/Libraries/NewAppScreen';

import BleManager from '../BleManager';
const BleManagerModule = NativeModules.BleManager;
const bleManagerEmitter = new NativeEventEmitter(BleManagerModule);

const App = () => {
  const [isScanning, setIsScanning] = useState(false);
  const peripherals = new Map();
  const [list, setList] = useState([]);

  const startScan = () => {
    if (!isScanning) {
      BleManager.scan([], 3, true).then((results) => {
        console.log('Scanning...');
        setIsScanning(true);
      }).catch(err => {
        console.error(err);
      });
    }
  }

  const handleStopScan = () => {
    console.log('Scan is stopped');
    setIsScanning(false);
  }

  const handleDisconnectedPeripheral = (data) => {
    let peripheral = peripherals.get(data.peripheral);
    if (peripheral) {
      peripheral.connected = false;
      peripherals.set(peripheral.id, peripheral);
      setList(Array.from(peripherals.values()));
    }
    console.log('Disconnected from ' + data.peripheral);
  }

  const handleUpdateValueForCharacteristic = (data) => {
    console.log('Received data from ' + data.peripheral + ' characteristic ' + data.characteristic, data.value);
  }

  const retrieveConnected = () => {
    BleManager.getConnectedPeripherals([]).then((results) => {
      if (results.length == 0) {
        console.log('No connected peripherals')
      }
      console.log(results);
      for (var i = 0; i < results.length; i++) {
        var peripheral = results[i];
        peripheral.connected = true;
        peripherals.set(peripheral.id, peripheral);
        setList(Array.from(peripherals.values()));
      }
    });
  }

  const handleDiscoverPeripheral = (peripheral) => {
    console.log('Got ble peripheral', peripheral);
    if (!peripheral.name) {
      peripheral.name = 'NO NAME';
    }
    peripherals.set(peripheral.id, peripheral);
    setList(Array.from(peripherals.values()));
  }

  const testPeripheral = (peripheral) => {
    if (peripheral){
      if (peripheral.connected){
        BleManager.disconnect(peripheral.id);
      }else{
        BleManager.connect(peripheral.id).then(() => {
          let p = peripherals.get(peripheral.id);
          if (p) {
            p.connected = true;
            peripherals.set(peripheral.id, p);
            setList(Array.from(peripherals.values()));
          }
          console.log('Connected to ' + peripheral.id);

          setTimeout(() => {

            /* Test read current RSSI value */
            BleManager.retrieveServices(peripheral.id).then((peripheralData) => {
              console.log('Retrieved peripheral services', peripheralData);

              BleManager.readRSSI(peripheral.id).then((rssi) => {
                console.log('Retrieved actual RSSI value', rssi);
                let p = peripherals.get(peripheral.id);
                if (p) {
                  p.rssi = rssi;
                  peripherals.set(peripheral.id, p);
                  setList(Array.from(peripherals.values()));
                }
              });
            });

            // Test using bleno's pizza example
            // https://github.com/sandeepmistry/bleno/tree/master/examples/pizza
            /*
            BleManager.retrieveServices(peripheral.id).then((peripheralInfo) => {
              console.log(peripheralInfo);
              var service = '13333333-3333-3333-3333-333333333337';
              var bakeCharacteristic = '13333333-3333-3333-3333-333333330003';
              var crustCharacteristic = '13333333-3333-3333-3333-333333330001';

              setTimeout(() => {
                BleManager.startNotification(peripheral.id, service, bakeCharacteristic).then(() => {
                  console.log('Started notification on ' + peripheral.id);
                  setTimeout(() => {
                    BleManager.write(peripheral.id, service, crustCharacteristic, [0]).then(() => {
                      console.log('Writed NORMAL crust');
                      BleManager.write(peripheral.id, service, bakeCharacteristic, [1,95]).then(() => {
                        console.log('Writed 351 temperature, the pizza should be BAKED');

                        //var PizzaBakeResult = {
                        //  HALF_BAKED: 0,
                        //  BAKED:      1,
                        //  CRISPY:     2,
                        //  BURNT:      3,
                        //  ON_FIRE:    4
                        //};
                      });
                    });

                  }, 500);
                }).catch((error) => {
                  console.log('Notification error', error);
                });
              }, 200);
            });*/

          }, 900);
        }).catch((error) => {
          console.log('Connection error', error);
        });
      }
    }

  }

  useEffect(() => {
    BleManager.start({showAlert: false});

    bleManagerEmitter.addListener('BleManagerDiscoverPeripheral', handleDiscoverPeripheral);
    bleManagerEmitter.addListener('BleManagerStopScan', handleStopScan );
    bleManagerEmitter.addListener('BleManagerDisconnectPeripheral', handleDisconnectedPeripheral );
    bleManagerEmitter.addListener('BleManagerDidUpdateValueForCharacteristic', handleUpdateValueForCharacteristic );

    if (Platform.OS === 'android' && Platform.Version >= 23) {
      PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION).then((result) => {
          if (result) {
            console.log("Permission is OK");
          } else {
            PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION).then((result) => {
              if (result) {
                console.log("User accept");
              } else {
                console.log("User refuse");
              }
            });
          }
      });
    }

    return (() => {
      console.log('unmount');
      bleManagerEmitter.removeListener('BleManagerDiscoverPeripheral', handleDiscoverPeripheral);
      bleManagerEmitter.removeListener('BleManagerStopScan', handleStopScan );
      bleManagerEmitter.removeListener('BleManagerDisconnectPeripheral', handleDisconnectedPeripheral );
      bleManagerEmitter.removeListener('BleManagerDidUpdateValueForCharacteristic', handleUpdateValueForCharacteristic );
    })
  }, []);

  const renderItem = (item) => {
    const color = item.connected ? 'green' : '#fff';
    return (
      <TouchableHighlight onPress={() => testPeripheral(item) }>
        <View style={[styles.row, {backgroundColor: color}]}>
          <Text style={{fontSize: 12, textAlign: 'center', color: '#333333', padding: 10}}>{item.name}</Text>
          <Text style={{fontSize: 10, textAlign: 'center', color: '#333333', padding: 2}}>RSSI: {item.rssi}</Text>
          <Text style={{fontSize: 8, textAlign: 'center', color: '#333333', padding: 2, paddingBottom: 20}}>{item.id}</Text>
        </View>
      </TouchableHighlight>
    );
  }

  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={styles.scrollView}>
          {global.HermesInternal == null ? null : (
            <View style={styles.engine}>
              <Text style={styles.footer}>Engine: Hermes</Text>
            </View>
          )}
          <View style={styles.body}>

            <View style={{margin: 10}}>
              <Button
                title={'Scan Bluetooth (' + (isScanning ? 'on' : 'off') + ')'}
                onPress={() => startScan() }
              />
            </View>

            <View style={{margin: 10}}>
              <Button title="Retrieve connected peripherals" onPress={() => retrieveConnected() } />
            </View>

            {(list.length == 0) &&
              <View style={{flex:1, margin: 20}}>
                <Text style={{textAlign: 'center'}}>No peripherals</Text>
              </View>
            }

          </View>
        </ScrollView>
        <FlatList
            data={list}
            renderItem={({ item }) => renderItem(item) }
            keyExtractor={item => item.id}
          />
      </SafeAreaView>
    </>
  );
};

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: Colors.lighter,
  },
  engine: {
    position: 'absolute',
    right: 0,
  },
  body: {
    backgroundColor: Colors.white,
  },
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    color: Colors.black,
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
    color: Colors.dark,
  },
  highlight: {
    fontWeight: '700',
  },
  footer: {
    color: Colors.dark,
    fontSize: 12,
    fontWeight: '600',
    padding: 4,
    paddingRight: 12,
    textAlign: 'right',
  },
});

export default App;


text:
/**
 * The Timeline Complete Event.
 *
 * This event is dispatched by a Tween Timeline when it completes playback.
 *
 * Listen to it from a Timeline instance using `Timeline.on('complete', listener)`, i.e.:
 *
 * ```javascript
 * var timeline = this.tweens.timeline({
 *     targets: image,
 *     ease: 'Power1',
 *     duration: 3000,
 *     tweens: [ { x: 600 }, { y: 500 }, { x: 100 }, { y: 100 } ]
 * });
 * timeline.on('complete', listener);
 * timeline.play();
 * ```
 *
 * @event Phaser.Tweens.Events#TIMELINE_COMPLETE
 * @since 3.0.0
 *
 * @param {Phaser.Tweens.Timeline} timeline - A reference to the Timeline instance that emitted the event.
 */
module.exports = 'complete';


text:
'use strict';
var request = require('request');

function createRepo(token, reponame, cb) {

  var url = 'https://api.github.com/user/repos';

  var data = {
    "name": reponame
  }

  var options = {
    uri: url,
    method: 'POST',
    headers: {
      'User-Agent': 'git-remote-create',
      'Authorization': 'token ' + token
    },
    json: data
  };

  request(options, function(err, response, body) {
    if (err) return cb(err);

    if (response && response.statusCode == 201) {
      cb(null, body);
    } else {
      cb(body.message);
    }
  });
}

module.exports = createRepo;


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

/* HotkeyModifiers.cs --
   Ars Magna project, http://arsmagna.ru */

#region Using directives

using System;

#endregion

namespace AM.Win32
{
    /// <summary>
    /// Hotkey modifiers.
    /// </summary>
	[Flags]
	public enum HotkeyModifiers
	{
        /// <summary>
        /// None.
        /// </summary>
		None = 0,

        /// <summary>
        /// Alt.
        /// </summary>
		Alt = 1,

        /// <summary>
        /// Control.
        /// </summary>
		Control = 2,

        /// <summary>
        /// Shift.
        /// </summary>
		Shift = 4,

        /// <summary>
        /// Win.
        /// </summary>
		Win = 8
	}
}


text:
using System.Collections.Generic;

namespace NuDoq
{
    /// <summary>
    /// Represents the <c>term</c> documentation tag.
    /// </summary>
    /// <remarks>
    /// See http://msdn.microsoft.com/en-US/library/y3ww3c7e(v=vs.80).aspx.
    /// </remarks>
    public class Term : Container
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Term"/> class.
        /// </summary>
        /// <param name="elements">The contained elements within this instance.</param>
        /// <param name="attributes">The attributes of the element, if any.</param>
        public Term(IEnumerable<Element> elements, IDictionary<string, string> attributes)
            : base(elements, attributes)
        {
        }

        /// <summary>
        /// Accepts the specified visitor.
        /// </summary>
        public override TVisitor Accept<TVisitor>(TVisitor visitor)
        {
            visitor.VisitTerm(this);
            return visitor;
        }

        /// <summary>
        /// Returns a <see cref="string" /> that represents this instance.
        /// </summary>
        public override string ToString() => "<term>" + base.ToString();
    }
}


text:
__author__ = 'kevin'

import traceback
import commands
import os

class Common:
    debug = False

    @staticmethod
    def set_debug(value):
        Common.debug = value

    @staticmethod
    def log(message):
        if Common.debug:
            print " > %s" % (message,)

    @staticmethod
    def check_url(url):
        import urllib2

        try:
            Common.log("check url %s exist" % (url,))
            response = urllib2.urlopen(url)
            return response.read()
        except:
            pass
        return False

    @staticmethod
    def execute(cmd, info=None):
        if info:
            Common.log("%s : %s" % (info, cmd,))
        else:
            Common.log("%s" % (cmd,))
        return commands.getoutput(cmd)

    @staticmethod
    def exist(file_path):
        Common.log("check file %s exist" % (file_path,))
        return os.path.exists(file_path)


text:
from __future__ import division
import sys

def run(args):
  assert len(args) == 0
  print """
LIBTBX_DISABLE_TRACEBACKLIMIT
  If set, Sorry and Usage exceptions are shown with the full traceback.

LIBTBX_NO_LD_PRELOAD
  If set, LD_PRELOAD is never set in the command-line launchers.

LIBTBX_VALGRIND
  Run "libtbx.valgrind python" for more information.

LIBTBX_PRINT_TRACE
  If set, print trace of all Python code executed.
  This can lead to very large output.

LIBTBX_NATIVE_TAR
  Inspected by libtbx.bundle_as_selfx to find alternative tar command.
  Example: setenv LIBTBX_NATIVE_TAR $HOME/bin/tar

LIBTBX_FULL_TESTING
  If set, forces libtbx.env.full_testing = True.

LIBTBX_DEBUG_LOG
  If set, enables libtbx.introspection.method_debug_log.
  See method_debug_log documentation for details.

LIBTBX_WINGIDE_DEBUG
  If set, triggers "import wingdbstub" when libtbx.env is loaded.

LIBTBX_CPP0X=False|True
  If False, disables -std=c++0x (if the boost tree is under revision
  control -std=c++0x is enabled automatically for some compilers).
  If True, enables -std=c++0x for some compilers.
"""

if (__name__ == "__main__"):
  run(sys.argv[1:])


text:
<?php
namespace YUti\Lda\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Logger\ConsoleLogger;
use Symfony\Component\Console\Output\OutputInterface;
use YUti\Lda\CorpusReader;
use YUti\Lda\ModelWriter;
use YUti\Lda\ParticleLda;

class ParticleLdaCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('lda:particle')
            ->setDescription('');

        $this
            ->addArgument(
                'corpus',
                InputArgument::REQUIRED,
                'Set the corpus file name to train'
            )
            ->addArgument(
                'topics',
                InputArgument::REQUIRED,
                'Set the number of topics'
            )
        ;

        $this
            ->addOption(
                'particles',
                'p',
                InputOption::VALUE_REQUIRED,
                'Set the number of particles',
                100
            )
            ->addOption(
                'rejuvenation',
                'r',
                InputOption::VALUE_REQUIRED,
                'Set the number of documents used for rejuvenation',
                10
            )
            ->addOption(
                'ess-threshold',
                'e',
                InputOption::VALUE_REQUIRED,
                'Set the ess threshold',
                0.2
            )
            ->addOption(
                'alpha',
                'a',
                InputOption::VALUE_REQUIRED,
                'Set the hyper-parameter alpha (not estimated, symmetric only)',
                0.1
            )
            ->addOption(
                'beta',
                'b',
                InputOption::VALUE_REQUIRED,
                'Set the hyper-parameter beta (not estimated, symmetric only)',
                0.01
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $logger = new ConsoleLogger($output);

        $corpusFile = $input->getArgument('corpus');
        $topics = intval($input->getArgument('topics'));
        $particles = intval($input->getOption('particles'));
        $rejuvenation = intval($input->getOption('rejuvenation'));
        $essThreshold = intval($input->getOption('ess-threshold'));
        $alpha = doubleval($input->getOption('alpha'));
        $beta = doubleval($input->getOption('beta'));

        $corpus = (new CorpusReader())->read($corpusFile);

        $lda = new ParticleLda(
            $topics,
            $alpha,
            $beta,
            $particles,
            $rejuvenation,
            $essThreshold
        );
        $lda->setLogger($logger);

        $lda->train($corpus, $particles, $rejuvenation, $essThreshold);
    }
}


text:
@interface Matomo : NSObject <RCTBridgeModule>
@end


text:
import javax.jms.Queue;
import javax.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class AbstractAction {

	@Autowired
	EntityManager em;

	@Autowired
	Queue queue;

	abstract public boolean createAction(Object obj);
	abstract public boolean readAction(Object obj);
	abstract public boolean updateAction(Object obj);
	abstract public boolean deleteAction(Object obj);
	}


text:
#include <geekos/kthread.h>
#include <geekos/int.h>
#include <geekos/kassert.h>
#include <geekos/screen.h>
#include <geekos/synch.h>

/*
 * NOTES:
 * - The GeekOS mutex and condition variable APIs are based on those
 *   in pthreads.
 * - Unlike disabling interrupts, mutexes offer NO protection against
 *   concurrent execution of interrupt handlers.  Mutexes and
 *   condition variables should only be used from kernel threads,
 *   with interrupts enabled.
 */

/* ----------------------------------------------------------------------
 * Private functions
 * ---------------------------------------------------------------------- */

static struct Semaphore_List s_semaphoreList;

int Create_Semaphore(char* name, int ival)
{
	struct Semaphore* sema = (&s_semaphoreList)->head;
	static ulong_t sid = 1;

	//find sem by sname
	while (sema != 0)
	{
		if (strcmp(sema->name, name) == 0)
		{
			//Print("exist sema->name: %s, %d\n", sema->name, sema->sid);
			return sema->sid;
		}
		sema = Get_Next_In_Semaphore_List(sema);
	}

	//if there is no sem, create sem
	sema = (struct Semaphore*)Malloc(sizeof(struct Semaphore));
	sema->sid = sid++;
	memcpy(sema->name, name, 25);
	sema->count = ival;
	//sema->refCount = 1;
	Mutex_Init(&(sema->mutex));
	Cond_Init(&(sema->cond));
	Add_To_Back_Of_Semaphore_List(&s_semaphoreList, sema);
	//Print("new sema->name: %s, %d\n", sema->name, sema->sid);
	return sema->sid;

}

int Destroy_Semaphore(int sid)
{
	struct Semaphore* sema = (&s_semaphoreList)->head;

	//find sem by sid
	while (sema != 0)
	{
		if (sema->sid == sid)
		{
			Remove_From_Semaphore_List(&s_semaphoreList, sema);
			Free(sema);
			return 0;
		}
		sema = Get_Next_In_Semaphore_List(sema);
	}

	return -1;
}

int P(int sid)
{
	struct Semaphore* sema = (&s_semaphoreList)->head;
	struct Mutex* mutex;
	struct Condition* cond;

	//find sem by sid
	while (sema != 0)
	{
		if (sema->sid == sid)
		{
			mutex = &(sema->mutex); // important
			cond = &(sema->cond);

			Enable_Interrupts();
			Mutex_Lock(mutex);
			while(sema->count <= 0)
			{
				Cond_Wait(cond, mutex);
				//Print("WAKE UP!");
			}
			sema->count--;
			Mutex_Unlock(mutex);
			Disable_Interrupts();

			return 0;
		}
		sema = Get_Next_In_Semaphore_List(sema);
	}

	return -1;
}

int V(int sid)
{
	struct Semaphore* sema = (&s_semaphoreList)->head;
	struct Mutex* mutex;
	struct Condition* cond;

	//find sem by sid
	while (sema != 0)
	{
		if (sema->sid == sid)
		{
			mutex = &(sema->mutex);
			cond = &(sema->cond);

			Enable_Interrupts();
			Mutex_Lock(mutex);
			sema->count = sema->count + 1;
			//Print("wait queue : %d", cond->waitQueue);
			Cond_Broadcast(cond);
			Mutex_Unlock(mutex);
			Disable_Interrupts();

			return 0;
		}
		sema = Get_Next_In_Semaphore_List(sema);
	}

	return -1;
}

/*
 * The mutex is currently locked.
 * Atomically reenable preemption and wait in the
 * mutex's wait queue.
 */
static void Mutex_Wait(struct Mutex *mutex)
{
    KASSERT(mutex->state == MUTEX_LOCKED);
    KASSERT(g_preemptionDisabled);

    Disable_Interrupts();
    g_preemptionDisabled = false;
    Wait(&mutex->waitQueue);
    g_preemptionDisabled = true;
    Enable_Interrupts();
}

/*
 * Lock given mutex.
 * Preemption must be disabled.
 */
static __inline__ void Mutex_Lock_Imp(struct Mutex* mutex)
{
    KASSERT(g_preemptionDisabled);

    /* Make sure we're not already holding the mutex */
    KASSERT(!IS_HELD(mutex));

    /* Wait until the mutex is in an unlocked state */
    while (mutex->state == MUTEX_LOCKED) {
	Mutex_Wait(mutex);
    }

    /* Now it's ours! */
    mutex->state = MUTEX_LOCKED;
    mutex->owner = g_currentThread;
}

/*
 * Unlock given mutex.
 * Preemption must be disabled.
 */
static __inline__ void Mutex_Unlock_Imp(struct Mutex* mutex)
{
    KASSERT(g_preemptionDisabled);

    /* Make sure mutex was actually acquired by this thread. */
    KASSERT(IS_HELD(mutex));

    /* Unlock the mutex. */
    mutex->state = MUTEX_UNLOCKED;
    mutex->owner = 0;

    /*
     * If there are threads waiting to acquire the mutex,
     * wake one of them up.  Note that it is legal to inspect
     * the queue with interrupts enabled because preemption
     * is disabled, and therefore we know that no thread can
     * concurrently add itself to the queue.
     */
    if (!Is_Thread_Queue_Empty(&mutex->waitQueue)) {
	Disable_Interrupts();
	Wake_Up_One(&mutex->waitQueue);
	Enable_Interrupts();
    }
}

/* ----------------------------------------------------------------------
 * Public functions
 * ---------------------------------------------------------------------- */

/*
 * Initialize given mutex.
 */
void Mutex_Init(struct Mutex* mutex)
{
    mutex->state = MUTEX_UNLOCKED;
    mutex->owner = 0;
    Clear_Thread_Queue(&mutex->waitQueue);
}

/*
 * Lock given mutex.
 */
void Mutex_Lock(struct Mutex* mutex)
{
    KASSERT(Interrupts_Enabled());

    g_preemptionDisabled = true;
    Mutex_Lock_Imp(mutex);
    g_preemptionDisabled = false;
}

/*
 * Unlock given mutex.
 */
void Mutex_Unlock(struct Mutex* mutex)
{
    KASSERT(Interrupts_Enabled());

    g_preemptionDisabled = true;
    Mutex_Unlock_Imp(mutex);
    g_preemptionDisabled = false;
}

/*
 * Initialize given condition.
 */
void Cond_Init(struct Condition* cond)
{
    Clear_Thread_Queue(&cond->waitQueue);
}

/*
 * Wait on given condition (protected by given mutex).
 */
void Cond_Wait(struct Condition* cond, struct Mutex* mutex)
{
    KASSERT(Interrupts_Enabled());

    /* Ensure mutex is held. */
    KASSERT(IS_HELD(mutex));

    /* Turn off scheduling. */
    g_preemptionDisabled = true;

    /*
     * Release the mutex, but leave preemption disabled.
     * No other threads will be able to run before this thread
     * is able to wait.  Therefore, this thread will not
     * miss the eventual notification on the condition.
     */
    Mutex_Unlock_Imp(mutex);

    /*
     * Atomically reenable preemption and wait in the condition wait queue.
     * Other threads can run while this thread is waiting,
     * and eventually one of them will call Cond_Signal() or Cond_Broadcast()
     * to wake up this thread.
     * On wakeup, disable preemption again.
     */
    Disable_Interrupts();
    g_preemptionDisabled = false;
    Wait(&cond->waitQueue);
    g_preemptionDisabled = true;
    Enable_Interrupts();

    /* Reacquire the mutex. */
    Mutex_Lock_Imp(mutex);

    /* Turn scheduling back on. */
    g_preemptionDisabled = false;
}

/*
 * Wake up one thread waiting on the given condition.
 * The mutex guarding the condition should be held!
 */
void Cond_Signal(struct Condition* cond)
{
    KASSERT(Interrupts_Enabled());
    Disable_Interrupts();  /* prevent scheduling */
    Wake_Up_One(&cond->waitQueue);
    Enable_Interrupts();  /* resume scheduling */
}

/*
 * Wake up all threads waiting on the given condition.
 * The mutex guarding the condition should be held!
 */
void Cond_Broadcast(struct Condition* cond)
{
    KASSERT(Interrupts_Enabled());
    Disable_Interrupts();  /* prevent scheduling */
    Wake_Up(&cond->waitQueue);
    Enable_Interrupts();  /* resume scheduling */
}


text:
Deface::Override.new(:virtual_path => "spree/admin/shared/_content_header",
                     :name => "repeat_order_button",
                     :insert_top => "[data-hook='toolbar']",
                     :partial => "spree/admin/orders/repeat_button",
                     :disabled => false)