text:
using System;
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.DataFactory.Models
{
    public partial class GoogleAdWordsLinkedService : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("type");
            writer.WriteStringValue(LinkedServiceType);
            if (Optional.IsDefined(ConnectVia))
            {
                writer.WritePropertyName("connectVia");
                writer.WriteObjectValue(ConnectVia);
            }
            if (Optional.IsDefined(Description))
            {
                writer.WritePropertyName("description");
                writer.WriteStringValue(Description);
            }
            if (Optional.IsCollectionDefined(Parameters))
            {
                writer.WritePropertyName("parameters");
                writer.WriteStartObject();
                foreach (var item in Parameters)
                {
                    writer.WritePropertyName(item.Key);
                    writer.WriteObjectValue(item.Value);
                }
                writer.WriteEndObject();
            }
            if (Optional.IsCollectionDefined(Annotations))
            {
                writer.WritePropertyName("annotations");
                writer.WriteStartArray();
                foreach (var item in Annotations)
                {
#if NET6_0_OR_GREATER
				writer.WriteRawValue(item);
#else
                    JsonSerializer.Serialize(writer, JsonDocument.Parse(item.ToString()).RootElement);
#endif
                }
                writer.WriteEndArray();
            }
            writer.WritePropertyName("typeProperties");
            writer.WriteStartObject();
            if (Optional.IsDefined(ConnectionProperties))
            {
                writer.WritePropertyName("connectionProperties");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(ConnectionProperties);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(ConnectionProperties.ToString()).RootElement);
#endif
            }
            if (Optional.IsDefined(ClientCustomerId))
            {
                writer.WritePropertyName("clientCustomerID");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(ClientCustomerId);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(ClientCustomerId.ToString()).RootElement);
#endif
            }
            if (Optional.IsDefined(DeveloperToken))
            {
                writer.WritePropertyName("developerToken");
                writer.WriteObjectValue(DeveloperToken);
            }
            if (Optional.IsDefined(AuthenticationType))
            {
                writer.WritePropertyName("authenticationType");
                writer.WriteStringValue(AuthenticationType.Value.ToString());
            }
            if (Optional.IsDefined(RefreshToken))
            {
                writer.WritePropertyName("refreshToken");
                writer.WriteObjectValue(RefreshToken);
            }
            if (Optional.IsDefined(ClientId))
            {
                writer.WritePropertyName("clientId");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(ClientId);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(ClientId.ToString()).RootElement);
#endif
            }
            if (Optional.IsDefined(ClientSecret))
            {
                writer.WritePropertyName("clientSecret");
                writer.WriteObjectValue(ClientSecret);
            }
            if (Optional.IsDefined(Email))
            {
                writer.WritePropertyName("email");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(Email);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(Email.ToString()).RootElement);
#endif
            }
            if (Optional.IsDefined(KeyFilePath))
            {
                writer.WritePropertyName("keyFilePath");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(KeyFilePath);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(KeyFilePath.ToString()).RootElement);
#endif
            }
            if (Optional.IsDefined(TrustedCertPath))
            {
                writer.WritePropertyName("trustedCertPath");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(TrustedCertPath);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(TrustedCertPath.ToString()).RootElement);
#endif
            }
            if (Optional.IsDefined(UseSystemTrustStore))
            {
                writer.WritePropertyName("useSystemTrustStore");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(UseSystemTrustStore);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(UseSystemTrustStore.ToString()).RootElement);
#endif
            }
            if (Optional.IsDefined(EncryptedCredential))
            {
                writer.WritePropertyName("encryptedCredential");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(EncryptedCredential);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(EncryptedCredential.ToString()).RootElement);
#endif
            }
            writer.WriteEndObject();
            foreach (var item in AdditionalProperties)
            {
                writer.WritePropertyName(item.Key);
#if NET6_0_OR_GREATER
				writer.WriteRawValue(item.Value);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(item.Value.ToString()).RootElement);
#endif
            }
            writer.WriteEndObject();
        }

        internal static GoogleAdWordsLinkedService DeserializeGoogleAdWordsLinkedService(JsonElement element)
        {
            string type = default;
            Optional<IntegrationRuntimeReference> connectVia = default;
            Optional<string> description = default;
            Optional<IDictionary<string, EntityParameterSpecification>> parameters = default;
            Optional<IList<BinaryData>> annotations = default;
            Optional<BinaryData> connectionProperties = default;
            Optional<BinaryData> clientCustomerId = default;
            Optional<FactorySecretBaseDefinition> developerToken = default;
            Optional<GoogleAdWordsAuthenticationType> authenticationType = default;
            Optional<FactorySecretBaseDefinition> refreshToken = default;
            Optional<BinaryData> clientId = default;
            Optional<FactorySecretBaseDefinition> clientSecret = default;
            Optional<BinaryData> email = default;
            Optional<BinaryData> keyFilePath = default;
            Optional<BinaryData> trustedCertPath = default;
            Optional<BinaryData> useSystemTrustStore = default;
            Optional<BinaryData> encryptedCredential = default;
            IDictionary<string, BinaryData> additionalProperties = default;
            Dictionary<string, BinaryData> additionalPropertiesDictionary = new Dictionary<string, BinaryData>();
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("connectVia"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    connectVia = IntegrationRuntimeReference.DeserializeIntegrationRuntimeReference(property.Value);
                    continue;
                }
                if (property.NameEquals("description"))
                {
                    description = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("parameters"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    Dictionary<string, EntityParameterSpecification> dictionary = new Dictionary<string, EntityParameterSpecification>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, EntityParameterSpecification.DeserializeEntityParameterSpecification(property0.Value));
                    }
                    parameters = dictionary;
                    continue;
                }
                if (property.NameEquals("annotations"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<BinaryData> array = new List<BinaryData>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(BinaryData.FromString(item.GetRawText()));
                    }
                    annotations = array;
                    continue;
                }
                if (property.NameEquals("typeProperties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("connectionProperties"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            connectionProperties = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                        if (property0.NameEquals("clientCustomerID"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            clientCustomerId = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                        if (property0.NameEquals("developerToken"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            developerToken = FactorySecretBaseDefinition.DeserializeFactorySecretBaseDefinition(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("authenticationType"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            authenticationType = new GoogleAdWordsAuthenticationType(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("refreshToken"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            refreshToken = FactorySecretBaseDefinition.DeserializeFactorySecretBaseDefinition(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("clientId"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            clientId = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                        if (property0.NameEquals("clientSecret"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            clientSecret = FactorySecretBaseDefinition.DeserializeFactorySecretBaseDefinition(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("email"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            email = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                        if (property0.NameEquals("keyFilePath"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            keyFilePath = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                        if (property0.NameEquals("trustedCertPath"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            trustedCertPath = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                        if (property0.NameEquals("useSystemTrustStore"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            useSystemTrustStore = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                        if (property0.NameEquals("encryptedCredential"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            encryptedCredential = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                    }
                    continue;
                }
                additionalPropertiesDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText()));
            }
            additionalProperties = additionalPropertiesDictionary;
            return new GoogleAdWordsLinkedService(type, connectVia.Value, description.Value, Optional.ToDictionary(parameters), Optional.ToList(annotations), additionalProperties, connectionProperties.Value, clientCustomerId.Value, developerToken.Value, Optional.ToNullable(authenticationType), refreshToken.Value, clientId.Value, clientSecret.Value, email.Value, keyFilePath.Value, trustedCertPath.Value, useSystemTrustStore.Value, encryptedCredential.Value);
        }
    }
}


text:
import matplotlib
matplotlib.use('Qt5Agg')

from PyQt5 import QtCore

from PyQt5.QtWidgets import QWidget, QVBoxLayout, QSizePolicy
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class MplCanvas(FigureCanvas):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)

        super(MplCanvas, self).__init__(fig)
        self.setParent(parent)

        super(MplCanvas, self).setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        super(MplCanvas, self).updateGeometry()

class CurvePlotWidget(QWidget):
    def __init__(self, parent=None):
        super(CurvePlotWidget, self).__init__(parent)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.mplCanvas = MplCanvas()
        self.layout.addWidget(self.mplCanvas)

    def setCurveData(self, bssrdf):
        colors = [ 'r', 'g', 'b' ]
        for i in range(3):
            self.mplCanvas.axes.plot(bssrdf.distances, bssrdf.colors[:,i], colors[i])

redpajama_set_name: RedPajamaGithub


text:
(function(jarvic) {
  'use strict';
  var jarvisFace;

  jarvis.oninit.push(() => {
    if(!jarvisFace) {
      jarvisFace = document.body.appendChild(document.createElement('div'));
      jarvisFace.className = 'jarvis jarvis--passive';
      jarvisFace.onclick = (e) => {
        e.stopPropagation();
        e.preventDefault();
        jarvis.listen();
      }
    }
  });

  jarvis.onpassive.push(() => {
    jarvisFace.className = 'jarvis jarvis--passive';
  });

  jarvis.onlisten.push(() => {
    jarvisFace.className = 'jarvis jarvis--listen';
  });

  jarvis.ontalk.push(() => {
    jarvisFace.className = 'jarvis jarvis--talk';
  });
})(jarvis);


text:
require 'rails_helper'

RSpec.describe BulkController, type: :controller do
  login_admin

  describe "GET scrape" do
    it "returns http success" do
      get :scrape
      expect(response).to have_http_status(:success)
    end
  end

  describe "GET scrape_api" do
    xit "returns http success" do
      get :scrape_api
      expect(response).to have_http_status(:success)
    end
  end

  describe "GET ogp_api" do
    it "should call the OpenGraphProtocol.fetch method" do
      expect(OpenGraphProtocol).to receive(:fetch).with("http://foo/").and_return({"bar" => "baz"})
      get :ogp_api, format: :json, url: "http://foo/"
      expect(response).to be_success
      json = ActiveSupport::JSON.decode(response.body)
      expect(json).to eq({"bar" => "baz"})
    end
  end

  describe "GET import_csv" do
    xit "returns http success" do
      get :import_csv
      expect(response).to have_http_status(:success)
    end
  end

  describe "GET export_csv" do
    it "returns http success" do
      get :export_csv
      expect(response).to have_http_status(:success)
    end

    context "in CSV format" do
      render_views

      it "should return all submissions" do
        submission = FactoryGirl.create(:submission, title: "Foo", description: "Bar")
        submission.tags = [Tag.new(text: "Tag1"), Tag.new(text: "Tag2")]
        property_type = FactoryGirl.create(:property_type, name: "URL")
        submission.properties.create(property_type_id: property_type.id, value: "http://foo/")
        get :export_csv, format: :csv
        expect(response).to be_success
        csv = CSV.parse(response.body, headers: true)
        expect(csv.size).to eq 1
        expect(csv.first["ID"]).to eq submission.id.to_s
        expect(csv.first["Title"]).to eq "Foo"
        expect(csv.first["Description"]).to eq "Bar"
        expect(csv.first["Tags"]).to eq "Tag1 Tag2"
        expect(csv.first["URL"]).to eq "http://foo/"
      end

      it "should send the file as type text/csv" do
        get :export_csv, format: :csv
        expect(response).to be_success
        expect(response.headers["Content-Type"].to_s).to start_with "text/csv"
      end

      it "should send the file as a download if ?download=1 is set" do
        get :export_csv, format: :csv, download: 1
        expect(response).to be_success
        expect(response.headers["Content-Disposition"].to_s).to start_with "attachment;"
      end
    end
  end
end


text:
<TITLE>Review for Prospero's Books (1991)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Prospero's Books (1991)

reviewed by
Frank Maloney

version which had disk corruption.  -Moderator]

                              PROSPERO'S BOOKS
                       A film review by Frank Maloney
                        Copyright 1991 Frank Maloney

     PROSPERO'S BOOKS is a film by Peter Greenaway.  The film stars John
Gielgud.  The music is by Michael Nyman.

     I have been postponing writing about PROSPERO'S BOOKS because,
beyond shouting I loved it and admitting that I nearly dozed off in one
place, I am somewhat at loss to know what I can say.  It is a complex
film that certainly pushes the limits the definition of what a motion
picture is.  It also pushes the limits of what the viewer can take in.
I refer to the complex imagery, the multi-voiced dialogue, the
play-within-a-play structure, and the ambiguity of purpose and message.
In the meantime, allow me to present a few tentative, first impressions.

     I doubt that many of you reading this do not know that PROSPERO'S
BOOKS is a version, a vision, of Shakespeare's final play, "The
Tempest."  You probably also have read a synopsis of the story or are
already familiar with it, so I won't rework those tailings.  "The
Tempest" is easy to read as Shakespeare's farewell to the stage and as
such it may well represent a coherent commentary on play-making and the
play-maker.  The playwright is the magician who creates and destroys
entire worlds, who has the power to name and marshal characters and
forces not accessible to you and me, mere mortals, the audience.

     Although I don't imagine that Greenaway is bidding farewell to
movie-making, his way of presenting "The Tempest" is a commentary on his
own art, a visual essay on film-making, perhaps.  Certainly, it would
not be too startling to find a correlation between the magician and the
director.  One of my favorite moments in PROSPERO'S BOOKS comes when
Prospero leads his trains of spirits past a tableau of Prospero himself
writing the dialogue the ambulatory Prospero is speaking.  In the movie,
it is the act of writing the play "The Tempest" that is the magic that
moves the action (as, indeed, it is in our quotidian life)--not a
startlingly original idea on Greenaway's part, but a masterly, succinct
image of the idea.  It is an image that is suggestive, too, of the
question of how much the creator exists outside his (or her) creation,
how much the creator is self-creating.  Of course, the maddening thing
about what one might think of as visual criticism or visual philosophy
is that the image seldoms poses more than the question.  Imagery is
inherently ambiguous.  For many viewers, the ambiguities of PROSPERO'S
BOOKS will be a barrier to the film's accessibility.

     This film is first and foremost a visual art form.  There is some
irony, perhaps, in the way Greenaway subordinates the famous dialogue to
its visual equivalents; it is almost as if a contemporary director
proposed returning to the silent film.  Of course, films are primarily
visual experiences (whereas drama, and especially poetical drama such as
Shakespeare's, are essentially verbal experiences), particularly as
films are usually made these days; great dialogue is rare and such films
are subject to criticism of being "talky."

     It occurs to me that the most useful comparisons amongst recent
films are to be made with contemporary Shakespearean films, HENRY V by
Kenneth Branagh and HAMLET by Zeffirelli.  Such films typically struggle
to find ways not to be merely filmed plays.  The directors use realistic
or even historic sets, move scenes to outdoors locations, extend action
sequences, make use of appropriate special effects, and so forth.  But
woe betide the incautious director who dares rearrange scenes, edit
speeches, or take other liberties with the "Master's received text."

     Compared with Greenaway, Branagh and Zeffirelli produced utterly
conventional film versions of the plays.  It is, it seems to me, wholly
unfair to say that Greenaway has produced not so much as a film version
of "The Tempest," but a visualization of the play's major theme.  And
that has got some people upset.

     I confessed in the beginning to an attack of the drowsies while
watching PROSPERO'S BOOKS.  This came during the wedding sequence which
more like watching "The Tempest" as one would expect to see, and had
little to do with the playfulness, the richly detailed, painterly
surfaces, cinematic fantasies that I associate with Greenaway.  Of
course, I had put in a hard day's work at work, but the fact is that
during the parts of the film that were more challenging, more daring, I
stayed right in there, alert and happy.

     And speaking of staying right in there, the man who performed that
amazing version of Caliban never failed to delight and surprise me with
his ceaseless movements -- stretching, pointing, forever straining
against the invisible chains with which Prospero enslaved him.  The
three actors who played Ariel presented a charming concept of that airy
spirit.

     Watching the calligraphy in action was beautiful and fascinating,
more choreography than calligraphy at moments.  The costumes of the
courtiers, those amazing hats, collars, and shoes, were whimsical,
hilarious, and satirical, existing in ludicrous contrast to the wisps
and scraps that clothed the spirits, speaking volumes about
artificiality and civilization.  (These clothes put me in mind of BARON
MUNCHAUSEN, for what that's worth; exaggerated styles for exaggerated
imaginations, styles that say more than the wearer knows.)

     I loved the nudity, the lack both of coyness and titillation, the
variety of bodies, the way before the movie was over I had stopped
seeing them as naked and started them merely as nude.

     I wasn't too thrilled by the silly queen act of the two servants
who team up with Caliban to take over the island, but I can live with
it, I think.

     I was pleased and impressed by the interludes in which we were told
about Prospero's 24 books, the animation, the use of HDTV in the
inserts, and especially by the identity of the 24th book.  I was also
shocked by the fate of those books, as any literate person has to be;
our reactions, as much as the movie's (and the play's) actions vis-a-vis
the books speaks volumes about the power of books over us.  The power,
rarity, and beauty of the written word is one of the essential ideas in
"The Tempest"--an idea also acted by the close-ups of the calligraphy.
Greenaway's version of the books is remarkably like the television
version of another famous fictive book, THE HITCHHIKER'S GUIDE TO THE
GALAXY, books that can't stay still, that squirm and babble with powers
all their own.

     I haven't any idea whether to recommend PROSPERO'S BOOKS to you;
some of you will share my love of this movie, others will be subject to
various negative reactions, including irritation and frustration.  I
intend to see it again and I won't be particularly concerned about
whether I have to pay full price or not.

--
Frank Richard Aloysius Jude Maloney
.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
class AddMedicalDocumentUploadOption < ActiveRecord::Migration[5.1]
  def change
    add_column :registrants, :medical_document, :string
    add_column :event_configurations, :require_medical_document, :boolean, default: false, null: false
  end
end


text:
package org.wave.repository.validators;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.wave.repository.enums.ErrorEnum;
import org.wave.repository.enums.MethodEnum;
import org.wave.repository.exceptions.RepositoryException;
import org.wave.repository.validators.ClassValidator;
import org.wave.repository.validators.examples.ClasseEntidade;
import org.wave.repository.validators.examples.ClasseNaoSerializavel;
import org.wave.repository.validators.examples.ClasseSemActive;
import org.wave.repository.validators.examples.ClasseSemActiveBoolean;
import org.wave.repository.validators.examples.ClasseSemAtEntity;
import org.wave.repository.validators.examples.ClasseSemAtId;
import org.wave.repository.validators.examples.ClasseSemAtVersion;
import org.wave.repository.validators.examples.ClasseSemConstrutorPadrao;
import org.wave.repository.validators.examples.ClasseSemEquals;
import org.wave.repository.validators.examples.ClasseSemHashCode;
import org.wave.repository.validators.examples.ClasseSemId;
import org.wave.repository.validators.examples.ClasseSemIdLong;
import org.wave.repository.validators.examples.ClasseSemVersion;
import org.wave.repository.validators.examples.ClasseSemVersionInteger;

public class ClassValidatorTest {

	private ClassValidator validator;

	private Class<?> klass;

	@Before
	public void setUp() {
		this.validator = new ClassValidator();
	}

	@Test(expected = RepositoryException.class)
	public void deveLancarExcecaoQuandoAClasseNaoEstiverAnotadaComAtEntityException() throws RepositoryException {
		this.klass = ClasseSemAtEntity.class;

		this.validator.validate(this.klass);
	}

	@Test
	public void deveLancarExcecaoQuandoAClasseNaoEstiverAnotadaComAtEntity() {
		this.klass = ClasseSemAtEntity.class;

		try {
			this.validator.validate(this.klass);
		} catch (RepositoryException e) {
			assertEquals(ErrorEnum.ANNOTATION_ENTITY_NOT_FOUND.getMessage(this.klass.getName()), e.getMessage());
		}
	}

	@Test(expected = RepositoryException.class)
	public void deveLancarExcecaoQuandoAClasseNaoForSerializavelException() throws RepositoryException {
		this.klass = ClasseNaoSerializavel.class;

		this.validator.validate(this.klass);
	}

	@Test
	public void deveLancarExcecaoQuandoAClasseNaoForSerializavel() {
		this.klass = ClasseNaoSerializavel.class;

		try {
			this.validator.validate(this.klass);
		} catch (RepositoryException e) {
			assertEquals(ErrorEnum.INTERFACE_NOT_FOUND.getMessage(), e.getMessage());
		}
	}

	@Test(expected = RepositoryException.class)
	public void deveLancarExcecaoQuandoAClasseNaoTiverUmAtributoIdException() throws RepositoryException {
		this.klass = ClasseSemId.class;

		this.validator.validate(this.klass);
	}

	@Test
	public void deveLancarExcecaoQuandoAClasseNaoTiverUmAtributoId() {
		this.klass = ClasseSemId.class;

		try {
			this.validator.validate(this.klass);
		} catch (RepositoryException e) {
			assertEquals(ErrorEnum.ID_NOT_FOUND.getMessage(), e.getMessage());
		}
	}

	@Test(expected = RepositoryException.class)
	public void deveLancarUmaExcecaoQuandoOIdDaClasseNaoForDoTipoLongException() throws RepositoryException {
		this.klass = ClasseSemIdLong.class;

		this.validator.validate(this.klass);
	}

	@Test
	public void deveLancarUmaExcecaoQuandoOIdDaClasseNaoForDoTipoLong() {
		this.klass = ClasseSemIdLong.class;

		try {
			this.validator.validate(this.klass);
		} catch (RepositoryException e) {
			assertEquals(ErrorEnum.ID_NOT_LONG.getMessage(), e.getMessage());
		}
	}

	@Test(expected = RepositoryException.class)
	public void deveLancarUmaExcecaoQuandoOIdDaClasseNaoEstiverAnotadoComAtIdException() throws RepositoryException {
		this.klass = ClasseSemAtId.class;

		this.validator.validate(this.klass);
	}

	@Test
	public void deveLancarUmaExcecaoQuandoOIdDaClasseNaoEstiverAnotadoComAtId() {
		this.klass = ClasseSemAtId.class;

		try {
			this.validator.validate(this.klass);
		} catch (RepositoryException e) {
			assertEquals(ErrorEnum.ANNOTATION_ID_NOT_FOUND.getMessage(), e.getMessage());
		}
	}

	@Test(expected = RepositoryException.class)
	public void deveLancarExcecaoQuandoAClasseNaoTiverUmAtributoVersionException() throws RepositoryException {
		this.klass = ClasseSemVersion.class;

		this.validator.validate(this.klass);
	}

	@Test
	public void deveLancarExcecaoQuandoAClasseNaoTiverUmAtributoVersion() {
		this.klass = ClasseSemVersion.class;

		try {
			this.validator.validate(this.klass);
		} catch (RepositoryException e) {
			assertEquals(ErrorEnum.VERSION_NOT_FOUND.getMessage(), e.getMessage());
		}
	}

	@Test(expected = RepositoryException.class)
	public void deveLancarUmaExcecaoQuandoOVersionDaClasseNaoForDoTipoIntegerException() throws RepositoryException {
		this.klass = ClasseSemVersionInteger.class;

		this.validator.validate(this.klass);
	}

	@Test
	public void deveLancarUmaExcecaoQuandoOVersionDaClasseNaoForDoTipoInteger() {
		this.klass = ClasseSemVersionInteger.class;

		try {
			this.validator.validate(this.klass);
		} catch (RepositoryException e) {
			assertEquals(ErrorEnum.VERSION_NOT_INTEGER.getMessage(), e.getMessage());
		}
	}

	@Test(expected = RepositoryException.class)
	public void deveLancarUmaExcecaoQuandoOVersionDaClasseNaoEstiverAnotadoComAtVersionException() throws RepositoryException {
		this.klass = ClasseSemAtVersion.class;

		this.validator.validate(this.klass);
	}

	@Test
	public void deveLancarUmaExcecaoQuandoOVersionDaClasseNaoEstiverAnotadoComAtVersion() {
		this.klass = ClasseSemAtVersion.class;

		try {
			this.validator.validate(this.klass);
		} catch (RepositoryException e) {
			assertEquals(ErrorEnum.ANNOTATION_VERSION_NOT_FOUND.getMessage(), e.getMessage());
		}
	}

	@Test(expected = RepositoryException.class)
	public void deveLancarExcecaoQuandoAClasseNaoTiverUmAtributoActiveException() throws RepositoryException {
		this.klass = ClasseSemActive.class;

		this.validator.validate(this.klass);
	}

	@Test
	public void deveLancarExcecaoQuandoAClasseNaoTiverUmAtributoActive() {
		this.klass = ClasseSemActive.class;

		try {
			this.validator.validate(this.klass);
		} catch (RepositoryException e) {
			assertEquals(ErrorEnum.ACTIVE_NOT_FOUND.getMessage(), e.getMessage());
		}
	}

	@Test(expected = RepositoryException.class)
	public void deveLancarUmaExcecaoQuandoOActiveDaClasseNaoForDoTipoBooleanException() throws RepositoryException {
		this.klass = ClasseSemActiveBoolean.class;

		this.validator.validate(this.klass);
	}

	@Test
	public void deveLancarUmaExcecaoQuandoOActiveDaClasseNaoForDoTipoBoolean() {
		this.klass = ClasseSemActiveBoolean.class;

		try {
			this.validator.validate(this.klass);
		} catch (RepositoryException e) {
			assertEquals(ErrorEnum.ACTIVE_NOT_BOOLEAN.getMessage(), e.getMessage());
		}
	}

	@Test(expected = RepositoryException.class)
	public void deveLancarExcecaoQuandoAClasseNaoTiverConstrutorPadraoException() throws RepositoryException {
		this.klass = ClasseSemConstrutorPadrao.class;

		this.validator.validate(this.klass);
	}

	@Test
	public void deveLancarExcecaoQuandoAClasseNaoTiverConstrutorPadrao() {
		this.klass = ClasseSemConstrutorPadrao.class;

		try {
			this.validator.validate(this.klass);
		} catch (RepositoryException e) {
			assertEquals(ErrorEnum.CONSTRUCTOR_NOT_FOUND.getMessage(this.klass.getName()), e.getMessage());
		}
	}

	@Test(expected = RepositoryException.class)
	public void deveLancarExcecaoQuandoAClasseNaoSobrescreverOMetodoEqualsException() throws RepositoryException {
		this.klass = ClasseSemEquals.class;

		this.validator.validate(this.klass);
	}

	@Test
	public void deveLancarExcecaoQuandoAClasseNaoSobrescreverOMetodoEquals() {
		this.klass = ClasseSemEquals.class;

		try {
			this.validator.validate(this.klass);
		} catch (RepositoryException e) {
			assertEquals(ErrorEnum.METHOD_NOT_FOUND.getMessage(MethodEnum.EQUALS.getValue()), e.getMessage());
		}
	}

	@Test(expected = RepositoryException.class)
	public void deveLancarExcecaoQuandoAClasseNaoSobrescreverOMetodoHashCodeException() throws RepositoryException {
		this.klass = ClasseSemHashCode.class;

		this.validator.validate(this.klass);
	}

	@Test
	public void deveLancarExcecaoQuandoAClasseNaoSobrescreverOMetodoHashCode() {
		this.klass = ClasseSemHashCode.class;

		try {
			this.validator.validate(this.klass);
		} catch (RepositoryException e) {
			assertEquals(ErrorEnum.METHOD_NOT_FOUND.getMessage(MethodEnum.HASHCODE.getValue()), e.getMessage());
		}
	}

	@Test
	public void deveRetornarFalsoSeAClasseNaoForUmaEntidade() {
		assertFalse(this.validator.isEntity(ClasseSemHashCode.class));
	}

	@Test
	public void deveRetornarVerdadeiroSeAClasseForUmaEntidade() {
		assertTrue(this.validator.isEntity(ClasseEntidade.class));
	}

	@After
	public void tearDown() {
		this.validator = null;
	}

}


text:
git config --global user.name "some_user"
git config --global user.email "some_email"

export PATH=${PYENV_ROOT}/bin:${PATH}
eval "$(pyenv init -)"

mkdir -p ~/.cirrus
virtualenv ~/.cirrus/venv
(

. ~/.cirrus/venv/bin/activate
export LOCATION=~/.cirrus
pip install /opt/cirrus-cli-latest.tar.gz
export CIRRUS_HOME=$LOCATION
export VIRTUALENV_HOME=$LOCATION/venv
selfsetup --robot

)

TIMESTAMP=`date +%s`
REPO_DIR="test_${TIMESTAMP}"
export USER=some_user
mkdir -p $REPO_DIR
cd $REPO_DIR
git init

# set up a new package
git cirrus package init --bootstrap -p test_package -v 0.0.0 -s src --no-remote -o integ_test -d "this is a test"  --python python3.5
# set up simple container templates
git cirrus build   # build local dev virtualenv
git cirrus test                                     # run tests
git cirrus feature new integ_test --no-remote
git cirrus feature merge --no-remote
git cirrus release new --micro --no-remote
git cirrus release build                  # create a build artifact to add to the container
git cirrus release merge --cleanup --no-remote


text:
package com.touwolf.mailchimp.data.condiction.types;

public class McTextMerge extends McParent {
    private McTextMergeOpEnum op;

    private String field;

    private String value;

    /**
     * Whether the email address is/not exactly, contains/doesn't contain, starts/ends with a string.
     * Possible Values:
     * <p>
     * is
     * not
     * contains
     * notcontain
     * starts
     * ends
     * greater
     * less
     * blank
     * blank_not
     */
    public McTextMergeOpEnum getOp() {
        return op;
    }

    public void setOp(McTextMergeOpEnum op) {
        this.op = op;
    }

    /**
     * The segment field, one of 'merge0' or 'EMAIL'.
     */
    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    /**
     * The value to compare.
     */
    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}


text:
package iso20022

// Unique and unambiguous way to identify an organisation.
type PartyIdentification12Choice struct {

	// Unique and unambiguous way to identify an organisation.
	BICOrBEI *AnyBICIdentifier `xml:"BICOrBEI"`

	// Unique and unambiguous way to identify an organisation.
	NameAndAddress *NameAndAddress5 `xml:"NmAndAdr"`

	// Unique and unambiguous way to identify an organisation.
	Country *CountryCode `xml:"Ctry"`
}

func (p *PartyIdentification12Choice) SetBICOrBEI(value string) {
	p.BICOrBEI = (*AnyBICIdentifier)(&value)
}

func (p *PartyIdentification12Choice) AddNameAndAddress() *NameAndAddress5 {
	p.NameAndAddress = new(NameAndAddress5)
	return p.NameAndAddress
}

func (p *PartyIdentification12Choice) SetCountry(value string) {
	p.Country = (*CountryCode)(&value)
}


text:
function [ signal, states, parameters, total_samples ] = load_bcidat( varargin )
%LOAD_BCIDAT Load BCI2000 data files into Matlab workspace variables.
%
%  [ signal, states, parameters, total_samples ] = load_bcidat( 'filename1', 'filename2', ... )
%
%  loads signal, state, and parameter data from the files whose names are given
%  as function arguments.
%
%  Examples for loading multiple files:
%    files = dir( '*.dat' );
%    [ signal, states, parameters ] = load_bcidat( files.name );
%
%    files = struct( 'name', uigetfile( 'MultiSelect', 'on' ) );
%    [ signal, states, parameters ] = load_bcidat( files.name );
%
%
%  For multiple files, number of channels, states, and signal type must be
%  consistent.
%
%  By default, signal data will be in raw A/D units, and will be represented by the
%  smallest Matlab data type that accommodates them.
%  To obtain signal data calibrated into physical units (microvolts),
%  specify '-calibrated' as an option anywhere in the argument list.
%
%  The 'states' output variable will be a Matlab struct with BCI2000 state
%  names as struct member names, and the number of state value entries matching
%  the first dimension of the 'signal' output variable.
%
%  The 'parameters' output variable will be a Matlab struct with BCI2000
%  parameter names as struct member names.
%  Individual parameter values are represented as cell arrays of strings in a
%  'Value' struct member, and additionally as numeric matrices in a 'NumericValue'
%  struct member. When there is no numeric interpretation possible, the
%  corresponding matrix entry will be NaN. For nested matrices, no NumericValue
%  field is provided.
%  If multiple files are given, parameter values will match the ones contained
%  in the first file.
%
%  Optionally, sample ranges may be specified for individual files:
%  [ signal, states, parameters ] = load_bcidat( 'filename', [first last] )
%  will load a subset of samples defined by first and last sample index.
%  Specifying [0 0] for an empty sample range allows to read states and
%  parameters from a file without reading sample data:
%  [ ignored, states, parameters ] = load_bcidat( 'filename', [0 0] );
%
%  The 'total_samples' output variable reports the total number of samples
%  present in all files.
%
%
%  The load_bcidat function is part of the BCI2000 project.
%  (C) 2000-2008, BCI2000 Project
%  http://www.bci2000.org

%  This is a help file documenting the functionality contained in
%  load_bcimat.mex.
%  $Id: load_bcidat.m 1957 2008-05-14 14:22:16Z mellinger $
%
error( 'There is no load_bcidat mex file for your platform available.' );


text:
import unittest
from flask import request
from voodoo.gen import load_dir
from voodoo.gen.registry import GLOBAL_REGISTRY

class TestViewLogin(unittest.TestCase):

    def setUp(self):
        GLOBAL_REGISTRY.clear()
        """
        Prepares the test by creating a new weblab instance from a for-testing configuration.
        The instance is configured *not* to start a flask server, but to allow Flask test methods
        instead.
        :return:
        """

        # Load the configuration of the weblab instance that we have set up for just this test.
        self.global_config = load_dir('test/deployments/webclient_dummy')

        # Start the weblab instance. Because we have activated the dont-start flag it won't actually
        # start listening on the port, but let us use the Flask test methods instead.
        self.handler = self.global_config.load_process('myhost', 'myprocess')

        self.core_server = GLOBAL_REGISTRY['mycore:myprocess@myhost']

        self.app = self.core_server.app.test_client()
        """ :type: flask.testing.FlaskClient """

    def test_login_page(self):
        """
        Ensure that the login screen seems to load.
        """
        rv = self.app.get('/weblab/web/webclient/')
        self.assertEqual(rv.status_code, 200, "Login page does not return 200")
        self.assertIn("Remote Laboratory", rv.data, "Login page does not contain the expected 'Remote Laboratory' text")
        self.assertIn("Support", rv.data, "Login page does not contain the expected 'Support' text")

    def test_login_wrongpass(self):
        """
        Ensure that a login POST with a wrong password results in an 'Invalid username or password' message.
        """
        rv = self.app.post('/weblab/web/webclient/', data=dict(username='any', password='wrongpassword'))
        """ :type: flask.wrappers.Response """

        self.assertEqual(rv.status_code, 302, "Login POST with wrong pass does not return 302")
        self.assertTrue(rv.location.endswith("/web/webclient/"), "Redirection does not lead to index")

        rv = self.app.get(rv.location)
        self.assertIn("Invalid username or password", rv.data, "After wrong password login 'Invalid username...' does not appear")

    def test_login_rightpass(self):
        """
        Ensure that a login POST with a right password results in a redirection to the labs page.
        """
        rv = self.app.post('/weblab/web/webclient/', data=dict(username='any', password='password'))
        """ :type: flask.wrappers.Response """

        print rv.location
        self.assertEqual(rv.status_code, 302, "Login POST with right pass does not return 302")
        self.assertTrue(rv.location.endswith("/web/webclient/labs.html"), "Redirection does not lead to the labs page")

        with self.app as c:
            # Just so the context is set, to be able to read cookies.
            c.get("/")
            self.assertIn("weblabsessionid", request.cookies, "Cookie weblabsessionid was not set")
            self.assertIn("loginweblabsessionid", request.cookies, "Cookie loginweblabsessionid was not set")

    def tearDown(self):
        """
        Shutdown the WebLab instance that we have started for the test.
        """
        rv = self.app.post('/weblab/web/webclient/', data=dict(username='any', password='password'))
        self.assertEqual(rv.status_code, 302, "Login POST with right pass does not return 302")

        self.handler.stop()

def suite():
    return unittest.TestSuite((
            unittest.makeSuite(TestViewLogin),
        ))


text:
package org.powermock.tests.utils;

import java.lang.reflect.AnnotatedElement;

public interface TestClassesExtractor {
	/**
	 * @return Returns null if the element was not annotated, an
	 *         empty String[] if it is annotated but contains no classes, or a
	 *         string-array of all class names if interest.
	 */
	String[] getTestClasses(AnnotatedElement element);

	boolean isPrepared(AnnotatedElement element, String fullyQualifiedClassName);
}


text:
package subscriptions

import (
	"encoding/json"
	"net/http"

	"github.com/gorilla/mux"
)

func Configure(router *mux.Router) {

	router.HandleFunc("/subscription", newSubscription).Methods("POST")
}

func newSubscription(resp http.ResponseWriter, req *http.Request) {

	decoder := json.NewDecoder(req.Body)
	var jsonData Subscription
	decoder.Decode(&jsonData)

	write(jsonData)
}


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

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Peersview</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="css/peersview.css" />

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

My Profile

Account Setting

Peersview Support

Log-Out

Home

Forum

Campus

Leisure

Notifications

 Angela Gill started following you 2 hours ago

 Faith Black commented on your post 3 hours ago

 Olivia Metcalfe like your post 4 hours ago

 Gordon Piper invite you to join the community Today at 1:20pm

 Adekunle Amodu likes your post. Yesterday at 5:35pm

View All

MessagesNew Message

 Angela Gill Tue

 Faith Black Tue

 Olivia Metcalfe Tue

 Adekunle Amodu Tue

 Gordon Piper Tue

View All

                <form action="">
                  <input type="text" class="search-field" placeholder="Type search text here...">

                    <input type="submit" value="" class="submit">

                </form>

                Advanced Search

 Welcome John

My Profile

Account Setting

Peersview Support

Log-Out

Messages

 Angela Gill Tue

 Faith Black Tue

 Olivia Metcalfe Tue

 Adekunle Amodu Tue

 Gordon Piper Tue

 David Ball Tue

 Megan Vaughan Tue

 Gavin Newman Tue

Angela Gill

Student   |     Los Anageles, LA

How are you doing?

doing great, thanks. How are you?

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

          <textarea class="form-control" placeholder="Type a message..."></textarea>
          Send

 AD

Copyright 2017 All rights reserved.

About Us

Our Team

Careers

Support

Events

Campus

Privacy Policy

Terms & Conditions

Contact Us

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

New Message

          To
          <input type="text" class="form-control" placeholder="Name" />

          Message
          <textarea placeholder="Write a message here..."  rows="3"class="form-control"></textarea>

          Attach a File
          <input type="file" />

        <button type="button" class="btn btn-grey" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-blue">Send</button>


text:
const mongoose = require('mongoose')
const validator = require('validator')

// The database name is provided as part of the url
const dbName = 'task-manager-api'
const connectionURL = 'mongodb://127.0.0.1:27017/' + dbName

// Connect to the DB. Result is a Mongoose object with DB details.
console.log('Connecting to ', connectionURL, ' ...')
mongoose.connect(connectionURL, {
    useUnifiedTopology: true,
    useCreateIndex: true
}).then((result) => {
    console.log('Connect Result: ', result)
}).catch((error) => {
    console.log('Connect Error: ', error)
})

// Define a 'User' mongoose model
const User = mongoose.model('User', {
    name: {
        type: String,
        required: true,   // Validation   : field is required
        trim: true        // Sanitization : Trim leading/trailing whitespace
    },
    email: {
        type: String,
        required: true,   // Validation   : field is required
        trim: true,       // Sanitization : Trim leading/trailing whitespace
        lowercase: true,  // Sanitization : Convert to lowercase
        validate(value) { // Validation   : Custom Validator
            if(!validator.isEmail(value)) {
                msg = 'Invalid email : ', value
                throw new Error(msg)
            }
        }
    },
    age: {
        type: Number,
        default: 0,       // Sanitization : Provide default value
        validate(value) { // Validation   : Custom Validator
            if(value < 0) {
                throw new Error('Age must be a positive number')
            }
        }
    },
    password: {
        type: String,
        required: true,   // Validation   : field is required
        trim: true,       // Sanitization : Trim leading/trailing whitespace
        validate(value) { // Validation   : Custom Validator
            console.log('value.length: ', value.length)
            if(value.length < 10) {
                throw new Error('Minimum password length is 10 characters')
            }

            if(value.toLowerCase().includes('password')) {
                throw new Error('Unsecure password provided')
            }
        }
    }
})

// Create an instance of the model
const myUser = new User({
    name: 'Georgie',
    age: 22,
    email: ' I.AM.SCREAMING@REALLY.LOUD ',
    password: '   123456789A   '
})

// Save it to the DB
//   Result : Result:  { _id: 5dd445499b746932c00d5a06, name: 'Jimi', age: 92, __v: 0 }
myUser.save().then(() => {
    console.log('Result: ', myUser)
}).catch((error) => {
    console.log('Error: ', error)
})

// Define a 'Task' mongoose model
const Task = mongoose.model('Task', {
    description: {
        type: String,
        required: true  // Validation   : field is required
    },
    completed: {
        type: Boolean
    }
})

// Create an instance of the model
const myTask = new Task({
    description: 'Grocery shopping',
    completed: false
})

// Save it to the DB
myTask.save().then(() => {
    console.log('Result: ', myTask)
}).catch((error) => {
    console.log('Error: ', error)
})


text:
TreadmillPrototype::TreadmillPrototype()
{
    this->setType("Treadmill");
}

TreadmillPrototype::TreadmillPrototype(const TreadmillPrototype& other)
{
    this->setType(other.getType());
}

EquipmentPrototype* TreadmillPrototype::clone() const
{
    return new TreadmillPrototype(*this);
}


text:
namespace ChaosCMS
{
    /// <summary>
    ///
    /// </summary>
    public class ChaosMarkerService
    {
    }
}


text: Space invaders arcade game in JS


text:
module.exports = function (array) {
  var hash = {};

  // Loop though the array adding all the elements together in a hash
  array.forEach(function (num) {
    hash[num] = hash[num] + 1 || 1;
  });

  // Loop through all the keys in the hash, returning the number if we have an
  // even number of occurances
  for (var i in hash) {
    if (!(hash[i] & 1)) {
      return Number(i);
    }
  }

  return false;
};


text:
import { accessor, accessors } from 'index';
import Backbone from 'backbone';

describe('Decorators / Backbone / Accessors', () => {

  describe('accessor', () => {
    let model;

    class AccessorModel extends Backbone.Model {

      @accessor
      testProp;
    }

    beforeEach(() => {
      model = new AccessorModel();
    });

    it('should throw an exception if the decorator is attached to a class property', () => {
      try {
        @accessor
        class FailedAccessorModel extends Backbone.Model {}
      } catch (e) {
        expect(e.message).to.equal('@accessor can only be applied to class properties');
      }
    });

    it('should create getters and setters for the attached property', () => {
      expect(model.get('testProp')).to.be.undefined;
      expect(model.testProp).to.be.undefined;

      model.testProp = 55;

      expect(model.get('testProp')).to.equal(55);
      expect(model.testProp).to.equal(55);

      model.set('testProp', 100)

      expect(model.get('testProp')).to.equal(100);
      expect(model.testProp).to.equal(100);
    });

  });

  describe('accessors', () => {
    let model;

    @accessors(['testProp', 'testProp2'])
    class AccessorsModel extends Backbone.Model {}

    beforeEach(() => {
      model = new AccessorsModel();
    });

    it('should throw an exception if the decorator is not given an array of attributes', () => {
      try {
        @accessors()
        class FailedAccessorsModel extends Backbone.Model {}
      } catch (e) {
        expect(e.message).to.equal('@accessors must be an array');
      }
    });

    it('should create getters and setters for the attached property', () => {
      expect(model.get('testProp')).to.be.undefined;
      expect(model.testProp).to.be.undefined;

      model.testProp = 55;

      expect(model.get('testProp')).to.equal(55);
      expect(model.testProp).to.equal(55);

      model.set('testProp', 100)

      expect(model.get('testProp')).to.equal(100);
      expect(model.testProp).to.equal(100);

      expect(model.get('testProp2')).to.be.undefined;
      expect(model.testProp2).to.be.undefined;

      model.testProp2 = 55;

      expect(model.get('testProp2')).to.equal(55);
      expect(model.testProp2).to.equal(55);

      model.set('testProp2', 100)

      expect(model.get('testProp2')).to.equal(100);
      expect(model.testProp2).to.equal(100);
    });

  });

});


text:
<?php

namespace Test\Integration\Version2x8;

include_once(__DIR__. '/../Version2x6/PubSubCommandsTest.php');

use RedisClient\Client\Version\RedisClient2x8;
use Test\Integration\Version2x6\PubSubCommandsTest as PubSubCommandsTestVersion2x6;

/**
 * @see \RedisClient\Command\Traits\Version2x8\PubSubCommandsTrait
 */
class PubSubCommandsTest extends PubSubCommandsTestVersion2x6 {

    const TEST_REDIS_SERVER_1 = TEST_REDIS_SERVER_2x8_1;

    /**
     * @inheritdoc
     */
    public static function setUpBeforeClass() {
        static::$Redis = new RedisClient2x8([
            'server' =>  static::TEST_REDIS_SERVER_1,
            'timeout' => 2,
        ]);
        static::$Redis2 = new RedisClient2x8([
            'server' =>  static::TEST_REDIS_SERVER_1,
            'timeout' => 2,
        ]);
    }
}


text:
#ifndef _XTENSA_PROCESSOR_H
#define _XTENSA_PROCESSOR_H

#include <variant/core.h>
#include <platform/hardware.h>

#include <linux/compiler.h>
#include <asm/ptrace.h>
#include <asm/types.h>
#include <asm/regs.h>

/* Assertions. */

#if (XCHAL_HAVE_WINDOWED != 1)
# error Linux requires the Xtensa Windowed Registers Option.
#endif

#define ARCH_SLAB_MINALIGN	XCHAL_DATA_WIDTH

/*
 * User space process size: 1 GB.
 * Windowed call ABI requires caller and callee to be located within the same
 * 1 GB region. The C compiler places trampoline code on the stack for sources
 * that take the address of a nested C function (a feature used by glibc), so
 * the 1 GB requirement applies to the stack as well.
 */

#ifdef CONFIG_MMU
#define TASK_SIZE	__XTENSA_UL_CONST(0x40000000)
#else
#define TASK_SIZE	(PLATFORM_DEFAULT_MEM_START + PLATFORM_DEFAULT_MEM_SIZE)
#endif

#define STACK_TOP	TASK_SIZE
#define STACK_TOP_MAX	STACK_TOP

/*
 * General exception cause assigned to debug exceptions. Debug exceptions go
 * to their own vector, rather than the general exception vectors (user,
 * kernel, double); and their specific causes are reported via DEBUGCAUSE
 * rather than EXCCAUSE.  However it is sometimes convenient to redirect debug
 * exceptions to the general exception mechanism.  To do this, an otherwise
 * unused EXCCAUSE value was assigned to debug exceptions for this purpose.
 */

#define EXCCAUSE_MAPPED_DEBUG	63

/*
 * We use DEPC also as a flag to distinguish between double and regular
 * exceptions. For performance reasons, DEPC might contain the value of
 * EXCCAUSE for regular exceptions, so we use this definition to mark a
 * valid double exception address.
 * (Note: We use it in bgeui, so it should be 64, 128, or 256)
 */

#define VALID_DOUBLE_EXCEPTION_ADDRESS	64

/* LOCKLEVEL defines the interrupt level that masks all
 * general-purpose interrupts.
 */
#define LOCKLEVEL XCHAL_EXCM_LEVEL

/* WSBITS and WBBITS are the width of the WINDOWSTART and WINDOWBASE
 * registers
 */
#define WSBITS  (XCHAL_NUM_AREGS / 4)      /* width of WINDOWSTART in bits */
#define WBBITS  (XCHAL_NUM_AREGS_LOG2 - 2) /* width of WINDOWBASE in bits */

#ifndef __ASSEMBLY__

/* Build a valid return address for the specified call winsize.
 * winsize must be 1 (call4), 2 (call8), or 3 (call12)
 */
#define MAKE_RA_FOR_CALL(ra,ws)   (((ra) & 0x3fffffff) | (ws) << 30)

/* Convert return address to a valid pc
 * Note: We assume that the stack pointer is in the same 1GB ranges as the ra
 */
#define MAKE_PC_FROM_RA(ra,sp)    (((ra) & 0x3fffffff) | ((sp) & 0xc0000000))

typedef struct {
	unsigned long seg;
} mm_segment_t;

struct thread_struct {

	/* kernel's return address and stack pointer for context switching */
	unsigned long ra; /* kernel's a0: return address and window call size */
	unsigned long sp; /* kernel's a1: stack pointer */

	mm_segment_t current_ds;    /* see uaccess.h for example uses */

	/* struct xtensa_cpuinfo info; */

	unsigned long bad_vaddr; /* last user fault */
	unsigned long bad_uaddr; /* last kernel fault accessing user space */
	unsigned long error_code;

	unsigned long ibreak[XCHAL_NUM_IBREAK];
	unsigned long dbreaka[XCHAL_NUM_DBREAK];
	unsigned long dbreakc[XCHAL_NUM_DBREAK];

	/* Make structure 16 bytes aligned. */
	int align[0] __attribute__ ((aligned(16)));
};

/*
 * Default implementation of macro that returns current
 * instruction pointer ("program counter").
 */
#define current_text_addr()  ({ __label__ _l; _l: &&_l;})

/* This decides where the kernel will search for a free chunk of vm
 * space during mmap's.
 */
#define TASK_UNMAPPED_BASE	(TASK_SIZE / 2)

#define INIT_THREAD  \
{									\
	ra:		0, 						\
	sp:		sizeof(init_stack) + (long) &init_stack,	\
	current_ds:	{0},						\
	/*info:		{0}, */						\
	bad_vaddr:	0,						\
	bad_uaddr:	0,						\
	error_code:	0,						\
}

/*
 * Do necessary setup to start up a newly executed thread.
 * Note: We set-up ps as if we did a call4 to the new pc.
 *       set_thread_state in signal.c depends on it.
 */
#define USER_PS_VALUE ((1 << PS_WOE_BIT) |				\
		       (1 << PS_CALLINC_SHIFT) |			\
		       (USER_RING << PS_RING_SHIFT) |			\
		       (1 << PS_UM_BIT) |				\
		       (1 << PS_EXCM_BIT))

/* Clearing a0 terminates the backtrace. */
#define start_thread(regs, new_pc, new_sp) \
	memset(regs, 0, sizeof(*regs)); \
	regs->pc = new_pc; \
	regs->ps = USER_PS_VALUE; \
	regs->areg[1] = new_sp; \
	regs->areg[0] = 0; \
	regs->wmask = 1; \
	regs->depc = 0; \
	regs->windowbase = 0; \
	regs->windowstart = 1;

/* Forward declaration */
struct task_struct;
struct mm_struct;

/* Free all resources held by a thread. */
#define release_thread(thread) do { } while(0)

/* Copy and release all segment info associated with a VM */
#define copy_segments(p, mm)	do { } while(0)
#define release_segments(mm)	do { } while(0)
#define forget_segments()	do { } while (0)

#define thread_saved_pc(tsk)	(task_pt_regs(tsk)->pc)

extern unsigned long get_wchan(struct task_struct *p);

#define KSTK_EIP(tsk)		(task_pt_regs(tsk)->pc)
#define KSTK_ESP(tsk)		(task_pt_regs(tsk)->areg[1])

#define cpu_relax()  barrier()

/* Special register access. */

#define WSR(v,sr) __asm__ __volatile__ ("wsr %0,"__stringify(sr) :: "a"(v));
#define RSR(v,sr) __asm__ __volatile__ ("rsr %0,"__stringify(sr) : "=a"(v));

#define set_sr(x,sr) ({unsigned int v=(unsigned int)x; WSR(v,sr);})
#define get_sr(sr) ({unsigned int v; RSR(v,sr); v; })

#ifndef XCHAL_HAVE_EXTERN_REGS
#define XCHAL_HAVE_EXTERN_REGS 0
#endif

#if XCHAL_HAVE_EXTERN_REGS

static inline void set_er(unsigned long value, unsigned long addr)
{
	asm volatile ("wer %0, %1" : : "a" (value), "a" (addr) : "memory");
}

static inline unsigned long get_er(unsigned long addr)
{
	register unsigned long value;
	asm volatile ("rer %0, %1" : "=a" (value) : "a" (addr) : "memory");
	return value;
}

#endif /* XCHAL_HAVE_EXTERN_REGS */

#endif	/* __ASSEMBLY__ */
#endif	/* _XTENSA_PROCESSOR_H */


text:
package org.apache.kafka.streams.processor.internals;

import org.apache.kafka.common.utils.LogContext;
import org.apache.kafka.streams.internals.StreamsConfigUtils.ProcessingMode;
import org.apache.kafka.streams.processor.TaskId;

import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;

import static org.apache.kafka.streams.processor.internals.TopologyMetadata.UNNAMED_TOPOLOGY;

/**
 * Multi-threaded class that tracks the status of active tasks being processed. A single instance of this class is
 * shared between all StreamThreads.
 */
public class TaskExecutionMetadata {
    // TODO: implement exponential backoff, for now we just wait 5s
    private static final long CONSTANT_BACKOFF_MS = 5_000L;

    private final boolean hasNamedTopologies;
    private final Set<String> pausedTopologies;
    private final ProcessingMode processingMode;
    private final Collection<Task> successfullyProcessed = new HashSet<>();
    // map of topologies experiencing errors/currently under backoff
    private final ConcurrentHashMap<String, NamedTopologyMetadata> topologyNameToErrorMetadata = new ConcurrentHashMap<>();

    public TaskExecutionMetadata(final Set<String> allTopologyNames,
                                 final Set<String> pausedTopologies,
                                 final ProcessingMode processingMode) {
        this.hasNamedTopologies = !(allTopologyNames.size() == 1 && allTopologyNames.contains(UNNAMED_TOPOLOGY));
        this.pausedTopologies = pausedTopologies;
        this.processingMode = processingMode;
    }

    public boolean hasNamedTopologies() {
        return hasNamedTopologies;
    }

    public ProcessingMode processingMode() {
        return processingMode;
    }

    public boolean canProcessTask(final Task task, final long now) {
        final String topologyName = task.id().topologyName();
        if (!hasNamedTopologies) {
            // TODO implement error handling/backoff for non-named topologies (needs KIP)
            return !pausedTopologies.contains(UNNAMED_TOPOLOGY);
        } else {
            if (pausedTopologies.contains(topologyName)) {
                return false;
            } else {
                final NamedTopologyMetadata metadata = topologyNameToErrorMetadata.get(topologyName);
                return metadata == null || (metadata.canProcess() && metadata.canProcessTask(task, now));
            }
        }
    }

    public boolean canPunctuateTask(final Task task) {
        final String topologyName = task.id().topologyName();

        if (topologyName == null) {
            return !pausedTopologies.contains(UNNAMED_TOPOLOGY);
        } else {
            return !pausedTopologies.contains(topologyName);
        }
    }

    public void registerTaskError(final Task task, final Throwable t, final long now) {
        if (hasNamedTopologies) {
            final String topologyName = task.id().topologyName();
            topologyNameToErrorMetadata.computeIfAbsent(topologyName, n -> new NamedTopologyMetadata(topologyName))
                .registerTaskError(task, t, now);
        }
    }

    Collection<Task> successfullyProcessed() {
        return successfullyProcessed;
    }

    void addToSuccessfullyProcessed(final Task task) {
        successfullyProcessed.add(task);
    }

    void removeTaskFromSuccessfullyProcessedBeforeClosing(final Task task) {
        successfullyProcessed.remove(task);
    }

    void clearSuccessfullyProcessed() {
        successfullyProcessed.clear();
    }

    private class NamedTopologyMetadata {
        private final Logger log;
        private final Map<TaskId, Long> tasksToErrorTime = new ConcurrentHashMap<>();

        public NamedTopologyMetadata(final String topologyName) {
            final LogContext logContext = new LogContext(String.format("topology-name [%s] ", topologyName));
            this.log = logContext.logger(NamedTopologyMetadata.class);
        }

        public boolean canProcess() {
            // TODO: during long task backoffs, pause the full topology to avoid it getting out of sync
            return true;
        }

        public boolean canProcessTask(final Task task, final long now) {
            final Long errorTime = tasksToErrorTime.get(task.id());
            if (errorTime == null) {
                return true;
            } else if (now - errorTime > CONSTANT_BACKOFF_MS) {
                log.info("End backoff for task {} at t={}", task.id(), now);
                tasksToErrorTime.remove(task.id());
                if (tasksToErrorTime.isEmpty()) {
                    topologyNameToErrorMetadata.remove(task.id().topologyName());
                }
                return true;
            } else {
                log.debug("Skipping processing for unhealthy task {} at t={}", task.id(), now);
                return false;
            }
        }

        public synchronized void registerTaskError(final Task task, final Throwable t, final long now) {
            log.info("Begin backoff for unhealthy task {} at t={} due to {}", task.id(), now, t.getClass().getName());
            tasksToErrorTime.put(task.id(), now);
        }
    }
}


text:
from rest_framework import serializers
from project.organisations.models import Organisation, Membership
from project.accounts.serializers import UserProfileSerializer

class MembershipSerializer(serializers.ModelSerializer):
    class Meta:
        model = Membership
        fields = ('joined', 'is_owner', 'role')

class CreateOrganisationSerializer(serializers.ModelSerializer):
    membership_set = MembershipSerializer(many=True)

    class Meta:
        model = Organisation
        fields = ('name', 'slug', 'membership_set')

class OrganisationMembersSerializer(serializers.ModelSerializer):
    user = serializers.SerializerMethodField()

    class Meta:
        model = Membership
        fields = ('joined', 'user', 'is_owner', 'role')

    def get_user(self, obj):
        serializer = UserProfileSerializer(obj.user)
        return serializer.data

class OrganisationDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = Organisation
        fields = ('name', 'slug', 'is_active')

class RetrieveOrganisationSerializer(serializers.ModelSerializer):
    membership_set = MembershipSerializer()

    class Meta:
        model = Organisation
        fields = ('name', 'slug', 'is_active', 'membership_set')


text:
"""Auth utils tests"""
from open_discussions.auth_utils import (
    get_encoded_and_signed_subscription_token,
    unsign_and_verify_username_from_token,
)

def test_get_encoded_and_signed_subscription_token(user):
    """Tests that get_encoded_and_signed_subscription_token returns a token"""
    assert get_encoded_and_signed_subscription_token(user) is not None

def test_unsign_and_verify_username_from_token(user):
    """Tests that unsign_and_verify_username_from_token returns the encoded username"""
    token = get_encoded_and_signed_subscription_token(user)
    assert unsign_and_verify_username_from_token(token) == user.username


text:
/*----------------------------------------------------------------------------*\
  MODULE NAME: controls.h
      PROJECT: F3DB
       AUTHOR: Evert Bauwens
         DATE: september 8 2003
  DESCRIPTION:
\*----------------------------------------------------------------------------*/
#ifndef F3DB_CONTROLS_H
#define F3DB_CONTROLS_H
#include "types.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <dinput.h>
#include <d3dx9math.h>
#include "graphics.h"

namespace F3DB {

	enum MouseButton {
		F3DB_LMB = 0,
		F3DB_MMB = 2,
		F3DB_RMB = 1,
	};

	class Controls {

	public:

		Controls(Graphics *graphics);
		~Controls();

		void Init(Graphics *graphics = null);
		void CleanUp();
		void Reset(Graphics *graphics);

		void Update();

		bool IsKeyDown(uint8 key);
		bool IsMouseButtonDown(MouseButton button);
		D3DXVECTOR3 GetMousePosition();

	private:

		Graphics *graphics;
		HWND hWnd;
		HRESULT res;
		IDirectInput *di;
		IDirectInputDevice *diKeybourd, *diMouse;
		uint8 keys[256];
		DIMOUSESTATE mouseState;
		D3DXVECTOR3 mousePos;
	};

}

#endif // F3DB_CONTROLS_H


text:
echo "start the postgresql db"
gosu postgres /usr/bin/pg_ctl -D /var/lib/postgresql/data -l /var/lib/postgresql/data/logfile start