text:
using Newtonsoft.Json;
using System;

namespace ShopifySharp
{
    /// <summary>
    /// An object representing a physical store location.
    /// </summary>
    public class Location : ShopifyObject
    {
        /// <summary>
        /// Whether the location is active.
        /// </summary>
        [JsonProperty("active")]
        public bool? Active { get; set; }

        /// <summary>
        /// The name of the location.
        /// </summary>
        [JsonProperty("name")]
        public string Name { get; set; }

        /// <summary>
        /// The first line of the address.
        /// </summary>
        [JsonProperty("address1")]
        public string Address1 { get; set; }

        /// <summary>
        /// The second line of the address.
        /// </summary>
        [JsonProperty("address2")]
        public string Address2 { get; set; }

        /// <summary>
        /// The zip or postal code.
        /// </summary>
        [JsonProperty("zip")]
        public string Zip { get; set; }

        /// <summary>
        /// The city the location is in.
        /// </summary>
        [JsonProperty("city")]
        public string City { get; set; }

        /// <summary>
        /// The province the location is in.
        /// </summary>
        [JsonProperty("province")]
        public string Province { get; set; }

        /// <summary>
        /// The code of the province the location is in.
        /// </summary>
        [JsonProperty("province_code")]
        public string ProvinceCode { get; set; }

        /// <summary>
        /// The country the location is in.
        /// </summary>
        [JsonProperty("country")]
        public string Country { get; set; }

        /// <summary>
        /// The name of the country the location is in.
        /// </summary>
        [JsonProperty("country_name")]
        public string CountryName { get; set; }

        /// <summary>
        /// The code of the country the location is in.
        /// </summary>
        [JsonProperty("country_code")]
        public string CountryCode { get; set; }

        /// <summary>
        /// The phone number of the location. Can contain special chars like - and +.
        /// </summary>
        [JsonProperty("phone")]
        public string Phone { get; set; }

        /// <summary>
        /// The date and time when the location was created.
        /// </summary>
        [JsonProperty("created_at")]
        public DateTimeOffset? CreatedAt { get; set; }

        /// <summary>
        /// The date and time when the location was last updated.
        /// </summary>
        [JsonProperty("updated_at")]
        public DateTimeOffset? UpdatedAt { get; set; }

        /// <summary>
        /// Whether this is a fulfillment service location. If true, then the location is a fulfillment service location. If false, then the location was created by the merchant and isn't tied to a fulfillment service.
        /// </summary>
        [JsonProperty("legacy")]
        public bool? Legacy { get; set; }

        /// <summary>
        /// The localized name of the location's country.
        /// </summary>
        [JsonProperty("localized_country_name")]
        public string LocalizedCountryName { get; set; }

        /// <summary>
        /// The localized name of the location's region. Typically a province, state, or prefecture.
        /// </summary>
        [JsonProperty("localized_province_name")]
        public string LocalizedProvinceName { get; set; }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.basepom.mojo.duplicatefinder;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.nullToEmpty;

import static org.basepom.mojo.duplicatefinder.artifact.ArtifactHelper.isJarArtifact;
import static org.basepom.mojo.duplicatefinder.artifact.ArtifactHelper.isTestArtifact;

import java.io.File;
import java.util.Objects;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Ordering;

import org.apache.maven.artifact.Artifact;

/**
 * Describes any of the possible elements on the classpath. These can be elements from the boot classpath, artifacts and local
 * folder from the current project. For each of the possible types exists a subclass which holds additional information.
 */
public abstract class ClasspathElement implements Comparable<ClasspathElement>
{
    public abstract String getName();

    public File getFile()
    {
        throw new UnsupportedOperationException();
    }

    public Artifact getArtifact()
    {
        throw new UnsupportedOperationException();
    }

    public boolean isBootClasspathElement()
    {
        return false;
    }

    public boolean isLocalFolder()
    {
        return false;
    }

    public boolean hasArtifact()
    {
        return false;
    }

    @Override
    public int compareTo(ClasspathElement element)
    {
        return Ordering.natural().compare(this.getName(), element.getName());
    }

    public static final class ClasspathArtifact extends ClasspathElement
    {
        private final Artifact artifact;

        public ClasspathArtifact(final Artifact artifact)
        {
            this.artifact = checkNotNull(artifact, "artifact is null");
        }

        @Override
        public String getName()
        {
            return Joiner.on(':').skipNulls().join(artifact.getGroupId(),
                artifact.getArtifactId(),
                artifact.getVersion(),
                getType(artifact),
                getClassifier(artifact));
        }

        private String getType(final Artifact artifact)
        {
            if (isJarArtifact(artifact)) {
                // when the classifier is null but the type is jar, return null
                // so that in the Joiner expression both the type and classifier
                // are null and none is printed.
                return nullToEmpty(artifact.getClassifier()).isEmpty() ? null : "jar";
            }

            return artifact.getType();
        }

        private String getClassifier(final Artifact artifact)
        {
            if (nullToEmpty(artifact.getClassifier()).isEmpty()) {
                return null;
            }
            else if (isTestArtifact(artifact)) {
                return "tests";
            }

            return artifact.getClassifier();
        }

        @Override
        public boolean hasArtifact()
        {
            return true;
        }

        @Override
        public Artifact getArtifact()
        {
            return artifact;
        }

        @Override
        public int hashCode()
        {
            return Objects.hash(artifact);
        }

        @Override
        public boolean equals(Object o)
        {
            if (o == null || o.getClass() != this.getClass()) {
                return false;
            }

            if (o == this) {
                return true;
            }

            ClasspathArtifact that = (ClasspathArtifact) o;

            return Objects.equals(this.artifact, that.artifact);
        }
    }

    public static final class ClasspathLocalFolder extends ClasspathElement
    {
        private final File localFolder;

        public ClasspathLocalFolder(final File localFolder)
        {
            this.localFolder = checkNotNull(localFolder, "localFolder is null");
            checkState(localFolder.isDirectory(), "localFolder must be a directory");
        }

        @Override
        public String getName()
        {
            return localFolder.getAbsolutePath();
        }

        @Override
        public boolean isLocalFolder()
        {
            return true;
        }

        @Override
        public File getFile()
        {
            return localFolder;
        }

        @Override
        public int hashCode()
        {
            return Objects.hashCode(localFolder);
        }

        @Override
        public boolean equals(Object o)
        {
            if (o == null || o.getClass() != this.getClass()) {
                return false;
            }

            if (o == this) {
                return true;
            }

            ClasspathLocalFolder that = (ClasspathLocalFolder) o;

            return Objects.equals(this.localFolder, that.localFolder);
        }
    }

    public static class ClasspathBootClasspathElement extends ClasspathElement
    {
        private final File bootClasspathElement;

        public ClasspathBootClasspathElement(final File bootClasspathElement)
        {
            this.bootClasspathElement = checkNotNull(bootClasspathElement, "bootClasspathElement is null");
        }

        @Override
        public boolean isBootClasspathElement()
        {
            return true;
        }

        @Override
        public String getName()
        {
            return bootClasspathElement.getAbsolutePath();
        }

        @Override
        public File getFile()
        {
            return bootClasspathElement;
        }

        @Override
        public int hashCode()
        {
            return Objects.hashCode(bootClasspathElement);
        }

        @Override
        public boolean equals(Object o)
        {
            if (o == null || o.getClass() != this.getClass()) {
                return false;
            }

            if (o == this) {
                return true;
            }

            ClasspathBootClasspathElement that = (ClasspathBootClasspathElement) o;

            return Objects.equals(this.bootClasspathElement, that.bootClasspathElement);
        }
    }

    public static Function<ClasspathElement, String> getNameFunction()
    {
        return ClasspathElement::getName;
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'date_structure'
require 'file_attache_structure'

class Place < ActiveRecord::Base
  include DateStructure
  include FileAttacheStructure

  attr_accessible :category_id, :description, :galery_id, :name, :address_id, :type_id, :web_links, :address, :address_attributes

  belongs_to :type
  belongs_to :category
  belongs_to :address
  accepts_nested_attributes_for :address

  validates :description, :presence => true #,
  validates :name, :presence => true #,
  validates :address, :presence => true #,
  validates :type_id, :presence => true #,
  validates :category_id, :presence => true #,

  def get_map_info
    item = self.address.get_info
    item['title'] = self.name
    item
  end

  def self.get_info_for_all ids
    elems = self.includes(:address).where(:id => ids)
    result = []
    elems.each do |elem|
      result << elem.get_map_info
    end
    result
  end
end


text:
using System.Xml.Serialization;

namespace SvnBridge.Protocol
{
    public class TxDeltaData
    {
        [XmlText(DataType = "string")] public string Data = null;

        public TxDeltaData()
        {
        }
    }
}


text:
import { getMinScheduleTime } from './schedule';

describe('getMinScheduleTime', () => {
    afterEach(() => {
        jest.useRealTimers();
    });

    it('should get the correct min scheduled time if selected date is not today', () => {
        const fakeNow = new Date(2021, 0, 1, 9, 20, 0);
        jest.useFakeTimers('modern').setSystemTime(fakeNow.getTime());

        // Date which is currently selected is not today
        const date = new Date(2021, 0, 5, 9, 20, 0);
        const minTimeDate = getMinScheduleTime(date);

        // We expect the function to return undefined because if not today,
        // there is no min time (we want the whole interval from 00:00 to 23:30)
        const expectedMinTimeDate = undefined;

        expect(minTimeDate).toEqual(expectedMinTimeDate);
    });

    it('should get the correct min scheduled time if time < XX:30 and still in 2 minutes limit', () => {
        const fakeNow = new Date(2021, 0, 1, 9, 20, 0);
        jest.useFakeTimers('modern').setSystemTime(fakeNow.getTime());

        const minTimeDate = getMinScheduleTime(fakeNow);
        const expectedMinTimeDate = new Date(2021, 0, 1, 9, 30, 0);

        expect(minTimeDate).toEqual(expectedMinTimeDate);
    });

    it('should get the correct min scheduled time if time < XX:30 and not in 2 minutes limit', () => {
        const fakeNow = new Date(2021, 0, 1, 9, 28, 30);
        jest.useFakeTimers('modern').setSystemTime(fakeNow.getTime());

        const minTimeDate = getMinScheduleTime(fakeNow);

        // We cannot schedule a message within the next 2 minutes, so if it's 9:28, we should return 10:00
        const expectedMinTimeDate = new Date(2021, 0, 1, 10, 0, 0);

        expect(minTimeDate).toEqual(expectedMinTimeDate);
    });

    it('should get the correct min scheduled time if time > XX:30 and still in 2 minutes limit', () => {
        const fakeNow = new Date(2021, 0, 1, 9, 55, 0);
        jest.useFakeTimers('modern').setSystemTime(fakeNow.getTime());

        const minTimeDate = getMinScheduleTime(fakeNow);
        const expectedMinTimeDate = new Date(2021, 0, 1, 10, 0, 0);

        expect(minTimeDate).toEqual(expectedMinTimeDate);
    });

    it('should get the correct min scheduled time if time > XX:30 and not in 2 minutes limit', () => {
        const fakeNow = new Date(2021, 0, 1, 9, 58, 30);
        jest.useFakeTimers('modern').setSystemTime(fakeNow.getTime());

        const minTimeDate = getMinScheduleTime(fakeNow);

        // We cannot schedule a message within the next 2 minutes, so if it's 9:58, we should return 10:30
        const expectedMinTimeDate = new Date(2021, 0, 1, 10, 30, 0);

        expect(minTimeDate).toEqual(expectedMinTimeDate);
    });
});


text:
import warnings

from django.conf.urls import patterns, url, include
from django.utils.deprecation import RemovedInDjango20Warning

from .namespace_urls import URLObject
from .views import view_class_instance

testobj3 = URLObject('testapp', 'test-ns3')

# test deprecated patterns() function. convert to list of urls() in Django 2.0
with warnings.catch_warnings():
    warnings.filterwarnings('ignore', category=RemovedInDjango20Warning)

    urlpatterns = patterns('urlpatterns_reverse.views',
        url(r'^normal/$', 'empty_view', name='inc-normal-view'),
        url(r'^normal/(?P<arg1>[0-9]+)/(?P<arg2>[0-9]+)/$', 'empty_view', name='inc-normal-view'),

        url(r'^\+\\\$\*/$', 'empty_view', name='inc-special-view'),

        url(r'^mixed_args/([0-9]+)/(?P<arg2>[0-9]+)/$', 'empty_view', name='inc-mixed-args'),
        url(r'^no_kwargs/([0-9]+)/([0-9]+)/$', 'empty_view', name='inc-no-kwargs'),

        url(r'^view_class/(?P<arg1>[0-9]+)/(?P<arg2>[0-9]+)/$', view_class_instance, name='inc-view-class'),

        (r'^test3/', include(testobj3.urls)),
        (r'^ns-included3/', include('urlpatterns_reverse.included_urls', namespace='inc-ns3')),
        (r'^ns-included4/', include('urlpatterns_reverse.namespace_urls', namespace='inc-ns4')),
    )


text:
using System.Windows.Controls;
using DevExpress.Internal;
using DevExpress.Mvvm.UI.Native;
using NUnit.Framework;
using System;
using System.IO.Packaging;
using System.Linq;
using System.Security.Permissions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace DevExpress.Mvvm.UI.Tests {
    [TestFixture]
    public class NotificationTests {
        [TearDown]
        public void TearDown() {
            if(CustomNotifier.positioner != null) {
                Assert.AreEqual(0, CustomNotifier.positioner.Items.Count(i => i != null));
            }
        }

        [Test]
        public void PositionerTest() {
            var pos = new NotificationPositioner<string>();
            pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.TopRight, 3);
            Point p;

            Assert.AreEqual(true, pos.HasEmptySlot());

            p = pos.Add("item1", 200, 50);
            Assert.AreEqual(800 - 200, p.X);
            Assert.AreEqual(20, p.Y);

            p = pos.Add("item2", 200, 50);
            Assert.AreEqual(800 - 200, p.X);
            Assert.AreEqual(20 + 50 + 10, p.Y);

            p = pos.Add("item3", 200, 50);
            Assert.AreEqual(800 - 200, p.X);
            Assert.AreEqual(20 + 50 + 10 + 50 + 10, p.Y);

            Assert.AreEqual(false, pos.HasEmptySlot());

            pos.Remove("item2");
            p = pos.Add("item4", 200, 50);
            Assert.AreEqual(800 - 200, p.X);
            Assert.AreEqual(20 + 50 + 10, p.Y);

            pos.Remove("item3");
            p = pos.Add("item5", 200, 50);
            Assert.AreEqual(800 - 200, p.X);
            Assert.AreEqual(20 + 50 + 10 + 50 + 10, p.Y);

            Assert.AreEqual(false, pos.HasEmptySlot());
            pos.Remove("item1");
            Assert.AreEqual(true, pos.HasEmptySlot());

            pos = new NotificationPositioner<string>();
            pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.BottomRight, 3);
            p = pos.Add("item1", 200, 50);
            Assert.AreEqual(800 - 200, p.X);
            Assert.AreEqual(600 - 50 - 20, p.Y);

            p = pos.Add("item2", 200, 50);
            Assert.AreEqual(800 - 200, p.X);
            Assert.AreEqual(600 - 50 - 20 - 50 - 10, p.Y);

            p = pos.Add("item3", 200, 50);
            Assert.AreEqual(800 - 200, p.X);
            Assert.AreEqual(600 - 50 - 20 - 50 - 10 - 50 - 10, p.Y);

            Assert.AreEqual(false, pos.HasEmptySlot());

            pos.Remove("item2");
            p = pos.Add("item4", 200, 50);
            Assert.AreEqual(800 - 200, p.X);
            Assert.AreEqual(600 - 50 - 20 - 50 - 10, p.Y);

            pos.Remove("item3");
            p = pos.Add("item5", 200, 50);
            Assert.AreEqual(800 - 200, p.X);
            Assert.AreEqual(600 - 50 - 20 - 50 - 10 - 50 - 10, p.Y);

            Assert.AreEqual(false, pos.HasEmptySlot());
            pos.Remove("item1");
            Assert.AreEqual(true, pos.HasEmptySlot());
        }

        [Test]
        public void PositionerTest2() {
            var pos = new NotificationPositioner<string>();
            pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.TopRight, 100);
            pos.Add("item1", 200, 480);
            Assert.AreEqual(false, pos.HasEmptySlot());

            pos = new NotificationPositioner<string>();
            pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.TopRight, 100);
            pos.Add("item1", 200, 460);
            Assert.AreEqual(false, pos.HasEmptySlot());

            pos = new NotificationPositioner<string>();
            pos.Update(new Rect(0, 0, 800, 250), NotificationPosition.TopRight, 100);
            pos.Add("item1", 200, 100);
            pos.Add("item1", 200, 100);
            Assert.AreEqual(false, pos.HasEmptySlot());

            pos = new NotificationPositioner<string>();
            pos.Update(new Rect(0, 0, 800, 360), NotificationPosition.TopRight, 100);
            pos.Add("item1", 200, 100);
            pos.Add("item1", 200, 100);
            Assert.AreEqual(true, pos.HasEmptySlot());
        }

        [Test]
        public void PositionerTest3() {
            var pos = new NotificationPositioner<string>();
            pos.Update(new Rect(10, 25, 790, 575), NotificationPosition.TopRight, 100);
            Point p = pos.Add("item1", 200, 100);
            Assert.AreEqual(10 + 790 - 200, p.X);
            Assert.AreEqual(25 + 20, p.Y);

            pos = new NotificationPositioner<string>();
            pos.Update(new Rect(10, 25, 790, 575), NotificationPosition.BottomRight, 100);
            p = pos.Add("item1", 200, 100);
            Assert.AreEqual(10 + 790 - 200, p.X);
            Assert.AreEqual(600 - 20 - 100, p.Y);
        }

        [Test]
        public void PositionerTest4() {
            var pos = new NotificationPositioner<string>();
            pos.Update(new Rect(0, 50, 800, 650), NotificationPosition.TopRight, 100);
            pos.Add("item1", 200, 480);
            Assert.AreEqual(false, pos.HasEmptySlot());

            pos = new NotificationPositioner<string>();
            pos.Update(new Rect(0, 50, 800, 650), NotificationPosition.TopRight, 100);
            pos.Add("item1", 200, 460);
            Assert.AreEqual(false, pos.HasEmptySlot());

            pos = new NotificationPositioner<string>();
            pos.Update(new Rect(0, 50, 800, 300), NotificationPosition.TopRight, 100);
            pos.Add("item1", 200, 100);
            pos.Add("item1", 200, 100);
            Assert.AreEqual(false, pos.HasEmptySlot());

            pos = new NotificationPositioner<string>();
            pos.Update(new Rect(0, 50, 800, 410), NotificationPosition.TopRight, 100);
            pos.Add("item1", 200, 100);
            pos.Add("item1", 200, 100);
            Assert.AreEqual(true, pos.HasEmptySlot());
        }

        [Test]
        public void PositionerHasSlotTest() {
            var pos = new NotificationPositioner<string>();
            pos.Update(new Rect(0, 50, 800, 650), NotificationPosition.TopRight, 3);
            pos.Add("item1", 200, 100);
            Assert.AreEqual(true, pos.HasEmptySlot());
            pos.Remove("item1");
            Assert.AreEqual(true, pos.HasEmptySlot());
            pos.Add("item2", 200, 100);
            Assert.AreEqual(true, pos.HasEmptySlot());
            pos.Add("item3", 200, 100);
            Assert.AreEqual(true, pos.HasEmptySlot());
            pos.Add("item4", 200, 100);
            Assert.AreEqual(false, pos.HasEmptySlot());
        }

        static void WaitWithDispatcher(Task<NotificationResult> task) {
            while(task.Status != TaskStatus.RanToCompletion && task.Status != TaskStatus.Faulted) {
                DispatcherUtil.DoEvents();
            }
        }

        public static class DispatcherUtil {
            [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
            public static void DoEvents() {
                DispatcherFrame frame = new DispatcherFrame();
                Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
                    new DispatcherOperationCallback(ExitFrame), frame);
                Dispatcher.PushFrame(frame);
                System.Windows.Forms.Application.DoEvents();
            }

            private static object ExitFrame(object frame) {
                ((DispatcherFrame)frame).Continue = false;
                return null;
            }
        }

        [Test]
        public void ResultsTest() {
            CustomNotification toast;
            Task<NotificationResult> task;
            var notifier = new CustomNotifier();

            toast = new CustomNotification(null, notifier);
            task = notifier.ShowAsync(toast, 1);
            WaitWithDispatcher(task);
            Assert.AreEqual(NotificationResult.TimedOut, task.Result);

            toast = new CustomNotification(null, notifier);
            task = notifier.ShowAsync(toast, 1);
            toast.Activate();
            WaitWithDispatcher(task);
            Assert.AreEqual(NotificationResult.Activated, task.Result);

            toast = new CustomNotification(null, notifier);
            task = notifier.ShowAsync(toast, 1);
            toast.Dismiss();
            WaitWithDispatcher(task);
            Assert.AreEqual(NotificationResult.UserCanceled, task.Result);

            toast = new CustomNotification(null, notifier);
            task = notifier.ShowAsync(toast, 1);
            toast.Hide();
            WaitWithDispatcher(task);
            Assert.AreEqual(NotificationResult.ApplicationHidden, task.Result);

            var tasks = Enumerable.Range(0, 10).Select(_ => notifier.ShowAsync(new CustomNotification(null, notifier), 1)).ToList();
            tasks.ToList().ForEach(WaitWithDispatcher);
            tasks.ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
        }

        [Test]
        public void UpdatingPositionerTest() {
            CustomNotification toast;
            Task<NotificationResult> task;
            var notifier = new CustomNotifier();
            var tasks = Enumerable.Range(0, 5).Select(_ => notifier.ShowAsync(new CustomNotification(null, notifier), 1)).ToList();
            tasks.ToList().ForEach(WaitWithDispatcher);
            tasks.ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));

            toast = new CustomNotification(null, notifier);
            task = notifier.ShowAsync(toast, 1);
            notifier.UpdatePositioner(NotificationPosition.TopRight, 2);
            WaitWithDispatcher(task);
            Assert.AreEqual(NotificationResult.TimedOut, task.Result);
            tasks = Enumerable.Range(0, 10).Select(_ => notifier.ShowAsync(new CustomNotification(null, notifier), 1)).ToList();
            notifier.UpdatePositioner(NotificationPosition.TopRight, 2);
            tasks.ToList().ForEach(WaitWithDispatcher);
            tasks.ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
        }

        [Test]
        public void ShowingTooManyToastsTest() {
            var notifier = new CustomNotifier();
            notifier.UpdatePositioner(NotificationPosition.TopRight, 100);

            var tasks = Enumerable.Range(0, 100).Select(_ => notifier.ShowAsync(new CustomNotification(null, notifier), 1)).ToList();
            tasks.ToList().ForEach(WaitWithDispatcher);
            tasks.ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
        }

        [Test]
        public void SettingApplicationIDToNullTest() {
            var service = new NotificationService();
            service.ApplicationId = "";
            service.ApplicationId = null;
            Assert.IsTrue(true);
        }

        [Test]
        public void RemovePostponedNotificationTest() {
            var notifier = new CustomNotifier();
            notifier.UpdatePositioner(NotificationPosition.TopRight, 1);

            var toasts = Enumerable.Range(0, 3).Select(_ => new CustomNotification(null, notifier)).ToList();
            var tasks = toasts.Select(toast => notifier.ShowAsync(toast, 1)).ToList();
            toasts[2].Hide();
            tasks.ToList().ForEach(WaitWithDispatcher);
            Assert.AreEqual(NotificationResult.TimedOut, tasks[0].Result);
            Assert.AreEqual(NotificationResult.TimedOut, tasks[1].Result);
            Assert.AreEqual(NotificationResult.ApplicationHidden, tasks[2].Result);
        }

        class TestScreen : IScreen {
            public Rect bounds;
            public Rect GetWorkingArea() {
                return bounds;
            }
            public void Changed() {
                if(WorkingAreaChanged != null)
                    WorkingAreaChanged();
            }
            public event Action WorkingAreaChanged;
        }

        [Test]
        public void BasicResolutionChangedHandlingTest() {
            var testScreen = new TestScreen { bounds = new Rect(0, 0, 1000, 500) };
            var notifier = new CustomNotifier(testScreen);
            notifier.UpdatePositioner(NotificationPosition.BottomRight, 2);
            var toasts = Enumerable.Range(0, 3).Select(_ => new CustomNotification(null, notifier)).ToList();
            var tasks = toasts.Select(toast => notifier.ShowAsync(toast, 1)).ToList();

            var pos = CustomNotifier.positioner;
            var ps = pos.Items.Select(i => pos.GetItemPosition(i)).ToList();
            Assert.AreEqual(new Point(615, 390), ps[0]);
            Assert.AreEqual(new Point(615, 290), ps[1]);

            testScreen.bounds = new Rect(0, 0, 800, 600);
            testScreen.Changed();
            pos = CustomNotifier.positioner;
            ps = pos.Items.Select(i => pos.GetItemPosition(i)).ToList();
            Assert.AreEqual(new Point(415, 490), ps[0]);
            Assert.AreEqual(new Point(415, 390), ps[1]);

            tasks.ToList().ForEach(WaitWithDispatcher);
            tasks.ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
        }

        [Test]
        public void NotificationsArentLostOnPositionerUpdateTest() {
            var testScreen = new TestScreen { bounds = new Rect(0, 0, 1000, 500) };
            var notifier1 = new CustomNotifier(testScreen);
            var notifier2 = new CustomNotifier(testScreen);
            var positioner = CustomNotifier.positioner;
            notifier1.UpdatePositioner(NotificationPosition.BottomRight, 5);
            var toasts1 = Enumerable.Range(0, 1).Select(_ => new CustomNotification(null, notifier1)).ToList();
            var toasts2 = Enumerable.Range(0, 1).Select(_ => new CustomNotification(null, notifier2)).ToList();
            var tasks1 = toasts1.Select(toast => notifier1.ShowAsync(toast, 1)).ToList();
            var tasks2 = toasts2.Select(toast => notifier2.ShowAsync(toast, 1)).ToList();
            tasks1.Union(tasks2).ToList().ForEach(WaitWithDispatcher);
            tasks1.Union(tasks2).ToList().ForEach(t => Assert.AreEqual(NotificationResult.TimedOut, t.Result));
        }

        [Test]
        public void UpdatePositionerTest() {
            var testScreen = new TestScreen { bounds = new Rect(0, 0, 800, 600) };
            var notifier = new CustomNotifier(testScreen);
            var pos = CustomNotifier.positioner;

            var toast = new CustomNotification(null, notifier);
            var task = notifier.ShowAsync(toast, 1);
            var p1 = CustomNotifier.positioner.GetItemPosition(CustomNotifier.positioner.Items[0]);
            Assert.AreEqual(415, p1.X);
            Assert.AreEqual(20, p1.Y);

            notifier.UpdatePositioner(NotificationPosition.BottomRight, 3);
            p1 = CustomNotifier.positioner.GetItemPosition(CustomNotifier.positioner.Items[0]);
            Assert.AreEqual(415, p1.X);
            Assert.AreEqual(490, p1.Y);

            WaitWithDispatcher(task);
        }

        [Test]
        public void ResolutionChangingTest() {
            var testScreen = new TestScreen { bounds = new Rect(0, 0, 1000, 500) };
            var notifier = new CustomNotifier(testScreen);
            notifier.UpdatePositioner(NotificationPosition.BottomRight, 2);
            var toasts = Enumerable.Range(0, 3).Select(_ => new CustomNotification(null, notifier)).ToList();
            var tasks = toasts.Select(toast => notifier.ShowAsync(toast, 1)).ToList();

            Assert.AreEqual(2, CustomNotifier.positioner.Items.Count(i => i != null));

            testScreen.bounds = new Rect(0, 0, 800, 600);
            testScreen.Changed();

            Assert.AreEqual(2, CustomNotifier.positioner.Items.Count(i => i != null));

            tasks.ToList().ForEach(WaitWithDispatcher);
        }

        [Test]
        public void PositionUpdateTest() {
            var pos = new NotificationPositioner<string>();
            pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.TopRight, 3);
            Point p;

            p = pos.Add("item1", 200, 50);
            Assert.AreEqual(800 - 200, p.X);
            Assert.AreEqual(20, p.Y);

            pos.Update(new Rect(0, 0, 800, 600), NotificationPosition.BottomRight, 3);

            p = pos.GetItemPosition("item1");
            Assert.AreEqual(800 - 200, p.X);
            Assert.AreEqual(600 - 20 - 50, p.Y);
        }

        [Test]
        public void GetBackgroundTest() {
            string _ = PackUriHelper.UriSchemePack;
            Action<byte, byte, byte, string> assertMatch = (r, g, b, icon) => {
                string path = string.Format("pack://application:,,,/{0};component/Icons/{1}", "DevExpress.Mvvm.Tests.Free", icon);
                Uri uri = new Uri(path, UriKind.Absolute);
                var bmp = new System.Drawing.Bitmap(Application.GetResourceStream(uri).Stream);
                Assert.AreEqual(System.Windows.Media.Color.FromRgb(r, g, b), BackgroundCalculator.GetBestMatch(bmp));
            };
            assertMatch(9, 74, 178, "icon1.ico");
            assertMatch(210, 71, 38, "icon2.ico");
            assertMatch(81, 51, 171, "icon3.ico");
            assertMatch(210, 71, 38, "icon4.ico");
            assertMatch(81, 51, 171, "icon5.ico");
            assertMatch(0, 130, 153, "icon6.ico");
            assertMatch(9, 74, 178, "icon7.ico");
        }

        [Test]
        public void ThrowOnApplicationIDNullTest() {
            var service = new NotificationService();
            if(!service.AreWin8NotificationsAvailable)
                return;
            try {
                service.CreatePredefinedNotification("", "", "");
                Assert.Fail();
            } catch(ArgumentNullException e) {
                Assert.AreEqual("ApplicationId", e.ParamName);
            }
        }

        [Test]
        public void UpdateCustomToastPositionTest() {
            var service = new NotificationService();
            var toast = service.CreateCustomNotification(null);
            Assert.AreEqual(NotificationPosition.TopRight, CustomNotifier.positioner.position);
            service.CustomNotificationPosition = NotificationPosition.BottomRight;
            Assert.AreEqual(NotificationPosition.BottomRight, CustomNotifier.positioner.position);

            service = new NotificationService();
            service.CustomNotificationPosition = NotificationPosition.BottomRight;
            toast = service.CreateCustomNotification(null);
            Assert.AreEqual(NotificationPosition.BottomRight, CustomNotifier.positioner.position);
            service.CustomNotificationPosition = NotificationPosition.TopRight;
            Assert.AreEqual(NotificationPosition.TopRight, CustomNotifier.positioner.position);
        }

        [Test]
        public void ResettingTimerOfHiddenNotificationTest() {
            var customNotifier = new CustomNotifier(new TestScreen());
            var toast = new CustomNotification(null, customNotifier);
            customNotifier.ShowAsync(toast);
            customNotifier.Hide(toast);
            customNotifier.ResetTimer(toast);
            customNotifier.StopTimer(toast);
        }

        class TestTemplateSelector : DataTemplateSelector {
            public bool Called = false;
            public override DataTemplate SelectTemplate(object item, DependencyObject container) {
                Called = true;
                return base.SelectTemplate(item, container);
            }
        }

        [Test]
        public void CustomNotificationTemplateSelectorTest() {
            var customNotifier = new CustomNotifier(new TestScreen { bounds = new Rect(0, 0, 1000, 500) });
            var selector = new TestTemplateSelector();
            customNotifier.ContentTemplateSelector = selector;
            var toast = new CustomNotification(null, customNotifier);
            WaitWithDispatcher(customNotifier.ShowAsync(toast, 1));
            Assert.IsTrue(selector.Called);
        }
    }
}


text:
import xs from 'xstream';
import {run} from '@cycle/run';
import {button, div, input, section, span, makeDOMDriver} from '@cycle/dom';
import addListener, {addListenerStream} from 'jsutils_mn'

function intent(dom$) {
  const newItem$ = dom$.select('.new_item_submit').events('click')
    .mapTo({type: "NEW_ITEM"})
  const removeItem$ = dom$.select('.remove_item').events('click')
    .map((e) => ({type: "REMOVE_ITEM", payload: e.target.dataset.item_id}))
  return {newItem$, removeItem$ }
}
function model(actions) {
  const newItem$ = actions.newItem$.mapTo(function newItemReducer(prevState){
    return [
      ...prevState,
      {"item_id": 3, "title": "item03"}
    ]
  })
  const removeItem$ = actions.removeItem$.mapTo(function removeItemReducer(prevState) {
    return {}
  })
  return {newItem$, removeItem$}
}
function view(state$) {
  return state$.map( (state) => {
    const items = state
    return div([
      section(".new_item", [
        input(".new_item_title"),
        button(".new_item_submit", "Add Item"),
      ]),
      section(".item_list",
        items.map( (item) =>
          div(".item",[
            span(".item_title", `${item.title}`),
            button(".remove_item", {dataset: {item_id: item.item_id}}, `Remove ${item.item_id}`),
          ]),
        )
      )
    ])
  }
  )
}

const seeds = [
  {"item_id": 1, "title": "item01"},
  {"item_id": 2, "title": "item02"},
]
function main(sources) {
  const actions = intent(sources.DOM)
  const reducers = model(actions)
  const state$ = xs.merge(...reducers)
    .debug( (x) => {
      console.log("xs.merge")
      console.log(x)
    } )
    .fold((listItems, reducer) => reducer(listItems), seeds)
    .startWith(seeds)
  addListenerStream(state$, "state$")
  const vdom$ = view(state$)
  return {
    DOM: vdom$,
  };
    }

run(main, {
  DOM: makeDOMDriver('#app')
});


text:
<?php

namespace VR\AppBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

/**
 * Datamap
 *
 * @author Andrzej Prusinowski <andrzej@avris.it>
 * @author Michał Jabłoński <mjapko@gmail.com>
 *
 * @ORM\Entity(repositoryClass="VR\AppBundle\Entity\Repository\DatamapRepository")
 * @ORM\Table(name="datamaps")
 */
class Datamap
{
    const TYPE_DATA = 0;
    const TYPE_SEARCH = 1;
    const TYPE_EMAIL = 2;

    public static $types = [
        self::TYPE_DATA => 'Data',
        self::TYPE_SEARCH => 'Search',
        self::TYPE_EMAIL => 'Email',
    ];

	/**
	 * @ORM\Id
	 * @ORM\Column(type="bigint")
	 * @ORM\GeneratedValue(strategy="AUTO")
	 */
	protected $id;

    /**
     * @ORM\Column(name="name", type="string", unique=true, length=255)
     */
    protected $name;

    /**
     * @ORM\Column(name="type", type="integer")
     */
    protected $type;

    /**
     * Contains JSON with the datamap
     *
     * @ORM\Column(name="map", type="text")
     */
    protected $map;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    protected $description;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getMap()
    {
        return $this->map;
    }

    public function getMapArray()
    {
        $mapArray = json_decode($this->map, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new \Exception('JSON parsing error: ' . json_last_error_msg());
        }

        return $mapArray;
    }

    /**
     * @param string $map
     * @return $this
     */
    public function setMap($map)
    {
        $this->map = $map;

        return $this;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param $name string
     * @return $this
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * @return integer
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * @return string
     */
    public function getTypeName()
    {
        return isset(self::$types[$this->type]) ? self::$types[$this->type] : null;
    }

    /**
     * @param $type integer
     * @return $this
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * @Assert\Callback
     */
    public function validateMap(ExecutionContextInterface $context)
    {
        json_decode($this->getMap(), true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            $context->buildViolation('JSON parsing error: ' . json_last_error_msg())
                ->atPath('map')
                ->addViolation();
        }
    }

    /**
     * @return mixed
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * @param mixed $description
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }
}


text:
"""
Simple interface to TKP source identification & measurement code.
John Sanders & John Swinbank, 2011.

This is a simplified script for running source finding with a minimal set of
arguments. It does not provide a full configuration interface or access to
all features.

Run as:

  $ python pyse.py file ...

For help with command line options:

  $ python pyse.py --help

See chapters 2 & 3 of Spreeuw, PhD Thesis, University of Amsterdam, 2010,
<http://dare.uva.nl/en/record/340633> for details.
"""
import sys
import math
import numbers
import os.path
from cStringIO import StringIO
import argparse
import numpy
import astropy.io.fits as pyfits

import logging

from tkp.accessors import open as open_accessor
from tkp.accessors import sourcefinder_image_from_accessor
from tkp.accessors import writefits as tkp_writefits
from tkp.sourcefinder.utils import generate_result_maps
from tkp.management import parse_monitoringlist_positions

def regions(sourcelist):
    """
    Return a string containing a DS9-compatible region file describing all the
    sources in sourcelist.
    """
    output = StringIO()
    print >>output, "# Region file format: DS9 version 4.1"
    print >>output, "global color=green dashlist=8 3 width=1 font=\"helvetica 10 normal\" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1"
    print >>output, "image"
    for source in sourcelist:
        # NB, here we convert from internal 0-origin indexing to DS9 1-origin indexing
        print >>output, "ellipse(%f, %f, %f, %f, %f)" % (
            source.x.value + 1.0,
            source.y.value + 1.0,
            source.smaj.value*2,
            source.smin.value*2,
            math.degrees(source.theta)+90
        )
    return output.getvalue()

def skymodel(sourcelist, ref_freq=73800000):
    """
    Return a string containing a skymodel from the extracted sources for use in self-calibration.
    """
    output = StringIO()
    print >>output, "#(Name, Type, Ra, Dec, I, Q, U, V, MajorAxis, MinorAxis, Orientation, ReferenceFrequency='60e6', SpectralIndex='[0.0]') = format"
    for source in sourcelist:
        print >>output, "%s, GAUSSIAN, %s, %s, %f, 0, 0, 0, %f, %f, %f, %f, [0]" % (
            "ra:%fdec:%f" % (source.ra, source.dec),
            "%fdeg" % (source.ra,),
            "%fdeg" % (source.dec,),
            source.flux,
            source.smaj_asec,
            source.smin_asec,
            source.theta_celes,
            ref_freq
        )
    return output.getvalue()

def csv(sourcelist):
    """
    Return a string containing a csv from the extracted sources.
    """
    output = StringIO()
    print >> output, "ra, ra_err, dec, dec_err, smaj, smaj_err, smin, smin_err, pa, pa_err, int_flux, int_flux_err, pk_flux, pk_flux_err"
    for source in sourcelist:
        print >> output, "%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f" % (
            source.ra,
            source.ra.error,
            source.dec,
            source.dec.error,
            source.smaj_asec,
            source.smaj_asec.error,
            source.smin_asec,
            source.smin_asec.error,
            source.theta_celes,
            source.theta_celes.error,
            source.flux,
            source.flux.error,
            source.peak,
            source.peak.error,
        )
    return output.getvalue()

def summary(filename, sourcelist):
    """
    Return a string containing a human-readable summary of all sources in
    sourcelist.
    """
    output = StringIO()
    print >>output, "** %s **\n" % (filename)
    for source in sourcelist:
        print >>output, "RA: %s, dec: %s" % (str(source.ra), str(source.dec))
        print >>output, "Error radius (arcsec): %s" % (str(source.error_radius))
        print >>output, "Semi-major axis (arcsec): %s" % (str(source.smaj_asec))
        print >>output, "Semi-minor axis (arcsec): %s" % (str(source.smin_asec))
        print >>output, "Position angle: %s" % (str(source.theta_celes))
        print >>output, "Flux: %s" % (str(source.flux))
        print >>output, "Peak: %s\n" % (str(source.peak))
    return output.getvalue()

def get_argparser():
    parser = argparse.ArgumentParser(
        description="Source extraction for radio-synthesis images")

    #Arguments relating to source extraction:
    extraction = parser.add_argument_group("Extraction")
    extraction.add_argument("--detection", default=10, type=float,
                        help="Detection threshold")
    extraction.add_argument("--analysis", default=3, type=float,
                        help="Analysis threshold")
    extraction.add_argument("--fdr", action="store_true",
                        help="Use False Detection Rate algorithm")
    extraction.add_argument("--alpha", default=1e-2, type=float, help="FDR Alpha")
    extraction.add_argument("--deblend-thresholds", default=0, type=int,
                        help="Number of deblending subthresholds; 0 to disable")
    extraction.add_argument("--grid", default=64, type=int,
                        help="Background grid segment size")
    extraction.add_argument("--margin", default=0, type=int,
                        help="Margin applied to each edge of image (in pixels)")
    extraction.add_argument("--radius", default=0, type=float,
                        help="Radius of usable portion of image (in pixels)")
    extraction.add_argument("--bmaj", type=float, help="Set beam: Major axis of beam (deg)")
    extraction.add_argument("--bmin", type=float, help="Set beam: Minor axis of beam (deg)")
    extraction.add_argument("--bpa", type=float, help="Set beam: Beam position angle (deg)")
    extraction.add_argument("--force-beam", action="store_true",
                        help="Force fit axis lengths to beam size")
    extraction.add_argument("--detection-image", type=str,
                        help="Find islands on different image")
    extraction.add_argument('--fixed-posns', help="List of position coordinates to "
        "force-fit (decimal degrees, JSON, e.g [[123.4,56.7],[359.9,89.9]]) "
        "(Will not perform blind extraction in this mode)"              ,
        default=None)
    extraction.add_argument('--fixed-posns-file',
        help="Path to file containing a list of positions to force-fit "
             "(Will not perform blind extraction in this mode)",
        default=None)
    extraction.add_argument('--ffbox', type=float, default=3.,
        help="Forced fitting positional box size as a multiple of beam width.")

    #Arguments relating to output:
    output = parser.add_argument_group("Output")
    output.add_argument("--skymodel", action="store_true",
                        help="Generate sky model")
    output.add_argument("--csv", action="store_true",
                        help="Generate csv text file for use in programs such as TopCat")
    output.add_argument("--regions", action="store_true",
                        help="Generate DS9 region file(s)")
    output.add_argument("--rmsmap", action="store_true",
                        help="Generate RMS map")
    output.add_argument("--sigmap", action="store_true",
                        help="Generate significance map")
    output.add_argument("--residuals", action="store_true",
                        help="Generate residual maps")
    output.add_argument("--islands", action="store_true",
                        help="Generate island maps")

    #Finally, positional arguments- the file list:
    parser.add_argument('files', nargs='+',
                        help="Image files for processing")
    return parser

def handle_args(args=None):
    """
    Parses command line options & arguments using OptionParser.
    Options & default values for the script are defined herein.
    """
    parser = get_argparser()
    options= parser.parse_args()

    # Overwrite 'fixed_coords' with a parsed list of coords
    # collated from both command line and file.
    options.fixed_coords = parse_monitoringlist_positions(
        options, str_name="fixed_posns", list_name="fixed_posns_file"
    )
    # Quick & dirty check that the position list looks plausible
    if options.fixed_coords:
        mlist = numpy.array(options.fixed_coords)
        if not (len(mlist.shape) == 2 and mlist.shape[1] == 2):
            parser.error("Positions for forced-fitting must be [RA,dec] pairs")

    # We have four potential modes, of which we choose only one to run:
    #
    # 1. Blind sourcefinding
    #  1.1 Thresholding, no detection image (no extra cmd line options)
    #  1.2 Thresholding, detection image (--detection-image)
    #  1.3 FDR (--fdr)
    #
    # 2. Fit to fixed points (--fixed-coords and/or --fixed-list)

    if options.fixed_coords:
        if options.fdr:
            parser.error("--fdr not supported with fixed positions")
        elif options.detection_image:
            parser.error("--detection-image not supported with fixed positions")
        options.mode = "fixed" # mode 2 above
    elif options.fdr:
        if options.detection_image:
            parser.error("--detection-image not supported with --fdr")
        options.mode = "fdr" # mode 1.3 above
    elif options.detection_image:
        options.mode = "detimage" # mode 1.2 above
    else:
        options.mode = "threshold" # mode 1.1 above

    return options, options.files

def writefits(filename, data, header={}):
    try:
        os.unlink(filename)
    except OSError:
        # Thrown if file didn't exist
        pass
    tkp_writefits(data, filename, header)

def get_detection_labels(filename, det, anl, beam, configuration, plane=0):
    print "Detecting islands in %s" % (filename,)
    print "Thresholding with det = %f sigma, analysis = %f sigma" % (det, anl)
    ff = open_accessor(filename, beam=beam, plane=plane)
    imagedata = sourcefinder_image_from_accessor(ff, **configuration)
    labels, labelled_data = imagedata.label_islands(
        det * imagedata.rmsmap, anl * imagedata.rmsmap
    )
    return labels, labelled_data

def get_sourcefinder_configuration(options):
    configuration = {
        "back_size_x": options.grid,
        "back_size_y": options.grid,
        "margin": options.margin,
        "radius": options.radius,
    }
    if options.residuals or options.islands:
        configuration['residuals'] = True
    return configuration

def get_beam(bmaj, bmin, bpa):

    if (
        isinstance(bmaj, numbers.Real)
        and isinstance(bmin, numbers.Real)
        and isinstance(bpa, numbers.Real)
    ):
        return (float(bmaj), float(bmin), float(bpa))
    if bmaj or bmin or bpa:
        print "WARNING: partial beam specification ignored"
    return None

def bailout(reason):
    # Exit with error
    print "ERROR: %s" % (reason)
    sys.exit(1)

def run_sourcefinder(files, options):
    """
    Iterate over the list of files, running a sourcefinding step on each in
    turn. If specified, a DS9-compatible region file and/or a FITS file
    showing the residuals after Gaussian fitting are dumped for each file.
    A string containing a human readable list of sources is returned.
    """
    output = StringIO()

    beam = get_beam(options.bmaj, options.bmin, options.bpa)
    configuration = get_sourcefinder_configuration(options)

    if options.mode == "detimage":
        labels, labelled_data = get_detection_labels(
            options.detection_image, options.detection, options.analysis, beam, configuration
        )
    else:
        labels, labelled_data = [], None

    for counter, filename in enumerate(files):
        print "Processing %s (file %d of %d)." % (filename, counter+1, len(files))
        imagename = os.path.splitext(os.path.basename(filename))[0]
        ff = open_accessor(filename, beam=beam, plane=0)
        imagedata = sourcefinder_image_from_accessor(ff, **configuration)

        if options.mode == "fixed":
            sr = imagedata.fit_fixed_positions(options.fixed_coords,
                options.ffbox * max(imagedata.beam[0:2])
            )

        else:
            if options.mode == "fdr":
                print "Using False Detection Rate algorithm with alpha = %f" % (options.alpha,)
                sr = imagedata.fd_extract(
                    alpha=options.alpha,
                    deblend_nthresh=options.deblend_thresholds,
                    force_beam=options.force_beam
                )
            else:
                if labelled_data is None:
                    print "Thresholding with det = %f sigma, analysis = %f sigma" % (options.detection, options.analysis)

                sr = imagedata.extract(
                    det=options.detection, anl=options.analysis,
                    labelled_data=labelled_data, labels=labels,
                    deblend_nthresh=options.deblend_thresholds,
                    force_beam=options.force_beam
                )

        if options.regions:
            regionfile = imagename + ".reg"
            regionfile = open(regionfile, 'w')
            regionfile.write(regions(sr))
            regionfile.close()
        if options.residuals or options.islands:
            gaussian_map, residual_map = generate_result_maps(imagedata.data, sr)
        if options.residuals:
            residualfile = imagename + ".residuals.fits"
            writefits(residualfile, residual_map, pyfits.getheader(filename))
        if options.islands:
            islandfile = imagename + ".islands.fits"
            writefits(islandfile, gaussian_map, pyfits.getheader(filename))
        if options.rmsmap:
            rmsfile = imagename + ".rms.fits"
            writefits(rmsfile, numpy.array(imagedata.rmsmap), pyfits.getheader(filename))
        if options.sigmap:
            sigfile = imagename + ".sig.fits"
            writefits(sigfile, numpy.array(imagedata.data_bgsubbed / imagedata.rmsmap), pyfits.getheader(filename))
        if options.skymodel:
            with open(imagename + ".skymodel", 'w') as skymodelfile:
                if ff.freq_eff:
                    skymodelfile.write(skymodel(sr, ff.freq_eff))
                else:
                    print "WARNING: Using default reference frequency for %s" % (skymodelfile.name,)
                    skymodelfile.write(skymodel(sr))
        if options.csv:
            with open(imagename + ".csv", 'w') as csvfile:
                csvfile.write(csv(sr))
        print >>output, summary(filename, sr),
    return output.getvalue()

if __name__ == "__main__":
    logging.basicConfig()
    options, files = handle_args()
    print run_sourcefinder(files, options),


text:
require "common.p8declares"
require "common.p8init"
require "common.p8core"
require "common.c4_command"
require "common.c4_notify"
--require "common.c4_diagnostics" --DEBUG
require "p8proxy"
require "p8sky"

--Init Functions

function ON_DRIVER_EARLY_INIT.main()
end

function ON_DRIVER_INIT.main()
    --Init Connected Devices
    P8INT:SETUP()
end


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.androidtown.privatecloud">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/appicon"
        android:label="Private Cloud"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Login"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity"></activity>
        <activity android:name=".ExternalFile"></activity>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>


text:
import logging
from gii.core.tmpfile import TempDir

from PyQt4 import QtGui,QtCore
from PyQt4.QtCore import Qt

from gii.qt.controls.PropertyEditor import PropertyEditor

##----------------------------------------------------------------##
class PropertyDialog( QtGui.QDialog ):
	def __init__(self, prompt, *args, **options):
		super(PropertyDialog, self).__init__(*args)
		self.setWindowTitle( prompt )
		btnOK     = QtGui.QPushButton('OK')
		btnCancel = QtGui.QPushButton('Cancel')

		buttonBox=QtGui.QDialogButtonBox(QtCore.Qt.Horizontal)
		buttonBox.addButton(btnOK, QtGui.QDialogButtonBox.AcceptRole)
		if options.get( 'cancel_button', True ):
			buttonBox.addButton(btnCancel, QtGui.QDialogButtonBox.RejectRole)
		buttonBox.accepted.connect(self.accept)
		buttonBox.rejected.connect(self.reject)

		box = QtGui.QVBoxLayout( self )
		box.setMargin( 10 )
		box.setSpacing( 5 )

		propertyEditor = PropertyEditor( self )
		box.addWidget(propertyEditor)
		box.addWidget(buttonBox)

		self.propertyEditor = propertyEditor

	def setTarget( self, target ):
		self.propertyEditor.setTarget( target )

##----------------------------------------------------------------##
def requestProperty( prompt, target, **option ):
	dialog = PropertyDialog( prompt, **option )
	dialog.setTarget( target )
	dialog.move( QtGui.QCursor.pos() )

	if dialog.exec_():
		return True
	else:
		return False


text:
/*	$NetBSD: compat_13_machdep.c,v 1.5 1999/03/26 04:29:21 eeh Exp $	*/

/*-
 * Copyright (c) 1996, 1997, 1998 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
 * NASA Ames Research Center.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the NetBSD
 *	Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/user.h>
#include <sys/kernel.h>
#include <sys/mount.h>
#include <sys/signal.h>
#include <sys/signalvar.h>

#include <sys/syscallargs.h>
#include <sparc64/sparc64/sigdebug.h>

/*
 * System call to cleanup state after a signal
 * has been taken.  Reset signal mask and
 * stack state from context left by sendsig (above),
 * and return to the given trap frame (if there is one).
 * Check carefully to make sure that the user has not
 * modified the state to gain improper privileges or to cause
 * a machine fault.
 */
/* ARGSUSED */
int
compat_13_sys_sigreturn(p, v, retval)
	struct proc *p;
	void *v;
	register_t *retval;
{
	struct compat_13_sys_sigreturn_args /* {
		syscallarg(struct sigcontext13 *) sigcntxp;
	} */ *uap = v;
	struct sigcontext13 sc, *scp;
	sigset_t mask;
	struct trapframe *tf;

	/* First ensure consistent stack state (see sendsig). */
	write_user_windows();
#if 0
	/* Make sure our D$ is not polluted w/bad data */
	blast_vcache();
#endif
	if (rwindow_save(p)) {
#ifdef DEBUG
		printf("compat_13_sys_sigreturn: rwindow_save(%p) failed, sending SIGILL\n", p);
		Debugger();
#endif
		sigexit(p, SIGILL);
	}
#ifdef DEBUG
	if (sigdebug & SDB_FOLLOW) {
		printf("compat_13_sys_sigreturn: %s[%d], sigcntxp %p\n",
		    p->p_comm, p->p_pid, SCARG(uap, sigcntxp));
		if (sigdebug & SDB_DDB) Debugger();
	}
#endif

	scp = SCARG(uap, sigcntxp);
	if ((vaddr_t)scp & 3 || (copyin((caddr_t)scp, &sc, sizeof sc) != 0))
#ifdef DEBUG
	{
		printf("compat_13_sys_sigreturn: copyin failed: scp=%p\n", scp);
		Debugger();
		return (EFAULT);
	}
#else
		return (EFAULT);
#endif

	scp = ≻

	tf = p->p_md.md_tf;
	/*
	 * Only the icc bits in the psr are used, so it need not be
	 * verified.  pc and npc must be multiples of 4.  This is all
	 * that is required; if it holds, just do it.
	 */
	if (((scp->sc_pc | scp->sc_npc) & 3) != 0 || scp->sc_pc == 0 || scp->sc_npc == 0)
#ifdef DEBUG
	{
		printf("compat_13_sys_sigreturn: pc %p or npc %p invalid\n", scp->sc_pc, scp->sc_npc);
		Debugger();
		return (EINVAL);
	}
#endif
		return (EINVAL);
	/* take only psr ICC field */
#ifdef __arch64__
	tf->tf_tstate = (int64_t)(tf->tf_tstate & ~TSTATE_CCR) | scp->sc_tstate;
#else
	tf->tf_tstate = (int64_t)(tf->tf_tstate & ~TSTATE_CCR) | PSRCC_TO_TSTATE(scp->sc_psr);
#endif
	tf->tf_pc = scp->sc_pc;
	tf->tf_npc = scp->sc_npc;
	tf->tf_global[1] = scp->sc_g1;
	tf->tf_out[0] = scp->sc_o0;
	tf->tf_out[6] = scp->sc_sp;
#ifdef DEBUG
	if (sigdebug & SDB_FOLLOW) {
		printf("compat_13_sys_sigreturn: return trapframe pc=%p sp=%p tstate=%llx\n",
		       (vaddr_t)tf->tf_pc, (vaddr_t)tf->tf_out[6], tf->tf_tstate);
		if (sigdebug & SDB_DDB) Debugger();
	}
#endif

	if (scp->sc_onstack & SS_ONSTACK)
		p->p_sigacts->ps_sigstk.ss_flags |= SS_ONSTACK;
	else
		p->p_sigacts->ps_sigstk.ss_flags &= ~SS_ONSTACK;

	/* Restore signal mask */
	native_sigset13_to_sigset(&scp->sc_mask, &mask);
	(void) sigprocmask1(p, SIG_SETMASK, &mask, 0);

	return (EJUSTRETURN);
}


text:
<!DOCTYPE HTML>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <link rel="stylesheet" href="/static/css/style.css" media="screen" type="text/css" />

Loading Graph...

        <canvas id="myGraph" width="350" height="220"></canvas>


text:
echo ";if (typeof window == 'undefined' && typeof global == 'undefined') { var global = {}; };" > coffee-react-transform.js
node node_modules/browserify/bin/cmd.js \
  --require "coffee-react-transform" \
  --detect-globals "false" \
  --insert-global-vars "__filename,__dirname" \
  --standalone "coffeeReactTransform" \
  >> coffee-react-transform.js
echo ";if (typeof coffeeReactTransform == 'undefined') { var coffeeReactTransform = global.coffeeReactTransform; }" >> coffee-react-transform.js

echo ";if (typeof window == 'undefined' && typeof global == 'undefined') { var global = {}; };" > js-syntax-transform.js
cat node_modules/coffee-react-jstransform/dist/js-syntax-transform.js >> js-syntax-transform.js
echo ";if (typeof coffeeReactJSSyntaxTransform == 'undefined') { var coffeeReactJSSyntaxTransform = global.coffeeReactJSSyntaxTransform; }" >> js-syntax-transform.js


text:
在 `src/main/java/hello/controllers` 目录中创建 `UserController` 类:

[import](codes/UserController.java)

需要注意,`UserController` 继承了 `ModelController` ,这是开发数据 API 的基础模式,在后面会详细说明。


text:
module CompetitionsHelper

  def remaining_days_countdown_in phase
    if @competition.current_phase == phase
      days = @competition.remaining_days_in_current_phase
      if days == 1
        content_tag("p", Time.now.day_countdown, :class => "qtd day_countdown") +
        content_tag("p", "restantes", :class => "sobre")
      else
        content_tag("p", days, :class => "qtd") +
        content_tag("p", "dias restantes", :class => "sobre")
      end
    end
  end

  def phase_over_or_current?(competition, phase)
    return false unless competition.current_phase
    competition.phase_over?(phase) or competition.current_phase == phase
  end
end


text:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.Routing;

internal sealed partial class EndpointMiddleware
{
    internal const string AuthorizationMiddlewareInvokedKey = "__AuthorizationMiddlewareWithEndpointInvoked";
    internal const string CorsMiddlewareInvokedKey = "__CorsMiddlewareWithEndpointInvoked";

    private readonly ILogger _logger;
    private readonly RequestDelegate _next;
    private readonly RouteOptions _routeOptions;

    public EndpointMiddleware(
        ILogger<EndpointMiddleware> logger,
        RequestDelegate next,
        IOptions<RouteOptions> routeOptions)
    {
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        _next = next ?? throw new ArgumentNullException(nameof(next));
        _routeOptions = routeOptions?.Value ?? throw new ArgumentNullException(nameof(routeOptions));
    }

    public Task Invoke(HttpContext httpContext)
    {
        var endpoint = httpContext.GetEndpoint();
        if (endpoint is not null)
        {
            if (!_routeOptions.SuppressCheckForUnhandledSecurityMetadata)
            {
                if (endpoint.Metadata.GetMetadata<IAuthorizeData>() is not null &&
                    !httpContext.Items.ContainsKey(AuthorizationMiddlewareInvokedKey))
                {
                    ThrowMissingAuthMiddlewareException(endpoint);
                }

                if (endpoint.Metadata.GetMetadata<ICorsMetadata>() is not null &&
                    !httpContext.Items.ContainsKey(CorsMiddlewareInvokedKey))
                {
                    ThrowMissingCorsMiddlewareException(endpoint);
                }
            }

            if (endpoint.RequestDelegate is not null)
            {
                Log.ExecutingEndpoint(_logger, endpoint);

                try
                {
                    var requestTask = endpoint.RequestDelegate(httpContext);
                    if (!requestTask.IsCompletedSuccessfully)
                    {
                        return AwaitRequestTask(endpoint, requestTask, _logger);
                    }
                }
                catch (Exception exception)
                {
                    Log.ExecutedEndpoint(_logger, endpoint);
                    return Task.FromException(exception);
                }

                Log.ExecutedEndpoint(_logger, endpoint);
                return Task.CompletedTask;
            }
        }

        return _next(httpContext);

        static async Task AwaitRequestTask(Endpoint endpoint, Task requestTask, ILogger logger)
        {
            try
            {
                await requestTask;
            }
            finally
            {
                Log.ExecutedEndpoint(logger, endpoint);
            }
        }
    }

    private static void ThrowMissingAuthMiddlewareException(Endpoint endpoint)
    {
        throw new InvalidOperationException($"Endpoint {endpoint.DisplayName} contains authorization metadata, " +
            "but a middleware was not found that supports authorization." +
            Environment.NewLine +
            "Configure your application startup by adding app.UseAuthorization() in the application startup code. If there are calls to app.UseRouting() and app.UseEndpoints(...), the call to app.UseAuthorization() must go between them.");
    }

    private static void ThrowMissingCorsMiddlewareException(Endpoint endpoint)
    {
        throw new InvalidOperationException($"Endpoint {endpoint.DisplayName} contains CORS metadata, " +
            "but a middleware was not found that supports CORS." +
            Environment.NewLine +
            "Configure your application startup by adding app.UseCors() in the application startup code. If there are calls to app.UseRouting() and app.UseEndpoints(...), the call to app.UseCors() must go between them.");
    }

    private static partial class Log
    {
        [LoggerMessage(0, LogLevel.Information, "Executing endpoint '{EndpointName}'", EventName = "ExecutingEndpoint")]
        public static partial void ExecutingEndpoint(ILogger logger, Endpoint endpointName);

        [LoggerMessage(1, LogLevel.Information, "Executed endpoint '{EndpointName}'", EventName = "ExecutedEndpoint")]
        public static partial void ExecutedEndpoint(ILogger logger, Endpoint endpointName);
    }
}


text:
from __future__ import absolute_import
from . import main
import sys
import typing

sys.exit(main.main())


text: angular.module('budgetApp', ['budgetApp.controllers']);


text:
<!DOCTYPE html>
<meta charset="utf8">
<title>CSS Containment Test: Scrolling overflow works when paint is contained"</title>
<link rel="help" href="https://drafts.csswg.org/css-contain-1/#containment-paint">
<meta name="assert" content="Scrolling overflow works when paint is contained.">


text:
#include "../kroll.h"
#include "net.h"
#include <sstream>

using std::string;
using std::vector;
using Poco::Net::IPAddress;
using Poco::StringTokenizer;
using Poco::NumberParser;
using Poco::URI;

namespace kroll
{

static std::string& ProxyTypeToString(ProxyType type)
{
	static std::string httpString("http");
	static std::string httpsString("https");
	static std::string ftpString("ftp");
	static std::string socksString("socks");
	switch (type)
	{
		case HTTP:
			return httpString;
			break;
		case HTTPS:
			return httpsString;
			break;
		case FTP:
			return ftpString;
			break;
		case SOCKS:
		default:
			return socksString;
			break;
	}
}

/*static*/
ProxyType Proxy::SchemeToProxyType(string scheme)
{
	scheme = FileUtils::Trim(scheme);
	Poco::toLowerInPlace(scheme);

	if (scheme == "https")
		return HTTPS;
	else if (scheme == "ftp")
		return FTP;
	else if (scheme == "socks")
		return SOCKS;
	else
		return HTTP;
}

std::string Proxy::ToString()
{
	std::stringstream ss;
	ss << ProxyTypeToString(type) << "://";

	if (!username.empty() || !password.empty())
		ss << username << ":" << password << "@";

	ss << host;

	if (port != 0)
		ss << ":" << port;

	return ss.str();
}

static SharedProxy GetProxyFromEnvironment(std::string prefix)
{
	Poco::toUpperInPlace(prefix);
	std::string envName = prefix + "_PROXY";

	std::string proxyString(EnvironmentUtils::Get(envName));
	if (!proxyString.empty())
		return ProxyConfig::ParseProxyEntry(proxyString, prefix, std::string());

	Poco::toLowerInPlace(prefix);
	envName = prefix + "_proxy";
	proxyString = EnvironmentUtils::Get(envName);
	if (!proxyString.empty())
		return ProxyConfig::ParseProxyEntry(proxyString, prefix, std::string());

	return 0;
}

namespace ProxyConfig
{

SharedProxy httpProxyOverride(0);
SharedProxy httpsProxyOverride(0);

void SetHTTPProxyOverride(SharedProxy newProxyOverride)
{
	httpProxyOverride = newProxyOverride;
}

SharedProxy GetHTTPProxyOverride()
{
	return httpProxyOverride;
}

void SetHTTPSProxyOverride(SharedProxy newProxyOverride)
{
	httpsProxyOverride = newProxyOverride;
}

SharedProxy GetHTTPSProxyOverride()
{
	return httpsProxyOverride;
}

SharedProxy GetProxyForURL(string& url)
{
	static Logger* logger = GetLogger();
	URI uri(url);

	// Don't try to detect proxy settings for URLs we know are local
	std::string scheme(uri.getScheme());
	if (scheme == "app" || scheme == "ti" || scheme == "file")
		return 0;

	if (scheme == "http" && !httpProxyOverride.isNull())
		return httpProxyOverride;

	if (scheme == "https" && !httpsProxyOverride.isNull())
		return httpsProxyOverride;

	SharedProxy environmentProxy(GetProxyFromEnvironment(scheme));
	if (!environmentProxy.isNull())
	{
		logger->Debug("Found proxy (%s) in environment",
			environmentProxy->ToString().c_str());
		return environmentProxy;
	}

	logger->Debug("Looking up proxy information for: %s", url.c_str());
	SharedProxy proxy(ProxyConfig::GetProxyForURLImpl(uri));

	if (proxy.isNull())
		logger->Debug("Using direct connection.");
	else
		logger->Debug("Using proxy: %s", proxy->ToString().c_str());

	return proxy;
}

static inline bool EndsWith(string haystack, string needle)
{
	return haystack.find(needle) == (haystack.size() - needle.size());
}

static bool ShouldBypassWithEntry(URI& uri, SharedPtr<BypassEntry> entry)
{
	const std::string& uriHost = uri.getHost();
	const std::string& uriScheme = uri.getScheme();
	unsigned short uriPort = uri.getPort();
	const std::string& entryHost = entry->host;
	const std::string& entryScheme = entry->scheme;
	unsigned short entryPort = entry->port;

	GetLogger()->Debug("bypass entry: scheme='%s' host='%s' port='%i'",
		entry->scheme.c_str(), entry->host.c_str(), entry->port);

	// An empty bypass entry equals an unconditional bypass.
	if (entry.isNull())
	{
		return true;
	}
	else
	{
		if (entryHost == "<local>" && uriHost.find(".") == string::npos)
		{
			return true;
		}
		else if (EndsWith(uriHost, entryHost) &&
			(entryScheme.empty() || entryScheme == uriScheme) &&
			(entryPort == 0 || entryPort == uriPort))
		{
			return true;
		}
	}

	return false;
}

bool ShouldBypass(URI& uri, vector<SharedPtr<BypassEntry> >& bypassList)
{
	GetLogger()->Debug("Checking whether %s should be bypassed.",
		uri.toString().c_str());

	for (size_t i = 0; i < bypassList.size(); i++)
	{
		if (ShouldBypassWithEntry(uri, bypassList.at(i)))
			return true;
	}

	GetLogger()->Debug("No bypass");
	return false;
}

SharedPtr<BypassEntry> ParseBypassEntry(string entry)
{
	// Traditionally an endswith comparison is always done with the host
	// part, so we throw away explicit wildcards at the beginning. If the
	// entire string is a wildcard this is an unconditional bypass.
	if (entry.at(0) == '*' && entry.size() == 1)
	{
		// Null URI means always bypass
		return 0;
	}
	else if (entry.at(0) == '*' && entry.size() > 1)
	{
		entry = entry.substr(1);
	}

	SharedPtr<BypassEntry> bypass(new BypassEntry());
	size_t endScheme = entry.find("://");
	if (endScheme != string::npos)
	{
		bypass->scheme = entry.substr(0, endScheme);
		entry = entry.substr(endScheme + 3);
	}

	size_t scan = entry.size() - 1;
	while (scan > 0 && isdigit(entry[scan]))
		scan--;

	if (entry[scan] == ':' && scan != entry.size() - 1)
	{
		string portString = entry.substr(scan + 1);
		bypass->port = atoi(portString.c_str());
		entry = entry.substr(0, scan);
	}

	bypass->host = entry;
	return bypass;
}

Logger* GetLogger()
{
	static Logger* logger = Logger::Get("Proxy");
	return logger;
}

SharedProxy ParseProxyEntry(string entry, const string& urlScheme,
	const string& entryScheme)
{
	// If the hostname came with a scheme:// speicifier, read this,
	// though it has lower precedence than the other two places the
	// scheme can be defined.
	entry = FileUtils::Trim(entry);
	size_t schemeEnd = entry.find("://");
	std::string hostScheme;
	if (schemeEnd != string::npos)
	{
		hostScheme = entry.substr(0, schemeEnd);
		entry = entry.substr(schemeEnd + 3);
	}

	// We need to pull out the credentials before the port, because
	// the port just searches for the first ':', which can be in the
	// credentials section.
	string username, password;
	size_t credentialsEnd = entry.find('@');
	if (credentialsEnd != string::npos && credentialsEnd > 0 && entry.size() > 1)
	{
		username = entry.substr(0, credentialsEnd);
		entry = entry.substr(credentialsEnd + 1);

		size_t usernameEnd = username.find(':');
		if (usernameEnd != string::npos)
		{
			password = username.substr(usernameEnd + 1);
			username = username.substr(0, usernameEnd);
		}
	}

	size_t portStart = entry.find(':');
	unsigned port = 0;
	if (portStart != string::npos && portStart != entry.size())
	{
		std::string portString(entry.substr(portStart + 1));
		entry = entry.substr(0, portStart);
		try
		{
			portString = FileUtils::Trim(portString);
			port = NumberParser::parseUnsigned(portString);
		}
		catch (Poco::SyntaxException& e)
		{
			port = 0;
		}
	}

	std::string scheme;
	if (!entryScheme.empty())
		scheme = entryScheme;
	else if (!hostScheme.empty())
		scheme = hostScheme;
	else
		scheme = urlScheme;

	if (scheme == "direct")
		return 0;

	SharedProxy proxy = new Proxy();
	proxy->type = Proxy::SchemeToProxyType(scheme);
	proxy->host = FileUtils::Trim(entry);
	proxy->port = port;

	if (!username.empty())
		proxy->username = username;
	if (!password.empty())
		proxy->password = password;

	return proxy;
}

void ParseProxyList(string proxyListString,
	vector<SharedProxy>& proxyList, const string& urlScheme)
{
	string sep = "; ";
	StringTokenizer proxyTokens(proxyListString, sep,
		StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM);
	for (size_t i = 0; i < proxyTokens.count(); i++)
	{
		string entry = proxyTokens[i];

		// If this entry defines a scheme, make it override the argument.
		string entryScheme;
		size_t schemeEnd = entry.find('=');
		if (schemeEnd != string::npos)
		{
			// This proxy only applies to the scheme before '='
			entryScheme = entry.substr(0, schemeEnd);
			entry = entry.substr(schemeEnd + 1);
		}

		SharedProxy proxy(ParseProxyEntry(entry, urlScheme, entryScheme));
		GetLogger()->Debug("Proxy entry: %s", proxy->ToString().c_str());
		proxyList.push_back(proxy);
	}
}

} // namespace ProxyConfig
} // namespace kroll


text:
/* global it, describe, mocha, chai, mochaOpts, testOpts, shareSpec, includeHttpsSpec, includeFileSpec, semVer */
import Asciidoctor from '../../build/asciidoctor-browser.js'

// bootstrap
(async () => {
  let reporter
  if (typeof mochaOpts === 'function') {
    const opts = await mochaOpts()
    reporter = opts.reporter
  } else {
    reporter = 'html'
  }
  mocha.setup({
    ui: 'bdd',
    checkLeaks: false,
    reporter: reporter
  })

  const expect = chai.expect
  const asciidoctor = Asciidoctor({ runtime: { platform: 'browser' } })
  const baseDir = window.location.origin
  const asciidoctorCoreSemVer = semVer(asciidoctor.getCoreVersion())
  let remoteBaseUri
  if (typeof testOpts === 'function') {
    const opts = await testOpts()
    remoteBaseUri = opts.remoteBaseUri
  }
  const testOptions = {
    platform: 'Browser',
    baseDir: baseDir,
    coreVersion: asciidoctorCoreSemVer,
    remoteBaseUri: remoteBaseUri
  }
  shareSpec(testOptions, asciidoctor, expect)
  includeHttpsSpec(testOptions, asciidoctor, expect)
  includeFileSpec(testOptions, asciidoctor, expect)

  describe('Browser', function () {
    describe('Include', function () {
      // REMIND: Does not work because we are unable to get the current directory in a reliable way when running inside a browser
      /*
      it('should include file with a relative path (base_dir is not defined)', function () {
        var opts = {safe: 'safe'};
        var html = asciidoctor.convert('include::spec/fixtures/include.adoc[]', opts);
        expect(html).to.include('include content');
      });
      */
      it('should include file with an absolute path (base_dir is explicitly defined)', function () {
        const opts = { safe: 'safe', base_dir: testOptions.baseDir }
        const html = asciidoctor.convert('include::' + testOptions.baseDir + '/spec/fixtures/include.adoc[]', opts)
        expect(html).to.include('include content')
      })

      it('should resolve a stylesheet using chrome:// protocol (root)', function () {
        const attributes = {
          stylesheet: 'asciidoctor-plus.css',
          stylesdir: 'chrome://asciidoctor/extension/css',
          copycss: false
        }
        const options = {
          doctype: 'article',
          safe: 'unsafe',
          standalone: true,
          attributes
        }
        const defaultLogger = asciidoctor.LoggerManager.getLogger()
        const memoryLogger = asciidoctor.MemoryLogger.create()
        try {
          asciidoctor.LoggerManager.setLogger(memoryLogger)
          asciidoctor.convert('Hello world', options)
          const errorMessage = memoryLogger.getMessages()[0]
          expect(errorMessage.getSeverity()).to.equal('WARN')
          expect(errorMessage.getText()).to.include('could not retrieve contents of stylesheet at URI: chrome://asciidoctor/extension/css/asciidoctor-plus.css')
        } catch (e) {
          // the resource does not exist but chrome:// is a root path and should not be prepended by "./"
          // we expect the processor to try to load the resource 'chrome://asciidoctor/extension/css/asciidoctor-plus.css' and fail!
          if (asciidoctorCoreSemVer.lte('2.0.10')) {
            expect(e.message).to.include('Failed to load \'chrome://asciidoctor/extension/css/asciidoctor-plus.css\'')
          } else {
            throw e
          }
        } finally {
          asciidoctor.LoggerManager.setLogger(defaultLogger)
        }
      })
    })
  })

  mocha.run(function (failures) {
    if (failures > 0) {
      console.error('%d failures', failures)
    }
  })
})().catch(err => {
  console.error('Unable to start the browser tests suite: ' + err)
})


text:
package armpurview

import (
	"context"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
)

// DefaultAccountsClient contains the methods for the DefaultAccounts group.
// Don't use this type directly, use NewDefaultAccountsClient() instead.
type DefaultAccountsClient struct {
	host string
	pl   runtime.Pipeline
}

// NewDefaultAccountsClient creates a new instance of DefaultAccountsClient with the specified values.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewDefaultAccountsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*DefaultAccountsClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &DefaultAccountsClient{
		host: ep,
		pl:   pl,
	}
	return client, nil
}

// Get - Get the default account for the scope.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-07-01
// scopeTenantID - The tenant ID.
// scopeType - The scope for the default account.
// options - DefaultAccountsClientGetOptions contains the optional parameters for the DefaultAccountsClient.Get method.
func (client *DefaultAccountsClient) Get(ctx context.Context, scopeTenantID string, scopeType ScopeType, options *DefaultAccountsClientGetOptions) (DefaultAccountsClientGetResponse, error) {
	req, err := client.getCreateRequest(ctx, scopeTenantID, scopeType, options)
	if err != nil {
		return DefaultAccountsClientGetResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return DefaultAccountsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return DefaultAccountsClientGetResponse{}, runtime.NewResponseError(resp)
	}
	return client.getHandleResponse(resp)
}

// getCreateRequest creates the Get request.
func (client *DefaultAccountsClient) getCreateRequest(ctx context.Context, scopeTenantID string, scopeType ScopeType, options *DefaultAccountsClientGetOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Purview/getDefaultAccount"
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("scopeTenantId", scopeTenantID)
	reqQP.Set("scopeType", string(scopeType))
	if options != nil && options.Scope != nil {
		reqQP.Set("scope", *options.Scope)
	}
	reqQP.Set("api-version", "2021-07-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *DefaultAccountsClient) getHandleResponse(resp *http.Response) (DefaultAccountsClientGetResponse, error) {
	result := DefaultAccountsClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.DefaultAccountPayload); err != nil {
		return DefaultAccountsClientGetResponse{}, err
	}
	return result, nil
}

// Remove - Removes the default account from the scope.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-07-01
// scopeTenantID - The tenant ID.
// scopeType - The scope for the default account.
// options - DefaultAccountsClientRemoveOptions contains the optional parameters for the DefaultAccountsClient.Remove method.
func (client *DefaultAccountsClient) Remove(ctx context.Context, scopeTenantID string, scopeType ScopeType, options *DefaultAccountsClientRemoveOptions) (DefaultAccountsClientRemoveResponse, error) {
	req, err := client.removeCreateRequest(ctx, scopeTenantID, scopeType, options)
	if err != nil {
		return DefaultAccountsClientRemoveResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return DefaultAccountsClientRemoveResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) {
		return DefaultAccountsClientRemoveResponse{}, runtime.NewResponseError(resp)
	}
	return DefaultAccountsClientRemoveResponse{}, nil
}

// removeCreateRequest creates the Remove request.
func (client *DefaultAccountsClient) removeCreateRequest(ctx context.Context, scopeTenantID string, scopeType ScopeType, options *DefaultAccountsClientRemoveOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Purview/removeDefaultAccount"
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("scopeTenantId", scopeTenantID)
	reqQP.Set("scopeType", string(scopeType))
	if options != nil && options.Scope != nil {
		reqQP.Set("scope", *options.Scope)
	}
	reqQP.Set("api-version", "2021-07-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Set - Sets the default account for the scope.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-07-01
// defaultAccountPayload - The payload containing the default account information and the scope.
// options - DefaultAccountsClientSetOptions contains the optional parameters for the DefaultAccountsClient.Set method.
func (client *DefaultAccountsClient) Set(ctx context.Context, defaultAccountPayload DefaultAccountPayload, options *DefaultAccountsClientSetOptions) (DefaultAccountsClientSetResponse, error) {
	req, err := client.setCreateRequest(ctx, defaultAccountPayload, options)
	if err != nil {
		return DefaultAccountsClientSetResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return DefaultAccountsClientSetResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return DefaultAccountsClientSetResponse{}, runtime.NewResponseError(resp)
	}
	return client.setHandleResponse(resp)
}

// setCreateRequest creates the Set request.
func (client *DefaultAccountsClient) setCreateRequest(ctx context.Context, defaultAccountPayload DefaultAccountPayload, options *DefaultAccountsClientSetOptions) (*policy.Request, error) {
	urlPath := "/providers/Microsoft.Purview/setDefaultAccount"
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-07-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, defaultAccountPayload)
}

// setHandleResponse handles the Set response.
func (client *DefaultAccountsClient) setHandleResponse(resp *http.Response) (DefaultAccountsClientSetResponse, error) {
	result := DefaultAccountsClientSetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.DefaultAccountPayload); err != nil {
		return DefaultAccountsClientSetResponse{}, err
	}
	return result, nil
}