text:
from __future__ import absolute_import

from rest_framework import status
from rest_framework.response import Response

from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.api.serializers.rest_framework import RuleSerializer
from sentry.models import Rule

class ProjectRuleDetailsEndpoint(ProjectEndpoint):
    def get(self, request, project, rule_id):
        """
        Retrieve a rule

        Return details on an individual rule.

            {method} {path}

        """
        rule = Rule.objects.get(
            project=project,
            id=rule_id,
        )
        return Response(serialize(rule, request.user))

    def put(self, request, project, rule_id):
        """
        Update a rule

        Update various attributes for the given rule.

            {method} {path}
            {{
              "name": "My rule name",
              "conditions": [],
              "actions": [],
              "actionMatch": "all"
            }}

        """
        rule = Rule.objects.get(
            project=project,
            id=rule_id,
        )
        serializer = RuleSerializer({
            'actionMatch': rule.data.get('action_match', 'all'),
        }, context={'project': project}, data=request.DATA, partial=True)

        if serializer.is_valid():
            rule = serializer.save(rule=rule)

            return Response(serialize(rule, request.user))

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


text:
class _CommandData(object):
    def __init__(self, key, etag=None, metadata=None):
        self.key = key
        self.metadata = metadata
        self.etag = etag
        self.additionalData = None
        self.__command = True

    def to_json(self):
        raise NotImplementedError

    @property
    def command(self):
        return self.__command

class PutCommandData(_CommandData):
    def __init__(self, key, etag=None, document=None, metadata=None):
        super(PutCommandData, self).__init__(key, etag, metadata)
        self._method = "PUT"
        self.document = document

    def to_json(self):
        data = {"Method": self._method, "Key": self.key, "Document": self.document,
                "Metadata": self.metadata, "AdditionalData": self.additionalData}
        if self.etag is not None:
            data["Etag"] = self.etag

        return data

class DeleteCommandData(_CommandData):
    def __init__(self, key, etag=None):
        super(DeleteCommandData, self).__init__(key, etag)
        self._method = "DELETE"
        self.additionalData = None

    def to_json(self):
        return {"Key": self.key, "Etag": self.etag, "Method": self._method, "AdditionalData": self.additionalData}

class ScriptedPatchCommandData(_CommandData):
    def __init__(self, key, scripted_patch, etag=None, metadata=None, patch_if_missing=None, additional_data=None,
                 debug_mode=False):
        """
        @param key: key of a document to patch.
        :type str
        @param scripted_patch: (using JavaScript) that is used to patch the document.
        :type ScriptedPatchRequest
        @param etag: Current document etag, used for concurrency checks (null to skip check).
        :type str
        @param metadata: representing document's metadata.
        :type dict
        @param patch_if_missing: (using JavaScript) that is used to patch a default document.
        :type ScriptedPatchRequest
        @param additional_data: Additional command data. For internal use only.
        :type dict
        @param debug_mode: Indicates in the operation should be run in debug mode.
                           for additional information in response.
        :type bool

        """

        super(ScriptedPatchCommandData, self).__init__(key, etag)
        if additional_data is None:
            additional_data = {}
        if metadata is None:
            metadata = {}
        self._method = "EVAL"
        self.scripted_patch = scripted_patch
        self.metadata = metadata
        self.patch_if_missing = patch_if_missing
        self.additional_data = additional_data
        self.debug_Mode = debug_mode

    def to_json(self):
        data = {"Key": self.key, "Method": self._method, "Patch": self.scripted_patch.to_json(),
                "DebugMode": self.debug_Mode, "AdditionalData": self.additionalData, "Metadata": self.metadata}
        if self.etag is not None:
            data["Etag"] = self.etag
        if self.patch_if_missing is not None:
            data["PatchIfMissing"] = self.patch_if_missing.to_json()

        return data

redpajama_set_name: RedPajamaGithub


text:
function J = imp_freq_index(H, G, alpha, w, doPlot)
% IMP_FREQ_INDEX Implicit fractional transfer function approximation index calculation

    % Load configuration parameters
    config = fomcon('config');
    numPts = config.Core.Frequency_domain_computations.Num_points;

    % Check input argument number
    if nargin < 5, doPlot = false; end

    if nargin < 4
        error('IMPFREQINDEX:NotEnoughInputArguments', ...
              'Not enough input arguments.');
    end

    % Frequency range
    wb = w(1);
    wh = w(2);

    % Take N log-spaced points
    w = logspace(log10(wb), log10(wh), numPts);

    % Original response
    r_orig = squeeze(freqresp(G,w)).^alpha;

    % Approximation
    r = squeeze(freqresp(H,w));

    % Performance index
    J = sum(abs(r_orig - r).^2)/length(r);

    % Also plot BODE diagram if requested
    if doPlot
        bode(frd(r_orig, w),w);
        hold on;
        bode(frd(r, w),w);
        legend('Original response', 'Obtained approximation');
    end

end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Local Amenities Map</title>

    <link rel="stylesheet" href="/styles/css/bootstrap.min.css" type="text/css">

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="/styles/font-awesome/css/font-awesome.min.css" type="text/css">

    <link rel="stylesheet" href="/styles/css/animate.min.css" type="text/css">

    <link rel="stylesheet" href="/styles/css/creative.css" type="text/css">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Local Amenities Map

						 {{ url_text }}

					{%if url_text == "Logout"%}

							Search

					{% endif %}

                        About

                        Portfolio

                        Contact

Your favorite map which displays nearest local amenities

Local Amenities map provides information about the nearest local amenities! This will help you assess the locality in general!

                Find Out More

We've got what you need!

Local Amenities map displays some essential information required to get a good idea about the locality! All the information is free and easily accessible!

                    Get Started!

At Your Service

                                    General Practioner

                                    Displays general practioners closer to the postcode.

                                    Supermarket

                                    Displays supermarkets closer to the postcode.

                                    Train Station

                                    Displays train stations closer to the postcode.

                                    School

                                    Displays schools closer to the postcode.

                                    Selective display

                                    Allows selective display of each category.

									Additional detail

                                    Displays address and distance for every marker.

Let's Get In Touch!

 To report any issue or technical difficulty! Please give us a call or send us an email and we will get back to you as soon as possible!

123-456-6789

ss3n13@soton.ac.uk


text:
/*
 * TypeChangeListener.java
 * Creation date: May 10, 2004.
 * By: Edward Lam
 */
package org.openquark.gems.client;

import java.util.EventListener;

/**
 * A listener that listens for changes in the part types of the gem.
 * @author Edward Lam
 */
public interface TypeChangeListener extends EventListener {
    /**
     * Notify listeners that a part's type changed
     * @param e the related event.
     */
    public abstract void typeChanged(TypeChangeEvent e);

}


text:
class UserMailerPreview < ActionMailer::Preview
  def survey_completed
    sheet = Sheet.current.first
    UserMailer.survey_completed(sheet)
  end

  def sheet_unlock_request
    sheet_unlock_request = SheetUnlockRequest.current.first
    editor = User.first
    UserMailer.sheet_unlock_request(sheet_unlock_request, editor)
  end

  def sheet_unlocked
    sheet_unlock_request = SheetUnlockRequest.current.first
    project_editor = User.first
    UserMailer.sheet_unlocked(sheet_unlock_request, project_editor)
  end

  # Updated
  def daily_digest
    recipient = User.current.first
    UserMailer.daily_digest(recipient)
  end

  def subject_randomized
    randomization = Randomization.where.not(subject_id: nil).first
    user = User.current.first
    UserMailer.subject_randomized(randomization, user)
  end

  def adverse_event_reported
    adverse_event = AdverseEvent.current.first
    recipient = User.current.first
    UserMailer.adverse_event_reported(adverse_event, recipient)
  end

  def password_expires_soon
    recipient = User.current.first
    UserMailer.password_expires_soon(recipient)
  end
end


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Threading.Tasks

Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
    Partial Public Class FindReferencesTests
        <WorkItem(541167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541167")>
        <Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
        Public Async Function TestExtensionMethodToDelegateConversion() As Task
            Dim input =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document><![CDATA[
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        Func<int> x = "".[|$$Count|], y = "".[|Count|];
    }
}]]>
        </Document>
    </Project>
</Workspace>
            Await TestAsync(input)
        End Function

        <WorkItem(541697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541697")>
        <Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
        Public Async Function TestReducedExtensionMethod1() As Task
            Dim input =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document><![CDATA[
using System;
class Program
{
    static void Main(string[] args)
    {
        string s = "Hello";
        s.[|$$ExtensionMethod|]();
    }
}

public static class MyExtension
{
    public static int {|Definition:ExtensionMethod|}(this String s)
    {
        return s.Length;
    }
}
]]>
        </Document>
    </Project>
</Workspace>
            Await TestAsync(input)
        End Function

        <WorkItem(541697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541697")>
        <Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
        Public Async Function TestReducedExtensionMethod2() As Task
            Dim input =
<Workspace>
    <Project Language="C#" CommonReferences="true">
        <Document><![CDATA[
using System;
class Program
{
    static void Main(string[] args)
    {
        string s = "Hello";
        s.[|ExtensionMethod|]();
    }
}

public static class MyExtension
{
    public static int {|Definition:$$ExtensionMethod|}(this String s)
    {
        return s.Length;
    }
}
]]>
        </Document>
    </Project>
</Workspace>
            Await TestAsync(input)
        End Function

#Region "Normal Visual Basic Tests"

        <Fact, Trait(Traits.Feature, Traits.Features.FindReferences)>
        Public Async Function TestVisualBasicFindReferencesOnExtensionMethod() As Task
            Dim input =
<Workspace>
    <Project Language="Visual Basic" CommonReferences="true">
        <Document><![CDATA[
Imports System

Namespace System.Runtime.CompilerServices
    <AttributeUsage(AttributeTargets.Method Or AttributeTargets.Property Or AttributeTargets.Class Or AttributeTargets.Assembly)>
    Public Class ExtensionAttribute
        Inherits Attribute
    End Class
End Namespace

Class Program
    Private Shared Sub Main(args As String())
        Dim s As String = "Hello"
        s.[|ExtensionMethod|]()
    End Sub
End Class

Module MyExtension
    <System.Runtime.CompilerServices.Extension()> _
    Public Function {|Definition:$$ExtensionMethod|}(s As [String]) As Integer
        Return s.Length
    End Function
End Module]]>
        </Document>
    </Project>
</Workspace>

            Await TestAsync(input)
        End Function

#End Region
    End Class
End Namespace


text:
module Middle
  module Generators
    class InstallGenerator < ::Rails::Generators::Base
      source_root File.expand_path(File.join(File.dirname(__FILE__), 'templates'))

      desc "Creates an ability to your application"

      def copy_ability
        template 'ability.rb', 'app/abilities/ability.rb'
      end

    end
  end
end


text:
import numpy as np

from AnyQt.QtCore import QSize, Qt, QTimer
from AnyQt.QtGui import (
    QPen, QFont, QFontInfo, QPalette, QKeySequence,
)
from AnyQt.QtWidgets import QApplication, QAction

from sklearn.neighbors import NearestNeighbors
from sklearn.metrics import r2_score

import Orange
from Orange.data import Table, Domain, StringVariable, ContinuousVariable, \
    DiscreteVariable
from Orange.canvas import report
from Orange.data.sql.table import SqlTable, AUTO_DL_LIMIT
from Orange.preprocess.score import ReliefF, RReliefF
from Orange.widgets import gui
from Orange.widgets.settings import \
    DomainContextHandler, Setting, ContextSetting, SettingProvider
from Orange.widgets.utils.itemmodels import DomainModel
from Orange.widgets.visualize.owscatterplotgraph import OWScatterPlotGraph
from Orange.widgets.visualize.utils import VizRankDialogAttrPair
from Orange.widgets.widget import OWWidget, Default, AttributeList, Msg
from Orange.widgets.utils.annotated_data import (create_annotated_table,
                                                 ANNOTATED_DATA_SIGNAL_NAME)

def font_resize(font, factor, minsize=None, maxsize=None):
    font = QFont(font)
    fontinfo = QFontInfo(font)
    size = fontinfo.pointSizeF() * factor

    if minsize is not None:
        size = max(size, minsize)
    if maxsize is not None:
        size = min(size, maxsize)

    font.setPointSizeF(size)
    return font

class ScatterPlotVizRank(VizRankDialogAttrPair):
    captionTitle = "Score Plots"
    K = 10

    def check_preconditions(self):
        self.Information.add_message(
            "class_required", "Data with a class variable is required.")
        self.Information.class_required.clear()
        if not super().check_preconditions():
            return False
        if not self.master.data.domain.class_var:
            self.Information.class_required()
            return False
        return True

    def iterate_states(self, initial_state):
        # If we put initialization of `self.attrs` to `initialize`,
        # `score_heuristic` would be run on every call to `set_data`.
        if initial_state is None:  # on the first call, compute order
            self.attrs = self.score_heuristic()
        yield from super().iterate_states(initial_state)

    def compute_score(self, state):
        graph = self.master.graph
        ind12 = [graph.domain.index(self.attrs[x]) for x in state]
        valid = graph.get_valid_list(ind12)
        X = graph.jittered_data[ind12, :][:, valid].T
        Y = self.master.data.Y[valid]
        if X.shape[0] < self.K:
            return
        n_neighbors = min(self.K, len(X) - 1)
        knn = NearestNeighbors(n_neighbors=n_neighbors).fit(X)
        ind = knn.kneighbors(return_distance=False)
        if self.master.data.domain.has_discrete_class:
            return -np.sum(Y[ind] == Y.reshape(-1, 1)) / n_neighbors / len(Y)
        else:
            return -r2_score(Y, np.mean(Y[ind], axis=1)) * \
                   (len(Y) / len(self.master.data))

    def bar_length(self, score):
        return max(0, -score)

    def score_heuristic(self):
        X = self.master.graph.jittered_data.T
        Y = self.master.data.Y
        mdomain = self.master.data.domain
        dom = Domain([ContinuousVariable(str(i)) for i in range(X.shape[1])],
                     mdomain.class_vars)
        data = Table(dom, X, Y)
        relief = ReliefF if isinstance(dom.class_var, DiscreteVariable) \
            else RReliefF
        weights = relief(n_iterations=100, k_nearest=self.K)(data)
        attrs = sorted(zip(weights, mdomain.attributes),
                       key=lambda x: (-x[0], x[1].name))
        return [a for _, a in attrs]

class OWScatterPlot(OWWidget):
    """Scatterplot visualization with explorative analysis and intelligent
    data visualization enhancements."""

    name = 'Scatter Plot'
    description = "Interactive scatter plot visualization with " \
                  "intelligent data visualization enhancements."
    icon = "icons/ScatterPlot.svg"
    priority = 140

    inputs = [("Data", Table, "set_data", Default),
              ("Data Subset", Table, "set_subset_data"),
              ("Features", AttributeList, "set_shown_attributes")]

    outputs = [("Selected Data", Table, Default),
               (ANNOTATED_DATA_SIGNAL_NAME, Table),
               ("Features", Table)]

    settingsHandler = DomainContextHandler()

    auto_send_selection = Setting(True)
    auto_sample = Setting(True)
    toolbar_selection = Setting(0)

    attr_x = ContextSetting(None)
    attr_y = ContextSetting(None)

    graph = SettingProvider(OWScatterPlotGraph)

    jitter_sizes = [0, 0.1, 0.5, 1, 2, 3, 4, 5, 7, 10]

    graph_name = "graph.plot_widget.plotItem"

    class Information(OWWidget.Information):
        sampled_sql = Msg("Large SQL table; showing a sample.")

    def __init__(self):
        super().__init__()

        box = gui.vBox(self.mainArea, True, margin=0)
        self.graph = OWScatterPlotGraph(self, box, "ScatterPlot")
        box.layout().addWidget(self.graph.plot_widget)
        plot = self.graph.plot_widget

        axispen = QPen(self.palette().color(QPalette.Text))
        axis = plot.getAxis("bottom")
        axis.setPen(axispen)

        axis = plot.getAxis("left")
        axis.setPen(axispen)

        self.data = None  # Orange.data.Table
        self.subset_data = None  # Orange.data.Table
        self.data_metas_X = None  # self.data, where primitive metas are moved to X
        self.sql_data = None  # Orange.data.sql.table.SqlTable
        self.attribute_selection_list = None  # list of Orange.data.Variable
        self.__timer = QTimer(self, interval=1200)
        self.__timer.timeout.connect(self.add_data)

        common_options = dict(
            labelWidth=50, orientation=Qt.Horizontal, sendSelectedValue=True,
            valueType=str)
        box = gui.vBox(self.controlArea, "Axis Data")
        dmod = DomainModel
        self.xy_model = DomainModel(dmod.MIXED, valid_types=dmod.PRIMITIVE)
        gui.comboBox(
            box, self, "attr_x", label="Axis x:", callback=self.update_attr,
            model=self.xy_model, **common_options)
        self.cb_attr_y = gui.comboBox(
            box, self, "attr_y", label="Axis y:", callback=self.update_attr,
            model=self.xy_model, **common_options)

        vizrank_box = gui.hBox(box)
        gui.separator(vizrank_box, width=common_options["labelWidth"])
        self.vizrank, self.vizrank_button = ScatterPlotVizRank.add_vizrank(
            vizrank_box, self, "Find Informative Projections", self.set_attr)

        gui.separator(box)

        gui.valueSlider(
            box, self, value='graph.jitter_size', label='Jittering: ',
            values=self.jitter_sizes, callback=self.reset_graph_data,
            labelFormat=lambda x:
            "None" if x == 0 else ("%.1f %%" if x < 1 else "%d %%") % x)
        gui.checkBox(
            gui.indentedBox(box), self, 'graph.jitter_continuous',
            'Jitter continuous values', callback=self.reset_graph_data)

        self.sampling = gui.auto_commit(
            self.controlArea, self, "auto_sample", "Sample", box="Sampling",
            callback=self.switch_sampling, commit=lambda: self.add_data(1))
        self.sampling.setVisible(False)

        box = gui.vBox(self.controlArea, "Points")
        self.color_model = DomainModel(
            placeholder="(Same color)", valid_types=dmod.PRIMITIVE)
        self.cb_attr_color = gui.comboBox(
            box, self, "graph.attr_color", label="Color:",
            callback=self.update_colors,
            model=self.color_model, **common_options)
        self.label_model = DomainModel(
            placeholder="(No labels)")
        self.cb_attr_label = gui.comboBox(
            box, self, "graph.attr_label", label="Label:",
            callback=self.graph.update_labels,
            model=self.label_model, **common_options)
        self.shape_model = DomainModel(
            placeholder="(Same shape)", valid_types=DiscreteVariable)
        self.cb_attr_shape = gui.comboBox(
            box, self, "graph.attr_shape", label="Shape:",
            callback=self.graph.update_shapes,
            model=self.shape_model, **common_options)
        self.size_model = DomainModel(
            placeholder="(Same size)", valid_types=ContinuousVariable)
        self.cb_attr_size = gui.comboBox(
            box, self, "graph.attr_size", label="Size:",
            callback=self.graph.update_sizes,
            model=self.size_model, **common_options)
        self.models = [self.xy_model, self.color_model, self.label_model,
                       self.shape_model, self.size_model]

        g = self.graph.gui
        g.point_properties_box(self.controlArea, box)
        box = gui.vBox(self.controlArea, "Plot Properties")
        g.add_widgets([g.ShowLegend, g.ShowGridLines], box)
        gui.checkBox(
            box, self, value='graph.tooltip_shows_all',
            label='Show all data on mouse hover')
        self.cb_class_density = gui.checkBox(
            box, self, value='graph.class_density', label='Show class density',
            callback=self.update_density)
        gui.checkBox(
            box, self, 'graph.label_only_selected',
            'Label only selected points', callback=self.graph.update_labels)

        self.zoom_select_toolbar = g.zoom_select_toolbar(
            gui.vBox(self.controlArea, "Zoom/Select"), nomargin=True,
            buttons=[g.StateButtonsBegin, g.SimpleSelect, g.Pan, g.Zoom,
                     g.StateButtonsEnd, g.ZoomReset]
        )
        buttons = self.zoom_select_toolbar.buttons
        buttons[g.Zoom].clicked.connect(self.graph.zoom_button_clicked)
        buttons[g.Pan].clicked.connect(self.graph.pan_button_clicked)
        buttons[g.SimpleSelect].clicked.connect(self.graph.select_button_clicked)
        buttons[g.ZoomReset].clicked.connect(self.graph.reset_button_clicked)
        self.controlArea.layout().addStretch(100)
        self.icons = gui.attributeIconDict

        p = self.graph.plot_widget.palette()
        self.graph.set_palette(p)

        gui.auto_commit(self.controlArea, self, "auto_send_selection",
                        "Send Selection", "Send Automatically")

        def zoom(s):
            """Zoom in/out by factor `s`."""
            viewbox = plot.getViewBox()
            # scaleBy scales the view's bounds (the axis range)
            viewbox.scaleBy((1 / s, 1 / s))

        def fit_to_view():
            viewbox = plot.getViewBox()
            viewbox.autoRange()

        zoom_in = QAction(
            "Zoom in", self, triggered=lambda: zoom(1.25)
        )
        zoom_in.setShortcuts([QKeySequence(QKeySequence.ZoomIn),
                              QKeySequence(self.tr("Ctrl+="))])
        zoom_out = QAction(
            "Zoom out", self, shortcut=QKeySequence.ZoomOut,
            triggered=lambda: zoom(1 / 1.25)
        )
        zoom_fit = QAction(
            "Fit in view", self,
            shortcut=QKeySequence(Qt.ControlModifier | Qt.Key_0),
            triggered=fit_to_view
        )
        self.addActions([zoom_in, zoom_out, zoom_fit])

    # def settingsFromWidgetCallback(self, handler, context):
    #     context.selectionPolygons = []
    #     for curve in self.graph.selectionCurveList:
    #         xs = [curve.x(i) for i in range(curve.dataSize())]
    #         ys = [curve.y(i) for i in range(curve.dataSize())]
    #         context.selectionPolygons.append((xs, ys))

    # def settingsToWidgetCallback(self, handler, context):
    #     selections = getattr(context, "selectionPolygons", [])
    #     for (xs, ys) in selections:
    #         c = SelectionCurve("")
    #         c.setData(xs,ys)
    #         c.attach(self.graph)
    #         self.graph.selectionCurveList.append(c)

    def reset_graph_data(self, *_):
        self.graph.rescale_data()
        self.update_graph()

    def set_data(self, data):
        self.clear_messages()
        self.Information.sampled_sql.clear()
        self.__timer.stop()
        self.sampling.setVisible(False)
        self.sql_data = None
        if isinstance(data, SqlTable):
            if data.approx_len() < 4000:
                data = Table(data)
            else:
                self.Information.sampled_sql()
                self.sql_data = data
                data_sample = data.sample_time(0.8, no_cache=True)
                data_sample.download_data(2000, partial=True)
                data = Table(data_sample)
                self.sampling.setVisible(True)
                if self.auto_sample:
                    self.__timer.start()

        if data is not None and (len(data) == 0 or len(data.domain) == 0):
            data = None
        if self.data and data and self.data.checksum() == data.checksum():
            return

        self.closeContext()
        same_domain = (self.data and data and
                       data.domain.checksum() == self.data.domain.checksum())
        self.data = data
        self.data_metas_X = self.move_primitive_metas_to_X(data)

        if not same_domain:
            self.init_attr_values()
        self.vizrank.initialize()
        self.vizrank.attrs = self.data.domain.attributes if self.data is not None else []
        self.vizrank_button.setEnabled(
            self.data is not None and self.data.domain.class_var is not None
            and len(self.data.domain.attributes) > 1 and len(self.data) > 1)
        if self.data is not None and self.data.domain.class_var is None \
            and len(self.data.domain.attributes) > 1 and len(self.data) > 1:
            self.vizrank_button.setToolTip(
                "Data with a class variable is required.")
        else:
            self.vizrank_button.setToolTip("")
        self.openContext(self.data)

        def findvar(name, iterable):
            """Find a Orange.data.Variable in `iterable` by name"""
            for el in iterable:
                if isinstance(el, Orange.data.Variable) and el.name == name:
                    return el
            else:
                return None
        # handle restored settings from  < 3.3.9 when attr_* were stored
        # by name
        if isinstance(self.attr_x, str):
            self.attr_x = findvar(self.attr_x, self.xy_model)
        if isinstance(self.attr_y, str):
            self.attr_y = findvar(self.attr_y, self.xy_model)
        if isinstance(self.graph.attr_label, str):
            self.graph.attr_label = findvar(
                self.graph.attr_label, self.label_model)
        if isinstance(self.graph.attr_color, str):
            self.graph.attr_color = findvar(
                self.graph.attr_color, self.color_model)
        if isinstance(self.graph.attr_shape, str):
            self.graph.attr_shape = findvar(
                self.graph.attr_shape, self.shape_model)
        if isinstance(self.graph.attr_size, str):
            self.graph.attr_size = findvar(
                self.graph.attr_size, self.size_model)

    def add_data(self, time=0.4):
        if self.data and len(self.data) > 2000:
            return self.__timer.stop()
        data_sample = self.sql_data.sample_time(time, no_cache=True)
        if data_sample:
            data_sample.download_data(2000, partial=True)
            data = Table(data_sample)
            self.data = Table.concatenate((self.data, data), axis=0)
            self.data_metas_X = self.move_primitive_metas_to_X(self.data)
            self.handleNewSignals()

    def switch_sampling(self):
        self.__timer.stop()
        if self.auto_sample and self.sql_data:
            self.add_data()
            self.__timer.start()

    def move_primitive_metas_to_X(self, data):
        if data is not None:
            new_attrs = [a for a in data.domain.attributes + data.domain.metas
                         if a.is_primitive()]
            new_metas = [m for m in data.domain.metas if not m.is_primitive()]
            data = Table.from_table(Domain(new_attrs, data.domain.class_vars,
                                           new_metas), data)
        return data

    def set_subset_data(self, subset_data):
        self.warning()
        if isinstance(subset_data, SqlTable):
            if subset_data.approx_len() < AUTO_DL_LIMIT:
                subset_data = Table(subset_data)
            else:
                self.warning("Data subset does not support large Sql tables")
                subset_data = None
        self.subset_data = self.move_primitive_metas_to_X(subset_data)
        self.controls.graph.alpha_value.setEnabled(subset_data is None)

    # called when all signals are received, so the graph is updated only once
    def handleNewSignals(self):
        self.graph.new_data(self.data_metas_X, self.subset_data)
        if self.attribute_selection_list and \
                all(attr in self.graph.domain
                    for attr in self.attribute_selection_list):
            self.attr_x = self.attribute_selection_list[0]
            self.attr_y = self.attribute_selection_list[1]
        self.attribute_selection_list = None
        self.update_graph()
        self.cb_class_density.setEnabled(self.graph.can_draw_density())
        self.unconditional_commit()

    def set_shown_attributes(self, attributes):
        if attributes and len(attributes) >= 2:
            self.attribute_selection_list = attributes[:2]
        else:
            self.attribute_selection_list = None

    def get_shown_attributes(self):
        return self.attr_x, self.attr_y

    def init_attr_values(self):
        domain = self.data and self.data.domain
        for model in self.models:
            model.set_domain(domain)
        self.attr_x = self.xy_model[0] if self.xy_model else None
        self.attr_y = self.xy_model[1] if len(self.xy_model) >= 2 \
            else self.attr_x
        self.graph.attr_color = domain and self.data.domain.class_var or None
        self.graph.attr_shape = None
        self.graph.attr_size = None
        self.graph.attr_label = None

    def set_attr(self, attr_x, attr_y):
        self.attr_x, self.attr_y = attr_x, attr_y
        self.update_attr()

    def update_attr(self):
        self.update_graph()
        self.cb_class_density.setEnabled(self.graph.can_draw_density())
        self.send_features()

    def update_colors(self):
        self.graph.update_colors()
        self.cb_class_density.setEnabled(self.graph.can_draw_density())

    def update_density(self):
        self.update_graph(reset_view=False)

    def update_graph(self, reset_view=True, **_):
        self.graph.zoomStack = []
        if self.graph.data is None:
            return
        self.graph.update_data(self.attr_x, self.attr_y, reset_view)

    def selection_changed(self):
        self.send_data()

    def send_data(self):
        selected = None
        selection = None
        # TODO: Implement selection for sql data
        if isinstance(self.data, SqlTable):
            selected = self.data
        elif self.data is not None:
            selection = self.graph.get_selection()
            if len(selection) > 0:
                selected = self.data[selection]
        self.send("Selected Data", selected)
        self.send(ANNOTATED_DATA_SIGNAL_NAME,
                  create_annotated_table(self.data, selection))

    def send_features(self):
        features = None
        if self.attr_x or self.attr_y:
            dom = Domain([], metas=(StringVariable(name="feature"),))
            features = Table(dom, [[self.attr_x], [self.attr_y]])
            features.name = "Features"
        self.send("Features", features)

    def commit(self):
        self.send_data()
        self.send_features()

    def get_widget_name_extension(self):
        if self.data is not None:
            return "{} vs {}".format(self.attr_x.name, self.attr_y.name)

    def send_report(self):
        if self.data is None:
            return
        def name(var):
            return var and var.name
        caption = report.render_items_vert((
            ("Color", name(self.graph.attr_color)),
            ("Label", name(self.graph.attr_label)),
            ("Shape", name(self.graph.attr_shape)),
            ("Size", name(self.graph.attr_size)),
            ("Jittering", (self.attr_x.is_discrete or
                           self.attr_y.is_discrete or
                           self.graph.jitter_continuous) and
             self.graph.jitter_size)))
        self.report_plot()
        if caption:
            self.report_caption(caption)

    def onDeleteWidget(self):
        super().onDeleteWidget()
        self.graph.plot_widget.getViewBox().deleteLater()
        self.graph.plot_widget.clear()

def test_main(argv=None):
    import sys
    if argv is None:
        argv = sys.argv
    argv = list(argv)
    a = QApplication(argv)
    if len(argv) > 1:
        filename = argv[1]
    else:
        filename = "heart_disease"

    ow = OWScatterPlot()
    ow.show()
    ow.raise_()
    data = Orange.data.Table(filename)
    ow.set_data(data)
    ow.set_subset_data(data[:30])
    ow.handleNewSignals()

    rval = a.exec()

    ow.set_data(None)
    ow.set_subset_data(None)
    ow.handleNewSignals()
    ow.saveSettings()
    ow.onDeleteWidget()

    return rval

if __name__ == "__main__":
    test_main()


text:
package com.andrey7mel.stepbystep.view.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.andrey7mel.stepbystep.R;
import com.andrey7mel.stepbystep.other.BaseTest;
import com.andrey7mel.stepbystep.other.TestConst;
import com.andrey7mel.stepbystep.presenter.RepoInfoPresenter;
import com.andrey7mel.stepbystep.presenter.vo.Repository;
import com.andrey7mel.stepbystep.view.MainActivity;

import org.junit.Before;
import org.junit.Test;
import org.robolectric.Robolectric;

import javax.inject.Inject;

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

public class RepoInfoFragmentTest extends BaseTest {

    @Inject
    RepoInfoPresenter repoInfoPresenter;

    private RepoInfoFragment repoInfoFragment;
    private Repository repository;

    private MainActivity activity;

    private Bundle bundle;

    @Override
    @Before
    public void setUp() throws Exception {
        super.setUp();
        component.inject(this);
        repository = new Repository(TestConst.TEST_REPO, TestConst.TEST_OWNER);

        repoInfoFragment = RepoInfoFragment.newInstance(repository);
        activity = Robolectric.setupActivity(MainActivity.class);
        bundle = Bundle.EMPTY;

        repoInfoFragment.onCreate(null); // need for DI
    }

    @Test
    public void testOnCreate() {
        repoInfoFragment.onCreate(null);
        verify(repoInfoPresenter, times(2)).onCreate(repoInfoFragment, repository); //2 times setUp() + testOnCreate()
    }

    @Test
    public void testOnCreateView() {
        repoInfoFragment.onCreateView(LayoutInflater.from(activity), (ViewGroup) activity.findViewById(R.id.container), null);
        verify(repoInfoPresenter).onCreateView(null);
    }

    @Test
    public void testOnCreateViewWithBundle() {
        repoInfoFragment.onCreateView(LayoutInflater.from(activity), (ViewGroup) activity.findViewById(R.id.container), bundle);
        verify(repoInfoPresenter).onCreateView(bundle);
    }

    @Test
    public void testOnStop() {
        repoInfoFragment.onStop();
        verify(repoInfoPresenter).onStop();
    }

    @Test
    public void testOnSaveInstanceState() {
        repoInfoFragment.onSaveInstanceState(null);
        verify(repoInfoPresenter).onSaveInstanceState(null);
    }

    @Test
    public void testOnSaveInstanceStateWithBundle() {
        repoInfoFragment.onSaveInstanceState(bundle);
        verify(repoInfoPresenter).onSaveInstanceState(bundle);
    }
}


text:
//  This class represent the comment object of File

#import <Foundation/Foundation.h>
#import "SBTXMLDocument.h"
#import "SBTFilePersonEntry.h"

@interface SBTFileCommentEntry : NSObject

@property (strong, nonatomic) SBTXMLDocument *xmlDocument;
@property (strong, nonatomic) NSString *commentId;
@property (strong, nonatomic) NSString *comment;
@property (strong, nonatomic) SBTFilePersonEntry *personEntry;
@property (strong, nonatomic) SBTFilePersonEntry *modifier;

/* Fields dictionary for holding changed or created fields */
//@property (strong, nonatomic) NSMutableDictionary *fieldsDict;

#pragma mark - methods

- (id) init;
- (id) initWithXMLDocument:(SBTXMLDocument *) document;
+ (NSDictionary *) namespacesForCommentEntry;
- (NSString *) description;

@end


text:
<?php

use im\catalog\models\ProductType;
use im\eav\widgets\EAVEditor;
use yii\helpers\ArrayHelper;

/* @var $this yii\web\View */
/* @var $model im\catalog\models\Product */
/* @var $form yii\widgets\ActiveForm */

$attributes = $model->getEAttributes();
if (!$attributes) {
    $attributes = $model->getAvailableEAttributes();
}
?>

<?= $form->field($model, 'type_id')->dropDownList(
    ArrayHelper::map(ProductType::find()->asArray()->orderBy('name')->all(), 'id', 'name'),
    ['prompt' => '']
) ?>

<?= EAVEditor::widget(['attributes' => $attributes, 'form' => $form, 'model' => $model, 'options' => ['id' => 'eav-editor']]) ?>

<?php
$script = <<<JS
    var type = $('[name="Product[type_id]"]');
    var editor = $('#eav-editor').eavEditor();
    type.on('change', function() {
        $.ajax({
            url: '/api/v1/product-types/' + $(this).val() + '/attributes',
            dataType: 'json'
        })
        .done(function(data) {
            if (data) {
                var attributes = $.map(data, function(attr) {
                    return attr.id;
                });
                if (attributes.length > 0) {
                    editor.setAttributes(attributes);
                }
            }
        });
    });
JS;
$this->registerJs($script);
?>


text:
package org.compass.core.config;

import org.compass.core.mapping.CompassMapping;

/**
 * An interface allowing for custom components that wish to be aware of CompassMapping
 * to be injected with it.
 *
 * @author kimchy
 */
public interface CompassMappingAware {

    /**
     * Injects the component with the compass mappings.
     */
    void setCompassMapping(CompassMapping mapping);
}


text:
using System.Collections.Generic;

namespace BusinessLayer.DTO
{
    public class SongEditDTO : SongCreateDTO
    {
        public int Id { get; set; }

        public IEnumerable<int> RemovedAlbums { get; set; }
    }
}


text:
                    modules

trackr

Invoices

reportr


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace System.Windows.Controls
{
    public class ItemsPanelTemplate : FrameworkTemplate
    {
        //
    }
}


text:
''' Python DB API 2.0 driver compliance unit test suite.

    This software is Public Domain and may be used without restrictions.

 "Now we have booze and barflies entering the discussion, plus rumours of
  DBAs on drugs... and I won't tell you what flashes through my mind each
  time I read the subject line with 'Anal Compliance' in it.  All around
  this is turning out to be a thoroughly unwholesome unit test."

    -- Ian Bicking
'''

__rcs_id__  = '$Id: dbapi20.py, v 1.10 2003/10/09 03:14:14 zenzen Exp $'
__version__ = '$Revision: 1.10 $'[11:-2]
__author__ = 'Stuart Bishop <zen@shangri-la.dropbear.id.au>'

import unittest
import time
import sys

# $Log: dbapi20.py,v $
# Revision 1.10  2003/10/09 03:14:14  zenzen
# Add test for DB API 2.0 optional extension, where database exceptions
# are exposed as attributes on the Connection object.
#
# Revision 1.9  2003/08/13 01:16:36  zenzen
# Minor tweak from Stefan Fleiter
#
# Revision 1.8  2003/04/10 00:13:25  zenzen
# Changes, as per suggestions by M.-A. Lemburg
# - Add a table prefix, to ensure namespace collisions can always be avoided
#
# Revision 1.7  2003/02/26 23:33:37  zenzen
# Break out DDL into helper functions, as per request by David Rushby
#
# Revision 1.6  2003/02/21 03:04:33  zenzen
# Stuff from Henrik Ekelund:
#     added test_None
#     added test_nextset & hooks
#
# Revision 1.5  2003/02/17 22:08:43  zenzen
# Implement suggestions and code from Henrik Eklund - test that cursor.arraysize
# defaults to 1 & generic cursor.callproc test added
#
# Revision 1.4  2003/02/15 00:16:33  zenzen
# Changes, as per suggestions and bug reports by M.-A. Lemburg,
# Matthew T. Kromer, Federico Di Gregorio and Daniel Dittmar
# - Class renamed
# - Now a subclass of TestCase, to avoid requiring the driver stub
#   to use multiple inheritance
# - Reversed the polarity of buggy test in test_description
# - Test exception heirarchy correctly
# - self.populate is now self._populate(), so if a driver stub
#   overrides self.ddl1 this change propogates
# - VARCHAR columns now have a width, which will hopefully make the
#   DDL even more portible (this will be reversed if it causes more problems)
# - cursor.rowcount being checked after various execute and fetchXXX methods
# - Check for fetchall and fetchmany returning empty lists after results
#   are exhausted (already checking for empty lists if select retrieved
#   nothing
# - Fix bugs in test_setoutputsize_basic and test_setinputsizes
#

class DatabaseExcTest(unittest.TestCase):
    ''' Test a database self.driver for DB API 2.0 compatibility.
        This implementation tests Gadfly, but the TestCase
        is structured so that other self.drivers can subclass this
        test case to ensure compiliance with the DB-API. It is
        expected that this TestCase may be expanded in the future
        if ambiguities or edge conditions are discovered.

        The 'Optional Extensions' are not yet being tested.

        self.drivers should subclass this test, overriding setUp, tearDown,
        self.driver, connect_args and connect_kw_args. Class specification
        should be as follows:

        import dbapi20
        class mytest(dbapi20.DatabaseExcTest):
           [...]

        Don't 'import DatabaseExcTest from dbapi20', or you will
        confuse the unit tester - just 'import dbapi20'.
    '''

    # The self.driver module. This should be the module where the 'connect'
    # method is to be found
    driver = None
    connect_args = () # List of arguments to pass to connect
    connect_kw_args = {} # Keyword arguments for connect
    table_prefix = 'dbexctest_' # If you need to specify a prefix for tables

    ddl1 = '''CREATE TABLE %sweather (
                                    city varchar(80),
                                    temp_lo int, -- low temperature
                                    temp_hi int, -- high temperature
                                    prcp real, -- precipitation
                                    date date
                                    );''' % table_prefix

    ddl2 = '''CREATE TABLE %scities (
                                   name varchar(80),
                                   location point
                                   );''' % table_prefix

    xddl1 = 'drop table %sweather' % table_prefix
    xddl2 = 'drop table %scities' % table_prefix

    lowerfunc = 'lower' # Name of stored procedure to convert string->lowercase

    # Some drivers may need to override these helpers, for example adding
    # a 'commit' after the execute.
    def executeDDL1(self, cursor):
        cursor.execute(self.ddl1)

    def executeDDL2(self, cursor):
        cursor.execute(self.ddl2)

    def setUp(self):
        ''' self.drivers should override this method to perform required setup
            if any is necessary, such as creating the database.
        '''
        pass

    def tearDown(self):
        ''' self.drivers should override this method to perform required cleanup
            if any is necessary, such as deleting the test database.
            The default drops the tables that may be created.
        '''
        con = self._connect()
        try:
            cur = con.cursor()
            for ddl in (self.xddl1, self.xddl2):
                try:
                    cur.execute(ddl)
                    con.commit()
                except self.driver.Error:
                    # Assume table didn't exist. Other tests will check if
                    # execute is busted.
                    pass
        finally:
            con.close()

    def _connect(self):
        try:
            return self.driver.connect(
                *self.connect_args, **self.connect_kw_args
                )
        except AttributeError:
            self.fail("No connect method found in self.driver module")

    def test_create_database(self):
        con = self._connect()
        cur = con.cursor()
        q = "CREATE DATABASE testdb"
        self.assertRaises(self.driver.InternalError, cur.execute, q)

    def test_grant_privilege(self):
        con = self._connect()
        cur = con.cursor()
        q = "GRANT ALL ON %sweather to s000043" % self.table_prefix
        self.assertRaises(self.driver.ProgrammingError, cur.execute, q)

    def test_closed_connection(self):
        con = self._connect()
        cur = con.cursor()
        self.executeDDL1(cur)
        q = "SELECT * FROM  %sweather" % self.table_prefix
        con.close()
        self.assertRaises(self.driver.ProgrammingError, cur.execute, q)

    def test_commit_on_closed_connection(self):
        con = self._connect()
        cur = con.cursor()
        self.executeDDL1(cur)
        q = "SELECT * FROM  %sweather" % self.table_prefix
        con.close()
        self.assertRaises(self.driver.ProgrammingError, con.commit)

    def test_close_on_closed_connection(self):
        con = self._connect()
        con.close()
        self.assertRaises(self.driver.ProgrammingError, con.close)

    def test_syntax_error1(self):
        con = self._connect()
        cur = con.cursor()
        self.executeDDL1(cur)
        q="INSERT INTO %sweather VALUE ('San Francisco', 46, 50, 0.25, '1994-11-27');"%\
                                                           self.table_prefix
        self.assertRaises(self.driver.ProgrammingError, cur.execute, q)

    def test_fetchone_before_select_query(self):
        con = self._connect()
        cur = con.cursor()
        self.assertRaises(self.driver.ProgrammingError, cur.fetchone)

    def test_fetchmany_before_select_query(self):
        con = self._connect()
        cur = con.cursor()
        self.assertRaises(self.driver.ProgrammingError, cur.fetchmany, 10)

    def test_fetchall_before_select_query(self):
        con = self._connect()
        cur = con.cursor()
        self.assertRaises(self.driver.ProgrammingError, cur.fetchall)

    def test_fetchone_after_non_result_fetching_query(self):
        con = self._connect()
        cur = con.cursor()
        self.executeDDL1(cur)
        q="INSERT INTO %sweather VALUES ('San Francisco', 46, 50, 0.25, '1994-11-27');"%\
                                                                  self.table_prefix
        cur.execute(q)
        self.assertRaises(self.driver.ProgrammingError, cur.fetchone)

    def test_fetchmany_after_non_result_fetching_query(self):
        con = self._connect()
        cur = con.cursor()
        self.executeDDL1(cur)
        q="INSERT INTO %sweather VALUES ('San Francisco', 46, 50, 0.25, '1994-11-27');"%\
                                                                 self.table_prefix
        cur.execute(q)
        self.assertRaises(self.driver.ProgrammingError, cur.fetchmany, 10)

    def test_fetchall_after_non_result_fetching_query(self):
        con = self._connect()
        cur = con.cursor()
        self.executeDDL1(cur)
        q="INSERT INTO %sweather VALUES ('San Francisco', 46, 50, 0.25, '1994-11-27');"%\
                                                                     self.table_prefix
        cur.execute(q)
        self.assertRaises(self.driver.ProgrammingError, cur.fetchall)

    def test_fetch_gt_100_rows_1(self):
        con = self._connect()
        cur = con.cursor()
        self.executeDDL1(cur)
        q = "SELECT oid, typname, typelem FROM pg_type WHERE typtype = \'b\' ORDER BY oid"
        cur.execute(q)
        for i in range(100): cur.fetchone()
        self.assertRaises(self.driver.Warning, cur.fetchone)

    def test_fetch_gt_100_rows_2(self):
        con = self._connect()
        cur = con.cursor()
        self.executeDDL1(cur)
        q = "SELECT oid, typname, typelem FROM pg_type WHERE typtype = \'b\' ORDER BY oid"
        cur.execute(q)
        self.assertRaises(self.driver.Warning, cur.fetchmany, 111)

    def test_fetch_gt_100_rows_3(self):
        con = self._connect()
        cur = con.cursor()
        self.executeDDL1(cur)
        q = "SELECT oid, typname, typelem FROM pg_type WHERE typtype = \'b\' ORDER BY oid"
        cur.execute(q)
        self.assertRaises(self.driver.Warning, cur.fetchall)

    def test_drop_non_existent_table(self):
        con = self._connect()
        cur = con.cursor()
        q1="DROP TABLE IF EXISTS xyz;"
        q2="DROP TABLE xyz;"
        self.assertRaises(self.driver.ProgrammingError, cur.execute, q2)

    def test_create_existing_table(self):
        con = self._connect()
        cur = con.cursor()
        self.executeDDL1(cur)
        q="CREATE TABLE %sweather (city varchar(80);"%self.table_prefix
        self.assertRaises(self.driver.ProgrammingError, cur.execute, q)

    def test_copy_table_to_file(self):
        con = self._connect()
        cur = con.cursor()
        self.executeDDL1(cur)
        q="COPY %sweather TO 'xxx';"%self.table_prefix
        self.assertRaises(self.driver.ProgrammingError, cur.execute, q)

    def test_copy_table_from_file(self):
        con = self._connect()
        cur = con.cursor()
        self.executeDDL1(cur)
        q="COPY %sweather FROM 'xxx';"%self.table_prefix
        self.assertRaises(self.driver.ProgrammingError, cur.execute, q)


text:
package net.meisen.dissertation.model.persistence;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import net.meisen.dissertation.config.TestConfig;
import net.meisen.dissertation.config.xslt.DefaultValues;
import net.meisen.dissertation.exceptions.PersistorException;
import net.meisen.dissertation.help.ExceptionBasedTest;
import net.meisen.dissertation.model.persistence.mock.MockFactory;
import net.meisen.dissertation.model.persistence.mock.MockPersistable;
import net.meisen.dissertation.model.persistence.mock.MockPersistor;
import net.meisen.general.genmisc.exceptions.registry.IExceptionRegistry;
import net.meisen.general.sbconfigurator.api.IConfiguration;
import net.meisen.general.sbconfigurator.runners.JUnitConfigurationRunner;
import net.meisen.general.sbconfigurator.runners.annotations.ContextClass;
import net.meisen.general.sbconfigurator.runners.annotations.ContextFile;
import net.meisen.general.sbconfigurator.runners.annotations.SystemProperty;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * Tests the implementation of a {@code BasePersistor}.
 *
 * @author pmeisen
 *
 * @see BasePersistor
 *
 */
@RunWith(JUnitConfigurationRunner.class)
@ContextClass(TestConfig.class)
@ContextFile("test-sbconfigurator-core.xml")
@SystemProperty(property = "testBeans.selector", value = "?")
public class TestBasePersistor extends ExceptionBasedTest {

	@Autowired()
	@Qualifier("coreConfiguration")
	private IConfiguration configuration;

	@Autowired()
	@Qualifier(DefaultValues.EXCEPTIONREGISTRY_ID)
	private IExceptionRegistry exceptionRegistry;

	private BasePersistor persistor;

	/**
	 * Initializes a spy of a {@code BasePersistor}, which is based on the
	 * {@link MockPersistor}.
	 */
	@Before
	public void init() {
		persistor = spy(new MockPersistor(exceptionRegistry));
	}

	/**
	 * Tests the implicit call of
	 * {@link IPersistable#isRegistered(BasePersistor, Group)} which has to be
	 * triggered by the {@code BasePersistor} whenever an instance is
	 * registered, i.e. {@link BasePersistor#register(Group, IPersistable)} is
	 * called.
	 */
	@Test
	public void testIsRegisteredCall() {
		final Group group = new Group("my", "group");
		final IPersistable persistable = spy(configuration
				.createInstance(MockPersistable.class));

		// execute the method
		persistor.register(group, persistable);

		// make sure the methods are called correctly
		verify(persistor, times(1)).register(group, persistable);
		verify(persistable, times(1)).isRegistered(persistor, group);
	}

	/**
	 * Tests the registration of a {@code Persistable}.
	 */
	@Test
	public void testRegistration() {
		final Group group = new Group("MyGroup");
		final IPersistable persistable = new MockPersistable();

		// register the same persistable several times, that should work
		persistor.register(group, persistable);
		persistor.register(group, persistable);
		persistor.register(group, persistable);
		persistor.register(group, persistable);
	}

	/**
	 * Tests the implementation of {@link BasePersistor#getPersistable(Group)}.
	 */
	@Test
	public void testGetPersistable() {
		final Group group = new Group();
		final IPersistable persistable = new MockPersistable();

		// execute the method
		persistor.register(group, persistable);
		assertEquals(persistable, persistor.getPersistable(group));
		assertNull(persistor.getPersistable(null));
	}

	/**
	 * Tests the exception to be thrown when {@code null} is used as group for
	 * registration.
	 */
	@Test
	public void testExceptionWhenGroupNullRegistration() {
		thrown.expect(PersistorException.class);
		thrown.expectMessage("You have to specify a group when registering.");

		final IPersistable persistable = new MockPersistable();

		// execute the method
		persistor.register(null, persistable);
	}

	/**
	 * Tests the exception to be thrown when {@code null} persistable is
	 * registered.
	 */
	@Test
	public void testExceptionWhenPersistableNullRegistration() {
		thrown.expect(PersistorException.class);
		thrown.expectMessage("Please specify which persistable to be registered.");

		// execute the method
		persistor.register(new Group("MyGroup"), null);
	}

	/**
	 * Tests when different persistables are registered for the same group.
	 */
	@Test
	public void testExceptionWhenDoubleRegistration() {
		thrown.expect(PersistorException.class);
		thrown.expectMessage("Cannot register several persistables for the group 'MyGroup'.");

		final Group group = new Group("MyGroup");

		// execute the method
		persistor.register(group, new MockPersistable());
		persistor.register(group, new MockPersistable());
	}

	/**
	 * Tests the implementation of reading and writing values.
	 *
	 * @throws IOException
	 *             if the file cannot be created or accessed
	 * @throws ClassNotFoundException
	 *             if a object cannot be resolved
	 */
	@Test
	public void testReadWriteStuff() throws IOException, ClassNotFoundException {
		final File tmpFile = File.createTempFile(UUID.randomUUID().toString(),
				".test");

		final FileOutputStream fos = new FileOutputStream(tmpFile);

		// write some values
		persistor.writeByte(fos, (byte) 2);
		persistor.writeInt(fos, 2000);
		persistor.writeLong(fos, Long.MAX_VALUE);
		persistor.writeString(fos, "This is a äüöß String");
		persistor.writeObject(fos, "Hi there äüöß");
		persistor.writeObject(fos, null);
		persistor.writeObject(fos, "I'm another");
		persistor.writeInt(fos, Integer.MIN_VALUE);

		fos.flush();
		fos.close();

		final FileInputStream fis = new FileInputStream(tmpFile);
		assertEquals((byte) 2, persistor.readByte(fis));
		assertEquals(2000, persistor.readInt(fis));
		assertEquals(Long.MAX_VALUE, persistor.readLong(fis));
		assertEquals("This is a äüöß String", persistor.readString(fis));
		assertEquals("Hi there äüöß", persistor.readObject(fis));
		assertNull(persistor.readObject(fis));
		assertEquals("I'm another", persistor.readObject(fis));
		assertEquals(Integer.MIN_VALUE, persistor.readInt(fis));

		fis.close();

		assertTrue(tmpFile.delete());
	}

	/**
	 * Tests the calling of a factory.
	 */
	@Test
	public void testFactoryUsage() {

		// register a factory
		final Group factoryGroup = new Group("myGroup");
		final IPersistableFactory factory = spy(new MockFactory());
		persistor.register(factoryGroup, factory);

		// register a simple persistable
		final Group group = factoryGroup.append("1").append("value");
		final IPersistable persistable = spy(new MockPersistable());
		persistor.register(group, persistable);

		// read the data using the persistor
		final Identifier id = new Identifier("identifier.data", group);
		final InputStream is = new ByteArrayInputStream(
				"This is the data".getBytes());
		persistor.read(id, is);
		persistor.read(id, is);

		// verify the different calls
		verify(factory, times(2)).createInstance(persistor, id);
		verify(persistable, times(2)).load(persistor, id, is);
	}
}


text:
class AddMessageToActivityLog < ActiveRecord::Migration
  def change
    add_column :activity_logs, :message, :string
  end
end


text:
* Fix known issues before parsing response (see [LOG4J2-2537](https://issues.apache.org/jira/browse/LOG4J2-2537))
* Tested up to Apache Tika 1.28.2 and 2.4.0

## v1.2.3

* Removed debug statement when the JSON parse fails
* Added new known issues to README.md
* Tests runs now on GitHub Actions

## v1.2.1

* Fix known issues before parsing response (see [LOG4J2-2537](https://issues.apache.org/jira/browse/LOG4J2-2537))
* Tested up to Apache Tika 1.28 and 2.2.0

## v1.2.0

* Added specific methods to set OCR languages on web client (thanks to @aleksanm)
* Fixed CLI client encoding on Windows (see [TIKA-3515](https://issues.apache.org/jira/browse/TIKA-3515))
* Tested up to Apache Tika 2.1.0

## v1.1.1

* Tested up to Apache Tika 1.27

## v1.1.0

* Drop PHP 7.2 support
* Preliminary support for Apache Tika 2.0.0
* Tested up to Apache Tika 1.26

## v1.0.1

* `CLIClient::setEnvVars()` to allow users to set its own environment variables (thanks to @gregoriopellegrino)
* Tested up to Apache Tika 1.25

## v1.0.0

### Added
* Type declarations and return types

### Removed
* Support for PHP 5
* Support for Apache Tika 1.14 and lower

### Changed
* `$client->getRecursiveMetadata()` returns an array as expected
* `Client::getSupportedVersions()` and `Client::isVersionSupported()` methods cannot be called statically
* `Client::getAvailableDetectors()` and `Client::getAvailableParsers()` returns an array with new format

## v0.9.3

### Added
* Recursive metadata in command line mode

## v0.9.2

### Changed
* Tested up to Apache Tika 1.24.1

## v0.9.1

### Changed
* Tested up to Apache Tika 1.24

## v0.9.0

### Added
* `Client::setEncoding()` to avoid encoding problems using app mode
* _Troubleshooting_ section to the README.md

## v0.8.0

### Added
* Option to disable append on `Client::setCallback()` to save memory

## v0.7.2

### Changed
 * Tested up to Apache Tika 1.23
 * Spawn scripts 'autodetects' if module java.se.ee is required

## v0.7.1

### Changed
* Tested up to version 1.21

## v0.7.0

### Added
* Recursive metadata support (thanks to @svaningelgem)
* Encoding to `DocumentMetadata` (thanks to @svaningelgem)

### Changed
* Improve web client extensibility
* Abstracted cache layer
* Tested up to version 1.21

### Fixed
* Compatibility with Windows on command line mode (thanks to @GAMESTER90)

## v0.6.0

### Added
* `Client::prepare()` to avoid checks, saving HTTP calls and filesystem accesses
* Support to set host and port using an URL (thanks to @mpdude)

### Changed
* Reduced memory usage (thanks to @JBleijenberg)
* Tested up to Apache Tika 1.20

## v0.5.1

### Changed
* Tested up to Apache Tika 1.19.1
* Tested up to PHP 7.3

## v0.5.0

### Added
* `Client::isVersionSupported()` method
* `Client::getSupportedMIMETypes()` method
* `Client::getAvailableDetectors()` method
* `Client::getAvailableParsers()` method
* `Client::getOption()` and `Client::getOptions()` methods to web client
* `Client::getTimeout()` and `Client::getTimeout()` methods to web client

### Changed
* Enhanced spawn.sh script


text:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Facebook, NativeStorage } from 'ionic-native';
import { LoginPage } from '../login/login';
import { AboutPage } from '../about/about';
import {ContactPage} from "../contact/contact";

@Component({
  selector: 'page-user',
  templateUrl: 'user.html'
})

export class UserPage {

  user: any;
  userReady: boolean = false;

  constructor(public navCtrl: NavController) {

    this.navCtrl.push(AboutPage);
  }

  ionViewCanEnter(){
    let env = this;
    NativeStorage.getItem('user')
    .then(function (data){
      env.user = {
        name: data.name,
        gender: data.gender,
        picture: data.picture
      };
        env.userReady = true;
        // var contact = new ContactPage();
        AboutPage.changePic(data.picture);
    }, function(error){
      console.log(error);
    });
  }

  doFbLogout(){
    var nav = this.navCtrl;
    Facebook.logout()
    .then(function(response) {
      //user logged out so we will remove him from the NativeStorage
      NativeStorage.remove('user');
      nav.push(LoginPage);
    }, function(error){
      console.log(error);
    });
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.mockito.internal.invocation Class Hierarchy (Mockito 1.9.5 API)
</TITLE>

<META NAME="date" CONTENT="2012-10-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package org.mockito.internal.invocation

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

org.mockito.internal.invocation.ArgumentsComparator
org.mockito.internal.invocation.ArgumentsProcessor
org.mockito.internal.invocation.InvocationImpl (implements org.mockito.invocation.Invocation, org.mockito.internal.exceptions.VerificationAwareInvocation)

org.mockito.internal.invocation.InvocationMarker
org.mockito.internal.invocation.InvocationMatcher (implements org.mockito.internal.invocation.CapturesArgumensFromInvocation, org.mockito.invocation.DescribedInvocation, java.io.Serializable)

org.mockito.internal.invocation.InvocationsFinder
org.mockito.internal.invocation.MatchersBinder (implements java.io.Serializable)

org.mockito.internal.invocation.SerializableMethod (implements org.mockito.internal.invocation.MockitoMethod, java.io.Serializable)

org.mockito.internal.invocation.StubInfoImpl (implements java.io.Serializable, org.mockito.invocation.StubInfo)

org.mockito.internal.invocation.UnusedStubsFinder

Interface Hierarchy

org.mockito.internal.invocation.CapturesArgumensFromInvocation
org.mockito.internal.invocation.MockitoMethod

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'asm-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.scss']
})
export class ContentComponent implements OnInit {
  content: any = {};

  constructor(
    private route: ActivatedRoute) { }

  ngOnInit(): void {
    this.getContent();
  }

  getContent(): void {
    this.route.data.subscribe((data: { content: any }) => {
      this.content = data.content || {};
    });
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

namespace HealthMonitoring.AcceptanceTests.Helpers.Selenium
{
    public static class WebDriverExtensions
    {
        public static void LoadUrl(this IWebDriver driver, string url)
        {
            driver.Navigate().GoToUrl(url);
        }

        public static string ImplicitWaitPageTitle(this IWebDriver driver)
        {
            return driver.ImplicitWait(
                Timeouts.Default,
                _ => driver.Title,
                t => !string.IsNullOrEmpty(t),
                "Page does not contain title!");
        }

        public static IWebElement ImplicitWaitElementIsRendered(this IWebDriver driver, By selector)
        {
            return driver.ImplicitWait(
                TimeSpan.FromSeconds(60),
                _ => driver.FindElement(selector),
                element => element != null && element.Displayed,
                $"Element with selector:{selector} could not be rendered");
        }

        public static string ImplicitWaitTextIsRendered(this IWebDriver driver, By elementSelector)
        {
            return driver.ImplicitWait(
                Timeouts.Default,
                _ => driver.FindElement(elementSelector)?.Text,
                text => !string.IsNullOrEmpty(text),
                $"Element with selector:{elementSelector} could not be rendered");
        }

        public static IEnumerable<IWebElement> ImplicitWaitElementsAreRendered(this IWebDriver driver, By selector, Func<IWebElement, bool> condition = null)
        {
            condition = condition ?? (el => true);

            return driver.ImplicitWait(
                Timeouts.Default,
                _ => driver.FindElements(selector)?.Where(condition),
                elements => elements != null && elements.Any(),
                $"Elements with selector:{selector} could not be rendered");
        }

        public static string ImplicitWaitUntilPageIsChanged(this IWebDriver driver, string expectedUrl)
        {
            return driver.ImplicitWait(
                Timeouts.Default,
                _ => driver.Url,
                url => string.Equals(url, expectedUrl, StringComparison.CurrentCultureIgnoreCase),
                $"Page with url {expectedUrl} did not loaded!");
        }

        public static IWebElement ExplicitWaitElementIsRendered(this IWebDriver driver, Func<IWebDriver, IWebElement> selector)
        {
            return driver.ExplicitWait(
                TimeSpan.FromSeconds(60),
                selector,
                $"Element with selector:{selector} could not be rendered");
        }

        public static string ExplicitWaitTextIsRendered(this IWebDriver driver, Func<IWebDriver, IWebElement> selector)
        {
            return driver.ExplicitWait(
                Timeouts.Default,
                selector,
                $"Element with selector:{selector} could not be rendered").Text;
        }

        public static IEnumerable<IWebElement> ExplicitWaitElementsAreRendered(this IWebDriver driver,
            Func<IWebDriver, IEnumerable<IWebElement>> selector)
        {
             return driver.ExplicitWait(
                 Timeouts.Default,
                 selector,
                 $"Elements with selector:{selector} could not be rendered");
        }

        public static bool ExplicitWaitUntilPageIsChanged(this IWebDriver driver, Func<IWebDriver, bool> selector, string expectedUrl)
        {
            return driver.ExplicitWait(
                Timeouts.Default,
                selector,
                $"Page with url {expectedUrl} did not loaded!");
        }

        public static T ImplicitWait<T, TWebDriver>(this TWebDriver webDriver,
            TimeSpan implicitWait,
            Func<TWebDriver, T> selector,
            Func<T, bool> predicate,
            string errorMessage)
            where TWebDriver : IWebDriver
        {
            T valueFound = default(T);

            try
            {
                webDriver.Manage().Timeouts().ImplicitWait = implicitWait;

                valueFound = selector(webDriver);

                if (predicate(valueFound))
                    return valueFound;

                throw new NoSuchElementException($"{valueFound} not found");
            }
            catch (NoSuchElementException e)
            {
                throw new TimeoutException($"Error message : {errorMessage} ; " +
                                           $"Value sought : [{valueFound}] ; " +
                                           $"NoSuchElementException Message : [{e.Message}]");
            }
        }

        public static T ExplicitWait<T, TWebDriver>(this TWebDriver webDriver,
            TimeSpan explicitWait,
            Func<IWebDriver, T> selector,
            string errorMessage)
            where TWebDriver : IWebDriver
        {
            T valueFound = default(T);

            try
            {
                valueFound = new WebDriverWait(webDriver, explicitWait).Until(selector);

                return valueFound;
            }
            catch (NoSuchElementException e)
            {
                throw new TimeoutException($"Error message : {errorMessage} ; " +
                                           $"Value sought : [{valueFound}] ; " +
                                           $"NoSuchElementException Message : [{e.Message}]");
            }
        }

    }
}


text:
package ca.intelliware.ihtsdo.mlds.security.ihtsdo;

public interface HeaderConstants {
	String COOKIE = "Cookie";
	String SET_COOKIE = "Set-Cookie";
}


text:
var path = require('path');
var webpack = require('webpack');
var CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  entry: [
    './src/Seripap',
  ],
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'seripap.js',
    publicPath: '/',
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: `"production"`,
      },
      __DEV__: false,
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
      },
    }),
    new CopyWebpackPlugin([
      { from: path.resolve(__dirname, 'index.html') },
      { from: path.resolve(__dirname, 'src/public') },
      { from: path.resolve(__dirname, 'favicon.ico') },
      { from: path.resolve(__dirname, 'favicon-16x16.png') },
      { from: path.resolve(__dirname, 'favicon-32x32.png') },
    ]),
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: [path.resolve(__dirname, 'node_modules')],
      loaders: ['babel', 'strip-loader?strip[]=debug,strip[]=console.log'],
      include: path.resolve(__dirname, 'src'),
    },
    {
      test: /\.css$/,
      loader: 'style!css',
    },
    { test: /\.(png|jpg|jpeg|gif)$/,
      loader: 'url?limit=8192',
    },
    {
      test: /\.scss$/,
      loaders: ['style', 'css', 'sass'],
    },
    ],
  },
};


text:
<!--
   Suggested Usage:
      ant clean build

   The goal of this build is compile the SWC library and generate ASDoc documentation.
-->
<project name="SWFService AS3 SWC Library" basedir="." default="build">

	<!-- Properties -->

	<property environment="env" />

	<property file="${basedir}/build.properties" />

	<property name="src.loc" location="${basedir}/SWFService/src" />
	<property name="lib.loc" location="${basedir}/SWFService/lib" />

	<property name="dist.loc" location="${basedir}/dist" />
	<property name="bin.loc" location="${dist.loc}/bin" />
	<property name="doc.loc" location="${dist.loc}/doc" />

	<!-- SDK Tool Configuration -->

	<property name="FLEX_HOME" location="${env.FLEX_HOME}" />
	<taskdef resource="flexTasks.tasks" classpath="${FLEX_HOME}/ant/lib/flexTasks.jar" />

	<!-- Targets -->

	<target name="clean" description="Remove artifacts in build directory from previous builds.">
		<delete dir="${dist.loc}" />
	</target>

	<target name="init" description="Initialize build directory.">
		<echo message="Building ${ant.project.name} version: ${build.version}"/>

		<mkdir dir="${dist.loc}" />
		<mkdir dir="${bin.loc}" />
		<mkdir dir="${doc.loc}" />
	</target>

	<target name="compile" depends="init" description="Compile SWC library.">
		<echo message="FLEX_HOME is set to: ${env.FLEX_HOME}"/>

		<!-- Compile SWC -->
		<compc output="${bin.loc}/${build.fileName}.swc">
			<source-path path-element="${src.loc}" />
			<include-sources dir="${src.loc}" includes="**/*.as" />
			<library-path dir="${lib.loc}" append="true">
				<include name="*.swc" />
			</library-path>

			<!-- Configure the flex framework libraries as external link dependencies -->
			<external-library-path dir="${FLEX_HOME}/frameworks" append="true">
				<include name="libs" />
				<include name="locale/{locale}" />
				<include name="libs/air" />
				<include name="libs/automation" />
				<include name="libs/mobile" />
				<include name="libs/mx" />
				<include name="libs/player" />
			</external-library-path>

			<!-- Sets java.awt.headless=true so font compilation works in headless environments -->
			<headless-server>true</headless-server>
		</compc>
	</target>

	<target name="asdoc" depends="compile" description="Generate ASDoc documentation">
		<asdoc
			output="${doc.loc}"
			main-title="${ant.project.name} API Documentation"
			window-title="${ant.project.name} API Documentation"
			failonerror="true">

			<source-path path-element="${src.loc}" />
			<doc-sources path-element="${src.loc}" />
			<library-path dir="${lib.loc}" append="true">
				<include name="*.swc" />
			</library-path>
		</asdoc>
	</target>

	<target name="build" depends="asdoc" description="Build the library and ASDoc documentation." />

</project>